diff --git a/.github/workflows/_reusable-gradle.yml b/.github/workflows/_reusable-gradle.yml deleted file mode 100644 index 8392b08f..00000000 --- a/.github/workflows/_reusable-gradle.yml +++ /dev/null @@ -1,63 +0,0 @@ -name: reusable-gradle - -# One place that knows how a Gradle job starts. -# -# Every job in this repository opened with the same preamble: checkout, a three-line pinned -# wrapper-validation step, then the JDK/cache action. The wrapper step is gone (setup-gradle -# validates wrappers itself), and this workflow removes the rest of the repetition for the jobs whose -# only variation is the Gradle command they run. -# -# Jobs that need service containers, a matrix, artifact uploads or per-job env stay written out with -# `./.github/actions/setup-gradle-java`, because expressing those through `workflow_call` inputs -# means encoding YAML inside strings — which is how a "shared" workflow becomes less readable than -# the duplication it replaced. - -on: - workflow_call: - inputs: - tasks: - description: The Gradle task list, whitespace-separated. - required: true - type: string - gradle-args: - description: Flags appended after the task list. - required: false - type: string - default: "--stacktrace" - working-directory: - description: Directory the wrapper is invoked from. - required: false - type: string - default: src - timeout-minutes: - required: false - type: number - default: 30 - continue-on-error: - description: Run the job as an advisory signal rather than a gate. - required: false - type: boolean - default: false - -permissions: - contents: read - -jobs: - gradle: - runs-on: ubuntu-latest - timeout-minutes: ${{ inputs.timeout-minutes }} - continue-on-error: ${{ inputs.continue-on-error }} - steps: - - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # actions/checkout@v4.2.2 - - uses: ./.github/actions/setup-gradle-java - - name: Run ${{ inputs.tasks }} - working-directory: ${{ inputs.working-directory }} - env: - GRADLE_TASKS: ${{ inputs.tasks }} - GRADLE_ARGS: ${{ inputs.gradle-args }} - run: | - set -euo pipefail - # Word-split on purpose: both inputs are task/flag lists. They come from this repository's - # own workflow files, never from a pull request. - # shellcheck disable=SC2086 - ./gradlew ${GRADLE_TASKS} ${GRADLE_ARGS} diff --git a/.github/workflows/build-logic.yml b/.github/workflows/build-logic.yml new file mode 100644 index 00000000..fa593e9d --- /dev/null +++ b/.github/workflows/build-logic.yml @@ -0,0 +1,41 @@ +name: build-logic + +# The included builds' own tests (TestKit for the convention plugins, unit tests for build-tools). +# The main task graph does not reach them, so they run here — and only when a pull request touches +# the included builds or the catalog they read. + +on: + pull_request: + paths: + - "src/build-logic/**" + - "src/build-tools/**" + - "src/gradle/**" + - ".github/workflows/build-logic.yml" + push: + branches: ["main"] + paths: + - "src/build-logic/**" + - "src/build-tools/**" + - "src/gradle/**" + - ".github/workflows/build-logic.yml" + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + included-builds: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # actions/checkout@v4.2.2 + - uses: ./.github/actions/setup-gradle-java + - name: Test the build-logic convention plugins + working-directory: src + run: ./gradlew -p build-logic test --stacktrace + - name: Test the build-tools verifiers + working-directory: src + run: ./gradlew -p build-tools test --stacktrace diff --git a/.github/workflows/ci-quality-gates.yml b/.github/workflows/ci-quality-gates.yml index eecd5698..26e71224 100644 --- a/.github/workflows/ci-quality-gates.yml +++ b/.github/workflows/ci-quality-gates.yml @@ -30,18 +30,6 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # actions/checkout@v4.2.2 - - name: Require the committed public-path security baseline - run: | - set -euo pipefail - readonly snapshot='docs/security/public-paths-snapshot.txt' - if [[ ! -s "${snapshot}" ]]; then - echo "::error::${snapshot} is missing or empty. CI must not let verifyPublicPathSnapshot create its own first-run baseline." - exit 1 - fi - if ! git ls-files --error-unmatch "${snapshot}" >/dev/null 2>&1; then - echo "::error::${snapshot} exists locally but is not committed." - exit 1 - fi - uses: ./.github/actions/setup-gradle-java - name: Export the live Gradle verification task map working-directory: src @@ -54,47 +42,15 @@ jobs: if-no-files-found: error # `ci`, not `check`. A leaf's `check` is that leaf's — compile, its tests, Spotless, Checkstyle # and Error Prone — and the repository-wide gates are named tasks of their own: - # ci = every leaf check + architectureCheck + qualityCheck + configContractCheck + qualificationCheck - # so CI runs strictly more than it used to while `./gradlew :domain-core:check` runs strictly - # less. + # ci = every leaf check + architectureCheck + qualityCheck + # The main-branch stage (`mainCheck`: environment contract, full-boot qualification, public-path + # baseline, API surfaces, transport and messaging lanes) runs in integration-main.yml. - name: Run the pull-request gate working-directory: src - run: ./gradlew :ci :verifyPublicPathSnapshot :verifyDependencyLocks --warning-mode=fail --stacktrace - # Named as its own step because nothing else runs it: `check` does not depend on - # graphqlStableTest, so the lane's required-class guard — the check that its module-boundary - # suite has not silently stopped being discovered — would protect nothing in CI. - - name: Qualify the GraphQL Stable lane - working-directory: src - run: ./gradlew :adapter:inbound:graphql:graphqlStableTest --stacktrace - - name: Qualify opt-in inbound transports without skips - working-directory: src - run: ./gradlew :conditionalTransportQualification --stacktrace + run: ./gradlew :ci :verifyDependencyLocks --warning-mode=fail --stacktrace - name: Verify Compose profile contracts render exactly as declared run: bash scripts/verify-compose-profile-contracts.sh - build-logic: - # Included-build tests are independent of the main project task graph. Running them as a - # separate blocking job keeps plugin TestKit work off the quality-gates critical path. - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # actions/checkout@v4.2.2 - - uses: ./.github/actions/setup-gradle-java - - name: Test the build-logic convention plugins - working-directory: src - run: ./gradlew -p build-logic test --stacktrace - - build-tools: - # build-tools is an included build, so its verifier tests are not reached by the main :ci task. - # These tests protect env/JPA/messaging/Mongo/notification evidence parsers; a broken verifier - # must fail the pull-request gate rather than silently bless bad evidence. - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # actions/checkout@v4.2.2 - - uses: ./.github/actions/setup-gradle-java - - name: Test the build-time verifier plugins - working-directory: src - run: ./gradlew -p build-tools test --stacktrace - sample-portfolio: # The sample is excluded from production architecture/runtime membership policy, but it is still # the reference implementation adopters copy. Compile/test/OpenAPI drift must therefore block PRs. @@ -106,19 +62,6 @@ jobs: working-directory: src run: ./gradlew :sample-portfolio:check --stacktrace - redis-sdk: - # Milestone A of the Redis wrapper/typed API plan: policy catalog, typed API parity, permit - # provenance, connection isolation, and the executor guard. There is no real-server lane yet. - # - # `verifyConfigurationPropertiesProcessor` used to be in this list. It is deleted: the parity it - # enforced — a leaf declares Spring's configuration processor exactly when it owns - # @ConfigurationProperties — is now what applying `ca.spring-config` means. - # `verifyEnvKeys` is no longer named here either; it belongs to :app-bootstrap and runs through - # `configContractCheck`, which the quality-gates job covers. - uses: ./.github/workflows/_reusable-gradle.yml - with: - tasks: ":shared-contract:test --tests '*EdgeRateLimitProviderNeutralContractTest'" - optional-platforms: runs-on: ubuntu-latest steps: @@ -128,104 +71,11 @@ jobs: working-directory: src run: ./gradlew -p optional-platforms ci --stacktrace - configuration-cache: - # Two questions, and they are not the same question. - # - # The first is whether every task in the repository-wide gates can be *stored*. That is a - # property of the task graph, so `--dry-run` answers it for the whole of `ci`, - # `integrationCheck` and `releaseCheck` in seconds, and it is the question this job used to - # duck: it checked two leaves, because four tasks elsewhere held a live `Configuration` in - # their state and could not be serialised at all. They hold resolved root components now, so - # the honest scope is all three gates rather than two leaves. - # - # The second is whether a stored entry is actually *reused* and the build still executes its - # work. `--dry-run` cannot answer that, so the executing check stays — on the two core leaves, - # because doubling a full `ci` run to prove reuse would cost more than the guarantee is worth. - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # actions/checkout@v4.2.2 - - uses: ./.github/actions/setup-gradle-java - - name: Require every repository-wide gate to be storable - working-directory: src - shell: bash - run: | - set -euo pipefail - for gate in ci integrationCheck releaseCheck; do - echo "::group::${gate}" - ./gradlew "${gate}" --dry-run \ - --configuration-cache --configuration-cache-problems=fail --stacktrace - output="$({ ./gradlew "${gate}" --dry-run \ - --configuration-cache --configuration-cache-problems=fail --stacktrace; } 2>&1)" - printf '%s\n' "${output}" - echo '::endgroup::' - grep -Fq 'Reusing configuration cache.' <<<"${output}" || { - echo "::error::Gradle did not reuse the configuration cache for ${gate}." - exit 1 - } - done - - name: Store configuration cache for the everyday core build - working-directory: src - run: >- - ./gradlew - :domain-core:check - :application-core:check - --configuration-cache - --configuration-cache-problems=fail - --stacktrace - - name: Require configuration-cache reuse - working-directory: src - shell: bash - run: | - set -euo pipefail - output="$({ ./gradlew :domain-core:check :application-core:check \ - --configuration-cache --configuration-cache-problems=fail --stacktrace; } 2>&1)" - printf '%s\n' "${output}" - grep -Fq 'Reusing configuration cache.' <<<"${output}" || { - echo '::error::Gradle did not reuse the configuration cache on the second identical build.' - exit 1 - } - - jpa-candidate-evidence: - runs-on: ubuntu-latest - timeout-minutes: 20 - steps: - - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # actions/checkout@v4.2.2 - - uses: ./.github/actions/setup-gradle-java - - name: Produce zero-skip JPA candidate manifests - working-directory: src - run: >- - ./gradlew - :adapter:outbound:persistence-jpa:verifyJpaCandidateEvidence - - --stacktrace - - name: Retain content-addressed JPA candidate manifests - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # actions/upload-artifact@v7.0.1 - with: - name: jpa-candidate-evidence-${{ github.sha }} - path: src/adapter/outbound/persistence-jpa/build/jpa-evidence/manifests - if-no-files-found: error - retention-days: 14 - - # Advisory. The quarantine bucket runs so a flaky test is still executed and reported; it never - # blocks. The 14-day sunset registry that used to make an expired quarantine entry a build failure - # is gone — it was a 250-line YAML-and-Java parser guarding a registry with zero entries. - quarantine: - uses: ./.github/workflows/_reusable-gradle.yml - with: - tasks: ":quarantineTest" - gradle-args: "--stacktrace" - continue-on-error: true - release-gate: needs: - quality-gates - - build-logic - - build-tools - sample-portfolio - - redis-sdk - - jpa-candidate-evidence - optional-platforms - - configuration-cache if: always() runs-on: ubuntu-latest permissions: @@ -234,24 +84,14 @@ jobs: - name: Require every current blocking job to succeed env: QUALITY_RESULT: ${{ needs.quality-gates.result }} - BUILD_LOGIC_RESULT: ${{ needs.build-logic.result }} - BUILD_TOOLS_RESULT: ${{ needs.build-tools.result }} SAMPLE_RESULT: ${{ needs.sample-portfolio.result }} - REDIS_RESULT: ${{ needs.redis-sdk.result }} - JPA_CANDIDATE_RESULT: ${{ needs.jpa-candidate-evidence.result }} OPTIONAL_PLATFORMS_RESULT: ${{ needs.optional-platforms.result }} - CONFIGURATION_CACHE_RESULT: ${{ needs.configuration-cache.result }} run: | set -euo pipefail for result in \ "${QUALITY_RESULT}" \ - "${BUILD_LOGIC_RESULT}" \ - "${BUILD_TOOLS_RESULT}" \ "${SAMPLE_RESULT}" \ - "${REDIS_RESULT}" \ - "${JPA_CANDIDATE_RESULT}" \ - "${OPTIONAL_PLATFORMS_RESULT}" \ - "${CONFIGURATION_CACHE_RESULT}"; do + "${OPTIONAL_PLATFORMS_RESULT}"; do if [[ "${result}" != "success" ]]; then echo "::error::release-gate: required job result was ${result}" exit 1 diff --git a/.github/workflows/fileserver-certification.yml b/.github/workflows/fileserver-certification.yml index 84e14968..5525afc2 100644 --- a/.github/workflows/fileserver-certification.yml +++ b/.github/workflows/fileserver-certification.yml @@ -43,13 +43,6 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # actions/checkout@v4.2.2 - uses: ./.github/actions/setup-gradle-java - - name: Run the architecture-wide dependency and module verification - working-directory: src - run: >- - ./gradlew - :verifyCleanArchitectureDependencies - - --stacktrace - name: Run the complete fileserver suite across every leaf working-directory: src run: >- diff --git a/.github/workflows/fileserver-pr.yml b/.github/workflows/fileserver-pr.yml index a404aefe..c3fd762b 100644 --- a/.github/workflows/fileserver-pr.yml +++ b/.github/workflows/fileserver-pr.yml @@ -108,6 +108,5 @@ jobs: run: >- ./gradlew :adapter:outbound:fileserver:test --tests '*LargeFileBoundedMemoryTest' - :adapter:inbound:web:test --tests '*DataBufferReleaseTest' --stacktrace diff --git a/.github/workflows/integration-main.yml b/.github/workflows/integration-main.yml index 5a034181..80fe4072 100644 --- a/.github/workflows/integration-main.yml +++ b/.github/workflows/integration-main.yml @@ -15,21 +15,20 @@ name: integration-main # shared. They now run on every push to main as well as nightly, which is strictly more often # than before. # -# 2. Lanes that were registered in Gradle and invoked by nothing. Ten Gradle tasks — six MongoDB -# container lanes, app-bootstrap's Testcontainers `integrationTest`, and the three messaging -# evidence tasks that `verifyMessagingContracts` reaches — existed, failed closed, and executed -# in no workflow. A lane nobody runs is not coverage; it is a file that looks like coverage. They +# 2. Lanes that were registered in Gradle and invoked by nothing — the MongoDB container lanes and +# app-bootstrap's Testcontainers `integrationTest` — existed, failed closed, and executed in no +# workflow. A lane nobody runs is not coverage; it is a file that looks like coverage. They # are here rather than in stage 1 because every one of them either starts containers or re-runs # suites the PR gate already covers, and the pull-request budget is minutes for the whole gate. # -# What is deliberately NOT here: the web and WebSocket "Advanced capability" nightly lanes that used -# to exist as web-advanced-nightly.yml and websocket-advanced-nightly.yml. Both leaves' build files -# say it outright — "They also run inside `test`, deliberately ... excluding them from the PR gate to -# make this lane look meaningful would mean the PR gate stopped covering a fifth of the leaf" — so -# `webAdvancedTest` and `websocketAdvancedTest` select tagged tests that `::test` already runs, -# and `::test` runs inside the root `check` on every pull request and every push to main. The -# strict lanes themselves survive in release.yml, where their fail-on-nothing-discovered guard is -# worth a job. +# What is deliberately NOT here: the web "Advanced capability" nightly lane that used to exist as +# web-advanced-nightly.yml (websocket-advanced-nightly.yml went with the websocket Advanced code, +# deleted 2026-09-25). The web leaf's build file says it outright — "They also run inside `test`, +# deliberately ... excluding them from the PR gate to make this lane look meaningful would mean the +# PR gate stopped covering a fifth of the leaf" — so `webAdvancedTest` selects tagged tests that +# `::test` already runs, and `::test` runs inside the root `check` on every pull request +# and every push to main. The strict lane itself survives in release.yml, where its +# fail-on-nothing-discovered guard is worth a job. on: push: @@ -58,6 +57,93 @@ concurrency: # answer: does this link resolve. jobs: + # The main-branch stage of the Gradle gates (`:mainCheck`): the environment contract, full-boot + # qualification, the sample web contract, the public-path baseline, the API surfaces, the + # conditional transport lanes, the messaging contract lanes and the JPA readiness registry. They + # left the pull-request gate (review 2026-09-24 BUILD, item 12); none of them is deleted. + main-check: + runs-on: ubuntu-latest + timeout-minutes: 60 + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # actions/checkout@v4.2.2 + - name: Require the committed public-path security baseline + run: | + set -euo pipefail + readonly snapshot='docs/security/public-paths-snapshot.txt' + if [[ ! -s "${snapshot}" ]] || ! git ls-files --error-unmatch "${snapshot}" >/dev/null 2>&1; then + echo "::error::${snapshot} is missing, empty or not committed; verifyPublicPathSnapshot must not create its own baseline." + exit 1 + fi + - uses: ./.github/actions/setup-gradle-java + - name: Run the main-branch stage + working-directory: src + run: ./gradlew :mainCheck --warning-mode=fail --stacktrace + + # Two questions. Can every task in the repository-wide gates be *stored* (a property of the task + # graph, so `--dry-run` answers it for all of them in seconds)? And is a stored entry *reused* while + # the build still executes its work (checked on the two core leaves)? + configuration-cache: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # actions/checkout@v4.2.2 + - uses: ./.github/actions/setup-gradle-java + - name: Require every repository-wide gate to be storable + working-directory: src + shell: bash + run: | + set -euo pipefail + for gate in ci mainCheck integrationCheck releaseCheck; do + echo "::group::${gate}" + ./gradlew "${gate}" --dry-run \ + --configuration-cache --configuration-cache-problems=fail --stacktrace + output="$({ ./gradlew "${gate}" --dry-run \ + --configuration-cache --configuration-cache-problems=fail --stacktrace; } 2>&1)" + printf '%s\n' "${output}" + echo '::endgroup::' + grep -Fq 'Reusing configuration cache.' <<<"${output}" || { + echo "::error::Gradle did not reuse the configuration cache for ${gate}." + exit 1 + } + done + - name: Store configuration cache for the everyday core build + working-directory: src + run: >- + ./gradlew + :domain-core:check + :application-core:check + --configuration-cache + --configuration-cache-problems=fail + --stacktrace + - name: Require configuration-cache reuse + working-directory: src + shell: bash + run: | + set -euo pipefail + output="$({ ./gradlew :domain-core:check :application-core:check \ + --configuration-cache --configuration-cache-problems=fail --stacktrace; } 2>&1)" + printf '%s\n' "${output}" + grep -Fq 'Reusing configuration cache.' <<<"${output}" || { + echo '::error::Gradle did not reuse the configuration cache on the second identical build.' + exit 1 + } + + jpa-candidate-evidence: + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # actions/checkout@v4.2.2 + - uses: ./.github/actions/setup-gradle-java + - name: Produce zero-skip JPA candidate manifests + working-directory: src + run: ./gradlew :adapter:outbound:persistence-jpa:verifyJpaCandidateEvidence --stacktrace + - name: Retain content-addressed JPA candidate manifests + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # actions/upload-artifact@v7.0.1 + with: + name: jpa-candidate-evidence-${{ github.sha }} + path: src/adapter/outbound/persistence-jpa/build/jpa-evidence/manifests + if-no-files-found: error + retention-days: 14 + # Load, abuse and graceful shutdown measure behaviour that degrades gradually rather than breaking # outright — which is exactly the kind of regression a per-PR gate never catches. web-load-abuse-and-shutdown: @@ -72,7 +158,6 @@ jobs: ./gradlew :adapter:inbound:web:test :adapter:inbound:web:webJettyCompatTest - :adapter:inbound:web:webFluxContractTest --stacktrace - name: Publish the test reports @@ -181,40 +266,6 @@ jobs: path: src/adapter/outbound/persistence-mongo/build/reports/tests/ if-no-files-found: warn - # The messaging contract evidence DAG. `verifyMessagingContracts` is the root of a chain that ran - # nowhere: it depends on four production qualification tasks (application-core, - # shared-contract and two in adapter:outbound:messaging), each of which depends on - # `prepareMessagingContractEvidence`; it is finalizedBy - # `validateMessagingContractsEvidenceManifestSchema`; and it depends on - # `validateMessagingJsonSchemaV1EvidenceManifestSchema`, which depends on - # `verifyMessagingJsonSchemaV1`. Strict qualification tasks are registered outside `check` by - # design (ca.strict-qualification.gradle), so none of the seven was reachable from any workflow. - # - # The schema validators are the part that matters. They re-read the manifest bytes the run just - # wrote and validate them against config/messaging/evidence/build-evidence-manifest-v1.schema.json - # — a manifest that claims a qualification nobody executed is exactly the failure they exist to - # catch, and until now nothing executed them either. - # - # Stage 2 rather than stage 1: no containers, but it runs four qualification suites across three - # leaves plus two JavaExec validators, and the tests it re-runs are already inside the PR gate's - # `check`. What this job adds is the evidence manifest, which is a main-branch artifact. - messaging-contract-evidence: - runs-on: ubuntu-latest - timeout-minutes: 30 - steps: - - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # actions/checkout@v4.2.2 - - uses: ./.github/actions/setup-gradle-java - - name: Qualify the messaging contract, catalog, binding and schema evidence - working-directory: src - run: ./gradlew :verifyMessagingContracts --stacktrace - - name: Publish the messaging evidence manifest - if: always() - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # actions/upload-artifact@v4.6.2 - with: - name: messaging-contract-evidence - path: src/build/messaging-evidence/ - if-no-files-found: warn - # app-bootstrap's Testcontainers lane. The leaf gave it a source set of its own precisely so that # `./gradlew :app-bootstrap:test` would not require a Docker daemon — and the consequence nobody # closed is that a source set outside `test` is also outside `check`, so the real-PostgreSQL @@ -241,9 +292,6 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # actions/checkout@v4.2.2 - uses: ./.github/actions/setup-gradle-java - - name: RabbitMQ transport contract - working-directory: src - run: ./gradlew :messaging:messaging-rabbit:integrationTest --stacktrace - name: Inbox PostgreSQL contract working-directory: src run: ./gradlew :messaging:messaging-inbox-jdbc-postgresql:integrationTest --stacktrace @@ -274,9 +322,6 @@ jobs: - name: Distributed lock contract working-directory: src run: ./gradlew :adapter:outbound:persistence-jpa:postgresqlDistributedLockIntegrationTest --stacktrace - - name: Idempotency unique-scope contract - working-directory: src - run: ./gradlew :adapter:outbound:persistence-jpa:postgresqlIdempotencyUniqueScopeIntegrationTest --stacktrace - name: Integer lock migration compatibility working-directory: src run: ./gradlew :adapter:outbound:persistence-jpa:postgresqlIntLockMigrationCompatibilityIntegrationTest --stacktrace @@ -323,6 +368,9 @@ jobs: # main and nightly; a partial lane run is reproduction only and cannot satisfy this job. The count # is not written here on purpose — a number in prose drifts the moment a lane is added, and the # matrix file is the thing this job reads. + # + # The lanes boot the qualification image (src/Dockerfile COMPOSITION=qualification: every + # capability module present). The script selects it; release.yml builds the default image. compose-runtime-smoke: runs-on: ubuntu-latest timeout-minutes: 180 diff --git a/.github/workflows/jpa-next.yml b/.github/workflows/jpa-next.yml index b7fca39c..7492dbbb 100644 --- a/.github/workflows/jpa-next.yml +++ b/.github/workflows/jpa-next.yml @@ -21,17 +21,17 @@ jobs: - id: jakarta-persistence-4 target: Jakarta Persistence 4 coordinate: jakarta.persistence:jakarta.persistence-api:4.x - test: "*CompatibilityLaneDefinitionTest" + test: "*Jpa4CompatibilityTest" reason: the JPA 4 API is not on any configuration this build resolves, so nothing has been compiled against it - id: hibernate-8 target: Hibernate 8 coordinate: org.hibernate.orm:hibernate-core:8.x - test: "*HibernateCompatibilityPolicyTest" + test: "*Hibernate8CompatibilityTest" reason: Hibernate 8 is not resolvable from this build, so nothing has been compiled or run against it - id: postgresql-19 target: PostgreSQL 19 coordinate: postgres:19-alpine - test: "*ExperimentalPromotionGateTest" + test: "*PostgreSql19CompatibilityTest" reason: no PostgreSQL 19 image is published yet, so no container of that major has ever been started by this lane runs-on: ubuntu-latest timeout-minutes: 60 @@ -61,7 +61,7 @@ jobs: echo "status=NOT_EXECUTABLE" echo "probe-result=${PROBE_OUTCOME}" echo "reason=${REASON}" - echo "what-ran=the current runtime's own policy and lane-definition tests" + echo "what-ran=the current runtime's own version canary for this target" echo "sha=${{ github.sha }}" } > compatibility-evidence/status.properties echo "::notice::${TARGET} compatibility is NOT_EXECUTABLE: ${REASON}" diff --git a/.github/workflows/jpa-release.yml b/.github/workflows/jpa-release.yml index fe23717b..b8a3af7b 100644 --- a/.github/workflows/jpa-release.yml +++ b/.github/workflows/jpa-release.yml @@ -114,15 +114,12 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # actions/checkout@v4.2.2 - uses: ./.github/actions/setup-gradle-java - - name: Verify architecture boundaries and the support matrix + - name: Verify the release registry and the support matrix working-directory: src run: >- ./gradlew :verifyJpaReleaseGateTasks :verifyJpaReadinessRegistry - :verifyCleanArchitectureDependencies - checkstyleMain - :app-bootstrap:architectureTest :adapter:outbound:persistence-jpa:test --tests '*JpaReleaseManifestTest' --stacktrace diff --git a/.github/workflows/notification-platform.yml b/.github/workflows/notification-platform.yml index 62adbb61..75cccd4b 100644 --- a/.github/workflows/notification-platform.yml +++ b/.github/workflows/notification-platform.yml @@ -22,8 +22,8 @@ on: - 'src/adapter/outbound/notification/**' - 'src/adapter/outbound/persistence-jpa/src/**/notification/**' - 'src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/jpa/notification-platform/**' - - 'src/adapter/inbound/web/src/**/notification/**' - - 'src/app-bootstrap/src/**/notification/**' + - 'src/adapter/inbound/web-notification/**' + - 'src/composition/notification-platform/**' - 'src/app-bootstrap/src/main/resources/application*.yml' - 'src/gradle/notification-*.gradle' - 'src/config/architecture/modules.json' @@ -67,7 +67,7 @@ jobs: run: ./gradlew :adapter:outbound:notification:test --console=plain - name: Persistence and web working-directory: src - run: ./gradlew :adapter:outbound:persistence-jpa:test :adapter:inbound:web:test --console=plain + run: ./gradlew :adapter:outbound:persistence-jpa:test :adapter:inbound:web-notification:test :composition:notification-platform:test --console=plain # The PR tier never touched a database, so every claim about migrations, claim atomicity and # lease fencing rested on a fake. Docker is available on this runner; the lane fails closed # when the container cannot start, because a skipped contract reports success for a database @@ -78,22 +78,12 @@ jobs: - name: Notification migration upgrade (real PostgreSQL) working-directory: src run: ./gradlew :adapter:outbound:persistence-jpa:jpaPlatformMigrationTest --console=plain - - name: Architecture gates + # The architecture gates run in ci-quality-gates.yml on the same pull request; the evidence + # manifest (NotificationEvidenceVerifierTest) and the environment registry + # (NotificationEnvironmentRegistryTest) are leaf tests the steps above already ran. + - name: Notification API surface working-directory: src - run: | - ./gradlew :verifyCleanArchitectureDependencies --console=plain - ./gradlew :app-bootstrap:architectureTest --console=plain - - name: Configuration surface - working-directory: src - run: | - ./gradlew :app-bootstrap:verifyEnvKeys :verifyPublicPathSnapshot --console=plain - ./gradlew :verifyNotificationApiSurface :verifyNotificationConfiguration --console=plain - # A support grade is a promise about production behaviour. This refuses one the pipeline - # cannot back — the check that would have caught five channels reading "Stable" while no - # request had ever left the process. - - name: Evidence manifest - working-directory: src - run: ./gradlew :verifyNotificationEvidence --console=plain + run: ./gradlew :adapter:outbound:notification:verifyNotificationApiSurface --console=plain - name: Static analysis working-directory: src run: ./gradlew :adapter:outbound:notification:check -x test --console=plain @@ -125,7 +115,8 @@ jobs: :application-core:test :adapter:outbound:notification:test :adapter:outbound:persistence-jpa:test - :adapter:inbound:web:test + :adapter:inbound:web-notification:test + :composition:notification-platform:test --console=plain # A filter that matches nothing passes. Each --tests filter above names a class that exists # today; if one is renamed the job must fail rather than quietly stop covering it. @@ -149,5 +140,5 @@ jobs: # # The unimplemented state is still stated in two places that do not depend on a workflow: # ProviderSandboxSmokeTest itself, and the unsatisfied provider-wire-qualified claim in - # docs/notification/evidence-manifest.json, which verifyNotificationEvidence enforces inside - # check. When a real sandbox call is implemented, the job comes back with it. + # docs/notification/evidence-manifest.json, which NotificationEvidenceVerifierTest enforces in + # the notification leaf's tests. When a real sandbox call is implemented, the job comes back with it. diff --git a/.github/workflows/pr-adapters.yml b/.github/workflows/pr-adapters.yml index 04fe19a8..b13e5f81 100644 --- a/.github/workflows/pr-adapters.yml +++ b/.github/workflows/pr-adapters.yml @@ -12,8 +12,8 @@ name: pr-adapters # here is only what `check` does not run. # # What `check` does not run, and therefore what this file is for: -# * lanes with their own source set — a second servlet container, a real Nginx, Reactor Netty; -# * lanes selected by a tag that `test` excludes — the cross-stack parity recording comparison; +# * lanes with their own source set — the servlet system contract, a second servlet container, +# a real Nginx; # * lanes parameterised per run — one PostgreSQL major per job, one HTTP transport per job. # Each of those genuinely cannot run inside `check`, which is the test for whether a job belongs # here at all. @@ -126,10 +126,9 @@ jobs: '^infra/jpa/' \ "${common}" - # The parity gate depends on all three recording lanes and fails when one is missing, so it runs - # them itself rather than trusting a previous job to have left the recordings behind. Its tag is - # excluded from `test`, which is why `check` cannot cover it. - web-cross-stack-parity: + # The servlet system contract on both containers the template supports (Tomcat, Jetty). Real + # sockets, so neither lane is part of `check`. + web-servlet-containers: needs: changes if: needs.changes.outputs.web == 'true' runs-on: ubuntu-latest @@ -137,39 +136,21 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # actions/checkout@v4.2.2 - uses: ./.github/actions/setup-gradle-java - - name: Compare the wire contract across Tomcat, Jetty and Reactor Netty + - name: Run the servlet system contract on Tomcat and Jetty working-directory: src run: >- ./gradlew - :adapter:inbound:web:webCrossStackParityTest + :adapter:inbound:web:systemTest + :adapter:inbound:web:webJettyCompatTest --stacktrace - - name: Publish the parity recordings + - name: Publish the test reports if: always() uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # actions/upload-artifact@v4.6.2 with: - name: web-contract-parity - path: src/adapter/inbound/web/build/web-contract-parity/ - if-no-files-found: error - - # Docker-gated, and the lane fails rather than skipping when the runtime is missing. A proxy - # contract that quietly passes without a proxy has been certifying nothing since whenever the - # container runtime last broke. - web-nginx-proxy-contract: - needs: changes - if: needs.changes.outputs.web == 'true' - runs-on: ubuntu-latest - timeout-minutes: 30 - steps: - - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # actions/checkout@v4.2.2 - - uses: ./.github/actions/setup-gradle-java - - name: Run the proxy, prefix and spoofing contract behind a real Nginx - working-directory: src - run: >- - ./gradlew - :adapter:inbound:web:webNginxProxyTest - - --stacktrace + name: web-servlet-containers-reports + path: src/adapter/inbound/web/build/reports/tests/ + if-no-files-found: warn websocket-container-matrix: needs: changes diff --git a/.github/workflows/redis-sdk-topology.yml b/.github/workflows/redis-sdk-topology.yml index a16aa3c1..d29b8a77 100644 --- a/.github/workflows/redis-sdk-topology.yml +++ b/.github/workflows/redis-sdk-topology.yml @@ -31,6 +31,8 @@ name: redis-sdk-topology on: pull_request: paths: + - "src/adapter/outbound/redis-runtime/**" + - "src/adapter/outbound/redis-sdk/**" - "src/adapter/outbound/cache-redis/**" - "infra/redis-sdk/**" - ".github/workflows/redis-sdk-topology.yml" @@ -145,10 +147,15 @@ jobs: working-directory: src run: | set -euo pipefail + # Each leaf declares the lanes its tests qualify; a mode a leaf does not declare fails + # closed, so each topology names exactly the leaves that have classes for it. + runtime=:adapter:outbound:redis-runtime:redisTopologyTest + sdk=:adapter:outbound:redis-sdk:redisTopologyTest + semantic=:adapter:outbound:cache-redis:redisTopologyTest case '${{ matrix.topology }}' in - standalone) port=6379; extra='' ;; - sentinel) port=27010; extra='-Predis.topology.master=skeleton' ;; - cluster) port=7100; extra='' ;; + standalone) port=6379; extra=''; tasks="$runtime $sdk $semantic" ;; + sentinel) port=27010; extra='-Predis.topology.master=skeleton'; tasks="$runtime $sdk" ;; + cluster) port=7100; extra=''; tasks="$runtime $sdk $semantic" ;; # The TLS lane's CA is generated at start-up, so the trust material is extracted from # the lane rather than checked in. A checked-in key is a secret in the repository # however loudly the file is named "test". @@ -156,10 +163,11 @@ jobs: port=6390 docker compose -f ../infra/redis-sdk/tls/compose.yml cp redis:/tls/ca.crt "$RUNNER_TEMP/redis-lane-ca.pem" extra="-Predis.topology.trust-material=$RUNNER_TEMP/redis-lane-ca.pem" + tasks="$runtime" ;; *) echo "unknown topology"; exit 1 ;; esac - ./gradlew :adapter:outbound:cache-redis:redisTopologyTest --console=plain \ + ./gradlew $tasks --continue --console=plain \ -Predis.topology.host=localhost \ -Predis.topology.port="$port" \ -Predis.topology.mode='${{ matrix.topology }}' \ @@ -168,7 +176,7 @@ jobs: if: always() run: | set -euo pipefail - out=src/adapter/outbound/cache-redis/build/test-results/redisTopologyTest + out=src/build/redis-topology-evidence mkdir -p "$out" cat > "$out/evidence-manifest.txt" <- ./gradlew - :adapter:inbound:web:webCrossStackParityTest - :adapter:inbound:web:webNginxProxyTest - :adapter:inbound:web:webAdvancedTest + :adapter:inbound:web:systemTest + :adapter:inbound:web:webJettyCompatTest + :adapter:inbound:web-advanced:webAdvancedTest --stacktrace - name: Publish the release evidence @@ -88,8 +87,8 @@ jobs: with: name: web-release-evidence path: | - src/adapter/inbound/web/build/web-contract-parity/ src/adapter/inbound/web/build/reports/tests/ + src/adapter/inbound/web-advanced/build/reports/tests/ if-no-files-found: error websocket-stable-release-gate: @@ -98,15 +97,15 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # actions/checkout@v4.2.2 - uses: ./.github/actions/setup-gradle-java - - name: Run every websocket lane, Stable and Advanced + - name: Run every websocket lane working-directory: src run: >- ./gradlew :adapter:inbound:websocket:test + :adapter:inbound:websocket:systemTest :adapter:inbound:websocket:websocketJettyTest :adapter:inbound:websocket:websocketNginxTest :adapter:inbound:websocket:websocketTransportQualificationTest - :adapter:inbound:websocket:websocketAdvancedTest --stacktrace - name: Publish the release evidence @@ -120,7 +119,7 @@ jobs: # The three gRPC certification lanes. Their tests already run on every pull request — the # `grpc-inprocess`, `grpc-netty` and `grpc-fault` tags are NOT excluded from # `:grpc:grpc-testkit:test` (only `grpc-performance` is), and that task runs inside the root - # `check`. So this job adds exactly what the web and WebSocket Advanced lanes above add: the lane + # `check`. So this job adds exactly what the web Advanced lane above adds: the lane # fails closed when its tag selects nothing, which is the one thing a tag-filtered suite inside # `test` cannot tell you. A renamed or deleted @Tag would otherwise leave the in-process, # transport and fault evidence grades claiming coverage that stopped existing. diff --git a/AGENTS.md b/AGENTS.md index 70d13656..d42f2b5a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -49,8 +49,8 @@ root `CLAUDE.md`는 이 목록의 동기화된 요약이다. 두 문서가 어 ## Gradle 정책 권위 - `src/config/architecture/modules.json`: 등록된 모든 leaf의 ID, repository-relative 소스 경로, - Gradle path, 허용 production project dependency edge. runtime membership은 실제 resolved - runtimeClasspath에서 검증하며 registry에 별도 membership 목록을 복제하지 않는다. leaf 목록과 그 개수의 SSOT는 registry다. 문서는 개수를 복제하지 않는다 — + Gradle path, 허용 production project dependency edge. runtime membership 목록은 없다: 조립 루트가 + 받을 수 있는 모듈은 `allowed_dependencies`가 정하고, 방향 게이트가 그 밖의 edge를 막는다. leaf 목록과 그 개수의 SSOT는 registry다. 문서는 개수를 복제하지 않는다 — 산문에 적힌 숫자는 leaf가 추가되는 순간 drift하기 때문이다. 이제 이걸 강제하는 태스크는 없다: `verifyDocumentedLeafCount`는 삭제됐다. 문서에 적힌 수가 틀린 것은 결함이지만 빌드를 실패시킬 사유는 아니고, 그 태스크는 모든 `CLAUDE.md`와 `build.gradle`을 정규식으로 훑는 파서였다. @@ -59,10 +59,15 @@ root `CLAUDE.md`는 이 목록의 동기화된 요약이다. 두 문서가 어 경로, 없는 디렉터리)만 여기서 실패한다. 허용되지 않는 edge 같은 아키텍처 규칙은 `verifyCleanArchitectureDependencies`가 답한다 — settings에서 죽으면 실행할 수 있는 태스크가 하나도 없다. -- `src/build-logic/`: convention plugin. leaf는 `ca.java-library` / `ca.spring-library` / - `ca.platform-module` 중 자기 성격을 선언하고, 그 플러그인이 toolchain·락·정적분석·테스트 - 기본값을 준다. `ca.architecture`가 아키텍처 검증 태스크를 소유한다. -- `src/build.gradle`: 루트 라이프사이클(`ci`, `releaseCheck`, `qualityCheck`, +- `src/build-logic/`: 아키텍처 코어(registry, 방향·순수성 task), 컨벤션, 테스트 레인 하나 + (`strictTestLanes`). leaf는 `ca.java-library` / `ca.spring-library` / `ca.platform-module` 중 + 자기 성격을 선언하고, 그 플러그인이 toolchain·락·정적분석·테스트 기본값을 준다. + `ca.architecture`가 아키텍처 검증 태스크를 소유한다. 기능별 검사(notification·mongo·messaging· + graphql 등)는 build-logic이 아니라 소유 leaf의 테스트다. 테스트가 저장소 파일을 읽으면 그 파일을 + 그 leaf의 test task `inputs`로 선언한다. +- `src/build-tools/`: 아직 옮기지 않은 검사만 남는다(`ca.config-contract`의 `verifyEnvKeys`, JPA + evidence·readiness·release registry). 새 검사를 여기에 추가하지 않는다. +- `src/build.gradle`: 루트 라이프사이클(`ci`, `mainCheck`, `releaseCheck`, `qualityCheck`, `configContractCheck`, `integrationCheck`)과 버전/리비전 작업 파일의 소유 leaf는 registry의 `source_path`로 판단하고 가장 가까운 `src/**/CLAUDE.md`를 @@ -86,7 +91,7 @@ commit 정책은 모든 플랫폼에서 `human-only`이며 agent는 stage/commit ## 모듈 책임 -모든 leaf 모듈의 ID, 실제 소스 경로, Gradle path, 허용 production 의존성, runtime membership은 +모든 leaf 모듈의 ID, 실제 소스 경로, Gradle path, 허용 production 의존성은 `src/config/architecture/modules.json`이 SSOT다. focused test는 소유 leaf의 `gradle_path`에서 파생한다. 이 문서는 leaf 목록을 복제하지 않고 family 책임만 정의한다. 작업 파일에서는 가장 가까운 `src/**/CLAUDE.md`를 함께 읽는다. @@ -145,6 +150,27 @@ Gradle 의존성 검증도 같은 registry를 읽는다. root 문서나 기억 - 그 밖의 `adapter:outbound:*`: external capability adapter contract를 검증한다. - `app-bootstrap/settings`: configuration binding, validation, logging 설정을 검증한다. +테스트 작성 규칙 (새로 쓰거나 고치는 테스트에 적용): + +1. 이름은 lowerCamelCase 행동 문장(`<상황/주체><결과>`)이다. 이름에 적은 성질은 반드시 단언한다. +2. `@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`로 쓴다. +6. 포트 대역은 hand-rolled fake를 포트당 하나, 포트 소유 모듈 testFixtures에 둔다. adapter가 있는 + 포트는 fake와 adapter가 같은 추상 계약 테스트(`XxxContract`)를 통과한다. Mockito는 프레임워크 + 경계(Spring Data repository, SDK client)와 장애 주입에만 쓴다. + +GWT 주석을 검사하는 자동 게이트는 만들지 않는다. 주석은 bytecode에 없어 ArchUnit이 볼 수 없고, +실질적인 강제 수단은 fake와 adapter가 같은 계약 테스트를 상속하는 구조다. + 검증 원칙: - 완료를 주장하기 전에 `superpowers:verification-before-completion`을 사용한다. @@ -157,9 +183,10 @@ Gradle 의존성 검증도 같은 registry를 읽는다. root 문서나 기억 cd src ./gradlew :check --console=plain # 그 leaf만: 컴파일·테스트·포맷·스타일·ErrorProne ./gradlew check # 모든 leaf의 check -./gradlew architectureCheck # 의존 방향·런타임 멤버십·application-core 순수성 +./gradlew architectureCheck # 의존 방향·domain-core/shared-contract/application-* 순수성·ArchUnit ./gradlew qualityCheck # SpotBugs + FindSecBugs (leaf check에는 없다) -./gradlew ci # PR 게이트 = leaf check + architecture + quality + config + qualification +./gradlew ci # PR 게이트 = leaf check + architecture + quality +./gradlew mainCheck # main 단계 = env 계약·전체 기동·public path·API surface·전송/메시징 레인·JPA readiness ./gradlew verifyPublicPathSnapshot ./gradlew :app-bootstrap:verifyEnvKeys ``` @@ -169,6 +196,39 @@ leaf의 `check`는 그 leaf만 검사한다. 저장소 전체 질문은 이름 소유 leaf의 정확한 Gradle path는 `src/config/architecture/modules.json`에서 읽고 focused test 명령을 파생한다. root 문서에 leaf별 명령 목록을 복제하지 않는다. +## 부가 기능(capability) 모듈 규칙 + +Redis, Kafka, JPA 같은 부가 기능은 "의존성을 붙이면 켜지고, 떼면 사라지는 모듈"로 제공한다. +각 서비스는 `app-bootstrap/build.gradle`에 필요한 모듈만 `runtimeOnly` 한 줄로 고른다. +설계 근거는 `docs/superpowers/specs/2026-09-25-capability-module-packaging-design.md`. + +템플릿 기본 조립은 web에서 쓰는 부분뿐이다: `adapter:inbound:web`, 운영 관측(actuator·metrics· +tracing·로그), `domain-core`·`application-core`·`shared-contract`, `adapter:outbound:support`· +`adapter:outbound:identifier`. 그 밖의 기능(JPA 포함)은 한 줄을 추가해서 켠다. + +capability 모듈 완료 기준 (7개 모두 충족해야 "포장 완료"): + +1. 서비스 코드는 application-core의 포트만 호출한다. 그래서 모듈을 `runtimeOnly`로 받을 수 있다. +2. 모듈이 자기 `AutoConfiguration.imports`를 가진다. 모듈이 있으면 켜지고, 필요하면 `enabled` + 설정으로 끌 수 있다. 다른 자동 설정에 기대면 순서를 명시한다(`afterName`). +3. 켜면 완전히 동작한다. 문서에 적은 옵션은 전부 실제로 동작하고, 동작하지 않는 옵션은 설정 키 + 자체를 두지 않는다. +4. 설정 prefix는 하나만 쓴다. 바인딩은 `StrictSettingsBinder`, 값 검증은 설정 record의 compact + constructor에서 한다. +5. 포트 소유 모듈 testFixtures의 포트 계약 테스트(추상 클래스)를 fake와 실제 어댑터가 모두 + 통과한다. 실제 벤더(Testcontainers)로 도는 테스트가 1개 이상 있다. +6. 모듈 README에 세 가지를 적는다: 제공하는 것, 추가할 한 줄, 필요한 env 키. +7. 이 모듈을 아는 곳은 모듈 자신뿐이다. bootstrap의 scan 정규식이나 스위치 목록에 등록하지 + 않고, 한 줄을 지우면 기능이 완전히 사라진다. + +모듈 설정 기본값은 `config/module-defaults/<모듈>.yml`에 두고 `adapter:outbound:support`의 +`ModuleDefaultsEnvironmentPostProcessor` 하나가 읽는다. 의존성 closure에 support가 없는 leaf +(persistence-mongo, graphql)만 자기 EPP가 `config/<이름>.yml`을 읽는다. + +서비스 코드가 모듈 타입을 직접 호출해야 하는 라이브러리형 기능은 `runtimeOnly`로 컴파일되지 +않는다. 그런 기능은 가능한 한 포트 뒤로 옮기고, 불가피하면 서비스의 어댑터 leaf에서 +`implementation`으로 받는다. + ## 설정과 런타임 설정 규칙: diff --git a/CLAUDE.md b/CLAUDE.md index 4fb22433..1910b05a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -21,12 +21,18 @@ If this summary drifts from `AGENTS.md`, `AGENTS.md` wins and this summary must ## Gradle policy authorities - `src/config/architecture/modules.json`: every registered leaf identity, repository-relative source - paths, Gradle paths, allowed production project dependency edges, and the exact runtime - memberships of both composition roots. The registry owns the leaf list and its size; no document - restates the count, because a number written in prose drifts the moment a leaf is added. + paths, Gradle paths and allowed production project dependency edges. There is no runtime + membership list: what a composition root may take is its `allowed_dependencies`, and the direction + gate refuses any other edge. The registry owns the leaf list and its size; no document restates + the count, because a number written in prose drifts the moment a leaf is added. - `src/settings.gradle`: fail-closed registry validation, project inclusion, and directory mapping. -- `src/build.gradle`: `verifyCleanArchitectureDependencies` and the other architecture-wide - verification tasks. +- `src/build-logic/`: the architecture core (registry, direction and purity tasks), the conventions, + and one test-lane mechanism (`strictTestLanes`). Feature-specific checks are the owning leaf's + tests; a test that reads repository files declares them as that leaf's test `inputs`. +- `src/build-tools/`: only checks not yet moved (`verifyEnvKeys`, JPA evidence/readiness/release + registry). Do not add new checks there. +- `src/build.gradle`: the root lifecycle (`ci`, `mainCheck`, `releaseCheck` and the named + repository-wide gates). Commit policy is `human-only`: agents do not stage, commit, amend, or push implementation changes. @@ -112,15 +118,30 @@ Architecture-wide commands: ``` A leaf's `check` covers that leaf only — compile, its tests, Spotless, Checkstyle, Error Prone. -Repository-wide questions have their own names: `architectureCheck` (dependency direction, runtime -membership, application-core purity, Git-carryable sources), `qualityCheck` (SpotBugs, FindSecBugs), -`configContractCheck` (the environment contract), `integrationCheck` (the declared strict test -lanes). `ci` is leaf checks + architectureCheck + qualityCheck + configContractCheck + qualificationCheck; `releaseCheck` adds -provenance, archive hygiene and the public-path snapshot. +Repository-wide questions have their own names: `architectureCheck` (dependency direction, purity +of domain-core/shared-contract/application-*, Git-carryable sources, ArchUnit), `qualityCheck` +(SpotBugs, FindSecBugs), `configContractCheck` (the environment contract), `integrationCheck` (the +declared strict integration lanes). `ci` (pull request) is leaf checks + architectureCheck + +qualityCheck; `mainCheck` (main branch) is configContractCheck + qualificationCheck + the sample web +contract + the public-path snapshot + API surfaces + the transport and messaging qualification lanes ++ the JPA readiness registry; `releaseCheck` is `ci` + provenance, archive hygiene and the +public-path snapshot. + +Test-writing rules (behavior-sentence names that assert what they promise, given/when/then comments, +one `// when`, one fake per port in the port owner's testFixtures, fake and adapter sharing one +abstract contract test) are canonical in `AGENTS.md`. Use public-path and env-key checks only when their surfaces changed. Full `test`, `check` or `ci` requires the controller's workflow authorization. +## Capability modules + +Optional features (JPA, Redis, Kafka, notification, Mongo, object storage, HTTP client, GraphQL, +WebSocket, gRPC, file server) are modules that turn on when present and disappear when removed. A +service selects them with one `runtimeOnly` line each in `app-bootstrap/build.gradle`; the template's +default composition is the web inbound adapter, observability, the cores, and support/identifier. The +seven completion criteria for a capability module are canonical in `AGENTS.md`. + ## Advisory and reporting Use dependency-DAG/topological reasoning and 3–5 materially distinct alternatives when that many diff --git a/README.md b/README.md index 6ff9d533..b837502b 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ family 수준의 책임은 다음과 같습니다. | `application-core` | command·유스케이스·application 정책·트랜잭션 port. inbound DTO·persistence entity 금지 | | `adapter:inbound:*` | HTTP·gRPC·GraphQL·WebSocket transport 경계, DTO·validation·인증·에러 매핑 | | `adapter:outbound:persistence-*` | JPA/PostgreSQL·MongoDB 영속 구현과 매핑·migration | -| `adapter:outbound:*` | support(공유 베이스)·messaging·cache·notification·object storage·file·HTTP client·identifier 능력을 port 뒤에서 구현. 외부 연동 어댑터(messaging·cache·notification·HTTP client)는 기본 비활성 | +| `adapter:outbound:*` | support(공유 베이스)·messaging·cache·notification·object storage·file·HTTP client·identifier 능력을 port 뒤에서 구현. 기본 조립에는 support·identifier만 들어 있고, 나머지는 `app-bootstrap/build.gradle`의 `runtimeOnly` 한 줄로 고릅니다 | | `shared-contract` | skeleton 전역 운영 계약. business/domain 개념 저장 금지 | | `app-bootstrap` | Spring Boot entrypoint와 composition root | | `sample-portfolio` | WorkLog 예시 도메인(fixture/reference). production이 의존하지 않음 | @@ -42,7 +42,7 @@ cd src ./gradlew bootstrap ``` -`bootstrap`은 compile 검사, PostgreSQL Compose 기동, 애플리케이션 이미지 build·기동(startup Flyway 포함), sample 격리 검증, `GET /api/healthcheck` HTTP smoke를 순서대로 실행합니다. 각 단계가 별도 Gradle task라 실패 단계가 task 이름으로 드러납니다. 기동을 확인하려면 health endpoint를 호출합니다. +`bootstrap`은 compile 검사, PostgreSQL Compose 기동, 애플리케이션 이미지 build·기동, sample 격리 검증, `GET /api/healthcheck` HTTP smoke를 순서대로 실행합니다. 각 단계가 별도 Gradle task라 실패 단계가 task 이름으로 드러납니다. 기동을 확인하려면 health endpoint를 호출합니다. ```bash curl -fsS http://localhost:8080/api/healthcheck @@ -56,22 +56,27 @@ docker compose -f docker-compose.yml -f docker-compose.local.yml down `src/.env.example`은 배포 환경 변수의 추적 가능한 복사/검증 계약이고 `src/.env`는 로컬 실행 입력입니다. 전체 환경 변수 목록과 조정 시점은 [src/README.md](src/README.md)와 [docs/registries/env-keys.yaml](docs/registries/env-keys.yaml)에 있습니다. -### 프로파일별 데이터스토어 +### 기본 조립과 부가 기능 -`bootstrap`은 컨테이너 경로(PostgreSQL)를 검증하는 첫 실행 진입점입니다. 일상 개발은 Docker 없이 돌리는 `local` 프로파일이며, 이때 데이터스토어는 H2 in-memory입니다. +기본 조립(`bootJar`)은 web, 관측, `domain-core`·`application-core`·`shared-contract`, support, +identifier뿐이라 DB·Redis·Kafka 없이 기동합니다. ```bash cd src ./gradlew :app-bootstrap:bootRun ``` -| 프로파일 | 데이터스토어 | 스키마 소유자 | +DB, Redis, Kafka, 알림, 파일 서버 같은 부가 기능은 `app-bootstrap/build.gradle`에 주석 처리된 +`runtimeOnly` 한 줄씩으로 있습니다. 줄의 주석을 풀고 필요한 env를 넣으면 켜지고, 줄을 지우면 사라집니다. +줄마다 필요한 env와 끄는 키는 [src/README.md](src/README.md)의 "기능 추가 = 한 줄 + env" 표에 있습니다. + +| 프로파일 | 데이터스토어 (persistence-jpa 줄을 넣었을 때) | 스키마 소유자 | | --- | --- | --- | -| `local` (bootRun 기본) | H2 in-memory | Hibernate `create-drop` | +| `local` | Compose PostgreSQL (`./gradlew :app-bootstrap:bootRunH2`는 줄 없이도 모듈을 자기 classpath에 올려 H2 in-memory로 실행) | Flyway (H2는 Hibernate `create-drop`) | | `dev` | PostgreSQL | Flyway | | `prod` | PostgreSQL | Flyway | -`local`은 wiring과 애플리케이션 동작을 검증하고, migration과 vendor 동작은 검증하지 않습니다. 프로파일별 설정은 [src/app-bootstrap/src/main/resources/](src/app-bootstrap/src/main/resources/)의 `application-{local,dev,prod}.yml`이, 상세 설명은 [src/README.md](src/README.md)가 소유합니다. +H2 실행은 wiring과 애플리케이션 동작만 검증하고, migration과 vendor 동작은 검증하지 않습니다. 프로파일별 설정은 [src/app-bootstrap/src/main/resources/](src/app-bootstrap/src/main/resources/)의 `application-{local,dev,prod}.yml`이, 상세 설명은 [src/README.md](src/README.md)가 소유합니다. ## 새 프로젝트로 시작하기 diff --git a/docker-compose.yml b/docker-compose.yml index 06bcb473..dcb44cdb 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -33,7 +33,12 @@ services: BUILD_VERSION: "${BUILD_VERSION:-0.0.1+0000000}" GIT_SHA: "${GIT_SHA:-0000000}" SOURCE_URL: "${SOURCE_URL:-https://example.invalid/ca-tmpl}" - image: caskeleton:${BUILD_VERSION:-0.0.1_local_0000000} + # default = the composition a service ships. scripts/run-compose-runtime-smoke.sh sets + # qualification: every capability module present, each lane switching on what it tests. + COMPOSITION: "${COMPOSITION:-default}" + # The composition is in the tag, so a lane's qualification image is never reused as the + # default one (Compose reuses a matching tag instead of building). + image: caskeleton:${BUILD_VERSION:-0.0.1_local_0000000}-${COMPOSITION:-default} # Generated per run by scripts/run-compose-runtime-smoke.sh and removed on teardown. Seven values # have no inline default on purpose — the datasource address and credential, the application # name, and the JWT issuer and audience — so a lane has to supply them, and a lane that borrowed diff --git a/docs/adr/ADR-JPA-002-full-transaction-retry.md b/docs/adr/ADR-JPA-002-full-transaction-retry.md index 76eb2cb6..e10b4063 100644 --- a/docs/adr/ADR-JPA-002-full-transaction-retry.md +++ b/docs/adr/ADR-JPA-002-full-transaction-retry.md @@ -1,6 +1,9 @@ # ADR-JPA-002 — Retry re-runs the whole use case -- Status: Accepted +- Status: Superseded (2026-09-25) — the retry engine this ADR describes + (`FullTransactionRetryCoordinator`, `JpaTransactionExecutor`) was removed. `SpringTransactionPort` + retries nothing; a caller that retries still re-runs the whole use case, which is the part of this + decision that stands. The last commit is in `docs/capability-status.md`. - Date: 2026-08-11 - Design: §19.2 diff --git a/docs/adr/ADR-JPA-003-completion-unknown.md b/docs/adr/ADR-JPA-003-completion-unknown.md index 82e4caf9..b78a0d25 100644 --- a/docs/adr/ADR-JPA-003-completion-unknown.md +++ b/docs/adr/ADR-JPA-003-completion-unknown.md @@ -1,6 +1,8 @@ # ADR-JPA-003 — Completion unknown is never retried -- Status: Accepted +- Status: Accepted; amended 2026-09-25 — `TransactionCompletionResolver`, `CommitFailureClassifier` + and the retry engine were removed. The invariant holds because `SpringTransactionPort`, the only + transaction engine, retries nothing; enforcement below is updated accordingly. - Date: 2026-08-11 - Design: §17 @@ -14,7 +16,7 @@ acknowledgement may simply have been lost. The driver cannot tell the two apart. `TransactionCompletionUnknownException` is never retried, automatically or otherwise. It is produced only by a failure observed while the transaction phase is `COMMITTING`, and only for SQLSTATE `40003`, a connection-class (`08*`) state, or a transport break. Recovery is -domain-specific reconciliation through `TransactionCompletionResolver`. +domain-specific reconciliation. ## Consequences @@ -37,5 +39,6 @@ which idempotency record, business row, or outbox entry proves the write happene ## Enforcement -`JpaFailureContextTest`; `DefaultJpaRetryPolicyTest`; `CommitFailureClassifierTest`; release gate -`completion-unknown-no-retry`. +`JpaFailureContextTest`; +`PostgreSqlTransactionIntegrationTest#connectionLossDuringCommitSurfacesAsAFailureAndIsNeverRetried` +(also the `jpa-failure` lane, i.e. release gate `completion-unknown-no-retry`). diff --git a/docs/adr/ADR-JPA-004-flyway-schema-source-of-truth.md b/docs/adr/ADR-JPA-004-flyway-schema-source-of-truth.md index 584424be..c063e5e0 100644 --- a/docs/adr/ADR-JPA-004-flyway-schema-source-of-truth.md +++ b/docs/adr/ADR-JPA-004-flyway-schema-source-of-truth.md @@ -33,5 +33,6 @@ intended cost: it makes schema change reviewable and reversible. ## Enforcement -`JpaDangerousConfigurationGuard`; `FlywaySchemaPolicy`; `FlywayValidationGate`; -`PostgreSqlRuntimeRoleVerifier`; release gates `flyway-validate` and `runtime-role-no-ddl`. +`JpaDangerousConfigurationGuard`; `FlywaySchemaPolicy`; `FlywayValidationGate` (testkit, used by the +migration contract tests); `PostgreSqlRuntimeRoleVerifier`; release gates `flyway-validate` and +`runtime-role-no-ddl`. diff --git a/docs/adr/ADR-MONGO-ADV-001-capability-promotion.md b/docs/adr/ADR-MONGO-ADV-001-capability-promotion.md index ad6a969f..a3b54030 100644 --- a/docs/adr/ADR-MONGO-ADV-001-capability-promotion.md +++ b/docs/adr/ADR-MONGO-ADV-001-capability-promotion.md @@ -3,6 +3,13 @@ - **Status:** Accepted - **Date:** 2026-08-13 - **Design source:** design §2 (D-15), §3.2–§3.3; Advanced expansion plan Task 15 +- **Amended 2026-09-25:** the `ca-skeleton.persistence-mongo.advanced.*.enabled` binding + (`MongoAdvancedConfiguration`/`MongoAdvancedSettings`) was imported by nothing, so no deployment + property ever reached the flags; it was removed together with `propertyFor`. The flags are now + built in code by the adapter that constructs an entry point. `MongoAdvancedPromotionGate`, + `MongoAdvancedPromotionEvidence`, `MongoVectorSearchBenchmarkGate` and the search, vector, time + series and GridFS packages (interfaces with no implementation) were removed. The evidence + categories below remain a review obligation; no class checks them. ## Context diff --git a/docs/adr/ADR-WEB-ADV-001-streaming-is-live-delivery.md b/docs/adr/ADR-WEB-ADV-001-streaming-is-live-delivery.md index b6a59ec6..e54311a0 100644 --- a/docs/adr/ADR-WEB-ADV-001-streaming-is-live-delivery.md +++ b/docs/adr/ADR-WEB-ADV-001-streaming-is-live-delivery.md @@ -19,15 +19,16 @@ retention, its own eviction and its own opinion about ordering. ## Decision -**Three outcomes, expressed in the stream rather than in the status.** `WebStreamEnvelope` is sealed -over `Item`, `Failure` and `Complete`. A client that sees neither terminal envelope has been cut off, -and that third case is recorded as `ABRUPT_CLOSE` rather than counted as a completion — which is -where a rising rate of mid-stream failures would otherwise hide. +**Three outcomes, expressed in the stream rather than in the status.** The wire record (for NDJSON, +`NdjsonRecord`) is an item, a failure or a completion. A client that sees neither terminal record +has been cut off, and that third case is recorded as `ABRUPT_CLOSE` rather than counted as a +completion — which is where a rising rate of mid-stream failures would otherwise hide. -**Nothing writes a problem document onto a committed response.** `WebStreamTerminationMapper` -branches on whether any byte has been written. Before commit, an RFC 9457 problem with a real -status; after, a terminal record. Attempting both produces a body that is half stream and half JSON, -which no client parses and every proxy caches as a success. +**Nothing writes an error body onto a committed response.** Before commit, a failure is an ordinary +HTTP error (the `Envelope`) with a real status; after, a terminal record. Attempting both produces a +body that is half stream and half JSON, which no client parses and every proxy caches as a success. +(The mapper that encoded this, `WebStreamTerminationMapper`, was removed on 2026-09-25 with the +problem-document vocabulary it returned; the rule stands.) **Positions are monotonic, and it is enforced.** `WebStreamEvidence.recordDelivered` refuses a repeated or regressing position. A client deduplicating on position would silently drop the second diff --git a/docs/adr/ADR-WEB-ADV-002-virtual-threads-do-not-remove-admission.md b/docs/adr/ADR-WEB-ADV-002-virtual-threads-do-not-remove-admission.md index 12a27e64..e76ebc72 100644 --- a/docs/adr/ADR-WEB-ADV-002-virtual-threads-do-not-remove-admission.md +++ b/docs/adr/ADR-WEB-ADV-002-virtual-threads-do-not-remove-admission.md @@ -6,8 +6,9 @@ ## Context -Advanced Task 2 offers a virtual-thread executor for MVC; Task 3 offers a bounded blocking bridge -for WebFlux. +Advanced Task 2 offers a virtual-thread executor for MVC; Task 3 offered a bounded blocking bridge +for WebFlux. (The WebFlux adapter for it was removed on 2026-09-25 — the template is servlet only; +`advanced.blockingbridge` remains as library code.) A platform-thread MVC deployment has an implicit concurrency limit — the thread pool — and that limit is usually what has been protecting the database pool, the outbound HTTP bulkhead and every @@ -40,6 +41,9 @@ offload; `BlockingBridgeBudget` bounds the concurrency and refuses a caller that in time, because otherwise a slow dependency's callers accumulate until the heap does and the fast dependencies starve behind them. +> 2026-09-25: `advanced.blockingbridge` was removed. Its WebFlux adapter went with the WebFlux twin +> (D4), and a budget for a bridge that no longer exists bounded nothing. + **Pinning is observed, not assumed away.** `VirtualThreadProfile.requiredObservations()` lists what has to be watched — `jdk.VirtualThreadPinned` above all. A synchronized block held across a blocking call pins the carrier thread, the carrier pool is bounded by CPU count, and enough pinned carriers is diff --git a/docs/adr/ADR-WEB-ADV-003-openapi-32-remains-experimental.md b/docs/adr/ADR-WEB-ADV-003-openapi-32-remains-experimental.md index 052fa3de..f91133d0 100644 --- a/docs/adr/ADR-WEB-ADV-003-openapi-32-remains-experimental.md +++ b/docs/adr/ADR-WEB-ADV-003-openapi-32-remains-experimental.md @@ -23,6 +23,10 @@ contributor that mutates it on the way to 3.2 changes the artifact that is actua silently, and only when the experimental lane runs. `OpenApi32CompatibilityReport` compares the snapshot hash before and after and makes a difference a promotion blocker. +> 2026-09-25: `OpenApi32CompatibilityReport` and `OpenApiToolchainMatrix` were removed — promotion +> checks kept in production code, called only by their own tests. `WebOpenApi32Generator` remains +> as library code in `adapter:inbound:web-advanced`; the decision below is unchanged. + **Four kinds of tool are checked separately.** A parser reports structural errors; a linter applies style rules and accepts documents a parser rejects; a generator produces client code, and this is where an unsupported construct surfaces — not as an error but as a method with the wrong signature; diff --git a/docs/adr/ADR-WS-001-platform-as-packages-and-its-boundaries.md b/docs/adr/ADR-WS-001-platform-as-packages-and-its-boundaries.md index 77cf914d..442ebee5 100644 --- a/docs/adr/ADR-WS-001-platform-as-packages-and-its-boundaries.md +++ b/docs/adr/ADR-WS-001-platform-as-packages-and-its-boundaries.md @@ -1,6 +1,9 @@ # ADR-WS-001: The WebSocket platform ships as packages in one leaf, with machine-checked boundaries -- Status: accepted +- Status: Superseded 2026-09-25 — the eighteen-package platform was cut to the parts a Spring + configuration or a real-container lane reaches: the `stomp` channel and the servlet handler + library (`servlet`, `outbound`, `budget`). The Advanced packages, the reactive runtime and the + `WebSocketArchitectureRules` pack went with the rest (see `docs/capability-status.md`). - Date: 2026-08-25 - Scope: `:adapter:inbound:websocket` diff --git a/docs/adr/ADR-WS-002-resume-and-cluster.md b/docs/adr/ADR-WS-002-resume-and-cluster.md index 54c0f375..6f2be96e 100644 --- a/docs/adr/ADR-WS-002-resume-and-cluster.md +++ b/docs/adr/ADR-WS-002-resume-and-cluster.md @@ -1,6 +1,7 @@ # ADR-WS-002: Resume and cluster state are caches, and are treated as caches -- Status: Accepted +- Status: Superseded 2026-09-25 — `advanced.resume`, `advanced.cluster` and `advanced.presence` + were removed: nothing assembled them (see `docs/capability-status.md`). - Date: 2026-08-25 - Scope: `adapter:inbound:websocket` — `advanced.resume`, `advanced.cluster`, `advanced.presence` diff --git a/docs/adr/ADR-WS-003-stomp-and-broker-relay.md b/docs/adr/ADR-WS-003-stomp-and-broker-relay.md index c0b0d684..6f8aff4b 100644 --- a/docs/adr/ADR-WS-003-stomp-and-broker-relay.md +++ b/docs/adr/ADR-WS-003-stomp-and-broker-relay.md @@ -1,6 +1,7 @@ # ADR-WS-003: STOMP is an Advanced adapter with a declared destination catalog -- Status: Accepted +- Status: Superseded 2026-09-25 — `advanced.stomp` and `advanced.stomp.rabbit` were removed; the + `stomp` package is the only STOMP channel (see `docs/capability-status.md`). - Date: 2026-08-25 - Scope: `adapter:inbound:websocket` — `advanced.stomp`, `advanced.stomp.rabbit` diff --git a/docs/architecture/graphql-api-surface.txt b/docs/architecture/graphql-api-surface.txt index e61fafc6..29640c18 100644 --- a/docs/architecture/graphql-api-surface.txt +++ b/docs/architecture/graphql-api-surface.txt @@ -5,180 +5,22 @@ # split into capability artifacts. # Update only after review with: # ./gradlew :adapter:inbound:graphql:updateGraphQlApiSurface -PapproveGraphQlApiSurfaceChange -# types: 401 +# types: 168 dev.caskeleton.adapter.inbound.graphql.HealthGraphqlController -dev.caskeleton.adapter.inbound.graphql.advanced.admin.GraphQlAdminPrincipal -dev.caskeleton.adapter.inbound.graphql.advanced.admin.GraphQlPersistedOperationAdminAuthorization -dev.caskeleton.adapter.inbound.graphql.advanced.admin.GraphQlPersistedOperationAdminDeniedException -dev.caskeleton.adapter.inbound.graphql.advanced.admin.GraphQlPersistedOperationAdminPort -dev.caskeleton.adapter.inbound.graphql.advanced.admin.GraphQlPersistedOperationAdminService -dev.caskeleton.adapter.inbound.graphql.advanced.admin.GraphQlPersistedOperationAudit -dev.caskeleton.adapter.inbound.graphql.advanced.admin.GraphQlPersistedOperationBlockCommand -dev.caskeleton.adapter.inbound.graphql.advanced.admin.GraphQlPersistedOperationRemovalGate -dev.caskeleton.adapter.inbound.graphql.advanced.admin.GraphQlPersistedOperationRemovalRejectedException -dev.caskeleton.adapter.inbound.graphql.advanced.admin.GraphQlPersistedOperationUsage -dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedCapability -dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedCapabilityDisabledException -dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedCapabilityGrade -dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedDependencyRules -dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedFeatureFlags -dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedModuleGuard -dev.caskeleton.adapter.inbound.graphql.advanced.chaining.GraphQlChainedDataLoaderPolicy -dev.caskeleton.adapter.inbound.graphql.advanced.chaining.GraphQlChainedDispatchConfigurer -dev.caskeleton.adapter.inbound.graphql.advanced.chaining.GraphQlChainedLoaderMetrics -dev.caskeleton.adapter.inbound.graphql.advanced.chaining.GraphQlDataLoaderCycleDetector -dev.caskeleton.adapter.inbound.graphql.advanced.chaining.GraphQlDataLoaderDependencyCycleException -dev.caskeleton.adapter.inbound.graphql.advanced.chaining.GraphQlDataLoaderDependencyGraph -dev.caskeleton.adapter.inbound.graphql.advanced.codegen.GraphQlClientOperationGenerator -dev.caskeleton.adapter.inbound.graphql.advanced.codegen.GraphQlCodegenBoundaryException -dev.caskeleton.adapter.inbound.graphql.advanced.codegen.GraphQlCodegenProfile -dev.caskeleton.adapter.inbound.graphql.advanced.codegen.GraphQlGeneratedCompatibilityGate -dev.caskeleton.adapter.inbound.graphql.advanced.codegen.GraphQlGeneratedSourceBoundary -dev.caskeleton.adapter.inbound.graphql.advanced.codegen.GraphQlOperationValidator -dev.caskeleton.adapter.inbound.graphql.advanced.codegen.GraphQlScalarMapping -dev.caskeleton.adapter.inbound.graphql.advanced.codegen.GraphQlTransportTypeGenerator -dev.caskeleton.adapter.inbound.graphql.advanced.composition.GraphQlFederationCompositionGate -dev.caskeleton.adapter.inbound.graphql.advanced.composition.GraphQlFederationCompositionResult -dev.caskeleton.adapter.inbound.graphql.advanced.composition.GraphQlFederationDeploymentOrder -dev.caskeleton.adapter.inbound.graphql.advanced.composition.GraphQlFederationLatencyBudget -dev.caskeleton.adapter.inbound.graphql.advanced.composition.GraphQlFederationReleaseEvidence -dev.caskeleton.adapter.inbound.graphql.advanced.composition.GraphQlFederationReleaseRejectedException -dev.caskeleton.adapter.inbound.graphql.advanced.composition.GraphQlFederationUsageReport -dev.caskeleton.adapter.inbound.graphql.advanced.composition.GraphQlSubgraphContract -dev.caskeleton.adapter.inbound.graphql.advanced.federation.GraphQlFederationBatchResolver -dev.caskeleton.adapter.inbound.graphql.advanced.federation.GraphQlFederationCapability -dev.caskeleton.adapter.inbound.graphql.advanced.federation.GraphQlFederationEntityKey -dev.caskeleton.adapter.inbound.graphql.advanced.federation.GraphQlFederationEntityResolver -dev.caskeleton.adapter.inbound.graphql.advanced.federation.GraphQlFederationProperties -dev.caskeleton.adapter.inbound.graphql.advanced.federation.GraphQlFederationRepresentationException -dev.caskeleton.adapter.inbound.graphql.advanced.federation.GraphQlFederationSchemaFactory -dev.caskeleton.adapter.inbound.graphql.advanced.get.GraphQlHttpDraftCompatibilityReport -dev.caskeleton.adapter.inbound.graphql.advanced.get.GraphQlHttpGetCachePolicy -dev.caskeleton.adapter.inbound.graphql.advanced.get.GraphQlHttpGetCsrfPolicy -dev.caskeleton.adapter.inbound.graphql.advanced.get.GraphQlHttpGetOperationPolicy -dev.caskeleton.adapter.inbound.graphql.advanced.get.GraphQlHttpGetProfile -dev.caskeleton.adapter.inbound.graphql.advanced.get.GraphQlHttpGetRejectedException -dev.caskeleton.adapter.inbound.graphql.advanced.get.GraphQlHttpGetRequestParser -dev.caskeleton.adapter.inbound.graphql.advanced.incremental.GraphQlIncrementalCancellation -dev.caskeleton.adapter.inbound.graphql.advanced.incremental.GraphQlIncrementalCompatibilityGate -dev.caskeleton.adapter.inbound.graphql.advanced.incremental.GraphQlIncrementalDeliveryCapability -dev.caskeleton.adapter.inbound.graphql.advanced.incremental.GraphQlIncrementalDeliveryProfile -dev.caskeleton.adapter.inbound.graphql.advanced.incremental.GraphQlIncrementalDeliveryRejectedException -dev.caskeleton.adapter.inbound.graphql.advanced.incremental.GraphQlIncrementalPatch -dev.caskeleton.adapter.inbound.graphql.advanced.incremental.GraphQlIncrementalTransportPolicy -dev.caskeleton.adapter.inbound.graphql.advanced.persisted.GraphQlPersistedOperation -dev.caskeleton.adapter.inbound.graphql.advanced.persisted.GraphQlPersistedOperationConflictException -dev.caskeleton.adapter.inbound.graphql.advanced.persisted.GraphQlPersistedOperationId -dev.caskeleton.adapter.inbound.graphql.advanced.persisted.GraphQlPersistedOperationInterceptor -dev.caskeleton.adapter.inbound.graphql.advanced.persisted.GraphQlPersistedOperationLookup -dev.caskeleton.adapter.inbound.graphql.advanced.persisted.GraphQlPersistedOperationNotFoundException -dev.caskeleton.adapter.inbound.graphql.advanced.persisted.GraphQlPersistedOperationPolicy -dev.caskeleton.adapter.inbound.graphql.advanced.persisted.GraphQlPersistedOperationRecordMapping -dev.caskeleton.adapter.inbound.graphql.advanced.persisted.GraphQlPersistedOperationRegistry -dev.caskeleton.adapter.inbound.graphql.advanced.persisted.GraphQlPersistedOperationRejectedException -dev.caskeleton.adapter.inbound.graphql.advanced.persisted.GraphQlPersistedOperationRequest -dev.caskeleton.adapter.inbound.graphql.advanced.persisted.GraphQlPersistedOperationStatus -dev.caskeleton.adapter.inbound.graphql.advanced.persisted.GraphQlPersistedOperationTransition -dev.caskeleton.adapter.inbound.graphql.advanced.persisted.GraphQlPersistedPreparsedBridge -dev.caskeleton.adapter.inbound.graphql.advanced.persisted.OperationalStoreGraphQlPersistedOperationRegistry -dev.caskeleton.adapter.inbound.graphql.advanced.release.GraphQlAdvancedCompatibilityMatrix -dev.caskeleton.adapter.inbound.graphql.advanced.release.GraphQlAdvancedPromotionDecision -dev.caskeleton.adapter.inbound.graphql.advanced.release.GraphQlAdvancedReleaseEvidence -dev.caskeleton.adapter.inbound.graphql.advanced.release.GraphQlAdvancedReleaseException -dev.caskeleton.adapter.inbound.graphql.advanced.release.GraphQlAdvancedReleaseGate -dev.caskeleton.adapter.inbound.graphql.advanced.release.GraphQlAdvancedRunbookIndex -dev.caskeleton.adapter.inbound.graphql.advanced.release.GraphQlAdvancedSoakScenario -dev.caskeleton.adapter.inbound.graphql.advanced.replay.GraphQlReplayAuthorization -dev.caskeleton.adapter.inbound.graphql.advanced.replay.GraphQlReplayAuthorizationException -dev.caskeleton.adapter.inbound.graphql.advanced.replay.GraphQlReplayGapException -dev.caskeleton.adapter.inbound.graphql.advanced.replay.GraphQlReplayHistoryLostException -dev.caskeleton.adapter.inbound.graphql.advanced.replay.GraphQlReplayPosition -dev.caskeleton.adapter.inbound.graphql.advanced.replay.GraphQlReplaySource -dev.caskeleton.adapter.inbound.graphql.advanced.replay.GraphQlSnapshotLiveHandoff -dev.caskeleton.adapter.inbound.graphql.advanced.replay.GraphQlSubscriptionCursor -dev.caskeleton.adapter.inbound.graphql.advanced.rsocket.GraphQlRSocketAdmission -dev.caskeleton.adapter.inbound.graphql.advanced.rsocket.GraphQlRSocketAuthentication -dev.caskeleton.adapter.inbound.graphql.advanced.rsocket.GraphQlRSocketCapability -dev.caskeleton.adapter.inbound.graphql.advanced.rsocket.GraphQlRSocketErrorMapper -dev.caskeleton.adapter.inbound.graphql.advanced.rsocket.GraphQlRSocketHandlerFactory -dev.caskeleton.adapter.inbound.graphql.advanced.rsocket.GraphQlRSocketProperties -dev.caskeleton.adapter.inbound.graphql.advanced.rsocket.GraphQlRSocketRoutePolicy -dev.caskeleton.adapter.inbound.graphql.advanced.rsocket.GraphQlRSocketRouteRejectedException -dev.caskeleton.adapter.inbound.graphql.advanced.security.GraphQlSubscriptionAuthorizationPolicy -dev.caskeleton.adapter.inbound.graphql.advanced.security.GraphQlWebSocketAuthenticationException -dev.caskeleton.adapter.inbound.graphql.advanced.security.GraphQlWebSocketAuthenticationInterceptor -dev.caskeleton.adapter.inbound.graphql.advanced.security.GraphQlWebSocketCloseReason -dev.caskeleton.adapter.inbound.graphql.advanced.security.GraphQlWebSocketCredentialExpiry -dev.caskeleton.adapter.inbound.graphql.advanced.security.GraphQlWebSocketPrincipal -dev.caskeleton.adapter.inbound.graphql.advanced.security.GraphQlWebSocketRevocationSignal -dev.caskeleton.adapter.inbound.graphql.advanced.springdata.GraphQlRepositoryAllowlist -dev.caskeleton.adapter.inbound.graphql.advanced.springdata.GraphQlRepositoryArgumentPolicy -dev.caskeleton.adapter.inbound.graphql.advanced.springdata.GraphQlRepositoryExposure -dev.caskeleton.adapter.inbound.graphql.advanced.springdata.GraphQlRepositoryExposureRejectedException -dev.caskeleton.adapter.inbound.graphql.advanced.springdata.GraphQlRepositoryExposureValidator -dev.caskeleton.adapter.inbound.graphql.advanced.springdata.GraphQlRepositoryPaginationPolicy -dev.caskeleton.adapter.inbound.graphql.advanced.springdata.GraphQlRepositoryProjectionPolicy -dev.caskeleton.adapter.inbound.graphql.advanced.sse.GraphQlSseAdmission -dev.caskeleton.adapter.inbound.graphql.advanced.sse.GraphQlSseConnectionPolicy -dev.caskeleton.adapter.inbound.graphql.advanced.sse.GraphQlSseHandlerFactory -dev.caskeleton.adapter.inbound.graphql.advanced.sse.GraphQlSseHeartbeat -dev.caskeleton.adapter.inbound.graphql.advanced.sse.GraphQlSseProperties -dev.caskeleton.adapter.inbound.graphql.advanced.sse.GraphQlSseRejectedException -dev.caskeleton.adapter.inbound.graphql.advanced.sse.GraphQlSseTermination -dev.caskeleton.adapter.inbound.graphql.advanced.subscription.GraphQlSlowConsumerPolicy -dev.caskeleton.adapter.inbound.graphql.advanced.subscription.GraphQlSubscriptionBufferPolicy -dev.caskeleton.adapter.inbound.graphql.advanced.subscription.GraphQlSubscriptionCancellation -dev.caskeleton.adapter.inbound.graphql.advanced.subscription.GraphQlSubscriptionContext -dev.caskeleton.adapter.inbound.graphql.advanced.subscription.GraphQlSubscriptionDispatcher -dev.caskeleton.adapter.inbound.graphql.advanced.subscription.GraphQlSubscriptionDrainCoordinator -dev.caskeleton.adapter.inbound.graphql.advanced.subscription.GraphQlSubscriptionDrainPhase -dev.caskeleton.adapter.inbound.graphql.advanced.subscription.GraphQlSubscriptionDrainingException -dev.caskeleton.adapter.inbound.graphql.advanced.subscription.GraphQlSubscriptionEvent -dev.caskeleton.adapter.inbound.graphql.advanced.subscription.GraphQlSubscriptionExecutionPolicy -dev.caskeleton.adapter.inbound.graphql.advanced.subscription.GraphQlSubscriptionLease -dev.caskeleton.adapter.inbound.graphql.advanced.subscription.GraphQlSubscriptionMetrics -dev.caskeleton.adapter.inbound.graphql.advanced.subscription.GraphQlSubscriptionOrderingProfile -dev.caskeleton.adapter.inbound.graphql.advanced.subscription.GraphQlSubscriptionSource -dev.caskeleton.adapter.inbound.graphql.advanced.subscription.GraphQlSubscriptionState -dev.caskeleton.adapter.inbound.graphql.advanced.subscription.GraphQlSubscriptionTermination dev.caskeleton.adapter.inbound.graphql.api.GraphQlClientProfile -dev.caskeleton.adapter.inbound.graphql.api.GraphQlClientProfileName dev.caskeleton.adapter.inbound.graphql.api.GraphQlOperationId dev.caskeleton.adapter.inbound.graphql.api.GraphQlOperationName dev.caskeleton.adapter.inbound.graphql.api.GraphQlSchemaCoordinate -dev.caskeleton.adapter.inbound.graphql.architecture.GraphQlAsyncReturnShape -dev.caskeleton.adapter.inbound.graphql.architecture.GraphQlControllerContractException -dev.caskeleton.adapter.inbound.graphql.architecture.GraphQlControllerInspector -dev.caskeleton.adapter.inbound.graphql.architecture.GraphQlControllerTransactionRule -dev.caskeleton.adapter.inbound.graphql.architecture.GraphQlInputTypePolicy -dev.caskeleton.adapter.inbound.graphql.architecture.GraphQlResolverBoundaryRules -dev.caskeleton.adapter.inbound.graphql.architecture.GraphQlReturnTypePolicy -dev.caskeleton.adapter.inbound.graphql.architecture.GraphQlTransportTypeRules -dev.caskeleton.adapter.inbound.graphql.architecture.GraphQlTypeGraph dev.caskeleton.adapter.inbound.graphql.autoconfigure.GraphQlActivationEnvironmentPostProcessor dev.caskeleton.adapter.inbound.graphql.autoconfigure.GraphQlDeploymentMode -dev.caskeleton.adapter.inbound.graphql.autoconfigure.GraphQlOffAutoConfigurationImportFilter -dev.caskeleton.adapter.inbound.graphql.autoconfigure.GraphQlPlatformActuatorEndpoint dev.caskeleton.adapter.inbound.graphql.autoconfigure.GraphQlPlatformAutoConfiguration dev.caskeleton.adapter.inbound.graphql.autoconfigure.GraphQlPlatformConfigurationException -dev.caskeleton.adapter.inbound.graphql.autoconfigure.GraphQlPlatformConfigurationReport dev.caskeleton.adapter.inbound.graphql.autoconfigure.GraphQlPlatformRuntime dev.caskeleton.adapter.inbound.graphql.autoconfigure.GraphQlPlatformSettings dev.caskeleton.adapter.inbound.graphql.autoconfigure.GraphQlPlatformStartupValidator dev.caskeleton.adapter.inbound.graphql.autoconfigure.GraphQlRetiredSafetyAxis dev.caskeleton.adapter.inbound.graphql.autoconfigure.GraphQlRootAutoConfiguration dev.caskeleton.adapter.inbound.graphql.autoconfigure.GraphQlRuntimeTransport -dev.caskeleton.adapter.inbound.graphql.compat.GraphQlChangeKind -dev.caskeleton.adapter.inbound.graphql.compat.GraphQlClientOwnerApproval -dev.caskeleton.adapter.inbound.graphql.compat.GraphQlCompatibilityImpact -dev.caskeleton.adapter.inbound.graphql.compat.GraphQlCompatibilityPolicy -dev.caskeleton.adapter.inbound.graphql.compat.GraphQlCompatibilityReport -dev.caskeleton.adapter.inbound.graphql.compat.GraphQlDeprecationGate -dev.caskeleton.adapter.inbound.graphql.compat.GraphQlRemovalDecision -dev.caskeleton.adapter.inbound.graphql.compat.GraphQlRemovalRequest -dev.caskeleton.adapter.inbound.graphql.compat.GraphQlSchemaChange -dev.caskeleton.adapter.inbound.graphql.compat.GraphQlSchemaComparator -dev.caskeleton.adapter.inbound.graphql.compat.GraphQlSchemaUsage dev.caskeleton.adapter.inbound.graphql.context.ActorRef dev.caskeleton.adapter.inbound.graphql.context.GraphQlCommandAttribution dev.caskeleton.adapter.inbound.graphql.context.GraphQlDeadline @@ -193,16 +35,7 @@ dev.caskeleton.adapter.inbound.graphql.cost.GraphQlDocumentComplexityScorer dev.caskeleton.adapter.inbound.graphql.cost.GraphQlDocumentShape dev.caskeleton.adapter.inbound.graphql.cost.GraphQlDocumentShapeAnalyzer dev.caskeleton.adapter.inbound.graphql.cost.GraphQlFieldCostDescriptor -dev.caskeleton.adapter.inbound.graphql.cost.GraphQlParserLimitPolicy -dev.caskeleton.adapter.inbound.graphql.cost.GraphQlParserLimits -dev.caskeleton.adapter.inbound.graphql.cost.GraphQlParserOptionsFactory -dev.caskeleton.adapter.inbound.graphql.cost.GraphQlParserRejectedException dev.caskeleton.adapter.inbound.graphql.cost.GraphQlResolverWeight -dev.caskeleton.adapter.inbound.graphql.cost.GraphQlResponseByteLimiter -dev.caskeleton.adapter.inbound.graphql.cost.GraphQlResponseNodeCounter -dev.caskeleton.adapter.inbound.graphql.cost.GraphQlRuntimeBudget -dev.caskeleton.adapter.inbound.graphql.cost.GraphQlRuntimeBudgetExceededException -dev.caskeleton.adapter.inbound.graphql.cost.GraphQlRuntimeBudgetTracker dev.caskeleton.adapter.inbound.graphql.cost.GraphQlStructuralLimitException dev.caskeleton.adapter.inbound.graphql.cost.GraphQlStructuralLimitPolicy dev.caskeleton.adapter.inbound.graphql.cost.GraphQlStructuralLimits @@ -227,33 +60,21 @@ dev.caskeleton.adapter.inbound.graphql.error.GraphQlErrorCategory dev.caskeleton.adapter.inbound.graphql.error.GraphQlErrorCode dev.caskeleton.adapter.inbound.graphql.error.GraphQlErrorContext dev.caskeleton.adapter.inbound.graphql.error.GraphQlExceptionResolver -dev.caskeleton.adapter.inbound.graphql.error.GraphQlFailureBoundary dev.caskeleton.adapter.inbound.graphql.error.GraphQlInternalErrorMasker -dev.caskeleton.adapter.inbound.graphql.error.GraphQlNullabilityContract -dev.caskeleton.adapter.inbound.graphql.error.GraphQlRequestErrorMapper -dev.caskeleton.adapter.inbound.graphql.error.GraphQlSubscriptionExceptionResolver dev.caskeleton.adapter.inbound.graphql.error.GraphQlWireError dev.caskeleton.adapter.inbound.graphql.execution.BoundedPreparsedDocumentProvider dev.caskeleton.adapter.inbound.graphql.execution.GraphQlAnonymousOperationException -dev.caskeleton.adapter.inbound.graphql.execution.GraphQlCancellation -dev.caskeleton.adapter.inbound.graphql.execution.GraphQlDeadlinePropagator dev.caskeleton.adapter.inbound.graphql.execution.GraphQlExecutionPipeline dev.caskeleton.adapter.inbound.graphql.execution.GraphQlExecutionPipelineException dev.caskeleton.adapter.inbound.graphql.execution.GraphQlExecutionPipelineValidator dev.caskeleton.adapter.inbound.graphql.execution.GraphQlExecutionProfile dev.caskeleton.adapter.inbound.graphql.execution.GraphQlExecutionProfileException -dev.caskeleton.adapter.inbound.graphql.execution.GraphQlExecutionProfileValidator dev.caskeleton.adapter.inbound.graphql.execution.GraphQlExecutionStage -dev.caskeleton.adapter.inbound.graphql.execution.GraphQlOperationNameInterceptor -dev.caskeleton.adapter.inbound.graphql.execution.GraphQlOperationNamePolicy dev.caskeleton.adapter.inbound.graphql.execution.GraphQlOperationSelection dev.caskeleton.adapter.inbound.graphql.execution.GraphQlPreparsedCacheKey dev.caskeleton.adapter.inbound.graphql.execution.GraphQlPreparsedCacheMetrics dev.caskeleton.adapter.inbound.graphql.execution.GraphQlPreparsedCachePolicy dev.caskeleton.adapter.inbound.graphql.execution.GraphQlRequestCancelledException -dev.caskeleton.adapter.inbound.graphql.execution.GraphQlResolverBudget -dev.caskeleton.adapter.inbound.graphql.execution.GraphQlResolverCatalog -dev.caskeleton.adapter.inbound.graphql.execution.GraphQlResolverDescriptor dev.caskeleton.adapter.inbound.graphql.execution.GraphQlTimeoutPolicy dev.caskeleton.adapter.inbound.graphql.fetch.GraphQlFetchProfile dev.caskeleton.adapter.inbound.graphql.fetch.GraphQlFetchProfileClassifier @@ -265,41 +86,22 @@ dev.caskeleton.adapter.inbound.graphql.fetch.GraphQlSelectionCoordinate dev.caskeleton.adapter.inbound.graphql.fetch.GraphQlSelectionSetView dev.caskeleton.adapter.inbound.graphql.fetch.GraphQlSelectionSignature dev.caskeleton.adapter.inbound.graphql.fetch.GraphQlUnmappedSelectionException -dev.caskeleton.adapter.inbound.graphql.http.GraphQlAcceptHeader -dev.caskeleton.adapter.inbound.graphql.http.GraphQlExecutionOutcome dev.caskeleton.adapter.inbound.graphql.http.GraphQlExtensionsPolicy dev.caskeleton.adapter.inbound.graphql.http.GraphQlHttpContractException -dev.caskeleton.adapter.inbound.graphql.http.GraphQlHttpExecutor dev.caskeleton.adapter.inbound.graphql.http.GraphQlHttpOutcome -dev.caskeleton.adapter.inbound.graphql.http.GraphQlHttpProfile dev.caskeleton.adapter.inbound.graphql.http.GraphQlHttpRequestEnvelope -dev.caskeleton.adapter.inbound.graphql.http.GraphQlHttpResponse -dev.caskeleton.adapter.inbound.graphql.http.GraphQlHttpResponseFactory -dev.caskeleton.adapter.inbound.graphql.http.GraphQlHttpResponsePolicy -dev.caskeleton.adapter.inbound.graphql.http.GraphQlHttpStatusMapper dev.caskeleton.adapter.inbound.graphql.http.GraphQlJsonStructurePolicy dev.caskeleton.adapter.inbound.graphql.http.GraphQlJsonValues -dev.caskeleton.adapter.inbound.graphql.http.GraphQlMediaTypes dev.caskeleton.adapter.inbound.graphql.http.GraphQlRequestEnvelopeValidator dev.caskeleton.adapter.inbound.graphql.http.GraphQlRequestFormatException dev.caskeleton.adapter.inbound.graphql.http.GraphQlRequestSize dev.caskeleton.adapter.inbound.graphql.http.GraphQlRequestTooLargeException -dev.caskeleton.adapter.inbound.graphql.moduleboundary.GraphQlAdvancedModule -dev.caskeleton.adapter.inbound.graphql.moduleboundary.GraphQlModuleBoundary -dev.caskeleton.adapter.inbound.graphql.moduleboundary.GraphQlModulePurity -dev.caskeleton.adapter.inbound.graphql.moduleboundary.GraphQlStableModule dev.caskeleton.adapter.inbound.graphql.mutation.GraphQlBatchMutationItemResult dev.caskeleton.adapter.inbound.graphql.mutation.GraphQlBusinessResult -dev.caskeleton.adapter.inbound.graphql.mutation.GraphQlCanonicalInput dev.caskeleton.adapter.inbound.graphql.mutation.GraphQlExpectedVersion -dev.caskeleton.adapter.inbound.graphql.mutation.GraphQlIdempotencyConflictException -dev.caskeleton.adapter.inbound.graphql.mutation.GraphQlIdempotencyKey dev.caskeleton.adapter.inbound.graphql.mutation.GraphQlMutationContractException dev.caskeleton.adapter.inbound.graphql.mutation.GraphQlMutationContractValidator dev.caskeleton.adapter.inbound.graphql.mutation.GraphQlMutationCoordinate -dev.caskeleton.adapter.inbound.graphql.mutation.GraphQlMutationFingerprint -dev.caskeleton.adapter.inbound.graphql.mutation.GraphQlMutationIdempotencyContext -dev.caskeleton.adapter.inbound.graphql.mutation.GraphQlMutationIdempotencyInterceptor dev.caskeleton.adapter.inbound.graphql.mutation.GraphQlMutationPayload dev.caskeleton.adapter.inbound.graphql.mutation.GraphQlMutationResultMapper dev.caskeleton.adapter.inbound.graphql.observation.GraphQlDataLoaderObservationConvention @@ -307,7 +109,6 @@ dev.caskeleton.adapter.inbound.graphql.observation.GraphQlMetricCardinalityPolic dev.caskeleton.adapter.inbound.graphql.observation.GraphQlObservationContractException dev.caskeleton.adapter.inbound.graphql.observation.GraphQlObservationNames dev.caskeleton.adapter.inbound.graphql.observation.GraphQlOperationNameCardinality -dev.caskeleton.adapter.inbound.graphql.observation.GraphQlProfilerAccessPolicy dev.caskeleton.adapter.inbound.graphql.observation.GraphQlRequestObservationConvention dev.caskeleton.adapter.inbound.graphql.observation.GraphQlResolverObservationConvention dev.caskeleton.adapter.inbound.graphql.observation.GraphQlSensitiveAttributeFilter @@ -329,23 +130,7 @@ dev.caskeleton.adapter.inbound.graphql.pagination.GraphQlKeysetWindow dev.caskeleton.adapter.inbound.graphql.pagination.GraphQlPageInfo dev.caskeleton.adapter.inbound.graphql.pagination.HmacGraphQlCursorCodec dev.caskeleton.adapter.inbound.graphql.policy.GraphQlClientPolicy -dev.caskeleton.adapter.inbound.graphql.policy.GraphQlClientPolicyManifest -dev.caskeleton.adapter.inbound.graphql.policy.GraphQlOperationCatalog -dev.caskeleton.adapter.inbound.graphql.policy.GraphQlOperationPolicy dev.caskeleton.adapter.inbound.graphql.policy.GraphQlOperationType -dev.caskeleton.adapter.inbound.graphql.policy.GraphQlPolicyViolation -dev.caskeleton.adapter.inbound.graphql.policy.GraphQlUnknownClientProfileException -dev.caskeleton.adapter.inbound.graphql.policy.GraphQlUnknownOperationException -dev.caskeleton.adapter.inbound.graphql.policy.ResolverExecutionType -dev.caskeleton.adapter.inbound.graphql.release.GraphQlCompatibilityMatrix -dev.caskeleton.adapter.inbound.graphql.release.GraphQlFaultScenario -dev.caskeleton.adapter.inbound.graphql.release.GraphQlPerformanceScenario -dev.caskeleton.adapter.inbound.graphql.release.GraphQlReleaseEvidence -dev.caskeleton.adapter.inbound.graphql.release.GraphQlReleaseException -dev.caskeleton.adapter.inbound.graphql.release.GraphQlReleaseGate -dev.caskeleton.adapter.inbound.graphql.release.GraphQlReleaseOverride -dev.caskeleton.adapter.inbound.graphql.release.GraphQlReleaseReportWriter -dev.caskeleton.adapter.inbound.graphql.release.GraphQlStableCapabilityManifest dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlBatchLoaderRegistrar dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlBlockingBridge dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlBlockingBridgeFullException @@ -373,25 +158,9 @@ dev.caskeleton.adapter.inbound.graphql.scalar.GraphQlScalarWiringConfigurer dev.caskeleton.adapter.inbound.graphql.scalar.InstantScalar dev.caskeleton.adapter.inbound.graphql.scalar.LongScalar dev.caskeleton.adapter.inbound.graphql.scalar.UuidScalar -dev.caskeleton.adapter.inbound.graphql.schema.GraphQlContractVersion -dev.caskeleton.adapter.inbound.graphql.schema.GraphQlMappingInspectionGate -dev.caskeleton.adapter.inbound.graphql.schema.GraphQlMappingIssue -dev.caskeleton.adapter.inbound.graphql.schema.GraphQlMappingPolicy -dev.caskeleton.adapter.inbound.graphql.schema.GraphQlOneOfInputValidator -dev.caskeleton.adapter.inbound.graphql.schema.GraphQlOneOfPolicy -dev.caskeleton.adapter.inbound.graphql.schema.GraphQlOneOfSchemaGate -dev.caskeleton.adapter.inbound.graphql.schema.GraphQlOneOfViolationException dev.caskeleton.adapter.inbound.graphql.schema.GraphQlScalarDefinition dev.caskeleton.adapter.inbound.graphql.schema.GraphQlScalarManifest dev.caskeleton.adapter.inbound.graphql.schema.GraphQlScalarPolicy -dev.caskeleton.adapter.inbound.graphql.schema.GraphQlSchemaAssembler -dev.caskeleton.adapter.inbound.graphql.schema.GraphQlSchemaAssemblyException -dev.caskeleton.adapter.inbound.graphql.schema.GraphQlSchemaAssemblyResult -dev.caskeleton.adapter.inbound.graphql.schema.GraphQlSchemaContract -dev.caskeleton.adapter.inbound.graphql.schema.GraphQlSchemaHash -dev.caskeleton.adapter.inbound.graphql.schema.GraphQlSchemaMappingException -dev.caskeleton.adapter.inbound.graphql.schema.GraphQlSchemaOwnership -dev.caskeleton.adapter.inbound.graphql.schema.GraphQlSchemaResource dev.caskeleton.adapter.inbound.graphql.security.ApplicationObjectAuthorization dev.caskeleton.adapter.inbound.graphql.security.GraphQlAuthenticatedPrincipal dev.caskeleton.adapter.inbound.graphql.security.GraphQlAuthenticationContextFactory @@ -401,8 +170,6 @@ dev.caskeleton.adapter.inbound.graphql.security.GraphQlAuthorizationDeniedExcept dev.caskeleton.adapter.inbound.graphql.security.GraphQlAuthorizationInterceptor dev.caskeleton.adapter.inbound.graphql.security.GraphQlAuthorizationPolicy dev.caskeleton.adapter.inbound.graphql.security.GraphQlBatchContext -dev.caskeleton.adapter.inbound.graphql.security.GraphQlClientProfileResolver -dev.caskeleton.adapter.inbound.graphql.security.GraphQlContextCleanup dev.caskeleton.adapter.inbound.graphql.security.GraphQlContextPropagator dev.caskeleton.adapter.inbound.graphql.security.GraphQlObjectAuthorizationPort dev.caskeleton.adapter.inbound.graphql.security.GraphQlTenantIsolationException diff --git a/docs/architecture/jpa-adopter-api-surface.txt b/docs/architecture/jpa-adopter-api-surface.txt index af9027c6..ecd30f10 100644 --- a/docs/architecture/jpa-adopter-api-surface.txt +++ b/docs/architecture/jpa-adopter-api-surface.txt @@ -10,14 +10,10 @@ dev.caskeleton.adapter.outbound.persistence.config.PersistenceVendorSettings dev.caskeleton.adapter.outbound.persistence.failure.SqlStateErrorMapping dev.caskeleton.adapter.outbound.persistence.fileserver.FileserverSchemaActivation dev.caskeleton.adapter.outbound.persistence.hibernate.HibernateProviderPolicy -dev.caskeleton.adapter.outbound.persistence.idempotency.IdempotencyClaimRepository dev.caskeleton.adapter.outbound.persistence.migration.FlywaySchemaPolicy dev.caskeleton.adapter.outbound.persistence.outbox.OutboxClaimRepository -dev.caskeleton.adapter.outbound.persistence.postgresql.PostgreSqlIdempotencyClaimRepository -dev.caskeleton.adapter.outbound.persistence.postgresql.PostgreSqlLocalTimeoutConfigurer dev.caskeleton.adapter.outbound.persistence.postgresql.PostgreSqlOutboxClaimRepository dev.caskeleton.adapter.outbound.persistence.postgresql.PostgreSqlPersistenceConfig dev.caskeleton.adapter.outbound.persistence.postgresql.PostgreSqlSqlStateErrorMapping dev.caskeleton.adapter.outbound.persistence.security.DatabasePrivilegeReport dev.caskeleton.adapter.outbound.persistence.security.PostgreSqlRuntimeRoleVerifier -dev.caskeleton.adapter.outbound.persistence.transaction.TransactionLocalTimeoutConfigurer diff --git a/docs/architecture/jpa-api-surface.txt b/docs/architecture/jpa-api-surface.txt index 407d304d..891b9908 100644 --- a/docs/architecture/jpa-api-surface.txt +++ b/docs/architecture/jpa-api-surface.txt @@ -5,7 +5,7 @@ # root yet. # Update only after review with: # ./gradlew :adapter:outbound:persistence-jpa:updateJpaApiSurface -PapproveJpaApiSurfaceChange -# types: 311 +# types: 214 dev.caskeleton.adapter.outbound.persistence.api.PersistenceOperationName dev.caskeleton.adapter.outbound.persistence.api.capability.CapabilitySupport dev.caskeleton.adapter.outbound.persistence.api.capability.JpaCapability @@ -28,12 +28,9 @@ dev.caskeleton.adapter.outbound.persistence.api.error.QueryTimeoutException dev.caskeleton.adapter.outbound.persistence.api.error.SchemaMismatchException dev.caskeleton.adapter.outbound.persistence.api.error.SerializationFailureException dev.caskeleton.adapter.outbound.persistence.api.error.SqlExceptionSqlStateResolver -dev.caskeleton.adapter.outbound.persistence.api.error.SqlStateResolver dev.caskeleton.adapter.outbound.persistence.api.error.TransactionCompletionUnknownException dev.caskeleton.adapter.outbound.persistence.api.error.TransactionTimeoutException dev.caskeleton.adapter.outbound.persistence.api.error.UniqueConstraintViolationException -dev.caskeleton.adapter.outbound.persistence.api.error.VendorFailureTranslator -dev.caskeleton.adapter.outbound.persistence.api.query.CursorCodec dev.caskeleton.adapter.outbound.persistence.api.query.CursorPayloadCodec dev.caskeleton.adapter.outbound.persistence.api.query.KeysetPageRequest dev.caskeleton.adapter.outbound.persistence.api.query.KeysetSlice @@ -43,18 +40,7 @@ dev.caskeleton.adapter.outbound.persistence.api.query.QueryObservation dev.caskeleton.adapter.outbound.persistence.api.query.QueryScope dev.caskeleton.adapter.outbound.persistence.api.query.SignedJsonCursorCodec dev.caskeleton.adapter.outbound.persistence.api.query.SortDirection -dev.caskeleton.adapter.outbound.persistence.api.transaction.IsolationLevel -dev.caskeleton.adapter.outbound.persistence.api.transaction.JitterMode -dev.caskeleton.adapter.outbound.persistence.api.transaction.JpaRetryPolicy -dev.caskeleton.adapter.outbound.persistence.api.transaction.JpaTransactionExecutor -dev.caskeleton.adapter.outbound.persistence.api.transaction.PropagationMode -dev.caskeleton.adapter.outbound.persistence.api.transaction.RetryDecision -dev.caskeleton.adapter.outbound.persistence.api.transaction.RetryDisposition -dev.caskeleton.adapter.outbound.persistence.api.transaction.RetryEventListener -dev.caskeleton.adapter.outbound.persistence.api.transaction.RetryProfile -dev.caskeleton.adapter.outbound.persistence.api.transaction.TransactionAttempt dev.caskeleton.adapter.outbound.persistence.api.transaction.TransactionCompletionEvidence -dev.caskeleton.adapter.outbound.persistence.api.transaction.TransactionProfile dev.caskeleton.adapter.outbound.persistence.audit.AuditContextPort dev.caskeleton.adapter.outbound.persistence.audit.AuditableEntity dev.caskeleton.adapter.outbound.persistence.audit.DomainContextAuditContextPort @@ -69,20 +55,11 @@ dev.caskeleton.adapter.outbound.persistence.config.PersistenceVendorSettings dev.caskeleton.adapter.outbound.persistence.envers.EntityRevision dev.caskeleton.adapter.outbound.persistence.envers.EnversConfigurationGuard dev.caskeleton.adapter.outbound.persistence.envers.EnversHistoryPolicy -dev.caskeleton.adapter.outbound.persistence.envers.EnversHistoryReader dev.caskeleton.adapter.outbound.persistence.envers.EnversRevisionMetadata dev.caskeleton.adapter.outbound.persistence.envers.HibernateEnversHistoryReader -dev.caskeleton.adapter.outbound.persistence.experimental.ExperimentalFeature -dev.caskeleton.adapter.outbound.persistence.experimental.ExperimentalFeatureGate dev.caskeleton.adapter.outbound.persistence.experimental.database.TenantDataSourceLifecycle dev.caskeleton.adapter.outbound.persistence.experimental.database.TenantDataSourceRegistry -dev.caskeleton.adapter.outbound.persistence.experimental.database.TenantEntityManagerFactoryRegistry dev.caskeleton.adapter.outbound.persistence.experimental.database.TenantPoolBudget -dev.caskeleton.adapter.outbound.persistence.experimental.next.CompatibilityLane -dev.caskeleton.adapter.outbound.persistence.experimental.next.ExperimentalPromotionGate -dev.caskeleton.adapter.outbound.persistence.experimental.next.HibernateCompatibilityPolicy -dev.caskeleton.adapter.outbound.persistence.experimental.next.PromotionDecision -dev.caskeleton.adapter.outbound.persistence.experimental.next.PromotionEvidence dev.caskeleton.adapter.outbound.persistence.experimental.replica.ConsistencyAwareDataSourceRouter dev.caskeleton.adapter.outbound.persistence.experimental.replica.ConsistencyToken dev.caskeleton.adapter.outbound.persistence.experimental.replica.ReadConsistency @@ -90,7 +67,6 @@ dev.caskeleton.adapter.outbound.persistence.experimental.replica.ReplicaLagMonit dev.caskeleton.adapter.outbound.persistence.experimental.replica.ReplicaRoutingDecision dev.caskeleton.adapter.outbound.persistence.experimental.replica.ReplicaTarget dev.caskeleton.adapter.outbound.persistence.experimental.replica.TransactionContext -dev.caskeleton.adapter.outbound.persistence.experimental.rls.RlsAdminBypassToken dev.caskeleton.adapter.outbound.persistence.experimental.rls.RlsPolicyVerifier dev.caskeleton.adapter.outbound.persistence.experimental.rls.RlsTenantSessionBinder dev.caskeleton.adapter.outbound.persistence.experimental.schema.SchemaMultiTenantConnectionProvider @@ -99,13 +75,10 @@ dev.caskeleton.adapter.outbound.persistence.experimental.schema.SchemaTenantRegi dev.caskeleton.adapter.outbound.persistence.experimental.schema.TenantMigrationStatus dev.caskeleton.adapter.outbound.persistence.experimental.tenant.TenantAwareRepositoryGuard dev.caskeleton.adapter.outbound.persistence.experimental.tenant.TenantContext -dev.caskeleton.adapter.outbound.persistence.experimental.tenant.TenantEntityListenerGuard dev.caskeleton.adapter.outbound.persistence.experimental.tenant.TenantId dev.caskeleton.adapter.outbound.persistence.failure.PersistenceExceptionTranslator dev.caskeleton.adapter.outbound.persistence.failure.SqlStateErrorMapping dev.caskeleton.adapter.outbound.persistence.failure.StandardSqlStateErrorMapping -dev.caskeleton.adapter.outbound.persistence.h2.H2IdempotencyClaimRepository -dev.caskeleton.adapter.outbound.persistence.h2.H2LocalTimeoutConfigurer dev.caskeleton.adapter.outbound.persistence.h2.H2OutboxClaimRepository dev.caskeleton.adapter.outbound.persistence.h2.H2PersistenceConfig dev.caskeleton.adapter.outbound.persistence.h2.H2SqlStateErrorMapping @@ -118,50 +91,30 @@ dev.caskeleton.adapter.outbound.persistence.hibernate.QueryNameContext dev.caskeleton.adapter.outbound.persistence.hibernate.batch.BatchExecutionResult dev.caskeleton.adapter.outbound.persistence.hibernate.batch.HibernateBatchConfigurationGuard dev.caskeleton.adapter.outbound.persistence.hibernate.batch.HibernateJpaBatchExecutor -dev.caskeleton.adapter.outbound.persistence.hibernate.batch.JpaBatchExecutor dev.caskeleton.adapter.outbound.persistence.hibernate.batch.JpaBatchProfile -dev.caskeleton.adapter.outbound.persistence.hibernate.batch.JpaBatchProfileRegistry dev.caskeleton.adapter.outbound.persistence.hibernate.bulk.AffectedRowsExpectation -dev.caskeleton.adapter.outbound.persistence.hibernate.bulk.BulkDmlExecutor dev.caskeleton.adapter.outbound.persistence.hibernate.bulk.BulkDmlResult dev.caskeleton.adapter.outbound.persistence.hibernate.bulk.BulkOperationName dev.caskeleton.adapter.outbound.persistence.hibernate.bulk.HibernateBulkDmlExecutor dev.caskeleton.adapter.outbound.persistence.hibernate.stateless.HibernateStatelessSessionRunner dev.caskeleton.adapter.outbound.persistence.hibernate.stateless.StatelessRowCapExceededException -dev.caskeleton.adapter.outbound.persistence.hibernate.stateless.StatelessSessionRunner dev.caskeleton.adapter.outbound.persistence.hibernate.stateless.StatelessWorkName dev.caskeleton.adapter.outbound.persistence.hibernate.stateless.StatelessWorkResult -dev.caskeleton.adapter.outbound.persistence.idempotency.IdempotencyClaimRepository dev.caskeleton.adapter.outbound.persistence.idempotency.IdempotencyReaper dev.caskeleton.adapter.outbound.persistence.idempotency.IdempotencyRecordJpaRepository -dev.caskeleton.adapter.outbound.persistence.idempotency.IdempotencyResponseObjectStore -dev.caskeleton.adapter.outbound.persistence.idempotency.IdempotencyStoreAdapter dev.caskeleton.adapter.outbound.persistence.idempotency.entity.IdempotencyRecordEntity -dev.caskeleton.adapter.outbound.persistence.idempotency.mapper.IdempotencyRecordEntityMapper dev.caskeleton.adapter.outbound.persistence.liveevent.JpaLiveEventReplayAdapter dev.caskeleton.adapter.outbound.persistence.liveevent.LiveEventJpaRepository dev.caskeleton.adapter.outbound.persistence.liveevent.entity.LiveEventEntity dev.caskeleton.adapter.outbound.persistence.lock.DistributedLockPersistenceConfig dev.caskeleton.adapter.outbound.persistence.lock.LockRegistryDistributedLockAdapter dev.caskeleton.adapter.outbound.persistence.lock.LockSettings -dev.caskeleton.adapter.outbound.persistence.migration.ConcurrentIndexMigrationInspector -dev.caskeleton.adapter.outbound.persistence.migration.FailedConcurrentIndexRecovery dev.caskeleton.adapter.outbound.persistence.migration.FlywaySchemaPolicy -dev.caskeleton.adapter.outbound.persistence.migration.FlywayValidationGate -dev.caskeleton.adapter.outbound.persistence.migration.MigrationResource -dev.caskeleton.adapter.outbound.persistence.migration.NonTransactionalMigrationPolicy dev.caskeleton.adapter.outbound.persistence.migration.SchemaManagementMode -dev.caskeleton.adapter.outbound.persistence.migration.SchemaVersionSnapshot dev.caskeleton.adapter.outbound.persistence.notification.NotificationJpaPersistenceConfig dev.caskeleton.adapter.outbound.persistence.notification.NotificationSchemaActivation dev.caskeleton.adapter.outbound.persistence.notification.NotificationSchemaStream dev.caskeleton.adapter.outbound.persistence.notification.configuration.NotificationJpaPersistenceFacade -dev.caskeleton.adapter.outbound.persistence.notification.crypto.DirectAeadNotificationPayloadCrypto -dev.caskeleton.adapter.outbound.persistence.notification.crypto.NotificationCiphertext -dev.caskeleton.adapter.outbound.persistence.notification.crypto.NotificationCryptoException -dev.caskeleton.adapter.outbound.persistence.notification.crypto.NotificationHmacDigester -dev.caskeleton.adapter.outbound.persistence.notification.crypto.NotificationKeyMaterialHandle -dev.caskeleton.adapter.outbound.persistence.notification.crypto.NotificationKeyMaterialProvider dev.caskeleton.adapter.outbound.persistence.notification.platform.AdminAuditEntity dev.caskeleton.adapter.outbound.persistence.notification.platform.AdminAuditJpaRepository dev.caskeleton.adapter.outbound.persistence.notification.platform.ConsentEntity @@ -206,8 +159,6 @@ dev.caskeleton.adapter.outbound.persistence.notification.platform.inbox.InboxIte dev.caskeleton.adapter.outbound.persistence.notification.platform.inbox.InboxOutboxRecordFactory dev.caskeleton.adapter.outbound.persistence.notification.platform.inbox.JpaNotificationInbox dev.caskeleton.adapter.outbound.persistence.observation.JpaMetricTags -dev.caskeleton.adapter.outbound.persistence.observation.JpaRetryObservation -dev.caskeleton.adapter.outbound.persistence.observation.JpaTransactionObservation dev.caskeleton.adapter.outbound.persistence.observation.LowCardinality dev.caskeleton.adapter.outbound.persistence.observation.MicrometerQueryObservation dev.caskeleton.adapter.outbound.persistence.observation.SqlDiagnosticRedactor @@ -219,8 +170,6 @@ dev.caskeleton.adapter.outbound.persistence.outbox.OutboxEventJpaRepository dev.caskeleton.adapter.outbound.persistence.outbox.OutboxReaper dev.caskeleton.adapter.outbound.persistence.outbox.OutboxStoreAdapter dev.caskeleton.adapter.outbound.persistence.outbox.entity.OutboxEventEntity -dev.caskeleton.adapter.outbound.persistence.postgresql.PostgreSqlIdempotencyClaimRepository -dev.caskeleton.adapter.outbound.persistence.postgresql.PostgreSqlLocalTimeoutConfigurer dev.caskeleton.adapter.outbound.persistence.postgresql.PostgreSqlOutboxClaimRepository dev.caskeleton.adapter.outbound.persistence.postgresql.PostgreSqlPersistenceConfig dev.caskeleton.adapter.outbound.persistence.postgresql.PostgreSqlSqlStateErrorMapping @@ -233,50 +182,29 @@ dev.caskeleton.adapter.outbound.persistence.postgresql.copy.CopyFormat dev.caskeleton.adapter.outbound.persistence.postgresql.copy.CopyLimits dev.caskeleton.adapter.outbound.persistence.postgresql.copy.CopyOperationName dev.caskeleton.adapter.outbound.persistence.postgresql.copy.CopyResult -dev.caskeleton.adapter.outbound.persistence.postgresql.copy.PostgreSqlCopyLoader dev.caskeleton.adapter.outbound.persistence.postgresql.copy.RegisteredCopyStatement dev.caskeleton.adapter.outbound.persistence.postgresql.copy.RegisteredPostgreSqlCopyLoader -dev.caskeleton.adapter.outbound.persistence.postgresql.error.ConstraintCatalog dev.caskeleton.adapter.outbound.persistence.postgresql.error.PostgreSqlExceptionTranslator dev.caskeleton.adapter.outbound.persistence.postgresql.error.PostgreSqlFailureClassifier dev.caskeleton.adapter.outbound.persistence.postgresql.error.PostgreSqlServerErrorFields dev.caskeleton.adapter.outbound.persistence.postgresql.error.PostgreSqlState +dev.caskeleton.adapter.outbound.persistence.postgresql.idempotency.IdempotencySchemaStream dev.caskeleton.adapter.outbound.persistence.postgresql.idempotency.PostgreSqlOwnerSafeIdempotencyStore -dev.caskeleton.adapter.outbound.persistence.postgresql.inbox.PostgreSqlSameStoreInboxAdapter dev.caskeleton.adapter.outbound.persistence.postgresql.json.JsonDocument dev.caskeleton.adapter.outbound.persistence.postgresql.json.JsonDocumentCodec dev.caskeleton.adapter.outbound.persistence.postgresql.json.JsonPathName dev.caskeleton.adapter.outbound.persistence.postgresql.json.PostgreSqlJsonQuerySupport -dev.caskeleton.adapter.outbound.persistence.postgresql.lock.LockWaitObservation dev.caskeleton.adapter.outbound.persistence.postgresql.lock.PostgreSqlLockExceptionTranslator dev.caskeleton.adapter.outbound.persistence.postgresql.lock.PostgreSqlLockOptions -dev.caskeleton.adapter.outbound.persistence.postgresql.lock.PostgreSqlWorkClaimExecutor -dev.caskeleton.adapter.outbound.persistence.postgresql.lock.WorkClaim -dev.caskeleton.adapter.outbound.persistence.postgresql.lock.WorkClaimExecutor -dev.caskeleton.adapter.outbound.persistence.postgresql.lock.WorkQueueDefinition -dev.caskeleton.adapter.outbound.persistence.postgresql.lock.WorkQueueName -dev.caskeleton.adapter.outbound.persistence.postgresql.outbox.PostgreSqlImmutableOutboxAppendAdapter -dev.caskeleton.adapter.outbound.persistence.postgresql.outbox.PostgreSqlPollingDeliveryAdapter dev.caskeleton.adapter.outbound.persistence.postgresql.range.PgRange dev.caskeleton.adapter.outbound.persistence.postgresql.range.PgRangeCodec -dev.caskeleton.adapter.outbound.persistence.postgresql.range.PgRangeJdbcType -dev.caskeleton.adapter.outbound.persistence.postgresql.range.PostgreSqlRangeQuerySupport -dev.caskeleton.adapter.outbound.persistence.postgresql.write.NativeWriteName -dev.caskeleton.adapter.outbound.persistence.postgresql.write.PostgreSqlUpsertExecutor -dev.caskeleton.adapter.outbound.persistence.postgresql.write.RegisteredPostgreSqlUpsertExecutor -dev.caskeleton.adapter.outbound.persistence.postgresql.write.RegisteredUpsertStatement -dev.caskeleton.adapter.outbound.persistence.postgresql.write.UpsertConflictTarget -dev.caskeleton.adapter.outbound.persistence.postgresql.write.UpsertResult -dev.caskeleton.adapter.outbound.persistence.postgresql.write.WriteDisposition dev.caskeleton.adapter.outbound.persistence.querydsl.PredicatePolicy dev.caskeleton.adapter.outbound.persistence.querydsl.QueryPage -dev.caskeleton.adapter.outbound.persistence.querydsl.QuerydslJpaSupport dev.caskeleton.adapter.outbound.persistence.security.DatabasePrivilegeReport dev.caskeleton.adapter.outbound.persistence.security.DatabaseRolePolicy dev.caskeleton.adapter.outbound.persistence.security.PostgreSqlRuntimeRoleVerifier dev.caskeleton.adapter.outbound.persistence.security.SearchPathPolicy dev.caskeleton.adapter.outbound.persistence.springdata.EntityGraphCatalog -dev.caskeleton.adapter.outbound.persistence.springdata.EntityManagerAccess dev.caskeleton.adapter.outbound.persistence.springdata.FetchPlanApplier dev.caskeleton.adapter.outbound.persistence.springdata.FetchPlanName dev.caskeleton.adapter.outbound.persistence.springdata.JpaKeysetQuerySupport @@ -291,29 +219,4 @@ dev.caskeleton.adapter.outbound.persistence.springdata.SafeSortField dev.caskeleton.adapter.outbound.persistence.springdata.SafeSortMapper dev.caskeleton.adapter.outbound.persistence.springdata.SafeSortRegistry dev.caskeleton.adapter.outbound.persistence.springdata.ScrollPolicy -dev.caskeleton.adapter.outbound.persistence.springdata.SpecificationPolicy -dev.caskeleton.adapter.outbound.persistence.transaction.BackoffCalculator -dev.caskeleton.adapter.outbound.persistence.transaction.CommitFailureClassifier -dev.caskeleton.adapter.outbound.persistence.transaction.CompletionUnknownRecord -dev.caskeleton.adapter.outbound.persistence.transaction.CompletionUnknownRecorder -dev.caskeleton.adapter.outbound.persistence.transaction.DefaultJpaRetryPolicy -dev.caskeleton.adapter.outbound.persistence.transaction.EffectiveTransactionTimeouts -dev.caskeleton.adapter.outbound.persistence.transaction.EvidenceAwareJpaTransactionManager -dev.caskeleton.adapter.outbound.persistence.transaction.FullTransactionRetryCoordinator -dev.caskeleton.adapter.outbound.persistence.transaction.JpaTransactionConfig -dev.caskeleton.adapter.outbound.persistence.transaction.JpaTransactionSettings -dev.caskeleton.adapter.outbound.persistence.transaction.OptimisticConflictTranslator -dev.caskeleton.adapter.outbound.persistence.transaction.PersistenceFailureTranslatorChain -dev.caskeleton.adapter.outbound.persistence.transaction.RetryBudget -dev.caskeleton.adapter.outbound.persistence.transaction.RetrySleeper -dev.caskeleton.adapter.outbound.persistence.transaction.SpringJpaTransactionExecutor dev.caskeleton.adapter.outbound.persistence.transaction.SpringTransactionPort -dev.caskeleton.adapter.outbound.persistence.transaction.ThreadRetrySleeper -dev.caskeleton.adapter.outbound.persistence.transaction.TransactionDefinitionMapper -dev.caskeleton.adapter.outbound.persistence.transaction.TransactionEvidenceContext -dev.caskeleton.adapter.outbound.persistence.transaction.TransactionEvidenceFrame -dev.caskeleton.adapter.outbound.persistence.transaction.TransactionEvidenceScope -dev.caskeleton.adapter.outbound.persistence.transaction.TransactionLocalTimeoutConfigurer -dev.caskeleton.adapter.outbound.persistence.transaction.TransactionProfileRegistry -dev.caskeleton.adapter.outbound.persistence.transaction.TransactionStartBudget -dev.caskeleton.adapter.outbound.persistence.transaction.UnknownOperation diff --git a/docs/architecture/mongo-api-surface.txt b/docs/architecture/mongo-api-surface.txt index 85535c5c..0e6f84a9 100644 --- a/docs/architecture/mongo-api-surface.txt +++ b/docs/architecture/mongo-api-surface.txt @@ -5,8 +5,8 @@ # root yet. # Update only after review with: # ./gradlew :adapter:outbound:persistence-mongo:updateMongoApiSurface -PapproveMongoApiSurfaceChange -# types: 346 -dev.caskeleton.adapter.outbound.mongo.MongoOptInAutoConfigurationImportFilter +# types: 271 +dev.caskeleton.adapter.outbound.mongo.MongoDefaultsEnvironmentPostProcessor dev.caskeleton.adapter.outbound.mongo.MongoPersistenceConfig dev.caskeleton.adapter.outbound.mongo.MongoPersistenceSettings dev.caskeleton.adapter.outbound.mongo.MongoRootAutoConfiguration @@ -14,22 +14,10 @@ dev.caskeleton.adapter.outbound.mongo.advanced.MongoAdvancedCapabilityFlags dev.caskeleton.adapter.outbound.mongo.advanced.MongoAdvancedCapabilityGuard dev.caskeleton.adapter.outbound.mongo.advanced.MongoAdvancedEntryPoint dev.caskeleton.adapter.outbound.mongo.advanced.MongoAdvancedPolicy -dev.caskeleton.adapter.outbound.mongo.advanced.MongoAdvancedPromotionEvidence -dev.caskeleton.adapter.outbound.mongo.advanced.MongoAdvancedPromotionGate -dev.caskeleton.adapter.outbound.mongo.advanced.autoconfigure.MongoAdvancedConfiguration -dev.caskeleton.adapter.outbound.mongo.advanced.autoconfigure.MongoAdvancedSettings -dev.caskeleton.adapter.outbound.mongo.advanced.bridge.MongoBridgeCheckpointPolicy -dev.caskeleton.adapter.outbound.mongo.advanced.bridge.MongoBridgeOutboxPolicy -dev.caskeleton.adapter.outbound.mongo.advanced.bridge.MongoChangeMessagingBridge -dev.caskeleton.adapter.outbound.mongo.advanced.bridge.MongoChangeToIntegrationEventMapper -dev.caskeleton.adapter.outbound.mongo.advanced.bridge.MongoIntegrationEventEnvelope -dev.caskeleton.adapter.outbound.mongo.advanced.bridge.MongoIntegrationEventPublisher -dev.caskeleton.adapter.outbound.mongo.advanced.bridge.MongoPublishResult dev.caskeleton.adapter.outbound.mongo.advanced.encryption.csfle.MongoCsfleClientFactory dev.caskeleton.adapter.outbound.mongo.advanced.encryption.csfle.MongoCsfleFieldPolicy dev.caskeleton.adapter.outbound.mongo.advanced.encryption.csfle.MongoCsfleMode dev.caskeleton.adapter.outbound.mongo.advanced.encryption.csfle.MongoCsfleProfile -dev.caskeleton.adapter.outbound.mongo.advanced.encryption.csfle.MongoDataKeyResolver dev.caskeleton.adapter.outbound.mongo.advanced.encryption.qe.MongoEncryptedFieldDescriptor dev.caskeleton.adapter.outbound.mongo.advanced.encryption.qe.MongoEncryptionMetadataOwnership dev.caskeleton.adapter.outbound.mongo.advanced.encryption.qe.MongoQueryShape @@ -37,15 +25,6 @@ dev.caskeleton.adapter.outbound.mongo.advanced.encryption.qe.MongoQueryShapeSupp dev.caskeleton.adapter.outbound.mongo.advanced.encryption.qe.MongoQueryableEncryptionCollectionManager dev.caskeleton.adapter.outbound.mongo.advanced.encryption.qe.MongoQueryableEncryptionProfile dev.caskeleton.adapter.outbound.mongo.advanced.encryption.qe.MongoQueryableEncryptionQueryType -dev.caskeleton.adapter.outbound.mongo.advanced.gridfs.MongoGridFsCompatibilityReader -dev.caskeleton.adapter.outbound.mongo.advanced.gridfs.MongoGridFsMigrationCheckpoint -dev.caskeleton.adapter.outbound.mongo.advanced.gridfs.MongoGridFsMigrationJob -dev.caskeleton.adapter.outbound.mongo.advanced.gridfs.MongoGridFsObjectReference -dev.caskeleton.adapter.outbound.mongo.advanced.search.MongoSearchIndexDescriptor -dev.caskeleton.adapter.outbound.mongo.advanced.search.MongoSearchIndexState -dev.caskeleton.adapter.outbound.mongo.advanced.search.MongoSearchOperations -dev.caskeleton.adapter.outbound.mongo.advanced.search.MongoSearchQuery -dev.caskeleton.adapter.outbound.mongo.advanced.search.MongoSearchReadinessGate dev.caskeleton.adapter.outbound.mongo.advanced.sharding.MongoRoutingClassification dev.caskeleton.adapter.outbound.mongo.advanced.sharding.ShardAwareQueryValidator dev.caskeleton.adapter.outbound.mongo.advanced.sharding.ShardKeyDescriptor @@ -56,25 +35,12 @@ dev.caskeleton.adapter.outbound.mongo.advanced.sharding.admin.ReshardApproval dev.caskeleton.adapter.outbound.mongo.advanced.sharding.admin.ShardKeyAnalyzer dev.caskeleton.adapter.outbound.mongo.advanced.sharding.admin.ShardKeyReadinessReport dev.caskeleton.adapter.outbound.mongo.advanced.tenancy.database.MongoTenantClientRegistry -dev.caskeleton.adapter.outbound.mongo.advanced.tenancy.database.MongoTenantDatabaseResolver dev.caskeleton.adapter.outbound.mongo.advanced.tenancy.database.MongoTenantLifecyclePolicy dev.caskeleton.adapter.outbound.mongo.advanced.tenancy.database.MongoTenantMigrationCheckpointStore dev.caskeleton.adapter.outbound.mongo.advanced.tenancy.database.MongoTenantMigrationCoordinator dev.caskeleton.adapter.outbound.mongo.advanced.tenancy.shared.MongoTenantContext dev.caskeleton.adapter.outbound.mongo.advanced.tenancy.shared.MongoTenantManifestValidator dev.caskeleton.adapter.outbound.mongo.advanced.tenancy.shared.MongoTenantPredicateInjector -dev.caskeleton.adapter.outbound.mongo.advanced.tenancy.shared.TenantScopedMongoOperations -dev.caskeleton.adapter.outbound.mongo.advanced.timeseries.MongoTimeSeriesCapability -dev.caskeleton.adapter.outbound.mongo.advanced.timeseries.MongoTimeSeriesCapabilityValidator -dev.caskeleton.adapter.outbound.mongo.advanced.timeseries.MongoTimeSeriesDescriptor -dev.caskeleton.adapter.outbound.mongo.advanced.timeseries.MongoTimeSeriesGranularity -dev.caskeleton.adapter.outbound.mongo.advanced.timeseries.MongoTimeSeriesOperations -dev.caskeleton.adapter.outbound.mongo.advanced.timeseries.MongoTimeSeriesSupport -dev.caskeleton.adapter.outbound.mongo.advanced.vector.MongoEmbedding -dev.caskeleton.adapter.outbound.mongo.advanced.vector.MongoVectorIndexDescriptor -dev.caskeleton.adapter.outbound.mongo.advanced.vector.MongoVectorQuery -dev.caskeleton.adapter.outbound.mongo.advanced.vector.MongoVectorSearchBenchmarkGate -dev.caskeleton.adapter.outbound.mongo.advanced.vector.MongoVectorSearchOperations dev.caskeleton.adapter.outbound.mongo.aggregation.MongoAggregationPlan dev.caskeleton.adapter.outbound.mongo.aggregation.MongoAggregationProfile dev.caskeleton.adapter.outbound.mongo.aggregation.MongoAggregationRisk @@ -95,7 +61,6 @@ dev.caskeleton.adapter.outbound.mongo.api.consistency.MongoConsistencyDescriptor dev.caskeleton.adapter.outbound.mongo.api.consistency.MongoConsistencyGuarantee dev.caskeleton.adapter.outbound.mongo.api.consistency.MongoConsistencyProfile dev.caskeleton.adapter.outbound.mongo.api.consistency.MongoConsistencyRegistry -dev.caskeleton.adapter.outbound.mongo.api.error.MongoBulkPartialFailureException dev.caskeleton.adapter.outbound.mongo.api.error.MongoConnectionException dev.caskeleton.adapter.outbound.mongo.api.error.MongoCursorException dev.caskeleton.adapter.outbound.mongo.api.error.MongoDataSchemaUnsupportedException @@ -124,7 +89,6 @@ dev.caskeleton.adapter.outbound.mongo.api.mapping.DomainDocumentId dev.caskeleton.adapter.outbound.mongo.api.mapping.MongoBigIntegerRepresentation dev.caskeleton.adapter.outbound.mongo.api.mapping.MongoDecimalRepresentation dev.caskeleton.adapter.outbound.mongo.api.mapping.MongoEnumRepresentation -dev.caskeleton.adapter.outbound.mongo.api.mapping.MongoIdRepresentation dev.caskeleton.adapter.outbound.mongo.api.mapping.MongoTemporalRepresentation dev.caskeleton.adapter.outbound.mongo.api.mapping.MongoTypeMetadataPolicy dev.caskeleton.adapter.outbound.mongo.api.mapping.MongoTypeRepresentationManifest @@ -148,27 +112,6 @@ dev.caskeleton.adapter.outbound.mongo.autoconfigure.MongoPlatformSettings dev.caskeleton.adapter.outbound.mongo.autoconfigure.MongoProfileProperties dev.caskeleton.adapter.outbound.mongo.autoconfigure.MongoStartupValidator dev.caskeleton.adapter.outbound.mongo.autoconfigure.MongoTopologyProbe -dev.caskeleton.adapter.outbound.mongo.changestream.MongoChangeEventIdentity -dev.caskeleton.adapter.outbound.mongo.changestream.MongoChangeStreamPipeline -dev.caskeleton.adapter.outbound.mongo.changestream.MongoChangeStreamState -dev.caskeleton.adapter.outbound.mongo.changestream.MongoChangeStreamSubscription -dev.caskeleton.adapter.outbound.mongo.changestream.MongoClusterTime -dev.caskeleton.adapter.outbound.mongo.changestream.MongoResumeCheckpoint -dev.caskeleton.adapter.outbound.mongo.changestream.MongoResumeCheckpointStore -dev.caskeleton.adapter.outbound.mongo.changestream.MongoResumePosition -dev.caskeleton.adapter.outbound.mongo.changestream.MongoResumeTokenCodec -dev.caskeleton.adapter.outbound.mongo.changestream.consumer.MongoChangeStreamSource -dev.caskeleton.adapter.outbound.mongo.changestream.consumer.ReactiveMongoChangeStreamConsumer -dev.caskeleton.adapter.outbound.mongo.changestream.consumer.SpringReactiveChangeStreamSource -dev.caskeleton.adapter.outbound.mongo.changestream.projector.MongoChangeClaim -dev.caskeleton.adapter.outbound.mongo.changestream.projector.MongoChangeDeduplicationStore -dev.caskeleton.adapter.outbound.mongo.changestream.projector.MongoChangeProjectionResult -dev.caskeleton.adapter.outbound.mongo.changestream.projector.MongoChangeProjector -dev.caskeleton.adapter.outbound.mongo.changestream.projector.MongoChangeStreamRunner -dev.caskeleton.adapter.outbound.mongo.changestream.recovery.MongoChangeHistoryLostException -dev.caskeleton.adapter.outbound.mongo.changestream.recovery.MongoChangeStreamRecoveryDecision -dev.caskeleton.adapter.outbound.mongo.changestream.recovery.MongoChangeStreamRecoveryPolicy -dev.caskeleton.adapter.outbound.mongo.changestream.recovery.MongoInvalidateRecovery dev.caskeleton.adapter.outbound.mongo.client.MongoClientSettingsFactory dev.caskeleton.adapter.outbound.mongo.failure.DefaultMongoFailureClassifier dev.caskeleton.adapter.outbound.mongo.failure.DefaultMongoFailureTranslator @@ -276,18 +219,6 @@ dev.caskeleton.adapter.outbound.mongo.query.pagination.MongoKeysetQueryBuilder dev.caskeleton.adapter.outbound.mongo.query.pagination.MongoKeysetSlice dev.caskeleton.adapter.outbound.mongo.query.pagination.MongoKeysetSort dev.caskeleton.adapter.outbound.mongo.query.pagination.MongoNullSortOrdering -dev.caskeleton.adapter.outbound.mongo.reactive.DefaultReactiveMongoExecutor -dev.caskeleton.adapter.outbound.mongo.reactive.ReactiveMongoCallback -dev.caskeleton.adapter.outbound.mongo.reactive.ReactiveMongoCollectionAccess -dev.caskeleton.adapter.outbound.mongo.reactive.ReactiveMongoConsistencyBinder -dev.caskeleton.adapter.outbound.mongo.reactive.ReactiveMongoContextKeys -dev.caskeleton.adapter.outbound.mongo.reactive.ReactiveMongoExecutor -dev.caskeleton.adapter.outbound.mongo.reactive.ReactiveScopedMongoOperations -dev.caskeleton.adapter.outbound.mongo.reactive.cursor.MongoCursorGuard -dev.caskeleton.adapter.outbound.mongo.reactive.cursor.MongoCursorLease -dev.caskeleton.adapter.outbound.mongo.reactive.cursor.MongoCursorTermination -dev.caskeleton.adapter.outbound.mongo.reactive.cursor.MongoReactiveCursorPublisher -dev.caskeleton.adapter.outbound.mongo.reactive.cursor.MongoResultBudgetTracker dev.caskeleton.adapter.outbound.mongo.schema.index.MongoIndexApplyPolicy dev.caskeleton.adapter.outbound.mongo.schema.index.MongoIndexDescriptorView dev.caskeleton.adapter.outbound.mongo.schema.index.MongoIndexDiff @@ -337,18 +268,12 @@ dev.caskeleton.adapter.outbound.mongo.transaction.MongoTransactionProfile dev.caskeleton.adapter.outbound.mongo.transaction.MongoTransactionScope dev.caskeleton.adapter.outbound.mongo.transaction.MongoTransactionSession dev.caskeleton.adapter.outbound.mongo.transaction.MongoTransactionSessionFactory -dev.caskeleton.adapter.outbound.mongo.transaction.ReactiveMongoTransactionExecutor -dev.caskeleton.adapter.outbound.mongo.transaction.ReactiveMongoTransactionSession -dev.caskeleton.adapter.outbound.mongo.transaction.ReactiveMongoTransactionSessionFactory dev.caskeleton.adapter.outbound.mongo.transaction.SpringMongoTransactionExecutor dev.caskeleton.adapter.outbound.mongo.transaction.SpringMongoTransactionSessionFactory -dev.caskeleton.adapter.outbound.mongo.transaction.SpringReactiveMongoTransactionExecutor -dev.caskeleton.adapter.outbound.mongo.transaction.SpringReactiveMongoTransactionSessionFactory dev.caskeleton.adapter.outbound.mongo.transaction.retry.MongoCommitReconciler dev.caskeleton.adapter.outbound.mongo.transaction.retry.MongoRetryBudget dev.caskeleton.adapter.outbound.mongo.transaction.retry.MongoRetryDecision dev.caskeleton.adapter.outbound.mongo.transaction.retry.MongoTransactionRetryCoordinator dev.caskeleton.adapter.outbound.mongo.transaction.session.MongoCausalSessionContext dev.caskeleton.adapter.outbound.mongo.transaction.session.MongoCausalSessionExecutor -dev.caskeleton.adapter.outbound.mongo.transaction.session.ReactiveMongoCausalSessionExecutor dev.caskeleton.adapter.outbound.mongo.transaction.session.SpringMongoCausalSessionExecutor diff --git a/docs/capability-status.md b/docs/capability-status.md index 9d5297b0..f1f147be 100644 --- a/docs/capability-status.md +++ b/docs/capability-status.md @@ -9,7 +9,7 @@ real provider." | Column | The question | Who decides it | | --- | --- | --- | | **IMPLEMENTED** | Does this repository contain the capability? | `src/config/architecture/modules.json` — the leaf is registered | -| **WIRED** | Does the shipped `app-bootstrap` artifact assemble it when its switch is on? | the leaf's `META-INF/spring/...AutoConfiguration.imports`, its edge in `app-bootstrap/build.gradle`, and a composition test that boots `CaSkeletonApplication` | +| **WIRED** | Present when selected: does the module assemble itself — own `AutoConfiguration.imports`, own settings, on when present, off with `enabled=false` — once a service adds its one `runtimeOnly` line to `app-bootstrap/build.gradle`? | the leaf's `META-INF/spring/...AutoConfiguration.imports`, the commented line in `app-bootstrap/build.gradle`, and an activation test in the leaf (present = on, `enabled=false` = off) | | **QUALIFIED** | Has it been proven against a real provider, by something CI runs? | a strict test lane against a real provider **and** a workflow that executes it | The third column is the one that rots quietly, because a lane can exist and be invoked by nothing. @@ -17,35 +17,240 @@ Each row below names the lane *and* the workflow, so "qualified" can be checked ## Status -| Capability | Master switch | IMPLEMENTED | WIRED | QUALIFIED | Evidence | +The default composition — what `bootJar` builds — is web, observability, `domain-core`, +`application-core`, `shared-contract`, `adapter:outbound:support` and `adapter:outbound:identifier`. +Every **yes** row in WIRED below is absent from it until a service uncomments that row's +`runtimeOnly` line in `app-bootstrap/build.gradle`. A module on the classpath is on; its enabled key +defaults to `true`, and `false` turns a present module fully off. `./gradlew +:app-bootstrap:qualificationBootJar` packages the main runtime plus every capability, for compose +lanes and CI; it is not a deployment artifact. + +| Capability | Enabled key (property / env, default) | IMPLEMENTED | WIRED | QUALIFIED | Evidence | | --- | --- | --- | --- | --- | --- | -| Relational persistence (JPA/PostgreSQL) | `APP_PERSISTENCE_JPA_ENABLED` | yes | yes | yes | six `postgresql*IntegrationTest` lanes, run by `integration-main.yml` → `jpa-provider-ownership-contracts` | -| Document persistence (MongoDB) | `APP_PERSISTENCE_MONGO_ENABLED` | yes | yes | yes | six container lanes (`mongoReplicaSetTest`, `mongoFailoverTest`, …), run by `integration-main.yml` → `mongo-container-lanes` | -| Messaging (broker-neutral core) | `APP_MESSAGING_ENABLED` | yes | yes | Kafka only | `messaging-kafka:messagingCertificationTest` behind `verifyMessagingCertificationEvidence`, run by `messaging-certification.yml`. **No broker starter ships**: a deployment composes `messaging-spring-boot-starter-kafka` or `-rabbit` itself, and selecting a broker it did not compose is refused at startup. Rabbit ships validators and no transport. | -| Redis capabilities (cache / rate-limit / lease / idempotency) | `APP_REDIS_ENABLED` | yes | yes | yes | `cache-redis:redisTopologyTest`, run by `redis-sdk-topology.yml` | -| Notification platform | `APP_NOTIFICATION_PLATFORM_ENABLED` | yes | yes | claim-scoped | `verifyNotificationEvidence` refuses a grade in `docs/notification/support-matrix.md` that no proven claim backs; run by `notification-platform.yml`. There is no real-SMTP lane, and the matrix says so rather than implying one. | -| File export publication (R2) | `APP_FILESERVER_ENABLED` | yes | yes | yes | A different capability from the platform row below, in its own namespace so the two cannot be switched on together by accident. Atomic publication and durability are proven by `adapter:outbound:fileserver`'s own lanes inside its `check`, which every PR runs. | -| File server platform | `APP_FILESERVER_PLATFORM_ENABLED` | yes | yes | yes | `app-bootstrap:integrationTest` → `FileserverCompositionIntegrationTest` (required by the strict lane, so it cannot silently disappear), run by `integration-main.yml` → `bootstrap-integration` | -| Outbound HTTP client | `APP_HTTPCLIENT_ENABLED` | yes | yes | yes | `httpclient:httpClientFailureInjectionTest` against a faulted upstream, run by `integration-main.yml` → `httpclient-fault-injection` | -| GraphQL transport | `APP_GRAPHQL_ENABLED` | yes | yes | compose-level | `local-graphql` and the three `off-*` lanes in `src/config/runtime/compose-profile-contracts.json`, run by `integration-main.yml` → `compose-runtime-smoke`. The route's absence when the switch is off is what those lanes prove. | -| Object storage | `app.object-storage.enabled` (no `MasterSwitch` entry) | yes | **no** | MinIO only | The leaf is **not** an `app-bootstrap` dependency — only `sample-portfolio` consumes it, and `app-bootstrap:integrationTest` assembles it test-only against digest-pinned MinIO. A fork that wants it adds the edge. | +| Relational persistence (JPA/PostgreSQL) | `ca-skeleton.persistence-jpa.enabled` / `APP_PERSISTENCE_JPA_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:outbound:persistence-jpa')`) | yes | Not in the default composition. The one line brings everything — its own `AutoConfiguration.imports` (`PersistenceJpaAutoConfiguration`, `PersistenceJpaRuntimeConfig`, `JpaStartupAutoConfiguration`), its environment handling (`JpaActivationEnvironmentPostProcessor`, `spring.factories`: readiness `db` while on; with `false` it also excludes Boot's JDBC, Hibernate, Spring Data JPA and Flyway auto-configuration, so no DataSource is bound), the startup guards (Flyway strategy, datasource/OSIV/DDL/pool/TLS/vendor checks, exit codes unchanged) and its settings (`config/module-defaults/persistence-jpa.yml`). `persistence-jpa:PersistenceJpaCapabilityAssemblyTest` proves the module assembles on its own; six `postgresql*IntegrationTest` lanes, run by `integration-main.yml` → `jpa-provider-ownership-contracts`, qualify it against PostgreSQL. `sample-portfolio` selects it by its build dependency and the module's auto-configuration (no broad scan of the persistence package). `bootRunH2` adds the module to its own classpath only. | +| Document persistence (MongoDB) | `ca-skeleton.persistence-mongo.enabled` / `APP_PERSISTENCE_MONGO_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:outbound:persistence-mongo')`) | yes | On when present; `false` also excludes Boot's Mongo auto-configuration (`MongoCapabilityActivationTest`). The connection-source rule (`SPRING_MONGODB_URI` or the selected profile's `uri-secret`) is checked by the module's own `MongoDefaultsEnvironmentPostProcessor`. Six container lanes (`mongoReplicaSetTest`, `mongoFailoverTest`, …), run by `integration-main.yml` → `mongo-container-lanes` | +| Messaging (Kafka) | `app.messaging.enabled` / `APP_MESSAGING_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:outbound:messaging-kafka')`, which brings the application bridge, the legacy `KafkaSender` seam and the vendored platform with its Kafka transport) | Kafka only | On when present (`KafkaCapabilityActivationTest`). `messaging-kafka:messagingCertificationTest` behind `verifyMessagingCertificationEvidence`, run by `messaging-certification.yml`; the starter's `integrationTest` is the live Kafka round trip. Kafka is the only registered broker; the RabbitMQ broker keys were removed (no transport). | +| Redis capabilities (cache / rate-limit / lease / idempotency) | `app.redis.enabled` / `APP_REDIS_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:outbound:cache-redis')`, which brings `redis-runtime`) | yes | `cache-redis:redisTopologyTest`, run by `redis-sdk-topology.yml`. Not in the default composition. On when present; `false` contributes no Redis bean — no settings, client, connection, thread or health contributor. The module owns its readiness contribution (`RedisReadinessGroupPostProcessor`, `spring.factories`) and its settings (`config/module-defaults/cache-redis.yml`: `app.redis.enabled`, `app.rate-limit.*`, the Redis `ca-skeleton.capabilities.*`). No `app-bootstrap` main source names a Redis type. | +| Request idempotency | `APP_IDEMPOTENCY_PROVIDER` (`disabled` \| `redis` \| `postgresql`; a selector, not an on/off key) | yes | yes | Redis only | One generation: the application `IdempotencyExecutor`, built once by `app-bootstrap` `IdempotencyProviderSelectionConfig` over the one store the selected provider contributes (`cache-redis` or `persistence-jpa`); startup is refused unless exactly one store exists. `sample-portfolio` cannot depend on `app-bootstrap`, so its own `SampleIdempotencyConfig` builds its one executor from the same keys. Redis is covered by the row above. PostgreSQL has `persistence-jpa:postgresqlIdempotencyIntegrationTest`, but no workflow runs it. The `postgresql` provider refuses a non-PostgreSQL data source, so `bootRunH2` uses `disabled` or `redis`.. The executor stays in the composition root on purpose — it needs only application-core and its settings — while each store comes with its module: `postgresql` needs the persistence-jpa line, `redis` the cache-redis one. | +| Transactional outbox relay | `ca-skeleton.outbox.enabled` / `APP_OUTBOX_ENABLED`, `false` (+ `APP_OUTBOX_RELAY_ENABLED`, `false`; persistence-jpa settings) | yes | yes (with the persistence-jpa line; the scheduler also needs the messaging-kafka line) | yes | The store and its settings are persistence-jpa's; the relay (`OutboxConfig`) is application composition in `app-bootstrap` because a driven adapter must not build or call a use case. It turns on only when an `OutboxStorePort` bean exists, and the scheduler only when an `OutboxMessagePublishPort` does (the messaging bridge), each ordered after its contributor by `afterName` — so an environment with no publisher keeps its PENDING rows. The bridge registers no stand-in publisher: a present-and-enabled bridge with a blank broker and no canonical transport is refused at startup. `postgresqlLegacyOutboxConcurrentRelayIntegrationTest` qualifies claim/fencing against PostgreSQL. | +| Notification platform | `ca-skeleton.notification.platform.enabled` / `APP_NOTIFICATION_PLATFORM_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':composition:notification-platform')`, plus the persistence-jpa line) | claim-scoped | Not in the default composition. The one line brings the use-case assembly, `adapter:outbound:notification`, the HTTP surface `adapter:inbound:web-notification` and its own settings (`config/module-defaults/notification.yml`), each registered through the module's own `AutoConfiguration.imports`; `adapter:inbound:web` no longer depends on `application-notification`. `verifyNotificationEvidence` refuses a grade in `docs/notification/support-matrix.md` that no proven claim backs; run by `notification-platform.yml`. There is no real-SMTP lane, and the matrix says so rather than implying one. | +| 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 `integration-main.yml` → `bootstrap-integration` | +| 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 `integration-main.yml` → `httpclient-fault-injection` | +| 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` (no `APP_*` row), `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. | | gRPC platform | — (build-level) | yes | **no** | yes | Absent from the main build entirely: `optional-platforms` is a separate Gradle build, so the switch is the `include`, not an environment variable. `-p optional-platforms ci` runs on every PR and `integrationCheck` certifies the operation ledger against real PostgreSQL. | -| WebSocket transport | — (build-level) | yes | **no** | — | Qualification-only edge in `app-bootstrap`; `ConditionalTransportBuildContractTest` asserts it has no production edge. | +| gRPC transport (`adapter:inbound:grpc`) | `ca-skeleton.grpc.enabled` (no `APP_*` row), `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 `ca-skeleton.grpc.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. | +| Web Advanced library (`adapter:inbound:web-advanced`) | — (build-level; three `backend.web.advanced.*.enabled` switches inside) | yes | **no** | — | No composition root depends on it; `app-bootstrap` takes it `testRuntimeOnly` for the ArchUnit import. No real-provider lane: `webAdvancedTest` (the `web-advanced` tag, run by `release.yml` → `web-stable-release-gate`) is unit and context-runner level. The Nginx lane went with the proxy library on 2026-09-25. | ## Reading the "no" rows -A **no** in WIRED is not a defect. It is the review's Build Composition principle working: the -repository holds more capabilities than any one derived service should ship, and a capability that -is absent from the artifact holds no beans, no connections and no threads whatever its configuration -says. The three **no** rows are the ones where that choice has been made and is enforced by a test. +A **yes** in WIRED means "present when its line is selected": uncommenting the one line is the whole +change, and deleting it removes the module's beans, settings and dependencies together. It does not +mean the default artifact ships the capability — none of the **yes** rows is in the default +composition. A capability that is absent from the artifact holds no beans, no connections and no +threads whatever its configuration says, so the missing line is the ordinary off state and +`enabled=false` is only the explicit off for a module that is present. -The rows that say **yes** are the ones where the choice is still "ship it and switch it off", which -is a weaker guarantee — correct, but it depends on the switch being honest rather than on the code -being absent. Moving more rows to **no** is what `app-bootstrap`'s composition-ownership work is for. +A **no** in WIRED is not a defect either. It marks a capability with no one-line selection: the gRPC +platform is a separate Gradle build, and the web-advanced library is taken as `implementation` by a +service's own adapter leaf, never by a composition root. ## Keeping this honest -`CapabilityStatusDocumentTest` derives the switch list from `MasterSwitch` and fails when a switch -has no row here. That is deliberately the only automated check: a table of facts that a parser +`CapabilityStatusDocumentTest` checks that the column sources above are named — the module +registry, `AutoConfiguration.imports`, and a workflow that executes the lane. The switch list it used +to derive from `MasterSwitch` went with that class (2026-09-25). That is deliberately the only +automated check: a table of facts that a parser re-derives would be a second source of truth, and the columns above are judgements about evidence, which is exactly the thing the review says a build must not pretend to compute. + +## 제거된 코드 (2026-09-25 리팩터링) + +web 경로의 `W/`는 `src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/`, `WF/`는 `src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/`. + +복구가 필요하면 표의 커밋에서 경로를 꺼낸다(`git show <커밋>:<경로>`). + +| 대상 | 경로 | 마지막으로 존재한 커밋 | 이유 | +| --- | --- | --- | --- | +| 파일 publication R1/R2 어댑터(`FileserverR2Config`, `FileExportConfig`, local-persistent provider 등 31개)와 테스트 | `src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/*.java`, 같은 위치의 `src/test` 루트 파일 | `208077fd` | 조립 경로 없음(component scan 밖, 호출자 없음) | +| `FilePublicationPort`·`FileExportPort` 계약 | `src/application-core/src/main/java/dev/caskeleton/application/filepublication/`, `.../application/fileexport/` | `208077fd` | 호출자 없음 | +| `MasterSwitch.FILESERVER`, `app.fileserver.*`·`app.file-export.*` 설정, `APP_FILESERVER_ENABLED`·`APP_FILESERVER_LOCAL_*` env key | `src/shared-contract/.../activation/MasterSwitch.java`, `src/app-bootstrap/src/main/resources/config/fileserver.yml` | `208077fd` | 읽는 코드 없음 | +| websocket Advanced STOMP·RabbitMQ relay(`StompBrokerExclusivity` 포함), `APP_WEBSOCKET_ADVANCED_STOMP_*` env key | `src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/` | `208077fd` | 같은 기능의 중복 구현(`stomp/`가 남음) | +| websocket main의 검증용 코드(`moduleboundary`, `evidence`, `release`) | `src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/{moduleboundary,evidence,release}/` | `208077fd` | 호출자 없음 | +| httpclient `BoundedErrorBody` | `src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/restclient/BoundedErrorBody.java` | `208077fd` | 호출자 없음 | +| httpclient Spring 7 service group·`RestTemplate` 이행 패키지 | `src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/{spring7,migration}/` | `208077fd` | 테스트에서만 사용 | +| `UuidCodec` | `src/adapter/outbound/identifier/src/main/java/dev/caskeleton/adapter/outbound/identifier/UuidCodec.java` | `208077fd` | 호출자 없음 | +| object storage legacy adoption(`maintenance/`, `ObjectStorageLegacyMigrationConfig`, `LegacyObjectAdoptionSettings`), `storage/migration` 포트, sample `AdoptLegacyPosterImageUseCase`와 전용 타입 | `src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/maintenance/`, `src/application-objectstorage/src/main/java/dev/caskeleton/application/storage/migration/`, `src/sample-portfolio/.../application/poster/migration/` | `208077fd` | 켜면 기동 실패(SPI 구현 없음) | +| object storage readiness 타입(`ObjectStorageCapabilityEvidence`, `ObjectStorageCapabilityCard`, `ObjectStorageReadinessLevel`) | `src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/readiness/` | `208077fd` | 테스트에서만 사용(검증은 `ObjectStorageReadinessRegistryTest`로 이동) | +| `ObjectControlRecordEnvelope` | `src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/control/ObjectControlRecordEnvelope.java` | `208077fd` | 호출자 없음 | +| application-core 테스트 헬퍼 `CompiledPackageScanner` | `src/application-core/src/test/java/dev/caskeleton/application/testsupport/CompiledPackageScanner.java` | `208077fd` | 호출자 없음 | +| web WebFlux 플랫폼 (`WebFluxPlatformAutoConfiguration` 외) | `W/webflux/` | `208077fd` | D4: servlet + virtual threads 단일 스택, 기본 조립이 선택할 수 없음 | +| web Advanced WebFlux 스트리밍·blocking bridge 어댑터 | `W/advanced/webflux/` | `208077fd` | D4: WebFlux 쌍둥이 | +| 알림 콜백 WebFlux 핸들러 | `W/notification/platform/callback/reactive/` | `208077fd` | D4: WebFlux 쌍둥이 (MVC 컨트롤러가 유일 경로) | +| 파일 서버 WebFlux 전송 | `WF/reactive/` | `208077fd` | D4: WebFlux 쌍둥이, 조립 불가 | +| WebFlux 계약·성능 lane, cross-stack parity lane | `src/adapter/inbound/web/src/webfluxContractTest/`, `build.gradle`의 `webFluxContractTest`·`webFluxPerformanceTest`·`webCrossStackParityTest` | `208077fd` | D4: Reactor Netty 대상 lane, 비교 대상 소멸 | +| web 모듈 경계 맵 (`WebStableModule` 외) | `W/moduleboundary/`, `src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/moduleboundary/` | `208077fd` | main에 둔 governance 코드, 소비자 없음 | +| 서명 커서 코덱 (`CursorCodec`, `CursorException`) | `W/cursor/` | `208077fd` | 호출자 0, `GlobalExceptionHandler` 커서 처리도 함께 제거 | +| 2세대 관측 (`WebAccessLog*`, `WebAudit*`, `WebObservationConvention`, `WebMetricCardinalityPolicy`) | `W/observability/` | `208077fd` | 조립 안 된 2세대, `RequestLoggingFilter`가 정본 | +| 2세대 조건부 요청 (`EntityTag`, `ConditionalReadEvaluator`, `MutationPreconditionEvaluator` 외) | `W/conditional/` | `208077fd` | 2세대, `ETags`·`PreconditionFailedException`이 정본 | +| 2세대 페이지네이션 (`HmacWebCursorCodec`, `WebCollectionRequestParser` 외 16개) | `W/pagination/` | `208077fd` | 2세대, `PageParams`·`SortParam`이 정본 | +| 응답 계약·헤더 이름 (`WebHeaderName`, `WebResponseContract`, `WebSuccessResponse`, `DeprecationHeaderWriter`) | `W/http/`, `W/versioning/` | `208077fd` | 호출자 0 | +| 병렬 rate-limit (`WebRateLimiter`, web `RateLimitDecision`·`RateLimitFailurePolicy`·`RateLimitProfileName`, `WebMvcThrottleFilter`, `ThrottleProblemWriter`) | `W/ratelimit/`, `W/mvc/throttle/`, `W/error/` | `208077fd` | 2세대, `RateLimitInterceptor` + shared-contract `RateLimitDecision`이 정본 | +| rate-limit draft 헤더 (`RATELIMIT_DRAFT_HEADERS`) | `W/advanced/ratelimit/`, `WebAdvancedFeature` 상수 | `208077fd` | 병렬 rate-limit 세트에만 붙는 부가 기능 | +| admission 제어 | `W/admission/` | `208077fd` | 조립 안 된 2세대 | +| evidence 필터·startup check·platform snapshot | `W/evidence/`, `W/mvc/filter/WebMvcEvidenceFilter.java`, `W/mvc/autoconfigure/WebMvcPlatformStartupCheck.java`, `W/admin/platform/` | `208077fd` | 읽는 곳 없는 bean, `WebMvcPlatformAutoConfiguration`은 3개 bean만 유지 | +| 검증 예외 매퍼 | `W/validation/` | `208077fd` | 제거된 bean·problem handler에서만 도달 | +| WebProblem 어휘 (`ProblemCode`, `ProblemCatalog`, `WebProblem`, `WebProblemFactory` 외) | `W/error/`, `W/mvc/error/`, `src/adapter/inbound/web/src/main/resources/META-INF/web/problem-catalog.yaml`, `W/openapi/ProblemSchemaContributor.java`, `W/openapi/WebOpenApiReleaseGate.java` | `208077fd` | 운영 에러는 `GlobalExceptionHandler`의 Envelope, `spring.mvc.problemdetails.enabled=false` | +| 요청 budget 필터 (`WebMvcBudgetFilter`, `BudgetProblemMapper`) | `W/mvc/budget/`, `W/error/BudgetProblemMapper.java` | `208077fd` | fixture 전용, WebProblem 어휘에 의존 | +| stream 종료 어휘 (`TerminationDecision`, `WebStreamEnvelope`, `WebStreamTerminationMapper`) | `W/advanced/stream/` | `208077fd` | `ProblemCode`에 의존, 호출자 0 | +| durable operation HTTP 투영 (`OperationQueryService`, `OperationHttpController` 외) | `W/operationasync/`, `W/mvc/operation/` | `208077fd` | 운영 조립 없음(scan 제외·bean 없음), 실패를 `WebProblem`으로만 표현. application-core use case는 유지 | +| WebProblem·budget·throttle·operation fixture와 lane | `src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/{budget,throttle,operation,contract,webflux}/`, `webtestkit/{Budget,Throttle}FixtureApplication.java`, `systemTest`·`jettyCompatTest`의 budget/contract/operation/throttle IT | `208077fd` | 제거된 표면만 인증. Tomcat/Jetty 전송 lane은 Envelope 기준으로 유지 | +| WebFlux 전용 오버로드 (`ZeroCopyEligibility.isEligible(ServerHttpResponse…)`·`supportsZeroCopy`, `CallbackRequestFactory.create(…externalUrl…)`) | `WF/http/ZeroCopyEligibility.java`, `W/notification/platform/callback/CallbackRequestFactory.java` | `208077fd` | 제거된 reactive 핸들러만 호출 | +| graphql 부팅 시 컨트롤러 경계 검사 `architecture/` (9개, ~970줄) | `src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/architecture/` | `208077fd` | 부팅마다 리플렉션으로 검사하던 것. 규칙 2개(resolver 전송 타입, raw DataFetcher 위치)는 `GraphQlTransportBoundaryArchitectureTest`(ArchUnit)로 옮김 | +| `GraphQlPlatformAutoConfiguration.graphQlControllerBoundaryCheck` bean | `src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPlatformAutoConfiguration.java` | `208077fd` | 위 검사를 부팅 때 돌리던 bean. 빌드 때 ArchUnit으로 대체 | +| graphql 스키마 호환성 비교기 `compat/` (11개, ~1,560줄) | `src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/compat/` | `208077fd` | 호출하는 production 코드 없음(테스트만) | +| graphql 모듈 경계 모델 `moduleboundary/` (main 4개 + test 스캐너 3개) | `src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/moduleboundary/` | `208077fd` | sub-package 경계 선언과 소스 스캐너 테스트. 런타임 소비자 없음 | +| graphql 릴리스 게이트 `release/` (9개) | `src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/release/` | `208077fd` | 호출하는 곳 없음. 성능·장애 증거도 없었음 | +| graphql Advanced 릴리스 게이트 `advanced/release/` (7개) | `src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/release/` | `208077fd` | 호출하는 곳 없음 | +| `GraphQlAdvancedDependencyRules` | `src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/bootstrap/GraphQlAdvancedDependencyRules.java` | `208077fd` | `moduleboundary` 전용, 테스트에서만 사용 | +| `GraphQlGeneratedCompatibilityGate` | `src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/codegen/GraphQlGeneratedCompatibilityGate.java` | `208077fd` | `compat` 전용, 테스트에서만 사용 | +| testFixtures `GraphQlSchemaContractSuite` | `src/adapter/inbound/graphql/src/testFixtures/java/dev/caskeleton/adapter/inbound/graphql/testkit/GraphQlSchemaContractSuite.java` | `208077fd` | `compat` 의존, 테스트에서만 사용 | +| messaging adapter R1 contract/binding 컴파일러 `contract/`·`destination/`·`config/` (MessagingCapabilityCardRegistry 포함) | `src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/{contract,destination,config}/` | `208077fd` | 어느 조립에도 연결되지 않은 R1 세대 | +| messaging adapter R1 JSON Schema envelope encoder `envelope/` + pin한 Draft 2020-12 meta-schema 리소스 | `src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/envelope/, src/adapter/outbound/messaging/src/main/resources/contracts/messaging/meta/` | `208077fd` | 조립 없음. NetworkNT가 production 의존성에서 빠짐. `IntegrationEventEncoderPort`는 adopter 확장 지점으로 유지 | +| messaging adapter `realtime/` (`MessagingDurableFanoutAdapter`, `RealtimeFanoutEnvelopeJson`) | `src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/realtime/` | `208077fd` | bean 없음 | +| strict lane `messagingCompiledContractsQualificationTest`·`messagingJsonSchemaV1QualificationTest`, 루트 `verifyMessagingJsonSchemaV1`·`validateMessagingJsonSchemaV1EvidenceManifestSchema` | `src/adapter/outbound/messaging/build.gradle, src/build-tools/src/main/java/dev/caskeleton/buildtools/messaging/MessagingQualificationPlugin.java` | `208077fd` | 삭제한 R1 코드만 검증하던 레인. `verifyMessagingContracts`는 application·shared 레인으로 남김 | +| `MessagingEvidenceManifestSchemaValidator`(+Test)와 루트 JavaExec `validateMessagingContractsEvidenceManifestSchema` | `src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/qualification/` | `208077fd` | 삭제한 `LocalJsonSchemaRegistry`에 의존했고, 다른 project의 test classpath를 루트 task가 풀어 쓰는 구조였음. 같은 검증을 build-tools `MessagingEvidenceSchemaValidator`로 옮겨 `verifyMessagingContracts`가 직접 수행 | +| `messaging-pulsar-experimental` leaf | `src/messaging/messaging-pulsar-experimental/` | `208077fd` | SDK 없는 seam, 기본 비활성, 조립 없음 | +| `messaging-nats-experimental` leaf | `src/messaging/messaging-nats-experimental/` | `208077fd` | SDK 없는 seam, 기본 비활성, 조립 없음 | +| `messaging-kafka-share-experimental` leaf | `src/messaging/messaging-kafka-share-experimental/` | `208077fd` | 기본 비활성, 조립 없음 | +| `messaging-spring-cloud-stream-bridge` leaf | `src/messaging/messaging-spring-cloud-stream-bridge/` | `208077fd` | StreamBridge 연동 없는 seam, 조립 없음 | +| `messaging-rabbit` leaf | `src/messaging/messaging-rabbit/` | `208077fd` | production transport가 없어 선택하면 기동 거부되던 상태 | +| `messaging-spring-boot-starter-rabbit` leaf | `src/messaging/messaging-spring-boot-starter-rabbit/` | `208077fd` | 위 rabbit leaf의 조립 모듈 | +| Debezium outbox 매핑 (`DebeziumOutboxEventRouter` 등 4개 + `debezium/outbox-event-router.properties`) | `src/messaging/messaging-outbox-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/outbox/Debezium*.java` | `208077fd` | 조립 없음. `routing_key` 컬럼은 유지 | +| `MessagingSettings.Experimental`·`Bridge` (`app.messaging.experimental.*`, `app.messaging.bridge.*`) | `src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/MessagingSettings.java` | `208077fd` | 바인딩만 되고 읽는 코드 없음 | +| `MessagingProviderSelection`의 rabbit 항목 | `src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/MessagingProviderSelection.java` | `208077fd` | rabbit leaf 삭제에 따름 | +| starter의 `messaging-cloudevents`·`messaging-claim-check` 의존 edge (leaf는 유지) | `src/messaging/messaging-spring-boot-starter/build.gradle, src/config/architecture/modules.json` | `208077fd` | starter main이 두 leaf를 참조하지 않음 | +| RabbitMQ·Pulsar·NATS 개발용 compose | `infra/messaging/{rabbitmq,pulsar,nats}/docker-compose.yml` | `208077fd` | 해당 어댑터 삭제에 따름 | +| Notification R1 타입 96개(`NotificationPort`·`Notification`·`NotificationChannel` 제외)와 테스트 19개 | `src/application-notification/src/{main,test}/java/dev/caskeleton/application/notification/*.java` | `208077fd` | production 소비자 0건. platform이 canonical(NOTIF-ADR-005) | +| ArchUnit 규칙 `NOTIFICATION_R1_AND_PLATFORM_DO_NOT_DEPEND_ON_EACH_OTHER` | `src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ApplicationBoundaryArchitectureTest.java` | `208077fd` | R1이 없어져 지킬 경계가 없음 | +| Notification Reactor facade와 `reactor-core`·`reactor-test`·`spring-web` 의존 | `src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/reactor/` | `208077fd` | 조립 0건. `spring-web`은 import 0건 | +| `NotificationOrchestrator` | `src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/api/NotificationOrchestrator.java` | `208077fd` | 호출자는 연산별 use case 포트로 이미 분리됨 | +| notification platform `sms`·`push`·`email`·`webpush` facade와 `ApplicationReceiptServiceImpl` | `src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/{sms,push,email,webpush}/`, `.../platform/dispatch/ApplicationReceiptServiceImpl.java` | `208077fd` | 구현·조립 0건 | +| 던지는 곳이 없는 notification 예외 12종 | `src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/api/error/` | `208077fd` | throw 0건 | +| notification redaction 5종(`NotificationRedactor`, `SafeDiagnosticContext`, `SensitiveValueClassifier`, `SensitiveValueKind`, `UnsafeDiagnosticFieldException`) | `src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/security/` | `208077fd` | production 호출 0건 | +| `contract-v1` 테스트 템플릿 4개 | `src/adapter/outbound/notification/src/test/resources/notification/templates/` | `208077fd` | 읽는 테스트 없음 | +| JPA notification crypto 6종과 테스트 | `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/crypto/` | `208077fd` | 테스트 외 사용 0건. `ContactPointRoundTripTest`는 application-notification으로 이동 | +| JPA 두 번째 트랜잭션·재시도 엔진 19종(`SpringJpaTransactionExecutor`, `FullTransactionRetryCoordinator`, `CommitFailureClassifier`, `EvidenceAwareJpaTransactionManager`, `CompletionUnknownRecorder` 등), `JpaTransactionAutoConfiguration`, `JpaObservabilityAutoConfiguration`, `JpaRetryObservation`, `api/transaction/*`(`TransactionCompletionEvidence` 제외) | `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/{transaction,autoconfigure,observation,api/transaction}/` | `208077fd` | 빈은 있었으나 호출자 0건. 트랜잭션 엔진을 `SpringTransactionPort` 하나로 | +| `VendorFailureTranslator` 빈 2개와 `H2FailureTranslator` | `.../persistence/postgresql/PostgreSqlPersistenceConfig.java`, `.../persistence/h2/` | `208077fd` | 유일한 소비자(위 엔진)가 사라짐 | +| 위 엔진 전용 테스트(`CommitAmbiguityContractTest`, `OptimisticRetryIntegrationTest`, `PostgreSqlVendorFailureTranslatorRegistrationTest` 등) | `src/adapter/outbound/persistence-jpa/src/{test,postgresqlIntegrationTest}/` | `208077fd` | 대상 코드 삭제 | +| `PolicyTransactionPort` 계열(`TransactionRequest`, `TransactionResult`, `TransactionPolicyId`, `TransactionPhase`, `TransactionOutcome`, `ReconciliationReference`, `TransactionAdmissionException`) | `src/application-core/src/main/java/dev/caskeleton/application/transaction/` | `208077fd` | 유일한 호출자(fileserver 보상)를 `TransactionPort.inNew`로 교체 | +| `SpringPolicyTransactionPort`, `TransactionRetryBackoff`, `TransactionRetryClassifier`, 타임아웃 계열(`TransactionDeadlineCalculator`, `TransactionStartBudget`, `EffectiveTransactionTimeouts`, `TransactionLocalTimeoutConfigurer`, `PostgreSqlLocalTimeoutConfigurer`, `H2LocalTimeoutConfigurer`, `JpaTransactionSettings`, `JpaTransactionConfig`)과 `ca-skeleton.jpa.transaction.*` 설정 | `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/`, `src/app-bootstrap/src/main/resources/config/persistence.yml` | `208077fd` | policy 경로 전용. 교체 후 사용처 0건 | +| `FileserverCompensationTransaction` | `src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/` | `208077fd` | `transactions.inNew(...)` 한 줄로 대체 | +| Mongo reactive 경로(`reactive/**`, reactive transaction/session 6종, `ReactiveExecution`, `applyTo(ReactiveMongoTemplate)`)와 reactive starter·`reactor-test` 의존 | `src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/{reactive,transaction}/` | `208077fd` | 기본 조립에서 exclude되어 도달 불가, 포트 없음 | +| Mongo change stream(`changestream/**`)과 change-stream→messaging bridge(`advanced/bridge/`), 문서 `change-stream-guide.md`·`runbooks/history-lost.md` | `src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/{changestream,advanced/bridge}/`, `docs/mongodb/` | `208077fd` | driver source가 없어 실행 불가 | +| application-core cache 20종(`CacheAsideExecutor`, `CacheAsidePolicy`, `CacheSingleFlight`, `CacheRefresh*`, `CacheObservation*` 등)과 테스트 4개 | `src/application-core/src/main/java/dev/caskeleton/application/cache/` | `208077fd` | 조립·소비자 0건. cache-redis는 `CacheRegionPort` 계열 9종만 사용 | +| `LeaseWatchdog` | `src/application-core/src/main/java/dev/caskeleton/application/lease/` | `208077fd` | main 참조 0건 | +| `TransactionCompletionResolver`, `CompletionResolution` | `src/application-core/src/main/java/dev/caskeleton/application/transaction/` | `208077fd` | 구현체 0건 | +| same-store inbox(`application/inbox/`, `PostgreSqlSameStoreInboxAdapter`, `PostgreSqlInboxIntegrationTest`, `db/migration/jpa/inbox`, readiness card `jpa-inbox-same-store-v1`) | `src/application-core/src/main/java/dev/caskeleton/application/inbox/`, `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/inbox/` | `208077fd` | 어떤 조립도 migration 트리를 적용한 적 없음 | +| `EphemeralFanoutPort`, `RedisEphemeralFanoutAdapter` | `src/application-core/src/main/java/dev/caskeleton/application/realtime/`, `src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/realtime/` | `208077fd` | bean·테스트·호출자 0건 | +| PostgreSQL work-claim 실행기(`WorkClaimExecutor`, `PostgreSqlWorkClaimExecutor`, `WorkClaim`, `WorkQueueDefinition`, `WorkQueueName`) | `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/lock/` | `208077fd` | 호출자 0건 | +| PostgreSQL upsert 실행기 7종 | `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/write/` | `208077fd` | 호출자 0건 | +| Mongo `ca-skeleton.persistence-mongo.advanced..enabled` 바인딩(`MongoAdvancedConfiguration`, `MongoAdvancedSettings`)과 `MongoAdvancedCapabilityFlags.PROPERTY_PREFIX`·`propertyFor` | `src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/autoconfigure/`, `src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/MongoAdvancedCapabilityFlags.java` | `208077fd` | import하는 main 코드 0건이라 어떤 배포 property도 flag에 닿지 않음. flag는 진입점을 만드는 어댑터 코드가 직접 만든다 | +| Mongo search·vector(`advanced/search/` 5종, `advanced/vector/` 5종, `MongoSearchReadinessGate`·`MongoVectorSearchBenchmarkGate` 포함), 문서 `docs/mongodb/advanced/search-vector.md` | `src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/{search,vector}/` | `208077fd` | `MongoSearchOperations`·`MongoVectorSearchOperations` 구현체 0건. 나머지는 그 인터페이스의 인자와 main에 둔 gate | +| Mongo time series(`advanced/timeseries/` 6종), 문서 `docs/mongodb/advanced/time-series.md` | `src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/timeseries/` | `208077fd` | `MongoTimeSeriesOperations` 구현체 0건. 나머지는 descriptor와 모든 항목이 unsupported인 표 | +| Mongo GridFS 호환(`advanced/gridfs/` 4종), 문서 `docs/mongodb/advanced/gridfs-migration.md` | `src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/gridfs/` | `208077fd` | `MongoGridFsCompatibilityReader` 구현체 0건이라 `MongoGridFsMigrationJob`을 실행할 수 없음 | +| `MongoDataKeyResolver`, `MongoTenantDatabaseResolver`, `TenantScopedMongoOperations` | `src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/{encryption/csfle,tenancy/database,tenancy/shared}/` | `208077fd` | 구현체·호출자 0건 | +| `MongoAdvancedPromotionGate`, `MongoAdvancedPromotionEvidence` | `src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/` | `208077fd` | production classpath의 promotion gate, 자기 테스트 외 호출자 0건. 증거 항목은 ADR-MONGO-ADV-001의 리뷰 의무로 남김 | +| testFixtures `MongoAtlasCapabilityContractSuite`, provider testkit `MongoAtlasLocalContainer`, release contract `MONGO-REL-011` | `src/adapter/outbound/persistence-mongo/src/{testFixtures,mongoProviderTestkit}/java/dev/caskeleton/adapter/outbound/mongo/testkit/atlas/`, `src/config/mongodb/release-contracts.json` | `208077fd` | 위 promotion gate 테스트만 사용. 등록된 lane 없음 | +| `MongoIdRepresentation`, `MongoBulkPartialFailureException` | `src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/api/mapping/`, `src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/api/error/` | `208077fd` | 참조 0건. 문서는 "`_id` 표현을 정한다", "부분 실패를 알린다"고 했지만 쓰거나 던지는 코드가 없음 | +| Mongo `platform.change-streams` 키(`MongoPlatformSettings.changeStreams`, `MongoStartupValidator`의 change stream 검사) | `src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/autoconfigure/` | `208077fd` | 켜면 기동 실패만 하는 키. change stream 기능은 이미 삭제됨 | +| Mongo profile 키 `consistency-default`, `decimal-representation`, `runtime-auto-create-indexes` | `src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/autoconfigure/MongoProfileProperties.java`, `src/app-bootstrap/src/main/resources/config/persistence.yml`(주석 예시), `docs/mongo/persistence-profile.example.yml` | `208077fd` | 검증만 하고 읽는 코드 0건. decimal은 허용 값이 `DECIMAL128` 하나, auto-index는 Spring Data 설정에 연결되지 않음 | +| 위 대상 전용 테스트 5개 클래스(36개)와 테스트 메서드 2개 | `src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/advanced/{autoconfigure,search,timeseries,gridfs}/`, `.../advanced/MongoAdvancedPromotionGateTest.java`, `MongoPlatformSettingsTest.productionRefusesRuntimeIndexCreation`, `MongoStartupValidationTest.changeStreamsCannotBeSwitchedOn` | `208077fd` | 대상 코드 삭제. guard 거부 검증은 `MongoAdvancedCapabilityGuardTest`로 옮김 | +| redis-sdk 진입 인터페이스 `RedisOperations`·`ReactiveRedisOperations` | `src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/` | `208077fd` | 구현체 없음 | +| redis-sdk `ExpirationUpdatePolicy` | `src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/` | `208077fd` | 호출자 없음 | +| redis-sdk `RedisCommandMetadataDiff`·`RedisServerCommandMetadata`와 테스트 | `src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/` | `208077fd` | main에 둔 gate, 연결된 build 검사 없음(테스트에서만 사용) | +| redis-sdk `RedisConnectionRegistry`·`RedisConnectionLease`와 테스트 | `src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/` | `208077fd` | 테스트에서만 사용. lane 한도는 redis-runtime `RedisRuntimeOwner`가 소유 | +| `app.redis.limits.*`·`advanced.*`·`raw.*`·`timeout.collection`·`timeout.admin`·`blocking.max-block`·`lifecycle.tls-handshake-timeout`·`capacity.maximum-in-flight-bytes`·`capacity.maximum-reply-bytes`·`pubsub.overflow-policy`, env key 23개, `RedisCredentialRole.RAW` | `src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisSdkSettings.java`, `RedisSdkAutoConfiguration.java` | `208077fd` | 검증만 하고 읽는 코드 없음. `raw.*`는 어떤 lane도 쓰지 않는 RAW 계정 클라이언트를 만들고 allowlist 파일은 존재만 확인. SDK 한도·advanced 정책·raw 승인은 코드(`RedisOperationLimits`, `ConfiguredRedisPolicyAuthority`, `RawCommandApprovals`)로 준다 | +| application-core outbox V2 포트·유스케이스 17종(`NewOutboxEventV2`, `OutboxAppendPortV2`, `OutboxPollingDeliveryPortV2`, `PublishNextOutboxDeliveryUseCase`, `OutboxV2RetryPolicy`, `OutboxPublicationAuthority` 등)과 계약 테스트 2개 | `src/application-core/src/{main,test}/java/dev/caskeleton/application/outbox/v2/` | `208077fd` | 어떤 조립도 만들지 않은 세대(D2). v1 relay 한 세대만 남기고 owner/token fencing은 v1로 이식 | +| JPA outbox V2 adapter(`PostgreSqlImmutableOutboxAppendAdapter`, `PostgreSqlPollingDeliveryAdapter`, `CanonicalOutboxEventRowMapper`)와 단위 테스트(`PostgreSqlOutboxTransitionDigestTest`, `OutboxStorageMigrationSafetyTest`) | `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/outbox/`, `.../src/test/java/.../persistence/{postgresql/outbox,migration}/` | `208077fd` | 빈 등록 0건, 위 V2 포트 전용 | +| outbox V2 migration stream `jpa/outbox-storage`(V1·V2), `jpa/outbox-polling`(V1·V2)과 `applied-migrations.sha256`의 해당 4줄 | `src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/jpa/{outbox-storage,outbox-polling}/` | `208077fd` | 어떤 composition도 Flyway location으로 설정한 적 없음 | +| outbox V2 PostgreSQL 통합 테스트(`PostgreSqlOutboxStorageIntegrationTest`, `PostgreSqlOutboxPollingIntegrationTest`, `CanonicalOutboxV2TestFixture`, `LegacyOutboxDrainContractTest`), lane `postgresqlOutboxStorageIntegrationTest`·`postgresqlOutboxPollingIntegrationTest`, `PostgreSqlOptionalStreamLifecycle.outboxStorage()/outboxPolling()` | `src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/`, `src/build-logic/src/main/java/dev/caskeleton/buildlogic/jpa/JpaTestLanesPlugin.java` | `208077fd` | 대상 코드 삭제. CI에 걸린 lane 없음 | +| readiness card `jpa-outbox-storage-v2`, `jpa-outbox-polling-delivery-v2`, `jpa-outbox-cdc-retention-v1`(storage-v2 전제)과 polling/CDC 동시 선택 금지 규칙 | `src/config/jpa/readiness-cards.yaml`, `src/build-tools/src/main/java/dev/caskeleton/buildtools/jpa/JpaReadinessRegistryValidator.java` | `208077fd` | 대상 stream·adapter 삭제 | +| web Advanced release gate (`WebAdvancedPromotionGate`, `WebAdvancedReleaseManifest`)와 기능 카탈로그 `WebAdvancedFeature`, 테스트 `WebAdvancedReleaseTest`·`WebAdvancedRollbackIT`의 gate 테스트 2개 | `W/advanced/release/`, `W/advanced/WebAdvancedFeature.java`, `src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/release/` | `208077fd` | main에 둔 승격 gate, 테스트에서만 호출. 카탈로그는 읽는 코드 없는 설정 키(`…json-merge-patch.enabled`, `…sse.enabled`, `…cbor.enabled` 등)를 문서에 약속 | +| OpenAPI 3.2 승격 리포트 (`OpenApi32CompatibilityReport`, `OpenApiToolchainMatrix`)와 테스트 5개 | `W/advanced/openapi/`, `src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/openapi/OpenApi32CompatibilityReportTest.java` | `208077fd` | main에 둔 승격 gate, 테스트에서만 호출. `OpenApiVersionLane` 테스트 1개는 `OpenApiVersionLaneTest`로 남김 | +| blocking bridge 예산 (`BlockingBridgeBudget`, `BlockingBridgeProfile`, `BlockingBridgeRejectedException`)과 테스트 | `W/advanced/blockingbridge/`, `src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/blockingbridge/` | `208077fd` | 예산을 거는 WebFlux bridge 어댑터가 이미 삭제됨(D4) | +| 호출자 0 타입: `SpringMvcRouteInventoryCollector`, `WebPartialResponseException`, `WebBudgetMeter`(+ `WebBudgetOutcome`·`WebBudgetExceededException`·`WebBudgetViolation`), `WebStatusContract`, `WebJsonDecodingException` | `W/admin/route/`, `W/advanced/stream/`, `W/budget/`, `W/http/`, `W/json/` | `208077fd` | main·테스트 어디서도 참조 없음 | +| 쓰지 않는 테스트 대역 `InMemoryIdempotencyStore` | `src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/idempotency/` | `208077fd` | 참조 0 | +| websocket Advanced 전체(resume, cluster, presence, CBOR·Protobuf codec, compression, 외부 client, GraphQL bridge, HTTP/2·3 profile, SockJS profile·`SockJsConfiguration`, `AdvancedPromotionGate`, `WebSocketAdvancedCapability`)와 테스트 16개, lane `websocketAdvancedTest`, `compileOnly` CBOR·protobuf 의존, `application-core` 의존 | `WS/advanced/`, `WST/advanced/`, `src/adapter/inbound/websocket/build.gradle` | `208077fd` | 어떤 Spring 설정도 import하지 않음(`AutoConfiguration.imports` 없음, bootstrap scan 밖). `SockJsConfiguration`은 켜면 조립되지 않는 platform bean 3개를 요구. `application-core` edge는 이 코드만 사용 | +| `app.websocket.platform.*` 설정(`WebSocketPlatformSettings`, `WebSocketPlatformSafetyConfiguration`, `WebSocketPlatformStartupValidator`, `WebSocketStackExclusivity`)과 env key 15개(`APP_WEBSOCKET_PLATFORM_*` 14개, `APP_WEBSOCKET_ADVANCED_SOCKJS_ENABLED`) | `WS/config/`, `docs/registries/env-keys.yaml`, `src/.env.example` | `208077fd` | 바인딩하는 코드 없음(`@EnableConfigurationProperties` 없음). safety config는 import하는 곳이 없고, 켜면 아무도 만들지 않는 catalog bean 6개를 요구해 기동 실패 | +| platform catalog·정책 패키지 `admin`, `authz`, `codec`, `handler`, `handshake`, `lifecycle`, `observability`, `ordering`, `security`, `session`, `protocol`(`WebSocketMessageId` 제외), `core`(`WebSocketConnectionId`와 idempotency가 쓰는 2개 제외)와 테스트 | `WS/{admin,authz,codec,handler,handshake,lifecycle,observability,ordering,security,session,protocol,core}/`, `WST/` 같은 패키지 | `208077fd` | 테스트에서만 사용. `PlatformWebSocketHandler`도 쓰지 않음. `HandshakeAdmissionPipeline`은 bearer/cookie를 헤더 존재만으로 통과시켰고(2026-09-24 모듈 리뷰 K#1), `WebSocketSessionRegistry`는 연결 수 상한 경쟁 조건이 있었음(K#7) | +| reactive runtime `webflux/`(`ReactiveFrameSink`, `WebSocketDataBufferLifecycle`, `WebSocketDataBufferPolicy`)와 `spring-webflux`·`reactor-core` 의존 | `WS/webflux/`, `WST/webflux/` | `208077fd` | 템플릿은 servlet 전용(D4). 호출자 없음. sink 버퍼가 무제한이라 budget이 동작하지 않았음(K#3) | +| `inbound/FragmentAssembler`, close-code catalog `error/`, `WebSocketConnectionBudget`의 `maxFrameBytes`·`maxFragments`·`maxInboundMessagesPerSecond`·`maxConnectionAge`·`idleTimeout` | `WS/{inbound,error}/`, `WS/budget/WebSocketConnectionBudget.java` | `208077fd` | servlet handler는 whole-message 모드라 frame·fragment를 볼 수 없어 frame/fragment 상한이 동작하지 않았음(K#2). 나머지 3개는 읽는 코드 없음. 수신 상한은 `maxMessageBytes`(UTF-8 바이트) 하나, idle timeout은 컨테이너 설정. close는 Spring `CloseStatus`(1001/1009/1013) 직접 사용 | +| testFixtures `WebSocketArchitectureRules`(WS-ARCH-1~6)와 `WebSocketArchitectureRulesTest`, ArchUnit test 의존 | `src/adapter/inbound/websocket/src/testFixtures/java/dev/caskeleton/adapter/inbound/websocket/testkit/arch/`, `WST/arch/` | `208077fd` | 규칙 대상 패키지(`handler`, `webflux`, `advanced`)가 삭제됨. 남는 WS-ARCH-4(persistence 금지)는 registry 의존 게이트가 이미 막음 | +| 문서 `docs/websocket/advanced-support-matrix.md`, `docs/websocket/repository-adaptation.md`, `docs/websocket/runbooks/resume-history-loss.md` | `docs/websocket/` | `208077fd` | 삭제한 코드와 존재하지 않는 `…advanced.*.enabled` 플래그를 설명 | +| messaging adapter `realtime/` (`MessagingDurableFanoutAdapter`, `RealtimeFanoutEnvelopeJson`) | `src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/realtime/` | `208077fd` | bean 없음. `DurableFanoutPort`는 websocket이 쓰므로 유지 | +| `app.jpa-platform.addons-enabled` 조건(`PersistenceJpaRuntimeConfig`, bootstrap `JpaPlatformRuntimeAutoConfiguration`)과 그 스위치 테스트 2개 | `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PersistenceJpaRuntimeConfig.java`, `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/jpa/JpaPlatformRuntimeAutoConfiguration.java` | `208077fd` | 어떤 property source·env 키도 설정하지 않음(테스트만 false로 설정). JPA 마스터 스위치 `ca-skeleton.persistence-jpa.enabled` 하나로 켜고 끈다 | +| `backend.jpa.experimental.*` 플래그 8개(`ExperimentalFeature`, `ExperimentalFeatureGate`, 진입점 3개의 `enabledBy(..)` 팩토리)와 `ExperimentalEntryConsentTest` | `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/` | `208077fd` | 설정에서 플래그를 읽는 코드 0건. gate는 호출자가 직접 만든 Map만 검사했고 "기동 실패" 문서 약속은 거짓. 진입점은 public 생성자로 직접 만든다 | +| `experimental/next/*`(`CompatibilityLane`, `ExperimentalPromotionGate`, `PromotionDecision`, `PromotionEvidence`, `HibernateCompatibilityPolicy`)와 테스트 `CompatibilityLaneDefinitionTest`·`ExperimentalPromotionGateTest`·`HibernateCompatibilityPolicyTest` | `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/next/` | `208077fd` | main에 둔 promotion/lane gate, 자기 테스트 외 호출자 0건. `HibernateProviderPolicy` 검증은 `HibernateProviderPolicyTest`로, 버전 canary는 `Jpa4/Hibernate8/PostgreSql19CompatibilityTest`로 남김(`jpa-next.yml`이 실행) | +| `TenantEntityManagerFactoryRegistry`, `RlsAdminBypassToken`, `TenantEntityListenerGuard` | `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/{database,rls,tenant}/` | `208077fd` | 테스트·호출자 0건 | +| `JpaTransactionObservation`(`jpa.transaction.*` meter)와 테스트 메서드 2개 | `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/observation/JpaTransactionObservation.java` | `208077fd` | 생성하는 곳 0건이라 문서의 transaction metric은 나온 적 없음. `docs/jpa/observability.md` 정정 | +| 단일 구현 인터페이스 `JpaBatchExecutor`, `BulkDmlExecutor`, `StatelessSessionRunner`, `PostgreSqlCopyLoader`, `EnversHistoryReader`, `CursorCodec`, `VendorFailureTranslator`, `SqlStateResolver`, `ConstraintCatalog` | `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/{hibernate/batch,hibernate/bulk,hibernate/stateless,postgresql/copy,envers,api/query,api/error,postgresql/error}/` | `208077fd` | 구현 1개, 인터페이스를 참조하는 테스트·외부 코드 0건. 테스트된 구현(`HibernateJpaBatchExecutor` 등)을 진입점으로 남김 | +| 구현 없는 인터페이스 `EntityManagerAccess`, `LockWaitObservation` | `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/springdata/`, `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/lock/` | `208077fd` | 구현·호출자 0건 | +| `JpaBatchProfileRegistry`, `SpecificationPolicy`, `QuerydslJpaSupport`, `PgRangeJdbcType`, `PostgreSqlRangeQuerySupport`, `FailedConcurrentIndexRecovery`, `NonTransactionalMigrationPolicy`, `SchemaVersionSnapshot` | `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/{hibernate/batch,springdata,querydsl,postgresql/range,migration}/` | `208077fd` | 테스트·호출자 0건. invalid index 확인은 `docs/jpa/runbooks.md`의 SQL로 대체 | +| `FlywayValidationGate`, `ConcurrentIndexMigrationInspector`, `MigrationResource`(main에서 testkit으로 이동, 삭제 아님) | `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/migration/` → `src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/` | `208077fd` | 테스트·testkit에서만 쓰는 gate. 기동 검증은 Flyway validate-on-migrate와 `ddl-auto=validate`가 한다 | +| `JpaCapability.TRANSACTION_RETRY`·`POSTGRESQL_NATIVE_WRITE`·`POSTGRESQL_WORK_CLAIM`과 `jpaplatform` actuator 보고 항목 | `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/capability/JpaCapability.java`, `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/jpa/JpaPlatformAutoConfiguration.java` | `208077fd` | 해당 코드(재시도 엔진, upsert·work-claim 실행기)가 이미 삭제됐는데 보고서는 Stable/Advanced로 광고함 | +| web Advanced functional routes (`FunctionalRouteRegistry`, `WebFunctionalHandlerAdapter` 외)와 테스트, web-advanced의 `spring-webflux` 의존 | `W/advanced/functional/`, `src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/functional/` (W3-2에서 `adapter:inbound:web-advanced`로 옮긴 뒤 삭제) | `208077fd` | D4: WebFlux `RouterFunction`을 만든다. servlet 전용 템플릿에서 서빙할 곳이 없음 | +| forwarded header 라이브러리 (`ForwardedHeaderSanitizer`, `TrustedProxyPolicy`, `NormalizedForwardedHeaders`, `UntrustedForwardedHeaderException`)와 외부 URI (`ExternalOrigin`, `ExternalPrefix`, `ExternalUriBuilder`, `ExternalUriPolicy`), 테스트 | `W/proxy/`, `W/http/External*.java` (W3-2에서 web-advanced로 옮긴 뒤 삭제) | `208077fd` | 한 기능에 한 세대: 운영은 `server.forward-headers-strategy`(`app-bootstrap/.../config/server.yml`) | +| Nginx proxy lane `webNginxProxyTest`와 CI job (`pr-adapters.yml` → `web-nginx-proxy-contract`, `release.yml`) | `src/adapter/inbound/web/src/nginxProxyTest/` | `208077fd` | 위 forwarded header 라이브러리만 인증하던 lane | +| CORS/CSRF 프로필 (`CorsProfile`, `CsrfProfile`, `WebCorsPolicyValidator`, `WebCredentialMode`, `WebCsrfPolicyResolver`)과 테스트 | `W/security/` 의 해당 5개 파일 (W3-2에서 web-advanced로 옮긴 뒤 삭제) | `208077fd` | 한 기능에 한 세대: 운영은 `CorsSettings` + `SecurityConfig`. 같은 패키지의 security-context bridge는 유지 | +| cache 정책 카탈로그 (`WebCachePolicyCatalog`, `WebCachePolicy`, `WebVaryPolicy`, `WebCacheHeaders`)와 테스트 | `W/cache/` (W3-2에서 web-advanced로 옮긴 뒤 삭제) | `208077fd` | 한 기능에 한 세대: 운영은 `CacheControlFilter` | +| JSON mapper factory (`WebObjectMapperFactory`, `WebJsonProfile`, `BoundedJsonFactory`)와 테스트 | `W/json/` (W3-2에서 web-advanced로 옮긴 뒤 삭제) | `208077fd` | 한 기능에 한 세대: 운영은 Boot `JsonMapper` + `spring.jackson.*`. 스트리밍 encoder는 Boot `JsonMapper` bean을 받도록 변경 | +| OpenAPI customizer (`WebOpenApiCustomizer`, `WebOpenApiProfile`, `CursorSchemaContributor`)와 `WebOpenApiSnapshotTest` | `W/openapi/` 의 해당 3개 파일 (W3-2에서 web-advanced로 옮긴 뒤 삭제) | `208077fd` | 한 기능에 한 세대: 운영은 springdoc + `OpenApiContractConfig`. `CursorPage` 스키마는 이미 삭제된 커서 페이지네이션을 설명 | +| realtime 포트 (`ConnectionRegistryPort`, `DurableFanoutPort` 외 7개 타입)와 Redis 연결 레지스트리 (`RedisConnectionRegistryAdapter`) | `src/application-core/src/main/java/dev/caskeleton/application/realtime/`, `src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/realtime/` | `208077fd` | 소비자 0 (websocket 정리 후 호출자 없음, bean 없음). `LiveEventReplayPort` 계열은 유지 | +| graphql `advanced/**` 전체 (15개 패키지, 130개, ~5,600줄) + 테스트 | `src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/` | `208077fd` | 모든 진입점이 `GraphQlAdvancedModuleGuard`를 거치는데 그 플래그(`GraphQlAdvancedFeatureFlags`)를 바인딩하는 코드가 없다. Spring GraphQL/graphql-java SPI를 구현한 타입이 없어 SSE·RSocket·federation·incremental·GET·chaining은 이름만 있는 모델. `GraphQlReplaySource`·`GraphQlPersistedOperationAdminPort`는 구현체 없는 인터페이스, persisted 레지스트리가 기대는 `OperationalRecordStorePort`도 구현체 0. composition/incremental/bootstrap은 gate·등급 코드 | +| `backend.graphql.unsupported.*` 6개 키 (`GraphQlPlatformSettings.Unsupported`, `withUnsupportedCapability`, 검증기 분기) | `src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPlatformSettings.java`, `GraphQlPlatformStartupValidator.java` | `208077fd` | 켜면 부팅 실패만 한다. 구현하지 않은 기능에는 설정 키를 두지 않는다(AGENTS 기준 3) | +| `backend.graphql.cursor.key-ids` (`GraphQlPlatformSettings.Cursor`, `withCursorKeyIds`) | `src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPlatformSettings.java` | `208077fd` | 읽는 곳이 등록되지 않은 actuator 보고서뿐. 커서 서명은 라이브러리(`HmacGraphQlCursorCodec`)를 서비스가 직접 조립한다 | +| `GraphQlPlatformActuatorEndpoint`, `GraphQlPlatformConfigurationReport` | `src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/` | `208077fd` | 빈으로 등록하는 곳이 없어 노출되지 않는 endpoint. 테스트만 호출 | +| `GraphQlClientPolicy`의 `persistedOperationOnly`·`maxResponseNodes`·`maxResponseBytes` | `src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/policy/GraphQlClientPolicy.java` | `208077fd` | 아무도 읽지 않는 필드. `persistedOperationOnly=true`는 허용 목록 우회(fail-open)였다 | +| `GraphQlRequestErrorMapper`, `GraphQlSubscriptionExceptionResolver`, `GraphQlNullabilityContract`, `GraphQlFailureBoundary` | `src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/error/` | `208077fd` | main 참조 0 | +| `GraphQlWireErrorMapper.mapRequestRejection` | `src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlWireErrorMapper.java` | `208077fd` | 호출처 0. 요청 단계는 `GraphQlPlatformRejectionMapper.map`을 직접 쓴다(Javadoc에 사실대로 적음) | +| parser 한도(`GraphQlParserLimitPolicy`, `GraphQlParserLimits`, `GraphQlParserOptionsFactory`, `GraphQlParserRejectedException`) | `src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/cost/` | `208077fd` | auto-configuration이 parser 기본값을 바꾸지 않는다. 테스트만 호출 | +| 응답 runtime budget(`GraphQlRuntimeBudgetTracker`, `GraphQlRuntimeBudget`, `GraphQlResponseByteLimiter`, `GraphQlResponseNodeCounter`, `GraphQlRuntimeBudgetExceededException`) | `src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/cost/` | `208077fd` | 유일한 소비자가 `advanced/incremental`. 요청 경로에 없음 | +| `GraphQlCancellation`, `GraphQlDeadlinePropagator`, `GraphQlResolverBudget`, `GraphQlOperationNameInterceptor`, `GraphQlOperationNamePolicy`, `GraphQlResolverCatalog`, `GraphQlResolverDescriptor`, `GraphQlExecutionProfileValidator` | `src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/execution/` | `208077fd` | 등록·호출하는 곳이 없는 interceptor·검증기·신호. 익명 operation 거부는 `GraphQlOperationSelectionHandler`가 이미 한다 | +| `GraphQlClientPolicyManifest`, `GraphQlOperationCatalog`, `GraphQlOperationPolicy`, `GraphQlPolicyViolation`, `GraphQlUnknownClientProfileException`, `GraphQlUnknownOperationException`, `ResolverExecutionType`, `api/GraphQlClientProfileName` | `src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/policy/`, `api/` | `208077fd` | 요청 경로가 참조하지 않는 카탈로그·manifest. 테스트만 호출 | +| schema gate·병렬 조립기(`GraphQlMappingInspectionGate`, `GraphQlOneOf*` 4개, `GraphQlSchemaAssembler`/`AssemblyResult`/`AssemblyException`, `GraphQlSchemaContract`, `GraphQlSchemaHash` 등 14개) | `src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/schema/` | `208077fd` | 스키마 조립·mapping inspection·`@oneOf` 검증은 Spring GraphQL/graphql-java가 한다. 이 gate들은 어디에도 등록되지 않았다 | +| 병렬 HTTP 전송 모델(`GraphQlHttpExecutor`, `GraphQlHttpResponseFactory`, `GraphQlHttpStatusMapper`, `GraphQlMediaTypes`, `GraphQlAcceptHeader`, `GraphQlHttpProfile` 등 9개) | `src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/http/` | `208077fd` | HTTP 처리는 Spring GraphQL handler가 한다. `GraphQlHttpExecutor`는 구현체 없는 인터페이스 | +| `GraphQlClientProfileResolver`, `GraphQlContextCleanup`, `GraphQlProfilerAccessPolicy` | `src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/security/`, `observation/` | `208077fd` | 등록·호출하는 곳 없음 | +| testFixtures testkit(계약 suite 5개, JPA/Mongo 통합 fixture, `GraphQlStorageIntegrationEvidence`, `GraphQlPartialResponseFixture`)와 `GraphQlCrossModuleContractSuiteTest` | `src/adapter/inbound/graphql/src/testFixtures/java/dev/caskeleton/adapter/inbound/graphql/testkit/` | `208077fd` | 삭제한 병렬 HTTP 모델 위에서 자기 자신만 검사하던 증거 코드. 다른 모듈이 testFixtures를 쓰지 않는다. `GraphQlRequestContexts`만 남김 | +| 요청 멱등성 v1 모델 (`IdempotencyExecutor`(v1), `IdempotencyStorePort`(v1), `IdempotencyScope`, `IdempotencyContext`, `IdempotencyRecord`, `IdempotencyStatus`, `IdempotencyScopeMissingException`, `Sleeper`)와 `IdempotencyScopeTest`, `IdempotencyV2ContractSingularityTest` | `src/application-core/src/main/java/dev/caskeleton/application/idempotency/` | `208077fd` | W2-6 한 세대: V2(owner-safe store, scope digest, 대기 없는 경합 처리)가 정본. V2 타입은 `v2` 패키지에서 상위 패키지로 옮기고 `V2` 접미사를 뗐다(`IdempotencyExecutorV2`→`IdempotencyExecutor`, `IdempotencyStorePortV2`→`IdempotencyStorePort`) | +| JPA v1 멱등성 store (`IdempotencyStoreAdapter`, `IdempotencyClaimRepository`, `IdempotencyResponseObjectStore`, `mapper/IdempotencyRecordEntityMapper`, `postgresql/PostgreSqlIdempotencyClaimRepository`, `h2/H2IdempotencyClaimRepository`)와 `IdempotencyStoreAdapterTest`, `PostgreSqlIdempotencyUniqueScopeIntegrationTest`, lane `postgresqlIdempotencyUniqueScopeIntegrationTest` | `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/` (`idempotency/`, `postgresql/`, `h2/`) | `208077fd` | W2-6: v1 `jdbc` provider 구현. `postgresql` provider는 `PostgreSqlOwnerSafeIdempotencyStore`. unique-scope lane은 v1 제약 `uq_idempotency_scope`만 확인했다(마이그레이션 파일은 그대로) | +| bootstrap 멱등성 조립 (`IdempotencyConfig`, `IdempotencyComposition`, `PostgreSqlIdempotencyProviderConfig`, `IdempotencyProviderSettings`, `config/idempotency.yml`)와 `IdempotencyProviderSettingsTest`, `IdempotencyShippedAutoConfigurationTest`, `IdempotencyProviderScanCollisionTest` | `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/` | `208077fd` | W2-6: executor를 여러 곳에서 만들고 lease/codec을 하드코딩했다. 이제 `IdempotencyProviderSelectionConfig`가 `IdempotencySettings` 하나로 한 번 만든다. 테스트는 `IdempotencyProviderCompositionTest`로 합침 | +| sample v1 멱등성 설정 (`SampleIdempotencySettings`) | `src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/idempotency/` | `208077fd` | W2-6: v1 `ca-skeleton.idempotency.ttl` 바인딩. `SampleIdempotencyConfig`가 `ca-skeleton.capabilities.idempotency`를 직접 읽는다 | +| websocket command ledger (`idempotency/CommandReconciliation`, `CommittedResultLedger`, `WebSocketCommandKey`, `WebSocketCommandOutcome`, `core/WebSocketActorReference`, `core/WebSocketEndpointName`, testFixtures `testkit/fault/WebSocketFaultInjector`, `WebSocketFaultPoint`)와 `InMemoryCommittedResultLedger`, `WebSocketCommandIdempotencyTest`, `CommandLossRecoveryTest` | `src/adapter/inbound/websocket/src/` | `208077fd` | W2-6: v1 executor 전용 ledger. `core/` 두 타입은 ledger 삭제 뒤 참조가 없다. 멱등성이 필요하면 use case 안에서 `IdempotencyExecutor`를 쓴다 | +| GraphQL mutation 멱등성 (`GraphQlMutationIdempotencyInterceptor`, `GraphQlMutationIdempotencyContext`, `GraphQlIdempotencyKey`, `GraphQlIdempotencyConflictException`, `GraphQlCanonicalInput`, `GraphQlMutationFingerprint`, `GraphQlExtensionsPolicy`의 `idempotencyKey` 허용, `GraphQlMutationContractValidator.requireIdempotency`)와 `GraphQlMutationIdempotencyContextTest` | `src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/` (`mutation/`, `http/`) | `208077fd` | W2-6: store에 연결된 적 없는 v1 executor 사용처. `idempotencyKey` extension은 이제 거부된다 | +| web v1 멱등성 fake (test `idempotency/InMemoryIdempotencyStore`, testFixtures `testkit/fault/FaultFixtureStore`) | `src/adapter/inbound/web/src/` | `208077fd` | W2-6: application-core testFixtures `testkit/InMemoryIdempotencyStore` 하나로 대체 | +| Import filters `MongoOptInAutoConfigurationImportFilter`, `GraphQlOffAutoConfigurationImportFilter`, `MessagingOffAutoConfigurationImportFilter` (+ `MessagingOffAutoConfigurationImportFilterParityTest`) and their `spring.factories` entries | `src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/`, `src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/`, `src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/autoconfigure/` | `208077fd` | W4-4: off machinery for a jar shipped switched off. A capability is now absent unless selected; an explicit `enabled=false` excludes Boot's Mongo/GraphQL auto-configuration from the module's own environment post-processor | +| bootstrap capability settings `config/messaging.yml`, `config/graphql.yml`, `config/httpclient.yml`, `config/fileserver.yml`, the Mongo block of `config/persistence.yml`, `spring.servlet.multipart` in `application.yml`, `app.messaging.broker` in `application-local.yml` | `src/app-bootstrap/src/main/resources/` | `208077fd` | W4-4: moved into the owning modules (`config/.yml`, loaded at lowest precedence by each module) | +| RabbitMQ broker settings (`BrokerSettings` `addresses`/`publisher-confirms`/`publisher-returns`/`mandatory`/`confirm-timeout`/`auto-ack`/`prefetch`/`quorum-queues`, `BrokerSettings.RABBITMQ`, the compiler and key-validator Rabbit branches) and the RabbitMQ YAML example | `src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/`, `docs/messaging/configuration-reference.md` | `208077fd` | W4-4 (criterion 3): the keys bound with no transport behind them; `type: rabbitmq` and Rabbit keys now fail startup naming the key | +| bootstrap tests for shipped-and-switched-off capabilities: `MongoShippedCompositionContractTest` (moved to the Mongo leaf as `MongoReactiveDriverAbsenceTest`), `MessagingMembershipQualificationTest`, systemTest `GraphQlShippedAndGatedTest`; the Mongo/GraphQL/messaging cases of `ShippedRuntimeFacadePresenceTest`, the HTTP client/Kafka cases of `OptionalAdapterBeanGatingTest` and `BootstrapCapabilityReachabilitySystemTest` | `src/app-bootstrap/src/test/`, `src/app-bootstrap/src/systemTest/` | `208077fd` | W4-4: absent from the default composition is the off state; each leaf proves present = on and `enabled=false` = off itself | +| `JpaOffAutoConfigurationImportFilter`, `DataSourceRequirement`과 `DataSourceRequirementTest` | `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/jpa/`, `src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/jpa/` | `208077fd` | W4-2: JPA를 싣지 않는 조립에서는 Boot의 관계형 자동 설정이 classpath에 없어 꺼진다. 끄는 장치 불필요 | +| `JpaPlatformAutoConfiguration`(플랫폼 조립 factory), `PersistenceJpaRootAutoConfiguration`, `JpaPlatformRuntimeAutoConfiguration`, `MigrationStartupConfig`와 `JpaPlatformAddonAssemblyTest`, `PersistenceJpaRootAutoConfigurationOrderingTest` | `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/jpa/`, `src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/jpa/` | `208077fd` | W4-2: persistence-jpa `startup.JpaStartupAutoConfiguration` 하나로 합침. 보고서 조립은 `JpaPlatformReport.read`/`platformCapabilities` | +| `DistributedLockConfig`와 `DistributedLockConfigTest` | `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/lock/`, `src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/lock/` | `208077fd` | W4-1: `distributedLockProvider` bean을 persistence-jpa `DistributedLockPersistenceConfig`로 옮김(테스트도 그쪽에 합침) | +| `DisabledMessagingSentinelAutoConfiguration` | `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/messaging/` | `208077fd` | W4-1: relay 스케줄러가 `OutboxMessagePublishPort` bean이 있을 때만 생기므로 대역 publisher가 필요 없다 | +| `OutboxRelayBrokerRequirementValidator`와 테스트 | `src/app-bootstrap/src/{main,test}/java/dev/caskeleton/bootstrap/autoconfigure/outbox/` | `208077fd` | W4-1: 발행 포트가 없으면 스케줄러 자체가 없어 PENDING 행을 DEAD로 소진할 경로가 없다 | +| `RuntimeSafetySettings.migrationOnStartup` | `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/settings/RuntimeSafetySettings.java` | `208077fd` | W4-2: 읽는 곳이 persistence-jpa뿐. 키 `ca-skeleton.runtime.migration-on-startup`은 그 모듈 기본 설정으로 이동 | +| systemTest H2 도달성 케이스 3개(lock/outbox/PostgreSQL 멱등성)와 `ShippedCompositionHarness.allOffWithH2`, `ShippedRuntimeFacadePresenceTest`의 JPA 케이스 | `src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/activation/`, `src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/activation/ShippedRuntimeFacadePresenceTest.java` | `208077fd` | W4-2: 기본 조립이 JPA를 싣지 않는다. 같은 증명은 persistence-jpa `PersistenceJpaCapabilityAssemblyTest` | +| 모듈별 설정 로더 `HttpClientDefaultsEnvironmentPostProcessor`, `FileserverDefaultsEnvironmentPostProcessor`, `NotificationDefaultsEnvironmentPostProcessor`, `MessagingDefaultsEnvironmentPostProcessor`와 각 `spring.factories` | `src/adapter/outbound/httpclient/`, `src/composition/fileserver-platform/`, `src/composition/notification-platform/`, `src/adapter/outbound/messaging-kafka/` | `208077fd` | W4 병합: 설정 파일을 `config/module-defaults/<모듈>.yml`로 옮기고 support의 `ModuleDefaultsEnvironmentPostProcessor` 하나가 읽는다. support에 닿지 않는 persistence-mongo·graphql만 자기 EPP가 `config/<이름>.yml`을 읽는다 | +| `DisabledOutboxMessagePublisher`(outbox 대역 publisher) | `src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/outbox/` | `208077fd` | W4 병합: 대역이 있으면 relay 스케줄러가 켜져 모든 발행이 실패하고 PENDING 행이 DEAD로 소진된다. broker가 비어 있고 canonical transport도 없으면 기동을 거부한다 | +| bootstrap `config/persistence.yml`, `config/outbox.yml`, `config/redis.yml`, `config/ratelimit.yml`와 그 import 줄, 기본 조립의 `cache-redis`·`redis-runtime`·`adapter:outbound:messaging` 의존성 | `src/app-bootstrap/` | `208077fd` | W4 병합: 설정은 persistence-jpa·cache-redis 모듈 기본 설정으로, 의존성은 `app-bootstrap/build.gradle`의 주석 한 줄 목록으로 | +| `AutoConfigurationReachabilityParityTest.offImportFiltersReferenceCurrentBootCandidates`와 stale-target 검사 | `src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/` | `208077fd` | W4 병합: 검사할 off import filter가 남아 있지 않다 | +| `MasterSwitch`, `MasterSwitchParser`, `MasterSwitchParseResult`(shared-contract `activation` 패키지 전체)와 `MasterSwitchParserTest` | `src/shared-contract/src/main/java/dev/caskeleton/shared/activation/`, `src/shared-contract/src/test/java/dev/caskeleton/shared/activation/` | `208077fd` | W4-5: 모든 capability를 한 jar에 싣고 스위치로 끄던 장치의 SSOT. 이제 capability는 `app-bootstrap/build.gradle`의 `runtimeOnly` 한 줄로 고르고, 있는 모듈은 자기 `enabled` 키(기본 `true`)로만 끈다 | +| bootstrap `activation` 패키지: `MasterSwitchEnvironmentPostProcessor`, `CapabilityDependencyValidator`, `CapabilityDependencyEnvironmentValidator`, `CapabilityDependencyStartupCheck`, `AdapterActivationAutoConfiguration`, `AdapterActivationEndpoint`(`/actuator/adapteractivation`), `AdapterActivationReport` | `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/activation/` | `208077fd` | W4-5: 스위치 값을 정규화하고, 켠 capability가 꺼진 의존을 가리키면 기동을 거부하고, 스위치 상태를 endpoint로 보고하던 코드. capability 사이 의존은 이제 build 줄로 표현한다(알림·파일 서버는 persistence-jpa 줄도 넣는다). 무엇이 조립됐는지는 Boot의 `conditions` endpoint로 본다(기본 노출 목록에는 없으니 `management.endpoints.web.exposure.include`에 추가). 같은 패키지의 `RuntimeEnvironmentProfileValidator`는 삭제가 아니라 `dev.caskeleton.bootstrap.runtime`으로 옮김 | +| `CaSkeletonApplication.AUTO_CONFIGURED_PACKAGES`(component scan 제외 정규식) | `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/CaSkeletonApplication.java` | `208077fd` | W4-5: scan은 이제 `dev.caskeleton.bootstrap`만 본다. web은 `WebAdapterAutoConfiguration`, support는 `OutboundSupportConfig`를 자기 `AutoConfiguration.imports`로 공개하므로 제외할 패키지가 없다 | +| `StartupOrder.MASTER_SWITCH_NORMALISATION`, `StartupOrder.CAPABILITY_DEPENDENCY` | `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/startup/StartupOrder.java`(지금은 `adapter:outbound:support`의 `support.startup.StartupOrder`) | `208077fd` | W4-5: 순서를 정해 줄 post-processor·validator가 삭제됨 | +| `RedisActivationValidator`, `RedisActivationAutoConfiguration`과 `RedisActivationValidatorTest` | `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/redis/RedisActivationValidator.java`, `src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/redis/RedisActivationValidatorTest.java`(W4 병합 중 cache-redis로 옮긴 뒤 삭제) | `208077fd` | W4-5: Redis를 기본으로 끈 채 싣던 시절의 활성화 가드. 이제 cache-redis 줄이 있으면 켜지고(`APP_REDIS_ENABLED` 기본 `true`), `false`면 `RedisCapabilityConfig`·`RedisSdkAutoConfiguration`이 bean을 하나도 만들지 않는다 | +| `DatabaseReadinessGroupPostProcessor` | `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/jpa/DatabaseReadinessGroupPostProcessor.java` | `208077fd` | W4-5: persistence-jpa `startup.JpaActivationEnvironmentPostProcessor`로 대체. 켜져 있으면 readiness에 `db`를 넣고, `APP_PERSISTENCE_JPA_ENABLED=false`면 Boot의 JDBC·Hibernate·Spring Data JPA·Flyway 자동 설정까지 빼서 완전히 끈다 | +| 끄는 장치 테스트: `AdapterActivationEndpointTest`, `AdapterActivationReportShapeTest`, `CapabilityDependencyValidatorTest`, `MasterSwitchRegistryContractTest`, `ShippedRuntimeFacadePresenceTest`, `DisabledAdapterSentinelTest`, `OptionalAdapterBeanGatingTest`, `AutoConfigurationReachabilityParityTest`, `RedisOptionalityContractTest`, persistence-jpa `OutboxMasterSwitchWiringContractTest` | `src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/{activation,contract}/`, `src/app-bootstrap/src/test/java/dev/caskeleton/adapter/outbound/`, `src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/` | `208077fd` | W4-5: 기본 jar에 실린 capability가 꺼져 있음을 증명하던 테스트. 이제 기본 조립에 없는 것이 꺼진 상태이고, 각 leaf가 "있으면 켜짐 / `enabled=false`면 꺼짐"을 스스로 증명한다 | +| systemTest `activation/AdapterActivationInventory`, `DependencyErrorStartupContractTest`, `FiveAdapterOffInventoryTest`, `MasterSwitchEnvironmentPostProcessorTest` | `src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/activation/` | `208077fd` | W4-5: 다섯 어댑터를 모두 싣고 끈 기동과 의존 오류 메시지를 확인하던 lane. 기본 조립 기동은 systemTest `composition/DefaultCompositionBootTest`(local/dev/prod, capability bean 0개)가, capability별 켜짐/꺼짐은 각 leaf의 activation 테스트가 본다 | +| bootstrap `GraphQlDeploymentModeRegistryParityTest` | `src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/activation/GraphQlDeploymentModeRegistryParityTest.java` | `208077fd` | W4-5: 규칙(deployment mode ↔ runtime profile)이 graphql `GraphQlPlatformStartupValidator`로 옮겨 가면서 테스트도 graphql leaf의 같은 이름 테스트로 옮김 | diff --git a/docs/fileserver/configuration.md b/docs/fileserver/configuration.md index 0f52e9d5..b7461e2b 100644 --- a/docs/fileserver/configuration.md +++ b/docs/fileserver/configuration.md @@ -1,9 +1,7 @@ # Fileserver configuration Every key below lives under `app.fileserver-platform` (environment form -`APP_FILESERVER_PLATFORM_*`). That namespace is the HTTP platform's alone: `app.fileserver.*` -belongs to the R2 tabular publication capability and `app.file-export.*` to the R1 CSV export, and -the three are deliberately separate so switching one on cannot switch on another. +`APP_FILESERVER_PLATFORM_*`). While `app.fileserver-platform.enabled` is false none of these keys is bound at all — the auto-configuration that binds them is not processed — so a malformed value in a block nobody diff --git a/docs/fileserver/http-contract.md b/docs/fileserver/http-contract.md index 44fed52c..05589e22 100644 --- a/docs/fileserver/http-contract.md +++ b/docs/fileserver/http-contract.md @@ -64,6 +64,7 @@ port rather than the public one. | `416` | unsatisfiable Range; carries the real length | | `422` | digest, signature, or scanner rejection | | `429` | transfer admission or rate limit | +| `460` | tus `Upload-Checksum` does not match that request's bytes; the chunk is discarded and the offset does not move | | `503` | storage or scanner unavailable | | `504` | downstream timeout | | `507` | out of storage capacity | diff --git a/docs/fileserver/support-matrix.md b/docs/fileserver/support-matrix.md index df7172c2..d50f0db0 100644 --- a/docs/fileserver/support-matrix.md +++ b/docs/fileserver/support-matrix.md @@ -20,7 +20,6 @@ that does not exist, so a level can never outlive the test that justified it. |---|---|---| | Local filesystem (ext4) content store | Stable | `fileserver-local-ext4-contract` | | Spring MVC transport (raw, multipart, batch, download) | Stable | `fileserver-http-contract` | -| Spring WebFlux transport | Experimental | `fileserver-http-contract` | | Path, filename, range, and problem-detail hardening | Stable | `fileserver-security-suite` | | Bounded-memory transfer | Stable | `fileserver-bounded-memory` | | Application and architecture invariants | Stable | `fileserver-unit-and-architecture` | @@ -37,21 +36,11 @@ that does not exist, so a level can never outlive the test that justified it. | Full release verification | Stable | `fileserver-full-verification` | | HTTP resumable uploads draft-12 | Experimental | `fileserver-http-contract` | -### Why WebFlux is Experimental, not Stable +### WebFlux transport removed -The reactive router, handlers and readers are now wired: `FileserverReactiveConfiguration` -contributes the scheduler, the handlers and a `RouterFunction` bean under -`@ConditionalOnWebApplication(type = REACTIVE)` plus the platform master switch. Previously nothing -built them at all, so "Stable" described the source tree rather than a running server. - -It stays `Experimental` because the shipped composition cannot select it. `adapter:inbound:web` -also puts `DispatcherServlet` on the classpath — deliberately, so adding `spring-webflux` does not -drag a second embedded server onto the runtime — and Boot's application-type deduction therefore -resolves SERVLET. A fork that removes the servlet stack and adds a reactive server gets working -routes without editing any Fileserver code; the shipped template does not exercise that path. - -Raising it to Stable requires a contract job that drives the routes over a running reactive server -rather than through direct construction. +The reactive router and handlers (`web.fileserver.reactive`) were removed on 2026-09-25 (D4: the +template is servlet on virtual threads). The shipped composition could never select them — the web +leaf puts `DispatcherServlet` on the classpath, so Boot resolves SERVLET. ## Explicitly not claimed diff --git a/docs/httpclient/configuration-reference.md b/docs/httpclient/configuration-reference.md index 7a7d9369..39316bc5 100644 --- a/docs/httpclient/configuration-reference.md +++ b/docs/httpclient/configuration-reference.md @@ -12,18 +12,19 @@ production deployment must decide has either no default or an unusable one, and | Property | Type | Default | Environment | |---|---|---|---| -| `app.httpclient.enabled` | boolean | `false` | `APP_HTTPCLIENT_ENABLED` | +| `app.httpclient.enabled` | boolean | `true` | `APP_HTTPCLIENT_ENABLED` | -Off is the shipped state and it is a structural one. `HttpClientPlatformAutoConfiguration` lives in -a package the composition root's component scan excludes, so while the switch is absent or false the -class is never processed and neither is anything it imports: no property is bound, and no transport +The module is on when present: a service adds `runtimeOnly project(':adapter:outbound:httpclient')` +to `app-bootstrap/build.gradle`, and the module's own `config/module-defaults/httpclient.yml` (loaded at the lowest +precedence by the support leaf's `ModuleDefaultsEnvironmentPostProcessor`) supplies `enabled: true`. Absent from the +build is the ordinary off state. `false` is the explicit off: `HttpClientPlatformAutoConfiguration` +is then never processed and neither is anything it imports — no property is bound, and no transport provider, connection pool, TLS context, credential, thread, gateway or actuator endpoint exists. A -malformed HTTP client setting cannot fail the startup of a deployment that never wanted outbound -HTTP. +malformed HTTP client setting cannot fail the startup of a deployment that switched it off. -Anything that is not exactly `true` — `yes`, `1`, blank — leaves the platform off. Turning it on -with no client declared is a startup failure carrying `HTTPCLIENT_ACTIVE_WITHOUT_CLIENTS`: a -platform with nothing to call still holds transport providers and gateways no caller can reach. +Anything that is not exactly `true` — `yes`, `1`, blank — turns the platform off. On with no client +declared is a startup failure carrying `HTTPCLIENT_ACTIVE_WITHOUT_CLIENTS`: a platform with nothing +to call still holds transport providers and gateways no caller can reach. ## Declaring clients from the environment diff --git a/docs/httpclient/migration-guide.md b/docs/httpclient/migration-guide.md deleted file mode 100644 index d4693ba5..00000000 --- a/docs/httpclient/migration-guide.md +++ /dev/null @@ -1,64 +0,0 @@ -# Migrating from `RestTemplate` - -`RestTemplate` is permitted only inside `…httpclient.migration`; `RestTemplateBoundaryTest` enforces -that. New retry, Dynamic Target, and HTTP/3 capabilities are deliberately unreachable from the -migration path — a caller that wants them moves to a Named Client Profile. - -## 1. Audit before changing anything - -```java -RestTemplateInventory inventory = new RestTemplateInventoryScanner().scan(existingTemplate); -``` - -The inventory reports the request factory, message converters, interceptors, error handler, and URI -template handler, plus findings: - -| Code | Severity | Meaning | -|---|---|---| -| `SIMPLE_REQUEST_FACTORY` | blocking | no connection pool; unsupported in production | -| `NO_MESSAGE_CONVERTERS` | blocking | the template cannot encode or decode a body | -| `NO_INTERCEPTORS` | warning | confirm where correlation and timeouts are applied | -| `TIMEOUTS_NOT_INTROSPECTABLE` | informational | declare timeouts explicitly on the target profile | - -## 2. Bridge without changing behaviour - -```java -RestClient client = new RestTemplateToRestClientAdapter().adaptChecked(existingTemplate); -``` - -`adaptChecked` refuses to migrate a template with a blocking finding. The bridge carries the -existing converters, interceptors, error handler, and URI handler across, so this step changes the -API and nothing else. - -## 3. Move to a Named Client Profile - -Turn the platform on with `APP_HTTPCLIENT_ENABLED=true` — it ships off, and while it is off none of -the settings below are bound — then declare the upstream as `app.httpclient.clients[N]` with its -`name` and an explicit base URL, transport, timeouts, pool, body limits, authentication, retry -policy, redirect policy, and TLS profile. Startup validation will tell you exactly which of those is -missing. See `docs/httpclient/configuration-reference.md` for the environment form. - -## 4. Move to a typed client - -```java -@HttpClientProfile("payment") -@HttpExchange("/payments") -public interface PaymentClient { - - @PostExchange - @HttpOperationPolicy( - name = "create-payment", - idempotency = OperationIdempotency.IDEMPOTENCY_KEY_REQUIRED, - retryPolicy = "payment-write") - PaymentResponse create( - @RequestHeader("Idempotency-Key") String idempotencyKey, @RequestBody PaymentRequest request); -} -``` - -The interface fails startup validation unless it declares a profile, gives every method a stable -operation name and an explicit idempotency, supplies a key parameter when the operation requires -one, keeps a single execution model, and does not enable retry on a non-idempotent write. - -## 5. Retire the template - -Once no production package references `RestTemplate`, `RestTemplateBoundaryTest` keeps it that way. diff --git a/docs/httpclient/release-checklist.md b/docs/httpclient/release-checklist.md index f2bec408..10d0967a 100644 --- a/docs/httpclient/release-checklist.md +++ b/docs/httpclient/release-checklist.md @@ -38,7 +38,7 @@ python3 ../scripts/verify-httpclient-docs.py - [ ] Logical calls and attempts are separate metrics with no forbidden label. - [ ] DNS, pool, TLS, reset, partial response, and HTTP/2 GOAWAY are reproducible. - [ ] Thread, heap, direct memory, pool, and retry budget bounds hold. -- [ ] The support matrix, configuration reference, security guide, runbook, and migration guide match the code. +- [ ] The support matrix, configuration reference, security guide and runbook match the code. ## Experimental diff --git a/docs/httpclient/repository-adaptation.md b/docs/httpclient/repository-adaptation.md index 39b74f9d..8a65a2ed 100644 --- a/docs/httpclient/repository-adaptation.md +++ b/docs/httpclient/repository-adaptation.md @@ -52,8 +52,6 @@ Root package: `io.backend.skeleton.httpclient` → `dev.caskeleton.adapter.outbo | `httpclient-webclient` | `…httpclient.webclient` | `…outbound.httpclient.webclient` | | `httpclient-service-client` | `…httpclient.service` | `…outbound.httpclient.service` | | `httpclient-dynamic-target` | `…httpclient.dynamic` | `…outbound.httpclient.dynamic` | -| `httpclient-resttemplate-migration` | `…httpclient.migration` | `…outbound.httpclient.migration` | -| `httpclient-spring7-service-groups` | `…httpclient.spring7` | `…outbound.httpclient.spring7` | | `httpclient-jetty-http3-experimental` | `…httpclient.http3` | `…outbound.httpclient.http3` | | `httpclient-spring-boot-starter` | `…httpclient.autoconfigure` | `dev.caskeleton.adapter.outbound.httpclient.autoconfigure` | | `httpclient-testkit` | `…httpclient.testkit` | `…outbound.httpclient.testkit` (`testkit` source set) | @@ -63,7 +61,7 @@ Root package: `io.backend.skeleton.httpclient` → `dev.caskeleton.adapter.outbo | Design assumption | Repository reality | Adaptation | |---|---|---| | Gradle Kotlin DSL, `build-logic` convention plugin | Groovy DSL, root `build.gradle` conventions, `LockMode.STRICT` dependency locking | Dependencies declared in `src/adapter/outbound/httpclient/build.gradle`; `gradle.lockfile` regenerated. | -| Spring Framework 6.2 baseline with 7.0 compatibility | Spring Boot 4.0.8 / Spring Framework 7.0 is the repository baseline | Common code targets the Spring 6.2 **API surface** (no 6.2-only or 7.0-only classes in common packages). The Spring 7 HTTP Service Group integration stays isolated in `…httpclient.spring7`, exactly as the design requires. | +| Spring Framework 6.2 baseline with 7.0 compatibility | Spring Boot 4.0.8 / Spring Framework 7.0 is the repository baseline | Common code targets the Spring 6.2 **API surface** (no 6.2-only or 7.0-only classes in common packages). The Spring 7 HTTP Service Group integration and the `RestTemplate` migration package were removed. | | `settings.gradle.kts` module registration | Fail-closed registry | No registry change; leaf identity, gradle path, allowed dependencies unchanged. | | Design §6.2 grades Apache HttpClient 5 as HTTP/2-capable | Spring's blocking factory drives Apache's **classic** client, which is HTTP/1.1 only; HTTP/2 lives in Apache's async client | `ApacheBlockingTransportProvider` declares HTTP/1.1 and rejects an HTTP/2 profile at startup. Blocking HTTP/2 is served by the JDK transport, measured by `NegotiatedProtocolContractTest`. | | Design §28.1 names WireMock for stateful fixtures | WireMock's Jetty modules bind a different Jetty 12 ABI than the Boot-managed one this module already needs for HTTP/3, and fail at server start | `StatefulUpstream` provides path-keyed stateful responses on the existing fixture server; the WireMock dependency was removed rather than worked around with a shaded jar | diff --git a/docs/httpclient/support-matrix.md b/docs/httpclient/support-matrix.md index 50877528..3505ea36 100644 --- a/docs/httpclient/support-matrix.md +++ b/docs/httpclient/support-matrix.md @@ -10,7 +10,6 @@ proves it; anything the suite cannot prove is **Experimental** and says so. | `RestClient` | Stable | Blocking execution | Bounded concurrency and an effective deadline are mandatory | | `WebClient` | Stable | Reactive, streaming, SSE | No blocking work on the event loop | | HTTP Service Client (`@HttpExchange`) | Default | Declarative typed client | Operation metadata is mandatory | -| `RestTemplate` | Migration only | Moving existing calls | No new profile or feature | | Generic Exchange (H2) | Restricted | Dynamic method, path, body | Base URL and policy are immutable | | Dynamic Target (H3) | Restricted | User-supplied URL | Separate SSRF policy; inherits no credential | | Native engine | Internal | Engine-specific configuration | Never an application-facing API | @@ -70,8 +69,8 @@ gives route-scoped pooling and Dynamic Target pinning, JDK gives HTTP/2. This repository's Spring Boot 4.0 baseline pins Spring Framework 7, so a real 6.2 runtime cannot be resolved here. `spring62CompatibilityTest` therefore verifies the **API surface**: the common -packages must not reference any Spring 7-only type, and `org.springframework.web.service.registry` -is confined to `…httpclient.spring7`. Executing the suite against an actual 6.2 distribution +packages must not reference any Spring 7-only type, and no class uses +`org.springframework.web.service.registry`. Executing the suite against an actual 6.2 distribution requires a host project on that line. This limitation is stated rather than hidden behind a passing check. diff --git a/docs/jpa/experimental-promotion-checklist.md b/docs/jpa/experimental-promotion-checklist.md index 80d3814f..c6906018 100644 --- a/docs/jpa/experimental-promotion-checklist.md +++ b/docs/jpa/experimental-promotion-checklist.md @@ -1,6 +1,8 @@ # Experimental Promotion Checklist -`ExperimentalPromotionGate` evaluates this checklist. Every technical item, then the ADR. +A reviewer evaluates this checklist. Every technical item, then the ADR. (The +`ExperimentalPromotionGate` class that encoded it in main code was removed on 2026-09-25; nothing +called it.) ## Technical evidence diff --git a/docs/jpa/experimental-support-matrix.md b/docs/jpa/experimental-support-matrix.md index f7293fa6..99e4e862 100644 --- a/docs/jpa/experimental-support-matrix.md +++ b/docs/jpa/experimental-support-matrix.md @@ -1,22 +1,22 @@ # Experimental Support Matrix -Everything here is off unless its `backend.jpa.experimental.*` flag is explicitly true, and none of -it is part of the Stable composition. +Experimental code is library code in `dev.caskeleton.adapter.outbound.persistence.experimental`. +Nothing composes it and no setting turns it on: a deployment that wants one of these creates the +entry point in its own adapter code, and that call is the opt-in. None of it is part of the Stable +composition, and `JpaModuleBoundaryTest` keeps Stable packages from depending on it. -| Feature | Flag | State | -|---|---|---| -| Shared-schema multi-tenancy (column) | `backend.jpa.experimental.multitenancy-column` | Experimental | -| PostgreSQL RLS multi-tenancy | `backend.jpa.experimental.multitenancy-rls` | Experimental | -| Schema-per-tenant | `backend.jpa.experimental.multitenancy-schema` | Experimental | -| Database-per-tenant | `backend.jpa.experimental.multitenancy-database` | Experimental | -| Consistency-aware read replica | `backend.jpa.experimental.read-replica` | Experimental | -| Jakarta Persistence 4.0 lane | `backend.jpa.experimental.jakarta-persistence-4` | Experimental | -| Hibernate ORM 8 lane | `backend.jpa.experimental.hibernate-8` | Experimental | -| PostgreSQL 19 lane | `backend.jpa.experimental.postgresql-19` | Experimental | +| Feature | Entry point | Evidence (PostgreSQL lane unless noted) | State | +|---|---|---|---| +| Shared-schema multi-tenancy (column) | `tenant.TenantContext`, `tenant.TenantAwareRepositoryGuard` | `TenantColumnIsolationTest` | Experimental | +| PostgreSQL RLS multi-tenancy | `rls.RlsTenantSessionBinder`, `rls.RlsPolicyVerifier` | `RlsIsolationFailureTest` | Experimental | +| Schema-per-tenant | `schema.SchemaMultiTenantConnectionProvider`, `schema.SchemaTenantMigrationOrchestrator` | `SchemaTenantMigrationContractTest` | Experimental | +| Database-per-tenant pool budget | `database.TenantDataSourceRegistry`, `database.TenantPoolBudget` | `TenantPoolCapacityContractTest` | Experimental | +| Consistency-aware read replica | `replica.ConsistencyAwareDataSourceRouter` (you implement `ReplicaLagMonitor`) | `ReadAfterWriteRoutingContractTest` | Experimental | +| Jakarta Persistence 4.0, Hibernate ORM 8, PostgreSQL 19 | none — probes in `.github/workflows/jpa-next.yml` record `NOT_EXECUTABLE` | `Jpa4CompatibilityTest`, `Hibernate8CompatibilityTest`, `PostgreSql19CompatibilityTest` (unit-lane version canaries) | Not executable | -Presence on the classpath is not consent. `ExperimentalFeatureGate` fails startup when a module is -present and its flag is not set, because an experimental module can arrive transitively and a -tenant-isolation feature that switched itself on would be the worst possible default. +The `backend.jpa.experimental.*` flags and `ExperimentalFeatureGate` that used to front these were +removed on 2026-09-25: no code read the flags from configuration, so setting one did nothing, and +the gate only checked a map the caller built itself. ## Known constraints diff --git a/docs/jpa/migration-guide.md b/docs/jpa/migration-guide.md index f5cef523..550e4b03 100644 --- a/docs/jpa/migration-guide.md +++ b/docs/jpa/migration-guide.md @@ -18,8 +18,10 @@ whichever instance started first. ## Validation fails closed and never repairs -`FlywayValidationGate` throws `SchemaMismatchException` on a checksum mismatch, a missing migration, -or a schema Hibernate disagrees with. It never calls `repair`. +At startup Flyway's own validation (and Hibernate `ddl-auto=validate`) refuses a checksum mismatch, +a missing migration, or a schema Hibernate disagrees with. Nothing in the application calls +`repair`. In tests, the testkit's `FlywayValidationGate` turns a failed `ValidateResult` into +`SchemaMismatchException`; the migration contract tests use it. Repair rewrites the schema history table to match whatever scripts are on disk. That resolves the symptom by deleting the evidence: a checksum mismatch means the deployed script differs from the @@ -40,15 +42,15 @@ one by default. The migration therefore needs a companion configuration: executeInTransaction=false ``` -`ConcurrentIndexMigrationInspector` fails validation without it, and additionally requires the -migration to contain nothing else. A failed concurrent build leaves an invalid index behind; +The testkit's `ConcurrentIndexMigrationInspector` checks a script for this in a migration test +(nothing checks it at startup), and additionally requires the migration to contain nothing else. A failed concurrent build leaves an invalid index behind; recovering is a single `DROP INDEX` when the migration did nothing else, and a manual reconstruction of partial state when it did. An invalid index is not merely useless — the planner ignores it while every write still maintains -it. `FailedConcurrentIndexRecovery` reports them with the statement to run, and deliberately does -not drop them: an invalid index can also mean a build is still running, and the two are -indistinguishable from the catalog alone. +it. [runbooks.md](runbooks.md) has the query that finds them. Nothing drops them automatically: an +invalid index can also mean a build is still running, and the two are indistinguishable from the +catalog alone. ## Upgrade scenarios diff --git a/docs/jpa/observability.md b/docs/jpa/observability.md index 3e242447..660bfb67 100644 --- a/docs/jpa/observability.md +++ b/docs/jpa/observability.md @@ -2,55 +2,52 @@ Design §37. What is measured, and what must never appear in a measurement. +## What is emitted by default + +Nothing JPA-specific. No composition constructs a `MeterRegistry`-backed observation for the +platform, and `SpringTransactionPort` records no transaction metric. The `jpa.transaction.*` meters +this page used to list (`duration`, `rollback`, `timeout`, `completion.unknown`) were produced by +`JpaTransactionObservation`, which nothing constructed; it was removed on 2026-09-25 +(`docs/capability-status.md`). Transaction outcomes are visible through the shared persistence error +codes and the application's own metrics, not through a JPA meter. + +## Query metrics — only when the caller asks + +`jpa.query.duration` and `jpa.query.rows` are recorded by `MicrometerQueryObservation`, and only +when a service passes it to a library executor that accepts a `QueryObservation` +(`JpaStreamExecutor`, `HibernateBulkDmlExecutor`). The default is `NoopQueryObservation`. Rows are +measured as well as duration because a query that issues one statement and hydrates twenty thousand +rows is fast per statement and catastrophic per request — a duration metric alone reports it as +merely slow. + ## Bounded tags, always -Every JPA metric carries exactly five tags: persistence unit, operation, query, outcome, failure -category. All five are registered identifiers, validated by `LowCardinality` at construction rather -than at the registry — so an unbounded value fails where it was introduced instead of surviving -until a dashboard stops loading. +Every meter `MicrometerQueryObservation` records carries exactly five tags: persistence unit, +operation, query, outcome, failure category (`JpaMetricTags`). All five are registered identifiers, +validated by `LowCardinality` at construction rather than at the registry — so an unbounded value +fails where it was introduced instead of surviving until a dashboard stops loading. Never a tag: entity id, tenant id, SQL parameter, exception message, JDBC URL. Each is unbounded, so each creates a time series per row or per failure; several are also the data the platform keeps out of logs, which a metrics backend would store just as durably and export just as widely. -## Transaction metrics - -| Meter | Why it exists | -|---|---| -| `jpa.transaction.duration` | the baseline | -| `jpa.transaction.rollback` | rollback rate by failure category | -| `jpa.transaction.timeout` | timeouts, distinct from other rollbacks | -| `jpa.transaction.completion.unknown` | its own counter, deliberately | - -Completion-unknown gets a separate counter rather than being folded into failures. It is the one -outcome that means a human has to look: every other failure is a transaction that definitely did not -happen, while this one is a transaction that may have. - -## Query metrics - -`jpa.query.duration` and `jpa.query.rows`. Rows are measured as well as duration because a query -that issues one statement and hydrates twenty thousand rows is fast per statement and catastrophic -per request — a duration metric alone reports it as merely slow. - -## Retry metrics - -Attempts are metrics, not warnings. Optimistic conflicts and serialization failures are the expected -cost of concurrency; logging each at WARN pages someone for a system working as designed, after -which the retry log gets filtered out and takes the genuinely interesting entries with it. - -`jpa.retry.attempt`, `jpa.retry.attempts` (distribution per operation), `jpa.retry.exhausted`. - ## Query names in SQL -`NamedStatementInspector` prefixes each statement with its registered query name as a SQL comment, -which travels into `pg_stat_activity`, `auto_explain`, and the slow-query log. Without it, "which -endpoint issues this query" is answered by grepping the codebase for fragments of SQL. +`JpaRepositoryFragmentSupport` sets the registered query name as the `org.hibernate.comment` hint; +Hibernate writes it into the SQL only when `hibernate.use_sql_comments=true`. The alternative is +`NamedStatementInspector`, which prefixes a statement with the query name bound by +`JpaStreamExecutor`, `JpaKeysetQuerySupport` or `JpaRepositoryFragmentSupport.observing(..)`. +Neither is on by default: a deployment enables the inspector with +`spring.jpa.properties.hibernate.session_factory.statement_inspector=dev.caskeleton.adapter.outbound.persistence.hibernate.NamedStatementInspector`. +The comment then travels into `pg_stat_activity`, `auto_explain`, and the slow-query log. Without it, +"which endpoint issues this query" is answered by grepping the codebase for fragments of SQL. ## Diagnostics -`SqlDiagnosticRedactor` removes string literals, numbers, and anything email-shaped before SQL -reaches a log. Redaction is blunt on purpose: preserving "harmless" values would require knowing -which columns hold personal data. +`SqlDiagnosticRedactor.redact(sql)` removes string literals, numbers, and anything email-shaped. It is +a utility for code that is about to log SQL; nothing in the platform logs SQL through it. Redaction +is blunt on purpose: preserving "harmless" values would require knowing which columns hold personal +data. ## The actuator endpoint diff --git a/docs/jpa/postgresql-extensions.md b/docs/jpa/postgresql-extensions.md index 7b2a2640..2124e0e8 100644 --- a/docs/jpa/postgresql-extensions.md +++ b/docs/jpa/postgresql-extensions.md @@ -17,28 +17,6 @@ single field with a magic zero is how "no wait" becomes "wait forever". the first leaves the transaction alive and the caller in control; the second has already been rolled back by the server. -## Work claims - -`FOR UPDATE SKIP LOCKED` is reachable only through a registered `WorkQueueName`, never as a -repository flag. It deliberately returns an incomplete view of the table: correct for handing -disjoint work to competing workers, silently wrong for anything that needs to see every matching -row. A registered claim statement must skip locked rows and impose a deterministic `ORDER BY`. - -## Upserts - -`INSERT ... ON CONFLICT ... RETURNING` under a registered `NativeWriteName` with a fixed conflict -target and update column set. The conflict target cannot be a bound parameter, so accepting one from -a caller would mean building SQL from input. - -An upsert is the correct answer to a create race precisely because the database decides. -Read-then-write cannot be made correct: another transaction can commit between the read and the -write. `(xmax = 0) AS inserted` in the `RETURNING` list is what lets the platform report -insert-versus-update without a second query. - -The executor flushes before and clears after: a native write is invisible to the Persistence -Context, so a pending managed change would otherwise overwrite it, and a managed entity loaded -beforehand would keep serving pre-upsert values. - ## JSONB `JsonDocument` carries a schema name and version alongside the payload. A JSONB column is schemaless diff --git a/docs/jpa/query-fetch-guide.md b/docs/jpa/query-fetch-guide.md index ac73f945..75b023ad 100644 --- a/docs/jpa/query-fetch-guide.md +++ b/docs/jpa/query-fetch-guide.md @@ -4,9 +4,10 @@ Design §23-§28. How queries are chosen, bounded, and proven. ## Named queries -Every registered query carries a `QueryName`. It becomes the metric tag, the trace attribute, and -the SQL comment that appears in `pg_stat_activity` and the slow-query log — which is the only thing -that connects a statement on the server back to the use case that issued it. The format rejects raw +Every registered query carries a `QueryName`. It is the tag `MicrometerQueryObservation` records +under and the SQL comment that appears in `pg_stat_activity` and the slow-query log — which is the +only thing that connects a statement on the server back to the use case that issued it. Neither is on +by default; [observability.md](observability.md) says how a deployment turns each on. The format rejects raw SQL for a reason: a metric tag built from a query string is unbounded by construction, and one built from a parameterised value leaks row data into telemetry. diff --git a/docs/jpa/repository-adaptation.md b/docs/jpa/repository-adaptation.md index 5a8896da..230a6483 100644 --- a/docs/jpa/repository-adaptation.md +++ b/docs/jpa/repository-adaptation.md @@ -29,7 +29,7 @@ This is the same adaptation already applied to the HTTP client platform | Plan module | Repository home | Reason | |---|---|---| -| `jpa-spring-boot-starter` | `:app-bootstrap` (`dev.caskeleton.bootstrap.autoconfigure.jpa`) | This repository's composition root owns wiring, startup validation, and actuator surface; an adapter leaf must not auto-configure itself. `AGENTS.md` assigns composition to `app-bootstrap`. | +| `jpa-spring-boot-starter` | `:adapter:outbound:persistence-jpa` (`…persistence.autoconfigure`, `…persistence.startup`) | Relational persistence is a capability module selected by one build line (`AGENTS.md` capability rules): the leaf registers its own auto-configuration, startup validation, actuator view and shipped settings, and the default composition does not carry it. Use-case assembly over its ports (the outbox relay) stays in `app-bootstrap`. | | `jpa-testkit`, `jpa-testkit-postgresql`, `jpa-testkit-migration`, `jpa-testkit-queryplan` | `:adapter:outbound:persistence-jpa` `src/testkit/java/**/testkit` | The plan forbids production modules depending on the testkit. A source set whose dependencies are declared only on test configurations gives the same guarantee without a new Gradle project, and more than one lane consumes it. | The package boundary is enforced by `JpaModuleBoundaryTest`. It holds a closed catalog of the @@ -57,17 +57,17 @@ Root package: `io.backend.skeleton.jpa` → `dev.caskeleton.adapter.outbound.per | `jpa-spring-data` | `…jpa.springdata` | `…persistence.springdata` | | `jpa-querydsl` | `…jpa.querydsl` | `…persistence.querydsl` | | `jpa-hibernate` | `…jpa.hibernate` (+ `.batch`, `.bulk`, `.stateless`) | `…persistence.hibernate` (+ same subpackages) | -| `jpa-postgresql` | `…jpa.postgresql` (+ `.error`, `.lock`, `.constraint`, `.json`, `.array`, `.range`, `.write`) | `…persistence.postgresql` (+ same subpackages) | +| `jpa-postgresql` | `…jpa.postgresql` (+ `.error`, `.lock`, `.constraint`, `.json`, `.array`, `.range`, `.write`) | `…persistence.postgresql` (+ same subpackages except `.write`, removed 2026-09-25) | | `jpa-postgresql-copy` | `…jpa.postgresql.copy` | `…persistence.postgresql.copy` | | `jpa-migration-flyway` | `…jpa.migration` | `…persistence.migration` | -| `jpa-auditing` | `…jpa.auditing` | `…persistence.auditing` | +| `jpa-auditing` | `…jpa.auditing` | none — removed; `…persistence.audit.AuditableEntity` is the one audit mechanism | | `jpa-envers` | `…jpa.envers` | `…persistence.envers` | | `jpa-cache-hibernate` | `…jpa.cache` | `…persistence.cache` | | `jpa-observability` | `…jpa.observation` | `…persistence.observation` | | `jpa-security` | `…jpa.security` | `…persistence.security` | -| `jpa-spring-boot-starter` | `…jpa.autoconfigure` | `dev.caskeleton.bootstrap.autoconfigure.jpa` | +| `jpa-spring-boot-starter` | `…jpa.autoconfigure` | `…persistence.autoconfigure`, `…persistence.startup` | | `jpa-testkit*` | `…jpa.testkit` (+ `.id`, `.mapping`, `.lifecycle`, `.query`, `.fetch`, `.postgresql`, `.migration`, `.queryplan`, `.failure`, `.pool`, `.release`) | `…persistence.testkit` (+ same subpackages), `testkit` source set | -| `jpa-experimental/*` | `…jpa.experimental` (+ `.tenant`, `.rls`, `.schema`, `.database`, `.replica`, `.next`) | `…persistence.experimental` (+ same subpackages) | +| `jpa-experimental/*` | `…jpa.experimental` (+ `.tenant`, `.rls`, `.schema`, `.database`, `.replica`, `.next`) | `…persistence.experimental` (+ same subpackages except `.next`, removed 2026-09-25) | The existing `…persistence.transaction` and `…persistence.postgresql` packages already hold this leaf's `TransactionPort` implementation and PostgreSQL vendor composition. The platform types are @@ -121,7 +121,7 @@ boundary the module map exists to hold. |---|---|---|---| | `TransactionCompletionEvidence` | `jpa-transaction` | `…persistence.api.transaction` | `TransactionCompletionUnknownException` (design §17.3 types the field) | | `ConstraintCode` | `jpa-postgresql` | `…persistence.api.error` | `ConstraintViolationDetails` (design §22.4) | -| `SqlStateResolver`, `SqlExceptionSqlStateResolver` | `jpa-transaction` | `…persistence.api.error` | both the transaction module's commit classifier and the PostgreSQL translator | +| `SqlExceptionSqlStateResolver` | `jpa-transaction` | `…persistence.api.error` | the PostgreSQL translators | The ArchUnit rule pack (`JpaArchitectureRules`, `EntityMappingCondition`, `EntityExposureCondition`) is placed in the `testkit` source set rather than in `…persistence.security` production code. ArchUnit @@ -136,10 +136,9 @@ showed it. Both are recorded here because the design text still reads the old wa - **§17.2 commit ambiguity is not only SQLSTATE class `08`.** `pg_terminate_backend` on a backend with a commit in flight reports `57P01` (`admin_shutdown`), not a connection-class state — and the - commit record may already be in the WAL when it arrives. `CommitFailureClassifier` now treats - `57P01`/`57P02`/`57P03` as completion-unknown alongside `40003`, class `08`, and transport breaks. - `CommitAmbiguityContractTest` asserts the SQLSTATE directly so the rule cannot silently narrow - again. + commit record may already be in the WAL when it arrives. The classifier that encoded this + (`CommitFailureClassifier`) was removed with the second transaction engine on 2026-09-25; + `PostgreSqlConcurrencyFailureContractTest` still pins the injection points. - **Schema-per-tenant status must be read back, not inferred from the run.** `MigrateResult`'s target version is empty for a tenant that was already current, so recording it reported migrated tenants as unmigrated during a partial rollout. `SchemaTenantMigrationOrchestrator` now reads the @@ -159,6 +158,7 @@ showed it. Both are recorded here because the design text still reads the old wa `ddl-auto` never mutates a deployed schema. - `CREATE INDEX CONCURRENTLY` requires an explicit non-transactional migration marker. - Metric labels and ordinary logs never carry SQL parameters, entity IDs, tenant IDs, or PII. -- Experimental features (multi-tenancy, RLS, schema/database tenancy, read replica, JPA 4, - Hibernate 8, PostgreSQL 19) stay behind `backend.jpa.experimental.*` flags and never enter the - Stable composition. +- Experimental features (multi-tenancy, RLS, schema/database tenancy, read replica) are library code + a deployment constructs itself and never enter the Stable composition. JPA 4, Hibernate 8 and + PostgreSQL 19 are `NOT_EXECUTABLE` probes, not features. The `backend.jpa.experimental.*` flags + were removed on 2026-09-25: nothing read them. diff --git a/docs/jpa/runbooks.md b/docs/jpa/runbooks.md index 1e585db6..d4598b11 100644 --- a/docs/jpa/runbooks.md +++ b/docs/jpa/runbooks.md @@ -4,8 +4,8 @@ Operator procedures for the failures this platform is designed to surface rather ## A transaction reported completion unknown -**Signal:** `jpa.transaction.completion.unknown` incremented; a `CompletionUnknownRecord` in the -reconciliation channel. +**Signal:** a write use case failed with a commit-phase error (connection lost, `57P01`, class +`08`) from `TransactionPort`. **What it means:** the commit may or may not have happened. It is not a rollback. @@ -14,31 +14,26 @@ reason. **Procedure:** -1. Take the `transactionKey` from the record. +1. Take the idempotency key or operation id of the failed request. 2. Check the idempotency record for that key. 3. Check the business row the use case would have written. 4. Check the outbox for a corresponding event. -5. If all three agree the write happened, mark the record `COMMITTED` and stop. +5. If all three agree the write happened, stop — the request succeeded. 6. If all three agree it did not, the use case may be re-run. -7. If they disagree or are inconclusive, leave it `STILL_UNKNOWN` and escalate. An inconclusive - answer is a legitimate outcome; guessing is not. - -A record with no `transactionKey` cannot be resolved automatically — use the operation name and -timestamp. +7. If they disagree or are inconclusive, escalate. An inconclusive answer is a legitimate outcome; + guessing is not. ## Deadlock or serialization rate rising -**Signal:** `jpa.retry.attempt` rising; `jpa.retry.exhausted` non-zero. +**Signal:** `DB_DEADLOCK` / serialization failures rising in the persistence error codes. -Retries are expected. Exhaustion is not. +`SpringTransactionPort` does not retry, so each one reaches the caller. -1. Group `jpa.retry.attempt` by operation. A single operation dominating means a hot row or an +1. Group the failures by operation. A single operation dominating means a hot row or an inconsistent lock order. 2. For deadlocks, check whether two operations take the same rows in opposite orders — that is a code fix, not a tuning one. 3. For serialization failures under `SERIALIZABLE`, confirm the isolation is actually required. -4. Only then consider raising `maxAttempts`. A larger budget on a hot row converts a fast failure - into a slow one. ## Pool exhaustion @@ -64,12 +59,20 @@ The deployment is running against a schema it was not built for. It failed close ## An invalid index exists -**Signal:** `FailedConcurrentIndexRecovery.invalidIndexes()` is non-empty. +**Signal:** this query returns rows. + +```sql +select n.nspname || '.' || i.relname as invalid_index +from pg_index x +join pg_class i on i.oid = x.indexrelid +join pg_namespace n on n.oid = i.relnamespace +where not x.indisvalid; +``` A concurrent build failed. The index is ignored by the planner and maintained by every write. 1. Confirm no build is currently running. An in-progress build looks identical in the catalog. -2. Run the reported `DROP INDEX CONCURRENTLY` outside a migration. +2. Run `DROP INDEX CONCURRENTLY IF EXISTS ;` outside a migration. 3. Re-apply the index migration. The platform does not drop these automatically: on a rolling deploy every instance would race to diff --git a/docs/jpa/security.md b/docs/jpa/security.md index a466e37e..2d0813f4 100644 --- a/docs/jpa/security.md +++ b/docs/jpa/security.md @@ -59,8 +59,6 @@ Refusing the runtime role `CREATE` closes the same route from the other side. | sort field | part of ORDER BY | `SafeSortRegistry` allowlist | | JSON path | part of the statement | registered `JsonPathName` | | schema name | an identifier | registered `SchemaTenantRegistry` | -| upsert conflict target | an identifier list | registered `UpsertConflictTarget` | | COPY table | an identifier | registered `RegisteredCopyStatement` | -| queue claim SQL | a whole statement | registered `WorkQueueDefinition` | Values are always bound. Identifiers are always registered. diff --git a/docs/jpa/support-matrix.md b/docs/jpa/support-matrix.md index a22dd748..4f5d2dea 100644 --- a/docs/jpa/support-matrix.md +++ b/docs/jpa/support-matrix.md @@ -31,7 +31,7 @@ it. | PostgreSQL 16 | Stable | full contract suite, release lane (own matrix job) | | PostgreSQL 17 | Stable | full contract suite, release lane (own matrix job) | | PostgreSQL 18 | Stable | full contract suite, release lane (own matrix job) | -| PostgreSQL 19 | Experimental | [`jpa-next-postgresql19.yml`](../../.github/workflows/jpa-next-postgresql19.yml) — `NOT_EXECUTABLE`: no `postgres:19-alpine` is published, so no container of that major has been started; promotion requires an ADR | +| PostgreSQL 19 | Experimental | [`jpa-next.yml`](../../.github/workflows/jpa-next.yml) — `NOT_EXECUTABLE`: no `postgres:19-alpine` is published, so no container of that major has been started; promotion requires an ADR | | H2 | Local convenience | **never** evidence of PostgreSQL behaviour | Each major gets its **own release job**, because for a while it did not. The release lane passed @@ -78,17 +78,18 @@ the difference visible instead of asserting a constant against itself. See ## Capability support levels +The levels are the ones `JpaPlatformAutoConfiguration.capabilities()` reports through the +`jpaplatform` actuator endpoint. Advanced and Experimental rows are library code a service calls +itself (`src/adapter/outbound/persistence-jpa/README.md` "라이브러리 API"). + | Capability | Level | |---|---| -| Full-transaction retry | Stable | -| Commit completion evidence | Stable | | Keyset pagination | Stable | -| JDBC batch | Stable | | Flyway schema gate | Stable | | Runtime role verification | Stable | -| Observability | Stable | -| PostgreSQL native write (`ON CONFLICT`/`RETURNING`) | Advanced | -| PostgreSQL work claim (`SKIP LOCKED`) | Advanced | +| Commit completion evidence | Advanced | +| JDBC batch | Advanced | +| Observability (query metrics, redaction) | Advanced | | PostgreSQL JSONB | Advanced | | PostgreSQL array and range | Advanced | | Bulk DML | Advanced | @@ -113,24 +114,17 @@ Each row is a way the platform could pass its tests and still be wrong in produc | `runtime-role-no-ddl` | gate | the application's own credential being able to alter or drop schema objects | | `collection-fetch-pagination` | gate | a paged collection fetch silently reading the whole table and paginating in memory | -### The two audit mechanisms +### The audit mechanism -`audit/AuditableEntity` is the canonical one: `created_*`/`updated_*`, a 256-character actor, -stamped explicitly by the repository adapter. It is what the sample entities extend and what the -migrations were written for. +`audit/AuditableEntity` is the only one: `created_*`/`updated_*`, a 256-character actor, stamped +explicitly by the repository adapter. It is what the sample entities extend and what the migrations +were written for. A second, Spring Data listener-based mechanism (`auditing/AuditMetadata`) was never +composed and has been removed; `JpaAuditMechanismRule.entitiesUseExactlyOneAuditMechanism` keeps it +from coming back on an entity. -`auditing/AuditMetadata` is a second, complete mechanism with different column names -(`modified_*`), a different actor length (64) and a different capture lifecycle (Spring Data -listeners). Nothing embeds it and nothing composes `JpaAuditingConfiguration`, which is why it is -listed as a candidate rather than as a capability: promoting it means choosing between reshaping it -to the canonical columns and writing a forward migration for the new ones, and that choice has not -been made. Until it is, an entity picks one mechanism or none — enforced on the production graph by -`JpaAuditMechanismRule.entitiesUseExactlyOneAuditMechanism`. - -Neither mechanism reaches a bulk or native update. Both stamp on an ordinary save — one in the -adapter, one on a managed entity's lifecycle — so a statement that goes straight to the database -leaves the audit columns showing the previous save. A bulk update of an audited entity must -therefore set the audit column in the statement, which +The mechanism does not reach a bulk or native update. It stamps on an ordinary save in the adapter, +so a statement that goes straight to the database leaves the audit columns showing the previous save. +A bulk update of an audited entity must therefore set the audit column in the statement, which `JpaAuditMechanismRule.bulkUpdatesOfAuditedEntitiesStampAudit` checks over the production graph. ## Explicitly unsupported diff --git a/docs/jpa/transaction-guide.md b/docs/jpa/transaction-guide.md index ac5e8df8..2c1802ab 100644 --- a/docs/jpa/transaction-guide.md +++ b/docs/jpa/transaction-guide.md @@ -4,63 +4,52 @@ Design §15-§20. What owns a transaction, what may be retried, and what must ne ## The application service owns the boundary -Repository adapters do not open transactions. The use case does, through `TransactionPort` or -`JpaTransactionExecutor`, because the unit of work is a business decision and only the use case -knows where it starts and ends. +Repository adapters do not open transactions. The use case does, through `TransactionPort`, +because the unit of work is a business decision and only the use case knows where it starts and +ends. `SpringTransactionPort` is the only implementation: one pre-built `TransactionTemplate` per +mode over Spring's `PlatformTransactionManager`, every mode pinned to `READ_COMMITTED`. + +| Call | Propagation | When | +|---|---|---| +| `inWrite` | `REQUIRED`, read-write | command default | +| `inRootWrite` | `REQUIRED`, read-write, rejects an ambient transaction before running | orchestration that must prove a physical commit | +| `inRead` | `REQUIRED`, read-only | query default | +| `inNew` | `REQUIRES_NEW`, read-write | outbox / audit / compensation that must commit on its own | Open Session In View is off in every runtime profile. It is on by default in Spring Boot, which is why `JpaDangerousConfigurationGuard` fails startup rather than trusting configuration review. -## Profiles - -A `TransactionProfile` fixes propagation, isolation, timeout, read-only, and the retry budget. A -write profile must carry a positive finite timeout — the type refuses to represent one without — -because an unbounded write transaction holds a connection, its locks, and its row versions for as -long as one stuck statement takes. - -`REQUIRES_NEW` is opt-in. It acquires a second physical connection while pinning the first, so a -profile using it must be paired with the pool-pressure evidence in design §38: +`REQUIRES_NEW` acquires a second physical connection while pinning the first, so the pool must +satisfy: ```text maximumPoolSize >= (concurrent_threads x (1 + max_requires_new_depth)) + 1 ``` -## Retry is per use case, never per statement +## Nothing is retried by the port -`FullTransactionRetryCoordinator` re-enters the executor, which produces a new transaction and a new -Persistence Context for every attempt. That granularity is the whole point: an optimistic conflict -means the state the attempt computed against is no longer the committed state, so re-issuing the -same statement would compute the same wrong answer. The domain rules have to run again against -reloaded data. +`SpringTransactionPort` runs the action once. A failure rolls back and propagates, translated to +the shared persistence error codes where the SQLSTATE is known. A caller that decides to retry must +re-run the whole use case in a new transaction — never re-issue one statement — because an +optimistic conflict or a serialization failure means the state the attempt computed against is no +longer the committed state. -Retryable: serialization failure (`40001`), deadlock (`40P01`), optimistic conflict. -Not retryable: constraint violations, schema mismatch, query timeout, and anything unclassified. - -Two additional refusals, independent of budget: - -- An attempt that declared an irreversible external effect through `IrreversibleSideEffectContext`. - Rollback reverses database work only; an email or a card charge has already changed the world. -- Anything completion-unknown. +A second engine with named policies, deadline budgets, transaction-local timeouts and automatic +full-transaction retry (`SpringJpaTransactionExecutor`, `FullTransactionRetryCoordinator`, +`PolicyTransactionPort`) existed next to this one and was removed on 2026-09-25. Its last commit is +recorded in `docs/capability-status.md`. ## Completion unknown -`TransactionCompletionUnknownException` is never retried, and the type system enforces it twice: -`JpaFailureContext` refuses to represent a retryable completion-unknown failure, and the exception -rebuilds its context through the safe factory whatever it is handed. - -`EvidenceAwareJpaTransactionManager` marks the phase `COMMITTING` immediately before delegating to -the provider commit and never after. If the network, the JVM, or the server dies inside that call, -the last thing written is "we asked, we do not know" — which is exactly the state that must not be -mistaken for a rollback. +A connection can break while a commit is in flight; the server may have committed and only the +acknowledgement was lost. `TransactionCompletionUnknownException` is never retried, and the type +system enforces it: `JpaFailureContext` refuses to represent a retryable completion-unknown failure. +The port itself retries nothing, so such a commit surfaces to the caller as a failure exactly once +(`PostgreSqlTransactionIntegrationTest#connectionLossDuringCommitSurfacesAsAFailureAndIsNeverRetried`). Recovery is reconciliation, not retry: ```text -record the transaction key -> check the idempotency record - -> check the business row - -> check the outbox - -> still undetermined? reconciliation queue +check the idempotency record -> check the business row -> check the outbox + -> still undetermined? escalate ``` - -`CompletionUnknownRecorder` writes that record through a channel outside the unknown transaction. -Writing it through the same connection would make the audit trail share the failure it documents. diff --git a/docs/messaging/configuration-reference.md b/docs/messaging/configuration-reference.md index ea220b4a..d4dc00dd 100644 --- a/docs/messaging/configuration-reference.md +++ b/docs/messaging/configuration-reference.md @@ -28,7 +28,7 @@ producing-service identity다. `APP_OUTBOX_CANONICAL_TRANSPORT_ENABLED` / `ca-skeleton.outbox.canonical-transport-enabled`은 기존 `outbox_event` writer/claim/status authority를 유지한 채 canonical row의 **transport만** platform -publish path로 보내는 compatibility gate다. 기본값은 `false`이며 `POLLING_V2`를 활성화하지 않는다. +publish path로 보내는 compatibility gate다. 기본값은 `false`이며 두 번째 relay를 만들지 않는다. `true`일 때는 `OutboxAppendPort`가 `ValidatedIntegrationEvent`의 exact envelope bytes와 canonical metadata를 기존 outbox row에 저장하고, claim된 canonical row는 `IntegrationEventPublishPort`로 간다. @@ -135,9 +135,10 @@ app: ## Broker profile -브로커는 `app.messaging.brokers` 아래에 한 번만 기술한다. `type`이 어느 계열의 설정이 적용되는지 -결정하며, 다른 계열의 키(Kafka 항목의 `prefetch` 같은)는 무시되지 않고 부팅 실패로 거절된다 — -무시하면 그 줄을 쓴 사람은 무언가가 적용됐다고 믿게 된다. +브로커는 `app.messaging.brokers` 아래에 한 번만 기술한다. `type`은 `kafka`만 받는다 — transport가 +있는 계열이 Kafka 하나뿐이다. RabbitMQ 키(`addresses`, `prefetch`, `quorum-queues` 등)와 +`type: rabbitmq`는 2026-09-25에 설정 모델에서 삭제됐다. 연결할 transport 없이 바인딩만 되던 키라, +지금은 무시되지 않고 키 이름을 담아 부팅 실패로 거절된다. ### Kafka @@ -160,30 +161,9 @@ app: authentication-enabled: false # production이면 필수 ``` -### RabbitMQ - -```yaml -app: - messaging: - brokers: - rabbit-primary: - type: rabbitmq - stable: true - production: false - addresses: [rabbit-1:5671] - publisher-confirms: true # stable에서 필수 - publisher-returns: true # stable에서 필수 - mandatory: true # stable에서 필수 - confirm-timeout: 5s - auto-ack: false # 항상 금지 - prefetch: 16 - quorum-queues: true # durable work queue 필수 - tls-enabled: false - authentication-enabled: false -``` - -`production: true`인 브로커는 `tls-enabled`와 `authentication-enabled`가 모두 참이어야 하고, -그렇지 않으면 `KafkaProfileValidator` / `RabbitProfileValidator`가 부팅을 거절한다. 위 예시가 +`production: true`인 Kafka 브로커는 `tls-enabled`와 `authentication-enabled`가 모두 참이어야 하고, +그렇지 않으면 `KafkaProfileValidator`가 부팅을 거절한다. `app.messaging.broker`로 고를 수 있는 값은 +`kafka`뿐이다. 위 예시가 `production: false`인 것은 이 페이지가 그대로 실행되는 fixture이기 때문이며, 실 배포는 셋 다 참이다. ## 보안 @@ -211,20 +191,13 @@ app: 연결 시점에 해석하므로, 설정 덤프나 힙 덤프에서 나오는 것은 이름뿐이다. producer와 consumer는 서로 다른 `credential-id`를 써야 하며, 같으면 부팅에 실패한다. -## Experimental / Optional - -기본값은 전부 `false`다. - -```yaml -app: - messaging: - experimental: - kafka-share: false - pulsar: false - nats: false - bridge: - spring-cloud-stream: false -``` +Kafka producer는 이 항목을 실제 클라이언트 설정(`security.protocol`, `sasl.mechanism`, +`sasl.jaas.config`, `ssl.enabled.protocols=TLSv1.3,TLSv1.2`, hostname 검증)으로 옮긴다. 평문으로 +조용히 넘어가지 않도록 다음 경우 부팅에 실패한다: 브로커가 `tls-enabled`나 +`authentication-enabled`를 켰는데 `app.messaging.security.`가 없을 때, security 항목은 +있는데 `CredentialProvider` bean이 없을 때, 같은 브로커에 맞는 항목이 둘 이상일 때. +한계: truststore/keystore 설정 키가 없어 TLS는 JVM 기본 truststore를 쓰고, `MUTUAL_TLS`는 클라이언트 +인증서를 제출할 수 없다(미지원). ## Backpressure diff --git a/docs/messaging/cutover.md b/docs/messaging/cutover.md index a65e341f..f697177e 100644 --- a/docs/messaging/cutover.md +++ b/docs/messaging/cutover.md @@ -27,8 +27,9 @@ `PublishResult` → `OutboxPublishOutcome`. registry에 leaf를 추가하는 변경이라 별도 커밋. - golden contract 테스트: event/message ID, type, schema revision, partition/order/correlation/ causation/tenant/trace, payload digest, wire version이 bytes 단위로 보존되는지. -- 단일 publication authority: 기존 `OutboxPublicationAuthority` fence를 재사용해 writer/relay가 - 동시에 ACTIVE가 되지 않도록. **dual write/publish는 금지** — 한 business fact가 두 durable store와 +- 단일 publication authority: writer/relay가 동시에 ACTIVE가 되지 않도록 하는 fence. 이 용도로 쓰려던 + outbox V2의 `OutboxPublicationAuthority`는 한 번도 조립되지 않은 채 2026-09-25에 삭제됐으므로 + (`docs/capability-status.md` "제거된 코드") cutover가 자기 fence를 새로 가져야 한다. **dual write/publish는 금지** — 한 business fact가 두 durable store와 두 relay로 나가는 상태가 cutover에서 가장 위험하다. - 첫 cutover 범위는 **transport만** 교체(저장소는 기존 유지). storage migration은 shadow read → authority switch → old backlog drain 순서로 별도 release. diff --git a/docs/messaging/experimental-policy.md b/docs/messaging/experimental-policy.md index e2052c4b..de8f5b1c 100644 --- a/docs/messaging/experimental-policy.md +++ b/docs/messaging/experimental-policy.md @@ -17,24 +17,22 @@ stopsAcceptingNewWorkDuringShutdown **Experimental**은 아직 그 증명이 끝나지 않은 어댑터다. +현재 Experimental 어댑터는 없다. Kafka Share Group·Pulsar·NATS JetStream(Experimental), RabbitMQ, +Spring Cloud Stream bridge(Optional)는 SDK 없는 seam이거나 선택할 수 없는 상태여서 2026-09-25에 +삭제했다(`docs/capability-status.md` 제거 표). 이 문서는 새 어댑터를 들일 때 지킬 규칙이다. + ## 규칙 ### 1. 기본 비활성 -```yaml -messaging.experimental.kafka-share: false -messaging.experimental.pulsar: false -messaging.experimental.nats: false -``` - +새 Experimental 어댑터는 자기 활성화 플래그를 가지고 기본값은 `false`다. 활성화하지 않으면 validator가 `MessagingCapabilityUnavailableException`을 던진다. Contract Suite가 아직 증명 중인 어댑터가 누군가의 기본 설정 때문에 load-bearing이 되어서는 안 된다. ### 2. Stable 모듈이 Experimental 모듈에 의존하지 않는다 -Gradle 의존 그래프로 강제된다. `messaging-spring-boot-starter`의 `allowed_dependencies`에 -`messaging-kafka-share-experimental`, `messaging-pulsar-experimental`, -`messaging-nats-experimental`, `messaging-spring-cloud-stream-bridge`가 **없다**. +Gradle 의존 그래프로 강제된다. Experimental leaf는 `messaging-spring-boot-starter`의 +`allowed_dependencies`에 넣지 않는다. `verifyCleanArchitectureDependencies`가 위반을 빌드 실패로 만든다. @@ -45,45 +43,8 @@ Experimental 어댑터는 브로커의 차이를 `MessagingCapabilities`로 표 ### 4. 없는 기능을 광고하지 않는다 -| 어댑터 | 광고하지 않는 것 | 이유 | -|---|---|---| -| Kafka Share Group | orderedStream, keyedOrdering, replay, brokerTransaction | 경쟁 소비자 + 개별 ack는 partition 순서를 유지할 수 없다 | -| Pulsar | brokerTransaction | Pulsar에 있지만 플랫폼 Contract Suite로 증명되지 않았다 | -| Pulsar (Shared) | keyedOrdering | round-robin 분배 | -| NATS JetStream | nativeDeadLetter | delivery limit 초과 시 terminate할 뿐 라우팅하지 않는다 | -| NATS JetStream | keyedOrdering | subject 기반 모델에 per-key 순서가 없다 | - -`false`인 capability를 요구하는 profile은 startup에서 실패한다. -조용히 약화되지 않는다. - -### 5. 명시적 거부 - -| 조합 | 결과 | -|---|---| -| Kafka Share Group + ordering != NONE | 거부 | -| Kafka Share Group + pause/resume | `MessagingCapabilityUnavailableException` | -| Pulsar Shared + ordering=KEY | 거부 (Key_Shared 필요) | -| Pulsar + ordering=DESTINATION | 거부 | -| NATS Core + AT_LEAST_ONCE | 거부 (JetStream 필요) | -| NATS ordered consumer + 경쟁 워커 > 1 | 거부 | -| NATS + ordering=KEY | 거부 | - -## Spring Cloud Stream bridge - -Experimental이 아니라 **Optional**이다. 위험이 다르다. - -Stream은 자체 binder 설정을 소유하므로, binding이 destination profile이 모르는 -serializer·error handling·acknowledgement mode를 조용히 획득할 수 있다. - -따라서 브리지는 **플랫폼 보장에 의존하지 않는 destination에만** 허용한다. - -```text -ordering scope 선언 → 거부 -retry policy 선언 → 거부 -dead letter 선언 → 거부 -``` - -이 셋 중 하나라도 필요하면 native adapter를 쓴다. 거기서만 실제로 강제되기 때문이다. +Contract Suite로 증명하지 않은 capability는 `MessagingCapabilities`에서 `false`로 둔다. +`false`인 capability를 요구하는 profile은 startup에서 실패한다. 조용히 약화되지 않는다. ## 승격 조건 diff --git a/docs/messaging/operations.md b/docs/messaging/operations.md index 5cea33b4..5bccc75d 100644 --- a/docs/messaging/operations.md +++ b/docs/messaging/operations.md @@ -3,8 +3,7 @@ ## 배포 전 체크 ```bash -./gradlew verifyCleanArchitectureDependencies --console=plain -./gradlew verifyRuntimeModuleMembership --console=plain +./gradlew architectureCheck --console=plain ./gradlew checkstyleMain --console=plain ``` diff --git a/docs/messaging/outbox-inbox.md b/docs/messaging/outbox-inbox.md index 4dac3ee0..d4b68ab7 100644 --- a/docs/messaging/outbox-inbox.md +++ b/docs/messaging/outbox-inbox.md @@ -107,13 +107,11 @@ message_id만으로 중복 제거하면 같은 event를 소비하는 두 번째 broker의 최대 redelivery window보다 **길어야** 한다. row를 먼저 지우면 늦게 도착한 redelivery가 두 번 처리된다. -## Debezium CDC 대안 +## CDC 대안 -polling relay 대신 WAL을 읽는다. polling interval과 lease 경합이 사라지지만 -인프라와 그 자체의 실패 모드가 추가된다. - -wire contract는 동일하다. `DebeziumOutboxEventRouter`가 polling relay와 같은 reserved header를 -방출하므로 consumer는 어느 쪽이 발행했는지 구분할 수 없고, 전환은 배포 결정일 뿐 계약 변경이 아니다. +relay는 polling 하나뿐이다. Debezium Event Router 매핑(`DebeziumOutboxEventRouter` 등)은 조립하는 +곳이 없어 2026-09-25에 삭제했다(`docs/capability-status.md` 제거 표). `messaging_outbox`의 +`routing_key` 컬럼은 남아 있으므로 CDC를 다시 들일 때 그 컬럼을 message key로 쓴다. ## Claim Check diff --git a/docs/messaging/support-matrix.md b/docs/messaging/support-matrix.md index 563bd88a..84c9647f 100644 --- a/docs/messaging/support-matrix.md +++ b/docs/messaging/support-matrix.md @@ -4,10 +4,12 @@ 여기 없는 조합은 지원되지 않는다. > **등급은 증거를 따른다.** `CompatibilityMatrix.Entry.hasLiveBrokerCertification()`은 선언된 -> boolean이 아니라 `CertifiedEvidence`가 가진 레인 증거에서 파생된다. RabbitMQ가 Stable에서 내려온 -> 이유가 이것이다 — 어댑터는 공유 contract 7개를 통과하고 `RabbitBrokerIT`가 실 컨테이너에서 정상 -> 경로를 돌리지만, 이 저장소의 Stable 기준인 **장애 시나리오 증거**가 하나도 없다. 레인이 생겨 -> 증거를 내면 등급은 코드 수정 없이 따라 올라간다. +> boolean이 아니라 `CertifiedEvidence`가 가진 레인 증거에서 파생된다. 레인이 생겨 증거를 내면 등급은 +> 코드 수정 없이 따라 올라간다. + +> **삭제된 어댑터.** RabbitMQ(선택할 수 없던 validator·설정 모음), Pulsar·NATS JetStream·Kafka Share +> Group(Experimental, SDK 없는 seam), Spring Cloud Stream bridge, Debezium outbox 매핑은 2026-09-25에 +> 삭제했다. 복구 경로는 `docs/capability-status.md`의 제거 표에 있다. > **인증 근거.** 이 표의 버전은 이 저장소의 컨테이너 레인이 실제로 실행한 이미지다. 이전 판은 > Kafka 4.2/4.3을 선언했지만 fixture는 `apache/kafka:4.1.0`, lockfile client는 4.1.1이었다 — 표와 @@ -29,10 +31,7 @@ | 브로커 | 등급 | 인증 기준 | Stable 기능 | 제한 | |---|---|---|---|---| -| Kafka | Stable | 4.1.x | producer idempotence, consumer group, batch, pause/resume, replay, transaction capability | Share Group은 Experimental | -| RabbitMQ | Experimental | 4.3.x | exchange/routing, publisher confirm, mandatory return, manual ACK, quorum queue, retry queue, DLQ | **현재 starter에서 선택 불가** — production `RabbitChannelPublisher`/transport bridge가 없어 `app.messaging.broker=rabbit`은 startup에서 거부된다. 장애 시나리오 증거도 아직 없음 | -| Pulsar | Experimental | 4.0 LTS + 4.2 | typed publish/consume, Shared, Key_Shared, schema | transaction 미승격, 기본 비활성 | -| NATS JetStream | Experimental | 2.14.x | stream, durable consumer, explicit ACK, dedupe, replay | native DLQ 없음(플랫폼이 대행), 기본 비활성 | +| Kafka | Stable | 4.1.x | producer idempotence, consumer group, batch, pause/resume, replay, transaction capability | Share Group 미지원 | | Artemis/JMS | Extension | 범위 밖 | adapter SPI만 | 별도 ADR + Contract Suite 통과 필요 | ## Capability 매트릭스 @@ -40,27 +39,20 @@ `MessagingCapabilities`가 런타임에 선언하는 값이다. `false`인 기능을 요구하는 destination profile은 **startup에서 실패**하며, 조용히 약화되지 않는다. -| Capability | Kafka | Kafka Share | RabbitMQ | Pulsar | NATS JS | -|---|---|---|---|---|---| -| brokerAcknowledgement | O | O | O | O | O | -| replicationOrPersistenceEvidence | O | O | O | O | O | -| perMessageSettlement | O | O | O | O | O | -| batchSettlement | O | X | X | O | O | -| orderedStream | O | **X** | X | X | O | -| keyedOrdering | O | **X** | X | Key_Shared만 | X | -| replay | O | X | X | O | O | -| delayedDelivery | X | X | retry queue로 대행 | O | X | -| brokerTransaction | O | X | X | 미승격 | X | -| deduplicatedPublish | O | X | X | X | O | -| nativeDeadLetter | X | X | O | O | **X** | -| topologyManagement | O | X | O | O | O | - -Kafka Share Group이 ordering 전부 `X`인 것은 설계 결정이다. share group은 개별 record를 -경쟁 소비자에게 나눠주고 개별 ack하므로 partition 순서를 유지할 수 없다. ordered destination을 -share group에 설정하면 `KafkaShareProfileValidator`가 거부한다. - -NATS JetStream의 `nativeDeadLetter=X`도 마찬가지다. JetStream은 delivery limit 초과 시 메시지를 -**terminate**할 뿐 어디로도 라우팅하지 않으므로, 플랫폼이 DLQ publish를 직접 수행한다. +| Capability | Kafka | +|---|---| +| brokerAcknowledgement | O | +| replicationOrPersistenceEvidence | O | +| perMessageSettlement | O | +| batchSettlement | O | +| orderedStream | O | +| keyedOrdering | O | +| replay | O | +| delayedDelivery | X | +| brokerTransaction | O | +| deduplicatedPublish | O | +| nativeDeadLetter | X | +| topologyManagement | O | ## 기능 등급 @@ -73,8 +65,6 @@ NATS JetStream의 `nativeDeadLetter=X`도 마찬가지다. JetStream은 delivery | Batch / Manual settlement / Pause·Resume / Delayed / Replay 요청 | M2 | | Broker transaction / partition / routing / subscription | M3 | | Replay 실행 / Redrive / offset reset / purge / delete | M4 Admin | -| Kafka Share Group, Pulsar, NATS | Experimental | -| Spring Cloud Stream bridge | Optional | ## 무엇이 "Stable"을 증명하는가 @@ -82,7 +72,7 @@ Stable 등급은 두 가지를 **모두** 통과해야 한다. `CompatibilityMat ### 1. 공유 Contract Suite (`MessagingAdapterContract`, 7개) -Kafka와 RabbitMQ가 동일한 7개 테스트를 변경 없이 통과한다. 결정적 하네스를 쓰므로 +Kafka가 7개 테스트를 변경 없이 통과한다. 결정적 하네스를 쓰므로 확인 유실·settlement 유실 같은 장애를 요청 시점에 재현할 수 있다. ### 2. 실 브로커 인증 (Testcontainers) @@ -92,7 +82,6 @@ Kafka와 RabbitMQ가 동일한 7개 테스트를 변경 없이 통과한다. 결 | `KafkaBrokerIT` | `acks=all`이 실제 replication 증거를 만든다 / 잘못된 토픽은 `REJECTED` / 발행-소비 왕복에서 identity 보존 및 contiguous commit | | `KafkaAmbiguityChaosIT` | 브로커를 `docker pause`로 멈춘 상태의 publish가 **`AMBIGUOUS`** 로 보고된다 (broker acceptance 없음, confirmation level `NONE`, 비-retryable) | | `KafkaBrokerCertificationIT` | 인증 레인. Toxiproxy를 broker 앞에 두고 connection cut / confirm 유실 / 지연 / settlement 유실을 각각 주입하고, 통과한 시나리오마다 `BrokerCertificationEvidence` 한 줄을 manifest에 쓴다 | -| `RabbitBrokerIT` | exchange가 confirm했는데 어떤 큐에도 바인딩되지 않은 publish가 **`REJECTED` + `UNROUTABLE`** 로 보고된다 | | `OutboxPostgresIT` | 롤백된 트랜잭션은 발행 가능한 행을 남기지 않는다 / `SKIP LOCKED` lease가 두 relay를 분리한다 / ambiguous 행이 같은 `messageId`로 재클레임된다 | | `InboxPostgresIT` | 재전달이 side effect를 두 번 적용하지 않는다 / 롤백은 예약도 되돌린다 | @@ -137,7 +126,7 @@ delivery timeout으로 나타난다. 이를 `REJECTED`로 보고하는 것은 1. **Outbox `IN_FLIGHT` 고아 행** — lease 쿼리가 `PENDING`/`AMBIGUOUS`만 클레임 대상으로 봐서, publish 도중 죽은 relay가 남긴 행이 lease 만료 후에도 영영 회수되지 않았다. -2. **Rabbit confirm 경합** — transport가 publish *후에* confirm을 등록해서, 연결 스레드에서 +2. **Rabbit confirm 경합**(2026-09-25에 삭제된 Rabbit transport) — transport가 publish *후에* confirm을 등록해서, 연결 스레드에서 confirm이 먼저 도착하면 유실되고 호출자가 무한 대기했다. 둘 다 인메모리 double이 실제보다 관대해서 통과하고 있었다. @@ -154,21 +143,10 @@ delivery timeout으로 나타난다. 이를 `REJECTED`로 보고하는 것은 - DLQ publish 확인 전 source ACK -## R1 compiler status - -`adapter:outbound:messaging`의 contract/catalog/envelope compiler 군은 현재 **의도적으로 미배선**이다. -`DISABLED` + 빈 catalog/binding이 zero-resource 상태이며, 이 R1 compiler를 legacy -`MessagingConfig`에 연결해 Kafka ACK, wire compatibility, `ACTIVE_READY`, R2 qualification을 -주장하지 않는다. 코드는 다음 세대 계약을 보존하지만 현재 채택 경로가 아니며, 실제 활성화는 별도 R2 -composition/cutover에서 명시적으로 이뤄져야 한다. - - -### Optional mapping / bridge utilities +### Optional mapping utilities - `messaging-cloudevents`는 starter runtime에 자동 편입되지 않는 **opt-in mapping utility**다. 내부 envelope와 CloudEvent 객체 사이의 제한된 profile mapping을 제공하지만 binary/structured CloudEvents wire mode 전체를 구현하거나 임의 CloudEvents producer와의 1.0 interoperability를 인증하지 않는다. -- `messaging-spring-cloud-stream-bridge`는 현재 `ChannelSend` seam과 publish-evidence 판단을 제공하는 - framework-neutral bridge contract다. Spring Cloud Stream `StreamBridge` dependency/auto-configuration은 - 제공하지 않으므로 shipped Spring Cloud Stream integration으로 분류하지 않는다. +- `messaging-claim-check`도 starter에 편입되지 않는 opt-in utility다. diff --git a/docs/mongo/persistence-profile.example.yml b/docs/mongo/persistence-profile.example.yml index b277f475..41618f17 100644 --- a/docs/mongo/persistence-profile.example.yml +++ b/docs/mongo/persistence-profile.example.yml @@ -12,7 +12,6 @@ ca-skeleton: topology: REPLICA_SET production: true stable-api-strict: true - consistency-default: PRIMARY_MAJORITY server-selection-timeout: 3s connect-timeout: 2s socket-read-timeout: 5s @@ -21,7 +20,5 @@ ca-skeleton: pool-max-size: 40 pool-max-wait-time: 500ms uuid-representation: STANDARD - decimal-representation: DECIMAL128 - runtime-auto-create-indexes: false tls-required: true authentication-required: true diff --git a/docs/mongodb/advanced/encryption.md b/docs/mongodb/advanced/encryption.md index a1885890..29e3f038 100644 --- a/docs/mongodb/advanced/encryption.md +++ b/docs/mongodb/advanced/encryption.md @@ -1,8 +1,9 @@ # Advanced — CSFLE and Queryable Encryption **Capabilities:** `MongoCapability.CSFLE`, `MongoCapability.QUERYABLE_ENCRYPTION` -**Properties:** `ca-skeleton.persistence-mongo.advanced.csfle.enabled`, -`ca-skeleton.persistence-mongo.advanced.queryable-encryption.enabled` +**Enablement:** library API, no configuration property. The service's own adapter constructs the +entry point with a `MongoAdvancedCapabilityGuard` built from `MongoAdvancedCapabilityFlags` that +enables the capability; construction is refused otherwise. **Status:** Advanced. ## Requirements @@ -18,7 +19,8 @@ `MongoCsfleProfile` binds a collection to its `MongoCsfleFieldPolicy` list, a key vault `MongoCredentialReference` and the key vault namespace. `MongoCsfleClientFactory` builds the encrypted -client; `MongoDataKeyResolver` resolves data keys. +client settings. Data-key selection is the adopter's: `MongoCsfleFieldPolicy.keyAlias()` is the +alias the driver resolves against the key vault. `MongoCsfleMode`: @@ -87,5 +89,5 @@ an outage. Per [ADR-MONGO-ADV-001](../../adr/ADR-MONGO-ADV-001-capability-promotion.md), promotion requires the real KMS and key vault, plus negative cases that fail closed: wrong key, missing permission, rotation -mid-operation (`MongoAtlasCapabilityContractSuite.kmsFailureModes`). A local key provider certifies +mid-operation. A local key provider certifies none of these — it never rejects anything. diff --git a/docs/mongodb/advanced/gridfs-migration.md b/docs/mongodb/advanced/gridfs-migration.md deleted file mode 100644 index 6cbf32ec..00000000 --- a/docs/mongodb/advanced/gridfs-migration.md +++ /dev/null @@ -1,63 +0,0 @@ -# Advanced — GridFS compatibility and migration - -**Capability:** `MongoCapability.GRIDFS_COMPATIBILITY` -**Property:** `ca-skeleton.persistence-mongo.advanced.gridfs-compatibility.enabled` -**Status:** Advanced, compatibility only. Decision D-14. - -## Position - -GridFS is a **compatibility adapter for files that already exist there**. New files use the existing -Fileserver / Object Storage adapter, which is the source of truth for binary content. - -The reason is not preference. GridFS stores file chunks in the same collections, on the same replica -set, competing for the same working set as your documents. A large file read evicts document pages -from cache, and file storage growth becomes replica-set growth — which means it becomes oplog -pressure, backup duration and failover time. Object storage was built for this and MongoDB was not. - -## Reading legacy files - -`MongoGridFsCompatibilityReader` reads existing GridFS content as -`GridFsLegacyContent(legacyId, filename, sizeBytes, checksum, stream)`. It reads; it does not write. - -## Migration - -`MongoGridFsMigrationJob` moves a file to object storage in a fixed order: - -``` -read legacy content -→ write to object storage -→ verify the target checksum matches the source -→ switch the reference -→ (later, separately) delete the source -``` - -Three properties, each of which exists because of a specific way this goes wrong: - -1. **Verify before switching.** `MongoGridFsObjectReference` requires a non-blank checksum, and the - job returns empty and writes no reference when the target checksum does not match the source. A - migration that switches the reference on a successful *write* rather than a verified *copy* - silently points at a truncated object. -2. **The source is never deleted here.** Deletion is a separate, later decision after the new - location has been serving reads long enough to be trusted. A migration that deletes as it goes has - no rollback. -3. **The checkpoint separates migrated from failed.** `MongoGridFsMigrationCheckpoint` tracks - `migratedCount()`, `failedCount()`, `clean()` and `lastMigratedLegacyId()`, so a restart continues - from the last completed file rather than starting over, and a partially failed run is visible as - partial rather than as "done". - -## Failure recovery - -| Symptom | Cause | Action | -|---|---|---| -| `migrate` returns empty | Checksum mismatch | The copy is bad. Investigate before retrying; do not force the reference. | -| `IllegalArgumentException` on the reference | Missing checksum | A reference without a checksum cannot be verified and is refused. | -| Checkpoint not `clean()` | Some files failed | Re-run for the failed ids only; the checkpoint names the last successful one. | -| Reference switched but content missing | Source deleted too early | Restore from backup. This is what rule 2 prevents. | - -## Promotion evidence - -Actual-topology evidence against the real object storage backend, a security review of the storage -credential, the migration path above, failure cases (checksum mismatch refused, missing checksum -refused, restart resumes), and this document as the runbook. - -New file storage does not go through here at all — see the fileserver adapter. diff --git a/docs/mongodb/advanced/multi-tenancy.md b/docs/mongodb/advanced/multi-tenancy.md index 5064a1f2..722cd872 100644 --- a/docs/mongodb/advanced/multi-tenancy.md +++ b/docs/mongodb/advanced/multi-tenancy.md @@ -2,16 +2,19 @@ **Capabilities:** `MongoCapability.SHARED_COLLECTION_TENANCY` (Advanced), `MongoCapability.DATABASE_PER_TENANT` (Experimental) -**Properties:** `ca-skeleton.persistence-mongo.advanced.shared-collection-tenancy.enabled`, -`ca-skeleton.persistence-mongo.advanced.database-per-tenant.enabled` +**Enablement:** library API, no configuration property. The service's own adapter constructs the +entry point with a `MongoAdvancedCapabilityGuard` built from `MongoAdvancedCapabilityFlags` that +enables the capability; construction is refused otherwise. +Shared-collection tenancy has no entry point (its types are policies), so only +`DATABASE_PER_TENANT` is ever checked. ## 1. Shared collection Every tenant's documents live in one collection, discriminated by a tenant field. `MongoTenantContext` carries the tenant. `MongoTenantPredicateInjector` adds the tenant predicate to -every query, every atomic filter and the **first** aggregation stage. `TenantScopedMongoOperations` -is the entry point, so a caller cannot construct an unscoped operation by forgetting. +every query, every atomic filter and the **first** aggregation stage. The adopter's repository calls +the injector on every tenant-scoped path; there is no tenant-scoped operations facade in this leaf. Three details are load-bearing: @@ -38,8 +41,8 @@ grows with the customer list, and the tag ships tenant identity into the metrics ## 2. Database per tenant (Experimental) -`MongoTenantDatabaseResolver` maps a tenant to its database; `MongoTenantClientRegistry` holds the -clients. +`MongoTenantClientRegistry` holds one client per tenant under a cap with idle eviction; mapping a +tenant to its database is the adopter's code. Experimental for a specific reason: it is correct in the small and unbounded in the large. Each tenant database costs connections, file handles and monitoring cardinality. It works beautifully at 20 @@ -76,7 +79,7 @@ contractual isolation or per-tenant-restore requirement. | Symptom | Cause | Action | |---|---|---| -| Cross-tenant data visible | An operation bypassed `TenantScopedMongoOperations` | Treat as a security incident. Find the path, close it, audit access. | +| Cross-tenant data visible | An operation skipped `MongoTenantPredicateInjector` | Treat as a security incident. Find the path, close it, audit access. | | Unique constraint fires across tenants | Unique index missing the tenant field | Rebuild the index with the tenant field as prefix; the validator catches this before it ships. | | One shard holds most data | Tenant id as shard-key prefix with a dominant tenant | Refine the shard key with a high-cardinality suffix. | | Connection exhaustion | Database-per-tenant beyond the connection budget | The scale limit. Consolidate or move to shared collections. | diff --git a/docs/mongodb/advanced/search-vector.md b/docs/mongodb/advanced/search-vector.md deleted file mode 100644 index 4f61294b..00000000 --- a/docs/mongodb/advanced/search-vector.md +++ /dev/null @@ -1,81 +0,0 @@ -# Advanced — Search and Vector Search - -**Capabilities:** `MongoCapability.SEARCH`, `MongoCapability.VECTOR_SEARCH` -**Properties:** `ca-skeleton.persistence-mongo.advanced.search.enabled`, -`ca-skeleton.persistence-mongo.advanced.vector-search.enabled` -**Status:** Experimental (design §3.3). Hybrid search likewise. - -## Requirements - -| | | -|---|---| -| Topology | A deployment with the search service. Atlas Local in a container is a pull-request convenience and is **not** release evidence. | -| Privilege | `MongoPrincipalRole.SEARCH_ADMIN` for index management; the application role queries only. | -| Gate | `MongoAtlasCapabilityContractSuite` on the actual target deployment. | - -## 1. Created is not ready - -`MongoSearchIndexState`: `CREATED` → `BUILDING` → `READY`, plus `FAILED` and `DELETING`. - -`MongoSearchReadinessGate.requireReady(state)` refuses anything but `READY`. A search index is built -asynchronously: the create call returns immediately and the index answers queries with *partial* -results while building. Not an error, not empty — partial. A deployment that creates an index and -starts querying serves incomplete results for as long as the build takes, and nothing reports it. - -## 2. Search indexes are not application-owned - -`MongoSearchIndexDescriptor.metadataOwnership()` is `MongoMetadataOwnership.SEARCH_MANAGED`, and -`droppableByApplicationDrift()` is false. The index reconciliation described in -[ADR-MONGO-004](../../adr/ADR-MONGO-004-index-schema-admin-plane.md) must not drop it. - -## 3. Query guardrails - -`MongoSearchQuery` binds an index, an allowlist of paths, the search text and a result limit. - -- `requireAllowedPaths(allowed)` raises `MongoOperationRejectedException` on a path outside the - allowlist. Without it, a caller can search any indexed field, including ones indexed for a - different purpose. -- Search text length and result count are bounded at construction. An unbounded search text is a - cost multiplier on someone else's service. - -## 4. Vector search - -`MongoVectorIndexDescriptor.cosine(path, dimensions)` declares the index. -`MongoEmbedding.forIndex(index, values)` binds an embedding to it and **rejects a dimension -mismatch** — a 1536-dimension embedding against a 768-dimension index is not a runtime degradation, -it is a category error, and catching it at construction beats catching it as a confusing server -message. - -`MongoEmbedding` copies its backing array in and out. A vector that shares an array with its caller -can be mutated after the query is built, which produces a query nobody wrote. - -`MongoVectorQuery` requires `numCandidates > limit` — searching 10 candidates to return 10 results is -an exhaustive scan wearing an ANN index's name. `MongoVectorQuery.nearest(embedding, 10)` uses the -standard 20× ratio (200 candidates for 10 results). - -## 5. Relevance is the gate, not functionality - -`MongoVectorSearchBenchmarkGate.standard()` requires **recall** alongside latency and index size. -`requiredEvidence()` names recall explicitly. - -This is the difference between search and everything else in the platform. A vector index can be -functionally perfect — it accepts the index, accepts the query, returns k results, within the latency -budget — and return the wrong k. A gate that measures only latency certifies a fast wrong answer. -`failures(recall, latencyMs, indexMb)` reports which dimension failed so the finding is actionable. - -## 6. Failure recovery - -| Symptom | Cause | Action | -|---|---|---| -| Incomplete results after a deploy | Queried a `BUILDING` index | Wait for `READY`. The gate prevents this; if it fired, something bypassed it. | -| `MongoOperationRejectedException` on a path | Path not in the allowlist | Add it deliberately, or fix the caller. | -| Dimension mismatch | Model changed | A new model means a new index. Build alongside, cut over, then retire. | -| Recall dropped without a code change | The index was rebuilt with different parameters, or the data distribution shifted | Re-run the benchmark gate; treat a recall regression like a failing test. | -| Index `FAILED` | Build error on the search service | Search-side diagnosis; the application must not fall back to a scan silently. | - -## 7. Promotion evidence - -Per [ADR-MONGO-ADV-001](../../adr/ADR-MONGO-ADV-001-capability-promotion.md): the actual target -deployment (not Atlas Local), security review of `SEARCH_ADMIN`, a rebuild path, failure cases -(non-ready index refused, disallowed path refused, dimension mismatch refused), this document as the -runbook, **and** relevance evidence. Search and vector search do not promote on functional success. diff --git a/docs/mongodb/advanced/sharding.md b/docs/mongodb/advanced/sharding.md index 5853484b..2987a243 100644 --- a/docs/mongodb/advanced/sharding.md +++ b/docs/mongodb/advanced/sharding.md @@ -1,7 +1,9 @@ # Advanced — Sharding **Capability:** `MongoCapability.SHARDING` -**Property:** `ca-skeleton.persistence-mongo.advanced.sharding.enabled` +**Enablement:** library API, no configuration property. The service's own adapter constructs the +entry point with a `MongoAdvancedCapabilityGuard` built from `MongoAdvancedCapabilityFlags` that +enables the capability; construction is refused otherwise. **Status:** Advanced. Reshard orchestration remains Experimental. ## Requirements diff --git a/docs/mongodb/advanced/time-series.md b/docs/mongodb/advanced/time-series.md deleted file mode 100644 index 7228da3f..00000000 --- a/docs/mongodb/advanced/time-series.md +++ /dev/null @@ -1,73 +0,0 @@ -# Advanced — Time Series - -**Capability:** `MongoCapability.TIME_SERIES` -**Property:** `ca-skeleton.persistence-mongo.advanced.time-series.enabled` -**Status:** Advanced. - -## Requirements - -| | | -|---|---| -| Topology | Replica set or sharded cluster. | -| Server | MongoDB 7.0 or 8.0. | -| Privilege | Standard application role; collection creation goes through the admin plane. | - -## Descriptor - -`MongoTimeSeriesDescriptor` declares: - -- **timeField** — required, a BSON date. This is the bucketing axis. -- **metaField** — optional but nearly always wanted: the series identity (device id, tenant, sensor). - Documents sharing a `metaField` value bucket together, which is where the compression comes from. -- **granularity** — `MongoTimeSeriesGranularity`: - -| Granularity | Bucket span | Use for | -|---|---|---| -| `SECONDS` | 1 hour | Sub-second to per-second ingest. | -| `MINUTES` | 24 hours | Per-minute metrics. | -| `HOURS` | 30 days | Hourly rollups. | - -Granularity that is too fine produces many small buckets and loses the compression; too coarse -produces oversized buckets that must be read whole to answer a narrow query. - -## What a time series collection is not - -`MongoTimeSeriesCapabilityValidator` refuses the operations the collection type does not support, at -declaration time rather than at first use: - -- **No arbitrary updates.** Time series data is append-mostly. Delete and limited update support - exists on recent servers but is not part of this platform's contract. -- **No unique index on the measurement.** There is no `_id` to be unique on in the usual sense. -- **No CSFLE.** Refused — see [encryption.md](encryption.md). -- **No change stream on the raw buckets** as a business event source. The bucket documents are a - storage representation, not your measurements. - -Converting an existing regular collection to a time series collection is a copy, not an alter. Plan -it as a migration with a dual-write window. - -## TTL - -Time series collections use `expireAfterSeconds` on the collection rather than a TTL index on a -field. The [TTL rules](../schema-index-migration-guide.md#4-ttl) still apply: expiry is physical -cleanup on a bucket boundary, so a measurement can outlive its expiry by up to a bucket span plus the -monitor interval. Do not treat absence as a deadline. - -## Operations - -`MongoTimeSeriesOperations` is the port for insert and windowed read. Reads are bounded by the same -`MongoOperationBudget` as everything else: an unbounded time-range query on a time series collection -is the fastest way to read a year of data into heap. - -## Failure recovery - -| Symptom | Cause | Action | -|---|---|---| -| Writes rejected with an unsupported-operation error | An update or unique-index expectation | The collection type does not support it; change the access pattern. | -| Poor compression / large storage | Missing `metaField`, or granularity too fine | Both require a rebuild; measure on a copy before committing. | -| Slow range queries | Granularity too coarse for the query window | Same: rebuild with the granularity matched to the dominant query. | - -## Promotion evidence - -Actual-topology evidence on the target deployment, a migration path from the existing collection, -failure cases (unsupported update refused, CSFLE combination refused), and this document as the -runbook. diff --git a/docs/mongodb/change-stream-guide.md b/docs/mongodb/change-stream-guide.md deleted file mode 100644 index f92ba7c1..00000000 --- a/docs/mongodb/change-stream-guide.md +++ /dev/null @@ -1,105 +0,0 @@ -# Change Stream Guide - -Design §20, decision D-12. A change stream is an **at-least-once projector**, not an event bus. - -## 1. What a change stream is not - -D-12 is explicit: a physical change event is not a business integration event. The two differ in -ways that matter to every consumer: - -| Change event | Integration event | -|---|---| -| Emitted per document write | Emitted per business fact | -| Shape follows the storage schema | Shape is a published contract | -| A refactor of the document changes it | A refactor of the document does not change it | -| Replayed on resume, duplicated on retry | Versioned and deliberately evolved | - -Publishing raw change events externally makes your storage schema a public API, and the first time -someone renames a field the downstream consumers break. If you need to bridge to messaging, use the -Advanced bridge, which maps to an owned envelope -([advanced/multi-tenancy.md](advanced/multi-tenancy.md) is separate; -the bridge is described in §7 below). - -## 2. Subscription and resume - -`MongoChangeStreamSubscription` declares the collection, pipeline and consistency. `MongoResumePosition` -is either a resume token or a cluster time; `MongoResumeCheckpoint` is what gets persisted and -`MongoResumeCheckpointStore` persists it. - -The checkpoint stores the token as a Base64 `encodedToken` string rather than a byte array — a record -with an array component has broken equality, and a checkpoint that does not compare correctly is a -checkpoint that silently fails its own dedup test. - -## 3. Checkpoint after processing, not after receiving - -The ordering rule that makes at-least-once actually hold: - -``` -receive event -→ process it (idempotently) -→ persist the checkpoint -``` - -Checkpointing on receipt turns the delivery guarantee into at-most-once, and the events lost are -exactly the ones the process died while handling. - -## 4. Idempotency - -`MongoChangeEventIdentity` is the dedup key: `(resumeToken, documentKey, clusterTime, operationType)`. -`MongoChangeDeduplicationStore` records what has been applied. Duplicates are not an edge case — every -resume after any interruption replays at least one event, so a projector that is not idempotent is -wrong on its first restart, not on some rare day. - -`MongoChangeProjector` returns a `MongoChangeProjectionResult` so the runner can distinguish applied -from skipped-as-duplicate, and the skip count is worth a metric: a sudden rise means something is -looping. - -## 5. States and recovery - -`MongoChangeStreamState`: `STARTING`, `RUNNING`, `RESUMING`, `STOPPED`, `HISTORY_LOST`. - -`MongoChangeStreamRecoveryPolicy` returns a `MongoChangeStreamRecoveryDecision`, which is either -`resume()` (auto-resume from the checkpoint) or `halt(state, runbook)`. A halting decision **must** -name a runbook — a decision that only says "stopped" leaves the on-call engineer to work out from -scratch whether the projection can be rebuilt and from what. - -| Situation | Decision | -|---|---| -| Transient network error, token still valid | `resume()` | -| Primary failover | `resume()` — the token survives an election | -| `invalidate` (collection dropped/renamed) | `halt(STOPPED, …)` → `MongoInvalidateRecovery` | -| Token no longer in the oplog | `halt(HISTORY_LOST, "history-lost")` → `MongoChangeHistoryLostException` | - -## 6. History lost - -`MongoChangeHistoryLostException` is raised when the resume token predates the oldest oplog entry. -The stream **cannot** be resumed: the events between the checkpoint and now are gone from the server, -and no amount of retrying brings them back. - -What the platform will not do is silently restart from "now". That looks like a recovery and is -actually a silent gap in the projection — the worst possible outcome, because nothing reports it. The -runner halts and requires an operator decision. See -[runbooks/history-lost.md](runbooks/history-lost.md). - -## 7. Bridging to messaging (Advanced) - -`MongoChangeMessagingBridge` is opt-in behind `MongoCapability.CHANGE_STREAM` plus the bridge's own -flag. It maps a change event to a platform-owned `MongoIntegrationEventEnvelope` through -`MongoChangeToIntegrationEventMapper` and hands it to a `MongoIntegrationEventPublisher` port. - -The port is defined in the bridge package rather than imported from the messaging adapter because the -architecture registry forbids adapter-to-adapter dependencies; the composition root supplies the -implementation. - -`MongoBridgeOutboxPolicy` and `MongoBridgeCheckpointPolicy` state the delivery contract: publish then -checkpoint, at-least-once, consumers must dedup on the envelope's event id. - -## 8. Operating notes - -- Change streams require a replica set. `MongoStartupValidator` refuses a change-stream profile on - `STANDALONE`. -- The change-stream principal is its own role (`MongoPrincipalRole.CHANGE_STREAM`) with - `changeStream` and `find` — not the application write credential. -- Oplog window is the recovery budget. If the oplog holds four hours, a consumer that is down for five - hours needs a rebuild, not a resume. Alert on consumer lag against the oplog window, not against - wall-clock. diff --git a/docs/mongodb/consistency-transaction-guide.md b/docs/mongodb/consistency-transaction-guide.md index 06ff6c9e..bff0f3e3 100644 --- a/docs/mongodb/consistency-transaction-guide.md +++ b/docs/mongodb/consistency-transaction-guide.md @@ -31,8 +31,7 @@ Collapsing these two into one is how a concurrent overwrite becomes a 404. ## 3. Consistency profiles `MongoConsistencyProfile` names the read/write concern pair; `MongoConsistencyRegistry` binds a -profile to an operation or collection, and `MongoConsistencyBinder` / -`ReactiveMongoConsistencyBinder` apply it at execution. +profile to an operation or collection, and `MongoConsistencyBinder` applies it at execution. | Profile | Meaning | Use for | |---|---|---| @@ -47,17 +46,14 @@ without a registered profile is rejected rather than defaulting. ## 4. Causal sessions -`MongoCausalSessionContext` plus `SpringMongoCausalSessionExecutor` / -`ReactiveMongoCausalSessionExecutor` carry the cluster time and operation time between operations, so +`MongoCausalSessionContext` plus `SpringMongoCausalSessionExecutor` carry the cluster time and +operation time between operations, so "write then read" returns the write even when the read lands on a different node. Without a causal session, `PRIMARY_MAJORITY` gives you durability but not read-your-writes across two calls. -In the reactive path the session travels in the Reactor context (`ReactiveMongoContextKeys`), not in -a thread local — a thread local is empty on the next operator in the chain. - ## 5. Transactions -`MongoTransactionExecutor` / `ReactiveMongoTransactionExecutor` open a session through the session +`MongoTransactionExecutor` opens a session through the session factory, run the body, and commit. `MongoTransactionProfile` carries the consistency profile, the `maxCommitTime` and the retry budget. Topology matters: a transaction requires a replica set, and `MongoStartupValidator` refuses a transaction-declaring profile on `STANDALONE` at startup rather @@ -122,5 +118,5 @@ driver type. `MongoBulkExecutor` returns a `MongoBulkResult` with per-item `MongoBulkItemFailure` entries. An unordered bulk write that partially fails is `PARTIAL_BULK_WRITE`, not a failure: some documents were -written. `MongoBulkPartialFailureException` carries the succeeded and failed indexes so a caller can +written. The result's per-item outcomes say which indexes succeeded and which failed, so a caller can resume rather than replay. diff --git a/docs/mongodb/document-modeling-guide.md b/docs/mongodb/document-modeling-guide.md index 492744f4..a110e341 100644 --- a/docs/mongodb/document-modeling-guide.md +++ b/docs/mongodb/document-modeling-guide.md @@ -39,8 +39,8 @@ is the first symptom, and by then the collection is already full of near-limit d ## 4. Identity -`DomainDocumentId` and `MongoIdRepresentation` fix how a domain identifier becomes `_id`. Pick the -representation once per collection and record it in the manifest: +`DomainDocumentId` is written to `_id` as a BSON string by `DomainIdWriteConverter`. Any other +representation is the document class's own field type. Pick the representation once per collection: - `OBJECT_ID` — server-generated, monotonic, 12 bytes. Good default when the domain has no natural id. - `UUID_BINARY` — a domain UUID stored as `Binary` subtype 4 (`STANDARD`). Never store a UUID as a @@ -70,7 +70,7 @@ becomes a data migration; storing an alias keeps it a refactor. See `MongoCollectionProfileRegistry` binds a `CollectionProfileName` to its consistency profile, budget and allowlist. A collection that is not registered cannot be reached through -`MongoImperativeExecutor` or `ReactiveMongoExecutor` — the allowlist is the mechanism that keeps an +`MongoImperativeExecutor` — the allowlist is the mechanism that keeps an unreviewed collection from appearing in production by accident. ## 8. What to write down before the first insert diff --git a/docs/mongodb/query-aggregation-guide.md b/docs/mongodb/query-aggregation-guide.md index 812e0309..ad2712ae 100644 --- a/docs/mongodb/query-aggregation-guide.md +++ b/docs/mongodb/query-aggregation-guide.md @@ -92,21 +92,7 @@ registered plan. `allowDiskUse` is a declared property of the plan, not a runtime flag. A pipeline that needs disk is a pipeline whose shape should be reviewed. -## 6. Reactive execution and cursors - -`ReactiveMongoExecutor` / `DefaultReactiveMongoExecutor` carry the operation context in the Reactor -context. `MongoCursorGuard` and `MongoCursorLease` bound cursor lifetime: - -- a cursor has a lease with a deadline -- cancellation closes the server-side cursor (`MongoCursorTermination`) -- an abandoned cursor is a server-side resource, so the lease is released on cancel, error *and* - completion — `MongoReactiveCursorPublisher` uses `Flux.using` so all three paths run the same - release - -A leaked cursor does not fail anything locally; it consumes a connection and a snapshot on the server -until the server's own timeout, which is why the guard is not optional. - -## 7. Geospatial +## 6. Geospatial `MongoGeoQuery` + `MongoGeoPoint` + `MongoGeoDistance` over a `2dsphere` index. Distances are metres on a sphere (`nearSphere` with `maxDistance`), never degrees — a degree of longitude is a different @@ -114,7 +100,7 @@ distance in Oslo than in Nairobi, and a radius expressed in degrees is a bug tha from the equator. `SpringMongoGeospatialOperations` is the Spring Data binding; `MongoGeospatialOperations` is the port. -## 8. Native capability gateway +## 7. Native capability gateway When a registered operation genuinely needs something outside the Stable API, it goes through `MongoNativeCapabilityGateway` (`PolicyAwareMongoNativeGateway`), never through the driver directly. diff --git a/docs/mongodb/repository-adaptation.md b/docs/mongodb/repository-adaptation.md index de665c7f..9061ff42 100644 --- a/docs/mongodb/repository-adaptation.md +++ b/docs/mongodb/repository-adaptation.md @@ -27,9 +27,8 @@ the tree for exact equality, and every observed edge must appear in it. A forbid build the same way a missing Gradle dependency would, and so does a new package nobody registered. This used to be a stronger claim than the test. The rules forbade a handful of reverse dependencies -and said nothing about the rest, so four edges outside the design's DAG existed and passed: -`reactive → imperative`, `reactive → query`, `transaction → reactive` and `geo → imperative`. They -are declared in the matrix now rather than removed — each is a real coupling the code relies on, and +and said nothing about the rest, so edges outside the design's DAG existed and passed, among them +`geo → imperative`. They are declared in the matrix now rather than removed — each is a real coupling the code relies on, and the point of recording them is that the next one is a decision instead of an accident. ## 2. Package mapping @@ -43,12 +42,10 @@ Root package: `io.backend.skeleton.mongodb` → `dev.caskeleton.adapter.outbound | `mongodb-core-api` | `…outbound.mongo.api` (+ `.capability`, `.consistency`, `.error`, `.mapping`, `.observation`, `.profile`, `.schema`) | | `mongodb-spring-data` | `…outbound.mongo.mapping` (+ `.type`), `…outbound.mongo.failure` | | `mongodb-imperative` | `…outbound.mongo.imperative` (+ `.atomic`, `.bulk`, `.revision`) | -| `mongodb-reactive` | `…outbound.mongo.reactive` (+ `.cursor`) | | `mongodb-query` | `…outbound.mongo.query` (+ `.budget`, `.pagination`) | | `mongodb-aggregation` | `…outbound.mongo.aggregation` | | `mongodb-transaction` | `…outbound.mongo.transaction` (+ `.retry`, `.session`) | | `mongodb-index-schema` | `…outbound.mongo.schema` (+ `.index`, `.manifest`, `.model`, `.ttl`, `.validation`) | -| `mongodb-change-stream` | `…outbound.mongo.changestream` (+ `.projector`, `.recovery`) | | `mongodb-geospatial` | `…outbound.mongo.geo` | | `mongodb-migration-core` | `…outbound.mongo.migration` | | `mongodb-migration-flamingock` | `…outbound.mongo.migration.flamingock` | @@ -68,22 +65,22 @@ the reusable ArchUnit rule set a fork applies to its own document/repository cod | Design module | Repository package | |---|---| | `mongodb-sharding` | `…outbound.mongo.advanced.sharding` (+ `.admin` for the D4 shard plane) | -| `mongodb-timeseries` | `…outbound.mongo.advanced.timeseries` | | `mongodb-csfle` | `…outbound.mongo.advanced.encryption.csfle` | | `mongodb-queryable-encryption` | `…outbound.mongo.advanced.encryption.qe` | -| `mongodb-search` | `…outbound.mongo.advanced.search` | -| `mongodb-vector-search` | `…outbound.mongo.advanced.vector` | | `mongodb-tenancy-shared` | `…outbound.mongo.advanced.tenancy.shared` | | `mongodb-tenancy-database` | `…outbound.mongo.advanced.tenancy.database` | -| `mongodb-change-stream-messaging-bridge` | `…outbound.mongo.advanced.bridge` | -| `mongodb-gridfs-compat` | `…outbound.mongo.advanced.gridfs` | | `mongodb-testkit-sharded` | `…outbound.mongo.testkit.sharded` (`testkit` source set) | -| `mongodb-testkit-atlas` | `…outbound.mongo.testkit.atlas` (`testkit` source set) | + +`mongodb-timeseries`, `mongodb-search`, `mongodb-vector-search`, `mongodb-gridfs-compat` and +`mongodb-testkit-atlas` have no package any more: each was an operations interface with no +implementation plus the descriptors that parametrised it, and was removed on 2026-09-25 +(`docs/capability-status.md`). The design's rule that a Stable module never depends on an Advanced one survives as an ArchUnit rule -(`stableNeverDependsOnAdvanced`) plus the opt-in flag: every Advanced entry point requires -`MongoAdvancedCapabilityFlags` to have the matching capability enabled and refuses construction -otherwise. Being on the classpath is not being enabled. +(`stableNeverDependsOnAdvanced`). Every Advanced entry point takes a `MongoAdvancedCapabilityGuard` +and refuses construction unless its `MongoAdvancedCapabilityFlags` enable the matching capability. +There is no configuration property behind the flags: the Advanced types are library API, and the +adopter's adapter that constructs them builds the guard. ## 3. Other deliberate substitutions @@ -114,13 +111,11 @@ otherwise. Being on the classpath is not being enabled. - Registered operation names and manifests for query, aggregation and index; no free-form JSON query and no unbounded pipeline. - Keyset pagination with an authenticated cursor and a unique tie-breaker requirement. -- Change stream as an at-least-once projector with resume-token checkpointing and explicit - history-lost handling. - TTL as physical cleanup only, never the sole basis for access denial or business scheduling. - Manifest-owned index/validator state with an apply policy that never drops what it does not own. - Low-cardinality observation tags, command redaction, and the credential reference indirection. -- The Stable release gate's evidence categories, and the Advanced promotion gate's requirement for - actual-topology evidence. +- The Stable release gate's evidence categories. The Advanced promotion requirements + (actual-topology evidence) are a review obligation in ADR-MONGO-ADV-001; no class checks them. ## 5. Verification diff --git a/docs/mongodb/runbooks/history-lost.md b/docs/mongodb/runbooks/history-lost.md deleted file mode 100644 index b24cd70f..00000000 --- a/docs/mongodb/runbooks/history-lost.md +++ /dev/null @@ -1,90 +0,0 @@ ---- -title: Runbook — MongoDB change stream history lost -category: mongodb -severity: P1 -owner: oncall -last_updated: 2026-08-13 -status: active ---- - -# Runbook: change stream history lost - -Design §20.3, scenarios `OPLOG_HISTORY_LOSS`, `RESUME_TOKEN_LOSS`. - -The stored resume token predates the oldest entry in the oplog. The events between the checkpoint and -now are gone from the server; no retry recovers them. `MongoChangeStreamRecoveryPolicy` returns -`halt(HISTORY_LOST, "history-lost")` and the runner stops. - -**The platform will not silently restart from "now".** That looks like a recovery and is actually a -permanent, unreported gap in the projection. - -## Symptoms - -- `MongoChangeHistoryLostException`. -- `MongoChangeStreamState.HISTORY_LOST`; the consumer is stopped, not looping. -- Precedes it: consumer lag approaching the oplog window, or a consumer that was down for a long - period (a deploy that failed, a scaled-to-zero worker, a long outage). - -## Diagnosis - -1. **Determine the gap.** The checkpoint's cluster time is the start; the oldest oplog entry is the - end of what is unrecoverable. Everything in between was never processed. -2. **Determine the oplog window.** `rs.printReplicationInfo()` on the primary gives the first and last - oplog timestamps. If the window is materially smaller than it was, the write rate rose or the - oplog was resized — the consumer may be fine and the server changed. -3. **Determine what the projection is missing.** Which collections and which operations does this - projector consume? The gap is bounded by that, not by everything that happened. -4. **Check for a second consumer.** If another projector on the same collection is healthy, its - checkpoint tells you whether the problem is this consumer or the oplog. - -## Action - -Resuming is not an option. The choices are: - -**Rebuild from source.** If the projection is derivable from the current state of the source -collections, rebuild it: stop the consumer, rebuild the projection, then start the stream from the -cluster time at which the rebuild snapshot was taken. This is the correct answer whenever the -projection is a materialised view rather than an event log, and it is the reason a projection should -be derivable. - -**Backfill the gap.** If the source documents carry a timestamp covering the gap, run a bounded -backfill for that window through the migration runner (checkpointed, resumable — see -[schema-index-migration-guide.md](../schema-index-migration-guide.md) §5), then resume from the -current cluster time. - -**Accept the gap explicitly.** Only when the projection is advisory and the business owner says so. -Record the window in the incident log and reset the checkpoint. This is a decision someone signs, not -a default. - -Never: reset the checkpoint to "now" and restart quietly. That converts a visible P1 into an -invisible data-quality defect that surfaces months later as "the report has been wrong since March". - -## Prevention - -- **Alert on lag against the oplog window, not wall-clock.** "Consumer is 30 minutes behind" is fine - with a 24-hour oplog and an emergency with a 45-minute one. The threshold that matters is - `lag / oplogWindow`. -- **Size the oplog for the longest tolerable consumer outage**, including a failed deploy discovered - the next morning. -- **Checkpoint after processing, never on receipt** — see - [change-stream-guide.md](../change-stream-guide.md) §3. -- **Back up the checkpoint store.** `RESUME_TOKEN_LOSS` is the same incident reached from the other - direction: the oplog is fine, the checkpoint is gone. -- **Make the projection rebuildable.** A projection that can only be built by replaying every event - has no recovery path once the oplog rolls. - -## Escalation - -- P1 on detection. The consumer is stopped, so lag grows for as long as this is unresolved. -- Page the service owner for the rebuild decision, and the database owner if the oplog window shrank - unexpectedly. - -## Verification - -```bash -cd src -./gradlew :adapter:outbound:persistence-mongo:mongoFailoverTest --console=plain -``` - -`MongoFailoverScenario.OPLOG_HISTORY_LOSS` and `RESUME_TOKEN_LOSS` assert the runner halts and names -this runbook rather than restarting from the current position. diff --git a/docs/mongodb/security-observability.md b/docs/mongodb/security-observability.md index 1adb4c63..dc140065 100644 --- a/docs/mongodb/security-observability.md +++ b/docs/mongodb/security-observability.md @@ -119,13 +119,14 @@ command's arguments. `MongoStartupValidator` runs at context refresh, before the first request: -1. `MongoTopologyProbe` reports the actual `MongoTopology`. -2. Each declared `MongoTopologyRequirement` is checked against it — a transaction, causal-session or - change-stream requirement fails closed on `STANDALONE`. -3. `MongoSecurityProfileValidator` checks credentials and TLS. -4. `MongoCapabilitySupport` checks declared capabilities against the server version, with - `MongoSupportLevel` distinguishing `STABLE` / `ADVANCED` / `EXPERIMENTAL` / `UNSUPPORTED`. -5. `MongoPlatformHealthIndicator` reports the outcome for the readiness probe. +1. `MongoTopologyProbe` reports the actual `MongoTopology` and its `MongoCapabilitySet`. +2. Every profile's declared topology must match it, and a production profile on `STANDALONE` fails. +3. With `platform.transactions=true`, the probe must report `TRANSACTION` as `STABLE`; on + `STANDALONE` it does not, so startup fails. +4. `MongoSecurityProfileValidator` checks credentials and TLS, and that the admin credential differs + from the runtime one; the `MongoSchemaVersionRange` must not be inverted. +5. `MongoPlatformHealthIndicator` reports topology mismatch and secondary availability for the + readiness probe. A misconfiguration found at startup costs a failed deploy. The same misconfiguration found at runtime costs an incident, and the failing operation is rarely the one that reveals the cause. diff --git a/docs/mongodb/support-matrix.md b/docs/mongodb/support-matrix.md index 3398f366..1fa103b1 100644 --- a/docs/mongodb/support-matrix.md +++ b/docs/mongodb/support-matrix.md @@ -12,7 +12,6 @@ adds a row. | Spring Boot | 4.0.0 | BOM-managed. Individual driver overrides are forbidden. | | Spring Data MongoDB | 5.0.0 | Repository and `MongoTemplate` integration. Version comes from the Boot BOM. | | MongoDB Java Driver | 5.6.1 | BOM-managed. Never pinned directly in the module. | -| Reactor | 3.8.0 | Reactive execution path. | | Micrometer | 1.16.0 | Driver-native observability. | | Testcontainers | 2.0.2 | Replica-set, failover, migration and compatibility lanes. | @@ -40,19 +39,19 @@ fails `certifies()`. | Topology | Status | What is certified | What is not | |---|---|---|---| -| Standalone | **Smoke only** | Basic CRUD and mapping. | Not a production profile and never counts as Stable release evidence (D-03). Transactions, retryable writes and change streams are refused at startup by `MongoStartupValidator`. | +| Standalone | **Smoke only** | Basic CRUD and mapping. | Not a production profile and never counts as Stable release evidence (D-03). A production profile, or `platform.transactions=true`, on a Standalone server is refused at startup by `MongoStartupValidator`. | | Single-node replica set | **Local default** (D-02) | Transactions, retryable writes, change streams — the same semantics as production. | Elections. A single-node set never holds one, so failover behaviour is untested here. | -| 3-node replica set | **Stable production gate** | Everything above plus primary failover, unknown-commit handling and change-stream resume across an election. | Shard routing. | +| 3-node replica set | **Stable production gate** | Everything above plus primary failover and unknown-commit handling. | Shard routing. | | Sharded cluster | **Advanced gate** | Shard-key routing classification, scatter-gather refusal, `admin` plane operations. | Not included in the Stable gate. | -| Atlas / provider-managed | **Per-capability gate** | Search, vector search and encryption against the actual target deployment. | Atlas Local in a container is a pull-request convenience, explicitly **not** release evidence (`MongoAtlasCapabilityContractSuite.Environment`). | +| Atlas / provider-managed | **Not certified** | Encryption against the actual target deployment is the adopter's evidence to produce. | Search and vector search have no implementation in this leaf; a native `$search` command can only go through `PolicyAwareMongoNativeGateway` as a registered D3 operation. | ## 4. Stable API and client generations | Plane | Stable API | Purpose | |---|---|---| | D1 Standard document persistence | V1, `apiStrict=true` | Repositories, typed queries, atomic updates, optimistic revision. | -| D2 Advanced document operations | V1, `apiStrict=true` | `MongoTemplate`, transactions, bulk, aggregation, keyset cursors, change streams. | -| D3 Explicit Mongo capability | Not strict | Native BSON, time series, search/vector, CSFLE/QE, shard-aware operations — each behind a registered capability. | +| D2 Advanced document operations | V1, `apiStrict=true` | `MongoTemplate`, transactions, bulk, aggregation, keyset cursors. | +| D3 Explicit Mongo capability | Not strict | Native BSON, CSFLE/QE, shard-aware operations — each behind a registered capability. | | D4 Admin plane | Not strict | Collection, validator, index, migration, shard and repair commands. Separate credential, separate client. | D3 is not a raw-client escape. Every call passes capability registration → database profile → @@ -83,9 +82,10 @@ feature request: | Tier | Capabilities | Enablement | |---|---|---| -| Stable | Mapping, imperative/reactive execution, atomic update, optimistic lock, transactions, consistency profiles, retry/translation, query and aggregation guardrails, schema/index manifests, keyset pagination, bulk partial results, change streams, TTL contract, GeoJSON, security, observability | On when `ca-skeleton.persistence-mongo.enabled=true`. | -| Advanced | Sharding-aware query, time series, CSFLE, Queryable Encryption (equality/range), change-stream→messaging bridge, shared-collection multi-tenancy | Each behind `ca-skeleton.persistence-mongo.advanced..enabled`. | -| Experimental | Search, vector search, hybrid search, database-per-tenant, collection-per-tenant, reshard orchestration, provider-specific features | Same flag mechanism; promotion additionally requires the evidence in [ADR-MONGO-ADV-001](../adr/ADR-MONGO-ADV-001-capability-promotion.md). | +| Stable, auto-configured | Mapping and BSON converters, imperative execution, atomic update, bulk partial results, consistency profiles, retry/translation, operation budgets, observability, typed client profiles, startup validation, health | Beans registered when `ca-skeleton.persistence-mongo.enabled=true`. | +| Stable, library API | Transactions, causal sessions, optimistic revision, query builder and keyset pagination, aggregation executor, schema/index/validator manifests and diffs, TTL contract, GeoJSON, migration runner, admin plane, native capability gateway | The adopter's adapter leaf takes this leaf as `implementation` and constructs the type. | +| Advanced, library API | Sharding-aware query and shard admin, CSFLE, Queryable Encryption (equality/range), shared-collection tenancy policies | Same, plus a `MongoAdvancedCapabilityGuard` whose flags enable the capability. No configuration property. | +| Experimental, library API | Database-per-tenant client registry and migration coordinator, reshard approval | Same as Advanced; promotion additionally requires the evidence in [ADR-MONGO-ADV-001](../adr/ADR-MONGO-ADV-001-capability-promotion.md). | -`MongoAdvancedCapabilityFlags.propertyFor(capability)` is the authoritative property name for any -capability; the table above is its prose form. +Search, vector search, time series and GridFS compatibility were interfaces with no implementation +and were removed on 2026-09-25 (`docs/capability-status.md`). diff --git a/docs/notification/adr/NOTIF-ADR-005-canonical-namespace.md b/docs/notification/adr/NOTIF-ADR-005-canonical-namespace.md index a3bf5c63..41e11c10 100644 --- a/docs/notification/adr/NOTIF-ADR-005-canonical-namespace.md +++ b/docs/notification/adr/NOTIF-ADR-005-canonical-namespace.md @@ -4,6 +4,13 @@ Accepted (2026-08-15). NTF-018 대응. +**갱신 (2026-09-25):** R1 type은 삭제됐다. production consumer가 끝까지 0건이었고 fake로만 증명된 +계약이라, 새 consumer를 막는 ArchUnit 규칙을 유지할 이유가 없어졌다. 남은 것은 adapter core의 +`RoutingNotifier`가 구현하는 단순 알림 포트 3개(`NotificationPort`, `Notification`, +`NotificationChannel`)뿐이다. 그래서 아래 「강제」의 `NOTIFICATION_R1_AND_PLATFORM_DO_NOT_DEPEND_ON_EACH_OTHER` +규칙과 `compatibility.r1` 예외 패키지도 함께 없어졌다. 삭제 목록과 마지막 커밋은 +`docs/capability-status.md`의 「제거된 코드」 표에 있다. 아래 본문은 결정 당시 기록이다. + ## 문제 같은 저장소에 notification 모델이 **두 개** 있다. diff --git a/docs/notification/api-surface-snapshot.txt b/docs/notification/api-surface-snapshot.txt index d47d325c..5253b9e5 100644 --- a/docs/notification/api-surface-snapshot.txt +++ b/docs/notification/api-surface-snapshot.txt @@ -1,6 +1,8 @@ -# NTF-022 — public type surface of the notification platform. -# Every top-level public type under the platform packages. Growth is a reviewed -# change: ./gradlew updateNotificationApiSurface -PapproveNotificationApiChange +# NTF-022 — public type surface of the notification platform (application-notification + adapter:outbound:notification). +# Every top-level public type under the platform packages. Growth is a reviewed change. +# Update only after review with: +# ./gradlew :adapter:outbound:notification:updateNotificationApiSurface -PapproveNotificationApiSurfaceChange +# types: 416 dev.caskeleton.adapter.outbound.notification.NotificationConfig dev.caskeleton.adapter.outbound.notification.NotificationRoutesSettings dev.caskeleton.adapter.outbound.notification.core.FailOpenNotificationProvider @@ -34,7 +36,6 @@ dev.caskeleton.adapter.outbound.notification.platform.dispatch.ConfiguredProfile dev.caskeleton.adapter.outbound.notification.platform.dispatch.CredentialProbe dev.caskeleton.adapter.outbound.notification.platform.dispatch.CredentialValidationException dev.caskeleton.adapter.outbound.notification.platform.dispatch.JacksonRoutingPlanCodec -dev.caskeleton.adapter.outbound.notification.platform.dispatch.LeaseRecoveryService dev.caskeleton.adapter.outbound.notification.platform.dispatch.LoggingInboxSignalPublisher dev.caskeleton.adapter.outbound.notification.platform.dispatch.MapTemplateRendererRegistry dev.caskeleton.adapter.outbound.notification.platform.dispatch.NotificationBackgroundWorkers @@ -120,9 +121,6 @@ dev.caskeleton.adapter.outbound.notification.platform.provider.webpush.WebPushNo dev.caskeleton.adapter.outbound.notification.platform.provider.webpush.WebPushProviderProperties dev.caskeleton.adapter.outbound.notification.platform.provider.webpush.WebPushReceiptCapability dev.caskeleton.adapter.outbound.notification.platform.provider.webpush.WebPushRequestMapper -dev.caskeleton.adapter.outbound.notification.platform.reactor.ReactiveNotificationOrchestrator -dev.caskeleton.adapter.outbound.notification.platform.reactor.ReactorContextBridge -dev.caskeleton.adapter.outbound.notification.platform.reactor.ReactorNotificationOrchestrator dev.caskeleton.adapter.outbound.notification.platform.security.AesGcmCallbackPayloadProtection dev.caskeleton.adapter.outbound.notification.platform.security.AesGcmContactPointProtector dev.caskeleton.adapter.outbound.notification.platform.security.AesGcmNotificationPayloadProtection @@ -147,105 +145,9 @@ dev.caskeleton.adapter.outbound.notification.platform.template.ThymeleafStringTe dev.caskeleton.adapter.outbound.notification.slack.webhook.SlackClient dev.caskeleton.adapter.outbound.notification.slack.webhook.SlackNotificationAdapterConfig dev.caskeleton.adapter.outbound.notification.slack.webhook.SlackWebhookProvider -dev.caskeleton.application.notification.ApplyNotificationReceiptCommand -dev.caskeleton.application.notification.ApplyNotificationReceiptResult -dev.caskeleton.application.notification.ApplyNotificationReceiptUseCase -dev.caskeleton.application.notification.ConsentCheckMode -dev.caskeleton.application.notification.EmailRecipientReference -dev.caskeleton.application.notification.InitializeNotificationWriterFencesCommand -dev.caskeleton.application.notification.InitializeNotificationWriterFencesOperation -dev.caskeleton.application.notification.InitializeNotificationWriterFencesResult -dev.caskeleton.application.notification.InitializeNotificationWriterFencesUseCase -dev.caskeleton.application.notification.InlineNotificationAttemptPort -dev.caskeleton.application.notification.NormalizedNotificationReceiptCommand dev.caskeleton.application.notification.Notification -dev.caskeleton.application.notification.NotificationAdmissionClass -dev.caskeleton.application.notification.NotificationAdmissionGateCommand -dev.caskeleton.application.notification.NotificationAdmissionGateUseCase -dev.caskeleton.application.notification.NotificationAdmissionReadinessPort -dev.caskeleton.application.notification.NotificationAppendResult -dev.caskeleton.application.notification.NotificationApplicationException -dev.caskeleton.application.notification.NotificationAttemptId -dev.caskeleton.application.notification.NotificationCanonicalWriterFenceGuard -dev.caskeleton.application.notification.NotificationCanonicalWriterFencePort -dev.caskeleton.application.notification.NotificationCanonicalWriterRouteSet -dev.caskeleton.application.notification.NotificationCapabilityCompatibilityValidator dev.caskeleton.application.notification.NotificationChannel -dev.caskeleton.application.notification.NotificationDeliveryId -dev.caskeleton.application.notification.NotificationDeliveryStorePort -dev.caskeleton.application.notification.NotificationDispatchCommand -dev.caskeleton.application.notification.NotificationDispatchResult -dev.caskeleton.application.notification.NotificationDispatchUseCase -dev.caskeleton.application.notification.NotificationEvidenceTrustSnapshot -dev.caskeleton.application.notification.NotificationFaultScope -dev.caskeleton.application.notification.NotificationFrozenPlan -dev.caskeleton.application.notification.NotificationIntentAppendPort -dev.caskeleton.application.notification.NotificationIntentDraft -dev.caskeleton.application.notification.NotificationIntentId -dev.caskeleton.application.notification.NotificationKindId -dev.caskeleton.application.notification.NotificationKindPolicy -dev.caskeleton.application.notification.NotificationLegacyWriterPermitCommand -dev.caskeleton.application.notification.NotificationLegacyWriterPermitResult -dev.caskeleton.application.notification.NotificationLegacyWriterPermitUseCase -dev.caskeleton.application.notification.NotificationMaintenanceCommand -dev.caskeleton.application.notification.NotificationMaintenanceResult -dev.caskeleton.application.notification.NotificationMaintenanceStorePort -dev.caskeleton.application.notification.NotificationMaintenanceUseCase -dev.caskeleton.application.notification.NotificationMode -dev.caskeleton.application.notification.NotificationOperationsSnapshot -dev.caskeleton.application.notification.NotificationOperationsSnapshotPort -dev.caskeleton.application.notification.NotificationOperationsSnapshotQuery -dev.caskeleton.application.notification.NotificationOperationsSnapshotUseCase -dev.caskeleton.application.notification.NotificationPlanPort -dev.caskeleton.application.notification.NotificationPlanningResult dev.caskeleton.application.notification.NotificationPort -dev.caskeleton.application.notification.NotificationProviderAttemptPort -dev.caskeleton.application.notification.NotificationProviderCapabilityDescriptor -dev.caskeleton.application.notification.NotificationReasonCode -dev.caskeleton.application.notification.NotificationReceiptEventId -dev.caskeleton.application.notification.NotificationReceiptFact -dev.caskeleton.application.notification.NotificationReceiptIngressCapabilityDescriptor -dev.caskeleton.application.notification.NotificationReceiptProjection -dev.caskeleton.application.notification.NotificationReceiptStorePort -dev.caskeleton.application.notification.NotificationRecipientReference -dev.caskeleton.application.notification.NotificationReconciliationPort -dev.caskeleton.application.notification.NotificationRequestResult -dev.caskeleton.application.notification.NotificationRouteId -dev.caskeleton.application.notification.NotificationRouteStrategy -dev.caskeleton.application.notification.NotificationSignedEvidenceHeader -dev.caskeleton.application.notification.NotificationStoreCapabilityDescriptor -dev.caskeleton.application.notification.NotificationTechnicalSuppressionPort -dev.caskeleton.application.notification.NotificationTemplateParameters -dev.caskeleton.application.notification.NotificationTemplateRef -dev.caskeleton.application.notification.NotificationTemplateValue -dev.caskeleton.application.notification.NotificationWriterCutoverPort -dev.caskeleton.application.notification.NotificationWriterInventoryEvidence -dev.caskeleton.application.notification.NotificationWriterInventoryEvidenceVerifierPort -dev.caskeleton.application.notification.NotificationWriterOwnership -dev.caskeleton.application.notification.NotificationWriterQuiescenceAttestationPort -dev.caskeleton.application.notification.NotificationWriterRouteSet -dev.caskeleton.application.notification.ProviderAttemptOutcome -dev.caskeleton.application.notification.ReconcileNotificationDeliveriesCommand -dev.caskeleton.application.notification.ReconcileNotificationDeliveriesResult -dev.caskeleton.application.notification.ReconcileNotificationDeliveriesUseCase -dev.caskeleton.application.notification.RecordNotificationWriterQuiescenceAttestationCommand -dev.caskeleton.application.notification.RecordNotificationWriterQuiescenceAttestationOperation -dev.caskeleton.application.notification.RecordNotificationWriterQuiescenceAttestationResult -dev.caskeleton.application.notification.RecordNotificationWriterQuiescenceAttestationUseCase -dev.caskeleton.application.notification.RetryDisposition -dev.caskeleton.application.notification.SignedNotificationWriterInventoryManifest -dev.caskeleton.application.notification.SignedNotificationWriterQuiescenceManifest -dev.caskeleton.application.notification.SlackAudienceReference -dev.caskeleton.application.notification.SubmissionCertainty -dev.caskeleton.application.notification.SwitchNotificationWriterOwnershipCommand -dev.caskeleton.application.notification.SwitchNotificationWriterOwnershipOperation -dev.caskeleton.application.notification.SwitchNotificationWriterOwnershipResult -dev.caskeleton.application.notification.SwitchNotificationWriterOwnershipUseCase -dev.caskeleton.application.notification.TargetAttemptOutcome -dev.caskeleton.application.notification.TerminalizeExpiredNotificationWriterPermitsCommand -dev.caskeleton.application.notification.TerminalizeExpiredNotificationWriterPermitsOperation -dev.caskeleton.application.notification.TerminalizeExpiredNotificationWriterPermitsResult -dev.caskeleton.application.notification.TerminalizeExpiredNotificationWriterPermitsUseCase dev.caskeleton.application.notification.platform.admin.AdminAccessDeniedException dev.caskeleton.application.notification.platform.admin.AdminActor dev.caskeleton.application.notification.platform.admin.AdminAuthorizationGuard @@ -280,7 +182,6 @@ dev.caskeleton.application.notification.platform.api.NormalizedEventType dev.caskeleton.application.notification.platform.api.NormalizedProviderEvent dev.caskeleton.application.notification.platform.api.NotificationAcceptance dev.caskeleton.application.notification.platform.api.NotificationId -dev.caskeleton.application.notification.platform.api.NotificationOrchestrator dev.caskeleton.application.notification.platform.api.NotificationPlan dev.caskeleton.application.notification.platform.api.NotificationReceipt dev.caskeleton.application.notification.platform.api.NotificationSnapshot @@ -311,31 +212,19 @@ dev.caskeleton.application.notification.platform.api.delivery.DeliveryOutcome dev.caskeleton.application.notification.platform.api.delivery.EvidenceLevel dev.caskeleton.application.notification.platform.api.delivery.RecipientDeliveryState dev.caskeleton.application.notification.platform.api.delivery.SubmissionOutcome -dev.caskeleton.application.notification.platform.api.error.AmbiguousSubmissionException dev.caskeleton.application.notification.platform.api.error.AttachmentIntegrityException dev.caskeleton.application.notification.platform.api.error.AttachmentUnavailableException -dev.caskeleton.application.notification.platform.api.error.CallbackProjectionException dev.caskeleton.application.notification.platform.api.error.CallbackValidationException dev.caskeleton.application.notification.platform.api.error.FailureCategory dev.caskeleton.application.notification.platform.api.error.IdempotencyConflictException -dev.caskeleton.application.notification.platform.api.error.InvalidContactPointException -dev.caskeleton.application.notification.platform.api.error.NotificationCapacityException dev.caskeleton.application.notification.platform.api.error.NotificationException dev.caskeleton.application.notification.platform.api.error.NotificationExpiredException dev.caskeleton.application.notification.platform.api.error.NotificationFailureCode dev.caskeleton.application.notification.platform.api.error.NotificationFailureDescriptor -dev.caskeleton.application.notification.platform.api.error.NotificationSuppressedException dev.caskeleton.application.notification.platform.api.error.NotificationValidationException -dev.caskeleton.application.notification.platform.api.error.ProviderAuthenticationException -dev.caskeleton.application.notification.platform.api.error.ProviderAuthorizationException dev.caskeleton.application.notification.platform.api.error.ProviderConfigurationException dev.caskeleton.application.notification.platform.api.error.ProviderPayloadLimitException -dev.caskeleton.application.notification.platform.api.error.ProviderPermanentException -dev.caskeleton.application.notification.platform.api.error.ProviderRejectedException -dev.caskeleton.application.notification.platform.api.error.ProviderThrottledException -dev.caskeleton.application.notification.platform.api.error.ProviderTransientException dev.caskeleton.application.notification.platform.api.error.ProviderUnavailableException -dev.caskeleton.application.notification.platform.api.error.ReconciliationException dev.caskeleton.application.notification.platform.api.error.TemplateNotFoundException dev.caskeleton.application.notification.platform.api.error.TemplateRenderingException dev.caskeleton.application.notification.platform.api.error.TemplateVariableValidationException @@ -378,7 +267,6 @@ dev.caskeleton.application.notification.platform.contact.MobilePushTarget dev.caskeleton.application.notification.platform.contact.PhoneNumber dev.caskeleton.application.notification.platform.contact.WebPushSubscriptionValue dev.caskeleton.application.notification.platform.dispatch.AcceptNotificationApplicationUseCase -dev.caskeleton.application.notification.platform.dispatch.ApplicationReceiptServiceImpl dev.caskeleton.application.notification.platform.dispatch.AttachmentIntegrityGuard dev.caskeleton.application.notification.platform.dispatch.CancelNotificationApplicationUseCase dev.caskeleton.application.notification.platform.dispatch.CanonicalNotificationPlanEncoder @@ -393,6 +281,7 @@ dev.caskeleton.application.notification.platform.dispatch.DispatchOutcomeRecorde dev.caskeleton.application.notification.platform.dispatch.DispatchPipeline dev.caskeleton.application.notification.platform.dispatch.DuplicateIdempotencyKeyException dev.caskeleton.application.notification.platform.dispatch.GetNotificationApplicationUseCase +dev.caskeleton.application.notification.platform.dispatch.LeaseRecoveryService dev.caskeleton.application.notification.platform.dispatch.MessageDigestPort dev.caskeleton.application.notification.platform.dispatch.NotificationDispatchService dev.caskeleton.application.notification.platform.dispatch.NotificationIdGeneratorPort @@ -423,8 +312,6 @@ dev.caskeleton.application.notification.platform.dispatch.SubmitNotificationAppl dev.caskeleton.application.notification.platform.dispatch.SyntheticEventFingerprint dev.caskeleton.application.notification.platform.dispatch.TemplateRendererRegistry dev.caskeleton.application.notification.platform.dispatch.TenantContextPort -dev.caskeleton.application.notification.platform.email.EmailNotification -dev.caskeleton.application.notification.platform.email.EmailNotifier dev.caskeleton.application.notification.platform.inbox.CreateInboxItemCommand dev.caskeleton.application.notification.platform.inbox.InboxContentCodecPort dev.caskeleton.application.notification.platform.inbox.InboxCursor @@ -512,35 +399,14 @@ dev.caskeleton.application.notification.platform.provider.ReconciliationCapabili dev.caskeleton.application.notification.platform.provider.ReconciliationResult dev.caskeleton.application.notification.platform.provider.ResolvedAttachment dev.caskeleton.application.notification.platform.provider.TraceContext -dev.caskeleton.application.notification.platform.push.ApplicationIdentity -dev.caskeleton.application.notification.platform.push.ApplicationReceipt -dev.caskeleton.application.notification.platform.push.ApplicationReceiptService -dev.caskeleton.application.notification.platform.push.MobilePushNotification -dev.caskeleton.application.notification.platform.push.MobilePushNotifier -dev.caskeleton.application.notification.platform.push.ReceiptAuthorizationException -dev.caskeleton.application.notification.platform.push.ReceiptKind -dev.caskeleton.application.notification.platform.push.ReceiptResult dev.caskeleton.application.notification.platform.security.AccessContext dev.caskeleton.application.notification.platform.security.ContactPointProtector dev.caskeleton.application.notification.platform.security.NotificationPayloadProtection dev.caskeleton.application.notification.platform.security.NotificationPayloadUnreadableException -dev.caskeleton.application.notification.platform.security.NotificationRedactor dev.caskeleton.application.notification.platform.security.ProtectedContactPoint -dev.caskeleton.application.notification.platform.security.SafeDiagnosticContext dev.caskeleton.application.notification.platform.security.SecretKeyMaterial dev.caskeleton.application.notification.platform.security.SecretMaterialProvider dev.caskeleton.application.notification.platform.security.SecretPurpose -dev.caskeleton.application.notification.platform.security.SensitiveValueClassifier -dev.caskeleton.application.notification.platform.security.SensitiveValueKind -dev.caskeleton.application.notification.platform.security.UnsafeDiagnosticFieldException -dev.caskeleton.application.notification.platform.sms.E164PhoneNumberParser -dev.caskeleton.application.notification.platform.sms.GsmAlphabet -dev.caskeleton.application.notification.platform.sms.InvalidPhoneNumberException -dev.caskeleton.application.notification.platform.sms.SmsEncoding -dev.caskeleton.application.notification.platform.sms.SmsEstimate -dev.caskeleton.application.notification.platform.sms.SmsNotification -dev.caskeleton.application.notification.platform.sms.SmsNotifier -dev.caskeleton.application.notification.platform.sms.SmsSegmentEstimator dev.caskeleton.application.notification.platform.template.NotificationTemplateRenderer dev.caskeleton.application.notification.platform.template.NotificationTemplateVersion dev.caskeleton.application.notification.platform.template.RenderCommand @@ -553,5 +419,3 @@ dev.caskeleton.application.notification.platform.template.TemplateStatus dev.caskeleton.application.notification.platform.template.TemplateVariableValidator dev.caskeleton.application.notification.platform.template.TemplateVersionConflictException dev.caskeleton.application.notification.platform.template.VariableSchema -dev.caskeleton.application.notification.platform.webpush.WebPushNotification -dev.caskeleton.application.notification.platform.webpush.WebPushNotifier diff --git a/docs/notification/at-rest-threat-model.md b/docs/notification/at-rest-threat-model.md index 7a32a722..03b90b07 100644 --- a/docs/notification/at-rest-threat-model.md +++ b/docs/notification/at-rest-threat-model.md @@ -104,7 +104,7 @@ the three they achieved. one thing — `AesGcmCallbackPayloadProtection`, which protects raw callback bodies — and by nothing on the accept path. Demanding it would make a deployment supply a key that protects nothing while the payload it appears to be about stays in plaintext. The repository already has one defect of that -exact shape: `backend.graphql.cursor.key-ids`, which production refuses to start without and which no +exact shape: `backend.graphql.cursor.key-ids` (key removed 2026-09-25), which production refuses to start without and which no code signs a cursor with (GQL-INT-003). Adding a second would make the pattern a habit. ## Consequence diff --git a/docs/notification/configuration-reference.md b/docs/notification/configuration-reference.md index b68c1664..c07761ac 100644 --- a/docs/notification/configuration-reference.md +++ b/docs/notification/configuration-reference.md @@ -1,20 +1,25 @@ # Configuration reference The notification delivery platform binds under `ca-skeleton.notification.platform`. The tree lives in -`src/app-bootstrap/src/main/resources/application.yml`, disabled by default, and every value carries -an inline default so a deployment that leaves the platform off supplies nothing. +`src/composition/notification-platform/src/main/resources/config/module-defaults/notification.yml`, +which the support leaf's `ModuleDefaultsEnvironmentPostProcessor` loads at the lowest precedence, +so an application without the module carries none of it. The module is in no default composition: a +service selects it with `runtimeOnly project(':composition:notification-platform')` (plus the +persistence-jpa line) in `app-bootstrap/build.gradle`, and it is on when present. Every value carries +an inline default, so a deployment that switches the platform off supplies nothing. Until 2026-08-15 this page named properties the binding did not have — `max-retry-concurrency`, `scheduler-poll-interval`, `callback-worker-concurrency` — and omitted three it did. There was no tree in `application.yml` at all, so the only way to configure the platform was to guess environment -variable names from Boot's relaxed binding. `./gradlew verifyNotificationConfiguration` now fails -when this page, the YAML tree and `docs/registries/env-keys.yaml` disagree. +variable names from Boot's relaxed binding. `NotificationEnvironmentRegistryTest` +(`:composition:notification-platform:test`) now fails when the shipped YAML and +`docs/registries/env-keys.yaml` disagree. ## Master switch | Property | Environment variable | Default | Meaning | |---|---|---|---| -| `enabled` | `APP_NOTIFICATION_PLATFORM_ENABLED` | `false` | Binds nothing at all while false: no runtime, no schema check, no scheduler thread, no secret required | +| `enabled` | `APP_NOTIFICATION_PLATFORM_ENABLED` | `true` | On while the module is present. `false` binds nothing at all: no runtime, no schema check, no scheduler thread, no secret required | | `mode` | `APP_NOTIFICATION_PLATFORM_MODE` | `SERVING` | `SERVING` refuses to start without a working provider; `INGEST_ONLY` stores requests and does not dispatch | ## Dispatch @@ -40,7 +45,7 @@ still waiting on gets claimed by a second worker, and the recipient receives the |---|---|---|---| | `callbacks.enabled` | `APP_NOTIFICATION_PLATFORM_CALLBACKS_ENABLED` | `false` | boolean | | `callbacks.max-body-bytes` | `APP_NOTIFICATION_PLATFORM_CALLBACK_MAX_BODY_BYTES` | `65508` | 1..65508 | -| `callbacks.replay-skew` | `APP_NOTIFICATION_PLATFORM_CALLBACK_REPLAY_SKEW` | `5m` | positive | +| `callbacks.replay-skew` | `APP_NOTIFICATION_PLATFORM_CALLBACK_REPLAY_SKEW` | `5m` | positive; SNS messages whose `Timestamp` is further than this from receipt, either way, are rejected | | `callbacks.trusted-proxies` | `APP_NOTIFICATION_PLATFORM_CALLBACK_TRUSTED_PROXIES` | *(empty)* | CSV of peer addresses | 여러 provider가 요청 URL에 서명하므로, 그 URL을 잘못 재구성하면 정상 webhook이 전부 서명 실패가 된다. @@ -87,6 +92,7 @@ An enabled SES profile adds a typed `ses` block: | `ses.sender-identity` | verified SES From identity | | `ses.access-key-id` | AWS access key id; identifier only, not secret material | | `ses.configuration-set` | optional SES configuration-set name | +| `ses.allowed-topic-arns` | SNS topic ARNs whose SES events this profile accepts (`APP_NOTIFICATION_PLATFORM_SES_ALLOWED_TOPIC_ARNS`, comma-separated). Required when `callbacks.enabled=true`: binding fails without it, because a valid SNS signature only proves AWS sent the message and anyone can own a topic | | `credential-profile` | key id for the secret access-key material; generation 1 is activated at assembly | The shipped reference profile is `providers.ses` and is disabled by default. It is controlled by diff --git a/docs/notification/evidence-manifest.json b/docs/notification/evidence-manifest.json index d97dcedc..3fe4076c 100644 --- a/docs/notification/evidence-manifest.json +++ b/docs/notification/evidence-manifest.json @@ -6,7 +6,7 @@ "ran no restart, and a provider sandbox job whose entire body was two echo statements behind", "continue-on-error. So the strongest claim in the document rested on the weakest evidence in", "the pipeline, and nothing connected the two.", - "verifyNotificationEvidence reads this file, checks that every claim marked satisfied names", + "NotificationEvidenceVerifierTest reads this file, checks that every claim marked satisfied names", "test classes that exist, and refuses a grade whose claims are not all satisfied." ], "claims": { diff --git a/docs/notification/migration-guide.md b/docs/notification/migration-guide.md index 7880e87e..9e50ee4b 100644 --- a/docs/notification/migration-guide.md +++ b/docs/notification/migration-guide.md @@ -37,11 +37,9 @@ R1 public type 100개를 어떻게 할 것인지 다루지 않았다. 그래서 문서 어디에도 답이 없었다. - **canonical은 `..notification.platform..`이다.** NOTIF-ADR-005가 근거와 함께 정한다. -- **application R1 public contract는 남지만 새 production consumer를 받지 않는다.** 삭제 계획은 - 별개이며, R0 삭제와 함께 사라지지 않는다. +- **application R1 public type은 2026-09-25에 삭제했다.** production consumer가 0건이었다. 남은 것은 + 단순 알림 포트 `NotificationPort`·`Notification`·`NotificationChannel`뿐이다. - R1을 따라 만들어졌지만 composition root에서 한 번도 조립되지 않았던 outbound adapter의 - `catalog/`, `provider/`, `template/` 실험 구현은 제거했다. 실제 runtime은 + `catalog/`, `provider/`, `template/` 실험 구현도 제거했다. 실제 runtime은 `dev.caskeleton.adapter.outbound.notification.platform..`만 사용한다. -- **전수 분류표는 `docs/notification/module-mapping.md`에 있다** (replace / bridge / retain / delete). -- **두 namespace 간 production dependency는 0건이며 ArchUnit이 강제한다.** 변환이 필요하면 - `dev.caskeleton.application.notification.compatibility.r1` 한 곳에만 둔다. +- 삭제 목록과 마지막 커밋은 `docs/capability-status.md`의 「제거된 코드」 표에 있다. diff --git a/docs/notification/module-mapping.md b/docs/notification/module-mapping.md index 7b2e6515..2effd41a 100644 --- a/docs/notification/module-mapping.md +++ b/docs/notification/module-mapping.md @@ -30,13 +30,9 @@ that owns its responsibility. No public contract, evidence rule, or reliability | `notification-policy` | `application-core` | `…platform.policy` | | `notification-provider-spi` | `application-core` | `…platform.provider` | | `notification-callback-api` | `application-core` | `…platform.callback` | -| `notification-email-api` | `application-core` | `…platform.email` | -| `notification-sms-api` | `application-core` | `…platform.sms` | -| `notification-push-api` | `application-core` | `…platform.push` | -| `notification-webpush` (API half) | `application-core` | `…platform.webpush` | | `notification-inbox-api` | `application-core` | `…platform.inbox` | | `notification-admin-api` | `application-core` | `…platform.admin` | -| `notification-security` (ports + redaction) | `application-core` | `…platform.security` | +| `notification-security` (ports) | `application-core` | `…platform.security` | | `notification-observability` (ports) | `application-core` | `…platform.observation` | | `notification-dispatch-runtime` | `adapter:outbound:notification` | `dev.caskeleton.adapter.outbound.notification.platform.dispatch` | | `notification-security` (AES-GCM/HMAC impl) | `adapter:outbound:notification` | `…platform.security` | @@ -50,12 +46,12 @@ that owns its responsibility. No public contract, evidence rule, or reliability | `notification-webhook-extension` | `adapter:outbound:notification` | `…platform.provider.webhook` | | `notification-observability` (Micrometer impl) | `adapter:outbound:notification` | `…platform.observation` | | `notification-admin-runtime` | `adapter:outbound:notification` | `…platform.admin` | -| `notification-reactor` | `adapter:outbound:notification` | `…platform.reactor` | | `notification-spring-boot-starter` | `adapter:outbound:notification` | `…platform.autoconfigure` | | `notification-persistence-jpa` | `adapter:outbound:persistence-jpa` | `dev.caskeleton.adapter.outbound.persistence.notification.platform` | | `notification-inbox-jpa` | `adapter:outbound:persistence-jpa` | `…persistence.notification.platform.inbox` | -| `notification-callback-mvc` | `adapter:inbound:web` | `dev.caskeleton.adapter.inbound.web.notification.platform.callback` | -| `notification-callback-webflux` | `adapter:inbound:web` | `…callback.reactive` | +| `notification-callback-mvc` | `adapter:inbound:web-notification` | `dev.caskeleton.adapter.inbound.web.notification.platform.callback` | +| `notification-submission-mvc` | `adapter:inbound:web-notification` | `dev.caskeleton.adapter.inbound.web.notification.platform.submission` | +| application composition (use cases, callback bridge, `config/module-defaults/notification.yml`) | `composition:notification-platform` | `dev.caskeleton.composition.notification` | | `notification-testkit` | test source sets of the owning leaves | `…platform.testkit` | ## Dependency-direction consequences @@ -66,9 +62,11 @@ by the leaf DAG that the registry already enforces: ```text application-core (all *-api, provider SPI, policy, callback contracts) ↑ ↑ ↑ -adapter:outbound:notification adapter:outbound:persistence-jpa adapter:inbound:web - ↑ ↑ ↑ - app-bootstrap +adapter:outbound:notification adapter:outbound:persistence-jpa adapter:inbound:web-notification + ↑ ↑ (→ adapter:inbound:web) + └──────────── composition:notification-platform ────┘ + ↑ + app-bootstrap (one line) ``` Two plan edges cannot be expressed as project edges in this repository, and are replaced by ports: @@ -111,24 +109,11 @@ reachability is SMTP and SES for dispatch, with SES also available for callback provider packages are extension assets until a composition contributes a `ProviderRuntimeAssembler` with the settings and secret sources that family requires. See `support-matrix.md` for the explicit table. -## R1 public type disposition (NOTIF-ADR-005) +## R1 public types (NOTIF-ADR-005) -NOTIF-ADR-005 makes `..notification.platform..` canonical and keeps the R1 namespace in place -without new consumers. The ADR owns the rule; this table owns the list, so the two do not drift -apart by being written twice. - -`NOTIFICATION_R1_AND_PLATFORM_DO_NOT_DEPEND_ON_EACH_OTHER` in `ApplicationBoundaryArchitectureTest` enforces the -boundary: production dependencies between the two namespaces are zero, and the only permitted -exception is `dev.caskeleton.application.notification.compatibility.r1`. - -| Disposition | Meaning | Types | -| --- | --- | --- | -| `replace` (27) | the platform has an equivalent; new consumers use it | `ApplyNotificationReceiptCommand`, `ApplyNotificationReceiptResult`, `ApplyNotificationReceiptUseCase`, `Channel`, `InlineNotificationAttemptPort`, `NormalizedNotificationReceiptCommand`, `NotificationAttemptId`, `NotificationDeliveryId`, `NotificationDeliveryStorePort`, `NotificationDispatchCommand`, `NotificationDispatchResult`, `NotificationDispatchUseCase`, `NotificationEvidenceTrustSnapshot`, `NotificationFrozenPlan`, `NotificationPlanPort`, `NotificationPlanningResult`, `NotificationProviderAttemptPort`, `NotificationReceiptEventId`, `NotificationReceiptFact`, `NotificationReceiptIngressCapabilityDescriptor`, `NotificationReceiptProjection`, `NotificationReceiptStorePort`, `NotificationSignedEvidenceHeader`, `NotificationWriterInventoryEvidence`, `NotificationWriterInventoryEvidenceVerifierPort`, `ProviderAttemptOutcome`, `TargetAttemptOutcome` | -| `bridge` (28) | conversion needed if an R1 caller remains; conversion lives only in the ACL | `InitializeNotificationWriterFencesCommand`, `InitializeNotificationWriterFencesOperation`, `InitializeNotificationWriterFencesResult`, `InitializeNotificationWriterFencesUseCase`, `NotificationAdmissionGateCommand`, `NotificationAdmissionGateUseCase`, `NotificationAppendResult`, `NotificationLegacyWriterPermitCommand`, `NotificationLegacyWriterPermitResult`, `NotificationLegacyWriterPermitUseCase`, `NotificationMaintenanceCommand`, `NotificationMaintenanceResult`, `NotificationMaintenanceUseCase`, `NotificationOperationsSnapshot`, `NotificationOperationsSnapshotQuery`, `NotificationOperationsSnapshotUseCase`, `NotificationRequestResult`, `ReconcileNotificationDeliveriesCommand`, `ReconcileNotificationDeliveriesResult`, `ReconcileNotificationDeliveriesUseCase`, `SwitchNotificationWriterOwnershipCommand`, `SwitchNotificationWriterOwnershipOperation`, `SwitchNotificationWriterOwnershipResult`, `SwitchNotificationWriterOwnershipUseCase`, `TerminalizeExpiredNotificationWriterPermitsCommand`, `TerminalizeExpiredNotificationWriterPermitsOperation`, `TerminalizeExpiredNotificationWriterPermitsResult`, `TerminalizeExpiredNotificationWriterPermitsUseCase` | -| `retain` (45) | a concern the platform does not cover; left as it is | `ConsentCheckMode`, `EmailRecipientReference`, `Notification`, `NotificationAdmissionClass`, `NotificationAdmissionReadinessPort`, `NotificationApplicationException`, `NotificationCanonicalWriterFenceGuard`, `NotificationCanonicalWriterFencePort`, `NotificationCanonicalWriterRouteSet`, `NotificationCapabilityCompatibilityValidator`, `NotificationChannel`, `NotificationFaultScope`, `NotificationIntentAppendPort`, `NotificationIntentDraft`, `NotificationIntentId`, `NotificationKindId`, `NotificationKindPolicy`, `NotificationMaintenanceStorePort`, `NotificationMode`, `NotificationOperationsSnapshotPort`, `NotificationPort`, `NotificationProviderCapabilityDescriptor`, `NotificationReasonCode`, `NotificationRecipientReference`, `NotificationReconciliationPort`, `NotificationRouteId`, `NotificationRouteStrategy`, `NotificationStoreCapabilityDescriptor`, `NotificationTechnicalSuppressionPort`, `NotificationTemplateParameters`, `NotificationTemplateRef`, `NotificationTemplateValue`, `NotificationWriterCutoverPort`, `NotificationWriterOwnership`, `NotificationWriterQuiescenceAttestationPort`, `NotificationWriterRouteSet`, `RecordNotificationWriterQuiescenceAttestationCommand`, `RecordNotificationWriterQuiescenceAttestationOperation`, `RecordNotificationWriterQuiescenceAttestationResult`, `RecordNotificationWriterQuiescenceAttestationUseCase`, `RetryDisposition`, `SignedNotificationWriterInventoryManifest`, `SignedNotificationWriterQuiescenceManifest`, `SlackAudienceReference`, `SubmissionCertainty` | - -Total: 100 public types, every one classified. - -No type carries `@Deprecated(forRemoval = true)`: no removal release is fixed, and -`forRemoval` without a date is a promise the codebase cannot keep. The boundary is -enforced by the ArchUnit rule instead. +NOTIF-ADR-005 made `..notification.platform..` canonical. The R1 types directly under +`dev.caskeleton.application.notification` had no production consumer and were removed on +2026-09-25, together with the ArchUnit rule that kept the two namespaces apart. What remains there +is the simple notification port the adapter core implements — `NotificationPort`, `Notification`, +`NotificationChannel`. The removed types and their last commit are listed in +`docs/capability-status.md` under "제거된 코드". diff --git a/docs/notification/security-privacy.md b/docs/notification/security-privacy.md index cf068210..0bbf9e4f 100644 --- a/docs/notification/security-privacy.md +++ b/docs/notification/security-privacy.md @@ -28,10 +28,8 @@ would turn every historical row into a tag failure at read time. Addresses, tokens, Web Push endpoints and keys, message bodies, template variables, provider credentials, unsubscribe tokens, attachment URLs, raw callback payloads and raw provider request ids. -Two mechanisms enforce this rather than convention: - -- `CardinalityGuard` validates every metric tag against a closed allowlist. -- `SafeDiagnosticContext` rejects any structured-diagnostic field outside its allowlist. +`CardinalityGuard` enforces this for metrics rather than convention: it validates every metric tag +against a closed allowlist. An allowlist rather than a denylist, because the failure mode of a denylist is that the one field nobody thought of is the one that leaks. diff --git a/docs/notification/support-matrix.md b/docs/notification/support-matrix.md index 54dec6d3..67d91041 100644 --- a/docs/notification/support-matrix.md +++ b/docs/notification/support-matrix.md @@ -4,8 +4,8 @@ What each channel can actually prove, and what the platform refuses to claim. The grade column is not an opinion. `docs/notification/evidence-manifest.json` declares which claims each grade requires and which executable artifact proves each claim, and -`./gradlew verifyNotificationEvidence` refuses a grade whose claims are not all backed by a file that -exists. Raising a grade means adding the artifact first. +`NotificationEvidenceVerifierTest` (in `:adapter:outbound:notification:test`) refuses a grade whose +claims are not all backed by a file that exists. Raising a grade means adding the artifact first. Five channels read `Stable` until 2026-08-15. Nothing in the pipeline had ever sent a request to a provider — the sandbox job's whole body was two `echo` statements behind `continue-on-error` — and @@ -32,7 +32,7 @@ implementation is selectable in the default composition. Dispatch reachability i | Provider family | Dispatch assembler in shipped composition | Callback assembler | Current use | |---|---|---|---| | SMTP | **yes** | no | EMAIL dispatch reference family | -| SES | **yes** | **yes** | EMAIL dispatch + SNS callback ingestion; disabled reference profile ships in `config/notification.yml` | +| SES | **yes** | **yes** | EMAIL dispatch + SNS callback ingestion; disabled reference profile ships in `config/module-defaults/notification.yml` (`composition:notification-platform`) | | Twilio | no | no | contract implementation / extension wiring | | FCM | no | no | contract implementation / extension wiring | | APNs | no | no | contract implementation / extension wiring | diff --git a/docs/objectstorage/env-fields.yaml b/docs/objectstorage/env-fields.yaml index 4101c498..3e5c053d 100644 --- a/docs/objectstorage/env-fields.yaml +++ b/docs/objectstorage/env-fields.yaml @@ -131,19 +131,5 @@ fields: env: APP_OBJECT_STORAGE_LEGACY_PATH_STYLE_ACCESS - field: legacy.auto-create-bucket env: APP_OBJECT_STORAGE_LEGACY_AUTO_CREATE_BUCKET - - field: legacy-adoption.enabled - env: APP_OBJECT_STORAGE_LEGACY_ADOPTION_ENABLED - - field: legacy-adoption.mode - env: APP_OBJECT_STORAGE_LEGACY_ADOPTION_MODE - - field: legacy-adoption.report-path - env: APP_OBJECT_STORAGE_LEGACY_ADOPTION_REPORT_PATH - - field: legacy-adoption.reviewed-manifest-path - env: APP_OBJECT_STORAGE_LEGACY_ADOPTION_REVIEWED_MANIFEST_PATH - - field: legacy-adoption.reviewed-manifest-sha256 - env: APP_OBJECT_STORAGE_LEGACY_ADOPTION_REVIEWED_MANIFEST_SHA256 - - field: legacy-adoption.batch-size - env: APP_OBJECT_STORAGE_LEGACY_ADOPTION_BATCH_SIZE - - field: legacy-adoption.operation-timeout - env: APP_OBJECT_STORAGE_LEGACY_ADOPTION_OPERATION_TIMEOUT - field: scan-maintenance.enabled env: APP_OBJECT_STORAGE_SCAN_MAINTENANCE_ENABLED diff --git a/docs/redis/command-policy.md b/docs/redis/command-policy.md index 5f4a34a3..2aa5c325 100644 --- a/docs/redis/command-policy.md +++ b/docs/redis/command-policy.md @@ -1,6 +1,6 @@ # Command policy -`src/adapter/outbound/cache-redis/src/main/resources/redis-sdk/redis-command-policy.yml` is the +`src/adapter/outbound/redis-sdk/src/main/resources/redis-sdk/redis-command-policy.yml` is the single source of truth for what this SDK is willing to do with each Redis command. Official server metadata decides what a command *is*; this file decides what we allow. diff --git a/docs/redis/upgrade-guide.md b/docs/redis/upgrade-guide.md index 0b92940e..a2c5d21c 100644 --- a/docs/redis/upgrade-guide.md +++ b/docs/redis/upgrade-guide.md @@ -7,12 +7,16 @@ exists because skipping it produces a specific failure that only shows up in pro ## 1. Command metadata diff -Run the catalog drift check against the new server. Every command the server reports must be -classified in `src/adapter/outbound/cache-redis/src/main/resources/redis-sdk/redis-command-policy.yml`. +Compare `COMMAND DOCS` / `COMMAND INFO` from the new server with the policy by hand: every command +the server reports must be classified in +`src/adapter/outbound/redis-sdk/src/main/resources/redis-sdk/redis-command-policy.yml`, and every +key specification, ACL category and deprecation the policy relies on must still match. There is no +automated diff: `RedisCommandMetadataDiff` compared against server metadata nothing ever fetched, +and was removed (see `docs/capability-status.md`). *Why:* an unclassified command is refused by `CommandPolicyGuard`, so a server that grew a command does not create a hole — but a command whose **risk changed upstream** and is still classified R1 -here does. The diff is what surfaces that. +here does. The comparison is what surfaces that. ## 2. ACL regression diff --git a/docs/registries/env-keys.yaml b/docs/registries/env-keys.yaml index 33c980ef..15826ed0 100644 --- a/docs/registries/env-keys.yaml +++ b/docs/registries/env-keys.yaml @@ -1,7 +1,7 @@ # Registry: Env Keys # Schema owner: feature-contract-registry-governance # Owner branch: feature-env-driven-runtime-configuration -# Last updated: 2026-07-28 +# Last updated: 2026-09-25 # # Conventions: # - Application-owned env uses `APP_` prefix, fully unified (D2, 2026-06-05): @@ -1603,8 +1603,8 @@ env_keys: required_test: rate-limit-contract:cleanup-grace-bounded - name: APP_IDEMPOTENCY_TTL - # source: feature-rate-limit-idempotency-contract 2026-05-22 - # "idempotency TTL default = 24h. long-running use case는 use case 선언으로 72h까지 override 가능" + # ca-skeleton.capabilities.idempotency.replay-ttl: how long a completed response stays + # replayable. One value for every provider; IdempotencySettings refuses more than 72h at startup. type: duration default: 24h allowed_values: null @@ -1617,17 +1617,21 @@ env_keys: required_test: idempotency-contract:ttl-applied - name: APP_IDEMPOTENCY_PROVIDER - # postgresql selects the owner-safe V2 store on the primary data source. Provider selection is - # explicit and disabled by default; no implementation wins merely by being on the classpath. + # ca-skeleton.capabilities.idempotency.provider. redis and postgresql each contribute only the + # store; app-bootstrap builds the one IdempotencyExecutor and refuses startup unless exactly one + # store exists. postgresql uses the primary data source, applies its Flyway streams at startup + # and refuses a non-PostgreSQL data source, so bootRunH2 runs with disabled or redis. Selection + # is explicit and disabled by default; no implementation wins merely by being on the classpath. + # 2026-09-25: jdbc (the V1 store) was removed; a deployment still setting it fails to bind. type: enum default: disabled - allowed_values: [disabled, jdbc, redis, postgresql] + allowed_values: [disabled, redis, postgresql] classification: public-config required: false reload_policy: restart-only owner_branch: redis-production-capability-completion validation: enum_strict - compatibility_impact: additive + compatibility_impact: breaking required_test: redis-idempotency-contract:provider-exclusive - name: APP_IDEMPOTENCY_REDIS_KEY_HMAC_SECRET @@ -1756,14 +1760,16 @@ env_keys: required_test: redis-cache:canonical-cache-role-composition - name: APP_REDIS_ENABLED - # The single global Redis activation switch (property app.redis.enabled). + # 2026-09-25 capability packaging: the cache-redis module is on when present (its + # config/module-defaults/cache-redis.yml maps this key with default true); false is the explicit + # off. Absent from the build is the ordinary off state. # False loads no Redis settings, requires no Redis secret, and creates no client, connection, # thread or health contributor. Role selectors choose which capabilities compose once Redis is - # on; none of them is a second master switch. + # on; none of them is a second on/off key. property: app.redis.enabled - owner_module: app-bootstrap + owner_module: adapter-outbound-cache-redis type: boolean - default: false + default: true allowed_values: [true, false] classification: public-config required: false @@ -1772,7 +1778,7 @@ env_keys: owner_branch: redis-optionality-and-composition validation: boolean_strict compatibility_impact: behavior-change - required_test: redis-optionality:global-switch-off-creates-nothing + required_test: redis-capability-activation:the-switch-off-leaves-no-redis-bean-and-needs-no-redis - name: APP_CACHE_REDIS_POSITIVE_HARD_TTL @@ -1879,52 +1885,6 @@ env_keys: compatibility_impact: additive required_test: redis-sdk:typed-settings-bound-and-validated - - name: APP_REDIS_ADVANCED_ENABLED - property: app.redis.advanced.enabled - owner_module: adapter-outbound-redis-runtime - type: boolean - default: false - allowed_values: [true, false] - classification: public-config - required: false - required_when: app.redis.enabled=true - reload_policy: restart-only - owner_branch: redis-optionality-and-composition - validation: boolean_strict - compatibility_impact: additive - required_test: redis-sdk:typed-settings-bound-and-validated - - - name: APP_REDIS_ADVANCED_POLICIES - property: app.redis.advanced.policies - owner_module: adapter-outbound-redis-runtime - type: csv - default: "" - allowed_values: null - classification: public-config - required: false - required_when: app.redis.enabled=true - reload_policy: restart-only - owner_branch: redis-optionality-and-composition - validation: csv_nonempty - compatibility_impact: additive - required_test: redis-sdk:typed-settings-bound-and-validated - - - name: APP_REDIS_BLOCKING_MAX_BLOCK - # Hard ceiling on a server-side block; zero would be unbounded. - property: app.redis.blocking.max-block - owner_module: adapter-outbound-redis-runtime - type: duration - default: "30s" - allowed_values: null - classification: public-config - required: false - required_when: app.redis.enabled=true - reload_policy: restart-only - owner_branch: redis-optionality-and-composition - validation: duration_strict - compatibility_impact: additive - required_test: redis-sdk:typed-settings-bound-and-validated - - name: APP_REDIS_BLOCKING_MAX_CONNECTIONS property: app.redis.blocking.max-connections owner_module: adapter-outbound-redis-runtime @@ -1956,171 +1916,6 @@ env_keys: compatibility_impact: additive required_test: redis-sdk:typed-settings-bound-and-validated - - name: APP_REDIS_LIMITS_MAX_BATCH_COMMANDS - property: app.redis.limits.max-batch-commands - owner_module: adapter-outbound-redis-runtime - type: integer - default: 500 - allowed_values: null - classification: public-config - required: false - required_when: app.redis.enabled=true - reload_policy: restart-only - owner_branch: redis-optionality-and-composition - validation: positive_integer - compatibility_impact: additive - required_test: redis-sdk:typed-settings-bound-and-validated - - - name: APP_REDIS_LIMITS_MAX_BATCH_REPLY_BYTES - property: app.redis.limits.max-batch-reply-bytes - owner_module: adapter-outbound-redis-runtime - type: integer - default: 16777216 - allowed_values: null - classification: public-config - required: false - required_when: app.redis.enabled=true - reload_policy: restart-only - owner_branch: redis-optionality-and-composition - validation: positive_integer - compatibility_impact: additive - required_test: redis-sdk:typed-settings-bound-and-validated - - - name: APP_REDIS_LIMITS_MAX_BATCH_REQUEST_BYTES - property: app.redis.limits.max-batch-request-bytes - owner_module: adapter-outbound-redis-runtime - type: integer - default: 4194304 - allowed_values: null - classification: public-config - required: false - required_when: app.redis.enabled=true - reload_policy: restart-only - owner_branch: redis-optionality-and-composition - validation: positive_integer - compatibility_impact: additive - required_test: redis-sdk:typed-settings-bound-and-validated - - - name: APP_REDIS_LIMITS_MAX_BITMAP_OFFSET - property: app.redis.limits.max-bitmap-offset - owner_module: adapter-outbound-redis-runtime - type: integer - default: 10000000 - allowed_values: null - classification: public-config - required: false - required_when: app.redis.enabled=true - reload_policy: restart-only - owner_branch: redis-optionality-and-composition - validation: positive_integer - compatibility_impact: additive - required_test: redis-sdk:typed-settings-bound-and-validated - - - name: APP_REDIS_LIMITS_MAX_COLLECTION_ELEMENTS - property: app.redis.limits.max-collection-elements - owner_module: adapter-outbound-redis-runtime - type: integer - default: 1000 - allowed_values: null - classification: public-config - required: false - required_when: app.redis.enabled=true - reload_policy: restart-only - owner_branch: redis-optionality-and-composition - validation: positive_integer - compatibility_impact: additive - required_test: redis-sdk:typed-settings-bound-and-validated - - - name: APP_REDIS_LIMITS_MAX_HASH_FIELD_VALUE_BYTES - property: app.redis.limits.max-hash-field-value-bytes - owner_module: adapter-outbound-redis-runtime - type: integer - default: 524288 - allowed_values: null - classification: public-config - required: false - required_when: app.redis.enabled=true - reload_policy: restart-only - owner_branch: redis-optionality-and-composition - validation: positive_integer - compatibility_impact: additive - required_test: redis-sdk:typed-settings-bound-and-validated - - - name: APP_REDIS_LIMITS_MAX_KEY_BYTES - property: app.redis.limits.max-key-bytes - owner_module: adapter-outbound-redis-runtime - type: integer - default: 512 - allowed_values: null - classification: public-config - required: false - required_when: app.redis.enabled=true - reload_policy: restart-only - owner_branch: redis-optionality-and-composition - validation: positive_integer - compatibility_impact: additive - required_test: redis-sdk:typed-settings-bound-and-validated - - - name: APP_REDIS_LIMITS_MAX_SCAN_COUNT - property: app.redis.limits.max-scan-count - owner_module: adapter-outbound-redis-runtime - type: integer - default: 500 - allowed_values: null - classification: public-config - required: false - required_when: app.redis.enabled=true - reload_policy: restart-only - owner_branch: redis-optionality-and-composition - validation: positive_integer - compatibility_impact: additive - required_test: redis-sdk:typed-settings-bound-and-validated - - - name: APP_REDIS_LIMITS_MAX_STREAM_PAYLOAD_BYTES - property: app.redis.limits.max-stream-payload-bytes - owner_module: adapter-outbound-redis-runtime - type: integer - default: 262144 - allowed_values: null - classification: public-config - required: false - required_when: app.redis.enabled=true - reload_policy: restart-only - owner_branch: redis-optionality-and-composition - validation: positive_integer - compatibility_impact: additive - required_test: redis-sdk:typed-settings-bound-and-validated - - - name: APP_REDIS_LIMITS_MAX_VALUE_BYTES - property: app.redis.limits.max-value-bytes - owner_module: adapter-outbound-redis-runtime - type: integer - default: 1048576 - allowed_values: null - classification: public-config - required: false - required_when: app.redis.enabled=true - reload_policy: restart-only - owner_branch: redis-optionality-and-composition - validation: positive_integer - compatibility_impact: additive - required_test: redis-sdk:typed-settings-bound-and-validated - - - name: APP_REDIS_LIMITS_OFFLINE_QUEUE_COMMANDS - property: app.redis.limits.offline-queue-commands - owner_module: adapter-outbound-redis-runtime - type: integer - default: 1000 - allowed_values: null - classification: public-config - required: false - required_when: app.redis.enabled=true - reload_policy: restart-only - owner_branch: redis-optionality-and-composition - validation: positive_integer - compatibility_impact: additive - required_test: redis-sdk:typed-settings-bound-and-validated - - name: APP_REDIS_MODE # standalone | sentinel | cluster. property: app.redis.mode @@ -2198,67 +1993,6 @@ env_keys: compatibility_impact: additive required_test: redis-sdk:typed-settings-bound-and-validated - - name: APP_REDIS_RAW_CREDENTIAL_REFERENCE - property: app.redis.raw.credential-reference - owner_module: adapter-outbound-redis-runtime - type: string - default: null - allowed_values: null - classification: sensitive-config - required: false - required_when: app.redis.raw.enabled=true - reload_policy: restart-only - owner_branch: redis-optionality-and-composition - validation: nonblank_when_required - compatibility_impact: additive - required_test: redis-sdk:typed-settings-bound-and-validated - - - name: APP_REDIS_RAW_ENABLED - property: app.redis.raw.enabled - owner_module: adapter-outbound-redis-runtime - type: boolean - default: false - allowed_values: [true, false] - classification: public-config - required: false - required_when: app.redis.enabled=true - reload_policy: restart-only - owner_branch: redis-optionality-and-composition - validation: boolean_strict - compatibility_impact: additive - required_test: redis-sdk:typed-settings-bound-and-validated - - - name: APP_REDIS_RAW_POLICY_RESOURCE - # Classpath resource listing every approved raw command. Absent resource fails startup. - property: app.redis.raw.policy-resource - owner_module: adapter-outbound-redis-runtime - type: string - default: "classpath:redis-sdk/raw-command-allowlist.yml" - allowed_values: null - classification: public-config - required: false - required_when: app.redis.raw.enabled=true - reload_policy: restart-only - owner_branch: redis-optionality-and-composition - validation: nonblank_when_required - compatibility_impact: additive - required_test: redis-sdk:typed-settings-bound-and-validated - - - name: APP_REDIS_TIMEOUT_ADMIN - property: app.redis.timeout.admin - owner_module: adapter-outbound-redis-runtime - type: duration - default: "3s" - allowed_values: null - classification: public-config - required: false - required_when: app.redis.enabled=true - reload_policy: restart-only - owner_branch: redis-optionality-and-composition - validation: duration_strict - compatibility_impact: additive - required_test: redis-sdk:typed-settings-bound-and-validated - - name: APP_REDIS_TIMEOUT_BATCH property: app.redis.timeout.batch owner_module: adapter-outbound-redis-runtime @@ -2274,21 +2008,6 @@ env_keys: compatibility_impact: additive required_test: redis-sdk:typed-settings-bound-and-validated - - name: APP_REDIS_TIMEOUT_COLLECTION - property: app.redis.timeout.collection - owner_module: adapter-outbound-redis-runtime - type: duration - default: "2s" - allowed_values: null - classification: public-config - required: false - required_when: app.redis.enabled=true - reload_policy: restart-only - owner_branch: redis-optionality-and-composition - validation: duration_strict - compatibility_impact: additive - required_test: redis-sdk:typed-settings-bound-and-validated - - name: APP_REDIS_TIMEOUT_FAST # Single-key command profile; above 5s produces a startup warning. property: app.redis.timeout.fast @@ -2406,21 +2125,6 @@ env_keys: compatibility_impact: additive required_test: redis-sdk:runtime-composition-binds-and-validates - - name: APP_REDIS_CAPACITY_MAXIMUM_IN_FLIGHT_BYTES - property: app.redis.capacity.maximum-in-flight-bytes - owner_module: adapter-outbound-cache-redis - type: integer - default: null - allowed_values: null - classification: public-config - required: false - required_when: app.redis.enabled=true - reload_policy: restart-only - owner_branch: redis-optionality-and-composition - validation: positive_integer - compatibility_impact: additive - required_test: redis-sdk:runtime-composition-binds-and-validates - - name: APP_REDIS_CAPACITY_MAXIMUM_IN_FLIGHT_COMMANDS property: app.redis.capacity.maximum-in-flight-commands owner_module: adapter-outbound-cache-redis @@ -2452,21 +2156,6 @@ env_keys: compatibility_impact: additive required_test: redis-runtime:script-lane-physical-connections-bounded - - name: APP_REDIS_CAPACITY_MAXIMUM_REPLY_BYTES - property: app.redis.capacity.maximum-reply-bytes - owner_module: adapter-outbound-cache-redis - type: integer - default: null - allowed_values: null - classification: public-config - required: false - required_when: app.redis.enabled=true - reload_policy: restart-only - owner_branch: redis-optionality-and-composition - validation: positive_integer - compatibility_impact: additive - required_test: redis-sdk:runtime-composition-binds-and-validates - - name: APP_REDIS_CAPACITY_REJECT_WHEN_DISCONNECTED # True refuses commands while disconnected. False restores the driver offline queue, which replays a burst of writes on reconnect in arbitrary order relative to the outage. property: app.redis.capacity.reject-when-disconnected @@ -2514,6 +2203,7 @@ env_keys: required_test: redis-sdk:runtime-composition-binds-and-validates - name: APP_REDIS_LIFECYCLE_ACQUIRE_TIMEOUT + # How long a lane borrow waits for a returned connection before it is refused as not sent. property: app.redis.lifecycle.acquire-timeout owner_module: adapter-outbound-cache-redis type: duration @@ -2604,21 +2294,6 @@ env_keys: compatibility_impact: additive required_test: redis-sdk:runtime-composition-binds-and-validates - - name: APP_REDIS_LIFECYCLE_TLS_HANDSHAKE_TIMEOUT - property: app.redis.lifecycle.tls-handshake-timeout - owner_module: adapter-outbound-cache-redis - type: duration - default: "3s" - allowed_values: null - classification: public-config - required: false - required_when: app.redis.enabled=true - reload_policy: restart-only - owner_branch: redis-optionality-and-composition - validation: duration_strict - compatibility_impact: additive - required_test: redis-sdk:runtime-composition-binds-and-validates - - name: APP_REDIS_PUBSUB_BUFFER_CAPACITY property: app.redis.pubsub.buffer-capacity owner_module: adapter-outbound-cache-redis @@ -2634,22 +2309,6 @@ env_keys: compatibility_impact: additive required_test: redis-sdk:runtime-composition-binds-and-validates - - name: APP_REDIS_PUBSUB_OVERFLOW_POLICY - # error | drop-oldest | drop-latest. - property: app.redis.pubsub.overflow-policy - owner_module: adapter-outbound-cache-redis - type: string - default: "error" - allowed_values: [error, drop-oldest, drop-latest] - classification: public-config - required: false - required_when: app.redis.enabled=true - reload_policy: restart-only - owner_branch: redis-optionality-and-composition - validation: nonblank_when_required - compatibility_impact: additive - required_test: redis-sdk:runtime-composition-binds-and-validates - - name: APP_REDIS_SENTINEL_CREDENTIAL_REFERENCE property: app.redis.sentinel.credential-reference owner_module: adapter-outbound-cache-redis @@ -3264,7 +2923,8 @@ env_keys: # (app.messaging.broker=); blank = messaging disabled. Replaces the former # Kafka-binary APP_MESSAGING_KAFKA_ENABLED. Adding a broker is new files only. type: string - default: null + # The Kafka module's config/module-defaults/messaging.yml defaults it to kafka, the only registered broker. + default: kafka allowed_values: null classification: public-config required: false @@ -3292,6 +2952,8 @@ env_keys: - name: APP_MESSAGING_KAFKA_BROKERS # source: feature-domain-event-outbox-contract — "Kafka는 optional integration adapter" # (broker 활성화 시 endpoint 필요) + # Also feeds spring.kafka.bootstrap-servers (the messaging platform's Kafka transport) through + # the Kafka module's config/module-defaults/messaging.yml, so one key addresses both paths. type: csv_list default: null allowed_values: null @@ -3331,90 +2993,9 @@ env_keys: compatibility_impact: behavior-change required_test: adapter-contract:notification-email-provider-selection - - name: APP_FILESERVER_ENABLED - # source: Fileserver R2 control-plane/provider-selection design 2026-07-28. - # Disabled is the shipped safe default. Enabling requires every local attestation - # value below and an exact app.fileserver destination/provider graph. - type: boolean - default: false - allowed_values: [true, false] - classification: public-config - required: false - reload_policy: restart-only - owner_branch: fileserver-r2-control-plane-provider-selection - validation: boolean_strict - compatibility_impact: additive - required_test: fileserver-r2:disabled-default-and-enabled-attestation - - - name: APP_FILESERVER_LOCAL_ROOT - # Pre-provisioned local-persistent root. The runtime additionally attests real - # path, ancestor/root symlinks, owner/mode, FileStore, sentinel, and capabilities. - type: string - default: null - allowed_values: null - classification: public-config - required: false - reload_policy: restart-only - owner_branch: fileserver-r2-control-plane-provider-selection - validation: absolute_existing_directory_when_app_fileserver_enabled - compatibility_impact: additive - required_test: fileserver-r2:disabled-default-and-enabled-attestation - - - name: APP_FILESERVER_LOCAL_EXPECTED_FILE_STORE_NAME - # Exact FileStore.name() expected for the pre-provisioned root. - type: string - default: null - allowed_values: null - classification: public-config - required: false - reload_policy: restart-only - owner_branch: fileserver-r2-control-plane-provider-selection - validation: non_empty_string_when_app_fileserver_enabled - compatibility_impact: additive - required_test: fileserver-r2:disabled-default-and-enabled-attestation - - - name: APP_FILESERVER_LOCAL_EXPECTED_FILE_STORE_TYPE - # Exact FileStore.type() expected for the pre-provisioned root. - type: string - default: null - allowed_values: null - classification: public-config - required: false - reload_policy: restart-only - owner_branch: fileserver-r2-control-plane-provider-selection - validation: non_empty_string_when_app_fileserver_enabled - compatibility_impact: additive - required_test: fileserver-r2:disabled-default-and-enabled-attestation - - - name: APP_FILESERVER_LOCAL_MOUNT_SENTINEL_SHA256 - # Lowercase SHA-256 of the operator-created .ca-fileserver-volume sentinel. - type: string - default: null - allowed_values: null - classification: public-config - required: false - reload_policy: restart-only - owner_branch: fileserver-r2-control-plane-provider-selection - validation: lowercase_sha256_when_app_fileserver_enabled - compatibility_impact: additive - required_test: fileserver-r2:disabled-default-and-enabled-attestation - - - name: APP_FILESERVER_LOCAL_EXPECTED_OWNER - # Exact filesystem owner expected for the attested root and private namespace. - type: string - default: null - allowed_values: null - classification: public-config - required: false - reload_policy: restart-only - owner_branch: fileserver-r2-control-plane-provider-selection - validation: non_empty_string_when_app_fileserver_enabled - compatibility_impact: additive - required_test: fileserver-r2:disabled-default-and-enabled-attestation - # === HTTP Client platform (app.httpclient.*) === # - # Only the master switch is registered here. The per-client surface is an indexed list whose + # Only the enabled key is registered here. The per-client surface is an indexed list whose # element cannot be templated in application.yml without materialising a nameless client in every # deployment, so it has no deployment-independent value for this registry to hold and is # registered in docs/httpclient/env-fields.yaml instead. That manifest is derived from @@ -3422,11 +3003,14 @@ env_keys: # HttpClientPlatformEnvManifestTest, and an APP_HTTPCLIENT_ variable with no field fails startup. - name: APP_HTTPCLIENT_ENABLED - # Master switch. While false the platform block is not bound at all: the auto-configuration that + # 2026-09-25 capability packaging: the module is on when present (its own config yml maps + # this key with default true); false is the explicit off. Absent from the build is the + # ordinary off state. + # While false the platform block is not bound at all: the auto-configuration that # binds it is not processed, so no bean, connection pool, TLS context, credential, thread or # gateway exists, and a malformed HTTP client setting cannot fail this deployment's startup. type: boolean - default: false + default: true allowed_values: [true, false] classification: public-config required: false @@ -3451,16 +3035,15 @@ env_keys: required_test: httpclient-platform:off-state-zero-side-effects-and-env-manifest-parity # === Fileserver HTTP platform (app.fileserver-platform.*) === - # - # A different capability from the app.fileserver R2 publication block above. Separate - # namespaces so the two cannot be switched on together by accident, and so a change to one - # cannot silently re-shape the other. - name: APP_FILESERVER_PLATFORM_ENABLED - # Master switch. While false the platform block is not bound at all: the auto-configuration that + # 2026-09-25 capability packaging: the module is on when present (its own config yml maps + # this key with default true); false is the explicit off. Absent from the build is the + # ordinary off state. + # While false the platform block is not bound at all: the auto-configuration that # binds it is not processed, so no bean, route, thread, schema check or filesystem call exists. type: boolean - default: false + default: true allowed_values: [true, false] classification: public-config required: false @@ -3948,7 +3531,7 @@ env_keys: required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - name: APP_FILESERVER_PLATFORM_ADMIN_ENABLED - # Management plane, a separate decision from the data plane. Requires the master switch too: + # Management plane, a separate decision from the data plane. Requires APP_FILESERVER_PLATFORM_ENABLED too: # enabling it alone now does nothing instead of half-building a bean graph. type: boolean default: false @@ -4042,7 +3625,7 @@ env_keys: required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - name: APP_FILESERVER_PLATFORM_TUS_ENABLED - # tus 1.0. Requires the master switch too. + # tus 1.0. Requires APP_FILESERVER_PLATFORM_ENABLED too. type: boolean default: false allowed_values: [true, false] @@ -4055,7 +3638,7 @@ env_keys: required_test: fileserver-platform:off-state-zero-side-effects-and-env-round-trip - name: APP_FILESERVER_PLATFORM_HTTPBIS_DRAFT12_ENABLED - # Unratified draft whose contract can change without notice. Requires the master switch too. + # Unratified draft whose contract can change without notice. Requires APP_FILESERVER_PLATFORM_ENABLED too. type: boolean default: false allowed_values: [true, false] @@ -4197,12 +3780,14 @@ env_keys: # supplies nothing. Reference: docs/notification/configuration.md. - name: APP_PERSISTENCE_JPA_ENABLED - # source: five-adapter-runtime-remediation §5.1 — master switch for relational persistence. - # false means no DataSource, no entity scan, no repositories, no Hibernate, no Flyway and no DB - # health contributor; the old app.jpa-platform.enabled gated three add-on beans while reading - # like this one and defaulting to on. + # source: five-adapter-runtime-remediation §5.1 — switch for relational persistence, shipped by + # the persistence-jpa module itself (config/module-defaults/persistence-jpa.yml). The module is + # selected by one build line and is on while present; false switches off this module's beans + # (entity scan, repositories, stores, startup guards). Removing the build line removes the + # capability and this key's only reader. The old app.jpa-platform.enabled gated three add-on + # beans while reading like this one. type: boolean - default: false + default: true allowed_values: [true, false] classification: public-config required: false @@ -4287,9 +3872,12 @@ env_keys: required_test: jpa-contract:hibernate-runtime-settings - name: APP_PERSISTENCE_MONGO_ENABLED - # source: five-adapter-runtime-remediation §5.1 — master switch for MongoDB persistence. + # 2026-09-25 capability packaging: the module is on when present (its own config yml maps + # this key with default true); false is the explicit off. Absent from the build is the + # ordinary off state. + # source: five-adapter-runtime-remediation §5.1 — on/off key for MongoDB persistence. type: boolean - default: false + default: true allowed_values: [true, false] classification: public-config required: false @@ -4329,10 +3917,13 @@ env_keys: required_test: adapter-contract:persistence-mongo-connection-source - name: APP_MESSAGING_ENABLED - # source: five-adapter-runtime-remediation §5.1 — master switch for broker publication. + # 2026-09-25 capability packaging: the module is on when present (its own config yml maps + # this key with default true); false is the explicit off. Absent from the build is the + # ordinary off state. + # source: five-adapter-runtime-remediation §5.1 — on/off key for broker publication. # APP_MESSAGING_BROKER selects which transport and is no longer the de-facto switch. type: boolean - default: false + default: true allowed_values: [true, false] classification: public-config required: false @@ -4347,10 +3938,13 @@ env_keys: # decision and these rows do not imply runtime membership. - name: APP_WEBSOCKET_ENABLED + # 2026-09-25 capability packaging: the module is on when present (its own config yml maps + # this key with default true); false is the explicit off. Absent from the build is the + # ordinary off state. property: app.websocket.enabled owner_module: adapter-inbound-websocket type: boolean - default: false + default: true allowed_values: [true, false] classification: public-config required: false @@ -4402,249 +3996,14 @@ env_keys: compatibility_impact: behavior-change required_test: websocket-contract:canonical-property-namespace - - name: APP_WEBSOCKET_PLATFORM_ENABLED - property: app.websocket.platform.enabled - owner_module: adapter-inbound-websocket - type: boolean - default: false - allowed_values: [true, false] - classification: public-config - required: false - reload_policy: restart-only - owner_branch: 2026-09-20-inbound-realtime-review-remediation - validation: boolean_strict - compatibility_impact: behavior-change - required_test: websocket-contract:canonical-property-namespace - - - name: APP_WEBSOCKET_PLATFORM_NODE_ID - property: app.websocket.platform.node-id - owner_module: adapter-inbound-websocket - type: string - default: local - allowed_values: null - classification: public-config - required: false - reload_policy: restart-only - owner_branch: 2026-09-20-inbound-realtime-review-remediation - validation: non_empty_string - compatibility_impact: behavior-change - required_test: websocket-contract:canonical-property-namespace - - - name: APP_WEBSOCKET_PLATFORM_ALLOWED_ORIGINS - property: app.websocket.platform.allowed-origins - owner_module: adapter-inbound-websocket - type: csv - default: "" - allowed_values: null - classification: public-config - required: false - reload_policy: restart-only - owner_branch: 2026-09-20-inbound-realtime-review-remediation - validation: explicit_http_origins_when_enabled - compatibility_impact: behavior-change - required_test: websocket-contract:canonical-property-namespace - - - name: APP_WEBSOCKET_PLATFORM_ALLOW_MISSING_ORIGIN - property: app.websocket.platform.allow-missing-origin - owner_module: adapter-inbound-websocket - type: boolean - default: false - allowed_values: [true, false] - classification: public-config - required: false - reload_policy: restart-only - owner_branch: 2026-09-20-inbound-realtime-review-remediation - validation: boolean_strict - compatibility_impact: behavior-change - required_test: websocket-contract:canonical-property-namespace - - - name: APP_WEBSOCKET_PLATFORM_MAX_FRAME_BYTES - property: app.websocket.platform.max-frame-bytes - owner_module: adapter-inbound-websocket - type: integer - default: 65536 - allowed_values: null - classification: public-config - required: false - reload_policy: restart-only - owner_branch: 2026-09-20-inbound-realtime-review-remediation - validation: positive_integer_with_platform_ceiling - compatibility_impact: behavior-change - required_test: websocket-contract:canonical-property-namespace - - - name: APP_WEBSOCKET_PLATFORM_MAX_MESSAGE_BYTES - property: app.websocket.platform.max-message-bytes - owner_module: adapter-inbound-websocket - type: integer - default: 524288 - allowed_values: null - classification: public-config - required: false - reload_policy: restart-only - owner_branch: 2026-09-20-inbound-realtime-review-remediation - validation: positive_integer_with_platform_ceiling - compatibility_impact: behavior-change - required_test: websocket-contract:canonical-property-namespace - - - name: APP_WEBSOCKET_PLATFORM_MAX_FRAGMENTS - property: app.websocket.platform.max-fragments - owner_module: adapter-inbound-websocket - type: integer - default: 16 - allowed_values: null - classification: public-config - required: false - reload_policy: restart-only - owner_branch: 2026-09-20-inbound-realtime-review-remediation - validation: positive_integer - compatibility_impact: behavior-change - required_test: websocket-contract:canonical-property-namespace - - - name: APP_WEBSOCKET_PLATFORM_MAX_BUFFERED_OUTBOUND_BYTES_PER_CONNECTION - property: app.websocket.platform.max-buffered-outbound-bytes-per-connection - owner_module: adapter-inbound-websocket - type: integer - default: 1048576 - allowed_values: null - classification: public-config - required: false - reload_policy: restart-only - owner_branch: 2026-09-20-inbound-realtime-review-remediation - validation: positive_integer_with_platform_ceiling - compatibility_impact: behavior-change - required_test: websocket-contract:canonical-property-namespace - - - name: APP_WEBSOCKET_PLATFORM_MAX_BUFFERED_OUTBOUND_BYTES_PER_NODE - property: app.websocket.platform.max-buffered-outbound-bytes-per-node - owner_module: adapter-inbound-websocket - type: integer - default: 67108864 - allowed_values: null - classification: public-config - required: false - reload_policy: restart-only - owner_branch: 2026-09-20-inbound-realtime-review-remediation - validation: positive_integer - compatibility_impact: behavior-change - required_test: websocket-contract:canonical-property-namespace - - - name: APP_WEBSOCKET_PLATFORM_MAX_CONNECTIONS_PER_ACTOR - property: app.websocket.platform.max-connections-per-actor - owner_module: adapter-inbound-websocket - type: integer - default: 4 - allowed_values: null - classification: public-config - required: false - reload_policy: restart-only - owner_branch: 2026-09-20-inbound-realtime-review-remediation - validation: positive_integer - compatibility_impact: behavior-change - required_test: websocket-contract:canonical-property-namespace - - - name: APP_WEBSOCKET_PLATFORM_PING_INTERVAL - property: app.websocket.platform.ping-interval - owner_module: adapter-inbound-websocket - type: duration - default: 15s - allowed_values: null - classification: public-config - required: false - reload_policy: restart-only - owner_branch: 2026-09-20-inbound-realtime-review-remediation - validation: positive_duration - compatibility_impact: behavior-change - required_test: websocket-contract:canonical-property-namespace - - - name: APP_WEBSOCKET_PLATFORM_IDLE_TIMEOUT - property: app.websocket.platform.idle-timeout - owner_module: adapter-inbound-websocket - type: duration - default: 45s - allowed_values: null - classification: public-config - required: false - reload_policy: restart-only - owner_branch: 2026-09-20-inbound-realtime-review-remediation - validation: positive_duration - compatibility_impact: behavior-change - required_test: websocket-contract:canonical-property-namespace - - - name: APP_WEBSOCKET_PLATFORM_MAX_CONNECTION_AGE - property: app.websocket.platform.max-connection-age - owner_module: adapter-inbound-websocket - type: duration - default: 4h - allowed_values: null - classification: public-config - required: false - reload_policy: restart-only - owner_branch: 2026-09-20-inbound-realtime-review-remediation - validation: positive_duration - compatibility_impact: behavior-change - required_test: websocket-contract:canonical-property-namespace - - - name: APP_WEBSOCKET_PLATFORM_TICKET_LIFETIME - property: app.websocket.platform.ticket-lifetime - owner_module: adapter-inbound-websocket - type: duration - default: 30s - allowed_values: null - classification: public-config - required: false - reload_policy: restart-only - owner_branch: 2026-09-20-inbound-realtime-review-remediation - validation: positive_duration - compatibility_impact: behavior-change - required_test: websocket-contract:canonical-property-namespace - - - name: APP_WEBSOCKET_ADVANCED_SOCKJS_ENABLED - property: app.websocket.advanced.sockjs.enabled - owner_module: adapter-inbound-websocket - type: boolean - default: false - allowed_values: [true, false] - classification: public-config - required: false - reload_policy: restart-only - owner_branch: 2026-09-20-inbound-realtime-review-remediation - validation: boolean_strict - compatibility_impact: behavior-change - required_test: websocket-contract:canonical-property-namespace - - - name: APP_WEBSOCKET_ADVANCED_STOMP_ENABLED - property: app.websocket.advanced.stomp.enabled - owner_module: adapter-inbound-websocket - type: boolean - default: false - allowed_values: [true, false] - classification: public-config - required: false - reload_policy: restart-only - owner_branch: 2026-09-20-inbound-realtime-review-remediation - validation: boolean_strict - compatibility_impact: behavior-change - required_test: websocket-contract:canonical-property-namespace - - - name: APP_WEBSOCKET_ADVANCED_STOMP_RELAY_ENABLED - property: app.websocket.advanced.stomp.relay.enabled - owner_module: adapter-inbound-websocket - type: boolean - default: false - allowed_values: [true, false] - classification: public-config - required: false - reload_policy: restart-only - owner_branch: 2026-09-20-inbound-realtime-review-remediation - validation: boolean_strict - compatibility_impact: behavior-change - required_test: websocket-contract:canonical-property-namespace - - name: APP_GRAPHQL_ENABLED - # source: five-adapter-runtime-remediation §5.1 — master switch for the GraphQL transport. + # 2026-09-25 capability packaging: the module is on when present (its own config yml maps + # this key with default true); false is the explicit off. Absent from the build is the + # ordinary off state. + # source: five-adapter-runtime-remediation §5.1 — on/off key for the GraphQL transport. # false publishes no /graphql route, including the one Spring GraphQL would publish by itself. type: boolean - default: false + default: true allowed_values: [true, false] classification: public-config required: false @@ -4864,9 +4223,12 @@ env_keys: compatibility_impact: behavior-change required_test: adapter-contract:outbox-relay-dependency - name: APP_NOTIFICATION_PLATFORM_ENABLED - # source: NTF-025 — master switch for the notification delivery platform; false binds nothing at all + # 2026-09-25 capability packaging: the notification-platform module is on when present (its + # config/module-defaults/notification.yml maps this key with default true); false is the + # explicit off and binds nothing at all. Absent from the build is the ordinary off state. + # source: NTF-025. type: boolean - default: false + default: true allowed_values: [true, false] classification: public-config required: false @@ -5288,8 +4650,23 @@ env_keys: compatibility_impact: additive required_test: adapter-contract:notification-ses-provider-assembled + - name: APP_NOTIFICATION_PLATFORM_SES_ALLOWED_TOPIC_ARNS + # source: 2026-09-24 module review Critical #10 — SNS topics whose SES event callbacks the + # shipped SES profile accepts. A valid SNS signature only proves AWS sent the message and + # anyone can own a topic, so binding fails when callbacks are enabled and this is empty. + type: csv + default: "" + allowed_values: null + classification: security-relevant + required: false + reload_policy: restart-only + owner_branch: 2026-09-24-notification-critical-remediation + validation: non_empty_when_ses_and_callbacks_enabled + compatibility_impact: behavior-change + required_test: adapter-contract:notification-ses-callback-topic-allowlist + - name: APP_NOTIFICATION_PLATFORM_SMTP_ENABLED - # source: NTF-INT-001 — master switch of the shipped SMTP provider profile; false means assembly skips it entirely. + # source: NTF-INT-001 — on/off key of the shipped SMTP provider profile; false means assembly skips it entirely. type: boolean default: false allowed_values: [true, false] diff --git a/docs/registries/metrics.yaml b/docs/registries/metrics.yaml index 7ce326ef..0435f3a5 100644 --- a/docs/registries/metrics.yaml +++ b/docs/registries/metrics.yaml @@ -348,12 +348,13 @@ metrics: - name: event_type cardinality_limit: 50 - name: outcome - cardinality_limit: 4 - allowed_values: [PUBLISHED, FAILED, DEAD, IN_FLIGHT] + cardinality_limit: 5 + # STALE: the relay's claim was taken over before its result could be written (V17 lease fence). + allowed_values: [PUBLISHED, FAILED, DEAD, IN_FLIGHT, STALE] percentiles: null histogram_buckets: null alert_severity_thresholds: - p2: "FAILED rate > 1% for 10m" + p2: "FAILED rate > 1% for 10m, or STALE > 0 for 10m (in-flight timeout shorter than a relay stall)" owner_branch: feature-domain-event-outbox-contract log_field_mapping: [event_type, outcome, event_id] compatibility_impact: additive diff --git a/docs/reviews/2026-09-24-src-maintainability-review.md b/docs/reviews/2026-09-24-src-maintainability-review.md new file mode 100644 index 00000000..49ec4020 --- /dev/null +++ b/docs/reviews/2026-09-24-src-maintainability-review.md @@ -0,0 +1,1102 @@ +# `src/` 유지보수성·구조 리뷰 (2차) — 2026-09-24 + +## 개요 + +| 항목 | 내용 | +|---|---| +| 목적 | 1차 리뷰(`2026-09-24-src-module-code-review.md`, 결함 중심)에서 빠진 관점 — 유지보수, 단일 책임, 공통 계약 추출, 디자인 패턴, 테스트 가독성(given/when/then), 빌드 인프라 비례성 | +| 기준 | `main` @ `208077fd` 작업 트리 | +| 방법 | 읽기 전용 리뷰 에이전트 11개 병렬: 모듈 그룹별 구조 리뷰 7개(S1–S7), 모듈 간 기능 중복(X1), 공통 유틸·전송 경계(X2), 빌드 비례성(BUILD), 테스트 구조(TEST). 건수 제한 없이, 비슷한 사례는 한 건으로 묶음 | +| 규칙 | 패턴은 코드를 줄이는 경우에만 권고. 반대로 구현 1개짜리 인터페이스·전달만 하는 계층은 삭제 권고 | + +## 질문별 답 + +### 1. 유지보수·SRP·공통 계약 — 핵심은 "나쁜 코드"보다 "여러 세대와 미조립 코드의 공존" + +모듈 경계(HARD-STOP 1·2·3·5)는 지켜지고 있다. 문제는 한 기능에 2~3세대 구현이 함께 있고, 그중 상당수가 실제 앱에 조립되지 않는다는 점이다. adopter는 어느 것이 정본인지 알 수 없고, 수정이 한쪽에만 들어가 이미 갈라진 곳이 여러 군데다. + +**조립되지 않은(도달 불가) 코드 추정치** — 그룹마다 측정 방법이 달라 겹침·오차가 있다. 일부는 의도적으로 제공하는 라이브러리 코드다. + +| 영역 | 추정 | 근거 | +|---|---:|---| +| redis-sdk + redis-runtime의 SDK 전용 부분 | 약 25.7k | S3 #3, 1차 G-6 | +| graphql | 약 14.7k | 1차 J-10, S5 | +| web (2세대 platform, WebFlux) | 약 13.3k | S5 #2·#4 | +| persistence-mongo | 약 13.1k | S2 #2 | +| messaging:* | ≥12.7k | S7 | +| grpc:* / grpc-advanced | 약 12.4k | S7 | +| persistence-jpa (플랫폼 라이브러리·V2·중복 엔진) | 약 10.1k | S2 #3·#4·#7 | +| websocket 플랫폼 라이브러리 | 약 9.7k | S6 #1 | +| fileserver 어댑터 루트(R1/R2 publication) | 약 8.7k | S4 #1 | +| notification (R1 4.5k + platform 0.9k + provider 5종 3.0k) | 약 8.4k | S1 #14, S4 #3 | +| application-core | 약 4.9k | S1 #1–#3 | +| objectstorage (direct/multipart, legacy adoption) | 약 4.0k | 1차 D-7, S4 #10 | +| messaging 어댑터 R1 | 약 3.5k | S4 #2 | +| 합계 | **약 15만 줄 (main 32만 줄의 약 절반)** | | + +**여러 벌로 갈라진 기능과 권고(X1·X2 요약)** + +| 기능 | 현재 | 권고 | +|---|---|---| +| Outbox | 세대 3개. 실제 조립된 v1에만 fencing이 없음(중복 발행 위험). 고친 두 구현(V2, messaging)은 미조립 | 앱 쪽 1벌. v1 테이블 + V2/V1002 fencing 이식 후 V2 삭제(또는 반대). messaging outbox는 vendored라 유지 | +| 멱등성 | v1/V2 계약 2개, store 3개, executor 조립 3곳, inbound 전용 ledger 3개 | V2를 정본, v1 삭제, 조립 1곳 | +| 에러 어휘 | HTTP 응답 형식 3개(Envelope, WebProblem, Fileserver problem), 코드 체계 4개. 같은 코드의 status·retryable이 전송마다 다름 | `ApiErrorCode` 하나 + Envelope. shared 예외 5종에 `ApiErrorCarrier` 구현, GraphQL retryable은 코드별 값 | +| caller 트랜잭션 guard | 9벌 복사, 빠진 곳에서 dual-write 결함 | persistence-jpa `CallerTransaction.require` 하나 | +| 테스트 fake | 같은 포트 fake가 모듈마다 따로(`TransactionPort` 21~26개), 실제 adapter와 대조하는 kit는 1개 | 포트 소유 모듈 testFixtures에 추상 contract 클래스 | +| 시크릿·prod 판정·tenant·MDC | 시크릿 경로 4갈래, prod 판정 재구현, `TenantContext` 2개(문법 다름), `MdcKeys`가 web에 갇힘 | 기존 정본(`SecretSourcePort`, `RuntimeEnvironment`)에 bridge 1줄씩, tenant 값 타입 1개, `MdcKeys`는 shared-contract로 | +| capability 활성화 규칙 | 6곳에 흩어지고 기본값이 이미 3가지로 갈림 | 표 하나(키·기본값·필요 조건·prod secret)에서 validator·endpoint 파생 | +| readiness/evidence/API-surface | 카드 스키마 3개, API-surface gate 3개, moduleboundary 3벌 | build-logic 구현 하나 | +| 작은 유틸 | SHA-256 헬퍼 53개, JSON escape 3가지 동작, backoff "full jitter" 뜻 3가지, HMAC cursor codec 7개 | shared-contract `Sha256`, `Backoff`, 서명 헬퍼(삭제 후 남으면) | + +**디자인 패턴** — 코드가 줄어드는 곳에만 권고했다. +- Template Method: httpclient blocking/reactive 공통 코어(약 600~700줄 감소, S3 #1). +- 상태 전이표(State): `ProviderRuntime`, `FileState`, `LocalPersistentControlPlane`의 전이 규칙(S4 #5·#14, S1 #13). +- Strategy / `EnumMap` 표: GraphQL 에러 category switch 3개, Redis 스크립트 status switch 5개(S5 #6, S3 #5). +- 정적 factory / Value Object: `PublishResult` 7-인자 생성 28회, fileserver 원시 String 검증 73곳(S7 #6, S4 #8). +- Rule 목록: startup validator 19개 → `StartupRule` 목록 + runner 1개(S6 #3). +- 반대 방향(삭제): 구현 1개짜리 인터페이스·레지스트리·facade 다수 — httpclient 4개, application-fileserver 6개, notification 레지스트리 2개, `PolicyTransactionPort` 계열, `SelectedObjectStorageProviderFactory`, fileserver R2 routing 계층 등. + +### 2. 테스트 given/when/then + +- `// given // when // then`을 모두 갖춘 파일: **1,500개 중 0개**(일부만 5개). 다만 6줄 이상 테스트의 71%는 빈 줄로 단계를 나누고, 이름은 전부 camelCase 행동 문장이라 흐름 자체는 대체로 보인다. +- 더 급한 문제 두 가지: (a) fake가 실제 adapter와 같은 계약 테스트를 통과하지 않는다 — 1차 리뷰의 "fake가 숨긴 결함" 6건 중 5건이 여기에 해당. (b) 이름이 약속한 성질을 단언하지 않는 테스트가 약 1,050개(12%). +- adopter가 복사하는 `sample-portfolio`가 가장 약하다(DisplayName 0%, 단계 분리 54%, 115줄 테스트). +- 제안: GWT 주석을 규칙으로(본문 3문장 이상이면 필수, `// when`은 정확히 하나), 이름에 적은 성질은 반드시 단언, 포트별 추상 contract 테스트, Mockito는 프레임워크 경계에만. 새로 쓰거나 고치는 테스트에만 적용하고 sample부터 모범 사례로 재작성. 주석 게이트(자동 강제)는 만들지 않음 — 이유는 TEST 절. + +### 3. 빌드 인프라 — 목적 대비 과하다. 목적에 필요한 부분은 약 13% + +- build-logic + build-tools 16,768줄 중 **아키텍처 강제(A)는 2,242줄(13%)**, 핵심만 따지면 1,301줄(8%). 기능별 증거 검사(E)가 7,760줄(46%)로 가장 크다. +- Gradle 방향 게이트와 ArchUnit 규칙 105개는 **필요한 크기**다. 줄일 대상이 아니다. +- 최근 "gradle 얇게" 리팩터에서 빌드 코드가 늘었다: `ace8aaae`(09-17) → `208077fd`(09-24) 사이 build-logic/build-tools/script plugin 합계 **약 4.7k → 17.1k줄**(직접 측정). leaf 스크립트는 215줄만 줄었다. +- 권고: O3 — build-logic에는 아키텍처 코어(registry, 방향·순수성 task)·컨벤션·레인 하나만 두고, 기능별 검사는 소유 leaf의 테스트로 옮긴다(목표 약 3.5–4k줄, build-tools 0). 그 전에 **어느 안을 고르든 안전한 정리 11개로 약 3.4k줄 감소, 잃는 보호 없음**. 09-16 단계 분리 계획의 미이행분(PR에 남은 2단계 게이트 11개)은 삭제가 아니라 단계만 옮긴다. +- 빈틈 하나: 빌드 단계 순수성 검사가 `application-*`만 본다. domain-core에 외부 의존을 추가해도 빌드는 통과한다(필터 3줄 추가로 해결). + +## 결정 필요 (승인자: 저장소 소유자) + +| # | 결정 | 권고 | +|---|---|---| +| D1 | 미조립 대형 코드 처리 — redis-sdk, Mongo advanced/reactive, graphql advanced/compat, websocket 플랫폼, web 2세대·WebFlux, notification provider 5종, fileserver R2 publication, messaging experimental/rabbit/avro 등, grpc-advanced | family별로 "삭제 / `optional-platforms` 같은 별도 build로 이동 / 유지" 중 선택. 기본값은 이동(공개 약속 유지, 기본 빌드에서 제외) | +| D2 | Outbox 정본 | v1 테이블 유지 + fencing 이식, V2 삭제 (반대도 가능. 목표는 1벌) | +| D3 | 멱등성 정본 | V2 (Redis·소유자 fencing이 V2에만 있음) | +| D4 | WebFlux 지원 | 현재 어떤 조합으로도 켜지지 않음. 삭제 권고. 유지하려면 starter-web을 leaf에서 빼고 composition이 선택 | +| D5 | 빌드 목표안 | O3 (순서: 단계 재배치 → 안전한 정리 → O3) | +| D6 | 테스트 컨벤션 | 제안안 채택 여부, `@DisplayName` 언어(기본 영어) | + +## 권고 순서 + +1. **1차 Critical 수정과 함께 contract 테스트 추가.** fake가 결함을 숨긴 6개 포트의 추상 contract를 수정 PR에 같이 넣는다. contract가 현재 코드에서 먼저 실패하면 그것이 회귀 테스트다. +2. **빌드 안전 정리 1–11 + 단계 재배치(BUILD 절 "바로 할 것").** 서로 독립적이고 보호 손실 없음. +3. **D1–D4 결정 후 삭제/이동.** 가장 큰 LOC 감소. 그 뒤 outbox·멱등성·에러 어휘를 하나로 합친다. +4. **테스트 컨벤션 문서화 + sample-portfolio를 모범 사례로 재작성.** 나머지는 손대는 테스트부터. + +## 1차 리뷰 보정 + +- 1차 B-2(SNS 서명 우회): 영향 서술 중 "위조 callback이 `SesSuppressionUpdater`로 suppression을 만든다"는 과장이다. 이 클래스는 참조가 0이다(S4 #3). 서명 검증 우회 자체는 유효하다. +- 1차 A-2(websocket prod 판정): 수정이 더 간단하다. bridge 없이 `RuntimeEnvironment.isProductionActive(...)` 정적 호출 한 줄이면 된다(X2 P1-2). +- 1차 O-2 이후 측정: build 코드 증가 수치는 이 문서의 직접 측정값(약 4.7k → 17.1k)을 기준으로 한다(BUILD 에이전트는 6.3k → 17.0k로 셈, 포함 범위 차이). + +## 검증 기록 + +| 항목 | 결과 | +|---|---| +| 방식 | 전부 읽기 전용(grep·git·스크립트). Gradle과 테스트는 실행하지 않음 | +| 직접 재확인 | build-logic+build-tools 합계 16,768줄 일치; 09-17→09-24 증가 약 4.7k→17.1k; GWT 주석 완비 파일 0개; web·web-fileserver 둘 다 `implementation spring-boot-starter-web`(WebFlux 비활성 근거); application-core에 domain-core 의존 없음; 순수성 task가 `application-*`만 순회; persistence-mongo는 app-bootstrap `runtimeOnly`이고 다른 main 소스의 Mongo 타입 참조 없음 | +| 추정치 | 도달 불가 LOC, 약한 단언 수, 중복률은 이름 참조·regex 기반 추정. 리플렉션·문자열 bean 참조는 반영 안 됨 | + +## 그룹별 상세 + +아래는 각 에이전트 결과 원문이다. BUILD → TEST → X1 → X2 → S1–S7 순서. + +### BUILD — 빌드 인프라가 목적에 비해 과한가 + +#### 결론 +- **대부분 과하다.** 목적("빌드 시점에 아키텍처 위반을 막는 것", 카테고리 A)은 build-logic+build-tools 16,768줄 중 2,242줄(13%). 꼭 필요한 registry·의존 방향·순수성 검사만 따지면 1,301줄(8%). +- **가장 큰 덩어리는 기능(capability)별 증거 검사.** jpa·notification·messaging·mongo 전용 검사(E) 7,760줄(46%), 테스트 레인 검증(C) 2,559줄, 릴리스·스냅샷류(D) 2,714줄. +- **아키텍처 게이트 자체는 적정.** Gradle 방향 게이트와 ArchUnit 규칙 105개는 필요한 크기. 문제는 그 주변의 증거 검사 플랫폼. +- **"gradle을 얇게" 리팩터에서 코드가 두 배.** 09-17(`ace8aaae`) → 09-24(`208077fd`) 사이 included build 코드 6,276 → 17,010줄, 같은 기간 leaf·root 스크립트는 3,947 → 3,732줄(215줄 감소). 줄어든 스크립트 로직이 Java 플러그인으로 옮겨 가면서 두 배 이상 커짐. +- **09-16 단계 분리 계획은 절반만 이행.** 2단계(main)로 내려야 할 env 키·공개 경로 스냅샷·전체 system 테스트·API surface·기능 검사가 지금도 PR 게이트에서 돈다. + +#### 인벤토리 +카테고리: A 아키텍처, B 품질 도구, C 테스트 레인·증거, D 릴리스·스냅샷, E 기능별, F 개발 편의. 단계: PR = 1단계(머지 차단), main = 2단계, tag = 3단계. ✗ = 계획(`docs/superpowers/plans/2026-09-16-ci-stage-separation.md`)과 현재 위치 불일치. + +| # | 구성요소 | LOC (main+test) | 쓰는 곳 / 호출 경로 | 막는 것 | 카테고리 | 판정 | 단계 현재→목표 | +|---|---|---|---|---|---|---|---| +| 1 | `ca.architecture-registry`, `ca.optional-architecture-registry` (`ModuleRegistry`, `ModuleRegistrySettingsInstaller`) | 353+162 | `src/settings.gradle:13`, `optional-platforms/settings.gradle:6` | registry 모듈만 include, 디렉터리 매핑, registry 형식 | A | KEEP | 설정 단계 ✓ | +| 2 | `ca.architecture`: `verifyModuleDependencyDirection`, `verifyCleanArchitectureDependencies`, `verifyModuleDependencyPurity` (+`ResolvedComponents`) | 619+167 | `build.gradle:21`, `optional-platforms/build.gradle:2` → `architectureCheck` → `ci` | HS5, application-* 프레임워크 순수성 | A | KEEP, 순수성 필터에 domain-core·shared-contract 추가 | PR ✓ | +| 3 | `verifyNoIgnoredSourcePackages` | 128+0 | `architectureCheck` | Git 무시 패키지의 소스 | A 인접 | KEEP (1차 O-3 수정) | PR→main | +| 4 | `ca.runtime-membership` | 194+124 | `build.gradle:20`, `ArchitecturePlugin.java:216-225` | 조립 루트 런타임 모듈 ⊆ registry | A | **DELETE** (#2와 중복) | PR→없음 | +| 5 | `ca.dependency-policy` | 400+95 | `app-bootstrap/build.gradle:376-390`, `notification/build.gradle:63`, `messaging/build.gradle:44` → `check` | fileserver 미포함, yaml/jackson 부재 | A/E | REPLACE-WITH-NATIVE | PR ✓ | +| 6 | ArchUnit (`app-bootstrap/src/architectureTest`) | 7,786 (규칙·지원 6,342 + fixture 1,444), 그 밖에 leaf ArchUnit 26파일 3,052 | `architectureTestLaneCheck` → `architectureCheck` | HS1-4 import 규칙 (`@ArchTest` 105, `@Test` 109) | A | KEEP | PR ✓ | +| 7 | `ca.java-conventions` (+`verifyDependencyLocks`, `resolveAndLockAll`) | 206+0 | 모든 Java leaf | toolchain, `-Werror`, STRICT lock, BOM | B | SIMPLIFY (`quarantineTest` 삭제, leaf 버전 고정) | PR ✓ | +| 8 | `ca.quality-conventions` (+`qualityCheck`, `auxiliaryStyleCheck`) | 209+0 | 모든 Java leaf | Spotless, Checkstyle, Error Prone, SpotBugs | B | KEEP | PR ✓ (5분 넘으면 SpotBugs만 main) | +| 9 | `ca.java-library`, `ca.spring-library`, `ca.spring-config`, `ca.platform-module`, `ca.grpc-platform-module` | 83+105 | leaf 6/22/21/38/4 | leaf 종류별 조합 | B | KEEP | — | +| 10 | `ca.test-jvm-agents` | 90+0 | 모든 Java leaf | Mockito agent | B | SIMPLIFY → java-conventions 약 5줄 | — | +| 11 | `ca.auxiliary-source-set` | 151+145 | 15 leaf | 추가 source set | B | REPLACE-WITH-NATIVE (`jvm-test-suite`, ADR-BUILD-001 선례) | — | +| 12 | `ca.strict-test-lane` | 573+424 | 모든 Java leaf, 선언 레인 47개, root 집계(`build.gradle:109-130`) | 레인이 0개 실행·skip·필수 클래스 누락 시 실패 | C | KEEP, "필수 테스트 실행 + skip 금지"의 **유일한 구현**으로 SIMPLIFY | 레인별 | +| 13 | `ca.strict-qualification` | 393+273 | 9 leaf, 13회 등록 | #12와 같은 검사 3중(`*RequiredClasses` + listener + XML 재읽기) | C | **MERGE** → #12 | PR/main | +| 14 | `ca.evidence` + `JUnitEvidence` + `RequiredTestExecution` | 239+116 | `build.gradle:18`, #15, graphql | JUnit XML 기준 skip 금지 | C | MERGE 후 DELETE | — | +| 15 | `ca.conditional-transport-qualification` | 91+236 | `build.gradle:19`, `ci-quality-gates.yml:71` | 선택 transport 테스트 skip 금지 | C/E | MERGE → app-bootstrap 레인 1개 | PR→main ✗ | +| 16 | build-tools `junit` (`JUnitEvidenceReader`) | 138+76 | messaging, jpa | XML 재읽기 | C | MERGE | — | +| 17 | `ca.api-surface` (+`ApiSurfacePolicy`, `JavaPublicTypes`) | 549+172 | mongo·jpa·graphql `check` | 공개 타입 목록 변경 | D | SIMPLIFY: 유일 구현으로, #27·jpa-adopter 흡수 | PR→main ✗ | +| 18 | `ca.public-path-snapshot` | 288+37 (+#19와 공유 contract test 265) | `build.gradle:23`, `ci-quality-gates.yml:62`, `releaseCheck`, `notification-platform.yml:89` | permitAll 경로 기준선 | D (보안) | SIMPLIFY → app-bootstrap approval test (`approvaltests` 이미 의존성, `app-bootstrap/build.gradle:255`) | PR→main ✗ | +| 19 | `ca.archive-hygiene` | 216+46 | `build.gradle:22` → `releaseCheck` | SHA가 붙은 오래된 jar | D | **DELETE** (leaf 버전 고정 시 원인 소멸; 이미지는 `stageDockerJar` rename 경유 `app-bootstrap/build.gradle:306-311`) | tag→없음 | +| 20 | `ca.release-provenance` | 138+71 | root, optional-platforms; 모든 leaf jar 버전(`JavaConventionsPlugin.java:45-48`) | 버전·SHA 추적 | D | SIMPLIFY → app-bootstrap `springBoot { buildInfo() }` (런타임에서 `Build-Revision` 읽는 곳 0) | tag ✓ | +| 21 | `ca.jmh-benchmarks` | 166+79 | 4 leaf, workflow 호출 0 | — | D | REPLACE-WITH-NATIVE (`me.champeau.jmh`) 또는 DELETE | 없음 | +| 22 | `ca.config-contract` / `verifyEnvKeys` | 476+211 | `configContractCheck` → `ci`, `notification-platform.yml:89` | `env-keys.yaml`(5,869줄) ↔ 설정 바인딩 | D | SIMPLIFY → app-bootstrap JUnit (선례 `OperationalErrorRegistryContractTest`, `build.gradle:103-106`) | PR→main ✗ | +| 23 | `ca.graphql-platform` | 188+0 | `graphqlStableTest`(`ci-quality-gates.yml:68`), `verifyGraphQlProductionJar`(`check`) | stable 레인, jar 내용 | E | SIMPLIFY: 레인은 #12로, jar 검사만 | PR→main ✗ (레인) | +| 24 | `ca.jpa-test-lanes` | 159+118 | persistence-jpa | PostgreSQL 레인 목록 | E | SIMPLIFY → leaf `strictTestLanes` | main | +| 25 | `ca.redis-topology-lane` | 242+133 | cache-redis, `redis-sdk-topology.yml` | topology 레인 + 자체 tracker | E | SIMPLIFY → #12 레인 | PR(경로 필터) ✓ | +| 26 | `ca.jpa-evidence` + `ca.jpa-qualification` | 2,838+744 | jpa `check`(`build.gradle:184-185`), `ci-quality-gates.yml:188-207`, `jpa-release.yml`, `jpa-r2-evidence.yml` | readiness card, evidence manifest | E | 플랫폼 DELETE, registry 검사만 leaf 테스트로 | PR→main/tag ✗ | +| 27 | `ca.notification-api-surface` + `ca.notification-evidence` | 851+250 | `build.gradle:24-25`, notification `check`(`:84-87`) | API 목록, evidence | E | MERGE(API → #17) / DELETE(evidence) | PR→main ✗ | +| 28 | `ca.notification-configuration` | 222+140 | `build.gradle:26`, notification `check` | 설정 계약 | E | SIMPLIFY → leaf 테스트 | PR→main ✗ | +| 29 | `ca.messaging-qualification` + `ca.messaging-certification` | 819+253 | `build.gradle:28`, leaf 4, `integration-main.yml:209`, `messaging-certification.yml:44` | 계약 evidence, 해시 | E | SIMPLIFY → leaf 테스트 | main ✓ / PR(경로) ✓ | +| 30 | `ca.mongo-verification` | 544+223 | mongo `check`(`build.gradle:226-228`) | 레인 태그 분리, 자체 XML reader | E | DELETE/SIMPLIFY | PR→main ✗ | +| 31 | `ca.developer-bootstrap` + `ca.bootrun-dotenv` | 320+184 | `build.gradle:29` (1차 O-1 Critical 원인), `README.md:42` | 로컬 기동 순서 | F | SIMPLIFY (app-bootstrap에만 또는 `scripts/`) | 없음 | +| 32 | `architectureCheck` / `verifyDependencyLocks` | — | `ci-quality-gates.yml:62` | A, B | A/B | KEEP | PR ✓ | +| 33 | `ci` (`build.gradle:138-147`) | — | PR | PR 게이트 | — | SIMPLIFY (#34-36 빼기) | PR | +| 34 | `qualificationCheck` / `systemTestCheck` | — | `ci` | 전체 앱 기동 테스트 | C | KEEP | PR→main ✗ | +| 35 | `sampleWebContractCheck`, `configContractCheck` | — | `ci` | 실서버 sample, env 키 | D | KEEP | PR→main ✗ | +| 36 | `quarantineTest` (`build.gradle:88`) | — | `ci-quality-gates.yml:212-216` | `@Tag("quarantine")` 0개 | C | DELETE | PR(참고)→없음 | +| 37 | `integrationCheck`, `releaseCheck` | — | `integration-main.yml`, `release.yml:60` | 컨테이너 레인 / 릴리스 | C/D | KEEP (`releaseCheck`는 `ci`를 다시 돌림) | main ✓ / tag ✓ | +| 38 | `.github/workflows` 18개 | 2,767 | PR 1,358 · main 339 · tag 709 · 야간 298 · reusable 63 | — | 혼합 | SIMPLIFY | — | + +#### 카테고리별 LOC +| 카테고리 | build-logic | build-tools | 합계 | 비율 | +|---|---:|---:|---:|---:| +| A 아키텍처 | 2,242 | 0 | 2,242 | 13.4% | +| B 품질 도구 | 989 | 0 | 989 | 5.9% | +| C 레인·증거 | 2,345 | 214 | 2,559 | 15.3% | +| D 릴리스·스냅샷 | 2,027 | 687 | 2,714 | 16.2% | +| E 기능별 | 840 | 6,920 | 7,760 | 46.3% | +| F 개발 편의 | 504 | 0 | 504 | 3.0% | +| 합계 | 8,947 | 7,821 | 16,768 | | + +표 밖: leaf `build.gradle` 74개 3,531줄 = 의존성 857, plugins 295, 주석·빈 줄 1,400, 그 외 로직 979(그중 약 660줄이 레인 DSL: `strictTestLanes` 413, `auxiliarySourceSets` 122, `strictQualification` 약 125). **leaf 파일 안의 아키텍처 검사 로직은 0줄.** 요약: 목적(A)에 쓰이는 빌드 코드 약 1.3–2.2k줄, 나머지 14.5k줄은 다른 목적. + +#### 중복 +1. **의존 방향을 4번 검사.** 컴파일러(registry에 없는 모듈은 classpath에 없어 import 실패) / `verifyModuleDependencyDirection`(73개 leaf 전부, 선언 edge와 컴파일 가시 edge) / `verifyCompositionRuntimeMembership`("미등록"이 될 수 있는 건 `:sample-portfolio`뿐 → 방향 게이트가 이미 차단) / ArchUnit adapter 패키지 규칙 약 7개(`AdapterBoundaryArchitectureTest.java:76-392`). 09-16 계획이 runtime-membership 삭제를 "`runtimeClasspathManifest`를 `RuntimeMembershipClasspathAgreementTest`가 읽는다"며 기각했으나 지금 두 이름 모두 grep 0 → 근거 소멸. ArchUnit 쪽 중복은 비용이 작고 `modules.json`이 느슨해져도 잡아내므로 유지. +2. **"필수 테스트 실행 + skip 금지" 구현 6개**(1차 O-8의 5개 + `MongoJUnitXml`, `RedisTopologyExecutionTracker`): listener 방식 `StrictLaneExecutionTracker`, `RejectSkippedTestsListener`, `RedisTopologyExecutionTracker`; JUnit XML 파서 `JUnitEvidence.java`(128), `JUnitEvidenceReader.java`(114), `MongoJUnitXml.java`(79). #12가 이미 필수 클래스별 실행과 skip 금지를 모두 하므로(`StrictTestLanePlugin.java` 후반) #13·#14·#15·#16은 부분집합. +3. **API surface 검사 3개**: `ca.api-surface`(javac 파싱), `NotificationApiSurfaceVerifier`(정규식), `JpaAdopterApiSurfaceVerifier`(import 정규식). +4. **fileserver 제외 규칙이 두 곳에서 모순**: `modules.json`은 app-bootstrap → `application-fileserver`, `adapter-outbound-fileserver` 허용, `dependencyPolicy`는 같은 모듈을 `absent`로 금지. app-bootstrap 외에 fileserver edge를 허용받은 모듈 없음 → registry에서 두 항목을 빼면 방향 게이트가 전이 의존까지 차단. +5. **HS1은 빌드 단계에서 뚫려 있음.** 순수성 task는 `application-*`만 검사(`ArchitecturePlugin.java:147`) → domain-core에 외부 의존성을 추가해도 빌드 통과(ArchUnit `DOMAIN_IS_PURE`는 실제 import한 경우만). +6. **CI가 아키텍처 게이트를 반복 실행**: `notification-platform.yml:84-85`, `fileserver-certification.yml:50`, `jpa-release.yml:123-125`, `releaseCheck`는 `ci` 전체 재실행. +7. **기능 전용 플러그인 5개가 root에**(`build.gradle:24-28`) → `:domain-core:check` 한 번에도 notification·jpa·messaging 플러그인 설정 실행. +8. **ArchUnit이 모든 leaf를 보지 않음.** 대상은 app-bootstrap architectureTest 런타임 classpath; websocket·grpc 어댑터는 `conditionalTransportBuildContractTest` 쪽에만(`app-bootstrap/build.gradle:261-263`), optional-platforms 18 leaf와 sample도 빠짐. 전 leaf를 보는 HS5 게이트는 Gradle 방향 task뿐. + +#### 2026-09-16 계획 이행 상태 +- Track A: 완료(커밋 기록 기준). +- B1 공통화: 부분 — composite action은 널리 쓰임; `_reusable-gradle.yml`은 job 2개만 쓰고 그중 하나는 항상 실패(1차 O-2). +- B2 release 1개로: 미완 — tag `v*` 트리거 workflow 3개(`release.yml`, `jpa-release.yml`, `fileserver-certification.yml`). +- B3 PR은 변경 모듈만: 부분 — 경로 필터는 pr-adapters, notification, fileserver-pr, redis, messaging; `ci-quality-gates`는 PR마다 55개 leaf `:ci` 전체; `object-storage-qualification`은 경로 필터 없이 PR마다 MinIO 컨테이너. +- B4 게이트 재배치: 미이행 — 표의 ✗ 11개가 여전히 PR. +- B5 gate matrix: 방향 변경(매트릭스 파일 삭제, `ci-quality-gates.yml:5-10`). +- B6 도달 불가 task: 잔존(jmh 4 leaf, 테스트 0개 quarantine). +- Track C: 대부분 완료 — 이미지 build·push, CycloneDX SBOM, Trivy 스캔 있음, 서명 없음(cosign 0). + +#### 목표안 비교 +| 안 | build-logic+tools LOC | leaf build | workflows | HS1 | HS2/HS3 | HS5 | 잃는 것 | 작업 규모 | 위험 | +|---|---|---|---|---|---|---|---|---|---| +| O1 중복만 정리 | 약 12,500–13,000 | 약 3,450 | 약 2,700 | ArchUnit + 컴파일러 | registry + ArchUnit | Gradle 게이트 | 없음 | 파일 약 25개 삭제, leaf 약 12개 | 낮음 | +| O2 단계 재배치만 | 16,768 | 약 3,520 | 약 2,720 | 동일 | 동일 | 동일 | 없음(유지비 그대로) | root 약 20줄, leaf 3, workflow 3 | 낮음 | +| **O3 아키텍처 코어 + 컨벤션만 build-logic, 기능 검사는 소유 leaf 테스트로** | 약 3,500–4,000 (build-tools 0) + leaf 테스트 +2,000–3,000 | 약 3,200 | 약 2,400 | ArchUnit + 순수성 task(domain-core 포함) | 동일 | Gradle 게이트 | 빌드 산출물로서의 evidence manifest, 삭제 플러그인의 TestKit | 파일 약 120개 삭제, 테스트 30–40개 신설, leaf 약 20, workflow 약 8 | 중간 | +| O4 ArchUnit 중심 (Gradle 방향 task 제거) | 약 2,000–2,500 | 약 3,200 | 약 2,400 | 동일 | 동일 | ArchUnit만 | 선언만 된 edge, runtimeOnly edge, app-bootstrap classpath 밖 leaf 전부 | 중간 | HS5 약화, 높음 | +| O5 Gradle 기본 기능만 (Groovy 스크립트 플러그인, TestKit 없음) | 약 800–1,200 | 약 3,200 | 약 2,400 | 동일 | 동일 | 약 100줄 Groovy | 게이트 자체 테스트, configuration cache·parallel 안전성 재증명(`ArchitecturePlugin.java:91-95`) | 큼(09-18 Groovy→Java 전환 되돌림) | 높음 | + +#### 권고: O3 (순서: O2 → 바로 할 것 → O3) +- 이유: 목적에 필요한 빌드 코드는 registry, 방향·순수성 task, 컨벤션, 레인 하나로 충분(HS1-4는 ArchUnit이 이미 담당). 이미 내려진 결정과 같은 방향(`13-build-dependency-ci.md` §0 "build-tools evidence/readiness/qualification 플랫폼은 축소", "특수 plugin은 opt-in", §0-A 기능 계약은 "owner module test가 소유"). 선례 두 개(ADR-BUILD-001, `OperationalErrorRegistryContractTest`). +- 틀리면 반박되는 가정: (1) evidence manifest를 build-tools 밖에서 읽는 곳 없음(grep: build-tools, CI artifact 업로드 `ci-quality-gates.yml:195-201`, 문서뿐) — 감사·릴리스 소비자가 있으면 JPA manifest만 tag 단계에. (2) build-tools 로직 대부분 Gradle 무관(98파일 중 68파일, 3,416/5,888줄이 `org.gradle` 미import) → 테스트로 이전은 기계적. (3) 73개 leaf + 빌드 2개 전부를 보는 HS5 게이트는 Gradle 방향 task뿐. (4) leaf 테스트로 옮기는 검사는 읽는 파일을 `inputs`로 선언(안 하면 1차 O-4처럼 UP-TO-DATE 거짓 통과). +- 가장 강한 반론: 09-16 기록상 감사가 삭제하자던 17건이 실행으로 반박됐고 "작동하게 만드는 데는 코드가 든다"; Gradle task는 `@Disabled`로 조용히 꺼질 수 없지만 테스트는 가능. 답: 옮긴 테스트는 `rejectSkipped` 레인에서; 소유자 원칙상 이 검사들은 어차피 2단계 항목. +- 솔직한 평가: A 자체(TestKit 포함 약 1.3k줄)와 ArchUnit은 규모가 정당 — 줄일 대상 아님. + +#### 바로 할 것 (어느 안을 고르든 안전) +1. `ca.runtime-membership`과 연결 코드 삭제(−318줄, 방향 게이트가 대신). +2. `quarantineTest` 삭제: `JavaConventionsPlugin.java:149-165`, `build.gradle:88-92`, CI job(약 −30줄). +3. `redis-sdk` job 삭제(1차 O-2, 약 −12줄). +4. `ca.strict-qualification` 13건을 `strictTestLanes`의 `requires` + `rejectSkipped`로(−666줄); messaging evidence reader가 읽는 XML 경로만 레인 기본 경로로. +5. `ca.evidence` 삭제, conditional-transport를 app-bootstrap 레인으로(−682줄). +6. XML reader 통합: `JUnitEvidenceReader`, `MongoJUnitXml`(−293줄). +7. API surface 구현 하나로(약 −550줄). +8. `dependency-policy`를 Gradle 기본 기능으로(−495줄): fileserver는 app-bootstrap `allowed_dependencies`에서 두 항목 제거; yaml/jackson은 `constraints { … version { rejectAll() } }`(`rejectAll`이 모듈 유입 시 해석을 실패시키는지 leaf 1개로 먼저 확인 — 미검증). +9. 순수성 task 필터에 domain-core·shared-contract 추가(+약 3줄) → HS1 빌드 단계 공백 해소. +10. CI 아키텍처 게이트 중복 실행 제거(약 −10줄). +11. `ca.test-jvm-agents`를 java-conventions에 합침(−80줄), jmh는 `me.champeau.jmh` 또는 삭제(−245줄). +12. 단계만 옮기기(삭제 없음): `ci`에서 `configContractCheck`, `qualificationCheck`, `sampleWebContractCheck` 제거; `ci-quality-gates.yml:62`에서 `:verifyPublicPathSnapshot` 제거; graphqlStable·conditionalTransport, jpa-candidate job, configuration-cache job을 integration-main으로; notification·jpa·mongo·api-surface 검사를 leaf `check`에서 떼어 `mainCheck`로; build-logic·build-tools job에 경로 필터. + +1–11 합계 약 3,400줄 감소, 잃는 보호 없음. + +#### 조사 범위 +전체: root build·settings, build-logic `build.gradle`·README, `ArchitecturePlugin`과 task 3개, `ModuleRegistry`·installer, RuntimeMembership, Java·Quality·레인 컨벤션, `StrictTestLanePlugin`, `StrictQualificationExtension`, `EvidenceExtension`, `ci-quality-gates.yml`, 09-16 계획, 1차 Group O, 13-build §0. 훑음: build-tools(구조, task 등록, Gradle API 비중, API surface verifier 2개), 나머지 workflow(트리거·job·gradle 호출), leaf build(스크립트 분류 + 3개 정독), ArchUnit(규칙 이름 + 2개 파일). 추정: `rejectAll` 동작, 각 안의 LOC, PR 소요 시간. git 이력상 build-logic·build-tools는 `60b6a319`에서 새로 추가된 것으로만 보여 09-18 이전 구성요소별 도입 이유는 추적 불가. + +### TEST — 테스트 가독성과 구조 + +#### 결론 +given/when/then 흐름은 이미 상당 부분 보인다. 6줄 이상 테스트의 71%(5,313/7,463)는 빈 줄로 단계를 나누고, 이름은 8,743개 전부 camelCase 행동 문장이다. 필요한 일은 스타일 신규 도입이 아니라 **지금 스타일을 규칙으로 적고 `// given // when // then` 주석을 명시하는 것**이다(주석을 모두 갖춘 파일은 현재 0개). + +가독성보다 급한 문제 두 가지: +- **fake가 실제 adapter와 같은 계약 테스트를 통과하지 않는다.** 1차 리뷰의 "fake가 결함을 숨긴 6건" 중 5건은 공유 contract 테스트나 실제 구현을 거치는 테스트가 있었으면 잡혔을 것으로 판단. 나머지 tus 1건은 "테스트 하나에 행동 하나" 규칙으로 잡혔을 것. +- **이름이 약속한 것을 단언하지 않는 테스트가 많다.** 존재·타입·예외 없음만 확인하는 테스트 약 1,050개(12%). + +adopter가 복사하는 `sample-portfolio`가 가장 약하다(DisplayName 0%, 단계 분리 54%, 115줄 테스트 1개) → migration은 sample부터. 8,764개 전체 재작성은 권하지 않는다. + +#### 계층별 평가 +`blank%` = 6줄 이상 테스트 중 빈 줄로 단계를 나눈 비율, `DN%` = @DisplayName 메서드 비율, `weak%` = 존재·타입·no-throw 단언만 있는 비율. + +| 계층 / 모듈 그룹 | 샘플 파일 | GWT가 보이나? | 이름 | 단언 품질 | 주요 문제 | +|---|---|---|---|---|---| +| domain (`domain-core` 2 + sample domain) | `DomainCoreContractTest`, `WorkLogTest`, `PosterTest` | 짧아서 대체로 보임, `WorkLogTest`는 빈 줄 없음 | camelCase, DN 0% | 값과 reason 코드까지 | `WorkLogTest.java:35` NPE 타입만; `WorkLogTest.java:65`, `PosterTest.java:46` 한 테스트에 행동 2개. 좋은 예 `PosterTest.java:73` | +| shared-contract (242) | `TraceParentTest`, `OperationalErrorTest` | 대부분 한 줄(blank 27%) | DN 2% | 구체적 값 | 표 형태인데 파라미터화 안 됨(30개·32개가 거의 같음) | +| application-* (667) | `SubmitDurableOperationUseCaseTest`, `CacheAsideExecutorTest`, `DispatchOutcomeRecorderTest` | 좋음(78%) | 영어 문장, DN 14% | weak 16% | fake 중복(TransactionPort 15개), `DispatchOutcomeRecorderTest.java:169` no-op fake. 좋은 예 `SubmitDurableOperationUseCaseTest.java:92` | +| persistence (1,497) | `OutboxStoreAdapterTest`, `DurableOperationStoreContractTest`, `PostgreSqlWorkClaimContractTest`, `MongoChangeStreamRunnerTest`, sample `WorkLogRepositoryAdapter(Integration)Test` | 좋음(81%) | DN 52% | weak 15%, 필드 10개 한 줄씩 단언 | "contract" 테스트가 adapter가 아니라 raw SQL 검증; `OutboxStoreAdapterTest.java:140` 행동 5개. 좋은 예 `MongoChangeStreamRunnerTest.java:28` | +| outbound 기타 (1,804) | `RedisHashOperationsContractTest`, `LiveRedisGuardrailTest`, `RoutingNotifierTest`, `FailOpenDependencyLoggerTest`, `DefaultGenericHttpGatewayTest`, `LocalPersistentControlPlaneTest` | 74% | DN 33% | weak 12%, 30줄 넘는 테스트 143개 | Redis `*ContractTest` 16클래스(160 tests)가 in-memory에서만; PII 부재 단언이 항상 통과 | +| inbound (2,139) | `TusProtocolContractTest`, `NotificationCallbackMvcControllerTest`, `RateLimitKeyResolverTest`, `GlobalExceptionHandlerTest`, `GraphQlMutationIdempotencyContextTest`, `HandshakeAdmissionPipelineTest` | 65% | DN 47% | weak 11%, envelope 필드 줄마다 단언 | 수락+거부를 한 테스트에(#11을 숨김), 컨트롤러 직접 호출로 HTTP 경로 우회. 좋은 예 `HandshakeAdmissionPipelineTest.java:103` | +| grpc:* (588) | `GrpcIdempotencyInterceptorTest`, `GrpcOperationLedgerRepositoryTest`, `InMemoryOperationLedger` | 68% | DN 98% | **weak 3%, 최고** | fake가 FAILED→COMMITTED 허용(#15), 공유 ledger contract 없음 | +| messaging:* (829) | `MessagingAdapterContract`, `InMemoryHarnessContractTest`, `OutboxRelayTest` | 80% | DN 18% | weak 15%(대부분 validator 예외 타입) | **공유 contract 모범 사례가 이미 있음.** 단 relay 테스트 fake가 인코딩을 안 해 #7을 숨김. 좋은 예 `OutboxRelayTest.java:46` | +| bootstrap (757) | `ArchitectureViolationFixtureTest`, `CapabilityDependencyValidatorTest`, `TracingActivationContextTest`, `MetricsContractConfigTest` | 57% | DN 26% | weak 6% | 복붙 테스트 55개, `assertThat(context).isNotNull()` | +| **sample-portfolio (218)** | 파일 9개 | 54% | DN 0% | weak 11% | 115줄 테스트, 동작이 다른 FakeRepo 2개, 인자 7개 생성자 호출 7번 반복, TransactionPort fake 10개 | + +#### Findings (영향 큰 순) + +1. **[Required] fake가 실제 adapter와 같은 계약으로 묶여 있지 않다.** 일부 fake는 Javadoc에 "adapter와 같은 의미"라고 적었지만(`InMemoryDurableOperationStore.java:12-19`, `InMemoryOperationLedger.java:15-19`) 확인하는 테스트가 없다. 반대 계약 검증도 있다: `GrpcOperationLedgerRepositoryTest.java:191`은 JPA 쪽에서 "FAILED는 종료 상태"를 검증, fake는 그 상태에서 COMMITTED 허용. `DurableOperationStoreContractTest.java:183`은 adapter를 거치지 않고 raw SQL로 충돌만 확인(예외 타입만). + +2. **[Required] 이름이 약속한 성질을 단언하지 않는다.** + - `PostgreSqlWorkClaimContractTest.java:78` `claimsAreDeterministicallyOrdered`: 순서는 안 보고 `isNotEmpty()`만. + - `WorkLogUseCasesTest.java:281` `batchCreatePersistsEveryItemAtomically`: 트랜잭션 fake가 그냥 통과시켜 원자성 증명 불가, 개수 2개만. + - `RoutingNotifierTest.java:174`: 예외 메시지가 `"provider-failure"`라 원래 PII가 없어 `doesNotContain("secret@gmail.com")`은 절대 실패 안 함(`FailOpenDependencyLoggerTest.java:71` 동일). + - `NotificationCallbackMvcControllerTest.java:118` "…BeforeIngress": 미리 만든 `byte[]`를 컨트롤러에 직접 넘겨 converter 경로 우회. + - `MetricsContractConfigTest.java:57`: SLO 버킷 대신 `isNotEmpty()`. + - `SampleApplicationContextTest.java:45`, `TracingActivationContextTest.java:79`: `assertThat(context).isNotNull()`. + - 규모 추정: presence만 133, 예외 타입만 672, no-throw만 123, 섞임 124 → 약 1,050개(12%). 단언 없는 93개는 대부분 ArchUnit `.check()`라 정상. presence만 7개를 직접 봤더니 5개는 실제로 약함. 예외 타입만은 대부분 validator 테스트라 "틀린 이유로도 통과"(예: `WorkLogTest.java:35`는 어느 인자가 null이어도 NPE). + +3. **[Required] 한 테스트에 행동이 여러 개.** 약 646개(7.4%): 예외 단언 블록 2개 이상 484개 ∪ 단언 뒤 다시 행동 181개. 결함을 숨긴 사례: `TusProtocolContractTest.java:149`는 수락과 거부를 한 테스트에 묶고 chunk 2에는 틀린 checksum만 보내 누적 digest 버그(1차 C-1)가 안 보임. 규칙 "`// when`은 정확히 하나"로 GWT 요청과 이 문제가 같이 풀림. + +4. **[Required] 복사 원본인 sample이 가장 약하다.** `PosterImagePublicationWorkflowTest.java:73`: 115줄, mock 3개, `thenAnswer` 안에서 assert, inline FQCN, 인자 16개 생성자, 행동 4개. FakeRepo 두 벌이 다르게 동작: `WorkLogUseCasesTest.java:45`는 upsert + 필터, `CreateWorkLogOutboxTest.java:48`은 append + `findPage` 빈 결과; 둘 다 실제 adapter와 달리 정렬 무시(`WorkLogRepositoryAdapter.java:71-74`). `WorkLogRepositoryAdapterTest.java:70` "maps to entity and back": id만 확인. + +5. **[Consider] fake 중복.** 테스트 구현 3개 이상인 포트 42개, 구현 합계 198개(lambda fake 미포함 → 하한). `TransactionPort` 26개/25파일/4모듈(`application-notification`은 공유 `PlatformFakes.java:54`가 있는데도 10개 파일이 따로), `MessagePublisher` 15, `ObjectControlStore` 7(한 모듈 안, 이름만 다른 InMemory/Map/Recording/Noop), `RedisRuntimeClient` 7(`BrokenClient` 4), `Clock` 직접 상속한 가변 시계 10. + +6. **[Consider] 표 형태 테스트가 파라미터화 안 됨.** `@ParameterizedTest`는 45개 파일뿐. 대상: `TraceParentTest`(30), `OperationalErrorTest`(32), `ArchitectureViolationFixtureTest`(55), `OutboxStoreAdapterTest.java:140`. + +7. **[Consider] 예외 단언이 when과 then을 한 식에 묶음.** `assertThatThrownBy` 계열 2,400개(27%), `catchThrowable` 26개. 캐스팅 관용구 `extracting(ex -> ((X) ex).reason())` 9개 파일 18줄. + +8. **[Consider] 내부 구현을 직접 다루는 테스트 약 170개(2%, 상한).** reflection 42, 컨트롤러 직접 호출 9, `verify`만 있는 테스트 31, 타입 모양 확인 89(architectureTest lane 밖). + +9. **[Nit]** `assertThat(x.contains(y)).isTrue()` 14개 파일 29줄; DisplayName 3,430개 영어, 한국어 1개(`MetricsAlertingContractTest.java:205`), 상당수는 메서드 이름을 띄어 쓴 것뿐. + +#### Fakes와 contract 테스트 + +| port | fakes (개수, 위치) | 실제 adapter | 공유 contract? | 발견된 차이 | +|---|---|---|---|---| +| `DurableOperationStorePort` | 2 — `application-core/.../InMemoryDurableOperationStore.java`, web testFixtures `TestDurableOperationStore.java` | `DurableOperationStoreAdapter` | 없음, PG 테스트는 raw SQL | 1차 #4 재제출 25P02, fake는 통과 | +| `GrpcOperationLedger` | 1 — `grpc-policy/.../InMemoryOperationLedger.java` | `JpaGrpcOperationLedger` | 없음 | 1차 #15 FAILED→COMMITTED | +| `RedisCommandGateway` | 1 (2.4k줄) — `InMemoryRedisCommandGateway` | `LettuceRedisCommandGateway` | 부분적: `LiveRedisOperationsFixture`는 있으나 contract 16클래스(160 tests)가 `new RedisOperationsFixture()`에 고정, live는 20 tests | HDEL/PEXPIRE 미재현 | +| `UploadApplicationService` (tus) | 1 — `InMemoryUploadApplicationService.java:117` | `DefaultUploadApplicationService` | 없음 | fake가 버그와 같은 누적 digest. contract만으로 부족, chunk 2 정상 케이스 필요 | +| `DeliveryProjectionStorePort` | 3 — `DispatchOutcomeRecorderTest.java:169`(no-op), `NotificationPlatformNoops`, `ProviderEventLateMatchTest.java:211` | `JpaDeliveryAttemptStore` | 없음 | projection 덮어쓰기(1차 B-5) | +| `MessagePublisher` | 15 / 10파일 | `DefaultMessagePublisher` | 없음, relay는 `RecordingOutboxPublisher`(`OutboxRelayTest.java:416`) | 1차 #7 재인코딩 실패 | +| `WorkLogRepository` (sample) | 2, 서로 다른 동작 | `WorkLogRepositoryAdapter` | 없음 | 정렬 무시, save 의미 불일치 | +| `IdempotencyStorePort` | 4 (app-core, web ×2, sample) | `IdempotencyStoreAdapter`, `RedisIdempotencyStoreAdapter` | 없음 | 미평가 | +| `ObjectControlStore` | 7 (objectstorage 한 모듈) | `LocalDevObjectControlStore`, `S3ConditionalObjectControlStore` | 없음 | 미평가 | + +**권장 패턴:** 저장소 안에 이미 있는 `MessagingAdapterContract`(`messaging-testkit/.../MessagingAdapterContract.java:19`, 사용처 `InMemoryHarnessContractTest.java:14`)를 표준으로. +``` +포트 소유 모듈의 testFixtures: + abstract class XxxContract { protected abstract Xxx subject(); @Test ... } +fake 쪽 unit lane: InMemoryXxxContractTest → @Nested class Contract extends XxxContract +adapter 쪽 PG/live lane: JpaXxxContractTest → 같은 @Nested 구조 +``` +static kit 방식(`LegacyOutboxAppendContract`)은 쓰지 않는다 — 새 검증을 추가해도 사용하는 쪽이 호출하기 전까지 어디서도 실행되지 않음. 추상 클래스 방식은 케이스를 추가하는 순간 모든 구현에서 돈다. `application-core/src/testFixtures`는 이미 있지만 지금은 persistence-jpa PG lane만 소비(`persistence-jpa/build.gradle:88`) → 다른 모듈은 `testImplementation(testFixtures(project(':application-core')))` 추가. Object Mother는 이미 쓰는 `OutboxFixtures.pending()`, `ContractMessage.orderCreated()` 형태가 기본; builder는 인자 6개 이상이고 테스트마다 필드 2개 이상 바꿀 때만(`CreateWorkLogCommand` 9, `PublishPosterImageCommand` 10, `UpdateWorkLogCommand` 6). + +#### 제안 컨벤션 (새로 쓰거나 고치는 테스트에만) +1. **이름**: lowerCamelCase 행동 문장 `<상황/주체><결과>`(지금 방식 유지; `test`/`should` 접두어·snake_case 도입 안 함). **이름에 적은 성질은 반드시 단언한다.** +2. **@DisplayName**: 선택. 메서드 이름으로 못 쓰는 내용(숫자, 기호, "왜")이 있을 때만. 언어는 저장소 단위로 하나 — 기본 영어(현재 3,430개). 한국어 전환은 소유자 결정, 바꾸더라도 새 테스트부터. (반론: 한국어 팀은 IDE 리포트에서 한국어가 잘 읽힘 — 파일마다 섞이는 비용이 더 큼.) +3. **GWT 주석**: 본문 statement 3개 이상이면 `// given` `// when` `// then` 필수 + 구역 사이 빈 줄. 준비할 게 없으면 `// given` 생략. 한 줄 테스트(순수 함수 입력 → 단언 1개)와 ArchUnit `.check()`는 주석 없이. **`// when`은 정확히 하나** — 두 번 필요하면 테스트를 둘로. 예외 테스트는 `catchThrowable`로 when 분리; 기존 `assertThatThrownBy`는 손댈 때 `// when & then` 표시까지 허용. +4. **@Nested**: 테스트 10개 이상이고 대상 연산 2개 이상인 클래스에서만, 연산 단위 한 단계. contract 테스트에도 사용. +5. **단언**: then은 when의 결과 하나에 대해서만. 여러 필드는 `usingRecursiveComparison().isEqualTo(expected)` 또는 `extracting(..).containsExactly(..)`. `isNotNull`/`isNotEmpty`/`isPresent`/`doesNotThrowAnyException`만으로 끝내지 않음(이름이 "예외 없음" 자체를 말할 때만 예외). 예외는 타입 + reason/message(`isInstanceOfSatisfying`). `assertThat(x).contains(y)` 형태. 표 형태 입력은 `@ParameterizedTest`. +6. **fake vs mock**: 포트는 hand-rolled fake, 포트당 하나, 포트 소유 모듈 testFixtures에. adapter가 있는 포트면 fake와 adapter가 같은 `XxxContract` 통과. Mockito는 프레임워크 경계(Spring Data repo, SDK client)와 장애 주입에만, `thenAnswer` 안에서 assert 금지. no-op fake는 결과를 단언하지 않는 협력자에만. + +**Before** — `src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/worklog/WorkLogUseCasesTest.java:232-264` +```java + @Test + void updateRejectsRevertingStatusToOpen() { + FakeRepo repo = new FakeRepo(); + WorkLog created = + new CreateWorkLogUseCase( + repo, IDS, STUB_EVENT_IDS, NO_OP_OUTBOX, NO_CORRELATION, UTC_CLOCK, TX) + .handle(createCmd("status revert")); + WorkLog inProgress = + new UpdateWorkLogUseCase(repo, TX) + .handle( + new UpdateWorkLogCommand( + created.id(), + Patch.absent(), + Patch.absent(), + Patch.absent(), + Patch.absent(), + Patch.of(WorkLogStatus.IN_PROGRESS))); + + assertThatThrownBy( + () -> + new UpdateWorkLogUseCase(repo, TX) + .handle( + new UpdateWorkLogCommand( + inProgress.id(), + Patch.absent(), + Patch.absent(), + Patch.absent(), + Patch.absent(), + Patch.of(WorkLogStatus.OPEN)))) + .isInstanceOf(WorkLogInvariantException.class) + .extracting(ex -> ((WorkLogInvariantException) ex).reason()) + .isEqualTo(WorkLogInvariantException.Reason.INVALID_STATUS_TRANSITION); + } +``` + +**After** — 같은 동작 검증(필드는 JUnit 기본 수명이라 테스트마다 새 인스턴스) +```java + private final FakeRepo repo = new FakeRepo(); // sample testFixtures 공유 fake로 이동 예정 + private final CreateWorkLogUseCase create = + new CreateWorkLogUseCase(repo, IDS, STUB_EVENT_IDS, NO_OP_OUTBOX, NO_CORRELATION, UTC_CLOCK, TX); + private final UpdateWorkLogUseCase update = new UpdateWorkLogUseCase(repo, TX); + + @Nested + class Update { + + @Test + void rejectsMovingAnInProgressWorkLogBackToOpen() { + // given + WorkLog inProgress = update.handle(statusChange(aCreatedWorkLog().id(), IN_PROGRESS)); + + // when + Throwable thrown = catchThrowable(() -> update.handle(statusChange(inProgress.id(), OPEN))); + + // then + assertThat(thrown) + .isInstanceOfSatisfying( + WorkLogInvariantException.class, + e -> assertThat(e.reason()).isEqualTo(Reason.INVALID_STATUS_TRANSITION)); + } + } + + private WorkLog aCreatedWorkLog() { + return create.handle(createCmd("any title")); + } + + private static UpdateWorkLogCommand statusChange(WorkLogId id, WorkLogStatus status) { + return new UpdateWorkLogCommand( + id, Patch.absent(), Patch.absent(), Patch.absent(), Patch.absent(), Patch.of(status)); + } +``` + +#### Migration과 enforcement 계획 +1. **규칙 문서화 (PR 1개).** 위 6개 규칙을 canonical `AGENTS.md` "테스트 전략"에 약 25줄, `CLAUDE.md` Testing에는 포인터 한 줄. 이후 적용 범위는 새로 쓰거나 고친 테스트. +2. **`sample-portfolio` 전체 (62 files / 218 tests).** `WorkLogRepositoryContract`를 만들어 fake와 `WorkLogRepositoryAdapter`(integrationTest lane) 양쪽에서; TransactionPort fake 하나로; `PosterImagePublicationWorkflowTest` 행동별 분리. +3. **divergence가 확인된 6개 포트의 contract**를 1차 Wave 1 수정과 같은 PR에서. contract가 현재 코드에서 먼저 실패하면 그 자체가 회귀 테스트. Redis는 contract 16클래스를 fixture 타입으로 추상화하고 live lane subclass 추가. 공용 `RecordingTransactionPort`는 `application-core` testFixtures. +4. **계층별 모범 모듈 하나씩**(수정 때문에 어차피 손대는 곳): application-core `operation`/`idempotency`, persistence-jpa `operation`/`outbox`, web `error`, cache-redis `sdk/lettuce/operations`. +5. **약한 단언 정리(목록, 게이트 아님).** presence만 133 + no-throw만 123은 모듈별로; 예외 타입만 672는 이름이 reason을 약속하는 경우만; 나머지는 손댈 때(boy-scout). + +**Enforcement 판단** +- **GWT 주석 게이트는 만들지 않는다**: 주석은 bytecode에 없어 ArchUnit이 못 봄; Checkstyle로 "statement 3개 이상 메서드"만 골라 검사하기 어려움; 이 저장소는 텍스트 파서 게이트를 이미 지웠음(`verifyDocumentedLeafCount` 삭제); `// when`이 있다고 행동 하나가 증명되지도 않음. +- Consider: Checkstyle `MethodLength`(max 50)를 test에 — 설정 파일을 main/test가 공유(`QualityConventionsPlugin.java:60`), 현재 50줄 초과 테스트 68개를 baseline 억제 필요, integrationTest/systemTest lane은 Checkstyle 대상 아님 → 비용 작지만 효과 중간 이하, 지금은 보류 권고. +- 실질적 강제 수단은 구조: fake와 adapter가 같은 추상 contract를 상속하면 한쪽만 약해지는 일이 없다. + +#### Coverage note +범위: 등록 leaf 73개의 main·testFixtures 제외 모든 source set; `@Test/...` 파일 1,483, 메서드 8,743(호출 측 1,500/8,764와 차이는 regex 차이). 스크립트: scratchpad `{stats,methods,weak2,fakes,tgrep}.py`. 약 40개 파일을 메서드 단위로 읽고 약한 단언 분류 14개는 본문 직접 판정. 한계: 분류는 AST 아닌 regex 추정; lambda fake 미포함; graphql·websocket systemTest 깊게 안 읽음; "5/6건을 잡았을 것"은 판단(tus·notification 건은 누락 케이스 추가 가정); 단언 강도를 정확히 재려면 한두 모듈에 PIT mutation 테스트. + +### X1 — 모듈 간 기능 중복 + +#### 기능 지도 (현재 → 권고) + +| 기능 | 현재 구현 | 공유 계약? | 갈라짐? | 권고 | 크기 | +|---|---|---|---|---|---| +| Outbox | 저장 모델 3개(`outbox_event`, `*_v2` 테이블 5개, `messaging_outbox`), append 포트 4개, claim SQL 4개, relay 3개(+Debezium CDC), retry 정책 3개, 정리 작업 2개. 기본 조립은 v1만 | app-core에 세대 3개 공존, messaging은 별도 | 예 | 앱 쪽 1개(v1 테이블 + fencing claim), V2 삭제; messaging outbox는 유지 | L | +| 요청 멱등성 | 계약 2개(v1/V2), store 3개, executor 조립 위치 3곳, inbound 전용 ledger 3개(websocket SPI, graphql context, grpc ledger) | app-core v1+V2 | 예 | V2를 정본, v1 삭제, 조립 1곳, inbound는 V2 사용 | M | +| 자연키 생성-또는-반환 | durable operation(예외 catch), notification request(`ON CONFLICT`), 미사용 upsert executor | 없음 | 예 (Critical #4) | durable operation을 notification 방식으로, upsert executor 삭제 | S | +| Inbox / 소비자 dedup | app-core inbox(소비자 0), messaging inbox(미조립), mongo 변경 dedup, notification provider ledger | 포트 2개 | 복붙 흔적 33% | app-core inbox 삭제, 나머지 유지 | M | +| lock / lease / fencing | app-core 포트 4개(lock, lease, cache refresh, operation lease), row lease 약 9개, 범용 claim executor(참조 0) | owner·attempt record 중복 | 예 | 미사용분 삭제, fencing은 contract kit로 검증 | M | +| caller 트랜잭션 guard | 9벌 복사 | 없음 | 예 (E-3) | persistence-jpa 안 helper 1개 | S | +| Backoff 계산식 | 10개 | 없음 | "full jitter" 뜻 3가지 | 앱 쪽 5곳에 shared-contract `Backoff` | S | +| Rate limit | shared-contract 포트 + Redis 구현(조립됨), web 전용 병렬 타입 세트(구현체 0) | 있음 | 예 (FAIL_OPEN 허용 여부) | web 병렬 타입 삭제 | S | +| Admission / in-flight | 약 11개 | 없음 | 예 (gRPC M1 수정이 1곳만) | 유지, `Semaphore` 사용 | S | +| Kafka producer | 2개(legacy seam, platform) | messaging bridge | 둘 다 TLS/SASL 없음 | outbox 정리에 포함 | M | +| 파일 control plane / canonical JSON | 직접 짠 JSON parser 3개, 파일 CAS store 3개, `FilePublicationPort` 소비자 0 | 없음 | 예 | 결정 필요(삭제 권고) | L | +| readiness / evidence / API-surface / moduleboundary | 카드 스키마 3개, 검증기 3개, family별 evidence plugin 5개, API-surface gate 3개, moduleboundary 3벌(main 1.7k줄) | build-logic에 범용 plugin 있음 | 예 | build-logic으로 통합 | L | +| 테스트 fake / contract kit | `TransactionPort` fake 21개 등; 실제 adapter에 도는 kit는 1개 | ADR-BUILD-001 (`testFixtures`) | first-pass fake 결함 6건 | 포트별 kit를 `testFixtures`에 | M | + +#### 발견 (효과 큰 순) + +**1. [Required] Outbox: 세대 3개 공존, 실제 조립된 v1이 가장 약함** +- 구현: 조립(v1) `LegacyOutboxAppendPort` → `OutboxStoreAdapter` → `PostgreSqlOutboxClaimRepository`/`H2OutboxClaimRepository` → `PublishPendingOutboxEventsUseCase` + `OutboxRelayScheduler` → `OutboxReaper` (`ca-skeleton.outbox.enabled=true`일 때만). canonical 추가분 `OutboxAppendPort` → `CanonicalOutboxAppendAdapter`(같은 `outbox_event`). V2(미조립) `OutboxAppendPortV2`, `OutboxPollingDeliveryPortV2`, `PostgreSqlImmutableOutboxAppendAdapter`(376), `PostgreSqlPollingDeliveryAdapter`(549), `PublishNextOutboxDeliveryUseCase`, `OutboxV2RetryPolicy`, migration `jpa/outbox-storage`, `jpa/outbox-polling`. messaging `JdbcOutboxRepository`(721), `OutboxRelay`, `OutboxRelayWorker`, `OutboxRetryScheduler`, `OutboxCleanupJob`, `messaging_outbox`. +- 조립 상태: V2 adapter는 stereotype 없음(`PostgreSqlPollingDeliveryAdapter.java:29-43`), main 참조 0, migration location 미설정(grep `outbox-storage|outbox-polling` → 테스트만). messaging relay는 `@ConditionalOnBean(OutboxRepository)`(`MessagingReliabilityAutoConfiguration.java:81`)인데 앱에 bean 없음; app-bootstrap·adapter main의 `messaging.reliability` import 0. "새 코드는 이것을 쓰라"는 `OutboxAppendPort`(`LegacyOutboxAppendPort.java:6`) 소비자 0, 소비자 7곳 모두 `LegacyOutboxAppendPort`. +- 갈라진 증거: v1은 fencing 없음 — claim이 `IN_FLIGHT` 행 재획득(`PostgreSqlOutboxClaimRepository.java:15-29`), `markPublished`/`markFailed`가 `eventId`만으로 씀(`OutboxStoreAdapter.java:93,106`), claim·발행·결과 기록이 별도 트랜잭션(`PublishPendingOutboxEventsUseCase.java:91,142,160`). messaging `V1002__messaging_outbox_lease_fencing.sql:1-14` 주석이 바로 이 시나리오("A 멈춤 → B 재claim·발행 → A가 FAILED로 덮어씀 → 중복 발행")를 버그로 설명하고 `lease_owner/lease_token`으로 고침; V2도 owner CAS로 고침. **고친 두 구현은 미조립, 조립된 v1은 미수정.** 추가: `CanonicalOutboxAppendAdapter`만 트랜잭션 guard 없음(1차 E-3); canonical 이벤트가 v1 claim을 타며 aggregate 순서 깨짐(1차 E-5); `OutboxBackoffPolicy`·`OutboxV2RetryPolicy` 역할 중복(1차 A-3); legacy producer(`KafkaSenderAutoConfiguration.java:61-81`)도 TLS/SASL 없음(Critical #8과 같은 문제). +- 권고: 앱 outbox 1벌 — 저장소는 소비자와 V13/V14 canonical 컬럼이 있는 `outbox_event`; claim에 V2/V1002의 owner+token CAS 이식 후 V2(app-core `outbox/v2` 약 800줄, persistence-jpa 1,055줄, migration 2종) 삭제; append 포트는 `OutboxAppendPort` 하나(legacy는 cutover 후 삭제). 계약 위치 application-core `outbox`, contract kit는 기존 `application-core/src/testFixtures/.../LegacyOutboxAppendContract` 확장 + fencing 시나리오. messaging outbox는 vendored라 유지하되 `src/messaging/CLAUDE.md`에 "앱은 `messaging_outbox`를 쓰지 않는다" 명시. +- adopter가 몰라도 되는 것: 어느 append 포트/테이블이 정본인지, 어느 relay가 도는지. +- 가정/반론: V2 cutover 설계(`2026-09-18-outbox-v2-*` spec)를 계속 추진할 계획 없음 / V2가 더 안전 → 그렇다면 V2를 조립하고 v1 삭제. 어느 쪽이든 목표는 1벌. 승인자: 소유자. + +**2. [Required] 멱등성: 계약 2개, store 3개, 조립 3곳, inbound 전용 ledger 3개** +- 구현: v1 `IdempotencyStorePort`/`IdempotencyExecutor`/`IdempotencyStoreAdapter`(+H2·PG claim repo); V2 `IdempotencyStorePortV2`/`IdempotencyExecutorV2`, `PostgreSqlOwnerSafeIdempotencyStore`(662), `RedisIdempotencyStoreAdapter`(534) — v1과 같은 `idempotency_record` 테이블을 상태 어휘만 바꿔 사용(`jpa/idempotency/V1__expand_owner_safe_v2.sql:107`). inbound 전용: websocket `CommittedResultLedger`(inbound가 정의한 저장 SPI, main 구현 0), graphql `GraphQlMutationIdempotencyInterceptor`(요청 경로 밖), grpc `GrpcOperationLedger` + `JpaGrpcOperationLedger`(optional build, 별도 테이블). +- 소비자: v1 executor는 sample `PublishPosterImageUseCase.java:121`만; `IdempotencyExecutorV2`는 조립 클래스(`RedisIdempotencyConfig`, `PostgreSqlIdempotencyProviderConfig`, `IdempotencyProviderSelectionConfig`) 외 호출자 0. +- 갈라진 증거: V2 executor 두 곳에서 다르게 조립 — Redis는 `getProcessingLease()` 읽음(`RedisIdempotencyConfig.java:71-73`), PostgreSQL은 `Duration.ofMinutes(2)`·`"json.v1"` 하드코딩(`PostgreSqlIdempotencyProviderConfig.java:36,39`). v1 완료 기록 실패 시 action 재실행 결함(1차 A-8). 자연키 dedup 두 방식: `JpaNotificationRequestStore.java:47-77` `ON CONFLICT DO NOTHING` 후 승자 읽기(주석에 25P02 이유) vs `DurableOperationStoreAdapter.java:60` catch 후 같은 트랜잭션 재조회(Critical #4); 범용 `RegisteredPostgreSqlUpsertExecutor` 참조 0. +- 권고: V2를 정본으로 하고 이름에서 `v2` 제거(application-core `idempotency`); sample을 V2로 옮기고 v1 전부 삭제; executor는 `IdempotencyProviderSelectionConfig` 한 곳에서 `IdempotencySettings`로, provider는 store bean만; websocket `CommittedResultLedger` 삭제(inbound가 저장 SPI를 갖는 건 방향이 틀림); graphql은 V2에 연결하거나 `idempotencyKey` allowlist 제거; `DurableOperationStoreAdapter`는 notification 방식으로, upsert executor 삭제; grpc ledger는 유지(vendored, ADR-GRPC-004). +- 반론: v1이 더 단순 — 하지만 Redis는 V2만 구현하고 소유자 fencing은 V2에만 있음. + +**3. [Required] 테스트 fake: 같은 포트를 모듈마다 따로 흉내, 실제 adapter와 대조하는 kit 거의 없음** +- 구현(테스트 source set): `TransactionPort` fake 21개(application-notification 11, sample 6, app-core 4), `ObjectControlStore` fake 7개(한 leaf 안), `IdempotencyStorePort` 4 + V2 3, `DurableOperationStorePort` 2(app-core `InMemoryDurableOperationStore`, web `testFixtures/TestDurableOperationStore`), `OutboxRepository` 3, `InboxRepository` 2. +- 갈라진 증거: 1차 공통 패턴 4(grpc ledger fake, tus fake digest, Redis fake HDEL/PEXPIRE, notification recorder, durable operation, messaging fake publisher); PG contract test가 adapter를 거치지 않고 raw SQL만 실행; app-core `DistributedLockPortContractTest.java:46`은 테스트 안에 정의한 `FakeDistributedLockPort`를 검증(fake를 테스트); 실제 adapter에 도는 kit는 `LegacyOutboxAppendContract` 하나뿐. +- 권고: 포트 소유 leaf의 `src/testFixtures`(ADR-BUILD-001)에 포트별 contract kit를 두고 fake와 실제 adapter 양쪽에서 실행. 우선순위: `DurableOperationStorePort`, `IdempotencyStorePortV2`, `GrpcOperationLedger`(grpc-testkit), `RecipientLeaseStorePort`, tus upload, Redis gateway. `DirectTransactionPort`는 application-core testFixtures에 1개. `ObjectControlStore` fake는 `@TempDir` 위 `LocalDevObjectControlStore`로 대체. +- 반론: 실DB lane이 느림 — kit는 fake에서도 돌아 최소한 fake 의미 = 실제 adapter 의미를 보장. + +**4. [Required] caller 트랜잭션 guard 9벌 복사, 빠진 곳에서 결함** +- 구현: persistence-jpa 7곳(`OutboxStoreAdapter:130`, `DurableOperationStoreAdapter:178`, `JpaLiveEventReplayAdapter:163`, `PostgreSqlImmutableOutboxAppendAdapter:337`, `PostgreSqlSameStoreInboxAdapter:502`, `PostgreSqlPollingDeliveryAdapter:488`, `IdempotencyCapabilityGuard:93`), messaging 2곳(`JdbcOutboxRepository:229`, `JdbcInboxRepository:102`). +- 갈라짐: `CanonicalOutboxAppendAdapter` 0건(E-3, 조용한 dual-write); notification JPA store 11개도 0건. +- 권고: persistence-jpa `transaction` 패키지 `CallerTransaction.require(op)` 하나(messaging은 vendored라 자기 것 유지). `@Transactional(MANDATORY)`는 V2 adapter가 bean이 아니라 proxy가 안 붙어 불가. Size S. + +**5. [Required] Rate limit: 공유 계약이 있는데 web에 같은 이름의 병렬 세트** +- 조립된 경로 `RateLimitInterceptor` → `dev.caskeleton.shared.ratelimit.EdgeRateLimitPort` → `RedisEdgeRateLimitAdapter`(이 저장소에서 공유 계약을 올바르게 만든 유일한 사례). 병렬 세트 web `ratelimit/WebRateLimiter`, `RateLimitDecision`, `RateLimitFailurePolicy` — `WebMvcThrottleFilter:10-11,41`, `WebFluxThrottleFilter:10-11,44`가 쓰고 main 구현 0(testFixtures `CountingRateLimiter`뿐). +- 갈라짐: web enum은 `FAIL_OPEN` 허용, shared enum은 `FAIL_CLOSED`만; 단순 클래스 이름이 같아 import 오선택 쉬움. +- 권고: web 병렬 타입·throttle filter 삭제 또는 `EdgeRateLimitPort`로 재연결(1차 I-8과 같은 결정). Size S. + +**6. [Required] lock / lease / claim: 소비자가 있는 포트와 구현체가 있는 포트가 어긋남** +- app-core: `DistributedLockPort`(JDBC 구현, 비즈니스 소비자 0); `DistributedLeasePort` + `LeaseWatchdog`(Redis 구현, 소비자 0, `LeaseGuarantee`에 `EFFICIENCY_ONLY` 하나뿐); `CacheRefreshCoordinationPort`(소비자 `CacheAsideExecutor` 있음, main 구현은 `Disabled`뿐). +- 중복 value type: `IdempotencyOwner`·`InboxOwner` 필드 동일(scope, ownerToken, attempt, stateRevision, claimOperationId); `IdempotencyClaimAttempt`, `InboxClaimAttempt`, `LeaseAttempt` 같은 구조. +- 미사용 범용: `postgresql/lock/PostgreSqlWorkClaimExecutor`·`WorkQueue*` 참조 0 — 그 사이 outbox, durable operation, notification, fileserver가 claim SQL을 각자 작성. +- 갈라짐: fencing 있음(messaging outbox, V2, fileserver `LeaseFence`) vs 없음(v1 outbox, notification `recipients.save` — 1차 B-5). +- 권고: claim executor 삭제(테이블마다 순서 요구가 달라 SQL 공유 이득 없음); lock과 lease 중 하나만(멱등성처럼 "포트 1 + provider 2" 또는 Redis lease adapter가 `CacheRefreshCoordinationPort` 구현) — 결정 필요; app-core inbox 삭제로 중복 record 해소; 공유할 것은 규칙 하나("종결 쓰기는 owner+token을 명시하고 밀려난 쪽의 쓰기는 아무것도 매칭하지 않는다") → `ClaimFencingContract` kit를 application-core testFixtures에 두고 각 row lease store에서 실행. + +**7. [Required] readiness / evidence / API-surface / moduleboundary: 같은 일을 하는 자체 프레임워크 여러 벌** +- readiness 카드 스키마 3개: `config/jpa/readiness-cards.yaml:2`(kebab-case, `state: selected`, build-tools `JpaReadinessRegistryValidator`), `config/messaging/readiness-cards.yaml:1`(camelCase, `maturity:`, app-bootstrap `MessagingCapabilityRegistryContractTest:128`), `docs/registries/object-storage-readiness.yaml:5`(snake_case, `claimed_level: R1`, `ContractRegistrySchemaGovernanceTest:32` + objectstorage test). +- evidence plugin family별: jpa 2,838줄, messaging 819, notification 851, mongo 544 — 범용 `ca.strict-qualification`은 leaf 9개에 이미 적용. +- API-surface gate 3개: `ca.api-surface`(build-logic), `ca.notification-api-surface`(156줄 verifier), jpa `verifyJpaAdopterApiSurface`(`JpaQualificationPlugin.java:57-62`) — persistence-jpa는 `ca.api-surface`(`build.gradle:8,167`)와 이것을 **둘 다** 적용. +- moduleboundary: `*StableModule`, `*ModuleBoundary`, `*ModulePurity`가 web/graphql/websocket **main**에 3벌(1,723줄), 테스트 `*BuildModel`/`*SourceGraph`도 3벌. +- 갈라짐: jpa 카드가 messaging에 없는 `messaging-cdc-dispatch.v1`을 가리키고 성숙도 어휘 불일치(1차 E-11). +- 권고: build-logic에 카드 스키마 1개 + 검증기 1개(id, R0–R3, family 간 prerequisite, 필수 task, 증거 selector, 한계), family plugin에는 증거 실행기만; API-surface는 `ca.api-surface` 하나로; moduleboundary는 production jar에서 빼서 `ca.architecture`/ArchUnit 규칙 1개로. Size L. 반론: 빌드 시점 코드라 런타임 위험 없음 — 단 family 간 참조가 이미 깨짐. + +**8. [Consider] 파일 publication: control plane·canonical JSON codec 중복 (결정 필요)** +- 구현: app-core `filepublication`(399) → fileserver 최상위 패키지(publication plane 8,567줄, `FileserverControlRecordCodec` 855 포함), `FilePublicationPort` main 소비자 0; deprecated `FileExportPort` → `FilesystemCsvExportAdapter`; objectstorage `CanonicalJsonObjectControlRecordCodec`(898), `CanonicalJsonReader/Writer`, `ObjectControlStore`(sample만 사용, app-bootstrap edge 없음). +- 갈라짐: UTF-8 처리 — `FileserverControlRecordCodec.java:842` strict(`REPORT`) vs `LocalPublicationJournalCodec.java:156`, `CanonicalJsonReader.java:16` 느슨한 `new String`; 원자적 쓰기 — `LocalPublicationJournal.java:104-118` temp + `ATOMIC_MOVE` vs `LocalDevObjectControlStore.java:54-57` 제자리 `CREATE_NEW`(1차 D-5). +- 권고: fileserver HTTP 플랫폼과 objectstorage는 유지(`docs/storage-capability-boundary.md`에 결정 문서화). 소비자 0인 `FilePublicationPort` plane은 삭제 권고 — CSV가 필요하면 `StreamingCsvEncoder`를 `StagedObjectPublicationPort` 앞에; parser 3개 → 1개. 둘 다 유지해야 하면 canonical JSON을 shared-contract로(두 leaf 모두 edge 있음). 반론: R2의 표 형식 정책(수식 무력화 등)은 인코더 계층 문제. 승인자: 소유자. + +**9. [Consider] Backoff 계산식 10개, "full jitter" 뜻 3가지** +- `OutboxBackoffPolicy.java:63-65`: `base·2ⁿ + U(0,base)` (이름과 달리 더하기 jitter, 상한 없음); httpclient `:78`, jpa `:60`: `U(0,capped]`; messaging `:56`: `capped·U[0,1)`; notification `RetryBackoff.java:43`: base 하한. jpa 한 leaf에 `BackoffCalculator`·`TransactionRetryBackoff` 두 벌; grpc `GrpcRetryCoordinator` 소비자 0. +- 권고: shared-contract `Backoff(base, max, multiplier, Jitter)`(stdlib만) — app-core outbox, httpclient, jpa 2곳(notification은 registry edge 추가 필요); mongo(edge 없음), messaging, grpc는 자기 것 유지. 반론: 공식은 20줄 — 가치는 "같은 이름 = 같은 의미" 보장. + +**10. [FYI] 받아들일 수 있는 중복** +- admission 제한 약 11개: transport별 거부 처리가 달라 합치지 않음. 단 `GrpcAdmissionController.java:53-59` check-then-increment는 `Semaphore.tryAcquire`로(M1 수정이 `GrpcStreamAdmission`에만 적용). +- gRPC 스택 2개: 기본 `adapter:inbound:grpc`(623줄)와 optional build `grpc:*`(약 2만 줄) — 별도 build는 의도된 결정. +- SHA-256 hex 헬퍼 65벌: app-core `Sha256` record가 이미 있음; notification `MessageDigestPort`는 과한 추상화 → 정리 시 흡수. + +#### 조사 범위와 한계 +읽기 전용 grep/find/wc/sed; 기능마다 구현체·포트·main/test 참조 수·조립 조건(`@Conditional*`, stereotype)·migration 대조. "소비자 0" = 클래스명 `grep -w`로 main source set 확인(리플렉션·SPI 미확인). 실행 미확인: v1 outbox 이중 발행 경합, V2·v1 `idempotency_record` 공존 문제; 33% 복붙 비율은 정규화 줄 비교(84/253). 깊게 안 봄: fileserver `platform/**`, objectstorage direct/multipart, messaging 내부 중복. + +### X2 — 공통 유틸리티와 전송 경계 계약 + +#### Part 1: 작은 유틸리티 + +| utility | implementations (count) | canonical exists? | diverged? | recommendation | where it lives | +|---|---|---|---|---|---| +| 시크릿 조회 경로 | 앱 쪽 5개: `SecretSourcePort`, `S3ProviderBinding.SecretResolver`, `RedisSdkAutoConfiguration.RedisSecretSource`, `MongoCredentialResolver`, notification `SecretMaterialProvider`; 벤더 쪽 2개: messaging `CredentialProvider`, grpc `GrpcCallCredentialProvider` | 있음: `application/outbound/SecretSourcePort` + support `EnvironmentSecretSource` | 있음(Spring Environment / 프로세스 env / 무조건 거부로 갈림) | **Required**: 새 타입 없이 cache-redis 같은 1줄 bridge bean | 경로 유지, bridge는 각 capability config | +| prod 판정 | 정본 1개 + 다른 구현 5종(websocket, messaging(벤더), grpc 설정값(벤더), 같은 이름의 httpclient enum, sample 3곳) | 있음: `shared.runtime.RuntimeEnvironment` | 있음(websocket은 trim·소문자 안 함, `production`도 prod) | **Required**: 1줄 교체 | shared-contract(기존) | +| Settings 바인딩·검증 | `@ConfigurationProperties` 파일 64개, 방식 3가지, 오타 키 거부는 4곳 | 일부: `StrictSettingsBinder`(support), 규칙 문서 없음 | 있음 | **Required**(문서화) | 규칙은 root `CLAUDE.md`, 코드는 support | +| 서명된 불투명 토큰(cursor/resume) | HMAC codec 7개 | 없음 | 있음(TTL, kid, version 지원 제각각) | **Consider**: 먼저 삭제, 서명 계층 하나로 정한 뒤 공용 헬퍼 | shared-contract (grpc는 자체 사본) | +| SHA-256·hex | `MessageDigest.getInstance` 파일 66개, private helper 53개(47파일) | 없음 | 없음 | **Consider** | shared-contract `Sha256` (예외 아래) | +| JSON 문자열 escape | 직접 구현 8개(앱 7, 벤더 1) | 없음 | 있음(동작 3가지) | **Consider** | shared-contract 또는 기존 Jackson | +| Clock | Clock bean 3개, 주입 Clock 우회 약 20곳 | 있음: `BootstrapClockAutoConfiguration:21-24` | 있음(한 클래스 안에서 두 시간 소스 혼용) | **Consider**: 기존 bean 주입 | — | +| 상수 시간 비교 | `MessageDigest.isEqual` 19파일, 이것 없이 HMAC 검증하는 곳 0 | stdlib | 없음 | FYI | — | +| Base64url | 18파일, stdlib 한 줄 | stdlib | 없음 | FYI | — | +| 마스킹 `toString` | 약 45개, 표기 4종(`REDACTED`, `redacted`, ``, `***`), 로그 마스크 `****` | 로그는 `LogMaskingPatterns` | 표기만 | FYI (타입별 필요, 줄일 것 없음) | — | +| `requireNonBlank`/`requirePositive` | inline 검사 448곳(342파일), 이름 붙은 helper 14, `requirePositive(Duration)` 12 | 없음 | 메시지만 | FYI (관용구) | — | +| Size/Duration 파싱 | 직접 파서 0 (Spring 바인딩 + `env-keys.yaml` 규칙 `30s`, `10MB`) | Spring | 없음 | FYI | — | + +**P1-1 [Required] 시크릿 조회 경로 4갈래, bridge는 Redis 하나에만** +- 정본 `SecretSourcePort`(application-core), bootstrap `SecretSourceFactory`가 strategy 선택. +- S3는 `System::getenv` 고정(`adapter/outbound/objectstorage/.../s3/S3ObjectStorageProviderContribution.java:41`) → Spring property source·정본 strategy 둘 다 미적용. +- Redis 기본값도 `System.getenv`(`RedisSdkAutoConfiguration.java:212-216`)지만 cache-redis가 `RedisCapabilityConfig.java:68`에서 `SecretSourcePort`로 연결 → 결과적으로 정본 사용. **따라 할 모범 사례.** +- Mongo는 기본값 `MongoCredentialResolver.unconfigured()`, bridge 없음 → adopter가 Vault strategy를 설정해도 Mongo 연결만 실패. +- 수정: S3와 Mongo에 Redis 같은 bridge bean(`secretSource::resolve`), 새 추상화 없음. + +**P1-2 [Required] websocket prod 판정이 아직 직접 구현(BOOT-002 미해결)** +- `adapter/inbound/websocket/.../config/WebSocketPlatformSafetyConfiguration.java:78-85`: `"prod".equals(profile) || "production".equals(profile)` → `Prod`·앞뒤 공백 미인식(fail-open). 정본 `RuntimeEnvironment.fromProfile`은 trim + 소문자. +- websocket은 shared-contract에 의존 가능 → fileserver처럼 `RuntimeEnvironment.isProductionActive(List.of(environment.getActiveProfiles()))` 한 줄(`FileserverSecurityConfiguration.java:81` 참고). 1차는 "bridge가 outbound leaf에 있어 못 쓴다"고 봤지만 정적 메서드 직접 호출이면 bridge 불필요. +- 규칙상 허용되는 별도 구현: `MessagingAdminDurabilityValidator.java:25` `Set.of("prod","production")`, grpc `GrpcTlsProfile.Environment`(기본값 `LOCAL`, `GrpcPlatformProperties:26`) — 벤더 영역이라 자체 어휘 허용(`RuntimeEnvironment` Javadoc). 단 grpc bridge를 붙일 때 `RuntimeEnvironment` → `GrpcTlsProfile.Environment` 매핑 필요; GraphQL이 좋은 예(`CapabilityDependencyValidator.java:29-30,163-185`가 deployment mode를 runtime 환경과 대조). +- httpclient `profile/RuntimeEnvironment`는 정본에서 값을 만들어 동작은 문제없으나(`HttpClientProfileAutoConfiguration:154-159`) 이름이 같아 혼동 → Nit: `HttpClientHardening` 등으로 개명. + +**P1-3 [Required(문서)] Settings 검증 방식 3가지, 새 capability가 따를 규칙 없음** +- `@ConfigurationProperties` 파일 64개 기준: Bean Validation annotation 5, compact constructor throw 19, 별도 `*StartupValidator`/`*SettingsValidator` 34(중복 집계 있음). +- 오타 키 거부는 4곳: `StrictSettingsBinder`의 fileserver·httpclient, `ignoreUnknownFields=false`의 `GrpcServerProperties:17`·`GrpcPlatformProperties:19`. 나머지 약 60개는 오타 키를 조용히 무시. +- root `CLAUDE.md`·`AGENTS.md`에 규칙 없음(`web/CLAUDE.md:65` B4는 request DTO 전용). +- 잠재 충돌(런타임 미검증): `ca-skeleton.grpc`는 strict이고 `platform` 필드가 없음(`GrpcServerProperties.java:22-40`)인데 벤더 prefix가 `ca-skeleton.grpc.platform` → 두 gRPC stack을 같이 올리면 adapter 바인딩에서 "unbound"로 기동 실패 가능성 높음. +- 수정: root 문서에 한 줄 — "capability settings는 master-gated auto-config 안에서 `StrictSettingsBinder`로 바인딩, 값 검증은 compact constructor"(`StrictSettingsBinder` Javadoc에 근거 있음); gRPC adapter prefix 분리. + +**P1-4 [Consider] HMAC 서명 cursor·resume token codec 7개, 모두 production에서 생성 안 됨** + +| codec | 위치 | 상태 | +|---|---|---| +| `cursor/CursorCodec` | web | TTL 24h, kid 없음, test 전용, dev key 하드코딩(`"ca-skeleton-dev-cursor-key-0001"`, `CursorCodec.java:38-40`) | +| `HmacWebCursorCodec` | web pagination | keyring 지원 | +| `HmacGraphQlCursorCodec` | graphql | kid 있음, 만료 없음 | +| `SignedJsonCursorCodec` | persistence-jpa | version 있음, kid 없음 | +| `MongoKeysetCursorCodec` | persistence-mongo | kid·만료 없음 | +| `ResumeTokenCodec` | websocket | kid·만료 있음 | +| `GrpcResumeTokenCodec` | grpc(벤더) | kid·만료 있음 | + +- 이름 grep 기준 7개 모두 production에서 `new` 없음. inbound·outbound 양쪽에 서명 codec → adopter가 어느 계층에서 서명할지 모름; 같은 이름 `CursorCodec` 2개(web 클래스, persistence-jpa 인터페이스). +- 권고: (1) web `cursor/CursorCodec` 삭제 (2) 서명 계층 하나 — inbound에서 서명, persistence는 typed keyset만 (3) 남은 코드가 2개를 넘으면 stdlib sign/verify 헬퍼(약 80 LOC, kid + 선택적 만료)를 shared-contract에. + +**P1-5 [Consider] SHA-256 보일러플레이트** — 예외 래핑 65곳 중 64곳 `IllegalStateException`, 호출부마다 6~8줄; 결과 바이트는 모든 곳 동일(UTF-8, 소문자 `HexFormat.of()`, charset 없는 `getBytes()` 0곳) → V1 fingerprint(`EnvelopeHashV1`, `PartitionKeyV1`)를 교체해도 바이트 불변. shared-contract `Sha256.digest(byte[])`/`Sha256.hex(String)`로 약 51개 파일에서 약 350줄 감소(objectstorage 14, fileserver 12, messaging adapter 6). 자체 사본 유지: shared-contract에 의존할 수 없는 persistence-mongo(4), application-notification(3), application-objectstorage(2)(application-core가 shared-contract를 `implementation`으로 선언해 전달 안 됨, `application-core/build.gradle:11`); messaging(2)·grpc(2)는 벤더 규칙. + +**P1-6 [Consider] JSON 문자열 escape 3가지로 갈림** — RFC 8259 제어문자까지(5개: `OutboxEnvelopeJson.java:44`, redis-sdk `JsonEnvelopeFraming.java:166`, `LocalPublicationJournalCodec.java:121`, sample `PosterEventPublisher.java:89`, `WorkLogReservedIntegrationEventMapper.java:56`); ASCII만 허용·나머지 거부(`CanonicalJsonWriter.java:82`, digest 입력용 → 유지); `\`와 `"`만(sample `PosterImagePublicationEventPublisher.java:76-78` — 제어문자가 들어오면 잘못된 JSON, 지금 값은 ID·media type이라 위험 낮지만 sample은 adopter가 복사). 수정: sample 3곳은 Jackson, outbox adapter·fileserver 2곳은 공용 `JsonStrings.quote`(약 25 LOC), redis-sdk·messaging은 자체 사본. + +**P1-7 [Consider] Clock 우회** — `RoutingObjectMutationAdapter`는 `clock` 필드가 있는데(`:60,70`) `Instant.now()` 14번(`:128-349`), 게다가 설정 코드가 `Clock.systemUTC()`로 생성; objectstorage 설정 5곳 직접 `Clock.systemUTC()`(`ObjectStorageCapabilityConfig.java:78`, `ObjectStorageScanMaintenanceConfig.java:19`, `ObjectStorageBindingCompiler.java:40`, `S3ObjectStorageProviderContribution.java:33,35`); 그 밖에 `MvcStreamWriter` ×5, `WebFluxPlatformAutoConfiguration.java:54`, `LocalFilePublicationAdapter.java:184,229`, `FileserverR2Config.java:65`, `LiveEventStompBroadcaster.java:99`, `MongoTenantClientRegistry.java:70`, `KeyOperationRequests.java:139`. 수정: 기존 `Clock` bean 주입(adopter가 Clock을 바꾸면 테스트 시간이 이 코드에도 적용). + +#### Part 2: 전송 경계 관심사 + +| concern | implementations | shared contract? | diverged? | recommendation | +|---|---|---|---|---| +| 에러 어휘·wire 매핑 | 경로 9개 이상(아래) | 있음: `ApiErrorCode`, `ApiErrorCarrier`, `Category`, `OperationalError`, `error-codes.yaml` | 있음 | **Required**: 계약 적용 범위 확대, 병행 어휘 정리 | +| Carrier 적용 범위 | web만 타입별 handler로 매핑 | `ApiErrorCarrier` | 있음 | **Required**: 1줄 변경 5개 | +| Request·trace·correlation id | web 필터 3, GraphQL은 Spring id, websocket 자체 id, gRPC 없음 | 일부: `TraceParent`(3곳), `MdcKeys`는 web에만 | 있음 | 파서 정리 **Required**, 키 이동 **Consider** | +| 인증 컨텍스트·tenant | 전송마다 principal/tenant 타입 따로 | `AuthorizationPrincipal`(web만) | 있음(tenant 문법) | tenant **Required**, principal **Consider** | +| Rate limit | MVC `RateLimitInterceptor` + 연결 안 된 병행 stack | `EdgeRateLimitPort` | 병행 구현 | **Required**(삭제) | +| Body/message 크기 제한 | 전송별 knob | 불필요 | 에러 코드만 다름 | FYI | +| CORS/origin | 검증기 3, env key 3 | 없음 | 기본값 다름 | **Consider**: websocket 안의 2개만 합침 | +| 응답 envelope | 같은 servlet 앱에서 Envelope·problem+json 혼재 | `Envelope` | 있음 | **Required** | + +에러 매핑 구현(module · class · LOC): web — `GlobalExceptionHandler` 417, `ErrorResponseFactory` 35, `ClientSafeErrorMessages`/`ProblemCode` 81, `ProblemCatalog` 183, `problem-catalog.yaml`, `WebMvcProblemExceptionHandler` 174, `WebFluxProblemExceptionHandler` 164, `BudgetProblemMapper` 76, `ThrottleProblemWriter` 78; web-fileserver — `FileserverExceptionHandler` 46, `FileserverProblemFactory` 45; graphql — `GraphQlWireErrorMapper` 124, `GraphQlPlatformRejectionMapper` 136, `GraphQlErrorCategory` 40, `GraphQlErrorCode` 113, `GraphQlRequestErrorMapper` 57(참조 0); websocket — `SafeStompSubProtocolErrorHandler` 32, `WebSocketCloseCode` 95; grpc adapter — `GrpcStatusMapper` 57, `GrpcExceptionHandlingInterceptor` 131; grpc 벤더 — `GrpcErrorMapper` 182(규칙상 유지). + +**P2-1 [Required] 같은 코드 이름이 status나 retryable이 다르게 나감** +- `VALIDATION_FAILED`: `OperationalError.java:15`·`error-codes.yaml:756-758` 400, `problem-catalog.yaml` 422. +- budget 경로 크기 초과: `URI_TOO_LONG`(원래 414, `OperationalError:41`)이 `REQUEST_TOO_LARGE`(413)로(`BudgetProblemMapper.java:34`), JSON 깊이 초과는 `VALIDATION_FAILED`(422)로(`:37`). `WebMvcBudgetExceptionHandler`는 `backend.web.budgets.enabled=true`면 켜져(`:40`) Envelope servlet 앱 안에서 budget 초과만 problem+json. +- `ProblemCode`는 이름이 다른 동의어 병행 어휘(`error-codes.yaml`에서 0건): `RATE_LIMITED`/`RATE_LIMIT_EXCEEDED`, `REQUEST_TOO_LARGE`/`PAYLOAD_TOO_LARGE`, `IDEMPOTENCY_KEY_REUSED`/`IDEMPOTENT_REQUEST_MISMATCH`, `AUTHENTICATION_REQUIRED`/`UNAUTHENTICATED`, `ACCESS_DENIED`/`FORBIDDEN`. +- GraphQL은 `retryable`을 코드별이 아니라 category에서 계산(`GraphQlWireError.java:73`, `GraphQlErrorCategory:13-28`, `GraphQlWireErrorMapper.java:104-106`) — shared README는 "retryable은 코드별 값": `RATE_LIMIT_EXCEEDED` REST true(`OperationalError:46`) vs GraphQL false; `DB_DEADLOCK`/`DB_SERIALIZATION_FAILURE`/`LOCK_ACQUISITION_TIMEOUT` true vs false; `DB_QUERY_CANCELED` false(`:61`) vs true. +- 사용자 메시지: web 코드별 영어(`ClientSafeErrorMessages.java:14`), GraphQL category별 한국어(`GraphQlWireErrorMapper.java:114`). gRPC trailer에는 `retryable` 없음(`GrpcStatusMapper.trailersFor`). +- 수정: (a) GraphQL `fromApiError`에서 `retryable = code.retryable()`, 플랫폼 자체 코드만 category 기본값 (b) `ProblemCode`·`ProblemCatalog` 제거, problem document는 `ApiErrorCode`의 `httpStatus()`·`code()`에서(약 260 LOC + yaml 감소) (c) Envelope 계약이 켜져 있으면 budget handler도 Envelope (d) client-safe 메시지 표 하나로. + +**P2-2 [Required] shared 예외가 `ApiErrorCarrier`를 구현하지 않아 web에서만 제대로 매핑** +- `MappingException`(`shared/error/MappingException.java:11`), `AdapterDisabledException`(`:13`), application-core `Idempotency{InFlight,RequestMismatch,ScopeMissing}Exception`은 평범한 `RuntimeException`. web은 타입별 handler(`GlobalExceptionHandler.java:79,91,193,205,218`); GraphQL(`GraphQlWireErrorMapper.mapCommon`)·gRPC(`GrpcExceptionHandlingInterceptor.java:105,121`)는 `instanceof ApiErrorCarrier`만 봐서 `INTERNAL_ERROR`. +- `IllegalArgumentException`: web 400 `BAD_PARAMETER`(`:103-109`), GraphQL·gRPC `INTERNAL_ERROR` → 같은 검증 실패가 REST에선 클라이언트 잘못, 다른 전송에선 서버 장애. +- 수정: 위 5종이 `ApiErrorCarrier` 구현(`errorCode()` 1줄씩) → 모든 전송의 기존 carrier 분기가 처리, web 타입별 handler 5개 삭제 가능. IAE → 400은 정책 결정(전송 전체에 한 번에 적용 또는 web에서도 제거). + +**P2-3 [Required] HTTP 에러 응답 모양이 기능마다 다름** — shared README는 Envelope가 RFC 7807을 대체(D5); 같은 servlet 앱에서 fileserver는 항상 problem+json(`FileserverExceptionHandler.java:35-40`), budget 초과 problem+json, 나머지 Envelope; WebFlux엔 Envelope advice 없음(flag off면 Spring 기본 형식). `FileserverErrorCode`는 이미 `ApiErrorCode` 구현 → Envelope 전환 거의 무비용; `UNAUTHENTICATED`, `PRECONDITION_FAILED`, `UNSUPPORTED_MEDIA_TYPE`은 `OperationalError`와 이름이 같음(status 같으나 코드 문자열이 enum 두 곳에 정의). 허용: GraphQL·gRPC(프로토콜이 형식 결정), STOMP close code, notification callback(외부 provider용 본문 없는 204/400/413, `NotificationCallbackMvcController.java:87-98`). + +**P2-4 [Required] 한 요청 안에서 traceparent를 두 번, 다른 규칙으로 파싱** — `WebMvcRequestIdFilter.java:49-50`·`WebFluxRequestContextFilter.java:46-47`은 정규식 사본(version 무시, 전부 0인 trace-id 허용) vs `RequestLoggingFilter.java:57-69`는 엄격한 `TraceParent.parse`(version `00`만, 전부 0 거부); 두 필터 기본 동시 활성(`WebMvcPlatformAutoConfiguration.java:50-54,146-150`) → request attribute `WebTraceId`와 MDC `trace_id`(Envelope `meta.traceId`)가 다른 값이 될 수 있음; request id도 두 필터가 각각 생성 가능(`RequestLoggingFilter:60`). 수정: 정규식 2개 삭제, `TraceParent.parse` 사용. (1차 I-4와 같은 영역) + +**P2-5 [Consider] correlation이 HTTP 밖으로 이어지지 않음** — `MdcKeys`(13 LOC)가 `adapter/inbound/web/observability`에 있어 다른 inbound가 못 씀; `MDC.put` 1파일(`RequestLoggingFilter`); `CorrelationIdPort` 구현은 web MDC adapter 하나 → STOMP·gRPC 호출에서 outbox 등의 correlation 단절; GraphQL `executionId`는 Spring GraphQL request id(`GraphQlPlatformWebInterceptor.java:156-159`), `X-Request-Id`·로그와 무관. 수정: `MdcKeys`를 shared-contract로(원본 `docs/registries/mdc-keys.yaml`), 전송마다 MDC 채우는 얇은 코드, GraphQL은 platform request id. + +**P2-6 [Required(tenant) / Consider(principal)] 인증 컨텍스트** +- 같은 이름 `TenantContext` 두 개, 허용 값 다름: web `[A-Za-z0-9][A-Za-z0-9_.-]{0,63}`(`web/core/TenantContext.java:20`) vs graphql 비어 있지 않고 128자 이하면 무엇이든(`graphql/context/TenantContext.java:17,30`) → 같은 tenant가 한 전송은 통과, 다른 전송은 거부. 수정: application-core tenant id 값 타입 하나 + 두 context가 감쌈. +- principal 전송마다: web `AuthenticatedPrincipal`(19) + `ActorContext`(52) + `SecurityIdentity`(22); graphql `GraphQlPrincipalResolver`(기본 anonymous → web 필터 체인이 검증한 JWT를 안 씀); websocket `request.getPrincipal()`; gRPC `GrpcAuthenticationPolicy`는 `boolean`만(principal·tenant 없음). +- 가명 처리도 전송마다: `UserPrincipalPseudonymizerPort`(`APP_PRIVACY_PSEUDONYMIZATION_SALT`), GraphQL `GraphQlIdentityFingerprinter`(150, 자체 key), 키 없는 `ActorRef.sha256Prefix`, websocket salt SHA-256 → 같은 사용자가 전송마다 다른 가명으로 로그. +- 권고: application `AuthorizationPrincipal`에 tenant 추가, 모든 전송이 이것을 생성; bootstrap에 Spring Security → GraphQL 기본 bridge resolver. + +**P2-7 [Required] 연결되지 않은 두 번째 rate-limit stack** — `WebRateLimiter`(25), `WebMvcThrottleFilter`(136), `WebFluxThrottleFilter`(142), `ThrottleProblemWriter`(78) 모두 Spring 어노테이션 없음, production 생성 0, 테스트 0; 동작하는 것은 `RateLimitInterceptor`(`EdgeRateLimitPort`, `:75`)뿐 → 삭제. WebFlux·websocket·gRPC엔 rate limit 없음; GraphQL-over-HTTP가 MVC interceptor에 걸리는지 미확인(걸려도 모든 요청이 `POST /graphql` 하나). client IP 신뢰 규칙도 모듈 안에서 두 갈래: `ForwardedHeaderClientIpResolver.java:11-16`(trusted-proxy 없이 XFF 첫 hop) vs `ExternalRequestUrlResolver.java:31`(trusted proxy 요청만) — 1차 I-5. + +**P2-8 [Consider] Origin 검증기 3개** — web `WebCorsPolicyValidator.java:59`, websocket `WebSocketOriginPolicy.java:95`, `WebSocketProperties` `@AssertTrue`가 각자 "wildcard 없이 정확 일치" 구현; env key 3개 기본값 다름(`APP_SECURITY_CORS_ORIGINS` 빈 값, `APP_WEBSOCKET_ALLOWED_ORIGINS` `http://localhost:3000`, `APP_WEBSOCKET_PLATFORM_ALLOWED_ORIGINS` 빈 값). websocket 안의 두 사본만 합침(모듈 간 공유는 약 40 LOC라 가치 없음). + +**P2-9 [FYI] 크기 제한** — knob은 전송마다 맞음(web budgets, graphql `maxBodyBytes`/`maxDocumentBytes`, websocket `maxMessageBytes`, grpc `maxInboundMessageBytes`); 위반 코드는 다름(`PAYLOAD_TOO_LARGE`, `REQUEST_TOO_LARGE`, `GRAPHQL_DOCUMENT_SHAPE_REJECTED`, close 1009, `RESOURCE_EXHAUSTED`) → P2-1 정리 때 이름만 통일. websocket STOMP는 모든 실패를 `WEBSOCKET_REQUEST_REJECTED` 하나로(`SafeStompSubProtocolErrorHandler.java:12`, carrier 코드 소실). gRPC adapter `GrpcStatusMapper`와 벤더 `GrpcErrorMapper`는 bridge 미연결이며 그 사실이 `grpc/CLAUDE.md:88-93`에 기재 → 공존 가능. + +#### Coverage note +대상: `src/*/src/main/java` 73개 source set(`grpc-codegen` fixture, `build/`, `bin/` 제외); 개수는 ERE grep(이름 기준 helper 수는 최소치); 벤더 영역은 규칙상 자체 사본이라 권고 제외. 미확인: MVC rate-limit interceptor가 GraphQL route에 걸리는지, `ca-skeleton.grpc` prefix 충돌의 실제 기동 실패 여부, Spring GraphQL `request.getId()` 값. capability 단위 중복은 X1 담당, grpc-advanced edge·notification callback 서명 검증은 상수 시간 비교 여부만 확인. + +### S1 — Core and application leaves + +Path abbreviations: `AC/` = `src/application-core/src/main/java/dev/caskeleton/application/`, `AN/` = `src/application-notification/src/main/java/dev/caskeleton/application/notification/`, `AF/` = `src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/`, `AO/` = `src/application-objectstorage/src/main/java/dev/caskeleton/application/`, `SC/` = `src/shared-contract/src/main/java/dev/caskeleton/shared/` + +#### Per-leaf maintainability verdict +| leaf | main LOC | verdict | one-line reason | +|---|---|---|---| +| domain-core | 110 | HEALTHY | 마커 3개 + ID 인터페이스 2개. 단, application-core가 이 leaf에 의존하지 않아 production에서 안 쓰임(#16) | +| shared-contract | 2.8k | NEEDS_WORK | 한 leaf만 쓰는 타입 약 550줄; CLAUDE.md 책임 목록은 13개 패키지 중 6개만 설명 | +| application-core | 9.1k | OVERBUILT | 약 4.9k줄(54%)이 production 호출 경로 밖; idempotency 2세대·outbox 3세대 공존 | +| application-notification | 17.0k | OVERBUILT | R1 4.5k(1차) + platform 미사용 약 0.9k; 생성자 15개짜리 dispatch 서비스; 같은 전략만 담은 레지스트리 | +| application-fileserver | 6.8k | NEEDS_WORK | use-case 계약 밖 `*Service`/`Default*` 쌍 10개; retire 로직 3곳 복사, 이미 다름; 에러 코드마다 예외 클래스 | +| application-objectstorage | 2.7k | NEEDS_WORK | 포트만 담은 단순 구조. 거의 같은 식별자 클래스 6개, 복사된 가드, deprecated legacy 네임스페이스 | + +#### Findings (highest leverage first) + +1. **[Required][duplication] idempotency 엔진 2세대 공존, V2는 bean만 있고 호출자 0** — `AC/idempotency/IdempotencyExecutor.java:19`, `AC/idempotency/v2/IdempotencyExecutorV2.java:33,94` + - Evidence: V1 = executor + `IdempotencyStorePort` + `IdempotencyScope`; V2 = executor + `IdempotencyStorePortV2` + `IdempotencyScopeDigest` + outcome 타입 13종(767줄). V2 executor는 `PostgreSqlIdempotencyProviderConfig.java:51`, `RedisIdempotencyConfig.java:68`에서 생성만, main `execute` 호출 0; 실제 호출은 sample V1(`PublishPosterImageUseCase.java:61`)뿐; bootstrap에 두 세대 bean 수를 세는 배타성 가드(`IdempotencyProviderSelectionConfig.java:42-57`, `IdempotencyComposition.java`, 112줄); 실패 처리 이미 다름(1차 A-8). + - Remedy: 한 세대로 — V2 정본(web·sample scope 생성 이전, V1·가드 삭제) 또는 소비자 생길 때까지 V2 삭제. Size L · 약 300줄 + 가드 112줄(또는 반대로 V2 767줄 + 어댑터 2개). + +2. **[Required][duplication] outbox 포트 3세대, 실제 사용은 legacy 하나** — `AC/outbox/LegacyOutboxAppendPort.java:11`, `AC/outbox/OutboxAppendPort.java:13`, `AC/outbox/v2/OutboxAppendPortV2.java:9` (append 포트 3개 중 main 호출자는 sample이 쓰는 legacy뿐; 폴링 포트 둘 `OutboxStorePort.java:14`·`OutboxPollingDeliveryPortV2.java:7`; retry 정책 둘 `OutboxBackoffPolicy.java:15`·`OutboxV2RetryPolicy.java:16`; `ClaimedOutboxEvent.java:11`이 legacy·canonical을 sealed로 묶음). Remedy: 한 세대만(append 1, 폴링 1, retry 1), 1차 A-3의 V2 publish 466줄 포함. Size L · 약 0.7–1.0k줄, 포트 4개. 반론: 세대 전환 중 — 템플릿 adopter에겐 옮겨올 세대 이력이 없음. + +3. **[Required][reachability] application-core 호출자 없는 코드 약 2.8k줄(#1·#2 제외)** — 호출자 자체 없음: cache executor 계열 20파일 1,488줄(`AC/cache/CacheAsideExecutor.java:19`, `@Deprecated`, "shipped runtime does not compose"), `LeaseWatchdog`(`AC/lease/LeaseWatchdog.java:28`) 228줄, `TransactionCompletionResolver`/`CompletionResolution` 50줄. 어댑터 구현은 있으나 use case가 안 부름: `lease/*` 399, `inbox/*` 213(`InboxOwner`·`InboxClaimAttempt`는 `idempotency/v2` 같은 역할 타입과 필드 동일), `filepublication/*` 399, `EphemeralFanoutPort` 58. Remedy: use case가 생길 때 추가, 유지하면 별도 library leaf/testFixtures. Size L. 반론: H5 결정이 "검증된 reference"로 유지 — 코드 스스로 `@Deprecated`. + +4. **[Required][SRP|readability] `NotificationDispatchService` 한 클래스가 흐름 제어·record 복사·실패 분류** — `AN/platform/dispatch/NotificationDispatchService.java:72-87,202-231,253-288,483-508` (생성자 15개; 22필드 record를 필드별로 재조립하는 곳이 이 파일 2곳 + `DispatchOutcomeRecorder.java:66-90,108-132` 2곳 → `record()` 105줄; catch 분기 `:253-288`은 provider 결과 분류 정책; 종료 상태 계산 `:473-475`·`:510-514` 두 번; FQN 11줄; record 전체 재작성 방식이 1차 B-5(stale snapshot 덮어쓰기)의 구조적 원인). Remedy: record 전이 메서드(`DeliveryAttemptRecord.completed(result, at)`/`leaseLost(at)`, `RecipientDeliveryRecord.advancedRoute(now)`), catch 분기는 `ProviderOutcomeClassifier` 정적 메서드. Size M · 약 150줄. + +5. **[Required][duplication] fileserver retire 절차 3곳 복사, 이미 다름** — `AF/lifecycle/DefaultFileLifecycleService.java:84-104`, `AF/admin/DefaultFileserverAdminService.java:159-181`, `AF/upload/DefaultUploadApplicationService.java:250-270` (셋 다 `markDeleting` 후 `cleanupQueue.enqueue`; lifecycle은 content 키 없으면 DELETING→DELETED, admin `forceDelete`엔 이 분기 없음 → content 없는 레코드가 DELETING에 남음(바로 위 주석 "must not ... leave a file unreachable"과 모순); cancel 쪽은 1차 C-4). Remedy: `retire(FileRecord)` 하나. Size S. + +6. **[Required][structure] fileserver 인바운드가 use-case 계약 밖** — `AF/upload/UploadApplicationService.java` 외 9개 (이 leaf의 `@UseCaseCapability`/`CommandUseCase`/`QueryUseCase` 0건(notification은 17/18) → capability fitness gate 미적용; 인터페이스 6개 `CleanupService`, `WriterLeaseCoordinator`, `FileLifecycleService`, `TransferAdmissionController`, `FileReconciliationService`, `FileStateMachine`은 두 번째 구현·fake 없음). Remedy: 최소안은 6개 인터페이스 삭제; 템플릿 정합은 transport가 부르는 연산을 `*UseCase` + capability 선언으로. Size M/L. + +7. **[Consider][duplication|pattern] 에러 코드마다 예외 서브클래스 약 45개, 타입 분기는 5개** — `AF/api/error/*Exception.java`(23파일, 571줄), `AN/platform/api/error/*Exception.java`(25파일, 323줄) (transport는 code/context로 매핑(`FileserverExceptionHandler.java:35`); 타입 catch는 fileserver 3(`AmbiguousCompletion`, `UploadOffsetMismatch`, `FileNotFound`) + notification 2; notification 예외 12개는 throw 0; `FileTooLargeException.java:8` 생성자가 아무 context나 받아 타입≠code 가능; `FileNotFoundException`, `FileAlreadyExistsException`, `InvalidPathException`은 JDK 이름과 같아 어댑터가 FQN으로 구분(`LocalPersistentRootAttestor.java:283`)). Remedy: base를 구체 클래스 + `of(code, …)`, 서브클래스는 타입 분기 5개만. Size M · 약 700줄. + +8. **[Consider][over-abstraction] `PolicyTransactionPort` 계열이 호출 1곳을 위해 존재** — `AC/transaction/PolicyTransactionPort.java:9`, `AF/upload/FileserverCompensationTransaction.java:20-59` (main `inTransaction` 호출 1곳, 정책 7개 중 `MAINTENANCE_NEW`만; 결과 5종을 전부 예외로 되돌려 결국 `inNew`와 같음; 딸린 타입 7개 약 290줄). Remedy: `TransactionPort.inNew` 사용, persistence-jpa `SpringPolicyTransactionPort`까지 삭제. Size M. + +9. **[Consider][over-abstraction] 같은 전략만 담은 레지스트리 2개** — `AN/platform/callback/ProviderEventProjectorRegistry.java:7`(구현은 `StandardDeliveryProjector` 하나; Twilio/Ses 서브클래스는 providerId만 넘기고 "No provider-specific transitions are needed"), `AN/platform/dispatch/TemplateRendererRegistry.java:10`(모든 channel에 같은 클래스 등록, `NotificationPlatformProviderConfig.java:55-77`). Remedy: 구현체 직접 주입. Size S · 타입 7개, 약 140줄. + +10. **[Consider][duplication] 알림 제출 진입점 두 벌** — `AN/platform/dispatch/NotificationSubmissionService.java:38,81-90,186-191` vs `Submit/ScheduleNotificationApplicationUseCase.java` (`prepare → inWrite(commit) → recordAccepted` 흐름·주석까지 복사; `NotificationOrchestrator`의 유일한 소비자는 호출자 없는 `ReactorNotificationOrchestrator`(1차 B-8)). Remedy: Reactor facade와 함께 `NotificationOrchestrator`·서비스 public 진입 메서드 삭제. Size S. + +11. **[Consider][duplication] SHA-256 헬퍼 분산, `RequestFingerprint` 이름 충돌** — `AN/platform/dispatch/MessageDigestPort.java`(stdlib 해시를 outbound 포트+어댑터로 감쌈; 다른 7곳은 `MessageDigest.getInstance("SHA-256")` 직접, 예 `AO/objectstorage/model/ObjectDigest.java:35`), `AN/platform/dispatch/RequestFingerprint.java:15` vs `AC/idempotency/RequestFingerprint.java:13`(grep 결과가 섞임 — 이 리뷰의 도달성 스캔도 한 번 잘못 셈). Remedy: application-core `Sha256.hex(byte[])` 하나, 포트·어댑터 삭제, notification 쪽은 `PlanFingerprint`로 개명. Size S. + +12. **[Consider][over-abstraction] fileserver content SPI를 application이 안 씀** — `AF/api/content/{BlockingContentStore,AsyncContentStore,CopyCapableContentStore,CapacityAwareContentStore,DelegatedDownloadStore}.java` (application은 좁은 gateway 8개만; `BlockingContentStore`는 어댑터만 참조; 나머지 4개 + record 3개는 구현·호출 0, 143줄). Remedy: 확장 4개 삭제, `BlockingContentStore`는 어댑터 내부로. Size S · 약 190줄. + +13. **[Consider][pattern] `FileStateMachine` 인터페이스 → enum 메서드** — `AF/api/FileStateMachine.java:9`, `AF/api/DefaultFileStateMachine.java` (전이표 Map 하나를 인터페이스·구현·bean으로 감쌈; 반대로 notification `RecipientDeliveryState`는 전이표 없이 여러 파일에서 제각각 전이 결정). Remedy: `FileState.canTransitionTo(target)`. Size S. + +14. **[Consider][reachability] notification platform에서 R1 외 약 920줄(40파일) 미사용** — `AN/platform/api/error/`(throw 0 예외 12), `AN/platform/security/{NotificationRedactor,SafeDiagnosticContext,SensitiveValueClassifier}.java`(157), `AN/platform/sms/*`(218), `push/`, `email/`, `webpush/`. Remedy: 삭제. Size S. + +15. **[Consider][structure] shared-contract가 한 leaf만 쓰는 타입 보관소** — `SC/activation/*`(207, app-bootstrap만), `SC/opstore/*`(128, graphql `advanced/**`만, 구현 0), `SC/ratelimit/{RateLimitPolicy,RateLimitAlgorithm,RateLimitEvaluationDedupPolicy}.java`(216, cache-redis만; `RateLimitEvaluationDedupPolicy.java:9-10`은 "Redis program" 전제 — 어댑터 구현 설정); `src/shared-contract/CLAUDE.md` 책임 목록은 13개 패키지 중 6개만. Remedy: 유일한 소비자 leaf로 이동, opstore 삭제. Size M. + +16. **[Consider][structure] 문서가 말하는 `application-core → domain-core` 의존이 빌드에 없음** — `src/application-core/build.gradle:11` (registry는 허용, `CLAUDE.md:54`·AGENTS.md 작업 순서도 전제; 실제 의존은 `b3add016`(2026-07-28)에서 빠짐; application-* 전체 `dev.caskeleton.domain` import 0; 그 결과 domain-core `IdFactory` 대신 `NotificationIdGeneratorPort`, `UploadIdentifierFactory`가 따로 생김). Remedy: 의존 한 줄 복원, 또는 domain-core를 "fork에서만 쓰는 leaf"로 문서화. Size S. + +17. **[Consider][duplication] objectstorage 식별자·가드 복사, legacy 네임스페이스 공존** — `AO/objectstorage/identity/{ObjectId,ObjectReference,ObjectStageHandle,ObjectVersionToken,PartReceiptToken,DirectTransferSessionId}.java`(40줄 클래스 6개, 이름·검증 호출만 다름), `AO/objectstorage/model/ObjectModelSupport.java:11` vs `AO/objectstorage/request/ObjectRequestSupport.java:18`(본문 같고 인자 순서만 반대), `AO/storage/ObjectStoragePort.java:6,28`(legacy `application.storage` 284줄은 sample만; Javadoc이 "the only dependency"와 "Legacy compatibility only"를 동시에). Remedy: 식별자 record + `toString`만 재정의, 가드 하나, legacy 네임스페이스는 sample로 옮길지 결정. Size S/M · 약 160줄. + +18. **[Consider][structure] 포트·서비스 이름 규칙이 leaf마다 다름** — `AF/api/metadata/FileQuotaService.java`(outbound인데 Service); CLAUDE.md는 outbound = `*Port`; fileserver outbound 이름: Store 7, Gateway 8, Port 5, 그 외 Probe/Queue/Ledger/Locator/Service/Factory/Verifier; notification outbound: Port 34, StorePort 15, Registry/Ledger/Inbox/Protector; 인바운드 `*UseCase`/`*ApplicationUseCase`/`*Service`+`Default*` 혼재; `V2` 접미사 타입 5개; 파일 관련 어휘 4곳(`filepublication`, deprecated `fileexport`, fileserver, objectstorage). Remedy: outbound `*Port`, inbound `*UseCase`로 기계적 개명, #1·#2 정리 뒤 `V2` 제거. Size M. + +19. **[Nit][readability]** 이력 주석 약 50곳("used to", "Replaces an injected", "There were two V2 store contracts" — 예 `NotificationDispatchService.java:57-62,187-189,264-267,334-339`, `IdempotencyExecutorV2.java:17-31`); inline FQN notification 82줄, application-core 7줄. + +20. **[Nit][structure] notification `dispatch/` 패키지에 여러 기능** — `AN/platform/dispatch/`(46파일, 3.8k줄)에 제출, 템플릿 게시, 조회, `ContactPoint*`(`contact/` 패키지가 따로 있는데도), reconciliation, worker. Remedy: `submission/`, `dispatch/`, `reconciliation/`. Size M(이동만). + +#### Cross-module leads (not investigated) +- `messaging:*` 자체 outbox/inbox(`messaging-outbox-jdbc-postgresql`, `messaging-inbox-jdbc-postgresql/IdempotentConsumer.java`)와 application-core `outbox`/`inbox` 같은 패턴 3~4벌. +- UUIDv7 생성: notification `UuidV7Generator`, fileserver `RandomUploadIdentifierFactory`, sample `Uuid*IdFactory`. +- outbound 어댑터(`RedisIdempotencyConfig.java:68`)가 application executor 조립. +- 어댑터 `Local*Gateway` 7개(383줄)는 `LocalBlockingContentStore`를 넘기기만. +- persistence-jpa `SpringPolicyTransactionPort`는 #8과 함께 정리. +- fileserver 전이 규칙이 `DefaultFileStateMachine`과 persistence `FileTransitionRepository` SQL 두 곳. + +#### Coverage note +정독: dispatch/submission 서비스·제출 use case, 두 idempotency executor, outbox/transaction 포트, fileserver upload/lifecycle/admin/error/content, objectstorage identity/support, shared-contract ratelimit/opstore. 도달성은 클래스 이름 grep으로 이 leaf들 밖 main에서의 전이 참조(리플렉션·문자열 bean 미포착; 이름 충돌로 한 번 잘못 셈 → 수동 교정). 훑음: notification policy/observation/provider, fileserver finalize/cleanup. + +### S2 — Persistence leaves + +Path prefixes: `JPA/` = `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/`, `MONGO/` = `src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/`, `FS/` = `src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/` + +#### Per-leaf maintainability verdict +| leaf | main LOC | verdict | one-line reason | +|---|---|---|---| +| persistence-jpa | 26,317 | OVERBUILT | Three things in one: a JPA platform library (~13.6k), skeleton-wide stores (~5.7k), the notification feature (~7.1k). Only 16.2k statically reachable from wiring; supported adopter surface is 20 types. | +| persistence-mongo | 23,188 | OVERBUILT | `allowed_dependencies` is `[]` → implements no application port, no production consumer; 13.1k lines not referenced even by its own auto-config. | +| persistence-fileserver | 2,538 | HEALTHY | One self-contained feature; its tests/docs were left in another leaf; same gate repeated on root config and 9 classes. | + +**Q1 (is persistence-jpa one leaf?):** No — three things. Skeleton-wide stores (outbox, idempotency, inbox, operation, liveevent, lock) implement application-core ports and belong here; notification is the same case fileserver was and should come out the same way (#1). +**Q2 (how much Mongo is "advanced"?):** `advanced` = 3.4k; reactive + change streams ~2.7–4k (excluded from the shipped jar). What an adopter needs: ~1–1.5k (opt-in gate, client profile, health, startup validator). + +#### Findings (highest leverage first) + +1. **[Required][structure] persistence-jpa carries notification persistence (27% of the leaf)** — `JPA/notification/**` (7,066 lines), `db/migration/jpa/notification-platform` (841 SQL lines) + - Evidence: notification imports only `application.notification` (184) and itself; 0 imports from other `persistence.*`; only reverse edge `JPA/autoconfigure/PersistenceJpaAutoConfiguration.java:6,24` → forces `persistence-jpa` → `application-notification` (`modules.json:68`), so every JPA deployment resolves notification. Three things exist only to exclude it: `JPA/config/PersistenceJpaConfig.java:87` (`OPT_IN_NOTIFICATION_PACKAGE`), a 19-package list repeated in `@EntityScan` and `@EnableJpaRepositories` (only 5 packages hold entities), `PersistenceEntityScanCoverageTest`. `JPA/notification/crypto` (505 lines) is test-only, a parallel copy of the wired `adapter/outbound/notification/.../AesGcmNotificationPayloadProtection`. + - Remedy: new module using the `persistence-fileserver/build.gradle:3-14` recipe; delete `crypto`. Size L · Removes the jpa→application-notification edge, both 19×2 lists, the constant, the coverage test, 505 dead lines. + - Assumption/Counter: notification ITs need jpa's container fixture (reuse via `testFixtures`) / one more registry leaf. + +2. **[Required][reachability] persistence-mongo: a 23k-line platform with no consumer** — `modules.json:84`, `src/app-bootstrap/build.gradle:129` + - Evidence: `runtimeOnly`, no main source names a Mongo type; reachability from its 3 auto-config entry points 10.1k/23.2k; unreferenced by any wiring: transaction 1.6k, schema 1.9k, migration 1.2k, query 1.5k, security.admin 0.6k, `advanced` 3.4k. Nothing imports `MONGO/advanced/autoconfigure/MongoAdvancedConfiguration.java` → every `ca-skeleton.persistence-mongo.advanced.*.enabled` flag is bound by nobody. 10 interfaces without implementation: `MongoSearchOperations`, `MongoVectorSearchOperations`, `MongoTimeSeriesOperations`, `MongoGridFsCompatibilityReader`, `MongoIntegrationEventPublisher`, `MongoChangeToIntegrationEventMapper`, `MongoDataKeyResolver`, `MongoTenantDatabaseResolver`, `MongoTenantMigrationCheckpointStore`, `TenantScopedMongoOperations`. Carrying cost: 16k test lines, 261-line build.gradle, 2 release scripts. + - Remedy: keep a "Stable core" ~1.5k (`MongoOptInAutoConfigurationImportFilter`, `MongoRootAutoConfiguration`, `MongoPersistenceSettings`, `client/*`, `MongoProfileProperties`, health/startup/topology); delete the rest (git keeps it) or move to a separately versioned library. Size L · Removes ~20k main + ~14k test. + - Assumption/Counter: tech-log-backend does not use platform types (to check) / leaf CLAUDE.md declares an intentional platform with an API snapshot. + +3. **[Required][duplication/reachability] Two transaction/retry engines, one used** — `JPA/transaction/`, `JPA/autoconfigure/PersistenceJpaRuntimeConfig.java:54-78` + - Evidence: live: `SpringTransactionPort.java:29` → `SpringPolicyTransactionPort` + `TransactionRetryBackoff` + `TransactionRetryClassifier` (40001/40P01 hard-coded `:8-9`). Second: `SpringJpaTransactionExecutor`, `FullTransactionRetryCoordinator`, `DefaultJpaRetryPolicy`, `BackoffCalculator`, `RetryBudget`, `PersistenceFailureTranslatorChain`, `EvidenceAwareJpaTransactionManager`, `CompletionUnknownRecorder`, `TransactionProfileRegistry` — beans created, `JpaTransactionExecutor` 0 consumers, last three referenced only from Javadoc/tests. `JpaTransactionAutoConfiguration.java:37` claims "the retry coordinator implements PolicyTransactionPort" — false. SQLSTATE tables duplicated: `failure.SqlStateErrorMapping` (Standard/PostgreSql/H2) and `postgresql.error.PostgreSqlState` + `h2/H2FailureTranslator.java:48-52`; 40001 in 4 places. + - Remedy: keep the port-backed engine, delete the second; one SQLSTATE enum per vendor for mapping and retry. Size L · Removes ~1.2k lines, 2 of 4 tables. + - Assumption/Counter: CLAUDE.md invariant "CompletionUnknown is not retried" is enforced only by the unused engine — move it into the live one if it matters. + +4. **[Required][duplication] Three outbox generations and two idempotency generations side by side** — `JPA/outbox/OutboxStoreAdapter.java:43`, `JPA/outbox/CanonicalOutboxAppendAdapter.java:28`, `JPA/postgresql/outbox/*` (1,055), `JPA/postgresql/inbox/*` (596), `JPA/idempotency/IdempotencyStoreAdapter.java:30` vs `JPA/postgresql/idempotency/PostgreSqlOwnerSafeIdempotencyStore.java:61` + - Evidence: V2 outbox, V2 polling, inbox adapters constructed by no production code (only `CandidateAdapterCompositionTest` + ITs); `outbox/entity/OutboxEventEntity.java` has 57 public methods (legacy + canonical columns); outbox migrations across 3 streams (`postgresql/V3,V13,V14`, `jpa/outbox-storage`, `jpa/outbox-polling`). + - Remedy: finish the migration, one generation per capability; keep possibly-applied migrations, delete code only. Size L · Removes ~1.7k (unwired V2) or ~1k (legacy) + matching port versions. + - Assumption/Counter: adopters start from an empty DB / README treats "implemented-candidate" as deliberate staging. + +5. **[Required][duplication] Mongo reactive twin stack — excluded from the jar, already diverged once** — `MONGO/reactive/**`, `MONGO/transaction/*Reactive*`, `MONGO/transaction/session/ReactiveMongoCausalSessionExecutor.java`, `MONGO/changestream/**` + - Evidence: executor, consistency binder, scoped operations, collection access, transaction executor, session factory, causal session each exist twice; ~2.7k lines / 30 files touch reactor; `app-bootstrap/build.gradle:129-135` excludes the reactive starter ("kept for a future promotion"); `ReactiveMongoConsistencyBinder` Javadoc: "The imperative binder was given this contract and the reactive one was not." + - Remedy: delete the reactive half and change streams (first-pass change-stream defects go with it). Size L · Removes ~4k lines, reactor-test, reactive starter. + +6. **[Required][duplication] Owner-lease claim mechanics copy-pasted across PostgreSQL stores** — `JPA/postgresql/inbox/PostgreSqlSameStoreInboxAdapter.java:223-277` vs `PostgreSqlOwnerSafeIdempotencyStore.java:120-170` + - Evidence: same claim decision sequence; `digestFields` identical twice (`inbox:559`, `PostgreSqlPollingDeliveryAdapter.java:523`); write-tx guard 4× (`inbox:501`, `polling:487`, `PostgreSqlImmutableOutboxAppendAdapter.java:336`, `IdempotencyCapabilityGuard.java:93`); `capability_schema_registry` check 6× (4 stores + `NotificationSchemaActivation` + `FS/FileserverSchemaActivation.java`) — copies disagree (`= 2` vs `>= 2`; only 2 of 6 handle an unreadable registry); only idempotency was split into collaborators. + - Remedy: package-private `PostgreSqlStoreSupport` (write-tx guard, capability check, db now, owner token, digest) + `CapabilitySchemaRequirement` record; fold in first-pass E-3 guard for outbox/operation/liveevent. Size M · Removes ~200 lines, 5 SQL copies. + +7. **[Required][reachability] JPA platform library outside the supported surface** — `docs/architecture/jpa-adopter-api-surface.txt` (20 types) vs `jpa-api-surface.txt` (311) + - Evidence: types referenced by composition/sample match the 20-type list exactly. Outside it and unused beyond the leaf: `springdata` (1.0k), `hibernate.batch/bulk/stateless` (0.8k), `postgresql.{copy,json,range,write,array,lock}` (1.8k), `api.query` (0.4k), `envers/querydsl/cache` (0.6k), `experimental` (1.5k). 8 single-impl interfaces without test/outside reference: `JpaBatchExecutor`, `BulkDmlExecutor`, `StatelessSessionRunner`, `PostgreSqlCopyLoader`, `PostgreSqlUpsertExecutor`, `WorkClaimExecutor`, `EnversHistoryReader`, `JpaTransactionExecutor`. `postgresql/lock/PostgreSqlWorkClaimExecutor` (generic SKIP LOCKED claimer) has 0 callers while 6 places hand-write SKIP LOCKED (`PostgreSqlOutboxClaimRepository`, `PostgreSqlPollingDeliveryAdapter`, `RecipientClaimSql`, `JpaRecipientLeaseStore`, `JdbcReconciliationJobStore`, `DurableOperationJpaRepository`). + - Remedy: shrink to supported surface + what stores use. Size L · Removes ~6–7k lines. + - Counter: design doc describes "18 Stable modules" — but the leaf's own surface file says public implementation types are not compatibility promises. + +8. **[Consider][structure] Three wiring styles, stale rationale** — `JPA/config/JpaAdapterComponentsConfig.java`, `JPA/notification/configuration/NotificationJpaPersistenceFacade.java`, `FS/FileserverJpaPersistenceConfig.java` (scanned stereotypes with per-class conditions / explicit facades / "deliberately no stereotype" classes nothing constructs; the paragraph "Both composition roots component-scan dev.caskeleton.adapter" in 4 classes + `CandidateAdapterCompositionTest.java:18` is false — `CaSkeletonApplication.java:106` excludes `adapter.outbound.persistence..*`; fileserver repeats its gate 10×; Mongo repeats `enabled` 8×). Remedy: explicit `@Bean` wiring per feature config only; drop per-class stereotypes/conditions, stale paragraphs, candidate test. Size M. + +9. **[Consider][structure] Features scattered by vendor; two unrelated "inbox" packages** — outbox over 5 Java locations (`outbox/`, `outbox/entity/`, `postgresql/PostgreSqlOutboxClaimRepository.java`, `postgresql/outbox/`, `h2/H2OutboxClaimRepository.java`) and 3 migration dirs; idempotency over 6 locations; `postgresql/inbox` (message dedupe, `application.inbox`) vs `notification/platform/inbox` (user inbox). Remedy: package by feature (`outbox/{jpa,postgresql,h2}`), rename the first to `messageinbox`. Size M (moves). + +10. **[Consider][over-abstraction] Promotion/benchmark gates on the production classpath** — JPA `experimental/next/*` (186); Mongo `advanced/MongoAdvancedPromotionGate.java` (incl. `addsStarterDependency() { return false; }` `:41-46`), `MongoAdvancedPromotionEvidence`, `MongoVectorSearchBenchmarkGate`, `MongoSearchReadinessGate` — test-only, parallel designs; Mongo CLAUDE.md already moved release gating to the testkit. Remedy: testkit or delete. Size S · ~450 lines. + +11. **[Consider][structure] Fileserver extraction left its tests behind** — `persistence-jpa/build.gradle:86-87` (4 fileserver ITs in jpa's `postgresqlIntegrationTest`; `FS/JpaFileQuotaService.reservedBytes/committedBytes` public only for them; leaf has no CLAUDE.md/README; removing fileserver means editing jpa). Remedy: own IT source set via `testFixtures(project(':adapter:outbound:persistence-jpa'))` + short CLAUDE.md. Size M. + +12. **[Consider][readability] Javadoc tells history** — comment lines 21% of JPA main, 28% of Mongo main; ~90 files with "used to", "until now", "nothing registered", "documented as registered and never was"; worst: `JpaAdapterComponentsConfig.java` (52 comment vs 13 code lines), `MongoPlatformAutoConfiguration.java:140-145,176-180,322-325,410-412,431-434`, `MongoRootAutoConfiguration`, `PostgreSqlPersistenceConfig.java`, `PersistenceJpaConfig.java:90`, `MongoAdvancedPromotionGate.java:28-30` (MNG-008). Remedy: 1–2 lines of invariant, history to git/ADR. Size M. + +13. **[Nit][readability]** `JpaTransactionAutoConfiguration.java:40` is a plain factory instantiated twice (`PersistenceJpaRuntimeConfig.java:58,70`); `new JpaTransactionSettings(null ×9)` at `SpringTransactionPort.java:42,53` despite `defaultSettings()` at `:221`; 36 port implementations use 7 naming conventions (`*StoreAdapter`, `*Adapter`, `Jpa*Store`, `Jdbc*`, `PostgreSql*Store`, port-like `SpringTransactionPort`/`DomainContextAuditContextPort`, `JpaFileQuotaService`). Remedy: inline factory, `JpaTransactionSettings.defaults()`, `` naming. + +14. **[Nit][docs]** jpa CLAUDE.md "NoSQL extension rule" (`:306-316`) says create a Mongo leaf (exists); MapStruct section (`:281-304`) for an unused tool; `jpa-adopter-api-surface.txt:11` lists moved `FileserverSchemaActivation`; Mongo CLAUDE.md `:157` `MongoAdvancedProperties` (class is `MongoAdvancedSettings`); `JpaAdapterComponentsConfig` `{@link}` into a leaf not on its classpath. + +#### Cross-module leads (not investigated) +- application-core port versions `IdempotencyStorePort`/`V2`, `OutboxAppendPort`/`LegacyOutboxAppendPort`/`OutboxAppendPortV2`, `OutboxStorePort`/`OutboxPollingDeliveryPortV2` are the root cause of #4. +- Idempotency claim decision table duplicated in cache-redis `RedisIdempotencyStoreAdapter` and `PostgreSqlOwnerSafeIdempotencyStore.claim` → one pure function in application-core. +- Signed cursor codecs ×4: jpa `SignedJsonCursorCodec`, mongo `MongoKeysetCursorCodec`, web `CursorCodec`/`WebCursorKeyRing`, graphql `HmacGraphQlCursorCodec`. +- Failure hierarchies ×3: jpa `api/error` (23 types), mongo `api/error` (25), shared-contract `PersistenceFailureException`. +- `sample-portfolio/.../SamplePostgreSqlPersistenceConfig.java:71-78` redeclares claim-repository beans of `PostgreSqlPersistenceConfig`. +- JPA wiring split between the leaf's `PersistenceJpaRuntimeConfig` and bootstrap's `JpaPlatformAutoConfiguration`/`JpaPlatformRuntimeAutoConfiguration`. + +#### Coverage note +Reachability computed from auto-config entry points, scanned stereotypes and types referenced by composition/sample main code (imports, same-package names, FQNs; strings/reflection not tracked → approximate). Read in full: wiring/config of all three leaves, claim/helper paths of the 4 PostgreSQL stores, transaction wiring, each CLAUDE.md. Not in depth: notification store internals, Mongo schema/migration/query internals. + +### S3 — Redis와 outbound HTTP client + +#### Leaf별 유지보수성 판정 +| leaf | main LOC | 판정 | 한 줄 사유 | +|---|---|---|---| +| `redis-runtime` | 7,306 | OVERBUILT | 약 절반이 redis-sdk 전용: gateway 118개 메서드 중 약 110개, lane 6개 중 4개, raw/admin/pubsub 역할, SDK 설정 섹션 | +| `redis-sdk` | 21,724 | OVERBUILT | 내부는 정돈(sync/reactive가 `*OperationRequests` 3.3k 공유)되어 있으나 명령 하나 추가에 leaf 3개·약 10개 파일 수정, 소비자 없음 | +| `cache-redis` | 4,574 | NEEDS_WORK | capability별 패키지는 좋음. "lease 빌림 → 대기 → 실패 분류" 틀이 15곳에 복사되어 이미 달라짐 | +| `httpclient` | 16,828 | NEEDS_WORK | autoconfig·패키지 분리는 좋음. blocking/reactive가 사실상 두 벌(동일 코드 약 675줄), 진입점 6개가 호출 파이프라인을 각자 조립 | + +#### Findings (영향 큰 순) + +1. **[Required][duplication] httpclient blocking/reactive 병렬 스택이 이미 갈라짐** — `src/adapter/outbound/httpclient/.../restclient/DefaultGenericHttpGateway.java` ↔ `.../webclient/DefaultReactiveHttpGateway.java` 외 14쌍 + - 근거: 짝 15개(약 3.1k줄 대 약 3.0k줄), 이름만 바꾸면 같은 줄 약 675줄. `BlockingClientRuntime`↔`ReactiveClientRuntime` 86%, `RestClientRuntimeFactory`↔`WebClientRuntimeFactory` 80%, `DefaultHttpServiceRegistry`↔`DefaultReactiveHttpServiceRegistry` 80%, `KernelHttpExchangeAdapter`↔`ReactiveKernelHttpExchangeAdapter` 102줄 동일. 이미 갈라진 곳(1차 `categoryOf` 외): 401 credential refresh가 blocking에만 있음(`DefaultGenericHttpGateway.java:213-225` vs reactive `:314` `false` 고정); `AttemptBudgetCalculator` 생성 방식 상이(`:194` vs `:275`); reactive `firstByteDelivered` `false` 고정(`ReactiveAttemptExecutor.java:157,164,172`); `withCredentialQuery` 수정이 한쪽 먼저(주석 `ReactiveAttemptExecutor.java:206`); reactive runtime이 `BlockingExecutionSupport` 반환(`ReactiveClientRuntime.java:117`). + - Remedy: Template Method — `AbstractLogicalCall`(context/finish/ambiguous/retryExhausted/onRetryGranted/credentialRequest + attempt guard; `RetryContext` 17-arg 생성 한 곳), `AttemptCore`(observation, `mapResponse`, `mapFailure`, credential 병합), 공통 필드는 `ClientRuntime`으로, permit 획득을 `Permits acquire()` 하나로(`AttemptResiliencePipeline.java:69-86` = `ReactiveAttemptResiliencePipeline.java:50-70`), registry·kernel adapter는 요청 매핑 static helper 공유. Size L · Removes 약 600~700줄, "두 번 고치기" 제거. + - 가정/반론: Mono와 동기 흐름을 한 추상화에 억지로 넣으면 읽기 어려움 → 합치는 범위는 순수 함수(매핑, 컨텍스트 생성)와 permit 획득까지, 재시도 루프(sleep vs `Mono.delay`)는 두 벌 유지. + +2. **[Required][duplication/structure] 진입점 6개가 호출 파이프라인을 각자 조립, 적용 단계가 제각각** + - 근거: lease → metadata → prepare → admission → deadline → credential → observation을 각자 손으로 조립. Generic/Reactive와 `BlockingStreamingGateway`는 admission·deadline·credential 모두 O; `DefaultReactiveSseGateway`는 credential만; `DefaultDynamicTargetGateway`는 자체 binding; `ReactiveStreamingGateway.java:50-107`은 셋 다 X. `BlockingStreamingGateway.java:63-68` 주석은 이 누락을 버그로 적고 고쳤는데 reactive streaming은 그대로 → 인증 profile에서 streaming 요청이 credential 없이 나갈 수 있음(동작 테스트로 확인 필요, correctness backlog). + - Remedy: `CallSetup.prepare(lease, operation)`이 metadata/prepared/deadline/admission/credentials 반환, 진입점은 전송 방식만 다르게 + 명시적 opt-out. Size M · Removes 약 150줄, 공통 단계 추가 시 1곳 수정. + - 가정/반론: streaming에서 retry 없음은 의도 → 공통 범위는 retry 이전 단계까지. + +3. **[Required][over-abstraction] 118개 메서드 `RedisCommandGateway`는 template에 불필요** — `src/adapter/outbound/redis-runtime/.../lettuce/operations/RedisCommandGateway.java`(1227), `LettuceRedisCommandGateway.java`(1282) + - 근거: 배선된 semantic adapter·health가 쓰는 메서드 8개(`get, set, getAndDelete, incrementBy, loadScript, evaluateRegisteredForList, evaluateRegisteredForLong, ping`), 죽은 realtime이 11개, 나머지 약 99개는 redis-sdk 전용. production lane은 `REGULAR`/`SCRIPT`뿐(`BLOCKING/TRANSACTION/PUBSUB/ADMIN`은 `RedisSdkAutoConfiguration.java:277-282` 한도 설정에만). runtime이 SDK 개념에 역의존: `RedisConnectionKind.forCommand(RedisCommandDescriptor)`(호출자 SDK `CommandPolicyGuard.java:104`), `sendApprovedRaw/sendAdminDiagnostic/sendExtension`(`:1107-1134`). `RedisSdkSettings`의 Limits/Blocking/Transaction/PubSub/Advanced/Raw/Admin 섹션 약 350줄도 SDK용. production 클래스가 `Sdk` 이름·`...redis.sdk` 패키지를 쓰고 redis-sdk와 split package 9개 공유. + - Remedy: 8개 메서드 `SemanticRedisCommands`(fake용 인터페이스는 유지), lane 2개, 역할 APPLICATION/ADVANCED만, `RedisRuntimeSettings`로 개명, `...redis.runtime.*` 패키지. Size L(대부분 삭제) · Removes 약 4k/7.3k줄 + 2,481줄 test fake 축소. + - 가정/반론: redis-sdk 유지 결정 시 잘라낸 메서드는 redis-sdk 확장 인터페이스로 이동. runtime 계약은 어느 경우든 8개로. + +4. **[Required][duplication] cache-redis "lease 빌림 → `.get(timeout)` → 예외 처리" 틀 15곳 복사, 이미 달라짐** — idempotency 6, lease 4, cache 4, rate-limit 1 (+probe 1, realtime 5) + - 근거: `try (borrow) {...get(..NANOSECONDS)} catch Interrupted catch Exception` 반복. `RedisOperationException.metadata().ambiguousExecution()`로 "안 보냄/보냈는지 모름" 구분하는 곳은 rate-limit뿐(`RedisEdgeRateLimitAdapter.java:123-131`); 나머지 셋은 lane 거절도 `Indeterminate`(1차 #1 부수 증상과 같은 원인). Lua 응답 디코더 3벌: `IdempotencyScripts.java:286-300`, `RateLimitScripts.java:275-285`, `LeaseScripts.java:169-185`. + - Remedy: `SemanticRedisCall.run(kind, capability, op, gw -> stage, onReply, onFailure(NOT_SENT|AMBIGUOUS|INTERRUPTED))` + 1차 #8의 `RegisteredLuaScript`에 reply 디코딩까지. Size M · Removes 약 180줄. + - 가정/반론: capability마다 fallback이 다름 → fallback은 호출자, 분류만 공통. + +5. **[Consider][pattern] `RedisIdempotencyStoreAdapter.transition` 파라미터 15개(outcome enum 7개), `complete`/`markFailed`/`releaseBeforeExecution`은 이를 안 쓰고 재구현** — `:420-481`, `:212-252`, `:270-306`, `:311-338` (같은 status 문자열 위 `switch` 5개). Remedy: `IdempotencyScripts.Reply`에서 `enum ScriptStatus`로 한 번 파싱, 호출부는 `Map`. Size M · Removes 약 120줄(#4와 합치면 534 → 약 300줄). 반론: 명시적 switch가 리뷰 쉬움 — 단 5벌이 이미 서로 다른 default. + +6. **[Consider][over-abstraction] 대체 불가능한 확장 지점** — `HttpClientObservationAutoConfiguration.java:23-35` (`@ConditionalOnMissingBean HttpClientTagPolicy` 소비처 없음; `BlockingExecutionSupport.standard()`가 `HttpClientTagPolicy.standard()`를 다시 만들어(`BlockingExecutionSupport.java:77`) override 무효; `BlockingExecutionSupport`는 구성요소 19개 묶음, 11개가 상태 없는 `new X()`). Remedy: bean 삭제 또는 support에 주입, `ExecutionSupport`로 개명. Size S. + +7. **[Consider][over-abstraction] 구현 1개짜리 인터페이스(테스트 대역 없음)** — `RetryCoordinator`(참조 0), `RetryEligibilityEngine`/`Default…`, `ExecutionEvidenceClassifier`/`Default…`, `BackoffStrategy`/`ExponentialFullJitterBackoff`(테스트도 `Default*` 직접 생성). Remedy: 인터페이스 삭제·구현체 개명. Size S · 개념 4개 제거. 반론: design 문서가 SPI로 기재 — 교체 소비자 없음. + +8. **[Consider][reachability] httpclient에서 `HttpClientPlatformAutoConfiguration`으로 도달 불가 약 820줄** — `BoundedErrorBody`(54줄, main·test 참조 0 → 즉시 삭제), `MultipartReplayability`, `SafeHttpLogEvent`, `spring7/*`(107), `migration/*`(164)는 테스트만 참조, `http3/*`(392, Experimental, compileOnly Jetty + 별도 lane). Remedy: http3만 유지, 나머지 삭제 또는 docs로. Size S~M. + +9. **[Consider][SRP] `RedisTopologyClientFactory`(662줄) 역할 과다** — URI/TLS/ClientOptions factory + `RuntimeClient` 구현 3개(`:427` Standalone, `:475` Cluster, `:551` RoleRouting) + 참조 카운트(`SharedClientResources` `:382`) + `ShutdownBudget`. Remedy: 구현 3개를 package-private top-level로 이동(이동만). Size M · 파일 약 350줄로. + +10. **[Consider][duplication] settings → profile 필드 단위 복사** — `HttpClientProfileFactory.java:40-153` (`Pool` 11, `Timeout` 9, `Tls` 8 필드…; `valueOf(x.toUpperCase())` 8번). Remedy: settings 필드를 enum 타입으로(binder가 대소문자 무시 변환). Size S. 반론: `@DefaultValue`가 Spring 타입이라 profile 레코드 직접 바인딩 불가 — 복사 구조 자체는 정당. + +11. **[Nit][readability] 이력 서술 주석** — httpclient "used to/no longer" 27곳(`ProtocolEvidenceReader.java:8`, `HttpClientTransportAutoConfiguration.java:66`, `BlockingStreamingGateway.java:63`), `RedisCapabilityConfig.java:30-33` "376 lines … (BOOT-007)", `CapabilityKeyspace.java:11`, redis leaf 23곳; 인라인 FQN 약 160줄(`HttpMethod`/`HttpStatus` 충돌만 정당; `RedisKeys.java:37-80` javax.crypto, `RedisIdempotencyStoreAdapter.java:435`, `ReactiveAttemptExecutor.java:208-213`). Remedy: 불변 조건만 남기고 이력은 git/ADR로. + +12. **[Nit][structure] cache-redis 세부** — `CacheKeys`가 가변 generation 상태 보유(`RedisCacheRegionAdapter.java:421-450`) → `RegionGeneration` 분리; HMAC `KeyDigest`가 설정 패키지(`capability/RedisKeys.java`)에 있고 `RedisNamespace.prefix()` 대신 env:service:domain 재조립; `cache-redis/CLAUDE.md`의 "legacy cache router" 존재하지 않음. + +13. **[Nit] 기타** — Jackson 2 사용 main 파일은 `RemoteProblemDecoder` 하나(`build.gradle:58-66` 주석은 "two files") → Jackson 3로 옮기면 의존성 1개 감소; "runtime draining"·"retry budget exhausted"를 `HttpRateLimitRejectedException`으로 던짐(`DefaultGenericHttpGateway.java:182,280`, reactive `:265,351`) → 텔레메트리 카테고리 오기; `RedisSdkAutoConfiguration.java:297-338` health indicator 둘은 DOWN 값만 달라 하나로. + +#### Cross-module leads (조사 안 함) +- `RedisSdkAutoConfiguration.RedisSecretSource` + `System.getenv` fallback(`:213-217,375`) vs `SecretSourcePort`(`RedisCapabilityConfig.java:68`); httpclient는 port 직접. +- `HttpClientEnvironmentKeys`(179줄, 리플렉션 env 이름 파생) vs support `StrictSettingsBinder`. +- TLS material 로딩: `RedisTopologyClientFactory.java:327-380`, `RedisSdkAutoConfiguration.java:253` vs `httpclient/security/TlsMaterialProvider.java`. +- `ca-skeleton.capabilities.*` selector 문자열이 bootstrap/persistence-jpa/redis main 16개 파일에 흩어짐(`RedisCorrectnessRoles.java` 포함). +- `secret:///` 파싱(`RedisKeys.java`)의 다른 leaf 존재 여부. + +#### Coverage note +깊게: httpclient gateway·executor·resilience·runtime·support·autoconfig, cache-redis main 전체, redis-runtime gateway 사용처·lane·settings·autoconfig·topology. 훑음: redis-sdk(구조·크기), httpclient profile/security/dynamic. 수치는 grep·정규화 diff 추정. #2 reactive streaming credential 누락은 동작 테스트로 확인 필요. + +### S4 — 그 밖의 outbound capability adapter + +#### Leaf별 유지보수성 판정 +| leaf | main LOC | 판정 | 한 줄 이유 | +|---|---|---|---| +| `adapter/outbound/notification` | 13,512 | OVERBUILT | provider 7종 중 조립되는 건 SES·SMTP 2종. 나머지 5종 약 2.75k줄은 테스트에서만 생성 | +| `adapter/outbound/fileserver` | 14,230 | OVERBUILT | 루트 패키지 8.7k줄(R1/R2 publication)의 port 호출처 0. `platform/**`와 코드 공유 없는 별도 제품 | +| `adapter/outbound/objectstorage` | 14,478 | OVERBUILT | legacy/신규 두 세대 공존. legacy adoption은 SPI 구현체가 없어 켜면 기동 실패. direct/multipart는 1차 D#7 | +| `adapter/outbound/messaging` | 4,249 | OVERBUILT | 79%(3.36k줄)가 연결되지 않은 R1 compiler/encoder | +| `adapter/outbound/messaging-kafka` | 367 | HEALTHY | 작은 R0 seam | +| `adapter/outbound/support` | 279 | HEALTHY | 결함은 1차에서 다룸 | +| `adapter/outbound/identifier` | 83 | HEALTHY | `UuidCodec`은 1차에서 다룸 | + +#### Findings (영향 큰 순) + +1. **[Required][reachability/structure] fileserver 루트 패키지 publication 제품군(R1+R2) 호출처 없음** — `src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/*.java` (31파일, 8,659줄) + - 근거: main에서 `FilePublicationPort`/`FileExportPort`를 쓰는 곳은 이 leaf와 application-core뿐(sample·composition·bootstrap 0). `FileserverR2Config.java:20-23`은 component scan으로, `FileExportConfig.java:23,49`는 bean 등록. 루트 패키지와 `platform/**`는 서로 import 0. leaf 안에 FilePublicationPort 계열 구현 3개(`FilesystemCsvExportAdapter`, `LocalFilePublicationAdapter`, R2 provider). + - Remedy: 삭제. 유지 결정이면 별도 optional leaf로 추출. Size L · Removes 약 8.7k줄, 설정 네임스페이스 2개(`app.fileserver.*`, `app.file-export.*`), `FileserverActivationValidator`. + - 가정/반론: 어떤 fork도 R2 publication을 안 씀 / CLAUDE.md가 "first qualified R2 provider"로 공개 API 취급. + +2. **[Required][reachability] messaging R1 compiler/encoder 체인 미연결** — `src/adapter/outbound/messaging/.../envelope`(1,573) + `contract`(628) + `destination`(723) + `config`(439) + - 근거: 진입점 `JsonSchemaIntegrationEventEncoder`가 main에 나오는 곳은 `app-bootstrap/.../OutboxCanonicalTransportRequirementValidator.java:55`의 에러 메시지 문자열뿐; `CompiledMessagingDescriptor` main 참조 0; CLAUDE.md "R1 compiler is intentionally not wired". 그런데 NetworkNT validator가 runtime 의존성(`implementation(libs.json.schema.validator)`), schema 리소스 9개·YAML 배제 정책 유지. `realtime/MessagingDurableFanoutAdapter`(+`RealtimeFanoutEnvelopeJson`, 138줄)는 생성처·테스트 0. leaf에 R0 legacy(`MessageBroker`)·R1(미연결)·canonical bridge 세 세대 공존. + - Remedy: R1 체인·realtime fanout 삭제(evidence 생성에 필요하면 qualification source set으로). Size L · Removes 약 3.5k줄 + runtime 의존성 1개. + - 가정/반론: R1 encoder는 canonical bridge(vendored `messaging-schema-*`)로 대체됨 / R2 qualification evidence가 사용 — 그래도 test 전용이면 충분. + +3. **[Required][reachability] notification provider 5종 미조립, 확장 슬롯도 비어 있음** — `.../platform/provider/{apns,fcm,twilio,webpush,webhook}` (2,750줄) + - 근거: `ProviderRuntimeAssembler` 구현은 `SesProviderRuntimeAssembler.java:28`, `SmtpProviderRuntimeAssembler.java:48` 2개; `ProviderCallbackAssembler`는 SES 1개; 둘 다 `AssembledProvider.dispatchOnly` 반환(`:98`, `:112`) → projector/reconciliation 슬롯·`MapProviderEventProjectorRegistry`·`CapabilityReconciliationGateway`에 production 입력 없음. 참조 0: `SesDeliveryProjector`, `TwilioDeliveryProjector`, `SesSuppressionUpdater`, `FcmContactPointUpdater`, `TwilioReconciliationCapability`. 자격증명 회전 경로(`ProviderRuntimeRotator`, `RuntimeDrainCoordinator`, `CredentialProbe` 구현 0) 미연결. 설정 문서는 7종 모두 유효값으로 기재(`docs/notification/configuration-reference.md:64`); `Provider.validate`는 APNs topic·VAPID·Twilio secret까지 검사 후 `NotificationProviderAssembly.java:141-143`에서 "missing assembler"로 실패. + - **1차 B#2 보정:** B#2는 위조 callback이 `SesSuppressionUpdater`로 suppression을 만든다고 적었으나 이 클래스는 참조 0 → 그 영향 서술은 과장(서명 우회 자체는 유효). + - Remedy: 5종을 extension source set/sample로 이동 또는 삭제; `ProviderType`을 SES/SMTP로; 빈 projector/reconciliation 슬롯 제거. Size L · Removes 약 3.0k줄, 개념 6개. + - 가정/반론: support-matrix가 "contract implemented / unqualified"로 광고 — 계약 보존이 목적이면 이동이 맞음. + +4. **[Required][duplication(어긋남)] SMTP capability 두 곳에 서로 다른 값** — `SmtpProviderRuntimeAssembler.java:138-152` vs `SmtpNotificationProviderAdapter.java:75-76` (maxPayload 26,214,400 vs 25,000,000; TTL 24h vs 1d; assembler는 자기 사본(`:126`), SES assembler는 `adapter.capabilities()`(`SesProviderRuntimeAssembler.java:95`); 11개 위치 인자 `new ProviderCapabilities(false,false,…)` 8곳). Remedy: 사본 삭제·`adapter.capabilities()` 사용, named factory(application-notification record라 cross-leaf). Size S. + +5. **[Required][SRP] `LocalPersistentControlPlane` 7가지 일** — `.../fileserver/LocalPersistentControlPlane.java` (1,470줄; #1에서 유지할 때만) + - ① 레코드 repository(`:176-352`, `:728-790`) ② 상태 전이표(`validateOperationTransition`, `isAllowedAdjacentTransition` `:499-592`) ③ 2단 lock manager(static stripe, `FileLock`, `ThreadLocal` 재진입, static `POISONED_OPERATION_LOCK_ROOTS` `:40-46`, `:205-268`, `:1377-1449`) ④ durable write 프로토콜(temp→force→replace→read-back→repair `:352-497`) ⑤ 보안 디렉터리 syscall facade `SystemSecureRecordOperations`(`:1036-1272`) ⑥ fault-injection 타입 7개 + test 생성자·factory 6개(`:62-147`, `:1273-1376`) ⑦ R1 호환 decode(`:1318`). + - Remedy: 전이표 → `DurablePublicationRecord.State.canAdvanceTo()`(objectstorage는 이미 `ObjectOperationStateMachine`으로 분리); 나머지 `OperationLockManager`, `DurableRecordFile`, 얇은 repository로. Size L · 한 번 수정 시 읽을 범위 1.4k → 약 300줄. + +6. **[Required][duplication(어긋남)] "attested root 아래 private shard" 구현 3벌** — `LocalPersistentControlPlane.java:668-715` / `LocalPersistentPayloadOperations.java:356-406,607-700,780-1064` / `LocalPersistentRootAttestor.java:662-773` (각자 `FaultCallback`, `IdentityVerifier`, `FailureKind`, 예외, `SecureShard`/`ShardAttributes`, System* facade 약 550줄; 검증도 다름 — control은 symlink·`Files.getFileStore`, payload는 fileKey 공백·store 이름; `forceDirectory` 3곳(`:808`, `LocalPublicationJournal.java:209`, `LocalFilePublicationAdapter.java:338`), `MessageDigest.getInstance` 7개 파일). Remedy: package-private `AttestedDirectory` 하나 + System 구현 1 + fault test double 1. Size M · Removes 약 400줄, seam 인터페이스 9개. 반론: crash qualification 테스트가 FaultPoint에 묶여 이전 비용 큼. + +7. **[Required][duplication(어긋남)] 손으로 만든 flat JSON parser 2개** — `FileserverControlRecordCodec.java:655-855` vs `LocalPublicationJournalCodec.java:110-266` (control은 엄격한 `decodeUtf8`, journal은 `new String(bytes, UTF_8)`로 잘못된 byte를 대체 문자로 조용히 변환; 빈 객체·쉼표 루프 상이). Remedy: `FlatCanonicalJson` 하나. Size S · 약 120줄. 반론: R1 journal은 읽기 전용 호환이라 관대 decode 의도 — 그렇다면 한 줄 명시. + +8. **[Consider][Value Object] 원시 String 검증 73곳** — `FileserverControlRecordCodec.java:463-558`(codec이 validator 13개 겸함), `FileserverR2Validation.java:36-125` (`requireText` 22, `requireDigest` 12, `requireFileId` 8; `requireDigest(value, field)`와 `requireSha256(label, value)`는 인자 순서만 다른 중복). Remedy: `Sha256Hex`, `FileId`, `RouteToken`, `SafeSegment` record. Size M. + +9. **[Consider][pattern] notification provider 공통 템플릿은 절반만 있음** — 공유: `ProviderResults`, `NotificationHttpGateway`. HTTP adapter 5개가 각자 재구현: `completedFuture(send)`, nanoTime, `protector.reveal(AccessContext.dispatch)`, request map, exchange, 2xx→accepted 아니면 `rejected(classifier.classify)`, transport catch(`ApnsNotificationProviderAdapter.java:74-100`, `SesNotificationProviderAdapter.java:105`, `TwilioSmsProviderAdapter.java:76-126`, `WebPushNotificationProviderAdapter.java:80`, `WebhookNotificationProviderAdapter.java:107`); classifier가 `new ProviderFailure(…5인자)` 18회. callback SPI는 있고 구현은 SES·Twilio(미연결). Remedy: #3 적용 시 HTTP provider는 SES 하나라 불필요; 3개 이상 유지 시 `HttpProviderSend.run(...)` helper + `ProviderResults.failure(code, category, reason)` factory(success mapper 인자). Size M · 약 150줄. + +10. **[Consider][reachability] objectstorage legacy adoption은 켜면 기동 실패** — `.../maintenance/*`(609줄), `config/ObjectStorageLegacyMigrationConfig.java`, `LegacyObjectAdoptionSettings` (`LegacyObjectInspector`, `LegacyAdoptionApprovalReplayStore` 구현체 없음; `Ed25519LegacyAdoptionApprovalVerifier` main 참조 0; readiness `ObjectStorageCapabilityEvidence`/`Card`(112줄) 테스트 전용; `control/ObjectControlRecordEnvelope` 참조 0). Remedy: 삭제 또는 별도 migration 도구. Size M · 약 800줄. 반론: fork가 구현을 공급하는 SPI일 수 있음 → 그렇다면 README에 필수 bean 명시. + +11. **[Consider][structure] objectstorage 세대 구분·패키지 위치 불명확** — 루트 `ObjectStorageConfig.java`, `config/RoutingObjectMutationAdapter.java:52-57,96-170,273-406` (legacy(`ObjectStoragePort`, 동기 `S3Client`)와 신규(`S3AsyncClient`+netty)가 코드 공유 없이 공존; port 구현 4개가 `config/`; managed publish(약 230줄)는 router inline, staged는 `kernel/` → 비대칭). Remedy: legacy → `legacy/`, `Routing*Adapter` → `routing/`, `kernel/ManagedObjectPublicationKernel` 추출. Size M. sample이 legacy 기본 사용 → legacy 삭제는 sample 이전 후. + +12. **[Consider][over-abstraction] `SelectedObjectStorageProviderFactory`는 factory가 아님** — telescoping 생성자 4개, `Object` 슬롯 3개를 `Class` cast로 꺼내는 type-unsafe service locator(슬롯은 미연결 direct/multipart 전용). Remedy: `record ProviderInstance(ObjectStorageProvider, ObjectControlStore, Runnable close)`. Size S · 약 70줄. + +13. **[Consider][over-abstraction] provider 1개인데 fileserver R2 routing 계층** — `RoutingFilePublicationAdapter`, `FilePublicationProvider`(구현 1), `LocalPersistentPublicationProvider.java:60-86`(destination마다 넘긴 뒤 "전부 같은 인스턴스인지" 재검증). Remedy: provider가 `(controlPlane, payload, Map)`를 받게 하고 router·interface 삭제. Size S. + +14. **[Consider][State 전이표] `ProviderRuntime` 상태 전이가 7개 메서드에 흩어짐** — `ProviderRuntime.java:127-241`, `RegistryProviderRuntimeControl.java:30-45` (`markAuthenticationFailed`만 무조건 `set` → DISABLED·DRAINING도 덮어씀). Remedy: `EnumMap>` + `transition(target, reason)`. Size S · 약 70줄. + +15. **[Consider][readability] Settings가 모든 provider 필드를 한 record에** — `NotificationPlatformSettings.java:209-256,280` (`switch (resolved.name())` 문자열 분기, 테스트 호환용 11-인자 오버로드). Remedy: enum switch, #3과 함께 미조립 provider 필드 제거. Size S. + +16. **[Nit][readability]** 이력 서술 주석 notification 56건·fileserver 18건(예: `ProviderType.java:10-19`, 예외 메시지 `:85` "used to bind successfully…", `MapProviderCallbackAdapterRegistry.java:10-15`, `AesGcmCallbackPayloadProtection.java:11-15`); objectstorage main inline FQN 84줄(`RoutingObjectMutationAdapter.java:74,80`, `ObjectStorageConfig.java` `@Conditional`) — objectstorage CLAUDE에 금지 규칙 없음. + +17. **[Nit][structure] 용어 혼재** — fileserver 한 leaf 안에서 루트는 `*Config`, platform은 `*Configuration`; notification `*ProviderProperties` 7개는 `@ConfigurationProperties`가 아닌 파생 값 → `*ProviderProfile`; 클래스 이름의 버전 라벨(`FileserverR2Config`, `R2PublishedReferenceCodec`). + +#### Cross-module leads (조사 안 함) +- 손으로 만든 canonical JSON codec이 3개 leaf에: fileserver 2벌, objectstorage `control/CanonicalJsonReader/Writer`, messaging `DeterministicEnvelopeWriter`. +- 로컬 보안 파일시스템 primitive 중복: fileserver `LocalPersistent*`·`platform/local/SafeFileChannelFactory`·`SecureDirectoryWalk` vs objectstorage `LocalObjectPathGuard`·`LocalDev*Store`. +- notification `JdkNotificationHttpGateway`·`AwsSignatureV4Signer` vs `adapter:outbound:httpclient` + objectstorage의 AWS SDK. +- adapter `LocalJsonSchemaRegistry` vs vendored `messaging-schema-json`; `adapter:outbound:messaging-kafka` vs vendored `messaging/messaging-kafka`. +- `ProviderCapabilities`(application-notification) 11개 위치 인자 → named factory. + +#### Coverage note +구조: fileserver 루트 대형 파일 5개 outline·핵심 구간, notification provider/assembly/runtime, objectstorage config/kernel/maintenance/readiness, 네 leaf 전체 타입의 main 참조 grep(`.imports`/`spring.factories` 확인, 문자열·reflection wiring은 grep 한계). 얕게: notification template/security/observation, fileserver `platform/local`, objectstorage `s3/*`. + +### S5 — Inbound HTTP / GraphQL + +#### Leaf별 유지보수성 판정 +| leaf | main LOC | 판정 | 이유 | +|---|---|---|---| +| `src/adapter/inbound/web` | 23,095 (340 파일) | OVERBUILT | servlet 진입점에서 닿는 코드 155/340 파일, 9.8k/23.1k LOC. 관심사마다 구현 두 벌. WebFlux 쪽은 어떤 조합으로도 안 켜짐 | +| `src/adapter/inbound/web-fileserver` | 3,976 (62 파일) | NEEDS_WORK | 전부 도달하나 reactive 907줄은 안 켜짐; 별도 problem+json 형식; 업로드 정책이 4개 transport에 복사; leaf 문서 없음 | +| `src/adapter/inbound/graphql` | 25,984 (400 파일) | OVERBUILT | 도달 136/400(1차와 같음). 배선된 코어는 정리됐으나 에러 진입점 우회, autoconfig 706줄, 부팅마다 reflection 아키텍처 검사 | + +#### 발견 (효과 큰 순) + +1. **[Required][duplication] HTTP 에러 어휘가 web+fileserver 안에 3개, 이미 갈라짐** — `web/.../error/ClientSafeValidationDetails.java:18-43` 외 + - 응답 형식 3개·코드 체계 4개: Envelope(`GlobalExceptionHandler`, `AuthErrorResponseWriter`, `RateLimitInterceptor`; 코드 `OperationalError`, `RateLimitTransportError`); `WebProblem`(`ProblemCode` enum, `ProblemCatalog.standard()` `ProblemCatalog.java:51-162`, `problem-catalog.yaml`이 같은 목록 세 벌; MVC/WebFlux problem handler, `ThrottleProblemWriter`, `BudgetProblemMapper`, `WebMvcBudgetExceptionHandler`); `FileserverProblem`(필드 15개 problem+json, `FileserverExceptionHandler.java:24-40`). + - 갈라짐 1 — 검증 규칙표 두 벌: `ClientSafeValidationDetails`(`NotNull→NOT_NULL`, 고정 문구, 점 경로) vs `validation/WebValidationIssueMapper.java:56-86`(`must-not-be-null`, 치환된 메시지를 그대로 노출(`${`만 거름), RFC 6901 pointer) → README "치환 메시지 미노출" 규칙을 한쪽만 지킴. + - 갈라짐 2 — 운영은 `spring.mvc.problemdetails.enabled=false`(`app-bootstrap/.../application.yml:17-22`)라 WebProblem은 fixture(`ContractFixtureApplication.java:35-40`)에서만; 반대로 fileserver는 D5(ProblemDetail 거부)와 달리 운영에서 problem+json을 보내는데 `FileserverErrorCode`는 이미 `ApiErrorCode` 구현. + - 조치: HTTP 에러 형식을 Envelope 하나로; WebProblem 어휘(yaml, 핸들러 2, writer 3 포함) 삭제 또는 testFixtures로; fileserver는 `ErrorResponseFactory.envelope(code,…, details)`(프로토콜이 요구하는 `Draft12OffsetProblem`만 유지); 검증 규칙표 하나로. 규모 L · 약 1.3k LOC, 응답 형식 2개, 코드 체계 1개 제거. + - 가정/반론: fileserver 클라이언트가 problem+json 의존 가능 / 템플릿이라 외부 소비자가 없는 지금이 가장 쌈. + +2. **[Required][reachability/duplication] WebFlux 쌍둥이 코드는 어떤 조합에서도 안 켜짐** — `web/build.gradle:26`, `web-fileserver/build.gradle:27` + - 근거: 두 leaf 모두 `implementation spring-boot-starter-web` → 소비자 classpath에 DispatcherServlet → Boot는 항상 SERVLET → `@ConditionalOnWebApplication(REACTIVE)` 모두 false. `FileserverReactiveConfiguration.java:24-30` Javadoc도 "inert in the shipped composition". + - 규모: web main 약 1.8k(`webflux/*` 1,010, `advanced/webflux` 525, `callback/reactive` 221), fileserver reactive 907, test 약 2k, strict lane 2개(`webFluxContractTest`, `webFluxPerformanceTest`). + - 중복 정도: 주석·import 제외 쌍마다 40–69% 동일(problem handler 0.69, budget 0.49, throttle 0.44, request-id 0.40). transport 중립 코어(`core/`, `budget/`, `operation/`, `ProblemCatalog`, `WebValidationExceptionMapper`)는 **이미 있음** → 중립 코어를 더 뽑아도 줄어드는 양은 300줄 미만. + - 갈라짐: `NoResourceFoundException`→404는 MVC에만(`WebMvcProblemExceptionHandler.java:150`); reactive fileserver에는 tus/draft12/lifecycle/describe 없음. `WebFluxPlatformAutoConfiguration.java:34-37`의 중복 정당화("공유 설정을 쓰면 servlet 타입이 딸려 온다")는 사실이 아님(중복 bean 7개 — 주석은 6개 — 모두 stdlib/Jackson만 import). + - 조치: reactive 껍데기 삭제. 꼭 지원해야 하면 graphql처럼 leaf에서 starter-web을 빼서 서버 선택을 composition으로, 공통 bean 7개는 `WebPlatformCommonConfiguration`으로. 규모 L · main 약 2.7k + test 약 2k, lane 2개 제거. + - 반론: 설계서가 WebFlux를 Stable로 약속 — 실행할 composition이 repo에 없음. + +3. **[Required][over-abstraction] `WebMvcPlatformAutoConfiguration`: bean 14개 중 9개는 운영에서 읽는 곳 없음, startup check는 실패 불가** — `mvc/autoconfigure/WebMvcPlatformAutoConfiguration.java:56-178` + - 읽는 곳 없는 bean: `webOperationCatalog`(읽는 `FunctionalRouteRegistry`, `WebRouteInventory` 둘 다 도달 불가), `webBudgetCatalog`, `webProblemCatalog`, `webProblemFactory`, `webValidationExceptionMapper`, `webValidationIssueMapper`, `webWireTypeManifest`, `webUriPolicy`, `webMethodPolicy`. `WebMvcEvidenceFilter.java:52-57`은 매 요청 tracker 생성하지만 main의 `markApplication*`/`snapshot()`/`requireTracker` 호출 0. `WebMvcPlatformStartupCheck.java:33-53`은 같은 클래스가 무조건 만드는 bean 3개의 존재만 확인 → 실패 불가. `WebPlatformSnapshot` 필드 7개 중 4개는 항상 빔. + - 조치: bean 9개, evidence filter 배선, startup check, `admin/platform` 삭제. 규모 M · 약 600 LOC, 개념 약 12개. + +4. **[Required][structure] web 안에 같은 관심사가 "1세대(운영·sample 사용)"와 "2세대 platform(읽는 곳 0)" 두 벌** (1차 I-8 확장) + - 조건부 요청: `ETags`/`PreconditionFailedException`(sample 사용, handler 있음) vs `EntityTag*`/`ConditionalReadEvaluator`/`MutationPreconditionEvaluator`/`WebPreconditionFailedException`(test만, handler 없어 실제로 쓰면 500; `WebPreconditionFailedException.java:13`이 스스로 인정). + - 페이지네이션: `PageParams`/`SortParam` vs `WebCollectionRequestParser` + catalog 5종(약 1.1k). cursor codec은 web 2벌(`cursor/CursorCodec`, `pagination/HmacWebCursorCodec`) + graphql 1벌(`HmacGraphQlCursorCodec`), 셋 다 운영 경로 밖. + - 헤더 상수: 같은 패키지 `http/ApiHeaders`와 `http/WebHeaderName` 11개 겹침(표준 헤더는 Spring `HttpHeaders`에 이미 있음). + - rate limit: `RateLimitInterceptor`(운영) vs `WebRateLimiter` + `Web{Mvc,Flux}ThrottleFilter` + `admission/*` + `advanced/ratelimit`(fixture 전용). + - 로깅: `RequestLoggingFilter` vs `WebAccessLog*`/`WebAudit*`(381). 동시 실행 제한 semaphore 3벌: `SemaphoreAdmissionController`, `VirtualThreadAdmissionGuard`, `BlockingBridgeBudget`. + - 조치: 관심사마다 하나만(기본은 2세대 삭제 — 1세대가 문서·sample·handler와 연결). 규모 L · 약 5k LOC, 병렬 개념 약 8개. + - 반론: 2세대가 설계 목표일 수 있음 → 그렇다면 1세대를 옮기고 삭제. 둘 다 두는 것이 최악. + +5. **[Required][duplication] Retry-After 초 계산 3벌, 결과 다름** — 운영 `ratelimit/RateLimitInterceptor.java:107-111`은 `"0"` 가능; `error/ThrottleProblemWriter.java:72-76`은 최소 1("0은 즉시 재시도" 주석); `mvc/operation/OperationHttpController.java:81`, `ReactiveOperationHttpController.java:100`은 `toSeconds()` 버림. 조치: `RetryAfter.seconds(Duration)` 하나. 규모 S. + +6. **[Required][duplication/pattern] GraphQL 에러 "단일 진입점"이 우회되고 Category switch 3개** — `runtime/GraphQlWireErrorMapper.java:23,57-72` + - Javadoc "Everything routes through here"인데 요청 단계 경로 2곳(`GraphQlPlatformWebInterceptor.java:165`, `GraphQlPlatformInstrumentation.java:88`)은 `GraphQlPlatformRejectionMapper.map`을 직접 호출; `mapRequestRejection` 호출처 0, 본문이 `mapFieldFailure`와 동일. 결과: adopter `GraphQlPrincipalResolver`가 `ApiErrorCarrier`를 던지면 요청 단계는 `INTERNAL_ERROR`, 필드 단계는 제 코드. + - Category switch 3개(`category` :102, `clientMessage` :112, `GraphQlWireErrors.classificationOf` :54); `mapKnown` instanceof 분기 9개(`GraphQlPlatformRejectionMapper.java:54-121`); "요청한 리소스를 찾을 수 없습니다." 3곳 중복. 실제 매퍼는 `runtime/`, 참조 0인 것(`GraphQlRequestErrorMapper`, `GraphQlSubscriptionExceptionResolver`, `GraphQlNullabilityContract`, 186줄)은 `error/`. + - 조치: 세 호출부가 하나의 `map(Throwable, ctx)`; `EnumMap` 표로 switch 3개 대체; platform 예외가 code/category/message 인터페이스를 구현해 instanceof 사슬 제거; 실제 쓰는 에러 클래스는 `error/`로, 참조 0 삭제. 규모 M · 약 250 LOC. + +7. **[Consider][SRP] `GraphQlPlatformAutoConfiguration` 706줄 + 부팅마다 reflection 아키텍처 검사** — `autoconfigure/GraphQlPlatformAutoConfiguration.java:83,151` (bean 약 40개가 10가지 기능: startup 검증, runtime 감지, body limit, chain, auth, cost, 에러, 관측 7, preparsed cache, DataLoader; `graphQlControllerBoundaryCheck`가 `architecture/`(969 LOC)를 매 부팅 실행 — 같은 경계를 `app-bootstrap` ArchUnit `AdapterBoundaryArchitectureTest.java:50,345`가 빌드 때 이미 검사; Javadoc(:76) "A real @AutoConfiguration"인데 실제는 FQN `@Configuration`, :626-660 FQN 투성이). 조치: 기능별 `@Configuration`으로 나누고 root에서 import, `architecture/`는 ArchUnit test로. 규모 L. + +8. **[Consider][over-abstraction] web이 하위 leaf 패키지 구조를 앎** — `web/.../moduleboundary/WebStableModule.java:119-172` (web main이 web-fileserver 패키지 12개 선언 — 방향이 거꾸로 된 지식; test `WebBuildModel.java:190-207`은 형제 leaf 디렉터리를 경로로 스캔; main 669줄은 test에서만; graphql도 같은 구조(main 535); 자체 import 스캐너 285/293줄은 ArchUnit `layeredArchitecture()`/`slices()`로 대체 가능). 조치: leaf마다 ArchUnit 규칙 하나, enum·스캐너 삭제. 규모 M · 약 2.1k LOC. + +9. **[Consider][structure] notification HTTP는 일반 web leaf 소속이 아님** — `web/.../notification/platform/**` (18 파일, 1,168줄; web에서 `application-notification`을 import하는 유일한 패키지(17곳); web 쪽은 `core`·`observability`만 사용; web-fileserver 분리 이유(`web-fileserver/build.gradle:8-20`)와 같은 모양; 이 패키지 때문에 모든 HTTP 앱이 `application-notification`을 classpath에 둠(`web/build.gradle:18`); web `CLAUDE.md` Allowed 목록에 이 의존 없음). 조치: `adapter:inbound:web-notification` leaf. 규모 M. + +10. **[Consider][SRP] fileserver 업로드 세션 정책(namespace, 만료 시각)이 4개 transport에 복사** — `FileUploadController.java:180-187`, `TusController.java:105-110`, `Draft12UploadController.java:86-93`, `reactive/FileUploadHandler.java:116-123` (TTL 설정 3개·검증 복사: `FileserverWebProperties.java:24-26`, `TusProperties.java:22`, `Draft12Properties.java:16-21`; 만료 계산은 세션 정책이라 HARD-STOP 4에 가까움). 조치: application-fileserver가 `UploadMode`별로 계산. 규모 S-M. + +11. **[Consider][pattern] `compat/GraphQlSchemaComparator.java`(791줄, S5 최대 파일) + `GraphQlChangeKind.java`(285줄)는 graphql-java 기능 재구현** — graphql-java 25에 `graphql.schema.diff.SchemaDiff`/`DiffCategory` 있음; compat 패키지는 도달 불가. 조치: 삭제(1,562 LOC), 필요하면 `SchemaDiff` 빌드 태스크. 가정: 세부 분류가 `SchemaDiff`와 같게 나오는지 미확인. + +12. **[Nit][pattern] profile-name record 5개 복사본, 1개는 이미 다름** — `operation/{Admission,Authorization,Response}ProfileName`, `CachePolicyName`, `budget/WebBudgetProfileName` = `[a-z][a-z0-9.-]{2,63}`; `ratelimit/RateLimitProfileName`만 `[a-z][a-z0-9-]{0,63}`. 조치: `ProfileName` 하나 또는 #3과 함께 삭제. 약 140줄. + +13. **[Nit][over-abstraction] GraphQL `Unsupported` 플래그 6개는 "켜면 부팅 실패"만** — `GraphQlPlatformSettings.java:151-176`, `GraphQlPlatformStartupValidator.java:54-72`, 문자열 `with(String,…)`. 미구현 기능에는 설정 키를 두지 않음. + +14. **[Nit][readability]** web README `:3` 패키지 루트 `dev.caskeleton.adapter.web` 틀림; web 문서에 WebFlux·notification·problem catalog·advanced·operationasync 전혀 없음(LOC 절반 이상); web-fileserver CLAUDE.md/README 없음; 주석 비율 web 30%, graphql 33%; 이력 서술 web 34, graphql 74; graphql "design §" 92회, "Task N" 17회; inline FQN web 58, graphql 92; `GraphQlPlatformWebInterceptor.java:66` 생성자 인자 9개(anonymous 관련 3값 parameter object). + +#### 다른 모듈로 이어지는 단서 (조사 안 함) +- Category→status/message switch가 grpc `GrpcStatusMapper.java:40`에도; web 영어 문구, graphql 한국어 문구로 이미 다름 → shared-contract 표 하나 후보. +- moduleboundary 세 번째 사본: websocket `WebSocketStableModule.java`(394), `WebSocketBuildModel`(264). +- request context 타입 3종: web `core/WebRequestContext`, graphql `GraphQlRequestContext`, shared `TenantContext`. +- release/promotion gate(web `advanced/release`, graphql `release`)가 websocket/grpc에도 반복되는지. +- bulkhead: graphql `GraphQlBlockingBridge`, fileserver `BlockingTransferExecutor`, httpclient 겹침 여부. + +#### 검토 범위 +자세히: leaf 문서, 두 web autoconfig, error/validation/ratelimit/conditional, graphql autoconfig/error/runtime, fileserver 컨트롤러·problem·reactive 설정. 도달성은 servlet 진입점(autoconfig, 스캔 대상 stereotype, 다른 main leaf import, sample 제외) 스크립트. 대충: `advanced/*`, pagination 내부, compat 내부. 1차 결함은 재보고 안 함. + +### S6 — Realtime/gRPC inbound adapters, composition roots, sample + +#### Per-leaf maintainability verdict +| leaf | main LOC | verdict | one-line reason | +|---|---|---|---| +| adapter-inbound-websocket | 12,954 | OVERBUILT | 문서상 기능은 `stomp/` 8클래스(479줄)뿐. 나머지 약 9.7k줄은 leaf 자체 `@Configuration`에서도 닿지 않고, 두 composition root 어디에도 조립 안 됨 | +| adapter-inbound-grpc | 623 | HEALTHY | 9파일, config 1, runner 1. 다른 곳에 gRPC 스택이 하나 더 있다는 것만 문제(lead) | +| app-bootstrap | 6,366 | NEEDS_WORK | 활성화 규칙 6곳 이상에 흩어지고 기본값이 이미 다름; validator 19개가 5패키지·3 lifecycle; scan 제외 regex가 약 12개 leaf 내부 패키지를 앎 | +| sample-portfolio | 9,496 | NEEDS_WORK | WorkLog slice는 복사할 만함. 그러나 main의 48%가 poster-image; bootstrap 코드 약 540줄 복사; bootstrap이 결함으로 규정한 scan 방식 사용; yml 1/3 미사용 | +| composition-fileserver-platform | 868 | HEALTHY | root 1개 + `@Import`로 얇게 조립. 오래된 주석, 쓰지 않는 registry edge 1개 | + +#### 그룹 질문에 대한 답 +- **활성화 지도가 한눈에 읽히는가:** 아니다. 스위치↔capability 대응이 `MasterSwitch`(shared-contract, 9개), auto-config 9개의 `@ConditionalOnProperty` 문자열, `CapabilityDependencyValidator`·`DataSourceRequirement`·`RedisActivationValidator`·`SecretSourceValidator`·`OutboxRelayBrokerRequirementValidator`, `AdapterActivationEndpoint`, `build.gradle` `dependencyPolicy`, `docs/capability-status.md`에 나뉘고 이미 서로 어긋남(#2, #5). bean 등록 경로도 3가지(component scan, `AutoConfiguration.imports`, `spring.factories` EPP 6개). +- **sample이 복사할 만한가:** WorkLog는 그렇다(얇은 컨트롤러, 순수 Java use case + `@Bean` 명시 wiring, 직접 만든 fake 테스트). 모듈 전체로는 아니다(#7–#11). +- **capability 하나 켜려면:** Outbox+relay = 스위치 5개(`APP_OUTBOX_ENABLED`, `APP_OUTBOX_RELAY_ENABLED`, `APP_PERSISTENCE_JPA_ENABLED`, `APP_MESSAGING_ENABLED`, `APP_MESSAGING_BROKER`) + broker starter 의존성 + `APP_MESSAGING_KAFKA_BROKERS`, yml 3개와 build.gradle, 검증 클래스 4개. Redis cache = `redis.yml`·`capabilities.yml` 스위치 1개씩, 연결 env(`APP_REDIS_MODE/NODES`)는 어느 yml에도 없음, prod HMAC secret, 검증 클래스 2개. 전체 표면: bootstrap yml 19개(1,388줄, 52% 주석), env placeholder 273개, `.env.example` 401줄. + +#### Findings (highest leverage first) + +1. **[Required][reachability] websocket leaf가 안 쓰는 플랫폼 라이브러리를 보유** — `src/adapter/inbound/websocket/src/main/java/.../websocket/` + - Evidence: 7개 Spring config에서 닿는 코드는 48클래스 3,230줄; 닿지 않음: `advanced/` 4,041, `outbound` 689, `moduleboundary` 519, `handler` 467, `evidence` 407, `release` 311. `release/WebSocketStableReleaseGate`, `advanced/release/AdvancedPromotionGate`는 테스트만 호출; `moduleboundary/WebSocketStableModule`(394줄 enum)은 leaf 안의 두 번째 모듈 registry; `WebSocketAdvancedCapability.java:71` "Read by the startup validator"는 거짓(호출처 `ResumeTokenTest:184-186`뿐); STOMP 스택 2개(`stomp/WebSocketConfig` vs `advanced/stomp/**` 1,491줄), `StompBrokerExclusivity`는 둘의 충돌 방지용으로만 존재. + - Remedy: `stomp/` + safety config만 남기고 gate·moduleboundary·evidence는 test source로; 플랫폼 라이브러리는 `optional-platforms` 같은 별도 build로 빼거나 삭제; STOMP 스택 하나로. Size L · 기본 빌드에서 약 9–12k줄 제거. + - 가정/반론: 향후 채택용 vendored 라이브러리 → 그렇다면 `messaging:*`처럼 별도 family로, inbound adapter leaf 안에 둘 이유 없음. + +2. **[Required][duplication] capability 의존 규칙 6곳, 기본값 이미 갈라짐** (1차 L-6보다 넓음) + - Evidence: `ca-skeleton.outbox.relay-enabled` 없을 때 해석 셋: `CapabilityDependencyValidator.java:54,196-198` false, `OutboxConfig.java:66` `matchIfMissing = true`, `OutboxRelayBrokerRequirementValidator.java:50` `Boolean.TRUE` → ORBRV는 "키 없을 때"만 실패, 명시적 true면 CDV가 EPP 단계에서 먼저 거부. `capabilities.idempotency.provider` 기본값이 CDV:89·DSR:37·RAV:69는 "disabled", `SecretSourceValidator.java:137`은 "jdbc". Redis role 표 두 벌(`RedisActivationValidator.java:27-33` 맵 vs `SecretSourceValidator` prefix 분기); `SecretSourceValidator.java:31` `REDIS_ENABLED_PROPERTY`는 `MasterSwitch.REDIS` 중복. 같은 키 문자열 반복: `idempotency.provider` 9회/6파일, `relay-enabled` 7회/3파일, `multi-instance-enabled` 5회/3파일. + - Remedy: 규칙을 표 하나로(`RuntimeNumericBoundsValidator.BOUNDS` 모양): 키·기본값·필요한 것(JPA/MESSAGING/REDIS)·prod secret. CDV, DSR, Redis 모순 검사, 필요 secret 목록, endpoint를 표에서 파생. Size M · 약 350줄, 클래스 4개 제거. + - 가정/반론: 표가 작은 DSL로 커질 수 있음 / 소비처 이미 5곳, 기본값 drift 실재. + +3. **[Required][SRP|duplication] startup validator 19개가 3 lifecycle·5 패키지에 흩어짐** + - Evidence: EPP 3, `InitializingBean` 4, `SmartInitializingSingleton` 12; 12개는 `Environment`만 받음; 합계 약 1.5k줄(main의 24%). OSIV 검사 두 벌: `OpenInViewSafetyValidator.java:26-27`(모든 profile 거부) vs `JpaDangerousConfigurationGuard.java:51`(local-convenience 허용) — 앞의 것이 무조건 등록(`RuntimeSafetyConfig.java:28-30`)이라 뒤의 예외는 죽은 코드. ddl-auto 검사 두 벌(`JpaSchemaSafetyValidator`, `JpaDangerousConfigurationGuard:62-65`). `isProdActive()` 5곳 복사(`JpaSchemaSafetyValidator:51`, `FlywayProdSafetyValidator:55`, `PersistenceVendorProdSafetyValidator:81`, `PostgreSqlTransportSecurityValidator:86`, `SecretSourceValidator:161`). `runtime/startup/`(CLAUDE.md상 vocabulary 패키지)에 guard 3개. CDV는 EPP와 `CapabilityDependencyStartupCheck`에서 두 번 실행. + - Remedy: `StartupRule { List violations(Environment) }` 목록 + EPP runner 하나; bean 필요한 검사 3개만 bean; OSIV/DDL 하나로. Size M · 약 500줄, 클래스 약 10개 제거. + +4. **[Required][structure] root가 넓게 scan한 뒤 다른 leaf 패키지를 blacklist** — `app-bootstrap/.../CaSkeletonApplication.java:42,58,96-117` + - Evidence: `AUTO_CONFIGURED_PACKAGES`에 약 12개 leaf 내부 패키지를 가리키는 alternative 18개; `bootstrap.notification`(:98)은 존재하지 않는 패키지. scan이 실제로 잡는 stereotype 38개(web 27, bootstrap 8), regex가 빼는 것 70개. `@ConfigurationPropertiesScan`에 별도 whitelist 11개. + - Remedy: scan을 `dev.caskeleton.bootstrap`(autoconfigure 제외)로 좁히고, `adapter:inbound:web`은 persistence/httpclient처럼 자기 `AutoConfiguration.imports` publish. Size M · regex, whitelist, parity 테스트, "새 패키지를 root에도 등록" 규칙 제거. + - 반론: web advice·controller 순서를 auto-config로 옮길 때 추가 작업. + +5. **[Required][structure] Fileserver는 build에서 빠졌는데 스위치·설정은 남음** + - Evidence: `app-bootstrap/build.gradle:376-390` `dependencyPolicy`가 4개 모듈을 runtime에서 제외; 그런데 `application.yml:244`가 `config/fileserver.yml`(116줄) import; `MasterSwitch.FILESERVER*`가 endpoint에 보고되고 `DataSourceRequirement.java:54-59`는 이 capability 때문에 pool을 열며, `CaSkeletonApplication` regex에 3개 항목; `docs/capability-status.md:27-28` WIRED=yes. 결과(코드상 추론, 미실행): shipped jar에서 `APP_FILESERVER_PLATFORM_ENABLED=true` → fileserver bean 없음, 에러 없음, DB pool만 열림. + - Remedy: fileserver 설정을 composition 모듈 채택 문서/테스트 resource로; "스위치 켜졌는데 capability auto-config 클래스가 없으면 실패" 검사(`ClassUtils.isPresent`). Size S–M · root에서 약 130줄. + +6. **[Required][duplication] idempotency 설정이 binder 3개·yml 2개, 서로 불일치** + - Evidence: `IdempotencySettings`(`ca-skeleton.idempotency`, `config/idempotency.yml:9`), `IdempotencyProviderSettings`(provider만), cache-redis `RedisCapabilitySettings`. `APP_IDEMPOTENCY_TTL`이 두 키에 바인딩(`capabilities.yml:34`). `PostgreSqlIdempotencyProviderConfig.java:36,39`는 lease 2분·codec `json.v1` 하드코딩, `capabilities.yml:33,38`은 30s·`json-v2` 광고(PostgreSQL provider는 안 읽음). 같은 패턴: `APP_RATE_LIMIT_DEFAULT_POLICY_ID`가 `ratelimit.yml:10`·`capabilities.yml:55` 둘 다. + - Remedy: `ca-skeleton.capabilities.idempotency` settings record 하나를 모든 provider가 사용; `config/idempotency.yml`·하드코딩 상수 삭제. Size M. + +7. **[Required][duplication] sample이 bootstrap 인프라 약 540줄 복사, 이미 갈라짐** — `sample-portfolio/.../bootstrap/{tracing,idempotency,settings,logging,metrics,context,management}` (difflib 유사도 0.22–0.89; `SampleIdempotencyConfig` Javadoc "Sample-local copy"; `SampleTracingSampleRateResolver`의 `"staging" -> 0.10` 자체 profile 어휘 — bootstrap CLAUDE.md는 `RuntimeEnvironment` 밖 profile 판정 금지; 원인: app-bootstrap이 라이브러리가 아니라 두 번째 root는 복사할 수밖에 없음). Remedy: root 무관 부분을 두 root가 쓰는 library leaf로(`composition:fileserver-platform` 모양, registry edge 추가). Size M · 약 500줄. + +8. **[Required][structure] sample root가 bootstrap이 결함이라 적은 scan 방식을 가르침** — `SamplePortfolioApplication.java` (`@ComponentScan("dev.caskeleton")` + `@ConfigurationPropertiesScan("dev.caskeleton")`, 타입 3개만 제외; `CaSkeletonApplication` Javadoc은 이를 "꺼진 capability의 settings가 바인딩되는 원인"으로 설명). Remedy: sample 패키지만 scan, leaf는 auto-config(#4 이후). Size S–M. + +9. **[Required][reachability] sample `application.yml` 327줄 중 109줄을 읽는 코드 없음** — `ca-skeleton.capabilities.cache`(30), `app.cache.redis`(25), `app.outbound.http`(20), `ca-skeleton.logging`(17), `app.notification`(5), `app.messaging`(4), `ca-skeleton.bootstrap`(2) (1차의 rate-limit 6줄 제외; sample classpath에 binder 없음). Remedy: 삭제. Size S. + +10. **[Consider][structure] sample 대표 예제가 poster-image에 묻힘** — poster-image 약 4.6k줄 vs WorkLog 2.2k; `application/`에 종류별(`command/`, `query/`, `event/`, `port/`, `exception/`)과 기능별(`poster/`, `posterimage/`, `worklog/`) 패키지 혼재; 상태 머신 `PosterImageUploadIntent`(333줄, 필드 24)가 application 계층(WorkLog는 domain); `PublishPosterImageUseCase` 생성자 14개; legacy API 모드 약 420줄; `WorkLogSortField`(domain)가 HTTP 이름(`fromRequest`)과 persistence property 이름을 둘 다 앎; `sample-portfolio/CLAUDE.md:15-21`은 WorkLog만, 경로 틀림. Remedy: 기능별 패키지, poster-image는 별도 sample 모듈/objectstorage 검증 consumer로 이동, legacy 모드 삭제. Size L. 반론: object-storage publication·idempotency V2를 끝까지 쓰는 유일한 consumer → 삭제가 아니라 이동. + +11. **[Consider][duplication] sample 컨트롤러·테스트 반복** — `toId()` 4벌(`WorkLogController:239`, `PosterController:161`, `LegacyPosterImageController:49`, `PosterImagePublicationController:110`); sort 파싱 2벌(`WorkLogController:99-113`, `PosterController:91-105`); `WorkLogController.requireIfMatch:209`가 update 전에 get use case를 추가 호출(컨트롤러가 use case 2개 조율, 읽기-비교가 트랜잭션 밖); 테스트 9개 파일이 `TransactionPort` fake를 각자 작성, testFixtures에 공용 fake 없음. Remedy: `UpdateWorkLogCommand`에 `expectedVersion`, id/sort helper 하나, `InlineTransactionPort`를 testFixtures로. Size S. + +12. **[Consider][over-abstraction] JPA 정책 클래스** — `JpaPlatformAutoConfiguration`은 auto-config가 아니라 factory·report·16개 항목 정적 catalog 겸용; `jpaDataSourceProfileValidator` bean(`JpaPlatformRuntimeAutoConfiguration:59-64`) 주입처 없음(`PersistenceJpaRootAutoConfiguration:43`이 따로 `new`); `app.jpa-platform.addons-enabled`(:30) 테스트만 설정. Remedy: 개명/inline, 미사용 bean·플래그 삭제. Size S. + +13. **[Consider][over-abstraction] 역할 없는 startup 예외 subclass 4개** — `runtime/startup/{MigrationFailed,ProfileMismatch,RequiredAdapterDisabled,StartupValidation}Exception` (각자 `StartupErrorCode`를 부모에 넘기기만; 타입 구분 55곳 모두 테스트). Remedy: 구체 클래스 하나 + `errorCode()` 단언. Size S. + +14. **[Consider][structure] 스위치 prefix·"capability" 뜻 제각각** — prefix 셋: `ca-skeleton.*`(jpa, mongo, notification, outbox, tracing, grpc), `app.*`(messaging, redis, fileserver, httpclient, websocket, rate-limit), `backend.graphql`; "capability" 4가지 뜻(`@UseCaseCapability`, master switch, `capabilities.*` provider selector, `JpaCapability`/`WebSocketAdvancedCapability`); outbox·tracing·lock 스위치는 `MasterSwitch`에 없어 endpoint에 미보고. Remedy: `MasterSwitch.legacyProperties()` 이관 장치로 prefix 통일. Size M. 반론: property 이름 변경은 fork breaking. + +15. **[Consider][structure] bootstrap `:test`에 저장소 governance 테스트 약 7.6k줄** — `src/test/.../contract/` (47파일 중 33개가 docs/registry/yml을 직접 읽음). Remedy: `architectureTest`처럼 별도 lane. Size M. + +16. **[Nit][readability]** 이력/리뷰 ID 주석: bootstrap 105줄(주석 비율 25%), websocket 35%; `CapabilityDependencyEnvironmentValidator.java` 30줄 Javadoc이 3줄짜리 클래스 설명; hikari `connection-timeout` 주석 "It shipped as 5s…"; config yml 15개가 같은 3줄 헤더 반복; `OpenInViewSafetyValidator` 예외 메시지에 "D2"; `FileserverPlatformAutoConfiguration`의 "identifier generator" 설명 틀림(identifier 의존성 없음 → registry edge `adapter-outbound-identifier`도 미사용). + +17. **[Nit]** `TracingSettings.sampleRate`가 String이라 3곳에서 파싱(클래스 5개, 377줄; `TracingSampleRateResolver` inline FQN) → 범위 검증 붙은 `Double`. + +#### Cross-module leads (not investigated) +- gRPC 서버 스택 2개: `adapter/inbound/grpc`(`GrpcServerRunner`, `GrpcStatusMapper`) vs `grpc/grpc-server` + `grpc-spring-boot-starter`(`GrpcErrorMapper`), 둘 다 조립 안 됨. +- inline `TransactionPort` fake가 저장소 전체 테스트 19곳 이상 → application-core testFixtures로 하나. +- 복사용 예제 `CreateWorkLogUseCase`가 `LegacyOutboxAppendPort` 사용(MSG-015 cutover 관련). +- `docs/capability-status.md:27-28` WIRED=yes vs `dependencyPolicy` 모순; `MasterSwitch`(shared-contract)가 shipped build에 없는 capability 나열. +- `DefaultUploadApplicationService` 생성자 14개(application-fileserver), `FileserverUploadServiceConfiguration.java:74`에서 조립. + +#### Coverage note +깊게: bootstrap `activation/`, `autoconfigure/{idempotency,jpa,outbox,redis}`, `CaSkeletonApplication`, validator 목록·핵심 본문, yml; sample entry, `bootstrap/*`, 컨트롤러, 대표 use case·테스트, yml; gRPC main 전체. websocket 도달 가능성은 단순 이름 참조 그래프(Spring config root, reflection 미반영). + +### S7 — Vendored platforms (`messaging:*`, `grpc:*`, `grpc-advanced:*`) + +#### Per-family / per-leaf maintainability verdict +| leaf or family | main LOC | verdict | one-line reason | +|---|---|---|---| +| messaging-core-api | 3,948 | NEEDS_WORK | 예외 서브클래스 12개 미사용, `MessageHandler` 연결 없음, boolean 12개 capability | +| messaging-schema-api / schema-json | 654 / 226 | HEALTHY | 조립되는 코덱은 json 하나; schema-api는 core-api와 합칠 후보 | +| schema-avro / schema-protobuf / cloudevents / claim-check | 1,190 | OVERBUILT | 쓰는 곳 없음(100% 도달 불가); starter가 cloudevents·claim-check edge를 쓰지 않으면서 달고 있음 | +| policy / transport-spi / runtime-core / security / observability | 5,140 | HEALTHY | 발행 경로, 도달 불가 0–38% | +| messaging-kafka | 3,454 | NEEDS_WORK | 71% 도달 불가(consume 쪽 전체), 645줄 registrar | +| rabbit + starter-rabbit | 2,625 | OVERBUILT | 기동 시 선택하면 거부; 운영 코드에 `RabbitChannelPublisher` 구현 없음 | +| pulsar / nats / kafka-share / stream-bridge | 2,082 | OVERBUILT | vendor SDK 의존성 없음, 쓰는 곳 없음 | +| reliability-api / outbox-jdbc / inbox-jdbc | 3,599 | NEEDS_WORK | leaf 하나가 서로 다른 일 4가지; 호출자 없는 port 메서드 | +| admin-api + admin-runtime | 2,858 | NEEDS_WORK | 진입점 없음, leaf 2개로 나눈 이유 없음 | +| messaging-spring-boot-starter | 3,328 | NEEDS_WORK | 550줄 god config, 20필드 union settings, 쓰는 곳 없는 facade 3개 | +| starter-kafka / testkit | 197 / 1,145 | HEALTHY | capability artifact / 테스트 지원 | +| grpc-core-api | 1,897 | NEEDS_WORK | registry 내용을 코드로 재기술(`GrpcStableModuleCatalog`) | +| grpc policy+server+client+discovery+admin | 8,197 | NEEDS_WORK | 의존성 경계 1개를 leaf 5개로 쪼갬; io.grpc import는 운영 파일 5개뿐 | +| grpc-proto-contract + codegen | 1,297 | OVERBUILT | protoc/Buf를 regex로 재구현 | +| grpc-observability | 354 | NEEDS_WORK | 쓰는 곳 0 | +| grpc-operation-ledger-jpa / starter / testkit | 336 / 494 / 2,323 | HEALTHY | JPA·Spring·netty라는 실제 의존성 경계 | +| advanced bootstrap/edition/streaming/resilience/diagnostics | 3,021 | OVERBUILT | stdlib뿐인 leaf 5개, 런타임 진입점 0 | +| grpc-advanced-compat | 962 | NEEDS_WORK | reactor·spring-integration 실제 의존성 있음, gate 클래스 섞임 | + +도달성(starter/adapter/app-bootstrap main에서 클래스 이름 참조 전이 폐포, 과대 추정 → 도달 불가 수치는 하한): messaging testkit 제외 **≥12.7k/29.3k LOC(43%)**, grpc starter 기준 **12.4k/16.6k(75%)** 도달 불가. + +#### Findings (highest leverage first) + +1. **[Required][granularity|reachability] 선택 불가하거나 쓰는 곳 없는 messaging leaf 10개가 기본 빌드에** — `messaging-pulsar-experimental`, `-nats-experimental`, `-kafka-share-experimental`, `-spring-cloud-stream-bridge`(build.gradle에 SCSt 의존성 없음), `-rabbit` + `-starter-rabbit`(`MessagingProviderSelection.java:69` 기동 거부), `-schema-avro`, `-schema-protobuf`, `-cloudevents`, `-claim-check` + - Evidence: 운영 5,897 + 테스트 4,016 LOC; pulsar/nats/kafka-share/stream-bridge는 vendor 의존성 없이 자체 `*SendOperation` seam만(`PulsarMessagingTransport.java:264`); starter가 cloudevents·claim-check를 `implementation`으로 달지만 main 참조 0(`messaging-spring-boot-starter/build.gradle:36,43`); `MessagingSettings.Experimental`/`Bridge`(`:150,:212`)는 바인딩만. + - Remedy: grpc처럼 `optional-platforms` build로 이동; experimental 4개와 Debezium은 삭제 권고; starter edge 2개·설정 클래스 2개 삭제. Size M · 기본 빌드 leaf 10개, 약 5.9k LOC. + - Assumption/Counter: 기본 adopter는 Kafka 발행만 / `docs/messaging/support-matrix.md` 공개 약속 — 이동은 삭제가 아님. + +2. **[Required][structure|over-abstraction] consume 계약 3개, 조립 0** — `messaging-core-api/.../delivery/MessageHandler.java:15`(참조 0), `DefaultDeliveryProcessor.java:40`(`Function,HandleResult>`), `reliability-api/.../IdempotentMessageHandler.java:21` + - Evidence: `MessagingTransport.register()` main 호출 0; 자동 조립 transport는 발행 전용 생성자(`KafkaMessagingTransport.java:80-91` → `KAFKA_CONSUMER_NOT_CONFIGURED`); `KafkaConsumerRegistrar`(645), `KafkaBatchConsumerRegistrar`, delivery/retry mapper 합쳐 약 2.4k LOC 도달 불가. + - Remedy: `MessageHandler` 하나로; `DefaultDeliveryProcessor`가 codec registry로 decode; starter-kafka가 `consumerFactory`로 registrar 조립(`@ConditionalOnBean(MessageHandler.class)`). consume을 범위에서 빼면 handler 3종·registrar를 #1처럼 이동. Size M. + - Counter: README(`messaging-spring-boot-starter/README.md:34`) "직접 조립" — 예제 없고 계약 3개라 따라갈 수 없음. + +3. **[Required][granularity] grpc 18 leaf → 9 leaf** — io.grpc import 운영 파일 5개뿐(`grpc-policy` 4, `GrpcServerInterceptorChain`) + - Evidence: `grpc-client`는 `api "io.grpc:grpc-api"`(`build.gradle:12`) 선언하나 io.grpc import 0; `grpc-codegen`의 proto-contract 의존(`:13`), `grpc-advanced-edition`의 project 의존 3개(`:9-11`)는 미사용. 실제 의존성 경계는 core-api(0), ledger-jpa(JPA), observability(Micrometer), compat(reactor/SI), starter, testkit. 설계서 §2(`2026-08-30-grpc-platform-adaptation-design.md:78-81`)도 advanced는 "합쳐도 불변 조건 유지". + - Remedy: policy+server+client+discovery+admin → `grpc-runtime`; proto-contract+codegen → `grpc-contract`; advanced 5개 → `grpc-advanced`, compat 유지. "grpc:* → grpc-advanced:* 금지"는 prefix 두 개로 표현. Size L(이동만) · leaf 9개, phantom edge 5개. + - Counter: 원본 31-모듈 계획과의 1:1 대응 — Gradle이 강제하는 규칙은 없음. + +4. **[Required][over-abstraction] governance를 운영 코드로 구현** — grpc/advanced main의 gate/guard/matrix/promotion/catalog 약 1,690줄 + - Evidence: 인자 없이 상수를 반환하는 메서드 11개 — `GrpcStableBuildInvariant.java:26`, `GrpcKotlinCompatibilityGate.java:67`, `GrpcWebCompatibilityGate.java:54`, `GrpcServletStartupValidator.java:49`, `GrpcEdition2026Guard.java:18,46`, `GrpcEdition2024Gate.java:50,59`, `GrpcResolverSafetyPolicy.java:77,82`, `GrpcXdsStartupGuard.java:98`. `GrpcStableModuleCatalog.java`는 leaf 목록을 core-api 안에 재기술(registry SSOT 규칙 위반). `GrpcRawApiImportRule`/`GrpcApplicationBoundaryRules`(200줄)는 문자열로 ArchUnit 흉내, 자기 테스트에서만. + - Remedy: 상수 gate, catalog, invariant, `GrpcAdvancedInfrastructureTestkit` 삭제; import rule은 ArchUnit으로. Size M · 약 700–1,000 LOC. 1차 N-9(`validateAdvancedIsolation`)와 겹침. + - Counter: 테스트가 "결정을 붙든다" — `return false`를 검증하는 테스트는 오타만 막음. + +5. **[Required][SRP] `messaging-outbox-jdbc-postgresql`이 서로 다른 일 4가지** — vendor 중립 relay 7클래스(약 877), PostgreSQL repository(721), Debezium 4개(약 351, SDK 없음, 참조 0), `JdbcAdminOperationJournal`(326, 오류 메시지 문자열에서만 언급). leaf 19클래스 중 Spring JDBC import는 3개(`Jdbc*`); inbox도 6개 중 5개가 stdlib. + - Remedy: `messaging-reliability`(reliability-api + relay/inbox 로직, stdlib) + `messaging-reliability-jdbc-postgresql`(Jdbc 3종), Debezium 삭제. Size M · leaf 3→2, 약 350 LOC. + +6. **[Required][duplication|pattern] `PublishResult` 7-인자 생성 11개 파일 28회** — 실제 모양은 rejected/ambiguous/confirmed 3가지. `PublishEvidence.ambiguous()`가 있는데 7곳이 `new PublishEvidence(true, MAY_HAVE_BEEN_TRANSMITTED, false, NONE)` 직접 사용(`PublishResults.java:43-67`); `rejectedLocally` 4곳 복사(`KafkaMessagingTransport.java:200`, `RabbitMessagingTransport.java:271`, `PulsarMessagingTransport.java:246`, `NatsJetStreamTransport.java:263`); `PulsarPreSendRejection`·`NatsPreSendRejection` Javadoc만 다름. Remedy: `PublishResult.rejected/ambiguous/confirmed` 정적 factory, `PreSendRejection`은 transport-spi 하나. Size S–M · 약 200 LOC. + +7. **[Required][duplication] envelope ↔ canonical header 변환 3번 작성** — `KafkaHeaderMapper.java:32-100` + `KafkaDeliveryMapper.java:66-125`, `RabbitHeaderMapper.java:31` + `RabbitDeliveryMapper.java:65-94`, `DebeziumOutboxEventRouter.java:35`(ReservedHeaders 참조 31개). Remedy: core-api `CanonicalEnvelopeHeaders`에 `write(envelope, BiConsumer)`·`read(Function)`; broker mapper는 연결 코드만, `RESERVED_HEADER_FORGED` 규칙 한 곳. Size M · 약 300 LOC. + +8. **[Consider][over-abstraction] outbox port·repository 죽은 표면** — `OutboxRepository.java:36` `leaseBatch`(deprecated, main 0), 4-인자 `claimBatch`·3-인자 `markAmbiguous` 오버로드(main 0), `JdbcOutboxRepository.java:426-455` `*Unfenced` 4개(main 0), `:600-721` 손 JSON 직렬화 약 115줄. Remedy: 메서드 7개 삭제, JSON은 Jackson(starter 런타임에 있음) 또는 `jsonb_each_text`. Size M · 약 250 LOC(purge 오버로드는 1차 M-6). + +9. **[Consider][SRP] starter 조립 구조** — `MessagingCoreAutoConfiguration.java` 550줄·`@Bean` 28·inline FQN 46줄; `BrokerSettings.java:42`는 Kafka·Rabbit 20필드 union record인데 broker 중립 core starter에; Blocking/Reactive/Batch facade(약 566 LOC)는 외부 사용 0인데 Reactive 때문에 `api 'io.projectreactor:reactor-core'`(`build.gradle:54`)가 모든 앱에 노출. Remedy: config/validation, publish pipeline, observability 세 configuration; broker별 필드는 broker starter가 `Binder`로; facade 삭제 또는 reactor `compileOnly`. Size M. + +10. **[Consider][over-abstraction] 미사용 API 타입(1차 M-9 목록 외)** — `MessagingException` 서브클래스 23개 중 12개 main 참조 0(Authentication, BrokerUnavailable, Consumer, DeadLetter, HandlerTimeout, HeaderRejected, PublishAmbiguous, PublishRejected, Redrive, RetryExhausted, Routing, SettlementUnknown; 각 약 50줄, (category, retryable)만 다름; 서브클래스별 catch는 1곳); `MessageHandler`, `KafkaTopologyInspector`, `RabbitRequestReply`, `ReliableMessagePublisher`, `InboxRecord` 구현·참조 0. Remedy: 삭제. Size M · 약 750 LOC. Counter: public surface breaking — 구현·사용처 없음. + +11. **[Consider][pattern] `MessagingCapabilities` 위치 boolean 12개** — `KafkaMessagingTransport.java:62-63` `new MessagingCapabilities(true, true, …, true)`, 생성 11곳, main에서 읽는 flag는 12개 중 3개. Remedy: `EnumSet`, 안 읽는 flag 삭제. Size S. + +12. **[Consider][granularity] messaging API leaf 병합** — core-api + schema-api → 1개; admin-api + admin-runtime → 1개. #1·#5와 합치면 기본 빌드 messaging leaf 27 → 14. transport-spi·runtime-core는 bridge 격리 규칙 때문에 유지. Size M. + +13. **[Consider][reinvention] `GrpcProtoContractValidator`(447줄 regex .proto 파서)와 `grpc-codegen`(Buf lint/breaking 재구현, Java import regex)** — 근거 "Buf CLI가 없다"(`grpc-codegen/build.gradle:8-9`); protoc은 Maven artifact, Buf도 Gradle로 받을 수 있음; 실제 stub 생성 0건. Remedy: `com.google.protobuf` 플러그인 + buf를 CI에서, 두 leaf 삭제. Size L · 약 1.1k LOC. 반론: 설계 결정 D5/D6. + +14. **[Consider][structure] 패키지·leaf 이름 불일치, 용어 혼재** — `dev.caskeleton.grpc.resilience`/`streaming`은 `grpc-policy`의 패키지인데 `grpc-advanced-resilience`/`-streaming`은 leaf 이름; `discovery`는 반대; `grpc-policy`에 interceptor·writer·rotation manager 같은 런타임 코드; 지원 등급 이름 4개(`CapabilityTier{M1..M3}`, `CompatibilityMatrix.Tier`, `GrpcCapabilityGrade`, `GrpcEvidenceGrade`). Remedy: #3으로 대부분 해소, 용어 하나로. Size S. + +15. **[Consider][readability]** messaging main 주석 30%(9,234/30,446), grpc 17%; "used to / no longer" 78줄(`KafkaConsumerRegistrar` 6줄), 리뷰 ID `MSG-*` 9곳(`MessagingCoreAutoConfiguration.java:370,442,480` 등); inline FQN 190줄(`KafkaConsumerRegistrar` 31, `DefaultBatchMessagePublisher` 20). Remedy: 이력은 git/ADR, OpenRewrite `ShortenFullyQualifiedTypeReferences`. Size M(기계적). + +16. **[Nit][structure]** `dev.caskeleton.messaging.autoconfigure` 패키지가 leaf 3개에 걸침(package-private `StartupProfileValidation` 때문); registry의 starter-kafka `allowed_dependencies` 10개인데 build.gradle은 2개만 사용; `KafkaConsumerRegistrar.dispatch` 75줄(`:264`). + +#### Cross-module leads (not investigated) +- outbox relay 3개: `application-core/.../PublishPendingOutboxEventsUseCase`, `.../outbox/v2/PublishNextOutboxDeliveryUseCase`, messaging `OutboxRelay`. +- 멱등성 저장소 3개: application idempotency, `grpc-operation-ledger-jpa`, `messaging-inbox-jdbc`. +- Kafka producer 경로 2개: `adapter/outbound/messaging-kafka` `LegacyKafkaMessagingRootAutoConfiguration`(R0) vs `KafkaMessagingTransport`. +- lease/claimBatch: `JpaRecipientLeaseStore.claimBatch` vs `OutboxRepository.claimBatch`. +- messaging 기본 off 처리 두 곳: `DisabledMessagingSentinelAutoConfiguration`(app-bootstrap) vs starter master switch. + +#### Coverage note +leaf 45개 전부 LOC/파일, 의존성 선언, import, 도달성 계산. 자세히: starter 3종·조립 클래스, transport 4종 publish/classify, outbox/inbox, core-api publish·error·capabilities, grpc starter·core-api·advanced gate, 설계서 §2. rabbit/kafka consumer 내부, grpc-policy streaming 개별 클래스는 이름·크기만. + diff --git a/docs/reviews/2026-09-24-src-module-code-review.md b/docs/reviews/2026-09-24-src-module-code-review.md new file mode 100644 index 00000000..2bec08e7 --- /dev/null +++ b/docs/reviews/2026-09-24-src-module-code-review.md @@ -0,0 +1,1130 @@ +# `src/` 모듈별 코드 리뷰 — 2026-09-24 + +## 개요 + +| 항목 | 내용 | +|---|---| +| 대상 | `src/` 아래 모든 등록 leaf(`src/config/architecture/modules.json`) + `src/build-logic`, `src/build-tools`, root Gradle, `.github/workflows` | +| 기준 | 현재 작업 트리 (`main` @ `208077fd`). `944a1e34`(2026-09-17) 이후 변경분을 중점 검토 | +| 규모 | main 코드 약 32만 줄 | +| 방법 | 기능 단위 15개 그룹으로 나눠 리뷰 에이전트 15개를 병렬 실행(읽기 전용, Gradle 미실행). 이후 Critical 15건은 오케스트레이터가 코드에서 직접 재확인 | +| 축 | correctness, readability/simplicity, architecture(HARD-STOP 1-5), security, performance, tests, 문서 drift | +| 이전 리뷰 | `docs/reviews/2026-09-18-techlead-review/*`, `2026-09-19-review-remediation-master.md` 기준으로 closed 항목의 회귀 여부를 함께 판정 | + +## 판정 + +**Verdict: BLOCKED** + +- Critical 15건, Required 76건(중복 1건 제외), Consider 약 55건. +- 게이트 결과: `./gradlew architectureCheck --console=plain` → **BUILD SUCCESSFUL** (1m 43s). 의존 방향·application-core 순수성·runtime membership·Clean Architecture 의존 검사 전부 통과. +- 모듈 경계(HARD-STOP 1, 2, 3, 5)는 모든 그룹에서 위반 0건. 막히는 이유는 경계가 아니라 **동작 결함, 보안 설정의 실제 미적용, 최근 리팩터 커밋의 회귀**다. +- HARD-STOP 4 위반 1건: web 어댑터가 저장소 포트·트랜잭션·객체 인가를 직접 수행(I-1 = A-4). + +## 그룹별 요약 + +| 그룹 | 대상 leaf | 판정 | Critical | Required | +|---|---|---|---|---| +| A Core | domain-core, shared-contract, application-core, support, identifier | NEEDS_FIX | 0 | 6 (A-4는 I-1과 같은 결함) | +| B Notification | application-notification, adapter-outbound-notification | NEEDS_FIX | 2 | 5 | +| C File server | application-fileserver, persistence-fileserver, outbound fileserver, web-fileserver, composition | BLOCKED | 1 | 9 | +| D Object storage | application-objectstorage, adapter-outbound-objectstorage | NEEDS_FIX | 0 | 4 | +| E JPA | adapter-outbound-persistence-jpa | BLOCKED | 2 | 4 | +| F Mongo | adapter-outbound-persistence-mongo | NEEDS_FIX | 0 | 6 | +| G Redis | redis-runtime, redis-sdk, cache-redis | NEEDS_FIX | 1 | 5 | +| H HTTP client / messaging bridge | httpclient, outbound messaging, messaging-kafka | NEEDS_FIX | 1 | 5 | +| I Web | adapter-inbound-web | BLOCKED | 1 | 6 | +| J GraphQL | adapter-inbound-graphql | NEEDS_FIX | 1 | 5 | +| K Realtime / gRPC adapter | adapter-inbound-websocket, adapter-inbound-grpc | NEEDS_FIX | 0 | 7 | +| L Bootstrap / sample | app-bootstrap, sample-portfolio | NEEDS_FIX | 1 | 3 | +| M Messaging platform | `messaging:*` | NEEDS_FIX | 2 | 5 | +| N gRPC platform | `grpc:*`, `grpc-advanced:*` | NEEDS_FIX | 1 | 5 | +| O Build / CI | build-logic, build-tools, root Gradle, workflows | BLOCKED | 2 | 2 | + +## Critical 15건 (오케스트레이터 재확인 결과 포함) + +"코드 확인"은 인용된 줄을 직접 열어 주장과 일치함을 확인했다는 뜻이다. 실행으로 재현한 것은 없다. + +| # | 그룹 | 결함 | 위치 | 재확인 | +|---|---|---|---|---| +| 1 | O | root plugin `apply()`가 `../docker-compose..yml` 부재 시 예외 → Docker 빌드 컨텍스트(`src`)에서 `verifyDependencyLocks` 불가, release 이미지 빌드 차단 | `src/build-logic/.../bootstrap/DeveloperBootstrapPlugin.java:40-50` | 코드 확인 (`repositoryDirectory = projectDir.getParentFile()`, Dockerfile `WORKDIR /build/src`) | +| 2 | O | CI `redis-sdk` job의 `--tests '*…'` 따옴표가 word-split 후에도 남아 매칭 0 → 항상 실패, `release-gate`가 success 요구 | `.github/workflows/ci-quality-gates.yml:120`, `_reusable-gradle.yml:58-63` | 코드 확인 (CI 미실행) | +| 3 | E | 이미 적용된 Flyway 마이그레이션 3개를 제자리 수정 → 이전 버전이 적용된 DB 전부 checksum mismatch로 기동 실패 | `persistence-jpa/.../postgresql/V9__…sql`, `V13__…sql`, `jpa/outbox-storage/V1__…sql` | 코드 확인 (`git log --follow`: V9는 08-15 생성 후 9da00eb7에서 주석 변경, V13은 09-18 생성 후 09-23 변경, outbox V1은 07-31 생성 후 09-23 변경. `validate-on-migrate` 끄는 설정 없음). 템플릿에서 파생된 서비스 DB도 영향 | +| 4 | E | durable operation 재제출이 같은 트랜잭션에서 unique 위반 후 재조회 → PostgreSQL 25P02로 실패 | `persistence-jpa/.../operation/DurableOperationStoreAdapter.java:47-78` | 코드 확인 (PostgreSQL 실행 미검증) | +| 5 | L | outbox relay의 `@Scheduled`가 `@EnableScheduling` 없이는 동작 안 함. 앱 전체에서 유일한 `@EnableScheduling`이 `idempotency.provider=jdbc` 조건부 | `app-bootstrap/.../outbox/OutboxRelayScheduler.java:36`, `.../idempotency/IdempotencyConfig.java:17-19` | 코드 확인 (main의 `@EnableScheduling`은 sample·composition·IdempotencyConfig 3곳뿐) | +| 6 | H | canonical bridge의 `@ConditionalOnBean(EncodedMessagePublisher)`가 platform auto-config보다 먼저 평가됨(after 지정 없음) + 빈 `producer-id`가 조건을 통과해 `new ProducerId("")` 예외 | `adapter/outbound/messaging/.../MessagingBridgeRootAutoConfiguration.java:25,39-44` | 코드 확인 (컨텍스트 조립 테스트 미실행) | +| 7 | M | outbox relay·DLQ·retry-topic이 이미 인코딩된 `EncodedMessage`를 `publish()`로 넘김 → 재인코딩 실패 → 모든 row REJECTED/FAILED | `messaging-outbox-jdbc-postgresql/.../OutboxRelay.java:223-229`, `DefaultMessagePublisher.java:177` | 코드 확인 | +| 8 | M | 검증은 통과하는 Kafka TLS/SASL 설정이 producer에 적용되지 않음 (`KafkaSecurityConfigurer`는 bean으로만 생성, 호출 0) | `messaging-spring-boot-starter-kafka/.../KafkaMessagingAutoConfiguration.java:109-154` | 코드 확인 | +| 9 | B | 알림 recovery/replay 워커가 `@Modifying` 쿼리를 트랜잭션 없이 실행 → 매 pass 실패, 예외는 WARN으로 삼켜짐 | `adapter/outbound/notification/.../dispatch/LeaseRecoveryService.java:106` 외 3곳 | 코드 확인 (파일 내 `inWrite/TransactionPort/@Transactional` 0건. PG 실행 미검증) | +| 10 | B | SNS 인증서 URL 검증이 `*.amazonaws.com` 전체 허용(공격자 S3 버킷 통과), TopicArn allowlist·Timestamp 검사 없음, 콜백은 `permitAll` | `.../ses/SnsSignatureVerifier.java:99-109`, `SesProviderCallbackAssembler.java:19` | 코드 확인 (suffix `"amazonaws.com"`). SES callback 활성 시에만 노출(기본 off) | +| 11 | C | tus `Upload-Checksum`을 chunk가 아니라 파일 전체 누적 digest와, 그것도 offset 커밋 후에 비교 | `adapter/inbound/web-fileserver/.../tus/TusController.java:167-174` | 코드 확인 | +| 12 | I | durable-operation 조회/취소를 web 어댑터가 저장소 포트·트랜잭션·인가로 직접 수행(HARD-STOP 4), 운영 조립처 없음 | `adapter/inbound/web/.../operationasync/OperationQueryService.java:54-58,80` | 코드 확인 (`new OperationQueryService(` main 0건) | +| 13 | J | 인가 단계가 fragment를 visit budget 없이 재귀 전개 → 1.6KB 문서로 2^40 방문, cost 단계보다 먼저 실행 | `adapter/inbound/graphql/.../runtime/GraphQlDocumentAuthorizationHandler.java:109-137` | 코드 확인 (chain 순서 `selection → authorization → cost`) | +| 14 | G | SCRIPT lane 한도(기본 8)가 연결이 아니라 동시 lease 수 → Redis 정상이어도 동시 9번째 호출부터 거부, rate-limit fail-closed로 전면 429/503 | `redis-runtime/.../RedisRuntimeOwner.java:134-140`, `RedisSdkSettings.java:687` | 코드 확인. closed H8의 회귀 | +| 15 | N | gRPC idempotency가 FAILED_TERMINAL 행에서 claim 없이 PROCEED → 커밋 시 예외 또는 중복 실행, fake는 이 전이를 허용해 차이를 숨김 | `grpc/grpc-policy/.../GrpcIdempotencyInterceptor.java:109-114` | 코드 확인 (production caller 0, 잠복) | + +## 공통 패턴 + +1. **closed로 기록됐지만 코드가 따라오지 않은 항목**: Redis H8(#14)·M4(rate-limit hash), Kafka H6(timeout 취소 무효), object storage L3(파일 unchanged), websocket BOOT-002(prod 판정 재구현), messaging MSG-006(cleanup job 미전환), gRPC M1(admission race 일부만), JPA H10(tenant 규칙 이름 기반), GraphQL M1(DataLoader 에러 코드). closure 문서가 코드 상태를 보장하지 못한다. +2. **보안·안전 설정이 바인딩·검증만 되고 적용되지 않음**: Redis 안전 설정 약 20개, Kafka TLS/SASL(#8), gRPC `environment` 기본 LOCAL, GraphQL `persistedOperationOnly`·`idempotencyKey`, httpclient dynamic `trace-propagation`, `StartupSafetyValidator`의 prod 에러 상세 차단 주장, `wire-type-manifest.yaml`, Mongo tenancy/CSFLE, shared-contract cardinality 보호. 운영자는 보호받는다고 믿는다. +3. **조립되지 않은 코드가 대량으로 남아 있음**: GraphQL 약 57%(14.7k LOC), redis-sdk 약 22k LOC, notification R1 약 4.5k LOC, web library-only 약 5.7k LOC, object storage direct/multipart 약 3.2k LOC, messaging 미사용 API 타입. 일부 문서는 이 코드를 "제공되는 보호"로 서술한다. +4. **fake가 실제 adapter와 계약이 달라 결함을 숨김**: gRPC ledger fake(#15), tus fake digest(#11), Redis fake HDEL/PEXPIRE, notification recorder fake, durable operation in-memory store(#4), messaging fake publisher(#7). +5. **최근 리팩터 커밋의 회귀**: `208077fd`(#1), `9da00eb7`(#2, #3, BOOT-002, `StartupSafetyValidator` 축소), `60b6a319`(#3 V13), `ace8aaae`(sample이 중앙 ArchUnit에서 빠짐). + +## 권고 순서 + +1. **Wave 0 — 결정 없이 바로 고칠 수 있는 차단 항목**: #1, #2, #3(파일 3개 원복 + 새 버전 추가 + 버전 파일 해시 고정 테스트), #5, #6, L-2(prod 에러 상세 validator), L-3(sample `loggers` read-only). +2. **Wave 1 — 데이터·보안 Critical**: #4, #7, #8, #9, #10, #11, #13, #14, #15, #12(유스케이스를 application-core로 옮기거나 기능 삭제). +3. **Wave 2 — 그룹별 Required**: 아래 각 그룹 섹션 순서대로. closed 항목 회귀분은 remediation master에 재오픈 기록. +4. **Wave 3 — 조립되지 않은 코드 정리**: 삭제 vs 유지는 소유자 결정이 필요(아래). + +### 결정 필요 + +- 조립되지 않은 대형 코드(redis-sdk, GraphQL `advanced/**` 등, notification R1, web library-only, object storage direct/multipart)를 삭제할지, 별도 artifact로 옮길지, 유지할지. 이전 closure(C3, NOTIF-ADR-005, M1 LIBRARY_ONLY)가 "유지"로 결정했으나, 이번 리뷰는 그 전제(도입 가능성, 테스트된 부품)가 일부 성립하지 않음을 확인했다. — 승인자: 저장소 소유자 + +## 검증 기록 + +| 항목 | 결과 | +|---|---| +| `cd src && ./gradlew architectureCheck --console=plain` | BUILD SUCCESSFUL, 172 tasks (`verifyApplicationCoreDependencyPurity`, `verifyNoIgnoredSourcePackages`, `verifyRuntimeModuleRegistry`, `verifyRuntimeModuleMembership`, `verifyCleanArchitectureDependencies`, `:app-bootstrap:architectureTest` 포함) | +| Critical 15건 코드 재확인 | 15/15 인용 위치의 코드가 주장과 일치 | +| 테스트·`check`·`ci` | 미실행 (전체 실행은 별도 승인 범위. 리뷰 에이전트는 병렬 Gradle 충돌 방지를 위해 읽기 전용) | +| 실행으로만 확정 가능한 항목 | #4(PostgreSQL 25P02), #6(auto-config 조립 순서), #9(TransactionRequiredException), #2(CI), #13(DoS 시간) — 각 그룹 섹션에 확인용 테스트를 제안해 둠 | + +> **보정 (2차 리뷰 반영):** B-2의 "위조 callback이 `SesSuppressionUpdater`로 suppression을 만든다"는 과장이다. 이 클래스는 참조가 0이다. 서명 검증 우회 자체는 유효하다. A-2는 bridge 없이 `RuntimeEnvironment.isProductionActive(...)` 정적 호출 한 줄로 고칠 수 있다. 상세는 `2026-09-24-src-maintainability-review.md`의 "1차 리뷰 보정" 절. + +## 그룹별 상세 + +아래는 그룹별 리뷰 결과 원문이다. 경로는 저장소 루트 기준이며, 일부 그룹은 약어(`B/`, `BR/`, `S/`, `.../`)를 쓴다. 각 발견의 Status는 이전 리뷰 ID 기준(new / regression / known-open)이다. + +### Group A — Core + +#### Leaf별 판정 +| leaf | 판정 | 이유 | +|---|---|---| +| `src/domain-core` | PASS | 순수 Java. main 7개 파일이 마커와 포트뿐; README가 말한 ArchUnit 규칙이 app-bootstrap architectureTest에 실제로 있음 | +| `src/shared-contract` | NEEDS_FIX | 코드 결함 없음. 쓰는 곳 없는 "계약" 타입 여럿, README가 없는 런타임 보호를 약속 | +| `src/application-core` | NEEDS_FIX | 테스트 0·호출자 0인 V2 발행 코드 약 466줄; operation 조회/취소 유스케이스 부재로 web 어댑터가 대신 보유; 문서 불일치 | +| `src/adapter/outbound/support` | NEEDS_FIX | 예외 메시지를 그대로 WARN 로그 → PII·비밀값 누출 가능; `RuntimeProfileSnapshot` "유일한 reader" 주장 틀림 | +| `src/adapter/outbound/identifier` | NEEDS_FIX | 문서만 문제(의존성·훅·테스트 이름 불일치). `UuidCodec`은 죽은 코드 | + +#### 발견 (심각도 순) + +1. **[Required][security] `FailOpenDependencyLogger`가 `cause.getMessage()`를 그대로 WARN 로그에 남김** — `src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/FailOpenDependencyLogger.java:37-47` + - 근거: `error="{}: {}"`에 `getSimpleName()`과 `getMessage()`. Javadoc `:10-11`은 "PII cannot reach the log". 호출자 `FailOpenNotificationProvider.java:42`로 fork의 `GoogleEmailClient`/`SlackClient` 예외가 올라옴. 테스트 `FailOpenDependencyLoggerTest.java:64-73`은 메시지 `"connection refused"`로 `@gmail.com` 부재를 확인 → 아무것도 증명 못 함. + - 왜 문제인가: 메일 예외 메시지엔 수신자 주소, RestClient I/O 예외엔 Slack webhook URL 전체(비밀값)가 흔히 포함. 따옴표·줄바꿈이 key=value 로그 형식도 깸. + - 수정: 예외 클래스 이름만 기록(필요 시 길이 제한·정제된 reason code). 테스트는 `alice@example.com`, `https://hooks.slack.com/...`를 메시지에 넣어 재작성. + - 상태: new (application-core README "notification 값은 로그에 안 남긴다"를 우회하는 경로) + +2. **[Required][security] BOOT-002 회귀: prod 판정을 손으로 재구현, 가드는 bootstrap만 검사** — `src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/config/WebSocketPlatformSafetyConfiguration.java:78-84` + - 근거: `"prod".equals(profile) || "production".equals(profile)` (trim/소문자 없음) vs `RuntimeEnvironment.fromProfile`(trim+소문자). 결과가 `:63` `WebSocketPlatformStartupValidator(production(...))`로 전달. 9da00eb7(09-23)에서 생긴 파일. `RuntimeProfileSnapshot.java:12-13`의 "the only production type ... that reads getActiveProfiles"는 거짓(fileserver, httpclient, objectstorage, websocket도 직접 읽음). 가드 `RuntimeProfileAccessArchitectureTest.java:13,21`은 `dev.caskeleton.bootstrap..`만 검사. 근본 원인: 브리지가 outbound leaf에 있어 `INBOUND_ADAPTERS_DO_NOT_DEPEND_ON_OUTBOUND_ADAPTERS` 때문에 websocket이 못 씀. + - 왜 문제인가: `SPRING_PROFILES_ACTIVE=Prod` → bootstrap 검증기는 PROD로 보지만 websocket prod 안전 검증은 건너뜀(fail-open 분기). + - 수정: websocket은 `RuntimeEnvironment.isProductionActive(List.of(env.getActiveProfiles()))`(shared-contract edge 허용); ArchUnit 범위를 `dev.caskeleton..`로(messaging, sample 제외); Javadoc(`RuntimeEnvironment.java:39-41` 포함) 정정. + - 상태: BOOT-002 회귀 (websocket 그룹 코드) + +3. **[Required][tests] V2 단건 발행 코드가 테스트 0, 호출자 0** — `src/application-core/src/main/java/dev/caskeleton/application/outbox/v2/PublishNextOutboxDeliveryUseCase.java:26-242`, `OutboxV2RetryPolicy.java:33-151` + - 근거: `git grep 'PublishNextOutboxDelivery\|OutboxV2RetryPolicy\|OutboxPublicationAdmissionPort'` → 자기 파일과 docs뿐; 테스트 삭제 이력 없음; 계획서 `docs/superpowers/plans/2026-09-18-outbox-v2-one-record-publication-policy.md`의 "Prove …" 8개 항목 모두 미체크. 위험: `:111-115` `publisher.publish()`가 future 반환 전 동기로 오래 걸리면 `publishTimeout` 미적용 → lease 만료 후 `requireTransition`이 `IllegalStateException`; `:84-87` 2건 이상 claim 후에야 예외 → 행들이 lease 동안 묶임. + - 수정: `PublishNextOutboxDeliveryUseCaseTest`, `OutboxV2RetryPolicyTest` 추가, 또는 어댑터/bulkhead가 당분간 없으면 삭제(`OutboxBackoffPolicy`와 역할 중복). + - 가정/반론: 곧 wiring하지 않음 / Javadoc이 "Unwired" 명시한 의도적 후보. + - 상태: new (H7과 같은 종류; H7 종결은 당시 16개 클래스만) + +4. **[Required][architecture] operation 조회·취소 유스케이스 부재 → web이 store 포트·트랜잭션·객체 권한 규칙 보유** — `src/application-core/src/main/java/dev/caskeleton/application/operation/` + - 근거: `adapter/inbound/web/.../operationasync/OperationQueryService.java:54-58,71-80`이 `DurableOperationStorePort.find/cancel`, `transactions.inWrite` 직접 호출; `OperationAccessPolicy.java:28`(owner+tenant)가 web에 있음 → `application-core/CLAUDE.md:211`(D3 "no thin web→read-port path"), `ObjectAccessPolicy.java:16`("Owned here rather than by the transport")에 어긋남. 반대로 `SubmitDurableOperationUseCase`는 `CommandUseCase`가 아니고 production 호출자 0, `LegacyOutboxAppendPort`(Javadoc상 legacy/sample 전용) 사용. + - 수정: `GetDurableOperationUseCase`(QueryUseCase), `CancelDurableOperationUseCase`(CommandUseCase + `@UseCaseCapability`) 추가; owner·tenant 판정은 `ObjectAccessPolicy` 뒤로; web은 `WebRequestContext`→actor·tenant 변환만. + - 가정/반론: `DurableOperationStorePort`가 D3의 read-port / `AdapterBoundaryArchitectureTest.java:354`가 inbound→outbound 포트 접근을 허용하고 기능이 아직 조립 전. HARD-STOP 4 해당 여부는 web 그룹 판단. + - 상태: new + +5. **[Required][docs] shared-contract가 존재하지 않는 런타임 보호를 약속** — `src/shared-contract/README.md:350`, `src/shared-contract/CLAUDE.md:22` + - 근거: README "1001번째 tenant 부터는 bucket folding 자동 적용" — `CardinalityBounds`/`MetricNaming` production 참조 0, 실제 필터 `MetricsCardinalityMeterFilter.java`는 `ForbiddenMetricTags`만. `RedisHealthSnapshotProvider` 구현·소비자 0인데 CLAUDE.md는 "used by adapters and bootstrap health composition"(M5 잔재). `AlertSeverity`, `BaggageAllowlist`는 테스트에서만. + - 수정: tenant 상한을 `MeterFilter.maximumAllowableTags`로 실제 연결하거나 README 주장 삭제; 소비자 없는 타입 삭제 또는 testFixtures로. + - 상태: new + +6. **[Required][docs] leaf CLAUDE.md/README가 현재 코드와 다름** + - `application-core/CLAUDE.md:76-106`, `README.md:143-165,545-575`: notification 패키지는 application-notification으로 이동했는데 규칙 잔존; cache, lease, realtime, operation, filepublication, inbox 절 없음. + - `identifier/CLAUDE.md:30-33`: 의존성 "`:domain-core` + uuid-creator" (실제 `:application-core`뿐); `:38` `.claude/hooks/ca_import_gate.py` 없음; `:47` `UuidCodecSpec` → `UuidCodecTest`. + - `identifier/README.md`: 패키지명 오류(`dev.caskeleton.adapter.identifier`), 폐기된 Spock 절, SSOT를 `allowedProjectDependencies`로 기재. + - `support/README.md:6-8,24`: "CLAUDE.md 없음"(있음), SSOT를 `src/build.gradle`로(실제 modules.json), 없는 `OutboundHttpDependencyLogger` 언급. + - `shared-contract/README.md:436,499`: `RateLimiter`, `RateLimiterFactory` 없음. + - 수정: modules.json·코드 기준 동기화, 사라진 타입/파일 언급 삭제. + +7. **[Consider][correctness] `ValidatedIntegrationEvent`가 `envelopeSha256`–`envelopeBytes` 일치를 확인 안 함** — `src/application-core/.../messaging/event/ValidatedIntegrationEvent.java:40-88` (DB 복원 경로 `OutboxStoreAdapter.java:197`, `CanonicalOutboxEventRowMapper.java:71`가 저장된 해시를 그대로 신뢰; `CORRELATION_GRAMMAR`가 `*`라 길이 무제한인데 메시지는 "bounded"). 수정: 생성자에서 해시 재계산·비교, correlationId `{0,127}`. 가정/반론: DB 행 손상·변조 가능 / 인코더가 올바른 해시 생성. + +8. **[Consider][correctness] v1 `IdempotencyExecutor.runAndComplete`가 완료 기록 실패를 action 실패로 처리** — `src/application-core/.../idempotency/IdempotencyExecutor.java:103-110` (action 성공 후 `codec.serialize`/`store.complete` 실패 → `discard` → 재시도 때 action 재실행; 전체를 한 `inWrite`로 감쌀 때만 안전 — sample `PublishPosterImageUseCase.java:119`는 그렇게 함 — 전제 미기재·미강제. V2 `IdempotencyExecutorV2.java:207-211`은 `preserveUnknown` 예외가 원래 예외를 삼킴). 수정: try 범위를 `action.get()`으로 축소; V2는 `addSuppressed`. + +9. **[Consider][structure] 죽은 코드** — `identifier/.../UuidCodec.java` (외부 참조 0; "canonical" 계약도 틀림 — jshell로 `UUID.fromString("1-1-1-1-1")` 수용 확인), `application-core/src/test/.../CompiledPackageScanner.java`(참조 0), `application-core/.../fileexport/FileExportPort.java`(`@Deprecated(forRemoval)`, `exportCsv` 호출자 0). 수정: 삭제. + +10. **[Nit]** identifier가 `ca.spring-library`를 써서 순수 단위 테스트에 webmvc-test·tomcat 유입 → `ca.java-library`; `MasterSwitch.java:57-66` 주석 줄 깨짐; `DomainContextStrategy`/`Factory`는 case 하나뿐인 확장 지점. + +#### 확인 후 기각한 lead +- `RateLimiterFactory`, support README lead: 사실 → #6. notification PII: `Notification` 객체 자체는 logger로 안 감(예외 메시지 경로로 샘 → #1). +- 5개 leaf build.gradle edge 모두 허용 범위; application-core의 비-`dev.caskeleton`/`java`/`javax` import 0. +- `DB_LOCK_TIMEOUT` retryable=false는 `docs/registries/error-codes.yaml:873`과 일치; 새 `MasterSwitch` 상수는 `values()`로 모두 소비; `StrictSettingsBinder`는 httpclient env manifest 테스트가 간접 검증; `CacheAsideExecutor`/`LeaseWatchdog`는 H5 결정대로 유지, 회귀 없음. + +#### 커버리지 +정독: domain-core, support, identifier 전체; shared-contract 변경분 + activation/runtime/tracing/ratelimit/concurrency/metrics; application-core 944a1e34 이후 변경분 전체 + idempotency(v1·V2), outbox relay, cache executor, operation. 훑음: realtime, lease, inbox, lock, filepublication, OutboxPayloadPolicy. 동작 확인은 jshell UUID 파싱 1건. + +### Group B — Notification (vertical slice) + +#### Per-leaf verdict +| leaf | verdict | one-line reason | +|---|---|---| +| `application-notification` | NEEDS_FIX | Template/variable failure in dispatch repeats forever; recorder overwrites the recipient row with stale data; admin reconcile has no tenant check; ~4.5k lines of R1 code with no production implementation or caller. | +| `adapter-outbound-notification` | NEEDS_FIX | Forged SNS callbacks can be accepted; recovery and replay passes likely fail on every run; the HTTP response size cap does not limit what is read. | + +No HARD-STOP violations; every import within `modules.json` edges. + +#### Findings (most severe first) + +1. **[Critical][correctness] Background recovery and replay passes run `@Modifying` queries with no transaction, so every pass fails** — `src/adapter/outbound/notification/src/main/java/.../platform/dispatch/LeaseRecoveryService.java:106` + - Evidence: first statement of `recoverOnce()` is `leases.expireOverdue(batchSize)` → `RecipientDeliveryJpaRepository.java:58-60` `@Modifying ... int expireOverdue`. `grep 'TransactionPort\|inWrite'` over the adapter main → 0. `NotificationDispatchService.java:334-338` already records this exact failure for a query in the same repository ("…so the release threw TransactionRequiredException"). PG integration tests wrap modifying calls in `fixture.inTransaction(...)` (`PostgreSqlRecipientLeaseFencingIntegrationTest.java:60,152`). Same defect in: `ProviderEventProjectionService.java:58,120` (`markFailed`, `bindAttempt` outside `inWrite`), `ProviderEventReplayWorker.java:72` (`markFailed` in catch, `@Modifying` at `ProviderEventJpaRepository.java:144-149`), `ReconciliationService.java:82` (`ledger.append` without transaction). + - Why it matters: `NotificationBackgroundWorkers` swallows the exception with a WARN → crash recovery, expiry retirement and callback replay silently never happen. The dispatch error path relies on recovery (`NotificationSchedulerWorker.java:96-98`) → failed deliveries stay DISPATCHING forever. + - Fix: wrap each row's work in `TransactionPort.inWrite` (e.g. move recovery into an application-notification service with the dispatch transaction boundary); move `resolve`/`markFailed` inside `inWrite`; add one real-DB PG-lane test running `recoverOnce`/`replayOnce`. + - Status: new. Not execution-confirmed (Gradle not run); the PG test would confirm. + +2. **[Critical][security] SNS signature checks can be bypassed (bucket host, no topic allowlist, no freshness)** — `.../SnsSignatureVerifier.java:101-109`, `.../SesProviderCallbackAssembler.java:19` + - Evidence: host check accepts `amazonaws.com` or any `*.amazonaws.com` + path `/SimpleNotificationService-*.pem` → an attacker's S3 bucket (`https://.s3.amazonaws.com/SimpleNotificationService-x.pem`) passes and their cert verifies any envelope (`SnsCertificateUrlTest` has no S3 case). `SesCallbackAdapter.java:50-53` checks only `isValid` — no TopicArn allowlist, so a genuine AWS-signed message from the attacker's own topic is accepted. `Timestamp` never checked. Endpoint is `permitAll` (`CallbackMvcSecurityConfiguration.java:35`). Certificate cache (`NotificationCallbackProviderConfig.java:36-46`) is unbounded, keyed by attacker-supplied URL, network fetch inside `computeIfAbsent`. + - Why it matters: forged Bounce/Complaint/Delivery → suppressions (`SesSuppressionUpdater`) and false delivery states; with #6 one request can OOM. + - Fix: host `^sns\.[a-z0-9-]+\.amazonaws\.com(\.cn)?$`; required per-profile `allowed-topic-arns` when SES callbacks are on; reject stale Timestamp; bounded cache + cert subject check. + - Status: new. Exposure only when an SES profile + callbacks are enabled (default off). + +3. **[Required][correctness] Template/variable failure in dispatch repeats forever (poison pill)** — `NotificationDispatchService.java:146` + - Evidence: `render()`, `gateway.profile()`, `URI::create` run before the attempt row is inserted, uncaught. Submit only checks `templates.get(plan.template())` (`NotificationSubmissionService.java:118`); variable schema, SUBJECT control chars, URI scheme checked only at dispatch (`CanonicalNotificationRenderer.java:70`, `TemplateSlotPolicy`). No attempt row → recovery re-queues (`LeaseRecoveryService.java:111-120`). No render-failure test. + - Why it matters: a missing variable or newline in a subject → "accepted", then fails and re-queues every lease period forever; never FAILED. + - Fix: catch pre-dispatch `NotificationException`s before `insertDispatching` → FAILED with `TEMPLATE_FAILURE`; run the variable-schema check in `prepare()` too. + - Status: new + +4. **[Required][correctness] Recovery leaves some rows DISPATCHING forever, then gets stuck on them** — `LeaseRecoveryService.java:122-140` + - Evidence: when every attempt already has a completion (crash between `recorder.record` and `applyNextAction`, or failed retry dispatch) the loop does nothing; `reconcile` → `Unsupported` also leaves the row (SMTP and SES have no reconciliation → every mid-send SMTP crash). `selectExpiredDispatching` (`ORDER BY lease_until LIMIT batchSize`) returns the same rows each pass. No "all attempts completed" test. + - Why it matters: once `claimBatchSize` such rows exist no other abandoned delivery is ever recovered. + - Fix: all attempts completed → re-derive recipient state from the last attempt via retry policy; `Unsupported` → RECONCILIATION_REQUIRED (not re-picked, operator-visible). + - Status: new + +5. **[Required][correctness] Recorder writes a stale recipient snapshot without the lease check, undoing the late-match callback it just applied** — `DispatchOutcomeRecorder.java:105,123-124,135` + - Evidence: `bindUnmatched(...).forEach(projection::project)` rolls the callback result (e.g. DELIVERED) onto the recipient row (`JpaDeliveryAttemptStore.java:221-239`); right after, `recipients.save(updated)` writes back `deliveryOutcome()`/`evidenceLevel` from the dispatch-start snapshot. `save` is unfenced, breaking `RecipientLeaseStorePort.java:14` ("Every operation after the claim is fenced"). Only test uses a no-op `projections.save` fake (`DispatchOutcomeRecorderTest.java:176`). + - Why it matters: attempt row DELIVERED, recipient row back to UNKNOWN; the event is already APPLIED so replay won't fix it. + - Fix: re-read the recipient after projection; write only recorder-owned fields through `saveHeldBy(lease)`. + - Status: new + +6. **[Required][security/perf] HTTP response "cap" reads the whole body first** — `JdkNotificationHttpGateway.java:136-141` + - Evidence: `BodySubscribers.mapping(ofByteArray(), body -> copyOf(...))` buffers everything then truncates; comment `:73-75` claims never-ending chunked responses are prevented — false. No test. + - Fix: `BodySubscribers.ofInputStream()` + `readNBytes(max)` (or a custom subscriber); oversized-body test. + - Status: new + +7. **[Required][security] Admin reconcile has no tenant check and calls providers inside a write transaction** — `NotificationAdminApplicationService.java:156-158`, `:287-289` + - Evidence: `redrive`/`suppress` call `requireTenant`, `reconcile` does not → tenant-scoped operator acts on another tenant's attempts. `setProviderState` changes a global runtime but a tenant-scoped actor may call it. `AdminOperationExecutor` wraps the batch in `transactions.inWrite` → up to 200 provider round-trips in one DB transaction (contradicts `NotificationDispatchService.java:36-39`). `AdminAuthorizationGuard.java:43` always reports `SUPPRESS` as the denied authority. + - Fix: look up each attempt's tenant + `requireTenant`; `PROVIDER_CONTROL` only for unscoped actors; executor only claims/saves the operation, provider calls outside the transaction. + - Status: new + +8. **[Consider][structure] Large body of code with no caller** — ~95 files / 4.5k lines of R1 types in root package `application.notification` (per-file `grep -rlw` = 0 except `NotificationPort`, `Notification`, `NotificationChannel`); `platform/reactor/*` no bean/test/consumer yet `reactor-core`/`reactor-test` declared; `spring-web` declared as "Slack RestClient" but `grep org.springframework.web` over the adapter = 0; `EmailNotifier`, `SmsNotifier`, `MobilePushNotifier`, `WebPushNotifier`, `ApplicationReceiptServiceImpl` no main references. Fix: delete Reactor facade + deps + `spring-web` now; re-check the R1 "retain" decision. Counter: NOTIF-ADR-005 retains R1 without a removal date. + +9. **[Consider][correctness] SMTP reports pre-send failures as "ambiguous"; one dispatch branch clears next-dispatch time** — `SmtpNotificationProviderAdapter.java` throws `IllegalArgumentException` for non-email contact points and `reveal` failures surface as plain exceptions → not `ProviderCallNotStartedException` → `NotificationDispatchService.java:278-287` records AMBIGUOUS, duplicateRisk, reconciliation for a never-sent message. `DispatchPipeline.java:57-58` returns `READY_TO_DISPATCH` when `notBefore` not reached → caller `transition(..., Optional.empty())` sets `next_dispatch_at` NULL → row never claimed again (hard to hit). Fix: `ProviderCallNotStartedException` for these; pass `notBefore` as next-dispatch time. + +10. **[Consider][docs]** Adapter `README.md:3-5` / `CLAUDE.md:18-31` call the whole implementation "R0 legacy" (R2 platform is most of the leaf; SMTP/SES shipped); `application-notification` has no CLAUDE.md (rules in `application-core/CLAUDE.md:76-111`); `CLAUDE.md:8` Boot 4.0.0 vs 4.0.8; "no inline FQN" rule violated on 65 adapter main lines (e.g. `LeaseRecoveryService.java:34-36`) — rest of known-open L6. Fix: rewrite around R2; new `src/application-notification/CLAUDE.md`. + +11. **[Nit][structure] `contract-v1` test templates orphaned** — `src/adapter/outbound/notification/src/test/resources/notification/templates/**` (`grep -rn 'contract-v1\|notification/templates' src docs` → only historical plan `docs/superpowers/plans/2026-07-28-...md:927-930`; no `getResource`/`ClassPathResource`; filters `|html_text`, `|mrkdwn` match neither `{name}` placeholders nor `TemplateSlotMode`; consumer `NotificationTemplateRendererTest` deleted in 9da00eb7). Fix: delete the 4 files. Status: new (lead confirmed) + +#### Leads checked and dismissed +- HARD-STOP/edges: application-notification imports only `java.*` + `dev.caskeleton`; adapter only `application.notification`, own packages, `support`, `shared.error`. +- H3 (Thymeleaf OGNL) not regressed (default `PlaceholderTemplateEngine`, `NotificationPlatformCoreConfig.java:70`); L7 keep; L9 effectively closed (`NotificationPlatformReachabilityTest.java:67-72`). +- AES-GCM random 12-byte nonce + header as AAD; Twilio signature constant-time; HTML slot `href` https-only + allowlisted tags/attrs; SSRF resolves every address (DNS rebinding window documented). + +#### Coverage note +Deep: dispatch, scheduler, recovery, background, recorder, reconciliation, projection, submission, pipeline, retry policy, admin; SNS/SES callback path; HTTP gateway/endpoints; template engine/policy/renderer; provider runtime/gateway; SMTP adapter; persistence-jpa stores/SQL to confirm behavior. Skimmed: non-default adapters (FCM, APNs, WebPush, Twilio, Webhook), inbox/contact, settings/autoconfigure. R1: usage scan only. + +### Group C — File server (vertical slice) + +#### Per-leaf verdict +| leaf | verdict | one-line reason | +|---|---|---| +| `src/application-fileserver` | NEEDS_FIX | Quarantined bytes deleted; recovery path never runs; cancel leaves records/bytes behind; terminal sessions not checked; no per-file owner authz. | +| `src/adapter/outbound/persistence-fileserver` | NEEDS_FIX | 0 tests; race-critical writer/cleanup SQL untested anywhere. | +| `src/adapter/outbound/fileserver` | NEEDS_FIX | Every append re-reads the whole prefix. Path-traversal guards solid. | +| `src/adapter/inbound/web-fileserver` | BLOCKED | tus checksum checked against the wrong digest, after bytes are saved (Critical). | +| `src/composition/fileserver-platform` | PASS | Wiring only; every edge allowed by modules.json. | + +No HARD-STOP violations: build.gradle edges ⊆ `allowed_dependencies`; `application-fileserver/src/main` has 0 Spring/Jakarta imports. + +#### Findings (most severe first) + +1. **[Critical][correctness/security] tus `Upload-Checksum` compared with the running whole-file digest, after the chunk is saved** — `src/adapter/inbound/web-fileserver/.../tus/TusController.java:167-174` + - Evidence: `uploadService.append(...)` commits the offset first; then `checksumVerifier.verify(header, appended.sha256Snapshot())`, where `sha256Snapshot` is the running digest from byte 0 (`LocalAppendEngine.java:55-58,71`). + - Why it matters: an honest client with a correct per-chunk checksum fails on every chunk after the first; a mismatching chunk stays saved with the offset advanced and finalize publishes it. Returns 422 where tus says 460. + - Test gap: `TusProtocolContractTest.java:149-167` sends a *wrong* checksum on chunk 2 and the fake's `digestOf` (`InMemoryUploadApplicationService.java:117`) is also cumulative — the test hides the bug. + - Fix: per-request digest inside append; pass expected checksum into `append`, verify before `commitOffset`, roll back on mismatch; map to 460; add a correct-checksum chunk-2 test. + - Status: new + +2. **[Required][correctness/data] QUARANTINE verdict schedules staged bytes for deletion** — `src/application-fileserver/.../upload/DefaultFinalizeUploadService.java:236-253` + - Evidence: javadoc `:220-222` says only REJECT schedules removal; code queues `FAILED_VERIFICATION_CONTENT` for both. `DefaultCleanupService.cleanStaging` (`:134-146`) deletes without state check (`isReclaimable` `:219-223` covers published content only). Admin `reverify` (`DefaultFileserverAdminService.java:136-157`) then has no bytes. + - Fix: queue cleanup only for REJECT (or move to `quarantineRoot`); `cleanStaging` re-checks reclaimability. + - Status: new + +3. **[Required][correctness] "Ambiguous completion → reconciliation" does not work end to end** — `DefaultFinalizeUploadService.java:317-333` + - Evidence: no caller of the reconciler (`grep -rn 'reconcileRecoverable\|\.reconcile(\|FileReconciliationService'` → bean def `FileserverMaintenanceServiceConfiguration.java:59-65` + one test); `RecoveryQueue.pending/resolve` have no production caller. Content key written only in the VERIFYING→READY commit, so a failed commit leaves bytes under a key no record names → `reconcilePrePublishWithKey` (`DefaultFileReconciliationService.java:108-155`) unreachable (tests fabricate a VERIFYING record with a key). `AmbiguousCompletionException` from `publish` (`AtomicMoveContentPublisher.java:63-80`) never reaches the queue. + - Why it matters: `docs/fileserver/operations.md:71-76`, `security.md:72-75` promise this recovery. + - Fix: choose `ContentKey` in the application and persist it on VERIFYING before the move (write-ahead); add a scheduled worker calling `reconcileRecoverable` and draining `RecoveryQueue`. + - Status: new + +4. **[Required][correctness] `cancel` is a partial copy of the delete logic** — `DefaultUploadApplicationService.java:250-270` + - Evidence: `markDeleting` accepts READY (`FileTransitionRepository.java:68-69`) but cancel only queues `forStaging`; `cleanStaging` never moves DELETING→DELETED. + - Why it matters: tus DELETE on a finished upload (or single-shot rollback after `releaseLease` fails post-READY) leaves published bytes and quota forever, record stuck in DELETING; every cancelled upload stays DELETING. + - Fix: refuse cancel after UPLOADED, or reuse `DefaultFileLifecycleService.delete` retire step (`:84-104`) + DELETED transition in staging cleanup. + - Status: new + +5. **[Required][correctness] Abandoned uploads never cleaned up** — `cleanup/CleanupType.java` (`EXPIRED_UPLOAD`) + - Evidence: no producer of `EXPIRED_UPLOAD` (`grep enqueue(`); `LocalOrphanScanAdapter` walks only `contentRoot` (`:64,80`); `forOrphan` items marked done without deleting (`DefaultCleanupService.java:155-158`). tus accepts `Upload-Defer-Length: 1` (`TusRequestParser.java:48-50`) but no PATCH sets the length, so such uploads can never finish. + - Why it matters: unbounded disk growth any client can trigger. + - Fix: sweep sessions past `expiresAt` → EXPIRED + `EXPIRED_UPLOAD`; orphan items actually delete; reject `Upload-Defer-Length` until implemented. + - Status: new + +6. **[Required][correctness] Terminal sessions treated as live** — `DefaultUploadApplicationService.java:319-328` + - Evidence: `UploadSession.terminal()` never read (grep `\.terminal()` → 0). Append to cancelled/rejected upload → `acquireLease` refused by SQL → `JpaUploadSessionStore.java:146-150` reports "writer lease is held by another owner", `retryable=true`; tus HEAD still 204 with an offset. + - Fix: `requireActiveSession` and `status` return 410/404 when `terminal()`. + - Status: new + +7. **[Required][performance] Every append rehashes the whole prefix — O(n²) IO** — `src/adapter/outbound/fileserver/.../LocalBlockingContentStore.java:365-374` + - Evidence: `reattach` builds a new `LocalUploadHandle` per request (`DefaultUploadApplicationService.append:209-211`) so `digestAt` misses and `rehashPrefix` re-reads 0..offset (`LocalAppendEngine.java:55-58`); finalize reads the file twice more (`stagingDigest:346-362`, `verifyStaged:41`) on the servlet thread outside `transferExecutor` (`TusController.java:178`). + - Why it matters: 10 GiB in 5 MiB chunks ≈ 10 TiB re-read. + - Fix: bounded per-uploadId digest cache keyed by offset; reuse finalize digest in `verifyStaged`. + - Status: new + +8. **[Required][security] Authorization checks role tiers only** — `RoleBasedFileAccessPolicy.java:44-61` + - Evidence: `descriptor` argument unused; `FileDescriptor` has no owner; all controllers upload into `defaultNamespace()`. Any writer can cancel/delete/move anyone's file; any reader downloads everything. `FileOperation.FINALIZE` never authorized (grep 0) contrary to `security.md`. Admin reads use `READ_METADATA` (`DefaultFileserverAdminService.java:209-211`), mitigated by transport `RestrictedPathRule`. + - Fix: `ownerPrincipalId` on `FileRecord`/`FileDescriptor` checked by the default policy; authorize FINALIZE; admin tier for admin reads. + - Assumption: multiple mutually untrusted users. / Counterargument: may be a shared-drive template — then docs must say so, and the port still gives adopters no owner data. + - Status: new + +9. **[Required][correctness] Upload concurrency effectively 4 per node; limit returns 413** — `DefaultTransferAdmissionController.java:48-56` + - Evidence: all entry points share one default namespace scope → `scope-upload-permits=4` (`fileserver.yml:89`) caps the node, `instance-upload-permits=16` never reached; limit throws `QUOTA_EXCEEDED` (→413, `FileserverErrorCode.java:37`) which clients treat as permanent. `JpaFileQuotaService.reserve` checks no limit. + - Fix: `TRANSFER_ADMISSION_REJECTED` (429) for concurrency; scope by principal. + - Status: new + +10. **[Required][tests] persistence-fileserver's race-critical SQL untested** — `src/adapter/outbound/persistence-fileserver` (0 test files) + - Evidence: only coverage is `persistence-jpa/src/postgresqlIntegrationTest/.../PostgreSqlFileserver*` (`persistence-jpa/build.gradle:86-87`); `grep 'claimForCleanup\|terminate(\|reclaimExpiredClaims'` in tests → in-memory fakes only. `UploadLeaseRepository.terminate/claimForCleanup`, V4 `ACTIVE` clauses, claim-token settlement never run against real SQL. + - Fix: tests in the leaf's own strict lane: acquire-after-terminate, claim-while-leased, stale-token settlement. + - Status: new + +11. **[Consider][correctness] Draft-12 create ignores the POST body** — `Draft12UploadController.java:84-94,171-174` (Content-Length taken as final length, body dropped; empty POST → 0-byte upload). Fix: read `Upload-Length` or append the body. + +12. **[Nit][docs]** `adapter/outbound/fileserver/CLAUDE.md` lists 2 deps and says bootstrap owns the platform (actual: 4 deps, composition owns it); `composition/fileserver-platform/build.gradle` comments name `persistence-jpa`/`adapter:inbound:web`. + +#### Leads checked and dismissed +- Path traversal: `DefaultPhysicalPathResolver` (server key, shape regex, normalize + re-check) and Nginx mapper sound. +- M4 publish TOCTOU, C2 verification fail-open, L2 no-progress spin: no regression. +- Append rollback truncates+forces, escalates to ambiguous when unprovable. Correct. +- Size limits: multipart shares `max-file-size` placeholder; batch part count capped (MVC + reactive). +- `@EntityScan`/`@EnableJpaRepositories` follow repo pattern. `bin/` gitignored. Admin plane gated by `RestrictedPathRule` (`SecurityConfig.java:73-90`). + +#### Coverage note +Read in full: upload/finalize/cancel/cleanup/reconciliation/admin services, append/publish/store, tus/draft-12/upload controllers, reactive handlers, persistence session/lease/quota/cleanup adapters, migrations V3/V4. Skimmed: R1/R2 publication, problem mapping, metrics, most composition configs. Left out: always-true null checks in `FileserverStartupConfiguration.java:61-66`; reactive `contextFactory::current` reads a thread-local (inert in servlet setup). + +### Group D — Object storage + +#### Per-leaf verdict +| leaf | verdict | one-line reason | +|---|---|---| +| `application-objectstorage` | PASS | Registry edges OK (application-core only); strong identity parsing with tests. Fix #1 will likely add a fence field to `ObjectFinalizeRequest`. | +| `adapter-outbound-objectstorage` | NEEDS_FIX | No HARD-STOP. Staged-publication kernel + handoff service (wired, used by the sample) have a data-deletion path, non-idempotent replays, crash-recovery gaps, and no behavioral tests. | + +#### Findings (most severe first) + +1. **[Required][correctness] Abort can delete data behind an already-published reference; finalize not fenced by the handoff** — `src/adapter/outbound/objectstorage/.../kernel/StagedObjectPublicationKernel.java:257-269` + - Evidence: `abort` calls `provider.retire(...)` before `terminate(operation, ABORTED)`; `PUBLISHED` is terminal so `ObjectOperationRecord.java:143-148` throws — after the delete. Local-dev really deletes (`LocalDevObjectDataStore.java:147-155`). `ObjectPublicationHandoffService.authorizeAbort` (`:100-113`) reads only the stage record; `ObjectPublicationHandoffRecord.java:136-139` allows abort when released or lease expired. `finalizePublication` (`:183-237`) never reads the handoff; `ObjectFinalizeRequest` has no fence. + - Result: claim → finalize → release → authorizeAbort → abort deletes the file while manifest/pointer/lifecycle stay PUBLISHED; same with a late finalize racing an abort after lease expiry. + - Severity note: only `filesystem-local-dev` is deployable and S3 `retire` is UNSUPPORTED (`S3ManagedObjectProvider.java:121-125`); becomes Critical once a production provider implements retire. + - Fix: load the operation first and reject `REFERENCE_PUBLISH_IN_PROGRESS`/`PUBLISHED`; CAS an ABORT_IN_PROGRESS fence before the destructive call (like `DirectMultipartCoordinator`); add fence+claimant to `ObjectFinalizeRequest` and require an active matching lease; `authorizeAbort` rejects once in publish phase. + - Status: new + +2. **[Required][correctness] Handoff release, authorizeAbort and staged abort replays are not idempotent** — `.../control/ObjectPublicationHandoffRecord.java:119-120,165-171` + - release on an already-released record → `requireOwner` throws "owner/fence is stale"; the sample calls `releaseClaim` on every reconcile of a terminal READY intent (`ReconcilePosterImageUploadUseCase.java:96-97`) → second reconcile always throws. + - authorizeAbort `:137` throws if released with a future lease, otherwise writes a new revision and never reports `REPLAYED`. + - second `abort`: `deleteIfExists` false → `StagedObjectPublicationKernel.java:264-265` throws "could not be retired"; `AbortPosterImageUploadUseCase` (marked `IDEMPOTENT`, `:28`) re-calls abort (`:91-92`) while ABORT_AUTHORIZED → stuck permanently. Contrast `DirectMultipartCoordinator.abortMultipart:322-324` returns `REPLAYED`. + - Fix: same terminal state + same fence/claimant → return `REPLAYED` without writing; abort returns `REPLAYED` if operation already `ABORTED`, before touching the provider. + - Status: new + +3. **[Required][correctness] Four crash windows leave staged operations stuck** — `.../kernel/StagedObjectPublicationKernel.java` + - stage: operation advanced to DATA_UPLOADED (`:123-127`) before stage record created (`:139`) → replay `loadStage` null → `:91-92` "not uploadable"; data orphaned and un-abortable. + - verifyIntegrity: stage CAS (`:161`) before operation advance (`:166`) → replay REPLAYED at `:156-157`, later finalize fails at `:206`. + - finalize: once REFERENCE_PUBLISH_IN_PROGRESS (`:210`), `:206-207` throws "not finalizable" on every retry. + - scan verdict: same ordering in `RoutingObjectScanMaintenanceAdapter.java:84-110`. + - The managed path (`RoutingObjectMutationAdapter.publish:140-154`) recovers from these states. + - Fix: operation record as single source of truth; secondary writes create-or-require-same; replay path completes the missing advance; finalize accepts REFERENCE_PUBLISH_IN_PROGRESS and re-runs idempotent `references.publish`. + - Status: new + +4. **[Required][tests] Staged kernel and handoff service have no behavioral tests** — `.../test/.../kernel/StagedObjectPublicationKernelTest.java:11-23` (tests only `ObjectScanVerdictPolicy`); grep for `ObjectPublicationHandoffService`/`finalizePublication`/`authorizeAbort` in adapter tests → 0; `ObjectPublicationHandoffRaceTest` one takeover case; bootstrap `ObjectStorageCompositionIntegrationTest:73-83` legacy put/get only; sample `PosterImagePublicationWorkflowTest` mocks ports. Fix: local-dev full-flow + replay tests, failure injection between the two writes (wrap `ObjectControlStore`). Status: new + +5. **[Consider][correctness] Local control-store `create` not atomic** — `.../filesystem/LocalDevObjectControlStore.java:51-65` (`CREATE_NEW` then write; concurrent reserve reads empty/partial file → corrupt decode `CanonicalJsonObjectControlRecordCodec.java:72-73`; crash mid-write leaves key corrupt forever). Fix: temp file + force + `Files.createLink` as in `LocalDevObjectDataStore.create:55-60`. Assumption/Counter: few concurrent retries in local-dev / README claims restart+corruption characterization. + +6. **[Consider][security] Legacy filesystem adapter: unbounded read + absolute server path in HTTP response** — `.../FilesystemObjectStorageAdapter.java:61,71` + - `:71` still `Files.readAllBytes` — remediation master records L3 closed, but `git log` shows the file unchanged since `821fe00c`/`5f10b791`. + - `:61` returns `target.toUri()` (`file:////...`); `PosterWebMapper.java:35` puts it in the HTTP `location` field; sample `application.yml:324-327` enables this backend by default. + - Fix: logical URI (`objectstorage:` + key); check `Files.size` against a configured max before reading. + - Status: regression of L3 (closure record does not match code); path leak new. + +7. **[Consider][structure] ~3.2k lines of direct/multipart code unreachable, plus empty placeholders** + - 0 main callers: `DirectTransferCoordinator`, `DirectMultipartCoordinator`, `ManagedMultipartCoordinator`, `MultipartOperationResolver`, `S3ObjectOperationResolver`, `ObjectOperationResolutionService`, `ObjectOperationEpochRecord`; `SelectedObjectStorageProviderFactory.{managedMultipart,directTransfer,directMultipart}Provider(..)` only from `S3ProviderCompositionTest`. `RoutingObjectDirectGrantAdapter` 0 references anywhere; `ObjectStorageMaintenanceCapabilityConfig` empty `@Configuration`. Ports `DirectObjectUploadPort`, `DirectObjectDownloadGrantPort`, `DirectMultipartUploadPort` have no consumers; `ObjectPurgeMaintenancePort` no implementation. + - S3 contribution resolves credentials with `System::getenv` (`S3ObjectStorageProviderContribution.java:41`) instead of `SecretSourcePort` (same pattern fixed for httpclient H6). + - Fix: delete the two empty types; stop constructing the unused multipart provider/presigner (`:130-158`); move direct/multipart code+ports out of main until a consumer exists; `SecretSourcePort` before S3 promotion. + - Assumption/Counter: no fork needs direct/multipart before S3 promotion / code captures worked-out S3 behavior. + - Status: new + +8. **[Consider][readability] Publication/identity logic duplicated** — `.../config/RoutingObjectMutationAdapter.java:354-421,473-505` (`persistPublishedReference`/`createOrRequireSame` ≈ `ObjectReferencePublicationService.java:20-92`; `objectId`/`sha256Hex` ≈ `StagedObjectPublicationKernel.java:389-415`; `split("\\.")[1]` at `:504` and `RoutingObjectReadAdapter.java:103`; holds a `clock` but calls `Instant.now()` 10×). Fix: route through `ObjectReferencePublicationService`, one identity helper in `codec`, `ObjectReferenceCodec.routeToken(..)`, inject clock. + +9. **[Consider][correctness] `inspect` always reports scan state NOT_REQUIRED** — `.../config/RoutingObjectReadAdapter.java:53` (SCAN_CLEAN destinations require CLEAN at finalize, `StagedObjectPublicationKernel.java:191`). Fix: derive from destination `publicationRequirement`. + +10. **[Nit][correctness] Close order not actually reversed** — `.../config/ObjectStorageCapabilityAssembler.java:74,113-115` (`Map.copyOf` unordered; one throwing close skips the rest). Fix: ordered list + try/catch + `addSuppressed`. + +11. **[Nit][docs]** `CLAUDE.md:30` allowed deps omit `application-objectstorage`; `CLAUDE.md:17,40` say `application-core` for types now in `application-objectstorage`; `CLAUDE.md:8` Boot 4.0.0 vs 4.0.8; `README.md:40` says local-dev rejected under "prod/production" (code: `prod` only); `.tmp` "report-first reconciliation" comments (`LocalDevObjectDataStore.java:81`, `LocalDevObjectControlStore.java:100`) point to non-existent code. + +#### Leads checked and dismissed +- HARD-STOP 5: all edges allowed. +- Key traversal/namespace escape: fixed regex (`ObjectStorageProviderOperation.java:36-45`, `LocalObjectPathGuard.java:119-136`), root confinement, symlink rejection; references have fixed format + checksum. +- Presigned grants redact `toString`; `DirectGrantReplayCache` bounded (M4 holds). S3 blocked by readiness gate (H7 holds); L8 holds. +- `resolve()` objectId formula matches staged kernel; `LocalObjectStreamTransfer.write` checks digest before linking; direct multipart abort idempotent; Ed25519 approval checks two distinct keys + validity window. + +#### Coverage note +Read in full: kernel (staged/handoff/operation), routing adapters, local-dev provider, capability config/assembler, legacy filesystem adapter, identity/request contracts, diff since baseline. Skimmed: S3 providers, codecs, direct/multipart coordinators, legacy adoption. + +### Group E — JPA / PostgreSQL persistence + +#### Leaf별 판정 +| leaf | verdict | 한 줄 사유 | +|---|---|---| +| `src/adapter/outbound/persistence-jpa` | **BLOCKED** | Critical 2건: 이미 적용된 Flyway 마이그레이션을 제자리 수정, durable operation 재제출이 PostgreSQL에서 트랜잭션을 깨뜨림. HARD-STOP 위반 없음(엔티티·리포지토리가 inbound/bootstrap으로 새지 않음). | +| `src/config/jpa/readiness-cards.yaml` | PASS | 외부 prerequisite 하나가 없는 카드를 가리킴(FYI). | + +#### 발견 (심각도 순) + +1. **[Critical][correctness/migration] 이미 적용된 versioned 마이그레이션 세 개를 제자리에서 수정** — `src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/postgresql/V9__widen_capability_schema_stream.sql:3-8`, `.../postgresql/V13__outbox_canonical_transport_compatibility.sql:18-26,71`, `.../jpa/outbox-storage/V1__initialize_or_adopt.sql:140,218,296` + - 근거(`git log --follow`): V9는 2026-08-15 생성, 9da00eb7에서 주석 변경. V13은 60b6a319(09-18) 생성, 9da00eb7에서 `char(64)→varchar(64)`, `NOT VALID` 추가. outbox-storage V1은 07-31 생성 후 트리거 `FOR EACH STATEMENT`, 파티션 제거, digest sha256으로 변경. V9 새 주석은 "renumbering an applied production migration would invalidate Flyway history"라면서 그 수정 자체가 checksum을 바꿈. + - 왜 문제인가: Flyway SQL checksum은 주석 포함 파일 전체 CRC. `validate-on-migrate`는 Boot 기본값(true)이고 끄는 설정 없음 → 이전 파일이 적용된 모든 DB(local 프로필도 PostgreSQL+Flyway → 개발자 DB, 파생 서비스 DB)가 기동 시 checksum mismatch로 실패. 09-18판 V13이 적용된 DB는 컬럼이 `bpchar`로 남아 `ddl-auto: validate`에서도 실패. + - 수정: 세 파일을 적용 당시 바이트로 복원(V9 `944a1e34`, V13 `60b6a319`). H3·M5 수정은 새 버전(`V16__…` ALTER TYPE + 재검증, outbox-storage `V3__…`)으로. 적용된 버전 파일 해시를 고정하는 단위 테스트 추가. + - Status: new (H3/M5 수정 중 생김) + +2. **[Critical][correctness] 같은 요청 재제출이 PostgreSQL에서 트랜잭션을 깨뜨림** — `src/adapter/outbound/persistence-jpa/.../operation/DurableOperationStoreAdapter.java:47-78` + - 근거: `saveAndFlush`에서 `uq_durable_operation_scope`(23505) → `catch (DataIntegrityViolationException)` 안에서 같은 트랜잭션으로 `findByTenantAndPrincipal…` 재조회. `SubmitDurableOperationUseCase.submit`(application-core:87-99)이 미리 조회하지 않으므로 경쟁뿐 아니라 **모든** 동일 재제출이 이 경로. PostgreSQL은 에러 난 트랜잭션의 후속 문장을 25P02로 거부(`autosave` 설정 없음, grep 0). `SimpleJpaRepository.saveAndFlush`의 `@Transactional`이 caller 트랜잭션을 rollback-only로 표시하는 문제도 겹침. 같은 leaf `JpaProviderEventLedger.java:72-76`은 이 함정을 설명하고 `ON CONFLICT DO NOTHING`으로 회피. + - 왜 문제인가: "resubmission being safe" 계약이 실제 DB에서 500. in-memory fake만 통과; PostgreSQL 계약 테스트(`DurableOperationStoreContractTest:183-188`)는 adapter를 거치지 않고 raw SQL로 충돌만 확인. + - 수정: native `INSERT … ON CONFLICT (tenant, principal, operation_name, request_hash) DO NOTHING`; 0건이면 기존 row 조회. 실제 PostgreSQL에서 adapter 경유 이중 submit 테스트. + - Status: new (원래 있던 결함, M6 수정 때 누락) + +3. **[Required][correctness] `CanonicalOutboxAppendAdapter.append`에 caller 트랜잭션 확인 없음** — `.../outbox/CanonicalOutboxAppendAdapter.java:36-77` + - 근거: 형제 `OutboxStoreAdapter.append`(:55-56)에는 `requireTransaction` 있음. 포트 Javadoc은 "participates in the caller's existing write transaction" 요구. `repository.save`는 트랜잭션이 없으면 스스로 열고 커밋. `PersistenceTransactionOwnershipTest`, `CanonicalOutboxAppendAdapterTest` 모두 미커버. + - 왜 문제인가: 잘못 호출되면 outbox row가 비즈니스 쓰기와 따로 커밋 → 조용한 dual-write. + - 수정: 같은 guard 추가; 세 벌(outbox/operation/liveevent)로 복사된 guard를 `transaction` 패키지 공용 helper로; ownership 테스트에 이 adapter 추가. + - Status: new (H7 수정이 형제 클래스에만 적용) + +4. **[Required][correctness+tests] 전체/단건 읽음 처리가 ARCHIVED inbox 항목을 되살림** — `.../notification/platform/inbox/InboxItemJpaRepository.java:83-99`, `InboxItemEntity.java:107-127` + - 근거: `markAllRead` 서브쿼리가 `read_at IS NULL`만 보고 state로 거르지 않는데 `archive()`는 `readAt`을 설정하지 않음 → 읽지 않고 보관한 항목이 `state='READ'`로 바뀌어 기본 목록에 재등장. `unreadCount`는 ARCHIVED 제외(배지 0)인데 markAllRead는 그 항목을 갱신. 엔티티 `markRead`/`markSeen`도 ARCHIVED 미차단. `JpaNotificationInbox`/`InboxItemJpaRepository` 실행 테스트 없음; `PostgreSqlInboxCutoffIntegrationTest:86-105`는 운영 쿼리를 **복사한 SQL 문자열**을 돌리고 enum에 없는 `'UNREAD'` 사용. + - 수정: 서브쿼리에 `AND state NOT IN ('ARCHIVED','EXPIRED','DELETED')`; 엔티티 전이에서 terminal/ARCHIVED 차단; 통합 테스트는 실제 repository로. + - Status: new + +5. **[Required][correctness] canonical 이벤트가 legacy claim을 타면서 aggregate 순서와 tenant 범위를 잃음** — `.../postgresql/PostgreSqlOutboxClaimRepository.java:15-29`, `README.md:177` + - 근거: FIFO gate가 `aggregate_id`와 `occurred_at <`만 봄. `CanonicalOutboxAppendAdapter`가 저장하는 `tenant_scope`/`aggregate_type`/`aggregate_sequence`/`event_index`를 claim이 안 씀(`AggregateOrder`는 "Total order within one aggregate identity"). `occurred_at`이 같은 두 이벤트는 함께 claim, 순서 미정(`...RowLifecycleIntegrationTest:311`이 "LegacyFifoLimitation"으로 기록; README는 "aggregate 당 최대 한 row"). 다른 tenant/type의 같은 `aggregate_id` DEAD row가 서로 영구 차단. + - 수정: canonical row(`contract_id IS NOT NULL`) gate를 `(tenant_scope, aggregate_type, aggregate_id)` + `(aggregate_sequence, event_index)` 순서로; 부분 유니크 인덱스; README 수정. + - 가정/반론: 한 command가 같은 aggregate에 같은 `occurredAt` 이벤트를 2개 이상 냄 / 이 경로 플래그 기본 off(`outbox.yml:22`), V2 polling 경로는 이미 해결. + - Status: new + +6. **[Required][tests/security] H10 tenant 규칙이 필드 이름 `tenantId`로만 판정** — `src/adapter/outbound/persistence-jpa/src/testFixtures/.../testkit/arch/TenantScopedRepositoryPredicate.java:19,48-50` + - 근거: Javadoc "Structural rather than name-based"인데 `TENANT_FIELD = "tenantId"` 이름 비교. `DurableOperationEntity.tenant`, `IdempotencyRecordEntity.tenant`, `OutboxEventEntity.tenantScope` 누락; 세 리포지토리 모두 `extends JpaRepository`(findAll/deleteAll 상속). + - 수정: `tenant*` 필드/컬럼 모두 또는 marker annotation; 세 리포지토리를 `Repository` marker로 축소. + - 가정/반론: 템플릿 사용자가 상속 CRUD를 호출 / 현재 adapter는 범위 지정 쿼리만 사용. + - Status: new (H10 종결 범위의 빈틈) + +7. **[Consider][correctness] 잘못된 canonical row 하나가 relay 전체를 멈춤** — `.../outbox/OutboxStoreAdapter.java:73-85,161-170` (배치 중 `IllegalStateException` → claim 트랜잭션 전체 롤백 → 같은 row가 매 주기 재선택). 수정: 해당 row DEAD 전이 후 계속. 가정/반론: DB CHECK로 못 막는 불일치(payload/envelope, 수동 UPDATE) / V13·V14 CHECK가 대부분 차단. + +8. **[Consider][performance] outbox 지표 쿼리가 5초마다 테이블 전체를 셈** — `.../outbox/OutboxEventJpaRepository.java:21-27` (`countGroupedByStatus` 무필터, 7일치 PUBLISHED 포함, `OutboxRelayScheduler` 매 poll(PT5S) 호출; `OutboxReaper.deletePublishedBefore` 무제한 단일 트랜잭션 삭제). 수정: `status <> 'PUBLISHED'`만 집계; 삭제는 `LIMIT` 루프. + +9. **[Consider][structure] `JpaObservabilityAutoConfiguration` 미사용 코드** — `.../autoconfigure/JpaObservabilityAutoConfiguration.java:26` (자기 자신 외 참조 0, package-private; Javadoc이 bootstrap 타입 링크). 수정: 삭제. 반론: M10에서 고급 capability 경로로 남겼을 수 있음. + +10. **[Consider][security] experimental tenant guard의 "audited" admin scope가 기록을 남기지 않고 게이트 없이 생성됨** — `.../experimental/tenant/TenantAwareRepositoryGuard.java:36-54` (reason을 ThreadLocal에만 둠; public 생성자라 `ExperimentalEntryConsentTest:34-36` 게이트 목록에서 빠짐; `SchemaMultiTenantConnectionProvider.releaseConnection:50-57`은 reset 실패 시에도 tenant `search_path` 커넥션을 pool에 반환). 수정: audit sink + `enabledBy(gate, …)` factory; reset 실패 시 커넥션 `abort`. 반론: 운영 호출처 없는 experimental 코드. + +11. **[FYI][docs] readiness card 외부 prerequisite가 없는 카드를 가리킴** — `src/config/jpa/readiness-cards.yaml:434-439` (`messaging-cdc-dispatch.v1`이 messaging 카드 11개에 없음; `minimum-readiness: R2` 어휘가 messaging `maturity:`와 불일치; `JpaReadinessRegistryValidator:169-179`는 형식만 검사; `postgresqlOutboxCdcCleanupIntegrationTest` 태스크 부재). 수정: `not-implemented` 동안 prerequisite 제거 또는 validator에 대상 파일 조회 추가. + +12. **[Nit][docs]** `CLAUDE.md:237-243` 벤더 SQLState 표에 `55P03 → DB_LOCK_TIMEOUT` 누락(`PostgreSqlSqlStateErrorMapping.java:43`에는 있음). + +#### 점검 후 기각한 lead +- SQL 문자열 조립: `set_config` 값은 bind parameter; `NamedStatementInspector`가 `*/` 차단; identifier는 validate된 registry 경유. +- `PersistenceExceptionTranslator` cause chain 탐색·unknown→empty 정상; `TransactionRetryClassifier` 40001/40P01만 재시도 정상. +- HARD-STOP 2/3: inbound의 persistence import 0; bootstrap은 SPI/config 타입만. +- live-event position: counter row 락이 커밋까지 유지 → 커밋 순서 = position 순서, gap 없음. +- 이전 `JpaModuleBoundaryTest` `auditing` 잔여물 해소. `JpaProviderEventLedger.bindUnmatched` stale 엔티티는 해시 매칭으로 자기 복구. + +#### 커버리지 +자세히: outbox, operation, liveevent, inbox, transaction, failure/h2/postgresql 에러 매핑, autoconfigure, experimental tenant/rls, 변경된 마이그레이션(V9, V13, V14, V15, outbox-storage V1/V2), 관련 테스트, readiness cards. 훑음: notification platform 저장소 나머지, `PostgreSqlOwnerSafeIdempotencyStore`(claim 경로), springdata/hibernate 패키지. Flyway checksum 실패·25P02는 코드와 벤더 동작 근거 판단(실제 DB 재현 없음). + +### Group F — MongoDB persistence + +#### Per-leaf verdict +| leaf | verdict | one-line reason | +|---|---|---| +| `adapter-outbound-persistence-mongo` | NEEDS_FIX | No HARD-STOP violation; zero-dependency edge confirmed. Operator injection, multi-profile, bulk mapping, CSFLE and change-stream paths have correctness/security holes; tenancy docs promise enforcement the code does not have. | + +#### Findings (most severe first) + +1. **[Required][security] Operator injection through an `Object` value on the equality paths** — `src/adapter/outbound/persistence-mongo/.../query/PolicyAwareMongoQueryBuilder.java:43-47`, `.../imperative/atomic/AtomicFilter.java:66-74` + - Evidence: `whereEquals(String path, Object value)` → `Criteria.where(path).is(value)`; `AtomicFilter.toQuery()` passes values through `.is(entry.getValue())` with no type check. Javadoc (`:16-19`) claims NoSQL operator injection is "a compile-time impossibility". A `Map`/`Document` such as `{"$ne": null}` or `{"$regex": ".*"}` is sent as an embedded document the server reads as an operator — bypasses the field operator allowlist and `MongoRegexPolicy`; `AtomicFilter.id(Map.of("$gt",""))` defeats the single-document guarantee. No test covers it; the security lane (`build.gradle:189`) claims "injection" coverage but `MongoSecurityIntegrationLaneTest` has none. + - Fix: one shared `requireScalar(value)` guard used by the builder and `AtomicFilter` (reject `Map`/`Bson`/`Document`, and collections for EQ) + regression test with `Map.of("$ne", …)`. + - Status: new + +2. **[Required][correctness] With more than one profile, startup and readiness ignore `active-profile`** — `.../autoconfigure/MongoStartupValidator.java:69-92`, `.../autoconfigure/MongoPlatformHealthIndicator.java:86-89` + - Evidence: `active-profile` is read only by the client customizer via raw `environment.getProperty` (`client/MongoProfileClientSettingsAutoConfiguration.java:52-53`). Validator iterates every profile and throws on topology mismatch; health uses `anyMatch(profile.topology() != observed)`. Multi-profile is a tested setup (`MongoClientSettingsFactoryTest.java:117`); validator/health tests use one profile only. `primary` (REPLICA_SET) + `local` (STANDALONE) → startup always fails, or health permanently DOWN. + - Fix: bind `activeProfile` once into typed settings; customizer, validator and health use only that profile; add a two-profile test. + - Status: new (side effect of the H1 fix) + +3. **[Required][correctness/data loss] Change-stream pipeline and consumer lose events** — `.../changestream/MongoChangeStreamPipeline.java:48-64`, `.../changestream/consumer/ReactiveMongoChangeStreamConsumer.java:174-179` + - (a) `advancesPosition` passes only events strictly after the high-water mark (`isAfter`); events of one multi-document transaction share a `clusterTime`, so the 2nd+ are dropped. `MongoChangeStreamPipelineTest.twoEventsInOneTransactionAreDistinct` checks identity only, never the pipeline. + - (b) `rawOf` passes only `fullDocument`; a delete arrives as `{}` without `operationType`/`documentKey`, contrary to `MongoChangeProjector` Javadoc. + - (c) `BUSY`/`PARKED` do not advance the checkpoint (`projector/MongoChangeStreamRunner.java:293-297`) but `concatMap` continues and the next event's checkpoint moves past the skipped one. + - (d) `MongoResumeCheckpoint.belongsTo()` has no production caller; factories fill `clusterIdentity` with `""` (`:186-194`), so the cross-cluster token check never runs. + - Why Required not Critical: unreachable in the shipped bootJar (reactive excluded, `change-streams=true` refused) — but it is the consumer the README tells forks to adopt. + - Fix: accept equal `clusterTime` and dedupe by identity; pass the full change envelope; error on a result that cannot advance the checkpoint; enforce `belongsTo` in `resumeFrom`. + - Status: new + +4. **[Required][correctness] Bulk path skips Spring mapping** — `.../imperative/bulk/MongoBulkExecutor.java:75-86`, `.../imperative/bulk/MongoBulkWritePlan.java:65-69` + - Evidence: bulk builds `UpdateOneModel` from raw `getQueryObject()`/`getUpdateObject()` and calls the driver; atomic path uses `operations.updateFirst(query, update, documentType, collection)` (`MongoAtomicOperationsTemplate.java:137-139`) which applies `@Field` names and custom conversions. `DomainDocumentId`/`BigInteger` values have no codec (estimator `toJson()` fails); `@Field` aliases are written under the wrong name. Tests use String values only. + - Fix: take `documentType` and map via `QueryMapper`/`UpdateMapper`, or reuse `MongoOperations.bulkOps(...)`; estimate on the mapped result. + - Status: new (MNG-026 fixed the policy bypass; mapping bypass remains) + +5. **[Required][security] `MongoCsfleClientFactory` ignores the profile's encryption policy** — `.../advanced/encryption/csfle/MongoCsfleClientFactory.java:40-47` + - Evidence: `schemaMap` keyed by bare `profile.collection()` while the driver matches `db.coll` → nothing auto-encrypted; `profile.fields()` never read; `keyVaultCredential` not passed to `keyVaultMongoClientSettings` (contradicts `MongoCsfleProfile` Javadoc). No test, no caller. + - Fix: key by namespace, generate schema from `fields()`, set key-vault settings from the separate credential, unit-test the generated settings. + - Status: new + +6. **[Required][security/docs] Shared-collection tenancy enforcement point does not exist** — `.../advanced/tenancy/shared/TenantScopedMongoOperations.java:19`, `docs/mongodb/advanced/multi-tenancy.md:13-14,79` + - Evidence: no implementation or caller of `TenantScopedMongoOperations`; `MongoTenantPredicateInjector` called only from a test; docs say it is the entry point so callers "cannot construct an unscoped operation by forgetting". The injector itself is sound (fails closed on duplicate criteria, overwrites caller `tenantId`). + - Fix: ship an implementation wrapping atomic ops + executor as the only route, or delete the interface and rewrite the doc. + - Assumption: adopters trust the doc. / Counterargument: Advanced, flag-gated; fork expected to implement. + - Status: new + +7. **[Consider][performance] Reactive cursor re-serializes every row twice** — `.../reactive/cursor/MongoReactiveCursorPublisher.java:78-80` (`converter.write` + `toBsonDocument` in `doOnNext` just to measure bytes; fails for projection proxies). Fix: `RawBsonDocument` or decode-time hook. Status: new (side effect of M4 fix) + +8. **[Consider][correctness] Migration lock swallows all write errors as "lost the race"** — `.../migration/MongoCollectionMigrationLock.java:112`. Fix: return empty only for code 11000, rethrow otherwise. Status: new + +9. **[Nit][readability/docs]** `MongoPlatformAutoConfiguration.java` has 41 lines of inline FQNs (forbidden by leaf CLAUDE.md) and an orphaned Javadoc at `:192-198`; `CLAUDE.md:46` says `implementation(project(...))` but it is `runtimeOnly` (`app-bootstrap/build.gradle:129`); `CLAUDE.md:53` broken sentence. + +#### Leads checked and dismissed +- Zero allowed dependencies: main imports resolve only to `…adapter.outbound.mongo`; no `project(` in build.gradle; no re-declared application types. +- Regex: `Pattern.quote` on starts-with/contains; `whereMatches` validates; every query has `maxTimeMS`. +- Keyset cursor: HMAC + `MessageDigest.isEqual` + length cap. OK. +- Resume token: `toString` shows length only; invalidate → `startAfter`. OK. +- CSFLE key material / credential URI: not stored or logged. +- Prior H2 no regression; prior H6 now closed (16 files tracked). +- `DataAccessException` unwrap loses cause but classifies UNCLASSIFIED/non-retryable — safe. +- Tenant field updates blocked unless explicitly registered updatable. + +#### Coverage note +Read in full: tenancy, CSFLE, changestream core/consumer/runner/pipeline, query builder/policy/regex, atomic, bulk, imperative executor, failure classifier, client settings/profile autoconfig, platform autoconfig, startup validator, health, topology probe, migration lock, diff since `944a1e34`. Skimmed: QE, search/vector, sharding, timeseries, gridfs, transaction, reactive executor, schema, observation, admin. + +### Group G — Redis + +#### Leaf별 판정 +| leaf | 판정 | 한 줄 사유 | +|---|---|---| +| `redis-runtime` | NEEDS_FIX | lease 하나가 연결 하나를 독점하고 SCRIPT 한도 8 → Redis가 정상이어도 동시 9번째 요청부터 거부. 공개 안전 설정 약 20개가 무효. 자기 테스트 1개 | +| `redis-sdk` | NEEDS_FIX | 약 21.7k LOC인데 facade 구현·pub/sub 전송·조립 코드가 없어 도입 불가. 자기 테스트 0개 | +| `cache-redis` | NEEDS_FIX | rate-limit hash 무한 증가(M4 회귀), lease replay가 유효 시간 부풀림, 남의 테스트 64개 보유, realtime adapter는 죽은 코드 | + +#### Findings (심각도 순) + +1. **[Critical][performance/correctness] SCRIPT lane이 호출자마다 연결을 독점 → Redis 정상이어도 동시 9번째 호출부터 거부** — `src/adapter/outbound/redis-runtime/.../RedisRuntimeOwner.java:134-140` + - Evidence: `if (current >= limits.get(kind)) throw reject(...)`의 `current`는 연결 수가 아니라 대여 중 lease 수. 한도 `RedisSdkAutoConfiguration.java:279` `limits.put(SCRIPT, getMaximumScriptConnections())`, 기본값 `RedisSdkSettings.java:687` `= 8`. 호출부(`RedisEdgeRateLimitAdapter.java:109`, `RedisIdempotencyStoreAdapter.java:109`, `RedisDistributedLeaseAdapter.java:145`)가 RTT 전체 동안 lease 보유. `RedisScriptLaneCapacityTest`가 세 번째 동시 borrow 거부를 단언(동작 고정). + - Why it matters: rate-limit은 fail-closed → lane 포화 시 모든 요청 503/429; Redis 지연이 조금만 튀어도 전면 거부. 요청이 Redis에 전송되지 않았는데 idempotency·lease는 `Indeterminate` 보고(`RedisIdempotencyStoreAdapter.java:128-131`, `RedisDistributedLeaseAdapter.java:166-172`). `RedisHealthContributor.java:51`도 REGULAR lane에서 lease를 빌려 포화 시 `redisRequired` DOWN. + - Fix: REGULAR/SCRIPT lane은 공유 멀티플렉싱 연결 N개 round-robin + in-flight `Semaphore`/`requestQueueSize`로 동시성 제한; 독점 lease는 TRANSACTION/BLOCKING/PUBSUB만; borrow 거부는 `Unavailable`로 분류. + - Status: H8 회귀 (H8은 "한도 단위가 틀렸다"였는데 단위는 그대로 두고 64→8로 낮춤) + +2. **[Required][correctness/performance] fixed-window/sliding-counter hash 무한 증가** — `src/adapter/outbound/cache-redis/.../ratelimit/RateLimitScripts.java:58-59,89-90` + - Evidence: `HDEL`은 정확히 `windowStart - 2w` 필드 하나만 지우고, 허용 요청마다 `PEXPIRE`로 TTL 갱신. 기본값(sliding, w=1s, TTL 7s)에서 1.5s 간격 요청 → 버킷 0, 3000, 6000…이 삭제 대상에 안 걸리고 key도 만료 안 됨. `:39-40` 주석("refreshed per hit이 아니다")은 코드와 반대. fake(`InMemoryRedisCommandGateway.java:1717-1753`)가 HDEL/PEXPIRE를 흉내내지 않아 미테스트. + - Why it matters: 활동 subject마다 메모리 누적; 같은 Redis의 idempotency/lease가 eviction·OOM 영향. + - Fix: fixed window는 `start`/`count` 두 필드 덮어쓰기; sliding은 `start`/`cur`/`prev` 회전; live lane HLEN 상한 테스트. + - Status: M4 회귀(수정 불완전) + +3. **[Required][correctness] lease replay(status 2)가 서버 잔여 TTL을 무시하고 전체 TTL 재부여** — `.../lease/RedisDistributedLeaseAdapter.java:157-161` + - Evidence: `ReplayedSameOperation(handle(request, ownership, startedAt))`가 재시도 시점부터 `leaseTtl - drift` 부여; 스크립트가 돌려주는 잔여 `PTTL`을 버림. 같은 파일 `inspect()`는 M7 수정으로 `observedValidityOf(reply.remainingMillis())` 사용(`:213`). + - Why it matters: 첫 응답 유실 후 재시도 시 보유자가 서버보다 더 오래 lease를 가졌다고 믿음 → 두 보유자 겹침 가능. + - Fix: status 2에서 `observedValidityOf(reply.remainingMillis())`; `localValidityOf`의 TTL≤drift 검사를 Redis 호출 전에. + - Status: new (M7 계열) + +4. **[Required][security/performance] 공개 Redis 안전 설정 약 20개가 바인딩·검증만 되고 적용 안 됨** — `src/adapter/outbound/redis-runtime/.../RedisSdkSettings.java:717,725` + - Evidence: 모든 getter를 `redis-runtime`/`redis-sdk`/`cache-redis`/`app-bootstrap` `src/main`에서 `\.\(\)` grep → 설정 클래스 밖 참조 0: `getMaximumInFlightBytes`, `getMaximumReplyBytes`, 모든 `getMax*`(`limits`), `getCollection`/`getAdvanced`/`getMaxBlock` timeout, `getAcquireTimeout`, `getTlsHandshakeTimeout`, `getOverflowPolicy`, `getOfflineQueueCommands`. SDK는 하드코딩된 `RedisOperationLimits.defaults()`(`RedisOperationLimits.java:56`). 공개 env key로 등록됨(`docs/registries/env-keys.yaml:1959-2109` `APP_REDIS_LIMITS_*` 11개, `:2409`, `:2455`). + - Why it matters: 운영자는 응답 크기·in-flight 상한으로 OOM을 막는다고 믿지만 아무것도 안 막음(closed된 H3와 같은 종류). + - Fix: 우선 설정·env key 삭제; 필요한 것만 `RedisOperationLimits.from(settings)`로 연결. + - Status: new + +5. **[Required][tests/architecture] redis-runtime·redis-sdk 테스트가 cache-redis에 있어 해당 leaf focused check가 빈 초록불** — `src/adapter/outbound/cache-redis/build.gradle:22` + - Evidence: cache-redis 테스트 76개 중 64개가 `.../redis/sdk/**`(2481줄 `InMemoryRedisCommandGateway` 포함); `redis-sdk/src`에는 `main`만; `redis-runtime` 테스트는 `RedisSdkAutoConfigurationRegistrationTest` 1개; 두 leaf 모두 CLAUDE.md/README 없음. + - Why it matters: CLAUDE.md는 "소유 leaf의 `:test`를 돌려라" — redis-sdk는 NO-SOURCE, runtime은 1개(HARD-STOP 6 위험). 게이트 위반은 아님(`ArchitecturePlugin.java:22-23`은 production 선언만 검사). + - Fix: `sdk/**` 테스트를 소유 leaf로 이동, fake는 `java-test-fixtures`로 공유, `testImplementation` edge 제거, leaf별 CLAUDE.md 추가. + - Status: new (build.gradle 주석에 "temporarily") + +6. **[Required][structure] "optional SDK"와 realtime adapter를 실제로 쓸 수 없음** — `src/adapter/outbound/redis-sdk/.../api/RedisOperations.java`, `src/adapter/outbound/cache-redis/.../realtime/*` + - Evidence: `implements RedisOperations|ReactiveRedisOperations` main/test 0건; `implements RedisPubSubGateway`는 test `InMemoryRedisPubSubGateway.java:18` 하나뿐, runtime에 `connectPubSub`/`StatefulRedisPubSubConnection` 0건(구현 불가); `RedisConnectionRegistry`(redis-sdk) main 호출자 0이고 `RedisRuntimeOwner` lane 한도 로직 중복; `RedisEphemeralFanoutAdapter`, `RedisConnectionRegistryAdapter` 조립처 없음(test 외 grep 0). + - Why it matters: README는 "SDK를 composition에 넣을 때만" 적용된다는데 넣을 대상이 없음. 약 22k LOC가 유지보수·리뷰 표면만 차지. + - Fix: redis-sdk와 realtime 패키지 삭제; 필요 시 facade 구현 + PUBSUB 연결과 함께 재도입. + - Assumption/반론: 6개월 내 SDK 소비자 없음 / C3 closure가 "optional library 유지" 결정 — 단, 도입 가능하다는 전제 위. + - Status: new (C3 closure 미포함) + +7. **[Consider][architecture] runtime에 SDK 표면이 섞여 있음** — `redis-runtime/.../RedisCommandGateway.java`(1227줄), `LettuceRedisCommandGateway.java`(1282줄) (메서드 118개 중 cache-redis main이 쓰는 건 약 15개; raw/admin 자격 증명·raw allowlist(`RedisSdkAutoConfiguration.java:119-142,182-193`)가 runtime에; runtime·sdk가 같은 패키지 9개 공유; `RedisCorrectnessRoles`가 consumer selector 값 하드코딩). Fix: runtime gateway는 semantic adapter에 필요한 메서드만, 나머지는 sdk로(#6 삭제 시 함께 사라짐); 패키지 `...redis.runtime.*`로. + +8. **[Consider][readability] EVALSHA+NOSCRIPT 재로드 헬퍼 4벌 복사, 서로 조금씩 다름** — `CacheScripts.java:55-87`, `RateLimitScripts`, `LeaseScripts`, `IdempotencyScripts` (`CacheScripts`만 `startsWith("NOSCRIPT")` 폴백). Fix: `RegisteredLuaScript` 하나로 공유. + +9. **[Consider][observability] 장애 로그가 JVM 수명 동안 한 번만 WARN, 예외 타입이 wrapper 이름** — `RedisSemanticFailureLogger.java:19,24-26` (`WARNED` 미초기화; `.get()`에서 잡아 `failureType`이 거의 항상 `ExecutionException`). Fix: cause unwrap, WARN을 시간 창 단위로. + +10. **[Consider][security/ops] SCRIPT ACL probe가 스크립트 내부 명령 권한을 확인 안 함** — `RedisSemanticScriptAclProbe.java:420` (`return {1}`은 명령 0개 → ADVANCED 계정에 `+hset/+pexpire/+time` 없어도 기동 통과, 첫 요청 실패; `redisRequired`는 REGULAR lane만 probe → ADVANCED 자격 증명이 깨져도 readiness UP). Fix: `TIME/HSET/PEXPIRE/DEL`을 실제 수행하는 probe 스크립트; script capability 선택 시 health가 SCRIPT lane probe. + +11. **[Consider][architecture] application executor를 adapter leaf에서 조립** — `RedisIdempotencyConfig.java:251-265` (PostgreSQL 쪽 `PostgreSqlIdempotencyProviderConfig.java:36-60`은 processing-lease 2m, codec `json.v1` 하드코딩으로 따로 조립 → `APP_IDEMPOTENCY_PROCESSING_LEASE` 적용 여부가 provider마다 다름). Fix: executor는 bootstrap에서 설정 소스 하나로 한 번만 조립, leaf는 store만 제공. + +12. **[Nit][docs]** `app-bootstrap/CLAUDE.md:80,89`가 `autoconfigure/redis/RedisCapabilityConfig`·`RedisKeys`를 가리킴(실제 `cache-redis/.../capability/`); `cache-redis/CLAUDE.md`의 위치·패키지 루트·"Boot 4.0.0" 틀림; `src/README.md:302-306` `APP_CACHE_REDIS_ENABLED`/`CLIENT_MODE`는 `env-keys.yaml:2786-2794`에서 orphaned; cache-redis README의 `:app-bootstrap:test --tests '*RedisSemanticScriptAclProbeTest'`는 잘못된 leaf; `app.redis.capacity.*` env 레지스트리 `owner_module`이 cache-redis. + +#### 확인 후 기각한 lead +- NOSCRIPT 재로드 경쟁: NOSCRIPT = 미실행, `SCRIPT LOAD` idempotent, cluster에선 Lettuce advanced `scriptLoad`가 모든 master 전파. +- cluster 해시 태그·구분자 주입: 단일 키 스크립트; `CapabilityKeyspace.requireSegment`가 비-마지막 segment의 `:` 거부; digest 검증. +- KEYS는 policy에서 `BLOCKED`, region 무효화는 generation INCR. M9, M13/L3 closed 확인. +- 비밀 로깅: `RedisCredentials.toString` 마스킹, failure logger는 예외 클래스만. HARD-STOP 1-5 해당 없음. + +#### Coverage note +깊게: cache-redis main 전체, runtime owner/topology/auto-config/health/credential/keys, gateway script 메서드, 관련 테스트·fake 일부. 훑음: redis-sdk(policy yml, pub/sub, script 연산, connection registry), Lettuce gateway 데이터 명령. + +### Group H — Outbound HTTP client + messaging bridge adapters + +#### Per-leaf verdict +| leaf | verdict | one-line reason | +|---|---|---| +| `adapter/outbound/httpclient` | NEEDS_FIX | Dynamic Target sends trace headers to external hosts and skips redirect safety; custom API-key header not stripped on cross-origin redirect; reactive failures reported as NOT_SENT; OAuth2 token fetch blocks inside a map lock | +| `adapter/outbound/messaging` | NEEDS_FIX | Canonical bridge bean never created in the assembled app (auto-config ordering); fixing that breaks startup on the shipped default (blank `producer-id`) | +| `adapter/outbound/messaging-kafka` | PASS | Edges OK; only an interrupt-swallow (Consider) and javadoc drift (Nit) | + +HARD-STOP 1–5: none. All `project(...)` edges within `modules.json`. + +#### Findings (most severe first) + +1. **[Critical][correctness] Canonical bridge `@ConditionalOnBean` evaluated before the platform auto-config; blank `producer-id` breaks startup** — `src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/autoconfigure/MessagingBridgeRootAutoConfiguration.java:25,39-44` + - (a) `@AutoConfiguration` has no `after`/`afterName`. The `EncodedMessagePublisher` bean (`DefaultMessagePublisher`) is registered only in `MessagingCoreAutoConfiguration:461`, imported by `dev.caskeleton.messaging.autoconfigure.MessagingPlatformRootAutoConfiguration`. Boot's `AutoConfigurationSorter` sorts alphabetically first → `dev.caskeleton.adapter…` precedes `dev.caskeleton.messaging…` → `@ConditionalOnBean(EncodedMessagePublisher.class)` sees no definition yet. Neither class has `AutoConfigureAfter`/`Order` (grep). + - (b) `config/messaging.yml:15` `producer-id: ${APP_MESSAGING_PRODUCER_ID:}` always exists as an empty string; `@ConditionalOnProperty(name="producer-id")` treats `""` as "not false" and matches → `new ProducerId("")` → IAE at `ProducerId.java:16`. + - No test assembles both: `MessagingPlatformBridgeAutoConfigurationTest` uses `withBean(EncodedMessagePublisher)` (user bean, always first) and "property absent". + - Why it matters: docs (MSG-015) say the canonical bridge exists; in the real assembly `IntegrationEventPublishPort` is never created, and `canonical-transport-enabled=true` is refused by the validator (fail-closed, no data loss). Fixing (a) alone then breaks startup on defaults via (b). + - Fix: `@AutoConfiguration(afterName = "dev.caskeleton.messaging.autoconfigure.MessagingPlatformRootAutoConfiguration")`; producer-id condition → `@ConditionalOnExpression("!'${app.messaging.producer-id:}'.isBlank()")`; one `ApplicationContextRunner` test with starter + bridge (blank / set). + - Needs confirmation: Gradle not run; the assembly test confirms or refutes. + - Status: new + +2. **[Required][security] Dynamic Target sends `traceparent` and `X-Correlation-Id` to user-chosen external hosts even with `trace-propagation=false`** — `src/adapter/outbound/httpclient/.../dynamic/DefaultDynamicTargetGateway.java:154` + - Evidence: `prepare()` always calls `PlatformHeaderPropagation.apply(headers)`; no main code reads `DynamicTargetPolicy.tracePropagation` (grep: record, settings, test asserts only). `docs/httpclient/configuration-reference.md:178`: "Off by default for dynamic targets". + - Fix: `if (policy.tracePropagation()) headers = PlatformHeaderPropagation.apply(headers);` + absence test. + - Status: new (H4 fix added propagation unconditionally to the dynamic path) + +3. **[Required][security] Dynamic redirect loop bypasses `RedirectEvaluator`/`SensitiveHeaderStripper`** — `DefaultDynamicTargetGateway.java:121-136` + - Evidence: on 303 only `method = GET` changes and `operation.withMethod(...)` keeps the body (`HttpOperation.java:91-101`) — the bug `BlockingRedirectCoordinator.java:97-104` already fixed; no `BODY_NOT_REPLAYABLE` check on 307/308; caller headers (e.g. `X-Api-Key`, allowed by `HeaderPolicy`) forwarded cross-origin; no test calls `DefaultDynamicTargetGateway.exchange` (grep 0). + - Why it matters: `max-redirect-hops` is configurable (`HttpClientPlatformSettings.java:156`); enabling it sends POST payloads to an upstream-chosen host. + - Fix: reuse `RedirectEvaluator.evaluate` + `stripForCrossOrigin` per hop, `EmptyBody` on 303; redirect contract tests (303 body, 307 one-shot, cross-origin header). + - Status: new + +4. **[Required][security] Allowed API-key header `X-Client-Key` not stripped on cross-origin redirect** — `.../security/SensitiveHeaderStripper.java:23,47`, `.../restclient/BlockingExecutionSupport.java:90` + - Evidence: `ALLOWED_API_KEY_HEADERS = Set.of("X-Api-Key","Api-Key","X-Client-Key")` (`HttpClientAuthenticationAutoConfiguration.java:34-35`); the stripper in use is `standard()` which strips only `x-api-key`/`api-key`; `withAdditional` has no main caller; empty `allowedHosts` → `TrustedTargetPolicy.java:168` allows every host. + - Why it matters: a profile with `redirect.enabled` + `allow-cross-origin` leaks the secret to the redirect target (both default off). + - Fix: strip the actually resolved `RequestCredentials.headers().keySet()` on cross-origin hops; delete `withAdditional`. + - Status: new + +5. **[Required][correctness] Reactive path reports post-send failures as NOT_SENT / `HttpConnectException`** — `.../webclient/ReactiveAttemptExecutor.java:167`, `.../reactor/ReactorFailureClassifier.java:106-108`, `.../restclient/StableBlockingExceptionMapper.java:37` + - Evidence: `classify(failure, baseMetadata.stage())` always gets `VALIDATION` (`provesNotSent=true`); no `AttemptProgressTracker` on the reactive path (grep 0); unknown exceptions → `fallback` `notSent(UNKNOWN)` → mapper `default` → `HttpConnectException`. Examples: `DataBufferLimitException` from `DataBufferUtils.join` over `maxWireBytes` (`WebClientResponseMapper.java:33`; handled nowhere), mid-response `PrematureCloseException`; no reactive too-large / mid-body tests. + - Why it matters: NOT_SENT promises the server never received the request; callers re-send an executed POST → duplicate side effects. Breaks parity with blocking (H9 fixed blocking only). + - Fix: record stage inside `exchangeToMono` (`REQUEST_BODY` after send, `RESPONSE_HEADERS`/`RESPONSE_BODY` on receipt); map `DataBufferLimitException` → `HttpResponseTooLargeException`; mapper `default` → dedicated unknown type. + - Status: new + +6. **[Required][performance] OAuth2 token network fetch runs inside `ConcurrentHashMap.compute`** — `.../auth/OAuth2CredentialProvider.java:62-66`, `.../auth/SingleFlightTokenLoader.java:79-83` + - Evidence: `cache.compute(key, … tokenLoader.load(key))` holds the bin monitor up to 10 s; same-key/same-bin callers queue on the monitor instead of joining the single-flight future; after a timeout the next caller starts another 10 s load → Nth caller ≈ N×10 s. `SingleFlightTokenLoaderTest` tests the loader alone. Also: a timed-out caller calls `cancel(true)` on the shared future → late joiners get raw `CancellationException`; `CompletableFuture.cancel` does not interrupt → the 2-thread pool can stay blocked. + - Fix: `get` + expiry check, `tokenLoader.load` outside the lock, then `cache.put` (loader already dedupes); translate `CancellationException` → `HttpAuthenticationException`. + - Status: new + +7. **[Consider][structure] `categoryOf` duplicated as `getSimpleName()` string switches, already diverged** — `BlockingAttemptExecutor.java:292-312`, `ReactiveAttemptExecutor.java:183-199` (reactive lacks `HttpCircuitOpenException`/`RateLimitRejected`/`BulkheadRejected` though `ReactiveAttemptResiliencePipeline.java:57-70` throws them → telemetry `UNKNOWN`). Fix: `FailureCategory category()` on each `HttpClientException` subclass; delete both switches. + +8. **[Consider][error-handling] Bridge `prepare` turns every `RuntimeException` into `REJECTED_BEFORE_SEND` without a cause** — `.../platformbridge/PlatformIntegrationEventPublishAdapter.java:59-63`. Fix: narrow to `IllegalArgumentException`; carry cause via `OutboxRelayFailureReport` or `OutboxPublishRefusedException(outcome, cause)`. + +9. **[Consider][correctness] Kafka seam swallows `InterruptedException`** — `src/adapter/outbound/messaging-kafka/.../KafkaSenderAutoConfiguration.java:110` (`OutboxMessagePublishAdapter.java:94` → `AMBIGUOUS`, `OutboundMessagePublisher.java:36` logs and ignores → relay keeps processing during shutdown, up to 30 s per item). Fix: catch in the lambda, `Thread.currentThread().interrupt()`, rethrow. + +10. **[Nit][docs]** `src/README.md:320-345` describes activation via `ca-skeleton.capabilities.http-client` / `OutboundHttpSettings.bindLegacy` — actual `app.httpclient.enabled` (`HttpClientPlatformSettings.PREFIX`, `config/httpclient.yml:12`, `.env:236`); `OutboundHttpSettings` not in main. Kafka javadoc (`KafkaSender.java:7`, `KafkaAdapterConfig.java:14`) says the project must supply `KafkaSender` — the leaf supplies both; `KafkaAdapterSettings.addresses()` unused. + +#### Leads checked and dismissed +- README vs CLAUDE activation key: confirmed → #10 (code + CLAUDE correct). +- SSRF first line: userinfo rejected, IDN → punycode before allowlist, suffix at label boundary, all DNS answers validated, Apache socket pinned; DYNAMIC + JDK/Reactor/proxy refused at startup (`ClientProfileValidator:173-207`). +- Engine-level redirects disabled on all 4 transports; Apache auto-retry off; TLS hostname verification `BOTH` with no off switch. +- Retry idempotency: 408/425/429/5xx, write failure, timeout all gated by `safelyIdempotent`; negative `Retry-After` ignored. +- Blocking response size enforced while reading (`CountingBoundedInputStream`); no header/credential logging (0 loggers in main), redacted `toString`. +- C1-style component-scan bypass: exclusion regex in `CaSkeletonApplication.java:106,108` covers both packages. +- `OutboxEnvelopeJson` payload pre-validated by `OutboxPayloadPolicy.requireValidPayload`; `OutboxMessagePublishAdapter.java:78` `join()` bounded by platform `orTimeout`. +- Known-open: L5, L6 appear wired in code (not run-verified); M9 — no spring-kafka in `messaging-kafka` lock. + +#### Coverage note +Deep: messaging main autoconfigure/config/outbox/platformbridge/core/realtime; messaging-kafka main; httpclient `dynamic/*`, blocking/reactive executors, redirect, reader/limiter, header, stripper, OAuth2/single-flight, retry engine/backoff, Apache/Jetty factory + cited tests. Skimmed: messaging R1 compiler/envelope/schema; httpclient `service`/`spring7`/`migration`/`observation`/`profile`. #1 and #5 need an assembly test / reactive contract test to confirm. + +### Group I — Inbound HTTP (web) + +#### Leaf별 판정 +| leaf | 판정 | 한 줄 이유 | +|---|---|---| +| `adapter-inbound-web` (`src/adapter/inbound/web`) | **BLOCKED** | 인바운드 어댑터가 저장소 포트 직접 호출·트랜잭션 개시·객체 단위 인가 결정(HARD-STOP 4). 인증 없는 콜백은 본문 크기 제한 없이 수신. 에러 envelope 계약에 빈틈. | + +#### 발견 (심각한 순) + +1. **[Critical][architecture] durable-operation 조회/취소 유스케이스가 web 어댑터 안에 있고 운영에서 조립도 안 됨** — `src/adapter/inbound/web/.../operationasync/OperationQueryService.java:54-58,80`, `.../operationasync/OperationAccessPolicy.java:28-40` + - 근거: `OperationQueryService`가 `DurableOperationStorePort.find/cancel` 직접 호출, `transactions.inWrite(...)`로 트랜잭션 개시, `OperationAccessPolicy.mayAccess`로 principal/tenant 인가 판단 → AGENTS.md "repository 직접 호출과 비즈니스 정책 금지", CLAUDE.md 표는 authorization을 `application-core`에 둠. + - 조립 불가: `new OperationQueryService(`는 `testFixtures/.../OperationFixtureSupport.java:74`에만(운영 grep 0) → `app.web-platform.durable-operations.enabled=true`면 기동 실패. MVC에서 `WebMvcRequestContextHolder.store` 호출 0 → `WebMvcRequestContextArgumentResolver.java:40` `require`가 항상 예외. `OperationHttpController.java:75,100`의 `WebResourceNotVisibleException`은 opt-in problem 핸들러만 처리 → 기본 envelope 계약에선 catch-all **500**. 실서버 IT는 `OperationFixtureController.java:53`이 합성 context를 넣어 못 잡음(닫힌 H7과 같은 모양). + - 수정: find/cancel + 접근 정책을 `application-core` 유스케이스(`QueryDurableOperationUseCase`/`CancelDurableOperationUseCase`)로; 컨트롤러는 `Authentication` → command 매핑만; `GlobalExceptionHandler`에 `WebResourceNotVisibleException` → 404. 당장 쓸 계획이 없으면 MVC/Reactive 컨트롤러와 `operationasync` 삭제가 가장 작은 변경. + - 가정/반론: 가시성 판단 = 인가 정책 / `docs/web/repository-adaptation.md` §7이 HTTP projection을 web에 둠 — 단 저장소 호출·트랜잭션 조율까지는 아님. + - 상태: new (Group A #4와 같은 결함을 반대편에서 본 것) + +2. **[Required][security] 운영 servlet 앱에 요청 본문 상한 없음; 인증 없는 콜백이 본문 전체를 메모리에 읽은 뒤 크기 검사** — `.../notification/platform/callback/NotificationCallbackMvcController.java:85-87` + - 근거: `@RequestBody byte[] body` 후 `if (body.length > maxBodyBytes)` — Spring 컨버터(`readNBytes(contentLength)`/`readAllBytes()`)가 이미 전체 버퍼링. 경로는 `CallbackMvcSecurityConfiguration.java:31-35` `permitAll`. Reactive는 `BoundedCallbackBodyReader.java:30` `DataBufferUtils.join(..., maxBytes)`로 막음 — servlet만 누락. + - 근본 원인: `WebMvcBudgetFilter`는 fixture 앱에서만 생성(main grep 0); `backend.web.budgets.enabled=true`면 `WebMvcBudgetExceptionHandler`가 운영에 없는 `BudgetProblemMapper` 빈을 찾아 기동 실패; 그런데 `docs/web/repository-adaptation.md:158,160`은 본문 크기·JSON 깊이를 "Application, always"가 막는다고 기재. `NotificationCallbackMvcControllerTest.java:117-124`는 배열을 직접 넘겨 컨버터 경로 미검증. + - 영향: `APP_NOTIFICATION_PLATFORM_CALLBACKS_ENABLED=true`(기본 false, `notification.yml:44`)면 누구나 수 GB 본문으로 힙 고갈; 가상 스레드라 스레드 수 제한도 없음. + - 수정: 컨트롤러가 `HttpServletRequest`를 받아 `getContentLengthLong() > maxBodyBytes`면 413, 본문은 `getInputStream().readNBytes(maxBodyBytes + 1)`; 예산 필터를 유지하려면 `WebMvcPlatformAutoConfiguration`에서 등록, 아니면 문서 §8 정정. + - 상태: new + +3. **[Required][correctness] Envelope 에러 계약에서 `ProblemDetail`이 새어 나감** — `.../error/GlobalExceptionHandler.java:54,290-293` + - 근거: `ResponseEntityExceptionHandler`가 처리하는 예외 20종 중 8개 hook만 override → 나머지(`MissingServletRequestParameterException`, `MissingRequestHeaderException`, `MissingServletRequestPartException`, `HandlerMethodValidationException`, `ResponseStatusException`, `AsyncRequestTimeoutException`, `TypeMismatchException` 등)는 Spring 7.0.9 `handleExceptionInternal`(630-631)에서 `ProblemDetail` 본문; `EnvelopeBodyAdvice.java:45`는 `application/json`이 아니면 감싸지 않음 → `application/problem+json` 그대로 → README.md:168(D5 "ProblemDetail 거부")과 모순. 실제 경로: sample `PosterImagePublicationController.java:58-61` 필수 헤더 `Idempotency-Key`·필수 파라미터 누락. 이 예외들의 테스트 0건. 추가로 `handleMethodArgumentNotValid`는 `getFieldErrors()`만 → 클래스 레벨 제약 위반은 `details: []`. + - 수정: `handleExceptionInternal` 하나 override(status → `OperationalError`, `ErrorResponseFactory.body` 반환); `getGlobalErrors()`도 details에; 필수 파라미터/헤더 누락 slice 테스트. + - 상태: new (C2 종결 범위는 opt-in 핸들러까지) + +4. **[Required][correctness] `RequestLoggingFilter`가 Spring Security 뒤에서 돌고 trace id를 따로 생성** — `.../filter/RequestLoggingFilter.java:37,65-71,69` + - 근거: `@Component`에 `@Order` 없음 → LOWEST_PRECEDENCE, Security 체인(-100) 뒤. MDC가 이 필터 안에서만 채워짐 → `AuthErrorResponseWriter.java:46-70`의 401/403 응답 `meta` id 전부 null, 경고 로그에 request_id 없음, 해당 요청은 `http_request` 접근 로그도 없음. `:69`는 traceparent 없으면 새 값 생성 → `WebMvcRequestIdFilter.java:78-80`의 `WebTraceId`와 불일치(H1과 같은 모양, trace id 쪽). + - 수정: MDC 채우기를 security보다 앞의 `WebMvcRequestIdFilter`로 이동; 로깅 필터는 `WebTraceId`도 읽기; `OperationalContractRuntimeTest`에 "request-id 필터가 `springSecurityFilterChain`보다 앞" 단언. + - 상태: new (H1/H7 형제) + +5. **[Required][security] `FORWARDED_HEADERS_TRUSTED` 레이트리밋 키가 XFF 맨 왼쪽 값 사용, peer 검증 없음; forwarded 헤더 신뢰 판단이 네 벌** — `.../ratelimit/ForwardedHeaderClientIpResolver.java:15` + - 근거: `split(",", 2)[0]`, `getRemoteAddr()` 신뢰 프록시 확인 없음. 저장소 자체 `infra/fileserver/nginx/nginx.conf:44`가 `$proxy_add_x_forwarded_for`(뒤에 덧붙임) → 맨 왼쪽은 클라이언트가 정함 → 요청마다 새 버킷, 비인증 레이트리밋 우회. `RateLimitKeyResolverTest.java:79-86`이 이 동작을 정답으로 고정. 판단이 네 곳: `proxy/TrustedProxyPolicy`(CIDR, 운영 호출 0), `ExternalRequestUrlResolver`(정확 문자열 집합), 이 resolver(검증 없음), reactive 콜백 `NotificationCallbackWebFluxHandler.java:105`(`request.uri()` 그대로 → servlet과 서명 대상 URL 불일치). + - 수정: `TrustedProxyPolicy` 하나로 통일(XFF 오른쪽부터 첫 비신뢰 주소; peer 비신뢰면 remoteAddr). 더 간단: 이 모드 삭제 + `server.forward-headers-strategy=native`(Tomcat RemoteIpValve `internal-proxies`) + `REMOTE_ADDR_ONLY`. + - 가정/반론: 뒤에 덧붙이는 LB(ALB, nginx 기본) 뒤에서 켬 / 기본값 안전, 문서에 "덮어쓰는 ingress에서만". + - 상태: new (H3 종결은 서버 기본값만) + +6. **[Required][architecture] 알림 제출 정책 기본값을 컨트롤러가 결정(HARD-STOP 4 후보)** — `.../notification/platform/submission/NotificationSubmissionController.java:48-51,81-89,120-123` + - 근거: category 생략 → `"transactional"`, 템플릿 버전 `1`, locale `Locale.getDefault()`(호스트 JVM). category는 suppression 범위(`SuppressionEntry.java:53-54`, `CompositeNotificationEligibilityPolicy.java:40`)와 중복 제거 식별자에 들어감 → 생략 시 marketing suppression 미적용 = transport 계층의 비즈니스 결정. `NotificationTemplateController.java:74` `1L`도 같음. + - 수정: `AcceptNotificationCommand`에서 세 값을 `Optional`로, 기본값은 유스케이스가 설정값으로 적용. + - 가정/반론: category가 동의/suppression 기준(코드상 그러함) / 호출자가 명시적으로 "transactional"을 넘길 수 있음. 소유자가 정책으로 보면 Critical. + - 상태: new + +7. **[Required][docs/contract] `wire-type-manifest.yaml`이 런타임에 없는 wire 계약을 공개** — `.../main/resources/META-INF/web/wire-type-manifest.yaml:25-29` (`LONG: INTEGER_STRING`, `BIG_DECIMAL: DECIMAL_STRING`, ":4 client author가 읽는 계약"; 실제로는 숫자 — `JacksonSerializationPolicyTest.java:83-93`이 BigDecimal plain 숫자 단언, sample `StoredObjectResponse.java:4` `long size` 숫자; `WebWireTypeManifest` 빈은 생성만(`WebMvcPlatformAutoConfiguration.java:123-127`); 테스트는 상수=상수). 수정: yaml·빈·클래스 삭제(최소), 유지하려면 Jackson 모듈로 적용 + 실제 JsonMapper 테스트. 상태: new (lead 확인) + +8. **[Consider][structure] 운영 소비자 없는 라이브러리 코드가 많고 운영 경로와 중복** — main 67개 파일(약 5.7k LOC) 운영 참조 0(클래스명별 grep); 외부 importer 0 패키지: `security/`, `cache/`, `openapi/`, `idempotency/`; `security/WebCorsPolicyValidator`가 실제 `CorsSettings`보다 엄격한 규칙인데 미호출; `observability/WebAuditPublisher` 참조 0; `RateLimitInterceptor.disabled(...)` M2 이후 dead; `cursor/CursorCodec.withDevKey()` 키 하드코딩. 수정: 쓸 것은 조립, 나머지 삭제; CORS 규칙은 `CorsSettings`로 합치고 validator 삭제. 반론: M1 종결 때 LIBRARY_ONLY 수용. 일부 known-open L4/L5/L6. + +9. **[Consider][docs] 같은 코드 이름이 스위치에 따라 다른 status** — `problem-catalog.yaml:19-22` `VALIDATION_FAILED` 422 vs `OperationalError.java:15` 400; README D5에 opt-in problem 경로(`spring.mvc.problemdetails.enabled`) 미기재; reactive 핸들러도 `spring.mvc.*`로 켜짐(`WebFluxProblemExceptionHandler.java:44-45`); reactive 스택엔 envelope 핸들러가 없어 스위치 off면 Boot 기본 에러 JSON. 수정: README에 opt-in 경로 기재, 코드/status 정합, reactive는 `spring.webflux.problemdetails.enabled`. + +#### 확인 후 기각한 리드 +- problem-catalog 422 vs README 400: 의도된 opt-in 경로(C2 종결), 기본 계약은 400 → 남는 문서 문제는 #9. `application-web-contract.yaml` `problemdetails: true`: testFixtures 전용. +- CORS wildcard + credentials: `CorsSettings.java:32-37`에서 거부, `setAllowedOrigins` 정확 일치. +- HARD-STOP 2/3: web main에 JPA/Spring Data/outbound import 0; `ProviderCallbackHttpRequest`는 bootstrap bridge에서 매핑. 문제는 #1뿐. +- 의존 edge: `application-core`, `application-notification`, `shared-contract` 모두 허용; `web-fileserver`는 test 범위. +- 인증 쪽 필터 순서 정상(request-id HIGHEST+10 < security; 콜백 체인 `securityMatcher` 분리; `RestrictedPathRule`이 `anyRequest`보다 먼저). +- FYI: 레이트리밋이 HandlerInterceptor라 401 폭주는 제한 안 됨(README에 적힌 설계). +- C3(known-open) 이제 닫힘: systemTest/performanceTest/testFixtures 리소스 10개 추적, untracked 없음. +- JWT lazy decoder: Security 7.0.7 `SupplierJwtDecoder`가 `SingletonSupplier` → 가상 스레드 pinning 없음. + +#### 검토 범위 +자세히: `auth/`, `settings/`, `notification/platform/**`, `ratelimit/`, `error/GlobalExceptionHandler`, `envelope/`, `filter/`, `mvc/{autoconfigure,filter,operation,context,budget}`, `operationasync/`, `proxy/`, `webflux/autoconfigure` + 관련 테스트·fixture; Spring 7.0.9 / Security 7.0.7 소스로 동작 확인. 대충: `advanced/`, `pagination`, `conditional`, `openapi`, `moduleboundary`. + +### Group J — Inbound GraphQL + +#### Per-leaf verdict +| leaf | verdict | one-line reason | +|---|---|---| +| `adapter-inbound-graphql` (`src/adapter/inbound/graphql`) | **NEEDS_FIX** | No HARD-STOP. One Critical DoS: the wired authorization stage expands fragments exponentially before any budget check. 5 Required: `__typename` rejected, errors masked and never logged, two security flags look active but do nothing. | + +#### Findings (most severe first) + +1. **[Critical][security/perf] Authorization stage walks fragments exponentially with no budget, before the cost stage** — `src/adapter/inbound/graphql/.../runtime/GraphQlDocumentAuthorizationHandler.java:63,109-137`, `.../cost/GraphQlDocumentShapeAnalyzer.java:190-216` + - Evidence: chain order `stable(selection, authorization, cost)` (`GraphQlPlatformAutoConfiguration.java:403-408`). Authorization calls `verifyIntrospection` → `selectsIntrospection` (analyzer 209-214) and `collect` (handler 130-135); both only guard cycles by push/pop on `expansionPath`, no visit budget. Only `walk` in the cost stage has the 200k budget. Attack document `query{...F0} fragment F0 on Query{...F1 ...F1} … fragment F39 on Query{_health}` ≈ 1.6KB (under the 16KiB cap) = 2^40 visits. `maxFragments=50` checked later in the cost stage. graphql-java 25 dedupes fragments in validation/execution (`OverlappingFieldsCanBeMerged:101-111`, `FieldCollector:85-95`, `NoFragmentCycles` memo) → the document validates fast; the blowup exists only in platform code. + - Why it matters: one request pins a request thread indefinitely (deadline never checked inside the walk). Anonymous in LOCAL/DEV; any authenticated principal in prod. + - Fix: in both walkers replace the path Deque with a document-wide never-popped `Set visited` (results are set membership → same answers, linear walk), or run budgeted `analyze()` before authorization; systemTest with a 40× doubling fragment. + - Status: new (side effect of the GQL-007 fix) + +2. **[Required][correctness] `__typename` treated as introspection** — `.../cost/GraphQlDocumentShapeAnalyzer.java:40,199` + - Evidence: `startsWith("__")`; shipped default `introspection-enabled: false` (`app-bootstrap/.../config/graphql.yml:18`), forced off in prod (`GraphQlPlatformStartupValidator.java:43-45`); no `__typename` test. + - Why it matters: Apollo `addTypename` and urql's cache add `__typename` everywhere → all their queries rejected (`GRAPHQL_DOCUMENT_SHAPE_REJECTED/INTROSPECTION`). Spring/graphql-java introspection-off blocks only `__schema`/`__type`. + - Fix: block only `__schema`/`__type`; systemTest `{ _health __typename }` succeeds with introspection off. + - Status: new + +3. **[Required][correctness/ops] Every failure masked, none logged** + - Evidence: `GraphQlExceptionResolver.java:55` always returns the masked error → Spring treats it as resolved and logs only at DEBUG (`spring-graphql 2.0.5 ExceptionResolversExceptionHandler:99-101`); `GraphQlPlatformWebInterceptor.java:94`, `GraphQlPlatformInstrumentation.java:84` convert unknown RuntimeExceptions without logging; `grep -rl 'LoggerFactory|getLogger|System.Logger'` over main → 0 files, yet Javadoc says "the detail stays in the logs" (`GraphQlWireErrorMapper.java:30`, `GraphQlPlatformRejectionMapper.java:28`). + - Why it matters: a prod NPE/DB error leaves no trace; the executionId the client gets matches nothing. + - Fix: log once at ERROR with executionId + exception on the masking branch. + - Status: new + +4. **[Required][correctness] Wired DataLoader path and blocking bridge errors reach the client as `INTERNAL_ERROR`** — `.../runtime/GraphQlPlatformRejectionMapper.java:114-121` + - Evidence: `GraphQlBatchTimeoutException`, `GraphQlMissingKeyException`, `GraphQlBlockingBridgeFullException` declare `CODE`s unknown to mapper and catalogue; `GraphQlErrorCodeCatalogTest.java:54-60` calls batch timeout "modelled-only" while `CLAUDE.md:171` marks DataLoader `wired`; bridge-full goes through Reactor `ExecutorScheduler.schedule` → `Schedulers.handleError` (ERROR log / uncaught handler on every rejection) → arrives wrapped in `RejectedExecutionException`; tests only assert `getErrors().isNotEmpty()` (`GraphQlBatchLoaderRegistrationTest.java:150`). + - Fix: `GraphQlBatchTimeoutException extends GraphQlRequestCancelledException`; unwrap bridge-full → `DEPENDENCY_UNAVAILABLE`; assert wire codes. + - Status: new (gap in M1 closure) + +5. **[Required][security] Stable extensions allowlist accepts `idempotencyKey`, which nothing honours** — `.../http/GraphQlExtensionsPolicy.java:44` (only consumer `mutation/GraphQlMutationIdempotencyInterceptor.java:48` is not on the request path). Why: retrying clients believe retries are deduplicated; the mutation runs twice. Fix: `stableDefaults()` → `none()` until wired. Status: new (side effect of M6 closure) + +6. **[Required][security] `GraphQlClientPolicy.persistedOperationOnly` does nothing** — `.../policy/GraphQlClientPolicy.java:50` (`grep -rn 'persistedOperationOnly()'` → only `GraphQlClientPolicyTest:75` getter assert). Why: adopter sets true, arbitrary documents still execute (fail-open allow-list bypass). Fix: remove the field or reject `true` in the compact constructor until wired. Status: new + +7. **[Consider][perf] Preparsed cache scans every entry under a global lock per lookup** — `.../execution/BoundedPreparsedDocumentProvider.java:142,167-178` (`expireIdle` iterates the whole map, default 1000). Fix: access-ordered `LinkedHashMap` → stop at first unexpired entry. Counter: tens of µs at 1000 entries. + +8. **[Consider][security] Root type names hard-coded for authorization** — `.../runtime/GraphQlDocumentAuthorizationHandler.java:80-83` (literals "Query/Mutation/Subscription" vs cost stage `schema.getQueryType()` at `GraphQlDocumentComplexityScorer.java:258-260`; renamed roots → rules never match, `denyByDefault(false)` allow rules fail open). Fix: names from `context.schema()`. + +9. **[Consider][correctness] Streaming path of the body-cap filter untested** — `.../runtime/servlet/GraphQlRequestBodyLimitFilter.java:85` (systemTest `GraphQlPlatformExecutionPathTest:224-241` covers only Content-Length fast path; `FrameworkServlet` likely wraps unresolved RuntimeException in `ServletException` → `catch (BodyTooLargeException)` misses → 500 instead of 413; unverified; cap itself holds). Fix: chunked-transfer test, catch via cause chain. + +10. **[Consider][structure] ~57% of the code unreachable** (known-open GQL-025) — static reference closure from the four Spring entry points reaches **136 of 400 files / 11.2k of 25.9k LOC**. Candidates: `advanced/**` 134 files / 5,986 LOC (nothing outside references it, nothing binds `GraphQlAdvancedFeatureFlags`); packages `compat` 1,562, `release` 540, `fetch` 434, `mutation` 683 LOC; unreachable classes in wired packages — parallel HTTP layer in `http/` (11 classes: `GraphQlRequestEnvelopeValidator`, `GraphQlHttpResponseFactory`, `StatusMapper`, `MediaTypes`, …), `error/GraphQlRequestErrorMapper` (second error vocabulary), `autoconfigure/GraphQlPlatformActuatorEndpoint` + `…ConfigurationReport` (not beans), 16 of 19 `schema/` files; `moduleboundary/` (535 LOC) test-only data in the production jar. Fix: delete or move to a non-shipped artifact (keep `pagination` if wanted). Counter: earlier review judged them tested parts awaiting wiring. + +11. **[Consider][docs]** `CLAUDE.md:168` marks Accept negotiation `wired` (`GraphQlMediaTypes` unreachable, unit test only); `CLAUDE.md:59,132-133`, `README.md:46-61` describe non-existent `GraphqlExceptionResolver` and "return null → Spring default" (reality: everything masked). Fix: grade `modelled`, document current resolver + masking. + +12. **[Consider][ops] Production boots with the anonymous principal resolver, then refuses every request** — `.../autoconfigure/GraphQlPlatformAutoConfiguration.java:319` (prod requires a `GraphQlAuthorizationPolicy` bean but not a `GraphQlPrincipalResolver` → startup OK, 100% `AUTHENTICATION_REQUIRED`). Fix: startup validator fails in prod without a principal resolver bean. + +#### Leads checked and dismissed +- HARD-STOP 1-5: edges `shared-contract` + `application-core` only; no persistence/Spring Data imports; no GraphQL types in application-core/domain-core/shared-contract. +- No internal detail leaks (allowlist + masking). `GraphQlBlockingBridge` pool and queue finite, opt-in (Nit: thread factory always names `-0`, `GraphQlBlockingBridge.java:56`). +- Subscription lease/backpressure and `advanced/persisted` bypass: modelled only, not on request path; lease release idempotent (CAS). +- Preparsed cache key uses server-side client profile + memoized schema hash → no cross-profile leak. BigDecimal expansion bounded (`GraphQlDecimalBounds`); `GraphQlRequestSize` recursion bounded by Jackson depth. +- H1-H3, M1-M7: no regressions. + +#### Coverage note +Read in full: wired path (`GraphQlPlatformAutoConfiguration`, all `runtime/*` incl. servlet filter), `cost/GraphQlDocumentShapeAnalyzer`, DataLoader executor/factory, `error/*`, client/extensions/authorization policies, preparsed cache, related tests/systemTests; checked graphql-java 25, spring-graphql 2.0.5, reactor 3.8.7 sources. Skimmed: `advanced/*` (except persisted + subscription lease), `compat`, `release`, `fetch`, `mutation`, `pagination`, `schema`, `observation`, `scalar`. Reachability computed with an inline script. + +### Group K — Inbound realtime (WebSocket) + gRPC adapter + +#### Per-leaf verdict +| leaf | verdict | one-line reason | +|---|---|---| +| `adapter-inbound-websocket` | NEEDS_FIX | No HARD-STOP; the live STOMP channel is sound. The platform library breaks advertised guarantees (authentication, size limits, backpressure, shutdown ordering, concurrency) — none has a production caller yet. | +| `adapter-inbound-grpc` | NEEDS_FIX | Deny-by-default config and error cleanup solid, but the exception interceptor drops `onComplete` and late `onCancel`. | + +#### Findings (most severe first) + +1. **[Required][security] `HandshakeAdmissionPipeline` admits cookie/bearer handshakes on header presence alone** — `src/adapter/inbound/websocket/.../handshake/HandshakeAdmissionPipeline.java:131-136,140-144` + - Evidence: `request.bearerToken().isPresent() ? Optional.of(anonymousReference())` (cookie branch the same); every caller gets the fixed actor `"0".repeat(64)`; comment says "the runtime replaces" it — nothing does. `grep -rn 'HandshakeAdmissionPipeline\|\.admit(' main` → no callers outside the class; no `BEARER_HEADER` test. + - Why it matters: `HandshakeDecision.actor` documented as "who is connecting" — any `Authorization: Bearer x` is admitted; all users collapse into one actor (`maxConnectionsPerActor=4` becomes node-wide 4). + - Fix: required `WebSocketCredentialVerifier` constructor parameter for COOKIE/BEARER; refuse 401 when absent. + - Assumption / Counterargument: adopters call `admit()` without separate verification / Javadoc says verification is the security integration's job — but the return type means "verified". + - Status: new + +2. **[Required][correctness/security] Message/fragment limits never enforced on the servlet runtime** — `.../servlet/PlatformWebSocketHandler.java:37,84`, `.../inbound/FragmentAssembler.java:75` + - Rule → Evidence: no `supportsPartialMessages()` override → Spring default `false` → `MessageHandler.Whole`, `isLast()` always true → `FragmentAssembler` returns early, never enforces `maxMessageBytes`/`maxFragments`; effective limit is Tomcat's 8 KiB default (no `maxTextMessageBufferSize`, grep 0). `WebSocketRuntimeContract.oversizedMessageClosesWith1009` passes only via the frame check. `:75` compares UTF-16 char counts against a byte budget. + - Fix: `supportsPartialMessages() { return true; }`; composition sets container buffer to `maxFrameBytes`; running UTF-8 byte count; fragmented-message runtime test. + - Status: new + +3. **[Required][performance/security] `ReactiveFrameSink` buffer is unbounded, contradicting its own comment** — `.../webflux/ReactiveFrameSink.java:41-43` + - Rule → Evidence: `Sinks.many().unicast().onBackpressureBuffer()` → reactor-core 3.8.7 `Queues.unbounded()`; `tryEmitNext` never fails, `write()` returns immediately, `releaseInFlight` returns both reservations → per-connection and node budgets do nothing on the reactive stack. No callers, no tests. + - Fix: bounded `onBackpressureBuffer(Queues.get(n).get())` + slow-consumer test, or delete until the reactive stack is assembled. + - Status: new + +4. **[Required][correctness] `SerializedOutboundWriter.drain()` can strand a message** — `.../outbound/SerializedOutboundWriter.java:110-127,156-158` + - Race: A polls empty, releases `queueLock`, still holds `writeLock`; B enqueues, `tryLock()` fails; A unlocks → B's message waits for an unrelated future offer. Javadoc `:106-108` ("nothing is stranded") false; `SerializedOutboundWriterTest.java:110` hides it by calling `drain()` manually. + - Fix: after `writeLock.unlock()` recheck `queue.size()>0` under `queueLock` and loop (or WIP counter); remove the manual drain from the test. + - Status: new + +5. **[Required][correctness] `PlatformWebSocketHandler.stop()` runs after the web server stops** — `.../servlet/PlatformWebSocketHandler.java:162-167` + - Rule → Evidence: `getPhase()` = `Integer.MIN_VALUE + 1` ("Stopped before the web server"); Spring stops higher phases first; Boot 4.0.8 `GRACEFUL_SHUTDOWN_PHASE = MAX-1024`, `START_STOP_LIFECYCLE_PHASE = MAX-2048` → this bean stops last, promised 1001 never sent. `TomcatWebSocketAbuseIT.java:71` calls `stop()` directly. + - Fix: phase above `GRACEFUL_SHUTDOWN_PHASE` (e.g. `SmartLifecycle.DEFAULT_PHASE`); IT closes the context. + - Status: new + +6. **[Required][correctness] gRPC exception interceptor drops `onComplete` and late `onCancel`** — `src/adapter/inbound/grpc/.../GrpcExceptionHandlingInterceptor.java:72-86,95-97` + - Rule → Evidence: `close()` sets `closed=true` on every close incl. OK; `runGuarded` returns early when closed → transport's `onComplete`/`onCancel` swallowed → grpc-stub 1.68.1 `ServerCalls` never runs `onCloseHandler`/`onCancelHandler` (`:193-215,277-307`) → streaming cleanup/metrics hooks broken. No test. + - Fix: always pass `onComplete`/`onCancel` through (try/catch only); keep the gate for `onMessage`/`onHalfClose`/`onReady`; wire test asserting `setOnCloseHandler` runs. + - Status: new + +7. **[Required][correctness] `WebSocketSessionRegistry` register/deregister race breaks the per-actor cap** — `.../session/WebSocketSessionRegistry.java:63-64,94-100` + - Race: register gets map M via `computeIfAbsent`; concurrent deregister empties M and `byActor.remove(actor, M)`; register inserts into detached M → `connectionsOf` misses it, next register creates M2 → cap exceeded. `countByEndpoint` (`:75`) same race. Test only runs concurrent registers. + - Fix: register via `byActor.compute(...)` (atomic check+insert); deregister via `computeIfPresent(... isEmpty ? null : held)`; `compute`/`merge` for endpoint counter. + - Status: new + +8. **[Consider][correctness] Conflation replacement skips the per-connection bound; loss reported as success** — `.../outbound/OutboundQueue.java:78-79,193-210` (`replace` only checks `globalBudget.reserve`; on failure both values dropped but `offer` returns `CONFLATED`). Fix: same local check as `offer`, return `DROPPED`. Assumption/Counter: conflated values can grow / typical conflatable payloads fixed-size. + +9. **[Consider][performance] `WebSocketCorrelationRegistry.countFor` scans all node in-flight entries per request** — `.../handler/WebSocketCorrelationRegistry.java:90,116-122` (O(total in-flight), check+insert not atomic). Fix: per-connection nested map and `size()`. + +10. **[Consider][security] gRPC authentication policy is yes/no and swallows exceptions silently** — `.../GrpcAuthenticationInterceptor.java:35-41` (`boolean isAuthenticated(Metadata)`, no `Context` identity, `catch (RuntimeException ignored)`). Fix: `Optional authenticate(Metadata)` + `Context.Key`; WARN log without credentials. Counter: P1 is loopback-only. + +11. **[Consider][performance] Live STOMP channel uses Spring's unbounded defaults** — `.../stomp/WebSocketConfig.java:57-66`, `.../stomp/LiveEventStompBroadcaster.java:174-208` (inbound `ThreadPoolTaskExecutor` `queueCapacity` = `Integer.MAX_VALUE`; synchronous `@EventListener` O(subscribers) fan-out on the publishing thread). Fix: set `queueCapacity` for inbound/outbound channels. Counter: docs label R1 best-effort. + +12. **[Nit][docs]** `moduleboundary/WebSocketStableModule.java:89-90` duplicated `HANDSHAKE` Javadoc (known-open L3); both leaves' `CLAUDE.md` say Boot 4.0.0 (catalog: 4.0.8). + +#### Leads checked and dismissed +- HARD-STOP 1-5: websocket imports only `application.realtime.*` ports and `@DomainEvent`; gRPC only `shared.error.*`; edges match modules.json. +- gRPC interceptor order: authentication outermost — correct. TLS/deadlines/external bind: documented P2; loopback enforced by `@AssertTrue`. +- STOMP authz: SUBSCRIBE exact match, SEND limited to `/app/`, `/app/../topic` does not reach broker; origin config rejects wildcards. +- `ResumeTokenCodec` constant-time compare + expiry after signature. Rollback phantom events documented P2. M4 no regression. `LateResponseTombstone`/`FanoutDeduplicator` have eviction. + +#### Coverage note +Read in full: entire gRPC main tree, STOMP scope, advanced STOMP/SockJS/Rabbit configs, safety configs, outbound, servlet, handshake, session, inbound, webflux sink + related tests; checked grpc-java/Spring/Reactor sources. Skimmed: codec/cbor/protobuf, evidence, release, presence, cluster, graphql-bridge. + +### Group L — Composition root + sample consumer + +Path shorthand: `B/` = `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/`, `BR/` = `src/app-bootstrap/src/main/resources/`, `S/` = `src/sample-portfolio/`. + +#### Per-leaf verdict +| leaf | verdict | one-line reason | +|---|---|---| +| app-bootstrap | NEEDS_FIX | Outbox relay only scheduled when idempotency=jdbc (Critical); the prod block on error-detail exposure exists in docs, not code. | +| sample-portfolio | NEEDS_FIX | Actuator loggers accept unauthenticated writes; sample dropped out of the central ArchUnit suite and its replacement has only 3 rules. | + +#### Findings (most severe first) + +1. **[Critical][correctness] Outbox relay never runs unless idempotency provider = jdbc** — `B/autoconfigure/outbox/OutboxRelayScheduler.java:36`, `B/autoconfigure/idempotency/IdempotencyConfig.java:17-19` + - Evidence: grep of all `src` for `EnableScheduling|ScheduledAnnotationBeanPostProcessor|SchedulingConfigurer` → in production code only the sample, `composition/fileserver-platform` (not shipped) and `IdempotencyConfig`, which is `@ConditionalOnProperty(...idempotency.provider, havingValue="jdbc")` with default `disabled` (`BR/config/capabilities.yml:30`). The relay is `@Scheduled` (`OutboxRelayScheduler.java:36`); `OutboxReaper` (persistence-jpa `OutboxReaper.java:39`) too. `BootstrapCapabilityReachabilitySystemTest` enables outbox only with `relay-enabled=false` and checks the scheduling processor only in the jdbc-idempotency case. + - Why it matters: outbox + relay-enabled + a broker (the documented fork path) with idempotency disabled/redis/postgresql → relay bean created, never runs; events pile up PENDING, nothing logged. + - Fix: `@EnableScheduling` on `OutboxConfig` (already gated by `ca-skeleton.outbox.enabled`); one `ApplicationContextRunner` test: outbox+relay on, idempotency=disabled → `SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME` exists. + - Status: new + +2. **[Required][security] Prod profile claims error details are blocked; no code checks it** — `BR/application-prod.yml:13` + - Evidence: comment "`StartupSafetyValidator` error-detail exposure and body-capture logging stay off"; `B/runtime/StartupSafetyValidator.java:30-32` only calls `validateMultiInstance()` (`validateProdSafety` deleted in 9da00eb7; the deleted `APP_ERROR_DETAIL_EXPOSURE_ENABLED` toggle was a no-op anyway). `BR/application.yml:26,28` lets `spring.web.error.include-stacktrace/include-message` be env-overridden in prod; grep `include-stacktrace` → only yml/.env/README; no custom `ErrorController`/`ErrorAttributes` → Boot `BasicErrorController` owns `/error`. Same false claim in `src/app-bootstrap/README.md:280-281` (contradicts `:785-788`), `src/README.md:219,223` ("5종"), `BR/config/runtime.yml:10-12`. + - Why it matters: `APP_SERVER_ERROR_INCLUDE_STACKTRACE=always` in prod boots fine while docs say it is blocked. + - Fix: one prod validator shaped like `JpaSchemaSafetyValidator` (exit 71 when `include-stacktrace`/`include-message` ≠ `never` or `include-exception=true`), registered in `RuntimeSafetyConfig`; fix the 4 doc locations. Unchecked: whether `/error` body is envelope-wrapped. + - Status: new + +3. **[Required][security] Anyone can change the sample app's log levels without auth** — `S/src/main/resources/application.yml:94` + - Evidence: exposure `include: ...,loggers`, `management.endpoint.loggers.access` unset (unrestricted); `S/.../bootstrap/security/SamplePublicAccessSecurityConfig.java:24-27` `securityMatcher("/**")` + `csrf.disable()` + `permitAll()` at `@Order(-100)`; `SampleManagementSecurityConfig.java:24-27` also permitAll; `src/Dockerfile.sample:131` `EXPOSE 8080 9001`. + - Why it matters: unauthenticated `POST /actuator/loggers/{name}` → TRACE (data leak) or OFF. Production denies this in `ManagementSecurityConfig`. + - Fix: `management.endpoint.loggers.access: read-only`. + - Status: new + +4. **[Required][architecture/tests] Sample left the central ArchUnit suite; replacement does not cover HARD-STOP 2/3** — `S/src/test/java/dev/caskeleton/sample/portfolio/architecture/SampleArchitectureTest.java:25-69` + - Evidence: ace8aaae deleted `sampleFixture project(':sample-portfolio')` (was `build.gradle:179` at 944a1e34); current `src/app-bootstrap/build.gradle` has 0 sample references → `DOMAIN_IS_PURE`, `WEB_DTOS_STAY_IN_WEB_ADAPTER`, `CONTROLLERS_DO_NOT_ACCESS_REPOSITORIES_OR_JPA_ENTITIES`, `APPLICATION_METHODS_DO_NOT_ACCEPT_WEB_DTOS` no longer see the sample. Replacement has 3 rules (framework bans for domain/application; web → sample persistence). Missing: domain → application/adapter/bootstrap; application → `..adapter.inbound.web..dto..`; controller → `org.springframework.data..`/`jakarta.persistence..`. Current code is clean (0 such imports). `S/CLAUDE.md:38-41` cites a non-existent rule `production_code_does_not_depend_on_sample_portfolio`. Also to check: `adapter:inbound:grpc` not on the architectureTest classpath and has 0 ArchUnit tests. + - Fix: add the 3 `noClasses()` rules or `architectureTestRuntimeOnly project(':sample-portfolio')`; fix CLAUDE.md. + - Assumption / Counterargument: sample is the reference adopters copy (README/CLAUDE say so) / disposable fixture. + - Status: new (regression from ace8aaae) + +5. **[Consider][structure] The remaining `StartupSafetyValidator` check can never fail** — `B/runtime/StartupSafetyValidator.java:42-61` (`B/autoconfigure/lock/DistributedLockConfig.java:23-29` creates `distributedLockProvider` under the same condition; missing dependency fails bean creation first; `CapabilityDependencyValidator.java:100-105` already requires JPA). Fix: delete it and the `RuntimeSafetyConfig.java:16-20` bean; #2's validator replaces it. + +6. **[Consider][structure] Relational-dependency list lives in two places and has drifted** — `B/autoconfigure/jpa/DataSourceRequirement.java:28-60` vs `B/activation/CapabilityDependencyValidator.java:57-116` (Fileserver entry `:52-58` missing from the validator → fileserver on + JPA off likely fails with a missing-bean error not naming the switch, unverified; `B/runtime/SecretSourceValidator.java:39-40,93-101` always requires `APP_DATASOURCE_PASSWORD` even for a no-DB prod deployment). Fix: when `!jpa`, reject each `DataSourceRequirement.reasons(env)` (removes 4 ifs); require DB password only when `isRequired(env)`. + +7. **[Consider][security/tests] Actuator endpoints that require login cannot be reached** — `B/management/security/ManagementSecurityConfig.java:25-54` (no `oauth2ResourceServer`/`httpBasic` on the actuator chain → `loggers` GET and `show-details: when-authorized` (`BR/config/observability.yml:45`) unreachable with any credential; `ActuatorSecurityHttpTest.java:95-96` injects `.with(user("ops"))` and asserts 200). Fix: drop `loggers` + `show-details: never`, or add `.oauth2ResourceServer(jwt())` and test with a real bearer token. Counter: fails closed. + +8. **[Consider][sample] Sample defaults to schema settings prod forbids** — `S/src/main/resources/application.yml:45,53` (`out-of-order: true`, `ddl-auto: ...:update` on a Flyway-owned schema; `BR/application-local.yml:79-83` records this combination hid 2 mapping/migration mismatches). Fix: `validate`, `out-of-order: false`. + +9. **[Nit][structure]** `B/autoconfigure/notification/NotificationApplicationCompositionAutoConfiguration.java` has 12 `@Bean`s (leaf CLAUDE.md: split at ~8), orphaned Javadoc at `:80-90`, many inline FQNs → split into submission/admin/dispatch/callback. + +10. **[Nit][docs]** `BR/config/outbox.yml:7-8` says "Bound into OutboxProperties" and "NO env placeholders" (actual `OutboxSettings`, placeholders at `:18,19,22`); `BR/config/idempotency.yml:8` names non-existent `IdempotencyProperties` (→ `IdempotencySettings`); `src/app-bootstrap/README.md:7` "19개 leaf" (registry: 73; stated counts are defects); `src/app-bootstrap/CLAUDE.md:80,89` point to deleted `RedisCapabilityConfig`/`RedisKeys` in bootstrap; `S/README.md:418-420,434-437` describe the deleted `TestEnclosedConfigurationFilter` and a two-location customizer; `src/app-bootstrap/build.gradle:90-92` orphaned comment. + +11. **[Nit][tests]** `src/app-bootstrap/src/test/resources/application-test.yml:113-117` sets `ca-skeleton.rate-limit.*` but the binder is `app.rate-limit` (`EdgeRateLimitTransportSettings.java:14`) — same in sample `application.yml:187-192`; `:112`/`:124` pair `api-base-path: ""` with `/api/healthcheck` (harmless, `addFilters=false`); `developer-experience/broken-readme.md` referenced by nothing (grep `broken-readme|definitelyMissingDxTask` → only itself) — delete. + +#### Leads checked and dismissed +- All seven graph-pass leads confirmed; doc/test ones are #10/#11, the `StartupSafetyValidator` false assurance is #2. +- No sample leak into production (no `allowed_dependencies` or production build.gradle reference). +- `ProviderCallbackIngressBridge.java:43-88` deliberately closed as Core C2. 0-B `PersistenceJpaRootAutoConfiguration` internal-name reference resolved. +- Deleted Outbox/DistributedLock/IdempotencyUniqueScope contract tests moved to persistence-jpa `postgresqlIntegrationTest`. +- Sample systemTest idempotency regression looks fixed (provider=jdbc in `S/src/main/resources/application.yml:176-177` and systemTest `application-test.yml:105-106`; not run). +- H5 commit inclusion can be closed (`git status --short src/app-bootstrap src/sample-portfolio` empty). `build.gradle:119-122` "Shipped so an operator can enable it" comment is known-open 0-A #2. + +#### Coverage note +Deep: app-bootstrap main activation, runtime, outbox, idempotency, lock, notification, security, management; every `application*.yml`, `config/*.yml`, logback file; build.gradle; key ArchUnit declarations; sample entry point, bootstrap config, yml, ArchUnit test, relevant README/CLAUDE sections. Skimmed: tracing/logging/metrics code, test bodies, sample domain/application bodies (boundaries checked by grep). + +### Group M — Vendored messaging platform (`messaging:*`) + +#### Per-leaf verdict +| leaf | verdict | 한 줄 사유 | +|---|---|---| +| messaging-core-api | PASS | 문제 없음. 쓰이지 않는 타입 잔존 (#9) | +| messaging-schema-api / -json / -avro / -protobuf | PASS | codec decode 크기 제한 있음 (avro/protobuf 훑음) | +| messaging-cloudevents | PASS | 훑음. starter runtime 잔존은 known-open M13 | +| messaging-policy | NEEDS_FIX | `DeadLetterOrchestrator`가 인코딩된 envelope을 `publish`로 넘김 (#1) | +| messaging-transport-spi | PASS | 미사용 `MessagingLifecycle` (#9) | +| messaging-runtime-core | NEEDS_FIX | #1 원인 지점, #4, #5 | +| messaging-observability | PASS | 훑음 | +| messaging-security | PASS | leaf 자체 이상 없음; 적용 누락은 #2 | +| messaging-kafka | NEEDS_FIX | #2, #3(H6 회귀), #7 | +| messaging-kafka-share-experimental | PASS | 훑음; 옛 prefix 오류 메시지 (#8) | +| messaging-rabbit | PASS | 선택 경로가 막혀 도달 불가; #10 | +| messaging-reliability-api | PASS | — | +| messaging-outbox-jdbc-postgresql | NEEDS_FIX | #1, #4, #6 | +| messaging-inbox-jdbc-postgresql | NEEDS_FIX | #6 | +| messaging-claim-check | PASS | 조립처 없음; 무결성 검사 fail-closed | +| messaging-admin-api / -admin-runtime | PASS | HMAC 상수시간 비교, plan digest·operation·source 바인딩 | +| messaging-pulsar/nats-experimental | PASS | 훑음; SDK 없음, 기본 runtime classpath에 없음 | +| messaging-spring-cloud-stream-bridge | PASS | 훑음; prefix drift (#8) | +| messaging-spring-boot-starter | NEEDS_FIX | #1 조립, #5, #8 | +| messaging-spring-boot-starter-kafka | NEEDS_FIX | #2, #5 | +| messaging-spring-boot-starter-rabbit | PASS | validator만, broker 선택은 startup에서 거부 | +| messaging-testkit | PASS | — | + +실험 leaf 기본 runtime 포함 여부: starter 의존 목록에 없고 `app-bootstrap/gradle.lockfile`에 pulsar/nats/kafka-share 없음. `kafka-clients`는 test/architecture classpath에만(lockfile:203). + +#### Findings (심각도 순) + +1. **[Critical][correctness] 플랫폼 내부 재발행 경로가 이미 인코딩된 payload를 다시 인코딩 → 전부 REJECTED** — `src/messaging/messaging-outbox-jdbc-postgresql/.../OutboxRelay.java:223-229` + - Evidence: `OutboxRelay.publish`, `DeadLetterOrchestrator.java:101-104`, `KafkaRetryTopicPublisher.java:68-70` 세 곳이 `MessageEnvelope`를 `MessagePublisher.publish`로 넘김. 자동 조립 구현 `DefaultMessagePublisher`(`MessagingCoreAutoConfiguration.java:459-477`)는 `encode(message)` 무조건 호출(`DefaultMessagePublisher.java:177,303-308`) → `JacksonMessageCodec.encode`의 `registered.isInstance(payload)` 실패 → `PAYLOAD_TYPE_MISMATCH`(`JacksonMessageCodec.java:115-119`) → `PUBLISH_PREPARATION_FAILED`=REJECTED(`:178-179`) → relay가 `markFailed`로 terminal(`OutboxRelay.java:204-211`). bridge는 `publishEncoded`로 고쳐졌으나 이 세 곳은 아님. 관련 테스트(`OutboxRelayTest.java:416`, `DeadLetterOrchestratorTest`)는 가짜 publisher. + - Why: platform outbox를 켜면 모든 row FAILED — business commit은 성공, 메시지는 0건. DLQ publish도 confirm 없이 영원히 requeue. + - Fix: 세 호출자를 `EncodedMessagePublisher.publishEncoded`로(`messaging-schema-api` edge 허용됨); relay 뒤에 실제 `DefaultMessagePublisher`를 붙인 테스트. + - Status: new + +2. **[Critical][security] 검증은 통과시키는 broker 보안 설정이 실제 producer에 적용 안 됨** — `src/messaging/messaging-spring-boot-starter-kafka/.../KafkaMessagingAutoConfiguration.java:128-154` + - Evidence: producer bean은 `spring.kafka.bootstrap-servers`, serializer, acks, idempotence만 설정; `KafkaSecurityConfigurer.configure` 호출 0건(bean 생성 `:109-111`뿐) → `app.messaging.security.` TLS/SASL, `app.messaging.brokers..bootstrap-servers` 미사용. per-broker `access.publishable`는 compile만(`MessagingConfigurationCompiler.java:243-246`), 실제 publish 판정은 `DeclaredDestinationAccess.of(destinations.all())`(`MessagingCoreAutoConfiguration.java:414-419`). configurer를 연결해도 SASL username에 credential 참조 id가 들어감(`KafkaSecurityConfigurer.java:149-151`). + - Why: production profile이 `TLS_REQUIRED`·credential-provider 검사를 통과하지만 실제 연결은 PLAINTEXT·무인증. 보안을 검증했다는 결과만 남음. + - Fix: producer config를 compile된 `KafkaBrokerProfile` + `BrokerSecurityProfile`에서 만들고 `KafkaSecurityConfigurer`로 병합, 하나라도 없으면 startup 실패; ACL은 `DestinationAccessPolicy`에 교집합; username은 provider가 반환. + - Status: new (bootstrap 중복은 10-messaging §8-2에서 번호 없이 언급) + +3. **[Required][correctness] handler timeout 시 취소가 아무것도 멈추지 않음** — `src/messaging/messaging-kafka/.../KafkaConsumerRegistrar.java:313-329` + - Evidence: `CompletableFuture.cancel(true)`는 실행 중 작업을 인터럽트하지 않고 완료 전이면 항상 true → `!cancel && !isDone` 분기 도달 불가 → permit 즉시 반환 → `requeueAfterFailure`가 같은 offset 재읽기 → 첫 handler가 돌고 있는데 같은 메시지 재처리. 새 테스트는 `isCancelled()`만 확인(`KafkaConsumerRegistrarTest.java:201`). + - Fix: handler 실제 종료(`whenComplete`) 시 permit 반환, 또는 우리가 소유한 `Future`에서 실행 후 `Future.cancel(true)`로 인터럽트; 테스트는 "첫 handler 종료 전 재dispatch 없음" 확인. + - Status: regression of H6 (closed 기록, 수정 무효) + +4. **[Required][correctness] admission 거부가 동기 예외로 던져져 relay pass 전체 중단, poison row 무한 반복** — `src/messaging/messaging-runtime-core/.../DefaultMessagePublisher.java:227` + - Evidence: `admission.admit(...)`가 `try` 밖 → `MessageTooLargeException`/`MessageBackpressureException` 동기 throw; `OutboxRelay.runOnce`에 record 단위 catch 없음; CLAIM SQL은 `attempts` 미증가(`JdbcOutboxRepository.java:118-145`) → 크기 초과 row, 다른 writer가 넣은 reserved header row(`OutboxEnvelopeFactory.java:70-77`)가 FAILED/EXHAUSTED로 안 가고 매 lease 재claim; 같은 batch 나머지도 lease 종료까지 묶임. `OutboxRelayWorker.java:184-190`은 로그 없이 삼킴, `failedPasses()` 호출 0. relay는 REJECTED를 `retryable` 무관 terminal 처리. `DefaultBatchMessagePublisher.java:254`만 자기 쪽에서 막음. + - Fix: `DefaultMessagePublisher` 안에서 admission 예외 → REJECTED(backpressure는 retryable=true); relay record별 try/catch + lease mark; 실패 pass 로그·metric. + - Status: new + +5. **[Required][performance] publish가 deadline 적용 전 caller thread를 최대 약 65초 막음(reactive thread 포함)** — `DefaultMessagePublisher.java:227-233` + - Evidence: `InFlightLimiter` 최대 5초(`MessagingCoreAutoConfiguration.java:436-437`) + `KafkaProducer.send` metadata/buffer 대기 `max.block.ms`(기본 60초), 둘 다 `withDeadline` 전 동기. producer bean에 `MAX_BLOCK_MS` 없음(IT는 직접 설정: `KafkaAmbiguityChaosIT.java:148`, `KafkaBrokerCertificationIT.java:410`). `DefaultReactiveMessagePublisher.java:37`이 이 전체를 subscriber thread에서 실행. + - Fix: `max.block.ms` ≤ publish timeout; reactive facade는 `subscribeOn(boundedElastic)` 또는 대기 없는 admission. + - Status: new + +6. **[Required][performance] cleanup job이 제한 없는 단일 DELETE** — `OutboxCleanupJob.java:50`, `InboxCleanupJob.java:56` + - Evidence: 1-인자 `purge*Before(cutoff)` = `DELETE ... WHERE < ?` 한 번; limit CTE 버전(`JdbcOutboxRepository.java:485`, `JdbcInboxRepository.java:141`)은 main 호출 0; `InboxCleanupJob.DEFAULT_BATCH_SIZE` 미사용; javadoc은 "bounded batches". + - Fix: `(cutoff, batchSize)` 버전 호출, 삭제 건수 < batch면 중지; 1-인자 버전은 port에서 제거. + - Status: MSG-006 §6 불완전 종결 + +7. **[Required][correctness] consumer poison message가 지연 없이 무한 재시도(현재 잠재)** — `KafkaConsumerRegistrar.java:115,283-286,341,609` + - Evidence: 기본 quarantine `unavailable()`; decode 실패·handler 예외 → `enqueueRequeue(Duration.ZERO)` → 즉시 seek+resume → 매 poll 같은 record, partition 영구 차단. `DefaultDeliveryProcessor.java:70-97`도 시도 제한 없이 requeue; `RetryDecisionEngine` bean 미사용. + - Fix: `BackoffCalculator` 지연, 시도 한도 초과 시 DLQ/park; production profile에서 quarantine `unavailable()`이면 startup 거부. + - Assumption/Counter: adopter가 README대로 consumer 직접 조립 / 유실보다 막힘이 낫다는 설계 — 단 지연 0은 그 선택의 요구 조건 아님. + - Status: new + +8. **[Consider][docs/config] 옛 prefix `backend.messaging` 잔존** — `messaging-spring-boot-starter/src/test/resources/application-valid.yml:6`, `application-invalid-ordering.yml`, `KafkaShareProfileValidator.java:35`, `StreamBridgePolicyGuard.java:34` (`grep -rnE "application-valid|invalid-ordering" src docs build-logic` → 과거 리뷰·plan만; 테스트 활성 profile은 `prod`/`production`뿐이라 fixture 미로드; 오류 메시지 두 곳이 `MessagingPrefixMigrationValidator`가 거부하는 키를 설정하라고 안내; `app.messaging.experimental.*` flag는 바인딩만). Fix: fixture 삭제, 메시지를 `MessagingSettings.PREFIX` 기준으로. Status: known-open L9 + 메시지 부분 new + +9. **[Consider][structure] 미사용 API 타입** — `messaging-core-api/.../BatchMessageHandler.java`, `CapabilityRegistry`, `DelayedMessagePublisher`, `ManualMessageHandler`, `PauseResumeController`, `ProcessingGuarantee`, `transport-spi/.../MessagingLifecycle.java` (main 참조 0). Fix: 삭제. Counter: public surface라 breaking — 구현체 0. Status: known-open L7/L8 + +10. **[Consider][correctness] Rabbit publish sequence 예약 비원자적** — `RabbitMessagingTransport.java:148-161` (`nextPublishSequence()`와 `publish()` 사이 lock 없음 → 같은 sequence, `pending.put` 덮어쓰기 → 한 caller stage 미완료). Fix: `synchronized` 또는 단일 스레드 계약 명시. Counter: 현재 구현 없음·broker 선택 거부로 도달 불가. + +11. **[Consider][correctness] outbox relay가 ordering key 순서를 지키지 않음** — `JdbcOutboxRepository.java:118-145` (CLAIM이 `ORDER BY created_at` + `SKIP LOCKED`, `ordering_key` 무시 → replica 여럿이거나 AMBIGUOUS row backoff 중 같은 key의 나중 row가 먼저). Fix: ordered destination + outbox 조합 startup 거부, 또는 같은 key의 더 오래된 미완료 row가 있으면 claim 안 함. Counter: relay는 "at-least-once, nothing more" 명시(`OutboxRelay.java:25-27`). + +#### Leads checked and dismissed +- `application-valid.yml` lead: 사실 → #8. `MediaTypeVerifier`/`Sha256Verifier`/`ScriptableContentPolicy`는 `adapter/outbound/fileserver` 소속(범위 밖). +- M9 spring-kafka 코드상 해소(build.gradle·lockfile grep 0; `SpringKafkaTransactionalProcessor` 이름만 오해). M13: `cloudevents-api/core`가 `app-bootstrap` productionRuntimeClasspath에 아직 있음(lockfile:85-86) — known-open. +- HARD-STOP: messaging main의 domain/application/shared/adapter import 0; 모든 edge 일치. +- H4(Rabbit 분류 typed), H7(종료 commit 실패), H8(replay 승인) 해소 확인. `messaging-inbox-jpa`/`messaging-outbox-jpa` 디렉터리는 gitignore된 `build/` 산출물(M16 회귀 아님). +- outbox CLAIM fencing token, `next_attempt_at`, attempt budget·partial index, inbox `ON CONFLICT DO NOTHING` + 트랜잭션 강제 정상. + +#### Coverage note +깊게: runtime-core publisher, starter core/kafka/rabbit/reliability 자동 설정·provider selection, outbox relay/worker/JDBC·SQL, inbox, `KafkaConsumerRegistrar`/transport/security configurer, admission/limiter, admin guard·HMAC, claim-check. 훑음: schema codec 3종, cloudevents, observability, rabbit(transport·classifier), 실험 leaf 3개, stream bridge, testkit. + +### Group N — gRPC 플랫폼 (`grpc:*` / `grpc-advanced:*`) + +#### Leaf별 판정 +| leaf | 판정 | 이유 | +| --- | --- | --- | +| grpc-core-api | NEEDS_FIX | `GrpcDeadlineBudget`이 시간이 흘러도 만료되지 않음 (#2) | +| grpc-policy | NEEDS_FIX | FAILED_TERMINAL 재시도 (#1), writer 백프레셔 (#6), rotation race (#5) | +| grpc-operation-ledger-jpa | NEEDS_FIX | #1의 상대편 계약, claim 경로가 검증 우회 (#11) | +| grpc-server | NEEDS_FIX | admission race (#5), `live()` 가드 무효 (#2) | +| grpc-spring-boot-starter | NEEDS_FIX | environment 기본값 LOCAL → 설정 누락 시 보안 해제 (#3) | +| grpc-admin | NEEDS_FIX | drain 이후 SERVING 복귀 race (#5) | +| grpc-client | NEEDS_FIX | `rotate` get/set race (#5) | +| grpc-advanced-resilience | NEEDS_FIX | resolver가 retry/hedging 설정 주입 가능 (#4) | +| grpc-advanced-compat | PASS | envoy.yaml은 Consider (#8) | +| grpc-advanced-streaming | PASS | Nit (#12) | +| discovery, observability, codegen, proto-contract, testkit, advanced-bootstrap/diagnostics/edition | PASS | 의존 방향·순수성 확인, 큰 결함 없음 | + +#### 발견 (심각도 순) + +1. **[Critical][correctness] FAILED_TERMINAL 뒤 재시도가 claim 없이 PROCEED** — `src/grpc/grpc-policy/…/idempotency/GrpcIdempotencyInterceptor.java:109-114` + - 근거: 기존 FAILED_TERMINAL 행(insert 0행) → `decide`가 `proceed(...)` 반환(호출자가 행을 소유하지 않음) → `recordCommit` → `GrpcOperationLedgerEntity.markCommitted:123-124` → `requireInProgress()`가 `IllegalStateException`. fake `InMemoryOperationLedger.java:50-60`은 FAILED→COMMITTED 허용해 차이를 가림. JPA 테스트 `GrpcOperationLedgerRepositoryTest:190`("a failed claim is terminal")은 반대 계약 검증. + - 왜 문제인가: ledger 쓰기가 business tx 안이면 키 영구 차단(모든 재시도 INTERNAL); tx 밖이면 mutation 커밋 + 행 FAILED 유지 → 다음 재시도가 같은 작업 재실행; 동시 재시도 두 개가 모두 PROCEED(원장이 막으려던 중복 실행). production caller 0(잠복, prior C1과 같은 종류). + - 수정: port에 `reclaimFailed`(`UPDATE … SET state='IN_PROGRESS' … WHERE storage_key=:k AND state='FAILED_TERMINAL'`, 1행이면 소유); fake도 같은 전이 규칙; JPA·fake 공유 계약 테스트. + - 상태: new + +2. **[Required][correctness] `GrpcDeadlineBudget`이 생성 시점 Duration을 들고 있어 만료 미감지** — `src/grpc/grpc-core-api/…/deadline/GrpcDeadlineBudget.java:13,82-83` + - 근거: `expired()`는 `remaining.isZero()`뿐(시계 입력 없음). 사용처: `GrpcRequestContext.live():84-85`, `GrpcServiceAdapter.handle:69-74`("deadline has passed" 가드), `GrpcContextSnapshot.live(now):69-71`, `GrpcClientCallContext:54`. 테스트는 `Duration.ZERO` budget만. + - 왜 문제인가: 큐에서 deadline을 넘긴 호출도 use case 진입; 워커에서 `GrpcDeadlineCalculator.forDependency`가 downstream에 inbound보다 긴 deadline 부여; `GrpcRetryCoordinator` backoff 비교도 오래된 값. + - 수정: 절대 시각 저장(`long deadlineNanos` + 주입 `LongSupplier`, 또는 `Instant` + `Clock`) → `remaining(now)`/`expired(now)`; 시간 경과 테스트. + - 상태: new + +3. **[Required][security] starter가 `environment` 미지정 시 LOCAL로 떠 보안 검사 전부 꺼짐** — `src/grpc/grpc-spring-boot-starter/…/boot/GrpcPlatformProperties.java:26` + - 근거: TLS off·trust-all·reflection ENABLED 거부 검사(`GrpcPlatformStartupValidator.java:87-102`)가 모두 `tlsRequired` 조건 안; `defaultFor(LOCAL)`은 ENABLED이고 bean이 됨(`GrpcPlatformAutoConfiguration.java:86-88`); `enabled=true`만 켜고 environment 누락한 운영 배포 → schema 전체 공개 + trust-all로 통과. 테스트는 전부 environment 명시(`GrpcPlatformAutoConfigurationContextTest:35,53`). + - 수정: 기본값 제거, `enabled=true`인데 environment 없으면 violation(또는 기본값 PROD). + - 상태: new + +4. **[Required][security] resolver service config의 retry/hedging 미검증** — `src/grpc-advanced/grpc-advanced-resilience/…/discovery/GrpcResolverSafetyPolicy.java:56-65,86-91` + - 근거: `GrpcResolverUpdate.java:8-11`은 "retry policy를 사람이 쓴 것처럼 검증" 약속; 실제 검사는 authority·revision·credential 유사 문자열 정규식뿐 → `methodConfig[].retryPolicy`/`hedgingPolicy`가 `acceptedServiceConfig`로 통과; 반대로 정상인 `"retryThrottling":{"maxTokens":…}`는 `token` 부분일치로 거부. + - 수정: JSON 파싱 + top-level 키 allowlist; retry/hedging은 `GrpcMethodPolicyCatalog` + `GrpcHedgingEligibility`로 검증하거나 거부; substring 정규식 삭제. + - 상태: new + +5. **[Required][correctness] 상태 보유 클래스들의 check-then-act / get-then-set race** + - `src/grpc/grpc-server/…/GrpcAdmissionController.java:51-60`: `get() < max` 확인 후 `incrementAndGet()` → 동시 수만큼 bound 초과. + - `src/grpc/grpc-policy/…/security/GrpcCredentialRotationManager.java:89-103,118-121`: `AtomicReference` get/set만 → `completeDrain`이 `rotate`와 겹치면 교체된 credential로 되돌아감; rotator 둘이 겹치면 문서(`:82`)가 금지한 역방향 rotation 통과. + - `src/grpc/grpc-client/…/GrpcChannelRuntimeRegistry.java:91-103`: 같은 패턴, replacement 하나가 drain 목록에서 빠져 누수; `:114,128` synchronizedList를 락 없이 순회. + - `src/grpc/grpc-admin/…/GrpcServiceHealthRegistry.java:50-53` vs `:85`: `draining` 확인과 `put(SERVING)` 사이 drain 시작 → drain 후 global SERVING(`:45` 주석이 막겠다던 상황). + - `src/grpc/grpc-policy/…/streaming/GrpcStreamAdmission.java:42-49`: `computeIfAbsent`가 global bound 검사 앞 → 포화 시 거부된 신규 caller마다 count 0 엔트리 영구 잔류. + - 수정: `synchronized` 또는 `updateAndGet`/CAS; `GrpcStreamAdmission`은 global 검사를 앞으로; `GrpcStreamAdmissionConcurrencyTest` 패턴으로 클래스별 동시성 테스트. + - 상태: `GrpcAdmissionController` known-open(prior M1 근거에서 지목, 종결 때 `GrpcStreamAdmission`만 고침); `GrpcStreamAdmission` 잔류는 M1(b) 미완; 나머지 new. + +6. **[Required][correctness] `GrpcSerializedStreamWriter`가 백프레셔 신호를 잃음** — `src/grpc/grpc-policy/…/streaming/GrpcSerializedStreamWriter.java:47,73,100-103,126-139` + - 근거: (a) `LongSupplier payloadSizer`는 실제 payload 크기를 모름(테스트는 공유 `AtomicLong`을 미리 set — 동시 producer에선 다른 메시지 크기); (b) `PAUSE`를 `ACCEPTED`로 반환; (c) `flush()`가 isReady 무관하게 큐 전체 전송. `GrpcFlowControlPolicy.java:11`이 경고한 "isReady를 무시하는 writer"가 바로 이 구현. + - 수정: `ToLongFunction`; `ACCEPTED_PAUSE` 결과 추가; `flush(BooleanSupplier ready)`. + - 상태: H3 잔여분(`ToLongFunction` 미적용) + (b)(c) new + +7. **[Consider][correctness] `GrpcContextBinder.wrap`이 io.grpc `Context`(취소·deadline)를 스레드 경계에서 버림** — `src/grpc/grpc-policy/…/context/GrpcContextBinder.java:12,60,86-98` (SNAPSHOT 값만 캡처해 실행 스레드의 `Context.current()`(보통 ROOT)에 붙임). 수정: `Context.current()` 캡처 후 `captured.wrap(work)`. 반론: platform 자체 token·`parentRemaining`은 따로 전달. + +8. **[Consider][config] `envoy.yaml` 참조 설정이 그대로는 동작하지 않음** — `src/grpc-advanced/grpc-advanced-compat/src/main/resources/envoy/envoy.yaml:32-39,50-53` (`DownstreamTlsContext`에 인증서 없음 — `envoy --mode validate` 확인 필요; `allow_headers`에 `x-user-agent`, `grpc-timeout` 없음; `expose_headers`가 `error-code,error-category`인데 `GrpcErrorMapper.java:30-39` 실제 trailer는 `error-reason`, `error-execution-id`, `completion-outcome`, `grpc-status-details-bin` 미노출; `timeout: 30s`로 server stream 30초 절단; 테스트 `GrpcWebCompatibilityGateTest:124`는 부분 문자열만; main resources라 jar에 포함). 수정: test resources/docs로 이동, header 목록을 Java 상수와 대조하는 테스트, `grpc_timeout_header_max: 0s`. + +9. **[Consider][architecture] starter의 미사용 의존과 아무것도 검사하지 않는 runtime 불변식** — `src/grpc/grpc-spring-boot-starter/build.gradle:21-22`, `GrpcPlatformAutoConfiguration.java:55-67,129-133` (main에서 `grpc.contract`/`grpc.codegen` import 0; `requireValid(..., Set.of())`로 advanced 격리 검사 항상 통과; `requireStableStarterIsClean` main caller 0 → `src/grpc/CLAUDE.md` "runtime에 강제" 설명 거짓; server profile bean이 `stableNetty` 값을 리터럴 복사). 수정: 두 edge + registry edge 삭제, 파라미터·`validateAdvancedIsolation` 삭제(Gradle gate 기준), 문서 정정, 팩토리 재사용. 반론: reflection에 descriptor 필요 가능. + +10. **[Consider][structure] 같은 한계값이 여러 곳에 따로 정의** — 1 MiB/8192가 `GrpcServerProfile:70-71`, starter `:59-60`, `GrpcMessageSizeProfile:43`, `GrpcNamedChannelProfile:80-81,95-96`, `GrpcMetadataBudget:33`에 각각(정합 검사 없음); `GrpcStreamProfile`은 자기 테스트에서만 참조, `GrpcFlowControlPolicy`의 256/8MiB 복제. grpc-policy 62파일 규모 자체는 과하지 않음(실제 비용은 production 조립 부재로 fake가 실제 adapter와 달라지는 것, #1). 수정: `GrpcTransportLimits` 하나로, validator에 "method profile ≤ server profile", `GrpcStreamProfile` 삭제. + +11. **[Consider][correctness] ledger claim 경로가 entity 검증 우회, storage_key가 컬럼 길이 초과 가능** — `src/grpc/grpc-operation-ledger-jpa/…/JpaGrpcOperationLedger.java:39-53` (native insert가 `sha256:` 형식 검증 안 거침; `callerFingerprint` 길이 무제한 → storageKey 최대 585자 vs `VARCHAR(512)`; insert 0행 + 조회 실패를 소유 획득으로 처리). 수정: `claim()`에서 형식 검증, fingerprint ≤256자, 키 해시로 고정 길이, 0행+조회 실패는 예외. + +12. **[Nit][performance]** `GrpcClientMessageDeduplicator.java:11-17,75,112` ("constant space"라지만 outcome이 세션 내내 누적, `endSession`이 O(N) `removeIf`); `ReactiveGrpcClient.serverStream:50`은 List 래퍼일 뿐(삭제). + +#### 확인했지만 문제 없던 항목 +- HARD-STOP 1-5: core-api 의존 0, framework-free 5개 leaf에 외부 import 없음, 모든 edge 허용, grpc→advanced 참조 0. +- 0-A/0-B(ledger IT CI 미호출) 닫힘: `optional-platforms/build.gradle` `integrationCheck` + `integration-main.yml:313`. H3, M2 회귀 없음. +- ledger SQL named param, `ON CONFLICT`가 PK·unique 모두 커버; NON_IDEMPOTENT retry 차단, hedging은 READ_ONLY unary만; `mapUnknown` description opaque; envoy admin 블록 없음·CORS exact; resume token HMAC + 상수시간 비교; `GrpcDrainCoordinator` 미거부는 prior §2에 기록됨. + +#### 커버리지 +자세히: ledger-jpa 전체, grpc-policy idempotency/streaming/context/deadline/error/security/resilience, server 핵심, starter 전체, admin, client, advanced resilience/diagnostics/compat + envoy, 944a1e34 이후 바뀐 main 파일 전부. 훑음: codegen, proto-contract validator, observability, edition, bootstrap, testkit. + +### Group O — 빌드 시스템, 아키텍처 registry, 의존성 게이트 + +#### 영역별 판정 +| area | verdict | 이유 | +|---|---|---| +| root lifecycle / settings | NEEDS_FIX | `ca.developer-bootstrap`가 설정 단계에서 실패해 Docker/release 이미지 빌드 불가 | +| CI workflows | BLOCKED | `redis-sdk` job이 항상 실패 → `release-gate` 매번 빨간불 | +| architecture gates (build-logic) | NEEDS_FIX | 방향·purity 게이트 정상. `verifyNoIgnoredSourcePackages`는 범위가 좁고 git 오류 시 통과(fail-open) | +| conventions (java/quality/lanes) | PASS | 품질 도구 배선이 리팩터 전 groovy 버전과 같고 약화 없음 | +| modules.json / leaf build.gradle | NEEDS_FIX | registry 밖 production edge 0건. app-bootstrap test 입력 미선언, 좌표 중복 | +| build-tools | PASS | 전부 fail-closed. 중복·규모는 known-open | +| supply chain | PASS (Consider) | 버전 고정 + STRICT lock 있음, checksum 검증 없음 | + +#### Findings (심각도 순) + +1. **[Critical][correctness] root plugin 적용 시점에 compose overlay가 없으면 빌드 전체 실패** — `src/build-logic/src/main/java/dev/caskeleton/buildlogic/bootstrap/DeveloperBootstrapPlugin.java:40-50` + - Evidence: `apply()` 안에서 `../docker-compose..yml`이 없으면 `GradleException`. root에서 적용(`src/build.gradle:29`). release는 context `src`로 `docker build --file src/Dockerfile ... src`(`.github/workflows/release.yml:329-338`); Dockerfile은 `WORKDIR /build/src`(`src/Dockerfile:29`)에서 `RUN ./gradlew verifyDependencyLocks`(`:57-60`) — `/build/docker-compose.local.yml`은 존재할 수 없음. 208077fd에서 추가. + - Why: root 설정 단계에서 죽어 어떤 task도 실행 안 됨 → release 이미지 빌드 차단, Dockerfile 헤더의 로컬 명령도 실패. + - Fix: overlay 확인을 `bootstrapDockerPreflight`의 `doFirst`로 이동, `apply()`는 부수효과 없음; TestKit 회귀 케이스(compose 파일 없는 root에서 `help` 성공). + - Status: new (regression 208077fd) + +2. **[Critical][CI] `redis-sdk` job은 통과 불가, `release-gate`가 이 job의 success를 요구** — `.github/workflows/ci-quality-gates.yml:120`, `.github/workflows/_reusable-gradle.yml:58-63` + - Evidence: 입력 `":shared-contract:test --tests '*EdgeRateLimitProviderNeutralContractTest'"`를 reusable workflow가 `./gradlew ${GRADLE_TASKS}`로 따옴표 없이 펼침 → bash는 확장 결과의 따옴표를 제거하지 않음(`printf '[%s]'` 재현 → `['*EdgeRateLimitProviderNeutralContractTest']`) → 어떤 클래스와도 매칭 안 됨 → `failOnNoMatchingTests` 기본값으로 실패. `release-gate`는 `REDIS_RESULT == success` 요구(`:240,246-258`). 9da00eb7에서 변경. 이 클래스는 tag가 없어 이미 `:ci` → `:shared-contract:check` → `test`로 실행되므로 job 자체가 중복. + - Fix: `redis-sdk` job과 `release-gate` 해당 줄 삭제(남긴다면 따옴표 제거). + - Status: new (regression 9da00eb7). CI 미실행, bash/Gradle 동작에서 도출. + +3. **[Required][HARD-STOP 6] "Git이 커밋할 수 있는 소스" 게이트가 main/test만 보고 git 오류 시 통과** — `ArchitecturePlugin.java:191-203`, `VerifyNoIgnoredSourcePackagesTask.java:70-87,102-119` + - Evidence: 대상이 `List.of("src/main/java","src/test/java")` 하드코딩 → 나머지 Java source root 45개(testFixtures 10, integrationTest 10, systemTest 5, architectureTest 등; H9가 다룬 종류) 미검사. `git rev-parse`/`check-ignore` exit code 무시 → 128(fatal)이면 stdout 비어 "not a Git checkout" 또는 위반 0으로 통과; `IOException`도 null → 통과. `optional-platforms`의 `ci`는 이 task에 의존하지 않아 grpc 소스 미검사. 테스트 0(`grep -rl IgnoredSource build-logic/src/test app-bootstrap/src build-tools/src/test`). + - Fix: 모든 project `sourceSets*.java.srcDirs` 수집; `.git`이 있는데 git이 0/1 외 코드로 끝나거나 실행 파일이 없으면 실패; `integrationTest`에 ignore 대상 패키지를 넣은 TestKit 케이스. + - Status: new (groovy 시절부터의 공백, regression 아님) + +4. **[Required][correctness/cache] app-bootstrap `test`가 선언하지 않은 저장소 파일을 읽음 → 로컬 UP-TO-DATE 거짓 통과** — `src/app-bootstrap/build.gradle:270-287` + - Evidence: `ca.repository.root`로 `docs/runbooks/**`(`RunbookCoverageContractTest.java:129`, `ContainerRuntimeOomContractTest.java:110`), `src/.env.example`(`EnvProfileMatrixContractTest.java:30`)을 읽는데 선언 입력은 `docs/registries`뿐(`:282`). `org.gradle.caching=true`에서 runbook만 수정하면 `:app-bootstrap:test` UP-TO-DATE. 같은 패턴 `adapter/outbound/messaging/build.gradle:30-34`(schema 경로 sysprop, `inputs.file` 없음). CI에선 `GITHUB_SHA` → version `0.0.1+`(`ReleaseProvenancePlugin.java:24-37`) → 모든 jar manifest(`JavaConventionsPlugin.java:45-48,66-75`) → 커밋마다 test runtime classpath가 달라 cache miss(가려짐; CI의 test/SpotBugs cache 이득 0). cache를 살리려고 `normalization.runtimeClasspath.metaInf.ignoreAttribute`를 넣는 순간 거짓 통과가 CI로 이동. + - Fix: `inputs.dir(docs/runbooks)`, `inputs.file(src/.env.example)`(RELATIVE), messaging `inputs.file(schema)` 선언 후 manifest normalization 검토. + - Assumption/Counter: setup-gradle이 `caches/build-cache-1`을 유지 / 유지하지 않아도 로컬 focused test 거짓 통과만으로 HARD-STOP 6 위험. + - Status: new + +5. **[Consider][supply chain] artifact checksum 검증 없음, included build 의존성 미lock** — `src/gradle/`, `src/build-logic/settings.gradle:6-9`, `src/build-tools/settings.gradle` (`verification-metadata.xml` 없음; build-logic은 spotless/spotbugs/errorprone/dependency-management plugin을 lock·hash 없이 `gradlePluginPortal`에서; `settings-gradle.lockfile`은 catalog만). Fix: `--write-verification-metadata sha256` 커밋, build-logic/build-tools `dependencyLocking`. Counter: Trivy·dependency-review·고정 버전이 CVE 위험은 막음, metadata 갱신 부담. + +6. **[Consider][correctness] 프로젝트 좌표 `dev.caskeleton:messaging-kafka` 중복** — `:adapter:outbound:messaging-kafka`(9da00eb7) vs `:messaging:messaging-kafka` (같은 이름, 같은 group(`JavaConventionsPlugin.java:44`); `VerifyDependencyPolicyTask`는 `group:name` 매칭이라 구분 불가; 같은 jar 파일명 → 한 composition에 둘 다 들어가면 `BOOT-INF/lib` 충돌; Gradle 충돌 해결이 둘을 합치는지 미확인). Fix: adapter leaf 이름 변경(예: `:adapter:outbound:kafka-sender`) + modules.json·디렉터리. + +7. **[Consider][simplicity] runtime membership 검사가 방향 게이트와 중복** — `RuntimeMembershipPlugin.java:35-44`, `VerifyCompositionRuntimeMembershipTask.java:166-188` ("등록된" 집합 = sample 제외 main 모듈 전부; settings는 registry 모듈만 include(`ModuleRegistrySettingsInstaller.java:278-280`) → "미등록" 가능한 건 `:sample-portfolio`뿐이고 방향 게이트가 이미 차단; build-logic README의 "registry's memberships" 필드는 없음). Fix: plugin, alias task, `ArchitecturePlugin.java:216-225`, `ConditionalTransportQualificationPlugin.java:56` 연결 삭제. Counter: 싸고 미래 보호막. + +8. **[Consider][simplicity] "지정 테스트가 실행됐고 skip 없음" 검사 구현이 5개** — `ca.strict-test-lane` `requires`/`rejectSkipped`; `ca.strict-qualification`(RequiredClasses task + listener + XML 재검사, 10개 leaf); `ConditionalTransportQualificationPlugin` XML 재읽기; `GraphQlPlatformPlugin` `graphqlStableTest` 자체 XML 검사; build-tools `JUnitEvidenceReader`(build-logic `JUnitEvidence` 복사본, README는 "one JUnit XML reader"). 규모: build-logic main 83파일/5,995 LOC, build-tools 98파일/5,888 LOC. Fix: 모두 `strictTestLanes { lane { requires ...; rejectSkipped = true } }`로, 나머지 삭제. Status: known-open (13-build §0-A/0-B) + +9. **[Consider][performance] quarantine job이 테스트 0개를 돌리려고 저장소 전체 컴파일** — `ci-quality-gates.yml:212-217`, `src/build.gradle:88-92`, `JavaConventionsPlugin.java:149-165` (leaf마다 test JVM, up-to-date 판정 없음; `Tag("quarantine")` 0건). Fix: job·task 삭제, 첫 quarantine 테스트 때 재추가. + +10. **[Nit][readability]** httpclient가 같은 sysprop 3줄을 7번 반복(`adapter/outbound/httpclient/build.gradle:131-229`); `-Duser.timezone=UTC`가 leaf build 파일에 18번 → `JavaConventionsPlugin`에 `withType(Test).configureEach { systemProperty 'user.timezone','UTC' }` 한 번(jvmArgs 아님 — `StrictTestLanePlugin.java:176-178` `setJvmArgs`가 덮어씀). + +11. **[Nit][docs]** CLAUDE.md `ci` 정의에 `sampleWebContractCheck`(`build.gradle:146`) 누락, `verifyDependencyLocks`는 `ci` 밖(workflow에서만, `ci-quality-gates.yml:62`); `libs.versions.toml:27-31`은 BOM override가 `src/build.gradle`에 이유와 함께 있다고 적었지만 실제 `JavaConventionsPlugin.java:90-92`이고 이유 사라짐, `netty.version`은 Boot 4.0.8 BOM 값(4.2.17.Final)과 같아 무효; `optional-platforms/README.md:3` 모듈 개수("18") 기재(no-count 규칙 위반). + +#### 확인했지만 문제 아닌 것 +- M6 (parallel): 방향/purity/membership task가 소유 project 안에서 `Provider`로 resolve(`ArchitecturePlugin.java:96-189`), `parallel=true` — 닫힌 것으로 보임(`--parallel` TestKit 없음). +- H9 (commit 포함): untracked는 graphify-out/.playwright-mcp뿐, 모든 leaf에 lockfile — 닫힌 것으로 보임. +- 이전 H1/H2, gRPC ledger lane 호출자: 닫힘. +- 정적 edge 감사: 모든 leaf ` project(...)`를 스크립트로 registry와 대조 → 허용 밖 production edge 0. +- 품질 게이트 약화 없음(checkstyle severity=error라 `maxWarnings=MAX` 무영향; errorprone/`-Werror`/`ignoreFailures`/`onlyIf` 해제 0). build-logic/build-tools catch 블록 전부 재던짐/실패. +- tree-sitter 파싱 실패 22건: 유효한 Groovy(파서 한계); `fileserver/build.gradle:10`의 `\`만 불필요. +- wrapper sha256 검증, action SHA 고정; quarantine·http3 job은 의도된 advisory. + +#### 커버리지 +깊게: root build/settings/properties, ArchitecturePlugin·task들, ModuleRegistry, RuntimeMembership, Java/Quality conventions, StrictTestLane/StrictQualification, DependencyPolicy, ReleaseProvenance, DeveloperBootstrap, ci-quality-gates·reusable workflow, Dockerfile builder stage, 큰 leaf build 4개, modules.json(스크립트). 훑음: build-tools, 나머지 leaf, integration/release workflow. + diff --git a/docs/roadmap/messaging-r2.md b/docs/roadmap/messaging-r2.md index 5eee3171..40d88248 100644 --- a/docs/roadmap/messaging-r2.md +++ b/docs/roadmap/messaging-r2.md @@ -10,8 +10,10 @@ - 대응하는 Test 태스크 없음 - 공통 스키마 validator 없음 -따라서 `config/messaging/readiness-cards.yaml`의 카드는 `verifyMessagingContracts`와 -`verifyMessagingJsonSchemaV1` 두 개를 제외하면 모두 `maturity: not-implemented`다. +따라서 `config/messaging/readiness-cards.yaml`의 카드는 모두 `maturity: not-implemented`다. +유일하게 `implemented-candidate`였던 `json-schema-envelope.v1`은 그 구현(adapter messaging의 +`JsonSchemaIntegrationEventEncoder`와 `verifyMessagingJsonSchemaV1`)을 2026-09-25에 삭제하면서 +`not-implemented`로 내렸다. 남은 evidence producer는 `verifyMessagingContracts` 하나다. ## 왜 Gradle 태스크를 미리 만들어 두지 않는가 @@ -40,8 +42,8 @@ verifyMessagingTargetBindingPreflight 1. 각 시나리오를 실제로 실행하는 Test 태스크. 2. 그 실행 결과(JUnit XML)에서 payload-free manifest를 만드는 producer. 3. `config/messaging/evidence/build-evidence-manifest-v1.schema.json`으로 그 manifest 바이트를 - 검증하는 finalizer. + 검증하는 단계(build-tools `VerifyMessagingEvidenceTask`가 쓰고 바로 검증한다). 4. 위 셋이 모두 생긴 다음에 `verifyMessagingR2` 태스크 등록. -`gradle/qualification/messaging-qualification.gradle`의 `verifyMessagingJsonSchemaV1`이 그 네 단계를 -모두 갖춘 예시다. +build-tools `MessagingQualificationPlugin`의 `verifyMessagingContracts`가 그 네 단계를 모두 갖춘 +예시다. diff --git a/docs/runbooks/outbox-publish-failed.md b/docs/runbooks/outbox-publish-failed.md index 45088e21..84d847c4 100644 --- a/docs/runbooks/outbox-publish-failed.md +++ b/docs/runbooks/outbox-publish-failed.md @@ -28,10 +28,11 @@ status: stub 2. broker 상태 확인: `APP_MESSAGING_BROKER` 값과 broker endpoint 가용성. 이 키는 활성화 스위치가 아니라 **선택자**다 — messaging을 끄는 것은 `APP_MESSAGING_ENABLED=false`이고, 이 값을 비운다고 messaging이 꺼지지는 않는다. - - `APP_MESSAGING_BROKER`가 공백인 채로 relay가 켜져 있으면 **애플리케이션이 기동하지 않는다** - (`OutboxRelayBrokerRequirementValidator`, MSG-024). 이 조합에서는 publish가 전부 - `AdapterDisabledException`으로 실패하며 PENDING row가 DEAD까지 소진되기 때문이다. - 기동 실패를 보고 있다면 broker를 설정하거나 `ca-skeleton.outbox.relay-enabled=false`로 둔다. + - relay 스케줄러는 발행 포트(`OutboxMessagePublishPort`, messaging bridge가 제공)가 있을 때만 + 생긴다. messaging을 고르지 않은 배포에서는 relay가 없고 PENDING row가 그대로 남는다(MSG-024의 + "DEAD까지 소진"은 대역 publisher가 있던 때의 이야기다). messaging 모듈이 켜져 있는데 + `APP_MESSAGING_BROKER`가 공백이면 기동이 거부된다(messaging `MessagingConfig`, messaging platform + `MessagingProviderSelection`) — broker를 설정하거나 messaging을 끈다. - 기동은 했는데 실패가 쌓인다면 broker는 설정돼 있고 도달이 안 되는 것이다 — endpoint부터 본다. 3. `outbox.pending.size` status 분포 확인 (FAILED 누적 vs PENDING 누적) diff --git a/docs/study/graphql-walkthrough.ko.md b/docs/study/graphql-walkthrough.ko.md index 752d426d..069478a1 100644 --- a/docs/study/graphql-walkthrough.ko.md +++ b/docs/study/graphql-walkthrough.ko.md @@ -1,5 +1,14 @@ # GraphQL 인바운드 모듈 완전 해부 +> **2026-09-25 이후 달라진 점**: `moduleboundary/`, `architecture/`, `compat/`, `release/`, +> `advanced/release/`, `GraphQlSchemaContractSuite`는 삭제됐다(`docs/capability-status.md` 제거 표). +> 부팅 시 컨트롤러 경계 검사는 `GraphQlTransportBoundaryArchitectureTest`(ArchUnit)로 옮겼다. +> 아래 §2·§18·§20.5·§21·§23.15의 해당 설명은 삭제 전 코드 기준이다. +> §25.1의 "shipped and gated" 배선도 끝났다. GraphQL은 기본 조립에 없고 +> `runtimeOnly project(':adapter:inbound:graphql')` 한 줄로 고르며, 모듈이 있으면 켜진다 +> (`APP_GRAPHQL_ENABLED` 기본 `true`, `false`면 Spring GraphQL 자동 설정까지 빠진다). §25.5의 끄는 장치 +> 테스트도 삭제됐다. + > **성격**: 정책 문서가 아니라 **읽기 기록**이다. `adapter:inbound:graphql` leaf와 그 주변 > (app-bootstrap 배선, 테스트 레인, 아티팩트 게이트, 스모크 스크립트, ADR, 코드 리뷰 문서)에 > 실제로 구현되어 있는 것을 코드 기준으로 하나씩 확인하면서, "무엇이 있는가"와 "왜 그렇게 @@ -1498,26 +1507,24 @@ GraphQL 에러로 남는다. top-level 에러 하나가 **모든 아이템의 결과를 버린다** — 성공했고 부수효과가 이미 일어난 것들까지. 그래서 `index`를 담아 클라이언트가 상관지을 수 있게 한다. -### 14.3 `GraphQlMutationIdempotencyContext` — 키 하나가 아니라 다섯 개의 스코프 +### 14.3 mutation 멱등성 — 2026-09-25 삭제 -``` -actor × tenant × mutation coordinate × contract version × normalised input -``` +GraphQL 전용 mutation 멱등성(`GraphQlMutationIdempotencyInterceptor`, +`GraphQlMutationIdempotencyContext`, `GraphQlIdempotencyKey`, `GraphQlIdempotencyConflictException`, +`GraphQlCanonicalInput`, `GraphQlExtensionsPolicy`의 `idempotencyKey` extension 허용, +`GraphQlMutationContractValidator.requireIdempotency`)은 저장소에 연결된 적이 없어서 삭제했다. +지금 기본 `GraphQlExtensionsPolicy`는 어떤 extension key도 허용하지 않는다. -| 축 | 없으면 | -|---|---| -| actor | 한 클라이언트의 재시도가 다른 클라이언트의 결과를 반환 | -| **tenant** | actor 정체성이 tenant를 함의하지 않음 — 같은 service account가 두 tenant에서 행동 가능 | -| mutation coordinate | 같은 키를 다른 mutation에 보내면 다른 오퍼레이션인데 같은 결과 | -| contract version | 계약이 바뀌면 같은 입력이 다른 의미 | -| normalised input | 같은 키에 다른 입력 = 두 개의 다른 부수효과 | +요청 재생 멱등성이 필요한 mutation은 transport가 아니라 use case 안에서 application +`IdempotencyExecutor`를 쓴다. 스코프는 `IdempotencyScopeDigest`(principal + 클라이언트 key + +operation code의 HMAC)로 만들고, mutation 하나를 멱등 단위로 잡는 원칙은 그대로다 — 한 GraphQL +요청이 여러 root mutation을 나를 수 있으므로 요청 전체를 한 단위로 다루면 전부 replay하거나 전부 +안 하거나가 된다. 삭제된 인터셉터가 스코프에 넣던 축(actor, tenant, mutation, contract version, +정규화된 입력)은 digest를 만들 때 여전히 점검할 목록이다. -javadoc이 tenant를 왜 따로 두는지 명시한다: *"Tenant is part of the scope because actor identity -does not imply it."* +### 14.4 `GraphQlCanonicalInput` — 지문 충돌 사건 (삭제된 코드의 기록) -### 14.4 `GraphQlCanonicalInput` — 지문 충돌 사건 - -**이 leaf에서 가장 교육적인 버그다.** +**이 leaf에서 가장 교육적인 버그다.** 코드는 §14.3과 함께 삭제됐지만 교훈은 남긴다. 이전 정규형은 최상위 키를 정렬하고 `key=value;`로 조인했다. 두 개의 서로 다른 입력이 동일하게 정규화될 수 있었다: @@ -1533,13 +1540,10 @@ does not imply it."* §13.4의 커서 프레이밍 버그와 **같은 부류**다: 구분자를 값 안에서 구분할 수 없다. 그리고 같은 레포 안에서 두 번 일어났다. 이게 §27의 원칙 하나가 된다. -### 14.5 `GraphQlIdempotencyKey` — 양쪽이 다 묶인다 +### 14.5 (삭제됨) `GraphQlIdempotencyKey` -8~128자. 이유가 양방향이다: -- **너무 짧으면** 무관한 요청 간에 충돌 → 한 호출자의 재시도가 다른 호출자의 결과를 반환 -- **무제한이면** 저장·로깅 문제 - -`GraphQlIdempotencyConflictException`은 **키도 입력도 담지 않는다.** +§14.3 참고. 키 길이 제한(8~128자)을 두던 이유 — 너무 짧으면 무관한 요청끼리 충돌하고, +무제한이면 저장·로깅 문제가 생긴다 — 는 클라이언트 key를 받는 쪽이 여전히 지켜야 한다. ### 14.6 `GraphQlMutationContractValidator` — GraphQL의 serial 실행은 트랜잭션이 아니다 @@ -1558,12 +1562,6 @@ does not imply it."* > *a transport-level retry would repeat a side effect the client never asked to repeat.* -`GraphQlMutationIdempotencyInterceptor`는 HTTP 요청이 아니라 **mutation 단위**로 스코프한다 — -한 GraphQL 요청이 여러 root mutation을 나를 수 있고, 요청 전체를 하나의 멱등 단위로 다루면 -전부 replay하거나 전부 안 하거나가 된다. - -현재 등급은 `modelled`다 — 이 인터셉터를 참조하는 configuration이 없다. - --- ## 15. `fetch` — over-fetch를 막는 프로파일 @@ -2062,7 +2060,7 @@ override는 **의도적 호환성 레인에서만** 허용 — 조용히 하나 | DataLoader / batching | `wired` | `GraphQlBatchLoaderRegistrationTest` (**50 parent → 3 downstream**) | | object 인가 | `modelled` | 실행 경로에 연결하는 configuration 없음 | | **cursor 서명** | `modelled` | **auto-configuration이 `HmacGraphQlCursorCodec`도 `GraphQlCursorKeyRing`도 만들지 않음** — `GraphQlPolicyRequestPathTest`가 고정 | -| mutation 멱등성 | `modelled` | 인터셉터를 참조하는 configuration 없음 | +| mutation 멱등성 | 삭제됨 (2026-09-25) | use case 안에서 application `IdempotencyExecutor` 사용 (§14.3) | | persisted operation | `modelled` | 중립 `OperationalRecordStorePort` 기반 레지스트리 + 방향성 테스트. durable 구현 미제공 | | subscription / WebSocket / SSE / RSocket | `modelled` | 정책·상태기계 단위 테스트만. **Spring transport handler 없음 — 그래서 타입 이름도 `*Admission`이다** | | federation / incremental / codegen / compat | `modelled` | 단위 테스트만 | @@ -3024,13 +3022,13 @@ if grep -q '"errors"' /tmp/gql.json; then fail "the query returned GraphQL error | 테스트 | 무엇 | |---|---| -| `GraphQlDeploymentModeRegistryParityTest` | enum 목록과 운영자용 레지스트리 동기화 (§4.1) | -| `ShippedRuntimeFacadePresenceTest` | shipped facade 존재 | -| `FiveAdapterOffInventoryTest` | 다섯 어댑터 off 상태 인벤토리 | -| `CapabilityDependencyValidatorTest` | capability 의존 검증 | -| `RuntimeMembershipClasspathAgreementTest` | `runtime_memberships`와 실제 classpath 일치 | +| `GraphQlDeploymentModeRegistryParityTest` | enum 목록과 운영자용 레지스트리 동기화 (§4.1). 2026-09-25에 graphql leaf로 이동 | +| `ShippedRuntimeFacadePresenceTest` | shipped facade 존재 (2026-09-25 삭제) | +| `FiveAdapterOffInventoryTest` | 다섯 어댑터 off 상태 인벤토리 (2026-09-25 삭제) | +| `CapabilityDependencyValidatorTest` | capability 의존 검증 (2026-09-25 삭제) | +| `RuntimeMembershipClasspathAgreementTest` | `runtime_memberships`와 실제 classpath 일치 (삭제됨. `verifyRuntimeModuleRegistry`가 대신 본다) | | `ConditionalTransportQualificationContractTest` | 조건부 전송 계약 | -| `AdapterActivationInventory` / `ShippedCompositionHarness` | 헬퍼 | +| `AdapterActivationInventory`(2026-09-25 삭제) / `ShippedCompositionHarness` | 헬퍼 | `RuntimeMembershipClasspathAgreementTest`가 특히 §25.1의 drift를 잡아 줄 수 있는 위치다 — 레지스트리와 classpath는 일치하고, 산문 문서만 어긋나 있다. @@ -3349,7 +3347,7 @@ javadoc 도구는 마지막 것만 연결한다. **`SPRING_DATA` 상수 다음, |---|---|---|---| | cursor 서명 | 완성 | 키 재료 출처 | P2 | | object 인가 | 완성 (`ObjectAccessPolicy` + bridge) | 실행 경로 연결 configuration | **누가 `GraphQlObjectAuthorizationPort`를 제공하나** — leaf 기본값? adopter? | -| mutation 멱등성 | 완성 (5축 스코프) | 인터셉터 참조 configuration | **멱등성 레코드 저장소** — persisted operation과 같은 `OperationalRecordStorePort`를 쓸 수 있나? | +| mutation 멱등성 | 삭제됨 (2026-09-25) | — | 없음. 필요한 mutation은 use case 안에서 application `IdempotencyExecutor`(provider `redis`/`postgresql`)를 쓴다 (§14.3) | **셋이 같은 모양이다**: 정책은 다 만들었고 **배포가 공급해야 하는 것 하나**가 비어 있다. `GraphQlPrincipalResolver`(§9.9)가 이미 그 패턴을 확립했으니, 셋 다 같은 방식으로 정리하는 게 diff --git a/docs/study/postgresql-jpa-walkthrough.ko.md b/docs/study/postgresql-jpa-walkthrough.ko.md index 63020435..0ab67edf 100644 --- a/docs/study/postgresql-jpa-walkthrough.ko.md +++ b/docs/study/postgresql-jpa-walkthrough.ko.md @@ -1254,12 +1254,12 @@ credential로 도는데, 그건 설계상 런타임 롤과 다른 롤이다 — ### 7.7 벤더 선택과 H2 대칭 -두 벤더 composition이 각각 **같은 네 개의 SPI 빈**을 등록한다. +두 벤더 composition이 각각 **같은 SPI 빈**을 등록한다. (V1 idempotency의 +`IdempotencyClaimRepository`와 벤더별 구현 두 개는 2026-09-25에 V1과 함께 삭제됐다.) | SPI | PostgreSQL | H2 | |---|---|---| | `OutboxClaimRepository` | `PostgreSqlOutboxClaimRepository` | `H2OutboxClaimRepository` | -| `IdempotencyClaimRepository` | `PostgreSqlIdempotencyClaimRepository` | `H2IdempotencyClaimRepository` | | `SqlStateErrorMapping` | `PostgreSqlSqlStateErrorMapping` | `H2SqlStateErrorMapping` | | `TransactionLocalTimeoutConfigurer` | `PostgreSqlLocalTimeoutConfigurer` | `H2LocalTimeoutConfigurer` | @@ -1272,27 +1272,14 @@ credential로 도는데, 그건 설계상 런타임 롤과 다른 롤이다 — 부재는 PostgreSQL이다(`matchIfMissing = true`) — 선택자가 생기기 전 모든 배포가 돌던 벤더. -**두 statement가 갈라지고, 이유는 추정이 아니라 측정이다 (H2 2.4.240).** +**H2에서 도는 벤더 statement는 outbox claim 하나이고, 동일하다 (H2 2.4.240, 측정).** H2가 +`FOR UPDATE SKIP LOCKED`를 받아들이고 잠긴 행을 진짜로 건너뛴다. 한 커넥션이 row lock을 든 +상태에서 동시 `SKIP LOCKED` claim이 블록하거나 락을 뚫고 읽는 게 아니라 **0행을 반환**하는 걸 +확인했다. 그래서 claim이 의미를 유지한다. `H2ClaimSqlTest`가 실제 H2에 실행한다. -- **outbox claim은 동일하다.** H2가 `FOR UPDATE SKIP LOCKED`를 받아들이고 잠긴 행을 진짜로 - 건너뛴다. 한 커넥션이 row lock을 든 상태에서 동시 `SKIP LOCKED` claim이 블록하거나 락을 - 뚫고 읽는 게 아니라 **0행을 반환**하는 걸 확인했다. 그래서 claim이 의미를 유지한다. -- **idempotency claim은 다르다.** H2에는 `INSERT ... ON CONFLICT ... RETURNING`이 없어서 - 같은 세 결과를 갖는 `MERGE ... USING`이다. `H2ClaimSqlTest`가 둘 다 실제 H2에 실행한다. - -H2의 `MERGE`가 세 결과를 어떻게 만드는지: - -| 상황 | 분기 | 반환 | -|---|---|---| -| scope에 행 없음 | `WHEN NOT MATCHED` insert | 1 | -| live 행 | 어느 분기도 발동 안 함 | 0 (live winner에게 짐) | -| expired 행 | `WHEN MATCHED AND expires_at <= now` | 1 (takeover) | - -한 statement인 게 SPI의 약속을 지킨다 — **claim 실패가 constraint violation이 아니라 0행**이라 -주변 트랜잭션을 오염시키지 않는다. - -`RETURNING`이 필요 없는 이유도 적혀 있다: PostgreSQL statement가 반환하는 `EXCLUDED.id`는 -양쪽 분기에서 proposed id이므로, claim된 행은 항상 이 caller의 proposed id다. +H2에는 idempotency store가 없다. 남은 idempotency store는 PostgreSQL 전용(§10.1)과 Redis뿐이고, +PostgreSQL provider는 H2 data source에서 기동을 거부한다. 그래서 `bootRunH2`는 provider를 +`disabled`나 `redis`로 둔다. **H2 vendor config에는 Flyway location customizer가 일부러 없다.** H2 등가 트리가 없고, local profile이 Flyway를 끄고 Hibernate가 엔티티에서 스키마를 만들게 하기 때문. 두 가지 @@ -1530,53 +1517,19 @@ CREATE TABLE idempotency_record ( CREATE INDEX ix_idempotency_record_expires_at ON idempotency_record (expires_at); ``` -**`tenant`가 절대 `null`이 아니다** (single-tenant는 빈 문자열). +테이블과 V1 migration은 그대로 남아 있지만, 이 컬럼을 쓰던 V1 코드 +(`IdempotencyStoreAdapter`, `IdempotencyClaimRepository`와 벤더 구현, `tryBegin`, +`IdempotencyResponseObjectStore` offload)는 2026-09-25에 삭제됐다. 지금 이 테이블에 쓰는 코드는 +owner-safe store(§10.1) 하나이고, `db/migration/jpa/idempotency` stream이 추가한 컬럼 +(`scope_hash`, `record_version = 2` 등)을 쓴다. `jdbc` provider 값도 없다. -> PostgreSQL은 NULL을 서로 distinct로 취급하므로, null을 허용하면 single-tenant 행의 unique -> scope dedup이 깨진다. +남은 V1 쪽 코드는 정리용이다. `IdempotencyRecordEntity`/`IdempotencyRecordJpaRepository`를 쓰는 +`IdempotencyReaper`(`@Scheduled`, 기본 10분, `deleteExpired` bulk delete)가 `expires_at`이 지난 +행을 지운다. store가 완료·실패 때 `expires_at`을 앞으로 옮기므로 reaper는 **테이블 성장을 묶는 +backstop**이다. reaper는 provider가 `postgresql`일 때만 돈다. -매퍼가 `null` 애플리케이션 tenant ↔ row의 `""`를 왕복시킨다. - -**엔티티에 setter가 없는 것도 의도**다. 상태 전이 때 row를 재구성·재저장한다(Vernon Option A) — -애플리케이션 관점에서 엔티티를 immutable로 유지. - -동시성 중재는 unique 제약이다. `tryBegin`: - -- SPI(`IdempotencyClaimRepository`)가 있으면 벤더 statement 한 방. -- 없으면 lookup → 만료 행 delete → `saveAndFlush`(flush가 unique 검사를 그 자리에서 강제) → - `DataIntegrityViolationException`이면 `false`. - -PostgreSQL SPI: - -```sql -INSERT INTO idempotency_record (...) VALUES (..., 'IN_FLIGHT', NULL, NULL, ...) -ON CONFLICT ON CONSTRAINT uq_idempotency_scope -DO UPDATE SET id = EXCLUDED.id, request_hash = EXCLUDED.request_hash, status = 'IN_FLIGHT', ... -WHERE idempotency_record.expires_at <= :now -RETURNING id -``` - -`DO UPDATE ... WHERE`가 실패하면 행이 반환되지 않는다 → 패자는 `Optional.empty()`. - -`tryClaim`이 하는 detach가 중요하다. - -```java -if (exactExpiredEntity != null && entityManager.contains(exactExpiredEntity)) { - entityManager.detach(exactExpiredEntity); -} -``` - -이 statement가 덮어쓰려는 행의 managed 복사본이 있으면 커밋 시점에 claim 위로 flush된다. - -만료는 **세 곳**에서 강제된다: read(`find`가 만료 행을 부재로 취급), reclaim(`tryBegin`이 -만료 행을 재claim 전에 처리), 그리고 `IdempotencyReaper`(`@Scheduled`, 기본 10분, -`deleteExpired` bulk delete). reaper는 유일한 만료 수단이 아니라 **테이블 성장을 묶는 -backstop**이다. - -§F responseRef split: payload ≤ 8KB는 row에 inline, 더 크면 `IdempotencyResponseObjectStore`로 -offload하고 reference만 보관. object store 빈이 없으면 **경고와 함께 inline으로 안전 degrade** -(D9 프로젝트 선택 — 8KB 임계와 object-store 분리는 cited normative basis가 없고 production -빈도도 미측정). +응답은 8 KiB 이하만 행에 inline으로 저장하고, 넘으면 store가 거부한다. object store offload +경로는 없다. ### 9.2 `outbox_event` (V3) @@ -1719,7 +1672,7 @@ setter가 아니라 **registry 생성자**에서 설정한다. ### 10.1 `PostgreSqlOwnerSafeIdempotencyStore` -`IdempotencyStorePortV2` 구현. 상태: +`IdempotencyStorePort` 구현. 상태: `CLAIMED → EXECUTING → COMPLETED | FAILED_RETRYABLE | ABANDONED`. 클래스가 하는 일과 협력자로 분리한 것이 명확히 문서화되어 있다. @@ -2716,13 +2669,13 @@ JpaPlatformRuntimeAutoConfiguration ← 8개 add-on 빈 ``` ca-skeleton.persistence-jpa.enabled = true ca-skeleton.outbox.enabled = true -ca-skeleton.capabilities.idempotency.provider = jdbc +ca-skeleton.capabilities.idempotency.provider = postgresql ca-skeleton.lock.multi-instance-enabled = true notification.platform.enabled && persistence != none app.fileserver-platform.enabled && transaction-provider != none ``` -> 풀은 JPA의 사유물이 아니다. outbox, JDBC idempotency store, multi-instance lock, +> 풀은 JPA의 사유물이 아니다. outbox, PostgreSQL idempotency store, multi-instance lock, > notification store, Fileserver 트랜잭션 경로가 전부 필요로 하고, "JPA 꺼졌나?"만 물으면 > **아무도 안 쓰는 풀을 열거나, 정당하게 쓰던 capability를 조용히 망가뜨린다.** @@ -2875,7 +2828,9 @@ Flyway는 세 옵션이 **pin**되어 있다(env-driven 아님): `baseline-on-mi `ca-skeleton.outbox.*`: `poll-interval: PT5S`, `batch-size: 20`, `in-flight-timeout: PT5M`, `reaper-interval: PT10M`, `published-retention: P7D`. -`ca-skeleton.idempotency.ttl: 24h`, `reaper-interval: 10m`. +`ca-skeleton.capabilities.idempotency.*`: `provider: disabled`, `processing-lease: 30s`, +`replay-ttl: 24h`(`APP_IDEMPOTENCY_TTL`, 최대 72h), `failure-retention: 24h`, +`reaper-interval: 10m`. 한 record(`IdempotencySettings`)가 전부 바인딩한다. --- @@ -3338,7 +3293,7 @@ grep -rnE "[0-9]+ ?(개 ?)?-?(leaf|leaves)" docs | grep -v "^docs/superpowers/\| | 클래스 | 조건 | |---|---| -| `IdempotencyStoreAdapter` | `@ConditionalOnProperty(ca-skeleton.capabilities.idempotency.provider = jdbc, matchIfMissing = true)` | +| `PostgreSqlIdempotencyStoreConfig` | `@ConditionalOnProperty(ca-skeleton.capabilities.idempotency.provider = postgresql)` | | `IdempotencyReaper` | 동일 | | `OutboxStoreAdapter` | **없음** (`@Repository`만) | | `OutboxReaper` | **없음** (`@Component` + `@Scheduled`) | diff --git a/docs/superpowers/plans/2026-09-25-capability-module-packaging.md b/docs/superpowers/plans/2026-09-25-capability-module-packaging.md new file mode 100644 index 00000000..419f3174 --- /dev/null +++ b/docs/superpowers/plans/2026-09-25-capability-module-packaging.md @@ -0,0 +1,564 @@ +# 부가 기능(capability) 모듈 포장 — 실행 계획 + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** 부가 기능을 "의존성을 붙이면 켜지고 떼면 사라지는 capability 모듈"로 바꾸고, 템플릿 기본 조립을 web만으로 줄인다. 그 전에 1차 리뷰 Critical을 고치고 리팩터링 잔재를 걷어낸다. + +**Architecture:** 서비스 코드는 application-core 포트만 호출한다. 각 capability 모듈은 자기 `AutoConfiguration.imports`로 켜지고, `app-bootstrap/build.gradle`의 `runtimeOnly` 한 줄로 선택된다. bootstrap의 끄는 장치(MasterSwitch, import filter, scan 제외 정규식, 흩어진 validator)는 capability가 모듈 안으로 들어가는 만큼 삭제한다. + +**Tech Stack:** Java 21, Spring Boot 4.0.8, Gradle 멀티모듈(registry `src/config/architecture/modules.json`), JUnit 5 + AssertJ + ArchUnit, Testcontainers(PostgreSQL 등), Flyway. + +**Spec:** `docs/superpowers/specs/2026-09-25-capability-module-packaging-design.md` (확정). 입력 리뷰: `docs/reviews/2026-09-24-src-module-code-review.md`(1차), `docs/reviews/2026-09-24-src-maintainability-review.md`(2차). + +## Global Constraints + +- 기본 조립 방식: **B — 서비스가 고른 capability만 `runtimeOnly` 한 줄** (spec 10절 1). +- 템플릿 기본 포함: web 인바운드 + 운영 관측 + 코어 + support/identifier. 나머지는 전부 기본 제외 (spec 10절 2). +- HARD-STOP 7개(`AGENTS.md`)는 모든 Wave에서 유지한다. 특히 5번: 모든 project 의존성은 `modules.json`의 `allowed_dependencies` 안에 있어야 한다. +- 커밋은 `human-only`. 에이전트는 stage/commit/amend/push 하지 않는다. Wave마다 `git diff` 스냅샷을 scratchpad에 남겨 추적한다. +- 이미 적용됐을 수 있는 Flyway versioned migration은 바이트를 바꾸지 않는다. 수정은 새 버전으로만 한다. +- 설정 키: 동작하지 않는 옵션은 설정 키 자체를 두지 않는다 (spec 6절 3). +- 문서에 leaf 개수를 적지 않는다 (registry가 SSOT). +- Gradle은 한 작업 트리에서 동시에 하나만 돌린다. 병렬 작업은 별도 복사본에서만 한다. + +## Review Focus + +사용자가 가장 먼저 부딪힐 입력·조건과 기대 동작. 각 줄의 테스트는 해당 Task에 넣는다. + +1. **이미 V9/V13이 적용된 DB로 기동** → checksum mismatch 없이 기동해야 한다. (Task 0-5: 적용 파일 해시 고정 테스트 + 원복) +2. **Docker 빌드 컨텍스트(`src`만 있음)에서 Gradle 실행** → compose 파일이 없어도 설정 단계가 통과해야 한다. (Task 0-3: compose 파일 없는 루트에서 `help` 성공 테스트) +3. **`APP_MESSAGING_PRODUCER_ID`를 비워 둔 채 messaging 활성화** → bridge bean만 생기지 않고 기동은 성공해야 한다. (Task 0-7: 빈 값·공백 값 테스트) +4. **prod에서 `APP_SERVER_ERROR_INCLUDE_STACKTRACE=always` 같은 env override** → 기동이 exit 71로 실패해야 한다. 대소문자(`Prod`, `ALWAYS`)도 같다. (Task 0-8) +5. **capability 한 줄을 지운 빌드** → 그 기능의 bean·설정 바인딩·validator가 전부 사라지고 나머지는 그대로 기동해야 한다. (Wave 4 완료 기준 — 기본 조립 system test) + +--- + +## 실행 방식 + +- Wave 0: 현재 세션에서 직접 실행(작고 서로 독립). +- Wave 1 이후: Wave마다 시작 시점에 이 문서 아래 "Wave N 상세 Task"를 추가한 뒤 실행한다(rolling-wave). 작업 단위 하나를 구현 subagent 하나에 맡기고, 끝나면 리뷰 subagent가 확인한다. Gradle 충돌을 피하려고 같은 작업 트리에서는 순차로 돌리고, 병렬이 필요하면 `rsync`로 만든 복사본에서 돌린 뒤 diff를 되가져온다. +- 매 Wave 종료 시: focused test + `./gradlew architectureCheck --console=plain` + (영향 범위에 따라) 통합 lane. Wave 종료 기록은 맨 아래 "진행 기록"에 남긴다. + +## Wave 개요 + +| Wave | spec 9절 단계 | 내용 | 완료 기준 | +|---|---|---|---| +| 0 | 1, 2(Wave 0) | 규칙 고정(AGENTS.md) + 결정 불필요 차단 결함 7건 | 7건 각각 회귀 테스트 통과, architectureCheck 통과 | +| 1 | 2(Wave 1) | 데이터·보안 Critical 10건 | 10건 각각 회귀 테스트(가능하면 포트 계약 테스트) 통과 | +| 2 | 3 | 분류 3(잔재) 삭제, 분류 4(실험용 자리) 삭제 | 삭제 후 전체 leaf `check` + architectureCheck 통과 | +| 3 | D1(분류 2) | 분류 2(라이브러리형 API) — 완성해서 포장(동작하지 않는 약속 제거, web 라이브러리는 opt-in leaf로 분리) | 기준 3 위반 0, web 기본 leaf에 라이브러리 없음 | +| 4 | 4 | 분류 1 capability 포장 + 기본 조립 web-only + 끄는 장치 삭제 | spec 6절 완료 기준 7개를 capability마다 충족, 기본 조립 system test 통과 | +| 5 | 5 | 빌드 O3(바로 할 것 1–12 포함) + 테스트 컨벤션(sample부터) | `ci` 통과, build-logic/build-tools 축소 | + +--- + +## Wave 0 — 규칙 고정 + 결정 불필요 차단 결함 + +### Task 0-1: 결정 기록 + +**Files:** +- Modify: `docs/superpowers/specs/2026-09-25-capability-module-packaging-design.md` (상태, 10절) + +- [x] **Step 1:** 10절을 "결정"으로 바꾸고 B안 확정, 기본 포함 목록(web만)과 해석 근거를 적는다. + +### Task 0-2: capability 완료 기준과 테스트 컨벤션을 AGENTS.md에 고정 + +**Files:** +- Modify: `AGENTS.md` (새 절 "부가 기능(capability) 모듈 규칙", "테스트 전략"에 컨벤션) +- Modify: `CLAUDE.md` (Testing 절에 포인터, capability 규칙 한 줄 요약) + +- [x] **Step 1: AGENTS.md에 capability 규칙 절 추가** — spec 6절 완료 기준 7개를 그대로 옮기고, 기본 조립 목록(spec 10절 2)과 "기능 추가 = `runtimeOnly` 한 줄 + env" 절차를 적는다. settings 규칙(prefix 하나, `StrictSettingsBinder`, compact constructor 검증)도 여기 둔다. +- [x] **Step 2: AGENTS.md "테스트 전략"에 컨벤션 6개 추가** — 2차 리뷰 TEST 절 "제안 컨벤션" 1–6(이름=행동 문장이고 이름이 약속한 성질을 단언, `@DisplayName` 선택·영어, GWT 주석은 본문 3문장 이상일 때 필수·`// when` 하나, `@Nested` 조건, 단언 규칙, 포트 fake는 포트 소유 모듈 testFixtures에 하나 + fake와 adapter가 같은 `XxxContract` 통과, Mockito는 프레임워크 경계만). 적용 범위: 새로 쓰거나 고치는 테스트. 주석 게이트는 만들지 않는다(이유 한 줄). +- [x] **Step 3: CLAUDE.md 동기화** — Testing 절 끝에 "테스트 작성 규칙과 capability 모듈 규칙은 `AGENTS.md`가 정본" 한 줄, capability 규칙 3줄 요약. +- [x] **Step 4: 확인** — `grep -n "capability" AGENTS.md CLAUDE.md`로 두 문서가 같은 7개 기준을 가리키는지 본다(요약과 정본이 어긋나지 않게). + +### Task 0-3: O-1 — compose overlay 확인을 task 실행 시점으로 + +1차 Critical #1. `DeveloperBootstrapPlugin.apply()`가 compose overlay가 없으면 설정 단계에서 실패해, Docker 빌드 컨텍스트(`src`만 있음)에서 어떤 task도 못 돈다. + +**Files:** +- Modify: `src/build-logic/src/main/java/dev/caskeleton/buildlogic/bootstrap/DeveloperBootstrapPlugin.java:40-50` +- Test: `src/build-logic/src/test/java/dev/caskeleton/buildlogic/bootstrap/DeveloperBootstrapPluginFunctionalTest.java` + +- [x] **Step 1: 실패하는 테스트 작성** — compose 파일이 하나도 없는 루트에서 `help`가 성공해야 한다. 기존 "없는 profile 거부" 테스트는 `tasks` 대신 `bootstrapDockerPreflight` 실행으로 바꾼다(거부는 task 실행 시점으로 옮겨진다). + +```java + @Test + void configurationDoesNotRequireComposeFiles(@TempDir Path temporaryDirectory) + throws IOException { + // The Docker image build copies only src/ into the build context, so the repository root and + // its compose files do not exist there. Configuring the root project must still succeed. + Path projectDirectory = fixtureWithoutComposeFiles(temporaryDirectory); + + BuildResult result = run(projectDirectory, "help"); + + assertThat(result.getOutput()).contains("BUILD SUCCESSFUL"); + } + + @Test + void aProfileWithNoOverlayIsRefusedAndTheMessageListsTheRealOnes( + @TempDir Path temporaryDirectory) throws IOException { + Path projectDirectory = fixture(temporaryDirectory); + + BuildResult failure = + runAndFail(projectDirectory, "bootstrapDockerPreflight", "-PbootstrapProfile=staging"); + + assertThat(failure.getOutput()) + .contains("names no overlay") + .contains("docker-compose.staging.yml") + .contains("[dev, local]"); + } +``` + +`fixtureWithoutComposeFiles`는 `fixture`와 같되 `docker-compose*.yml`을 만들지 않는다(`fixture`가 이것을 호출한 뒤 compose 파일을 추가하도록 나눈다). + +- [x] **Step 2: 실패 확인** — `cd src && ./gradlew :build-logic:test --tests '*DeveloperBootstrapPluginFunctionalTest' --console=plain` → `configurationDoesNotRequireComposeFiles` FAIL("names no overlay"). +- [x] **Step 3: 구현** — `apply()`의 overlay 확인 블록을 지우고 `bootstrapDockerPreflight`에 `doFirst`로 옮긴다. 캡처하는 값은 `File`/`String`만(configuration cache 호환). + +```java + task.doFirst( + ignored -> requireOverlay(overlay, bootstrapProfile, repositoryDirectory)); +``` + +```java + private static void requireOverlay(File overlay, String profile, File repositoryDirectory) { + if (!overlay.isFile()) { + throw new GradleException( + "bootstrap: -P" + PROFILE_PROPERTY + "=" + profile + " names no overlay; expected " + + overlay.getName() + " beside docker-compose.yml. Available: " + + availableProfiles(repositoryDirectory)); + } + } +``` + +- [x] **Step 4: 통과 확인** — Step 2 명령 → 5개 테스트 PASS. + +### Task 0-4: O-2 — 항상 실패하는 `redis-sdk` CI job 삭제 + +1차 Critical #2. `--tests '*…'`의 따옴표가 word-split 뒤에도 남아 매칭 0 → 항상 실패, `release-gate`가 success 요구. 같은 테스트는 이미 `:shared-contract:test`로 `ci`에서 돈다. + +**Files:** +- Modify: `.github/workflows/ci-quality-gates.yml` (`redis-sdk:` job 블록, `release-gate`의 `needs`·`REDIS_RESULT` 두 줄) + +- [x] **Step 1:** `redis-sdk:` job 블록 전체와 `release-gate`의 `- redis-sdk`, `REDIS_RESULT: ...`, `"${REDIS_RESULT}" \` 줄을 지운다. +- [x] **Step 2: 확인** — `grep -n "redis-sdk\|REDIS_RESULT" .github/workflows/ci-quality-gates.yml` → 0건. `python3 -c "import yaml,sys; yaml.safe_load(open('.github/workflows/ci-quality-gates.yml'))"` → 오류 없음. + +### Task 0-5: E-1 — 적용된 migration 원복 + 새 버전 + 해시 고정 + +1차 Critical #3. `postgresql/V9`, `postgresql/V13`이 적용 후 제자리 수정됐다(9da00eb7). 기본 Flyway location이라 이전 파일이 적용된 모든 DB가 checksum mismatch로 기동 실패한다. + +범위 결정: 세 번째 파일 `jpa/outbox-storage/V1`은 어떤 composition도 location을 설정하지 않은 미조립 V2 outbox 세대다. Wave 2(D2)에서 그 세대를 migration 트리째 삭제하므로 여기서는 손대지 않는다. + +**Files:** +- Restore: `src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/postgresql/V9__widen_capability_schema_stream.sql` (`9da00eb7^` 바이트) +- Restore: `.../postgresql/V13__outbox_canonical_transport_compatibility.sql` (`9da00eb7^` 바이트) +- Create: `.../postgresql/V16__outbox_canonical_hash_columns_varchar.sql` +- Create: `src/adapter/outbound/persistence-jpa/src/test/resources/db/applied-migrations.sha256` +- Create: `src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/AppliedMigrationImmutabilityTest.java` +- Modify: `.../migration/PostgreSqlConstraintMigrationSafetyTest.java` (V13 NOT VALID 단언 → V16 varchar 단언) + +- [x] **Step 1: 해시 고정 테스트 작성** — 매니페스트(` `)에 있는 파일은 바이트가 같아야 하고, 디스크의 모든 `V*.sql`은 매니페스트에 있어야 한다. 줄 끝은 `\n`으로 정규화(CRLF checkout 오탐 방지). + +```java +class AppliedMigrationImmutabilityTest { + + private static final Path MIGRATIONS = Path.of("src/main/resources/db/migration"); + private static final Path MANIFEST = Path.of("src/test/resources/db/applied-migrations.sha256"); + + @Test + void appliedMigrationsKeepTheBytesTheyWereAppliedWith() throws IOException { + // given + Map pinned = pinnedChecksums(); + + // when + Map actual = currentChecksums(); + + // then + assertThat(actual) + .as("an applied migration changed; add a new version instead of editing it") + .containsAllEntriesOf(pinned); + } + + @Test + void everyVersionedMigrationIsPinned() throws IOException { + // given + Map pinned = pinnedChecksums(); + + // when + Map actual = currentChecksums(); + + // then + assertThat(pinned.keySet()) + .as("pin a new migration in %s when it is added", MANIFEST) + .containsAll(actual.keySet()); + } + // pinnedChecksums(): 매니페스트 파싱, currentChecksums(): Files.walk로 V*.sql 수집 후 정규화 SHA-256 +} +``` + +- [x] **Step 2: 원복** — `git show 9da00eb7^: > `로 V9·V13을 되돌린다. +- [x] **Step 3: 매니페스트 생성** — 원복된 트리에서 모든 `V*.sql`의 정규화 SHA-256을 기록한다(원복 파일이 기준). V16은 Step 4 뒤에 추가. +- [x] **Step 4: V16 작성** — 9da00eb7이 V13에서 바꾼 `char(64)→varchar(64)`를 새 버전으로 옮긴다. 이미 varchar인 DB에서는 no-op. + +```sql +-- V13 created the canonical hash columns as char(64). The JPA mapping is String(length = 64), +-- which Hibernate validates as varchar, so ddl-auto=validate rejected a database migrated through +-- V13. Every stored value is exactly 64 hex characters, so widening keeps the data unchanged; on a +-- database whose columns are already varchar(64) this is a no-op. +ALTER TABLE outbox_event + ALTER COLUMN partition_key TYPE varchar(64), + ALTER COLUMN schema_set_hash TYPE varchar(64), + ALTER COLUMN envelope_sha256 TYPE varchar(64), + ALTER COLUMN envelope_schema_hash TYPE varchar(64), + ALTER COLUMN payload_schema_hash TYPE varchar(64); +``` + +- [x] **Step 5: `PostgreSqlConstraintMigrationSafetyTest` 갱신** — V13 내용 단언(varchar, NOT VALID) 2개를 "V16이 다섯 컬럼을 varchar(64)로 바꾼다" 단언 하나로 교체. V14 단언은 유지. +- [x] **Step 6: 확인** — `./gradlew :adapter:outbound:persistence-jpa:test --console=plain` PASS. Docker lane: `./gradlew :adapter:outbound:persistence-jpa:postgresqlIntegrationTest --tests '*Migration*' --console=plain` PASS(실제 PostgreSQL에서 V1→V16 적용 + `ddl-auto=validate`). +- [x] **Step 7: 문서** — `docs/` migration 안내(기존 persistence-jpa README의 migration 절)에 "09-23~09-25 사이 새로 만든 개발 DB는 `flyway repair` 필요" 한 줄. + +### Task 0-6: L-1 — outbox relay가 `@EnableScheduling` 없이 멈춤 + +1차 Critical #5. 앱 전체의 `@EnableScheduling`이 `idempotency.provider=jdbc` 조건부 `IdempotencyConfig`에만 있어, outbox relay가 다른 provider 조합에서 조용히 멈춘다. + +**Files:** +- Modify: `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxConfig.java` +- Test: `src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxConfigTest.java` + +- [x] **Step 1: 실패하는 테스트** + +```java + @Test + void outboxCapabilityEnablesSchedulingWithoutTheJdbcIdempotencyProvider() { + // given + ApplicationContextRunner runner = + new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(OutboxConfig.class)) + .withPropertyValues( + "ca-skeleton.outbox.enabled=true", "ca-skeleton.outbox.relay-enabled=false"); + + // when & then + runner.run( + context -> + assertThat(context) + .hasBean(TaskManagementConfigUtils.SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME)); + } +``` + +- [x] **Step 2: 실패 확인** — `./gradlew :app-bootstrap:test --tests '*OutboxConfigTest' --console=plain` → FAIL. +- [x] **Step 3: 구현** — `OutboxConfig`에 `@EnableScheduling` 추가(이미 `ca-skeleton.outbox.enabled`로 gate됨). +- [x] **Step 4: 통과 확인** — Step 2 명령 PASS. + +### Task 0-7: H-1 — messaging bridge 조립 순서 + 빈 producer-id + +1차 Critical #6. (a) bridge auto-config에 `after` 지정이 없어 알파벳 순서상 platform보다 먼저 평가되고 `@ConditionalOnBean(EncodedMessagePublisher)`가 항상 false. (b) `producer-id: ${APP_MESSAGING_PRODUCER_ID:}`가 빈 문자열로 존재해 `@ConditionalOnProperty`를 통과 → `new ProducerId("")` 예외. + +**Files:** +- Modify: `src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/autoconfigure/MessagingBridgeRootAutoConfiguration.java` +- Test: `src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/autoconfigure/MessagingPlatformBridgeAutoConfigurationTest.java` +- Create (test): `src/adapter/outbound/messaging/src/test/java/dev/caskeleton/messaging/autoconfigure/MessagingPlatformRootAutoConfiguration.java` — 실제 starter 클래스와 같은 FQN의 테스트 대역. 이 leaf의 test classpath에는 starter가 없으므로 충돌하지 않는다. `EncodedMessagePublisher` bean 하나만 등록한다. 목적: Boot의 auto-config 정렬(`afterName`)을 실제로 거치게 해서 (a)를 재현. + +- [x] **Step 1: 실패하는 테스트 2개** + +```java + @Test + void bridgeIsAssembledAfterThePlatformRootThatProvidesThePublisher() { + // given + ApplicationContextRunner assembled = + new ApplicationContextRunner() + .withConfiguration( + AutoConfigurations.of( + MessagingBridgeRootAutoConfiguration.class, + dev.caskeleton.messaging.autoconfigure.MessagingPlatformRootAutoConfiguration + .class)) + .withBean(FailOpenDependencyLogger.class, FailOpenDependencyLogger::new) + .withPropertyValues( + "app.messaging.enabled=true", "app.messaging.producer-id=portfolio-service"); + + // when & then + assembled.run( + context -> assertThat(context).hasSingleBean(IntegrationEventPublishPort.class)); + } + + @ParameterizedTest + @ValueSource(strings = {"", " "}) + void blankProducerIdLeavesTheBridgeOutWithoutFailingStartup(String producerId) { + runner + .withPropertyValues("app.messaging.producer-id=" + producerId) + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context).doesNotHaveBean(IntegrationEventPublishPort.class); + }); + } +``` + +- [x] **Step 2: 실패 확인** — `./gradlew :adapter:outbound:messaging:test --tests '*MessagingPlatformBridgeAutoConfigurationTest' --console=plain` → 두 테스트 FAIL. +- [x] **Step 3: 구현** + +```java +@AutoConfiguration( + afterName = "dev.caskeleton.messaging.autoconfigure.MessagingPlatformRootAutoConfiguration") +... + @Bean + @ConditionalOnBean(EncodedMessagePublisher.class) + @ConditionalOnMissingBean(IntegrationEventPublishPort.class) + @Conditional(ProducerIdConfigured.class) + public IntegrationEventPublishPort integrationEventPublishPort(...) + + /** {@code producer-id} is always present as a key (the yml default is empty), so presence alone is not configuration. */ + static final class ProducerIdConfigured extends SpringBootCondition { + @Override + public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { + String producerId = context.getEnvironment().getProperty("app.messaging.producer-id"); + return StringUtils.hasText(producerId) + ? ConditionOutcome.match("app.messaging.producer-id is set") + : ConditionOutcome.noMatch("app.messaging.producer-id is blank"); + } + } +``` + +- [x] **Step 4: 통과 확인** — Step 2 명령 PASS. + +### Task 0-8: L-2 — prod 에러 상세 노출 차단을 실제 코드로 + +1차 L-2. `application-prod.yml`은 "`StartupSafetyValidator`가 error-detail 노출을 막는다"고 적지만 그 검사는 9da00eb7에서 지워졌다. `spring.web.error.include-*`는 env로 prod에서도 켜진다. + +**Files:** +- Create: `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/ErrorDetailExposureSafetyValidator.java` +- Modify: `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/RuntimeSafetyConfig.java` (bean 등록) +- Test: `src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/ErrorDetailExposureSafetyValidatorTest.java` +- Modify(문서): `src/app-bootstrap/src/main/resources/application-prod.yml:13`, `src/app-bootstrap/README.md`(StartupSafetyValidator 절, RuntimeSafetySettings 절), `src/README.md`(Runtime safety 절) + +- [x] **Step 1: 실패하는 테스트** — `JpaSchemaSafetyValidatorTest`와 같은 `ApplicationContextRunner` 모양. + +```java + @ParameterizedTest + @CsvSource({ + "spring.web.error.include-stacktrace, always, APP_SERVER_ERROR_INCLUDE_STACKTRACE", + "spring.web.error.include-stacktrace, ON_PARAM, APP_SERVER_ERROR_INCLUDE_STACKTRACE", + "spring.web.error.include-message, always, APP_SERVER_ERROR_INCLUDE_MESSAGE", + "spring.web.error.include-binding-errors, always, spring.web.error.include-binding-errors", + "spring.web.error.include-exception, true, spring.web.error.include-exception" + }) + void prodRefusesToStartWhenErrorDetailsWouldReachClients(String key, String value, String named) { + runner + .withInitializer(context -> context.getEnvironment().setActiveProfiles("Prod")) + .withPropertyValues(key + "=" + value) + .run( + context -> { + assertThat(context).hasFailed(); + assertThat(context.getStartupFailure()) + .isInstanceOf(ProfileMismatchException.class) + .hasStackTraceContaining(named); + }); + } + + @Test + void prodStartsWhenEveryErrorDetailStaysHidden() { /* never/never/never/false → hasNotFailed */ } + + @Test + void nonProdMayExposeErrorDetailsForDebugging() { /* local + always → hasNotFailed */ } +``` + +- [x] **Step 2: 실패 확인** — `./gradlew :app-bootstrap:test --tests '*ErrorDetailExposureSafetyValidatorTest' --console=plain` → 컴파일 실패(클래스 없음). +- [x] **Step 3: 구현** — `SmartInitializingSingleton`. prod 판정은 `RuntimeProfileSnapshot.from(environment).isProduction()`(기존 validator와 같음). 위반을 모아 `StartupFailures.profileMismatch(...)` 한 번(exit 71). 키→사용자에게 보여줄 env 이름 표: stacktrace→`APP_SERVER_ERROR_INCLUDE_STACKTRACE`, message→`APP_SERVER_ERROR_INCLUDE_MESSAGE`, binding-errors·exception→property 이름 그대로. +- [x] **Step 4: 등록** — `RuntimeSafetyConfig`에 `@Bean ErrorDetailExposureSafetyValidator`. +- [x] **Step 5: 통과 확인** — Step 2 명령 PASS. +- [x] **Step 6: 문서 4곳 정정** — 거짓 주장("StartupSafetyValidator가 막는다", "shipped 구현이 없다", "5종")을 새 validator 이름과 실제 검사 키로 바꾼다. + +### Task 0-9: L-3 — sample actuator `loggers`를 읽기 전용으로 + +1차 L-3. sample은 `loggers`를 노출하고 모든 경로가 `permitAll`이라 인증 없이 로그 레벨을 바꿀 수 있다. + +**Files:** +- Modify: `src/sample-portfolio/src/main/resources/application.yml` (`management.endpoint.loggers.access: read-only`) +- Test: sample의 기존 actuator/설정 테스트에 단언 추가, 없으면 `SampleActuatorLoggersAccessTest`(yml을 `YamlPropertySourceLoader`로 읽어 값 단언). + +- [x] **Step 1: 실패하는 테스트** — `management.endpoint.loggers.access`가 `read-only`인지 단언. +- [x] **Step 2: 실패 확인** — `./gradlew :sample-portfolio:test --tests '*Loggers*' --console=plain` → FAIL. +- [x] **Step 3: 구현** — yml에 한 줄. +- [x] **Step 4: 통과 확인** — Step 2 명령 PASS. + +### Wave 0 종료 검증 + +- [x] `cd src && ./gradlew :build-logic:test :adapter:outbound:persistence-jpa:test :adapter:outbound:messaging:test :app-bootstrap:test :sample-portfolio:test --console=plain` +- [x] `./gradlew architectureCheck --console=plain` +- [x] `./gradlew :adapter:outbound:persistence-jpa:postgresqlIntegrationTest --tests '*Migration*' --console=plain` (Docker) +- [x] `git diff > /wave-0.patch`, 진행 기록 갱신 + +--- + +## Wave 1 — 데이터·보안 Critical 10건 + +각 항목은 "재현 테스트 먼저 → 수정 → 통과". fake가 결함을 숨긴 포트는 포트 소유 모듈 testFixtures에 추상 계약 테스트(`XxxContract`)를 만들고 fake와 실제 adapter가 둘 다 상속한다(spec 6절 5, 2차 리뷰 권고 순서 1). 상세 Task는 Wave 1 시작 때 이 절 아래에 추가한다. + +| # | 결함 (1차 리뷰) | 위치 | 수정 방향 | 회귀 테스트 | +|---|---|---|---|---| +| 1-1 | #4 durable operation 재제출이 PG 25P02 | `persistence-jpa/.../operation/DurableOperationStoreAdapter.java:47-78` | native `INSERT … ON CONFLICT DO NOTHING` 후 0건이면 기존 row 조회(`JpaNotificationRequestStore` 방식) | `DurableOperationStoreContract`(application-core testFixtures) — in-memory fake + PG adapter(Testcontainers)가 같은 이중 submit 시나리오 통과 | +| 1-2 | #12 web이 operation 조회·취소 유스케이스를 대신 수행(HARD-STOP 4) | `web/.../operationasync/OperationQueryService.java` | application-core에 `GetDurableOperationUseCase`(Query), `CancelDurableOperationUseCase`(Command + `@UseCaseCapability`), owner·tenant 판정은 `ObjectAccessPolicy` 뒤로; web은 요청 컨텍스트 변환만 | use case 단위 테스트(fake store), web slice 테스트 | +| 1-3 | #7 outbox relay·DLQ·retry-topic이 인코딩된 메시지를 재인코딩 | `messaging-outbox-jdbc-postgresql/.../OutboxRelay.java:223-229`, `DefaultMessagePublisher.java:177` | 이미 인코딩된 `EncodedMessage`는 raw publish 경로로(재인코딩 없이 transport로) | relay → publisher 경로 테스트: 저장된 row가 PUBLISHED | +| 1-4 | #8 Kafka TLS/SASL 설정이 producer에 적용 안 됨 | `messaging-spring-boot-starter-kafka/.../KafkaMessagingAutoConfiguration.java:109-154` | `KafkaSecurityConfigurer`를 producer properties 생성에 실제로 적용 | producer config에 `security.protocol`/`sasl.*`/`ssl.*`가 들어가는지 단언 | +| 1-5 | #9 알림 recovery/replay가 트랜잭션 없이 `@Modifying` 실행 | `adapter/outbound/notification/.../LeaseRecoveryService.java:106` 외 3곳 | 행 단위 작업을 `TransactionPort.inWrite`로 감쌈 | PG lane에서 `recoverOnce`/`replayOnce` 실제 실행 | +| 1-6 | #10 SNS 서명 검증 우회(호스트, TopicArn, Timestamp) | `.../ses/SnsSignatureVerifier.java:99-109`, `SesProviderCallbackAssembler.java:19` | 호스트 `^sns\.[a-z0-9-]+\.amazonaws\.com(\.cn)?$`, SES callback 켜면 `allowed-topic-arns` 필수, 오래된 Timestamp 거부, 인증서 캐시 상한 | S3 버킷 URL·타 토픽·오래된 메시지 거부 테스트 | +| 1-7 | #11 tus `Upload-Checksum`을 누적 digest와, 커밋 후 비교 | `web-fileserver/.../tus/TusController.java:167-174` | append에 기대 checksum 전달, chunk digest를 커밋 전에 검증, 불일치 시 롤백·460 | 정상 checksum 2번째 chunk 성공 + 불일치 chunk가 offset을 올리지 않음(tus 계약 테스트, fake digest도 chunk 단위로) | +| 1-8 | #13 GraphQL 인가 단계 fragment 재귀 전개 무제한 | `graphql/.../runtime/GraphQlDocumentAuthorizationHandler.java:109-137` | 방문 budget(노드 수 상한) + fragment 전개 memo, 초과 시 거부 | 1.6KB 중첩 fragment 문서가 제한 시간 안에 거부 | +| 1-9 | #14 Redis SCRIPT lane 한도가 동시 lease 수 → 정상 Redis에서도 9번째부터 거부 | `redis-runtime/.../RedisRuntimeOwner.java:134-140`, `RedisSdkSettings.java:687` | lane 한도를 연결(connection) 수에 맞게, lease는 대기 후 획득(짧은 timeout) | 동시 호출 N > 한도에서 정상 Redis면 전부 성공(fake gateway 동시성 테스트) | +| 1-10 | #15 gRPC 멱등성: FAILED_TERMINAL 행에서 claim 없이 PROCEED | `grpc/grpc-policy/.../GrpcIdempotencyInterceptor.java:109-114` | FAILED_TERMINAL은 재claim(새 attempt) 또는 거부로 명시, fake ledger도 같은 전이 규칙 | `GrpcOperationLedgerContract`(grpc-testkit) — fake와 JPA ledger 공통 | + +완료 기준: 10건 각각 회귀 테스트가 수정 전 FAIL·수정 후 PASS. 영향 leaf `check` + `architectureCheck` 통과. Docker 필요한 lane(1-1, 1-5, 1-10 JPA ledger)은 실제 실행. + +### Wave 1 상세 Task (작업 묶음) + +서로 다른 leaf를 건드리는 7개 묶음으로 나눠 복사본에서 병렬 실행한다. 묶음마다 구현 subagent 하나. + +| 묶음 | 항목 | 건드리는 leaf | 검증 명령 (`src/`에서) | +|---|---|---|---| +| W1-OP | 1-1, 1-2 | application-core(+testFixtures), persistence-jpa, adapter:inbound:web | `:application-core:check :adapter:outbound:persistence-jpa:check :adapter:inbound:web:check`, PG lane(durable operation) | +| W1-MSG | 1-3, 1-4 | messaging-outbox-jdbc-postgresql, messaging-runtime-core, messaging-spring-boot-starter-kafka | 해당 leaf `check` | +| W1-NOTIF | 1-5, 1-6 | adapter:outbound:notification(+ application-notification 필요 시) | leaf `check` + PG lane(recovery/replay) | +| W1-TUS | 1-7 | adapter:inbound:web-fileserver, application-fileserver, adapter:outbound:fileserver | leaf `check` | +| W1-GQL | 1-8 | adapter:inbound:graphql | leaf `check` | +| W1-REDIS | 1-9 | redis-runtime(+ cache-redis 영향 시) | leaf `check` | +| W1-GRPC | 1-10 | optional build `grpc:grpc-policy`, `grpc:grpc-testkit`, `grpc:grpc-operation-ledger-jpa` | `./gradlew -p optional-platforms :check`, ledger PG lane | + +공통 절차(각 묶음): +- [x] 재현 테스트 작성 → 실행해서 FAIL 확인(출력 기록) +- [x] 최소 수정 → 같은 테스트 PASS +- [x] fake가 결함을 숨긴 포트는 추상 계약 테스트로 fake·adapter 양쪽 실행 +- [x] `spotlessApply`, 영향 leaf `check`, `architectureCheck` +- [x] 복사본 diff를 main 작업 트리에 반영 후 main에서 영향 leaf `check` 재실행 + +--- + +## Wave 2 — 분류 3(리팩터링 잔재)·분류 4(실험용 자리) 삭제 + +원칙(spec 5절, 8절 D2–D4): 한 기능에 한 세대만 남긴다. 삭제한 것은 `docs/capability-status.md`의 "제거된 코드" 표에 마지막으로 존재한 커밋과 함께 한 줄씩 적는다(복구 경로). 분류 4는 SDK가 없거나 기동 시 거부되므로 optional build로 옮기지 않고 삭제한다(2차 리뷰 S7 #1 권고: experimental 4개·Debezium 삭제; rabbit은 기동 거부·운영 채널 구현 없음). + +| # | 대상 | 남길 것 | 삭제 | 근거 | +|---|---|---|---|---| +| 2-A | web 2세대·WebFlux | servlet 1세대(`RequestLoggingFilter`, `RateLimitInterceptor`, `ETags`, `PageParams`, Envelope 에러) | `webflux/*`, `advanced/webflux`, `callback/reactive`, web-fileserver reactive; 2세대 conditional/pagination/throttle/admission/access-log, `WebMvcPlatformAutoConfiguration`의 미사용 bean 9개·evidence filter·startup check·`admin/platform`, `cursor/CursorCodec`, main의 `moduleboundary`; WebProblem 어휘는 fixture 전용이면 삭제 | D4, S5 #2–#4, #8 | +| 2-B | outbox 3세대 | v1 `outbox_event` + fencing(owner+token CAS) | app-core `outbox/v2`, persistence-jpa `postgresql/outbox`, `jpa/outbox-storage`·`jpa/outbox-polling` 트리(미조립), `OutboxV2RetryPolicy` | D2, X1 #1. 새 migration `V17` (lease_owner, lease_token) | +| 2-C | 멱등성 2세대 | V2(이름에서 `V2` 제거), 조립 1곳 | v1 executor·port·adapter·H2/PG claim repo·`IdempotencyConfig`, websocket `CommittedResultLedger`, graphql `idempotencyKey` 미연결 allowlist | D3, X1 #2. sample을 V2로 이전 | +| 2-D | notification R1 | R2 platform | application-notification 루트 R1 타입, Reactor facade·의존성, `spring-web` 의존, 미사용 platform 코드(throw 0 예외, security 3종, sms/push/email/webpush), `NotificationOrchestrator`, contract-v1 템플릿 | 1차 B-8, S1 #10 #14 | +| 2-E | messaging adapter R1 | canonical bridge + R0 seam | `envelope`·`contract`·`destination`·`config` R1 체인, `realtime/MessagingDurableFanoutAdapter`, NetworkNT 런타임 의존 | S4 #2 | +| 2-F | fileserver R1/R2 publication | `platform/**` HTTP 파일 서버 | 루트 패키지 publication(31파일), app-core `filepublication`, `FileExportPort`, `app.fileserver.*`·`app.file-export.*` 설정 | S4 #1, X1 #8 | +| 2-G | STOMP 2벌, main의 governance gate | `stomp/` 스택 | `advanced/stomp/**`, `StompBrokerExclusivity`, websocket `moduleboundary`·`evidence`·`release`, graphql `architecture/`(런타임 경계 검사 — ArchUnit이 이미 검사)·`compat/`·`moduleboundary`, grpc 상수 gate·`GrpcStableModuleCatalog` | S5 #7 #11, S6 #1, S7 #4 | +| 2-H | 두 번째 트랜잭션·재시도 엔진, Mongo reactive 쌍둥이 | port 기반 엔진, imperative Mongo | persistence-jpa `SpringJpaTransactionExecutor` 계열, Mongo `reactive/**`·change stream | S2 #3 #5 | +| 2-I | messaging 분류 4 | Kafka | `messaging-pulsar-experimental`, `-nats-experimental`, `-kafka-share-experimental`, `-spring-cloud-stream-bridge`, `-rabbit`, `-starter-rabbit`, Debezium 클래스; starter의 미사용 edge(cloudevents, claim-check) | spec 5절 분류 4, S7 #1 #5 | +| 2-J | 호출자 0 잔재 | — | httpclient `BoundedErrorBody`·`spring7/`·`migration/`, objectstorage legacy adoption(켜면 기동 실패), `UuidCodec`, `CompiledPackageScanner`, app-core `@Deprecated` 캐시 executor 계열(소비자 확인 후), `PolicyTransactionPort` 계열 | 1차 A-9, S1 #3 #8, S3 #8, S4 #10 | + +완료 기준: 삭제한 타입의 main 참조 0(`grep -rw`), registry·settings·문서의 참조 정리, 영향 leaf `check` + `architectureCheck` + `:app-bootstrap:architectureTest` 통과, `docs/capability-status.md` 제거 표 갱신. + +### Wave 2 상세 Task (작업 묶음) + +사전 조사(읽기 전용) 결과로 범위를 확정했다. 조사에서 "아직 쓰인다"로 확인된 것은 삭제 대상에서 뺐다: +`PolicyTransactionPort` 계열(fileserver 보상 트랜잭션이 사용 — 삭제가 아니라 `TransactionPort.inNew`로 교체 후 삭제), +cache 타입 9개(cache-redis 사용), `IdempotencyReaper`와 멱등성 엔티티(V2 행 정리에 필요), v1 패키지의 공용 타입 8개(V2가 사용), +`NotificationSubmissionService`의 진입 메서드, `NotificationPort` bean. + +| 묶음 | 대상 | 결정 | +|---|---|---| +| W2-1 | T-F 파일 서버 publication 평면, T-G websocket 중복 STOMP·governance, T-J httpclient/identifier/objectstorage legacy 잔재 | 전부 삭제. MasterSwitch `FILESERVER`(R1 스위치)와 문서·env key 동반 삭제 | +| W2-2 | T-G graphql governance(`architecture/`, `compat/`, `moduleboundary`, `release`), T-E messaging adapter R1 체인, T-I messaging 분류 4 leaf | graphql 부팅 시 경계 검사에서 잃는 규칙 2개(resolver는 transport 타입만 반환, raw `DataFetcher`는 infra에만)는 ArchUnit으로 옮긴다. `IntegrationEventEncoderPort`는 adopter 확장 지점으로 남기고 검증 메시지만 고친다. rabbit·pulsar·nats·kafka-share·stream-bridge·Debezium 삭제 | +| W2-3 | T-A web 2세대·WebFlux·WebProblem | 전부 삭제. WebProblem을 인증하던 fixture lane은 transport 동작을 보는 것(Jetty 호환)은 Envelope 기준으로 고치고, WebProblem 표면만 인증하던 것은 삭제 | +| W2-4 | T-D notification R1, T-H 두 번째 트랜잭션 엔진·Mongo reactive, T-J application-core 잔재(cache 20개, `LeaseWatchdog`, inbox, `EphemeralFanoutPort`, 미사용 lock/write 실행기), `PolicyTransactionPort` 교체 | 삭제 + fileserver 보상 트랜잭션을 `TransactionPort.inNew`로 | +| W2-5 | T-B outbox V2 삭제 + v1 fencing(D2) | V2 코드·`jpa/outbox-storage`·`jpa/outbox-polling` 트리 삭제(어떤 조립도 적용한 적 없음), `V17` lease_owner/lease_token + CAS 완료 처리 | +| W2-6 | T-C 멱등성 v1 삭제(D3) | V2 정본. PostgreSQL provider는 켜지면 자기 migration stream(`jpa/idempotency`)을 적용해야 "켜면 동작"(기준 3)을 충족. 실행기 조립은 한 곳. sample을 V2로 이전. `IdempotencyReaper`는 `postgresql` provider로 재조건 | + +조사 원문: scratchpad `w2-inventory-A.md`, `w2-inventory-B.md`(세션 산출물). 순서: W2-1·W2-2·W2-4 병렬 → W2-3 → W2-5 → W2-6(동작 변경). + +--- + +## Wave 3 — 분류 2(라이브러리형 API) + +spec 5절: "완성해서 1번처럼 포장하거나 `optional-platforms`로 이동". 대상: redis-sdk, Mongo `advanced` 등, JPA 플랫폼 라이브러리, graphql `advanced`, websocket 플랫폼 라이브러리, web의 기본 경로 밖 라이브러리 패키지. + +**확인한 사실 (2026-09-25 실험):** optional build(`src/optional-platforms`)에 `includeBuild('..')`를 넣으면 main build를 composite로 불러와 `dev.caskeleton:` 좌표로 받을 수는 있다. 그러나 (1) redis-sdk의 테스트 전체가 cache-redis 테스트 소스에 들어 있어 이동하려면 테스트 이전이 먼저이고, (2) B안에서는 서비스가 고르지 않은 leaf가 jar에 들어가지 않으므로 optional build로 옮겨도 서비스가 내는 비용(jar·CVE·기동)은 줄지 않는다. 줄어드는 것은 main `ci` 시간뿐이다. + +**결정:** 분류 2는 "옮기기" 대신 "완성해서 포장"으로 처리한다. 라이브러리는 유지하되: +1. 동작하지 않는 약속은 없앤다(기준 3): 어떤 코드도 바인딩하지 않는 설정 키, 켜면 기동이 실패하는 `Unsupported` 플래그, 구현체 없는 인터페이스, main에 있는 promotion/release/evidence gate, 테스트에서만 쓰는 main 클래스. +2. 남는 라이브러리 API는 leaf README에 "라이브러리 API — 서비스의 어댑터 leaf에서 `implementation`으로 받아 직접 호출"로 적는다(AGENTS.md capability 규칙의 라이브러리형 예외). +3. 기본 조립에 들어가는 leaf(`adapter:inbound:web`)에 있는 라이브러리 패키지는 opt-in leaf `adapter:inbound:web-advanced`로 분리한다. 기본 서비스가 쓰지 않는 코드를 싣지 않게 하기 위해서다. +4. redis-sdk는 이미 독립 leaf다. 테스트를 cache-redis에서 redis-sdk leaf로 옮겨 cache-redis가 테스트에서도 redis-sdk에 의존하지 않게 한다. + +| 묶음 | leaf | 내용 | +|---|---|---| +| W3-1 | redis-sdk, cache-redis | SDK 테스트 이전, cache-redis의 redis-sdk test edge 제거, README | +| W3-2 | adapter:inbound:web → web-advanced | 기본 경로 밖 패키지(advanced, admin/route, budget, cache, contract, operation, proxy 등) 분리, registry 등록 | +| W3-2b | web-advanced | W3-2 결과 후속: `advanced/functional`(WebFlux `RouterFunction` — D4상 servlet 전용 템플릿에서 동작 불가)과 운영이 이미 다른 방식으로 하는 기능의 중복 패키지(`proxy`↔`forward-headers-strategy`, `security` 프로필↔`SecurityConfig`, `cache`↔`CacheControlFilter`, `json` factory↔Boot Jackson, `openapi` customizer↔`OpenApiContractConfig`) 삭제 — "한 기능에 한 세대" | +| W3-3 | graphql | 동작하지 않는 약속 제거, 라이브러리 API 문서화 | +| W3-4 | websocket | 같음 | +| W3-5 | persistence-mongo | 같음(구현체 없는 인터페이스 10개, 바인딩 안 되는 `advanced.*.enabled` 등) | +| W3-6 | persistence-jpa | 같음(지원 표면 밖 단일 구현 인터페이스, 호출자 없는 실행기 등) | + +완료 기준: 각 leaf에서 기준 3 위반(동작하지 않는 설정·인터페이스·gate) 0건, README에 라이브러리 API 목록, web 기본 leaf에 라이브러리 패키지 없음, 영향 leaf `check` + `architectureCheck` 통과. + +--- + +## Wave 4 — 분류 1 capability 포장 + 기본 조립 web-only + +대상 capability와 "한 줄": + +| capability | `app-bootstrap/build.gradle` 한 줄 | 모듈로 옮길 bootstrap 코드 | +|---|---|---| +| JPA/PostgreSQL (Flyway, TransactionPort, outbox store, JDBC 멱등성, 분산 락) | `runtimeOnly project(':adapter:outbound:persistence-jpa')` | `autoconfigure/jpa/*`, `autoconfigure/lock/*`, JPA 계열 `runtime/*Validator`, `MigrationStartup*`, `DataSourceRequirement` | +| outbox relay | (JPA + Kafka를 둘 다 고르면 켜짐) | `autoconfigure/outbox/*` → 발행 쪽 capability(messaging)로, `@ConditionalOnBean(OutboxStorePort)` + `afterName` | +| Redis (cache/lock/idempotency/rate-limit) | `runtimeOnly project(':adapter:outbound:cache-redis')` | `autoconfigure/redis/*`, Redis 계열 validator | +| Kafka 발행 | `runtimeOnly project(':adapter:outbound:messaging-kafka')` (bridge + platform starter-kafka를 끌어옴) | `autoconfigure/messaging/*`, `DisabledMessagingSentinelAutoConfiguration` 삭제 | +| 알림 (SES/SMTP) | `runtimeOnly project(':adapter:outbound:notification')` | `autoconfigure/notification/*`; notification persistence를 `persistence-notification` leaf로 추출(S2 #1), web notification HTTP를 `adapter:inbound:web-notification`으로 추출(S5 #9). 미조립 provider 5종 삭제(spec 6절 3) | +| Mongo | `runtimeOnly project(':adapter:outbound:persistence-mongo')` | `MongoOptInAutoConfigurationImportFilter` 삭제, "있으면 켜짐" | +| object storage (S3) | `runtimeOnly project(':adapter:outbound:objectstorage')` | 모듈 자체 auto-config 정리 | +| HTTP client | `runtimeOnly project(':adapter:outbound:httpclient')` | master switch 제거 | +| GraphQL | `runtimeOnly project(':adapter:inbound:graphql')` | `GraphQlOffAutoConfigurationImportFilter` 삭제 | +| WebSocket / gRPC 어댑터 | `runtimeOnly project(':adapter:inbound:websocket')` / `grpc` | conditional-transport qualification을 기본 조립 테스트로 대체 | +| 파일 서버 | `runtimeOnly project(':composition:fileserver-platform')` | bootstrap의 fileserver 스위치·설정·`dependencyPolicy` 항목 삭제 | + +capability마다 spec 6절 완료 기준 7개를 체크한다: 포트만 호출 / 자기 `AutoConfiguration.imports` + `enabled`(기본 true) + `afterName` / 켜면 완전히 동작 / prefix 하나 + `StrictSettingsBinder` + compact constructor / 포트 계약 테스트(fake + adapter, Testcontainers 1개 이상) / README(제공·한 줄·env) / bootstrap이 모듈을 모름. + +bootstrap에서 삭제: `MasterSwitch`(+ shared-contract `activation`), `MasterSwitchEnvironmentPostProcessor`, `CapabilityDependency*`, `AdapterActivation*`, `CaSkeletonApplication` scan 제외 정규식(scan은 `dev.caskeleton.bootstrap`으로 좁히고 web은 자기 auto-config 공개), 흩어진 startup validator(각 capability로 이동하거나 `StartupRule` 목록 하나로). + +아키텍처 검사 분리(spec 7절): `architectureTest` classpath에는 모든 모듈을 테스트 의존으로, 운영 `runtimeClasspath`에는 고른 모듈만. + +기본 조립: web + 관측 + 코어 + support/identifier. 나머지 한 줄은 주석으로 목록에 남긴다. + +완료 기준: +- 기본 조립으로 `bootRun`/system test 기동 성공, DB·Redis·Kafka 없이. +- capability 한 줄을 추가/삭제하는 system test(대표 3개: JPA, Redis, Kafka)가 bean 생성/부재를 확인. +- 끄는 장치 5종(MasterSwitch, import filter 2, sentinel, scan 정규식)의 main 참조 0. +- sample-portfolio가 자기 조립(JPA, objectstorage, web, identifier 한 줄씩)으로 기동·테스트 통과. + +--- + +### Wave 4 상세 Task (작업 묶음) + +조사 결과(세션 산출물 `w4-inventory.md`)로 순서를 정했다. 모두 app-bootstrap을 건드리므로 JPA 계열은 순차, 나머지는 파일이 겹치지 않는 범위에서 병렬. + +| 묶음 | 내용 | +|---|---| +| W4-1 | 준비: 옮겨 갈 클래스가 쓰는 bootstrap 전용 helper(`StartupFailures`, `ReadinessGroup` 등)를 `adapter:outbound:support`로, persistence-jpa에 support edge 추가, 연결 안 된 `JpaPlatformAutoConfiguration` 삭제. lock·outbox·Redis 조립 코드를 각 leaf로(outbox relay는 발행 포트 bean이 있을 때만), `DisabledMessagingSentinelAutoConfiguration` 삭제 | +| W4-2 | JPA root(`autoconfigure/jpa/*`, JPA validator, Flyway startup, `application.yml`의 datasource/flyway/jpa 블록, `persistence.yml`)를 persistence-jpa로. `JpaOffAutoConfigurationImportFilter`·`DataSourceRequirement` 삭제. sample이 broad scan 대신 leaf auto-config로 JPA를 받게 | +| W4-3 | 알림: `composition/notification-platform` 신설(조립 클래스 2개 + `notification.yml`), web의 `notification/` callback ingress를 web 밖으로 옮겨 기본 web이 `application-notification`을 싣지 않게 | +| W4-4 | messaging·Mongo·GraphQL·httpclient·objectstorage·websocket·gRPC·파일 서버: import filter 삭제, "있으면 켜짐"(`enabled` 기본 true), 설정 yml을 leaf로, Rabbit 설정 키 제거 | +| W4-5 | 끄는 장치 철거(`MasterSwitch`·activation 패키지·scan 정규식·`CapabilityDependency*`·`AdapterActivation*`), 기본 조립을 web-only로 바꾸고 나머지는 주석 한 줄 목록, architectureTest classpath에 모든 leaf, registry 정리, 관련 테스트 삭제·재작성, 기본 조립 기동 테스트 + capability 한 줄 추가/삭제 테스트(JPA·Redis·Kafka), capability README(제공·한 줄·env) | + +## Wave 5 — 빌드 O3 + 테스트 컨벤션 + +1. 2차 리뷰 BUILD 절 "바로 할 것" 1–12를 순서대로 적용한다(Wave 2–4에서 이미 사라진 대상은 건너뛰고 진행 기록에 적는다). +2. O3: build-logic에는 registry, 방향·순수성 task, 컨벤션, 레인 하나만. 기능별 검사(evidence, readiness, API-surface, family plugin)는 소유 leaf 테스트로 옮기고, 읽는 파일은 `inputs`로 선언한다. build-tools는 비운다. +3. 테스트 컨벤션: `sample-portfolio` 전체 테스트를 AGENTS.md 컨벤션으로 재작성(`WorkLogRepositoryContract`로 fake와 adapter 공통 계약, `TransactionPort` fake는 application-core testFixtures 하나). + +완료 기준: `./gradlew ci --console=plain` 통과, build-logic+build-tools 줄 수 감소 기록, sample 테스트 GWT 컨벤션 적용. + +--- + +## 진행 기록 + +| Wave | 상태 | 검증 | 스냅샷 | 비고 | +|---|---|---|---|---| +| 0 | 완료 (2026-09-25) | build-logic test, persistence-jpa·messaging·app-bootstrap·sample `check`, `architectureCheck`, PG lane `postgresqlMigrationIntegrationTest`·`postgresqlLegacyOutboxRowLifecycleIntegrationTest` 전부 통과 | scratchpad `wave-0.patch` | outbox-storage V1은 Wave 2(D2 삭제)로 넘김. V16 적용 확인(실제 PostgreSQL) | +| 1 | 완료 (2026-09-25) | 10건 모두 재현 테스트 FAIL→PASS. main에서 영향 leaf 20개 `check` + `app-bootstrap:check` + `sample-portfolio:check` + `architectureCheck` + `verifyDependencyLocks` + `verifyEnvKeys` 통과, optional gRPC `check`·ledger PG lane 통과. PG lane(durable operation 계약 24, notification background 7), gRPC ledger 계약 16 실제 DB 통과 | scratchpad `wave-1-cumulative.patch` | 새 env key `APP_NOTIFICATION_PLATFORM_SES_ALLOWED_TOPIC_ARNS`(SES 콜백 사용 시 필수). 남은 것: Redis 실제 lane 기존 실패 4건(테스트 ACL에 TIME 권한 없음, 시계 +1h), durable operation 같은 id 재시도 시 outbox 중복, Redis idempotency/lease의 lane 거부 분류가 Indeterminate, Kafka truststore/keystore 설정 키 없음 | +| 2 | 완료 (2026-09-25) | W2-1~W2-6 반영 후 main 전체 `check` + `architectureCheck` + locks + env keys + public path + config contract 통과. W2-5 fencing은 실제 PG에서 중복 전달 재현 후 해결, W2-6 PostgreSQL 멱등성은 빈 DB에서 실패 재현 후 해결 | scratchpad `wt-w2*.patch` | 제거 목록은 `docs/capability-status.md` "제거된 코드" 표 | +| 3 | 완료 (2026-09-25) | W3-1~W3-6, W3-2b 반영 후 main 전체 `check` 통과(Redis/Mongo/websocket/web/JPA/graphql 실제 lane은 각 묶음에서 실행) | scratchpad `wt-w3*.patch` | web 기본 leaf 13.9k→5.3k줄(라이브러리는 opt-in `web-advanced`), graphql 22k→12.8k, websocket 10.2k→1.9k. 추가 수정: notification admin 결과 codec jsonb 공백 결함(기존) | +| 4 | 완료 (2026-09-25) | main 전체 `check` + `architectureCheck` + locks + env keys + public path + config contract + `qualificationBootJar` 통과. 기본 runtimeClasspath = web·identifier·support·domain-core·application-core·shared-contract. `DefaultCompositionBootTest`(local/dev/prod, DB·Redis·Kafka 없이) + capability별 활성화 테스트 | scratchpad `wt-w4*.patch` | 끄는 장치(MasterSwitch·activation·scan 정규식·import filter·sentinel) 제거. CI compose 18 lane 실제 실행 안 함(정적 검증만). `S3AsyncResponseBodyBridgeTest` 부하 시 간헐 실패 | +| 5 | 완료 (2026-09-25) | `check`(481 task), `ci verifyDependencyLocks --warning-mode=fail`, `mainCheck`(14 lane 152 tests), build-logic 80·build-tools 35 tests, bootstrap/sample integration·system, configuration cache 통과 | scratchpad `wt-w51/w52/wfin.patch` | 빌드 코드 17.2k→10.8k줄(바로 할 것 1–12 적용, notification·mongo·messaging·graphql·jpa 검사를 leaf 테스트로). sample 테스트 컨벤션 적용(test 198→283, integration 13→49). 남은 설계 결정: `verifyEnvKeys`·JPA evidence·redis topology lane 이동 여부 | diff --git a/docs/superpowers/specs/2026-09-25-capability-module-packaging-design.md b/docs/superpowers/specs/2026-09-25-capability-module-packaging-design.md new file mode 100644 index 00000000..bb7e8833 --- /dev/null +++ b/docs/superpowers/specs/2026-09-25-capability-module-packaging-design.md @@ -0,0 +1,128 @@ +# 부가 기능(capability) 제공 방식과 리뷰 후속 정리 — 설계 초안 + +- 상태: **확정** (2026-09-25 소유자 결정 2건 반영 — 10절). 실행 계획: `docs/superpowers/plans/2026-09-25-capability-module-packaging.md` +- 작성: 2026-09-25 +- 입력: + - `docs/reviews/2026-09-24-src-module-code-review.md` (1차, 결함 중심 — Critical 15 / Required 76) + - `docs/reviews/2026-09-24-src-maintainability-review.md` (2차, 구조·SRP·공통 계약·테스트·빌드 비례성) +- 목표: 템플릿에서 새 프로젝트를 만들 때 도메인과 비즈니스 로직을 바로 붙이고, 실무에서 자주 쓰는 부가 기능(Redis, Kafka 등)은 필요할 때 빠르게 붙일 수 있게 한다. + +## 1. 전제 (소유자 설명) + +2차 리뷰에서 "연결 안 된 코드 약 15만 줄"로 잡힌 코드 상당수는 **의도적으로 넣어 둔 부가 기능**이다. 프로젝트마다 자주 쓰는 외부 기술(Redis, Kafka 등)을 템플릿이 미리 제공하려고 만들었다. 그러다 너무 커져서 지금 리팩터링하는 중이다. 따라서 목표는 부가 기능을 없애는 것이 아니라 **제공 방식을 바꾸는 것**이다. + +## 2. 핵심 결론 + +부가 기능을 제공하는 방향은 유지한다. 문제는 제공 방식이다. 지금은 부가 기능이 두 가지 상태로 흩어져 있다. + +- (a) 기본 모듈 안에 섞여 있다. +- (b) 설정으로 켜도 실제로 동작하지 않는 반쪽 상태다. + +그래서 그 기능을 쓰지 않는 서비스도 비용을 낸다. 해법은 두 가지다. + +- 부가 기능 하나하나를 **"의존성을 붙이면 켜지고, 떼면 사라지는 capability 모듈"**로 포장한다(Spring Boot starter와 같은 방식). +- 각 서비스는 필요한 모듈만 `runtimeOnly` 한 줄로 고른다. + +## 3. 흐름 + +``` +[도메인·유스케이스 코드] ──(포트만 호출)──▶ application-core 포트 (CachePort, LockPort …) + ▲ 구현 +app-bootstrap/build.gradle │ + runtimeOnly ':adapter:outbound:cache-redis' ──▶ cache-redis 모듈 + ├─ META-INF/spring/…AutoConfiguration.imports + └─ app.redis.* 설정 + 연결 env +``` + +기능 추가: `app-bootstrap/build.gradle`에 한 줄을 넣고, `.env`에 연결 정보를 넣는다. 유스케이스는 원래 쓰던 포트를 그대로 호출한다. +기능 제거: 그 한 줄을 지운다. 다른 파일은 손대지 않는다. + +```groovy +// app-bootstrap/build.gradle — 이 서비스가 쓰는 부가 기능 목록 (한 곳에서 관리) +dependencies { + runtimeOnly project(':adapter:outbound:cache-redis') // Redis: cache / lock / idempotency / rate-limit + runtimeOnly project(':adapter:outbound:messaging-kafka') // Kafka 발행 + // runtimeOnly project(':adapter:outbound:persistence-mongo') + // runtimeOnly project(':adapter:outbound:objectstorage') +} +``` + +## 4. 조립 방식 비교 + +| 방식 | 추가 속도 | 비용 | +|---|---|---| +| A. 모든 모듈을 runtimeOnly로 기본 포함 + 설정으로 on/off | 설정만 바꾸면 됨 | 끄는 장치 필요, 모든 서비스가 모든 의존성·CVE·이미지 크기를 짊어짐 | +| **B. 서비스가 고른 것만 runtimeOnly 한 줄 + "모듈이 있으면 켜짐" (권장)** | 한 줄 + env | 끄는 장치 불필요. upstream(템플릿) merge 시 서비스 쪽 차이는 이 목록 한 곳뿐 | +| C. 각 기능을 버전 붙은 사내 라이브러리로 배포 | 버전 한 줄 | 배포 파이프라인 필요. 파생 서비스가 3개 이상일 때 검토 | + +**A를 권하지 않는 이유:** Spring Boot는 "라이브러리가 classpath에 있으면 켠다"가 기본 동작이다. 쓰지 않는 기능을 jar에 넣어 두면 그것을 끄는 장치가 따로 필요하다. 지금 저장소에 있는 아래 목록이 바로 그 장치이고, 2차 리뷰에서 "활성화 규칙 6곳, 기본값 3가지"로 나온 복잡도의 원인이다. + +- `MongoOptInAutoConfigurationImportFilter` +- `GraphQlOffAutoConfigurationImportFilter` +- `DisabledMessagingSentinelAutoConfiguration` +- `CaSkeletonApplication`의 scan 제외 정규식(18개 패키지) +- `MasterSwitch` +- 흩어진 startup validator 19개 + +`runtimeOnly`라는 방식 자체는 맞다. 비즈니스 코드가 어댑터를 import하지 못하게 되기 때문이다. 다만 **서비스가 고른 것만** 넣어야 끄는 장치가 필요 없어진다. + +## 5. "연결 안 된 코드" 4분류 + +| 분류 | 예 | 처리 | +|---|---|---| +| 1. 제공할 부가 기능 (포트 뒤에 있음) | Redis cache/lock/idempotency/rate-limit, Kafka 발행, S3 object storage, SES/SMTP 알림, httpclient, Mongo 기본 연결 | 유지. 6절 완료 기준을 채워 capability 모듈로 포장 | +| 2. 라이브러리형 API (서비스 코드가 직접 호출) | redis-sdk facade(구현체 없음), Mongo advanced 연산, JPA bulk/copy, graphql advanced, websocket 플랫폼 라이브러리 | 완성해서 1번처럼 포장하거나 `optional-platforms`로 이동 | +| 3. 리팩터링 잔재 (이전·병행 세대) | web 2세대, WebFlux 쌍둥이, outbox V2와 v1, 멱등성 v1, notification R1, messaging R1 encoder, fileserver R2 publication, STOMP 스택 2벌, main에 있는 governance gate | 하나만 남기고 삭제. 제공 기능이 줄지 않으면서 크기가 가장 많이 줄어듦 | +| 4. SDK도 없는 실험용 자리 | pulsar, nats, kafka-share, stream-bridge, 기동 시 거부되는 rabbit, grpc-advanced | `optional-platforms`로 이동하거나 삭제 | + +모듈별 LOC와 근거는 2차 리뷰의 "조립되지 않은 코드 추정치" 표와 S1–S7 절에 있다. + +## 6. capability 모듈 완료 기준 + +1. 서비스 코드는 application-core의 **포트만** 호출한다. 그래서 모듈을 `runtimeOnly`로 받을 수 있다. +2. 모듈이 자기 `AutoConfiguration.imports`를 가진다. 모듈이 있으면 켜지고, 필요하면 `enabled` 설정으로 끌 수 있다. 다른 자동 설정에 기대는 경우 순서를 명시한다(`afterName`). 1차 리뷰 Critical #6(messaging bridge)이 이 순서 문제였다. +3. **켜면 완전히 동작한다.** 문서에 적은 옵션은 전부 실제로 동작해야 하고, 동작하지 않는 옵션은 설정 키 자체를 두지 않는다. 반례: 알림 provider 7종 중 5종은 켜면 기동에 실패한다. +4. 설정 prefix는 하나만 쓴다. 바인딩은 `StrictSettingsBinder`로 하고, 값 검증은 설정 record의 compact constructor에서 한다. +5. application-core testFixtures에 있는 **포트 계약 테스트**(추상 클래스)를 fake와 실제 어댑터가 모두 통과한다. 실제 벤더(Testcontainers)로 도는 테스트가 1개 이상 있다. +6. README에 세 가지를 적는다: 제공하는 것, 추가할 한 줄, 필요한 env 키. +7. 이 모듈을 아는 곳은 모듈 자신뿐이다. bootstrap의 scan 정규식이나 `MasterSwitch` 목록에 등록할 필요가 없고, 한 줄을 지우면 기능이 완전히 사라진다. + +## 7. 주의할 점 + +- **`runtimeOnly`의 한계:** 분류 2처럼 서비스 코드가 모듈 타입을 직접 호출하는 경우에는 `runtimeOnly`로 컴파일되지 않는다. 이런 모듈은 서비스의 어댑터 leaf에서 `implementation`으로 받아야 한다. 부가 기능은 가능한 한 분류 1(포트 뒤) 형태로 만든다. +- **아키텍처 검사 범위:** 운영 jar에 고른 모듈만 들어가면, app-bootstrap architectureTest의 classpath 기준으로 도는 ArchUnit이 빠진 모듈을 보지 못한다. 그래서 둘을 분리한다. + - architectureTest classpath에는 **모든 모듈을 테스트 의존으로** 넣는다. + - 운영 runtimeClasspath에는 고른 모듈만 넣는다. + - 참고로 Gradle 방향 검사는 이미 모든 leaf를 본다. + - 1차 리뷰 L-4에서 sample과 grpc 어댑터가 ArchUnit에서 빠진 것도 같은 원인이다. + +## 8. 리뷰 결정 D1–D6 권고 (이 방향 기준) + +| # | 결정 | 권고 | +|---|---|---| +| D1 | 연결 안 된 코드 | 5절 4분류를 적용한다: 1은 포장, 2는 완성 또는 이동, 3은 삭제, 4는 이동 | +| D2 | outbox 정본 | 앱 outbox를 하나로 합친다. v1 테이블을 유지하고 V2/V1002의 owner+token fencing을 이식한 뒤 V2를 삭제한다. Kafka capability는 이 outbox를 relay한다. messaging platform outbox는 vendored라 유지한다 | +| D3 | 멱등성 정본 | V2. Redis와 PostgreSQL 두 provider가 같은 포트를 구현하고, executor는 한 곳에서 조립한다 | +| D4 | WebFlux | 템플릿은 servlet(가상 스레드)으로 정하고 WebFlux 쌍둥이 코드는 삭제한다. 필요해지면 capability로 다시 추가한다 | +| D5 | 빌드 목표 | O3. 기능별 검증은 각 capability 모듈의 테스트로 옮기고, build-logic에는 아키텍처 검사와 공통 규칙만 남긴다. 먼저 2차 리뷰 BUILD 절의 "바로 할 것" 1–12를 적용한다 | +| D6 | 테스트 컨벤션 | 2차 리뷰 TEST 절의 제안안을 채택한다. 포트 계약 테스트가 6절 완료 기준 5번과 같은 것이다 | + +## 9. 진행 순서 + +1. capability 완료 기준(6절)과 테스트 컨벤션을 `AGENTS.md`에 고정한다. `CLAUDE.md`는 요약만 동기화한다. +2. 1차 리뷰 Critical을 수정한다. 대부분 제공 기능 자체의 결함이라 먼저 고친다. 수정 PR마다 해당 포트의 계약 테스트를 함께 추가한다. + - Wave 0(결정 불필요): 빌드 plugin(O-1), CI job(O-2), 마이그레이션 원복 + 새 버전(E-1), `@EnableScheduling`(L-1), bridge 순서/producer-id(H-1), prod 에러 상세 validator(L-2), sample loggers read-only(L-3) + - Wave 1: 나머지 데이터·보안 Critical +3. 분류 3·4를 삭제하거나 이동한다. 크기가 가장 많이 줄어든다. +4. 분류 1을 capability 모듈로 하나씩 포장한다. 끝날 때마다 bootstrap의 끄는 장치(import filter, scan 정규식, MasterSwitch 항목, 해당 validator)를 걷어낸다. +5. 빌드를 O3로 옮기고, 테스트 컨벤션을 적용한다(sample-portfolio부터 모범 예제로). + +## 10. 결정 (2026-09-25 소유자 확정) + +1. 기본 조립 방식은 **B(서비스가 고른 것만 runtimeOnly)**로 확정한다. +2. 템플릿이 처음부터 켜 두는 기능은 **web에서 쓰는 부분뿐**이다. + - 기본 포함: HTTP 인바운드(`adapter:inbound:web` — servlet, 보안, 에러 응답, 요청 로깅), 운영 관측(actuator·metrics·tracing·로그), 도메인·유스케이스 코어(`domain-core`, `application-core`, `shared-contract`), 저장소가 필요 없는 보조(`adapter:outbound:support`, `adapter:outbound:identifier`). + - 기본 제외(한 줄로 추가): JPA/PostgreSQL(Flyway·outbox·JDBC 멱등성·분산 락 포함), Redis, Kafka, 알림, Mongo, object storage, HTTP client, GraphQL, WebSocket, gRPC, 파일 서버. + - 해석 근거: "web에서 사용하는 부분"을 인바운드 HTTP와 그 운영 요소로 읽었다. DB도 기본에서 뺐으므로 새 서비스는 DB가 필요하면 `persistence-jpa` 한 줄을 넣는다. 이 해석이 다르면 `app-bootstrap/build.gradle`의 해당 줄 주석만 푼다(다른 파일 변경 없음 — 6절 7번). + +실행 계획: `docs/superpowers/plans/2026-09-25-capability-module-packaging.md` (Wave 0부터). diff --git a/docs/testing/TESTING_STRATEGY.md b/docs/testing/TESTING_STRATEGY.md index fc074ef5..50a4f770 100644 --- a/docs/testing/TESTING_STRATEGY.md +++ b/docs/testing/TESTING_STRATEGY.md @@ -71,7 +71,7 @@ Markdown 표와 Gradle source set을 대조하는 parser는 current-state를 또 | Application use case | TEST | fake/stub port, 필요 최소 mock | | startup validator / settings validation | TEST | `MockEnvironment` 또는 순수 객체 | | Spring `@Configuration` 한 조각 | TEST | `ApplicationContextRunner` | -| MVC/WebFlux controller 한 slice | TEST | framework slice test | +| MVC controller 한 slice | TEST | framework slice test | | hermetic serialization/API snapshot | TEST | contract assertion | | JPA repository + 실제 PostgreSQL | INTEGRATION | Testcontainers/real DB | | Kafka/Rabbit/Redis/Mongo와 실제 프로토콜 통신 | INTEGRATION | real service/container | diff --git a/docs/web/advanced-capabilities.md b/docs/web/advanced-capabilities.md index 9f398b3f..0491db98 100644 --- a/docs/web/advanced-capabilities.md +++ b/docs/web/advanced-capabilities.md @@ -1,58 +1,77 @@ # Web Advanced: support matrix -Every capability is off unless named. `WebAdvancedPromotionGate.forFeature` is the machine-checked -form of the last two columns; if this table disagrees with it, the code wins. +The Advanced capabilities live in their own leaf, `adapter:inbound:web-advanced` +(`src/adapter/inbound/web-advanced`, package `dev.caskeleton.adapter.inbound.web.advanced`). No +default composition carries it: `app-bootstrap` and `sample-portfolio` do not depend on it. A +service that wants one of these capabilities adds the leaf as `implementation` in its own adapter +leaf and calls the types directly. -| Capability | Flag | What it adds | Required suites | Soak | -| --- | --- | --- | --- | --- | -| `MVC_VIRTUAL_THREADS` | `backend.web.advanced.mvc-virtual-threads.enabled` | A different scheduling model for **every** request | `web:test`, `webCrossStackParityTest`, `virtual-thread-admission`, `pinning-jfr` | 24h | -| `WEBFLUX_BLOCKING_BRIDGE` | `…webflux-blocking-bridge.enabled` | A bounded offload; affects the shared event loop | `web:test`, `blocking-bridge-bounded`, `event-loop-guard` | 24h | -| `JSON_MERGE_PATCH` | `…json-merge-patch.enabled` | RFC 7396, partial documents | `web:test`, `patch-security`, `patch-atomicity` | 8h | -| `JSON_PATCH` | `…json-patch.enabled` | RFC 6902, arbitrary pointers | as merge patch | 8h | -| `SSE` | `…sse.enabled` | Long-lived connections | `web:test`, `streaming-soak-10k`, `slow-consumer-bounded`, `cancellation-propagation`, `pod-drain` | 24h | -| `NDJSON` | `…ndjson.enabled` | Long-lived connections | as SSE | 24h | -| `JSON_SEQUENCE` | `…json-sequence.enabled` | Long-lived connections | as SSE | 24h | -| `FUNCTIONAL_WEBFLUX` | `…functional-webflux.enabled` | Routes with no annotation to scan | `web:test`, `functional-route-parity` | 8h | -| `CBOR` | `…cbor.enabled` | A second decoder | `web:test`, `codec-security`, `codec-budget` | 8h | -| `XML` | `…xml.enabled` | A decoder with dangerous defaults | as CBOR | 8h | -| `OPENAPI_32` | `…openapi-32.enabled` | A parallel description artifact | `web:test`, `openapi-32-toolchain-matrix` | 8h | -| `RATELIMIT_DRAFT_HEADERS` | `…ratelimit-draft-headers.enabled` | Additive response headers | `web:test`, `ratelimit-draft-headers` | 8h | +Three capabilities have a runtime switch, published through the leaf's own +`META-INF/spring/...AutoConfiguration.imports`. Everything else is a library: no property, no bean, +nothing happens until service code calls it. -## Two capabilities change requests that do not use them +| Capability | How it is turned on | What it adds | Tests | +| --- | --- | --- | --- | +| MVC virtual threads | `backend.web.advanced.mvc-virtual-threads.enabled=true` (+ admission limit and budgets) | A different scheduling model for **every** request | `MvcAdvancedConfigurationTest`, `VirtualThreadAdmissionTest` | +| NDJSON streaming | `backend.web.advanced.ndjson.enabled=true` | Long-lived connections | `MvcStreamingWiringTest`, `WebStreamCoreTest`, `WebStreamDrainTest`, `WebStreamingSoakIT` | +| JSON text sequences (RFC 7464) | `backend.web.advanced.json-sequence.enabled=true` | Long-lived connections | as NDJSON | +| JSON Merge Patch (RFC 7396) | library — `JsonMergePatchApplier` | Partial documents | `JsonMergePatchApplierTest` | +| JSON Patch (RFC 6902) | library — `JsonPatchApplier` | Arbitrary pointers | `JsonPatchApplierTest` | +| CBOR / XML codecs | library — `WebCborMapperFactory`, `WebXmlMapperFactory`; the backend jar is the service's choice | A second decoder | `WebCodecMapperTest`, `WebCodecSecurityTest` | +| OpenAPI 3.2 | library — `WebOpenApi32Generator` | A parallel description artifact | `WebOpenApi32GeneratorTest` | +| Stream replay from messaging | library — `MessagingReplayBridge` | Resume after reconnect | `MessagingReplayBridgeTest` | -`WebAdvancedFeature.affectsUnrelatedRequests()` is true for exactly `MVC_VIRTUAL_THREADS` and -`WEBFLUX_BLOCKING_BRIDGE`. A codec affects only requests that negotiate it; a virtual-thread -executor affects every request in the process, and the blocking bridge affects the event loop they -all share. `WebAdvancedFeatureFlags.stableBehaviourPreserved()` reports whether either is on. +The same leaf also holds the web library packages the servlet production path never reaches: +`http` (URI and method policy), `versioning`, `operation`, `budget`, `contract`, `security` +(security-context bridge), `idempotency` (`JsonIdempotentResponseCodec`) and `admin/route`. -That distinction is why those two soak for 24 hours and why their rollback test is the one that -matters most. +`./gradlew :adapter:inbound:web-advanced:test` runs all of it. `webAdvancedTest` is the tagged +subset and fails when the tag selects nothing. + +## Removed on 2026-09-25 + +- The promotion/release gate (`WebAdvancedPromotionGate`, `WebAdvancedReleaseManifest`, + `WebAdvancedFeature`) and the OpenAPI 3.2 promotion report (`OpenApi32CompatibilityReport`, + `OpenApiToolchainMatrix`). They were checks on this repository's release process kept in + production code, and only their own tests called them. The feature catalog also named flags that + no code reads (`…json-merge-patch.enabled`, `…sse.enabled`, `…cbor.enabled` and others). +- `advanced.blockingbridge`: the accounting half of the WebFlux blocking bridge, whose adapter went + with the WebFlux twin. +- `functional` (`FunctionalRouteRegistry`, `WebFunctionalHandlerAdapter`): it built a WebFlux + `RouterFunction`, which nothing serves in a servlet-only template (D4). `spring-webflux` left the + leaf with it. +- Packages that re-implemented what the production web path already does another way, and the + `webNginxProxyTest` lane that certified only one of them: + - `proxy` + `http.External*` — production uses `server.forward-headers-strategy` + (`app-bootstrap/src/main/resources/config/server.yml`). + - `security` CORS/CSRF profiles — production uses `CorsSettings` and `SecurityConfig`. + - `cache` — production uses `CacheControlFilter`. + - `json` (`WebObjectMapperFactory`) — production uses Boot's `JsonMapper`; the streaming encoder + now writes with that bean. + - `openapi.WebOpenApiCustomizer` (+ `WebOpenApiProfile`, `CursorSchemaContributor`) — + production customizes springdoc through `OpenApiContractConfig`. + +Recovery paths are in `docs/capability-status.md` (the removed-code table). ## What is refused, and why the row is here | Refused | Reason | | --- | --- | | Virtual threads without an admission limit | The pool size *was* the admission policy. Removing it accepts every arrival and queues them on downstream budgets that did not grow. | -| A blocking offload for an unregistered operation | `boundedElastic()` is reachable from anywhere and unbounded in practice; an unenumerable set of offloads is invisible until the pool is the heap. | | A merge patch outside its field allowlist | A merge patch is partial, so no DTO's absent fields say "not permitted". Without an allowlist the writable set grows every time somebody adds a field. | | A JSON Patch pointer above its allowed prefix | Replacing a parent deletes every sibling, so permission on a child cannot grant it. | | A `move` whose source is unauthorized | Checking only the destination lets a caller relocate data out of a field they may not touch. | | XML with a DTD or an external entity | Billion-laughs and XXE. Neither errors when it fires; the parse succeeds and the document contains something it should not. | -| A non-JSON representation without all three gates | Flag, route `produces`, and client allowlist. An `Accept` header is not evidence the route was tested against that codec. | +| A non-JSON representation without all three gates | The enabled set the service passes to `RepresentationNegotiationPolicy`, route `produces`, and client allowlist. An `Accept` header is not evidence the route was tested against that codec. | | Compression-style silent fallback on a 406 | A client that asked only for CBOR and gets JSON parses the bytes as CBOR and fails somewhere far away. | | Changing HTTP status after commit | The body becomes half stream, half JSON, and the 200 is cached. | | Unbounded buffering for a slow consumer | It moves the client's slowness into the server's heap. | -## Promotion +## Turning it off -Each capability is promoted on its own evidence. Two conditions apply to all and are not waivable: - -- **Rollback exercised.** A flag nobody has turned off is not known to turn off. -- **Stable behaviour unchanged with the feature off.** If it is not, the feature was never optional - and every deployment has it. - -Parsers and patch appliers additionally require a security review — -`WebAdvancedPromotionGate.needsSecurityReview` names them. +Removing the dependency removes the capability. With the dependency present, the three switches +default to off; `WebAdvancedRollbackIT` asserts that no Advanced bean exists with no flag set and +with each flag explicitly `false`. See `docs/adr/ADR-WEB-ADV-001-streaming-is-live-delivery.md`, `ADR-WEB-ADV-002-virtual-threads-do-not-remove-admission.md`, and diff --git a/docs/web/openapi-32-compatibility.md b/docs/web/openapi-32-compatibility.md index 4c3abeb6..1f042656 100644 --- a/docs/web/openapi-32-compatibility.md +++ b/docs/web/openapi-32-compatibility.md @@ -9,49 +9,24 @@ The value of an API description is entirely in what consumes it. A document in a generator does not fully understand does not fail — it produces a client that compiles and is wrong, which is worse than no document at all. -So 3.1.2 stays the release artifact and 3.2 is generated beside it, with a report. +So 3.1.2 stays the release artifact and 3.2 is generated beside it. ## The invariant **Generating 3.2 must not change the 3.1 snapshot.** Both come from the same model, so a contributor that mutates it on the way to 3.2 changes the artifact that is actually shipped — silently, and only -when the experimental lane runs. +when 3.2 is generated. -`OpenApi32CompatibilityReport` hashes the snapshot before and after, and a difference is a promotion -blocker with its own message. +Nothing in this repository checks it any more. `OpenApi32CompatibilityReport` and +`OpenApiToolchainMatrix` — the promotion report that hashed the snapshot and recorded which parser, +linter, generator and client compile had read the 3.2 output — were removed on 2026-09-25: they +lived in production code and only their own tests called them. A service that generates 3.2 with +`WebOpenApi32Generator` (library, `adapter:inbound:web-advanced`) owns that check in its own build. -## The toolchain matrix - -Four kinds of tool, checked separately, because passing one says nothing about the others: - -| Kind | What it catches | What it misses | -| --- | --- | --- | -| Parser | Structural errors | Anything semantically odd | -| Linter | Style rule violations | Accepts documents a parser rejects | -| Generator | Unsupported constructs — sometimes | Usually emits a wrong-but-valid signature instead of failing | -| Client compile | The wrong signature the generator emitted | Runtime behaviour | - -`OpenApiToolchainMatrix.complete()` requires at least one passing tool of each kind. -`gaps()` names the kinds that have none. - -"OpenAPI 3.2 works" is not a statement anybody can make. "This document is read correctly by these -four tools at these versions" is. - -## Streaming descriptions - -The substantive difference between 3.1 and 3.2 for this application is how streaming responses are -described. Those differences are reported separately rather than folded into a pass/fail, because a -green pass hides what changed. - -## Promotion - -`promotionBlockers(adrAccepted)` always includes the ADR blocker until one is accepted, however -green the matrix is. A machine-checkable matrix cannot decide whether the consumer population is -ready; that is a judgement, and it belongs in +Promotion stays a judgement, recorded in `docs/adr/ADR-WEB-ADV-003-openapi-32-remains-experimental.md`. ## Running it -The experimental generation runs in its own workflow and publishes the 3.2 document and the -compatibility report as artifacts. It never runs in the release workflow, so the release artifact -cannot depend on whether it ran. +No workflow in this repository generates 3.2. `OpenApiVersionLane.STABLE_3_1` is the release +artifact; `WebOpenApi32GeneratorTest` covers the generator. diff --git a/docs/web/patch-contract.md b/docs/web/patch-contract.md index 7b58b605..8fffa985 100644 --- a/docs/web/patch-contract.md +++ b/docs/web/patch-contract.md @@ -1,6 +1,8 @@ # Web patch: the client contract -Two patch formats, and they are not interchangeable. +Two patch formats, and they are not interchangeable. Both appliers are library code in +`adapter:inbound:web-advanced` (opt-in): a service adds the leaf and calls `JsonMergePatchApplier` +or `JsonPatchApplier` from its controller. ## Choosing one diff --git a/docs/web/repository-adaptation.md b/docs/web/repository-adaptation.md index 2db0b012..4def4709 100644 --- a/docs/web/repository-adaptation.md +++ b/docs/web/repository-adaptation.md @@ -6,6 +6,12 @@ was written against a standalone repository. Four of its assumptions do not hold document records what each became and why, so a reader comparing the design to the tree is not left guessing whether a difference is a decision or a mistake. +> **2026-09-25 (D4, Wave 2 W2-3).** The template is servlet (Spring MVC) on virtual threads. The +> WebFlux twin, the second-generation problem-document/budget/throttle/admission platform, the +> durable-operation HTTP projection and the in-leaf module-boundary check were removed. HTTP errors +> are the `Envelope` written by `GlobalExceptionHandler`. What was removed, and the commit it last +> existed in, is listed in `docs/capability-status.md` ("제거된 코드"). + ## 1. Twenty-three Gradle modules became sub-packages of one leaf The design lays the platform out as `modules/web/web-core-api`, `web-contract`, `web-mvc` and so on. @@ -14,20 +20,14 @@ list, and adding twenty-three leaves to it is an architecture decision the desig repository's behalf. The JPA and GraphQL platforms reached the same fork and resolved it the same way, so this is the established answer rather than a new one. -The substitution only holds if the boundaries are enforced, because a Gradle dependency gate cannot -see inside a leaf. `WebStableModule` declares each module's identity, package, purity grade and -allowed edges; `WebModuleBoundaryTest` scans the real source tree and fails when the tree and the -declaration disagree **in either direction** — an undeclared edge, an undeclared package, or a -declared module with no source. Four negative fixtures prove each rule can fail. - -Each enum constant is already shaped like a leaf specification, so promoting a module to its own -Gradle path later is a registry edit rather than an archaeology exercise. +A Gradle dependency gate cannot see inside a leaf. The in-leaf module map that used to check the +package edges (`WebStableModule`) was removed with the second-generation platform; the ArchUnit +rules in `testkit/arch` (`WebArchitectureRules`) are what remains. | Design module | Package under `dev.caskeleton.adapter.inbound.web` | Status | | --- | --- | --- | | `web-core-api` | `core` | planned (Task 2+) | | `web-contract` | `contract` | planned | -| `web-validation` | `validation` | planned | | `web-error` | `error` | present | | `web-pagination` | `pagination` | present | | `web-idempotency` | `idempotency` | present | @@ -38,19 +38,16 @@ Gradle path later is a registry edit rather than an archaeology exercise. | `web-observability` | `observability` | present | | `web-openapi` | `openapi` | planned | | `web-mvc` | `mvc` | planned | -| `web-webflux` | `webflux` | planned | +| `web-webflux` | — | removed (D4: servlet only) | | `web-admin` | `admin` | planned | | `web-operation-jpa` | `operation.jpa` | planned | | `web-operation-messaging` | `operation.messaging` | planned | | `web-spring-boot-starter-mvc` | `autoconfigure.mvc` | planned | -| `web-spring-boot-starter-webflux` | `autoconfigure.webflux` | planned | -| `web-testkit-*` | `testkit`, `testkit.mvc`, `testkit.webflux`, `testkit.contract` | planned | -| — | `conditional`, `cursor`, `http`, `filter`, `envelope`, `config`, `controller`, `ratelimit`, `settings` | present, pre-dates the design | +| `web-spring-boot-starter-webflux` | — | removed (D4: servlet only) | +| `web-testkit-*` | `testkit`, `testkit.mvc` | present | +| — | `conditional`, `http`, `filter`, `envelope`, `config`, `controller`, `ratelimit`, `settings` | present, pre-dates the design | | — | `fileserver.*`, `notification.*` | present, feature integrations rather than platform modules | -A module is added to `WebStableModule` at the moment its package gains its first file, never before: -a declared module with no source is a claim about a rename that has not happened. - ## 2. Root package The design uses `io.backend.skeleton.web`. This repository's package root is @@ -78,10 +75,13 @@ carries the OpenAPI drift gate and the contract lanes the design's sample is spe ## 6. Idempotency: the design's store SPI is already owned by `application-core` The design gives `web-idempotency` its own `IdempotencyStore`, `IdempotencyRecord`, -`IdempotencyState`, `IdempotencyScope` and `RequestFingerprint`. This repository already has all -five in `application-core/idempotency`, with a JPA adapter -(`PostgreSqlOwnerSafeIdempotencyStore`, `IdempotencyStoreAdapter`) and a Redis cache behind them — -which is what the design's Tasks 39 and 40 ask for, built in the direction the registry permits. +`IdempotencyState`, `IdempotencyScope` and `RequestFingerprint`. This repository already has the +equivalents in `application-core/idempotency` — `IdempotencyStorePort`, `IdempotencyState`, +`IdempotencyScopeDigest` and `RequestFingerprint` — with two provider stores behind the port: +PostgreSQL (`PostgreSqlOwnerSafeIdempotencyStore` in `persistence-jpa`) and Redis +(`RedisIdempotencyStoreAdapter` in `cache-redis`), selected by +`ca-skeleton.capabilities.idempotency.provider`. That is what the design's Tasks 39 and 40 ask for, +built in the direction the registry permits. Implementing the design's SPI literally would have required `adapter-outbound-persistence-jpa → adapter-inbound-web`, an edge the registry forbids and one that @@ -97,7 +97,7 @@ application use-case boundary. | store / record / scope / claim / replay | `application-core/idempotency` | | request fingerprint policy | application use case, because only the use case knows which fields define the same work | | `Idempotency-Key` extraction | concrete inbound endpoint that opts into idempotency | -| replay JSON encoding | `adapter-inbound-web/idempotency/JsonIdempotentResponseCodec` | +| replay JSON encoding | `adapter-inbound-web-advanced/idempotency/JsonIdempotentResponseCodec` | This avoids two authorities for “same request”. The HTTP adapter does not run its own database replay policy; it translates the transport input into the application idempotency context and lets @@ -118,7 +118,7 @@ holding a JPA store for long-running operations, with the port This is the same shape as §6 and takes the same resolution — the one the repository already used for idempotency, where `IdempotencyStorePort` lives in `application-core` and -`IdempotencyStoreAdapter` in `persistence-jpa`: +`PostgreSqlOwnerSafeIdempotencyStore` in `persistence-jpa`: | Design type | Here | | --- | --- | @@ -128,15 +128,12 @@ for idempotency, where `IdempotencyStorePort` lives in `application-core` and | the lease | `application-core/operation/OperationLease` | | the stored failure | `application-core/operation/OperationFailure` — a code and an already-safe message, never an exception | | `JpaDurableOperationStore`, `JpaOperationEntity`, `V002__web_operation.sql` | `persistence-jpa/operation/*`, `db/migration/postgresql/V11__durable_operation.sql` | -| `OperationResource`, `OperationStatus`, `OperationProgress`, `OperationId` | web `operationasync` — the HTTP projection | -| — | web `operationasync/OperationResourceFactory`, which is the projection itself | +| `OperationResource`, `OperationStatus`, `OperationProgress`, `OperationId` | removed 2026-09-25 — the web `operationasync` projection and `/api/v1/operations` controller had no production wiring and published failures only as `WebProblem` | The split is not only a registry workaround; it puts each half where its invariants belong. A problem document is an HTTP concept and has no business being persisted, so the stored failure is a -code plus a safe message and the factory turns it into a `WebProblem` through the same catalog and -the same sanitiser as every synchronous error. An async failure therefore cannot publish something -a synchronous one would have redacted, and a worker cannot extend the published code vocabulary by -writing a row — an unrecognised code becomes `INTERNAL_ERROR`. +code plus a safe message. An HTTP surface for operations, if one is added again, maps it onto the +`Envelope` error contract. The state machine is enforced three times on purpose: in `DurableOperation`'s constructor, in the `CHECK` constraints of `V11__durable_operation.sql`, and in the `WHERE` clause of every statement @@ -147,6 +144,12 @@ no row and it learns that from the affected count. ## 8. Budget enforcement: what the edge stops and what the application stops +> **Removed 2026-09-25.** The servlet budget filter (`WebMvcBudgetFilter`) and its problem mapping +> were deleted with the second-generation platform. The shipped application no longer enforces the +> application column below; the `budget` catalog (`WebRequestBudget`, `WebBudgetCatalog`) remains as +> library code in `adapter:inbound:web-advanced`, and its unused meter (`WebBudgetMeter` and its +> outcome/violation types) was removed. The edge column still applies. + The design (Task 49) requires that the difference between an edge proxy's limits and the application's own be written down rather than discovered during an incident. Two limits on the same dimension always exist, they are never equal, and which one fires decides what the caller sees. @@ -163,8 +166,9 @@ dimension always exist, they are never equal, and which one fires decides what t Two consequences worth stating, because both are counterintuitive: -**An edge limit below the application's means clients never see a problem document.** nginx answers -its own HTML error page, so a client that branches on `ProblemCode` gets a body it cannot parse. +**An edge limit below the application's means clients never see the application's error body.** +nginx answers its own HTML error page, so a client that branches on `error.code` gets a body it +cannot parse. Where a dimension matters to clients, the edge limit must be set *above* the application's so the application is the one that refuses. @@ -172,61 +176,19 @@ application is the one that refuses. the process and a body large enough to matter before the application's own meter has counted it. Both belong; only their ordering is a decision. -The enforcement itself never materializes a body to measure it. `WebBudgetMeter` counts bytes as -they move — through a wrapped `ServletInputStream` on the servlet side and a `doOnNext` on the -buffer flux on the reactive side — and throws at the byte that crosses. A check that read the body -in order to size it would be the heap exhaustion the check exists to prevent, so the contract asserts -directly that an oversized body never reaches the handler in full. +## 9. The Nginx lane (removed 2026-09-25) -On the way out the split is between committed and not: +The `webNginxProxyTest` lane ran the forwarded-header library (`proxy`, `http.External*`) behind a +Testcontainers `nginx:1.27-alpine`. That library was a second way of doing what the shipped path +does with `server.forward-headers-strategy`, so the library and its lane were removed together +(`docs/capability-status.md`, "제거된 코드"). -- **Not committed** — the response is reset, which discards the partial body *and* the meter's - count of it, and the overrun is answered as a problem document. Resetting only the buffer was the - first implementation and it failed: the meter still held the count of the discarded bytes, so the - small problem document was refused too and the client got the container's error page. -- **Committed** — there is no status left to send. The exception propagates, the connection ends - mid-document, and the client sees a truncated response. That is worse for the client than a clean - error and better than a short response it would accept as complete. - -Statuses are never restated. `BudgetProblemMapper.statusFor` reads `ProblemCatalog` through the -violation's code; an earlier draft kept its own violation-to-status table and disagreed with the -catalog on two entries, which `requireStatusAgreement` turned into a 500. One table, no drift. - -## 9. The Nginx lane: what a real proxy caught that no unit test could - -Task 55 asks for the proxy contract to be verified against a real Nginx. It is implemented as a -separate `nginxProxyTest` source set with a Testcontainers-managed `nginx:1.27-alpine`, run by -`./gradlew :adapter:inbound:web:webNginxProxyTest`. Its own lane because it is the only one that -needs Docker; folded into `test`, every developer's `check` would depend on a container runtime, -and the usual end of that is an `@Disabled` nobody notices. - -**TLS is terminated in configuration, not in the container.** The design describes an `ssl` listener. -What the application can observe about TLS is exactly one thing — that the edge set -`X-Forwarded-Proto: https` authoritatively — and a proxy that terminates TLS and one that declares -the scheme produce an identical request upstream. Generating a certificate per run would add a -second failure mode to a lane whose subject is header handling. The lane asserts the observable -property; it does not assert that Nginx can do TLS. - -**The defect the lane found on its first run.** The first configuration set the forwarded headers -once at the `server` level and added only `X-Forwarded-Prefix` per `location`. Six of the ten cases -failed. Nginx's inheritance rule for array directives is *replacement*: a single `proxy_set_header` -inside a `location` discards every `proxy_set_header` inherited from `server`. So none of the -security headers were sent, the application fell back to the upstream's own `Host`, and a client's -`X-Forwarded-Host` would have been trusted. - -That configuration reads as correct, is a shape found throughout the wild, and no test of the -application could detect it — the application's forwarded-header handling is thoroughly unit-tested -and every one of those tests still passed. The bug lived entirely in the seam. The headers now live -in `proxy_headers.conf` and are `include`d by each location. - -| Bound | Where it fires | What the client sees | -| --- | --- | --- | -| `client_max_body_size 2m` | Nginx, before the application | Nginx's HTML 413, no problem document | -| application `maxBodyBytes` | the application | RFC 9457 problem, `REQUEST_TOO_LARGE` | -| unknown prefix | Nginx | 404; only `/api/` and `/dev-api/` are routed at all | - -The first row is the §8 table's consequence made concrete: an edge limit below the application's -means clients never see a problem document for that dimension. +One finding from that lane still applies to any Nginx in front of this service. Nginx's +inheritance rule for array directives is *replacement*: a single `proxy_set_header` inside a +`location` discards every `proxy_set_header` inherited from `server`. Setting the forwarded headers +once at `server` level and adding only `X-Forwarded-Prefix` per `location` therefore sends none of +the others, and the application falls back to the upstream's own `Host`. Keep the forwarded headers +in one included file and `include` it in every `location`. ## Advanced capabilities @@ -240,23 +202,15 @@ What the design wanted from the separation is enforced instead by two machine ch - **`WEB-ARCH-ADV`** in `WebArchitectureRules.stableDoesNotDependOnAdvanced()` fails the build when a Stable class names an Advanced type. A feature flag decides whether a bean is created; it does nothing about a compile-time edge, and one such edge makes Stable unbuildable without Advanced. -- **`WebStableModule`** declares eleven Advanced module identities with their own purity and edge - sets, checked by `WebModuleBoundaryTest`. Nine of the eleven are `CORE` — pure policy with no - framework import — which is stricter than the design's Gradle layout would have been. -Two modules are `FRAMEWORK_BOUND` and had to be: `advanced-patch` and `advanced-codec`. Jackson's -tree model is the reason for the first — a merge patch's null-means-delete has no representation in -a Java object, so the applier works on nodes — and `XMLInputFactory` is the reason for the second. -A third, `advanced-stream-encoding`, is separated from the pure `advanced-stream` for the same -reason: framing serializes, and serializing binds to Jackson. +`advanced.patch` and `advanced.codec` bind to a framework and had to: Jackson's tree model is the +reason for the first — a merge patch's null-means-delete has no representation in a Java object, so +the applier works on nodes — and `XMLInputFactory` is the reason for the second. +`advanced.stream.encoding` is separated from `advanced.stream` for the same reason: framing +serializes, and serializing binds to Jackson. ### What was adapted rather than copied -**`WebStreamEnvelope.Error` is named `Failure`.** A nested type called `Error` shadows -`java.lang.Error` inside its own file, so an unrelated `catch (Error e)` there would catch the wrong -thing. Error Prone's `JavaLangClash` refuses it outright, and the rename is the only difference from -the design's sealed hierarchy. - **`WebStreamErrorPolicy`'s factory methods are `startOver` / `resumeFromPosition` / `nothingToDo`.** The design's names collided with the record's own accessors, which Java rejects. @@ -288,13 +242,11 @@ coordinate. `RepresentationBackendScopeTest` reads `build.gradle` and fails if e returns to `implementation`, because nothing else catches it — the codec's own tests pass either way, and the failure only appears in whatever composes this leaf. -**The framing and the writers are separate, and both exist.** `NdjsonFraming` and -`JsonSequenceFraming` hold the contract; `MvcStreamWriter`, `WebFluxStreamWriter` and -`WebFluxSseAdapter` are what actually put it on a response. There is no MVC SSE writer: this -repository's `NO_SSE_EMITTER` ArchUnit rule forbids `SseEmitter` outright, so the servlet stack -streams NDJSON and JSON-seq and SSE is reactive-only. An earlier pass -stopped after the framing, which left the platform advertising SSE while nothing could serve it — -the same "control reached by nothing" shape this leaf has caught five other times. +**The framing and the writer are separate.** `NdjsonFraming` and `JsonSequenceFraming` hold the +contract; `MvcStreamWriter` is what puts it on a response. There is no MVC SSE writer: this +repository's `NO_SSE_EMITTER` ArchUnit rule forbids `SseEmitter` outright, and the only SSE writer +was the WebFlux one removed on 2026-09-25. So the servlet stack streams NDJSON and JSON-seq, and SSE +is framing-only — nothing serves it until a servlet writer exists. **`MessagingReplayBridge` is `WebStreamReplaySource`, an interface this module implements nowhere.** The design's requirement is that the web module store no durable event history; an implementation @@ -302,50 +254,18 @@ here would be the thing it forbids. ### What the execution layer had to get right -Three of these were only found by building the adapter rather than the policy. - -**A merged heartbeat means a finished source never completes.** `Flux.interval` is infinite, so -`source.mergeWith(heartbeat)` holds the connection for the full `maxStreamAge` after the last item — -thirty minutes of keepalives on a stream that ended. `WebFluxSseAdapter` therefore ends at the -terminal envelope (`takeUntil`), and supplies one for a source that finished without emitting its -own. - -**`onBackpressureBuffer(n)` does not close anything.** It propagates demand, so a subscriber that -stops requesting simply stops the source and the bound never fires. That is correct for a -well-behaved source and useless as a slow-consumer policy, because the sources this carries push -whether or not anybody asked. The working composition is `onBackpressureBuffer(n)` followed by -`onBackpressureError()`, verified by mutation: removing the second half makes both slow-consumer -tests fail. The merge prefetch is set to the same `n`, because its default of 256 would otherwise -be a larger backlog sitting behind the configured one. - -**The blocking bridge's permit cannot be released in `doFinally`.** That fires on the subscriber's -cancel signal, which arrives while the callable is still blocked on a thread — releasing there hands -the permit to another caller while the first still holds the database connection it was accounting -for. Acquire and release are in the same `try`/`finally` inside the callable, and the consequence, -stated rather than hidden, is that cancellation does not interrupt a blocking call. - -On the servlet side the equivalent is that there is no disconnect event at all: the first sign a -client is gone is a write that throws, which is why the heartbeat is the probe rather than a +On the servlet stack there is no disconnect event at all: the first sign a client is gone is a write that throws, which is why the heartbeat is the probe rather than a courtesy and why a failed beat is recorded as disconnect evidence. -### One pre-existing flake was fixed - -`HttpThrottleFixture.awaitSlotTaken` polled for a 503 while each probe spent quota, and refilled the -quota only after the loop. On a machine loaded enough that the holding request took a while to -occupy the slot, the quota ran out first and every remaining probe answered 429 — so the loop never -saw its 503 and failed on the deadline, which reads as a capacity bug and is a fixture bug. It now -refills before every probe and fails loudly if a probe is refused for quota immediately after a -refill. Found because the new virtual-thread and blocking-bridge tests load the machine enough to -trigger it. - ### Verification ```bash cd src -./gradlew :adapter:inbound:web:test # 861 tests, Advanced included -./gradlew :adapter:inbound:web:webAdvancedTest # 147, the Advanced lane on its own -./gradlew :adapter:inbound:web:webCrossStackParityTest -./gradlew :adapter:inbound:web:webNginxProxyTest # Docker +./gradlew :adapter:inbound:web:test # the shipped web leaf +./gradlew :adapter:inbound:web:systemTest # Tomcat, real socket +./gradlew :adapter:inbound:web:webJettyCompatTest # Jetty, real socket +./gradlew :adapter:inbound:web-advanced:test # the opt-in Advanced leaf +./gradlew :adapter:inbound:web-advanced:webAdvancedTest # the tagged Advanced lane ``` See `docs/web/advanced-capabilities.md`, `docs/web/streaming-contract.md`, diff --git a/docs/web/runbook.md b/docs/web/runbook.md index 52091e3e..d269dc52 100644 --- a/docs/web/runbook.md +++ b/docs/web/runbook.md @@ -3,68 +3,48 @@ What an operator needs when the HTTP boundary misbehaves. Organised by what you observe, because that is what you have at 3am — not by which module owns it. -## Reading the two "too much traffic" answers +## Reading a `429` -The platform never answers these two interchangeably, and the difference tells you where to look. +`RateLimitInterceptor` answers `429 RATE_LIMIT_EXCEEDED` with `Retry-After` when the edge rate +limit refuses a caller. `RATE_LIMIT_UNAVAILABLE` means the rate-limit store could not be reached, +not that the caller exceeded anything — look at the store, not the caller. -| You see | It means | Where to look | -| --- | --- | --- | -| `429 RATE_LIMITED` climbing for one caller | that caller exceeded its quota | the caller. Nothing is wrong with the service. | -| `429` climbing across **all** callers | quota is being charged for requests the service then shed | look at 503 first; see below | -| `503 ADMISSION_REJECTED` | the service has no capacity | saturation: check the admission profile's concurrency and what is holding slots | +## Errors that are not the `Envelope` -The second row is a real consequence of the design and worth knowing before it confuses you. Quota -is charged *before* capacity is requested, deliberately — the reverse order lets a caller who is -about to be rate-limited occupy a slot on the way to being told so. Under sustained overload every -caller's quota therefore drains on requests that never ran. **Rising 429 during an incident is a -symptom of shedding, not of callers misbehaving.** Read the 503 rate first. +Every HTTP error the application writes is the `Envelope` from `GlobalExceptionHandler` +(`spring.mvc.problemdetails.enabled=false`), with an `error.code` a client branches on. -## A control that appears configured and does nothing - -This has happened here, and the failure is silent by construction. A configured-but-unwired control -behaves exactly like a working one until it is needed. - -- **Check first:** the platform snapshot's `uninstalledControls()`. `WebPlatformStartupValidator` - fails startup on a missing required control, so a running instance with one missing means it was - not in the required list. -- **The instance found the hard way:** the problem catalog was complete, fully unit-tested, and - reached by nothing on the framework's error path. Spring answered failures with its own - `ProblemDetail` — RFC 9457-shaped, so it looked correct — carrying no `code` field. It was found - by a cross-stack parity recording, not by any test of the catalog. -- **How to confirm quickly:** send a request that must fail validation and check the body has a - `code`. No `code` means the platform's handler is not installed. +- **How to confirm quickly:** send a request that must fail validation and check the body has + `error.code`. A body without it (Spring's `ProblemDetail`, or the container's error page) means + the handler is not installed or the response came from the edge. ## A response is truncated or the connection dies mid-document Two different causes, distinguished by the status the client did receive. -- **Client got a status, then nothing** — the response budget was crossed after commit. The - platform cannot retract a status, so it ends the connection: a truncated response the client - rejects is better than a short one it accepts as complete. Raise `maxResponseBytes` for that - operation's profile, or make the endpoint paginate. -- **Client got nothing at all** — either the request budget was crossed before headers, in which - case there is a problem document, or the proxy refused it. `client_max_body_size` in nginx is - below the application's body budget by default, and nginx answers with its own HTML rather than a - problem document. See `repository-adaptation.md` §8 for which bound fires where. +- **Client got a status, then nothing** — the response failed after commit. The status cannot be + retracted, so the connection ends mid-document. +- **Client got nothing from the application** — the proxy refused it. `client_max_body_size` in + nginx answers with its own HTML rather than the `Envelope`. See `repository-adaptation.md` §8. ## A retried write happened twice The idempotency key is the control, and there are exactly three ways it fails to apply. -1. **The client did not send one.** The operation profile says `OPTIONAL`, so it ran unguarded. - Change the profile to `REQUIRED` if a duplicate is unacceptable. -2. **The client sent a different body.** Answered `422 IDEMPOTENCY_KEY_REUSED`, never a replay — - replaying would hand back a receipt for a request the caller never made. +1. **The client did not send one.** The endpoint does not require the key, so it ran unguarded. + Require it if a duplicate is unacceptable. +2. **The client sent a different body.** Answered `422 IDEMPOTENT_REQUEST_MISMATCH`, never a + replay — replaying would hand back a receipt for a request the caller never made. 3. **The record expired.** TTL is per-operation with a 72h cap. A retry after expiry is a new request by definition. -A `409 IDEMPOTENCY_REQUEST_IN_PROGRESS` is not a failure: an earlier attempt is still running and +A `409 IDEMPOTENT_IN_FLIGHT` is not a failure: an earlier attempt is still running and the caller should retry after `Retry-After`. ## Rolling deploy stalls with instances half-drained -`shutDownGracefully` waits for in-flight work, and on Reactor Netty an open-but-idle keep-alive -connection counts as in-flight. Calling `stop()` while that wait is in progress hangs. +`shutDownGracefully` waits for in-flight work, and an open-but-idle keep-alive connection can count +as in-flight. Calling `stop()` while that wait is in progress hangs. - **Symptom:** an instance neither serving nor exiting, no error in its log. - **Cause:** an unbounded graceful wait. `GracefulShutdownProbe` bounds it at a stated grace period @@ -74,9 +54,8 @@ connection counts as in-flight. Calling `stop()` while that wait is in progress ## Metrics stopped arriving, or the bill jumped -Almost always a high-cardinality tag. `WebMetricCardinalityPolicy` refuses anything off an -eight-name allowlist at the point of recording, so a new tag cannot appear by accident — but a -`routeTemplate` carrying a *resolved* path can, and that is one series per resource. +Almost always a high-cardinality tag — typically a `routeTemplate` carrying a *resolved* path, which +is one series per resource. - **Check:** the tag values in the metrics backend for `routeTemplate`. Braces mean templates; identifiers mean the resolved path leaked through. @@ -85,14 +64,17 @@ eight-name allowlist at the point of recording, so a new tag cannot appear by ac ## Cross-origin requests fail only in the browser -The API answers correctly and the browser refuses the response. Everything below is refused at -startup by `WebCorsPolicyValidator`, so a running instance with one of these means the profile was -built somewhere that does not validate. +The API answers correctly and the browser refuses the response. CORS is `CorsSettings` +(`ca-skeleton.cors.*`) applied by `SecurityConfig`. Startup refuses two settings: -- `*` with credentials — no browser honours it. -- An origin with a path, a trailing slash, or uppercase — never matches what the browser sends. -- `https://*.example.com` — matches nothing; CORS compares origins exactly. -- Wildcard `allowedHeaders` on a credentialed profile — not honoured with credentials. +- `APP_SECURITY_CORS_ENABLED=true` with no origin. +- `*` in `APP_SECURITY_CORS_ORIGINS` with `APP_SECURITY_CORS_ALLOW_CREDENTIALS=true` — no browser + honours it. + +Two more start fine and still fail in the browser: + +- `https://*.example.com` in the origin list — it is compared as a literal and matches nothing. +- An origin with a path (`https://app.example.com/ui`) — an origin is scheme, host and port only. A preflight answered `401` means CORS ran after authentication. Preflights carry no credentials by design; the order is asserted by `WebPipelineOrderContract`. @@ -109,8 +91,6 @@ both times, and every latency percentile computed from that data is wrong while ```bash cd src ./gradlew :adapter:inbound:web:test # unit, boundary, architecture -./gradlew :adapter:inbound:web:webCrossStackParityTest # Tomcat vs Jetty vs Reactor Netty -./gradlew :adapter:inbound:web:webNginxProxyTest # real proxy; needs Docker, fails without it +./gradlew :adapter:inbound:web:systemTest # Tomcat, real socket ./gradlew :adapter:inbound:web:webJettyCompatTest # second servlet container -./gradlew :adapter:inbound:web:webFluxContractTest # reactive stack ``` diff --git a/docs/web/streaming-contract.md b/docs/web/streaming-contract.md index bc0ada5d..330dacae 100644 --- a/docs/web/streaming-contract.md +++ b/docs/web/streaming-contract.md @@ -1,6 +1,12 @@ # Web streaming: the client contract -What a client must implement to consume SSE, NDJSON or `application/json-seq` from this platform. +What a client must implement to consume NDJSON or `application/json-seq` from this platform. SSE +framing exists, but since the WebFlux twin was removed (2026-09-25) nothing on the servlet stack +writes it. + +The writers ship in `adapter:inbound:web-advanced` (opt-in, switched by +`backend.web.advanced.ndjson.enabled` / `backend.web.advanced.json-sequence.enabled`); no default +composition carries them. ## Three outcomes, not two @@ -8,8 +14,8 @@ After the first byte the HTTP status is 200 and cannot change. So the status tel whether the stream succeeded, and a closed connection is ambiguous. There are three endings: 1. **A `Complete` envelope.** The stream finished. `lastSequence` is the final position. -2. **A `Failure` envelope.** Something failed after commit. Carries a `ProblemCode` and a - client-safe message. The status is still 200. +2. **A `Failure` record.** Something failed after commit. Carries an error code and a client-safe + message. The status is still 200. 3. **Neither.** The connection closed mid-stream. The server records this as `ABRUPT_CLOSE`; from the client's side it is indistinguishable from a completed stream *unless the client is looking for the terminal envelope*. diff --git a/docs/web/virtual-thread-profile.md b/docs/web/virtual-thread-profile.md index f35d3da7..4c37861e 100644 --- a/docs/web/virtual-thread-profile.md +++ b/docs/web/virtual-thread-profile.md @@ -16,7 +16,8 @@ that used to be shed at the front door is shed at the back, after the cost of ac ## Enabling it -Two settings, and the profile refuses to be constructed with only one: +The profile ships in `adapter:inbound:web-advanced`, which no default composition carries. Add +that leaf to the service, then two settings — the profile refuses to be constructed with only one: ```yaml backend: @@ -70,9 +71,8 @@ never used virtual threads at all. ## Rolling back -Set `enabled: false`. The rollback test asserts that Stable behaviour is then identical — if it is -not, the feature was never optional and every deployment has it. +Set `enabled: false`, or drop the leaf. The rollback test asserts that Stable behaviour is then +identical — if it is not, the feature was never optional and every deployment has it. -This is one of only two web Advanced capabilities that affect requests which do not use them (the -other is the WebFlux blocking bridge), which is why its soak is 24 hours and its rollback test is -the one that matters most. +This is the only web Advanced capability that affects requests which do not use them, which is why +its rollback test is the one that matters most. diff --git a/docs/websocket/advanced-support-matrix.md b/docs/websocket/advanced-support-matrix.md deleted file mode 100644 index 8db3f604..00000000 --- a/docs/websocket/advanced-support-matrix.md +++ /dev/null @@ -1,47 +0,0 @@ -# WebSocket Advanced: support matrix - -Every capability is off unless named. This table is what each one costs and what has to be true -before it is promoted. `AdvancedPromotionGate.forCapability` is the machine-checked form of the last -two columns; if they disagree, the code wins and this table is stale. - -| Capability | Flag | Adds | Required suites | Soak | -| --- | --- | --- | --- | --- | -| `RESUME` | `…advanced.resume.enabled` | A signed token and a replay store | `websocket:test`, `websocketJettyTest`, `resume-history-loss`, `resume-replay` | 8h | -| `CLUSTER_REDIS` | `…advanced.cluster-redis.enabled` | A Redis dependency on the routing path | `websocket:test`, `multi-node-fanout`, `node-loss`, `index-partition` | 24h | -| `CLUSTER_MESSAGING` | `…advanced.cluster-messaging.enabled` | A broker dependency on the delivery path | as `CLUSTER_REDIS` | 24h | -| `PRESENCE` | `…advanced.presence.enabled` | A read model over the cluster index | as `CLUSTER_REDIS` | 24h | -| `STOMP` | `…advanced.stomp.enabled` | A second protocol parser, pre-authentication | `websocket:test`, `broker-outage`, `broker-reconnect`, `user-destination` | 8h | -| `BROKER_RELAY_RABBIT` | `…advanced.stomp.relay.enabled` | A TCP dependency on an external broker | as `STOMP` | 8h | -| `CODEC_PROTOBUF` | `…advanced.codec-protobuf.enabled` | A second decode path | `websocket:test`, `websocketJettyTest` | 8h | -| `CODEC_CBOR` | `…advanced.codec-cbor.enabled` | A second decode path | `websocket:test`, `websocketJettyTest` | 8h | -| `COMPRESSION` | `…advanced.compression.enabled` | Per-connection memory, and a length side channel | `websocket:test`, `decompression-bound`, `memory-under-load` | 24h | -| `OUTBOUND_CLIENT` | `…advanced.outbound-client.enabled` | Long-lived connections this service initiates | `websocket:test`, `websocketJettyTest` | 8h | -| `SOCKJS_COMPAT` | `…advanced.sockjs.enabled` | Credentialed cross-origin HTTP, so CSRF | `websocket:test`, `websocketJettyTest` | 8h | -| `HTTP2_COMPAT` | `…advanced.http2.enabled` | RFC 8441 extended CONNECT | `websocket:test`, `websocketNginxTest`, `proxy-matrix`, `classic-upgrade-fallback` | 7d | -| `HTTP3_EXPERIMENTAL` | `…advanced.http3.enabled` | QUIC, and every hop problem HTTP/2 has | as `HTTP2_COMPAT` | 7d | -| `GRAPHQL_TRANSPORT` | `…advanced.graphql-transport.enabled` | A subprotocol on the Stable runtime | `websocket:test`, `websocketJettyTest` | 8h | - -## What is *not* supported, and why the row is here - -| Not supported | Reason | -| --- | --- | -| Simple broker in a multi-node deployment | It does not error. It delivers to whichever fraction of users is on the publishing node, which reads as intermittent loss. `SimpleBrokerProfile.activatableUnder` refuses it. | -| `permessage-deflate` on an endpoint mixing a secret with attacker-influenced content | The CRIME/BREACH shape. No parameter combination makes it safe; the leak is in the compressed length. `CompressionPolicy.mayCompress` refuses it. | -| JSONP polling on a sensitive endpoint | JSONP executes server-supplied script in the page. | -| Protobuf payloads above 256KB | The broker, the replay store and every in-memory queue would each hold the message whole. | -| Extended CONNECT on an untested hop | RFC 8441 fails by killing the connection, not by negotiating a fallback. | -| HTTP/3 as stable support | `Http3ExperimentalProfile.stableSupport()` returns false, always. | -| Both STOMP channels at once | The broker that results is whichever configurer ran last, with no error. `StompBrokerExclusivity` refuses it. | - -## Promotion - -Each capability is promoted on its own evidence. They share a feature-flag mechanism and nothing -else, so promoting them together means the evidence for the cheapest is treated as evidence for the -most dangerous. - -Two conditions apply to all of them and are not waivable: - -- **Rollback exercised.** A flag nobody has turned off is not known to turn off. -- **Stable artifact unchanged.** If enabling the capability changed Stable's wire contract or - dependency graph, Stable was never independent of it, and deployments that did not enable it are - affected anyway. diff --git a/docs/websocket/repository-adaptation.md b/docs/websocket/repository-adaptation.md deleted file mode 100644 index a24ea941..00000000 --- a/docs/websocket/repository-adaptation.md +++ /dev/null @@ -1,180 +0,0 @@ -# WebSocket platform: how the design maps onto this repository - -The design models the platform as eighteen Gradle modules under `modules/websocket`. This -repository's fail-closed registry (`src/config/architecture/modules.json`) owns the leaf list, so -those modules are packages inside the registered `:adapter:inbound:websocket` leaf — the same -resolution the JPA, GraphQL and web platforms reached. - -That is only honest if the boundaries are machine-checked, so `WebSocketStableModule` declares each -module's package, its purity grade and its exact allowed edges, and `WebSocketModuleBoundaryTest` -scans the source tree and fails when the two disagree in either direction. Promoting a package to -its own Gradle leaf later is a registry edit rather than an archaeology exercise. - -## Where the module map deviates from the design, and why - -| Design places it in | Here | Reason | -| --- | --- | --- | -| `WebSocketSubprotocolName` in `websocket-protocol` | `core` | The connection context must name the negotiated token, and the context is core — leaving the type in `protocol` made `core` depend on `protocol` while `protocol` already depended on `core`. The boundary test refused the cycle. The negotiation *policy* stays in `protocol`. | -| `StrictWebSocketJsonCodec` in `websocket-protocol` | `codec` (its own FRAMEWORK_BOUND module) | `protocol` is CORE here, and a Jackson import in a CORE module is refused. Splitting is better than relaxing the rule: the envelope's field rules stay testable with no mapper, and everything that touches a parser sits in one package a reviewer can read end to end. | -| `budget -> core` | `core -> budget` | `budget` imports nothing from `core` — numbers depend on nothing. The endpoint profile, which is core, has to name a budget. The declared direction was simply backwards. | -| — | `stomp` module | The pre-existing STOMP-over-SockJS channel predates this platform and still ships. Declared so the boundary is complete rather than excused; it has no edge to any platform module and none to it. | - -## What the design's rules actually prevent - -A few of the design's requirements read as style and are not. These are the ones worth keeping. - -**`websocket-core-api` names no framework.** Stricter here than in the HTTP platform, because a -connection is a long-lived object owned by a container and reaching for the container's own session -type is tempting from everywhere. A CORE module has no `WebSocketSession`, so the same decision -serves both runtimes and is testable without a server. The detector's framework list was missing -`tools.jackson` (this repo runs Jackson 3, not 2) — a CORE module could have imported a mapper -unnoticed. Fixed in both this leaf and the web leaf. - -**No Java class name on the wire.** A FQCN publishes the package layout, breaks every client on a -rename, and makes the receiver's type resolution an attack surface. `WebSocketMessageType` refuses -anything that looks like one; the manifest binds published names to records, and records cannot run -code while being populated. - -**The payload is an encoded string, not a `Map`.** A map accepts any shape, defers validation to -whichever handler reaches for a missing key, makes an entity trivially serializable onto the wire, -and brings unbounded nesting with it. - -**Handlers cannot write.** `WebSocketHandlerContext` has no session and no write method. This is -what makes ordering, backpressure and the drain sequence guarantees rather than conventions — a -handler that could write directly would bypass the queue, and every promise would hold only for the -handlers that cooperated. - -## Two findings from building it - -**Tomcat's graceful shutdown does not close WebSocket connections.** It waits for in-flight -*requests*, and an established WebSocket is not a request — so the shutdown completes with the -connections still open and they die when the socket is torn down. The client sees a **1006**, -indistinguishable from a network failure, which sends it into its most aggressive reconnect path at -exactly the moment the fleet is restarting. `PlatformWebSocketHandler` therefore implements -`SmartLifecycle` and closes its own connections with **1001 going away**, at a phase that runs -before the web server stops. Found by `TomcatWebSocketAbuseIT`, which failed on its first run. - -**Both runtimes on one classpath is a silent outage.** Spring Boot deduces one application type -from what is present, and picks the servlet one. A deployment that declared reactive endpoints and -shipped both starts, reports healthy, and never answers. `WebSocketStackExclusivity` reads what the -classpath will actually produce and fails startup with a sentence explaining it. - -## Lanes - -```bash -cd src -./gradlew :adapter:inbound:websocket:test # unit, boundary, architecture, Tomcat runtime -./gradlew :adapter:inbound:websocket:websocketJettyTest # the second servlet container -./gradlew :adapter:inbound:websocket:websocketNginxTest # real Nginx; needs Docker, fails without it -``` - -The Nginx lane carries a deliberately broken configuration alongside the correct one -(`nginx-no-upgrade.conf`) so the lane proves its own assertions can fail. A contract that only ever -runs against a correct configuration cannot tell whether it is checking anything. - -## The Stable behaviours that had no code - -A late audit compared every named type in the Stable plan against the source tree rather than -against memory, and found six that nothing implemented. They are listed because the way they were -missed is more useful than the fact that they were: each is a *behaviour under failure*, and the -plan named it inside a task whose other half was already built — so the task read as done. - -| Behaviour | Where it lives now | -| --- | --- | -| A queue observation an operator can read, separating a configured drop from a lossless overflow | `outbound/OutboundQueueSnapshot` + `OutboundQueue.snapshot()` | -| A timed-out correlation id that is remembered, so a late answer is not attached to a reused id | `handler/LateResponseTombstone` | -| Pooled-buffer retention on the reactive stack, bounded and counted | `webflux/WebSocketDataBufferPolicy` + `WebSocketDataBufferLifecycle` | -| What a proxy in front of this platform has to do | `release/WebSocketNginxProxyProfile` | -| What a rolling restart has to demonstrate, in order | `release/WebSocketRollingRestartScenario` | -| What the platform must show before promotion | `release/WebSocketStableReleaseGate` | - -The three `release` types share a module identity (`RELEASE`, CORE) that names no other module. -That is deliberate: a gate importing the parts it gates would be satisfiable by construction — the -evidence and the checklist would come from the same source. They are predicates over facts a release -engineer supplies, so a missing runtime stays a missing runtime. - -`WebSocketStableReleaseGate` overlaps `advanced/release/AdvancedPromotionGate` in shape and differs -in one condition that matters. Advanced capabilities are off unless a deployment names them, so a -broken one affects whoever enabled it; Stable is what every deployment gets, so its evidence has to -cover every runtime it claims — Tomcat, Jetty, Reactor Netty and Nginx — rather than the one the -author happened to test. It also refuses to promote an artifact containing an Advanced type. WS-ARCH-6 -already refuses that as a source edge; nothing in it notices a type that arrived through packaging, -and the effect is identical — Stable that does not build without Advanced is a naming convention. - -## Not yet implemented - -**Tasks 47–48, the browser matrix.** The design asks for a protocol test client driven through -Chromium, Firefox and WebKit. Not built: it needs Playwright and a browser download per engine, -which is a dependency and a network requirement this template does not otherwise carry, and a -browser lane that silently skips when the browsers are absent is worth less than no lane. The -properties it would cover that the Java client does not — that a browser cannot set headers on the -`WebSocket` constructor, and that it surfaces close codes to page script — are the reasons -`ONE_TIME_TICKET` and the standard close codes exist, and both are asserted at the unit level. - -## Advanced capabilities - -The Advanced expansion plan asks for fifteen Gradle modules under `modules/websocket-advanced/`. -They are packages under `advanced.**` in this leaf, for the same reason the Stable platform is — -`src/config/architecture/modules.json` is fail-closed and owns the leaf list, and a fifteen-leaf -addition to satisfy a directory layout is a change to the registry, not to the architecture. The -separation the design wanted is enforced by `WebSocketStableModule` and by WS-ARCH-6, which fails -the build when a Stable class names an Advanced one. A feature flag decides whether a bean exists; -it does nothing about a compile-time edge, and ArchUnit does. - -Three of the fifteen needed their own module identity rather than sharing `advanced`: - -- **`advanced-stomp`** (`advanced.stomp`) is `FRAMEWORK_BOUND`. STOMP here *is* Spring Messaging, and - folding it into `advanced` would have relaxed that module's purity for every capability in it. -- **`advanced-stomp-rabbit`** (`advanced.stomp.rabbit`) is separate again. The adapter parses a - protocol; the relay opens a TCP connection to somebody else's broker and makes every delivery - depend on it. Different blast radius, so a deployment can refuse one and keep the other. -- Everything else resolves to `advanced` by longest-prefix, which is what lets `advanced.codec.cbor` - exist without its own edge set. - -### What was adapted rather than copied - -**Task 8's presence record shape.** The design specifies -`(actorFingerprint, activeConnectionCount, state, lastObservedAt)` with a four-state observation -model. Implemented with `WebSocketActorReference` in place of a bare fingerprint string — it carries -the fingerprint and refuses to be constructed from raw identity, which is the property the design -was buying with the field name. The four states are implemented as specified; `PresenceState.STALE` -and `OFFLINE` are distinct because collapsing them reports every user as disconnected during a Redis -partition, when the connections are fine and the index went dark. - -**Task 14's Protobuf codec.** The descriptor compatibility gate and the profile are implemented and -tested. The encode/decode path is not: a Protobuf codec without generated message classes has -nothing to encode, and generating them requires a `.proto` source this template does not have and -should not invent. `DescriptorCompatibilityGate` is the part with the failure mode worth guarding — -a changed or reused field number reinterprets bytes already on the wire, and during a rolling deploy -both descriptor versions are live, so the receiver reads the wrong field without erroring. - -**Task 15's CBOR codec.** Same shape, same reason: `CborCodecProfile` fixes canonical encoding and -the duplicate-key policy, which are the two settings that decide whether two systems reading the -same bytes agree. `WebSocketCborCodec` implements the encode/decode path on top of it, and -`SchemaParity` is what stops it publishing a different catalog than JSON. - -`jackson-dataformat-cbor` and `protobuf-java` are `compileOnly` plus `testImplementation`, not -`implementation`. Both jars change an adopter's behaviour by their mere presence — Spring Boot -registers a `cborMapper` bean for the first and Spring registers a Protobuf message converter for -the second — so an adopting composition root would acquire both without enabling either capability. -The sibling web leaf shipped exactly that mistake and it broke the composition root outright; see -`docs/web/repository-adaptation.md`. `WebSocketBinaryCodecBackend` turns an absent backend into a -sentence naming the missing coordinate, and `BinaryCodecBackendScopeTest` reads `build.gradle` and -fails if either returns to `implementation`. - -**Task 12's relay configuration.** `RabbitBrokerRelayConfiguration` contributes only the broker, not -the destination prefixes. Two `WebSocketMessageBrokerConfigurer` beans each setting the application -prefix produce whichever ran last, silently — the same failure `StompBrokerExclusivity` exists to -catch between the two STOMP channels. - -### Verification - -```bash -cd src -./gradlew :adapter:inbound:websocket:test # 509 tests, Advanced included -./gradlew :adapter:inbound:websocket:websocketJettyTest -./gradlew :adapter:inbound:websocket:websocketNginxTest -``` - -See `docs/adr/ADR-WS-002-resume-and-cluster.md`, `docs/adr/ADR-WS-003-stomp-and-broker-relay.md`, -`docs/websocket/advanced-support-matrix.md` and `docs/websocket/runbooks/`. diff --git a/docs/websocket/runbook.md b/docs/websocket/runbook.md index f7902763..ac0e70e1 100644 --- a/docs/websocket/runbook.md +++ b/docs/websocket/runbook.md @@ -1,27 +1,26 @@ -# WebSocket platform runbook +# WebSocket handler runbook -> **Scope:** the default shipped compositions do not assemble the WebSocket platform runtime. -> This runbook applies only to a deployment that deliberately adopted the websocket leaf and -> explicitly wired `PlatformWebSocketHandler` and its lifecycle into that composition. If that bean -> is absent, the platform sections below describe library behavior, not a running endpoint. +> **Scope:** the shipped compositions do not assemble a WebSocket runtime. This runbook applies to +> a service that registered `PlatformWebSocketHandler` itself (see +> `src/adapter/inbound/websocket/README.md`, "라이브러리 API"). The STOMP channel's rules are in the +> leaf `CLAUDE.md`. Organised by what you observe, because that is what you have during an incident. ## Clients report 1006 — "closed abnormally, no reason" -The most important symptom here, because 1006 is indistinguishable from a network failure and -drives every client into its most aggressive reconnect path. +1006 is indistinguishable from a network failure and drives every client into its most aggressive +reconnect path. -- **During a deploy** — the platform did not close its connections. `PlatformWebSocketHandler` - implements `SmartLifecycle` and closes with **1001 going away**; a container's own graceful - shutdown does **not** do this, because it waits for in-flight *requests* and an established - WebSocket is not a request. Check the handler bean is registered and that its phase runs before - the web server stops. +- **During a deploy** — the handler did not close its connections. It closes them with + **1001 going away** from `SmartLifecycle.stop()`; a container's own graceful shutdown does not, + because it waits for in-flight *requests* and an established WebSocket is not a request. Check + the handler is a Spring bean (otherwise Spring never calls `stop()`). `TomcatWebSocketShutdownIT` + shows the order: with the handler's phase below the web server's, the client sees 1006. - **Behind a proxy** — the upgrade is mishandled, so the close frame never becomes a close frame. See the next section. - **Neither** — something threw while closing. A close reason longer than 123 bytes makes the - container throw mid-close and turns a clean refusal into a 1006; the platform truncates for that - reason. + container throw mid-close; the handler truncates for that reason. ## Connections work locally and not behind the load balancer @@ -33,80 +32,52 @@ Three nginx directives, each producing a different failure: | `Upgrade` / `Connection` forwarded | Upstream sees an ordinary GET and answers 404 or 200 for a route that works when tested directly. They are hop-by-hop headers, so a proxy is *required* to drop them. | | `proxy_read_timeout` raised | Every connection quieter than 60s is killed with no close frame. A WebSocket is idle by nature. | -`websocketNginxTest` asserts all three against a real Nginx, and carries a deliberately broken -configuration so it proves its own assertions can fail. +`websocketNginxTest` asserts these against a real Nginx, and carries a deliberately broken +configuration (`nginx-no-upgrade.conf`) so it proves its own assertions can fail. ## Connections vanish with no close frame and no error Almost always an intermediary's idle timeout, not the application. TCP does not report a departed peer — a closed laptop lid, a phone switching to cellular and a NAT forgetting its mapping all -produce no FIN. +produce no FIN. The handler has no heartbeat or idle timer; set the container idle timeout +(`ServletServerContainerFactoryBean.setMaxSessionIdleTimeout`) and the proxy read timeout, and have +clients ping below the smallest of them. -- Check `HeartbeatPolicy`: the ping interval must be under ~20s, because intermediaries commonly - drop idle connections at 30–60s and say nothing. -- The idle timeout must be at least two ping intervals. Below that, one dropped ping on a congested - network closes a healthy connection, and the reconnect storm makes the congestion worse. +## Clients are closed with 1009 + +The message exceeded a bound. Two places enforce one: the container's text buffer (Tomcat default +8 KiB) closes before the handler sees the message, and the handler closes when the message exceeds +`WebSocketConnectionBudget.maxMessageBytes` (UTF-8 bytes). Set the container buffer to the same +value so the answer does not depend on which one fired first. + +## Clients are closed with 1013 + +A reply could not be queued: the connection's outbound buffer (`maxBufferedOutboundBytes`) or the +node-wide `GlobalBufferBudget` is full, which means the peer reads more slowly than the service +answers. Closing is deliberate — a client that reconnects has lost nothing, while one that silently +missed a reply is wrong and does not know it. ## Memory grows and nothing is failing A slow consumer. It does not error — it reads more slowly than the server writes and the difference accumulates. Arranging it requires no tooling: reading slowly is enough. -- **Check first:** `WebSocketNodeSnapshot.droppedOutboundMessages`. Connection counts and buffered - bytes both look healthy while data is being lost; the drop count is the only number that says so. - **Bounds:** per connection (`maxBufferedOutboundBytes`) *and* node-wide (`GlobalBufferBudget`). The second is not redundant — a megabyte each is fine at a hundred connections and is the whole heap at fifty thousand. +- **Drops:** `OutboundQueue.snapshot().droppedCount()` counts droppable and conflatable messages + the queue shed. Connection counts and buffered bytes look healthy while data is being shed; the + drop count is the only number that says so. - **If drops are zero and memory still grows:** check that the queue lock and the socket lock are separate. When they were one lock, a stalled peer blocked every producer, the queue never filled, - and the shedding bound never fired. That is fixed, and it is the shape to look for if it recurs. - -## A command ran twice - -The reconnect is what makes this a WebSocket problem: a client replays everything it never saw an -answer for, on a new connection, all at once. - -1. **Key scoped to the connection?** It must not be. `WebSocketCommandKey` is endpoint + actor + - the client's own message id, so it survives the reconnect. -2. **Ledger not transactional?** The only implementation that works writes in the application's own - transaction. Anything else has a window between the business commit and the ledger write. -3. **Outcome `UNKNOWN`?** That is the window. Neither replaying nor re-running is safe — replaying - invents a result, re-running duplicates a committed write. Only `CommandReconciliation` reading - the business data can settle it, and `INDETERMINATE` is a real answer to act on. - -## A client cannot connect and the endpoint is definitely there - -- **403** — origin. The same-origin policy does **not** protect a WebSocket handshake and there is - no preflight, so the server's `Origin` check is the entire defence and it is strict: exact match, - lowercase, no path, no wildcard. -- **401** — the ticket was spent, expired (30s cap), or minted for another endpoint. All three are - deliberate; a longer-lived or unbound ticket is a bearer token in a query string again. -- **400** — no offered subprotocol is supported. Production refuses a client that offers none. -- **503** — the endpoint is at its connection cap. - -Order matters and is asserted: route → origin → capacity → credential → subprotocol. Origin is -checked before authentication because a cookie handshake from an attacker's page authenticates -perfectly; the credential is valid and the page is not allowed to use it. - -## Endpoints never answer and the app reports healthy - -Both runtimes on one classpath. Spring Boot deduces one application type and picks the servlet one, -so declared reactive endpoints are simply never served — no error, no warning. -`WebSocketStackExclusivity` fails startup on this; if a running instance has it, the check is not -wired. - -## Metrics stopped arriving - -A high-cardinality tag, and the risk is worse than for HTTP: a request produces one observation, -a connection produces them for hours, so the series outlive the connections and only accumulate. -`WebSocketMetricTags` allows eight names; `connectionId`, `sessionId` and `actor` are not among -them. `nodeId` is, because a fleet has a knowable number of nodes. + and the shedding bound never fired. ## Verification ```bash cd src -./gradlew :adapter:inbound:websocket:test # unit, boundary, architecture, Tomcat runtime +./gradlew :adapter:inbound:websocket:test # queue, writer, budget, handler +./gradlew :adapter:inbound:websocket:systemTest # real Tomcat, incl. context close → 1001 ./gradlew :adapter:inbound:websocket:websocketJettyTest # second servlet container ./gradlew :adapter:inbound:websocket:websocketNginxTest # real Nginx; needs Docker, fails without it ``` diff --git a/docs/websocket/runbooks/broker-outage.md b/docs/websocket/runbooks/broker-outage.md deleted file mode 100644 index bde26018..00000000 --- a/docs/websocket/runbooks/broker-outage.md +++ /dev/null @@ -1,55 +0,0 @@ -# Runbook: STOMP broker outage - -Applies when `advanced.stomp.relay` is enabled and the RabbitMQ broker becomes unreachable. - -## What the symptom looks like - -Not an error rate. The relay holds one TCP connection to the broker plus one per authenticated -session, and a broker that stops responding without closing leaves all of them **open**. The -platform's own health check stays green; connections stay established; publishes are accepted. - -The first real signal is one of: - -- subscriptions established but no `MESSAGE` frames arriving, for everyone at once; -- the relay's system heartbeat failing to receive (`systemHeartbeatReceiveInterval` elapsed); -- new sessions failing to subscribe while existing ones appear fine — this is the broker's - connection limit, not the outage itself. - -If the heartbeat is not configured, none of the above fires and the first signal is a user report. -`RabbitBrokerRelayProfile` refuses a zero heartbeat for exactly this reason. - -## Triage - -1. **Confirm the direction.** From a platform node, open a STOMP connection to the broker's host and - port directly. If that succeeds, the problem is the relay's connection state, not the broker. -2. **Check the connection count against the broker's limit.** `brokerConnectionsFor(sessions)` is - `sessions + 1`. A broker at its limit refuses new connections and serves existing ones, which - produces the "new users cannot subscribe" shape. -3. **Check whether messages are being accepted.** A half-open connection accepts every publish - silently. Publishes succeeding is not evidence the broker is alive. - -## Recovery - -- **Broker restarted, relay did not reconnect.** The relay reconnects on its own; if it has not - within two heartbeat intervals, restart the platform nodes one at a time. Do not restart them all - at once — every session reconnects simultaneously and the broker meets its whole client population - in one instant. -- **Broker at its connection limit.** Raise the limit or shed sessions. Shedding is the faster of - the two and the connection count falls with the sessions. -- **Broker gone and not coming back.** There is no safe fallback to the simple broker in a - multi-node deployment: it delivers to whichever fraction of users is on the publishing node. - `SimpleBrokerProfile.activatableUnder` refuses it outside local/test, and that refusal should not - be overridden during an incident. Scale to a single node first if the simple broker is the only - option. - -## What is lost - -Anything the broker held and did not persist. `StompEvidence.BROKER_ACK` is only durable if the -broker is durable, and RabbitMQ's durability is a property of the queue topology, not of the relay. -Messages acknowledged at `PROTOCOL_RECEIPT` were never in the broker at all. - -## Afterwards - -- If the heartbeat did not fire first, that is the finding. Fix it before the postmortem closes. -- If the connection limit was reached, record the session count that reached it. It is a hard - ceiling on the deployment and it is not otherwise written down anywhere. diff --git a/docs/websocket/runbooks/resume-history-loss.md b/docs/websocket/runbooks/resume-history-loss.md deleted file mode 100644 index a95654fa..00000000 --- a/docs/websocket/runbooks/resume-history-loss.md +++ /dev/null @@ -1,56 +0,0 @@ -# Runbook: resume history loss - -Applies when `advanced.resume` is enabled and clients present resume tokens the replay store can no -longer satisfy. - -## What the symptom looks like - -Clients reconnecting and resynchronising rather than resuming. This is the **designed** behaviour, -not a fault — `ResumeCoordinator` consults `ReplayAvailability` and refuses to honour a position the -store has evicted, because delivering a stream with a hole in it is worse than an explicit -resynchronise. - -It becomes an incident when the resynchronise rate is high enough to matter: - -- a resynchronise means the client re-reads its whole state, so a spike is a load spike on whatever - serves that state; -- for a client that cannot resynchronise cheaply, it is user-visible as a stall. - -## Triage - -1. **Establish which of the three causes it is.** - - *Store eviction under load.* The replay store's retention is shorter than the disconnect - durations being seen. Look at retention against reconnect latency, not against a nominal - figure. - - *Store restarted or partitioned.* Availability drops to nothing and every token fails at once. - - *Key rotation.* `ResumeTokenKeyRing` verifies against retired keys as well as the current one; - if a key was removed rather than retired, every token minted under it fails to verify. This - produces the same symptom and a different fix. - - `ResumeTokenOutcome` distinguishes these. A token that fails verification is not the same as one - that verifies and names an evicted position. - -2. **Check whether the resynchronise is succeeding.** A high resynchronise rate that completes is a - capacity problem. One that fails is a correctness problem and is more urgent. - -## Recovery - -- **Eviction under load.** Raise retention if the store can hold it. Retention is bounded by memory, - so this trades against the store's own stability — do not raise it past what the store survives. -- **Store restarted.** Nothing to recover; the tokens are genuinely unsatisfiable. Let clients - resynchronise. If the resynchronise load is the problem, shed connections so they arrive in - batches rather than all at once. -- **Key removed rather than retired.** Restore the key to the ring as a verify-only entry. Minting - continues under the current key. - -## What is lost - -Nothing that was acknowledged. Resume is an optimisation over resynchronise; the client's ability to -rebuild its state from the authoritative source is the actual guarantee, and it is unaffected. - -## Afterwards - -- If retention was the cause, record the disconnect duration distribution that exceeded it. The - nominal retention figure is meaningless without it. -- If a key was removed, that is a process finding, not a platform one. Keys are retired, never - deleted, and the ring is the place that is enforced. diff --git a/infra/messaging/nats/docker-compose.yml b/infra/messaging/nats/docker-compose.yml deleted file mode 100644 index 08e19069..00000000 --- a/infra/messaging/nats/docker-compose.yml +++ /dev/null @@ -1,21 +0,0 @@ -# NATS 2.14.x with JetStream, Experimental tier. -# -# JetStream is mandatory: core NATS is fire-and-forget with no persistence and no acknowledgement, -# so an at-least-once destination configured against it would report success for messages that were -# never stored. The adapter's validator refuses that combination. -services: - nats: - image: nats:2.14-alpine - container_name: messaging-nats - ports: - - "4222:4222" - - "8222:8222" - command: - - "--jetstream" - - "--store_dir=/data" - - "--http_port=8222" - healthcheck: - test: ["CMD-SHELL", "wget -q -O- http://localhost:8222/healthz || exit 1"] - interval: 5s - timeout: 5s - retries: 20 diff --git a/infra/messaging/postgres/docker-compose.yml b/infra/messaging/postgres/docker-compose.yml index 1502cee6..05bc5435 100644 --- a/infra/messaging/postgres/docker-compose.yml +++ b/infra/messaging/postgres/docker-compose.yml @@ -1,7 +1,7 @@ # PostgreSQL 16 for the Outbox and Inbox. # -# logical replication is enabled so the optional Debezium CDC relay can be exercised against the -# same database the polling relay uses; the two must produce an identical wire contract. +# logical replication stays enabled so a CDC relay can be tried against the same database the polling +# relay uses. The repository ships no CDC relay (the Debezium mapping was removed on 2026-09-25). services: postgres: image: postgres:16-alpine diff --git a/infra/messaging/pulsar/docker-compose.yml b/infra/messaging/pulsar/docker-compose.yml deleted file mode 100644 index 5e950cfc..00000000 --- a/infra/messaging/pulsar/docker-compose.yml +++ /dev/null @@ -1,17 +0,0 @@ -# Pulsar 4.0 LTS, Experimental tier. -# -# Present so the Experimental adapter can be exercised, not because it is supported. The adapter -# stays disabled unless backend.messaging.experimental.pulsar=true. -services: - pulsar: - image: apachepulsar/pulsar:4.0.3 - container_name: messaging-pulsar - ports: - - "6650:6650" - - "8080:8080" - command: bin/pulsar standalone --no-functions-worker --no-stream-storage - healthcheck: - test: ["CMD", "bin/pulsar-admin", "brokers", "healthcheck"] - interval: 10s - timeout: 10s - retries: 20 diff --git a/infra/messaging/rabbitmq/docker-compose.yml b/infra/messaging/rabbitmq/docker-compose.yml deleted file mode 100644 index 4e6c354c..00000000 --- a/infra/messaging/rabbitmq/docker-compose.yml +++ /dev/null @@ -1,22 +0,0 @@ -# RabbitMQ 4.3.x. -# -# Quorum queues are the default for durable work queues in this platform, so the classic mirroring -# policy is deliberately absent: classic mirrored queues can lose acknowledged messages during a -# partition, which is precisely the guarantee a durable work queue exists to provide. -services: - rabbitmq: - image: rabbitmq:4.3-management - container_name: messaging-rabbitmq - ports: - - "5672:5672" - - "15672:15672" - environment: - RABBITMQ_DEFAULT_USER: messaging - RABBITMQ_DEFAULT_PASS: messaging - # Publisher confirms and returns are client-side settings; the profile guard enforces them. - RABBITMQ_SERVER_ADDITIONAL_ERL_ARGS: "-rabbit consumer_timeout 1800000" - healthcheck: - test: ["CMD", "rabbitmq-diagnostics", "-q", "check_running"] - interval: 5s - timeout: 10s - retries: 20 diff --git a/infra/messaging/toxiproxy/docker-compose.yml b/infra/messaging/toxiproxy/docker-compose.yml index 9aac0b49..e271af36 100644 --- a/infra/messaging/toxiproxy/docker-compose.yml +++ b/infra/messaging/toxiproxy/docker-compose.yml @@ -10,7 +10,6 @@ services: ports: - "8474:8474" # control API - "19092:19092" # proxied Kafka - - "15673:15673" # proxied RabbitMQ - "15433:15433" # proxied PostgreSQL healthcheck: test: ["CMD", "/toxiproxy-cli", "list"] diff --git a/infra/redis-sdk/README.md b/infra/redis-sdk/README.md index d89dd101..307c6e82 100644 --- a/infra/redis-sdk/README.md +++ b/infra/redis-sdk/README.md @@ -28,7 +28,7 @@ day, so a stale lane fails visibly instead of drifting. REDIS_VERSION=7.4 docker compose -f infra/redis-sdk/tls/compose.yml up -d --wait # The client needs the generated CA; copy it out of the volume first. docker compose -f infra/redis-sdk/tls/compose.yml cp redis:/tls/ca.crt /tmp/redis-lane-ca.pem -cd src && ./gradlew :adapter:outbound:cache-redis:redisTopologyTest \ +cd src && ./gradlew :adapter:outbound:redis-runtime:redisTopologyTest \ -Predis.topology.host=127.0.0.1 -Predis.topology.port=6390 \ -Predis.topology.mode=tls -Predis.topology.trust-material=/tmp/redis-lane-ca.pem ``` @@ -74,12 +74,12 @@ rest of the topology is discovered. ```bash # Standalone REDIS_VERSION=7.4 docker compose -f infra/redis-sdk/standalone/compose.yml up -d --wait -cd src && ./gradlew :adapter:outbound:cache-redis:redisTopologyTest \ +cd src && ./gradlew :adapter:outbound:redis-runtime:redisTopologyTest :adapter:outbound:redis-sdk:redisTopologyTest :adapter:outbound:cache-redis:redisTopologyTest \ -Predis.topology.host=localhost -Predis.topology.port=6379 -Predis.topology.mode=standalone # Sentinel — the port is a sentinel, and the monitored primary has to be named REDIS_VERSION=7.4 docker compose -f infra/redis-sdk/sentinel/compose.yml up -d --wait -cd src && ./gradlew :adapter:outbound:cache-redis:redisTopologyTest \ +cd src && ./gradlew :adapter:outbound:redis-runtime:redisTopologyTest :adapter:outbound:redis-sdk:redisTopologyTest \ -Predis.topology.host=localhost -Predis.topology.port=27010 \ -Predis.topology.mode=sentinel -Predis.topology.master=skeleton @@ -87,10 +87,21 @@ cd src && ./gradlew :adapter:outbound:cache-redis:redisTopologyTest \ # Slot assignment finishes after the nodes are healthy, and a client that connects in between sees # CLUSTERDOWN for reasons that have nothing to do with the SDK. REDIS_VERSION=7.4 docker compose -f infra/redis-sdk/cluster/compose.yml up -d --wait -cd src && ./gradlew :adapter:outbound:cache-redis:redisTopologyTest \ +cd src && ./gradlew :adapter:outbound:redis-runtime:redisTopologyTest :adapter:outbound:redis-sdk:redisTopologyTest :adapter:outbound:cache-redis:redisTopologyTest \ -Predis.topology.host=localhost -Predis.topology.port=7100 -Predis.topology.mode=cluster ``` +Each leaf owns the lanes its tests qualify, and names the classes each lane must run in its +`build.gradle` (`redisTopologyLane { requiredClasses ... }`). Selecting a mode a leaf does not +declare fails instead of running nothing, so run only the leaves listed for the lane: + +| Lane | `redis-runtime` | `redis-sdk` | `cache-redis` | +| --- | --- | --- | --- | +| standalone | `LiveRedisCompositionTest` | `RedisTopologyContractTest`, `LiveRedisGuardrailTest` | `LiveRedisSemanticPortsTest` | +| sentinel | `LiveRedisCompositionTest` | `RedisTopologyContractTest`, `LiveRedisSentinelPromotionTest` | — | +| cluster | `LiveRedisCompositionTest` | `LiveRedisClusterTest`, `LiveRedisClusterTransactionTest` | `LiveRedisSemanticPortsTest` | +| tls | `LiveRedisTlsTest` | — | — | + Tear a lane down with `docker compose -f infra/redis-sdk//compose.yml down -v`. | Lane | Ports | Notes | diff --git a/scripts/run-compose-runtime-smoke.sh b/scripts/run-compose-runtime-smoke.sh index 594bd907..c0f60d3a 100755 --- a/scripts/run-compose-runtime-smoke.sh +++ b/scripts/run-compose-runtime-smoke.sh @@ -8,8 +8,7 @@ # and a stale directory cannot be mistaken for this run's; # 2. the static contract, then `config`, then `create` — a stack that cannot render has no partial # failure mode, and finding that out after `up` costs a teardown; -# 3. `up --wait` for long-running services only, then health and the resolved activation report, -# which is the application's answer rather than the flags this script passed in; +# 3. `up --wait` for long-running services only, then the application's own health answer; # 4. every one-shot the lane declares, each of which must exit zero — a missing or skipped # required client is a lane failure, not a lane that had nothing to check; # 5. sanitized evidence; @@ -28,6 +27,29 @@ RUN_ID="$(date -u +%Y%m%dT%H%M%SZ)-$$" # is lowercased for the project while the evidence directory keeps the readable timestamp. PROJECT_RUN_ID="$(tr '[:upper:]' '[:lower:]' <<<"${RUN_ID}")" +# The lanes boot the qualification image: the application with every capability module on the +# classpath (src/Dockerfile COMPOSITION, app-bootstrap qualificationBootJar). The default image is +# the composition a service ships and carries none of them, so a lane that switches JPA or Kafka on +# would have nothing to switch. docker-compose.yml passes this to the build and puts it in the tag. +export COMPOSITION=qualification + +# Every capability is on while its module is present, so each lane starts from all of them off and +# its activationEnv turns on what it is about. The off-* lanes therefore prove that a present but +# switched-off capability needs no infrastructure at all. +CAPABILITIES_OFF='{ + "APP_PERSISTENCE_JPA_ENABLED": "false", + "APP_REDIS_ENABLED": "false", + "APP_MESSAGING_ENABLED": "false", + "APP_PERSISTENCE_MONGO_ENABLED": "false", + "APP_GRAPHQL_ENABLED": "false", + "APP_HTTPCLIENT_ENABLED": "false", + "APP_OBJECTSTORAGE_ENABLED": "false", + "APP_WEBSOCKET_ENABLED": "false", + "CASKELETON_GRPC_ENABLED": "false", + "APP_FILESERVER_PLATFORM_ENABLED": "false", + "APP_NOTIFICATION_PLATFORM_ENABLED": "false" +}' + MODE="" SELECTED_LANE="" usage() { @@ -321,8 +343,8 @@ run_lane() { for entry in "${lane_environment[@]}"; do printf ' %s: "%s"\n' "${entry%%=*}" "${entry#*=}" done - jq -r --argjson override "${phase_override}" \ - '.activationEnv + $override | to_entries[] | " \(.key): \"\(.value)\""' \ + jq -r --argjson off "${CAPABILITIES_OFF}" --argjson override "${phase_override}" \ + '$off + .activationEnv + $override | to_entries[] | " \(.key): \"\(.value)\""' \ <<<"${lane_json}" } >"${lane_overlay}" ) @@ -384,59 +406,25 @@ run_lane() { # # The management port, not the application port. Actuator runs on its own connector here so the # management plane is not published on the public one, and fetching 8080/actuator returned an - # empty file that looked exactly like a failed assertion about the profile. + # empty file that looked exactly like a failed assertion. local management_port management_port="$(docker compose -p "${PROJECT}" "${LANE_ARGS[@]}" exec -T app \ sh -c 'echo "${MANAGEMENT_SERVER_PORT:-9001}"' 2>/dev/null | tr -d "\r\n")" management_port="${management_port:-9001}" # Poll rather than trust `up --wait`. Not every overlay defines a healthcheck — the dev one does - # not — and where there is none `--wait` returns as soon as the container is created, so the first - # fetch landed before the application had finished starting and produced an empty file that read - # exactly like a failed assertion about the profile. + # not — and where there is none `--wait` returns as soon as the container is created. local attempt for attempt in $(seq 1 60); do if docker compose -p "${PROJECT}" "${LANE_ARGS[@]}" exec -T app \ - wget -qO- "http://localhost:${management_port}/actuator/adapteractivation" \ - >"${LANE_EVIDENCE}/activation.json" 2>/dev/null \ - && [[ -s "${LANE_EVIDENCE}/activation.json" ]]; then - break + wget -qO- "http://localhost:${management_port}/actuator/health" \ + >"${LANE_EVIDENCE}/health.json" 2>/dev/null \ + && [[ -s "${LANE_EVIDENCE}/health.json" ]]; then + return 0 fi sleep 5 done - docker compose -p "${PROJECT}" "${LANE_ARGS[@]}" exec -T app \ - wget -qO- "http://localhost:${management_port}/actuator/health" \ - >"${LANE_EVIDENCE}/health.json" 2>/dev/null || true - - local reported - reported="$(jq -r '.activeProfile // empty' "${LANE_EVIDENCE}/activation.json" 2>/dev/null || true)" - if [[ "${reported}" != "${runtime}" ]]; then - echo "${id}: the application reports profile '${reported}', the contract says '${runtime}'" >&2 - return 1 - fi - - # The switches the application says are on must be exactly the ones the lane asked for. Without - # this a lane called local-jpa that ran with JPA off would render the right services, start - # cleanly, and prove nothing — which is the failure mode a green lane is least able to reveal. - local expected_on actual_on - expected_on="$(jq -r '.expectedSwitchesOn | sort | join(",")' <<<"${lane_json}")" - actual_on="$(jq -r '.switches | to_entries | map(select(.value)) | map(.key) | sort | join(",")' \ - "${LANE_EVIDENCE}/activation.json")" - if [[ "${expected_on}" != "${actual_on}" ]]; then - echo "${id}: the application reports [${actual_on}] on, the contract expects [${expected_on}]" >&2 - return 1 - fi - - # The vendor the application resolved, not the one the lane started. These differ exactly when a - # profile pins a datasource that outranks the lane's environment, and every other field in the - # report looks correct while it happens. - local expected_vendor actual_vendor - expected_vendor="$(jq -r '.expectedPersistenceVendor' <<<"${lane_json}")" - actual_vendor="$(jq -r '.persistenceVendor // "absent"' "${LANE_EVIDENCE}/activation.json")" - if [[ "${expected_vendor}" != "${actual_vendor}" ]]; then - echo "${id}: the application resolved vendor '${actual_vendor}', the contract expects '${expected_vendor}'" >&2 - return 1 - fi - + echo "${id}: the application never answered /actuator/health on port ${management_port}" >&2 + return 1 } await_application_report || return 1 @@ -460,7 +448,7 @@ run_lane() { return 1 fi redact_in_place "${LANE_EVIDENCE}/notification-smoke-phase1.log" - cp "${LANE_EVIDENCE}/activation.json" "${LANE_EVIDENCE}/activation-phase1.json" + cp "${LANE_EVIDENCE}/health.json" "${LANE_EVIDENCE}/health-phase1.json" # The application only. The database and its volume stay up, which is the whole point. echo "-- ${id}: restarting the application into the second phase" diff --git a/scripts/verify-httpclient-docs.py b/scripts/verify-httpclient-docs.py index 6fa87263..f8d00444 100755 --- a/scripts/verify-httpclient-docs.py +++ b/scripts/verify-httpclient-docs.py @@ -2,7 +2,7 @@ """Fail when the HTTP Client Platform's code and documentation have drifted. The design (§33 "Documentation") requires the support matrix, configuration reference, security -guide, runbook, and migration guide to match the code. Review cannot hold that line by itself, so +guide and runbook to match the code. Review cannot hold that line by itself, so this verifier extracts the names that are part of the public contract -- stable exceptions, metric names, configuration properties, startup violation codes, and transports -- and fails when one exists in code but nowhere in the documentation. @@ -30,7 +30,6 @@ REQUIRED_DOCS = [ "security.md", "streaming.md", "operations.md", - "migration-guide.md", "release-checklist.md", "performance-baseline.md", "repository-adaptation.md", diff --git a/scripts/verify-mongodb-advanced.sh b/scripts/verify-mongodb-advanced.sh index dd0170d8..e0da8549 100755 --- a/scripts/verify-mongodb-advanced.sh +++ b/scripts/verify-mongodb-advanced.sh @@ -6,20 +6,18 @@ # without provider infrastructure, and then reports -- explicitly -- which promotion evidence it # could NOT produce. # -# Required promotion categories (MongoAdvancedPromotionEvidence.REQUIRED): +# Required promotion categories (docs/adr/ADR-MONGO-ADV-001-capability-promotion.md): # # stable-platform, actual-topology, security, migration, failure, runbook # # `actual-topology` is the one that cannot be substituted. A container gives a functional pass for -# sharding, search, vector and encryption while exercising none of the behaviour that makes them -# Advanced rather than Stable: real shard distribution, a real analyzer, a real KMS. Atlas Local is -# a pull-request convenience and is not release evidence -- see -# MongoAtlasCapabilityContractSuite.Environment. +# sharding and encryption while exercising none of the behaviour that makes them Advanced rather +# than Stable: real shard distribution, a real KMS. # # Usage: # bash scripts/verify-mongodb-advanced.sh # MONGODB_DOCKER=1 bash scripts/verify-mongodb-advanced.sh -# MONGODB_SHARDED_URI=... MONGODB_ATLAS_URI=... MONGODB_KMS=... bash scripts/verify-mongodb-advanced.sh +# MONGODB_SHARDED_URI=... MONGODB_KMS=... bash scripts/verify-mongodb-advanced.sh # set -euo pipefail @@ -52,8 +50,7 @@ fi # --- failure + runbook (hermetic) ------------------------------------------------------------- # Every Advanced refusal contract: disabled capability refuses construction, CSFLE/QE cannot share a -# collection, QE substring/prefix/suffix unsupported on 8.0, a non-READY search index cannot serve, -# undeclared scatter-gather is rejected, a dimension mismatch is refused. +# collection, QE substring/prefix/suffix unsupported on 8.0, undeclared scatter-gather is rejected. echo "" echo "=== [failure] Advanced contract tests" if (cd "${GRADLE_DIR}" && "${GRADLE[@]}" "${MODULE}:test" --tests '*advanced*'); then @@ -64,7 +61,7 @@ fi echo "" echo "=== [runbook] capability documentation" -for doc in sharding time-series encryption search-vector multi-tenancy gridfs-migration; do +for doc in sharding encryption multi-tenancy; do path="${REPO_ROOT}/docs/mongodb/advanced/${doc}.md" if [[ -f "${path}" ]]; then echo " + ${doc}.md" @@ -106,15 +103,7 @@ fi # Present is not exercised. An environment variable proves somebody exported a string; the # contract is satisfied by a lane that ran against the deployment it names, which is why this -# records the variable as *not yet* evidence until MONGO-REL-011's class has run. -if [[ -n "${MONGODB_ATLAS_URI:-}" ]]; then - echo "actual-topology(search/vector): MONGODB_ATLAS_URI present (lane not yet implemented)" - MISSING_EVIDENCE+=("actual-topology: MONGO-REL-011 has no lane; an exported URI is not a run") -else - echo "actual-topology(search/vector): no MONGODB_ATLAS_URI" - MISSING_EVIDENCE+=("actual-topology: search/vector on the actual target deployment") -fi - +# records the variable as *not yet* evidence until MONGO-REL-012's class has run. if [[ -n "${MONGODB_KMS:-}" ]]; then echo "actual-topology(encryption): MONGODB_KMS present (lane not yet implemented)" MISSING_EVIDENCE+=("actual-topology: MONGO-REL-012 has no lane; an exported KMS is not a run") @@ -154,8 +143,7 @@ if (( ${#MISSING_EVIDENCE[@]} > 0 )); then for entry in "${MISSING_EVIDENCE[@]}"; do echo " ~ ${entry}"; done echo "" echo "A capability stays opt-in until every category in" - echo "MongoAdvancedPromotionEvidence.REQUIRED is supplied. See" - echo "docs/adr/ADR-MONGO-ADV-001-capability-promotion.md." + echo "docs/adr/ADR-MONGO-ADV-001-capability-promotion.md is supplied." echo "---------------------------------------------------------------" exit 2 fi diff --git a/scripts/verify-mongodb-platform.sh b/scripts/verify-mongodb-platform.sh index 9a268def..2808fcf2 100755 --- a/scripts/verify-mongodb-platform.sh +++ b/scripts/verify-mongodb-platform.sh @@ -99,7 +99,7 @@ echo "repository: ${REPO_ROOT}" # --- Always-on lanes ------------------------------------------------------------------------- # Static analysis, architecture boundaries, unit and hermetic contract tests. These produce the # mapping, transaction, migration, change-stream and security evidence that does not need a server. -run_lane "static-analysis" "check" -x "mongoStableContractTest" -x "verifyMongoReleaseContractLanes" +run_lane "static-analysis" "check" -x "mongoStableContractTest" run_lane "mapping+transaction+migration+change-stream+security" "mongoStableContractTest" # --- Container lanes ------------------------------------------------------------------------- diff --git a/src/.env.example b/src/.env.example index fab71e86..2c684ecd 100644 --- a/src/.env.example +++ b/src/.env.example @@ -123,7 +123,9 @@ APP_RATE_LIMIT_REFILL_PERIOD=1s APP_RATE_LIMIT_MAXIMUM_COST=10 APP_RATE_LIMIT_CLEANUP_GRACE=5s APP_IDEMPOTENCY_TTL=24h -APP_IDEMPOTENCY_PROVIDER=jdbc +# disabled | redis | postgresql. postgresql refuses a non-PostgreSQL data source, so bootRunH2 +# runs with disabled or redis. +APP_IDEMPOTENCY_PROVIDER=disabled APP_IDEMPOTENCY_REDIS_NAMESPACE_ENVIRONMENT=local APP_IDEMPOTENCY_PROCESSING_LEASE=30s APP_IDEMPOTENCY_FAILURE_RETENTION=24h @@ -131,7 +133,7 @@ APP_LEASE_PROVIDER=disabled APP_LEASE_REDIS_NAMESPACE_ENVIRONMENT=local APP_LEASE_REDIS_DRIFT_BUDGET=10ms APP_CACHE_CANONICAL_DEFAULT_PROVIDER=disabled -APP_REDIS_ENABLED=false +APP_REDIS_ENABLED=true APP_CACHE_REDIS_POSITIVE_HARD_TTL=5m APP_CACHE_REDIS_NEGATIVE_TTL=10s APP_IDEMPOTENCY_REDIS_COMMAND_TIMEOUT=200ms @@ -139,33 +141,14 @@ APP_LEASE_REDIS_COMMAND_TIMEOUT=200ms APP_LEASE_REDIS_CONTENTION_RETRY_AFTER=50ms APP_REDIS_ADMIN_CREDENTIAL_REFERENCE= APP_REDIS_ADMIN_ENABLED=false -APP_REDIS_ADVANCED_ENABLED=false -APP_REDIS_ADVANCED_POLICIES= -APP_REDIS_BLOCKING_MAX_BLOCK=30s APP_REDIS_BLOCKING_MAX_CONNECTIONS=32 APP_REDIS_DATABASE=0 -APP_REDIS_LIMITS_MAX_BATCH_COMMANDS=500 -APP_REDIS_LIMITS_MAX_BATCH_REPLY_BYTES=16777216 -APP_REDIS_LIMITS_MAX_BATCH_REQUEST_BYTES=4194304 -APP_REDIS_LIMITS_MAX_BITMAP_OFFSET=10000000 -APP_REDIS_LIMITS_MAX_COLLECTION_ELEMENTS=1000 -APP_REDIS_LIMITS_MAX_HASH_FIELD_VALUE_BYTES=524288 -APP_REDIS_LIMITS_MAX_KEY_BYTES=512 -APP_REDIS_LIMITS_MAX_SCAN_COUNT=500 -APP_REDIS_LIMITS_MAX_STREAM_PAYLOAD_BYTES=262144 -APP_REDIS_LIMITS_MAX_VALUE_BYTES=1048576 -APP_REDIS_LIMITS_OFFLINE_QUEUE_COMMANDS=1000 APP_REDIS_MODE=standalone APP_REDIS_NAMESPACE_DOMAIN=shared APP_REDIS_NAMESPACE_ENVIRONMENT=local APP_REDIS_NAMESPACE_SERVICE=sample-service APP_REDIS_NODES=localhost:6379 -APP_REDIS_RAW_CREDENTIAL_REFERENCE= -APP_REDIS_RAW_ENABLED=false -APP_REDIS_RAW_POLICY_RESOURCE=classpath:redis-sdk/raw-command-allowlist.yml -APP_REDIS_TIMEOUT_ADMIN=3s APP_REDIS_TIMEOUT_BATCH=2s -APP_REDIS_TIMEOUT_COLLECTION=2s APP_REDIS_TIMEOUT_FAST=500ms APP_REDIS_TIMEOUT_SCRIPT=1s APP_REDIS_TRANSACTION_MAX_CONNECTIONS=16 @@ -173,10 +156,8 @@ APP_REDIS_AUTHENTICATION_ADVANCED_CREDENTIAL_REFERENCE= APP_REDIS_AUTHENTICATION_ANONYMOUS_ACCESS_ACCEPTED=false APP_REDIS_AUTHENTICATION_CREDENTIAL_REFERENCE= APP_REDIS_AUTHENTICATION_PUBSUB_CREDENTIAL_REFERENCE= -APP_REDIS_CAPACITY_MAXIMUM_IN_FLIGHT_BYTES= APP_REDIS_CAPACITY_MAXIMUM_IN_FLIGHT_COMMANDS=64 APP_REDIS_CAPACITY_MAXIMUM_SCRIPT_CONNECTIONS=8 -APP_REDIS_CAPACITY_MAXIMUM_REPLY_BYTES= APP_REDIS_CAPACITY_REJECT_WHEN_DISCONNECTED=true APP_REDIS_CLUSTER_MAXIMUM_REDIRECTS=5 APP_REDIS_CLUSTER_TOPOLOGY_REFRESH_PERIOD=30s @@ -186,9 +167,7 @@ APP_REDIS_LIFECYCLE_CONNECT_TIMEOUT=2s APP_REDIS_LIFECYCLE_DRAIN_TIMEOUT=6s APP_REDIS_LIFECYCLE_SHUTDOWN_QUIET_PERIOD=100ms APP_REDIS_LIFECYCLE_SHUTDOWN_TIMEOUT=3s -APP_REDIS_LIFECYCLE_TLS_HANDSHAKE_TIMEOUT=3s APP_REDIS_PUBSUB_BUFFER_CAPACITY=1024 -APP_REDIS_PUBSUB_OVERFLOW_POLICY=error APP_REDIS_SENTINEL_CREDENTIAL_REFERENCE= APP_REDIS_SENTINEL_MASTER_NAME= APP_REDIS_SENTINEL_NODES=app.redis.nodes @@ -223,20 +202,14 @@ APP_CACHE_REDIS_L1_GENERATION_RECHECK_INTERVAL=5s APP_CACHE_REDIS_L1_INVALIDATION_QUEUE_CAPACITY=1024 APP_CACHE_DEFAULT_TTL=300s APP_CACHE_NEGATIVE_TTL=60s -APP_MESSAGING_BROKER= +APP_MESSAGING_BROKER=kafka APP_MESSAGING_PRODUCER_ID= APP_MESSAGING_KAFKA_BROKERS= APP_NOTIFICATION_SLACK_WEBHOOK_ENABLED=false APP_NOTIFICATION_GOOGLE_EMAIL_ENABLED=false -APP_FILESERVER_ENABLED=false -APP_FILESERVER_LOCAL_ROOT= -APP_FILESERVER_LOCAL_EXPECTED_FILE_STORE_NAME= -APP_FILESERVER_LOCAL_EXPECTED_FILE_STORE_TYPE= -APP_FILESERVER_LOCAL_MOUNT_SENTINEL_SHA256= -APP_FILESERVER_LOCAL_EXPECTED_OWNER= -APP_HTTPCLIENT_ENABLED=false +APP_HTTPCLIENT_ENABLED=true APP_HTTPCLIENT_ROTATION_DRAIN_TIMEOUT=30s -APP_FILESERVER_PLATFORM_ENABLED=false +APP_FILESERVER_PLATFORM_ENABLED=true APP_FILESERVER_PLATFORM_INSTANCE_ID=local-node APP_FILESERVER_PLATFORM_DEFAULT_NAMESPACE=default APP_FILESERVER_PLATFORM_STORAGE_ROOT=/var/lib/backend/files @@ -290,19 +263,19 @@ APP_FILESERVER_PLATFORM_OBSERVABILITY_METRICS_ENABLED=true APP_ASYNC_EXECUTOR_CORE_SIZE=10 APP_ASYNC_EXECUTOR_MAX_SIZE=50 APP_ASYNC_EXECUTOR_QUEUE_CAPACITY=200 -APP_PERSISTENCE_JPA_ENABLED=false +APP_PERSISTENCE_JPA_ENABLED=true APP_JPA_HIBERNATE_BATCH_SIZE=0 APP_JPA_HIBERNATE_ORDER_INSERTS=false APP_JPA_HIBERNATE_ORDER_UPDATES=false APP_JPA_HIBERNATE_DEFAULT_BATCH_FETCH_SIZE=0 APP_JPA_HIBERNATE_GENERATE_STATISTICS=false -APP_PERSISTENCE_MONGO_ENABLED=false +APP_PERSISTENCE_MONGO_ENABLED=true APP_PERSISTENCE_MONGO_ACTIVE_PROFILE= # Optional standard Boot 4 connection path. When omitted, the selected typed Mongo profile must # provide uri-secret and the deployment must supply a MongoCredentialResolver. SPRING_MONGODB_URI= -APP_MESSAGING_ENABLED=false -APP_GRAPHQL_ENABLED=false +APP_MESSAGING_ENABLED=true +APP_GRAPHQL_ENABLED=true APP_GRAPHQL_DEPLOYMENT_MODE= APP_GRAPHQL_EXECUTION_PROFILE=BLOCKING_MVC APP_GRAPHQL_VALIDATION_POLICY_VERSION=v1 @@ -317,31 +290,14 @@ APP_GRAPHQL_PREPARSED_CACHE_EXPIRE_AFTER_ACCESS=30m # Optional build-composition: these bind only when :adapter:inbound:websocket is present. # The default bootJar does not contain that leaf. -APP_WEBSOCKET_ENABLED=false +APP_WEBSOCKET_ENABLED=true APP_WEBSOCKET_ENDPOINT=/ws APP_WEBSOCKET_ALLOWED_ORIGINS=http://localhost:3000 APP_WEBSOCKET_BROADCAST_DESTINATION=/topic/events -APP_WEBSOCKET_PLATFORM_ENABLED=false -APP_WEBSOCKET_PLATFORM_NODE_ID=local -APP_WEBSOCKET_PLATFORM_ALLOWED_ORIGINS= -APP_WEBSOCKET_PLATFORM_ALLOW_MISSING_ORIGIN=false -APP_WEBSOCKET_PLATFORM_MAX_FRAME_BYTES=65536 -APP_WEBSOCKET_PLATFORM_MAX_MESSAGE_BYTES=524288 -APP_WEBSOCKET_PLATFORM_MAX_FRAGMENTS=16 -APP_WEBSOCKET_PLATFORM_MAX_BUFFERED_OUTBOUND_BYTES_PER_CONNECTION=1048576 -APP_WEBSOCKET_PLATFORM_MAX_BUFFERED_OUTBOUND_BYTES_PER_NODE=67108864 -APP_WEBSOCKET_PLATFORM_MAX_CONNECTIONS_PER_ACTOR=4 -APP_WEBSOCKET_PLATFORM_PING_INTERVAL=15s -APP_WEBSOCKET_PLATFORM_IDLE_TIMEOUT=45s -APP_WEBSOCKET_PLATFORM_MAX_CONNECTION_AGE=4h -APP_WEBSOCKET_PLATFORM_TICKET_LIFETIME=30s -APP_WEBSOCKET_ADVANCED_SOCKJS_ENABLED=false -APP_WEBSOCKET_ADVANCED_STOMP_ENABLED=false -APP_WEBSOCKET_ADVANCED_STOMP_RELAY_ENABLED=false APP_OUTBOX_ENABLED=false APP_OUTBOX_RELAY_ENABLED=false APP_OUTBOX_CANONICAL_TRANSPORT_ENABLED=false -APP_NOTIFICATION_PLATFORM_ENABLED=false +APP_NOTIFICATION_PLATFORM_ENABLED=true APP_NOTIFICATION_PLATFORM_MODE=SERVING # OpenAPI exposure. application-prod.yml pins both false regardless of these. APP_OPENAPI_DOCS_ENABLED=true @@ -372,6 +328,8 @@ APP_NOTIFICATION_PLATFORM_SES_REGION=us-east-1 APP_NOTIFICATION_PLATFORM_SES_SENDER_IDENTITY= APP_NOTIFICATION_PLATFORM_SES_ACCESS_KEY_ID= APP_NOTIFICATION_PLATFORM_SES_CONFIGURATION_SET= +# Comma-separated SNS topic ARNs whose SES events are accepted; required when callbacks are enabled. +APP_NOTIFICATION_PLATFORM_SES_ALLOWED_TOPIC_ARNS= # SMTP transport security and socket deadlines are Spring Mail's settings. When the SMTP provider # is enabled, configure the actual JavaMailSender with required STARTTLS (or implicit TLS) and # positive mail.smtp.connectiontimeout / mail.smtp.timeout / mail.smtp.writetimeout values. @@ -420,7 +378,8 @@ APP_CACHE_REDIS_KEY_HMAC_SECRET= APP_FILESERVER_PLATFORM_OBSERVABILITY_FINGERPRINT_KEY= # The notification platform's eight key purposes. Each is base64 of at least 32 bytes and must # differ from the other seven; the platform decodes all eight at startup and refuses to boot if one -# is blank, short or shared. Only needed when APP_NOTIFICATION_PLATFORM_ENABLED=true. +# is blank, short or shared. Only needed when the notification module is selected and not switched +# off with APP_NOTIFICATION_PLATFORM_ENABLED=false. APP_NOTIFICATION_PLATFORM_CONTACT_ENCRYPTION_KEY= APP_NOTIFICATION_PLATFORM_CONTACT_LOOKUP_HMAC_KEY= APP_NOTIFICATION_PLATFORM_CALLBACK_SIGNING_KEY= diff --git a/src/.env.local.example b/src/.env.local.example index eb5a94c3..e613683e 100644 --- a/src/.env.local.example +++ b/src/.env.local.example @@ -1,14 +1,15 @@ # ============================================================================= -# A local opt-in example: the five adapters are off in the shipped defaults, and this shows what -# turning some of them on looks like. Copy to src/.env.local and edit. +# A local example for a service that selected some capabilities. Copy to src/.env.local and edit. # -# Each switch here needs the infrastructure its Compose profile provides. Turning one on without -# it is refused at startup by CapabilityDependencyValidator, which names the missing value. +# The default composition is web-only. A capability is on when its runtimeOnly line in +# app-bootstrap/build.gradle is uncommented, and each needs the infrastructure its Compose profile +# provides. The values below are what each one needs once selected; a missing required value is +# refused at startup, naming the key. APP_*_ENABLED=false turns a selected capability off. # ============================================================================= SPRING_PROFILES_ACTIVE=local -# JPA: needs the PostgreSQL service. Flyway owns the schema from dev onward, and local uses the +# JPA (persistence-jpa line): needs the PostgreSQL service. Flyway owns the schema from dev onward, and local uses the # same vendor semantics so the two do not diverge. APP_PERSISTENCE_JPA_ENABLED=true APP_DATASOURCE_URL=jdbc:postgresql://localhost:5433/ca_skeleton @@ -16,21 +17,22 @@ APP_DATASOURCE_USERNAME=ca_skeleton APP_DATASOURCE_PASSWORD= APP_DATASOURCE_DDL_AUTO=validate -# Messaging: the broker id selects the transport; the switch decides whether there is one at all. -APP_MESSAGING_ENABLED=false -APP_MESSAGING_BROKER= +# Messaging (Kafka): on when app-bootstrap/build.gradle carries +# `runtimeOnly project(':adapter:outbound:messaging-kafka')`; APP_MESSAGING_ENABLED=false turns it off. +APP_MESSAGING_KAFKA_BROKERS=localhost:9092 # Outbox: needs JPA and messaging together, and a broker. relay-enabled only starts the scheduler. APP_OUTBOX_ENABLED=false APP_OUTBOX_RELAY_ENABLED=false -# Mongo: active-profile is required when the switch is on, and selects exactly one client. -APP_PERSISTENCE_MONGO_ENABLED=false -APP_PERSISTENCE_MONGO_ACTIVE_PROFILE= +# Mongo: on when its runtimeOnly line is in app-bootstrap/build.gradle. active-profile is required +# and selects exactly one client. +APP_PERSISTENCE_MONGO_ACTIVE_PROFILE=standard-uri +SPRING_MONGODB_URI=mongodb://localhost:27017/ca_skeleton -# GraphQL: the deployment mode must match the runtime environment (local -> LOCAL). -APP_GRAPHQL_ENABLED=false +# GraphQL: on when its runtimeOnly line is in app-bootstrap/build.gradle. The deployment mode must +# match the runtime environment (local -> LOCAL). APP_GRAPHQL_DEPLOYMENT_MODE=LOCAL -# Notification: stores requests relationally, so it needs JPA on. -APP_NOTIFICATION_PLATFORM_ENABLED=false +# Notification: on when its line and the persistence-jpa line are selected (it stores requests +# relationally). It then needs the eight key purposes and their ids listed in src/.env.example. diff --git a/src/Dockerfile b/src/Dockerfile index 00f4087f..bcf7891c 100644 --- a/src/Dockerfile +++ b/src/Dockerfile @@ -8,6 +8,8 @@ # --build-arg BUILD_VERSION=1.2.3+a1b2c3d4e5f6 \ # --build-arg GIT_SHA=a1b2c3d4e5f6 \ # --build-arg SOURCE_URL=https://github.com/your-org/your-repo +# Add --build-arg COMPOSITION=qualification for the Compose-lane image with every capability +# module on the classpath (see the builder stage). The default is the shipped composition. # # Design decisions (feature-container-runtime-contract D2/D3/D4): # D2 — read-only root filesystem: writable mounts must be declared explicitly. @@ -60,9 +62,20 @@ RUN test -n "${RELEASE_VERSION}" \ -PreleaseVersion="${RELEASE_VERSION}" -PgitRevision="${GIT_SHA}" # Copy full source and stage the executable JAR at Gradle's declared Docker output path. +# +# COMPOSITION picks which jar that is. `default` is the composition a service ships (bootJar) and the +# only one a release builds. `qualification` is the same application with every capability module +# on the classpath (qualificationBootJar), for the Compose lanes that turn one on; it is never +# released. Declared here, after the dependency layer, so both share that cache. +ARG COMPOSITION=default COPY . . -RUN ./gradlew :app-bootstrap:stageDockerJar --no-daemon -x test \ - -PreleaseVersion="${RELEASE_VERSION}" -PgitRevision="${GIT_SHA}" +RUN case "${COMPOSITION}" in \ + default) ./gradlew :app-bootstrap:stageDockerJar --no-daemon -x test \ + -PreleaseVersion="${RELEASE_VERSION}" -PgitRevision="${GIT_SHA}" ;; \ + qualification) ./gradlew :app-bootstrap:stageQualificationDockerJar --no-daemon -x test \ + -PreleaseVersion="${RELEASE_VERSION}" -PgitRevision="${GIT_SHA}" ;; \ + *) echo "COMPOSITION must be default or qualification, got '${COMPOSITION}'" >&2; exit 64 ;; \ + esac # ---- Layer extraction (D8) -------------------------------------------------- # Split the uber JAR into Spring Boot's four layers before it reaches the runtime stage. diff --git a/src/README.md b/src/README.md index 3e32317d..c3db6d2a 100644 --- a/src/README.md +++ b/src/README.md @@ -22,17 +22,18 @@ Checkstyle은 **포매터가 표현할 수 없는 것만** — 네이밍과 몇 | 게이트 | 하는 일 | | --- | --- | -| `architectureCheck` | Clean Architecture 의존 방향, runtime membership, application-core purity, Git에 실리지 않는 source package를 검사 | +| `architectureCheck` | Clean Architecture 의존 방향, domain-core·shared-contract·application-* 순수성, Git에 실리지 않는 source package, ArchUnit을 검사 | | `qualityCheck` | 모든 leaf의 SpotBugs + FindSecBugs를 실행 | | `configContractCheck` | `:app-bootstrap:verifyEnvKeys`로 환경 설정 계약을 검사 | -| `qualificationCheck` | Gradle TestKit 기반 build/repository behavior 검증을 실행 | +| `qualificationCheck` | 전체 기동(system) 레인과 보조 source set Checkstyle을 실행 | | `integrationCheck` | 명시적으로 선언된 strict integration lane을 실행. 일부 lane은 container runtime이 필요 | -| `ci` | 모든 leaf `check` + `architectureCheck` + `qualityCheck` + `configContractCheck` + `qualificationCheck` | +| `ci` | PR 게이트: 모든 leaf `check` + `architectureCheck` + `qualityCheck` | +| `mainCheck` | main 단계: `configContractCheck` + `qualificationCheck` + sample web 계약 + `verifyPublicPathSnapshot` + API surface + 전송·메시징 qualification 레인 + JPA readiness registry | | `releaseCheck` | `ci`에 release provenance/archive 관련 검증을 추가 | 따라서 로컬에서 한 모듈만 수정했다면 `./gradlew :domain-core:check`처럼 focused task를 -먼저 사용합니다. Gradle TestKit qualification은 일반 leaf `check`나 `:app-bootstrap:build`에 -매달지 않고 `qualificationCheck`/`ci`에서 실행합니다. +먼저 사용합니다. 전체 기동 qualification은 일반 leaf `check`나 `:app-bootstrap:build`에 +매달지 않고 `qualificationCheck`/`mainCheck`에서 실행합니다. **2026-09에 삭제한 게이트.** `verifyOneTypePerFile`(Checkstyle의 `OneTopLevelClass`가 같은 규칙을 파싱된 파일에 대해 검사한다), `verifyTrivyignore`·`verifyQuarantineSunset`(빈 레지스트리를 지키는 @@ -94,16 +95,9 @@ archive task 자체는 timestamp 비보존·재현 가능한 file order·고정 registry와 `:app-bootstrap:architectureTest`의 관련 ArchUnit 규칙을 함께 갱신해야 합니다. settings와 gate는 같은 registry를 읽고, 등록되지 않은 leaf나 허용되지 않은 edge를 fail-closed로 거부합니다. -### `verifyRuntimeModuleRegistry` - -- **하는 일.** `composition_roots`가 가리키는 실제 Gradle `runtimeClasspath`를 resolve해서 그 안의 - project dependency가 architecture registry에 등록된 application module인지 확인합니다. -- **SSOT.** 어떤 module이 runtime에 실리는지는 `app-bootstrap/build.gradle`의 Gradle dependency graph가 - 결정합니다. registry가 같은 membership 목록을 다시 저장하지 않습니다. -- **변경 규칙.** production edge를 추가하거나 제거할 때는 실제 Gradle dependency와 - `allowed_dependencies` 같은 architecture policy만 함께 검토합니다. exact runtime snapshot을 두 군데 - 맞추는 작업은 없습니다. -- 기존 `verifyRuntimeModuleMembership` task는 외부 스크립트 호환성을 위한 alias입니다. +조립 루트가 받는 모듈의 별도 membership 검사는 없습니다. `app-bootstrap`의 `allowed_dependencies` +밖의 모듈은 방향 게이트가 막고, 무엇이 실제로 실리는지는 `app-bootstrap/build.gradle`의 의존성이 +정합니다. 세 opt-in inbound transport의 test-only composition, 실제 wire 경계, positive-count/zero-skip 증거는 다음 release-blocking aggregate로 실행합니다. @@ -127,8 +121,9 @@ Checkstyle은 파싱된 파일에 같은 질문을 하고, leaf 단위로 돕니 - **소유.** app-bootstrap. 이 질문("이 애플리케이션의 배포에 무엇을 줘야 하는가")은 composition root의 것이고, `./gradlew :domain-core:check`가 알아야 할 사항이 아닙니다. 루트 집계 이름은 - `configContractCheck`이고 구현은 `build-logic`의 `ca.config-contract` convention plugin입니다. -- **하는 일.** `docs/registries/env-keys.yaml`, `application*.yml` + `config/*.yml`, + `configContractCheck`이고 구현은 `build-tools`의 `ca.config-contract` plugin입니다. +- **하는 일.** `docs/registries/env-keys.yaml`, app-bootstrap의 `application*.yml` + `config/*.yml`, + capability 모듈이 싣는 `config/*.yml`·`config/module-defaults/*.yml`(기본 조립에 없어도 검사한다), `src/.env.example`을 lock-step(서로 어긋나지 않게) 으로 유지합니다. `env-keys.yaml` 이 `APP_` 키의 SSOT 이고, drift 가 생기면 빌드를 실패시킵니다. - **막으려는 것 3가지.** (1) 필수 env 가 조용히 누락되는 것, (2) 더 이상 쓰지 않는 stale env 키가 @@ -177,9 +172,8 @@ Checkstyle은 파싱된 파일에 같은 질문을 하고, leaf 단위로 돕니 처리, 따옴표 제거 — 지키던 파일은 만들어진 이래 계속 비어 있었습니다. 실제 항목이 생기고 그것이 drift하기 시작하면 그때 자동화합니다. 진짜 항목을 상대로, 진짜 YAML 라이브러리로. -**플래키 격리.** 간헐 실패 테스트에 JUnit 기본 `@Tag("quarantine")`를 붙이면 메인 `test`가 -`excludeTags 'quarantine'`로 제외하므로 merge를 막지 않고, `./gradlew quarantineTest`(비차단)로만 -돕니다. 이 두 줄은 유지됩니다. +**플래키 격리.** `quarantineTest` 버킷과 CI의 비차단 `quarantine` 잡은 삭제했습니다. 격리된 +테스트가 한 번도 없었습니다. 간헐 실패 테스트는 고치거나 지웁니다. `flaky-quarantine.yaml` 레지스트리와 `verifyQuarantineSunset`(14일 sunset + drift 검사)은 삭제했습니다. 250줄짜리 YAML 파서 + Java 렉서(주석과 문자열 리터럴 안의 `@Tag("quarantine")`를 @@ -197,8 +191,9 @@ drift하기 시작하면 그때 자동화합니다. 진짜 항목을 상대로, 서로 같게 유지하는 일을 했습니다. 결과적으로 체크 하나를 추가하려면 Gradle · workflow · 표 · 검사기 기대값 · Java 계약 테스트 다섯 곳을 같이 고쳐야 했습니다. - **워크플로.** `.github/workflows/ci-quality-gates.yml` 의 `release-gate` 잡이 모든 release-blocking - 게이트의 fan-in(단일 required status check)입니다. 플래키 `quarantine` 잡은 의도적으로 `needs` 에서 - 제외(비차단)됩니다. 위임 게이트(Trivy SCA/이미지 스캔)는 `dependency-vulnerability.yml` 가 소유하며, + 게이트의 fan-in(단일 required status check)입니다. included build 테스트는 경로 필터가 걸린 + `build-logic.yml`이, main 단계(`mainCheck`)·configuration-cache·JPA candidate evidence는 + `integration-main.yml`이 돌립니다. 위임 게이트(Trivy SCA/이미지 스캔)는 `dependency-vulnerability.yml` 가 소유하며, GitHub Actions 는 워크플로 간 `needs` 를 못 쓰므로 branch protection 의 required check 합집합으로 묶습니다. @@ -216,20 +211,26 @@ drift하기 시작하면 그때 자동화합니다. 진짜 항목을 상대로, - **`SPRING_PROFILES_ACTIVE`** — 활성 Spring profile. 보통 `local` | `dev` | `stage` | `prod`. JSON 로그의 `profile` 필드도 이 값을 씁니다. -### Runtime safety (기동 시 `StartupSafetyValidator` 가 fail-fast 검사, D8) +### Runtime safety (기동 시 fail-fast 검사, D8) -- 내부 error detail 노출과 request/response body logging은 shipped 기능이 아닙니다. 구현되지 않은 - 기능을 예약 환경 변수로 노출하지 않으며, request logging은 body를 읽지 않는 계약을 검증합니다. -- **`APP_MULTI_INSTANCE_ENABLED`** — `true` 면 인스턴스 협조용 빈 5종(lock / cache-stampede / - leader / rate-limit / migration)이 모두 있어야 하며, 하나라도 없으면 기동이 실패합니다. +- **`APP_SERVER_ERROR_INCLUDE_STACKTRACE` / `APP_SERVER_ERROR_INCLUDE_MESSAGE`** — 로컬 디버깅용. + prod에서 `never`가 아니면 `ErrorDetailExposureSafetyValidator`가 기동을 막습니다(exit 71, + `spring.web.error.include-binding-errors`·`include-exception`도 같음). request logging은 body를 + 읽지 않는 계약을 검증합니다. +- **`APP_MULTI_INSTANCE_ENABLED`** — `true` 면 cross-instance `DistributedLockPort` + (`distributedLockProvider`)가 조립돼 있어야 하며, 없으면 기동이 실패합니다(exit 72, + `StartupSafetyValidator`). - **`APP_RATE_LIMIT_ENABLED`** — provider-neutral edge rate-limit interceptor 활성화 (429 + `Retry-After` + `X-RateLimit-*` 응답). 기본값은 `false`이며, `true`로 바꿀 때는 `APP_RATE_LIMIT_PROVIDER=redis`와 canonical coordination role을 함께 구성해야 합니다. - **`APP_RATE_LIMIT_CLIENT_IP_MODE`** — 클라이언트 IP 판별 방식. `remote-addr-only` | `forwarded-headers-trusted`. **신뢰된 ingress/LB 가 `X-Forwarded-For` 를 앱 도달 전에 덮어쓸 때만** `forwarded-headers-trusted` 를 쓰세요. 아니면 IP 위조에 노출됩니다. -- **`APP_IDEMPOTENCY_TTL`** — idempotency 레코드 기본 TTL. duration(예: `24h`, `72h`). 오래 도는 use - case 는 최대 72h 까지 override 가능. (D6) +- **`APP_IDEMPOTENCY_PROVIDER`** — 요청 멱등성 store. `disabled`(기본) | `redis` | `postgresql`. + `postgresql` 은 PostgreSQL data source 가 아니면 기동을 거부하므로 `bootRunH2` 에서는 + `disabled` 나 `redis` 를 씁니다. +- **`APP_IDEMPOTENCY_TTL`** — 완료 응답을 재생할 수 있는 기간(`replay-ttl`). duration(예: `24h`). + 최대 72h 이고 넘으면 기동을 거부합니다. (D6) ### Async executor @@ -240,32 +241,42 @@ drift하기 시작하면 그때 자동화합니다. 진짜 항목을 상대로, - **`APP_ASYNC_EXECUTOR_QUEUE_CAPACITY`** — 백로그 큐 용량. **bounded(유한) 필수, unbounded 금지(D7)**. 1 이상 정수. -### 다섯 master switch (activation SSOT) +### 기능 추가 = 한 줄 + env -한 bootJar가 다섯 어댑터를 모두 싣고, 각각은 아래 스위치 하나로만 켜집니다. **전부 기본 `false`** 이고, -다섯이 모두 꺼진 배포는 외부 자원 없이 기동합니다. 값의 SSOT는 -`dev.caskeleton.shared.activation.MasterSwitch`이며 `docs/registries/env-keys.yaml`이 같은 이름을 -등록합니다. +기본 조립(`bootJar`)에는 web, 관측(actuator·metrics·tracing·로그), `domain-core`·`application-core`· +`shared-contract`, `adapter:outbound:support`·`adapter:outbound:identifier`만 들어 있습니다. DB·Redis· +Kafka 없이 기동합니다. 나머지 기능은 `app-bootstrap/build.gradle`에 주석 처리된 `runtimeOnly` 한 줄로 +있습니다. -| 환경 변수 | Spring property | 기본값 | -|---|---|---| -| `APP_PERSISTENCE_JPA_ENABLED` | `ca-skeleton.persistence-jpa.enabled` | `false` | -| `APP_PERSISTENCE_MONGO_ENABLED` | `ca-skeleton.persistence-mongo.enabled` | `false` | -| `APP_MESSAGING_ENABLED` | `app.messaging.enabled` | `false` | -| `APP_NOTIFICATION_PLATFORM_ENABLED` | `ca-skeleton.notification.platform.enabled` | `false` | -| `APP_GRAPHQL_ENABLED` | `backend.graphql.enabled` | `false` | +- **켜기:** 그 줄의 주석을 풀고, 아래 env를 `src/.env`에 넣습니다. 모듈이 classpath에 있으면 켜집니다. +- **끄기:** 줄을 지웁니다. 모듈의 bean·설정·의존성이 함께 빠집니다. 줄은 두고 잠시 끄려면 "끄는 키"를 + `false`로 줍니다(모든 키의 기본값은 `true`). +- **줄을 바꾼 뒤:** strict lock을 갱신합니다. + `./gradlew :app-bootstrap:resolveAndLockAll --write-locks` +- 모든 capability를 한 번에 싣는 jar가 필요하면(compose 레인·CI) `./gradlew :app-bootstrap:qualificationBootJar`를 + 씁니다. 배포용이 아닙니다. -**어댑터가 꺼진 것과 없는 것은 다릅니다.** 다섯 어댑터의 클래스는 언제나 아티팩트 안에 있고, 운영자는 -재빌드 없이 스위치만으로 켭니다. 클래스가 없으면 애초에 켤 수 없습니다. +| capability | `build.gradle` 한 줄 | 켜진 뒤 필요한 env | 끄는 키 | +|---|---|---|---| +| JPA/PostgreSQL (Flyway·outbox store·JDBC 멱등성·분산 락) | `runtimeOnly project(':adapter:outbound:persistence-jpa')` | `APP_DATASOURCE_URL`, `APP_DATASOURCE_USERNAME`, `APP_DATASOURCE_PASSWORD` | `APP_PERSISTENCE_JPA_ENABLED` | +| Redis (cache·rate limit·lease·멱등성) | `runtimeOnly project(':adapter:outbound:cache-redis')` | `APP_REDIS_MODE`, `APP_REDIS_NODES`, `APP_REDIS_NAMESPACE_*`, `APP_REDIS_AUTHENTICATION_CREDENTIAL_REFERENCE`, 쓰는 역할의 선택자(`APP_CACHE_CANONICAL_DEFAULT_PROVIDER`, `APP_RATE_LIMIT_PROVIDER`, `APP_LEASE_PROVIDER`, `APP_IDEMPOTENCY_PROVIDER=redis`) | `APP_REDIS_ENABLED` | +| Kafka 발행 | `runtimeOnly project(':adapter:outbound:messaging-kafka')` | `APP_MESSAGING_KAFKA_BROKERS` (canonical 이벤트를 보내면 `APP_MESSAGING_PRODUCER_ID`) | `APP_MESSAGING_ENABLED` | +| Mongo | `runtimeOnly project(':adapter:outbound:persistence-mongo')` | `APP_PERSISTENCE_MONGO_ACTIVE_PROFILE`, `SPRING_MONGODB_URI`(또는 profile의 `uri-secret`) | `APP_PERSISTENCE_MONGO_ENABLED` | +| GraphQL | `runtimeOnly project(':adapter:inbound:graphql')` | `APP_GRAPHQL_DEPLOYMENT_MODE` (local→`LOCAL`, dev→`DEV`, prod→`PRODUCTION_*`) | `APP_GRAPHQL_ENABLED` | +| 외부 HTTP 호출 | `runtimeOnly project(':adapter:outbound:httpclient')` | client 하나 이상: `APP_HTTPCLIENT_CLIENTS_0_*` (`docs/httpclient/env-fields.yaml`) | `APP_HTTPCLIENT_ENABLED` | +| 객체 저장소 (S3/로컬) | `runtimeOnly project(':adapter:outbound:objectstorage')` | 전용 env 없음. `app.object-storage.*`의 provider·destination을 `application-*.yml`에 적음 | `app.object-storage.enabled` | +| WebSocket (STOMP push) | `runtimeOnly project(':adapter:inbound:websocket')` | 없음(기본값으로 동작). origin은 `APP_WEBSOCKET_ALLOWED_ORIGINS` | `APP_WEBSOCKET_ENABLED` | +| gRPC 서버 | `runtimeOnly project(':adapter:inbound:grpc')` | `CA_SKELETON_GRPC_ALLOW_INSECURE_LOCAL=true` (지금 받는 listener가 loopback plaintext뿐) | `ca-skeleton.grpc.enabled` | +| 파일 서버 (JPA 줄도 필요) | `runtimeOnly project(':composition:fileserver-platform')` | `APP_FILESERVER_PLATFORM_STORAGE_ROOT`, `APP_FILESERVER_PLATFORM_OBSERVABILITY_FINGERPRINT_KEY`, 그리고 `FileAccessPolicy` bean 또는 `APP_FILESERVER_PLATFORM_SECURITY_ACCESS_POLICY=role-based` | `APP_FILESERVER_PLATFORM_ENABLED` | +| 알림 (SMTP/SES, JPA 줄도 필요) | `runtimeOnly project(':composition:notification-platform')` | 키 8종과 각 `_ID`(`APP_NOTIFICATION_PLATFORM_*_KEY`, `*_KEY_ID`), 쓰는 provider 설정(`APP_NOTIFICATION_PLATFORM_SMTP_*` 또는 `_SES_*`) | `APP_NOTIFICATION_PLATFORM_ENABLED` | -켜진 capability가 의존하는 것이 꺼져 있으면 기동이 거부되고, **거부 메시지는 설정해야 할 정확한 -property 이름을 말합니다**(`CapabilityDependencyValidator`). 예: +전체 목록과 타입·기본값은 `docs/registries/env-keys.yaml`, 각 모듈이 제공하는 것은 그 모듈 README의 +"제공하는 것 · 추가할 한 줄 · env 키" 절에 있습니다. 기능 사이의 의존(알림·파일 서버 → JPA, outbox relay +→ JPA + Kafka)은 설정 검사가 아니라 build 줄로 맞춥니다. 표에 "JPA 줄도 필요"라고 적힌 기능은 두 줄을 +함께 넣습니다. -``` -This deployment enables capabilities whose dependencies are off: - - ca-skeleton.outbox.enabled=true needs relational persistence to store rows; - set ca-skeleton.persistence-jpa.enabled=true or turn the outbox off. -``` +어떤 자동 설정이 켜졌는지는 Spring Boot의 `conditions` endpoint로 봅니다. 기본 노출 목록에는 없으므로 +필요할 때 `management.endpoints.web.exposure.include`에 추가합니다. 종속 선택자 둘: @@ -295,24 +306,24 @@ This deployment enables capabilities whose dependencies are off: ### Optional integration adapters -선택형 Kafka / Redis / Slack / Google Email 어댑터 템플릿입니다. **기본은 전부 비활성**(비활성 = 선택 -모듈의 기본값). Layer 1 의 `@ConditionalOnProperty` 가 enabled 일 때만 실제 어댑터를 등록하고, 아니면 -fail-fast sentinel 이 포트를 충족합니다(Layer 3). +Kafka·Redis는 위 "기능 추가 = 한 줄 + env" 표의 한 줄로 고릅니다. 모듈이 있으면 켜지고, 없으면 그 +포트를 구현하는 bean이 아예 없습니다. 아래는 모듈을 고른 뒤 동작을 고르는 키입니다. -- **`APP_CACHE_REDIS_ENABLED`** — Redis 캐시 어댑터 on/off. `true` | `false`. +- **`APP_CACHE_REDIS_ENABLED`** — deprecated(2026-11-30 제거 예정). 읽는 곳은 `sample-portfolio`뿐이고, + 기본 조립에서 Redis를 켜고 끄는 것은 `APP_REDIS_ENABLED`입니다. - **`APP_CACHE_CANONICAL_DEFAULT_PROVIDER`** — canonical default semantic region 선택. `disabled`(기본) | `redis`. `redis`는 canonical Redis CACHE role binding을 함께 요구합니다. - **`APP_CACHE_REDIS_CLIENT_MODE`** — `managed`는 내장 Lettuce runtime, `external`은 프로젝트가 제공한 `RedisClient` bean을 사용합니다. -아래 세 키는 **활성화 스위치가 아니라 선택자**입니다. 어떤 capability가 켜지는지는 위의 master switch가 -정하고, 이 값들은 켜진 capability가 *무엇으로* 동작할지만 고릅니다. 예전에는 "빈 값 = 비활성"으로 +아래 세 키는 **활성화 스위치가 아니라 선택자**입니다. 어떤 capability가 켜지는지는 위의 build 한 줄과 +끄는 키가 정하고, 이 값들은 켜진 capability가 *무엇으로* 동작할지만 고릅니다. 예전에는 "빈 값 = 비활성"으로 설명돼 있었고, 그 문장이 남아 있는 동안 두 개의 활성화 모델이 공존했습니다. -- **`APP_MESSAGING_BROKER`** — 활성 메시지 브로커 id(예: `kafka`). `APP_MESSAGING_ENABLED=true`일 때 - **필수**이고, 빈 값이면 기동이 거부되면서 이 키 이름을 지목합니다. 이 키를 비워도 메시징이 꺼지지는 - 않습니다 — 끄는 것은 master switch입니다. -- **`APP_MESSAGING_KAFKA_BROKERS`** — `host:port` CSV. `APP_MESSAGING_BROKER=kafka` 일 때만 필수, - 아니면 빈 값. +- **`APP_MESSAGING_BROKER`** — 활성 메시지 브로커 id. Kafka 모듈의 설정 기본값이 `kafka`(등록된 유일한 + broker)라 보통 비워 두지 않습니다. 빈 값을 주면 기동이 거부되면서 이 키 이름을 지목합니다. 이 키를 비워도 메시징이 꺼지지는 + 않습니다 — 끄는 것은 `APP_MESSAGING_ENABLED=false`입니다. +- **`APP_MESSAGING_KAFKA_BROKERS`** — `host:port` CSV. Kafka 모듈을 고르면 필수. legacy seam과 + messaging platform의 Kafka transport(`spring.kafka.bootstrap-servers`)가 같은 값을 씁니다. - **`APP_NOTIFICATION_SLACK_WEBHOOK_ENABLED`** — Slack webhook R0 provider enable flag. notification 플랫폼이 켜졌을 때 어떤 provider를 쓸지 고르는 값입니다. - **`APP_NOTIFICATION_GOOGLE_EMAIL_ENABLED`** — Google Email R0 provider enable flag. 위와 같습니다. @@ -508,7 +519,8 @@ Docker 없이 빠르게 wiring·요청/응답·애플리케이션 로직만 확 `./gradlew :app-bootstrap:bootRunH2`를 명시적으로 사용합니다. 이 태스크만 `APP_PERSISTENCE_VENDOR=h2`, `APP_FLYWAY_ENABLED=false`, `APP_DATASOURCE_DDL_AUTO=create-drop`을 주입합니다. H2에는 PostgreSQL migration tree가 없으므로 -migration/vendor 계약의 증거로 사용하지 않습니다. +migration/vendor 계약의 증거로 사용하지 않습니다. 멱등성 provider(`APP_IDEMPOTENCY_PROVIDER`)는 +`disabled`(기본)나 `redis`로 둡니다. `postgresql`은 H2 data source에서 기동을 거부합니다. `dev` 를 호스트에서 띄우려면(`SPRING_PROFILES_ACTIVE=dev`) PostgreSQL 이 필요합니다. `docker-compose.local.yml` 의 `db` 서비스가 루프백(`127.0.0.1:5433`)에만 게시하며, 이 주소가 diff --git a/src/adapter/inbound/graphql/CLAUDE.md b/src/adapter/inbound/graphql/CLAUDE.md index c9649712..a296624b 100644 --- a/src/adapter/inbound/graphql/CLAUDE.md +++ b/src/adapter/inbound/graphql/CLAUDE.md @@ -28,30 +28,23 @@ SSOT(`src/config/architecture/modules.json`)까지 밀어올리지 않는다는 | | 방식 | 경계 강제 | | --- | --- | --- | | messaging | 레지스트리에 leaf 등록 | Gradle 의존 게이트 | -| graphql | 단일 leaf 내 sub-package | 아래 경계 테스트 | +| graphql | 단일 leaf 내 sub-package | 아래 ArchUnit 테스트 (전송 경계만) | -어느 쪽으로 통일할지는 **미결 아키텍처 결정**이다. graphql 을 leaf 로 분해하려면 이 문서의 -모듈 레코드가 그대로 leaf 명세로 승격될 수 있게 설계해 두었다. 그때까지 모듈 경계는 문서가 -아니라 기계가 지킨다: +어느 쪽으로 통일할지는 **미결 아키텍처 결정**이다. -- main 의 `moduleboundary/GraphQlStableModule` · `moduleboundary/GraphQlAdvancedModule` 이 모듈 - 정체성·purity 등급·허용 의존 edge 를 값으로 선언하고, `moduleboundary/GraphQlModuleBoundary` 가 - "이 패키지의 주인은 누구인가 / 이 edge 는 선언됐는가"를 답한다. -- test 의 `moduleboundary/GraphQlBuildModel` 이 실제 소스 트리를 스캔하고, - `moduleboundary/GraphQlModuleBoundaryTest` 가 (a) Stable 패키지의 `...graphql.advanced` import - 금지, (b) `CORE` 등급 모듈의 Spring/GraphQL Java/Reactor/Micrometer/Jakarta import 금지, - (c) 선언되지 않은 cross-module edge 금지, (d) 미등록 패키지 금지, (e) 선언만 있고 소스가 없는 - 모듈 금지를 강제한다. 각 규칙은 **거부되는 합성 트리(negative fixture)** 를 함께 가진다. +sub-package 사이의 경계(Stable↔Advanced 방향, 모듈 레코드)를 값으로 선언하던 `moduleboundary/` +모델과 부팅 때마다 컨트롤러를 리플렉션으로 검사하던 `architecture/` 는 2026-09-25 에 삭제했다 +(`docs/capability-status.md` 제거 표). 지금 기계가 지키는 것은 전송 경계 두 가지뿐이다 — +`GraphQlTransportBoundaryArchitectureTest`(ArchUnit, 이 leaf 패키지 대상): -**패키지 이름은 `build` 가 아니라 `moduleboundary` 다.** `src/.gitignore:2` 의 anchor 없는 -`build/` 규칙은 Gradle 산출물과 Java 패키지를 구분하지 못해서, 예전에 이 경계 모델 전체를 -커밋에서 삼켰다(프로덕션 코드는 계속 import 하고, 작성자 작업본만 컴파일되고, fresh checkout -은 7개 오류로 깨졌다). 레포 전역 `verifyNoIgnoredSourcePackages` 가 이 부류를 막고, -`graphqlStableTest` 의 required-class 검사가 "경계 테스트만 조용히 사라지고 레인은 green" 인 -나머지 절반을 막는다. +- resolver(`@SchemaMapping` 계열·`@BatchMapping`) 시그니처는 전송 타입만 쓴다. 반환·인자 타입과 + 그 제네릭 인자에 raw `Map`, persistence 매핑 타입(`@Entity`/`@Document`/`@Table` 등, 단순명 + 매칭), domain·outbound adapter·JPA/Hibernate/Spring Data/JDBC/Mongo/AWS/gRPC/Kafka 타입이 + 오면 실패한다. +- raw `DataFetcher` 구현은 `scalar`·`schema`·`execution` 패키지에만 둔다. -**새 플랫폼 sub-package 를 추가할 때는 반드시 해당 모듈 레코드에 정체성과 허용 edge 를 먼저 -등록한다.** 등록 없이 추가된 패키지는 경계 테스트가 실패시킨다. +두 규칙 모두 위반 fixture 로 실제로 잡히는지 같은 테스트가 확인한다. `graphqlStableTest` 의 +required-class 검사가 이 테스트가 조용히 사라지는 것을 막는다. ## Responsibility @@ -59,14 +52,15 @@ SSOT(`src/config/architecture/modules.json`)까지 밀어올리지 않는다는 프로토콜 에러 매핑(`GraphqlExceptionResolver`). Spring for GraphQL 이 스키마와 컨트롤러를 자동 합성/바인딩하도록 얹는 얇은 계층이다. - 그 위에 **GraphQL API 실행 플랫폼**(`...graphql` 하위 sub-package 군)이 스키마 계약·전송 - 프로파일·실행 정책·비용 한계·DataLoader·페이지네이션·에러/보안 경계·관측·릴리스 게이트를 + 프로파일·실행 정책·비용 한계·DataLoader·페이지네이션·에러/보안 경계·관측을 소유한다. 플랫폼은 여전히 **feature-agnostic** 이며 정책·계약·검증 기계만 제공한다. - feature-agnostic: `classpath:graphql/**` 스키마와 모든 `@Controller` `@QueryMapping`/ `@MutationMapping` 을 generic 하게 합성한다. **WorkLog 등 구체 기능을 이름으로 알지 않는다.** -- shipped-and-gated: `app-bootstrap` production composition 은 이 leaf 를 직접 의존하고, - `APP_GRAPHQL_ENABLED=false` 가 기본이다. 즉 "off"는 classpath 부재가 아니라 GraphQL - auto-configuration/route 부재로 검증한다. 실제 활성화 시 composition root 는 인증/인가·CORS 정책과 - GraphiQL/introspection 운영 설정을 함께 명시해야 한다. +- 있으면 켜진다: 서비스가 `app-bootstrap/build.gradle`에 `runtimeOnly project(':adapter:inbound:graphql')` + 한 줄로 고른다(기본 조립에는 없다). `APP_GRAPHQL_ENABLED=false`(`backend.graphql.enabled`)만 끄며, + 그때 `GraphQlActivationEnvironmentPostProcessor`가 Spring GraphQL 자동 설정도 exclude 한다. + 실제 활성화 시 composition root 는 인증/인가·CORS 정책과 GraphiQL/introspection 운영 설정을 함께 + 명시해야 한다. ## Error-code ownership @@ -98,9 +92,8 @@ application/platform namespace split. `spring-boot-starter-security`(HTTP 인증/CORS qualification 용), `io.micrometer:micrometer-core`(실제 `MeterRegistry` 로 metric label cardinality 를 **측정**). - `java-test-fixtures` — 계약 스위트·통합 fixture·in-memory 스텁은 `src/testFixtures/java` 가 - 소유하고 production jar 에 들어가지 않는다. 모듈 경계 스캐너 - (`moduleboundary/GraphQlBuildModel`)는 main 과 testFixtures 를 **함께** 스캔한다: 아티팩트가 - 갈렸다고 패키지 경계 규칙까지 갈리면, 규칙이 조용히 절반만 남는다. + 소유하고 production jar 에 들어가지 않는다. +- test scope 에 한해 `archunit-junit5` — 전송 경계 규칙(`GraphQlTransportBoundaryArchitectureTest`). **서버는 이 leaf 가 고르지 않는다.** production 파일 중 `org.springframework.web`· `jakarta.servlet`·`org.springframework.http` 을 import 하는 것은 **하나도 없다**. 예전에는 @@ -160,48 +153,29 @@ health 스키마만 소유한다. | --- | --- | --- | | 실행 파이프라인 / 인가 / cost 예산 | `wired` | `systemTest/runtime/GraphQlPlatformExecutionPathTest` (random-port, 거부 시 resolver 호출 0회) | | depth/complexity 제한 (`cost/`) | `wired` | 같은 테스트의 depth/alias/complexity 케이스 | -| graphql-java parser options (`GraphQlParserOptionsFactory`) | `modelled` | parser policy/factory 단위 테스트만. Stable auto-configuration은 static parser defaults를 교체하지 않는다. HTTP/document cap이 현재 request-path 방어다. | -| response runtime budget (`GraphQlRuntimeBudgetTracker`) | `modelled` | incremental transport 모델에서만 사용된다. Stable response path에는 설치되지 않아 complexity budget을 대체하지 않는다. | | preparsed document cache (`execution/`) | `wired` | `GraphQlPreparsedDocumentAdapter` + 같은 테스트의 캐시 hit 케이스 | | 커스텀 scalar (`scalar/`) | `wired` | 같은 테스트의 scalar coercion 케이스 | -| schema mapping inspection / parallel schema assembler (`schema/`) | `modelled` | `GraphQlMappingInspectionGate`·`GraphQlSchemaAssembler` 단위 테스트만. Stable runtime은 Spring의 schema assembly를 사용하며 소비자 없는 gate bean을 등록하지 않는다. | -| 요청 크기/Accept 협상 (`http/`) | `wired` | `GraphQlRequestBoundsTest`, `GraphQlAcceptNegotiationTest` | +| 요청 크기 (`http/`, body limit filter) | `wired` | `GraphQlRequestBoundsTest` | | 관측 tag cardinality (`observation/`) | `wired` | `runtime/GraphQlRequestObservationConventionAdapter` 가 Spring 의 `ExecutionRequestObservationConvention` 을 구현해 Boot 의 `GraphQlObservationAutoConfiguration` 이 이 컨벤션을 가져간다. `autoconfigure/GraphQlObservationWiringTest`(프레임워크가 실제로 해석), `runtime/GraphQlRequestObservationConventionAdapterTest`(실제 `MeterRegistry` 에 임의 이름 10,000개 → series 1개) | | object 인가 (`security/`) | `modelled` | 답하는 계약은 중립 `dev.caskeleton.application.security.ObjectAccessPolicy` 가 소유하고 이 leaf 는 `ApplicationObjectAuthorization` 매핑만 가진다. 실행 경로에 연결하는 configuration 은 없다 | | DataLoader/batching (`dataloader/`) | `wired` | `runtime/GraphQlBatchLoaderRegistrationTest` (실제 graphql-java 실행 + Spring `BatchLoaderRegistry`, 50 parent → 3 downstream 호출), `dataloader/GraphQlBatchContractTest` | -| cursor 서명 (`pagination/`) | `modelled` | `HmacGraphQlCursorCodec`·`GraphQlCursorKeyRing` 단위 테스트만. **auto-configuration 이 둘 중 무엇도 생성하지 않는다** — `autoconfigure/GraphQlPolicyRequestPathTest` 가 그 사실을 고정 | -| mutation 멱등성 (`mutation/`) | `modelled` | `GraphQlMutationIdempotencyInterceptor` 를 참조하는 configuration 이 없다. 같은 테스트가 고정 | -| persisted operation (`advanced/persisted/`) | `modelled` | 중립 `OperationalRecordStorePort` 기반 레지스트리 + 방향성 테스트. durable 구현체는 미제공 | -| subscription / SSE / RSocket | `modelled` | GraphQL leaf 는 구독 정책/보안/replay 모델만 소유한다. `graphql-transport-ws` 연결 상태기계와 close-code 전송은 `:adapter:inbound:websocket` 이 소유하며 이 leaf 에 병렬 WebSocket transport 구현을 두지 않는다. SSE/RSocket 은 모델/단위 테스트만 있다. | -| federation / incremental / codegen / compat | `modelled` | 단위 테스트만 | -| 실부하·장애 | 미달성 | `graphqlPerformanceTest` 레인이 자리를 예약, 증거 없으면 릴리스 게이트가 거부 | +| cursor 서명·connection (`pagination/`), fetch profile (`fetch/`) | 라이브러리 | 요청 경로에 없다. 서비스가 직접 호출한다 — README "라이브러리 API". `autoconfigure/GraphQlPolicyRequestPathTest` 가 auto-configuration 이 codec·key ring 을 만들지 않음을 고정 | +| 실부하·장애 | 미달성 | 증거 없음 | 여전히 미구현인 것: - feature GraphQL schema/resolver — 이 leaf 는 health 표면만 소유한다(변경 없음). -- 실부하 성능/장애 시나리오 증거 — `release/GraphQlPerformanceScenario`, - `GraphQlFaultScenario` 는 시나리오 카탈로그를 정의하고 `GraphQlReleaseGate` 는 그 증거가 - 없으면 릴리스를 **거부**한다. 증거 자체는 실제 부하 인프라를 요구하므로 이 leaf 밖에서 - 생성한다(`graphqlPerformanceTest` 레인이 그 자리를 예약해 둔다). -- 실제 datastore 통합 증거 — `testkit/GraphQlJpaIntegrationFixture` / - `GraphQlMongoIntegrationFixture` 가 계약을 정의하고 `GraphQlStorageIntegrationEvidence` 가 - 증거를 요구한다. 실 datastore 기동은 persistence leaf 의 책임 범위다. 이 testkit 은 - **production jar 에 없다** — `src/testFixtures/java` 에 살고 `verifyGraphQlProductionJar` 가 - 그 사실을 jar 내용으로 확인한다. -- **cursor 서명이 요청 경로에 없다 (GQL-INT-003).** `HmacGraphQlCursorCodec`와 - `GraphQlCursorKeyRing`은 `modelled` 부품이고 Stable auto-configuration은 어느 쪽도 생성하지 - 않는다. 따라서 `backend.graphql.cursor.key-ids`는 adopter가 직접 조립할 때 사용할 수 있는 - 선언 값일 뿐, production startup requirement도 아니고 활성 보호의 증거도 아니다. - `GraphQlCursorKeyRing.of`는 실제 `Map`를 요구하므로 다음 승격 조건은 key material - source와 request-path wiring을 함께 설계하는 것이다. 그 전까지 shipped `APP_GRAPHQL_*` 계약에는 - cursor key-id를 노출하지 않는다. -- persisted operation 의 durable 저장 구현체 — 이 leaf 는 중립 계약 - `dev.caskeleton.shared.opstore.OperationalRecordStorePort` 에만 의존하고 key/value 매핑만 - 소유한다. Postgres/Redis 구현체는 **그 중립 계약을** 구현하며, 이 leaf 의 타입을 구현하지 - 않는다(그랬다면 인프라 → 인바운드 전송으로 의존이 뒤집힌다). -- Advanced capability 는 전부 **기본 비활성**이다(`advanced/bootstrap/GraphQlAdvancedFeatureFlags`). - EXPERIMENTAL 등급(RSocket, incremental delivery, HTTP GET draft)은 명시적 승인 없이는 - `GraphQlAdvancedModuleGuard` 가 production 활성화를 거부한다. +- 실부하 성능/장애 시나리오 증거 — 없다. 시나리오 카탈로그와 릴리스 게이트(`release/`, + `advanced/release/`)와 스키마 호환성 비교기(`compat/`)는 호출하는 곳이 없어 2026-09-25 에 + 삭제했다. +- 실제 datastore 통합 증거 — 없다. +- `advanced/**`(SSE·RSocket·federation·incremental·HTTP GET·persisted operation·subscription + replay 등)는 바인딩되지 않는 feature flag gate 뒤의 모델뿐이어서 2026-09-25 에 삭제했다 + (`docs/capability-status.md` 제거 표). 다시 필요하면 Spring GraphQL/graphql-java SPI 를 구현하는 + 형태로 새로 만든다. +- 요청 단계 거부(`GraphQlPlatformWebInterceptor`, `GraphQlPlatformInstrumentation`)는 + `GraphQlWireErrorMapper` 를 거치지 않고 `GraphQlPlatformRejectionMapper.map` 을 직접 부른다. + 그래서 요청 단계의 `ApiErrorCarrier` 는 `INTERNAL_ERROR` 가 된다(리뷰 S5 #6, 미해결). ## Test @@ -211,34 +185,32 @@ cd src ./gradlew :adapter:inbound:graphql:graphqlTransportQualificationTest --console=plain ``` -플랫폼 테스트 레인(`ca.graphql-platform` convention plugin 등록). 기본 `test` 는 -`quarantine`·`graphql-performance` 태그를 제외한다: +테스트 레인: ```bash -./gradlew :adapter:inbound:graphql:graphqlStableTest --console=plain # 605 tests -./gradlew :adapter:inbound:graphql:graphqlContractTest --console=plain # 9 tests -./gradlew :adapter:inbound:graphql:graphqlAdvancedTest --console=plain # 152 tests -./gradlew :adapter:inbound:graphql:graphqlPerformanceTest --console=plain # 실부하 인프라 필요 +./gradlew :adapter:inbound:graphql:graphqlStableTest --console=plain # GraphQlTransportBoundaryArchitectureTest만, skip 금지 +./gradlew :adapter:inbound:graphql:systemTest --console=plain # 23 tests (실제 HTTP 서버) ``` -`graphqlPerformanceTest` 는 `@Tag("graphql-performance")` 가 하나도 없으면 **실패한다** — 이는 -버그가 아니라 "성능 증거 없음"을 통과로 위장하지 않기 위한 fail-closed 설계다. - -위 숫자는 `build/test-results//*.xml` 의 실제 실행 결과다(기본 `test` 757, transport -qualification 8). 문서에 옮겨 적은 숫자는 반드시 마지막 green 실행에서 다시 읽어 갱신한다 — -컴파일이 깨진 채로 남은 과거 숫자는 통과 증거가 아니라 통과했다는 인상일 뿐이다. +`graphqlStableTest` 는 `GraphQlTransportBoundaryArchitectureTest` 가 실행되지 않거나 skip 되면 +실패한다(`build.gradle` 의 strict lane `requires` + `rejectSkipped`). 같은 클래스는 `test` 에서도 돈다. ## 아티팩트 게이트 ```bash -./gradlew :adapter:inbound:graphql:verifyGraphQlProductionJar --console=plain +./gradlew :adapter:inbound:graphql:test --tests '*GraphQlProductionClassesTest' --console=plain ./gradlew :adapter:inbound:graphql:verifyGraphQlApiSurface --console=plain ``` -- `verifyGraphQlProductionJar` — production jar 에 `testkit`/`InMemory`/`Fixture`/`TestContext` - 클래스가 하나라도 있으면 실패한다. 계약 스위트와 in-memory 스텁은 `src/testFixtures/java` 가 - 소유한다. +- `GraphQlProductionClassesTest` — production 클래스에 `testkit`/`InMemory`/`ForTests`/`Fixture`/ + `TestContext` 가 하나라도 있으면 실패한다(`test` 의 일부). 테스트용 request context 헬퍼(`testkit/GraphQlRequestContexts`)는 + `src/testFixtures/java` 가 소유한다. - `verifyGraphQlApiSurface` — `docs/architecture/graphql-api-surface.txt` 스냅샷과 실제 public 타입 목록이 다르면 실패한다. 단일 jar 안에서 `public` 은 모든 adopter 에게 public 이므로, 표면 증가는 리뷰 결정이지 빌드 부산물이 아니다. 승인 후: `./gradlew :adapter:inbound:graphql:updateGraphQlApiSurface -PapproveGraphQlApiSurfaceChange`. + +- mutation 멱등성 — 저장소에 연결된 적 없는 `GraphQlMutationIdempotencyInterceptor`·context· + fingerprint 와 `idempotencyKey` extension 허용을 2026-09-25 에 삭제했다. Stable 기본 + `GraphQlExtensionsPolicy` 는 어떤 extension key 도 허용하지 않는다. 요청 재생 멱등성이 필요하면 + application `IdempotencyExecutor` 를 use case 안에서 쓴다. diff --git a/src/adapter/inbound/graphql/README.md b/src/adapter/inbound/graphql/README.md index d308de72..83a04b19 100644 --- a/src/adapter/inbound/graphql/README.md +++ b/src/adapter/inbound/graphql/README.md @@ -28,10 +28,28 @@ Spring for GraphQL 은 schema-first 다. 빈 스키마로는 부팅이 실패하 메서드를 바인딩한다. 향후 feature 의 GraphQL controller 는 스켈레톤을 수정하지 않고 등록할 수 있다. -현재 `app-bootstrap` production composition 은 이 leaf 를 **classpath 에 포함**하고 -`APP_GRAPHQL_ENABLED=false` 를 기본으로 두는 shipped-and-gated 구조다. 따라서 비활성은 jar 부재가 -아니라 runtime route/auto-configuration 비활성으로 증명한다. `sample-portfolio` 에 feature GraphQL -스키마/controller 가 있다는 뜻은 아니며, leaf 자체는 최소 health 스키마로 독립 기동할 수 있다. +## 제공하는 것 · 추가할 한 줄 · env 키 + +- 제공: `/graphql` HTTP endpoint(Spring for GraphQL), 플랫폼 정책(실행 프로파일·비용 한계· + DataLoader·에러/보안 경계·관측), 최소 health 스키마. 설정 기본값 `config/graphql.yml`을 모듈이 + 직접 읽는다(`GraphQlActivationEnvironmentPostProcessor`, 우선순위 가장 낮음). +- 추가할 한 줄(기본 조립에는 없다): + + ```groovy + // app-bootstrap/build.gradle + runtimeOnly project(':adapter:inbound:graphql') // GraphQL + ``` + + 이 줄을 지우면 endpoint, 플랫폼 bean, 설정 기본값이 모두 함께 빠진다. +- 켜기와 끄기: 모듈이 있으면 켜진다. `APP_GRAPHQL_ENABLED=false`로만 끈다. 끄면 이 모듈의 bean과 + Spring GraphQL 자신의 자동 설정(`org.springframework.boot.graphql.*`)이 함께 빠져 `/graphql`이 + 열리지 않는다. +- 필요한 env 키(`docs/registries/env-keys.yaml` SSOT): `APP_GRAPHQL_DEPLOYMENT_MODE`(runtime profile과 + 맞는 값: local→`LOCAL`, dev→`DEV`, prod→`PRODUCTION_INTERNAL`|`PRODUCTION_PUBLIC`). production mode는 + `GraphQlAuthorizationPolicy` bean도 필요하다. 나머지 `APP_GRAPHQL_*`는 기본값으로 동작한다. + +`sample-portfolio` 에 feature GraphQL 스키마/controller 가 있다는 뜻은 아니며, leaf 자체는 최소 +health 스키마로 독립 기동할 수 있다. ## 에러 매핑 — web `GlobalExceptionHandler` / gRPC 인터셉터의 GraphQL 형제 @@ -87,7 +105,7 @@ gRPC 와 달리 spring-graphql / graphql-java 는 Spring Boot BOM 이 관리한 가 소유한다. composition-root `application.yml` 에서 설정하며 모듈별 `yml` 은 없다. 플랫폼 정책은 `spring.graphql.*` 로 표현할 수 없다 — 실행 프로파일, cost/page 한계, preparsed -캐시 경계, cursor 키 링, 관측 label 로 허용할 operation 이름은 전부 이 leaf 의 결정이다. 그래서 +캐시 경계, 관측 label 로 허용할 operation 이름은 전부 이 leaf 의 결정이다. 그래서 `GraphQlPlatformProperties` 가 **`backend.graphql`** prefix 로 `@ConfigurationProperties` 를 바인딩한다(`spring.graphql.platform.*` 이 아니다 — 그 prefix 는 존재한 적이 없다). @@ -109,14 +127,13 @@ backend: observed-operation-names: [] # 비우면 모든 operation 이름이 `other` 로 접힌다 ``` -shipped composition에서는 위 wired 설정을 `APP_GRAPHQL_*`로 노출한다. `APP_GRAPHQL_ENABLED`와 +이 모듈의 `config/graphql.yml`이 위 wired 설정을 `APP_GRAPHQL_*`로 노출한다. `APP_GRAPHQL_ENABLED`와 `APP_GRAPHQL_DEPLOYMENT_MODE` 외에도 execution profile, console, page/complexity, preparsed-cache -한계와 관측 operation allowlist가 `config/graphql.yml`을 통해 같은 property tree로 들어간다. +한계와 관측 operation allowlist가 같은 property tree로 들어간다. production mode는 env만으로 완성되지 않는다. 애플리케이션 좌표를 스켈레톤이 알 수 없으므로 **명시적인 `GraphQlAuthorizationPolicy` bean이 반드시 필요**하며, 이것은 의도된 fail-closed -계약이다. 반대로 cursor signing은 아직 요청 경로에 연결되지 않은 `modelled` capability라 -`APP_GRAPHQL_CURSOR_KEY_IDS` 같은 운영 키를 제공하지 않고 startup requirement로도 취급하지 않는다. +계약이다. cursor 서명은 설정 키가 없다 — 아래 라이브러리 API로 서비스가 직접 조립한다. `observed-operation-names` 가 비어 있는 것이 기본값이자 안전한 값이다. operation 이름은 문법만 검증될 뿐 개수가 제한되지 않으므로, 원본을 그대로 metric label 로 쓰면 정상 클라이언트 하나가 @@ -148,49 +165,33 @@ composition root 는 이 leaf 를 채택할 때 인증/인가 및 CORS 정책을 **정직하게 기록해 둘 반례:** 이후 main 에 통합된 자매 플랫폼 messaging 은 정반대로 **24개 leaf 를 레지스트리에 등록**했다(현재 총 43개 leaf). 즉 레지스트리는 닫혀 있지 않았고, "확장하면 게이트가 깨진다"는 전제는 과했다. 두 플랫폼이 서로 다른 패턴을 쓰고 있으므로 -**어느 쪽으로 통일할지는 미결 아키텍처 결정**이다. graphql 쪽은 모듈 레코드 -(`GraphQlStableModule`/`GraphQlAdvancedModule`)가 그대로 leaf 명세로 승격될 수 있는 형태라 -분해 비용은 낮게 유지했다. +**어느 쪽으로 통일할지는 미결 아키텍처 결정**이다. -어느 패턴이든 "패키지는 경계가 아니다"라는 약점은 기계 검증으로 메웠다 — -`moduleboundary/GraphQlStableModule`·`GraphQlAdvancedModule` 이 모듈 정체성과 허용 edge 를 값으로 -선언하고, `GraphQlModuleBoundaryTest` 가 **실제 소스 트리를 스캔**해 Stable→Advanced import, -CORE 모듈의 프레임워크 import, 선언되지 않은 edge, 미등록 패키지를 실패시킨다. Gradle 이 -해주던 일을 테스트가 한다. +sub-package 경계를 값으로 선언하던 `moduleboundary/` 모델(소스 텍스트 스캐너 포함)은 +2026-09-25 에 삭제했다. 두 플랫폼 중 어느 패턴으로 통일할지 정할 때 다시 설계한다. -스캔은 컴파일된 클래스가 아니라 **소스 텍스트**를 읽는다. 경계가 금지하는 import 는 상수 -인라이닝이나 미보존 시그니처로 바이트코드에서 지워지는 경우가 많아서, 바이트코드 스캔은 -리뷰어가 읽는 소스가 여전히 경계를 넘는데도 clean 이라고 보고한다. 그리고 스캐너는 -**파일을 하나도 못 찾으면 통과가 아니라 실패한다** — 0개 스캔으로 green 이 되는 것이 이 -모델이 막으려는 실패 그 자체다. +## 전송 경계 규칙은 빌드 때 ArchUnit 으로 검사한다 -## ArchUnit/JPA 없이 아키텍처 규칙을 강제한 방법 - -`architecture/` 의 규칙(리졸버 경계, 전송 타입, `@Transactional` 금지, Entity/Document 반환 금지)은 -**리플렉션 + 단순명(simple name) 매칭**으로 구현했다. 인바운드 어댑터가 자신이 금지하는 대상 -(`jakarta.persistence`, `spring-tx`)에 의존해야 그걸 검사할 수 있다면 본말전도이기 때문이다. -`GraphQlControllerTransactionRule` 이 애노테이션 타입이 아니라 단순명 `Transactional` 을 보는 것은 -이 때문이며, 의도된 트레이드오프다. `GraphQlResolverBoundaryRules` 는 스캔 대상 패키지가 비어 -있으면 **실패한다** — 검사할 게 없어서 통과하는 조용한 무력화를 막는다. +예전에는 `architecture/` 가 부팅할 때마다 모든 `@Controller` 를 리플렉션으로 검사했다. 지금은 +`GraphQlTransportBoundaryArchitectureTest` 가 빌드 때 두 가지를 검사한다: resolver 시그니처(제네릭 +인자 포함)에 raw `Map`·persistence 매핑 타입·domain/driver 타입이 없을 것, raw `DataFetcher` +구현은 `scalar`·`schema`·`execution` 에만 있을 것. ArchUnit 은 test 의존성이라 +production classpath 에는 여전히 JPA/Spring Data 가 없다 — persistence 애노테이션은 단순명으로 +매칭한다. 이 leaf 패키지만 검사하므로 adopter 의 컨트롤러는 adopter 가 같은 규칙을 가져가야 한다. ## 부분 실패는 200, 요청 실패는 4xx -`http/GraphQlHttpStatusMapper.V1` 은 검증 통과 후 발생한 필드 에러를 HTTP 200 + partial data 로 -매핑한다. GraphQL over HTTP 초안의 status 294 는 **채택하지 않았다** -(`GraphQlHttpProfile.usesDraftPartialResponseStatus()` 가 `false` 로 못 박고, 초안 프로파일은 -`advanced/get/GraphQlHttpDraftCompatibilityReport` 가 "의도적 미채택"으로 기록한다). 초안 상태 -코드를 프로덕션 와이어 계약에 넣으면 초안이 바뀔 때 클라이언트가 깨진다. - -이 때문에 `Map.copyOf` 를 응답 데이터 경로에 쓸 수 없다 — partial data 는 **정당하게 null 값을 -가진다**. `GraphQlExecutionOutcome`·`GraphQlHttpResponse`·`GraphQlContractResponse` 는 null 을 -허용하는 `LinkedHashMap` 복사를 쓴다. +HTTP 응답은 Spring GraphQL handler가 만든다. 검증 통과 후 발생한 필드 에러는 HTTP 200 + partial +data 다. GraphQL over HTTP 초안의 status 294 는 쓰지 않는다. 이 leaf 가 따로 두던 HTTP 전송 +모델(`GraphQlHttpStatusMapper`, `GraphQlHttpProfile` 등)은 요청 경로에 없어서 2026-09-25 에 +삭제했다(`docs/capability-status.md` 제거 표). ## 요청 단위 DB 트랜잭션을 열지 않는다 GraphQL 한 요청은 여러 root field 를 담을 수 있고, 각 root 는 자기 use case 를 호출한다. 요청 전체를 하나의 트랜잭션으로 묶으면 커넥션을 요청 수명만큼 점유하고 부분 실패 의미론이 무너진다. `mutation/GraphQlMutationContractValidator.rejectRequestWideTransaction` 이 이를 -계약으로 강제하고, `GraphQlControllerTransactionRule` 이 컨트롤러의 `@Transactional` 을 막는다. +계약으로 강제한다. ## 커서는 HMAC 서명된 버전 있는 keyset @@ -210,30 +211,28 @@ tenant 간 데이터 누출 경로가 된다. `security/GraphQlBatchContext.cach 허용하고, 변수·인자·actor id 는 `GraphQlSensitiveAttributeFilter` 가 걸러낸다. GraphQL 은 카디널리티 폭발이 쉬운 전송이라 이 게이트가 없으면 메트릭 백엔드가 먼저 죽는다. -## Advanced 는 전부 기본 비활성 + 등급제 +## 라이브러리 API — 서비스의 어댑터 leaf에서 `implementation`으로 받아 직접 호출 -`advanced/bootstrap/GraphQlAdvancedFeatureFlags` 는 기본 전부 off 다. EXPERIMENTAL 등급 -(RSocket, incremental delivery, HTTP GET draft)은 명시적 승인 플래그 없이는 -`GraphQlAdvancedModuleGuard` 가 production 활성화를 거부한다. 등급 승격은 -`advanced/release/GraphQlAdvancedPromotionDecision` 이 ADR 번호·승인자·미해결 증거를 요구한다 — -"조용히 켜짐"을 구조적으로 불가능하게 만든다. +아래 타입은 auto-configuration 이 빈으로 만들지 않는다. 서비스가 자기 GraphQL 어댑터 leaf 에서 +`implementation project(':adapter:inbound:graphql')` 로 받아 resolver 안에서 직접 생성·호출한다 +(AGENTS.md capability 규칙의 라이브러리형 예외). 켜는 설정 키는 없다. -## 릴리스 게이트는 증거가 없으면 거부한다 +| 기능 | 진입점 | 테스트 | +| --- | --- | --- | +| Relay connection 조립 | `pagination/GraphQlConnectionAssembler`, `GraphQlConnectionPolicy`, `GraphQlConnectionRequest` | `pagination/GraphQlConnectionAssemblerTest` | +| 서명된 keyset cursor | `pagination/HmacGraphQlCursorCodec` + `GraphQlCursorKeyRing.of(Map)` — 키 material 은 서비스가 secret 저장소에서 넣는다 | `pagination/HmacGraphQlCursorCodecTest` | +| selection set → fetch profile | `fetch/GraphQlFetchProfileRegistry`, `GraphQlFetchProfileClassifier` | `fetch/GraphQlFetchProfileRegistryTest`, `fetch/GraphQlFetchProfileClassifierTest` | +| 객체 단위 인가 | `security/ApplicationObjectAuthorization` (`GraphQlObjectAuthorizationPort` 구현, application-core `ObjectAccessPolicy` 호출) | `security/ApplicationObjectAuthorizationTest` | +| mutation 결과 payload | `mutation/GraphQlMutationResultMapper`, `GraphQlBusinessResult`, `GraphQlMutationPayload` | `mutation/GraphQlMutationResultMapperTest` | -`release/GraphQlReleaseGate` 와 `advanced/release/GraphQlAdvancedReleaseGate` 는 성능·장애·보안· -호환성 증거가 없으면 **통과시키지 않는다**. Advanced 는 Stable 기준선 없이는 릴리스 자체가 -불가능하다. 같은 이유로 `graphqlPerformanceTest` 레인은 성능 태그가 하나도 없으면 실패한다 — -증거 부재를 통과로 위장하지 않기 위한 fail-closed 설계다. +`autoconfigure/GraphQlPolicyRequestPathTest` 가 auto-configuration 이 cursor codec·key ring 을 +만들지 않는다는 사실을 고정한다. -## 설계서의 내부 불일치 처리 - -Stable 16번째 모듈이 산문에서는 `graphql-testkit-security`, Task 1 파일 목록과 설계 §5 에서는 -`graphql-testkit-integration` 으로 서로 다르게 적혀 있다. **파일 목록 쪽(testkit-integration)을 -채택**하고, 보안 계약 표면은 `testkit/GraphQlSecurityContractSuite` 로 제공했다. 둘 다 실제로 -존재하므로 어느 쪽 독법이든 표면은 비지 않는다. +예전 `advanced/**`(SSE, RSocket, federation, incremental delivery, HTTP GET, persisted operation, +subscription replay 등)는 모든 진입점이 바인딩되지 않는 feature flag gate 를 거쳤고 Spring +GraphQL/graphql-java SPI 를 구현한 타입이 없어 2026-09-25 에 삭제했다. ## 아직 구현하지 않은 범위 feature GraphQL schema/resolver 는 여전히 이 leaf 밖이다(스켈레톤은 health 표면만 소유). -실부하 성능 증거와 실 datastore 통합 증거도 이 leaf 밖에서 생성해야 한다 — 다만 그 **부재가 -릴리스를 막도록** 게이트가 이미 서 있다. +실부하 성능 증거와 실 datastore 통합 증거도 없다. diff --git a/src/adapter/inbound/graphql/build.gradle b/src/adapter/inbound/graphql/build.gradle index 4e28bb5d..d5659e61 100644 --- a/src/adapter/inbound/graphql/build.gradle +++ b/src/adapter/inbound/graphql/build.gradle @@ -3,9 +3,7 @@ plugins { id 'ca.spring-config' id 'java-test-fixtures' id 'ca.auxiliary-source-set' - id 'ca.graphql-platform' id 'ca.api-surface' - id 'ca.strict-qualification' } // Driving adapter: GraphQL API (skeleton machinery, transport-only). @@ -30,7 +28,7 @@ auxiliarySourceSets { // from any adopter's runtime code — an in-memory persisted-operation registry is a perfectly // working bean until the second instance starts, and a `testContext(String)` mints an authenticated // actor without a credential. A separate test-fixtures artifact keeps them consumable by the tests -// that want them and out of the jar that runs in production; `verifyGraphQlProductionJar` checks +// that want them and out of the jar that runs in production; GraphQlProductionClassesTest checks // the second half rather than trusting it. @@ -93,6 +91,10 @@ dependencies { // micrometer-observation is on the production classpath; a registry that actually stores series // is what turns "this tag is bounded" into a number a test can fail on. testImplementation 'io.micrometer:micrometer-core' + + // GraphQlTransportBoundaryArchitectureTest: the resolver-signature and raw-DataFetcher rules + // that used to run by reflection at every boot. + testImplementation libs.archunit.junit5 } @@ -103,17 +105,23 @@ strictTestLanes { sourceSet = 'systemTest' description = 'Runs the GraphQL adapter over a real embedded HTTP server.' } + lane('graphqlTransportQualificationTest') { + sourceSet = 'systemTest' + description = 'Runs exact no-skip GraphQL conditional transport wire evidence.' + requires 'dev.caskeleton.adapter.inbound.graphql.GraphqlHttpBoundaryQualificationTest' + rejectSkipped = true + jvmArgs '-Duser.timezone=UTC' + } + // The transport-boundary ArchUnit suite runs in `test` too; this lane is the guard that it is + // still discovered and not skipped — a missing class leaves `test` green. + lane('graphqlStableTest') { + description = 'Runs the GraphQL transport-boundary architecture suite and fails if it is gone or skipped.' + requires 'dev.caskeleton.adapter.inbound.graphql.GraphQlTransportBoundaryArchitectureTest' + rejectSkipped = true + jvmArgs '-Duser.timezone=UTC' + } } -extensions.getByName('strictQualification').register( - 'graphqlTransportQualificationTest', - sourceSets.systemTest, - [ - 'dev.caskeleton.adapter.inbound.graphql.GraphqlHttpBoundaryQualificationTest' - ], - 'Runs exact no-skip GraphQL conditional transport wire evidence.' -) - // verifyGraphQlApiSurface — every public type this leaf exposes is a committed decision. // // One jar, 40-odd packages, and a public type in any of them is reachable from every adopter's diff --git a/src/adapter/inbound/graphql/gradle.lockfile b/src/adapter/inbound/graphql/gradle.lockfile index 60be229c..33dff35b 100644 --- a/src/adapter/inbound/graphql/gradle.lockfile +++ b/src/adapter/inbound/graphql/gradle.lockfile @@ -34,6 +34,11 @@ com.graphql-java:java-dataloader:6.0.0=compileClasspath,runtimeClasspath,systemT com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins com.jayway.jsonpath:json-path:2.10.0=systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath com.puppycrawl.tools:checkstyle:13.5.0=checkstyle +com.tngtech.archunit:archunit-junit5-api:1.3.0=systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +com.tngtech.archunit:archunit-junit5-engine-api:1.3.0=systemTestRuntimeClasspath,testRuntimeClasspath +com.tngtech.archunit:archunit-junit5-engine:1.3.0=systemTestRuntimeClasspath,testRuntimeClasspath +com.tngtech.archunit:archunit-junit5:1.3.0=systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +com.tngtech.archunit:archunit:1.3.0=systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath com.vaadin.external.google:android-json:0.0.20131108.vaadin1=systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath commons-beanutils:commons-beanutils:1.11.0=checkstyle commons-collections:commons-collections:3.2.2=checkstyle diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/admin/GraphQlAdminPrincipal.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/admin/GraphQlAdminPrincipal.java deleted file mode 100644 index 904b6ff8..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/admin/GraphQlAdminPrincipal.java +++ /dev/null @@ -1,37 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.admin; - -import java.util.Objects; - -/** - * A verified administrator, as the transport established them. - * - *

The admin service used to take the operator as a bare {@code String} and check it against an - * allowlist. A string is not evidence: any caller that could reach the service could name any - * operator on the list, so the allowlist described who may administer the registry while - * proving nothing about who actually did. The audit trail then recorded that name as fact. - * - *

Only the transport can construct this, having verified the credential, and it records whether - * the credential came from the request path. That check used to exist as a method nobody called. - * - * @param operator the verified operator reference - * @param applicationCredential whether the credential is one the request path also holds - */ -public record GraphQlAdminPrincipal(String operator, boolean applicationCredential) { - - public GraphQlAdminPrincipal { - Objects.requireNonNull(operator, "operator is required"); - if (operator.isBlank()) { - throw new IllegalArgumentException("operator is required"); - } - } - - /** A principal established from a dedicated operations credential. */ - public static GraphQlAdminPrincipal operations(String operator) { - return new GraphQlAdminPrincipal(operator, false); - } - - /** A principal established from a credential the request path also holds. */ - public static GraphQlAdminPrincipal fromApplicationCredential(String operator) { - return new GraphQlAdminPrincipal(operator, true); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/admin/GraphQlPersistedOperationAdminAuthorization.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/admin/GraphQlPersistedOperationAdminAuthorization.java deleted file mode 100644 index 8fbb6478..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/admin/GraphQlPersistedOperationAdminAuthorization.java +++ /dev/null @@ -1,46 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.admin; - -import java.util.Set; - -/** - * Who may change the approved-operation registry. - * - *

A separate authority from the request path. Application credentials are held by every running - * instance and reachable from any resolver; if one of them could register or block an operation, a - * compromised request path could rewrite what the whole platform is willing to execute. - */ -public final class GraphQlPersistedOperationAdminAuthorization { - - private final Set administrators; - - /** - * Creates the authorization. - * - * @param administrators operator references permitted to administer the registry - */ - public GraphQlPersistedOperationAdminAuthorization(Set administrators) { - this.administrators = Set.copyOf(administrators); - if (this.administrators.isEmpty()) { - throw new IllegalArgumentException("at least one registry administrator is required"); - } - } - - /** - * Requires a verified administrator holding an operations credential. - * - *

Both halves are checked here now. The credential-kind refusal used to be a separate public - * method that no caller invoked, so an application credential naming an allowlisted operator - * passed — which is the compromise this class exists to prevent, arriving through the door it - * documented. - * - * @throws GraphQlPersistedOperationAdminDeniedException when the principal is absent, not an - * administrator, or authenticated with a credential the request path also holds - */ - public void requireAdministrator(GraphQlAdminPrincipal principal) { - if (principal == null - || principal.applicationCredential() - || !administrators.contains(principal.operator())) { - throw new GraphQlPersistedOperationAdminDeniedException(); - } - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/admin/GraphQlPersistedOperationAdminDeniedException.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/admin/GraphQlPersistedOperationAdminDeniedException.java deleted file mode 100644 index 54d5a4bf..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/admin/GraphQlPersistedOperationAdminDeniedException.java +++ /dev/null @@ -1,17 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.admin; - -/** - * Raised when a caller may not administer the approved-operation registry. - * - *

Carries no operator identity, so a denial cannot be used to enumerate who the administrators - * are. - */ -public class GraphQlPersistedOperationAdminDeniedException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - /** Creates the failure. */ - public GraphQlPersistedOperationAdminDeniedException() { - super("persisted operation administration is denied"); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/admin/GraphQlPersistedOperationAdminPort.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/admin/GraphQlPersistedOperationAdminPort.java deleted file mode 100644 index e3246752..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/admin/GraphQlPersistedOperationAdminPort.java +++ /dev/null @@ -1,47 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.admin; - -import dev.caskeleton.adapter.inbound.graphql.advanced.persisted.GraphQlPersistedOperation; -import dev.caskeleton.adapter.inbound.graphql.advanced.persisted.GraphQlPersistedOperationId; -import dev.caskeleton.adapter.inbound.graphql.advanced.persisted.GraphQlPersistedOperationTransition; - -/** - * Applies a registry change and records it, as one durable unit. - * - *

The two used to be separate steps: the registry was mutated, then an entry was appended to an - * {@code ArrayList} field. A crash between them left a change nobody could account for, a failure - * in the append left a change with no record, and the list itself was not thread-safe, so two - * concurrent administrators could lose an entry outright. An audit trail with any of those - * properties is worse than none, because it is trusted. - * - *

A port rather than an implementation: transactional guarantees over both the registry and the - * trail need a store, and which store provides them is a deployment decision. - */ -public interface GraphQlPersistedOperationAdminPort { - - /** - * Registers an operation and records it atomically. - * - * @return the stored operation - * @throws dev.caskeleton.adapter.inbound.graphql.advanced.persisted - * .GraphQlPersistedOperationConflictException when the id already holds a different document - */ - GraphQlPersistedOperation register( - GraphQlPersistedOperation operation, GraphQlPersistedOperationAudit audit); - - /** - * Applies a transition and records it atomically. - * - * @return the operation as it now stands - * @throws dev.caskeleton.adapter.inbound.graphql.advanced.persisted - * .GraphQlPersistedOperationNotFoundException when the operation does not exist - * @throws dev.caskeleton.adapter.inbound.graphql.advanced.persisted - * .GraphQlPersistedOperationConflictException when the transition is not permitted - */ - GraphQlPersistedOperation apply( - GraphQlPersistedOperationId operationId, - GraphQlPersistedOperationTransition transition, - GraphQlPersistedOperationAudit audit); - - /** The recorded trail, oldest first. */ - java.util.List auditTrail(); -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/admin/GraphQlPersistedOperationAdminService.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/admin/GraphQlPersistedOperationAdminService.java deleted file mode 100644 index fb080c60..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/admin/GraphQlPersistedOperationAdminService.java +++ /dev/null @@ -1,161 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.admin; - -import dev.caskeleton.adapter.inbound.graphql.advanced.persisted.GraphQlPersistedOperation; -import dev.caskeleton.adapter.inbound.graphql.advanced.persisted.GraphQlPersistedOperationId; -import dev.caskeleton.adapter.inbound.graphql.advanced.persisted.GraphQlPersistedOperationTransition; -import java.time.Clock; -import java.util.List; -import java.util.Objects; - -/** - * The G4 operations plane for approved operations (Advanced plan Task 4). - * - *

Every change is authorized against a verified principal and recorded in the same durable unit - * as the change itself, because a registry change silently alters what the whole platform will - * execute. Blocking takes effect immediately; retiring has to pass the usage gate first. - * - *

Every command returns the stored operation. A command that cannot be applied throws, so the - * audit trail records changes that happened rather than changes that were attempted — the previous - * service wrote {@code ABSENT -> BLOCKED} for operations that did not exist, which is precisely the - * entry an operator would trust during an incident. - */ -public final class GraphQlPersistedOperationAdminService { - - private final GraphQlPersistedOperationAdminPort adminPort; - private final GraphQlPersistedOperationAdminAuthorization authorization; - private final GraphQlPersistedOperationRemovalGate removalGate; - private final Clock clock; - - /** - * Creates the service. - * - * @param adminPort applies registry changes and their audit entries atomically - * @param authorization who may administer the registry - * @param removalGate the usage gate protecting retirement - * @param clock clock used for audit timestamps and the quiet period - */ - public GraphQlPersistedOperationAdminService( - GraphQlPersistedOperationAdminPort adminPort, - GraphQlPersistedOperationAdminAuthorization authorization, - GraphQlPersistedOperationRemovalGate removalGate, - Clock clock) { - this.adminPort = Objects.requireNonNull(adminPort); - this.authorization = Objects.requireNonNull(authorization); - this.removalGate = Objects.requireNonNull(removalGate); - this.clock = Objects.requireNonNull(clock); - } - - /** Registers a new approved operation. */ - public GraphQlPersistedOperation register( - GraphQlPersistedOperation operation, - GraphQlAdminPrincipal principal, - String reason, - String traceId) { - authorization.requireAdministrator(principal); - return adminPort.register( - operation, - audit(operation.id(), principal, reason, "ABSENT", operation.status().name(), traceId)); - } - - /** - * Blocks an operation immediately. - * - *

Takes effect on the next request; a cached parse does not keep it executable. - */ - public GraphQlPersistedOperation block( - GraphQlPersistedOperationBlockCommand command, GraphQlAdminPrincipal principal) { - return transition( - command.operationId(), - GraphQlPersistedOperationTransition.BLOCK, - principal, - command.reason(), - command.traceId()); - } - - /** - * Reverses a block. - * - *

Its own command, so leaving the emergency state is an explicit decision with its own audit - * entry. It used to be reachable by marking a blocked operation deprecated, which reads like a - * documentation change and made it executable again. - */ - public GraphQlPersistedOperation unblock( - GraphQlPersistedOperationId operationId, - GraphQlAdminPrincipal principal, - String reason, - String traceId) { - return transition( - operationId, GraphQlPersistedOperationTransition.UNBLOCK, principal, reason, traceId); - } - - /** Marks an operation deprecated, which keeps it executable while clients migrate. */ - public GraphQlPersistedOperation deprecate( - GraphQlPersistedOperationId operationId, - GraphQlAdminPrincipal principal, - String reason, - String traceId) { - return transition( - operationId, GraphQlPersistedOperationTransition.DEPRECATE, principal, reason, traceId); - } - - /** - * Retires an operation once usage evidence permits it. - * - *

Named for what it does. It was called {@code remove}, and it blocked rather than deleted — - * an operator reading the method name would have believed the document was gone. - * - * @throws GraphQlPersistedOperationRemovalRejectedException when it was used within the quiet - * period - */ - public GraphQlPersistedOperation retireAndBlock( - GraphQlPersistedOperationId operationId, - GraphQlPersistedOperationUsage usage, - GraphQlAdminPrincipal principal, - String reason, - String traceId) { - authorization.requireAdministrator(principal); - removalGate.verify(usage, clock.instant()); - return transition( - operationId, GraphQlPersistedOperationTransition.RETIRE, principal, reason, traceId); - } - - /** The audit trail, in order. */ - public List auditTrail() { - return adminPort.auditTrail(); - } - - private GraphQlPersistedOperation transition( - GraphQlPersistedOperationId operationId, - GraphQlPersistedOperationTransition transition, - GraphQlAdminPrincipal principal, - String reason, - String traceId) { - - authorization.requireAdministrator(principal); - // The audit entry names the state the operation is actually leaving. The port applies both - // together, so a rejected transition leaves no entry at all. - GraphQlPersistedOperation updated = - adminPort.apply( - operationId, - transition, - audit( - operationId, - principal, - reason, - transition.name(), - transition.target().name(), - traceId)); - return updated; - } - - private GraphQlPersistedOperationAudit audit( - GraphQlPersistedOperationId operationId, - GraphQlAdminPrincipal principal, - String reason, - String before, - String after, - String traceId) { - return new GraphQlPersistedOperationAudit( - operationId.value(), principal.operator(), reason, before, after, clock.instant(), traceId); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/admin/GraphQlPersistedOperationAudit.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/admin/GraphQlPersistedOperationAudit.java deleted file mode 100644 index d2be758b..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/admin/GraphQlPersistedOperationAudit.java +++ /dev/null @@ -1,43 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.admin; - -import java.time.Instant; - -/** - * One audited change to the approved-operation registry. - * - *

Records operator, reason, before/after state, time and trace — the questions asked after an - * incident. It never records variables or credentials, so the audit trail itself stays safe to - * retain. - * - * @param operationId the operation that changed - * @param operator who made the change - * @param reason why - * @param before previous state - * @param after new state - * @param at when - * @param traceId correlation identity - */ -public record GraphQlPersistedOperationAudit( - String operationId, - String operator, - String reason, - String before, - String after, - Instant at, - String traceId) { - - public GraphQlPersistedOperationAudit { - if (operationId == null || operationId.isBlank()) { - throw new IllegalArgumentException("audited operation id is required"); - } - if (operator == null || operator.isBlank()) { - throw new IllegalArgumentException("audited operator is required"); - } - if (reason == null || reason.isBlank()) { - throw new IllegalArgumentException("audited reason is required"); - } - if (at == null) { - throw new IllegalArgumentException("audit instant is required"); - } - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/admin/GraphQlPersistedOperationBlockCommand.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/admin/GraphQlPersistedOperationBlockCommand.java deleted file mode 100644 index 0929217a..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/admin/GraphQlPersistedOperationBlockCommand.java +++ /dev/null @@ -1,31 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.admin; - -import dev.caskeleton.adapter.inbound.graphql.advanced.persisted.GraphQlPersistedOperationId; - -/** - * An instruction to block one approved operation immediately. - * - *

The incident-response tool: it stops a single expensive or dangerous operation without a - * redeploy and without taking the endpoint down for everyone. Operator and reason are required - * because a block is a production change that someone will have to explain and eventually reverse. - * - * @param operationId the operation to block - * @param operator who is blocking it - * @param reason why - * @param traceId incident correlation identity - */ -public record GraphQlPersistedOperationBlockCommand( - GraphQlPersistedOperationId operationId, String operator, String reason, String traceId) { - - public GraphQlPersistedOperationBlockCommand { - if (operationId == null) { - throw new IllegalArgumentException("operation id is required"); - } - if (operator == null || operator.isBlank()) { - throw new IllegalArgumentException("blocking operator is required"); - } - if (reason == null || reason.isBlank()) { - throw new IllegalArgumentException("blocking reason is required"); - } - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/admin/GraphQlPersistedOperationRemovalGate.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/admin/GraphQlPersistedOperationRemovalGate.java deleted file mode 100644 index 4cda0934..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/admin/GraphQlPersistedOperationRemovalGate.java +++ /dev/null @@ -1,45 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.admin; - -import java.time.Duration; -import java.time.Instant; - -/** - * Refuses to remove an approved operation that is still in use (Advanced plan Task 4). - * - *

The quiet period exists because "no traffic right now" is not the same as "no client uses - * this": a monthly report or a mobile build in slow rollout can be silent for weeks and then send - * the operation again. - */ -public final class GraphQlPersistedOperationRemovalGate { - - private final Duration quietPeriod; - - /** - * Creates the gate. - * - * @param quietPeriod how long an operation must be unused before it may be removed - */ - public GraphQlPersistedOperationRemovalGate(Duration quietPeriod) { - if (quietPeriod == null || quietPeriod.isNegative()) { - throw new IllegalArgumentException("quiet period must not be negative"); - } - this.quietPeriod = quietPeriod; - } - - /** The configured quiet period. */ - public Duration quietPeriod() { - return quietPeriod; - } - - /** - * Verifies that removal is safe. - * - * @throws GraphQlPersistedOperationRemovalRejectedException when the operation was used recently - */ - public void verify(GraphQlPersistedOperationUsage usage, Instant now) { - if (usage.executions() > 0 && usage.lastUsedAt().plus(quietPeriod).isAfter(now)) { - throw new GraphQlPersistedOperationRemovalRejectedException( - "persisted operation used within quiet period"); - } - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/admin/GraphQlPersistedOperationRemovalRejectedException.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/admin/GraphQlPersistedOperationRemovalRejectedException.java deleted file mode 100644 index 4551f823..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/admin/GraphQlPersistedOperationRemovalRejectedException.java +++ /dev/null @@ -1,21 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.admin; - -/** - * Raised when an approved operation may not be removed yet. - * - *

Removing an operation a deployed client still sends breaks that client with no warning and no - * migration path, so the gate refuses until the usage evidence says otherwise. - */ -public class GraphQlPersistedOperationRemovalRejectedException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - /** - * Creates the failure. - * - * @param reason why removal is blocked - */ - public GraphQlPersistedOperationRemovalRejectedException(String reason) { - super(reason); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/admin/GraphQlPersistedOperationUsage.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/admin/GraphQlPersistedOperationUsage.java deleted file mode 100644 index d3d48d64..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/admin/GraphQlPersistedOperationUsage.java +++ /dev/null @@ -1,29 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.admin; - -import java.time.Instant; - -/** - * Observed usage of one approved operation. - * - *

Counts and a last-used instant, never the callers: usage feeds a removal decision, and the - * identity of who ran an operation is not needed to decide whether it is still in use. - * - * @param lastUsedAt when it was last executed, or {@code null} when never - * @param executions executions observed in the window - */ -public record GraphQlPersistedOperationUsage(Instant lastUsedAt, long executions) { - - public GraphQlPersistedOperationUsage { - if (executions < 0) { - throw new IllegalArgumentException("executions cannot be negative"); - } - if (executions > 0 && lastUsedAt == null) { - throw new IllegalArgumentException("observed executions require a last-used instant"); - } - } - - /** Measured, and never used. */ - public static GraphQlPersistedOperationUsage unused() { - return new GraphQlPersistedOperationUsage(null, 0); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/bootstrap/GraphQlAdvancedCapability.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/bootstrap/GraphQlAdvancedCapability.java deleted file mode 100644 index ac1a7f99..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/bootstrap/GraphQlAdvancedCapability.java +++ /dev/null @@ -1,59 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap; - -import java.util.Locale; - -/** - * The Advanced and Experimental capabilities, each behind its own flag (Advanced plan Task 1). - * - *

Enumerated so a capability cannot activate merely by being on the classpath. Every one of - * these changes the platform's operational shape — a long-lived connection, an approved-operation - * registry, a second schema topology — and each deserves a deliberate decision. - */ -public enum GraphQlAdvancedCapability { - - /** Approved operation registry and execution lookup. */ - PERSISTED_OPERATION(GraphQlAdvancedCapabilityGrade.ADVANCED_STABLE), - - /** {@code graphql-transport-ws} subscriptions. */ - WEBSOCKET_SUBSCRIPTION(GraphQlAdvancedCapabilityGrade.ADVANCED_STABLE), - - /** Server-sent event subscriptions, one connection per subscription. */ - SSE_SUBSCRIPTION(GraphQlAdvancedCapabilityGrade.ADVANCED), - - /** Federation subgraph schema and entity resolution. */ - FEDERATION_SUBGRAPH(GraphQlAdvancedCapabilityGrade.ADVANCED), - - /** Client and transport DTO code generation. */ - CODE_GENERATION(GraphQlAdvancedCapabilityGrade.ADVANCED), - - /** GraphQL Java 25 chained DataLoader dispatch. */ - DATALOADER_CHAINING(GraphQlAdvancedCapabilityGrade.ADVANCED), - - /** Messaging-backed subscription replay. */ - SUBSCRIPTION_REPLAY(GraphQlAdvancedCapabilityGrade.ADVANCED), - - /** RSocket transport. */ - RSOCKET(GraphQlAdvancedCapabilityGrade.EXPERIMENTAL), - - /** GraphQL over HTTP GET, per the still-moving draft. */ - HTTP_GET(GraphQlAdvancedCapabilityGrade.EXPERIMENTAL), - - /** Incremental delivery. */ - INCREMENTAL_DELIVERY(GraphQlAdvancedCapabilityGrade.EXPERIMENTAL); - - private final GraphQlAdvancedCapabilityGrade grade; - - GraphQlAdvancedCapability(GraphQlAdvancedCapabilityGrade grade) { - this.grade = grade; - } - - /** The capability's support grade. */ - public GraphQlAdvancedCapabilityGrade grade() { - return grade; - } - - /** The property that enables it. */ - public String featureFlag() { - return "backend.graphql.advanced." + name().toLowerCase(Locale.ROOT).replace('_', '-'); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/bootstrap/GraphQlAdvancedCapabilityDisabledException.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/bootstrap/GraphQlAdvancedCapabilityDisabledException.java deleted file mode 100644 index 939917f0..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/bootstrap/GraphQlAdvancedCapabilityDisabledException.java +++ /dev/null @@ -1,21 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap; - -/** - * Raised when a disabled or unapproved capability is used. - * - *

Fails loudly rather than degrading: a subscription endpoint that silently does nothing because - * its flag is off is far harder to diagnose than one that refuses to start. - */ -public class GraphQlAdvancedCapabilityDisabledException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - /** - * Creates the failure. - * - * @param capabilityName the capability that is not enabled - */ - public GraphQlAdvancedCapabilityDisabledException(String capabilityName) { - super("GraphQL advanced capability is not enabled: " + capabilityName); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/bootstrap/GraphQlAdvancedCapabilityGrade.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/bootstrap/GraphQlAdvancedCapabilityGrade.java deleted file mode 100644 index 962d26e8..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/bootstrap/GraphQlAdvancedCapabilityGrade.java +++ /dev/null @@ -1,31 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap; - -/** - * How far a capability has been proven. - * - *

The grade decides what enabling it takes. An Advanced capability needs its feature flag; an - * Experimental one additionally needs an approval profile in production, because the evidence for - * it has not been collected yet and a config change alone should not put it in front of users. - */ -public enum GraphQlAdvancedCapabilityGrade { - - /** Proven in production use; enabled by its feature flag. */ - ADVANCED_STABLE(false), - - /** Supported; enabled by its feature flag. */ - ADVANCED(false), - - /** Not yet proven; production activation also requires an approval profile. */ - EXPERIMENTAL(true); - - private final boolean productionApprovalRequired; - - GraphQlAdvancedCapabilityGrade(boolean productionApprovalRequired) { - this.productionApprovalRequired = productionApprovalRequired; - } - - /** Whether production activation needs approval beyond the feature flag. */ - public boolean productionApprovalRequired() { - return productionApprovalRequired; - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/bootstrap/GraphQlAdvancedDependencyRules.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/bootstrap/GraphQlAdvancedDependencyRules.java deleted file mode 100644 index 16d3371f..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/bootstrap/GraphQlAdvancedDependencyRules.java +++ /dev/null @@ -1,52 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap; - -import dev.caskeleton.adapter.inbound.graphql.moduleboundary.GraphQlAdvancedModule; -import dev.caskeleton.adapter.inbound.graphql.moduleboundary.GraphQlModuleBoundary; -import dev.caskeleton.adapter.inbound.graphql.moduleboundary.GraphQlStableModule; -import java.util.ArrayList; -import java.util.List; -import java.util.Set; - -/** - * The Stable/Advanced dependency direction (Advanced plan Task 1). - * - *

Advanced consumes Stable, never the other way round. If a Stable module depended on an - * Advanced one, every Stable deployment would carry the Advanced capability's code and - * configuration surface — and the feature flag would be the only thing standing between an ordinary - * service and a subscription runtime. - */ -public final class GraphQlAdvancedDependencyRules { - - private GraphQlAdvancedDependencyRules() {} - - /** - * Verifies that no Stable module declares an Advanced dependency. - * - * @throws IllegalStateException naming the offending edges - */ - public static void verifyStableDoesNotDependOnAdvanced() { - Set advanced = GraphQlAdvancedModule.moduleIds(); - List violations = new ArrayList<>(); - GraphQlStableModule.dependencyEdges() - .forEach( - (module, dependencies) -> - dependencies.stream() - .filter(advanced::contains) - .forEach(dependency -> violations.add(module + " -> " + dependency))); - if (!violations.isEmpty()) { - throw new IllegalStateException( - "stable graphql modules must not depend on advanced capabilities: " + violations); - } - } - - /** Whether a package belongs to an Advanced capability. */ - public static boolean advancedPackage(String packageName) { - return packageName != null - && packageName.startsWith(GraphQlModuleBoundary.PACKAGE_ROOT + ".advanced"); - } - - /** Every capability that must be flagged before it can run. */ - public static Set flaggedCapabilities() { - return Set.of(GraphQlAdvancedCapability.values()); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/bootstrap/GraphQlAdvancedFeatureFlags.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/bootstrap/GraphQlAdvancedFeatureFlags.java deleted file mode 100644 index daeb0509..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/bootstrap/GraphQlAdvancedFeatureFlags.java +++ /dev/null @@ -1,40 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap; - -import java.util.Set; - -/** - * Which Advanced capabilities are enabled, and whether experimental approval was granted. - * - *

Nothing is on by default. An Advanced capability that arrived because a dependency was added - * is exactly what the Stable/Advanced split exists to prevent. - * - * @param enabled capabilities whose feature flag is set - * @param experimentalApprovedInProduction whether Experimental capabilities may run in production - */ -public record GraphQlAdvancedFeatureFlags( - Set enabled, boolean experimentalApprovedInProduction) { - - public GraphQlAdvancedFeatureFlags { - enabled = Set.copyOf(enabled); - } - - /** Nothing enabled. */ - public static GraphQlAdvancedFeatureFlags disabled() { - return new GraphQlAdvancedFeatureFlags(Set.of(), false); - } - - /** The given capabilities enabled, without experimental production approval. */ - public static GraphQlAdvancedFeatureFlags enabling(GraphQlAdvancedCapability... capabilities) { - return new GraphQlAdvancedFeatureFlags(Set.of(capabilities), false); - } - - /** Whether a capability's flag is set. */ - public boolean isEnabled(GraphQlAdvancedCapability capability) { - return enabled.contains(capability); - } - - /** Returns a copy with experimental capabilities approved for production. */ - public GraphQlAdvancedFeatureFlags withExperimentalApproval() { - return new GraphQlAdvancedFeatureFlags(enabled, true); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/bootstrap/GraphQlAdvancedModuleGuard.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/bootstrap/GraphQlAdvancedModuleGuard.java deleted file mode 100644 index b80a4228..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/bootstrap/GraphQlAdvancedModuleGuard.java +++ /dev/null @@ -1,63 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap; - -import java.util.Objects; - -/** - * The single gate every Advanced capability passes through. - * - *

One place to check means a capability cannot be half-enabled: the flag governs whether it - * starts at all, and an Experimental capability additionally needs production approval, so neither - * can be reached by a code path that forgot to ask. - */ -public final class GraphQlAdvancedModuleGuard { - - private final GraphQlAdvancedFeatureFlags flags; - private final boolean production; - - /** - * Creates a non-production guard. - * - * @param flags the enabled capabilities - */ - public GraphQlAdvancedModuleGuard(GraphQlAdvancedFeatureFlags flags) { - this(flags, false); - } - - /** - * Creates the guard. - * - * @param flags the enabled capabilities - * @param production whether production rules apply - */ - public GraphQlAdvancedModuleGuard(GraphQlAdvancedFeatureFlags flags, boolean production) { - this.flags = Objects.requireNonNull(flags); - this.production = production; - } - - /** - * Requires a capability to be enabled and, in production, approved. - * - * @throws GraphQlAdvancedCapabilityDisabledException when it is not - */ - public void requireEnabled(GraphQlAdvancedCapability capability) { - if (!flags.isEnabled(capability)) { - throw new GraphQlAdvancedCapabilityDisabledException(capability.name()); - } - if (production - && capability.grade().productionApprovalRequired() - && !flags.experimentalApprovedInProduction()) { - throw new GraphQlAdvancedCapabilityDisabledException( - capability.name() + " is experimental and requires an approval profile in production"); - } - } - - /** Whether a capability may run here. */ - public boolean enabled(GraphQlAdvancedCapability capability) { - try { - requireEnabled(capability); - return true; - } catch (GraphQlAdvancedCapabilityDisabledException ex) { - return false; - } - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/chaining/GraphQlChainedDataLoaderPolicy.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/chaining/GraphQlChainedDataLoaderPolicy.java deleted file mode 100644 index 50f0036b..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/chaining/GraphQlChainedDataLoaderPolicy.java +++ /dev/null @@ -1,25 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.chaining; - -/** - * Whether chained DataLoader dispatch is enabled, and how deep it may chain. - * - *

Off by default. Chained dispatch changes when loaders fire, which changes query counts, batch - * sizes and result ordering — all things existing N+1 regression tests assert on. Enabling it is a - * deliberate change with its own regression evidence, not a free improvement. - * - * @param enabled whether chained dispatch is active - * @param maximumDepth deepest dependency chain permitted - */ -public record GraphQlChainedDataLoaderPolicy(boolean enabled, int maximumDepth) { - - public GraphQlChainedDataLoaderPolicy { - if (maximumDepth < 1) { - throw new IllegalArgumentException("chained dispatch depth must be positive"); - } - } - - /** The Stable default: chained dispatch disabled. */ - public static GraphQlChainedDataLoaderPolicy disabled() { - return new GraphQlChainedDataLoaderPolicy(false, 1); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/chaining/GraphQlChainedDispatchConfigurer.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/chaining/GraphQlChainedDispatchConfigurer.java deleted file mode 100644 index 8cf1521e..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/chaining/GraphQlChainedDispatchConfigurer.java +++ /dev/null @@ -1,72 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.chaining; - -import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedCapability; -import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedModuleGuard; -import java.util.Objects; - -/** - * Enables chained dispatch, once the flag, the graph and the depth all allow it (Advanced plan Task - * 11). - * - *

Every Stable DataLoader rule still applies: request scope, actor and tenant isolation, and the - * loader's maximum batch size. Chaining changes dispatch timing, nothing else. - */ -public final class GraphQlChainedDispatchConfigurer { - - private final GraphQlAdvancedModuleGuard guard; - private final GraphQlDataLoaderCycleDetector cycleDetector; - - /** - * Creates the configurer. - * - * @param guard the Advanced capability guard - * @param cycleDetector the dependency cycle check - */ - public GraphQlChainedDispatchConfigurer( - GraphQlAdvancedModuleGuard guard, GraphQlDataLoaderCycleDetector cycleDetector) { - this.guard = Objects.requireNonNull(guard); - this.cycleDetector = Objects.requireNonNull(cycleDetector); - } - - /** - * Verifies chained dispatch may be enabled for a graph. - * - * @throws GraphQlDataLoaderDependencyCycleException when the graph has a cycle - * @throws IllegalArgumentException when the graph is deeper than the policy allows - */ - public void configure( - GraphQlChainedDataLoaderPolicy policy, GraphQlDataLoaderDependencyGraph graph) { - if (!policy.enabled()) { - return; - } - guard.requireEnabled(GraphQlAdvancedCapability.DATALOADER_CHAINING); - cycleDetector.verify(graph); - int depth = depthOf(graph); - if (depth > policy.maximumDepth()) { - throw new IllegalArgumentException( - "loader dependency depth " - + depth - + " exceeds the configured maximum of " - + policy.maximumDepth()); - } - } - - /** The longest dependency chain in the graph. */ - public int depthOf(GraphQlDataLoaderDependencyGraph graph) { - cycleDetector.verify(graph); - int deepest = 0; - for (String loader : graph.loaders()) { - deepest = Math.max(deepest, depthFrom(graph, loader)); - } - return deepest; - } - - private int depthFrom(GraphQlDataLoaderDependencyGraph graph, String loader) { - var dependencies = graph.edges().getOrDefault(loader, java.util.Set.of()); - int deepest = 0; - for (String dependency : dependencies) { - deepest = Math.max(deepest, 1 + depthFrom(graph, dependency)); - } - return deepest; - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/chaining/GraphQlChainedLoaderMetrics.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/chaining/GraphQlChainedLoaderMetrics.java deleted file mode 100644 index 446bc473..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/chaining/GraphQlChainedLoaderMetrics.java +++ /dev/null @@ -1,52 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.chaining; - -import java.util.concurrent.atomic.AtomicLong; - -/** - * Dispatch counters for chained loading. - * - *

Query count and batch size are the numbers that prove chaining helped or hurt. Without them, - * enabling chained dispatch is a change whose effect nobody can measure — which is exactly why it - * defaults to off. - */ -public final class GraphQlChainedLoaderMetrics { - - private final AtomicLong dispatches = new AtomicLong(); - private final AtomicLong keysLoaded = new AtomicLong(); - private final AtomicLong chainedDispatches = new AtomicLong(); - - /** - * Records one dispatch round. - * - * @param keys keys dispatched - * @param chained whether it was triggered by another loader's completion - */ - public void recordDispatch(int keys, boolean chained) { - dispatches.incrementAndGet(); - keysLoaded.addAndGet(keys); - if (chained) { - chainedDispatches.incrementAndGet(); - } - } - - /** Dispatch rounds. */ - public long dispatches() { - return dispatches.get(); - } - - /** Keys loaded in total. */ - public long keysLoaded() { - return keysLoaded.get(); - } - - /** Dispatch rounds triggered by chaining. */ - public long chainedDispatches() { - return chainedDispatches.get(); - } - - /** Average batch size, the number a chaining regression shows up in first. */ - public double averageBatchSize() { - long rounds = dispatches.get(); - return rounds == 0 ? 0 : (double) keysLoaded.get() / rounds; - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/chaining/GraphQlDataLoaderCycleDetector.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/chaining/GraphQlDataLoaderCycleDetector.java deleted file mode 100644 index a6709888..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/chaining/GraphQlDataLoaderCycleDetector.java +++ /dev/null @@ -1,51 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.chaining; - -import java.util.ArrayList; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Set; - -/** - * Finds dependency cycles before chained dispatch is enabled. - * - *

A depth-first walk that reports the cycle it found, not just that one exists — with a dozen - * loaders, "there is a cycle somewhere" is not an actionable diagnostic. - */ -public final class GraphQlDataLoaderCycleDetector { - - /** - * Verifies the graph is acyclic. - * - * @throws GraphQlDataLoaderDependencyCycleException naming the cycle - */ - public void verify(GraphQlDataLoaderDependencyGraph graph) { - Set settled = new LinkedHashSet<>(); - for (String loader : graph.loaders()) { - if (!settled.contains(loader)) { - walk(graph, loader, new LinkedHashSet<>(), settled); - } - } - } - - private void walk( - GraphQlDataLoaderDependencyGraph graph, - String loader, - Set path, - Set settled) { - - if (path.contains(loader)) { - List cycle = new ArrayList<>(path); - cycle.add(loader); - throw new GraphQlDataLoaderDependencyCycleException(cycle); - } - if (settled.contains(loader)) { - return; - } - path.add(loader); - for (String dependency : graph.edges().getOrDefault(loader, Set.of())) { - walk(graph, dependency, path, settled); - } - path.remove(loader); - settled.add(loader); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/chaining/GraphQlDataLoaderDependencyCycleException.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/chaining/GraphQlDataLoaderDependencyCycleException.java deleted file mode 100644 index 8217234c..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/chaining/GraphQlDataLoaderDependencyCycleException.java +++ /dev/null @@ -1,23 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.chaining; - -import java.util.List; - -/** - * Raised when loaders depend on each other in a cycle. - * - *

A cycle has no dispatch order that satisfies it, so chained dispatch would deadlock or never - * dispatch — failing at startup is far cheaper than discovering it under load. - */ -public class GraphQlDataLoaderDependencyCycleException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - /** - * Creates the failure. - * - * @param cycle the loaders on the cycle, in order - */ - public GraphQlDataLoaderDependencyCycleException(List cycle) { - super("data loader dependency cycle: " + cycle); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/chaining/GraphQlDataLoaderDependencyGraph.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/chaining/GraphQlDataLoaderDependencyGraph.java deleted file mode 100644 index e2300334..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/chaining/GraphQlDataLoaderDependencyGraph.java +++ /dev/null @@ -1,44 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.chaining; - -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.Map; -import java.util.Set; - -/** - * Declared dependencies between loaders. - * - *

Declared rather than inferred: chained dispatch changes when each loader fires, and the - * platform cannot discover from bytecode that one loader's keys come from another's results. - */ -public final class GraphQlDataLoaderDependencyGraph { - - private final Map> edges = new LinkedHashMap<>(); - - /** - * Declares that one loader depends on another. - * - * @param loader the dependent loader - * @param dependency the loader it needs first - */ - public GraphQlDataLoaderDependencyGraph dependsOn(String loader, String dependency) { - if (loader == null || dependency == null) { - throw new IllegalArgumentException("loader and dependency names are required"); - } - edges.computeIfAbsent(loader, ignored -> new LinkedHashSet<>()).add(dependency); - return this; - } - - /** The declared edges. */ - public Map> edges() { - return Collections.unmodifiableMap(edges); - } - - /** Loaders that appear in the graph. */ - public Set loaders() { - Set loaders = new LinkedHashSet<>(edges.keySet()); - edges.values().forEach(loaders::addAll); - return Collections.unmodifiableSet(loaders); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/codegen/GraphQlClientOperationGenerator.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/codegen/GraphQlClientOperationGenerator.java deleted file mode 100644 index 4e7a9a2d..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/codegen/GraphQlClientOperationGenerator.java +++ /dev/null @@ -1,63 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.codegen; - -import java.util.Objects; - -/** - * Plans client code generation and validates the operations it would generate from. - * - *

Named a plan because that is what it produces: which kinds may be generated and into which - * package. No source writer and no Gradle task exist behind it, and calling it a generator invited - * the reasonable assumption that running it emitted files. - * - *

Validation is the part that does real work, and it is most of the value: an operation that no - * longer matches the schema becomes a build failure in the client's repository instead of a runtime - * error in production. - */ -public final class GraphQlClientOperationGenerator { - - private final GraphQlCodegenProfile profile; - - /** - * Creates the generator. - * - * @param profile what to generate and where - */ - public GraphQlClientOperationGenerator(GraphQlCodegenProfile profile) { - this.profile = Objects.requireNonNull(profile); - } - - /** - * Validates that an operation document still matches the schema. - * - * @param sdl the schema - * @param operationDocument the operation to validate - * @throws GraphQlCodegenBoundaryException when the document does not parse or does not match - */ - public void validateOperation(String sdl, String operationDocument) { - validateOperation(sdl, operationDocument, null); - } - - /** - * Validates one named operation from a document. - * - * @param sdl the schema - * @param operationDocument the operation document - * @param operationName which operation, when the document declares several - * @throws GraphQlCodegenBoundaryException when the document does not parse, does not match the - * schema, or names no such operation - */ - public void validateOperation(String sdl, String operationDocument, String operationName) { - GraphQlOperationValidator.validate(sdl, operationDocument, operationName); - } - - /** The kinds this plan covers. */ - public java.util.Set generatedTypes() { - profile.generatedTypes().forEach(GraphQlGeneratedSourceBoundary.standard()::requireAllowed); - return profile.generatedTypes(); - } - - /** The package generated client sources are written to. */ - public String generatedPackage() { - return profile.generatedPackage(); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/codegen/GraphQlCodegenBoundaryException.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/codegen/GraphQlCodegenBoundaryException.java deleted file mode 100644 index 3e6296c5..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/codegen/GraphQlCodegenBoundaryException.java +++ /dev/null @@ -1,20 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.codegen; - -/** - * Raised when generation is attempted for a kind that must be written by hand. - * - *

Fails at build time, where a generated domain type is still cheap to delete. - */ -public class GraphQlCodegenBoundaryException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - /** - * Creates the failure. - * - * @param generatedType the kind that may not be generated - */ - public GraphQlCodegenBoundaryException(String generatedType) { - super(generatedType + " must be written by hand, not generated from the GraphQL schema"); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/codegen/GraphQlCodegenProfile.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/codegen/GraphQlCodegenProfile.java deleted file mode 100644 index e08fa7ec..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/codegen/GraphQlCodegenProfile.java +++ /dev/null @@ -1,34 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.codegen; - -import java.util.List; -import java.util.Set; - -/** - * What one generation run produces, and where. - * - *

Generated sources go to their own directory and package. Mixing them with hand-written code - * means the next run either overwrites something a person wrote or silently stops regenerating. - * - * @param generatedPackage package generated sources are written to - * @param generatedSourceDirectory directory they are written to - * @param generatedTypes kinds this run produces - * @param scalarMappings custom scalar mappings - */ -public record GraphQlCodegenProfile( - String generatedPackage, - String generatedSourceDirectory, - Set generatedTypes, - List scalarMappings) { - - public GraphQlCodegenProfile { - if (generatedPackage == null || generatedPackage.isBlank()) { - throw new IllegalArgumentException("generated package is required"); - } - if (generatedSourceDirectory == null || generatedSourceDirectory.isBlank()) { - throw new IllegalArgumentException("generated source directory is required"); - } - generatedTypes = Set.copyOf(generatedTypes); - scalarMappings = List.copyOf(scalarMappings); - generatedTypes.forEach(GraphQlGeneratedSourceBoundary.standard()::requireAllowed); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/codegen/GraphQlGeneratedCompatibilityGate.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/codegen/GraphQlGeneratedCompatibilityGate.java deleted file mode 100644 index 265c1a59..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/codegen/GraphQlGeneratedCompatibilityGate.java +++ /dev/null @@ -1,38 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.codegen; - -import dev.caskeleton.adapter.inbound.graphql.compat.GraphQlChangeKind; -import dev.caskeleton.adapter.inbound.graphql.compat.GraphQlCompatibilityReport; -import dev.caskeleton.adapter.inbound.graphql.compat.GraphQlSchemaChange; -import java.util.List; - -/** - * Reports schema changes that are wire-compatible but break generated client source. - * - *

The case worth naming: adding an enum value or a union member is additive on the wire, and it - * breaks a generated client whose {@code switch} is exhaustive. The server sees a successful - * release; the client sees a compile error, or worse, a runtime one. - */ -public final class GraphQlGeneratedCompatibilityGate { - - private GraphQlGeneratedCompatibilityGate() {} - - /** Changes that need a generated-client rebuild or review, in deterministic order. */ - public static List generatedClientImpacts(GraphQlCompatibilityReport report) { - return report.changes().stream() - .filter(GraphQlSchemaChange::reviewRequired) - .map(GraphQlSchemaChange::describe) - .toList(); - } - - /** Whether a change is additive on the wire yet risky for an exhaustive generated client. */ - public static boolean exhaustivenessRisk(GraphQlSchemaChange change) { - return change.kind() == GraphQlChangeKind.ENUM_VALUE_ADDED - || change.kind() == GraphQlChangeKind.UNION_MEMBER_ADDED - || change.kind() == GraphQlChangeKind.INTERFACE_IMPLEMENTATION_ADDED; - } - - /** Whether the report can be released without regenerating clients. */ - public static boolean generatedClientsUnaffected(GraphQlCompatibilityReport report) { - return generatedClientImpacts(report).isEmpty(); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/codegen/GraphQlGeneratedSourceBoundary.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/codegen/GraphQlGeneratedSourceBoundary.java deleted file mode 100644 index f1858982..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/codegen/GraphQlGeneratedSourceBoundary.java +++ /dev/null @@ -1,45 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.codegen; - -import java.util.Set; - -/** - * What code generation may and may not produce (design §21.2). - * - *

Client and transport types are good candidates: they mirror the schema exactly and carry no - * logic. Domain entities, use cases and repositories are not — they exist to hold behaviour the - * schema does not describe, and generating them from the schema inverts the dependency the whole - * architecture rests on. - */ -public final class GraphQlGeneratedSourceBoundary { - - /** Kinds that may be generated. */ - public static final Set ALLOWED = - Set.of("CLIENT_REQUEST", "CLIENT_RESPONSE", "TRANSPORT_INPUT", "TRANSPORT_OUTPUT"); - - /** Kinds that must be written by hand. */ - public static final Set FORBIDDEN = - Set.of("DOMAIN_ENTITY", "APPLICATION_USE_CASE", "REPOSITORY", "PERSISTENCE_MODEL"); - - private GraphQlGeneratedSourceBoundary() {} - - /** The standard boundary. */ - public static GraphQlGeneratedSourceBoundary standard() { - return new GraphQlGeneratedSourceBoundary(); - } - - /** Whether a kind may be generated. */ - public boolean isAllowed(String generatedType) { - return ALLOWED.contains(generatedType); - } - - /** - * Requires a kind to be generatable. - * - * @throws GraphQlCodegenBoundaryException when it is not - */ - public void requireAllowed(String generatedType) { - if (!isAllowed(generatedType)) { - throw new GraphQlCodegenBoundaryException(generatedType); - } - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/codegen/GraphQlOperationValidator.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/codegen/GraphQlOperationValidator.java deleted file mode 100644 index c4e0daee..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/codegen/GraphQlOperationValidator.java +++ /dev/null @@ -1,111 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.codegen; - -import graphql.language.Definition; -import graphql.language.Document; -import graphql.language.OperationDefinition; -import graphql.parser.InvalidSyntaxException; -import graphql.parser.Parser; -import graphql.schema.GraphQLSchema; -import graphql.schema.idl.RuntimeWiring; -import graphql.schema.idl.SchemaGenerator; -import graphql.schema.idl.SchemaParser; -import graphql.schema.idl.TypeDefinitionRegistry; -import graphql.schema.idl.errors.SchemaProblem; -import graphql.validation.ValidationError; -import graphql.validation.Validator; -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; - -/** - * Validates a client operation against the schema it will be compiled for. - * - *

The previous check confirmed both strings were non-blank and then compared the schema with - * itself, which is true of every schema. The operation document was never read, so a document with - * invalid syntax, an unknown field, or an argument that does not exist passed validation and became - * generated client code that fails at runtime — in the client's repository, against a schema that - * had already changed. - * - *

The schema is compiled to an executable {@link GraphQLSchema} because that is what the - * validator needs: field and argument existence, type compatibility and variable usage are - * questions about types, and a parsed SDL registry alone cannot answer them. - */ -public final class GraphQlOperationValidator { - - private GraphQlOperationValidator() {} - - /** - * Validates one operation document against a schema. - * - * @param sdl the schema, as SDL - * @param operationDocument the client operation - * @param operationName the operation to validate when the document declares several, or {@code - * null} when it declares one - * @throws GraphQlCodegenBoundaryException when either input is missing, the schema does not - * compile, the document does not parse, the document does not match the schema, or the - * operation to validate is ambiguous - */ - public static void validate(String sdl, String operationDocument, String operationName) { - if (sdl == null || sdl.isBlank() || operationDocument == null || operationDocument.isBlank()) { - throw new GraphQlCodegenBoundaryException("CLIENT_REQUEST"); - } - - GraphQLSchema schema = compile(sdl); - Document document = parse(operationDocument); - requireUnambiguousOperation(document, operationName); - - List errors = new Validator().validateDocument(schema, document, Locale.ROOT); - if (!errors.isEmpty()) { - List messages = new ArrayList<>(); - errors.forEach(error -> messages.add(error.getMessage())); - throw new GraphQlCodegenBoundaryException("CLIENT_REQUEST: " + String.join("; ", messages)); - } - } - - private static GraphQLSchema compile(String sdl) { - try { - TypeDefinitionRegistry registry = new SchemaParser().parse(sdl); - return new SchemaGenerator().makeExecutableSchema(registry, RuntimeWiring.MOCKED_WIRING); - } catch (SchemaProblem | InvalidSyntaxException invalid) { - throw new GraphQlCodegenBoundaryException("CLIENT_REQUEST: schema does not compile"); - } - } - - private static Document parse(String operationDocument) { - try { - return Parser.parse(operationDocument); - } catch (InvalidSyntaxException invalid) { - throw new GraphQlCodegenBoundaryException("CLIENT_REQUEST: operation does not parse"); - } - } - - /** - * Refuses a document whose operation cannot be identified. - * - *

Generating from a multi-operation document without being told which one means picking by - * position, and the generated client then changes meaning when someone reorders the file. - */ - private static void requireUnambiguousOperation(Document document, String operationName) { - List operations = new ArrayList<>(); - for (Definition definition : document.getDefinitions()) { - if (definition instanceof OperationDefinition operation) { - operations.add(operation); - } - } - if (operations.isEmpty()) { - throw new GraphQlCodegenBoundaryException("CLIENT_REQUEST: document declares no operation"); - } - if (operationName == null || operationName.isBlank()) { - if (operations.size() > 1) { - throw new GraphQlCodegenBoundaryException( - "CLIENT_REQUEST: document declares " + operations.size() + " operations"); - } - return; - } - boolean found = operations.stream().anyMatch(op -> operationName.equals(op.getName())); - if (!found) { - throw new GraphQlCodegenBoundaryException( - "CLIENT_REQUEST: no operation named " + operationName); - } - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/codegen/GraphQlScalarMapping.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/codegen/GraphQlScalarMapping.java deleted file mode 100644 index 519afe18..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/codegen/GraphQlScalarMapping.java +++ /dev/null @@ -1,27 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.codegen; - -/** - * How a custom scalar maps onto a generated Java type. - * - *

Declared explicitly, because a generator that does not know a scalar falls back to {@code - * String} — and a {@code BigDecimal} arriving as a {@code String} in generated client code is - * precisely the precision loss the scalar was defined to prevent. - * - * @param scalarName the GraphQL scalar - * @param javaType the generated Java type - * @param codecId the codec that converts between them - */ -public record GraphQlScalarMapping(String scalarName, String javaType, String codecId) { - - public GraphQlScalarMapping { - if (scalarName == null || scalarName.isBlank()) { - throw new IllegalArgumentException("scalar name is required"); - } - if (javaType == null || javaType.isBlank()) { - throw new IllegalArgumentException("generated Java type is required"); - } - if (codecId == null || codecId.isBlank()) { - throw new IllegalArgumentException("codec id is required"); - } - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/codegen/GraphQlTransportTypeGenerator.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/codegen/GraphQlTransportTypeGenerator.java deleted file mode 100644 index 58f8bdea..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/codegen/GraphQlTransportTypeGenerator.java +++ /dev/null @@ -1,54 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.codegen; - -import java.util.Objects; -import java.util.Set; - -/** - * Generates server-side transport DTOs. - * - *

Transport types only. A generated type that a resolver maps to and from is fine; a generated - * type the Application layer consumes directly would make every schema change a change to business - * code. - */ -public final class GraphQlTransportTypeGenerator { - - private static final Set TRANSPORT_KINDS = Set.of("TRANSPORT_INPUT", "TRANSPORT_OUTPUT"); - - private final GraphQlCodegenProfile profile; - - /** - * Creates the generator. - * - * @param profile what to generate and where - */ - public GraphQlTransportTypeGenerator(GraphQlCodegenProfile profile) { - this.profile = Objects.requireNonNull(profile); - } - - /** - * The transport kinds this profile generates. - * - * @throws GraphQlCodegenBoundaryException when the profile asks for a non-transport kind - */ - public Set transportTypes() { - profile.generatedTypes().stream() - .filter(kind -> !TRANSPORT_KINDS.contains(kind) && !kind.startsWith("CLIENT_")) - .findFirst() - .ifPresent( - kind -> { - throw new GraphQlCodegenBoundaryException(kind); - }); - return profile.generatedTypes().stream() - .filter(TRANSPORT_KINDS::contains) - .collect(java.util.stream.Collectors.toUnmodifiableSet()); - } - - /** - * Whether generated sources are separated from hand-written ones. - * - * @param handWrittenSourceDirectory where hand-written sources live - */ - public boolean separatedFrom(String handWrittenSourceDirectory) { - return !profile.generatedSourceDirectory().equals(handWrittenSourceDirectory); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/composition/GraphQlFederationCompositionGate.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/composition/GraphQlFederationCompositionGate.java deleted file mode 100644 index 6b18df6b..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/composition/GraphQlFederationCompositionGate.java +++ /dev/null @@ -1,44 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.composition; - -import java.util.ArrayList; -import java.util.List; - -/** - * Blocks a federated release without complete evidence. - * - *

The gate exists because in a federated topology a mistake is not contained: an entity key - * change or an unbudgeted cross-subgraph call degrades queries the owning team never wrote. - */ -public final class GraphQlFederationCompositionGate { - - /** - * Verifies a federated release. - * - * @throws GraphQlFederationReleaseRejectedException naming the missing evidence - */ - public void verify(GraphQlFederationReleaseEvidence evidence) { - List missing = missing(evidence); - if (!missing.isEmpty()) { - throw new GraphQlFederationReleaseRejectedException( - "federation composition evidence incomplete: " + missing); - } - } - - /** Which evidence is missing, in a deterministic order. */ - public List missing(GraphQlFederationReleaseEvidence evidence) { - List missing = new ArrayList<>(); - if (!evidence.compositionPassed()) { - missing.add("composition"); - } - if (!evidence.entityContractsPassed()) { - missing.add("entityContracts"); - } - if (!evidence.latencyPassed()) { - missing.add("latency"); - } - if (!evidence.failureContractsPassed()) { - missing.add("failureContracts"); - } - return List.copyOf(missing); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/composition/GraphQlFederationCompositionResult.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/composition/GraphQlFederationCompositionResult.java deleted file mode 100644 index 98ca41ea..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/composition/GraphQlFederationCompositionResult.java +++ /dev/null @@ -1,38 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.composition; - -import java.util.List; - -/** - * What composition CI reported. - * - *

Produced by the router project, consumed here: this repository owns a subgraph and cannot - * compose the supergraph itself, so the result is an input to the gate rather than something it - * computes. - * - * @param composed whether the supergraph composed - * @param supergraphHash hash of the composed supergraph, or {@code null} when composition failed - * @param problems composition problems, empty when it succeeded - */ -public record GraphQlFederationCompositionResult( - boolean composed, String supergraphHash, List problems) { - - public GraphQlFederationCompositionResult { - problems = problems == null ? List.of() : List.copyOf(problems); - if (composed && (supergraphHash == null || supergraphHash.isBlank())) { - throw new IllegalArgumentException("a successful composition must report a supergraph hash"); - } - if (!composed && problems.isEmpty()) { - throw new IllegalArgumentException("a failed composition must report its problems"); - } - } - - /** A successful composition. */ - public static GraphQlFederationCompositionResult composed(String supergraphHash) { - return new GraphQlFederationCompositionResult(true, supergraphHash, List.of()); - } - - /** A failed composition. */ - public static GraphQlFederationCompositionResult failed(List problems) { - return new GraphQlFederationCompositionResult(false, null, problems); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/composition/GraphQlFederationDeploymentOrder.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/composition/GraphQlFederationDeploymentOrder.java deleted file mode 100644 index d0eef52b..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/composition/GraphQlFederationDeploymentOrder.java +++ /dev/null @@ -1,42 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.composition; - -/** - * Which must deploy first, the subgraph or the router. - * - *

Order matters because the two are separate deployments. A subgraph that removes a field before - * the router stops asking for it breaks every query in flight; a router that starts asking for a - * field the subgraph does not have yet breaks just as loudly. Additive changes go subgraph-first, - * removals router-first. - */ -public enum GraphQlFederationDeploymentOrder { - - /** Subgraph first: it adds capability the router will start using. */ - SUBGRAPH_FIRST, - - /** Router first: it must stop using capability the subgraph is removing. */ - ROUTER_FIRST; - - /** - * The required order for a change. - * - * @param removesCapability whether the change removes a field, key or type - */ - public static GraphQlFederationDeploymentOrder forChange(boolean removesCapability) { - return removesCapability ? ROUTER_FIRST : SUBGRAPH_FIRST; - } - - /** - * Verifies a planned deployment order. - * - * @param removesCapability whether the change removes capability - * @param planned the planned order - * @throws GraphQlFederationReleaseRejectedException when the order would break in-flight queries - */ - public static void verify(boolean removesCapability, GraphQlFederationDeploymentOrder planned) { - GraphQlFederationDeploymentOrder required = forChange(removesCapability); - if (required != planned) { - throw new GraphQlFederationReleaseRejectedException( - "this change requires " + required + " deployment, not " + planned); - } - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/composition/GraphQlFederationLatencyBudget.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/composition/GraphQlFederationLatencyBudget.java deleted file mode 100644 index 36ebced1..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/composition/GraphQlFederationLatencyBudget.java +++ /dev/null @@ -1,40 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.composition; - -import java.time.Duration; - -/** - * The latency a federated query may spend, and how many subgraph hops it may take. - * - *

Hops matter as much as time. A query that fans out to four subgraphs pays four network round - * trips before any data is read, and a per-entity downstream call turns that into a cross-subgraph - * N+1 — invisible in any single subgraph's own metrics. - * - * @param maximumTotal end-to-end budget for a federated query - * @param maximumSubgraphHops subgraph calls one query may make - * @param maximumPerEntityCalls per-entity downstream calls permitted - */ -public record GraphQlFederationLatencyBudget( - Duration maximumTotal, int maximumSubgraphHops, int maximumPerEntityCalls) { - - public GraphQlFederationLatencyBudget { - if (maximumTotal == null || maximumTotal.isZero() || maximumTotal.isNegative()) { - throw new IllegalArgumentException("federation latency budget must be positive"); - } - if (maximumSubgraphHops < 1 || maximumPerEntityCalls < 0) { - throw new IllegalArgumentException("invalid federation call budget"); - } - } - - /** - * Whether measured behaviour is within budget. - * - * @param observedTotal measured end-to-end latency - * @param observedHops measured subgraph hops - * @param observedPerEntityCalls measured per-entity downstream calls - */ - public boolean within(Duration observedTotal, int observedHops, int observedPerEntityCalls) { - return observedTotal.compareTo(maximumTotal) <= 0 - && observedHops <= maximumSubgraphHops - && observedPerEntityCalls <= maximumPerEntityCalls; - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/composition/GraphQlFederationReleaseEvidence.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/composition/GraphQlFederationReleaseEvidence.java deleted file mode 100644 index dcce0384..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/composition/GraphQlFederationReleaseEvidence.java +++ /dev/null @@ -1,25 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.composition; - -/** - * The evidence a federated release requires (Advanced plan Task 13). - * - *

Composition succeeding is the weakest of the four. It proves the schemas fit together, not - * that entity keys are stable, that cross-subgraph latency is within budget, or that a partial - * subgraph failure produces a sensible response rather than a nulled supergraph. - * - * @param compositionPassed the supergraph composes - * @param entityContractsPassed entity keys and ownership verified - * @param latencyPassed cross-subgraph latency within budget - * @param failureContractsPassed partial-failure behaviour verified - */ -public record GraphQlFederationReleaseEvidence( - boolean compositionPassed, - boolean entityContractsPassed, - boolean latencyPassed, - boolean failureContractsPassed) { - - /** Whether every kind of evidence is present. */ - public boolean complete() { - return compositionPassed && entityContractsPassed && latencyPassed && failureContractsPassed; - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/composition/GraphQlFederationReleaseRejectedException.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/composition/GraphQlFederationReleaseRejectedException.java deleted file mode 100644 index 1f09b1ca..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/composition/GraphQlFederationReleaseRejectedException.java +++ /dev/null @@ -1,21 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.composition; - -/** - * Raised when a federated release lacks required evidence. - * - *

Names what is missing: a federated deployment affects services owned by other teams, so - * "blocked" has to come with the reason. - */ -public class GraphQlFederationReleaseRejectedException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - /** - * Creates the failure. - * - * @param reason which evidence is missing - */ - public GraphQlFederationReleaseRejectedException(String reason) { - super(reason); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/composition/GraphQlFederationUsageReport.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/composition/GraphQlFederationUsageReport.java deleted file mode 100644 index 733bd634..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/composition/GraphQlFederationUsageReport.java +++ /dev/null @@ -1,29 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.composition; - -import java.util.Map; -import java.util.Set; - -/** - * Which subgraphs use which of this subgraph's entity fields. - * - *

The precondition for changing an entity key: without it, the only way to find out who depended - * on a field is to remove it and wait for another team's incident. - * - * @param consumersByField consuming subgraph names, keyed by entity field - */ -public record GraphQlFederationUsageReport(Map> consumersByField) { - - public GraphQlFederationUsageReport { - consumersByField = Map.copyOf(consumersByField); - } - - /** Subgraphs that consume a field. */ - public Set consumersOf(String field) { - return consumersByField.getOrDefault(field, Set.of()); - } - - /** Whether a field may be changed without coordinating with another team. */ - public boolean safeToChange(String field) { - return consumersOf(field).isEmpty(); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/composition/GraphQlSubgraphContract.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/composition/GraphQlSubgraphContract.java deleted file mode 100644 index d71dd30a..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/composition/GraphQlSubgraphContract.java +++ /dev/null @@ -1,41 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.composition; - -import dev.caskeleton.adapter.inbound.graphql.advanced.federation.GraphQlFederationEntityKey; -import java.util.List; - -/** - * What one subgraph publishes into the supergraph. - * - *

An owner is required. In a federated topology an entity key change breaks other teams' - * queries, and "who approves this" has to be answerable before the change is proposed, not after it - * lands. - * - * @param subgraphName the subgraph's name - * @param owner the team that owns it - * @param schemaHash hash of the subgraph's schema - * @param entityKeys entity keys it publishes - */ -public record GraphQlSubgraphContract( - String subgraphName, - String owner, - String schemaHash, - List entityKeys) { - - public GraphQlSubgraphContract { - if (subgraphName == null || subgraphName.isBlank()) { - throw new IllegalArgumentException("subgraph name is required"); - } - if (owner == null || owner.isBlank()) { - throw new IllegalArgumentException("subgraph owner is required"); - } - if (schemaHash == null || schemaHash.isBlank()) { - throw new IllegalArgumentException("subgraph schema hash is required"); - } - entityKeys = List.copyOf(entityKeys); - } - - /** Whether an entity key changed compared with the deployed contract. */ - public boolean entityKeysChangedFrom(GraphQlSubgraphContract deployed) { - return deployed != null && !deployed.entityKeys().equals(entityKeys); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/federation/GraphQlFederationBatchResolver.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/federation/GraphQlFederationBatchResolver.java deleted file mode 100644 index 649307d8..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/federation/GraphQlFederationBatchResolver.java +++ /dev/null @@ -1,47 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.federation; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Objects; - -/** - * Resolves many entity representations as one batch. - * - *

A router sends the whole {@code _entities} array at once, so resolving them one at a time - * recreates the N+1 that DataLoader exists to prevent — except now it is one query per entity per - * subgraph per federated request. - */ -public final class GraphQlFederationBatchResolver { - - private final GraphQlFederationEntityResolver resolver; - - /** - * Creates the batch resolver. - * - * @param resolver the per-representation validator - */ - public GraphQlFederationBatchResolver(GraphQlFederationEntityResolver resolver) { - this.resolver = Objects.requireNonNull(resolver); - } - - /** - * Validates a batch and extracts the key values, preserving order. - * - *

Order matters: the router matches results back to representations positionally. - * - * @throws GraphQlFederationRepresentationException when any representation is incomplete - */ - public List> validateAndExtractKeys( - List> representations) { - - List> keys = new ArrayList<>(representations.size()); - for (Map representation : representations) { - resolver.validateRepresentation(representation); - Map keyValues = new java.util.LinkedHashMap<>(); - resolver.key().fields().forEach(field -> keyValues.put(field, representation.get(field))); - keys.add(Map.copyOf(keyValues)); - } - return List.copyOf(keys); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/federation/GraphQlFederationCapability.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/federation/GraphQlFederationCapability.java deleted file mode 100644 index a11b5aa8..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/federation/GraphQlFederationCapability.java +++ /dev/null @@ -1,45 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.federation; - -import java.util.List; - -/** - * What this repository owns in a federated topology (design §21.1). - * - *

The subgraph, and nothing else. A router is a separate deployment with its own availability, - * its own scaling and its own on-call — running one is a project, not a library feature. - */ -public enum GraphQlFederationCapability { - - /** This service publishes a subgraph schema. */ - SUBGRAPH(true), - - /** Composing subgraphs into a supergraph, owned by a separate project. */ - ROUTER(false), - - /** Schema stitching, not supported at all. */ - SCHEMA_STITCHING(false); - - private final boolean ownedHere; - - GraphQlFederationCapability(boolean ownedHere) { - this.ownedHere = ownedHere; - } - - /** Whether this repository implements the capability. */ - public boolean ownedHere() { - return ownedHere; - } - - /** The preconditions that must hold before federation is worth adopting. */ - public static List activationGate() { - return List.of( - "independently deployed services", - "schema ownership actually split across teams", - "composition CI", - "a router operations owner", - "distributed tracing", - "a cross-subgraph latency budget", - "an entity key lifecycle policy", - "a partial-failure policy"); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/federation/GraphQlFederationEntityKey.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/federation/GraphQlFederationEntityKey.java deleted file mode 100644 index 12df7fdf..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/federation/GraphQlFederationEntityKey.java +++ /dev/null @@ -1,31 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.federation; - -import java.util.List; - -/** - * An entity's {@code @key} fields. - * - *

A versioned public contract, not an implementation detail. Every other subgraph and the router - * send these fields to identify the entity, so changing one is a breaking change across services - * that deploy independently. - * - * @param typeName the entity type - * @param fields the key fields, in declaration order - */ -public record GraphQlFederationEntityKey(String typeName, List fields) { - - public GraphQlFederationEntityKey { - if (typeName == null || typeName.isBlank()) { - throw new IllegalArgumentException("federation entity type name is required"); - } - fields = List.copyOf(fields); - if (fields.isEmpty()) { - throw new IllegalArgumentException("federation entity key cannot be empty"); - } - } - - /** The {@code @key(fields: "...")} directive argument this key corresponds to. */ - public String directiveFields() { - return String.join(" ", fields); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/federation/GraphQlFederationEntityResolver.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/federation/GraphQlFederationEntityResolver.java deleted file mode 100644 index 7400a0e0..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/federation/GraphQlFederationEntityResolver.java +++ /dev/null @@ -1,49 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.federation; - -import java.util.Map; -import java.util.Objects; - -/** - * Validates entity representations before resolving them (Advanced plan Task 12). - * - *

Resolution itself goes through an Application query service, never a repository: an entity - * reference arriving from a router is still a request from outside, and it needs the same - * authorization and tenant scoping as one arriving over HTTP. - */ -public final class GraphQlFederationEntityResolver { - - private final GraphQlFederationEntityKey key; - - /** - * Creates the resolver. - * - * @param key the entity's declared key - */ - public GraphQlFederationEntityResolver(GraphQlFederationEntityKey key) { - this.key = Objects.requireNonNull(key); - } - - /** The entity key this resolver serves. */ - public GraphQlFederationEntityKey key() { - return key; - } - - /** - * Validates one representation. - * - * @throws GraphQlFederationRepresentationException when a declared key field is missing or the - * {@code __typename} does not match - */ - public void validateRepresentation(Map representation) { - Object typeName = representation.get("__typename"); - if (typeName != null && !key.typeName().equals(typeName)) { - throw new GraphQlFederationRepresentationException( - "representation is for a different entity type"); - } - for (String field : key.fields()) { - if (!representation.containsKey(field)) { - throw new GraphQlFederationRepresentationException("missing federation entity key field"); - } - } - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/federation/GraphQlFederationProperties.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/federation/GraphQlFederationProperties.java deleted file mode 100644 index e50e38a1..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/federation/GraphQlFederationProperties.java +++ /dev/null @@ -1,34 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.federation; - -import java.util.List; - -/** - * Federation configuration for this subgraph. - * - *

Off by default, and a single executable schema remains the Stable topology: federation buys - * independent deployment at the cost of cross-subgraph N+1, network amplification, deployment - * ordering and duplicated authorization. - * - * @param enabled whether federation wiring is registered - * @param subgraphName this subgraph's name in the supergraph - * @param entityKeys the entity keys this subgraph publishes - */ -public record GraphQlFederationProperties( - boolean enabled, String subgraphName, List entityKeys) { - - public GraphQlFederationProperties { - entityKeys = entityKeys == null ? List.of() : List.copyOf(entityKeys); - if (enabled && (subgraphName == null || subgraphName.isBlank())) { - throw new IllegalArgumentException("an enabled subgraph requires a name"); - } - if (enabled && entityKeys.isEmpty()) { - throw new IllegalArgumentException( - "an enabled subgraph must publish at least one entity key"); - } - } - - /** Federation disabled: the single executable schema default. */ - public static GraphQlFederationProperties disabled() { - return new GraphQlFederationProperties(false, null, List.of()); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/federation/GraphQlFederationRepresentationException.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/federation/GraphQlFederationRepresentationException.java deleted file mode 100644 index 962bc8b0..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/federation/GraphQlFederationRepresentationException.java +++ /dev/null @@ -1,21 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.federation; - -/** - * Raised when a router sends an entity representation missing a declared key field. - * - *

Rejected rather than resolved partially: without the full key the subgraph would have to guess - * which entity was meant, and a guess here returns another tenant's or another user's object. - */ -public class GraphQlFederationRepresentationException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - /** - * Creates the failure. - * - * @param reason bounded description; never the representation itself - */ - public GraphQlFederationRepresentationException(String reason) { - super(reason); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/federation/GraphQlFederationSchemaFactory.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/federation/GraphQlFederationSchemaFactory.java deleted file mode 100644 index b5720114..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/federation/GraphQlFederationSchemaFactory.java +++ /dev/null @@ -1,54 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.federation; - -import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedCapability; -import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedModuleGuard; -import java.util.List; -import java.util.Objects; - -/** - * Registers federation wiring, only when federation is actually enabled. - * - *

Without the flag nothing is registered at all: a schema that advertises {@code _entities} and - * {@code _service} tells a router it may send entity references, and the router will. - */ -public final class GraphQlFederationSchemaFactory { - - private final GraphQlAdvancedModuleGuard guard; - private final GraphQlFederationProperties properties; - - /** - * Creates the factory. - * - * @param guard the Advanced capability guard - * @param properties federation configuration - */ - public GraphQlFederationSchemaFactory( - GraphQlAdvancedModuleGuard guard, GraphQlFederationProperties properties) { - this.guard = Objects.requireNonNull(guard); - this.properties = Objects.requireNonNull(properties); - } - - /** Whether federation wiring should be registered. */ - public boolean federationEnabled() { - return properties.enabled() && guard.enabled(GraphQlAdvancedCapability.FEDERATION_SUBGRAPH); - } - - /** - * The entity resolvers this subgraph publishes. - * - * @throws dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap - * .GraphQlAdvancedCapabilityDisabledException when federation is configured but not enabled - */ - public List entityResolvers() { - if (!properties.enabled()) { - return List.of(); - } - guard.requireEnabled(GraphQlAdvancedCapability.FEDERATION_SUBGRAPH); - return properties.entityKeys().stream().map(GraphQlFederationEntityResolver::new).toList(); - } - - /** What this repository owns; a router is not part of it. */ - public GraphQlFederationCapability capability() { - return GraphQlFederationCapability.SUBGRAPH; - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/get/GraphQlHttpDraftCompatibilityReport.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/get/GraphQlHttpDraftCompatibilityReport.java deleted file mode 100644 index aef04d66..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/get/GraphQlHttpDraftCompatibilityReport.java +++ /dev/null @@ -1,45 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.get; - -import dev.caskeleton.adapter.inbound.graphql.http.GraphQlHttpProfile; -import java.util.List; -import java.util.Map; - -/** - * What this deployment implements of the moving GraphQL over HTTP draft. - * - *

The point of tracking it separately: the draft can change without the Stable POST contract - * changing. This report is where draft drift is observed, so adopting a change stays a decision - * rather than a consequence of upgrading a library. - * - * @param draftStage the draft stage this was checked against - * @param supportedFeatures draft features implemented - * @param deliberatelyUnsupported draft features deliberately not implemented - */ -public record GraphQlHttpDraftCompatibilityReport( - String draftStage, List supportedFeatures, List deliberatelyUnsupported) { - - public GraphQlHttpDraftCompatibilityReport { - supportedFeatures = List.copyOf(supportedFeatures); - deliberatelyUnsupported = List.copyOf(deliberatelyUnsupported); - } - - /** The current position: POST is Stable, GET is experimental, and 294 is not adopted. */ - public static GraphQlHttpDraftCompatibilityReport current() { - return new GraphQlHttpDraftCompatibilityReport( - "Stage 2 Draft", - List.of( - "POST", "application/graphql-response+json", "4xx request errors", "200 field errors"), - List.of( - "GET (experimental only)", - "status " + GraphQlHttpProfile.DRAFT_PARTIAL_RESPONSE_STATUS + " for partial responses", - "HTTP array batching")); - } - - /** The report as a flat map, for the release evidence. */ - public Map asMap() { - return Map.of( - "draftStage", draftStage, - "supported", supportedFeatures, - "deliberatelyUnsupported", deliberatelyUnsupported); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/get/GraphQlHttpGetCachePolicy.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/get/GraphQlHttpGetCachePolicy.java deleted file mode 100644 index 9ff8dd30..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/get/GraphQlHttpGetCachePolicy.java +++ /dev/null @@ -1,47 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.get; - -/** - * Whether a GET response may be cached, and by whom. - * - *

The reason GET is attractive is caching, and the reason it is dangerous is the same. A GraphQL - * response depends on the actor, so a shared cache keyed by URL will serve one user's data to - * another. - */ -public enum GraphQlHttpGetCachePolicy { - - /** No caching. */ - NO_STORE("no-store"), - - /** The requesting client may cache; no shared cache may. */ - PRIVATE("private, max-age=0"), - - /** - * A shared cache may store the response; only sound for responses with no actor-specific data. - */ - SHARED("public, max-age=60"); - - private final String cacheControl; - - GraphQlHttpGetCachePolicy(String cacheControl) { - this.cacheControl = cacheControl; - } - - /** The {@code Cache-Control} header this policy sets. */ - public String cacheControl() { - return cacheControl; - } - - /** - * The policy for a request. - * - * @param actorSpecificResponse whether the response depends on who asked - * @param profile the GET profile in force - */ - public static GraphQlHttpGetCachePolicy forRequest( - boolean actorSpecificResponse, GraphQlHttpGetProfile profile) { - if (actorSpecificResponse) { - return NO_STORE; - } - return profile.sharedCacheAllowed() ? SHARED : PRIVATE; - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/get/GraphQlHttpGetCsrfPolicy.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/get/GraphQlHttpGetCsrfPolicy.java deleted file mode 100644 index 7719f2df..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/get/GraphQlHttpGetCsrfPolicy.java +++ /dev/null @@ -1,42 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.get; - -/** - * CSRF protection for GET requests carrying ambient credentials. - * - *

Required whenever cookies are the credential. A GET with cookies is triggerable by any page - * that can make the browser fetch a URL, and the read it performs is a read of the victim's data. - */ -public final class GraphQlHttpGetCsrfPolicy { - - private final boolean cookieCredentials; - private final GraphQlHttpGetProfile profile; - - /** - * Creates the policy. - * - * @param cookieCredentials whether the deployment authenticates with cookies - * @param profile the GET profile in force - */ - public GraphQlHttpGetCsrfPolicy(boolean cookieCredentials, GraphQlHttpGetProfile profile) { - this.cookieCredentials = cookieCredentials; - this.profile = profile; - } - - /** Whether a CSRF token must accompany the request. */ - public boolean csrfTokenRequired() { - return cookieCredentials || profile.csrfRequired(); - } - - /** - * Verifies a request. - * - * @param csrfTokenPresent whether a valid CSRF token accompanied it - * @throws GraphQlHttpGetRejectedException when protection is required and missing - */ - public void verify(boolean csrfTokenPresent) { - if (csrfTokenRequired() && !csrfTokenPresent) { - throw new GraphQlHttpGetRejectedException( - "a CSRF token is required for cookie-authenticated GET requests"); - } - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/get/GraphQlHttpGetOperationPolicy.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/get/GraphQlHttpGetOperationPolicy.java deleted file mode 100644 index cee6dcbd..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/get/GraphQlHttpGetOperationPolicy.java +++ /dev/null @@ -1,28 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.get; - -/** - * Which operations GET may carry (Advanced plan Task 17). - * - *

Queries only. A mutation over GET is a side effect behind a URL: prefetchers follow it, caches - * store it, and a link is enough to trigger it. - */ -public final class GraphQlHttpGetOperationPolicy { - - private GraphQlHttpGetOperationPolicy() {} - - /** The query-only policy. */ - public static GraphQlHttpGetOperationPolicy queryOnly() { - return new GraphQlHttpGetOperationPolicy(); - } - - /** - * Verifies the operation type. - * - * @throws GraphQlHttpGetRejectedException for a mutation or subscription - */ - public void verify(String operationType) { - if (!"query".equals(operationType)) { - throw new GraphQlHttpGetRejectedException("GET supports query operations only"); - } - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/get/GraphQlHttpGetProfile.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/get/GraphQlHttpGetProfile.java deleted file mode 100644 index d9996cc4..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/get/GraphQlHttpGetProfile.java +++ /dev/null @@ -1,41 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.get; - -/** - * The GET draft profile's limits. - * - *

A URI budget, because query strings are truncated by proxies at lengths nobody controls, and a - * CSRF requirement whenever cookies are involved: a GET with ambient credentials is triggerable - * from any page. - * - * @param maximumUriBytes largest accepted request URI - * @param sharedCacheAllowed whether a shared cache may store responses - * @param csrfRequired whether CSRF protection is required - */ -public record GraphQlHttpGetProfile( - int maximumUriBytes, boolean sharedCacheAllowed, boolean csrfRequired) { - - /** A conservative URI budget, below common proxy limits. */ - public static final int CONSERVATIVE_URI_BYTES = 2_048; - - public GraphQlHttpGetProfile { - if (maximumUriBytes < 1) { - throw new IllegalArgumentException("maximum URI size must be positive"); - } - } - - /** The default: conservative URI budget, no shared caching, CSRF required. */ - public static GraphQlHttpGetProfile conservative() { - return new GraphQlHttpGetProfile(CONSERVATIVE_URI_BYTES, false, true); - } - - /** - * Verifies a request URI fits the budget. - * - * @throws GraphQlHttpGetRejectedException when it does not - */ - public void verifyUriSize(int uriBytes) { - if (uriBytes > maximumUriBytes) { - throw new GraphQlHttpGetRejectedException("request URI exceeds the configured maximum"); - } - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/get/GraphQlHttpGetRejectedException.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/get/GraphQlHttpGetRejectedException.java deleted file mode 100644 index 5e480f28..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/get/GraphQlHttpGetRejectedException.java +++ /dev/null @@ -1,21 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.get; - -/** - * Raised when a GET request is outside the query-only draft profile. - * - *

Carries no query text: a rejected GET's document is in the URL, which is the reason GET is - * risky in the first place. - */ -public class GraphQlHttpGetRejectedException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - /** - * Creates the failure. - * - * @param reason bounded description - */ - public GraphQlHttpGetRejectedException(String reason) { - super(reason); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/get/GraphQlHttpGetRequestParser.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/get/GraphQlHttpGetRequestParser.java deleted file mode 100644 index 21ee9fa2..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/get/GraphQlHttpGetRequestParser.java +++ /dev/null @@ -1,53 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.get; - -import dev.caskeleton.adapter.inbound.graphql.http.GraphQlHttpRequestEnvelope; -import java.nio.charset.StandardCharsets; -import java.util.Map; -import java.util.Objects; - -/** - * Parses a GET query string into the standard request envelope. - * - *

{@code variables} and {@code extensions} arrive as URL-encoded JSON text, which is one more - * place a malformed value can appear — the parser rejects rather than coerces, and the resulting - * envelope is the same one the POST profile validates. - */ -public final class GraphQlHttpGetRequestParser { - - private final GraphQlHttpGetProfile profile; - - /** - * Creates the parser. - * - * @param profile the GET profile's limits - */ - public GraphQlHttpGetRequestParser(GraphQlHttpGetProfile profile) { - this.profile = Objects.requireNonNull(profile); - } - - /** - * Parses query parameters into an envelope. - * - * @param parameters decoded query parameters - * @param uriBytes the raw request URI size - * @throws GraphQlHttpGetRejectedException when the URI is too large or the document is missing - */ - public GraphQlHttpRequestEnvelope parse(Map parameters, int uriBytes) { - profile.verifyUriSize(uriBytes); - - String query = parameters.get("query"); - if (query == null || query.isBlank()) { - throw new GraphQlHttpGetRejectedException("query parameter is required"); - } - verifyEncodable(query); - return new GraphQlHttpRequestEnvelope( - query, parameters.get("operationName"), Map.of(), Map.of()); - } - - private static void verifyEncodable(String value) { - if (value.getBytes(StandardCharsets.UTF_8).length != value.length() - && value.chars().anyMatch(Character::isISOControl)) { - throw new GraphQlHttpGetRejectedException("query parameter contains invalid characters"); - } - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/incremental/GraphQlIncrementalCancellation.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/incremental/GraphQlIncrementalCancellation.java deleted file mode 100644 index 21cede0d..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/incremental/GraphQlIncrementalCancellation.java +++ /dev/null @@ -1,45 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.incremental; - -import dev.caskeleton.adapter.inbound.graphql.execution.GraphQlCancellation; -import java.util.Objects; - -/** - * Stops outstanding patches when the client goes away. - * - *

A client that disconnects after the initial result leaves deferred work in flight. Without - * cancellation those fragments keep resolving — doing database and downstream work for a response - * that can no longer be delivered. - */ -public final class GraphQlIncrementalCancellation { - - private final GraphQlCancellation cancellation; - - /** - * Creates the cancellation bridge. - * - * @param cancellation the request's cancellation signal - */ - public GraphQlIncrementalCancellation(GraphQlCancellation cancellation) { - this.cancellation = Objects.requireNonNull(cancellation); - } - - /** Registers work producing a deferred patch. */ - public void onCancel(Runnable stopPatch) { - cancellation.onCancel(stopPatch); - } - - /** Cancels every outstanding patch. */ - public void cancel() { - cancellation.cancel(); - } - - /** - * Whether a further patch may still be produced. - * - *

Checked before each patch, so a disconnect stops the work at the next boundary rather than - * at the end. - */ - public boolean mayContinue() { - return !cancellation.cancelled(); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/incremental/GraphQlIncrementalCompatibilityGate.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/incremental/GraphQlIncrementalCompatibilityGate.java deleted file mode 100644 index 5102cca6..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/incremental/GraphQlIncrementalCompatibilityGate.java +++ /dev/null @@ -1,35 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.incremental; - -/** - * Refuses incremental delivery on a runtime that cannot serve it (Advanced plan Task 18). - * - *

Never falls back to a complete response. A silent fallback means the feature appears to work - * in every environment where it is not actually enabled, and fails only where someone relied on it. - */ -public final class GraphQlIncrementalCompatibilityGate { - - /** - * Verifies the runtime can serve incremental delivery. - * - * @throws GraphQlIncrementalDeliveryRejectedException when either half is missing - */ - public void verify(GraphQlIncrementalDeliveryCapability capability) { - if (!capability.engineSupported() || !capability.transportSupported()) { - throw new GraphQlIncrementalDeliveryRejectedException( - "incremental delivery runtime unsupported"); - } - } - - /** - * Verifies the client negotiated incremental delivery. - * - * @param clientNegotiated whether the client asked for it - * @throws GraphQlIncrementalDeliveryRejectedException when it did not - */ - public void verifyClientNegotiation(boolean clientNegotiated) { - if (!clientNegotiated) { - throw new GraphQlIncrementalDeliveryRejectedException( - "incremental responses require explicit client capability negotiation"); - } - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/incremental/GraphQlIncrementalDeliveryCapability.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/incremental/GraphQlIncrementalDeliveryCapability.java deleted file mode 100644 index 5433c3a6..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/incremental/GraphQlIncrementalDeliveryCapability.java +++ /dev/null @@ -1,19 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.incremental; - -/** - * Whether the engine and the transport can both do incremental delivery. - * - *

Both are required and they move independently: an engine that supports {@code @defer} over a - * transport that cannot stream produces a response the client cannot consume. - * - * @param engineSupported whether the GraphQL engine supports it - * @param transportSupported whether the transport can stream the patches - */ -public record GraphQlIncrementalDeliveryCapability( - boolean engineSupported, boolean transportSupported) { - - /** Whether both halves are present. */ - public boolean available() { - return engineSupported && transportSupported; - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/incremental/GraphQlIncrementalDeliveryProfile.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/incremental/GraphQlIncrementalDeliveryProfile.java deleted file mode 100644 index b582fb69..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/incremental/GraphQlIncrementalDeliveryProfile.java +++ /dev/null @@ -1,32 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.incremental; - -/** - * The version-gated incremental delivery profile. - * - *

Version-gated because {@code @defer} and {@code @stream} are not in the September 2025 Stable - * contract and their engine and transport support are still settling. Pinning the profile is what - * keeps a library upgrade from silently changing what clients receive. - * - * @param profileVersion the profile this deployment implements - * @param deferSupported whether {@code @defer} is served - * @param streamSupported whether {@code @stream} is served - */ -public record GraphQlIncrementalDeliveryProfile( - String profileVersion, boolean deferSupported, boolean streamSupported) { - - public GraphQlIncrementalDeliveryProfile { - if (profileVersion == null || profileVersion.isBlank()) { - throw new IllegalArgumentException("incremental delivery profile version is required"); - } - } - - /** Disabled, which is the Stable position. */ - public static GraphQlIncrementalDeliveryProfile disabled() { - return new GraphQlIncrementalDeliveryProfile("experimental-v0", false, false); - } - - /** Whether anything incremental is served at all. */ - public boolean enabled() { - return deferSupported || streamSupported; - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/incremental/GraphQlIncrementalDeliveryRejectedException.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/incremental/GraphQlIncrementalDeliveryRejectedException.java deleted file mode 100644 index 8da2ba07..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/incremental/GraphQlIncrementalDeliveryRejectedException.java +++ /dev/null @@ -1,22 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.incremental; - -/** - * Raised when incremental delivery cannot be served. - * - *

A configuration error rather than a silent fallback: a client that asked for {@code @defer} - * and received a complete response has been served correctly by accident, and will not notice until - * the response it depends on being incremental is not. - */ -public class GraphQlIncrementalDeliveryRejectedException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - /** - * Creates the failure. - * - * @param reason bounded description - */ - public GraphQlIncrementalDeliveryRejectedException(String reason) { - super(reason); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/incremental/GraphQlIncrementalPatch.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/incremental/GraphQlIncrementalPatch.java deleted file mode 100644 index 45952ec0..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/incremental/GraphQlIncrementalPatch.java +++ /dev/null @@ -1,32 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.incremental; - -import java.util.List; -import java.util.Map; - -/** - * One patch following an initial incremental result. - * - *

Carries its own path and errors. A deferred fragment can fail on its own, and its error - * belongs to the patch's path — attributing it to the initial result would tell the client the - * wrong field failed. - * - * @param path where in the response this patch applies - * @param data the patch's data, possibly partial - * @param errors errors raised while producing it - * @param hasNext whether more patches follow - */ -public record GraphQlIncrementalPatch( - List path, - Map data, - List> errors, - boolean hasNext) { - - public GraphQlIncrementalPatch { - path = path == null ? List.of() : List.copyOf(path); - data = - data == null - ? Map.of() - : java.util.Collections.unmodifiableMap(new java.util.LinkedHashMap<>(data)); - errors = errors == null ? List.of() : List.copyOf(errors); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/incremental/GraphQlIncrementalTransportPolicy.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/incremental/GraphQlIncrementalTransportPolicy.java deleted file mode 100644 index 5963f5c3..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/incremental/GraphQlIncrementalTransportPolicy.java +++ /dev/null @@ -1,42 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.incremental; - -import dev.caskeleton.adapter.inbound.graphql.cost.GraphQlRuntimeBudgetTracker; -import java.util.Objects; - -/** - * Keeps incremental responses inside the Stable budgets. - * - *

Patches are part of the same response, so they consume the same node and byte budget. Counting - * only the initial result would make a deferred fragment a way to send an unbounded response one - * patch at a time. - */ -public final class GraphQlIncrementalTransportPolicy { - - private final GraphQlRuntimeBudgetTracker budgetTracker; - - /** - * Creates the policy. - * - * @param budgetTracker the request's runtime budget - */ - public GraphQlIncrementalTransportPolicy(GraphQlRuntimeBudgetTracker budgetTracker) { - this.budgetTracker = Objects.requireNonNull(budgetTracker); - } - - /** - * Records a patch against the request's budget. - * - * @throws dev.caskeleton.adapter.inbound.graphql.cost.GraphQlRuntimeBudgetExceededException when - * the response budget is exhausted - */ - public void recordPatch(GraphQlIncrementalPatch patch) { - budgetTracker.recordNode(); - budgetTracker.recordBytes( - patch.data().toString().getBytes(java.nio.charset.StandardCharsets.UTF_8).length); - } - - /** Marks the response committed; from here an overrun terminates the connection. */ - public void markInitialResultSent() { - budgetTracker.markResponseCommitted(); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/GraphQlPersistedOperation.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/GraphQlPersistedOperation.java deleted file mode 100644 index 5426cf93..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/GraphQlPersistedOperation.java +++ /dev/null @@ -1,100 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.persisted; - -import java.util.Set; - -/** - * One approved operation (design §19). - * - *

Carries the schema hash it was approved against, so an operation cannot survive a schema - * change that invalidated it, and its own complexity and variable limits, so an - * approved-but-expensive operation stays bounded even for a client whose general profile is - * generous. - * - *

Deliberately holds no variables: variables are per-request data, and the registry is - * long-lived storage. - * - * @param id operation identity - * @param operationName the operation's name, which the request must match - * @param documentHash SHA-256 of the canonical document - * @param canonicalDocument the approved document text - * @param schemaContractHash schema the operation was approved against - * @param allowedClientProfiles client profiles that may run it - * @param maximumComplexity complexity ceiling for this operation - * @param maximumVariablesBytes variable size ceiling for this operation - * @param status lifecycle state - */ -public record GraphQlPersistedOperation( - GraphQlPersistedOperationId id, - String operationName, - String documentHash, - String canonicalDocument, - String schemaContractHash, - Set allowedClientProfiles, - long maximumComplexity, - int maximumVariablesBytes, - GraphQlPersistedOperationStatus status) { - - public GraphQlPersistedOperation { - if (id == null || status == null) { - throw new IllegalArgumentException("persisted operation id and status are required"); - } - if (operationName == null || operationName.isBlank()) { - throw new IllegalArgumentException("persisted operation name is required"); - } - if (documentHash == null || documentHash.isBlank()) { - throw new IllegalArgumentException("persisted operation document hash is required"); - } - if (canonicalDocument == null || canonicalDocument.isBlank()) { - throw new IllegalArgumentException("persisted operation document is required"); - } - if (schemaContractHash == null || schemaContractHash.isBlank()) { - throw new IllegalArgumentException("persisted operation schema hash is required"); - } - allowedClientProfiles = Set.copyOf(allowedClientProfiles); - if (allowedClientProfiles.isEmpty()) { - throw new IllegalArgumentException( - "a persisted operation must allow at least one client profile"); - } - if (maximumComplexity < 1 || maximumVariablesBytes < 1) { - throw new IllegalArgumentException("persisted operation limits must be positive"); - } - } - - /** Registers an active operation with first-party defaults. */ - public static GraphQlPersistedOperation active( - String id, - String operationName, - String documentHash, - String canonicalDocument, - String schemaHash) { - return new GraphQlPersistedOperation( - new GraphQlPersistedOperationId(id), - operationName, - documentHash, - canonicalDocument, - schemaHash, - Set.of("FIRST_PARTY"), - 10_000, - 65_536, - GraphQlPersistedOperationStatus.ACTIVE); - } - - /** Returns a copy in a different lifecycle state. */ - public GraphQlPersistedOperation withStatus(GraphQlPersistedOperationStatus newStatus) { - return new GraphQlPersistedOperation( - id, - operationName, - documentHash, - canonicalDocument, - schemaContractHash, - allowedClientProfiles, - maximumComplexity, - maximumVariablesBytes, - newStatus); - } - - /** Whether a client profile may run this operation. */ - public boolean allows(String clientProfileName) { - return allowedClientProfiles.contains(clientProfileName); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/GraphQlPersistedOperationConflictException.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/GraphQlPersistedOperationConflictException.java deleted file mode 100644 index 111db533..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/GraphQlPersistedOperationConflictException.java +++ /dev/null @@ -1,23 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.persisted; - -/** - * Raised when one operation id is registered with a different document. - * - *

Rejected rather than overwritten: clients already deployed are sending that id expecting the - * document that was approved with it, and replacing it would change what their requests execute - * without any client changing. - */ -public class GraphQlPersistedOperationConflictException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - /** - * Creates the failure. - * - * @param operationId the id that was registered twice - */ - public GraphQlPersistedOperationConflictException(String operationId) { - super( - "persisted operation " + operationId + " is already registered with a different document"); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/GraphQlPersistedOperationId.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/GraphQlPersistedOperationId.java deleted file mode 100644 index 61f16cb1..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/GraphQlPersistedOperationId.java +++ /dev/null @@ -1,23 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.persisted; - -import java.util.regex.Pattern; - -/** - * The identity a client sends instead of a document. - * - *

Bounded, because it becomes a registry key and a metric label. Versioned by convention — - * {@code get-order-v2} rather than mutating {@code get-order} — so a client on the old build keeps - * running while a new one ships. - * - * @param value operation id matching {@code [a-z][a-z0-9.-]{2,127}} - */ -public record GraphQlPersistedOperationId(String value) { - - private static final Pattern PATTERN = Pattern.compile("[a-z][a-z0-9.-]{2,127}"); - - public GraphQlPersistedOperationId { - if (value == null || !PATTERN.matcher(value).matches()) { - throw new IllegalArgumentException("invalid persisted operation id"); - } - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/GraphQlPersistedOperationInterceptor.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/GraphQlPersistedOperationInterceptor.java deleted file mode 100644 index 676b7801..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/GraphQlPersistedOperationInterceptor.java +++ /dev/null @@ -1,66 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.persisted; - -import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedCapability; -import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedModuleGuard; -import dev.caskeleton.adapter.inbound.graphql.policy.GraphQlClientPolicy; -import java.util.Objects; - -/** - * Runs the persisted-operation stage, before parsing (Advanced plan Task 3). - * - *

Before parsing because with an operation id the registry is the document source. - * Every check happens here in one place, and none of them is authorization: resolving an approved - * operation says the document is allowed to exist, not that this actor may run it. - */ -public final class GraphQlPersistedOperationInterceptor { - - private final GraphQlAdvancedModuleGuard guard; - private final GraphQlPersistedOperationLookup lookup; - - /** - * Creates the interceptor. - * - * @param guard the Advanced capability guard - * @param lookup the registry lookup - */ - public GraphQlPersistedOperationInterceptor( - GraphQlAdvancedModuleGuard guard, GraphQlPersistedOperationLookup lookup) { - this.guard = Objects.requireNonNull(guard); - this.lookup = Objects.requireNonNull(lookup); - } - - /** - * Resolves and validates a persisted operation request. - * - * @param request what the client sent - * @param clientProfileName the caller's client profile - * @param deployedSchemaHash the deployed schema hash - * @param clientPolicy the caller's client policy - * @return the approved operation, ready to execute - * @throws GraphQlPersistedOperationRejectedException on any failed check - */ - public GraphQlPersistedOperation resolve( - GraphQlPersistedOperationRequest request, - String clientProfileName, - String deployedSchemaHash, - GraphQlClientPolicy clientPolicy) { - - guard.requireEnabled(GraphQlAdvancedCapability.PERSISTED_OPERATION); - - GraphQlPersistedOperation operation = lookup.require(request.operationId()); - GraphQlPersistedOperationPolicy.requireActive(operation); - GraphQlPersistedOperationPolicy.requireClientAllowed(operation, clientProfileName); - GraphQlPersistedOperationPolicy.requireSchemaMatch(operation, deployedSchemaHash); - GraphQlPersistedOperationPolicy.requireDocumentMatch(operation, request.suppliedDocumentHash()); - GraphQlPersistedOperationPolicy.requireVariablesWithinLimit( - operation, request, clientPolicy.maxVariablesBytes()); - return operation; - } - - /** The complexity ceiling for an operation: the stricter of its own and the client's. */ - public long effectiveComplexityLimit( - GraphQlPersistedOperation operation, GraphQlClientPolicy clientPolicy) { - return GraphQlPersistedOperationPolicy.effectiveLimit( - operation.maximumComplexity(), clientPolicy.maxComplexity()); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/GraphQlPersistedOperationLookup.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/GraphQlPersistedOperationLookup.java deleted file mode 100644 index c2edece2..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/GraphQlPersistedOperationLookup.java +++ /dev/null @@ -1,37 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.persisted; - -import java.util.Objects; - -/** - * Resolves an operation id to its approved document. - * - *

An unknown id is rejected with the same message as a blocked one, so the response does not - * tell a caller which ids exist. - */ -public final class GraphQlPersistedOperationLookup { - - private final GraphQlPersistedOperationRegistry registry; - - /** - * Creates the lookup. - * - * @param registry the approved operation store - */ - public GraphQlPersistedOperationLookup(GraphQlPersistedOperationRegistry registry) { - this.registry = Objects.requireNonNull(registry); - } - - /** - * Resolves an operation. - * - * @throws GraphQlPersistedOperationRejectedException when it is unknown - */ - public GraphQlPersistedOperation require(GraphQlPersistedOperationId id) { - return registry - .find(id) - .orElseThrow( - () -> - new GraphQlPersistedOperationRejectedException( - "persisted operation is not available")); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/GraphQlPersistedOperationNotFoundException.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/GraphQlPersistedOperationNotFoundException.java deleted file mode 100644 index 2b10e30f..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/GraphQlPersistedOperationNotFoundException.java +++ /dev/null @@ -1,25 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.persisted; - -/** - * Raised when an admin command names an operation the registry does not hold. - * - *

A distinct failure from a conflict: "there is nothing here" and "you cannot do that from here" - * lead an operator to different next steps, and the admin plane used to report neither — an unknown - * id produced a successful-looking audit entry. - */ -public class GraphQlPersistedOperationNotFoundException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - /** Stable error code. */ - public static final String CODE = "GRAPHQL_PERSISTED_OPERATION_NOT_FOUND"; - - /** - * Creates the failure. - * - * @param operationId the operation that does not exist - */ - public GraphQlPersistedOperationNotFoundException(String operationId) { - super(CODE + ": " + operationId); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/GraphQlPersistedOperationPolicy.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/GraphQlPersistedOperationPolicy.java deleted file mode 100644 index 607259aa..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/GraphQlPersistedOperationPolicy.java +++ /dev/null @@ -1,90 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.persisted; - -/** - * The checks an approved operation must still pass at request time (Advanced plan Task 3). - * - *

Being in the registry is not permission to run. The operation must still be active, belong to - * this client, match the deployed schema, and stay inside the stricter of its own and the client's - * limits — and none of that is authorization, which happens afterwards against the actor. - */ -public final class GraphQlPersistedOperationPolicy { - - private GraphQlPersistedOperationPolicy() {} - - /** - * Requires the operation to be executable. - * - * @throws GraphQlPersistedOperationRejectedException when it is blocked - */ - public static GraphQlPersistedOperation requireActive(GraphQlPersistedOperation operation) { - if (operation.status() != GraphQlPersistedOperationStatus.ACTIVE) { - throw new GraphQlPersistedOperationRejectedException("persisted operation is not active"); - } - return operation; - } - - /** - * Requires the client profile to be allowlisted for this operation. - * - * @throws GraphQlPersistedOperationRejectedException when it is not - */ - public static void requireClientAllowed( - GraphQlPersistedOperation operation, String clientProfileName) { - if (!operation.allows(clientProfileName)) { - throw new GraphQlPersistedOperationRejectedException( - "persisted operation is not allowed for this client profile"); - } - } - - /** - * Requires the operation to match the deployed schema. - * - * @throws GraphQlPersistedOperationRejectedException when the schema has moved on - */ - public static void requireSchemaMatch( - GraphQlPersistedOperation operation, String deployedSchemaHash) { - if (!operation.schemaContractHash().equals(deployedSchemaHash)) { - throw new GraphQlPersistedOperationRejectedException( - "persisted operation was approved against a different schema"); - } - } - - /** - * Requires a supplied document to match the approved one. - * - * @throws GraphQlPersistedOperationRejectedException when the hashes differ - */ - public static void requireDocumentMatch( - GraphQlPersistedOperation operation, String suppliedDocumentHash) { - if (suppliedDocumentHash != null && !operation.documentHash().equals(suppliedDocumentHash)) { - throw new GraphQlPersistedOperationRejectedException( - "the supplied document does not match the persisted operation"); - } - } - - /** - * The effective limit: the stricter of the operation's and the client's. - * - * @param operationLimit the operation's own ceiling - * @param clientLimit the client policy's ceiling - */ - public static long effectiveLimit(long operationLimit, long clientLimit) { - return Math.min(operationLimit, clientLimit); - } - - /** - * Requires the request's variables to fit inside the effective limit. - * - * @throws GraphQlPersistedOperationRejectedException when they do not - */ - public static void requireVariablesWithinLimit( - GraphQlPersistedOperation operation, - GraphQlPersistedOperationRequest request, - int clientMaximumVariablesBytes) { - long limit = effectiveLimit(operation.maximumVariablesBytes(), clientMaximumVariablesBytes); - if (request.variablesBytes() > limit) { - throw new GraphQlPersistedOperationRejectedException( - "persisted operation variables too large"); - } - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/GraphQlPersistedOperationRecordMapping.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/GraphQlPersistedOperationRecordMapping.java deleted file mode 100644 index 3cc2a8dd..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/GraphQlPersistedOperationRecordMapping.java +++ /dev/null @@ -1,123 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.persisted; - -import dev.caskeleton.shared.opstore.OperationalRecord; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Objects; -import java.util.Set; - -/** - * Translates a persisted operation to and from a neutral operational record. - * - *

The whole point of the split. Durable storage for persisted operations has to live in - * infrastructure, and infrastructure must not implement a type that belongs to an inbound transport - * — a Postgres adapter implementing {@code GraphQlPersistedOperationRegistry} would point the - * dependency from the database back at the GraphQL boundary. So the store speaks {@link - * OperationalRecord} and knows nothing about GraphQL, and this class is the only place that knows - * both vocabularies. - * - *

The encoding is length-framed rather than delimited. A canonical document contains newlines, - * an operation name is client-influenced, and a client profile is a free-form string; any delimiter - * chosen from those alphabets is a delimiter a value can contain, and the field after it is then - * read as something else. Framing each field by its length removes the question. - */ -public final class GraphQlPersistedOperationRecordMapping { - - /** The key space this capability owns in the operational store. */ - public static final String NAMESPACE = "graphql.persisted-operation"; - - private static final int FIELDS = 9; - - private GraphQlPersistedOperationRecordMapping() {} - - /** - * The store key for an operation id. - * - * @param id the operation id - */ - public static String keyFor(GraphQlPersistedOperationId id) { - Objects.requireNonNull(id, "persisted operation id is required"); - return id.value(); - } - - /** - * Encodes an operation as a neutral record. - * - * @param operation the operation to store - * @param version the version the caller read, for the store's compare-and-set - */ - public static OperationalRecord toRecord(GraphQlPersistedOperation operation, long version) { - Objects.requireNonNull(operation, "persisted operation is required"); - StringBuilder encoded = new StringBuilder(); - write(encoded, operation.id().value()); - write(encoded, operation.operationName()); - write(encoded, operation.documentHash()); - write(encoded, operation.canonicalDocument()); - write(encoded, operation.schemaContractHash()); - write(encoded, String.join(",", operation.allowedClientProfiles())); - write(encoded, Long.toString(operation.maximumComplexity())); - write(encoded, Integer.toString(operation.maximumVariablesBytes())); - write(encoded, operation.status().name()); - return new OperationalRecord(NAMESPACE, keyFor(operation.id()), encoded.toString(), version); - } - - /** - * Decodes an operation from a neutral record. - * - * @param record the stored record - * @throws IllegalArgumentException when the record is not a persisted operation of this shape - */ - public static GraphQlPersistedOperation fromRecord(OperationalRecord record) { - Objects.requireNonNull(record, "operational record is required"); - if (!NAMESPACE.equals(record.namespace())) { - throw new IllegalArgumentException("operational record belongs to another namespace"); - } - List fields = readAll(record.value()); - if (fields.size() != FIELDS) { - throw new IllegalArgumentException("stored persisted operation has an unexpected shape"); - } - Set profiles = new LinkedHashSet<>(); - if (!fields.get(5).isEmpty()) { - profiles.addAll(List.of(fields.get(5).split(",", -1))); - } - return new GraphQlPersistedOperation( - new GraphQlPersistedOperationId(fields.get(0)), - fields.get(1), - fields.get(2), - fields.get(3), - fields.get(4), - profiles, - Long.parseLong(fields.get(6)), - Integer.parseInt(fields.get(7)), - GraphQlPersistedOperationStatus.valueOf(fields.get(8))); - } - - private static void write(StringBuilder out, String value) { - out.append(value.length()).append(':').append(value); - } - - private static List readAll(String encoded) { - List fields = new java.util.ArrayList<>(); - int cursor = 0; - while (cursor < encoded.length()) { - int separator = encoded.indexOf(':', cursor); - if (separator < 0) { - throw new IllegalArgumentException("stored persisted operation is not length-framed"); - } - int length; - try { - length = Integer.parseInt(encoded.substring(cursor, separator)); - } catch (NumberFormatException malformed) { - throw new IllegalArgumentException("stored persisted operation has an invalid frame"); - } - int start = separator + 1; - int end = start + length; - if (length < 0 || end > encoded.length()) { - throw new IllegalArgumentException("stored persisted operation frame runs past its value"); - } - fields.add(encoded.substring(start, end)); - cursor = end; - } - return List.copyOf(fields); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/GraphQlPersistedOperationRegistry.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/GraphQlPersistedOperationRegistry.java deleted file mode 100644 index 5273dfa4..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/GraphQlPersistedOperationRegistry.java +++ /dev/null @@ -1,39 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.persisted; - -import java.util.Optional; - -/** - * Storage for approved operations. - * - *

An SPI rather than a fixed implementation: a registry needs to survive restarts and stay - * consistent across instances, and which store provides that is a deployment decision the platform - * should not make. - */ -public interface GraphQlPersistedOperationRegistry { - - /** - * Registers an operation. - * - * @throws GraphQlPersistedOperationConflictException when the id already holds a different - * document - */ - void register(GraphQlPersistedOperation operation); - - /** Looks up an operation. */ - Optional find(GraphQlPersistedOperationId id); - - /** - * Applies a lifecycle transition and returns the operation as it now stands. - * - *

Returning the record, and failing when there is nothing to change, is what makes an audit - * entry trustworthy. The previous {@code updateStatus} was a no-op for an unknown id, so the - * admin plane recorded {@code ABSENT -> BLOCKED} as a successful incident response for an - * operation that had never existed — the one entry an operator would rely on afterwards. - * - * @throws GraphQlPersistedOperationNotFoundException when the operation does not exist - * @throws GraphQlPersistedOperationConflictException when the transition is not permitted from - * the operation's current state - */ - GraphQlPersistedOperation apply( - GraphQlPersistedOperationId id, GraphQlPersistedOperationTransition transition); -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/GraphQlPersistedOperationRejectedException.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/GraphQlPersistedOperationRejectedException.java deleted file mode 100644 index fd37ca70..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/GraphQlPersistedOperationRejectedException.java +++ /dev/null @@ -1,30 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.persisted; - -/** - * Raised when a persisted operation may not execute. - * - *

One exception for every reason — blocked, unknown, wrong client, stale schema, oversized - * variables — with a bounded message, so a caller cannot use the rejection reason to probe the - * registry. - */ -public class GraphQlPersistedOperationRejectedException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - /** Stable request-error code. */ - public static final String CODE = "PERSISTED_OPERATION_REJECTED"; - - /** - * Creates the failure. - * - * @param reason bounded reason, never containing the document or variables - */ - public GraphQlPersistedOperationRejectedException(String reason) { - super(reason); - } - - /** The stable request-error code. */ - public String code() { - return CODE; - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/GraphQlPersistedOperationRequest.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/GraphQlPersistedOperationRequest.java deleted file mode 100644 index 4fd21b90..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/GraphQlPersistedOperationRequest.java +++ /dev/null @@ -1,25 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.persisted; - -/** - * What a client sent when invoking a persisted operation. - * - *

{@code suppliedDocumentHash} exists because some clients send the id and the - * document. When they do, the two must agree — otherwise a caller could quote an approved id while - * executing a document of their own. - * - * @param operationId the operation identity - * @param suppliedDocumentHash hash of the document the client also sent, or {@code null} - * @param variablesBytes serialized variables size - */ -public record GraphQlPersistedOperationRequest( - GraphQlPersistedOperationId operationId, String suppliedDocumentHash, int variablesBytes) { - - public GraphQlPersistedOperationRequest { - if (operationId == null) { - throw new IllegalArgumentException("persisted operation id is required"); - } - if (variablesBytes < 0) { - throw new IllegalArgumentException("variables size cannot be negative"); - } - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/GraphQlPersistedOperationStatus.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/GraphQlPersistedOperationStatus.java deleted file mode 100644 index 40682d7a..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/GraphQlPersistedOperationStatus.java +++ /dev/null @@ -1,31 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.persisted; - -/** - * An approved operation's lifecycle state. - * - *

{@link #BLOCKED} is the reason this is a state rather than a boolean: during an incident, one - * expensive operation has to be stoppable immediately, without a redeploy and without disabling the - * endpoint for everyone else. - */ -public enum GraphQlPersistedOperationStatus { - - /** Executable. */ - ACTIVE(true), - - /** Still executable, but scheduled for removal. */ - DEPRECATED(true), - - /** Refused, effective immediately. */ - BLOCKED(false); - - private final boolean executable; - - GraphQlPersistedOperationStatus(boolean executable) { - this.executable = executable; - } - - /** Whether an operation in this state may run. */ - public boolean executable() { - return executable; - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/GraphQlPersistedOperationTransition.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/GraphQlPersistedOperationTransition.java deleted file mode 100644 index f67ae6a6..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/GraphQlPersistedOperationTransition.java +++ /dev/null @@ -1,80 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.persisted; - -import java.util.Map; -import java.util.Set; - -/** - * Which lifecycle changes the registry will accept. - * - *

Without a table, {@code updateStatus} accepted anything, and the sequence that mattered was - * {@code BLOCKED → DEPRECATED}: an operation stopped during an incident could be made executable - * again by a status change that read like a documentation update. Blocking is the emergency - * control, so leaving it is the transition that has to be deliberate. - * - *

{@code BLOCKED} is therefore terminal except through {@link #UNBLOCK}, which exists precisely - * so that reversing an incident block is its own audited command rather than a side effect of - * something else. - */ -public enum GraphQlPersistedOperationTransition { - - /** First registration of an operation. */ - REGISTER, - - /** Marks an operation deprecated while clients migrate. It stays executable. */ - DEPRECATE, - - /** Stops an operation immediately. */ - BLOCK, - - /** Reverses a block, deliberately and with its own audit entry. */ - UNBLOCK, - - /** Retires an operation: it is blocked and no longer offered. */ - RETIRE; - - private static final Map< - GraphQlPersistedOperationTransition, Set> - ALLOWED_FROM = - Map.of( - DEPRECATE, - Set.of( - GraphQlPersistedOperationStatus.ACTIVE, - GraphQlPersistedOperationStatus.DEPRECATED), - BLOCK, - Set.of( - GraphQlPersistedOperationStatus.ACTIVE, - GraphQlPersistedOperationStatus.DEPRECATED), - UNBLOCK, - Set.of(GraphQlPersistedOperationStatus.BLOCKED), - RETIRE, - Set.of( - GraphQlPersistedOperationStatus.ACTIVE, - GraphQlPersistedOperationStatus.DEPRECATED, - GraphQlPersistedOperationStatus.BLOCKED)); - - /** The state this transition leaves the operation in. */ - public GraphQlPersistedOperationStatus target() { - return switch (this) { - case REGISTER, UNBLOCK -> GraphQlPersistedOperationStatus.ACTIVE; - case DEPRECATE -> GraphQlPersistedOperationStatus.DEPRECATED; - case BLOCK, RETIRE -> GraphQlPersistedOperationStatus.BLOCKED; - }; - } - - /** Whether this transition may be applied to an operation currently in the given state. */ - public boolean allowedFrom(GraphQlPersistedOperationStatus current) { - return this != REGISTER && ALLOWED_FROM.getOrDefault(this, Set.of()).contains(current); - } - - /** - * Verifies the transition. - * - * @throws GraphQlPersistedOperationConflictException when the change is not permitted from here - */ - public void verify(GraphQlPersistedOperationId id, GraphQlPersistedOperationStatus current) { - if (!allowedFrom(current)) { - throw new GraphQlPersistedOperationConflictException( - id.value() + " cannot go " + current + " -> " + name()); - } - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/GraphQlPersistedPreparsedBridge.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/GraphQlPersistedPreparsedBridge.java deleted file mode 100644 index f1d90411..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/GraphQlPersistedPreparsedBridge.java +++ /dev/null @@ -1,44 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.persisted; - -import dev.caskeleton.adapter.inbound.graphql.execution.GraphQlPreparsedCacheKey; - -/** - * Bridges an approved operation onto the preparsed document cache. - * - *

The two are different things and must not be merged. The registry decides whether a - * document may run; the cache only avoids re-parsing one that already may. Blocking an operation - * therefore has to take effect immediately, even though its parsed form is still cached — which is - * why the block is checked on every request rather than at cache-fill time. - */ -public final class GraphQlPersistedPreparsedBridge { - - private GraphQlPersistedPreparsedBridge() {} - - /** - * The cache key for an approved operation. - * - * @param operation the approved operation - * @param validationPolicyVersion version of the validation rules in force - * @param clientSchemaProfile client profile whose schema view applies - */ - public static GraphQlPreparsedCacheKey cacheKey( - GraphQlPersistedOperation operation, - String validationPolicyVersion, - String clientSchemaProfile) { - return new GraphQlPreparsedCacheKey( - operation.documentHash(), - operation.schemaContractHash(), - validationPolicyVersion, - clientSchemaProfile); - } - - /** - * Whether a cached parse may be reused for this operation. - * - *

A blocked operation may never run, even though its parsed document is still cached — the - * cache is a parsing optimisation, never an execution permission. - */ - public static boolean executable(GraphQlPersistedOperation operation) { - return operation.status().executable(); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/OperationalStoreGraphQlPersistedOperationRegistry.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/OperationalStoreGraphQlPersistedOperationRegistry.java deleted file mode 100644 index 23921050..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/OperationalStoreGraphQlPersistedOperationRegistry.java +++ /dev/null @@ -1,96 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.persisted; - -import dev.caskeleton.shared.opstore.OperationalRecord; -import dev.caskeleton.shared.opstore.OperationalRecordConflictException; -import dev.caskeleton.shared.opstore.OperationalRecordStorePort; -import java.util.Objects; -import java.util.Optional; - -/** - * The persisted-operation registry, backed by whatever durable store the deployment provides. - * - *

This is the registry an adopter runs. The dependency points from here to a neutral contract in - * {@code shared-contract}, and the durable implementation of that contract points at the same - * contract from the other side — so a Postgres or Redis adapter never names a GraphQL type, and - * this leaf never names a datastore. The composition root connects the two and owns no policy. - * - *

Registration and transitions are compare-and-set against the version this registry read. Two - * admin planes blocking and approving the same operation a second apart used to resolve by arrival - * order, and the loser left no trace; now the loser is told. - */ -public final class OperationalStoreGraphQlPersistedOperationRegistry - implements GraphQlPersistedOperationRegistry { - - private final OperationalRecordStorePort store; - - /** - * Creates the registry. - * - * @param store the deployment's durable operational store - */ - public OperationalStoreGraphQlPersistedOperationRegistry(OperationalRecordStorePort store) { - this.store = Objects.requireNonNull(store, "operational record store is required"); - } - - @Override - public void register(GraphQlPersistedOperation operation) { - Objects.requireNonNull(operation, "persisted operation is required"); - String key = GraphQlPersistedOperationRecordMapping.keyFor(operation.id()); - Optional stored = - store.find(GraphQlPersistedOperationRecordMapping.NAMESPACE, key); - if (stored.isPresent()) { - GraphQlPersistedOperation existing = - GraphQlPersistedOperationRecordMapping.fromRecord(stored.get()); - if (!existing.canonicalDocument().equals(operation.canonicalDocument())) { - throw new GraphQlPersistedOperationConflictException(operation.id().value()); - } - return; - } - try { - store.compareAndSet( - GraphQlPersistedOperationRecordMapping.toRecord( - operation, OperationalRecord.ABSENT_VERSION), - OperationalRecord.ABSENT_VERSION); - } catch (OperationalRecordConflictException lost) { - // Another instance registered the same id between the read and the write. That is a conflict - // in exactly the sense this capability already has a name for. - throw new GraphQlPersistedOperationConflictException(operation.id().value()); - } - } - - @Override - public Optional find(GraphQlPersistedOperationId id) { - Objects.requireNonNull(id, "persisted operation id is required"); - return store - .find( - GraphQlPersistedOperationRecordMapping.NAMESPACE, - GraphQlPersistedOperationRecordMapping.keyFor(id)) - .map(GraphQlPersistedOperationRecordMapping::fromRecord); - } - - @Override - public GraphQlPersistedOperation apply( - GraphQlPersistedOperationId id, GraphQlPersistedOperationTransition transition) { - - Objects.requireNonNull(id, "persisted operation id is required"); - Objects.requireNonNull(transition, "transition is required"); - OperationalRecord stored = - store - .find( - GraphQlPersistedOperationRecordMapping.NAMESPACE, - GraphQlPersistedOperationRecordMapping.keyFor(id)) - .orElseThrow(() -> new GraphQlPersistedOperationNotFoundException(id.value())); - - GraphQlPersistedOperation current = GraphQlPersistedOperationRecordMapping.fromRecord(stored); - transition.verify(id, current.status()); - GraphQlPersistedOperation next = current.withStatus(transition.target()); - try { - store.compareAndSet( - GraphQlPersistedOperationRecordMapping.toRecord(next, stored.version() + 1), - stored.version()); - } catch (OperationalRecordConflictException lost) { - throw new GraphQlPersistedOperationConflictException(id.value()); - } - return next; - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/release/GraphQlAdvancedCompatibilityMatrix.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/release/GraphQlAdvancedCompatibilityMatrix.java deleted file mode 100644 index a6b7eab8..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/release/GraphQlAdvancedCompatibilityMatrix.java +++ /dev/null @@ -1,45 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.release; - -import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedCapability; -import dev.caskeleton.adapter.inbound.graphql.release.GraphQlCompatibilityMatrix; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -/** - * The protocol and library versions one Advanced capability was verified against. - * - *

Extends the Stable matrix rather than replacing it, and adds the protocol versions that only - * Advanced capabilities have: a WebSocket sub-protocol, a federation specification version, a - * codegen engine. - * - * @param capability the capability - * @param stableMatrix the Stable framework combination underneath it - * @param protocolVersions protocol versions verified, keyed by protocol name - */ -public record GraphQlAdvancedCompatibilityMatrix( - GraphQlAdvancedCapability capability, - GraphQlCompatibilityMatrix stableMatrix, - Map protocolVersions) { - - public GraphQlAdvancedCompatibilityMatrix { - if (capability == null || stableMatrix == null) { - throw new IllegalArgumentException("capability and stable matrix are required"); - } - protocolVersions = Map.copyOf(protocolVersions); - } - - /** Whether the whole combination is supported. */ - public boolean supported() { - return problems().isEmpty(); - } - - /** Why the combination is unsupported, in a deterministic order. */ - public List problems() { - List problems = new ArrayList<>(stableMatrix.problems()); - if (protocolVersions.isEmpty()) { - problems.add(capability.name() + " declares no verified protocol version"); - } - return List.copyOf(problems); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/release/GraphQlAdvancedPromotionDecision.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/release/GraphQlAdvancedPromotionDecision.java deleted file mode 100644 index 15df5823..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/release/GraphQlAdvancedPromotionDecision.java +++ /dev/null @@ -1,64 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.release; - -import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedCapability; -import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedCapabilityGrade; -import java.time.Instant; -import java.util.List; - -/** - * A decision to promote, hold or withdraw one capability. - * - *

Promotion out of Experimental needs a recorded decision with an owner. Without one a - * capability drifts into production by habit — enabled in one environment, then another, until - * nobody remembers it was never approved. - * - * @param capability the capability decided on - * @param fromGrade its grade before - * @param toGrade its grade after - * @param decisionRecord reference to the ADR or decision log entry - * @param owner who owns the capability - * @param decidedAt when the decision was made - * @param missingEvidence evidence still outstanding, empty when promotion is clean - */ -public record GraphQlAdvancedPromotionDecision( - GraphQlAdvancedCapability capability, - GraphQlAdvancedCapabilityGrade fromGrade, - GraphQlAdvancedCapabilityGrade toGrade, - String decisionRecord, - String owner, - Instant decidedAt, - List missingEvidence) { - - public GraphQlAdvancedPromotionDecision { - if (capability == null || fromGrade == null || toGrade == null) { - throw new IllegalArgumentException("capability and both grades are required"); - } - if (decisionRecord == null || decisionRecord.isBlank()) { - throw new IllegalArgumentException("a promotion requires a recorded decision reference"); - } - if (owner == null || owner.isBlank()) { - throw new IllegalArgumentException("a promotion requires an owner"); - } - if (decidedAt == null) { - throw new IllegalArgumentException("a promotion requires a decision instant"); - } - missingEvidence = List.copyOf(missingEvidence); - } - - /** Whether the decision actually promotes the capability. */ - public boolean promotes() { - return toGrade != fromGrade && toGrade != GraphQlAdvancedCapabilityGrade.EXPERIMENTAL; - } - - /** - * Verifies a promotion is supported by evidence. - * - * @throws GraphQlAdvancedReleaseException when evidence is still outstanding - */ - public void verify() { - if (promotes() && !missingEvidence.isEmpty()) { - throw new GraphQlAdvancedReleaseException( - capability.name() + " cannot be promoted with outstanding evidence: " + missingEvidence); - } - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/release/GraphQlAdvancedReleaseEvidence.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/release/GraphQlAdvancedReleaseEvidence.java deleted file mode 100644 index 784261f8..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/release/GraphQlAdvancedReleaseEvidence.java +++ /dev/null @@ -1,31 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.release; - -/** - * The evidence an Advanced capability release requires (Advanced plan Task 19). - * - *

The Stable baseline comes first and is not negotiable: an Advanced capability sits on top of - * the Stable platform's transport, error, security and cost guarantees, so releasing one on an - * unproven base means its own evidence was gathered against something that might not hold. - * - * @param stableBaselinePassed the Stable release gate passed - * @param capabilityContractsPassed the capability's own contract suites passed - * @param securityPassed authentication, authorization and isolation evidence - * @param soakPassed long-running behaviour under sustained load - * @param compatibilityPassed framework and protocol compatibility - */ -public record GraphQlAdvancedReleaseEvidence( - boolean stableBaselinePassed, - boolean capabilityContractsPassed, - boolean securityPassed, - boolean soakPassed, - boolean compatibilityPassed) { - - /** Whether every kind of evidence is present. */ - public boolean complete() { - return stableBaselinePassed - && capabilityContractsPassed - && securityPassed - && soakPassed - && compatibilityPassed; - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/release/GraphQlAdvancedReleaseException.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/release/GraphQlAdvancedReleaseException.java deleted file mode 100644 index 884f0e3d..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/release/GraphQlAdvancedReleaseException.java +++ /dev/null @@ -1,20 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.release; - -/** - * Raised when an Advanced capability may not be released. - * - *

Names what is missing, so the gate is a checklist rather than a wall. - */ -public class GraphQlAdvancedReleaseException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - /** - * Creates the failure. - * - * @param reason which evidence is missing - */ - public GraphQlAdvancedReleaseException(String reason) { - super(reason); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/release/GraphQlAdvancedReleaseGate.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/release/GraphQlAdvancedReleaseGate.java deleted file mode 100644 index d1ca06c5..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/release/GraphQlAdvancedReleaseGate.java +++ /dev/null @@ -1,50 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.release; - -import java.util.ArrayList; -import java.util.List; - -/** - * Blocks an Advanced capability release without complete evidence. - * - *

The Stable baseline is checked first and reported on its own, because everything else is - * measured against it: if the Stable platform's guarantees have not been demonstrated, the - * capability's soak numbers describe a system nobody has verified. - */ -public final class GraphQlAdvancedReleaseGate { - - /** - * Verifies an Advanced release. - * - * @throws GraphQlAdvancedReleaseException naming the missing evidence - */ - public void verify(GraphQlAdvancedReleaseEvidence evidence) { - if (!evidence.stableBaselinePassed()) { - throw new GraphQlAdvancedReleaseException("stable graphql baseline must pass first"); - } - List missing = missing(evidence); - if (!missing.isEmpty()) { - throw new GraphQlAdvancedReleaseException("advanced graphql evidence incomplete: " + missing); - } - } - - /** Which evidence is missing, in a deterministic order. */ - public List missing(GraphQlAdvancedReleaseEvidence evidence) { - List missing = new ArrayList<>(); - if (!evidence.stableBaselinePassed()) { - missing.add("stableBaseline"); - } - if (!evidence.capabilityContractsPassed()) { - missing.add("capabilityContracts"); - } - if (!evidence.securityPassed()) { - missing.add("security"); - } - if (!evidence.soakPassed()) { - missing.add("soak"); - } - if (!evidence.compatibilityPassed()) { - missing.add("compatibility"); - } - return List.copyOf(missing); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/release/GraphQlAdvancedRunbookIndex.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/release/GraphQlAdvancedRunbookIndex.java deleted file mode 100644 index feb2be2d..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/release/GraphQlAdvancedRunbookIndex.java +++ /dev/null @@ -1,52 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.release; - -import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedCapability; -import java.util.EnumMap; -import java.util.Map; - -/** - * The operational runbook each capability must have before release. - * - *

Every Advanced capability introduces a failure mode the Stable platform does not have — a - * connection storm, a blocked operation to reverse, a subgraph to roll back. Requiring the runbook - * up front is what stops that being written for the first time during the incident. - */ -public final class GraphQlAdvancedRunbookIndex { - - private final Map runbooks = - new EnumMap<>(GraphQlAdvancedCapability.class); - - /** - * Registers a capability's runbook. - * - * @param capability the capability - * @param runbookReference where the runbook lives - */ - public GraphQlAdvancedRunbookIndex register( - GraphQlAdvancedCapability capability, String runbookReference) { - if (runbookReference == null || runbookReference.isBlank()) { - throw new IllegalArgumentException("a runbook reference is required"); - } - runbooks.put(capability, runbookReference); - return this; - } - - /** - * Requires a capability to have a runbook. - * - * @throws GraphQlAdvancedReleaseException when it does not - */ - public String require(GraphQlAdvancedCapability capability) { - String reference = runbooks.get(capability); - if (reference == null) { - throw new GraphQlAdvancedReleaseException( - capability.name() + " cannot be released without an operational runbook"); - } - return reference; - } - - /** Registered runbooks. */ - public Map runbooks() { - return Map.copyOf(runbooks); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/release/GraphQlAdvancedSoakScenario.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/release/GraphQlAdvancedSoakScenario.java deleted file mode 100644 index fc32e78d..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/release/GraphQlAdvancedSoakScenario.java +++ /dev/null @@ -1,51 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.release; - -import java.util.List; - -/** - * The soak scenarios a long-lived transport must survive (design §24.4). - * - *

All of these are duration problems, invisible to a short test. A buffer leak, a connection - * that never re-authenticates and a source that reconnects badly all look fine for the first - * minute. - */ -public enum GraphQlAdvancedSoakScenario { - - /** A thousand persistent connections held open. */ - BASELINE_1K_CONNECTIONS, - - /** The deployment's target connection count. */ - TARGET_CONNECTION_COUNT, - - /** Several subscriptions multiplexed on one connection. */ - MULTIPLE_SUBSCRIPTIONS_PER_CONNECTION, - - /** A burst of events far above steady state. */ - EVENT_BURST, - - /** A client that reads more slowly than the source produces. */ - SLOW_CONSUMER, - - /** Many simultaneous cancellations. */ - CANCEL_STORM, - - /** Credentials expiring mid-stream. */ - AUTH_EXPIRY, - - /** The server restarting under load. */ - SERVER_RESTART, - - /** A rolling deployment across instances. */ - ROLLING_DEPLOYMENT, - - /** Graceful shutdown with subscriptions in flight. */ - GRACEFUL_DRAIN, - - /** The event source restarting underneath the subscriptions. */ - SOURCE_RESTART; - - /** Every scenario a realtime capability must pass before promotion. */ - public static List requiredForRealtime() { - return List.of(values()); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/replay/GraphQlReplayAuthorization.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/replay/GraphQlReplayAuthorization.java deleted file mode 100644 index f8eab8e7..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/replay/GraphQlReplayAuthorization.java +++ /dev/null @@ -1,49 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.replay; - -import dev.caskeleton.adapter.inbound.graphql.advanced.security.GraphQlWebSocketPrincipal; - -/** - * Authorizes a replay before any history is delivered. - * - *

Replay reads the past, so the check is stricter than for a live subscription: the tenant and - * actor resuming must be the ones the cursor was issued to, and must still be authorized now — - * access granted when the events were produced may since have been withdrawn. - * - *

Tenant is checked alongside actor rather than assumed to follow from it. Checking only the - * actor is correct exactly while one actor identity never spans two tenants, and nothing here - * enforces that; when it stops holding, the replay succeeds and hands over history the caller was - * never entitled to. - */ -public final class GraphQlReplayAuthorization { - - private GraphQlReplayAuthorization() {} - - /** - * Verifies a replay request. - * - * @param cursorActorFingerprint the actor the cursor was issued to - * @param cursorTenantFingerprint the tenant the cursor was issued to - * @param principal the actor presenting it - * @param stillAuthorized whether the Application still authorizes this actor for the subscription - * @throws GraphQlReplayAuthorizationException when tenant or actor differs, or authorization has - * since been withdrawn - */ - public static void verify( - String cursorActorFingerprint, - String cursorTenantFingerprint, - GraphQlWebSocketPrincipal principal, - boolean stillAuthorized) { - - if (cursorActorFingerprint == null - || !cursorActorFingerprint.equals(principal.actorFingerprint())) { - throw new GraphQlReplayAuthorizationException(); - } - if (cursorTenantFingerprint == null - || !cursorTenantFingerprint.equals(principal.tenantFingerprint())) { - throw new GraphQlReplayAuthorizationException(); - } - if (!stillAuthorized) { - throw new GraphQlReplayAuthorizationException(); - } - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/replay/GraphQlReplayAuthorizationException.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/replay/GraphQlReplayAuthorizationException.java deleted file mode 100644 index 5933591b..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/replay/GraphQlReplayAuthorizationException.java +++ /dev/null @@ -1,17 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.replay; - -/** - * Raised when a caller may not replay a subscription's history. - * - *

Carries no actor identity or position: a denial must not reveal whose cursor it was or how far - * it reached. - */ -public class GraphQlReplayAuthorizationException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - /** Creates the failure. */ - public GraphQlReplayAuthorizationException() { - super("subscription replay is not authorized"); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/replay/GraphQlReplayGapException.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/replay/GraphQlReplayGapException.java deleted file mode 100644 index 409454b5..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/replay/GraphQlReplayGapException.java +++ /dev/null @@ -1,22 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.replay; - -/** - * Raised when a snapshot and the live stream do not join up. - * - *

A gap means events happened between the snapshot and the first live event, and the client will - * never see them. Failing loudly is the only honest option: silently continuing would present an - * incomplete stream as a complete one. - */ -public class GraphQlReplayGapException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - /** - * Creates the failure. - * - * @param reason bounded description of the gap - */ - public GraphQlReplayGapException(String reason) { - super(reason); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/replay/GraphQlReplayHistoryLostException.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/replay/GraphQlReplayHistoryLostException.java deleted file mode 100644 index 4df1e523..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/replay/GraphQlReplayHistoryLostException.java +++ /dev/null @@ -1,25 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.replay; - -/** - * Raised when a resume position has fallen outside the retention window. - * - *

A distinct outcome from a rejected cursor: the cursor is genuine, the history is simply gone, - * and the client's correct response is to re-read a snapshot rather than to re-authenticate. - */ -public class GraphQlReplayHistoryLostException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - /** Stable error code. */ - public static final String CODE = "SUBSCRIPTION_HISTORY_LOST"; - - /** Creates the failure. */ - public GraphQlReplayHistoryLostException() { - super(CODE); - } - - /** The stable error code. */ - public String code() { - return CODE; - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/replay/GraphQlReplayPosition.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/replay/GraphQlReplayPosition.java deleted file mode 100644 index 146cfb37..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/replay/GraphQlReplayPosition.java +++ /dev/null @@ -1,23 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.replay; - -/** - * A position in the source event sequence. - * - *

The sequence is the messaging platform's, not GraphQL's: GraphQL has no resume token, and - * inventing one here would promise a durability guarantee the transport cannot keep. - * - * @param sequence monotonic source position - */ -public record GraphQlReplayPosition(long sequence) { - - public GraphQlReplayPosition { - if (sequence < 0) { - throw new IllegalArgumentException("sequence cannot be negative"); - } - } - - /** The position immediately after this one. */ - public GraphQlReplayPosition next() { - return new GraphQlReplayPosition(sequence + 1); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/replay/GraphQlReplaySource.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/replay/GraphQlReplaySource.java deleted file mode 100644 index a7352824..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/replay/GraphQlReplaySource.java +++ /dev/null @@ -1,41 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.replay; - -import dev.caskeleton.adapter.inbound.graphql.advanced.subscription.GraphQlSubscriptionEvent; -import org.reactivestreams.Publisher; - -/** - * A source that can replay from a position. - * - *

The durability is the messaging platform's, and so is the retention window. This interface - * only asks whether a position is still available — a cursor older than the window has to fail - * rather than silently resume from wherever history now begins. - */ -public interface GraphQlReplaySource { - - /** The earliest position still retained. */ - GraphQlReplayPosition earliestAvailable(); - - /** Whether a position can still be replayed. */ - default boolean available(GraphQlReplayPosition position) { - return position.sequence() >= earliestAvailable().sequence(); - } - - /** - * Replays from a position. - * - * @throws GraphQlReplayHistoryLostException when the position has fallen outside the retention - * window - */ - Publisher replayFrom(GraphQlReplayPosition position); - - /** - * Verifies a position is still replayable. - * - * @throws GraphQlReplayHistoryLostException when it is not - */ - default void requireAvailable(GraphQlReplayPosition position) { - if (!available(position)) { - throw new GraphQlReplayHistoryLostException(); - } - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/replay/GraphQlSnapshotLiveHandoff.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/replay/GraphQlSnapshotLiveHandoff.java deleted file mode 100644 index f7f6edb4..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/replay/GraphQlSnapshotLiveHandoff.java +++ /dev/null @@ -1,38 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.replay; - -/** - * The join between a snapshot and the live stream (Advanced plan Task 10). - * - *

Resuming means reading a snapshot and then continuing live, and the two have to meet exactly. - * A live stream starting later than the snapshot ends loses events; one starting earlier repeats - * them. Both are checked, because "roughly continuous" is not something a client can compensate - * for. - * - * @param snapshotPosition last position included in the snapshot - * @param liveStartPosition first position the live stream will deliver - */ -public record GraphQlSnapshotLiveHandoff( - GraphQlReplayPosition snapshotPosition, GraphQlReplayPosition liveStartPosition) { - - public GraphQlSnapshotLiveHandoff { - if (snapshotPosition == null || liveStartPosition == null) { - throw new IllegalArgumentException("both handoff positions are required"); - } - } - - /** - * Verifies the two streams join without a gap. - * - * @throws GraphQlReplayGapException when events would be missed - */ - public void verifyContiguous() { - if (liveStartPosition.sequence() > snapshotPosition.sequence() + 1) { - throw new GraphQlReplayGapException("snapshot and live stream contain a gap"); - } - } - - /** Whether the join would repeat events the snapshot already contained. */ - public boolean duplicates() { - return liveStartPosition.sequence() <= snapshotPosition.sequence(); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/replay/GraphQlSubscriptionCursor.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/replay/GraphQlSubscriptionCursor.java deleted file mode 100644 index 9d1029f8..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/replay/GraphQlSubscriptionCursor.java +++ /dev/null @@ -1,95 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.replay; - -import dev.caskeleton.adapter.inbound.graphql.advanced.security.GraphQlWebSocketPrincipal; -import dev.caskeleton.adapter.inbound.graphql.pagination.GraphQlCursorCodec; -import dev.caskeleton.adapter.inbound.graphql.pagination.GraphQlCursorFraming; -import dev.caskeleton.adapter.inbound.graphql.pagination.GraphQlCursorPayload; -import dev.caskeleton.adapter.inbound.graphql.pagination.GraphQlCursorScope; -import java.util.Map; -import java.util.Objects; - -/** - * A signed resume position for a subscription. - * - *

Signed and bound to the tenant, the actor and the subscription profile for the same reason - * connection cursors are: an unsigned resume token is a "start reading from here" parameter, and - * replay reads history. - * - *

The tenant is part of the binding, not left to the actor fingerprint to imply. An actor - * identifier that happens to be unique per tenant today stops being a tenant check the moment one - * identity can act in two tenants, and the failure is silent — the cursor verifies, the actor - * matches, and the replay delivers another tenant's history. Taking the principal rather than a - * bare fingerprint makes issuing a cursor without a tenant impossible to express. - * - *

GraphQL itself defines no resume mechanism — this is an extension, and the durability behind - * it belongs to the messaging platform. - */ -public final class GraphQlSubscriptionCursor { - - /** Query profile cursors of this kind are bound to. */ - public static final String QUERY_PROFILE = "subscription-replay"; - - private GraphQlSubscriptionCursor() {} - - /** - * Issues a resume cursor. - * - * @param codec the signing codec - * @param subscriptionProfile the subscription this cursor belongs to - * @param principal the tenant and actor it was issued to - * @param position the resume position - */ - public static String issue( - GraphQlCursorCodec codec, - String subscriptionProfile, - GraphQlWebSocketPrincipal principal, - GraphQlReplayPosition position) { - return codec.encode( - GraphQlCursorPayload.issue( - QUERY_PROFILE, - GraphQlCursorPayload.FORWARD, - Map.of("id", subscriptionProfile, "sequence", Long.toString(position.sequence())), - subscriptionProfile, - scopeOf(principal))); - } - - /** - * Verifies and decodes a resume cursor. - * - * @param codec the signing codec - * @param cursor the cursor the client presented - * @param subscriptionProfile the subscription being resumed - * @param principal the tenant and actor presenting it - * @throws dev.caskeleton.adapter.inbound.graphql.pagination.GraphQlCursorException when the - * cursor was issued for another tenant, actor or subscription - */ - public static GraphQlReplayPosition resume( - GraphQlCursorCodec codec, - String cursor, - String subscriptionProfile, - GraphQlWebSocketPrincipal principal) { - GraphQlCursorPayload payload = - codec.decode( - cursor, - new GraphQlCursorScope( - QUERY_PROFILE, - subscriptionProfile, - GraphQlCursorPayload.FORWARD, - scopeOf(principal))); - return new GraphQlReplayPosition(Long.parseLong(payload.keyset().get("sequence"))); - } - - /** - * The scope fingerprint a cursor is bound to. - * - *

Length-framed rather than concatenated, so a tenant ending in the prefix of an actor cannot - * produce the same scope string as a different pair. - */ - private static String scopeOf(GraphQlWebSocketPrincipal principal) { - Objects.requireNonNull(principal, "principal is required"); - StringBuilder scope = new StringBuilder(); - GraphQlCursorFraming.write(scope, principal.tenantFingerprint()); - GraphQlCursorFraming.write(scope, principal.actorFingerprint()); - return scope.toString(); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/rsocket/GraphQlRSocketAdmission.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/rsocket/GraphQlRSocketAdmission.java deleted file mode 100644 index 75b8f859..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/rsocket/GraphQlRSocketAdmission.java +++ /dev/null @@ -1,55 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.rsocket; - -import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedCapability; -import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedModuleGuard; -import dev.caskeleton.adapter.inbound.graphql.policy.GraphQlOperationType; -import java.util.Objects; - -/** - * Decides whether an RSocket route may be served, and which interaction model it gets. - * - *

Admission, not a handler and not a registration: nothing here touches an {@code RSocket} - * acceptor. It answers "is this route allowed, and is this request/stream or request/response", - * which is what the runtime needs before it binds anything. - * - *

Experimental, so in production the guard additionally requires an approval profile. The - * interaction model comes from the operation type rather than the caller's request. - */ -public final class GraphQlRSocketAdmission { - - private final GraphQlAdvancedModuleGuard guard; - private final GraphQlRSocketProperties properties; - private final GraphQlRSocketRoutePolicy routePolicy; - - /** - * Creates the factory. - * - * @param guard the Advanced capability guard - * @param properties transport configuration - */ - public GraphQlRSocketAdmission( - GraphQlAdvancedModuleGuard guard, GraphQlRSocketProperties properties) { - this.guard = Objects.requireNonNull(guard); - this.properties = Objects.requireNonNull(properties); - this.routePolicy = new GraphQlRSocketRoutePolicy(properties.allowedRoutes()); - } - - /** - * Accepts a request on a route. - * - * @param route the requested route - * @param operationType the operation type - * @return the interaction model to use - * @throws GraphQlRSocketRouteRejectedException when the route is not allowlisted - */ - public GraphQlRSocketCapability accept(String route, GraphQlOperationType operationType) { - guard.requireEnabled(GraphQlAdvancedCapability.RSOCKET); - routePolicy.requireAllowed(route); - return GraphQlRSocketCapability.forOperation(operationType); - } - - /** Whether the transport is registered at all. */ - public boolean enabled() { - return properties.enabled() && guard.enabled(GraphQlAdvancedCapability.RSOCKET); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/rsocket/GraphQlRSocketAuthentication.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/rsocket/GraphQlRSocketAuthentication.java deleted file mode 100644 index fbb9e51f..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/rsocket/GraphQlRSocketAuthentication.java +++ /dev/null @@ -1,49 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.rsocket; - -import java.util.Objects; -import java.util.Set; - -/** - * Authentication metadata accepted on an RSocket connection. - * - *

MIME types are allowlisted for the same reason routes are: metadata drives how a credential is - * parsed, and an unexpected encoding is an unexpected parser. - */ -public final class GraphQlRSocketAuthentication { - - private final Set allowedMetadataMimeTypes; - - /** - * Creates the authentication policy. - * - * @param allowedMetadataMimeTypes metadata MIME types accepted - */ - public GraphQlRSocketAuthentication(Set allowedMetadataMimeTypes) { - this.allowedMetadataMimeTypes = Set.copyOf(Objects.requireNonNull(allowedMetadataMimeTypes)); - } - - /** - * Requires a metadata MIME type to be allowlisted. - * - * @throws GraphQlRSocketRouteRejectedException when it is not - */ - public void requireAllowedMetadata(String mimeType) { - if (mimeType == null || !allowedMetadataMimeTypes.contains(mimeType)) { - throw new GraphQlRSocketRouteRejectedException("metadata MIME type " + mimeType); - } - } - - /** - * Requires an authenticated actor. - * - *

The same actor and tenant rules as HTTP: a different transport does not mean different - * security. - * - * @throws GraphQlRSocketRouteRejectedException when the connection is unauthenticated - */ - public void requireAuthenticated(boolean authenticated) { - if (!authenticated) { - throw new GraphQlRSocketRouteRejectedException("unauthenticated RSocket connection"); - } - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/rsocket/GraphQlRSocketCapability.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/rsocket/GraphQlRSocketCapability.java deleted file mode 100644 index 91011839..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/rsocket/GraphQlRSocketCapability.java +++ /dev/null @@ -1,28 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.rsocket; - -import dev.caskeleton.adapter.inbound.graphql.policy.GraphQlOperationType; - -/** - * How GraphQL operations map onto RSocket interaction models. - * - *

A fixed mapping, not a choice: a query as request-stream would leave the client waiting for a - * stream that emits once and never completes in the way it expects. - */ -public enum GraphQlRSocketCapability { - - /** Query and mutation: one request, one response. */ - REQUEST_RESPONSE, - - /** Subscription: one request, a stream of responses. */ - REQUEST_STREAM; - - /** The interaction model for an operation type. */ - public static GraphQlRSocketCapability forOperation(GraphQlOperationType operationType) { - return operationType == GraphQlOperationType.SUBSCRIPTION ? REQUEST_STREAM : REQUEST_RESPONSE; - } - - /** Whether RSocket is a public-facing transport. It is not. */ - public static boolean publicTransport() { - return false; - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/rsocket/GraphQlRSocketErrorMapper.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/rsocket/GraphQlRSocketErrorMapper.java deleted file mode 100644 index 736bcd55..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/rsocket/GraphQlRSocketErrorMapper.java +++ /dev/null @@ -1,36 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.rsocket; - -import dev.caskeleton.adapter.inbound.graphql.error.GraphQlErrorContext; -import dev.caskeleton.adapter.inbound.graphql.error.GraphQlExceptionResolver; -import dev.caskeleton.adapter.inbound.graphql.error.GraphQlWireError; -import java.util.Objects; - -/** - * Maps failures onto RSocket, reusing the HTTP error contract. - * - *

Deliberately the same resolver: a masked internal error over HTTP and a disclosed one over - * RSocket would mean the safest transport is whichever the attacker did not choose. - */ -public final class GraphQlRSocketErrorMapper { - - private final GraphQlExceptionResolver resolver; - - /** - * Creates the mapper. - * - * @param resolver the shared exception resolver - */ - public GraphQlRSocketErrorMapper(GraphQlExceptionResolver resolver) { - this.resolver = Objects.requireNonNull(resolver); - } - - /** A mapper using the default masking resolver. */ - public static GraphQlRSocketErrorMapper defaults() { - return new GraphQlRSocketErrorMapper(GraphQlExceptionResolver.defaults()); - } - - /** Maps a failure to the same wire error the HTTP transport would produce. */ - public GraphQlWireError map(Throwable failure, GraphQlErrorContext context) { - return resolver.resolve(failure, context); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/rsocket/GraphQlRSocketHandlerFactory.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/rsocket/GraphQlRSocketHandlerFactory.java deleted file mode 100644 index 1fb842e1..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/rsocket/GraphQlRSocketHandlerFactory.java +++ /dev/null @@ -1,84 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.rsocket; - -import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedCapability; -import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedCapabilityDisabledException; -import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedFeatureFlags; -import java.util.Objects; -import java.util.Set; - -/** - * Decides whether the experimental RSocket transport may exist, and on what terms. - * - *

Two gates rather than one, and the second is the reason this is a factory. RSocket is graded - * experimental here, so the capability flag alone is not enough: the deployment must also have - * given explicit experimental approval. A flag can be set by anyone editing configuration; the - * approval is a separate act, and separating them is what stops an experimental transport from - * being switched on the way a supported one would be. - * - *

The named-consumer list is the third condition, enforced by {@link GraphQlRSocketProperties} - * itself. An experimental transport with no named consumer is one nobody will notice breaking, - * which is the state it must not be allowed to reach. - */ -public final class GraphQlRSocketHandlerFactory { - - private final GraphQlAdvancedFeatureFlags flags; - private final GraphQlRSocketProperties properties; - private final GraphQlRSocketRoutePolicy routes; - - /** - * @param flags which capabilities this deployment named, and whether it approved experiments - * @param properties the transport settings, including the named consumers - * @param routes which RSocket routes reach GraphQL - */ - public GraphQlRSocketHandlerFactory( - GraphQlAdvancedFeatureFlags flags, - GraphQlRSocketProperties properties, - GraphQlRSocketRoutePolicy routes) { - this.flags = Objects.requireNonNull(flags, "flags"); - this.properties = Objects.requireNonNull(properties, "properties"); - this.routes = Objects.requireNonNull(routes, "routes"); - } - - /** Whether the transport may be installed at all. */ - public boolean enabled() { - return properties.enabled() && flags.isEnabled(GraphQlAdvancedCapability.RSOCKET); - } - - /** - * The settings a handler is installed with. - * - * @throws GraphQlAdvancedCapabilityDisabledException when the capability was not named, or was - * named without experimental approval - */ - public GraphQlRSocketHandlerSettings settings() { - if (!enabled()) { - throw new GraphQlAdvancedCapabilityDisabledException( - GraphQlAdvancedCapability.RSOCKET.name()); - } - return new GraphQlRSocketHandlerSettings( - routes, properties.allowedMetadataMimeTypes(), properties.namedConsumers()); - } - - /** - * What a handler is configured with. - * - * @param routes which RSocket routes reach GraphQL - * @param allowedMetadataMimeTypes the metadata encodings accepted - * @param namedConsumers who this transport exists for - */ - public record GraphQlRSocketHandlerSettings( - GraphQlRSocketRoutePolicy routes, - Set allowedMetadataMimeTypes, - Set namedConsumers) { - - public GraphQlRSocketHandlerSettings { - Objects.requireNonNull(routes, "routes"); - allowedMetadataMimeTypes = Set.copyOf(allowedMetadataMimeTypes); - namedConsumers = Set.copyOf(namedConsumers); - if (namedConsumers.isEmpty()) { - throw new IllegalArgumentException( - "an experimental transport with no named consumer is one nobody will notice breaking"); - } - } - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/rsocket/GraphQlRSocketProperties.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/rsocket/GraphQlRSocketProperties.java deleted file mode 100644 index d4212f7e..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/rsocket/GraphQlRSocketProperties.java +++ /dev/null @@ -1,39 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.rsocket; - -import java.util.Set; - -/** - * RSocket transport configuration. - * - *

Requires a named consumer. This is an experimental transport for internal systems, and one - * that nobody is identified as using is one nobody is testing. - * - * @param enabled whether the transport is registered - * @param allowedRoutes routes that reach GraphQL - * @param allowedMetadataMimeTypes metadata MIME types accepted - * @param namedConsumers the systems that use it - */ -public record GraphQlRSocketProperties( - boolean enabled, - Set allowedRoutes, - Set allowedMetadataMimeTypes, - Set namedConsumers) { - - /** The route GraphQL is conventionally served on. */ - public static final String DEFAULT_ROUTE = "graphql"; - - public GraphQlRSocketProperties { - allowedRoutes = Set.copyOf(allowedRoutes); - allowedMetadataMimeTypes = Set.copyOf(allowedMetadataMimeTypes); - namedConsumers = Set.copyOf(namedConsumers); - if (enabled && namedConsumers.isEmpty()) { - throw new IllegalArgumentException( - "an enabled RSocket transport must name the consumers that use it"); - } - } - - /** The transport disabled. */ - public static GraphQlRSocketProperties disabled() { - return new GraphQlRSocketProperties(false, Set.of(DEFAULT_ROUTE), Set.of(), Set.of()); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/rsocket/GraphQlRSocketRoutePolicy.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/rsocket/GraphQlRSocketRoutePolicy.java deleted file mode 100644 index 1de515c7..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/rsocket/GraphQlRSocketRoutePolicy.java +++ /dev/null @@ -1,43 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.rsocket; - -import java.util.Set; - -/** - * The RSocket routes that reach GraphQL. - * - *

An allowlist rather than a prefix match: RSocket routing is string-based, and a pattern is - * exactly how an unintended handler becomes reachable. - */ -public final class GraphQlRSocketRoutePolicy { - - private final Set allowedRoutes; - - /** - * Creates the policy. - * - * @param allowedRoutes routes that reach GraphQL execution - */ - public GraphQlRSocketRoutePolicy(Set allowedRoutes) { - this.allowedRoutes = Set.copyOf(allowedRoutes); - if (this.allowedRoutes.isEmpty()) { - throw new IllegalArgumentException("at least one RSocket route is required"); - } - } - - /** - * Requires a route to be allowlisted. - * - * @throws GraphQlRSocketRouteRejectedException when it is not - */ - public String requireAllowed(String route) { - if (!allowedRoutes.contains(route)) { - throw new GraphQlRSocketRouteRejectedException(route); - } - return route; - } - - /** The allowlisted routes. */ - public Set allowedRoutes() { - return allowedRoutes; - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/rsocket/GraphQlRSocketRouteRejectedException.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/rsocket/GraphQlRSocketRouteRejectedException.java deleted file mode 100644 index b4435df9..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/rsocket/GraphQlRSocketRouteRejectedException.java +++ /dev/null @@ -1,20 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.rsocket; - -/** - * Raised when an RSocket route is not allowlisted. - * - *

Routes are the RSocket equivalent of a URL path, and an unlisted one must not reach a handler. - */ -public class GraphQlRSocketRouteRejectedException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - /** - * Creates the failure. - * - * @param route the rejected route - */ - public GraphQlRSocketRouteRejectedException(String route) { - super("RSocket route is not allowlisted: " + route); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/security/GraphQlSubscriptionAuthorizationPolicy.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/security/GraphQlSubscriptionAuthorizationPolicy.java deleted file mode 100644 index b8736d57..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/security/GraphQlSubscriptionAuthorizationPolicy.java +++ /dev/null @@ -1,28 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.security; - -/** - * When a subscription re-checks authorization (design §20). - * - *

Checking only at subscribe time is fine for a stream whose ownership cannot change. Where it - * can — a shared document, an order someone can be removed from — the check has to happen per - * event, because the connection may have been authorized hours before the event was produced. - */ -public enum GraphQlSubscriptionAuthorizationPolicy { - - /** Authorize once, when the subscription starts. */ - ON_SUBSCRIBE(false), - - /** Re-authorize before delivering each event. */ - PER_EVENT(true); - - private final boolean revalidatePerEvent; - - GraphQlSubscriptionAuthorizationPolicy(boolean revalidatePerEvent) { - this.revalidatePerEvent = revalidatePerEvent; - } - - /** Whether each event is re-authorized before delivery. */ - public boolean revalidatePerEvent() { - return revalidatePerEvent; - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/security/GraphQlWebSocketAuthenticationException.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/security/GraphQlWebSocketAuthenticationException.java deleted file mode 100644 index d0761b14..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/security/GraphQlWebSocketAuthenticationException.java +++ /dev/null @@ -1,28 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.security; - -/** - * Raised when a connection must be closed for an authentication reason. - * - *

Carries the bounded close reason and nothing from the {@code connection_init} payload. - */ -public class GraphQlWebSocketAuthenticationException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - private final transient GraphQlWebSocketCloseReason closeReason; - - /** - * Creates the failure. - * - * @param closeReason why the connection is being closed - */ - public GraphQlWebSocketAuthenticationException(GraphQlWebSocketCloseReason closeReason) { - super("GraphQL WebSocket connection closed: " + closeReason); - this.closeReason = closeReason; - } - - /** The close reason. */ - public GraphQlWebSocketCloseReason closeReason() { - return closeReason; - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/security/GraphQlWebSocketAuthenticationInterceptor.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/security/GraphQlWebSocketAuthenticationInterceptor.java deleted file mode 100644 index 80d23a69..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/security/GraphQlWebSocketAuthenticationInterceptor.java +++ /dev/null @@ -1,76 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.security; - -import java.time.Instant; -import java.util.Objects; -import java.util.Optional; - -/** - * Authenticates a connection and keeps it authenticated (Advanced plan Task 6). - * - *

The credential arrives in the {@code connection_init} payload and is never logged or measured. - * From there the identity is pinned: the connection ends when the credential expires or is revoked, - * rather than being silently refreshed — a silent refresh would mean the server decided the client - * should stay connected after the credential it presented stopped being valid. - */ -public final class GraphQlWebSocketAuthenticationInterceptor { - - private final GraphQlWebSocketRevocationSignal revocationSignal; - - /** - * Creates the interceptor. - * - * @param revocationSignal tracks actors whose access was withdrawn - */ - public GraphQlWebSocketAuthenticationInterceptor( - GraphQlWebSocketRevocationSignal revocationSignal) { - this.revocationSignal = Objects.requireNonNull(revocationSignal); - } - - /** - * Authenticates {@code connection_init}. - * - * @param principal the verified identity, or {@code null} when authentication failed - * @return the pinned principal - * @throws GraphQlWebSocketAuthenticationException when there is no verified identity - */ - public GraphQlWebSocketPrincipal onConnectionInit(GraphQlWebSocketPrincipal principal) { - if (principal == null) { - throw new GraphQlWebSocketAuthenticationException( - GraphQlWebSocketCloseReason.AUTHENTICATION_FAILED); - } - return principal; - } - - /** - * Checks whether the connection must be closed now. - * - * @param principal the pinned identity - * @param now current instant - * @return the close reason, or empty when the connection may continue - */ - public Optional closeReason( - GraphQlWebSocketPrincipal principal, Instant now) { - if (principal.expiresAt() != null - && new GraphQlWebSocketCredentialExpiry(principal.expiresAt()).isExpired(now)) { - return Optional.of(GraphQlWebSocketCloseReason.CREDENTIAL_EXPIRED); - } - if (revocationSignal.revoked(principal.actorFingerprint())) { - return Optional.of(GraphQlWebSocketCloseReason.AUTHORIZATION_REVOKED); - } - return Optional.empty(); - } - - /** - * Requires an operation to run under the connection's pinned identity. - * - * @throws GraphQlWebSocketAuthenticationException when the operation presents a different - * identity - */ - public void requirePinnedIdentity( - GraphQlWebSocketPrincipal connection, GraphQlWebSocketPrincipal operation) { - if (!connection.sameIdentity(operation)) { - throw new GraphQlWebSocketAuthenticationException( - GraphQlWebSocketCloseReason.AUTHENTICATION_FAILED); - } - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/security/GraphQlWebSocketCloseReason.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/security/GraphQlWebSocketCloseReason.java deleted file mode 100644 index 7df8d802..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/security/GraphQlWebSocketCloseReason.java +++ /dev/null @@ -1,28 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.security; - -/** - * Why a subscription connection was closed. - * - *

A bounded set, so the reason is safe as a metric label and a client can tell "your credential - * expired, reconnect" apart from "the server is going away, retry". - */ -public enum GraphQlWebSocketCloseReason { - - /** {@code connection_init} did not authenticate. */ - AUTHENTICATION_FAILED, - - /** The credential expired while the connection was open. */ - CREDENTIAL_EXPIRED, - - /** Authorization was revoked while the connection was open. */ - AUTHORIZATION_REVOKED, - - /** The server is shutting down. */ - SERVER_DRAINING, - - /** The client could not keep up with the stream. */ - SLOW_CONSUMER, - - /** The connection reached its maximum age. */ - MAXIMUM_AGE_REACHED -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/security/GraphQlWebSocketCredentialExpiry.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/security/GraphQlWebSocketCredentialExpiry.java deleted file mode 100644 index 4bfdf40c..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/security/GraphQlWebSocketCredentialExpiry.java +++ /dev/null @@ -1,26 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.security; - -import java.time.Instant; - -/** - * When a connection's credential stops being valid. - * - *

Tracked because a subscription outlives the request that opened it. Authenticating once at - * {@code connection_init} and streaming for hours means a revoked or expired credential keeps - * receiving data — the connection has to end when the credential does. - * - * @param expiresAt when the credential expires - */ -public record GraphQlWebSocketCredentialExpiry(Instant expiresAt) { - - public GraphQlWebSocketCredentialExpiry { - if (expiresAt == null) { - throw new IllegalArgumentException("credential expiry is required"); - } - } - - /** Whether the credential has expired. */ - public boolean isExpired(Instant now) { - return !now.isBefore(expiresAt); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/security/GraphQlWebSocketPrincipal.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/security/GraphQlWebSocketPrincipal.java deleted file mode 100644 index ed473824..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/security/GraphQlWebSocketPrincipal.java +++ /dev/null @@ -1,34 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.security; - -import java.time.Instant; - -/** - * The authenticated identity a connection is pinned to. - * - *

Fingerprints rather than raw identifiers, and pinned for the connection's whole life: allowing - * the tenant to change per operation on one connection would make the authenticated context - * negotiable by the client. - * - * @param actorFingerprint non-reversible actor identity - * @param tenantFingerprint non-reversible tenant identity - * @param expiresAt when the credential expires - */ -public record GraphQlWebSocketPrincipal( - String actorFingerprint, String tenantFingerprint, Instant expiresAt) { - - public GraphQlWebSocketPrincipal { - if (actorFingerprint == null || actorFingerprint.isBlank()) { - throw new IllegalArgumentException("actor fingerprint is required"); - } - if (tenantFingerprint == null || tenantFingerprint.isBlank()) { - throw new IllegalArgumentException("tenant fingerprint is required"); - } - } - - /** Whether this principal is the same identity as another. */ - public boolean sameIdentity(GraphQlWebSocketPrincipal other) { - return other != null - && actorFingerprint.equals(other.actorFingerprint) - && tenantFingerprint.equals(other.tenantFingerprint); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/security/GraphQlWebSocketRevocationSignal.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/security/GraphQlWebSocketRevocationSignal.java deleted file mode 100644 index 1c823c84..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/security/GraphQlWebSocketRevocationSignal.java +++ /dev/null @@ -1,34 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.security; - -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; - -/** - * Tracks actors whose authorization has been revoked mid-connection. - * - *

Expiry alone is not enough: a credential valid for another hour is still valid after the - * user's access is removed, and a live subscription would keep delivering until it expired. - * Revocation closes that window. - */ -public final class GraphQlWebSocketRevocationSignal { - - private final Set revokedActorFingerprints = ConcurrentHashMap.newKeySet(); - - /** Marks an actor as revoked. */ - public void revoke(String actorFingerprint) { - if (actorFingerprint == null || actorFingerprint.isBlank()) { - throw new IllegalArgumentException("actor fingerprint is required"); - } - revokedActorFingerprints.add(actorFingerprint); - } - - /** Whether an actor has been revoked. */ - public boolean revoked(String actorFingerprint) { - return actorFingerprint != null && revokedActorFingerprints.contains(actorFingerprint); - } - - /** Clears a revocation, for example after access is restored. */ - public void clear(String actorFingerprint) { - revokedActorFingerprints.remove(actorFingerprint); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/springdata/GraphQlRepositoryAllowlist.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/springdata/GraphQlRepositoryAllowlist.java deleted file mode 100644 index b9b3a45b..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/springdata/GraphQlRepositoryAllowlist.java +++ /dev/null @@ -1,116 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.springdata; - -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -/** - * The repository exposures this deployment has actually decided to publish. - * - *

Empty by default, and that is the capability's entire safety property. Spring's - * {@code @GraphQlRepository} auto-registers a data fetcher for every annotated repository it finds, - * so without an allowlist the set of exposed fields is whatever somebody annotated — which is a - * decision made in a persistence class, by whoever was working on persistence, and reviewed as a - * persistence change. - * - *

Each registration carries its own argument, pagination and projection policies rather than - * sharing global ones. A coordinate that may sort by one column is not the same as one that may - * sort by another, and a single shared policy would have to be the union. - */ -public final class GraphQlRepositoryAllowlist { - - private final Map registrations; - - private GraphQlRepositoryAllowlist(Map registrations) { - this.registrations = Map.copyOf(registrations); - } - - /** Nothing exposed. The default, and what a deployment that has not decided has. */ - public static GraphQlRepositoryAllowlist empty() { - return new GraphQlRepositoryAllowlist(Map.of()); - } - - /** A builder, because an allowlist is written once at startup and read on every schema build. */ - public static Builder builder() { - return new Builder(); - } - - /** Whether a repository is exposed at all, under any coordinate. */ - public boolean contains(String repositoryName) { - return registrations.keySet().stream().anyMatch(key -> key.startsWith(repositoryName + "@")); - } - - /** The registration for one exposure, empty when it was never registered. */ - public Optional find(GraphQlRepositoryExposure exposure) { - Objects.requireNonNull(exposure, "exposure"); - return Optional.ofNullable(registrations.get(key(exposure))); - } - - /** Every registered exposure, for the startup report. */ - public List exposures() { - return registrations.keySet().stream().sorted().toList(); - } - - /** How many exposures are registered. */ - public int size() { - return registrations.size(); - } - - private static String key(GraphQlRepositoryExposure exposure) { - return exposure.repositoryName() + "@" + exposure.schemaCoordinate(); - } - - /** - * What one exposure is permitted to do. - * - * @param exposure which repository at which coordinate - * @param arguments the filters and sorts it accepts - * @param pagination how it pages - * @param projection what it may return - */ - public record Registration( - GraphQlRepositoryExposure exposure, - GraphQlRepositoryArgumentPolicy arguments, - GraphQlRepositoryPaginationPolicy pagination, - GraphQlRepositoryProjectionPolicy projection) { - - public Registration { - Objects.requireNonNull(exposure, "exposure"); - Objects.requireNonNull(arguments, "arguments"); - Objects.requireNonNull(pagination, "pagination"); - Objects.requireNonNull(projection, "projection"); - } - } - - /** Collects registrations and refuses a duplicate coordinate. */ - public static final class Builder { - - private final Map registrations = new LinkedHashMap<>(); - - private Builder() {} - - /** Register one exposure with its three policies. */ - public Builder expose( - GraphQlRepositoryExposure exposure, - GraphQlRepositoryArgumentPolicy arguments, - GraphQlRepositoryPaginationPolicy pagination, - GraphQlRepositoryProjectionPolicy projection) { - Registration registration = new Registration(exposure, arguments, pagination, projection); - Registration previous = registrations.putIfAbsent(key(exposure), registration); - if (previous != null) { - throw new IllegalArgumentException( - "two registrations for " - + key(exposure) - + "; whichever was added last would silently decide the coordinate's limits"); - } - return this; - } - - /** Freeze it. */ - public GraphQlRepositoryAllowlist build() { - return new GraphQlRepositoryAllowlist(registrations); - } - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/springdata/GraphQlRepositoryArgumentPolicy.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/springdata/GraphQlRepositoryArgumentPolicy.java deleted file mode 100644 index f56e818b..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/springdata/GraphQlRepositoryArgumentPolicy.java +++ /dev/null @@ -1,64 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.springdata; - -import java.util.Objects; -import java.util.Set; - -/** - * Which filter and sort arguments a coordinate accepts. - * - *

The other half of the persistence-leak problem, and the half that is easier to miss. A - * query-by-example or Querydsl fetcher derives its predicate from whatever arguments arrive, so an - * un-allowlisted argument set means the client writes the {@code WHERE} clause — including over - * columns the schema never published, because the binder resolves against the entity rather than - * against the GraphQL type. - * - *

Sort is allowlisted separately from filter. They read alike and behave differently under load: - * a filter on an unindexed column is one slow query, and a sort on one is a full sort of the table - * on every page. - */ -public final class GraphQlRepositoryArgumentPolicy { - - private final Set filterableFields; - private final Set sortableFields; - - /** - * @param filterableFields the arguments that may narrow the result - * @param sortableFields the fields that may order it - */ - public GraphQlRepositoryArgumentPolicy(Set filterableFields, Set sortableFields) { - this.filterableFields = - Set.copyOf(Objects.requireNonNull(filterableFields, "filterableFields")); - this.sortableFields = Set.copyOf(Objects.requireNonNull(sortableFields, "sortableFields")); - } - - /** A coordinate that accepts no filter and no sort. */ - public static GraphQlRepositoryArgumentPolicy none() { - return new GraphQlRepositoryArgumentPolicy(Set.of(), Set.of()); - } - - /** Whether a filter argument is permitted. */ - public boolean filterable(String field) { - return field != null && filterableFields.contains(field); - } - - /** Whether a sort field is permitted. */ - public boolean sortable(String field) { - return field != null && sortableFields.contains(field); - } - - /** - * The arguments a request used that this coordinate does not accept. - * - *

All of them, not the first: a caller fixing a query should not discover the rejections one - * round trip at a time. - */ - public java.util.List reject(Set filters, Set sorts) { - Objects.requireNonNull(filters, "filters"); - Objects.requireNonNull(sorts, "sorts"); - return java.util.stream.Stream.concat( - filters.stream().filter(field -> !filterable(field)).map(field -> "filter:" + field), - sorts.stream().filter(field -> !sortable(field)).map(field -> "sort:" + field)) - .sorted() - .toList(); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/springdata/GraphQlRepositoryExposure.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/springdata/GraphQlRepositoryExposure.java deleted file mode 100644 index cbeb9cf4..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/springdata/GraphQlRepositoryExposure.java +++ /dev/null @@ -1,28 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.springdata; - -import java.util.Objects; - -/** - * One repository offered at one schema coordinate. - * - *

The pair, never the repository alone. Spring's {@code @GraphQlRepository} binds a repository - * to whatever coordinate its return type matches, so the same repository reached from {@code - * Query.orders} and from {@code Query.allOrders} is two exposures with two different audiences — - * and an allowlist keyed only on the repository would authorise both from one decision. - * - * @param repositoryName the repository bean's name - * @param schemaCoordinate the {@code Type.field} it answers - */ -public record GraphQlRepositoryExposure(String repositoryName, String schemaCoordinate) { - - public GraphQlRepositoryExposure { - Objects.requireNonNull(repositoryName, "repositoryName"); - Objects.requireNonNull(schemaCoordinate, "schemaCoordinate"); - if (repositoryName.isBlank() || schemaCoordinate.isBlank()) { - throw new IllegalArgumentException("an exposure names a repository and a coordinate"); - } - if (schemaCoordinate.indexOf('.') < 1) { - throw new IllegalArgumentException("a schema coordinate is Type.field: " + schemaCoordinate); - } - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/springdata/GraphQlRepositoryExposureRejectedException.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/springdata/GraphQlRepositoryExposureRejectedException.java deleted file mode 100644 index 40ed568c..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/springdata/GraphQlRepositoryExposureRejectedException.java +++ /dev/null @@ -1,27 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.springdata; - -import java.util.Objects; - -/** - * A repository was about to be exposed as a data fetcher without being registered for it. - * - *

Raised at startup rather than at query time. An unregistered exposure that only failed when - * somebody queried it would be a schema field that exists, appears in introspection, and errors — - * which is worse than one that was never published. - */ -public final class GraphQlRepositoryExposureRejectedException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - private final transient String repositoryName; - - public GraphQlRepositoryExposureRejectedException(String repositoryName, String reason) { - super("repository exposure refused for '" + repositoryName + "': " + reason); - this.repositoryName = Objects.requireNonNull(repositoryName, "repositoryName"); - } - - /** Which repository. */ - public String repositoryName() { - return repositoryName; - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/springdata/GraphQlRepositoryExposureValidator.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/springdata/GraphQlRepositoryExposureValidator.java deleted file mode 100644 index fc7e17f2..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/springdata/GraphQlRepositoryExposureValidator.java +++ /dev/null @@ -1,88 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.springdata; - -import java.util.List; -import java.util.Objects; -import java.util.Set; - -/** - * Refuses a repository exposure the deployment did not register. - * - *

Runs at schema build, not at query time. An unregistered exposure that only failed when - * somebody queried it would be a field that exists, appears in introspection and errors — which is - * worse than one that was never published, because a client has already written code against it. - * - *

This whole capability is a compatibility path and is documented as one. It exists so an - * existing Spring Data GraphQL application can be brought onto this platform without rewriting - * every fetcher on day one; it is not the mainstream way to serve a field here, and a coordinate - * that stays on it indefinitely is a coordinate whose application-service boundary was never - * written. - */ -public final class GraphQlRepositoryExposureValidator { - - private final GraphQlRepositoryAllowlist allowlist; - - public GraphQlRepositoryExposureValidator(GraphQlRepositoryAllowlist allowlist) { - this.allowlist = Objects.requireNonNull(allowlist, "allowlist"); - } - - /** - * Require an exposure to be registered. - * - * @throws GraphQlRepositoryExposureRejectedException when it is not - */ - public GraphQlRepositoryAllowlist.Registration verify(GraphQlRepositoryExposure exposure) { - Objects.requireNonNull(exposure, "exposure"); - return allowlist - .find(exposure) - .orElseThrow( - () -> - new GraphQlRepositoryExposureRejectedException( - exposure.repositoryName(), - "no registration for coordinate " - + exposure.schemaCoordinate() - + "; a repository is exposed by a deployment decision, not by an" - + " annotation on a persistence class")); - } - - /** - * Check one request against the coordinate's registered limits. - * - * @param exposure which repository at which coordinate - * @param filters the filter arguments the request used - * @param sorts the sort fields it used - * @param pageSize the page size it asked for - * @param returnTypeName the type the fetcher would return - * @throws GraphQlRepositoryExposureRejectedException naming every violation at once - */ - public void verifyRequest( - GraphQlRepositoryExposure exposure, - Set filters, - Set sorts, - int pageSize, - String returnTypeName) { - GraphQlRepositoryAllowlist.Registration registration = verify(exposure); - List refused = - new java.util.ArrayList<>(registration.arguments().reject(filters, sorts)); - if (!registration.pagination().permits(pageSize)) { - refused.add("page size " + pageSize + " exceeds " + registration.pagination().maxPageSize()); - } - if (!registration.projection().permits(returnTypeName)) { - // The one that keeps this from becoming a database export. Returning the entity publishes - // every column and makes a rename in the database a breaking change for every client. - refused.add( - "return type " - + returnTypeName - + " is not an approved projection; returning the entity publishes the persistence" - + " model as an API"); - } - if (!refused.isEmpty()) { - throw new GraphQlRepositoryExposureRejectedException( - exposure.repositoryName(), String.join("; ", refused)); - } - } - - /** Whether the deployment has exposed anything at all. */ - public boolean anyExposure() { - return allowlist.size() > 0; - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/springdata/GraphQlRepositoryPaginationPolicy.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/springdata/GraphQlRepositoryPaginationPolicy.java deleted file mode 100644 index 04df7a25..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/springdata/GraphQlRepositoryPaginationPolicy.java +++ /dev/null @@ -1,35 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.springdata; - -/** - * How many rows one coordinate may return, and how they are addressed. - * - *

Explicit, never inherited. Spring Data's GraphQL integration defaults to offset pagination - * with a page size of twenty, and a default is exactly what nobody reviews: a field that quietly - * serves twenty rows is fine until the client asks for the offset at row four hundred thousand, at - * which point the database is sorting the whole table to skip it. - * - *

Keyset is the recommended shape and the policy says which one is in use, because the two have - * different failure modes and an operator reading a slow query needs to know which they are looking - * at. - * - * @param keyset whether the coordinate pages by cursor rather than by offset - * @param maxPageSize the largest page a caller may request - */ -public record GraphQlRepositoryPaginationPolicy(boolean keyset, int maxPageSize) { - - public GraphQlRepositoryPaginationPolicy { - if (maxPageSize < 1) { - throw new IllegalArgumentException("a page of nothing is not a page"); - } - if (maxPageSize > 200) { - throw new IllegalArgumentException( - "a page above 200 rows makes one query a bulk export; if that is the intent it belongs" - + " on an endpoint that was designed for it"); - } - } - - /** Whether a requested page size is permitted. */ - public boolean permits(int requested) { - return requested >= 1 && requested <= maxPageSize; - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/springdata/GraphQlRepositoryProjectionPolicy.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/springdata/GraphQlRepositoryProjectionPolicy.java deleted file mode 100644 index f5c89328..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/springdata/GraphQlRepositoryProjectionPolicy.java +++ /dev/null @@ -1,57 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.springdata; - -import java.util.Objects; -import java.util.Set; - -/** - * Which projection types a coordinate may return. - * - *

The rule that keeps this compatibility path from becoming a persistence-model export. Spring - * Data's integration will happily return the entity, and an entity returned from GraphQL is the - * database schema published as an API — every column, every relation the fetch plan happens to - * traverse, and a rename in the database becoming a breaking change for every client. - * - *

So the entity type itself is refused by name, and only an approved projection is allowed. - */ -public final class GraphQlRepositoryProjectionPolicy { - - private final Set approvedProjections; - private final Set forbiddenEntityTypes; - - /** - * @param approvedProjections the projection interfaces or records that may be returned - * @param forbiddenEntityTypes the persistence types that may never be - */ - public GraphQlRepositoryProjectionPolicy( - Set approvedProjections, Set forbiddenEntityTypes) { - this.approvedProjections = - Set.copyOf(Objects.requireNonNull(approvedProjections, "approvedProjections")); - this.forbiddenEntityTypes = - Set.copyOf(Objects.requireNonNull(forbiddenEntityTypes, "forbiddenEntityTypes")); - if (this.approvedProjections.isEmpty()) { - throw new IllegalArgumentException( - "a coordinate with no approved projection can only return the entity, which is the one" - + " thing this policy exists to prevent"); - } - Set both = - this.approvedProjections.stream() - .filter(this.forbiddenEntityTypes::contains) - .collect(java.util.stream.Collectors.toUnmodifiableSet()); - if (!both.isEmpty()) { - throw new IllegalArgumentException( - "a type cannot be both an approved projection and a forbidden entity: " + both); - } - } - - /** Whether a return type may be served. */ - public boolean permits(String returnTypeName) { - return returnTypeName != null - && !forbiddenEntityTypes.contains(returnTypeName) - && approvedProjections.contains(returnTypeName); - } - - /** The approved projections, for the startup report. */ - public Set approvedProjections() { - return approvedProjections; - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/sse/GraphQlSseAdmission.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/sse/GraphQlSseAdmission.java deleted file mode 100644 index 710fb5ef..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/sse/GraphQlSseAdmission.java +++ /dev/null @@ -1,63 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.sse; - -import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedCapability; -import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedModuleGuard; -import dev.caskeleton.adapter.inbound.graphql.http.GraphQlMediaTypes; -import java.time.Clock; -import java.util.Objects; - -/** - * Decides whether an SSE stream may be opened, and issues its heartbeat schedule if so. - * - *

Admission, not a handler: what it returns is a {@link GraphQlSseHeartbeat} and a {@link - * GraphQlSseTermination}, both plain schedules. Nothing here writes an event to a response — the - * runtime that owns the response does that, using these bounds. - * - *

The request shape is a POST with a JSON body and {@code Accept: text/event-stream} — the same - * request envelope as every other transport, with a streaming response. Authorization and cost - * policy are the WebSocket ones; only the delivery mechanism differs. - */ -public final class GraphQlSseAdmission { - - /** The {@code Accept} value that selects SSE. */ - public static final String EVENT_STREAM_MEDIA_TYPE = "text/event-stream"; - - private final GraphQlAdvancedModuleGuard guard; - private final GraphQlSseProperties properties; - private final Clock clock; - - /** - * Creates the factory. - * - * @param guard the Advanced capability guard - * @param properties connection bounds - * @param clock clock used for heartbeats and termination - */ - public GraphQlSseAdmission( - GraphQlAdvancedModuleGuard guard, GraphQlSseProperties properties, Clock clock) { - this.guard = Objects.requireNonNull(guard); - this.properties = Objects.requireNonNull(properties); - this.clock = Objects.requireNonNull(clock); - } - - /** - * Opens an SSE stream for a subscription. - * - * @param operationType the operation type the client asked for - * @param contentType the request content type - * @throws GraphQlSseRejectedException when the request is outside the SSE profile - */ - public GraphQlSseHeartbeat open(String operationType, String contentType) { - guard.requireEnabled(GraphQlAdvancedCapability.SSE_SUBSCRIPTION); - GraphQlSseConnectionPolicy.standard().requireSubscription(operationType); - if (!GraphQlMediaTypes.acceptableRequestContentType(contentType)) { - throw new GraphQlSseRejectedException("SSE requests use an application/json body"); - } - return new GraphQlSseHeartbeat(properties.heartbeatInterval(), clock.instant()); - } - - /** The termination check for a stream opened now. */ - public GraphQlSseTermination termination() { - return new GraphQlSseTermination(properties, clock.instant()); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/sse/GraphQlSseConnectionPolicy.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/sse/GraphQlSseConnectionPolicy.java deleted file mode 100644 index 2da657dd..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/sse/GraphQlSseConnectionPolicy.java +++ /dev/null @@ -1,50 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.sse; - -/** - * What SSE may be used for (design §20). - * - *

Subscriptions only. Spring's SSE support is a distinct-connection mode — one HTTP connection - * per subscription — which suits a server-to-client stream and is a poor fit for a query, where the - * client is paying for a streaming connection to receive one response. - */ -public final class GraphQlSseConnectionPolicy { - - /** The only operation type SSE serves. */ - public static final String SUPPORTED_OPERATION_TYPE = "subscription"; - - private GraphQlSseConnectionPolicy() {} - - /** The standard policy. */ - public static GraphQlSseConnectionPolicy standard() { - return new GraphQlSseConnectionPolicy(); - } - - /** Whether SSE serves this operation type. */ - public boolean supports(String operationType) { - return SUPPORTED_OPERATION_TYPE.equals(operationType); - } - - /** - * Requires the operation to be a subscription. - * - * @throws GraphQlSseRejectedException for a query or mutation - */ - public void requireSubscription(String operationType) { - if (!supports(operationType)) { - throw new GraphQlSseRejectedException("SSE serves subscription operations only"); - } - } - - /** - * How many HTTP connections a client needs for a number of subscriptions. - * - *

One each: unlike WebSocket, SSE does not multiplex, and that is the number capacity planning - * has to use. - */ - public int connectionsRequiredFor(int subscriptions) { - if (subscriptions < 0) { - throw new IllegalArgumentException("subscription count cannot be negative"); - } - return subscriptions; - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/sse/GraphQlSseHandlerFactory.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/sse/GraphQlSseHandlerFactory.java deleted file mode 100644 index 3ab7536e..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/sse/GraphQlSseHandlerFactory.java +++ /dev/null @@ -1,95 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.sse; - -import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedCapability; -import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedCapabilityDisabledException; -import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedFeatureFlags; -import java.time.Duration; -import java.util.Objects; - -/** - * Decides whether the SSE subscription transport may exist, and on what terms. - * - *

SSE here is the Distinct Connection variant of the GraphQL-over-HTTP specification: one POST - * per subscription, each holding its own connection for as long as the subscription lives. That is - * the property worth stating at the factory, because it is the one that surprises people — {@code - * graphql-transport-ws} multiplexes many subscriptions onto one socket and this does not, so a - * client with twenty subscriptions holds twenty connections and a browser's six-per-origin limit is - * reached at six. - * - *

{@link GraphQlSseConnectionPolicy#connectionsRequiredFor(int)} is the arithmetic; this is - * where the transport is refused if the capability was not named. - */ -public final class GraphQlSseHandlerFactory { - - private final GraphQlAdvancedFeatureFlags flags; - private final GraphQlSseProperties properties; - private final GraphQlSseConnectionPolicy policy; - - /** - * @param flags which capabilities this deployment named - * @param properties the connection bounds - * @param policy what the transport may carry - */ - public GraphQlSseHandlerFactory( - GraphQlAdvancedFeatureFlags flags, - GraphQlSseProperties properties, - GraphQlSseConnectionPolicy policy) { - this.flags = Objects.requireNonNull(flags, "flags"); - this.properties = Objects.requireNonNull(properties, "properties"); - this.policy = Objects.requireNonNull(policy, "policy"); - } - - /** Whether the transport may be installed at all. */ - public boolean enabled() { - return flags.isEnabled(GraphQlAdvancedCapability.SSE_SUBSCRIPTION); - } - - /** - * The settings a handler is installed with. - * - * @throws GraphQlAdvancedCapabilityDisabledException when the capability was not named - */ - public GraphQlSseHandlerSettings settings() { - if (!enabled()) { - throw new GraphQlAdvancedCapabilityDisabledException( - GraphQlAdvancedCapability.SSE_SUBSCRIPTION.name()); - } - return new GraphQlSseHandlerSettings( - properties.heartbeatInterval(), - properties.idleTimeout(), - properties.maximumDuration(), - policy); - } - - /** - * How many connections a client running this many subscriptions will hold. - * - *

Exposed on the factory so a deployment can answer the question before enabling the transport - * rather than after a support ticket about a browser that stopped loading images. - */ - public int connectionsRequiredFor(int subscriptions) { - return policy.connectionsRequiredFor(subscriptions); - } - - /** - * What a handler is configured with. - * - * @param heartbeatInterval how often a keepalive is written - * @param idleTimeout how long a silent connection is held - * @param maximumDuration the ceiling regardless of activity - * @param policy what the transport may carry - */ - public record GraphQlSseHandlerSettings( - Duration heartbeatInterval, - Duration idleTimeout, - Duration maximumDuration, - GraphQlSseConnectionPolicy policy) { - - public GraphQlSseHandlerSettings { - Objects.requireNonNull(heartbeatInterval, "heartbeatInterval"); - Objects.requireNonNull(idleTimeout, "idleTimeout"); - Objects.requireNonNull(maximumDuration, "maximumDuration"); - Objects.requireNonNull(policy, "policy"); - } - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/sse/GraphQlSseHeartbeat.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/sse/GraphQlSseHeartbeat.java deleted file mode 100644 index abb47e21..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/sse/GraphQlSseHeartbeat.java +++ /dev/null @@ -1,44 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.sse; - -import java.time.Duration; -import java.time.Instant; -import java.util.Objects; - -/** - * Decides when a keep-alive frame is due. - * - *

Measured from the last write of any kind, so a busy stream never sends redundant heartbeats - * and a quiet one is kept open through intermediaries that would otherwise time it out. - */ -public final class GraphQlSseHeartbeat { - - /** The SSE comment frame used as a keep-alive. */ - public static final String KEEP_ALIVE_FRAME = ":keep-alive\n\n"; - - private final Duration interval; - private Instant lastWriteAt; - - /** - * Creates the heartbeat. - * - * @param interval how often a keep-alive is due - * @param startedAt when the connection opened - */ - public GraphQlSseHeartbeat(Duration interval, Instant startedAt) { - if (interval == null || interval.isZero() || interval.isNegative()) { - throw new IllegalArgumentException("heartbeat interval must be positive"); - } - this.interval = interval; - this.lastWriteAt = Objects.requireNonNull(startedAt); - } - - /** Records that something was written to the client. */ - public void recordWrite(Instant at) { - lastWriteAt = at; - } - - /** Whether a keep-alive frame is due. */ - public boolean due(Instant now) { - return !now.isBefore(lastWriteAt.plus(interval)); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/sse/GraphQlSseProperties.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/sse/GraphQlSseProperties.java deleted file mode 100644 index 4d9f6914..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/sse/GraphQlSseProperties.java +++ /dev/null @@ -1,40 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.sse; - -import java.time.Duration; - -/** - * Bounds on an SSE connection. - * - *

The heartbeat is not decoration: proxies and load balancers close idle connections, and - * without a periodic comment frame a quiet subscription is dropped by infrastructure the - * application never sees. - * - * @param heartbeatInterval how often a keep-alive frame is written - * @param idleTimeout how long a connection may stay silent - * @param maximumDuration how long any connection may live - */ -public record GraphQlSseProperties( - Duration heartbeatInterval, Duration idleTimeout, Duration maximumDuration) { - - public GraphQlSseProperties { - requirePositive(heartbeatInterval, "heartbeatInterval"); - requirePositive(idleTimeout, "idleTimeout"); - requirePositive(maximumDuration, "maximumDuration"); - if (heartbeatInterval.compareTo(idleTimeout) >= 0) { - throw new IllegalArgumentException( - "the heartbeat must be shorter than the idle timeout or the connection times out between beats"); - } - } - - /** Conservative defaults. */ - public static GraphQlSseProperties defaults() { - return new GraphQlSseProperties( - Duration.ofSeconds(15), Duration.ofMinutes(1), Duration.ofHours(1)); - } - - private static void requirePositive(Duration value, String name) { - if (value == null || value.isZero() || value.isNegative()) { - throw new IllegalArgumentException(name + " must be positive"); - } - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/sse/GraphQlSseRejectedException.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/sse/GraphQlSseRejectedException.java deleted file mode 100644 index 85484dea..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/sse/GraphQlSseRejectedException.java +++ /dev/null @@ -1,21 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.sse; - -/** - * Raised when an SSE request is outside the supported profile. - * - *

Explicit, because silently serving a query over SSE would hand the client a streaming - * connection for a single response and quietly change the endpoint's capacity model. - */ -public class GraphQlSseRejectedException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - /** - * Creates the failure. - * - * @param reason bounded description - */ - public GraphQlSseRejectedException(String reason) { - super(reason); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/sse/GraphQlSseTermination.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/sse/GraphQlSseTermination.java deleted file mode 100644 index 52ce6c87..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/sse/GraphQlSseTermination.java +++ /dev/null @@ -1,54 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.sse; - -import dev.caskeleton.adapter.inbound.graphql.advanced.subscription.GraphQlSubscriptionTermination; -import java.time.Duration; -import java.time.Instant; -import java.util.Optional; - -/** - * Decides when an SSE connection must end. - * - *

The same termination vocabulary as WebSocket, so an operator reads one set of reasons - * regardless of which transport a client used. - */ -public final class GraphQlSseTermination { - - private final GraphQlSseProperties properties; - private final Instant startedAt; - - /** - * Creates the termination check. - * - * @param properties connection bounds - * @param startedAt when the connection opened - */ - public GraphQlSseTermination(GraphQlSseProperties properties, Instant startedAt) { - if (properties == null || startedAt == null) { - throw new IllegalArgumentException("SSE properties and start instant are required"); - } - this.properties = properties; - this.startedAt = startedAt; - } - - /** - * Whether the connection must end. - * - * @param now current instant - * @param lastEventAt when the last event was delivered - * @return the termination reason, or empty when it may continue - */ - public Optional terminationReason( - Instant now, Instant lastEventAt) { - if (elapsed(now, startedAt, properties.maximumDuration())) { - return Optional.of(GraphQlSubscriptionTermination.SERVER_DRAINING); - } - if (elapsed(now, lastEventAt, properties.idleTimeout())) { - return Optional.of(GraphQlSubscriptionTermination.COMPLETED); - } - return Optional.empty(); - } - - private static boolean elapsed(Instant now, Instant since, Duration limit) { - return !now.isBefore(since.plus(limit)); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/subscription/GraphQlSlowConsumerPolicy.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/subscription/GraphQlSlowConsumerPolicy.java deleted file mode 100644 index 470ec42e..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/subscription/GraphQlSlowConsumerPolicy.java +++ /dev/null @@ -1,17 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.subscription; - -/** - * What to do when a client cannot keep up (design §20). - * - *

Terminating is the default because GraphQL has no replay: a dropped event is simply gone, and - * the client has no way to learn that it missed one. Dropping is only acceptable where losing an - * event is genuinely harmless — telemetry, presence — and that has to be an explicit choice. - */ -public enum GraphQlSlowConsumerPolicy { - - /** Close the subscription rather than lose events silently. */ - TERMINATE, - - /** Drop events, for telemetry-style streams where loss is acceptable. */ - DROP_ALLOWED_FOR_TELEMETRY -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/subscription/GraphQlSubscriptionBufferPolicy.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/subscription/GraphQlSubscriptionBufferPolicy.java deleted file mode 100644 index 25af4ae5..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/subscription/GraphQlSubscriptionBufferPolicy.java +++ /dev/null @@ -1,32 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.subscription; - -/** - * Bounds on what one subscription may buffer. - * - *

Bounded in both events and bytes, because a slow consumer is a memory leak with a schedule: - * the source keeps producing, the socket keeps not draining, and the buffer grows until the process - * dies. Which of the two limits binds first depends on whether the events are many or large. - * - * @param maximumBufferedEvents events that may queue for one subscription - * @param maximumBufferedBytes bytes that may queue for one subscription - * @param slowConsumerPolicy what to do when a limit is reached - */ -public record GraphQlSubscriptionBufferPolicy( - int maximumBufferedEvents, - long maximumBufferedBytes, - GraphQlSlowConsumerPolicy slowConsumerPolicy) { - - public GraphQlSubscriptionBufferPolicy { - if (maximumBufferedEvents < 1 || maximumBufferedBytes < 1) { - throw new IllegalArgumentException("subscription buffer bounds must be positive"); - } - if (slowConsumerPolicy == null) { - throw new IllegalArgumentException("slow consumer policy is required"); - } - } - - /** The default: bounded buffer, terminate rather than drop. */ - public static GraphQlSubscriptionBufferPolicy defaultPolicy() { - return new GraphQlSubscriptionBufferPolicy(128, 1_048_576, GraphQlSlowConsumerPolicy.TERMINATE); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/subscription/GraphQlSubscriptionCancellation.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/subscription/GraphQlSubscriptionCancellation.java deleted file mode 100644 index 7b30a041..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/subscription/GraphQlSubscriptionCancellation.java +++ /dev/null @@ -1,40 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.subscription; - -import dev.caskeleton.adapter.inbound.graphql.execution.GraphQlCancellation; - -/** - * Propagates cancellation from the client to the source. - * - *

An unsubscribed client whose upstream keeps running is the expensive failure here: the Kafka - * consumer, the polling task and the nested publishers all continue for a subscriber that has gone, - * and nothing in the request path notices. - * - *

The signal itself is {@link GraphQlCancellation}, not a second copy of it. There used to be - * two one-way cancellation state machines in this platform with the same queue, the same flag and - * the same late-registration rule, which is two places for the run-every-hook guarantee to be - * correct in — and it was correct in one of them. Whatever the request path guarantees, a - * subscription now guarantees by construction: every hook runs exactly once, one that throws does - * not stop the rest, and the first failure carries the later ones as suppressed. - */ -public final class GraphQlSubscriptionCancellation { - - private final GraphQlCancellation cancellation = GraphQlCancellation.create(); - - /** Registers upstream work to stop on cancellation. */ - public void onCancel(Runnable stopUpstream) { - if (stopUpstream == null) { - throw new IllegalArgumentException("upstream cancellation hook is required"); - } - cancellation.onCancel(stopUpstream); - } - - /** Cancels the subscription and everything upstream of it. */ - public void cancel() { - cancellation.cancel(); - } - - /** Whether the subscription has been cancelled. */ - public boolean cancelled() { - return cancellation.cancelled(); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/subscription/GraphQlSubscriptionContext.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/subscription/GraphQlSubscriptionContext.java deleted file mode 100644 index 26b19a50..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/subscription/GraphQlSubscriptionContext.java +++ /dev/null @@ -1,35 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.subscription; - -import dev.caskeleton.adapter.inbound.graphql.advanced.security.GraphQlSubscriptionAuthorizationPolicy; -import dev.caskeleton.adapter.inbound.graphql.advanced.security.GraphQlWebSocketPrincipal; -import dev.caskeleton.adapter.inbound.graphql.api.GraphQlOperationName; - -/** - * The context one subscription streams under. - * - *

Carries the pinned principal, so every event is produced for the identity that subscribed and - * not for whoever the connection last saw. - * - * @param operationName the subscription operation - * @param principal the connection's pinned identity - * @param authorizationPolicy when authorization is re-checked - * @param bufferPolicy what this subscription may buffer - */ -public record GraphQlSubscriptionContext( - GraphQlOperationName operationName, - GraphQlWebSocketPrincipal principal, - GraphQlSubscriptionAuthorizationPolicy authorizationPolicy, - GraphQlSubscriptionBufferPolicy bufferPolicy) { - - public GraphQlSubscriptionContext { - if (operationName == null || principal == null) { - throw new IllegalArgumentException("subscription operation and principal are required"); - } - authorizationPolicy = - authorizationPolicy == null - ? GraphQlSubscriptionAuthorizationPolicy.ON_SUBSCRIBE - : authorizationPolicy; - bufferPolicy = - bufferPolicy == null ? GraphQlSubscriptionBufferPolicy.defaultPolicy() : bufferPolicy; - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/subscription/GraphQlSubscriptionDispatcher.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/subscription/GraphQlSubscriptionDispatcher.java deleted file mode 100644 index 7023adad..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/subscription/GraphQlSubscriptionDispatcher.java +++ /dev/null @@ -1,74 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.subscription; - -import java.util.Objects; -import java.util.Optional; - -/** - * Applies the buffer policy to one subscription's delivery (Advanced plan Task 7). - * - *

Tracks what is queued and decides, at the moment a limit is reached, whether to terminate or - * drop. Doing this explicitly is what keeps a slow consumer from becoming unbounded memory, and - * what makes the decision visible instead of implicit in a transport's buffering. - */ -public final class GraphQlSubscriptionDispatcher { - - private final GraphQlSubscriptionBufferPolicy policy; - private int bufferedEvents; - private long bufferedBytes; - private long droppedEvents; - - /** - * Creates the dispatcher. - * - * @param policy the subscription's buffer bounds - */ - public GraphQlSubscriptionDispatcher(GraphQlSubscriptionBufferPolicy policy) { - this.policy = Objects.requireNonNull(policy); - } - - /** - * Offers an event for delivery. - * - * @param event the translated event - * @return a termination reason when the subscription must stop, or empty when it may continue - */ - public Optional offer(GraphQlSubscriptionEvent event) { - long bytes = event.approximateBytes(); - boolean wouldExceed = - bufferedEvents + 1 > policy.maximumBufferedEvents() - || bufferedBytes + bytes > policy.maximumBufferedBytes(); - - if (wouldExceed) { - if (policy.slowConsumerPolicy() == GraphQlSlowConsumerPolicy.TERMINATE) { - return Optional.of(GraphQlSubscriptionTermination.SLOW_CONSUMER); - } - droppedEvents++; - return Optional.empty(); - } - - bufferedEvents++; - bufferedBytes += bytes; - return Optional.empty(); - } - - /** Records that an event was written to the client. */ - public void acknowledge(GraphQlSubscriptionEvent event) { - bufferedEvents = Math.max(0, bufferedEvents - 1); - bufferedBytes = Math.max(0, bufferedBytes - event.approximateBytes()); - } - - /** Events currently queued. */ - public int bufferedEvents() { - return bufferedEvents; - } - - /** Bytes currently queued. */ - public long bufferedBytes() { - return bufferedBytes; - } - - /** Events dropped, which is non-zero only under the telemetry policy. */ - public long droppedEvents() { - return droppedEvents; - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/subscription/GraphQlSubscriptionDrainCoordinator.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/subscription/GraphQlSubscriptionDrainCoordinator.java deleted file mode 100644 index 75e1853d..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/subscription/GraphQlSubscriptionDrainCoordinator.java +++ /dev/null @@ -1,143 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.subscription; - -import java.time.Duration; -import java.time.Instant; -import java.util.Objects; -import java.util.concurrent.atomic.AtomicReference; - -/** - * Graceful shutdown for long-lived subscriptions. - * - *

Draining rather than closing: dropping thousands of subscriptions at once produces a reconnect - * storm against an instance that is already leaving. New subscriptions are refused immediately, - * existing ones get a bounded window to finish, and the window has a deadline so a stuck stream - * cannot delay shutdown forever. - * - *

Phase, count and drain start move together as one immutable value behind a single - * compare-and-set, because they are one fact and not three. Held apart they raced in both - * directions: a subscription that passed the "not draining" check and then incremented the count - * was admitted onto a node that had begun draining in between, and a reader that saw the draining - * flag before the separate {@code drainStartedAt} field was written computed the deadline against - * {@code null}. Shutdown is exactly when both happen, and exactly when neither is easy to see. - */ -public final class GraphQlSubscriptionDrainCoordinator { - - /** - * The whole coordinator state, replaced atomically. - * - * @param phase where the node is in its lifetime - * @param active subscriptions currently streaming - * @param startedAt when draining began; non-null whenever the phase is not {@code ACCEPTING} - */ - private record State(GraphQlSubscriptionDrainPhase phase, int active, Instant startedAt) {} - - private static final State OPEN = new State(GraphQlSubscriptionDrainPhase.ACCEPTING, 0, null); - - private final Duration drainTimeout; - private final AtomicReference state = new AtomicReference<>(OPEN); - - /** - * Creates the coordinator. - * - * @param drainTimeout how long existing subscriptions may take to finish - */ - public GraphQlSubscriptionDrainCoordinator(Duration drainTimeout) { - if (drainTimeout == null || drainTimeout.isNegative()) { - throw new IllegalArgumentException("drain timeout must not be negative"); - } - this.drainTimeout = drainTimeout; - } - - /** - * Registers a new subscription and returns its lease. - * - *

The admission decision and the count increment are the same compare-and-set, so a - * subscription is never admitted onto a node that started draining between the two. - * - * @return the lease to close when the subscription ends - * @throws GraphQlSubscriptionDrainingException while draining or once closed - */ - public GraphQlSubscriptionLease register() { - while (true) { - State current = state.get(); - if (current.phase() != GraphQlSubscriptionDrainPhase.ACCEPTING) { - throw new GraphQlSubscriptionDrainingException(); - } - State next = new State(current.phase(), current.active() + 1, current.startedAt()); - if (state.compareAndSet(current, next)) { - return new GraphQlSubscriptionLease(this); - } - } - } - - /** - * Starts draining; no new subscriptions are accepted from here. - * - *

Idempotent: a second call keeps the original start instant, so a shutdown hook that fires - * twice cannot extend the window it is supposed to bound. - * - * @param now the instant draining began - */ - public void startDraining(Instant now) { - Objects.requireNonNull(now, "drain start instant is required"); - while (true) { - State current = state.get(); - if (current.phase() != GraphQlSubscriptionDrainPhase.ACCEPTING) { - return; - } - GraphQlSubscriptionDrainPhase next = - current.active() == 0 - ? GraphQlSubscriptionDrainPhase.CLOSED - : GraphQlSubscriptionDrainPhase.DRAINING; - if (state.compareAndSet(current, new State(next, current.active(), now))) { - return; - } - } - } - - /** - * Whether every subscription has finished, or the drain window has elapsed. - * - * @param now the current instant - */ - public boolean drained(Instant now) { - Objects.requireNonNull(now, "current instant is required"); - State current = state.get(); - return switch (current.phase()) { - case ACCEPTING -> false; - case CLOSED -> true; - case DRAINING -> - current.active() == 0 || !now.isBefore(current.startedAt().plus(drainTimeout)); - }; - } - - /** Subscriptions still streaming. */ - public int activeSubscriptions() { - return state.get().active(); - } - - /** Whether the coordinator has stopped accepting new subscriptions. */ - public boolean draining() { - return state.get().phase() != GraphQlSubscriptionDrainPhase.ACCEPTING; - } - - /** Where the node is in its subscription lifetime. */ - public GraphQlSubscriptionDrainPhase phase() { - return state.get().phase(); - } - - /** Releases one lease; called by {@link GraphQlSubscriptionLease#close()}. */ - void release() { - while (true) { - State current = state.get(); - int remaining = Math.max(0, current.active() - 1); - GraphQlSubscriptionDrainPhase next = - current.phase() == GraphQlSubscriptionDrainPhase.DRAINING && remaining == 0 - ? GraphQlSubscriptionDrainPhase.CLOSED - : current.phase(); - if (state.compareAndSet(current, new State(next, remaining, current.startedAt()))) { - return; - } - } - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/subscription/GraphQlSubscriptionDrainPhase.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/subscription/GraphQlSubscriptionDrainPhase.java deleted file mode 100644 index 1e42eb3c..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/subscription/GraphQlSubscriptionDrainPhase.java +++ /dev/null @@ -1,20 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.subscription; - -/** - * Where a node is in its subscription lifetime. - * - *

Three phases rather than a boolean, because "draining" and "finished draining" are different - * answers to the shutdown question and a boolean can only carry one of them. The transitions are - * one-way: a node that has started draining never accepts again, and a closed one never reopens. - */ -public enum GraphQlSubscriptionDrainPhase { - - /** New subscriptions are admitted. */ - ACCEPTING, - - /** New subscriptions are refused; existing ones have a bounded window to finish. */ - DRAINING, - - /** Every subscription finished, or the drain window elapsed. */ - CLOSED -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/subscription/GraphQlSubscriptionDrainingException.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/subscription/GraphQlSubscriptionDrainingException.java deleted file mode 100644 index e994f1de..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/subscription/GraphQlSubscriptionDrainingException.java +++ /dev/null @@ -1,17 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.subscription; - -/** - * Raised when a subscription is attempted while the server is draining. - * - *

Refused rather than accepted-and-immediately-closed, so the client retries against an instance - * that is staying up. - */ -public class GraphQlSubscriptionDrainingException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - /** Creates the failure. */ - public GraphQlSubscriptionDrainingException() { - super("server is draining and accepts no new subscriptions"); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/subscription/GraphQlSubscriptionEvent.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/subscription/GraphQlSubscriptionEvent.java deleted file mode 100644 index 591005f4..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/subscription/GraphQlSubscriptionEvent.java +++ /dev/null @@ -1,39 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.subscription; - -import dev.caskeleton.adapter.inbound.graphql.http.GraphQlRequestSize; -import java.util.Map; - -/** - * One event, already translated into a GraphQL DTO. - * - *

Translated deliberately, rather than forwarding the broker message. A messaging schema and a - * GraphQL schema evolve on different timelines and for different audiences; publishing the raw - * message would make every internal event-shape change a public API change. - * - * @param payload the GraphQL DTO to deliver - * @param sequence source ordering position, used by the ordered profile and by replay - */ -public record GraphQlSubscriptionEvent(Map payload, long sequence) { - - public GraphQlSubscriptionEvent { - payload = - payload == null - ? Map.of() - : java.util.Collections.unmodifiableMap(new java.util.LinkedHashMap<>(payload)); - if (sequence < 0) { - throw new IllegalArgumentException("event sequence cannot be negative"); - } - } - - /** - * This event's serialized size, for the byte budget. - * - *

Counted as canonical JSON, not as {@code Map.toString()}. The two diverge by more than a - * constant: {@code toString} writes {@code {a=1}} where JSON writes {@code {"a":1}}, omits the - * quoting that dominates a string-heavy payload, and renders a nested list differently again. A - * queue bounded by that number is bounded by something that is not the thing being queued. - */ - public long approximateBytes() { - return GraphQlRequestSize.jsonBytes(payload); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/subscription/GraphQlSubscriptionExecutionPolicy.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/subscription/GraphQlSubscriptionExecutionPolicy.java deleted file mode 100644 index a34b65d3..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/subscription/GraphQlSubscriptionExecutionPolicy.java +++ /dev/null @@ -1,34 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.subscription; - -/** - * The ordering guarantee one subscription runs with. - * - *

{@code keepSourceOrder} maps onto GraphQL Java's subscription ordering flag, so the engine - * buffers to preserve order rather than the transport pretending to. - * - * @param profile the ordering profile - * @param keepSourceOrder whether the engine preserves source ordering - */ -public record GraphQlSubscriptionExecutionPolicy( - GraphQlSubscriptionOrderingProfile profile, boolean keepSourceOrder) { - - public GraphQlSubscriptionExecutionPolicy { - if (profile == null) { - throw new IllegalArgumentException("ordering profile is required"); - } - if ((profile == GraphQlSubscriptionOrderingProfile.ORDERED) != keepSourceOrder) { - throw new IllegalArgumentException("ordering profile and source-order flag must agree"); - } - } - - /** Source order preserved. */ - public static GraphQlSubscriptionExecutionPolicy ordered() { - return new GraphQlSubscriptionExecutionPolicy(GraphQlSubscriptionOrderingProfile.ORDERED, true); - } - - /** Delivered as items complete. */ - public static GraphQlSubscriptionExecutionPolicy lowLatency() { - return new GraphQlSubscriptionExecutionPolicy( - GraphQlSubscriptionOrderingProfile.LOW_LATENCY, false); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/subscription/GraphQlSubscriptionLease.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/subscription/GraphQlSubscriptionLease.java deleted file mode 100644 index 964529f0..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/subscription/GraphQlSubscriptionLease.java +++ /dev/null @@ -1,37 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.subscription; - -import java.util.Objects; -import java.util.concurrent.atomic.AtomicBoolean; - -/** - * A subscription's claim on the node, released exactly once when the stream ends. - * - *

A lease rather than a paired {@code register}/{@code deregister} call, because the paired form - * makes correctness depend on the caller: a stream that ended on an error path without its matching - * deregister left the count permanently above zero, and the node then drained for the full timeout - * on every shutdown while reporting subscriptions that no longer existed. Releasing twice is just - * as damaging in the other direction — it decrements someone else's subscription — so the release - * is idempotent and the second call does nothing. - */ -public final class GraphQlSubscriptionLease implements AutoCloseable { - - private final GraphQlSubscriptionDrainCoordinator coordinator; - private final AtomicBoolean released = new AtomicBoolean(); - - GraphQlSubscriptionLease(GraphQlSubscriptionDrainCoordinator coordinator) { - this.coordinator = Objects.requireNonNull(coordinator, "coordinator is required"); - } - - /** Releases the lease; subsequent calls do nothing. */ - @Override - public void close() { - if (released.compareAndSet(false, true)) { - coordinator.release(); - } - } - - /** Whether this lease has already been released. */ - public boolean released() { - return released.get(); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/subscription/GraphQlSubscriptionMetrics.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/subscription/GraphQlSubscriptionMetrics.java deleted file mode 100644 index 133abe01..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/subscription/GraphQlSubscriptionMetrics.java +++ /dev/null @@ -1,68 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.subscription; - -import java.util.EnumMap; -import java.util.Map; -import java.util.concurrent.atomic.AtomicLong; - -/** - * Subscription counters, keyed by bounded values only. - * - *

Terminations are counted per reason, which is a small enum. Connection and operation - * identities are deliberately not dimensions: there is one of each per client, and as labels they - * would produce a time series per connection. - */ -public final class GraphQlSubscriptionMetrics { - - private final AtomicLong opened = new AtomicLong(); - private final AtomicLong eventsDelivered = new AtomicLong(); - private final AtomicLong eventsDropped = new AtomicLong(); - private final Map terminations = - new EnumMap<>(GraphQlSubscriptionTermination.class); - - /** Creates the counters. */ - public GraphQlSubscriptionMetrics() { - for (GraphQlSubscriptionTermination reason : GraphQlSubscriptionTermination.values()) { - terminations.put(reason, new AtomicLong()); - } - } - - /** Records a subscription starting. */ - public void recordOpened() { - opened.incrementAndGet(); - } - - /** Records an event delivered to the client. */ - public void recordDelivered() { - eventsDelivered.incrementAndGet(); - } - - /** Records an event dropped under the telemetry policy. */ - public void recordDropped() { - eventsDropped.incrementAndGet(); - } - - /** Records a subscription ending. */ - public void recordTermination(GraphQlSubscriptionTermination reason) { - terminations.get(reason).incrementAndGet(); - } - - /** Subscriptions opened. */ - public long opened() { - return opened.get(); - } - - /** Events delivered. */ - public long eventsDelivered() { - return eventsDelivered.get(); - } - - /** Events dropped. */ - public long eventsDropped() { - return eventsDropped.get(); - } - - /** Terminations recorded for one reason. */ - public long terminations(GraphQlSubscriptionTermination reason) { - return terminations.get(reason).get(); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/subscription/GraphQlSubscriptionOrderingProfile.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/subscription/GraphQlSubscriptionOrderingProfile.java deleted file mode 100644 index 319fe7dd..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/subscription/GraphQlSubscriptionOrderingProfile.java +++ /dev/null @@ -1,18 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.subscription; - -/** - * Whether source ordering is preserved (design §20). - * - *

An honest trade-off rather than a default. Subscription items complete asynchronously, so - * without buffering they can arrive out of source order — fine for a live counter, wrong for a - * state machine. Preserving order costs head-of-line blocking and memory, which is why the choice - * is per subscription. - */ -public enum GraphQlSubscriptionOrderingProfile { - - /** Deliver as soon as each item completes; order may differ from the source. */ - LOW_LATENCY, - - /** Preserve source order, at the cost of head-of-line blocking. */ - ORDERED -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/subscription/GraphQlSubscriptionSource.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/subscription/GraphQlSubscriptionSource.java deleted file mode 100644 index d2d7197c..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/subscription/GraphQlSubscriptionSource.java +++ /dev/null @@ -1,26 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.subscription; - -import org.reactivestreams.Publisher; - -/** - * Where a subscription's events come from. - * - *

A {@code Publisher}, so cancellation propagates back to the source: when the client - * disconnects, the Kafka consumer or application publisher behind this has to stop too, or the - * server keeps consuming for a subscriber that is gone. - * - *

The source provides events. It does not provide durability, acknowledgement or replay — those - * belong to the messaging platform, and GraphQL subscriptions do not reimplement them. - * - * @param event type - */ -@FunctionalInterface -public interface GraphQlSubscriptionSource { - - /** - * Opens the stream. - * - * @param context the subscription's context, including the pinned principal - */ - Publisher open(GraphQlSubscriptionContext context); -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/subscription/GraphQlSubscriptionState.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/subscription/GraphQlSubscriptionState.java deleted file mode 100644 index 8dc18323..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/subscription/GraphQlSubscriptionState.java +++ /dev/null @@ -1,45 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.subscription; - -import java.util.Set; - -/** - * The subscription lifecycle (design §20). - * - *

Explicit states, because "connected" covers several very different situations: a socket that - * has not authenticated, one that has but is not subscribed, and one that is streaming. Operational - * questions — how many are draining, how many never finished authenticating — need them - * distinguished. - */ -public enum GraphQlSubscriptionState { - - /** The socket is open. */ - CONNECTING, - - /** {@code connection_init} is being verified. */ - AUTHENTICATING, - - /** Authenticated, no subscription yet. */ - READY, - - /** A subscription was accepted. */ - SUBSCRIBED, - - /** Events are flowing. */ - STREAMING, - - /** Cancellation is propagating to the source. */ - CANCELLING, - - /** The subscription ended. */ - COMPLETED; - - /** States from which a subscription may still be accepted. */ - public static Set acceptingSubscriptions() { - return Set.of(READY, SUBSCRIBED, STREAMING); - } - - /** Whether events may be delivered in this state. */ - public boolean deliverable() { - return this == SUBSCRIBED || this == STREAMING; - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/subscription/GraphQlSubscriptionTermination.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/subscription/GraphQlSubscriptionTermination.java deleted file mode 100644 index 99c85945..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/advanced/subscription/GraphQlSubscriptionTermination.java +++ /dev/null @@ -1,29 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.subscription; - -/** - * Why a subscription stopped. - * - *

Bounded, and distinguishes the cases a client should react to differently: a completed stream - * is finished, a terminated slow consumer should reconnect and read less eagerly, and a failed - * source may recover on its own. - */ -public enum GraphQlSubscriptionTermination { - - /** The source completed normally. */ - COMPLETED, - - /** The client unsubscribed. */ - CANCELLED, - - /** The client could not keep up. */ - SLOW_CONSUMER, - - /** The source failed. */ - SOURCE_FAILED, - - /** The credential expired or authorization was revoked. */ - AUTHORIZATION_ENDED, - - /** The server is shutting down. */ - SERVER_DRAINING -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/api/GraphQlClientProfile.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/api/GraphQlClientProfile.java index f2c0492b..226eacb0 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/api/GraphQlClientProfile.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/api/GraphQlClientProfile.java @@ -10,8 +10,7 @@ import java.util.regex.Pattern; * cardinality and let a caller pick its own policy, so the shape is constrained to a short static * identifier and rejected otherwise. * - *

This is the transport-facing profile identity. The uppercase catalog name used by the - * operation-name and cost policies is {@link GraphQlClientProfileName}. + *

This is the transport-facing profile identity. * * @param value profile identity matching {@code [a-z][a-z0-9.-]{2,63}} */ diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/api/GraphQlClientProfileName.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/api/GraphQlClientProfileName.java deleted file mode 100644 index 86602c8c..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/api/GraphQlClientProfileName.java +++ /dev/null @@ -1,50 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.api; - -import java.util.Set; -import java.util.regex.Pattern; - -/** - * The bounded catalog name of a client policy profile (design §18). - * - *

The design fixes a small catalog — {@code PUBLIC}, {@code PARTNER}, {@code FIRST_PARTY}, - * {@code ADMIN}, {@code INTROSPECTION} — that operation-name, cost and introspection policies - * branch on. Deployments may add their own profile, so this is validated rather than a closed enum, - * but the shape stays a short uppercase identifier so it remains a safe metric label. - * - * @param value catalog name matching {@code [A-Z][A-Z0-9_]{2,31}} - */ -public record GraphQlClientProfileName(String value) { - - /** Unauthenticated or internet-facing clients: named or persisted-only operations. */ - public static final String PUBLIC = "PUBLIC"; - - /** Contracted external integrators. */ - public static final String PARTNER = "PARTNER"; - - /** Applications owned by the same organisation as the schema. */ - public static final String FIRST_PARTY = "FIRST_PARTY"; - - /** Operations plane clients (G4). */ - public static final String ADMIN = "ADMIN"; - - /** Schema discovery clients, governed by the environment introspection policy. */ - public static final String INTROSPECTION = "INTROSPECTION"; - - private static final Pattern PATTERN = Pattern.compile("[A-Z][A-Z0-9_]{2,31}"); - - public GraphQlClientProfileName { - if (value == null || !PATTERN.matcher(value).matches()) { - throw new IllegalArgumentException("invalid GraphQL client profile name"); - } - } - - /** Creates a catalog name, rejecting dynamic or unbounded values. */ - public static GraphQlClientProfileName of(String value) { - return new GraphQlClientProfileName(value); - } - - /** The profile names the design fixes as the calibration starting point. */ - public static Set designCatalog() { - return Set.of(PUBLIC, PARTNER, FIRST_PARTY, ADMIN, INTROSPECTION); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/architecture/GraphQlAsyncReturnShape.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/architecture/GraphQlAsyncReturnShape.java deleted file mode 100644 index d1abaaae..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/architecture/GraphQlAsyncReturnShape.java +++ /dev/null @@ -1,72 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.architecture; - -import java.util.List; -import java.util.Set; - -/** - * Whether a resolver's return container yields one value or many. - * - *

The distinction is what makes the subscription rule correct. The rule used to reject every - * {@code Publisher} outside a subscription, and {@code Mono} is a {@code Publisher} — so {@code - * Mono order()} on a query, which Spring for GraphQL supports and documents, was refused - * by the platform's own boundary check. A query may complete asynchronously; what it may not do is - * emit a stream, because the HTTP profile has no way to deliver one. - * - *

Recognised by name rather than by class reference: naming {@code reactor.core.publisher.Mono} - * here would drag Reactor into a rule that exists to keep this boundary framework-light, and the - * check has to work whether or not the adopter has Reactor at all. - */ -public enum GraphQlAsyncReturnShape { - - /** Not an async container at all. */ - SYNCHRONOUS, - - /** Completes once with at most one value: legal on every operation type. */ - SINGLE_VALUE, - - /** Emits zero or more values over time: legal only on a subscription. */ - MULTI_VALUE; - - private static final Set SINGLE_VALUE_CONTAINERS = - Set.of( - "reactor.core.publisher.Mono", - "java.util.concurrent.CompletionStage", - "java.util.concurrent.CompletableFuture", - "java.util.concurrent.Future", - "java.util.Optional", - "org.springframework.graphql.data.method.annotation.SchemaMapping"); - - private static final List MULTI_VALUE_INTERFACES = - List.of("org.reactivestreams.Publisher", "java.util.stream.Stream"); - - /** Classifies a resolver return type. */ - public static GraphQlAsyncReturnShape of(Class returnType) { - if (returnType == null) { - return SYNCHRONOUS; - } - if (SINGLE_VALUE_CONTAINERS.contains(returnType.getName())) { - return SINGLE_VALUE; - } - return implementsAny(returnType, MULTI_VALUE_INTERFACES) ? MULTI_VALUE : SYNCHRONOUS; - } - - /** Whether this shape may be returned from a field that is not a subscription. */ - public boolean allowedOutsideSubscription() { - return this != MULTI_VALUE; - } - - private static boolean implementsAny(Class type, List interfaceNames) { - if (type == null || type == Object.class) { - return false; - } - if (interfaceNames.contains(type.getName())) { - return true; - } - for (Class implemented : type.getInterfaces()) { - if (implementsAny(implemented, interfaceNames)) { - return true; - } - } - return implementsAny(type.getSuperclass(), interfaceNames); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/architecture/GraphQlControllerContractException.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/architecture/GraphQlControllerContractException.java deleted file mode 100644 index 47ba73df..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/architecture/GraphQlControllerContractException.java +++ /dev/null @@ -1,40 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.architecture; - -import java.util.List; - -/** - * Raised when a GraphQL resolver violates the transport boundary. - * - *

Reports the schema coordinate and the Java method, so the fix is obvious from the message - * alone. - */ -public class GraphQlControllerContractException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - private final transient List violations; - - /** - * Creates the failure with a single violation. - * - * @param violation description naming the coordinate and the Java method - */ - public GraphQlControllerContractException(String violation) { - this(List.of(violation)); - } - - /** - * Creates the failure with every violation found. - * - * @param violations descriptions naming the coordinate and the Java method - */ - public GraphQlControllerContractException(List violations) { - super("GraphQL resolver boundary violated: " + violations); - this.violations = List.copyOf(violations); - } - - /** The violations, in deterministic order. */ - public List violations() { - return violations; - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/architecture/GraphQlControllerInspector.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/architecture/GraphQlControllerInspector.java deleted file mode 100644 index 419ab399..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/architecture/GraphQlControllerInspector.java +++ /dev/null @@ -1,109 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.architecture; - -import java.lang.annotation.Annotation; -import java.lang.reflect.Method; -import java.lang.reflect.Parameter; -import java.util.ArrayList; -import java.util.List; -import java.util.Set; - -/** - * Inspects one annotated resolver method against the transport boundary (design §11). - * - *

Runs at startup rather than in review, and reports the schema coordinate together with the - * Java method so a violation is actionable. A {@code Publisher} return type is accepted only on a - * subscription: on a query it would mean the field completes asynchronously in a way the HTTP - * profile never delivers. - */ -public final class GraphQlControllerInspector { - - private static final String SUBSCRIPTION_MAPPING = - "org.springframework.graphql.data.method.annotation.SubscriptionMapping"; - - private static final Set GRAPHQL_MAPPINGS = - Set.of( - "org.springframework.graphql.data.method.annotation.QueryMapping", - "org.springframework.graphql.data.method.annotation.MutationMapping", - SUBSCRIPTION_MAPPING, - "org.springframework.graphql.data.method.annotation.SchemaMapping", - "org.springframework.graphql.data.method.annotation.BatchMapping"); - - private GraphQlControllerInspector() {} - - /** - * Inspects a resolver method. - * - * @throws GraphQlControllerContractException when the return type, an argument type or a {@code - * Publisher} outside a subscription violates the boundary - */ - public static void inspect(Method method) { - List violations = violations(method); - if (!violations.isEmpty()) { - throw new GraphQlControllerContractException(violations); - } - } - - /** Every boundary violation on a resolver method, in deterministic order. */ - public static List violations(Method method) { - if (method == null) { - throw new IllegalArgumentException("resolver method is required"); - } - List violations = new ArrayList<>(); - String coordinate = coordinateOf(method); - - // The generic type, not the erased one. `Mono` erases to `Mono`, which passes - // every persistence rule while carrying exactly the type those rules forbid. - for (Class referenced : GraphQlTypeGraph.referencedTypes(method.getGenericReturnType())) { - String returnRejection = GraphQlReturnTypePolicy.rejection(referenced); - if (returnRejection != null) { - violations.add(coordinate + " returns " + returnRejection); - } - } - - GraphQlAsyncReturnShape shape = GraphQlAsyncReturnShape.of(method.getReturnType()); - if (!shape.allowedOutsideSubscription() && !subscription(method)) { - violations.add( - coordinate - + " returns a multi-value publisher outside a subscription; a query or mutation may " - + "complete asynchronously but cannot emit a stream"); - } - - for (Parameter parameter : method.getParameters()) { - for (Class referenced : - GraphQlTypeGraph.referencedTypes(parameter.getParameterizedType())) { - String argumentRejection = GraphQlInputTypePolicy.rejection(referenced); - if (argumentRejection != null) { - violations.add(coordinate + " binds " + parameter.getName() + ": " + argumentRejection); - } - } - } - - violations.addAll(GraphQlControllerTransactionRule.violations(method)); - return List.copyOf(violations); - } - - /** Whether the method is annotated as a GraphQL resolver at all. */ - public static boolean isResolver(Method method) { - for (Annotation annotation : method.getAnnotations()) { - if (GRAPHQL_MAPPINGS.contains(annotation.annotationType().getName())) { - return true; - } - } - return false; - } - - /** Whether the method resolves a subscription field. */ - public static boolean subscription(Method method) { - for (Annotation annotation : method.getAnnotations()) { - if (SUBSCRIPTION_MAPPING.equals(annotation.annotationType().getName())) { - return true; - } - } - return false; - } - - /** Reportable identity of the resolver: declaring class and method. */ - public static String coordinateOf(Method method) { - return method.getDeclaringClass().getSimpleName() + "#" + method.getName(); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/architecture/GraphQlControllerTransactionRule.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/architecture/GraphQlControllerTransactionRule.java deleted file mode 100644 index 77073871..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/architecture/GraphQlControllerTransactionRule.java +++ /dev/null @@ -1,81 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.architecture; - -import java.lang.annotation.Annotation; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.List; -import java.util.Set; - -/** - * Forbids transaction annotations on GraphQL resolvers (design §11, §15). - * - *

A transaction on a resolver would span the whole field's execution — including DataLoader - * dispatches and downstream calls that have no business inside a database transaction — and it - * would put the boundary in transport code where it cannot be reasoned about with the use case. The - * transaction belongs on the Application Service the resolver calls. - * - *

Serial execution of mutation root fields is not a shared transaction either; two root - * mutations are two independent use cases, and anything that must be atomic belongs in one - * mutation. - */ -public final class GraphQlControllerTransactionRule { - - /** Fully qualified annotation names that open a transaction. */ - public static final Set TRANSACTION_ANNOTATIONS = - Set.of( - "org.springframework.transaction.annotation.Transactional", - "jakarta.transaction.Transactional", - "javax.transaction.Transactional"); - - /** - * Simple annotation name that opens a transaction, whichever library declares it. - * - *

Matching the simple name as well as the known fully qualified ones is deliberate: the rule - * is about a transaction boundary appearing in transport code, and a project-local or vendor - * {@code @Transactional} is exactly as wrong as Spring's. - */ - public static final String TRANSACTION_ANNOTATION_SIMPLE_NAME = "Transactional"; - - private GraphQlControllerTransactionRule() {} - - /** - * Asserts that a resolver method and its declaring class carry no transaction annotation. - * - * @throws GraphQlControllerContractException when either does - */ - public static void assertNoTransaction(Method method) { - List violations = violations(method); - if (!violations.isEmpty()) { - throw new GraphQlControllerContractException(violations); - } - } - - /** Transaction violations on a resolver method and its declaring class. */ - public static List violations(Method method) { - List violations = new ArrayList<>(); - String coordinate = method.getDeclaringClass().getSimpleName() + "#" + method.getName(); - - if (transactional(method.getAnnotations())) { - violations.add( - coordinate + " declares a transaction on the resolver instead of the use case"); - } - if (transactional(method.getDeclaringClass().getAnnotations())) { - violations.add( - method.getDeclaringClass().getSimpleName() - + " declares a transaction on the GraphQL controller instead of the use case"); - } - return List.copyOf(violations); - } - - /** Whether any annotation opens a transaction. */ - public static boolean transactional(Annotation[] annotations) { - for (Annotation annotation : annotations) { - Class type = annotation.annotationType(); - if (TRANSACTION_ANNOTATIONS.contains(type.getName()) - || TRANSACTION_ANNOTATION_SIMPLE_NAME.equals(type.getSimpleName())) { - return true; - } - } - return false; - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/architecture/GraphQlInputTypePolicy.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/architecture/GraphQlInputTypePolicy.java deleted file mode 100644 index 647166f4..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/architecture/GraphQlInputTypePolicy.java +++ /dev/null @@ -1,44 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.architecture; - -import java.util.Map; - -/** - * Which Java types a GraphQL argument may bind to (design §7.2). - * - *

Binding an input straight onto an entity or document is the write-side mirror of returning - * one: it silently exposes every persistence field as a writable API field, including the ones — - * version, tenant, audit columns, internal flags — that a client must never set. An unrestricted - * {@code Map} argument is rejected for the same reason a {@code Map} return type is: it defeats - * schema validation. - */ -public final class GraphQlInputTypePolicy { - - private GraphQlInputTypePolicy() {} - - /** Whether a GraphQL argument may bind to this type. */ - public static boolean allowed(Class type) { - return rejection(type) == null; - } - - /** - * Why this type may not be bound, or {@code null} when it is allowed. - * - * @param type declared argument type - */ - public static String rejection(Class type) { - if (type == null) { - return "argument type is required"; - } - Class subject = type.isArray() ? type.getComponentType() : type; - if (Map.class.isAssignableFrom(subject)) { - return "unrestricted Map argument bypasses GraphQL input validation"; - } - if (GraphQlReturnTypePolicy.isPersistenceMapped(subject)) { - return "GraphQL input must not bind directly to persistence type " + subject.getName(); - } - if (GraphQlReturnTypePolicy.forbiddenPrefix(subject) != null) { - return "GraphQL input must not bind directly to " + subject.getName(); - } - return null; - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/architecture/GraphQlResolverBoundaryRules.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/architecture/GraphQlResolverBoundaryRules.java deleted file mode 100644 index 8986f2fb..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/architecture/GraphQlResolverBoundaryRules.java +++ /dev/null @@ -1,313 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.architecture; - -import java.io.File; -import java.io.IOException; -import java.io.UncheckedIOException; -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.lang.reflect.Parameter; -import java.net.JarURLConnection; -import java.net.URL; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Enumeration; -import java.util.List; -import java.util.Set; -import java.util.TreeSet; -import java.util.function.Supplier; -import java.util.jar.JarEntry; -import java.util.jar.JarFile; -import java.util.stream.Stream; - -/** - * Architecture rules for GraphQL resolver packages (design §11). - * - *

A resolver may depend on Application use cases and DTO mappers. It may not reach a repository, - * an {@code EntityManager} or a {@code MongoTemplate} directly: the point of the boundary is that - * query shape, fetch plan, transaction and lock semantics stay owned by the storage module rather - * than being re-decided per GraphQL field. - * - *

The rules are enforced by reflection over the compiled package rather than by an architecture - * library, so an inbound adapter needs no compile dependency on the very technologies it forbids. - */ -public final class GraphQlResolverBoundaryRules { - - /** Type-name fragments that indicate direct persistence access from a resolver. */ - public static final Set FORBIDDEN_TYPE_NAMES = - Set.of("EntityManager", "MongoTemplate", "SessionFactory", "DataSource", "JdbcTemplate"); - - /** - * Type-name suffixes that suggest a repository dependency. - * - *

A supporting signal, not a verdict. A name is the weakest evidence available: {@code - * OrderRepository} may be a Spring Data interface or an application port that happens to be named - * that way, and a rule that decides on the suffix alone both misses the real repository imported - * under another name and refuses a legitimate collaborator. So the suffix only counts when the - * type also sits in a persistence-shaped package or is an interface — see {@link - * #repositoryEvidence}. - * - *

DTO mappers are deliberately absent: a resolver mapping an Application result onto a GraphQL - * payload is exactly what it is supposed to do. - */ - public static final Set FORBIDDEN_TYPE_SUFFIXES = Set.of("Repository", "Dao"); - - /** Package name fragments that make a repository-suffixed type a repository in fact. */ - public static final Set PERSISTENCE_PACKAGE_FRAGMENTS = - Set.of(".repository", ".persistence", ".dao", ".jpa", ".mongo"); - - /** Interfaces whose presence proves a type is a repository, matched by name. */ - public static final Set REPOSITORY_INTERFACES = - Set.of( - "org.springframework.data.repository.Repository", - "org.springframework.data.repository.CrudRepository", - "org.springframework.data.repository.PagingAndSortingRepository", - "org.springframework.data.repository.ListCrudRepository", - "org.springframework.data.repository.reactive.ReactiveCrudRepository"); - - /** Annotations whose presence proves a type is a repository, matched by name. */ - public static final Set REPOSITORY_ANNOTATIONS = - Set.of("org.springframework.stereotype.Repository"); - - private GraphQlResolverBoundaryRules() {} - - /** - * Asserts that no class in the package depends on persistence infrastructure. - * - * @param packageName package to scan, for example {@code com.example.order.graphql} - * @throws GraphQlControllerContractException when any class does - */ - public static void assertNoPersistenceAccess(String packageName) { - assertNoPersistenceAccess(classesIn(packageName)); - } - - /** - * Asserts that none of the given classes depends on persistence infrastructure. - * - * @throws GraphQlControllerContractException when any class does - */ - public static void assertNoPersistenceAccess(Collection> classes) { - List violations = persistenceViolations(classes); - if (!violations.isEmpty()) { - throw new GraphQlControllerContractException(violations); - } - } - - /** - * Persistence-access violations across the given classes, in deterministic order. - * - *

Every declared type is walked as a generic type graph. Checking the erased type would let - * {@code Optional}, {@code List} and {@code Mono} - * through — the wrapper is what a leak looks like once someone has tidied the signature. - */ - public static List persistenceViolations(Collection> classes) { - List violations = new ArrayList<>(); - for (Class type : classes) { - for (Field field : type.getDeclaredFields()) { - record( - violations, - field.getGenericType(), - () -> type.getSimpleName() + "." + field.getName() + " depends on "); - } - for (Constructor constructor : type.getDeclaredConstructors()) { - for (Parameter parameter : constructor.getParameters()) { - record( - violations, - parameter.getParameterizedType(), - () -> type.getSimpleName() + " constructor injects "); - } - } - for (Method method : type.getDeclaredMethods()) { - record( - violations, - method.getGenericReturnType(), - () -> type.getSimpleName() + "#" + method.getName() + " returns "); - for (Parameter parameter : method.getParameters()) { - record( - violations, - parameter.getParameterizedType(), - () -> type.getSimpleName() + "#" + method.getName() + " accepts "); - } - } - } - violations.sort(String::compareTo); - return List.copyOf(violations); - } - - private static void record( - List violations, java.lang.reflect.Type declared, Supplier prefix) { - for (Class referenced : GraphQlTypeGraph.referencedTypes(declared)) { - String evidence = repositoryEvidence(referenced); - if (evidence != null) { - violations.add(prefix.get() + referenced.getName() + " (" + evidence + ")"); - } - } - } - - /** Whether a type represents direct persistence or repository access. */ - public static boolean forbidden(Class type) { - return repositoryEvidence(type) != null; - } - - /** - * Why a type counts as persistence access, or {@code null} when it does not. - * - *

Ordered strongest first, so a diagnostic names the reason that would survive a rename. The - * name-only signal is last and qualified, because it is the one that is wrong in both directions. - */ - public static String repositoryEvidence(Class type) { - if (type == null || type.isPrimitive()) { - return null; - } - Class subject = type; - while (subject.isArray()) { - subject = subject.getComponentType(); - } - if (GraphQlReturnTypePolicy.forbiddenPrefix(subject) != null) { - return "declared in a persistence or driver package"; - } - if (GraphQlReturnTypePolicy.isPersistenceMapped(subject)) { - return "carries a persistence mapping annotation"; - } - if (implementsRepositoryInterface(subject)) { - return "implements a Spring Data repository interface"; - } - for (java.lang.annotation.Annotation annotation : subject.getAnnotations()) { - if (REPOSITORY_ANNOTATIONS.contains(annotation.annotationType().getName())) { - return "annotated as a repository"; - } - } - String simpleName = subject.getSimpleName(); - if (FORBIDDEN_TYPE_NAMES.contains(simpleName)) { - return "is a persistence infrastructure type"; - } - boolean repositoryName = FORBIDDEN_TYPE_SUFFIXES.stream().anyMatch(simpleName::endsWith); - if (repositoryName && type.isInterface()) { - return "is a repository-named interface"; - } - if (repositoryName && persistenceShaped(subject)) { - return "is named as a repository and declared in a persistence package"; - } - return null; - } - - /** - * Whether the type sits in a package that makes a repository name mean what it says. - * - *

The pair of name-based rules above is what demoting the suffix heuristic looks like in - * practice. A repository-named interface is a port by every convention this repository - * follows, so it still counts on its own. A repository-named concrete class outside a persistence - * package no longer does — that shape is far more often a value object or a view than a - * data-access type, and refusing it made the rule something to work around. - */ - private static boolean persistenceShaped(Class type) { - String packageName = "." + type.getPackageName() + "."; - return PERSISTENCE_PACKAGE_FRAGMENTS.stream() - .anyMatch(fragment -> packageName.contains(fragment + ".")); - } - - private static boolean implementsRepositoryInterface(Class type) { - if (type == null || type == Object.class) { - return false; - } - if (REPOSITORY_INTERFACES.contains(type.getName())) { - return true; - } - for (Class implemented : type.getInterfaces()) { - if (implementsRepositoryInterface(implemented)) { - return true; - } - } - return implementsRepositoryInterface(type.getSuperclass()); - } - - /** - * Loads every class in a package and its sub-packages from the current classpath. - * - *

Recursive and JAR-aware. The previous scan listed direct children of a {@code file:} - * directory only, so an adopter whose controllers sit one package deeper, or whose classes ship - * inside a jar — which is to say, every adopter running a packaged application — was checked - * against nothing while the rule reported success. - * - * @throws GraphQlControllerContractException when the package cannot be located, so a rule can - * never pass by scanning nothing - */ - public static List> classesIn(String packageName) { - if (packageName == null || packageName.isBlank()) { - throw new IllegalArgumentException("package name is required"); - } - String resourcePath = packageName.replace('.', '/'); - ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - Set classNames = new TreeSet<>(); - try { - Enumeration roots = classLoader.getResources(resourcePath); - while (roots.hasMoreElements()) { - URL root = roots.nextElement(); - if ("file".equals(root.getProtocol())) { - collectFromDirectory(Path.of(root.toURI()), packageName, classNames); - } else if ("jar".equals(root.getProtocol())) { - collectFromJar(root, resourcePath, classNames); - } - } - } catch (IOException ex) { - throw new UncheckedIOException(ex); - } catch (java.net.URISyntaxException ex) { - throw new IllegalStateException("cannot read package " + packageName, ex); - } - - if (classNames.isEmpty()) { - throw new GraphQlControllerContractException( - "no classes were found in " + packageName + "; the boundary rule would pass vacuously"); - } - - List> classes = new ArrayList<>(); - for (String className : classNames) { - try { - classes.add(Class.forName(className, false, classLoader)); - } catch (ClassNotFoundException | NoClassDefFoundError ex) { - throw new IllegalStateException("cannot load " + className, ex); - } - } - return List.copyOf(classes); - } - - private static void collectFromDirectory(Path directory, String packageName, Set into) - throws IOException { - try (Stream entries = Files.walk(directory)) { - entries - .filter(Files::isRegularFile) - .filter(path -> path.getFileName().toString().endsWith(".class")) - .forEach( - path -> { - String relative = - directory.relativize(path).toString().replace(File.separatorChar, '.'); - String className = - packageName - + "." - + relative.substring(0, relative.length() - ".class".length()); - if (!className.contains("$")) { - into.add(className); - } - }); - } - } - - private static void collectFromJar(URL root, String resourcePath, Set into) - throws IOException { - JarURLConnection connection = (JarURLConnection) root.openConnection(); - // The connection owns the jar file when caching is on, so it must not be closed here: doing so - // would shut a JarFile that the rest of the JVM is still reading from. - connection.setUseCaches(true); - JarFile jar = connection.getJarFile(); - Enumeration entries = jar.entries(); - while (entries.hasMoreElements()) { - String name = entries.nextElement().getName(); - if (!name.startsWith(resourcePath + "/") || !name.endsWith(".class") || name.contains("$")) { - continue; - } - into.add(name.substring(0, name.length() - ".class".length()).replace('/', '.')); - } - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/architecture/GraphQlReturnTypePolicy.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/architecture/GraphQlReturnTypePolicy.java deleted file mode 100644 index d4f7e591..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/architecture/GraphQlReturnTypePolicy.java +++ /dev/null @@ -1,111 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.architecture; - -import java.lang.annotation.Annotation; -import java.util.List; -import java.util.Map; - -/** - * Which Java types a GraphQL resolver may return (design §11). - * - *

Returning a JPA entity or a Mongo document couples the external API to the persistence model: - * a column rename becomes a breaking API change, a lazy association turns into an N+1 or an - * exception during serialization, and fields that were never meant to be public leak by default. An - * unrestricted {@code Map} is rejected for the mirror-image reason — it bypasses the typed contract - * entirely. - * - *

Persistence and provider types are detected by name rather than by class reference on - * purpose: an inbound adapter must not take a compile dependency on JPA, MongoDB or any provider - * SDK just to forbid them. - */ -public final class GraphQlReturnTypePolicy { - - /** Fully qualified annotation names that mark a persistence-mapped type. */ - public static final List PERSISTENCE_ANNOTATIONS = - List.of( - "jakarta.persistence.Entity", - "javax.persistence.Entity", - "jakarta.persistence.Embeddable", - "javax.persistence.Embeddable", - "jakarta.persistence.MappedSuperclass", - "org.springframework.data.mongodb.core.mapping.Document", - "org.springframework.data.relational.core.mapping.Table"); - - /** - * Simple annotation names that mark a persistence-mapped type, whichever library declares them. - * - *

Matched in addition to the fully qualified names so the rule keeps working without this - * adapter taking a compile dependency on JPA, Spring Data or a driver — the dependency the rule - * exists to prevent. - */ - public static final List PERSISTENCE_ANNOTATION_SIMPLE_NAMES = - List.of("Entity", "Embeddable", "MappedSuperclass", "Document", "Table"); - - /** Package prefixes that indicate a persistence, driver or provider SDK type. */ - public static final List FORBIDDEN_TYPE_PREFIXES = - List.of( - "jakarta.persistence.", - "javax.persistence.", - "org.hibernate.", - "org.springframework.data.mongodb.", - "org.springframework.data.repository.", - "org.springframework.data.relational.", - "org.springframework.jdbc.", - "com.mongodb.", - "org.bson.", - "java.sql.", - "javax.sql.", - "software.amazon.awssdk.", - "com.amazonaws.", - "io.grpc.", - "org.apache.kafka."); - - private GraphQlReturnTypePolicy() {} - - /** Whether a resolver may return this type. */ - public static boolean allowed(Class type) { - return rejection(type) == null; - } - - /** - * Why this type may not be returned, or {@code null} when it is allowed. - * - * @param type declared resolver return type - */ - public static String rejection(Class type) { - if (type == null) { - return "resolver return type is required"; - } - Class subject = type.isArray() ? type.getComponentType() : type; - if (Map.class.isAssignableFrom(subject)) { - return "unrestricted Map bypasses the typed GraphQL contract"; - } - if (isPersistenceMapped(subject)) { - return "persistence-mapped type " + subject.getName() + " must not be a GraphQL wire type"; - } - String forbiddenPrefix = forbiddenPrefix(subject); - if (forbiddenPrefix != null) { - return "persistence or provider type " - + subject.getName() - + " must not be a GraphQL wire type"; - } - return null; - } - - /** Whether the type carries a persistence mapping annotation. */ - public static boolean isPersistenceMapped(Class type) { - for (Annotation annotation : type.getAnnotations()) { - Class annotationType = annotation.annotationType(); - if (PERSISTENCE_ANNOTATIONS.contains(annotationType.getName()) - || PERSISTENCE_ANNOTATION_SIMPLE_NAMES.contains(annotationType.getSimpleName())) { - return true; - } - } - return false; - } - - /** The forbidden package prefix this type sits under, or {@code null}. */ - public static String forbiddenPrefix(Class type) { - String name = type.getName(); - return FORBIDDEN_TYPE_PREFIXES.stream().filter(name::startsWith).findFirst().orElse(null); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/architecture/GraphQlTransportTypeRules.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/architecture/GraphQlTransportTypeRules.java deleted file mode 100644 index fc934d49..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/architecture/GraphQlTransportTypeRules.java +++ /dev/null @@ -1,87 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.architecture; - -import graphql.schema.DataFetcher; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -/** - * Architecture rules for what crosses the GraphQL transport boundary (design §4, §11). - * - *

Two things are enforced here. Resolver signatures may only use transport types — DTOs, read - * models, connections, mutation payloads, and publishers on subscriptions. And a raw {@code - * DataFetcher} implementation is restricted to infrastructure packages: annotated controllers are - * the mainstream API, while a hand-written fetcher bypasses argument binding, the context and the - * inspection gate, so it belongs only where scalars, directives and type resolvers are wired. - */ -public final class GraphQlTransportTypeRules { - - /** Package fragments that may implement a raw {@code DataFetcher}. */ - public static final List INFRASTRUCTURE_PACKAGE_FRAGMENTS = - List.of(".graphql.scalar", ".graphql.schema", ".graphql.execution", ".graphql.advanced"); - - private GraphQlTransportTypeRules() {} - - /** - * Asserts that every resolver in the package uses transport types only. - * - * @throws GraphQlControllerContractException when any resolver does not - */ - public static void assertTransportTypesOnly(String packageName) { - assertTransportTypesOnly(GraphQlResolverBoundaryRules.classesIn(packageName)); - } - - /** - * Asserts that every resolver among the given classes uses transport types only. - * - * @throws GraphQlControllerContractException when any resolver does not - */ - public static void assertTransportTypesOnly(Collection> classes) { - List violations = new ArrayList<>(); - for (Class type : classes) { - for (Method method : type.getDeclaredMethods()) { - if (method.isSynthetic() || !GraphQlControllerInspector.isResolver(method)) { - continue; - } - violations.addAll(GraphQlControllerInspector.violations(method)); - } - } - if (!violations.isEmpty()) { - throw new GraphQlControllerContractException(List.copyOf(violations)); - } - } - - /** - * Asserts that raw {@code DataFetcher} implementations live only in infrastructure packages. - * - * @throws GraphQlControllerContractException when an application class implements one - */ - public static void assertRawDataFetcherIsInfrastructureOnly(Collection> classes) { - List violations = new ArrayList<>(); - for (Class type : classes) { - if (!DataFetcher.class.isAssignableFrom(type) - || type.isInterface() - || Modifier.isAbstract(type.getModifiers())) { - continue; - } - if (!infrastructure(type)) { - violations.add( - type.getName() - + " implements a raw DataFetcher outside an infrastructure package; " - + "use an annotated controller instead"); - } - } - if (!violations.isEmpty()) { - violations.sort(String::compareTo); - throw new GraphQlControllerContractException(List.copyOf(violations)); - } - } - - /** Whether a type sits in a package allowed to implement raw fetchers. */ - public static boolean infrastructure(Class type) { - String packageName = type.getPackageName(); - return INFRASTRUCTURE_PACKAGE_FRAGMENTS.stream().anyMatch(packageName::contains); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/architecture/GraphQlTypeGraph.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/architecture/GraphQlTypeGraph.java deleted file mode 100644 index a32cb82a..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/architecture/GraphQlTypeGraph.java +++ /dev/null @@ -1,112 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.architecture; - -import java.lang.reflect.GenericArrayType; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.lang.reflect.TypeVariable; -import java.lang.reflect.WildcardType; -import java.util.ArrayDeque; -import java.util.Deque; -import java.util.LinkedHashSet; -import java.util.Set; - -/** - * Every class a declared type actually reaches, generics included. - * - *

The boundary rules used to inspect {@code Method#getReturnType} and {@code Parameter#getType}, - * which erase to the container: {@code List} reports {@code List}, {@code - * Mono} reports {@code Mono}, and {@code Optional} reports {@code - * Optional}. Every one of those passed a rule whose whole purpose was to notice the type inside — - * the wrapper is exactly what a resolver leaking an entity looks like in practice. - * - *

Traversal is bounded and cycle-guarded. A type variable can refer to its own bound ({@code >}), and a rule that recursed into that would hang on a perfectly legal - * signature. - */ -public final class GraphQlTypeGraph { - - /** Ceiling on how many distinct types one signature may reach before it is refused. */ - public static final int MAXIMUM_VISITED_TYPES = 512; - - private GraphQlTypeGraph() {} - - /** - * Every concrete class reachable from a declared type. - * - *

Arrays contribute their component type, parameterized types contribute their raw type and - * every argument, wildcards and type variables contribute their bounds. - * - * @param type a declared return, parameter or field type - * @return the reachable classes, in first-seen order - */ - public static Set> referencedTypes(Type type) { - Set> found = new LinkedHashSet<>(); - if (type == null) { - return found; - } - Set visited = new LinkedHashSet<>(); - Deque pending = new ArrayDeque<>(); - pending.push(type); - - while (!pending.isEmpty() && visited.size() < MAXIMUM_VISITED_TYPES) { - Type current = pending.pop(); - if (current == null || !visited.add(current)) { - continue; - } - if (current instanceof Class raw) { - Class component = raw; - while (component.isArray()) { - component = component.getComponentType(); - } - if (!component.isPrimitive()) { - found.add(component); - } - } else if (current instanceof ParameterizedType parameterized) { - pending.push(parameterized.getRawType()); - for (Type argument : parameterized.getActualTypeArguments()) { - pending.push(argument); - } - } else if (current instanceof GenericArrayType array) { - pending.push(array.getGenericComponentType()); - } else if (current instanceof WildcardType wildcard) { - for (Type bound : wildcard.getUpperBounds()) { - pending.push(bound); - } - for (Type bound : wildcard.getLowerBounds()) { - pending.push(bound); - } - } else if (current instanceof TypeVariable variable) { - for (Type bound : variable.getBounds()) { - pending.push(bound); - } - } - } - return found; - } - - /** - * The raw class a declared type erases to, or {@code null}. - * - *

Used where the container itself is the subject — deciding whether a return type is a - * publisher, for instance — as opposed to what it contains. - */ - public static Class rawType(Type type) { - if (type instanceof Class raw) { - return raw; - } - if (type instanceof ParameterizedType parameterized) { - return rawType(parameterized.getRawType()); - } - if (type instanceof GenericArrayType array) { - Class component = rawType(array.getGenericComponentType()); - return component == null ? null : component.arrayType(); - } - if (type instanceof WildcardType wildcard) { - return wildcard.getUpperBounds().length == 0 ? null : rawType(wildcard.getUpperBounds()[0]); - } - if (type instanceof TypeVariable variable) { - return variable.getBounds().length == 0 ? null : rawType(variable.getBounds()[0]); - } - return null; - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlActivationEnvironmentPostProcessor.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlActivationEnvironmentPostProcessor.java index 346dc5a3..a33876c8 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlActivationEnvironmentPostProcessor.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlActivationEnvironmentPostProcessor.java @@ -1,42 +1,64 @@ package dev.caskeleton.adapter.inbound.graphql.autoconfigure; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.springframework.boot.EnvironmentPostProcessor; import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.AutoConfiguration; +import org.springframework.boot.context.annotation.ImportCandidates; +import org.springframework.boot.context.config.ConfigDataEnvironmentPostProcessor; +import org.springframework.boot.context.properties.bind.Bindable; +import org.springframework.boot.context.properties.bind.Binder; +import org.springframework.boot.env.YamlPropertySourceLoader; import org.springframework.core.Ordered; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.MapPropertySource; +import org.springframework.core.io.ClassPathResource; /** * Everything about {@code backend.graphql} that has to be settled before a bean exists. * - *

An environment post-processor rather than a bean, for the same reason the master switch uses - * one: these are the failures that have to arrive first, naming what an operator set, instead of - * surfacing as a bean somewhere downstream that could not be assembled because of it. - * - *

Two jobs, both scoped to the master switch being on: + *

An environment post-processor rather than a bean: these are the failures that have to arrive + * first, naming what an operator set, instead of surfacing as a bean somewhere downstream that + * could not be assembled because of it. * *

    + *
  1. Contribute the module's settings. {@code config/graphql.yml} maps the {@code + * APP_GRAPHQL_*} variables onto {@code backend.graphql.*}, which an environment variable + * cannot reach directly. Added last, so a deployment's own value always wins, and loaded only + * because the module is on the classpath — removing the module removes its settings. *
  2. Refuse a retired safety key. See {@link GraphQlRetiredSafetyAxis}. *
  3. Give the framework's console flags the platform's defaults. Spring Boot answers - * introspection by default; this platform does not. Both are defensible on their own and - * together they meant that turning GraphQL on failed at startup on a contradiction nobody had - * configured — the platform said introspection was off, the framework said it was on, and the - * runtime validator correctly refused a deployment with two answers to one question. The - * platform's value is contributed at the lowest precedence, so an operator who sets either - * key still wins and still gets validated; what is removed is the disagreement that existed - * with nothing set at all. + * introspection by default; this platform does not. The platform's value is contributed at + * the lowest precedence, so an operator who sets either key still wins and still gets + * validated. + *
  4. Make an explicit off complete. The module is on when present. {@code + * backend.graphql.enabled=false} turns off {@link GraphQlRootAutoConfiguration}, but Spring + * GraphQL's own auto-configurations would still publish {@code /graphql} from the schema on + * the classpath. So an explicit off appends them — read from Boot's own registration file, + * not listed here — to {@code spring.autoconfigure.exclude}, after whatever the deployment + * already excludes. *
* - *

Ordered last so profile-specific configuration data has already been contributed. A check that - * ran earlier would read {@code application-prod.yml}'s keys as absent, which is the same as not - * checking at all for the deployments that matter most. + *

Runs straight after config data, so profile-specific files are already contributed and every + * later reader of the switch sees the module's default. */ public class GraphQlActivationEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered { + static final String RESOURCE = "config/graphql.yml"; + + private static final String SWITCH = "backend.graphql.enabled"; + + private static final String EXCLUDE = "spring.autoconfigure.exclude"; + + private static final String BOOT_GRAPHQL_PACKAGE = + "org.springframework.boot.graphql.autoconfigure."; + /** Framework key to the platform key it defaults from. */ private static final Map FRAMEWORK_DEFAULTS = Map.of( @@ -49,11 +71,21 @@ public class GraphQlActivationEnvironmentPostProcessor @Override public void postProcessEnvironment( ConfigurableEnvironment environment, SpringApplication application) { + ClassLoader classLoader = GraphQlActivationEnvironmentPostProcessor.class.getClassLoader(); + try { + new YamlPropertySourceLoader() + .load("graphql-defaults (" + RESOURCE + ")", new ClassPathResource(RESOURCE, classLoader)) + .forEach(environment.getPropertySources()::addLast); + } catch (IOException failure) { + throw new UncheckedIOException("failed to read " + RESOURCE, failure); + } + List problems = GraphQlRetiredSafetyAxis.problems(environment); if (!problems.isEmpty()) { throw new IllegalStateException(String.join(System.lineSeparator(), problems)); } - if (!"true".equalsIgnoreCase(environment.getProperty("backend.graphql.enabled", "false"))) { + if (!"true".equalsIgnoreCase(environment.getProperty(SWITCH, "true"))) { + excludeTheFrameworkAutoConfigurations(environment, classLoader); return; } Map defaults = new LinkedHashMap<>(); @@ -68,8 +100,24 @@ public class GraphQlActivationEnvironmentPostProcessor } } + private static void excludeTheFrameworkAutoConfigurations( + ConfigurableEnvironment environment, ClassLoader classLoader) { + List excluded = + new ArrayList<>( + Binder.get(environment).bind(EXCLUDE, Bindable.listOf(String.class)).orElse(List.of())); + for (String candidate : ImportCandidates.load(AutoConfiguration.class, classLoader)) { + if (candidate.startsWith(BOOT_GRAPHQL_PACKAGE)) { + excluded.add(candidate); + } + } + environment + .getPropertySources() + .addFirst( + new MapPropertySource("graphql-off", Map.of(EXCLUDE, String.join(",", excluded)))); + } + @Override public int getOrder() { - return Ordered.LOWEST_PRECEDENCE; + return ConfigDataEnvironmentPostProcessor.ORDER + 1; } } diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlDeploymentMode.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlDeploymentMode.java index afae197b..30c9ea03 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlDeploymentMode.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlDeploymentMode.java @@ -1,5 +1,7 @@ package dev.caskeleton.adapter.inbound.graphql.autoconfigure; +import dev.caskeleton.shared.runtime.RuntimeEnvironment; + /** * The one axis that decides how safely this deployment behaves (design §17, GQL-INT-002). * @@ -69,4 +71,19 @@ public enum GraphQlDeploymentMode { public boolean production() { return production; } + + /** + * Whether a deployment running in {@code runtime} may select this mode: {@code local} takes + * {@link #LOCAL}, {@code dev} takes {@link #DEV}, {@code prod} takes either production mode. + * + * @param runtime the runtime environment the active profiles name + * @return true when this mode belongs to that environment + */ + public boolean permittedIn(RuntimeEnvironment runtime) { + return switch (runtime) { + case LOCAL -> this == LOCAL; + case DEV -> this == DEV; + case PROD -> production; + }; + } } diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlOffAutoConfigurationImportFilter.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlOffAutoConfigurationImportFilter.java deleted file mode 100644 index 0e2eb1d0..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlOffAutoConfigurationImportFilter.java +++ /dev/null @@ -1,64 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.autoconfigure; - -import java.util.Set; -import org.springframework.boot.autoconfigure.AutoConfigurationImportFilter; -import org.springframework.boot.autoconfigure.AutoConfigurationMetadata; -import org.springframework.context.EnvironmentAware; -import org.springframework.core.env.Environment; - -/** - * Keeps Spring GraphQL's own auto-configurations out of the candidate set while the master is off. - * - *

Conditioning this repository's configuration is not enough. The GraphQL starter contributes - * its auto-configurations through Boot's import metadata, so an ordinary - * {@code @EnableAutoConfiguration} application publishes {@code /graphql} from the classpath alone, - * whatever any project condition says. That is the difference between an endpoint that is off and - * one whose project beans are absent while the framework serves it anyway. - * - *

A misspelled or newly added Boot entry fails open silently — the filter simply never matches. - * The repository therefore protects both sides: AutoConfigurationReachabilityParityTest compares - * this exact target set with Boot's current GraphQL import candidates, while the shipped system - * test still proves the off state publishes no GraphQL route on a real port. - */ -public final class GraphQlOffAutoConfigurationImportFilter - implements AutoConfigurationImportFilter, EnvironmentAware { - - private static final String ENABLE_PROPERTY = "backend.graphql.enabled"; - - private static final Set GRAPHQL_AUTO_CONFIGURATIONS = - Set.of( - "org.springframework.boot.graphql.autoconfigure.GraphQlAutoConfiguration", - "org.springframework.boot.graphql.autoconfigure.data.GraphQlQueryByExampleAutoConfiguration", - "org.springframework.boot.graphql.autoconfigure.data.GraphQlQuerydslAutoConfiguration", - "org.springframework.boot.graphql.autoconfigure.data.GraphQlReactiveQueryByExampleAutoConfiguration", - "org.springframework.boot.graphql.autoconfigure.data.GraphQlReactiveQuerydslAutoConfiguration", - "org.springframework.boot.graphql.autoconfigure.observation.GraphQlObservationAutoConfiguration", - "org.springframework.boot.graphql.autoconfigure.reactive.GraphQlWebFluxAutoConfiguration", - "org.springframework.boot.graphql.autoconfigure.rsocket.GraphQlRSocketAutoConfiguration", - "org.springframework.boot.graphql.autoconfigure.rsocket.RSocketGraphQlClientAutoConfiguration", - "org.springframework.boot.graphql.autoconfigure.security.GraphQlWebFluxSecurityAutoConfiguration", - "org.springframework.boot.graphql.autoconfigure.security.GraphQlWebMvcSecurityAutoConfiguration", - "org.springframework.boot.graphql.autoconfigure.servlet.GraphQlWebMvcAutoConfiguration"); - - private Environment environment; - - @Override - public boolean[] match(String[] candidates, AutoConfigurationMetadata metadata) { - boolean enabled = - environment != null - && "true".equalsIgnoreCase(environment.getProperty(ENABLE_PROPERTY, "false")); - boolean[] matches = new boolean[candidates.length]; - for (int index = 0; index < candidates.length; index++) { - matches[index] = - enabled - || candidates[index] == null - || !GRAPHQL_AUTO_CONFIGURATIONS.contains(candidates[index]); - } - return matches; - } - - @Override - public void setEnvironment(Environment environment) { - this.environment = environment; - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPlatformActuatorEndpoint.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPlatformActuatorEndpoint.java deleted file mode 100644 index 399b846d..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPlatformActuatorEndpoint.java +++ /dev/null @@ -1,72 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.autoconfigure; - -import dev.caskeleton.adapter.inbound.graphql.http.GraphQlHttpProfile; -import dev.caskeleton.adapter.inbound.graphql.schema.GraphQlSchemaHash; -import java.util.Map; -import java.util.Set; - -/** - * The read-only operations view of the deployed platform. - * - *

Deliberately a plain component rather than an annotated actuator endpoint: this leaf does not - * depend on actuator, and the composition root is the right place to decide whether the operations - * plane is exposed at all and behind which authorization. - * - *

{@link #report()} returns hashes and bounded counts only — no SDL, no persisted documents, no - * keys. Cursor key ids are configuration declarations only; this endpoint does not claim that - * cursor signing is active unless a composition has separately wired that modelled capability. - */ -public final class GraphQlPlatformActuatorEndpoint { - - /** Endpoint id a composition root should register this under. */ - public static final String ENDPOINT_ID = "graphqlPlatform"; - - private final GraphQlPlatformSettings properties; - private final GraphQlSchemaHash schemaHash; - private final Set supportedCapabilities; - private final int registeredOperations; - private final int registeredFetchProfiles; - - /** - * Creates the endpoint. - * - * @param properties the validated configuration - * @param schemaHash hash of the deployed schema - * @param supportedCapabilities active capability names - * @param registeredOperations count of registered operations - * @param registeredFetchProfiles count of registered fetch profiles - */ - public GraphQlPlatformActuatorEndpoint( - GraphQlPlatformSettings properties, - GraphQlSchemaHash schemaHash, - Set supportedCapabilities, - int registeredOperations, - int registeredFetchProfiles) { - if (properties == null || schemaHash == null) { - throw new IllegalArgumentException("platform properties and schema hash are required"); - } - this.properties = properties; - this.schemaHash = schemaHash; - this.supportedCapabilities = Set.copyOf(supportedCapabilities); - this.registeredOperations = registeredOperations; - this.registeredFetchProfiles = registeredFetchProfiles; - } - - /** The configuration report. */ - public GraphQlPlatformConfigurationReport report() { - return new GraphQlPlatformConfigurationReport( - schemaHash.value(), - properties.executionProfile().name(), - properties.deploymentMode() == null ? "UNSET" : properties.deploymentMode().name(), - GraphQlHttpProfile.V1.name(), - supportedCapabilities, - properties.cursor().keyIds(), - registeredOperations, - registeredFetchProfiles); - } - - /** The report as a flat map, ready to serialize. */ - public Map reportAsMap() { - return report().asMap(); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPlatformAutoConfiguration.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPlatformAutoConfiguration.java index 82cd2289..0e5975e4 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPlatformAutoConfiguration.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPlatformAutoConfiguration.java @@ -1,9 +1,6 @@ package dev.caskeleton.adapter.inbound.graphql.autoconfigure; import dev.caskeleton.adapter.inbound.graphql.api.GraphQlClientProfile; -import dev.caskeleton.adapter.inbound.graphql.architecture.GraphQlControllerInspector; -import dev.caskeleton.adapter.inbound.graphql.architecture.GraphQlResolverBoundaryRules; -import dev.caskeleton.adapter.inbound.graphql.architecture.GraphQlTransportTypeRules; import dev.caskeleton.adapter.inbound.graphql.context.TenantContext; import dev.caskeleton.adapter.inbound.graphql.cost.GraphQlComplexityCalculator; import dev.caskeleton.adapter.inbound.graphql.cost.GraphQlCostCatalog; @@ -55,16 +52,14 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplicat import org.springframework.boot.graphql.autoconfigure.GraphQlProperties; import org.springframework.boot.graphql.autoconfigure.GraphQlSourceBuilderCustomizer; import org.springframework.boot.web.servlet.FilterRegistrationBean; -import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered; +import org.springframework.core.env.Environment; import org.springframework.graphql.execution.DataFetcherExceptionResolver; import org.springframework.graphql.execution.GraphQlSource; import org.springframework.graphql.observation.ExecutionRequestObservationConvention; import org.springframework.graphql.server.WebGraphQlInterceptor; -import org.springframework.stereotype.Controller; -import org.springframework.util.ClassUtils; /** * Assembles the Stable platform and validates it at startup (Stable plan Task 46). @@ -109,10 +104,8 @@ public class GraphQlPlatformAutoConfiguration { * refresh instead of being logged after the application has already begun serving. * *

This validates the adopter's configuration, which is the only part that varies at runtime. - * The Stable/Advanced module direction is a property of the source tree, not of a deployment, so - * it is enforced where it can actually fail — {@code GraphQlModuleBoundaryTest} scans the real - * imports at build time. Re-checking a compile-time constant during refresh proved nothing and - * cost every adopter a startup-time source scan. + * Structural rules are properties of the source tree, not of a deployment, so they belong in + * build-time tests ({@code GraphQlTransportBoundaryArchitectureTest}), not in refresh. */ @Bean public InitializingBean graphQlPlatformConfigurationCheck( @@ -122,9 +115,12 @@ public class GraphQlPlatformAutoConfiguration { GraphQlScalarWiringConfigurer scalarWiring, GraphQlClientPolicy clientPolicy, ObjectProvider transport, - ObjectProvider frameworkProperties) { + ObjectProvider frameworkProperties, + Environment environment) { return () -> { validator.validate(properties); + validator.validateRuntimeEnvironment( + properties.deploymentMode(), List.of(environment.getActiveProfiles())); GraphQlProperties framework = frameworkProperties.getIfAvailable(); validator.validateRuntime( new GraphQlPlatformRuntime( @@ -138,52 +134,6 @@ public class GraphQlPlatformAutoConfiguration { }; } - /** - * Checks the resolvers this application actually registered. - * - *

The boundary rules could only be pointed at a package name, which meant the fixture packages - * in this leaf's own tests were the only thing ever checked. An adopter's controllers — the ones - * that can actually return an entity or inject a repository — were never inspected by anything. - * Reading the context is what closes that: it sees the beans that will serve requests, including - * the ones contributed by a library the adopter did not write. - */ - @Bean - public InitializingBean graphQlControllerBoundaryCheck(ApplicationContext context) { - return () -> { - List> controllers = graphQlControllerClasses(context); - if (controllers.isEmpty()) { - return; - } - GraphQlTransportTypeRules.assertTransportTypesOnly(controllers); - GraphQlResolverBoundaryRules.assertNoPersistenceAccess(controllers); - GraphQlTransportTypeRules.assertRawDataFetcherIsInfrastructureOnly(controllers); - }; - } - - /** - * The user classes of every {@code @Controller} bean that declares a GraphQL mapping. - * - *

Proxies are unwrapped: a transactional or secured controller is registered as a CGLIB - * subclass whose declared methods carry no annotations, and inspecting that would find nothing. - */ - private static List> graphQlControllerClasses(ApplicationContext context) { - List> controllers = new java.util.ArrayList<>(); - for (String beanName : context.getBeanNamesForAnnotation(Controller.class)) { - Class beanType = context.getType(beanName); - if (beanType == null) { - continue; - } - Class userClass = ClassUtils.getUserClass(beanType); - for (java.lang.reflect.Method method : userClass.getDeclaredMethods()) { - if (!method.isSynthetic() && GraphQlControllerInspector.isResolver(method)) { - controllers.add(userClass); - break; - } - } - } - return List.copyOf(controllers); - } - /** * Detects a servlet runtime. * diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPlatformConfigurationReport.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPlatformConfigurationReport.java deleted file mode 100644 index fdc9a9a0..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPlatformConfigurationReport.java +++ /dev/null @@ -1,56 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.autoconfigure; - -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Set; -import java.util.TreeSet; - -/** - * What the platform is willing to disclose about its own configuration. - * - *

Hashes, capability names and bounded counts — never the SDL, a persisted document or a signing - * key. An operations endpoint is reachable by more people than the deployment pipeline is, and the - * schema is exactly what introspection is disabled to withhold. - * - * @param schemaHash hash of the deployed schema - * @param executionProfile active execution profile - * @param deploymentMode the single safety posture this deployment runs under - * @param httpProfile transport profile version - * @param supportedCapabilities capability names that are active - * @param cursorKeyIds declared cursor key identities, without the keys; not proof that signing is - * active - * @param registeredOperations count of registered operations - * @param registeredFetchProfiles count of registered fetch profiles - */ -public record GraphQlPlatformConfigurationReport( - String schemaHash, - String executionProfile, - String deploymentMode, - String httpProfile, - Set supportedCapabilities, - Set cursorKeyIds, - int registeredOperations, - int registeredFetchProfiles) { - - public GraphQlPlatformConfigurationReport { - supportedCapabilities = Set.copyOf(new TreeSet<>(supportedCapabilities)); - cursorKeyIds = Set.copyOf(new TreeSet<>(cursorKeyIds)); - if (registeredOperations < 0 || registeredFetchProfiles < 0) { - throw new IllegalArgumentException("report counts cannot be negative"); - } - } - - /** The report as a flat map, ready to serialize. */ - public Map asMap() { - Map report = new LinkedHashMap<>(); - report.put("schemaHash", schemaHash); - report.put("executionProfile", executionProfile); - report.put("deploymentMode", deploymentMode); - report.put("httpProfile", httpProfile); - report.put("supportedCapabilities", supportedCapabilities); - report.put("cursorKeyIds", cursorKeyIds); - report.put("registeredOperations", registeredOperations); - report.put("registeredFetchProfiles", registeredFetchProfiles); - return Map.copyOf(report); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPlatformSettings.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPlatformSettings.java index 983b934a..b8d7293a 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPlatformSettings.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPlatformSettings.java @@ -15,11 +15,6 @@ import org.springframework.boot.context.properties.bind.DefaultValue; * validator refuses, so the platform used to refuse to start until an operator supplied two numbers * that have perfectly good defaults. * - *

The unsupported capabilities appear here as explicit flags rather than being absent. A - * deployment that tries to enable multipart upload, HTTP array batching, a request-wide transaction - * or automatic repository exposure should fail at startup with a clear reason — silently ignoring - * the setting would leave an operator believing it took effect. - * *

{@code deploymentMode} is the exception to the defaults rule: it has none, and null survives * construction so {@link GraphQlPlatformStartupValidator} can refuse the startup by name. It * replaced a {@code production} boolean and an {@code environment} enum that defaulted to {@code @@ -30,8 +25,6 @@ import org.springframework.boot.context.properties.bind.DefaultValue; * @param executionProfile runtime execution profile * @param console query console and introspection exposure * @param limits page and cost ceilings - * @param cursor declared cursor signing key identities for adopter-composed/modelled support - * @param unsupported capabilities this platform deliberately does not implement * @param unbridgedBlockingResolvers resolvers that block without an approved bridge */ @ConfigurationProperties("backend.graphql") @@ -40,8 +33,6 @@ public record GraphQlPlatformSettings( @DefaultValue("BLOCKING_MVC") GraphQlExecutionProfile executionProfile, @DefaultValue Console console, @DefaultValue Limits limits, - @DefaultValue Cursor cursor, - @DefaultValue Unsupported unsupported, @DefaultValue("v1") String validationPolicyVersion, @DefaultValue Set observedOperationNames, @DefaultValue Set unbridgedBlockingResolvers) { @@ -54,8 +45,6 @@ public record GraphQlPlatformSettings( executionProfile == null ? GraphQlExecutionProfile.BLOCKING_MVC : executionProfile; console = console == null ? Console.disabled() : console; limits = limits == null ? Limits.defaults() : limits; - cursor = cursor == null ? Cursor.none() : cursor; - unsupported = unsupported == null ? Unsupported.none() : unsupported; // Part of the preparsed cache key: bumping it invalidates every cached validation, which is // what an adopter needs when their own validation rules change without the schema changing. validationPolicyVersion = @@ -110,71 +99,6 @@ public record GraphQlPlatformSettings( } } - /** - * Declared cursor signing key identities for the modelled cursor capability. - * - *

The Stable runtime does not construct a cursor codec or key ring. These ids become - * operationally meaningful only in an adopter composition that also supplies key material and - * request-path wiring. - * - * @param keyIds signing key identities; the keys themselves never appear in configuration - */ - public record Cursor(@DefaultValue Set keyIds) { - - public Cursor { - keyIds = keyIds == null ? Set.of() : Set.copyOf(keyIds); - } - - /** An empty key ring, which production refuses to start with. */ - public static Cursor none() { - return new Cursor(Set.of()); - } - - /** A key ring with the given identities. */ - public static Cursor of(Set keyIds) { - return new Cursor(keyIds); - } - } - - /** - * Capabilities the platform does not implement. - * - *

Present as flags so enabling one fails the boot instead of being ignored. - * - * @param multipartUpload GraphQL multipart upload - * @param httpArrayBatch HTTP array batching - * @param requestWideTransaction one database transaction spanning a whole request - * @param repositoryAutoExposure automatic repository exposure as GraphQL fields - * @param responseCache cross-request response caching - * @param advancedCapabilitiesOnStableStarter Advanced modules reachable from the Stable starter - */ - public record Unsupported( - @DefaultValue("false") boolean multipartUpload, - @DefaultValue("false") boolean httpArrayBatch, - @DefaultValue("false") boolean requestWideTransaction, - @DefaultValue("false") boolean repositoryAutoExposure, - @DefaultValue("false") boolean responseCache, - @DefaultValue("false") boolean advancedCapabilitiesOnStableStarter) { - - /** Nothing unsupported enabled. */ - public static Unsupported none() { - return new Unsupported(false, false, false, false, false, false); - } - - /** Returns a copy with one capability toggled, for startup-validation tests. */ - public Unsupported with(String capability, boolean enabled) { - return new Unsupported( - "multipart".equals(capability) ? enabled : multipartUpload, - "arrayBatch".equals(capability) ? enabled : httpArrayBatch, - "requestWideTransaction".equals(capability) ? enabled : requestWideTransaction, - "repositoryAutoExposure".equals(capability) ? enabled : repositoryAutoExposure, - "responseCache".equals(capability) ? enabled : responseCache, - "advancedOnStableStarter".equals(capability) - ? enabled - : advancedCapabilitiesOnStableStarter); - } - } - /** * Whether production rules apply, which is the deployment mode's answer and nothing else. * @@ -194,8 +118,6 @@ public record GraphQlPlatformSettings( GraphQlExecutionProfile.BLOCKING_MVC, Console.disabled(), Limits.defaults(), - Cursor.none(), - Unsupported.none(), "v1", Set.of(), Set.of()); @@ -208,8 +130,6 @@ public record GraphQlPlatformSettings( executionProfile, console, limits, - cursor, - unsupported, validationPolicyVersion, observedOperationNames, unbridgedBlockingResolvers); @@ -232,8 +152,6 @@ public record GraphQlPlatformSettings( executionProfile, replacement, limits, - cursor, - unsupported, validationPolicyVersion, observedOperationNames, unbridgedBlockingResolvers); @@ -246,36 +164,6 @@ public record GraphQlPlatformSettings( executionProfile, console, replacement, - cursor, - unsupported, - validationPolicyVersion, - observedOperationNames, - unbridgedBlockingResolvers); - } - - /** Returns a copy with different cursor signing keys. */ - public GraphQlPlatformSettings withCursorKeyIds(Set keyIds) { - return new GraphQlPlatformSettings( - deploymentMode, - executionProfile, - console, - limits, - Cursor.of(keyIds), - unsupported, - validationPolicyVersion, - observedOperationNames, - unbridgedBlockingResolvers); - } - - /** Returns a copy with one unsupported capability toggled, for startup-validation tests. */ - public GraphQlPlatformSettings withUnsupportedCapability(String capability, boolean enabled) { - return new GraphQlPlatformSettings( - deploymentMode, - executionProfile, - console, - limits, - cursor, - unsupported.with(capability, enabled), validationPolicyVersion, observedOperationNames, unbridgedBlockingResolvers); @@ -288,8 +176,6 @@ public record GraphQlPlatformSettings( executionProfile, console, limits, - cursor, - unsupported, validationPolicyVersion, observedOperationNames, Set.copyOf(coordinates)); @@ -302,8 +188,6 @@ public record GraphQlPlatformSettings( profile, console, limits, - cursor, - unsupported, validationPolicyVersion, observedOperationNames, unbridgedBlockingResolvers); diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPlatformStartupValidator.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPlatformStartupValidator.java index f4997899..4b9ee52e 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPlatformStartupValidator.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPlatformStartupValidator.java @@ -1,7 +1,10 @@ package dev.caskeleton.adapter.inbound.graphql.autoconfigure; import dev.caskeleton.adapter.inbound.graphql.execution.GraphQlExecutionProfile; +import dev.caskeleton.shared.runtime.RuntimeEnvironment; import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; import java.util.List; /** @@ -51,26 +54,6 @@ public final class GraphQlPlatformStartupValidator { problems.add("maximum complexity must be positive"); } - if (properties.unsupported().multipartUpload()) { - problems.add( - "GraphQL multipart upload is unsupported; use the Fileserver upload reservation"); - } - if (properties.unsupported().httpArrayBatch()) { - problems.add("HTTP array batching is unsupported"); - } - if (properties.unsupported().requestWideTransaction()) { - problems.add("request-wide database transactions are unsupported; use one mutation use case"); - } - if (properties.unsupported().repositoryAutoExposure()) { - problems.add( - "automatic repository exposure is unsupported outside the Advanced compatibility capability"); - } - if (properties.unsupported().responseCache()) { - problems.add("response caching is unsupported until an actor/tenant cache key model exists"); - } - if (properties.unsupported().advancedCapabilitiesOnStableStarter()) { - problems.add("the Stable starter must not activate Advanced capabilities"); - } if (properties.executionProfile() == GraphQlExecutionProfile.REACTIVE_WEBFLUX && !properties.unbridgedBlockingResolvers().isEmpty()) { problems.add( @@ -80,6 +63,35 @@ public final class GraphQlPlatformStartupValidator { return List.copyOf(problems); } + /** + * Refuses a deployment mode that does not belong to the runtime environment the active profiles + * name — a {@code prod} deployment serving under {@code LOCAL} safety rules, for instance. + * + *

A context whose profiles name no single environment is not judged here: that a deployable + * runtime names exactly one is the composition root's rule, and slice tests name none. + * + * @param mode the configured mode; an absent one is reported by {@link #problems} + * @param activeProfiles the active Spring profiles + * @throws GraphQlPlatformConfigurationException when the mode is not permitted + */ + public void validateRuntimeEnvironment( + GraphQlDeploymentMode mode, Collection activeProfiles) { + RuntimeEnvironment runtime = RuntimeEnvironment.resolve(activeProfiles).orElse(null); + if (mode == null || runtime == null || mode.permittedIn(runtime)) { + return; + } + throw new GraphQlPlatformConfigurationException( + List.of( + "backend.graphql.deployment-mode=" + + mode + + " is not permitted in the " + + runtime.profileName() + + " runtime; permitted here: " + + Arrays.stream(GraphQlDeploymentMode.values()) + .filter(candidate -> candidate.permittedIn(runtime)) + .toList())); + } + /** * Validates the beans the context actually assembled, not the ones the platform ships. * diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlRetiredSafetyAxis.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlRetiredSafetyAxis.java index 55b71a3c..ee420079 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlRetiredSafetyAxis.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlRetiredSafetyAxis.java @@ -18,7 +18,7 @@ import org.springframework.core.env.Environment; * state that produced the defect: two keys that can disagree about one question, with the winner * decided by whichever code path happens to read which. * - *

Only checked while the master switch is on. An adapter that is off has no configuration + *

Only checked while the capability switch is on. An adapter that is off has no configuration * surface to be wrong about, and a repository-wide property left over in someone's shell must not * stop an application that never publishes a GraphQL endpoint. */ @@ -39,10 +39,10 @@ public final class GraphQlRetiredSafetyAxis { * Returns one migration error per retired key that is still set, in a deterministic order. * * @param environment the resolved environment - * @return the problems; empty when the master switch is off or no retired key is present + * @return the problems; empty when the capability switch is off or no retired key is present */ public static List problems(Environment environment) { - if (!"true".equalsIgnoreCase(environment.getProperty("backend.graphql.enabled", "false"))) { + if (!"true".equalsIgnoreCase(environment.getProperty("backend.graphql.enabled", "true"))) { return List.of(); } List problems = new ArrayList<>(); diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlRootAutoConfiguration.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlRootAutoConfiguration.java index a012a182..1be8e1dd 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlRootAutoConfiguration.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlRootAutoConfiguration.java @@ -8,17 +8,21 @@ import org.springframework.context.annotation.Import; /** * The one place that decides whether this application exposes a GraphQL endpoint. * - *

The platform configuration this imports carried no master condition of any kind, so putting - * the leaf on the classpath would have activated it — which is why the leaf was kept out of the - * shipped jar entirely, and why "off" and "not built" had become the same thing. + *

On when present: an application that selected this module wants GraphQL, so a missing {@code + * backend.graphql.enabled} means on. Absent from the build is the ordinary off state. * *

An inbound adapter's off contract is not only about beans. Spring GraphQL publishes {@code - * /graphql} from its own auto-configuration, with no project bean involved, so the companion import - * filter has to keep those candidates out of the set as well. A bean-inventory assertion cannot see - * a route the framework published. + * /graphql} from its own auto-configuration, with no project bean involved, so an explicit {@code + * backend.graphql.enabled=false} also excludes those auto-configurations — see {@link + * GraphQlActivationEnvironmentPostProcessor}. A bean-inventory assertion cannot see a route the + * framework published. */ @AutoConfiguration -@ConditionalOnProperty(prefix = "backend.graphql", name = "enabled", havingValue = "true") +@ConditionalOnProperty( + prefix = "backend.graphql", + name = "enabled", + havingValue = "true", + matchIfMissing = true) @EnableConfigurationProperties(GraphQlPlatformSettings.class) @Import({ GraphQlPlatformAutoConfiguration.class, diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/compat/GraphQlChangeKind.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/compat/GraphQlChangeKind.java deleted file mode 100644 index e47efeef..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/compat/GraphQlChangeKind.java +++ /dev/null @@ -1,285 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.compat; - -/** - * Every schema change the comparator can classify, with its wire and generated-client impact - * (design §8.1). - * - *

The impacts live on the kind rather than being decided at each call site, so the compatibility - * table is stated once and cannot drift between the comparator, the policy and the release gate. - */ -public enum GraphQlChangeKind { - - /** A new type appeared. */ - TYPE_ADDED( - GraphQlCompatibilityImpact.COMPATIBLE, - GraphQlCompatibilityImpact.COMPATIBLE, - "new type is additive"), - - /** A type disappeared; every operation selecting it breaks. */ - TYPE_REMOVED( - GraphQlCompatibilityImpact.BREAKING, - GraphQlCompatibilityImpact.BREAKING, - "removing a type breaks existing operations"), - - /** A nullable output field appeared. */ - OUTPUT_FIELD_ADDED_NULLABLE( - GraphQlCompatibilityImpact.COMPATIBLE, - GraphQlCompatibilityImpact.COMPATIBLE, - "new nullable output field is additive"), - - /** A non-null output field appeared; the data guarantee must be verified. */ - OUTPUT_FIELD_ADDED_NON_NULL( - GraphQlCompatibilityImpact.COMPATIBLE, - GraphQlCompatibilityImpact.REVIEW_REQUIRED, - "new non-null output field changes generated models and requires a data guarantee"), - - /** An output field disappeared. */ - OUTPUT_FIELD_REMOVED( - GraphQlCompatibilityImpact.BREAKING, - GraphQlCompatibilityImpact.BREAKING, - "removing an output field breaks existing operations"), - - /** An output field became nullable; clients that relied on the guarantee break. */ - OUTPUT_FIELD_NULLABILITY_RELAXED( - GraphQlCompatibilityImpact.BREAKING, - GraphQlCompatibilityImpact.BREAKING, - "output T! to T withdraws a guarantee clients depend on"), - - /** An output field became non-null; wire-compatible but changes generated source types. */ - OUTPUT_FIELD_NULLABILITY_STRENGTHENED( - GraphQlCompatibilityImpact.COMPATIBLE, - GraphQlCompatibilityImpact.REVIEW_REQUIRED, - "output T to T! strengthens the contract but changes generated source types"), - - /** An output field changed to an unrelated type. */ - OUTPUT_FIELD_TYPE_CHANGED( - GraphQlCompatibilityImpact.BREAKING, - GraphQlCompatibilityImpact.BREAKING, - "changing an output field type breaks existing selections"), - - /** An optional argument appeared. */ - ARGUMENT_ADDED_OPTIONAL( - GraphQlCompatibilityImpact.COMPATIBLE, - GraphQlCompatibilityImpact.COMPATIBLE, - "new optional argument is additive"), - - /** A required argument appeared; every existing call omits it. */ - ARGUMENT_ADDED_REQUIRED( - GraphQlCompatibilityImpact.BREAKING, - GraphQlCompatibilityImpact.BREAKING, - "new required argument invalidates existing operations"), - - /** An argument disappeared. */ - ARGUMENT_REMOVED( - GraphQlCompatibilityImpact.BREAKING, - GraphQlCompatibilityImpact.BREAKING, - "removing an argument breaks existing operations"), - - /** An argument became required. */ - ARGUMENT_TYPE_STRENGTHENED( - GraphQlCompatibilityImpact.BREAKING, - GraphQlCompatibilityImpact.BREAKING, - "argument T to T! invalidates existing operations"), - - /** An argument became optional. */ - ARGUMENT_TYPE_RELAXED( - GraphQlCompatibilityImpact.COMPATIBLE, - GraphQlCompatibilityImpact.REVIEW_REQUIRED, - "argument T! to T is accepting but changes generated models"), - - /** An argument changed to an unrelated type. */ - ARGUMENT_TYPE_CHANGED( - GraphQlCompatibilityImpact.BREAKING, - GraphQlCompatibilityImpact.BREAKING, - "changing an argument type breaks existing operations"), - - /** An optional input field appeared. */ - INPUT_FIELD_ADDED_OPTIONAL( - GraphQlCompatibilityImpact.COMPATIBLE, - GraphQlCompatibilityImpact.COMPATIBLE, - "new optional input field is additive"), - - /** A required input field appeared. */ - INPUT_FIELD_ADDED_REQUIRED( - GraphQlCompatibilityImpact.BREAKING, - GraphQlCompatibilityImpact.BREAKING, - "new required input field invalidates existing variables"), - - /** An input field disappeared. */ - INPUT_FIELD_REMOVED( - GraphQlCompatibilityImpact.BREAKING, - GraphQlCompatibilityImpact.BREAKING, - "removing an input field breaks existing variables"), - - /** An input field became required. */ - INPUT_FIELD_STRENGTHENED( - GraphQlCompatibilityImpact.BREAKING, - GraphQlCompatibilityImpact.BREAKING, - "input T to T! invalidates existing variables"), - - /** An input field became optional. */ - INPUT_FIELD_RELAXED( - GraphQlCompatibilityImpact.COMPATIBLE, - GraphQlCompatibilityImpact.REVIEW_REQUIRED, - "input T! to T is accepting but changes generated models"), - - /** An input field changed to an unrelated type. */ - INPUT_FIELD_TYPE_CHANGED( - GraphQlCompatibilityImpact.BREAKING, - GraphQlCompatibilityImpact.BREAKING, - "changing an input field type breaks existing variables"), - - /** An enum value appeared; additive on the wire, risky for exhaustive generated switches. */ - ENUM_VALUE_ADDED( - GraphQlCompatibilityImpact.COMPATIBLE, - GraphQlCompatibilityImpact.REVIEW_REQUIRED, - "new output enum value can break exhaustive generated clients"), - - /** An enum value disappeared. */ - ENUM_VALUE_REMOVED( - GraphQlCompatibilityImpact.BREAKING, - GraphQlCompatibilityImpact.BREAKING, - "removing an enum value breaks existing operations"), - - /** A union member appeared. */ - UNION_MEMBER_ADDED( - GraphQlCompatibilityImpact.COMPATIBLE, - GraphQlCompatibilityImpact.REVIEW_REQUIRED, - "new union member can break exhaustive generated clients"), - - /** A union member disappeared. */ - UNION_MEMBER_REMOVED( - GraphQlCompatibilityImpact.BREAKING, - GraphQlCompatibilityImpact.BREAKING, - "removing a union member breaks existing operations"), - - /** An interface implementation appeared. */ - INTERFACE_IMPLEMENTATION_ADDED( - GraphQlCompatibilityImpact.COMPATIBLE, - GraphQlCompatibilityImpact.REVIEW_REQUIRED, - "new interface implementation can break exhaustive generated clients"), - - /** An interface implementation disappeared. */ - INTERFACE_IMPLEMENTATION_REMOVED( - GraphQlCompatibilityImpact.BREAKING, - GraphQlCompatibilityImpact.BREAKING, - "removing an interface implementation breaks existing fragments"), - - /** A scalar appeared. */ - SCALAR_ADDED( - GraphQlCompatibilityImpact.COMPATIBLE, - GraphQlCompatibilityImpact.COMPATIBLE, - "new scalar is additive"), - - /** A scalar disappeared. */ - SCALAR_REMOVED( - GraphQlCompatibilityImpact.BREAKING, - GraphQlCompatibilityImpact.BREAKING, - "removing a scalar breaks existing operations"), - - /** - * A scalar's SDL declaration changed. - * - *

Not a coercion change. Whether {@code DateTime} still parses the same strings is a property - * of its {@code Coercing} implementation, which the SDL does not contain — swapping the codec - * while leaving the SDL alone was invisible here, and editing the description raised a false - * breaking change. Coercion compatibility belongs to the scalar manifest's codec version, and - * this kind now says only what it can see. - */ - SCALAR_DECLARATION_CHANGED( - GraphQlCompatibilityImpact.REVIEW_REQUIRED, - GraphQlCompatibilityImpact.REVIEW_REQUIRED, - "a changed scalar declaration needs its manifest codec version checked for a coercion change"), - - /** - * A type kept its name but changed kind, such as {@code type Foo} becoming {@code input Foo}. - * - *

Compared before anything else. Field-by-field comparison of two different kinds produces - * plausible per-field findings and misses the only one that matters: every operation naming the - * type breaks, whatever its fields now are. - */ - TYPE_KIND_CHANGED( - GraphQlCompatibilityImpact.BREAKING, - GraphQlCompatibilityImpact.BREAKING, - "a type that changed kind breaks every operation naming it"), - - /** - * A default value was removed from an argument or input field. - * - *

Breaking for a non-null input: the default was the reason omitting it was legal. - */ - INPUT_DEFAULT_REMOVED( - GraphQlCompatibilityImpact.BREAKING, - GraphQlCompatibilityImpact.BREAKING, - "removing a default makes a previously omissible input required"), - - /** A default value changed, so an omitted input now means something different. */ - INPUT_DEFAULT_CHANGED( - GraphQlCompatibilityImpact.REVIEW_REQUIRED, - GraphQlCompatibilityImpact.REVIEW_REQUIRED, - "a changed default silently changes what an omitted input means"), - - /** A default value was added, which makes a previously required input omissible. */ - INPUT_DEFAULT_ADDED( - GraphQlCompatibilityImpact.COMPATIBLE, - GraphQlCompatibilityImpact.REVIEW_REQUIRED, - "a new default is accepting but changes generated models"), - - /** - * The directives applied to a schema element changed. - * - *

Distinct from a directive definition change. {@code @deprecated} appearing on a field, or - * {@code @oneOf} disappearing from an input, changes what clients are told and what the engine - * enforces, and comparing only definitions could not see either. - */ - APPLIED_DIRECTIVE_CHANGED( - GraphQlCompatibilityImpact.REVIEW_REQUIRED, - GraphQlCompatibilityImpact.REVIEW_REQUIRED, - "a change to applied directives changes advertised or enforced behaviour"), - - /** A directive definition appeared. */ - DIRECTIVE_ADDED( - GraphQlCompatibilityImpact.COMPATIBLE, - GraphQlCompatibilityImpact.COMPATIBLE, - "new directive is additive"), - - /** A directive definition disappeared. */ - DIRECTIVE_REMOVED( - GraphQlCompatibilityImpact.BREAKING, - GraphQlCompatibilityImpact.BREAKING, - "removing a directive breaks documents that use it"), - - /** A directive definition changed; the meaning may have changed with it. */ - DIRECTIVE_CHANGED( - GraphQlCompatibilityImpact.REVIEW_REQUIRED, - GraphQlCompatibilityImpact.REVIEW_REQUIRED, - "directive semantics change requires behavioural compatibility review"); - - private final GraphQlCompatibilityImpact wireImpact; - private final GraphQlCompatibilityImpact generatedClientImpact; - private final String reason; - - GraphQlChangeKind( - GraphQlCompatibilityImpact wireImpact, - GraphQlCompatibilityImpact generatedClientImpact, - String reason) { - this.wireImpact = wireImpact; - this.generatedClientImpact = generatedClientImpact; - this.reason = reason; - } - - /** Effect on the wire contract. */ - public GraphQlCompatibilityImpact wireImpact() { - return wireImpact; - } - - /** Effect on generated client source. */ - public GraphQlCompatibilityImpact generatedClientImpact() { - return generatedClientImpact; - } - - /** Why this classification holds. */ - public String reason() { - return reason; - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/compat/GraphQlClientOwnerApproval.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/compat/GraphQlClientOwnerApproval.java deleted file mode 100644 index f47a29a0..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/compat/GraphQlClientOwnerApproval.java +++ /dev/null @@ -1,40 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.compat; - -import java.time.Instant; - -/** - * A client owner's recorded approval for removing a deprecated schema element. - * - *

The record deliberately has no credential field at all: it holds who approved, why, and when. - * Removal approvals end up in release evidence and audit trails, so the type must be safe to - * persist and print in full. - * - * @param owner bounded reference to the approving client owner, for example a team handle - * @param reason why removal is acceptable for that client - * @param approvedAt when the approval was given - */ -public record GraphQlClientOwnerApproval(String owner, String reason, Instant approvedAt) { - - private static final int MAXIMUM_OWNER_LENGTH = 128; - private static final int MAXIMUM_REASON_LENGTH = 512; - - public GraphQlClientOwnerApproval { - if (owner == null || owner.isBlank() || owner.length() > MAXIMUM_OWNER_LENGTH) { - throw new IllegalArgumentException("approval owner reference is required and bounded"); - } - if (owner.contains("\n") || owner.contains("\r")) { - throw new IllegalArgumentException("approval owner reference must be a single line"); - } - if (reason == null || reason.isBlank() || reason.length() > MAXIMUM_REASON_LENGTH) { - throw new IllegalArgumentException("approval reason is required and bounded"); - } - if (approvedAt == null) { - throw new IllegalArgumentException("approval instant is required"); - } - } - - /** Stable description for the release report. */ - public String describe() { - return owner + " approved at " + approvedAt + ": " + reason; - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/compat/GraphQlCompatibilityImpact.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/compat/GraphQlCompatibilityImpact.java deleted file mode 100644 index f1c0d907..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/compat/GraphQlCompatibilityImpact.java +++ /dev/null @@ -1,20 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.compat; - -/** - * How severely a schema change affects one audience. - * - *

Wire impact and generated-client impact are tracked separately on purpose. Adding an enum - * value or a union member is additive on the wire, yet it can break a generated client whose {@code - * switch} is exhaustive — reporting a single "compatible" verdict would hide that. - */ -public enum GraphQlCompatibilityImpact { - - /** No action needed for this audience. */ - COMPATIBLE, - - /** Allowed, but a client owner has to look at it before release. */ - REVIEW_REQUIRED, - - /** Rejected by the Stable compatibility policy. */ - BREAKING -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/compat/GraphQlCompatibilityPolicy.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/compat/GraphQlCompatibilityPolicy.java deleted file mode 100644 index 1476785f..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/compat/GraphQlCompatibilityPolicy.java +++ /dev/null @@ -1,63 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.compat; - -import dev.caskeleton.adapter.inbound.graphql.schema.GraphQlContractVersion; -import java.util.List; - -/** - * Decides whether a compatibility report may be released (design §23, {@code - * backend.graphql.schema.compatibility-policy}). - * - *

The Stable policy refuses any breaking wire change outright — field or type removal, a new - * required argument or input field, an input strengthened to non-null, an output relaxed to - * nullable, a removed enum value or union member, and a changed scalar coercion, which needs a new - * scalar or a new scalar manifest version rather than an in-place edit. Additive changes that only - * affect generated client source are allowed but reported, so a client owner sees them before - * release. - */ -public final class GraphQlCompatibilityPolicy { - - private final GraphQlContractVersion version; - private final boolean breakingAllowed; - - private GraphQlCompatibilityPolicy(GraphQlContractVersion version, boolean breakingAllowed) { - this.version = version; - this.breakingAllowed = breakingAllowed; - } - - /** The Stable policy: no breaking wire change may ship. */ - public static GraphQlCompatibilityPolicy stableV1() { - return new GraphQlCompatibilityPolicy(GraphQlContractVersion.of("stable-v1"), false); - } - - /** - * A policy for an explicitly versioned breaking release. - * - *

Used only when a new major schema contract version is being published on purpose. - */ - public static GraphQlCompatibilityPolicy breakingRelease(GraphQlContractVersion version) { - return new GraphQlCompatibilityPolicy(version, true); - } - - /** The policy version this decision was made under. */ - public GraphQlContractVersion version() { - return version; - } - - /** Whether the report may be released under this policy. */ - public boolean permits(GraphQlCompatibilityReport report) { - return rejections(report).isEmpty(); - } - - /** Why the report was rejected, in deterministic order; empty when it is allowed. */ - public List rejections(GraphQlCompatibilityReport report) { - if (breakingAllowed) { - return List.of(); - } - return report.breakingChanges().stream().map(GraphQlSchemaChange::describe).toList(); - } - - /** Changes that are allowed but need a client owner's review before release. */ - public List reviewNotices(GraphQlCompatibilityReport report) { - return report.reviewChanges().stream().map(GraphQlSchemaChange::describe).toList(); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/compat/GraphQlCompatibilityReport.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/compat/GraphQlCompatibilityReport.java deleted file mode 100644 index a3a72d75..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/compat/GraphQlCompatibilityReport.java +++ /dev/null @@ -1,50 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.compat; - -import java.util.List; - -/** - * The classified differences between a deployed schema and a candidate schema. - * - *

Changes are held in a deterministic order so two runs over the same pair of schemas produce - * byte-identical reports — a release gate that cannot be diffed is not much of a gate. - * - * @param changes classified changes, ordered by coordinate then kind - */ -public record GraphQlCompatibilityReport(List changes) { - - public GraphQlCompatibilityReport { - changes = List.copyOf(changes); - } - - /** A report with no differences. */ - public static GraphQlCompatibilityReport identical() { - return new GraphQlCompatibilityReport(List.of()); - } - - /** Whether any change breaks the wire contract. */ - public boolean breaking() { - return changes.stream().anyMatch(GraphQlSchemaChange::breaking); - } - - /** Whether any change needs a client owner's review. */ - public boolean reviewRequired() { - return changes.stream().anyMatch(GraphQlSchemaChange::reviewRequired); - } - - /** Only the breaking changes. */ - public List breakingChanges() { - return changes.stream().filter(GraphQlSchemaChange::breaking).toList(); - } - - /** Only the changes that need review. */ - public List reviewChanges() { - return changes.stream() - .filter(change -> change.reviewRequired() && !change.breaking()) - .toList(); - } - - /** Changes of one kind. */ - public List changesOf(GraphQlChangeKind kind) { - return changes.stream().filter(change -> change.kind() == kind).toList(); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/compat/GraphQlDeprecationGate.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/compat/GraphQlDeprecationGate.java deleted file mode 100644 index 79f2b155..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/compat/GraphQlDeprecationGate.java +++ /dev/null @@ -1,91 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.compat; - -import java.time.Duration; -import java.time.Instant; -import java.util.ArrayList; -import java.util.List; - -/** - * The removal gate for deprecated schema elements (design §8.1). - * - *

Deprecation is a process, not a flag: an element may be removed only once it was actually - * marked deprecated, its usage was measured and found to be zero, the support window has elapsed, - * no registered persisted operation still references it, and the client owner has approved. Each of - * those is checked independently and every failure is reported, so one review round shows the whole - * remaining distance rather than the first obstacle. - * - *

Unknown usage never counts as zero usage — that substitution is the most common way a "safe" - * removal breaks a client nobody was measuring. - */ -public final class GraphQlDeprecationGate { - - private final Duration supportWindow; - - /** - * Creates a gate with an explicit support window. - * - * @param supportWindow how long a deprecated element must remain available after deprecation - */ - public GraphQlDeprecationGate(Duration supportWindow) { - if (supportWindow == null || supportWindow.isNegative()) { - throw new IllegalArgumentException("support window must not be negative"); - } - this.supportWindow = supportWindow; - } - - /** The configured support window. */ - public Duration supportWindow() { - return supportWindow; - } - - /** - * Evaluates usage alone. - * - *

A pre-check for tooling that only has the usage signal: unknown or observed usage already - * blocks removal, so the rest of the evidence does not need collecting. - */ - public static GraphQlRemovalDecision evaluate(GraphQlSchemaUsage usage) { - if (usage == null || !usage.measured()) { - return GraphQlRemovalDecision.blocked("usage is unknown and cannot be treated as zero usage"); - } - if (!usage.provenUnused()) { - return GraphQlRemovalDecision.blocked( - "element is still in use: " + usage.executions() + " observed executions"); - } - return GraphQlRemovalDecision.allow(); - } - - /** Evaluates the full removal evidence. */ - public GraphQlRemovalDecision evaluate(GraphQlRemovalRequest request, Instant now) { - List blockers = new ArrayList<>(); - - if (request.requiredInputElement()) { - blockers.add( - "a required non-null argument or input field cannot be removed through deprecation; " - + "make it nullable or give it a default first"); - } - if (request.deprecatedSince() == null) { - blockers.add("element was never marked @deprecated"); - } else if (request.deprecatedSince().plus(supportWindow).isAfter(now)) { - blockers.add("support window has not elapsed"); - } - - GraphQlRemovalDecision usageDecision = evaluate(request.usage()); - if (!usageDecision.allowed()) { - blockers.addAll(usageDecision.reasons()); - } - - if (request.persistedOperationReferences() > 0) { - blockers.add( - request.persistedOperationReferences() - + " registered persisted operations still reference this element"); - } - if (request.approval() == null) { - blockers.add("client owner approval is missing"); - } - - return blockers.isEmpty() - ? GraphQlRemovalDecision.allow() - : GraphQlRemovalDecision.blocked(blockers); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/compat/GraphQlRemovalDecision.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/compat/GraphQlRemovalDecision.java deleted file mode 100644 index 8258b335..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/compat/GraphQlRemovalDecision.java +++ /dev/null @@ -1,51 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.compat; - -import java.util.ArrayList; -import java.util.List; - -/** - * Whether a deprecated schema element may be removed, and why not when it may not. - * - *

Every blocking reason is kept rather than only the first, so one review round shows everything - * that still has to happen before the element can go. - * - * @param allowed whether removal may proceed - * @param reasons blocking reasons, empty when allowed - */ -public record GraphQlRemovalDecision(boolean allowed, List reasons) { - - public GraphQlRemovalDecision { - reasons = List.copyOf(reasons); - if (allowed && !reasons.isEmpty()) { - throw new IllegalArgumentException("an allowed removal cannot carry blocking reasons"); - } - if (!allowed && reasons.isEmpty()) { - throw new IllegalArgumentException("a blocked removal must state a reason"); - } - } - - /** Removal is blocked for a single reason. */ - public static GraphQlRemovalDecision blocked(String reason) { - return new GraphQlRemovalDecision(false, List.of(reason)); - } - - /** Removal is blocked for several reasons. */ - public static GraphQlRemovalDecision blocked(List reasons) { - return new GraphQlRemovalDecision(false, List.copyOf(reasons)); - } - - /** Removal may proceed. */ - public static GraphQlRemovalDecision allow() { - return new GraphQlRemovalDecision(true, List.of()); - } - - /** Combines two decisions, keeping every blocking reason. */ - public GraphQlRemovalDecision and(GraphQlRemovalDecision other) { - if (allowed && other.allowed) { - return allow(); - } - List combined = new ArrayList<>(reasons); - combined.addAll(other.reasons); - return blocked(combined); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/compat/GraphQlRemovalRequest.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/compat/GraphQlRemovalRequest.java deleted file mode 100644 index 64fe8efa..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/compat/GraphQlRemovalRequest.java +++ /dev/null @@ -1,39 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.compat; - -import java.time.Instant; - -/** - * Everything the deprecation gate needs to decide one removal. - * - *

Grouped into a value so the gate cannot be called with half the evidence: usage, deprecation - * start, persisted-operation references and owner approval are all required inputs, and a missing - * one has to be visible rather than defaulted. - * - * @param coordinate schema coordinate being removed - * @param usage what is known about its usage - * @param deprecatedSince when {@code @deprecated} was applied, or {@code null} when it never was - * @param persistedOperationReferences how many registered persisted operations still reference it - * @param approval the client owner's approval, or {@code null} when none was recorded - * @param requiredInputElement whether this is a required non-null argument or input field without a - * default - */ -public record GraphQlRemovalRequest( - String coordinate, - GraphQlSchemaUsage usage, - Instant deprecatedSince, - int persistedOperationReferences, - GraphQlClientOwnerApproval approval, - boolean requiredInputElement) { - - public GraphQlRemovalRequest { - if (coordinate == null || coordinate.isBlank()) { - throw new IllegalArgumentException("removal coordinate is required"); - } - if (usage == null) { - throw new IllegalArgumentException("removal usage observation is required"); - } - if (persistedOperationReferences < 0) { - throw new IllegalArgumentException("persisted operation references cannot be negative"); - } - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/compat/GraphQlSchemaChange.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/compat/GraphQlSchemaChange.java deleted file mode 100644 index 6a3e086f..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/compat/GraphQlSchemaChange.java +++ /dev/null @@ -1,61 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.compat; - -/** - * One classified difference between two schema versions. - * - *

Every change reports where it happened, what kind it is, what it does to the wire contract, - * what it does to generated client source, and why — so a release decision can be read from the - * report instead of re-derived from an SDL diff. - * - * @param coordinate type name, {@code TypeName.fieldName}, or {@code TypeName.fieldName(argument)} - * @param kind classified change - * @param wireImpact effect on the wire contract - * @param generatedClientImpact effect on generated client source - * @param reason why this classification holds - */ -public record GraphQlSchemaChange( - String coordinate, - GraphQlChangeKind kind, - GraphQlCompatibilityImpact wireImpact, - GraphQlCompatibilityImpact generatedClientImpact, - String reason) { - - public GraphQlSchemaChange { - if (coordinate == null || coordinate.isBlank()) { - throw new IllegalArgumentException("schema change coordinate is required"); - } - if (kind == null || wireImpact == null || generatedClientImpact == null) { - throw new IllegalArgumentException("schema change classification is required"); - } - } - - /** Creates a change using the kind's declared impacts and reason. */ - public static GraphQlSchemaChange of(String coordinate, GraphQlChangeKind kind) { - return new GraphQlSchemaChange( - coordinate, kind, kind.wireImpact(), kind.generatedClientImpact(), kind.reason()); - } - - /** Whether this change breaks the wire contract. */ - public boolean breaking() { - return wireImpact == GraphQlCompatibilityImpact.BREAKING; - } - - /** Whether a client owner has to review this change before release. */ - public boolean reviewRequired() { - return wireImpact == GraphQlCompatibilityImpact.REVIEW_REQUIRED - || generatedClientImpact == GraphQlCompatibilityImpact.REVIEW_REQUIRED; - } - - /** Stable, content-free description for the release report. */ - public String describe() { - return kind.name() - + " " - + coordinate - + " [wire=" - + wireImpact - + ", client=" - + generatedClientImpact - + "] " - + reason; - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/compat/GraphQlSchemaComparator.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/compat/GraphQlSchemaComparator.java deleted file mode 100644 index 177cd5f3..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/compat/GraphQlSchemaComparator.java +++ /dev/null @@ -1,791 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.compat; - -import graphql.language.AstPrinter; -import graphql.language.EnumTypeDefinition; -import graphql.language.EnumTypeExtensionDefinition; -import graphql.language.EnumValueDefinition; -import graphql.language.FieldDefinition; -import graphql.language.ImplementingTypeDefinition; -import graphql.language.InputObjectTypeDefinition; -import graphql.language.InputObjectTypeExtensionDefinition; -import graphql.language.InputValueDefinition; -import graphql.language.InterfaceTypeDefinition; -import graphql.language.InterfaceTypeExtensionDefinition; -import graphql.language.NonNullType; -import graphql.language.ObjectTypeDefinition; -import graphql.language.ObjectTypeExtensionDefinition; -import graphql.language.ScalarTypeDefinition; -import graphql.language.Type; -import graphql.language.TypeDefinition; -import graphql.language.UnionTypeDefinition; -import graphql.language.UnionTypeExtensionDefinition; -import graphql.schema.idl.ScalarInfo; -import graphql.schema.idl.SchemaParser; -import graphql.schema.idl.TypeDefinitionRegistry; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeSet; -import java.util.function.Function; -import java.util.stream.Collectors; - -/** - * Classifies every difference between a deployed schema and a candidate schema (design §8.1). - * - *

This is deliberately not an SDL text diff. Whether a change is breaking depends on direction - * and position: {@code T! → T} is breaking on output and accepting on input, a new argument is - * breaking only when it is required, and a new enum value is fine on the wire while it can still - * break a generated client. Comparison walks the parsed type system so those distinctions survive, - * and it sorts its output so the same pair of schemas always produces the same report. - */ -public final class GraphQlSchemaComparator { - - private static final Comparator DETERMINISTIC_ORDER = - Comparator.comparing(GraphQlSchemaChange::coordinate) - .thenComparing(change -> change.kind().name()); - - private GraphQlSchemaComparator() {} - - /** Compares two SDL documents. */ - public static GraphQlCompatibilityReport compare(String previousSdl, String candidateSdl) { - SchemaParser parser = new SchemaParser(); - return compare(parser.parse(previousSdl), parser.parse(candidateSdl)); - } - - /** Compares two parsed schemas. */ - public static GraphQlCompatibilityReport compare( - TypeDefinitionRegistry previous, TypeDefinitionRegistry candidate) { - - List changes = new ArrayList<>(); - - // Extensions folded in first. A registry keeps `extend type Query { … }` in a separate map from - // `type Query { … }`, so a comparison that reads only the base definitions cannot see a field - // an extension contributed — and cannot see it disappear either. Every schema that composes - // from several files is exactly this shape, which made the omission a breaking change the gate - // reported as no change at all. - Map> previousTypes = withExtensions(previous); - Map> candidateTypes = withExtensions(candidate); - - compareTypePresence(previousTypes, candidateTypes, changes); - compareTypeKinds(previousTypes, candidateTypes, changes); - compareOutputTypes(previousTypes, candidateTypes, changes); - compareInputTypes(previousTypes, candidateTypes, changes); - compareEnums(previousTypes, candidateTypes, changes); - compareUnions(previousTypes, candidateTypes, changes); - compareScalars(previous, candidate, changes); - compareDirectives(previous, candidate, changes); - compareAppliedDirectives(previousTypes, candidateTypes, changes); - - return new GraphQlCompatibilityReport(changes.stream().sorted(DETERMINISTIC_ORDER).toList()); - } - - /** - * Every type definition with the members its extensions contribute already merged in. - * - *

The merged form is what a client sees: the engine builds one type out of the base - * declaration and every extension of it, and a field's origin is invisible on the wire. - */ - private static Map> withExtensions(TypeDefinitionRegistry registry) { - Map> merged = new LinkedHashMap<>(); - registry.types().forEach((name, type) -> merged.put(name, mergeExtensions(registry, type))); - return merged; - } - - // graphql.language.Type stays raw here; see the note on typeNames. - @SuppressWarnings("rawtypes") - private static TypeDefinition mergeExtensions( - TypeDefinitionRegistry registry, TypeDefinition type) { - - String name = type.getName(); - if (type instanceof ObjectTypeDefinition object) { - List extensions = - registry.objectTypeExtensions().getOrDefault(name, List.of()); - if (extensions.isEmpty()) { - return object; - } - List fields = new ArrayList<>(object.getFieldDefinitions()); - List interfaces = new ArrayList<>(object.getImplements()); - List directives = new ArrayList<>(object.getDirectives()); - extensions.forEach( - extension -> { - fields.addAll(extension.getFieldDefinitions()); - interfaces.addAll(extension.getImplements()); - directives.addAll(extension.getDirectives()); - }); - return object.transform( - builder -> - builder.fieldDefinitions(fields).implementz(interfaces).directives(directives)); - } - if (type instanceof InterfaceTypeDefinition definition) { - List extensions = - registry.interfaceTypeExtensions().getOrDefault(name, List.of()); - if (extensions.isEmpty()) { - return definition; - } - List fields = new ArrayList<>(definition.getFieldDefinitions()); - List interfaces = new ArrayList<>(definition.getImplements()); - List directives = new ArrayList<>(definition.getDirectives()); - extensions.forEach( - extension -> { - fields.addAll(extension.getFieldDefinitions()); - interfaces.addAll(extension.getImplements()); - directives.addAll(extension.getDirectives()); - }); - return definition.transform( - builder -> builder.definitions(fields).implementz(interfaces).directives(directives)); - } - if (type instanceof InputObjectTypeDefinition input) { - List extensions = - registry.inputObjectTypeExtensions().getOrDefault(name, List.of()); - if (extensions.isEmpty()) { - return input; - } - List fields = new ArrayList<>(input.getInputValueDefinitions()); - List directives = new ArrayList<>(input.getDirectives()); - extensions.forEach( - extension -> { - fields.addAll(extension.getInputValueDefinitions()); - directives.addAll(extension.getDirectives()); - }); - return input.transform( - builder -> builder.inputValueDefinitions(fields).directives(directives)); - } - if (type instanceof EnumTypeDefinition enumeration) { - List extensions = - registry.enumTypeExtensions().getOrDefault(name, List.of()); - if (extensions.isEmpty()) { - return enumeration; - } - List values = new ArrayList<>(enumeration.getEnumValueDefinitions()); - List directives = new ArrayList<>(enumeration.getDirectives()); - extensions.forEach( - extension -> { - values.addAll(extension.getEnumValueDefinitions()); - directives.addAll(extension.getDirectives()); - }); - return enumeration.transform( - builder -> builder.enumValueDefinitions(values).directives(directives)); - } - if (type instanceof UnionTypeDefinition union) { - List extensions = - registry.unionTypeExtensions().getOrDefault(name, List.of()); - if (extensions.isEmpty()) { - return union; - } - List members = new ArrayList<>(union.getMemberTypes()); - List directives = new ArrayList<>(union.getDirectives()); - extensions.forEach( - extension -> { - members.addAll(extension.getMemberTypes()); - directives.addAll(extension.getDirectives()); - }); - return union.transform(builder -> builder.memberTypes(members).directives(directives)); - } - return type; - } - - /** The merged definitions of one kind. */ - private static > Map typesOf( - Map> types, Class kind) { - Map selected = new LinkedHashMap<>(); - types.forEach( - (name, type) -> { - if (kind.isInstance(type)) { - selected.put(name, kind.cast(type)); - } - }); - return selected; - } - - private static void compareTypePresence( - Map> previous, - Map> candidate, - List changes) { - - Set previousTypes = new TreeSet<>(previous.keySet()); - Set candidateTypes = new TreeSet<>(candidate.keySet()); - - previousTypes.stream() - .filter(name -> !candidateTypes.contains(name)) - .forEach(name -> changes.add(GraphQlSchemaChange.of(name, GraphQlChangeKind.TYPE_REMOVED))); - candidateTypes.stream() - .filter(name -> !previousTypes.contains(name)) - .forEach(name -> changes.add(GraphQlSchemaChange.of(name, GraphQlChangeKind.TYPE_ADDED))); - } - - /** - * Reports types that kept their name and changed kind. - * - *

Runs before the per-kind comparisons, which only ever look at types of their own kind and - * would therefore report {@code type Foo -> input Foo} as a removal from one map and an addition - * to another, or as nothing at all. - */ - private static void compareTypeKinds( - Map> previousTypes, - Map> candidateTypes, - List changes) { - - for (String name : new TreeSet<>(previousTypes.keySet())) { - TypeDefinition after = candidateTypes.get(name); - if (after == null) { - continue; - } - if (!previousTypes.get(name).getClass().equals(after.getClass())) { - changes.add(GraphQlSchemaChange.of(name, GraphQlChangeKind.TYPE_KIND_CHANGED)); - } - } - } - - /** - * Reports changes to the directives applied to types and their fields. - * - *

Applied directives, not definitions: {@code @deprecated} appearing on a field and - * {@code @oneOf} disappearing from an input are both behaviour changes that leave every directive - * definition untouched. - */ - private static void compareAppliedDirectives( - Map> previousTypes, - Map> candidateTypes, - List changes) { - - for (String name : new TreeSet<>(previousTypes.keySet())) { - TypeDefinition before = previousTypes.get(name); - TypeDefinition after = candidateTypes.get(name); - if (after == null || !before.getClass().equals(after.getClass())) { - continue; - } - if (!appliedDirectives(before).equals(appliedDirectives(after))) { - changes.add(GraphQlSchemaChange.of(name, GraphQlChangeKind.APPLIED_DIRECTIVE_CHANGED)); - } - if (before instanceof ImplementingTypeDefinition beforeType - && after instanceof ImplementingTypeDefinition afterType) { - compareFieldDirectives(name, beforeType, afterType, changes); - } - } - } - - private static void compareFieldDirectives( - String typeName, - ImplementingTypeDefinition before, - ImplementingTypeDefinition after, - List changes) { - - Map candidateFields = - byName(after.getFieldDefinitions(), FieldDefinition::getName); - for (FieldDefinition field : before.getFieldDefinitions()) { - FieldDefinition candidateField = candidateFields.get(field.getName()); - if (candidateField == null) { - continue; - } - if (!appliedDirectives(field).equals(appliedDirectives(candidateField))) { - changes.add( - GraphQlSchemaChange.of( - typeName + "." + field.getName(), GraphQlChangeKind.APPLIED_DIRECTIVE_CHANGED)); - } - } - } - - /** Applied directives, printed and sorted so declaration order is not a change. */ - private static Set appliedDirectives(graphql.language.Node node) { - List directives = - node instanceof graphql.language.DirectivesContainer container - ? container.getDirectives() - : List.of(); - return directives.stream() - .map(GraphQlSchemaComparator::print) - .collect(Collectors.toCollection(TreeSet::new)); - } - - /** - * Reports a change to an input's default value. - * - *

A default is part of the input contract: removing one from a non-null input makes every - * request that omitted the field invalid, and changing one silently changes what omitting it - * means. Neither shows up as a type change, which is all the comparator used to look at. - */ - private static void compareInputDefault( - String coordinate, - InputValueDefinition before, - InputValueDefinition after, - List changes) { - - String beforeDefault = - before.getDefaultValue() == null ? null : print(before.getDefaultValue()); - String afterDefault = after.getDefaultValue() == null ? null : print(after.getDefaultValue()); - if (java.util.Objects.equals(beforeDefault, afterDefault)) { - return; - } - if (beforeDefault == null) { - changes.add(GraphQlSchemaChange.of(coordinate, GraphQlChangeKind.INPUT_DEFAULT_ADDED)); - } else if (afterDefault == null) { - changes.add(GraphQlSchemaChange.of(coordinate, GraphQlChangeKind.INPUT_DEFAULT_REMOVED)); - } else { - changes.add(GraphQlSchemaChange.of(coordinate, GraphQlChangeKind.INPUT_DEFAULT_CHANGED)); - } - } - - private static void compareOutputTypes( - Map> previous, - Map> candidate, - List changes) { - - Map> previousTypes = implementingTypes(previous); - Map> candidateTypes = implementingTypes(candidate); - - for (String typeName : new TreeSet<>(previousTypes.keySet())) { - ImplementingTypeDefinition before = previousTypes.get(typeName); - ImplementingTypeDefinition after = candidateTypes.get(typeName); - if (after == null) { - continue; - } - compareOutputFields(typeName, before, after, changes); - compareInterfaces(typeName, before, after, changes); - } - } - - private static void compareOutputFields( - String typeName, - ImplementingTypeDefinition before, - ImplementingTypeDefinition after, - List changes) { - - Map previousFields = - byName(before.getFieldDefinitions(), FieldDefinition::getName); - Map candidateFields = - byName(after.getFieldDefinitions(), FieldDefinition::getName); - - for (String fieldName : new TreeSet<>(previousFields.keySet())) { - String coordinate = typeName + "." + fieldName; - FieldDefinition previousField = previousFields.get(fieldName); - FieldDefinition candidateField = candidateFields.get(fieldName); - if (candidateField == null) { - changes.add(GraphQlSchemaChange.of(coordinate, GraphQlChangeKind.OUTPUT_FIELD_REMOVED)); - continue; - } - compareOutputFieldType( - coordinate, previousField.getType(), candidateField.getType(), changes); - compareArguments(coordinate, previousField, candidateField, changes); - } - - candidateFields.keySet().stream() - .filter(fieldName -> !previousFields.containsKey(fieldName)) - .sorted() - .forEach( - fieldName -> - changes.add( - GraphQlSchemaChange.of( - typeName + "." + fieldName, - nonNull(candidateFields.get(fieldName).getType()) - ? GraphQlChangeKind.OUTPUT_FIELD_ADDED_NON_NULL - : GraphQlChangeKind.OUTPUT_FIELD_ADDED_NULLABLE))); - } - - // graphql.language.Type stays raw here; see the note on typeNames. - @SuppressWarnings("rawtypes") - private static void compareOutputFieldType( - String coordinate, Type before, Type after, List changes) { - - if (sameType(before, after)) { - return; - } - if (nonNull(before) && !nonNull(after) && sameType(unwrap(before), after)) { - changes.add( - GraphQlSchemaChange.of(coordinate, GraphQlChangeKind.OUTPUT_FIELD_NULLABILITY_RELAXED)); - return; - } - if (!nonNull(before) && nonNull(after) && sameType(before, unwrap(after))) { - changes.add( - GraphQlSchemaChange.of( - coordinate, GraphQlChangeKind.OUTPUT_FIELD_NULLABILITY_STRENGTHENED)); - return; - } - changes.add(GraphQlSchemaChange.of(coordinate, GraphQlChangeKind.OUTPUT_FIELD_TYPE_CHANGED)); - } - - private static void compareArguments( - String fieldCoordinate, - FieldDefinition before, - FieldDefinition after, - List changes) { - - Map previousArguments = - byName(before.getInputValueDefinitions(), InputValueDefinition::getName); - Map candidateArguments = - byName(after.getInputValueDefinitions(), InputValueDefinition::getName); - - for (String argumentName : new TreeSet<>(previousArguments.keySet())) { - String coordinate = fieldCoordinate + "(" + argumentName + ")"; - InputValueDefinition previousArgument = previousArguments.get(argumentName); - InputValueDefinition candidateArgument = candidateArguments.get(argumentName); - if (candidateArgument == null) { - changes.add(GraphQlSchemaChange.of(coordinate, GraphQlChangeKind.ARGUMENT_REMOVED)); - continue; - } - compareInputValueType( - coordinate, - previousArgument.getType(), - candidateArgument.getType(), - GraphQlChangeKind.ARGUMENT_TYPE_STRENGTHENED, - GraphQlChangeKind.ARGUMENT_TYPE_RELAXED, - GraphQlChangeKind.ARGUMENT_TYPE_CHANGED, - changes); - } - - candidateArguments.keySet().stream() - .filter(argumentName -> !previousArguments.containsKey(argumentName)) - .sorted() - .forEach( - argumentName -> - changes.add( - GraphQlSchemaChange.of( - fieldCoordinate + "(" + argumentName + ")", - required(candidateArguments.get(argumentName)) - ? GraphQlChangeKind.ARGUMENT_ADDED_REQUIRED - : GraphQlChangeKind.ARGUMENT_ADDED_OPTIONAL))); - } - - private static void compareInterfaces( - String typeName, - ImplementingTypeDefinition before, - ImplementingTypeDefinition after, - List changes) { - - Set previousInterfaces = typeNames(before.getImplements()); - Set candidateInterfaces = typeNames(after.getImplements()); - - previousInterfaces.stream() - .filter(name -> !candidateInterfaces.contains(name)) - .sorted() - .forEach( - name -> - changes.add( - GraphQlSchemaChange.of( - typeName + " implements " + name, - GraphQlChangeKind.INTERFACE_IMPLEMENTATION_REMOVED))); - candidateInterfaces.stream() - .filter(name -> !previousInterfaces.contains(name)) - .sorted() - .forEach( - name -> - changes.add( - GraphQlSchemaChange.of( - typeName + " implements " + name, - GraphQlChangeKind.INTERFACE_IMPLEMENTATION_ADDED))); - } - - private static void compareInputTypes( - Map> previous, - Map> candidate, - List changes) { - - Map previousTypes = - typesOf(previous, InputObjectTypeDefinition.class); - Map candidateTypes = - typesOf(candidate, InputObjectTypeDefinition.class); - - for (String typeName : new TreeSet<>(previousTypes.keySet())) { - InputObjectTypeDefinition after = candidateTypes.get(typeName); - if (after == null) { - continue; - } - Map previousFields = - byName( - previousTypes.get(typeName).getInputValueDefinitions(), - InputValueDefinition::getName); - Map candidateFields = - byName(after.getInputValueDefinitions(), InputValueDefinition::getName); - - for (String fieldName : new TreeSet<>(previousFields.keySet())) { - String coordinate = typeName + "." + fieldName; - InputValueDefinition candidateField = candidateFields.get(fieldName); - if (candidateField == null) { - changes.add(GraphQlSchemaChange.of(coordinate, GraphQlChangeKind.INPUT_FIELD_REMOVED)); - continue; - } - compareInputValueType( - coordinate, - previousFields.get(fieldName).getType(), - candidateField.getType(), - GraphQlChangeKind.INPUT_FIELD_STRENGTHENED, - GraphQlChangeKind.INPUT_FIELD_RELAXED, - GraphQlChangeKind.INPUT_FIELD_TYPE_CHANGED, - changes); - compareInputDefault(coordinate, previousFields.get(fieldName), candidateField, changes); - } - - candidateFields.keySet().stream() - .filter(fieldName -> !previousFields.containsKey(fieldName)) - .sorted() - .forEach( - fieldName -> - changes.add( - GraphQlSchemaChange.of( - typeName + "." + fieldName, - required(candidateFields.get(fieldName)) - ? GraphQlChangeKind.INPUT_FIELD_ADDED_REQUIRED - : GraphQlChangeKind.INPUT_FIELD_ADDED_OPTIONAL))); - } - } - - // graphql.language.Type stays raw here; see the note on typeNames. - @SuppressWarnings("rawtypes") - private static void compareInputValueType( - String coordinate, - Type before, - Type after, - GraphQlChangeKind strengthened, - GraphQlChangeKind relaxed, - GraphQlChangeKind changed, - List changes) { - - if (sameType(before, after)) { - return; - } - if (!nonNull(before) && nonNull(after) && sameType(before, unwrap(after))) { - changes.add(GraphQlSchemaChange.of(coordinate, strengthened)); - return; - } - if (nonNull(before) && !nonNull(after) && sameType(unwrap(before), after)) { - changes.add(GraphQlSchemaChange.of(coordinate, relaxed)); - return; - } - changes.add(GraphQlSchemaChange.of(coordinate, changed)); - } - - private static void compareEnums( - Map> previous, - Map> candidate, - List changes) { - - Map previousTypes = typesOf(previous, EnumTypeDefinition.class); - Map candidateTypes = typesOf(candidate, EnumTypeDefinition.class); - - for (String typeName : new TreeSet<>(previousTypes.keySet())) { - EnumTypeDefinition after = candidateTypes.get(typeName); - if (after == null) { - continue; - } - Set previousValues = names(previousTypes.get(typeName).getEnumValueDefinitions()); - Set candidateValues = names(after.getEnumValueDefinitions()); - - previousValues.stream() - .filter(value -> !candidateValues.contains(value)) - .sorted() - .forEach( - value -> - changes.add( - GraphQlSchemaChange.of( - typeName + "." + value, GraphQlChangeKind.ENUM_VALUE_REMOVED))); - candidateValues.stream() - .filter(value -> !previousValues.contains(value)) - .sorted() - .forEach( - value -> - changes.add( - GraphQlSchemaChange.of( - typeName + "." + value, GraphQlChangeKind.ENUM_VALUE_ADDED))); - } - } - - private static void compareUnions( - Map> previous, - Map> candidate, - List changes) { - - Map previousTypes = typesOf(previous, UnionTypeDefinition.class); - Map candidateTypes = typesOf(candidate, UnionTypeDefinition.class); - - for (String typeName : new TreeSet<>(previousTypes.keySet())) { - UnionTypeDefinition after = candidateTypes.get(typeName); - if (after == null) { - continue; - } - Set previousMembers = typeNames(previousTypes.get(typeName).getMemberTypes()); - Set candidateMembers = typeNames(after.getMemberTypes()); - - previousMembers.stream() - .filter(member -> !candidateMembers.contains(member)) - .sorted() - .forEach( - member -> - changes.add( - GraphQlSchemaChange.of( - typeName + " = " + member, GraphQlChangeKind.UNION_MEMBER_REMOVED))); - candidateMembers.stream() - .filter(member -> !previousMembers.contains(member)) - .sorted() - .forEach( - member -> - changes.add( - GraphQlSchemaChange.of( - typeName + " = " + member, GraphQlChangeKind.UNION_MEMBER_ADDED))); - } - } - - private static void compareScalars( - TypeDefinitionRegistry previous, - TypeDefinitionRegistry candidate, - List changes) { - - Map previousScalars = customScalars(previous); - Map candidateScalars = customScalars(candidate); - - for (String name : new TreeSet<>(previousScalars.keySet())) { - ScalarTypeDefinition after = candidateScalars.get(name); - if (after == null) { - changes.add(GraphQlSchemaChange.of("scalar " + name, GraphQlChangeKind.SCALAR_REMOVED)); - continue; - } - if (!declaration(previousScalars.get(name)).equals(declaration(after))) { - changes.add( - GraphQlSchemaChange.of("scalar " + name, GraphQlChangeKind.SCALAR_DECLARATION_CHANGED)); - } - } - candidateScalars.keySet().stream() - .filter(name -> !previousScalars.containsKey(name)) - .sorted() - .forEach( - name -> - changes.add( - GraphQlSchemaChange.of("scalar " + name, GraphQlChangeKind.SCALAR_ADDED))); - } - - private static void compareDirectives( - TypeDefinitionRegistry previous, - TypeDefinitionRegistry candidate, - List changes) { - - Map previousDirectives = - previous.getDirectiveDefinitions(); - Map candidateDirectives = - candidate.getDirectiveDefinitions(); - - for (String name : new TreeSet<>(previousDirectives.keySet())) { - graphql.language.DirectiveDefinition after = candidateDirectives.get(name); - if (after == null) { - changes.add(GraphQlSchemaChange.of("@" + name, GraphQlChangeKind.DIRECTIVE_REMOVED)); - continue; - } - if (!print(previousDirectives.get(name)).equals(print(after))) { - changes.add(GraphQlSchemaChange.of("@" + name, GraphQlChangeKind.DIRECTIVE_CHANGED)); - } - } - candidateDirectives.keySet().stream() - .filter(name -> !previousDirectives.containsKey(name)) - .sorted() - .forEach( - name -> - changes.add(GraphQlSchemaChange.of("@" + name, GraphQlChangeKind.DIRECTIVE_ADDED))); - } - - private static Map> implementingTypes( - Map> merged) { - Map> types = new LinkedHashMap<>(); - typesOf(merged, ObjectTypeDefinition.class).forEach(types::put); - typesOf(merged, InterfaceTypeDefinition.class).forEach(types::put); - return types; - } - - /** - * A scalar's declaration without its description. - * - *

The declaration is compared because it is the only signal SDL carries about how a scalar - * coerces — the {@code Coercing} implementation behind it is Java, and swapping it changes the - * wire contract without changing a character of schema. Prose is not that signal: reporting a - * reworded sentence as a possible coercion change is how a review that matters gets approved - * without being read. - */ - private static String declaration(ScalarTypeDefinition scalar) { - return print(scalar.transform(builder -> builder.description(null))); - } - - private static Map customScalars(TypeDefinitionRegistry registry) { - return registry.scalars().entrySet().stream() - .filter(entry -> !ScalarInfo.isGraphqlSpecifiedScalar(entry.getKey())) - .collect( - Collectors.toMap( - Map.Entry::getKey, - Map.Entry::getValue, - (first, second) -> first, - LinkedHashMap::new)); - } - - private static Map byName(List values, Function nameOf) { - Map byName = new LinkedHashMap<>(); - values.forEach(value -> byName.put(nameOf.apply(value), value)); - return byName; - } - - private static Set names(List values) { - return values.stream() - .map(EnumValueDefinition::getName) - .collect(Collectors.toCollection(LinkedHashSet::new)); - } - - /** - * The names of a type reference list, taken exactly as graphql-java hands it over. - * - *

Every {@code TypeDefinition} in this class is parameterized. {@code graphql.language.Type} - * is not, and cannot be: graphql-java declares {@code Type} — its own bound is - * raw — and its collections are raw on both sides. {@code getImplements()} and {@code - * getMemberTypes()} return {@code List}, which is not assignable to {@code List>} because a raw element type is not a subtype of {@code Type} in an argument - * position; and {@code UnionTypeDefinition.Builder.memberTypes} takes {@code List} back, so - * a parameterized local cannot be handed to it either. Reading and writing are both raw. - * - *

So the rawness is admitted at the six members that touch {@code Type} rather than hidden - * behind defensive copies at every boundary. A copy would imply this class needed one, and the - * suppression is deliberately per-member rather than on the class so that a raw type introduced - * anywhere else here still surfaces. - * - *

The build does not enable {@code -Xlint:rawtypes}, so javac is silent either way; this - * exists for the editor's compiler, which is not silent and should not be made silent globally. - */ - @SuppressWarnings("rawtypes") - private static Set typeNames(List types) { - return types.stream() - .map(GraphQlSchemaComparator::print) - .collect(Collectors.toCollection(LinkedHashSet::new)); - } - - private static boolean required(InputValueDefinition definition) { - return nonNull(definition.getType()) && definition.getDefaultValue() == null; - } - - // graphql.language.Type stays raw here; see the note on typeNames. - @SuppressWarnings("rawtypes") - private static boolean nonNull(Type type) { - return type instanceof NonNullType; - } - - // graphql.language.Type stays raw here; see the note on typeNames. - @SuppressWarnings("rawtypes") - private static Type unwrap(Type type) { - return type instanceof NonNullType nonNullType ? nonNullType.getType() : type; - } - - // graphql.language.Type stays raw here; see the note on typeNames. - @SuppressWarnings("rawtypes") - private static boolean sameType(Type left, Type right) { - return print(left).equals(print(right)); - } - - private static String print(graphql.language.Node node) { - return AstPrinter.printAst(node).trim(); - } - - /** Names every definition kind the comparator understands, for coverage reporting. */ - public static Set>> comparedDefinitionKinds() { - return Set.of( - ObjectTypeDefinition.class, - InterfaceTypeDefinition.class, - InputObjectTypeDefinition.class, - EnumTypeDefinition.class, - UnionTypeDefinition.class, - ScalarTypeDefinition.class); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/compat/GraphQlSchemaUsage.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/compat/GraphQlSchemaUsage.java deleted file mode 100644 index 5d728d6c..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/compat/GraphQlSchemaUsage.java +++ /dev/null @@ -1,71 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.compat; - -import java.time.Instant; - -/** - * What is actually known about a schema element's usage. - * - *

The distinction that matters is {@link Observation#UNKNOWN} versus {@link - * Observation#OBSERVED_UNUSED}. "We have no usage data" and "we measured and nobody used it" look - * the same in a naive counter and mean opposite things for a removal decision — so the state is - * explicit and unknown never counts as zero. - * - * @param observation what the usage pipeline could establish - * @param executions observed executions in the observation window - * @param lastUsedAt when it was last used, or {@code null} when never or unknown - * @param observedSince start of the observation window, or {@code null} when unknown - */ -public record GraphQlSchemaUsage( - Observation observation, long executions, Instant lastUsedAt, Instant observedSince) { - - /** Confidence in the usage measurement. */ - public enum Observation { - /** No trustworthy usage data exists for this element. */ - UNKNOWN, - /** Usage was measured over a known window and was zero. */ - OBSERVED_UNUSED, - /** Usage was measured and the element is in use. */ - OBSERVED_USED - } - - public GraphQlSchemaUsage { - if (observation == null) { - throw new IllegalArgumentException("usage observation is required"); - } - if (executions < 0) { - throw new IllegalArgumentException("executions cannot be negative"); - } - if (observation == Observation.OBSERVED_USED && (executions == 0 || lastUsedAt == null)) { - throw new IllegalArgumentException( - "observed usage requires executions and a last-used instant"); - } - if (observation == Observation.OBSERVED_UNUSED && observedSince == null) { - throw new IllegalArgumentException("observed-unused requires an observation window start"); - } - } - - /** No trustworthy usage data — never treated as zero usage. */ - public static GraphQlSchemaUsage unknown() { - return new GraphQlSchemaUsage(Observation.UNKNOWN, 0, null, null); - } - - /** Measured over a window starting at {@code observedSince} and found unused. */ - public static GraphQlSchemaUsage observedUnused(Instant observedSince) { - return new GraphQlSchemaUsage(Observation.OBSERVED_UNUSED, 0, null, observedSince); - } - - /** Measured and found in use. */ - public static GraphQlSchemaUsage observedUsed(long executions, Instant lastUsedAt) { - return new GraphQlSchemaUsage(Observation.OBSERVED_USED, executions, lastUsedAt, null); - } - - /** Whether the measurement is trustworthy at all. */ - public boolean measured() { - return observation != Observation.UNKNOWN; - } - - /** Whether the element is known to be unused. */ - public boolean provenUnused() { - return observation == Observation.OBSERVED_UNUSED; - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlDocumentShapeAnalyzer.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlDocumentShapeAnalyzer.java index b9275d7f..cbed063b 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlDocumentShapeAnalyzer.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlDocumentShapeAnalyzer.java @@ -18,6 +18,7 @@ import graphql.parser.Parser; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; +import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; @@ -58,6 +59,11 @@ public final class GraphQlDocumentShapeAnalyzer { this.maximumVisitedNodes = maximumVisitedNodes; } + /** The traversal budget; a pre-execution walk that visits more selections is rejected. */ + public int maximumVisitedNodes() { + return maximumVisitedNodes; + } + /** Parses and measures a document. */ public GraphQlDocumentShape analyze(String document) { return analyze(Parser.parse(document)); @@ -137,6 +143,7 @@ public final class GraphQlDocumentShapeAnalyzer { * * @param document the parsed document * @param operation the selected operation, or {@code null} to check every operation + * @throws GraphQlStructuralLimitException when traversal exceeds the node budget */ public boolean selectsIntrospection(Document document, OperationDefinition operation) { Map fragments = new LinkedHashMap<>(); @@ -147,8 +154,10 @@ public final class GraphQlDocumentShapeAnalyzer { } List candidates = operation != null ? List.of(operation) : operations(document); + Set expanded = new HashSet<>(); + Counters counters = new Counters(); for (OperationDefinition candidate : candidates) { - if (selectsIntrospection(candidate.getSelectionSet(), fragments, new ArrayDeque<>())) { + if (selectsIntrospection(candidate.getSelectionSet(), fragments, expanded, counters)) { return true; } } @@ -167,7 +176,8 @@ public final class GraphQlDocumentShapeAnalyzer { /** * Rejects introspection reached by the selected operation. * - * @throws GraphQlStructuralLimitException when introspection is selected but not permitted + * @throws GraphQlStructuralLimitException when introspection is selected but not permitted, or + * when traversal exceeds the node budget */ public void verifyIntrospection( Document document, OperationDefinition operation, boolean introspectionAllowed) { @@ -189,30 +199,32 @@ public final class GraphQlDocumentShapeAnalyzer { private boolean selectsIntrospection( SelectionSet selectionSet, Map fragments, - Deque expansionPath) { + Set expanded, + Counters counters) { if (selectionSet == null) { return false; } for (Selection selection : selectionSet.getSelections()) { + counters.visit(maximumVisitedNodes); + if (selection instanceof Field field) { if (field.getName().startsWith(INTROSPECTION_FIELD_PREFIX) - || selectsIntrospection(field.getSelectionSet(), fragments, expansionPath)) { + || selectsIntrospection(field.getSelectionSet(), fragments, expanded, counters)) { return true; } } else if (selection instanceof InlineFragment inlineFragment) { - if (selectsIntrospection(inlineFragment.getSelectionSet(), fragments, expansionPath)) { + if (selectsIntrospection(inlineFragment.getSelectionSet(), fragments, expanded, counters)) { return true; } } else if (selection instanceof FragmentSpread spread) { + // Each fragment is expanded once per walk: whether it reaches introspection does not depend + // on where it is spread, and re-walking every spread makes nested double spreads cost + // 2^depth. The same set cuts fragment cycles. FragmentDefinition fragment = fragments.get(spread.getName()); - if (fragment == null || expansionPath.contains(spread.getName())) { - continue; - } - expansionPath.push(spread.getName()); - boolean found = selectsIntrospection(fragment.getSelectionSet(), fragments, expansionPath); - expansionPath.pop(); - if (found) { + if (fragment != null + && expanded.add(spread.getName()) + && selectsIntrospection(fragment.getSelectionSet(), fragments, expanded, counters)) { return true; } } diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlParserLimitPolicy.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlParserLimitPolicy.java deleted file mode 100644 index 8a741bf7..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlParserLimitPolicy.java +++ /dev/null @@ -1,61 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.cost; - -import java.util.Objects; - -/** - * Applies parser limits before the document reaches the parser (design §18). - * - *

The character check runs first and outside GraphQL Java. A parser has to allocate - * proportionally to its input, so checking size after handing the document over has already paid - * the cost the limit exists to avoid; token, whitespace and grammar-depth limits are then enforced - * by the parser itself through {@link GraphQlParserOptionsFactory}. - */ -public final class GraphQlParserLimitPolicy { - - private final GraphQlParserLimits limits; - - /** - * Creates the policy. - * - * @param limits per-profile parser limits - */ - public GraphQlParserLimitPolicy(GraphQlParserLimits limits) { - this.limits = Objects.requireNonNull(limits); - } - - /** The limits this policy enforces. */ - public GraphQlParserLimits limits() { - return limits; - } - - /** - * Verifies the document's size before parsing. - * - * @throws GraphQlParserRejectedException when the character budget is exceeded - */ - public void verifyDocument(String document) { - if (document == null || document.length() > limits.maxCharacters()) { - throw GraphQlParserRejectedException.characters( - document == null ? 0 : document.length(), limits.maxCharacters()); - } - } - - /** - * Verifies counts the parser reported. - * - * @throws GraphQlParserRejectedException when any budget is exceeded - */ - public void verifyParsedCounts(int tokens, int whitespaceTokens, int grammarRuleDepth) { - if (tokens > limits.maxTokens()) { - throw GraphQlParserRejectedException.tokens(tokens, limits.maxTokens()); - } - if (whitespaceTokens > limits.maxWhitespaceTokens()) { - throw GraphQlParserRejectedException.whitespaceTokens( - whitespaceTokens, limits.maxWhitespaceTokens()); - } - if (grammarRuleDepth > limits.maxGrammarRuleDepth()) { - throw GraphQlParserRejectedException.grammarDepth( - grammarRuleDepth, limits.maxGrammarRuleDepth()); - } - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlParserLimits.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlParserLimits.java deleted file mode 100644 index bbff885c..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlParserLimits.java +++ /dev/null @@ -1,58 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.cost; - -import dev.caskeleton.adapter.inbound.graphql.policy.GraphQlClientPolicy; - -/** - * Parser-level limits for one client profile (design §18). - * - *

GraphQL Java ships generous library ceilings — around a mebibyte of characters and fifteen - * thousand tokens — because it cannot know the API. Those are safety nets for the parser, not - * business limits for a public endpoint: a document a thousand times larger than any real query - * would still be accepted. The platform sets its own, much smaller, per-profile values. - * - * @param maxCharacters largest accepted document, in characters - * @param maxTokens largest accepted token count - * @param maxWhitespaceTokens largest accepted whitespace-token count - * @param maxGrammarRuleDepth deepest accepted grammar nesting - */ -public record GraphQlParserLimits( - int maxCharacters, int maxTokens, int maxWhitespaceTokens, int maxGrammarRuleDepth) { - - public GraphQlParserLimits { - if (maxCharacters < 1 || maxTokens < 1 || maxWhitespaceTokens < 1 || maxGrammarRuleDepth < 1) { - throw new IllegalArgumentException("all parser limits must be positive"); - } - } - - /** Fraction of a library ceiling the derived limits are capped at. */ - private static final double CEILING_FRACTION = 0.8; - - /** Deepest grammar nesting a realistic operation needs. */ - private static final int DERIVED_GRAMMAR_RULE_DEPTH = 128; - - /** - * Derives parser limits from a client policy. - * - *

Token and whitespace budgets are derived from the document budget rather than configured - * separately: they bound the same input, and two independent knobs would let one contradict the - * other. Each derived value is additionally capped below the library ceiling, so a profile can - * only ever be stricter than GraphQL Java's default — never a restatement of it. - */ - public static GraphQlParserLimits from(GraphQlClientPolicy policy) { - int characters = - Math.min( - policy.maxDocumentBytes(), ceiling(graphql.parser.ParserOptions.MAX_QUERY_CHARACTERS)); - return new GraphQlParserLimits( - characters, - Math.max( - 1, Math.min(characters / 4, ceiling(graphql.parser.ParserOptions.MAX_QUERY_TOKENS))), - Math.max( - 1, - Math.min(characters / 2, ceiling(graphql.parser.ParserOptions.MAX_WHITESPACE_TOKENS))), - Math.min(DERIVED_GRAMMAR_RULE_DEPTH, ceiling(graphql.parser.ParserOptions.MAX_RULE_DEPTH))); - } - - private static int ceiling(int libraryCeiling) { - return (int) (libraryCeiling * CEILING_FRACTION); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlParserOptionsFactory.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlParserOptionsFactory.java deleted file mode 100644 index 36ebb6d1..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlParserOptionsFactory.java +++ /dev/null @@ -1,43 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.cost; - -import graphql.parser.ParserOptions; - -/** - * Maps platform parser limits onto GraphQL Java parser options. - * - *

The mapping is exact rather than approximate: these are the values the parser actually - * enforces, so a mismatch would mean the platform advertises one limit and the engine applies - * another. - * - *

Parser error messages are redacted, because an unredacted message quotes the offending token — - * that is, part of the rejected document — straight back to the client. - */ -public final class GraphQlParserOptionsFactory { - - private GraphQlParserOptionsFactory() {} - - /** Builds parser options for the given limits. */ - public static ParserOptions create(GraphQlParserLimits limits) { - return ParserOptions.newParserOptions() - .maxCharacters(limits.maxCharacters()) - .maxTokens(limits.maxTokens()) - .maxWhitespaceTokens(limits.maxWhitespaceTokens()) - .maxRuleDepth(limits.maxGrammarRuleDepth()) - .redactTokenParserErrorMessages(true) - .captureIgnoredChars(false) - .captureLineComments(false) - .build(); - } - - /** - * Builds operation-document parser options and installs them as the JVM default. - * - *

GraphQL Java resolves default parser options statically, so a deployment that never installs - * them silently keeps the library ceilings. - */ - public static ParserOptions installOperationDefaults(GraphQlParserLimits limits) { - ParserOptions options = create(limits); - ParserOptions.setDefaultOperationParserOptions(options); - return options; - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlParserRejectedException.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlParserRejectedException.java deleted file mode 100644 index b567e28f..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlParserRejectedException.java +++ /dev/null @@ -1,52 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.cost; - -/** - * Raised when a document exceeds a parser limit. - * - *

Names the limit and the two counts, never the document — a rejected document is by definition - * hostile or malformed input and must not be echoed into a log or a response. - */ -public class GraphQlParserRejectedException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - /** Stable request-error code for every parser-limit rejection. */ - public static final String CODE = "GRAPHQL_DOCUMENT_LIMIT_EXCEEDED"; - - private final transient String limitName; - - private GraphQlParserRejectedException(String limitName, long observed, long allowed) { - super(CODE + " " + limitName + ": " + observed + " > " + allowed); - this.limitName = limitName; - } - - /** The document exceeded the character limit. */ - public static GraphQlParserRejectedException characters(long observed, long allowed) { - return new GraphQlParserRejectedException("CHARACTERS", observed, allowed); - } - - /** The document exceeded the token limit. */ - public static GraphQlParserRejectedException tokens(long observed, long allowed) { - return new GraphQlParserRejectedException("TOKENS", observed, allowed); - } - - /** The document exceeded the whitespace-token limit. */ - public static GraphQlParserRejectedException whitespaceTokens(long observed, long allowed) { - return new GraphQlParserRejectedException("WHITESPACE_TOKENS", observed, allowed); - } - - /** The document exceeded the grammar-depth limit. */ - public static GraphQlParserRejectedException grammarDepth(long observed, long allowed) { - return new GraphQlParserRejectedException("GRAMMAR_RULE_DEPTH", observed, allowed); - } - - /** The exceeded limit's name. */ - public String limitName() { - return limitName; - } - - /** The stable request-error code. */ - public String code() { - return CODE; - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlResponseByteLimiter.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlResponseByteLimiter.java deleted file mode 100644 index 18d48f8c..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlResponseByteLimiter.java +++ /dev/null @@ -1,60 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.cost; - -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicLong; - -/** - * Limits serialized response bytes as they are written. - * - *

Tracks whether the body has already been committed, because that changes what can be done - * about the overrun. Before commit the response can be replaced with an error; after commit the - * only honest outcome is to terminate the connection and record it as a partial response, since a - * truncated JSON body would otherwise reach the client as corrupt data. - */ -public final class GraphQlResponseByteLimiter { - - private final long maximumBytes; - private final AtomicLong written = new AtomicLong(); - private final AtomicBoolean committed = new AtomicBoolean(); - - /** - * Creates the limiter. - * - * @param maximumBytes largest accepted serialized size - */ - public GraphQlResponseByteLimiter(long maximumBytes) { - if (maximumBytes < 1) { - throw new IllegalArgumentException("maximum response bytes must be positive"); - } - this.maximumBytes = maximumBytes; - } - - /** Marks the HTTP body as committed; from here an overrun terminates the connection. */ - public void markCommitted() { - committed.set(true); - } - - /** Whether the body has been committed. */ - public boolean committed() { - return committed.get(); - } - - /** - * Records serialized bytes. - * - * @throws GraphQlRuntimeBudgetExceededException on the write that crosses the budget - */ - public void record(long byteCount) { - if (byteCount < 0) { - throw new IllegalArgumentException("byte count cannot be negative"); - } - if (written.addAndGet(byteCount) > maximumBytes) { - throw new GraphQlRuntimeBudgetExceededException("response bytes exceeded", committed.get()); - } - } - - /** Bytes recorded so far. */ - public long written() { - return written.get(); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlResponseNodeCounter.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlResponseNodeCounter.java deleted file mode 100644 index 86803ab4..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlResponseNodeCounter.java +++ /dev/null @@ -1,44 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.cost; - -import java.util.concurrent.atomic.AtomicLong; - -/** - * Counts response nodes as they are produced. - * - *

Separate from the byte limiter because it stops the wrong shape earlier: an unbounded child - * list is detectable at the millionth node, long before those nodes have been serialized into - * bytes. - */ -public final class GraphQlResponseNodeCounter { - - private final long maximumNodes; - private final AtomicLong nodes = new AtomicLong(); - - /** - * Creates the counter. - * - * @param maximumNodes largest accepted node count - */ - public GraphQlResponseNodeCounter(long maximumNodes) { - if (maximumNodes < 1) { - throw new IllegalArgumentException("maximum response nodes must be positive"); - } - this.maximumNodes = maximumNodes; - } - - /** - * Records one node. - * - * @throws GraphQlRuntimeBudgetExceededException on the node that crosses the budget - */ - public void record() { - if (nodes.incrementAndGet() > maximumNodes) { - throw new GraphQlRuntimeBudgetExceededException("response nodes exceeded"); - } - } - - /** Nodes recorded so far. */ - public long count() { - return nodes.get(); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlRuntimeBudget.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlRuntimeBudget.java deleted file mode 100644 index 4c0ce21d..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlRuntimeBudget.java +++ /dev/null @@ -1,28 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.cost; - -import dev.caskeleton.adapter.inbound.graphql.policy.GraphQlClientPolicy; - -/** - * Runtime response limits (design §18). - * - *

Pre-execution complexity is an estimate over the document; it cannot know that a list the - * schema says is bounded actually holds fifty thousand rows today. The runtime budget is what stops - * that response from being built, so nodes and bytes are limited separately: a million tiny nodes - * and a few enormous strings are different failures with different costs. - * - * @param maxResponseNodes largest accepted response node count - * @param maxResponseBytes largest accepted serialized response size - */ -public record GraphQlRuntimeBudget(long maxResponseNodes, long maxResponseBytes) { - - public GraphQlRuntimeBudget { - if (maxResponseNodes < 1 || maxResponseBytes < 1) { - throw new IllegalArgumentException("runtime budgets must be positive"); - } - } - - /** Derives the runtime budget from a client policy. */ - public static GraphQlRuntimeBudget from(GraphQlClientPolicy policy) { - return new GraphQlRuntimeBudget(policy.maxResponseNodes(), policy.maxResponseBytes()); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlRuntimeBudgetExceededException.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlRuntimeBudgetExceededException.java deleted file mode 100644 index 599673e0..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlRuntimeBudgetExceededException.java +++ /dev/null @@ -1,54 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.cost; - -/** - * Raised when a response exceeds its runtime node or byte budget. - * - *

Carries counts only — never the data that was being serialized, and never a variable value. - */ -public class GraphQlRuntimeBudgetExceededException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - /** Stable error code while the response body can still be replaced. */ - public static final String CODE = "GRAPHQL_RESPONSE_BUDGET_EXCEEDED"; - - /** - * Stable code once the body has been committed and the connection must be terminated. - * - *

A separate code because the client's situation is different: it has already received a - * prefix of a response that will never be completed. - */ - public static final String PARTIAL_RESPONSE_CODE = "PARTIAL_RESPONSE"; - - private final transient boolean responseCommitted; - - /** - * Creates the failure. - * - * @param message content-free description - */ - public GraphQlRuntimeBudgetExceededException(String message) { - this(message, false); - } - - /** - * Creates the failure. - * - * @param message content-free description - * @param responseCommitted whether the HTTP body had already started being written - */ - public GraphQlRuntimeBudgetExceededException(String message, boolean responseCommitted) { - super(message); - this.responseCommitted = responseCommitted; - } - - /** Whether the response body had already been committed when the budget was exceeded. */ - public boolean responseCommitted() { - return responseCommitted; - } - - /** The stable error code, which depends on whether the body was already committed. */ - public String code() { - return responseCommitted ? PARTIAL_RESPONSE_CODE : CODE; - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlRuntimeBudgetTracker.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlRuntimeBudgetTracker.java deleted file mode 100644 index c297de8b..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlRuntimeBudgetTracker.java +++ /dev/null @@ -1,95 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.cost; - -import dev.caskeleton.adapter.inbound.graphql.execution.GraphQlCancellation; -import java.util.Objects; - -/** - * Enforces the runtime response budget during execution (design §18). - * - *

Exceeding the budget cancels the request rather than merely failing the current field: without - * cancellation the resolvers and publishers already in flight would keep producing the response - * that was just rejected, which is the opposite of what a budget is for. - */ -public final class GraphQlRuntimeBudgetTracker { - - private final GraphQlRuntimeBudget budget; - private final GraphQlResponseNodeCounter nodes; - private final GraphQlResponseByteLimiter bytes; - private final GraphQlCancellation cancellation; - - /** - * Creates a tracker with its own cancellation signal. - * - * @param budget the runtime limits - */ - public GraphQlRuntimeBudgetTracker(GraphQlRuntimeBudget budget) { - this(budget, GraphQlCancellation.create()); - } - - /** - * Creates a tracker bound to the request's cancellation signal. - * - * @param budget the runtime limits - * @param cancellation signal cancelled when a budget is exceeded - */ - public GraphQlRuntimeBudgetTracker( - GraphQlRuntimeBudget budget, GraphQlCancellation cancellation) { - this.budget = Objects.requireNonNull(budget); - this.cancellation = Objects.requireNonNull(cancellation); - this.nodes = new GraphQlResponseNodeCounter(budget.maxResponseNodes()); - this.bytes = new GraphQlResponseByteLimiter(budget.maxResponseBytes()); - } - - /** The limits being enforced. */ - public GraphQlRuntimeBudget budget() { - return budget; - } - - /** The cancellation signal, so in-flight work can stop when a budget is exceeded. */ - public GraphQlCancellation cancellation() { - return cancellation; - } - - /** - * Records one response node. - * - * @throws GraphQlRuntimeBudgetExceededException on the node that crosses the budget - */ - public void recordNode() { - try { - nodes.record(); - } catch (GraphQlRuntimeBudgetExceededException ex) { - cancellation.cancel(); - throw ex; - } - } - - /** - * Records serialized bytes. - * - * @throws GraphQlRuntimeBudgetExceededException on the write that crosses the budget - */ - public void recordBytes(long byteCount) { - try { - bytes.record(byteCount); - } catch (GraphQlRuntimeBudgetExceededException ex) { - cancellation.cancel(); - throw ex; - } - } - - /** Marks the HTTP body as committed. */ - public void markResponseCommitted() { - bytes.markCommitted(); - } - - /** Nodes recorded so far. */ - public long nodeCount() { - return nodes.count(); - } - - /** Bytes recorded so far. */ - public long byteCount() { - return bytes.written(); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlFailureBoundary.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlFailureBoundary.java deleted file mode 100644 index 79950e05..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlFailureBoundary.java +++ /dev/null @@ -1,21 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.error; - -/** - * Where a field failure stops propagating (design §7.3). - * - *

A null on a non-null field does not stay local: the error climbs to the nearest nullable - * ancestor, nulling everything on the way. So nullability is a failure-isolation decision, not a - * data-shape one — marking an enrichment field non-null can delete an entire order from the - * response when an unrelated service is down. - */ -public enum GraphQlFailureBoundary { - - /** The field itself is nullable; a failure nulls only this field. */ - FIELD, - - /** The nearest nullable ancestor absorbs the failure. */ - PARENT, - - /** The failure reaches the root and the whole {@code data} becomes null. */ - ROOT -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlNullabilityContract.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlNullabilityContract.java deleted file mode 100644 index aa2df633..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlNullabilityContract.java +++ /dev/null @@ -1,67 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.error; - -import dev.caskeleton.adapter.inbound.graphql.api.GraphQlSchemaCoordinate; - -/** - * The declared failure behaviour of one field. - * - *

Making a field non-null is a promise that it can always be provided — including when a - * dependency is down and when authorization redacts it. Recording that promise explicitly is what - * lets a golden test hold it, and what makes adding {@code !} a reviewable decision rather than a - * typo. - * - * @param coordinate schema coordinate - * @param nonNull whether the field is declared non-null - * @param boundary where a failure on this field stops propagating - * @param externalEnrichment whether the value comes from a dependency that can be partially - * unavailable - */ -public record GraphQlNullabilityContract( - String coordinate, - boolean nonNull, - GraphQlFailureBoundary boundary, - boolean externalEnrichment) { - - public GraphQlNullabilityContract { - GraphQlSchemaCoordinate.parse(coordinate); - if (boundary == null) { - throw new IllegalArgumentException("failure boundary is required"); - } - if (nonNull && externalEnrichment) { - throw new IllegalArgumentException( - coordinate - + " is filled by an external dependency and cannot promise non-null; " - + "introduce it as nullable first"); - } - if (nonNull && boundary == GraphQlFailureBoundary.FIELD) { - throw new IllegalArgumentException( - coordinate + " is non-null, so a failure cannot stop at the field itself"); - } - } - - /** A nullable field: a failure nulls only this field. */ - public static GraphQlNullabilityContract nullable(String coordinate) { - return new GraphQlNullabilityContract(coordinate, false, GraphQlFailureBoundary.FIELD, false); - } - - /** A nullable field filled by an external dependency. */ - public static GraphQlNullabilityContract enrichment(String coordinate) { - return new GraphQlNullabilityContract(coordinate, false, GraphQlFailureBoundary.FIELD, true); - } - - /** A non-null field whose failure is absorbed by the nearest nullable ancestor. */ - public static GraphQlNullabilityContract nonNull(String coordinate) { - return new GraphQlNullabilityContract(coordinate, true, GraphQlFailureBoundary.PARENT, false); - } - - /** - * Whether authorization may redact this field by returning null. - * - *

It may not on a non-null field: redaction would violate the schema promise and take the - * parent object with it. Such a field needs a separate permission model rather than a silent - * null. - */ - public boolean redactableByAuthorization() { - return !nonNull; - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlRequestErrorMapper.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlRequestErrorMapper.java deleted file mode 100644 index 6f505cb7..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlRequestErrorMapper.java +++ /dev/null @@ -1,57 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.error; - -import dev.caskeleton.adapter.inbound.graphql.http.GraphQlHttpOutcome; -import java.util.List; - -/** - * Maps failures that happen before execution starts (design §16). - * - *

A separate mapper from the resolver one, because a {@code DataFetcherExceptionResolver} never - * sees these: parse and validation failures happen before any data fetcher is invoked. They also - * carry no response path, and they are the failures that produce a 4xx rather than a 200. - */ -public final class GraphQlRequestErrorMapper { - - private GraphQlRequestErrorMapper() {} - - /** Maps a transport or pre-execution outcome to a wire error. */ - public static GraphQlWireError map(GraphQlHttpOutcome outcome, GraphQlErrorContext context) { - if (!outcome.requestError()) { - throw new IllegalArgumentException(outcome + " is not a request error"); - } - return GraphQlWireError.of( - clientMessage(outcome), - GraphQlErrorCode.platform(GraphQlErrorCode.REQUEST_ERROR), - GraphQlErrorCategory.REQUEST, - context); - } - - /** Maps a parse or validation failure, keeping the engine's own client-safe description. */ - public static GraphQlWireError mapValidation( - List validationMessages, GraphQlErrorContext context) { - String message = - validationMessages == null || validationMessages.isEmpty() - ? clientMessage(GraphQlHttpOutcome.VALIDATION_ERROR) - : GraphQlInternalErrorMasker.safeMessage(String.join("; ", validationMessages)); - return GraphQlWireError.of( - message, - GraphQlErrorCode.platform(GraphQlErrorCode.REQUEST_ERROR), - GraphQlErrorCategory.REQUEST, - context); - } - - private static String clientMessage(GraphQlHttpOutcome outcome) { - return switch (outcome) { - case MALFORMED_REQUEST -> "요청 본문을 해석할 수 없습니다."; - case PARSE_ERROR -> "GraphQL 문서를 파싱할 수 없습니다."; - case VALIDATION_ERROR -> "GraphQL 문서가 스키마와 맞지 않습니다."; - case VARIABLE_COERCION_ERROR -> "변수 값을 선언된 타입으로 변환할 수 없습니다."; - case REQUEST_TOO_LARGE -> "요청이 허용된 크기를 초과했습니다."; - case UNSUPPORTED_METHOD -> "지원하지 않는 HTTP 메서드입니다."; - case UNSUPPORTED_MEDIA_TYPE -> "지원하지 않는 미디어 타입입니다."; - case NOT_ACCEPTABLE -> "허용 가능한 응답 미디어 타입이 없습니다."; - case SUCCESS, FIELD_ERROR -> - throw new IllegalArgumentException(outcome + " is not a request error"); - }; - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlSubscriptionExceptionResolver.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlSubscriptionExceptionResolver.java deleted file mode 100644 index 7451e888..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlSubscriptionExceptionResolver.java +++ /dev/null @@ -1,62 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.error; - -import java.util.List; - -/** - * Maps failures that happen after a subscription has already started streaming. - * - *

A separate resolver because the response has already been committed: there is no {@code data} - * to make partial and no status left to change. All that can be delivered is a terminal error on - * the stream, and the client's next move is to resubscribe — which is why the error must say - * whether that is worth doing. - */ -public final class GraphQlSubscriptionExceptionResolver { - - private final GraphQlExceptionResolver delegate; - - /** - * Creates the resolver. - * - * @param delegate resolver used for failures the application deliberately models - */ - public GraphQlSubscriptionExceptionResolver(GraphQlExceptionResolver delegate) { - if (delegate == null) { - throw new IllegalArgumentException("delegate exception resolver is required"); - } - this.delegate = delegate; - } - - /** A resolver that masks every source failure. */ - public static GraphQlSubscriptionExceptionResolver defaults() { - return new GraphQlSubscriptionExceptionResolver(GraphQlExceptionResolver.defaults()); - } - - /** - * Maps a failure raised by the subscription source after the stream began. - * - * @param failure the source failure - * @param context correlation context - */ - public List resolveStreamFailure( - Throwable failure, GraphQlErrorContext context) { - return List.of(delegate.resolve(failure, context)); - } - - /** The terminal error delivered when the source stops because the credential expired. */ - public GraphQlWireError credentialExpired(GraphQlErrorContext context) { - return GraphQlWireError.of( - "구독 자격 증명이 만료되어 스트림을 종료합니다.", - GraphQlErrorCode.platform(GraphQlErrorCode.AUTHORIZATION_DENIED), - GraphQlErrorCategory.AUTHORIZATION, - context); - } - - /** The terminal error delivered when the server is draining for shutdown. */ - public GraphQlWireError serverDraining(GraphQlErrorContext context) { - return GraphQlWireError.of( - "서버 종료로 스트림을 종료합니다. 다시 구독하세요.", - GraphQlErrorCode.platform(GraphQlErrorCode.DEPENDENCY_UNAVAILABLE), - GraphQlErrorCategory.DEPENDENCY, - context); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/execution/GraphQlCancellation.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/execution/GraphQlCancellation.java deleted file mode 100644 index 145cc782..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/execution/GraphQlCancellation.java +++ /dev/null @@ -1,93 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.execution; - -import java.util.Queue; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.atomic.AtomicBoolean; - -/** - * A request-scoped cancellation signal. - * - *

A timeout that only unblocks the caller is not a cancellation: the database statement, the - * HTTP call and the reactive publisher keep running, and under load that is how a slow dependency - * turns into an exhausted pool. Work registers a listener here so the deadline actually reaches it. - * - *

Cancellation is one-way, and each listener runs exactly once — listeners are drained from a - * queue rather than iterated, so a listener registered concurrently with cancellation is neither - * dropped nor run twice. - * - *

A listener that throws does not stop the rest. The drain used to abandon the queue at the - * first failure, which meant a downstream client that refused to close left the statement and the - * publisher behind it running — the leaks the later listeners existed to prevent, caused by the - * first one failing and hidden behind the exception that stopped it. Every listener is now - * attempted; the first failure is rethrown once the queue is empty, with the later ones attached to - * it as suppressed, so a second broken listener is not invisible until the first is fixed. - */ -public final class GraphQlCancellation { - - private final AtomicBoolean cancelled = new AtomicBoolean(); - private final Queue listeners = new ConcurrentLinkedQueue<>(); - - /** Creates an uncancelled signal. */ - public static GraphQlCancellation create() { - return new GraphQlCancellation(); - } - - /** Whether cancellation has been requested. */ - public boolean cancelled() { - return cancelled.get(); - } - - /** - * Registers work to stop when the request is cancelled. - * - *

If cancellation already happened, the listener runs immediately — a late registration must - * not silently outlive the request. - */ - public void onCancel(Runnable listener) { - if (listener == null) { - throw new IllegalArgumentException("cancellation listener is required"); - } - listeners.add(listener); - if (cancelled.get()) { - drain(); - } - } - - /** Requests cancellation; subsequent calls do nothing. */ - public void cancel() { - if (cancelled.compareAndSet(false, true)) { - drain(); - } - } - - /** - * Fails fast when the request has already been cancelled. - * - * @throws GraphQlRequestCancelledException when cancellation has been requested - */ - public void requireActive() { - if (cancelled.get()) { - throw new GraphQlRequestCancelledException(); - } - } - - private void drain() { - RuntimeException firstFailure = null; - Runnable listener = listeners.poll(); - while (listener != null) { - try { - listener.run(); - } catch (RuntimeException failure) { - if (firstFailure == null) { - firstFailure = failure; - } else { - firstFailure.addSuppressed(failure); - } - } - listener = listeners.poll(); - } - if (firstFailure != null) { - throw firstFailure; - } - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/execution/GraphQlDeadlinePropagator.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/execution/GraphQlDeadlinePropagator.java deleted file mode 100644 index a29025ee..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/execution/GraphQlDeadlinePropagator.java +++ /dev/null @@ -1,71 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.execution; - -import dev.caskeleton.adapter.inbound.graphql.context.GraphQlDeadline; -import dev.caskeleton.adapter.inbound.graphql.context.GraphQlRequestContext; -import java.time.Clock; -import java.time.Duration; - -/** - * Derives the layered budgets a request hands down (design §10). - * - *

The layers are separate because they mean different things and expire at different points: a - * transport handshake, the request execution, one resolver, one DataLoader batch, and — for a - * subscription — the connection itself. The last one is deliberately not derived from the request - * budget: a subscription is a long-lived stream, and applying a five-second request timeout to it - * would terminate every subscription five seconds after it started. - */ -public final class GraphQlDeadlinePropagator { - - private final Clock clock; - - /** - * Creates a propagator. - * - * @param clock clock used to measure what remains of the request budget - */ - public GraphQlDeadlinePropagator(Clock clock) { - if (clock == null) { - throw new IllegalArgumentException("clock is required"); - } - this.clock = clock; - } - - /** - * The request-level policy derived from the context deadline. - * - * @throws GraphQlRequestCancelledException when the budget is already exhausted - */ - public GraphQlTimeoutPolicy requestPolicy(GraphQlRequestContext context) { - Duration remaining = context.deadline().remaining(clock); - if (remaining.isZero() || remaining.isNegative()) { - throw new GraphQlRequestCancelledException(); - } - return new GraphQlTimeoutPolicy(remaining); - } - - /** A resolver budget clamped by what remains of the request. */ - public GraphQlResolverBudget resolverBudget( - GraphQlRequestContext context, String coordinate, Duration requested) { - return GraphQlResolverBudget.from(coordinate, requestPolicy(context), requested); - } - - /** A DataLoader batch budget clamped by what remains of the request. */ - public Duration dataLoaderBatchTimeout(GraphQlRequestContext context, Duration requested) { - return requestPolicy(context).child(requested); - } - - /** A database or HTTP client deadline clamped by what remains of the request. */ - public GraphQlDeadline downstreamDeadline(GraphQlRequestContext context, Duration requested) { - Duration clamped = requestPolicy(context).child(requested); - return GraphQlDeadline.after(clamped, clock); - } - - /** - * The lifetime of a subscription, which the request budget deliberately does not govern. - * - * @param maximumConnectionAge transport-level maximum age for the streaming connection - */ - public GraphQlDeadline subscriptionDeadline(Duration maximumConnectionAge) { - return GraphQlDeadline.after(maximumConnectionAge, clock); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/execution/GraphQlExecutionProfileValidator.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/execution/GraphQlExecutionProfileValidator.java deleted file mode 100644 index 78d72d47..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/execution/GraphQlExecutionProfileValidator.java +++ /dev/null @@ -1,59 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.execution; - -import dev.caskeleton.adapter.inbound.graphql.policy.GraphQlOperationType; -import dev.caskeleton.adapter.inbound.graphql.policy.ResolverExecutionType; - -/** - * Checks a resolver's execution type against the runtime profile at startup (design §10). - * - *

Both directions matter. On a reactive stack an unbridged blocking resolver starves the event - * loop. On a servlet stack a reactive resolver still has to be adapted explicitly, because - * otherwise something has to block waiting for it and where that happens is left to chance. - */ -public final class GraphQlExecutionProfileValidator { - - private GraphQlExecutionProfileValidator() {} - - /** - * Validates one resolver against a profile. - * - * @throws GraphQlExecutionProfileException when the combination cannot be served safely - */ - public static void validate( - GraphQlExecutionProfile profile, GraphQlResolverDescriptor descriptor) { - - if (profile == null || descriptor == null) { - throw new IllegalArgumentException("execution profile and resolver descriptor are required"); - } - - if (profile == GraphQlExecutionProfile.REACTIVE_WEBFLUX - && descriptor.executionType() == ResolverExecutionType.BLOCKING - && !descriptor.approvedBridge()) { - throw new GraphQlExecutionProfileException( - "blocking resolver requires bridge: " + descriptor.coordinate()); - } - - if (profile == GraphQlExecutionProfile.BLOCKING_MVC - && descriptor.executionType() == ResolverExecutionType.REACTIVE - && !descriptor.approvedBridge()) { - throw new GraphQlExecutionProfileException( - "reactive resolver requires an explicit adapter on the blocking profile: " - + descriptor.coordinate()); - } - - if (profile == GraphQlExecutionProfile.MIXED_CONTROLLED - && (descriptor.executionType() == ResolverExecutionType.BLOCKING - || descriptor.executionType() == ResolverExecutionType.REACTIVE) - && !descriptor.approvedBridge()) { - throw new GraphQlExecutionProfileException( - "the mixed profile requires every crossing to declare a bridge: " - + descriptor.coordinate()); - } - - if (descriptor.executionType() == ResolverExecutionType.STREAM - && descriptor.operationType() != GraphQlOperationType.SUBSCRIPTION) { - throw new GraphQlExecutionProfileException( - "stream resolver requires subscription: " + descriptor.coordinate()); - } - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/execution/GraphQlOperationNameInterceptor.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/execution/GraphQlOperationNameInterceptor.java deleted file mode 100644 index c1c710dd..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/execution/GraphQlOperationNameInterceptor.java +++ /dev/null @@ -1,55 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.execution; - -import dev.caskeleton.adapter.inbound.graphql.api.GraphQlClientProfileName; -import dev.caskeleton.adapter.inbound.graphql.api.GraphQlOperationId; -import dev.caskeleton.adapter.inbound.graphql.context.GraphQlRequestContext; -import java.util.Locale; - -/** - * Applies the operation-name policy and pins the operation identity onto the context. - * - *

Runs at the parse/validate stage, once the selected operation is known: this is where the - * context's placeholder operation identity is replaced with the real one, so everything downstream - * — cost, authorization, metrics, logs — refers to the same bounded name. - */ -public final class GraphQlOperationNameInterceptor { - - private final GraphQlOperationNamePolicy policy; - - /** - * Creates the interceptor. - * - * @param policy the operation-name policy in force - */ - public GraphQlOperationNameInterceptor(GraphQlOperationNamePolicy policy) { - if (policy == null) { - throw new IllegalArgumentException("operation name policy is required"); - } - this.policy = policy; - } - - /** - * Verifies the selection and returns the context bound to it. - * - * @throws GraphQlAnonymousOperationException when the profile requires a name and none was given - */ - public GraphQlRequestContext apply( - GraphQlRequestContext context, - GraphQlClientProfileName clientProfileName, - GraphQlOperationSelection selection) { - - policy.verify(clientProfileName, selection); - return context.withOperationId(new GraphQlOperationId(operationId(selection))); - } - - private static String operationId(GraphQlOperationSelection selection) { - String name = - selection.named() - ? selection.operationName() - : dev.caskeleton.adapter.inbound.graphql.api.GraphQlOperationName - .ANONYMOUS_OBSERVATION_VALUE; - // The operation id is the lowercase, bounded form of the operation name so metric and trace - // identities stay stable regardless of the client's casing. - return name.toLowerCase(Locale.ROOT).replace('_', '-'); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/execution/GraphQlOperationNamePolicy.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/execution/GraphQlOperationNamePolicy.java deleted file mode 100644 index 94cf5019..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/execution/GraphQlOperationNamePolicy.java +++ /dev/null @@ -1,85 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.execution; - -import dev.caskeleton.adapter.inbound.graphql.api.GraphQlClientProfileName; -import dev.caskeleton.adapter.inbound.graphql.api.GraphQlOperationName; - -/** - * Requires production operations to be named (design §18). - * - *

The specification permits a single anonymous operation, and locally that is convenient. In - * production it removes the only stable identity an operation has: traces, cost exceptions, the - * persisted registry and usage analytics all key on the operation name, and without one the - * alternative key is the raw document — unbounded, and full of variables. - * - *

A multi-operation document always requires a name, in every environment, because otherwise - * there is no defined answer to which operation runs. - */ -public final class GraphQlOperationNamePolicy { - - private final boolean production; - - private GraphQlOperationNamePolicy(boolean production) { - this.production = production; - } - - /** The production policy: named operations required. */ - public static GraphQlOperationNamePolicy production() { - return new GraphQlOperationNamePolicy(true); - } - - /** The local policy: a single anonymous operation is tolerated. */ - public static GraphQlOperationNamePolicy local() { - return new GraphQlOperationNamePolicy(false); - } - - /** Whether this policy is the production one. */ - public boolean productionProfile() { - return production; - } - - /** - * Verifies the selection for a client profile. - * - * @throws GraphQlAnonymousOperationException when a name is required and absent - */ - public void verify(GraphQlClientProfileName client, GraphQlOperationSelection selection) { - if (client == null || selection == null) { - throw new IllegalArgumentException("client profile and operation selection are required"); - } - boolean namedRequired = production && !GraphQlClientProfileName.ADMIN.equals(client.value()); - if (selection.operationsInDocument() > 1 && !selection.named()) { - throw new GraphQlAnonymousOperationException( - "operationName required for multi-operation document"); - } - if (namedRequired && !selection.named()) { - throw new GraphQlAnonymousOperationException("named operation required"); - } - if (selection.named() && GraphQlOperationName.parse(selection.operationName()).isEmpty()) { - // Validates the bounded naming pattern; an unbounded name would defeat the reason for - // requiring one at all. - throw new GraphQlAnonymousOperationException("named operation required"); - } - } - - /** - * Verifies that a persisted operation's registered name matches the request. - * - * @throws GraphQlAnonymousOperationException when they differ - */ - public void verifyPersistedName(String registeredName, GraphQlOperationSelection selection) { - if (!selection.persisted()) { - return; - } - if (registeredName == null || !registeredName.equals(selection.operationName())) { - throw new GraphQlAnonymousOperationException( - "persisted operation name does not match the request"); - } - } - - /** The bounded observation tag for a selection. */ - public String observationName(GraphQlOperationSelection selection) { - return selection.named() - ? selection.operationName() - : GraphQlOperationName.ANONYMOUS_OBSERVATION_VALUE; - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/execution/GraphQlResolverBudget.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/execution/GraphQlResolverBudget.java deleted file mode 100644 index 0ad5cbc5..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/execution/GraphQlResolverBudget.java +++ /dev/null @@ -1,32 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.execution; - -import java.time.Duration; - -/** - * The time budget for one resolver, derived from the request budget. - * - *

A per-resolver budget exists so one slow field cannot consume the whole request: the field - * fails, its value becomes null and the rest of the response still resolves. That is only sound - * when the resolver's own budget is clamped by what remains of the request — which is what {@link - * GraphQlTimeoutPolicy} guarantees. - * - * @param coordinate schema coordinate the budget belongs to - * @param budget time this resolver may take - */ -public record GraphQlResolverBudget(String coordinate, Duration budget) { - - public GraphQlResolverBudget { - if (coordinate == null || coordinate.isBlank()) { - throw new IllegalArgumentException("resolver coordinate is required"); - } - if (budget == null || budget.isZero() || budget.isNegative()) { - throw new IllegalArgumentException("resolver budget must be positive"); - } - } - - /** Derives a resolver budget from the request budget, clamped to what remains. */ - public static GraphQlResolverBudget from( - String coordinate, GraphQlTimeoutPolicy requestPolicy, Duration requested) { - return new GraphQlResolverBudget(coordinate, requestPolicy.child(requested)); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/execution/GraphQlResolverCatalog.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/execution/GraphQlResolverCatalog.java deleted file mode 100644 index edf98420..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/execution/GraphQlResolverCatalog.java +++ /dev/null @@ -1,61 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.execution; - -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Set; - -/** - * The registry of resolvers and how each of them executes. - * - *

Registration is what makes the profile check possible: an unregistered resolver cannot be - * checked against the runtime profile, so looking one up fails rather than assuming it is safe. - */ -public final class GraphQlResolverCatalog { - - private final Map descriptors = new LinkedHashMap<>(); - - /** - * Registers one resolver. - * - * @throws IllegalArgumentException when the coordinate is already registered - */ - public GraphQlResolverCatalog register(GraphQlResolverDescriptor descriptor) { - if (descriptor == null) { - throw new IllegalArgumentException("resolver descriptor is required"); - } - if (descriptors.putIfAbsent(descriptor.coordinate(), descriptor) != null) { - throw new IllegalArgumentException( - "duplicate resolver coordinate " + descriptor.coordinate()); - } - return this; - } - - /** - * Resolves a registered descriptor. - * - * @throws GraphQlExecutionProfileException when the coordinate is not registered - */ - public GraphQlResolverDescriptor require(String coordinate) { - GraphQlResolverDescriptor descriptor = descriptors.get(coordinate); - if (descriptor == null) { - throw new GraphQlExecutionProfileException("unregistered resolver " + coordinate); - } - return descriptor; - } - - /** Registered coordinates, used for startup reporting and bounded observation. */ - public Set coordinates() { - return Set.copyOf(descriptors.keySet()); - } - - /** - * Validates every registered resolver against a runtime profile. - * - * @throws GraphQlExecutionProfileException on the first incompatible resolver - */ - public void validateAll(GraphQlExecutionProfile profile) { - descriptors - .values() - .forEach(descriptor -> GraphQlExecutionProfileValidator.validate(profile, descriptor)); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/execution/GraphQlResolverDescriptor.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/execution/GraphQlResolverDescriptor.java deleted file mode 100644 index 5db63e2c..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/execution/GraphQlResolverDescriptor.java +++ /dev/null @@ -1,53 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.execution; - -import dev.caskeleton.adapter.inbound.graphql.api.GraphQlSchemaCoordinate; -import dev.caskeleton.adapter.inbound.graphql.policy.GraphQlOperationType; -import dev.caskeleton.adapter.inbound.graphql.policy.ResolverExecutionType; - -/** - * How one resolver executes, registered so the runtime profile can be checked against it. - * - *

The coordinate is validated as a bounded schema position, because this is also what the - * resolver observation is tagged with — a dynamic value here would become unbounded metric - * cardinality. - * - * @param coordinate schema coordinate the resolver serves - * @param executionType how the resolver executes - * @param approvedBridge whether an approved executor or scheduler bridge wraps it - * @param operationType root operation type the resolver belongs to - * @param publisherReturnType whether the resolver returns a {@code Publisher} - */ -public record GraphQlResolverDescriptor( - String coordinate, - ResolverExecutionType executionType, - boolean approvedBridge, - GraphQlOperationType operationType, - boolean publisherReturnType) { - - public GraphQlResolverDescriptor { - GraphQlSchemaCoordinate.parse(coordinate); - if (executionType == null || operationType == null) { - throw new IllegalArgumentException("resolver execution and operation type are required"); - } - if (executionType == ResolverExecutionType.STREAM) { - if (operationType != GraphQlOperationType.SUBSCRIPTION) { - throw new IllegalArgumentException("stream resolver requires subscription"); - } - if (!publisherReturnType) { - throw new IllegalArgumentException("stream resolver requires a Publisher return type"); - } - } - } - - /** Registers a query resolver. */ - public GraphQlResolverDescriptor( - String coordinate, ResolverExecutionType executionType, boolean approvedBridge) { - this(coordinate, executionType, approvedBridge, GraphQlOperationType.QUERY, false); - } - - /** Registers a subscription resolver. */ - public static GraphQlResolverDescriptor subscription(String coordinate) { - return new GraphQlResolverDescriptor( - coordinate, ResolverExecutionType.STREAM, false, GraphQlOperationType.SUBSCRIPTION, true); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlAcceptHeader.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlAcceptHeader.java deleted file mode 100644 index 6e9f4cd0..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlAcceptHeader.java +++ /dev/null @@ -1,151 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.http; - -import java.util.ArrayList; -import java.util.Comparator; -import java.util.List; -import java.util.Locale; -import java.util.regex.Pattern; - -/** - * A parsed {@code Accept} header, ordered the way the client asked for. - * - *

Two properties of the header are easy to drop and expensive to get wrong. {@code q=0} is not a - * weak preference, it is a refusal — {@code application/graphql-response+json;q=0} means "never - * send me that" — and quality ranks the client's alternatives against each other. Iterating the - * server's own preference list and returning the first type that appears anywhere in the header - * ignores both, which is how a refused media type gets sent as if it had been requested. - * - *

Parsing is done here rather than with the framework's {@code MediaType} because this module is - * framework free, and the grammar involved is a comma-separated list with one parameter that - * matters. A malformed entry is dropped rather than failing the request: a client that sends - * nonsense alongside a usable type gets the usable type, and one that sends only nonsense gets the - * same answer as one that sent nothing acceptable. - * - * @param type the type half, lowercased, for example {@code application} - * @param subtype the subtype half, lowercased, for example {@code graphql-response+json} - * @param quality the {@code q} parameter, defaulting to {@code 1.0} - * @param specificity how concrete the entry is: 2 for a full type, 1 for {@code type/*}, 0 for - * {@code * / *} - * @param order the entry's position in the header, which breaks ties in the client's stated order - */ -public record GraphQlAcceptHeader( - String type, String subtype, double quality, int specificity, int order) { - - private static final double DEFAULT_QUALITY = 1.0; - private static final String WILDCARD = "*"; - - // Precompiled with an explicit limit: String.split drops trailing empty results, which would - // silently change how a header ending in a comma is read. - private static final Pattern ENTRY_SEPARATOR = Pattern.compile(","); - private static final Pattern PARAMETER_SEPARATOR = Pattern.compile(";"); - - /** - * Parses an {@code Accept} header into entries ranked most acceptable first. - * - *

Ranked by quality, then by specificity, then by the order the client wrote them. Entries - * with {@code q=0} are dropped, because they are refusals and must never be selectable. - * - * @param accept the raw header, possibly {@code null} - */ - public static List parse(String accept) { - if (accept == null || accept.isBlank()) { - return List.of(); - } - List entries = new ArrayList<>(); - String[] parts = ENTRY_SEPARATOR.split(accept, -1); - for (int index = 0; index < parts.length; index++) { - GraphQlAcceptHeader entry = parseEntry(parts[index], index); - if (entry != null && entry.quality() > 0) { - entries.add(entry); - } - } - entries.sort( - Comparator.comparingDouble(GraphQlAcceptHeader::quality) - .reversed() - .thenComparing( - Comparator.comparingInt(GraphQlAcceptHeader::specificity) - .reversed()) - .thenComparingInt(GraphQlAcceptHeader::order)); - return List.copyOf(entries); - } - - /** - * Whether this entry explicitly refuses a media type. - * - *

Only a refusal that names the type or its subtype family counts. A {@code * / *;q=0} entry - * is dropped at parse time and never reaches here. - */ - public static boolean refuses(String accept, String mediaType) { - if (accept == null || accept.isBlank()) { - return false; - } - String[] parts = ENTRY_SEPARATOR.split(accept, -1); - for (int index = 0; index < parts.length; index++) { - GraphQlAcceptHeader entry = parseEntry(parts[index], index); - if (entry != null && entry.quality() == 0 && entry.matches(mediaType)) { - return true; - } - } - return false; - } - - /** Whether a concrete media type is covered by this entry. */ - public boolean matches(String mediaType) { - if (mediaType == null) { - return false; - } - int separator = mediaType.indexOf('/'); - if (separator < 0) { - return false; - } - String candidateType = mediaType.substring(0, separator).strip().toLowerCase(Locale.ROOT); - String candidateSubtype = mediaType.substring(separator + 1).strip().toLowerCase(Locale.ROOT); - return (WILDCARD.equals(type) || type.equals(candidateType)) - && (WILDCARD.equals(subtype) || subtype.equals(candidateSubtype)); - } - - private static GraphQlAcceptHeader parseEntry(String raw, int order) { - String entry = raw.strip(); - if (entry.isEmpty()) { - return null; - } - int parameterStart = entry.indexOf(';'); - String base = (parameterStart < 0 ? entry : entry.substring(0, parameterStart)).strip(); - int separator = base.indexOf('/'); - if (separator < 0) { - return null; - } - String type = base.substring(0, separator).strip().toLowerCase(Locale.ROOT); - String subtype = base.substring(separator + 1).strip().toLowerCase(Locale.ROOT); - if (type.isEmpty() || subtype.isEmpty()) { - return null; - } - // `*/subtype` is not a shape the grammar allows, and treating it as a wildcard would let a - // malformed header match more than a well-formed one. - if (WILDCARD.equals(type) && !WILDCARD.equals(subtype)) { - return null; - } - double quality = - parameterStart < 0 ? DEFAULT_QUALITY : qualityOf(entry.substring(parameterStart + 1)); - int specificity = WILDCARD.equals(type) ? 0 : WILDCARD.equals(subtype) ? 1 : 2; - return new GraphQlAcceptHeader(type, subtype, quality, specificity, order); - } - - private static double qualityOf(String parameters) { - for (String parameter : PARAMETER_SEPARATOR.split(parameters, -1)) { - String candidate = parameter.strip(); - if (!candidate.regionMatches(true, 0, "q=", 0, 2)) { - continue; - } - try { - double value = Double.parseDouble(candidate.substring(2).strip()); - // Out-of-range values are not meaningful quality; treating them as the default keeps a - // sloppy client working without letting `q=5` outrank an honest `q=1`. - return value < 0 || value > 1 ? DEFAULT_QUALITY : value; - } catch (NumberFormatException malformed) { - return DEFAULT_QUALITY; - } - } - return DEFAULT_QUALITY; - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlExecutionOutcome.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlExecutionOutcome.java deleted file mode 100644 index 97840ca0..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlExecutionOutcome.java +++ /dev/null @@ -1,42 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.http; - -import java.util.List; -import java.util.Map; - -/** - * What GraphQL execution produced, before it is shaped into a transport response. - * - *

Separating this from {@link GraphQlHttpResponse} is what lets both transports share one status - * and media-type decision: execution reports data and errors, and the transport decides the rest. - * - * @param data resolved data, possibly partial, or {@code null} when execution never started - * @param errors GraphQL errors, never {@code null} - */ -public record GraphQlExecutionOutcome(Map data, List> errors) { - - public GraphQlExecutionOutcome { - errors = errors == null ? List.of() : List.copyOf(errors); - // A nulled field is the normal shape of partial data, and Map.copyOf rejects null values — so - // the defensive copy has to tolerate them. - data = - data == null - ? null - : java.util.Collections.unmodifiableMap(new java.util.LinkedHashMap<>(data)); - } - - /** Execution completed with no errors. */ - public static GraphQlExecutionOutcome success(Map data) { - return new GraphQlExecutionOutcome(data, List.of()); - } - - /** Execution started and at least one field failed; data may still be present. */ - public static GraphQlExecutionOutcome partial( - Map data, List> errors) { - return new GraphQlExecutionOutcome(data, errors); - } - - /** Whether any field failed. */ - public boolean failed() { - return !errors.isEmpty(); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlExtensionsPolicy.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlExtensionsPolicy.java index fb3d7f3e..19d1263f 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlExtensionsPolicy.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlExtensionsPolicy.java @@ -18,9 +18,6 @@ public final class GraphQlExtensionsPolicy { /** Persisted-operation key used by the Advanced persisted-operation capability. */ public static final String PERSISTED_QUERY = "persistedQuery"; - /** Client-supplied idempotency key for side-effecting mutations. */ - public static final String IDEMPOTENCY_KEY = "idempotencyKey"; - private final Set allowedKeys; private GraphQlExtensionsPolicy(Set allowedKeys) { @@ -38,10 +35,10 @@ public final class GraphQlExtensionsPolicy { } /** - * The Stable default: idempotency only, since persisted operations are an Advanced capability. + * The Stable default: no extension key, since persisted operations are an Advanced capability. */ public static GraphQlExtensionsPolicy stableDefaults() { - return allowing(IDEMPOTENCY_KEY); + return none(); } /** Registered keys. */ diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlHttpExecutor.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlHttpExecutor.java deleted file mode 100644 index 61133b5a..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlHttpExecutor.java +++ /dev/null @@ -1,24 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.http; - -import dev.caskeleton.adapter.inbound.graphql.context.GraphQlRequestContext; - -/** - * Executes a validated request envelope. - * - *

The transport's seam onto GraphQL execution. Keeping it this narrow is what stops transport - * code from acquiring opinions about parsing, cost or resolvers — and it lets both the MVC and the - * reactive adapter be tested without a running engine. - */ -@FunctionalInterface -public interface GraphQlHttpExecutor { - - /** - * Executes one request. - * - * @param envelope validated request envelope - * @param context immutable per-request platform context - * @return the data and errors execution produced - */ - GraphQlExecutionOutcome execute( - GraphQlHttpRequestEnvelope envelope, GraphQlRequestContext context); -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlHttpProfile.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlHttpProfile.java deleted file mode 100644 index fe000f8f..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlHttpProfile.java +++ /dev/null @@ -1,89 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.http; - -/** - * The versioned Stable HTTP transport profile (design §9). - * - *

GraphQL over HTTP is a Stage 2 Draft, and its status-code section is still moving — the draft - * currently proposes {@code 294} for a partial {@code data + errors} response while Spring for - * GraphQL returns {@code 200}. Pinning the platform to an explicitly versioned profile is what lets - * the draft change without the deployed contract changing underneath clients: {@code V1} is - * Spring's actual behaviour, and a future profile version can adopt the draft deliberately. - * - *

{@code V1} accepts {@code POST} with a JSON body only. GET, multipart upload and array - * batching are not part of it: GET is a draft {@code MAY} that leaks documents into logs and - * caches, multipart is a non-standard convention the Fileserver capability already covers properly, - * and array batching is outside GraphQL core and defeats per-operation cost accounting. - */ -public enum GraphQlHttpProfile { - - /** Spring for GraphQL 2.0 behaviour, pinned as the Stable contract. */ - V1; - - /** - * HTTP status the draft proposes for partial responses and this profile deliberately does not - * use. - */ - public static final int DRAFT_PARTIAL_RESPONSE_STATUS = 294; - - /** - * Validates the HTTP method. - * - * @throws GraphQlHttpContractException for anything other than {@code POST} - */ - public void validateMethod(String method) { - if (!"POST".equals(method)) { - throw new GraphQlHttpContractException( - "POST required", GraphQlHttpOutcome.UNSUPPORTED_METHOD); - } - } - - /** - * Validates the request media type. - * - * @throws GraphQlHttpContractException when it is not {@code application/json} - */ - public void validateContentType(String contentType) { - if (!GraphQlMediaTypes.acceptableRequestContentType(contentType)) { - throw new GraphQlHttpContractException( - "application/json request body required", GraphQlHttpOutcome.UNSUPPORTED_MEDIA_TYPE); - } - } - - /** - * Negotiates the response media type. - * - * @throws GraphQlHttpContractException when no offered media type can be produced - */ - public String negotiateResponseContentType(String accept) { - String negotiated = GraphQlMediaTypes.negotiateResponseContentType(accept); - if (negotiated == null) { - throw new GraphQlHttpContractException( - "no acceptable GraphQL response media type", GraphQlHttpOutcome.NOT_ACCEPTABLE); - } - return negotiated; - } - - /** - * Rejects transport features this profile does not support. - * - * @param multipart whether the request arrived as multipart - * @param arrayBatch whether the body was a JSON array of operations - * @throws GraphQlHttpContractException when either is present - */ - public void rejectUnsupportedTransportFeatures(boolean multipart, boolean arrayBatch) { - if (multipart) { - throw new GraphQlHttpContractException( - "GraphQL multipart upload is unsupported; use the Fileserver upload reservation", - GraphQlHttpOutcome.UNSUPPORTED_MEDIA_TYPE); - } - if (arrayBatch) { - throw new GraphQlHttpContractException( - "HTTP array batching is unsupported", GraphQlHttpOutcome.MALFORMED_REQUEST); - } - } - - /** Whether this profile ever emits the draft partial-response status. */ - public boolean usesDraftPartialResponseStatus() { - return false; - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlHttpResponse.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlHttpResponse.java deleted file mode 100644 index 54978717..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlHttpResponse.java +++ /dev/null @@ -1,44 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.http; - -import java.util.List; -import java.util.Map; - -/** - * A transport-shaped GraphQL response: status, media type, partial data and errors. - * - *

Deliberately independent of MVC and WebFlux types so both transports produce the same value - * and one contract test covers both. - * - * @param status HTTP status - * @param contentType negotiated response media type - * @param outcome classified outcome - * @param data resolved data, possibly partial, or {@code null} - * @param errors GraphQL errors, never {@code null} - */ -public record GraphQlHttpResponse( - int status, - String contentType, - GraphQlHttpOutcome outcome, - Map data, - List> errors) { - - public GraphQlHttpResponse { - if (contentType == null || contentType.isBlank()) { - throw new IllegalArgumentException("response content type is required"); - } - if (outcome == null) { - throw new IllegalArgumentException("response outcome is required"); - } - errors = errors == null ? List.of() : List.copyOf(errors); - // Partial data legitimately contains nulled fields, which Map.copyOf refuses to hold. - data = - data == null - ? null - : java.util.Collections.unmodifiableMap(new java.util.LinkedHashMap<>(data)); - } - - /** Whether the response carries data that resolved despite an error. */ - public boolean partial() { - return data != null && !data.isEmpty() && !errors.isEmpty(); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlHttpResponseFactory.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlHttpResponseFactory.java deleted file mode 100644 index d316d49c..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlHttpResponseFactory.java +++ /dev/null @@ -1,84 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.http; - -import java.util.List; -import java.util.Map; - -/** - * Builds transport responses with the status the profile mandates. - * - *

Having one factory is what keeps the 4xx/200 split from drifting: every transport builds its - * response here, so a new outcome cannot be introduced with an ad-hoc status at one call site. - */ -public final class GraphQlHttpResponseFactory { - - private final GraphQlHttpStatusMapper statusMapper; - private final GraphQlHttpResponsePolicy responsePolicy; - - /** - * Creates a factory for one negotiated response policy. - * - * @param statusMapper profile-versioned status mapping - * @param responsePolicy negotiated response media type policy - */ - public GraphQlHttpResponseFactory( - GraphQlHttpStatusMapper statusMapper, GraphQlHttpResponsePolicy responsePolicy) { - if (statusMapper == null || responsePolicy == null) { - throw new IllegalArgumentException("status mapper and response policy are required"); - } - this.statusMapper = statusMapper; - this.responsePolicy = responsePolicy; - } - - /** A factory for the preferred media type under the {@code V1} profile. */ - public static GraphQlHttpResponseFactory preferredV1() { - return new GraphQlHttpResponseFactory( - GraphQlHttpStatusMapper.V1, GraphQlHttpResponsePolicy.preferred()); - } - - /** A factory for a negotiated media type under the {@code V1} profile. */ - public static GraphQlHttpResponseFactory v1(String negotiatedContentType) { - return new GraphQlHttpResponseFactory( - GraphQlHttpStatusMapper.V1, - GraphQlHttpResponsePolicy.forContentType(negotiatedContentType)); - } - - /** A successful response. */ - public GraphQlHttpResponse success(Map data) { - return response(GraphQlHttpOutcome.SUCCESS, data, List.of()); - } - - /** A response where execution began and a field failed; data may be partial. */ - public GraphQlHttpResponse fieldError( - Map data, List> errors) { - return response(GraphQlHttpOutcome.FIELD_ERROR, data, errors); - } - - /** A response for a failure that happened before execution started. */ - public GraphQlHttpResponse requestError( - GraphQlHttpOutcome outcome, List> errors) { - if (!outcome.requestError()) { - throw new IllegalArgumentException(outcome + " is not a request error"); - } - return response(outcome, null, errors); - } - - /** A response for a transport contract violation. */ - public GraphQlHttpResponse requestError(GraphQlHttpContractException failure) { - return requestError( - failure.outcome(), - List.of( - Map.of( - "message", failure.getMessage(), - "extensions", Map.of("code", failure.outcome().name(), "category", "REQUEST")))); - } - - private GraphQlHttpResponse response( - GraphQlHttpOutcome outcome, Map data, List> errors) { - return new GraphQlHttpResponse( - statusMapper.status(outcome, responsePolicy), - responsePolicy.contentType(), - outcome, - data, - errors); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlHttpResponsePolicy.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlHttpResponsePolicy.java deleted file mode 100644 index 546105a1..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlHttpResponsePolicy.java +++ /dev/null @@ -1,46 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.http; - -/** - * How a response is shaped for one negotiated media type. - * - *

Kept separate from the status mapper because the two answer different questions: the status - * says whether execution began, while this says which body conventions the negotiated media type - * implies. - * - * @param contentType negotiated response media type - * @param preferredMediaType whether this is the preferred GraphQL response media type - */ -public record GraphQlHttpResponsePolicy(String contentType, boolean preferredMediaType) { - - public GraphQlHttpResponsePolicy { - if (contentType == null || contentType.isBlank()) { - throw new IllegalArgumentException("response content type is required"); - } - } - - /** The preferred {@code application/graphql-response+json} policy. */ - public static GraphQlHttpResponsePolicy preferred() { - return new GraphQlHttpResponsePolicy(GraphQlMediaTypes.GRAPHQL_RESPONSE_JSON, true); - } - - /** The compatibility {@code application/json} policy. */ - public static GraphQlHttpResponsePolicy legacy() { - return new GraphQlHttpResponsePolicy(GraphQlMediaTypes.LEGACY_RESPONSE_JSON, false); - } - - /** Chooses the policy for a negotiated media type. */ - public static GraphQlHttpResponsePolicy forContentType(String contentType) { - return GraphQlMediaTypes.GRAPHQL_RESPONSE_JSON.equals(contentType) ? preferred() : legacy(); - } - - /** - * Whether a request error may use a 4xx status under this policy. - * - *

Legacy {@code application/json} clients were written when every GraphQL response was 200, so - * the platform keeps returning 200 for them and reports the failure in {@code errors}. The - * preferred media type is what unlocks the 4xx contract. - */ - public boolean supportsRequestErrorStatus() { - return preferredMediaType; - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlHttpStatusMapper.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlHttpStatusMapper.java deleted file mode 100644 index 7f283686..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlHttpStatusMapper.java +++ /dev/null @@ -1,42 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.http; - -/** - * Maps a classified outcome to an HTTP status, versioned by transport profile (design §3.1). - * - *

The rule the whole error contract rests on: once validation passes and execution starts, a - * field error is HTTP {@code 200} with partial {@code data} and {@code errors}. Turning that into a - * 5xx would discard the data that did resolve and tell every proxy and client retry policy that the - * server is broken, when in fact one field is. - * - *

The draft's proposed {@code 294} for partial responses is deliberately not emitted here. - */ -public enum GraphQlHttpStatusMapper { - - /** Status mapping of {@link GraphQlHttpProfile#V1}. */ - V1; - - /** Maps an outcome to a status under the preferred response media type. */ - public int status(GraphQlHttpOutcome outcome) { - return switch (outcome) { - case SUCCESS, FIELD_ERROR -> 200; - case MALFORMED_REQUEST, PARSE_ERROR, VALIDATION_ERROR, VARIABLE_COERCION_ERROR -> 400; - case UNSUPPORTED_METHOD -> 405; - case NOT_ACCEPTABLE -> 406; - case REQUEST_TOO_LARGE -> 413; - case UNSUPPORTED_MEDIA_TYPE -> 415; - }; - } - - /** - * Maps an outcome to a status for a negotiated response policy. - * - *

A legacy {@code application/json} client keeps receiving 200 with the failure in {@code - * errors}, because that is the contract it was written against. - */ - public int status(GraphQlHttpOutcome outcome, GraphQlHttpResponsePolicy policy) { - if (outcome.requestError() && !policy.supportsRequestErrorStatus()) { - return 200; - } - return status(outcome); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlMediaTypes.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlMediaTypes.java deleted file mode 100644 index 20d965e9..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlMediaTypes.java +++ /dev/null @@ -1,100 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.http; - -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Locale; -import java.util.Set; - -/** - * Media types of the Stable HTTP profile (design §9.1). - * - *

Requests are {@code application/json}. Responses prefer {@code - * application/graphql-response+json}, which is what tells a client that 4xx and 200 mean what the - * GraphQL over HTTP profile says they mean; {@code application/json} stays supported so clients - * written before that media type existed keep working. - */ -public final class GraphQlMediaTypes { - - /** The only accepted request media type. */ - public static final String APPLICATION_JSON = "application/json"; - - /** Preferred response media type. */ - public static final String GRAPHQL_RESPONSE_JSON = "application/graphql-response+json"; - - /** Response media type kept for compatibility with older clients. */ - public static final String LEGACY_RESPONSE_JSON = APPLICATION_JSON; - - /** Media types this profile will produce, most preferred first. */ - public static final List PRODUCIBLE = - List.of(GRAPHQL_RESPONSE_JSON, LEGACY_RESPONSE_JSON); - - private GraphQlMediaTypes() {} - - /** Whether a request {@code Content-Type} is acceptable, ignoring parameters such as charset. */ - public static boolean acceptableRequestContentType(String contentType) { - if (contentType == null) { - return false; - } - return baseType(contentType).equals(APPLICATION_JSON); - } - - /** - * Chooses the response media type for an {@code Accept} header. - * - *

The client's ranking decides, not the server's. Walking the server's preference list first - * and returning the first type named anywhere in the header ignored both quality and refusal, so - * {@code application/graphql-response+json;q=0, application/json} — a client saying "anything but - * that one" — was answered with exactly the refused type. - * - *

Absent or blank {@code Accept} means no constraint, so the profile's preferred type is - * returned. A wildcard is matched like any other entry, at its own quality and specificity, which - * is what lets {@code * / *;q=0.1, application/json;q=0.9} pick JSON rather than the wildcard. - * - *

Where the client ranked two producible types equally — same quality, same specificity, as in - * a plain {@code application/json, application/graphql-response+json} — it has expressed no - * preference between them, and the server's own preference breaks the tie. That is the one place - * server preference still applies, and it applies only after the client's ranking has been - * exhausted. - * - * @param accept raw {@code Accept} header, possibly {@code null} - * @return the negotiated media type, or {@code null} when nothing acceptable was offered - */ - public static String negotiateResponseContentType(String accept) { - if (accept == null || accept.isBlank()) { - return GRAPHQL_RESPONSE_JSON; - } - - Set bestTier = new LinkedHashSet<>(); - double tierQuality = 0; - int tierSpecificity = -1; - - for (GraphQlAcceptHeader entry : GraphQlAcceptHeader.parse(accept)) { - List matches = - PRODUCIBLE.stream() - // A concrete refusal outranks a wildcard acceptance: `*/*, application/json;q=0` - // accepts everything and then names one exception, and the exception is the specific - // instruction. - .filter(candidate -> entry.matches(candidate)) - .filter(candidate -> !GraphQlAcceptHeader.refuses(accept, candidate)) - .toList(); - if (matches.isEmpty()) { - continue; - } - if (bestTier.isEmpty()) { - tierQuality = entry.quality(); - tierSpecificity = entry.specificity(); - } else if (entry.quality() != tierQuality || entry.specificity() != tierSpecificity) { - break; - } - bestTier.addAll(matches); - } - - return PRODUCIBLE.stream().filter(bestTier::contains).findFirst().orElse(null); - } - - private static String baseType(String mediaType) { - int parameterStart = mediaType.indexOf(';'); - String base = parameterStart < 0 ? mediaType : mediaType.substring(0, parameterStart); - return base.strip().toLowerCase(Locale.ROOT); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/moduleboundary/GraphQlAdvancedModule.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/moduleboundary/GraphQlAdvancedModule.java deleted file mode 100644 index b39537e6..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/moduleboundary/GraphQlAdvancedModule.java +++ /dev/null @@ -1,165 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.moduleboundary; - -import java.util.Arrays; -import java.util.Map; -import java.util.Set; -import java.util.TreeMap; -import java.util.stream.Collectors; - -/** - * The Advanced GraphQL capability modules and their allowed internal dependencies. - * - *

Advanced consumes Stable, never the other way round. If a Stable module depended on an - * Advanced one, every Stable deployment would carry the Advanced capability's code and - * configuration surface, and the feature flag would be the only thing standing between an ordinary - * service and a subscription runtime. {@code GraphQlAdvancedDependencyRules} checks that direction - * against this declaration; {@code GraphQlModuleBoundaryTest} checks it against the real imports. - * - *

Advanced modules are {@link GraphQlModulePurity#CORE} by default: the capabilities are state - * machines and policies, and the transport binding for the ones that need it stays in the Stable - * {@code http} seam. Exceptions are declared per module rather than assumed — {@code - * advanced.codegen} is the one that has to compile a schema to do its job. - */ -public enum GraphQlAdvancedModule { - - /** Persisted operation administration and removal gating. */ - ADMIN("advanced.admin", "advanced.admin", "advanced.persisted"), - - /** Advanced capability grades, feature flags and the activation guard. */ - BOOTSTRAP("advanced.bootstrap", "advanced.bootstrap", "moduleboundary"), - - /** DataLoader chaining and cycle detection. */ - CHAINING("advanced.chaining", "advanced.chaining", "advanced.bootstrap"), - - /** - * Client code generation planning, operation validation and generated-source boundary rules. - * - *

The one Advanced module that is not framework free. Validating a client operation means - * compiling the schema and running GraphQL Java's validator — there is no way to answer "does - * this field exist" without the type system, and a hand-rolled approximation would be the kind of - * check that passes on exactly the documents that break. - */ - CODEGEN("advanced.codegen", "advanced.codegen", GraphQlModulePurity.FRAMEWORK_BOUND, "compat"), - - /** Federated schema composition gating. */ - COMPOSITION("advanced.composition", "advanced.composition", "advanced.federation"), - - /** Federation entity resolution. */ - FEDERATION("advanced.federation", "advanced.federation", "advanced.bootstrap"), - - /** The draft HTTP GET operation profile. */ - GET("advanced.get", "advanced.get", "http"), - - /** Incremental delivery (`@defer`/`@stream`) compatibility gating. */ - INCREMENTAL("advanced.incremental", "advanced.incremental", "cost", "execution"), - - /** Persisted operation registry and the interceptor that enforces it. */ - PERSISTED( - "advanced.persisted", "advanced.persisted", "advanced.bootstrap", "execution", "policy"), - - /** The Advanced release gate. */ - RELEASE("advanced.release", "advanced.release", "advanced.bootstrap", "release"), - - /** Subscription snapshot replay and live handoff. */ - REPLAY( - "advanced.replay", - "advanced.replay", - "advanced.security", - "advanced.subscription", - "pagination"), - - /** The experimental RSocket transport route policy. */ - RSOCKET("advanced.rsocket", "advanced.rsocket", "advanced.bootstrap", "error", "policy"), - - /** Transport authentication for long-lived Advanced connections. */ - SECURITY("advanced.security", "advanced.security"), - - /** Server-sent event connection policy. */ - SSE("advanced.sse", "advanced.sse", "advanced.bootstrap", "advanced.subscription", "http"), - - /** Subscription execution policy, buffering and backpressure. */ - SUBSCRIPTION( - "advanced.subscription", - "advanced.subscription", - "advanced.security", - "api", - "execution", - "http", - "security"), - - /** The GraphQL over WebSocket protocol state machine. */ - /** - * The allowlisted Spring Data compatibility path. - * - *

Pure policy and no edge to persistence, which is the point: this module decides which - * repository exposures a deployment published, and it decides that without being able to name a - * repository, an entity or a Spring Data type. Everything it works with is a name the deployment - * registered. - */ - SPRING_DATA("advanced.springdata", "advanced.springdata"); - - private final String id; - private final String packageSuffix; - private final GraphQlModulePurity purity; - - /** - * Populated only from {@link Set#of}, which is genuinely immutable. Error Prone's {@code - * ImmutableEnumChecker} recognises Guava's {@code ImmutableSet} but not the JDK's unmodifiable - * factories, and this leaf has no Guava dependency to add for one field. - */ - @SuppressWarnings("ImmutableEnumChecker") - private final Set allowedDependencies; - - GraphQlAdvancedModule(String id, String packageSuffix, String... allowedDependencies) { - this(id, packageSuffix, GraphQlModulePurity.CORE, allowedDependencies); - } - - GraphQlAdvancedModule( - String id, String packageSuffix, GraphQlModulePurity purity, String... allowedDependencies) { - this.id = id; - this.packageSuffix = packageSuffix; - this.purity = purity; - this.allowedDependencies = Set.of(allowedDependencies); - } - - /** The module identifier used on both sides of a declared dependency edge. */ - public String id() { - return id; - } - - /** The fully qualified package that carries this module, including its sub-packages. */ - public String packageName() { - return GraphQlModuleBoundary.PACKAGE_ROOT + "." + packageSuffix; - } - - /** - * Whether this capability may reference framework types. - * - *

Advanced capabilities are policy and state machines, so they are framework free by default - * and the exceptions are declared one by one rather than assumed. - */ - public GraphQlModulePurity purity() { - return purity; - } - - /** The module identifiers this module is allowed to import. */ - public Set allowedDependencies() { - return allowedDependencies; - } - - /** Every Advanced module identifier. */ - public static Set moduleIds() { - return Arrays.stream(values()) - .map(GraphQlAdvancedModule::id) - .collect(Collectors.toUnmodifiableSet()); - } - - /** The declared Advanced dependency edges, keyed by module identifier in deterministic order. */ - public static Map> dependencyEdges() { - Map> edges = new TreeMap<>(); - for (GraphQlAdvancedModule module : values()) { - edges.put(module.id(), module.allowedDependencies()); - } - return Map.copyOf(edges); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/moduleboundary/GraphQlModuleBoundary.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/moduleboundary/GraphQlModuleBoundary.java deleted file mode 100644 index 8d7b467d..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/moduleboundary/GraphQlModuleBoundary.java +++ /dev/null @@ -1,126 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.moduleboundary; - -import java.util.Arrays; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.TreeMap; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -/** - * The declared module map of the GraphQL platform: identities, purity grades and allowed edges. - * - *

This type is the read side of {@link GraphQlStableModule} and {@link GraphQlAdvancedModule}. - * It answers the two questions every boundary check needs — "which module owns this package?" and - * "is this edge declared?" — so the rules never re-implement package-prefix arithmetic. - * - *

Note what it deliberately does not do: it never reads the source tree. Scanning the checkout - * is build-time work and lives in the test source set, because a running application cannot - * meaningfully react to its own source layout and a runtime scan only fails in the environments - * where the sources are absent. - */ -public final class GraphQlModuleBoundary { - - /** The package that carries the whole platform. */ - public static final String PACKAGE_ROOT = deriveRootPackage(); - - private GraphQlModuleBoundary() {} - - /** Every declared module identifier, Stable and Advanced. */ - public static Set allModuleIds() { - return Stream.concat( - GraphQlStableModule.moduleIds().stream(), GraphQlAdvancedModule.moduleIds().stream()) - .collect(Collectors.toUnmodifiableSet()); - } - - /** Every declared dependency edge, Stable and Advanced, in deterministic order. */ - public static Map> dependencyEdges() { - Map> edges = new TreeMap<>(); - edges.putAll(GraphQlStableModule.dependencyEdges()); - edges.putAll(GraphQlAdvancedModule.dependencyEdges()); - return Map.copyOf(edges); - } - - /** Every module that must not reference a framework type. */ - public static Set coreModuleIds() { - return Stream.concat( - GraphQlStableModule.coreModuleIds().stream(), - Arrays.stream(GraphQlAdvancedModule.values()) - .filter(module -> module.purity() == GraphQlModulePurity.CORE) - .map(GraphQlAdvancedModule::id)) - .collect(Collectors.toUnmodifiableSet()); - } - - /** The declared package of every module, keyed by identifier. */ - public static Map packagesById() { - Map packages = new LinkedHashMap<>(GraphQlStableModule.packagesById()); - for (GraphQlAdvancedModule module : GraphQlAdvancedModule.values()) { - packages.put(module.id(), module.packageName()); - } - return Map.copyOf(packages); - } - - /** - * The module owning a package. - * - *

Ownership is by longest declared package prefix, so {@code ...graphql.http.webflux} belongs - * to {@code http} and {@code ...graphql.advanced.sse} belongs to {@code advanced.sse} rather than - * to a hypothetical {@code advanced} module. - * - *

The root module is the exception: it owns the platform root package itself and nothing below - * it. Letting it absorb descendants would make every possible package "declared", and the - * unregistered-package rule — the one that forces a new sub-package to be given an identity and - * an edge set before it can ship — would silently never fire. - * - * @param packageName a fully qualified package name - * @return the owning module identifier, or empty when the package is outside the platform or - * belongs to no declared module - */ - public static Optional moduleIdForPackage(String packageName) { - if (packageName == null || !insidePlatform(packageName)) { - return Optional.empty(); - } - String best = null; - String bestPackage = null; - for (Map.Entry candidate : packagesById().entrySet()) { - String candidatePackage = candidate.getValue(); - boolean owns = - candidatePackage.equals(PACKAGE_ROOT) - ? packageName.equals(PACKAGE_ROOT) - : matches(packageName, candidatePackage); - if (!owns) { - continue; - } - if (bestPackage == null || candidatePackage.length() > bestPackage.length()) { - best = candidate.getKey(); - bestPackage = candidatePackage; - } - } - return Optional.ofNullable(best); - } - - /** Whether a package name belongs to the platform at all. */ - public static boolean insidePlatform(String packageName) { - return packageName != null && matches(packageName, PACKAGE_ROOT); - } - - /** Whether an edge between two declared modules is allowed. */ - public static boolean edgeAllowed(String from, String to) { - if (from == null || to == null || from.equals(to)) { - return true; - } - Set allowed = dependencyEdges().get(from); - return allowed != null && allowed.contains(to); - } - - private static boolean matches(String packageName, String candidate) { - return packageName.equals(candidate) || packageName.startsWith(candidate + "."); - } - - private static String deriveRootPackage() { - String self = GraphQlModuleBoundary.class.getPackageName(); - return self.substring(0, self.lastIndexOf('.')); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/moduleboundary/GraphQlModulePurity.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/moduleboundary/GraphQlModulePurity.java deleted file mode 100644 index e86b13a0..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/moduleboundary/GraphQlModulePurity.java +++ /dev/null @@ -1,19 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.moduleboundary; - -/** - * Whether a platform module is allowed to reference transport, framework or GraphQL engine types. - * - *

The split is what keeps the policy model portable. A {@link #CORE} module holds the decision - * ("this document is too deep", "this cursor is out of scope") as plain Java, so the same rule can - * be exercised by a unit test, reused from a different transport, or promoted to its own leaf - * without dragging a servlet container along. A {@link #FRAMEWORK_BOUND} module is the seam where - * that decision meets Spring, GraphQL Java or Reactor. - */ -public enum GraphQlModulePurity { - - /** Java standard library only: no Spring, GraphQL Java, Reactor, Micrometer or Jakarta types. */ - CORE, - - /** May bind to the framework, because it is the adapter seam that has to. */ - FRAMEWORK_BOUND -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/moduleboundary/GraphQlStableModule.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/moduleboundary/GraphQlStableModule.java deleted file mode 100644 index 9a9c6520..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/moduleboundary/GraphQlStableModule.java +++ /dev/null @@ -1,225 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.moduleboundary; - -import java.util.Arrays; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Set; -import java.util.TreeMap; -import java.util.stream.Collectors; - -/** - * The Stable GraphQL platform modules, their purity grade and their allowed internal dependencies. - * - *

The platform splits into bounded sub-packages inside one registered leaf rather than into - * Gradle leaves (see {@code CLAUDE.md}). That choice only holds if the boundaries are machine - * checked, so this enum is the declared identity: each constant names a module, the package that - * carries it, whether it may touch the framework, and exactly which other modules it may import. - * {@code GraphQlModuleBoundaryTest} scans the real source tree and fails when the tree and this - * declaration disagree in either direction — an undeclared edge, or an undeclared package. - * - *

Declaring the edge set is what makes the leaf split reversible: each constant is already - * shaped like a leaf specification, so promoting a module to its own Gradle path is a registry edit - * rather than an archaeology exercise. - */ -public enum GraphQlStableModule { - - /** Skeleton transport surface: health schema controller and the Spring exception resolver. */ - TRANSPORT_ROOT("root", "", GraphQlModulePurity.FRAMEWORK_BOUND), - - /** Shared identifiers and value types every other module is allowed to speak. */ - API("api", "api", GraphQlModulePurity.CORE), - - /** Resolver and controller boundary rules enforced by reflection over the compiled package. */ - ARCHITECTURE("architecture", "architecture", GraphQlModulePurity.FRAMEWORK_BOUND), - - /** Spring auto-configuration, configuration properties and startup validation. */ - AUTOCONFIGURE( - "autoconfigure", - "autoconfigure", - GraphQlModulePurity.FRAMEWORK_BOUND, - "api", - "architecture", - "context", - "cost", - "error", - "execution", - "http", - "observation", - "policy", - "runtime", - "scalar", - "schema", - "security"), - - /** Schema compatibility comparison and deprecation gating. */ - COMPAT("compat", "compat", GraphQlModulePurity.FRAMEWORK_BOUND, "schema"), - - /** Per-request execution context: actor, tenant and deadline. */ - CONTEXT("context", "context", GraphQlModulePurity.CORE, "api"), - - /** Document shape analysis, complexity scoring and runtime budget tracking. */ - COST("cost", "cost", GraphQlModulePurity.FRAMEWORK_BOUND, "api", "execution", "policy"), - - /** Batch loading, chunking and per-request DataLoader registry. */ - DATALOADER("dataloader", "dataloader", GraphQlModulePurity.CORE, "context"), - - /** Wire error shape, error categories and null propagation contract. */ - ERROR("error", "error", GraphQlModulePurity.CORE, "api", "http"), - - /** Execution pipeline stages, operation naming, timeouts and document caching. */ - EXECUTION("execution", "execution", GraphQlModulePurity.CORE, "api", "context", "policy"), - - /** Fetch profile classification and registry. */ - FETCH("fetch", "fetch", GraphQlModulePurity.CORE, "api"), - - /** - * HTTP profile, request envelope validation, media negotiation and status mapping. - * - *

{@code CORE} since the custom MVC and WebFlux transport adapters were removed: what remains - * is the platform's opinion about the HTTP contract, expressed as plain values. The route belongs - * to Spring, and the seam that applies these decisions to it lives in {@code runtime}. - */ - HTTP("http", "http", GraphQlModulePurity.CORE, "api", "context", "execution", "policy"), - - /** This module: the declared module identities and their allowed edges. */ - MODULE_BOUNDARY("moduleboundary", "moduleboundary", GraphQlModulePurity.CORE), - - /** Mutation idempotency context and result mapping. */ - MUTATION("mutation", "mutation", GraphQlModulePurity.CORE, "api", "context", "http"), - - /** Observation conventions, metric cardinality policy and sensitive attribute filtering. */ - OBSERVATION( - "observation", - "observation", - GraphQlModulePurity.CORE, - "api", - "cost", - "dataloader", - "policy"), - - /** Connection assembly and signed keyset cursors. */ - PAGINATION("pagination", "pagination", GraphQlModulePurity.CORE, "policy"), - - /** Client and operation policy values shared by the enforcement modules. */ - POLICY("policy", "policy", GraphQlModulePurity.CORE, "api"), - - /** Release gate, performance and fault scenario catalogues. */ - RELEASE("release", "release", GraphQlModulePurity.CORE), - - /** The executable pipeline and the Spring GraphQL seams that run it on a real request. */ - RUNTIME( - "runtime", - "runtime", - GraphQlModulePurity.FRAMEWORK_BOUND, - "api", - "context", - "cost", - "dataloader", - "error", - "execution", - "http", - "observation", - "policy", - "security"), - - /** Custom scalar coercions and the runtime wiring configurer that registers them. */ - SCALAR("scalar", "scalar", GraphQlModulePurity.FRAMEWORK_BOUND, "schema"), - - /** Schema assembly, mapping inspection and scalar manifest. */ - SCHEMA("schema", "schema", GraphQlModulePurity.FRAMEWORK_BOUND, "api"), - - /** Authentication context, authorization policy and tenant isolation. */ - SECURITY("security", "security", GraphQlModulePurity.CORE, "api", "context", "error"), - - /** Cross-module contract suites and integration fixtures. */ - TESTKIT( - "testkit", - "testkit", - GraphQlModulePurity.CORE, - "api", - "compat", - "context", - "dataloader", - "error", - "execution", - "http", - "pagination", - "policy", - "schema", - "security"); - - private final String id; - private final String packageSuffix; - private final GraphQlModulePurity purity; - - /** - * Populated only from {@link Set#of}, which is genuinely immutable. Error Prone's {@code - * ImmutableEnumChecker} recognises Guava's {@code ImmutableSet} but not the JDK's unmodifiable - * factories, and this leaf has no Guava dependency to add for one field. - */ - @SuppressWarnings("ImmutableEnumChecker") - private final Set allowedDependencies; - - GraphQlStableModule( - String id, String packageSuffix, GraphQlModulePurity purity, String... allowedDependencies) { - this.id = id; - this.packageSuffix = packageSuffix; - this.purity = purity; - this.allowedDependencies = Set.of(allowedDependencies); - } - - /** The module identifier used on both sides of a declared dependency edge. */ - public String id() { - return id; - } - - /** The fully qualified package that carries this module, including its sub-packages. */ - public String packageName() { - return packageSuffix.isEmpty() - ? GraphQlModuleBoundary.PACKAGE_ROOT - : GraphQlModuleBoundary.PACKAGE_ROOT + "." + packageSuffix; - } - - /** Whether this module may reference framework types. */ - public GraphQlModulePurity purity() { - return purity; - } - - /** The module identifiers this module is allowed to import. */ - public Set allowedDependencies() { - return allowedDependencies; - } - - /** Every Stable module identifier. */ - public static Set moduleIds() { - return Arrays.stream(values()) - .map(GraphQlStableModule::id) - .collect(Collectors.toUnmodifiableSet()); - } - - /** The declared Stable dependency edges, keyed by module identifier in deterministic order. */ - public static Map> dependencyEdges() { - Map> edges = new TreeMap<>(); - for (GraphQlStableModule module : values()) { - edges.put(module.id(), module.allowedDependencies()); - } - return Map.copyOf(edges); - } - - /** Every Stable module that must not reference a framework type. */ - public static Set coreModuleIds() { - return Arrays.stream(values()) - .filter(module -> module.purity() == GraphQlModulePurity.CORE) - .map(GraphQlStableModule::id) - .collect(Collectors.toUnmodifiableSet()); - } - - /** The declared package name of every Stable module, keyed by identifier. */ - public static Map packagesById() { - Map packages = new LinkedHashMap<>(); - for (GraphQlStableModule module : values()) { - packages.put(module.id(), module.packageName()); - } - return Map.copyOf(packages); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/mutation/GraphQlCanonicalInput.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/mutation/GraphQlCanonicalInput.java deleted file mode 100644 index 58abd9df..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/mutation/GraphQlCanonicalInput.java +++ /dev/null @@ -1,87 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.mutation; - -import java.math.BigDecimal; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; - -/** - * The one canonical serialization a mutation input is fingerprinted from. - * - *

The previous form sorted top-level keys and joined {@code key=value;}, which two different - * inputs could produce identically: {@code {a: "b;c=d"}} and {@code {a: "b", c: "d"}} both - * canonicalise to {@code a=b;c=d;}. Two different requests sharing a fingerprint is an idempotency - * collision — the second one is answered with the first one's result. - * - *

Three properties remove the ambiguity. Every value carries a type tag, so the string {@code - * "1"} and the number {@code 1} never collide. Every string is length-prefixed, so no character is - * a separator and no value can imitate the framing. And nesting is sorted recursively, so a map - * inside a list inside a map still canonicalises the same way whatever order it arrived in. - * - *

Numbers normalise through {@link BigDecimal}, because {@code 1}, {@code 1.0} and {@code 1e0} - * are the same value and a client library is free to pick any of them for the same field. - */ -public final class GraphQlCanonicalInput { - - /** Deepest input nesting this serializer will walk before refusing. */ - public static final int MAXIMUM_DEPTH = 64; - - private GraphQlCanonicalInput() {} - - /** - * Canonicalises a decoded input value. - * - * @param value a decoded JSON value: map, list, string, number, boolean or {@code null} - * @throws GraphQlMutationContractException when nesting exceeds {@link #MAXIMUM_DEPTH} - */ - public static String of(Object value) { - StringBuilder canonical = new StringBuilder(); - write(canonical, value, 0); - return canonical.toString(); - } - - private static void write(StringBuilder out, Object value, int depth) { - if (depth > MAXIMUM_DEPTH) { - throw new GraphQlMutationContractException( - "mutation input nesting exceeds the canonical limit"); - } - if (value == null) { - out.append("z;"); - return; - } - if (value instanceof Map map) { - out.append("m").append(map.size()).append(';'); - // Recursive, not just top level: an unsorted nested map would fingerprint differently for - // the same request depending on the client's serialization order. - Map sorted = new TreeMap<>(); - map.forEach((key, entry) -> sorted.put(String.valueOf(key), entry)); - sorted.forEach( - (key, entry) -> { - writeString(out, key); - write(out, entry, depth + 1); - }); - return; - } - if (value instanceof List list) { - // Order-sensitive on purpose: a list is a sequence, and two orders are two different inputs. - out.append("l").append(list.size()).append(';'); - list.forEach(element -> write(out, element, depth + 1)); - return; - } - if (value instanceof Boolean flag) { - out.append('b').append(flag ? '1' : '0').append(';'); - return; - } - if (value instanceof Number number) { - out.append('n'); - writeString(out, new BigDecimal(number.toString()).stripTrailingZeros().toPlainString()); - return; - } - out.append('s'); - writeString(out, String.valueOf(value)); - } - - private static void writeString(StringBuilder out, String value) { - out.append(value.length()).append(':').append(value).append(';'); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/mutation/GraphQlIdempotencyConflictException.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/mutation/GraphQlIdempotencyConflictException.java deleted file mode 100644 index 9959cf97..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/mutation/GraphQlIdempotencyConflictException.java +++ /dev/null @@ -1,32 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.mutation; - -/** - * Raised when one idempotency key is reused with different input. - * - *

A conflict rather than a fresh execution: the same key with different input means the client - * is either retrying something it changed, or reusing a key by accident. Executing would produce a - * second, different side effect under a key that promises exactly one. - * - *

Carries neither the key nor the input. - */ -public class GraphQlIdempotencyConflictException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - /** Stable error code. */ - public static final String CODE = "IDEMPOTENCY_KEY_CONFLICT"; - - /** - * Creates the failure. - * - * @param message content-free description - */ - public GraphQlIdempotencyConflictException(String message) { - super(message); - } - - /** The stable error code. */ - public String code() { - return CODE; - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/mutation/GraphQlIdempotencyKey.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/mutation/GraphQlIdempotencyKey.java deleted file mode 100644 index 733e32fd..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/mutation/GraphQlIdempotencyKey.java +++ /dev/null @@ -1,19 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.mutation; - -/** - * A client-supplied idempotency key. - * - *

Length-bounded at both ends. Too short and keys collide between unrelated requests, which - * makes one caller's retry return another's result; unbounded and the key becomes a storage and - * logging problem. - * - * @param value the key, 8 to 128 characters - */ -public record GraphQlIdempotencyKey(String value) { - - public GraphQlIdempotencyKey { - if (value == null || value.length() < 8 || value.length() > 128) { - throw new IllegalArgumentException("invalid idempotency key"); - } - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/mutation/GraphQlMutationContractValidator.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/mutation/GraphQlMutationContractValidator.java index e260e2d0..3bf82eef 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/mutation/GraphQlMutationContractValidator.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/mutation/GraphQlMutationContractValidator.java @@ -71,22 +71,4 @@ public final class GraphQlMutationContractValidator { coordinate.value() + " requires an expectedVersion"); } } - - /** - * Verifies a mutation that requires an idempotency key received one. - * - * @param coordinate the mutation field - * @param idempotencyRequired whether the operation policy requires it - * @param supplied the derived idempotency scope, or {@code null} - * @throws GraphQlMutationContractException when it is required and absent - */ - public static void requireIdempotency( - GraphQlMutationCoordinate coordinate, - boolean idempotencyRequired, - GraphQlMutationIdempotencyContext supplied) { - if (idempotencyRequired && supplied == null) { - throw new GraphQlMutationContractException( - coordinate.value() + " requires an idempotency key"); - } - } } diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/mutation/GraphQlMutationFingerprint.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/mutation/GraphQlMutationFingerprint.java deleted file mode 100644 index f200f388..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/mutation/GraphQlMutationFingerprint.java +++ /dev/null @@ -1,49 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.mutation; - -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.HexFormat; -import java.util.Map; - -/** - * A fingerprint of a mutation's normalised input. - * - *

A hash rather than the input itself: the fingerprint is stored and compared on every retry, - * and the input can contain exactly the values that must not be retained. Normalisation sorts the - * fields so two semantically identical requests fingerprint identically regardless of serialization - * order. - * - * @param value fingerprint, conventionally {@code sha256:} - */ -public record GraphQlMutationFingerprint(String value) { - - public GraphQlMutationFingerprint { - if (value == null || value.isBlank()) { - throw new IllegalArgumentException("mutation fingerprint is required"); - } - } - - /** - * Fingerprints a decoded input map. - * - *

Canonicalised by {@link GraphQlCanonicalInput}, which type-tags and length-frames every - * value and sorts nesting recursively. The previous form joined {@code key=value;} over top-level - * keys only, so {@code {a: "b;c=d"}} and {@code {a: "b", c: "d"}} produced the same fingerprint — - * and an idempotent retry of one returned the other's result. - */ - public static GraphQlMutationFingerprint of(Map normalizedInput) { - return sha256(GraphQlCanonicalInput.of(normalizedInput)); - } - - /** Fingerprints already-canonical text. */ - public static GraphQlMutationFingerprint sha256(String canonical) { - try { - byte[] digest = - MessageDigest.getInstance("SHA-256").digest(canonical.getBytes(StandardCharsets.UTF_8)); - return new GraphQlMutationFingerprint("sha256:" + HexFormat.of().formatHex(digest)); - } catch (NoSuchAlgorithmException ex) { - throw new IllegalStateException("SHA-256 is required for mutation fingerprints", ex); - } - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/mutation/GraphQlMutationIdempotencyContext.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/mutation/GraphQlMutationIdempotencyContext.java deleted file mode 100644 index 85663589..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/mutation/GraphQlMutationIdempotencyContext.java +++ /dev/null @@ -1,95 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.mutation; - -/** - * The full scope one idempotency key applies to (design §15). - * - *

Scoped by actor, tenant, mutation, contract version and normalised input together — not by key - * alone. A key scoped only to itself would let one client's retry return another client's result, - * and would let the same key stand for two different requests. - * - *

Tenant is part of the scope because actor identity does not imply it: the same service account - * acting for two tenants would otherwise share one idempotency namespace, and a retry issued for - * one tenant could be answered with the other tenant's stored result. Contract version is part of - * it because a mutation whose input or semantics changed is a different operation — replaying the - * old result against the new contract is the silent wrong answer versioning exists to prevent. - * - *

This is context handed to the Application's idempotency capability. The platform does not - * implement replay, record storage or locking: those need transactional guarantees the transport - * layer cannot give. - * - * @param actorFingerprint keyed actor fingerprint, from the deployment's identity fingerprinter - * @param tenantFingerprint keyed tenant fingerprint, from the same fingerprinter - * @param coordinate the mutation the key belongs to - * @param contractVersion the mutation contract version the key was issued under - * @param key the client-supplied key - * @param fingerprint fingerprint of the normalised input - */ -public record GraphQlMutationIdempotencyContext( - String actorFingerprint, - String tenantFingerprint, - GraphQlMutationCoordinate coordinate, - String contractVersion, - GraphQlIdempotencyKey key, - GraphQlMutationFingerprint fingerprint) { - - public GraphQlMutationIdempotencyContext { - if (actorFingerprint == null || actorFingerprint.isBlank()) { - throw new IllegalArgumentException("actor fingerprint is required"); - } - if (tenantFingerprint == null || tenantFingerprint.isBlank()) { - throw new IllegalArgumentException("tenant fingerprint is required"); - } - if (contractVersion == null || contractVersion.isBlank()) { - throw new IllegalArgumentException("mutation contract version is required"); - } - if (coordinate == null || key == null || fingerprint == null) { - throw new IllegalArgumentException( - "idempotency scope requires coordinate, key and fingerprint"); - } - } - - /** Creates the scope. */ - public static GraphQlMutationIdempotencyContext of( - String actorFingerprint, - String tenantFingerprint, - GraphQlMutationCoordinate coordinate, - String contractVersion, - GraphQlIdempotencyKey key, - GraphQlMutationFingerprint fingerprint) { - return new GraphQlMutationIdempotencyContext( - actorFingerprint, tenantFingerprint, coordinate, contractVersion, key, fingerprint); - } - - /** - * Verifies a retry carries the same input as the original. - * - * @throws GraphQlIdempotencyConflictException when it does not - */ - public void assertCompatible(GraphQlMutationFingerprint candidate) { - if (!fingerprint.equals(candidate)) { - throw new GraphQlIdempotencyConflictException("idempotency fingerprint conflict"); - } - } - - /** - * The storage scope for the Application's idempotency record. - * - *

Uses the keyed fingerprints rather than the raw actor and tenant, so the scope can be - * persisted and logged without naming the caller to whoever holds the store. Length-framed for - * the same reason the canonical input form is: joining five caller-influenced values with a - * separator lets one of them contain the separator and collide with a different scope. - */ - public String scope() { - StringBuilder scope = new StringBuilder(); - frame(scope, actorFingerprint); - frame(scope, tenantFingerprint); - frame(scope, coordinate.value()); - frame(scope, contractVersion); - frame(scope, key.value()); - return scope.toString(); - } - - private static void frame(StringBuilder out, String value) { - out.append(value.length()).append(':').append(value).append('|'); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/mutation/GraphQlMutationIdempotencyInterceptor.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/mutation/GraphQlMutationIdempotencyInterceptor.java deleted file mode 100644 index dc025868..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/mutation/GraphQlMutationIdempotencyInterceptor.java +++ /dev/null @@ -1,77 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.mutation; - -import dev.caskeleton.adapter.inbound.graphql.context.GraphQlIdentityFingerprinter; -import dev.caskeleton.adapter.inbound.graphql.context.GraphQlRequestContext; -import dev.caskeleton.adapter.inbound.graphql.http.GraphQlExtensionsPolicy; -import java.util.Map; -import java.util.Optional; - -/** - * Builds the idempotency scope for a side-effecting mutation. - * - *

Deliberately scoped to the mutation rather than the HTTP request. A GraphQL request can carry - * several root mutations, and treating the whole request as one idempotent unit would either replay - * all of them or none. - * - *

Neither the key nor the variables are logged or measured here; only the derived scope leaves - * this class. - */ -public final class GraphQlMutationIdempotencyInterceptor { - - private GraphQlMutationIdempotencyInterceptor() {} - - /** - * Derives the idempotency scope for one mutation. - * - * @param context the request context, whose actor scopes the key - * @param fingerprinter the deployment's keyed identity fingerprinter - * @param coordinate the mutation being executed - * @param extensions request extensions, which may carry the key - * @param normalizedInput the mutation's normalised business input - * @return the scope, or empty when the client supplied no key - */ - public static Optional from( - GraphQlRequestContext context, - GraphQlIdentityFingerprinter fingerprinter, - GraphQlMutationCoordinate coordinate, - String contractVersion, - Map extensions, - Map normalizedInput) { - - if (fingerprinter == null) { - // No key, no scope. Falling back to a plain digest here would put a recoverable actor and - // tenant into a record the Application persists, which is the failure the keyed fingerprint - // exists to stop — and it would do it silently, on a deployment that never configured a key. - throw new IllegalArgumentException("an identity fingerprinter is required"); - } - Object supplied = - extensions == null ? null : extensions.get(GraphQlExtensionsPolicy.IDEMPOTENCY_KEY); - if (supplied == null) { - return Optional.empty(); - } - if (!(supplied instanceof String key)) { - throw new IllegalArgumentException("idempotencyKey extension must be a string"); - } - return Optional.of( - GraphQlMutationIdempotencyContext.of( - fingerprinter.actor(context.actor()), - fingerprinter.tenant(context.tenant()), - coordinate, - contractVersion, - new GraphQlIdempotencyKey(key), - GraphQlMutationFingerprint.of(normalizedInput))); - } - - /** - * Verifies a retry against the recorded scope. - * - * @throws GraphQlIdempotencyConflictException when the same key carries different input - */ - public static void verifyRetry( - GraphQlMutationIdempotencyContext recorded, GraphQlMutationIdempotencyContext candidate) { - if (!recorded.scope().equals(candidate.scope())) { - throw new GraphQlIdempotencyConflictException("idempotency scope mismatch"); - } - recorded.assertCompatible(candidate.fingerprint()); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlProfilerAccessPolicy.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlProfilerAccessPolicy.java deleted file mode 100644 index dca256ad..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlProfilerAccessPolicy.java +++ /dev/null @@ -1,57 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.observation; - -import java.util.Set; - -/** - * Where the GraphQL Java profiler may be enabled (design §22). - * - *

Never as a general response extension. The profiler reports per-field timings and DataLoader - * behaviour — genuinely useful locally and in an operations plane, and a precise map of the - * backend's internals if returned to a client. - */ -public enum GraphQlProfilerAccessPolicy { - - /** Local development. */ - LOCAL(true, false), - - /** Shared development environment. */ - DEVELOPMENT(true, false), - - /** Operations plane diagnostics, for an authorised admin actor only. */ - ADMIN_DIAGNOSTIC(true, false), - - /** Production request path. */ - PRODUCTION(false, false); - - private static final Set NON_PRODUCTION_ENVIRONMENTS = Set.of("local", "dev", "test"); - - private final boolean profilerEnabled; - private final boolean exposedInResponseExtensions; - - GraphQlProfilerAccessPolicy(boolean profilerEnabled, boolean exposedInResponseExtensions) { - this.profilerEnabled = profilerEnabled; - this.exposedInResponseExtensions = exposedInResponseExtensions; - } - - /** Whether the profiler may run. */ - public boolean profilerEnabled() { - return profilerEnabled; - } - - /** Whether profiler output may appear in a client response. Never true. */ - public boolean exposedInResponseExtensions() { - return exposedInResponseExtensions; - } - - /** The policy for an environment name. */ - public static GraphQlProfilerAccessPolicy forEnvironment(String environment) { - if (environment == null) { - return PRODUCTION; - } - String normalized = environment.toLowerCase(java.util.Locale.ROOT); - if ("local".equals(normalized)) { - return LOCAL; - } - return NON_PRODUCTION_ENVIRONMENTS.contains(normalized) ? DEVELOPMENT : PRODUCTION; - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/policy/GraphQlClientPolicy.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/policy/GraphQlClientPolicy.java index 1fad7643..71a9c11b 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/policy/GraphQlClientPolicy.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/policy/GraphQlClientPolicy.java @@ -25,11 +25,8 @@ import java.time.Duration; * @param defaultPageSize page size used for cost when a connection omits {@code first}/{@code last} * @param maxPageSize largest accepted page size * @param maxComplexity largest accepted pre-execution complexity score - * @param maxResponseNodes largest accepted response node count - * @param maxResponseBytes largest accepted serialized response size * @param maxExecutionTime request execution budget * @param introspectionAllowed whether this profile may run introspection - * @param persistedOperationOnly whether this profile may only run registered operations * @param namedOperationRequired whether this profile must name its operation */ public record GraphQlClientPolicy( @@ -43,11 +40,8 @@ public record GraphQlClientPolicy( int defaultPageSize, int maxPageSize, long maxComplexity, - long maxResponseNodes, - long maxResponseBytes, Duration maxExecutionTime, boolean introspectionAllowed, - boolean persistedOperationOnly, boolean namedOperationRequired) { public GraphQlClientPolicy { @@ -59,8 +53,6 @@ public record GraphQlClientPolicy( requirePositive(maxFragments, "maxFragments"); requirePositive(maxInputListElements, "maxInputListElements"); requirePositive(maxComplexity, "maxComplexity"); - requirePositive(maxResponseNodes, "maxResponseNodes"); - requirePositive(maxResponseBytes, "maxResponseBytes"); if (defaultPageSize < 1 || maxPageSize < defaultPageSize) { throw new IllegalArgumentException("invalid page policy"); } @@ -95,11 +87,8 @@ public record GraphQlClientPolicy( Math.min(20, Math.max(1, maximumPageSize)), Math.max(1, maximumPageSize), Math.max(1, maximumComplexity), - 10_000, - 5L * 1024 * 1024, Duration.ofSeconds(10), introspectionAllowed, - false, false); } diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/policy/GraphQlClientPolicyManifest.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/policy/GraphQlClientPolicyManifest.java deleted file mode 100644 index f5daca0c..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/policy/GraphQlClientPolicyManifest.java +++ /dev/null @@ -1,92 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.policy; - -import dev.caskeleton.adapter.inbound.graphql.api.GraphQlClientProfile; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Set; - -/** - * The per-environment set of client policies. - * - *

The design keeps benchmarked limits in an environment manifest rather than in application - * code, so this is the one place a profile is resolved from. An unknown profile is a startup or - * request failure rather than a silent fallback to a permissive default, and a duplicate profile is - * rejected at construction because two conflicting policies for one client cannot be resolved - * safely later. - */ -public final class GraphQlClientPolicyManifest { - - private final Map policies; - - private GraphQlClientPolicyManifest(Map policies) { - this.policies = Map.copyOf(policies); - } - - /** - * Builds a manifest from distinct profile entries. - * - * @throws IllegalArgumentException when a profile appears twice - */ - public static GraphQlClientPolicyManifest of( - Map entries) { - Map copy = new LinkedHashMap<>(); - entries.forEach( - (profile, policy) -> { - if (copy.putIfAbsent(profile, policy) != null) { - throw new IllegalArgumentException("duplicate client profile " + profile.value()); - } - }); - if (copy.isEmpty()) { - throw new IllegalArgumentException("client policy manifest cannot be empty"); - } - return new GraphQlClientPolicyManifest(copy); - } - - /** Builder that rejects a duplicate profile at the point it is added. */ - public static Builder builder() { - return new Builder(); - } - - /** - * Resolves the policy for a profile. - * - * @throws GraphQlUnknownClientProfileException when the profile is not registered - */ - public GraphQlClientPolicy require(GraphQlClientProfile profile) { - GraphQlClientPolicy policy = policies.get(profile); - if (policy == null) { - throw new GraphQlUnknownClientProfileException(profile.value()); - } - return policy; - } - - /** Registered profiles, for startup reporting and the actuator configuration report. */ - public Set profiles() { - return policies.keySet(); - } - - /** Accumulates distinct profile entries. */ - public static final class Builder { - - private final Map entries = new LinkedHashMap<>(); - - private Builder() {} - - /** - * Registers one profile policy. - * - * @throws IllegalArgumentException when the profile was already registered - */ - public Builder policy(GraphQlClientProfile profile, GraphQlClientPolicy policy) { - if (entries.putIfAbsent(profile, policy) != null) { - throw new IllegalArgumentException("duplicate client profile " + profile.value()); - } - return this; - } - - /** Builds the immutable manifest. */ - public GraphQlClientPolicyManifest build() { - return of(entries); - } - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/policy/GraphQlOperationCatalog.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/policy/GraphQlOperationCatalog.java deleted file mode 100644 index 9248df8d..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/policy/GraphQlOperationCatalog.java +++ /dev/null @@ -1,72 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.policy; - -import dev.caskeleton.adapter.inbound.graphql.api.GraphQlOperationName; -import dev.caskeleton.adapter.inbound.graphql.api.GraphQlSchemaCoordinate; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Optional; -import java.util.Set; - -/** - * The registry of operations the platform will execute in production, keyed by operation name. - * - *

Every production operation needs both a registered name and a schema coordinate: the name is - * what tracing, cost exceptions, the persisted registry and usage analytics key on, and the - * coordinate is what the cost catalog, fetch profiles and field authorization key on. Registering a - * duplicate name is rejected because two policies for one name cannot be resolved deterministically - * afterwards. - */ -public final class GraphQlOperationCatalog { - - private final Map registrations = new LinkedHashMap<>(); - - /** - * Registers one operation. - * - * @throws IllegalArgumentException when the operation name is already registered - */ - public GraphQlOperationCatalog register( - GraphQlOperationPolicy policy, GraphQlSchemaCoordinate coordinate) { - if (policy == null || coordinate == null) { - throw new IllegalArgumentException("operation policy and schema coordinate are required"); - } - if (registrations.putIfAbsent(policy.name(), new Registration(policy, coordinate)) != null) { - throw new IllegalArgumentException("duplicate operation name " + policy.name().value()); - } - return this; - } - - /** - * Resolves a registered operation policy. - * - * @throws GraphQlUnknownOperationException when the operation is not registered - */ - public GraphQlOperationPolicy require(GraphQlOperationName name) { - return find(name) - .orElseThrow(() -> new GraphQlUnknownOperationException(name.value())) - .policy(); - } - - /** The schema coordinate registered for an operation. */ - public GraphQlSchemaCoordinate coordinateOf(GraphQlOperationName name) { - return find(name) - .orElseThrow(() -> new GraphQlUnknownOperationException(name.value())) - .coordinate(); - } - - /** Whether the operation is registered. */ - public boolean contains(GraphQlOperationName name) { - return name != null && registrations.containsKey(name); - } - - /** Registered operation names, used for low-cardinality observation and startup reporting. */ - public Set operationNames() { - return Set.copyOf(registrations.keySet()); - } - - private Optional find(GraphQlOperationName name) { - return name == null ? Optional.empty() : Optional.ofNullable(registrations.get(name)); - } - - private record Registration(GraphQlOperationPolicy policy, GraphQlSchemaCoordinate coordinate) {} -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/policy/GraphQlOperationPolicy.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/policy/GraphQlOperationPolicy.java deleted file mode 100644 index ff1041ef..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/policy/GraphQlOperationPolicy.java +++ /dev/null @@ -1,53 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.policy; - -import dev.caskeleton.adapter.inbound.graphql.api.GraphQlOperationName; - -/** - * Registered metadata for one operation the platform is willing to execute. - * - *

Two invariants are enforced here rather than at runtime. A {@code STREAM} resolver only makes - * sense for a subscription, and idempotency or an expected version only mean something for a - * mutation — declaring either on a query would promise a guarantee the read path does not - * implement. - * - * @param name registered operation name - * @param operationType root operation type - * @param executionType how the resolver executes - * @param idempotencyRequired whether the mutation requires an idempotency key - * @param expectedVersionRequired whether the mutation requires an optimistic expected version - */ -public record GraphQlOperationPolicy( - GraphQlOperationName name, - GraphQlOperationType operationType, - ResolverExecutionType executionType, - boolean idempotencyRequired, - boolean expectedVersionRequired) { - - public GraphQlOperationPolicy { - if (name == null || operationType == null || executionType == null) { - throw new IllegalArgumentException("operation policy requires name, type and execution type"); - } - if (executionType == ResolverExecutionType.STREAM - && operationType != GraphQlOperationType.SUBSCRIPTION) { - throw new IllegalArgumentException("stream resolver requires subscription"); - } - if (operationType == GraphQlOperationType.SUBSCRIPTION - && executionType != ResolverExecutionType.STREAM) { - throw new IllegalArgumentException("subscription requires a stream resolver"); - } - if ((idempotencyRequired || expectedVersionRequired) - && operationType != GraphQlOperationType.MUTATION) { - throw new IllegalArgumentException( - "idempotency and expected version apply to mutations only"); - } - } - - /** Registers an operation that needs no expected version. */ - public GraphQlOperationPolicy( - GraphQlOperationName name, - GraphQlOperationType operationType, - ResolverExecutionType executionType, - boolean idempotencyRequired) { - this(name, operationType, executionType, idempotencyRequired, false); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/policy/GraphQlPolicyViolation.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/policy/GraphQlPolicyViolation.java deleted file mode 100644 index fd7b63f0..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/policy/GraphQlPolicyViolation.java +++ /dev/null @@ -1,31 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.policy; - -/** - * One exceeded or contradicted policy limit. - * - *

Diagnostics report the limit that was hit and the two numbers involved — never the document, - * the variables or the value that triggered it — so a rejection can be explained to a client and - * counted in a metric without leaking request content. - * - * @param limitName bounded limit identity, for example {@code MAX_DEPTH} - * @param observed measured value - * @param allowed configured ceiling - */ -public record GraphQlPolicyViolation(String limitName, long observed, long allowed) { - - public GraphQlPolicyViolation { - if (limitName == null || limitName.isBlank()) { - throw new IllegalArgumentException("policy limit name is required"); - } - } - - /** Creates a violation for a named limit. */ - public static GraphQlPolicyViolation of(String limitName, long observed, long allowed) { - return new GraphQlPolicyViolation(limitName, observed, allowed); - } - - /** Stable, content-free description safe for a client-visible error and for logs. */ - public String describe() { - return limitName + " exceeded: " + observed + " > " + allowed; - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/policy/GraphQlUnknownClientProfileException.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/policy/GraphQlUnknownClientProfileException.java deleted file mode 100644 index f6c7891c..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/policy/GraphQlUnknownClientProfileException.java +++ /dev/null @@ -1,21 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.policy; - -/** - * Raised when a request or startup check names a client profile the manifest does not register. - * - *

Fail-closed on purpose: an unregistered profile must not fall back to a permissive default, - * which would silently grant unbounded documents, complexity and page sizes. - */ -public class GraphQlUnknownClientProfileException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - /** - * Creates the failure. - * - * @param profile the bounded profile identity that was not registered - */ - public GraphQlUnknownClientProfileException(String profile) { - super("unknown GraphQL client profile " + profile); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/policy/GraphQlUnknownOperationException.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/policy/GraphQlUnknownOperationException.java deleted file mode 100644 index 2c2911c4..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/policy/GraphQlUnknownOperationException.java +++ /dev/null @@ -1,20 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.policy; - -/** - * Raised when an operation is not present in the operation catalog. - * - *

Carries only the bounded operation name, never the document or the variables. - */ -public class GraphQlUnknownOperationException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - /** - * Creates the failure. - * - * @param operationName the bounded operation name that was not registered - */ - public GraphQlUnknownOperationException(String operationName) { - super("unknown GraphQL operation " + operationName); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/policy/ResolverExecutionType.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/policy/ResolverExecutionType.java deleted file mode 100644 index d618cd7d..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/policy/ResolverExecutionType.java +++ /dev/null @@ -1,23 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.policy; - -/** - * How a resolver actually executes (design §10). - * - *

Registered per resolver so the platform can reject a combination the runtime profile cannot - * serve — a blocking repository call on a WebFlux event loop, or a stream outside a subscription — - * at startup instead of discovering it under load. - */ -public enum ResolverExecutionType { - - /** Blocks the calling thread; needs a virtual thread or a bounded platform-thread executor. */ - BLOCKING, - - /** Returns a {@code CompletionStage} completed elsewhere. */ - ASYNC, - - /** Returns a Reactor type and never blocks. */ - REACTIVE, - - /** Returns a {@code Publisher} of events; valid only for a subscription. */ - STREAM -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/release/GraphQlCompatibilityMatrix.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/release/GraphQlCompatibilityMatrix.java deleted file mode 100644 index c6ed0c31..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/release/GraphQlCompatibilityMatrix.java +++ /dev/null @@ -1,75 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.release; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -/** - * The framework combination a release was verified against (design §3). - * - *

The Spring Boot BOM is the source of truth for the Spring for GraphQL and GraphQL Java - * pairing. An independent override of either is allowed only in a deliberate compatibility lane — - * silently pinning one of them is how a deployment ends up on a combination nobody tested. - * - * @param javaVersion Java runtime major version - * @param springBootVersion Spring Boot BOM version - * @param springGraphQlVersion Spring for GraphQL version - * @param graphQlJavaVersion GraphQL Java version - * @param bomManaged whether the GraphQL versions came from the BOM - */ -public record GraphQlCompatibilityMatrix( - int javaVersion, - String springBootVersion, - String springGraphQlVersion, - String graphQlJavaVersion, - boolean bomManaged) { - - /** Minimum Java version the platform supports. */ - public static final int MINIMUM_JAVA_VERSION = 21; - - /** Spring for GraphQL major line the platform targets. */ - public static final String SUPPORTED_SPRING_GRAPHQL_LINE = "2."; - - /** GraphQL Java major line the platform targets. */ - public static final String SUPPORTED_GRAPHQL_JAVA_LINE = "25."; - - public GraphQlCompatibilityMatrix { - if (springBootVersion == null || springGraphQlVersion == null || graphQlJavaVersion == null) { - throw new IllegalArgumentException("every framework version is required"); - } - } - - /** Whether this combination is supported. */ - public boolean supported() { - return problems().isEmpty(); - } - - /** Why this combination is unsupported, in a deterministic order. */ - public List problems() { - List problems = new ArrayList<>(); - if (javaVersion < MINIMUM_JAVA_VERSION) { - problems.add("Java " + javaVersion + " is below the supported " + MINIMUM_JAVA_VERSION); - } - if (!springGraphQlVersion.startsWith(SUPPORTED_SPRING_GRAPHQL_LINE)) { - problems.add("Spring for GraphQL " + springGraphQlVersion + " is outside the supported line"); - } - if (!graphQlJavaVersion.startsWith(SUPPORTED_GRAPHQL_JAVA_LINE)) { - problems.add("GraphQL Java " + graphQlJavaVersion + " is outside the supported line"); - } - if (!bomManaged) { - problems.add( - "GraphQL versions must come from the Spring Boot BOM unless a compatibility lane is declared"); - } - return List.copyOf(problems); - } - - /** The matrix as a flat map, for the release report. */ - public Map asMap() { - return Map.of( - "java", javaVersion, - "springBoot", springBootVersion, - "springGraphQl", springGraphQlVersion, - "graphQlJava", graphQlJavaVersion, - "bomManaged", bomManaged); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/release/GraphQlFaultScenario.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/release/GraphQlFaultScenario.java deleted file mode 100644 index 01ed8793..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/release/GraphQlFaultScenario.java +++ /dev/null @@ -1,36 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.release; - -import java.util.List; - -/** - * The fault scenarios a Stable release must have run (design §24.3). - * - *

Cancellation leak is the one most often skipped and most often broken: a timeout that releases - * the caller while the database statement and the HTTP call keep running turns a slow dependency - * into an exhausted pool, and no functional test detects it. - */ -public enum GraphQlFaultScenario { - - /** A dependency stops responding. */ - DOWNSTREAM_TIMEOUT, - - /** One dependency of several fails. */ - PARTIAL_DEPENDENCY_FAILURE, - - /** A request is cancelled and downstream work must stop with it. */ - CANCELLATION_LEAK, - - /** The runtime response budget is exceeded mid-serialization. */ - RESPONSE_BUDGET_EXCEEDED, - - /** In-flight queries during shutdown. */ - SHUTDOWN_IN_FLIGHT_QUERY, - - /** An internal failure must not disclose SQL, queries, URLs or stack traces. */ - ERROR_MASKING; - - /** Every scenario the Stable gate requires. */ - public static List required() { - return List.of(values()); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/release/GraphQlPerformanceScenario.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/release/GraphQlPerformanceScenario.java deleted file mode 100644 index 2fd82f51..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/release/GraphQlPerformanceScenario.java +++ /dev/null @@ -1,52 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.release; - -import java.util.List; - -/** - * The load scenarios a Stable release must have run (design §24.3). - * - *

Each one exercises a different limit. A deep query and a wide alias query stress different - * budgets; pool saturation and virtual-thread saturation fail differently; and event-loop blocking - * only shows up under concurrency. Running one and calling it "load tested" is how the others reach - * production untested. - */ -public enum GraphQlPerformanceScenario { - - /** A named query at high concurrency. */ - NAMED_QUERY_HIGH_CONCURRENCY, - - /** A deep but valid selection. */ - DEEP_VALID_QUERY, - - /** A wide alias query, which a depth limit alone does not catch. */ - WIDE_ALIAS_QUERY, - - /** Nested connections, where page sizes multiply. */ - NESTED_CONNECTION, - - /** DataLoader batch saturation. */ - DATALOADER_SATURATION, - - /** JPA connection pool saturation. */ - JPA_POOL_SATURATION, - - /** MongoDB connection pool saturation. */ - MONGO_POOL_SATURATION, - - /** Downstream HTTP bulkhead saturation. */ - HTTP_BULKHEAD_SATURATION, - - /** Large response serialization. */ - LARGE_RESPONSE_SERIALIZATION, - - /** Virtual-thread saturation on the blocking profile. */ - VIRTUAL_THREAD_SATURATION, - - /** Event-loop blocking detection on the reactive profile. */ - EVENT_LOOP_BLOCKING_DETECTION; - - /** Every scenario the Stable gate requires. */ - public static List required() { - return List.of(values()); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/release/GraphQlReleaseEvidence.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/release/GraphQlReleaseEvidence.java deleted file mode 100644 index 6f4abf15..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/release/GraphQlReleaseEvidence.java +++ /dev/null @@ -1,83 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.release; - -/** - * The evidence a Stable release requires (design §27). - * - *

Five independent kinds, all mandatory. They fail in different ways and none substitutes for - * another: a passing contract suite says nothing about behaviour under load, and a passing load - * test says nothing about what happens when a dependency stops responding. - * - * @param schemaPassed schema assembly, mapping and compatibility gates - * @param contractsPassed transport, security, DataLoader and pagination contract suites - * @param performancePassed load scenarios - * @param faultPassed fault and cancellation scenarios - * @param compatibilityPassed framework version matrix - */ -public record GraphQlReleaseEvidence( - boolean schemaPassed, - boolean contractsPassed, - boolean performancePassed, - boolean faultPassed, - boolean compatibilityPassed) { - - /** A builder, so a partially collected evidence set is obvious at the call site. */ - public static Builder builder() { - return new Builder(); - } - - /** Whether every kind of evidence is present. */ - public boolean complete() { - return schemaPassed - && contractsPassed - && performancePassed - && faultPassed - && compatibilityPassed; - } - - /** Accumulates evidence. */ - public static final class Builder { - - private boolean schema; - private boolean contracts; - private boolean performance; - private boolean fault; - private boolean compatibility; - - private Builder() {} - - /** Records the schema gate result. */ - public Builder schemaPassed(boolean value) { - schema = value; - return this; - } - - /** Records the contract suite result. */ - public Builder contractsPassed(boolean value) { - contracts = value; - return this; - } - - /** Records the performance lane result. */ - public Builder performancePassed(boolean value) { - performance = value; - return this; - } - - /** Records the fault lane result. */ - public Builder faultPassed(boolean value) { - fault = value; - return this; - } - - /** Records the compatibility matrix result. */ - public Builder compatibilityPassed(boolean value) { - compatibility = value; - return this; - } - - /** Builds the evidence set. */ - public GraphQlReleaseEvidence build() { - return new GraphQlReleaseEvidence(schema, contracts, performance, fault, compatibility); - } - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/release/GraphQlReleaseException.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/release/GraphQlReleaseException.java deleted file mode 100644 index 902a6d10..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/release/GraphQlReleaseException.java +++ /dev/null @@ -1,20 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.release; - -/** - * Raised when the Stable release gate refuses a release. - * - *

Names the missing evidence, so the answer to "why is this blocked" is in the message. - */ -public class GraphQlReleaseException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - /** - * Creates the failure. - * - * @param message which evidence is missing - */ - public GraphQlReleaseException(String message) { - super(message); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/release/GraphQlReleaseGate.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/release/GraphQlReleaseGate.java deleted file mode 100644 index 9fda0650..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/release/GraphQlReleaseGate.java +++ /dev/null @@ -1,78 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.release; - -import java.time.Instant; -import java.util.ArrayList; -import java.util.List; - -/** - * The Stable release gate (design §27). - * - *

Refuses a release with incomplete evidence. An override exists because incidents happen, but - * it must name an approver, a reason and an expiry — an override without an expiry is simply a - * permanently disabled gate, which is how a gate stops meaning anything. - */ -public final class GraphQlReleaseGate { - - /** - * Verifies a release. - * - * @throws GraphQlReleaseException naming the missing evidence - */ - public void verify(GraphQlReleaseEvidence evidence) { - List missing = missing(evidence); - if (!missing.isEmpty()) { - throw new GraphQlReleaseException( - "schema, contract, performance, fault and compatibility evidence are all required; missing: " - + missing); - } - } - - /** Which evidence is missing, in a deterministic order. */ - public List missing(GraphQlReleaseEvidence evidence) { - List missing = new ArrayList<>(); - if (!evidence.schemaPassed()) { - missing.add("schema"); - } - if (!evidence.contractsPassed()) { - missing.add("contracts"); - } - if (!evidence.performancePassed()) { - missing.add("performance"); - } - if (!evidence.faultPassed()) { - missing.add("fault"); - } - if (!evidence.compatibilityPassed()) { - missing.add("compatibility"); - } - return List.copyOf(missing); - } - - /** - * Verifies a release under an audited override. - * - * @param evidence the collected evidence - * @param override the audited override, or {@code null} - * @param now current instant, used to reject an expired override - * @throws GraphQlReleaseException when evidence is missing and no valid override covers it - */ - public void verify( - GraphQlReleaseEvidence evidence, GraphQlReleaseOverride override, Instant now) { - List missing = missing(evidence); - if (missing.isEmpty()) { - return; - } - if (override == null) { - verify(evidence); - return; - } - if (!override.valid(now)) { - throw new GraphQlReleaseException( - "the release override has expired; missing evidence: " + missing); - } - if (!override.covers(missing)) { - throw new GraphQlReleaseException( - "the release override does not cover the missing evidence: " + missing); - } - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/release/GraphQlReleaseOverride.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/release/GraphQlReleaseOverride.java deleted file mode 100644 index aec1c281..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/release/GraphQlReleaseOverride.java +++ /dev/null @@ -1,48 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.release; - -import java.time.Instant; -import java.util.List; -import java.util.Set; -import java.util.TreeSet; - -/** - * An audited, expiring waiver for missing release evidence. - * - *

Every field is required. An override with no approver cannot be questioned, one with no reason - * cannot be reviewed, and one with no expiry never gets removed — at which point the gate it waives - * has been permanently disabled by something nobody remembers approving. - * - * @param approver who approved the waiver - * @param reason why it was acceptable - * @param waivedEvidence which evidence kinds it covers - * @param expiresAt when the waiver stops being valid - */ -public record GraphQlReleaseOverride( - String approver, String reason, Set waivedEvidence, Instant expiresAt) { - - public GraphQlReleaseOverride { - if (approver == null || approver.isBlank()) { - throw new IllegalArgumentException("a release override requires an approver"); - } - if (reason == null || reason.isBlank()) { - throw new IllegalArgumentException("a release override requires a reason"); - } - if (expiresAt == null) { - throw new IllegalArgumentException("a release override requires an expiry"); - } - waivedEvidence = Set.copyOf(new TreeSet<>(waivedEvidence)); - if (waivedEvidence.isEmpty()) { - throw new IllegalArgumentException("a release override must name the evidence it waives"); - } - } - - /** Whether the waiver is still valid. */ - public boolean valid(Instant now) { - return now.isBefore(expiresAt); - } - - /** Whether the waiver covers every missing evidence kind. */ - public boolean covers(List missing) { - return waivedEvidence.containsAll(missing); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/release/GraphQlReleaseReportWriter.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/release/GraphQlReleaseReportWriter.java deleted file mode 100644 index cbdadd37..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/release/GraphQlReleaseReportWriter.java +++ /dev/null @@ -1,57 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.release; - -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -/** - * Renders the release decision as machine-readable evidence. - * - *

Machine-readable so a pipeline can gate on it and a later audit can read what was actually - * verified. The report carries verdicts, capability names and framework versions — never the - * schema, a persisted document or a key. - */ -public final class GraphQlReleaseReportWriter { - - private final GraphQlReleaseGate gate; - - /** - * Creates the writer. - * - * @param gate the gate whose decision is reported - */ - public GraphQlReleaseReportWriter(GraphQlReleaseGate gate) { - if (gate == null) { - throw new IllegalArgumentException("release gate is required"); - } - this.gate = gate; - } - - /** - * Writes the release report. - * - * @param evidence collected evidence - * @param matrix the verified framework combination - * @param schemaHash hash of the released schema - */ - public Map write( - GraphQlReleaseEvidence evidence, GraphQlCompatibilityMatrix matrix, String schemaHash) { - - List missing = gate.missing(evidence); - Map report = new LinkedHashMap<>(); - report.put("verdict", missing.isEmpty() && matrix.supported() ? "PASS" : "BLOCKED"); - report.put("schemaHash", schemaHash); - report.put("missingEvidence", missing); - report.put("compatibility", matrix.asMap()); - report.put("compatibilityProblems", matrix.problems()); - report.put( - "requiredPerformanceScenarios", - GraphQlPerformanceScenario.required().stream().map(Enum::name).toList()); - report.put( - "requiredFaultScenarios", - GraphQlFaultScenario.required().stream().map(Enum::name).toList()); - report.put("stableCapabilities", GraphQlStableCapabilityManifest.STABLE); - report.put("unsupportedCapabilities", GraphQlStableCapabilityManifest.UNSUPPORTED); - return Map.copyOf(report); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/release/GraphQlStableCapabilityManifest.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/release/GraphQlStableCapabilityManifest.java deleted file mode 100644 index a88f6b76..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/release/GraphQlStableCapabilityManifest.java +++ /dev/null @@ -1,91 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.release; - -import java.util.List; -import java.util.Set; - -/** - * What the Stable platform supports, and what it deliberately does not (design §25, §28). - * - *

Written down so "unsupported" is a decision with a reason rather than a gap someone might fill - * by accident. Every entry in {@link #UNSUPPORTED} has an alternative in the design: uploads go - * through the Fileserver, atomic multi-step work goes through one mutation use case, and - * cross-request caching goes through the cache capability with its own key model. - */ -public final class GraphQlStableCapabilityManifest { - - /** Capabilities the Stable platform supports. */ - public static final Set STABLE = - Set.of( - "SDL_FIRST_SCHEMA", - "QUERY_MUTATION", - "HTTP_POST", - "GRAPHQL_RESPONSE_JSON", - "PARTIAL_DATA_AND_ERRORS", - "REQUEST_CONTEXT", - "SECURITY", - "DATALOADER", - "SIGNED_CURSOR_CONNECTION", - "COST_CONTROL", - "PREPARSED_CACHE", - "FETCH_PROFILE", - "OBSERVABILITY"); - - /** Capabilities that require the Advanced plan and an explicit feature flag. */ - public static final Set ADVANCED = - Set.of( - "PERSISTED_OPERATION", - "WEBSOCKET_SUBSCRIPTION", - "SSE_SUBSCRIPTION", - "FEDERATION_SUBGRAPH", - "DATALOADER_CHAINING", - "CODE_GENERATION"); - - /** Capabilities that remain experimental until a promotion decision is recorded. */ - public static final Set EXPERIMENTAL = - Set.of("RSOCKET", "HTTP_GET", "INCREMENTAL_DELIVERY"); - - /** Capabilities the platform does not implement, with the alternative in each case. */ - public static final List UNSUPPORTED = - List.of( - "GRAPHQL_MULTIPART_UPLOAD", - "HTTP_ARRAY_BATCH", - "ARBITRARY_JSON_INPUT_GATEWAY", - "PERSISTENCE_ENTITY_AUTO_EXPOSURE", - // Was an allowlisted Advanced capability. An allowlist that lets a repository back a - // GraphQL field is still a controller reaching a repository — the second canonical - // hard-stop in AGENTS.md — and a capability flag cannot make an architectural rule - // conditional. Resolvers reach storage through an application use case or not at all. - "SPRING_DATA_REPOSITORY_AUTO_EXPOSURE", - "REQUEST_WIDE_DB_TRANSACTION", - "DURABLE_SUBSCRIPTION_GUARANTEE", - "EXACTLY_ONCE_SUBSCRIPTION_DELIVERY", - "RAW_ENGINE_ACCESS_FOR_APPLICATIONS", - "UNBOUNDED_LIST_AND_DEFAULT_TOTAL_COUNT", - "RESPONSE_CACHE"); - - private GraphQlStableCapabilityManifest() {} - - /** Whether a capability is part of the Stable surface. */ - public static boolean stable(String capability) { - return STABLE.contains(capability); - } - - /** - * Verifies a capability may be activated on the Stable starter. - * - * @throws GraphQlReleaseException when it is Advanced, Experimental or unsupported - */ - public static void requireStable(String capability) { - if (STABLE.contains(capability)) { - return; - } - if (UNSUPPORTED.contains(capability)) { - throw new GraphQlReleaseException(capability + " is not supported by the GraphQL platform"); - } - if (ADVANCED.contains(capability) || EXPERIMENTAL.contains(capability)) { - throw new GraphQlReleaseException( - capability + " requires the Advanced plan and an explicit feature flag"); - } - throw new GraphQlReleaseException(capability + " is not a registered GraphQL capability"); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlDocumentAuthorizationHandler.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlDocumentAuthorizationHandler.java index 9b384bec..682afa11 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlDocumentAuthorizationHandler.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlDocumentAuthorizationHandler.java @@ -2,6 +2,7 @@ package dev.caskeleton.adapter.inbound.graphql.runtime; import dev.caskeleton.adapter.inbound.graphql.api.GraphQlSchemaCoordinate; import dev.caskeleton.adapter.inbound.graphql.cost.GraphQlDocumentShapeAnalyzer; +import dev.caskeleton.adapter.inbound.graphql.cost.GraphQlStructuralLimitException; import dev.caskeleton.adapter.inbound.graphql.execution.GraphQlExecutionStage; import dev.caskeleton.adapter.inbound.graphql.policy.GraphQlClientPolicy; import dev.caskeleton.adapter.inbound.graphql.security.GraphQlAuthorizationInterceptor; @@ -12,8 +13,7 @@ import graphql.language.InlineFragment; import graphql.language.OperationDefinition; import graphql.language.Selection; import graphql.language.SelectionSet; -import java.util.ArrayDeque; -import java.util.Deque; +import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; @@ -64,7 +64,7 @@ public final class GraphQlDocumentAuthorizationHandler implements GraphQlExecuti context.requireDocument(), operation, policy.introspectionAllowed()); String rootTypeName = rootTypeName(operation); - for (String fieldName : rootFieldNames(context, operation)) { + for (String fieldName : rootFieldNames(context, operation, analyzer.maximumVisitedNodes())) { authorization.authorize( context.requestContext(), new GraphQlSchemaCoordinate(rootTypeName, fieldName)); } @@ -89,9 +89,15 @@ public final class GraphQlDocumentAuthorizationHandler implements GraphQlExecuti *

Fragments are expanded rather than skipped: a root field reached only through a named * fragment is executed exactly like one written inline, so authorizing only the inline ones would * make {@code query { ...Hidden }} a bypass. + * + *

Each fragment is expanded once per walk. The result is a set, and a fragment contributes the + * same root names wherever it is spread, so a second expansion adds nothing — while re-walking + * every spread lets a 1.6 KB document of nested double spreads cost 2^40 visits before the cost + * stage ever sees it. The same set cuts fragment cycles. The analyzer's traversal budget stays as + * a backstop and rejects exactly as the cost stage does. */ private static Set rootFieldNames( - GraphQlExecutionContext context, OperationDefinition operation) { + GraphQlExecutionContext context, OperationDefinition operation, int maximumVisitedNodes) { Map fragments = new LinkedHashMap<>(); context @@ -104,35 +110,47 @@ public final class GraphQlDocumentAuthorizationHandler implements GraphQlExecuti } }); - Set names = new LinkedHashSet<>(); - collect(operation.getSelectionSet(), fragments, names, new ArrayDeque<>()); - return names; + RootFieldWalk walk = new RootFieldWalk(fragments, maximumVisitedNodes); + walk.collect(operation.getSelectionSet()); + return walk.names; } - private static void collect( - SelectionSet selectionSet, - Map fragments, - Set names, - Deque expansionPath) { + private static final class RootFieldWalk { - if (selectionSet == null) { - return; + private final Map fragments; + private final int maximumVisitedNodes; + private final Set expanded = new HashSet<>(); + private final Set names = new LinkedHashSet<>(); + private int visited; + + RootFieldWalk(Map fragments, int maximumVisitedNodes) { + this.fragments = fragments; + this.maximumVisitedNodes = maximumVisitedNodes; } - for (Selection selection : selectionSet.getSelections()) { - if (selection instanceof Field field) { - if (!field.getName().startsWith(GraphQlDocumentShapeAnalyzer.INTROSPECTION_FIELD_PREFIX)) { - names.add(field.getName()); + + void collect(SelectionSet selectionSet) { + if (selectionSet == null) { + return; + } + for (Selection selection : selectionSet.getSelections()) { + if (++visited > maximumVisitedNodes) { + throw GraphQlStructuralLimitException.of( + "DOCUMENT_TRAVERSAL", visited, maximumVisitedNodes); } - } else if (selection instanceof InlineFragment inlineFragment) { - collect(inlineFragment.getSelectionSet(), fragments, names, expansionPath); - } else if (selection instanceof FragmentSpread spread) { - FragmentDefinition fragment = fragments.get(spread.getName()); - if (fragment == null || expansionPath.contains(spread.getName())) { - continue; + if (selection instanceof Field field) { + if (!field + .getName() + .startsWith(GraphQlDocumentShapeAnalyzer.INTROSPECTION_FIELD_PREFIX)) { + names.add(field.getName()); + } + } else if (selection instanceof InlineFragment inlineFragment) { + collect(inlineFragment.getSelectionSet()); + } else if (selection instanceof FragmentSpread spread) { + FragmentDefinition fragment = fragments.get(spread.getName()); + if (fragment != null && expanded.add(spread.getName())) { + collect(fragment.getSelectionSet()); + } } - expansionPath.push(spread.getName()); - collect(fragment.getSelectionSet(), fragments, names, expansionPath); - expansionPath.pop(); } } } diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlWireErrorMapper.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlWireErrorMapper.java index 8b022e2a..8b4eb089 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlWireErrorMapper.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlWireErrorMapper.java @@ -20,10 +20,12 @@ import java.util.Objects; * the failure happened to take — and the two resolver classes differed only in the case of one * letter, so importing the wrong one compiled. * - *

Everything routes through here now. Request-level rejections and field-level failures are - * different strategies, because they are genuinely different situations — one has no response path - * and produces a 4xx, the other is a field inside a 200 — but both draw codes, categories, - * retryability and masking from this catalogue. + *

Field-level failures route through here. Request-stage rejections do not yet: {@code + * GraphQlPlatformWebInterceptor} and {@code GraphQlPlatformInstrumentation} call {@link + * GraphQlPlatformRejectionMapper#map} directly, so an {@link ApiErrorCarrier} thrown before + * execution (for example by an adopter's {@code GraphQlPrincipalResolver}) becomes {@code + * INTERNAL_ERROR} there while the same exception from a resolver keeps its code. Both paths share + * the platform catalogue in {@link GraphQlPlatformRejectionMapper#mapKnown}. * *

An unrecognised failure never contributes its own message. That is the fail-closed direction: * a new exception type nobody mapped becomes an opaque internal error with a correlation id, and @@ -48,22 +50,11 @@ public final class GraphQlWireErrorMapper { return new GraphQlWireErrorMapper(GraphQlExceptionResolver.defaults()); } - /** - * Maps a rejection raised before execution started. - * - *

These carry no response path and become a transport-level failure, so the strategy differs - * from {@link #mapFieldFailure}; the vocabulary does not. - */ - public GraphQlWireError mapRequestRejection(Throwable failure, GraphQlErrorContext context) { - GraphQlWireError platform = GraphQlPlatformRejectionMapper.mapKnown(failure, context); - return platform != null ? platform : mapCommon(failure, context); - } - /** * Maps a failure thrown by a data fetcher. * - *

Platform rejections are consulted first here too: an authorization denial raised from inside - * a resolver means the same thing to a client as one raised before execution, and giving it a + *

Platform rejections are consulted first: an authorization denial raised from inside a + * resolver means the same thing to a client as one raised before execution, and giving it a * different code because of where it was thrown would be an implementation detail on the wire. */ public GraphQlWireError mapFieldFailure(Throwable failure, GraphQlErrorContext context) { diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlContractVersion.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlContractVersion.java deleted file mode 100644 index 772376b6..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlContractVersion.java +++ /dev/null @@ -1,29 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.schema; - -import java.util.regex.Pattern; - -/** - * A version of one schema-governing policy — breaking-change rules, the scalar manifest or the - * directive manifest. - * - *

These are versioned separately from the schema hash because they change independently: a - * scalar's coercion or a directive's meaning can change while the SDL text stays byte-identical, - * and that is still a client-visible change. - * - * @param value bounded version identity, for example {@code stable-v1} - */ -public record GraphQlContractVersion(String value) { - - private static final Pattern PATTERN = Pattern.compile("[a-z][a-z0-9.-]{1,63}"); - - public GraphQlContractVersion { - if (value == null || !PATTERN.matcher(value).matches()) { - throw new IllegalArgumentException("invalid GraphQL contract version"); - } - } - - /** Creates a contract version. */ - public static GraphQlContractVersion of(String value) { - return new GraphQlContractVersion(value); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlMappingInspectionGate.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlMappingInspectionGate.java deleted file mode 100644 index 652af3bd..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlMappingInspectionGate.java +++ /dev/null @@ -1,52 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.schema; - -import java.util.List; - -/** - * Turns schema mapping inspection from a report into a gate. - * - *

Runs after all controller, scalar and type-resolver wiring is registered — inspecting earlier - * would report resolvers that simply had not been contributed yet. Under the Stable policy any - * blocking issue fails startup; under the Local policy issues are advisory except a forbidden - * scalar or an unknown resolver, neither of which can work at runtime under any profile. - */ -public final class GraphQlMappingInspectionGate { - - private final GraphQlMappingPolicy policy; - - private GraphQlMappingInspectionGate(GraphQlMappingPolicy policy) { - this.policy = policy; - } - - /** The Stable gate: blocking issues fail startup. */ - public static GraphQlMappingInspectionGate stable() { - return new GraphQlMappingInspectionGate(GraphQlMappingPolicy.FAIL); - } - - /** The Local gate: advisory, except for issues that cannot work at runtime. */ - public static GraphQlMappingInspectionGate local() { - return new GraphQlMappingInspectionGate(GraphQlMappingPolicy.WARN); - } - - /** The policy this gate applies. */ - public GraphQlMappingPolicy policy() { - return policy; - } - - /** - * Verifies inspection output. - * - * @throws GraphQlSchemaMappingException when the policy treats any issue as fatal - */ - public void verify(List issues) { - List fatal = issues.stream().filter(policy::fatal).toList(); - if (!fatal.isEmpty()) { - throw new GraphQlSchemaMappingException(fatal); - } - } - - /** Issues the policy tolerates, for reporting at startup. */ - public List advisory(List issues) { - return issues.stream().filter(issue -> !policy.fatal(issue)).toList(); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlMappingIssue.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlMappingIssue.java deleted file mode 100644 index b1eb5a25..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlMappingIssue.java +++ /dev/null @@ -1,102 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.schema; - -/** - * One problem found while inspecting schema-to-resolver mapping. - * - *

Each issue names the schema coordinate and, where known, the resource that declared it — and - * nothing else. A mapping report runs at startup and lands in logs, so it must never carry request - * or credential content. - * - * @param kind what went wrong - * @param coordinate schema coordinate the issue is anchored to - * @param owningResource resource that declared the coordinate, or {@code "unknown"} - */ -public record GraphQlMappingIssue( - GraphQlMappingIssueKind kind, String coordinate, String owningResource) { - - /** Categories of schema/resolver mismatch the inspection can find. */ - public enum GraphQlMappingIssueKind { - /** A schema field has neither a DataFetcher nor a matching Java property. */ - UNMAPPED_FIELD(true), - /** A DataFetcher is registered for a field the schema does not declare. */ - UNKNOWN_RESOLVER(true), - /** A resolver argument does not match the schema argument. */ - ARGUMENT_MISMATCH(true), - /** A resolver's nullness does not match the schema's nullability. */ - NULLABILITY_MISMATCH(true), - /** A scalar the platform forbids appears in the schema. */ - FORBIDDEN_SCALAR(true), - /** A field is reachable but was reported for review rather than rejection. */ - ADVISORY(false); - - private final boolean blocking; - - GraphQlMappingIssueKind(boolean blocking) { - this.blocking = blocking; - } - - /** Whether this kind fails a Stable startup. */ - public boolean blocking() { - return blocking; - } - } - - private static final String UNKNOWN_RESOURCE = "unknown"; - - public GraphQlMappingIssue { - if (kind == null) { - throw new IllegalArgumentException("mapping issue kind is required"); - } - if (coordinate == null || coordinate.isBlank()) { - throw new IllegalArgumentException("mapping issue coordinate is required"); - } - owningResource = - owningResource == null || owningResource.isBlank() ? UNKNOWN_RESOURCE : owningResource; - } - - /** A schema field with no resolver and no matching property. */ - public static GraphQlMappingIssue unmapped(String coordinate) { - return new GraphQlMappingIssue( - GraphQlMappingIssueKind.UNMAPPED_FIELD, coordinate, UNKNOWN_RESOURCE); - } - - /** A resolver registered against a field the schema does not declare. */ - public static GraphQlMappingIssue unknownResolver(String coordinate) { - return new GraphQlMappingIssue( - GraphQlMappingIssueKind.UNKNOWN_RESOLVER, coordinate, UNKNOWN_RESOURCE); - } - - /** A resolver argument that does not match the schema argument. */ - public static GraphQlMappingIssue argumentMismatch(String coordinate) { - return new GraphQlMappingIssue( - GraphQlMappingIssueKind.ARGUMENT_MISMATCH, coordinate, UNKNOWN_RESOURCE); - } - - /** A resolver nullness that does not match the schema nullability. */ - public static GraphQlMappingIssue nullabilityMismatch(String coordinate) { - return new GraphQlMappingIssue( - GraphQlMappingIssueKind.NULLABILITY_MISMATCH, coordinate, UNKNOWN_RESOURCE); - } - - /** A scalar the platform does not permit in the external contract. */ - public static GraphQlMappingIssue forbiddenScalar(String scalarName) { - return new GraphQlMappingIssue( - GraphQlMappingIssueKind.FORBIDDEN_SCALAR, "scalar " + scalarName, UNKNOWN_RESOURCE); - } - - /** Returns a copy attributed to the resource that declared the coordinate. */ - public GraphQlMappingIssue ownedBy(GraphQlSchemaOwnership ownership) { - return new GraphQlMappingIssue( - kind, coordinate, ownership.logicalModule() + ":" + ownership.logicalPath()); - } - - /** Whether this issue fails a Stable startup. */ - public boolean blocking() { - return kind.blocking(); - } - - /** Stable, content-free description for logs and the actuator report. */ - public String describe() { - return kind.name() + " " + coordinate + " (" + owningResource + ")"; - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlMappingPolicy.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlMappingPolicy.java deleted file mode 100644 index 60f76512..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlMappingPolicy.java +++ /dev/null @@ -1,30 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.schema; - -/** - * What a mapping inspection does with the issues it finds (design §23, {@code - * backend.graphql.schema.mapping-inspection}). - * - *

Spring's schema mapping inspection can report as information; the Stable profile promotes that - * report to a startup failure. A silently unmapped field returns {@code null} at runtime instead of - * failing at boot, which is exactly the class of defect the gate exists to prevent. - */ -public enum GraphQlMappingPolicy { - - /** Stable profile: any blocking issue fails startup. */ - FAIL, - - /** - * Local profile: blocking issues are reported rather than fatal — except a forbidden scalar or an - * unknown resolver, which are always fatal because neither can be made to work at runtime. - */ - WARN; - - /** Whether an issue of this kind must fail startup under this policy. */ - public boolean fatal(GraphQlMappingIssue issue) { - if (this == FAIL) { - return issue.blocking(); - } - return issue.kind() == GraphQlMappingIssue.GraphQlMappingIssueKind.FORBIDDEN_SCALAR - || issue.kind() == GraphQlMappingIssue.GraphQlMappingIssueKind.UNKNOWN_RESOLVER; - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlOneOfInputValidator.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlOneOfInputValidator.java deleted file mode 100644 index abc186cf..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlOneOfInputValidator.java +++ /dev/null @@ -1,55 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.schema; - -import java.util.List; -import java.util.Map; -import java.util.Objects; - -/** - * Validates a {@code @oneOf} input value before any resolver runs. - * - *

Both failure modes are rejected: zero supplied members would leave the resolver guessing, and - * two supplied members would let the resolver's field-checking order decide which selector wins — a - * difference that shows up as inconsistent behaviour between two mutations rather than as an error. - * - *

Diagnostics name the supplied members, never their values. - */ -public final class GraphQlOneOfInputValidator { - - private GraphQlOneOfInputValidator() {} - - /** - * Validates that exactly one member carries a non-null value. - * - * @throws GraphQlOneOfViolationException when zero or several members are supplied - */ - public static void validate(Map values) { - if (values == null) { - throw new GraphQlOneOfViolationException("exactly one value required, none supplied"); - } - List present = - values.entrySet().stream() - .filter(entry -> Objects.nonNull(entry.getValue())) - .map(Map.Entry::getKey) - .sorted() - .toList(); - if (!GraphQlOneOfPolicy.satisfied(present.size())) { - throw new GraphQlOneOfViolationException( - GraphQlOneOfPolicy.violationMessage(present.size()), present); - } - } - - /** - * Validates and returns the single supplied member name. - * - * @throws GraphQlOneOfViolationException when zero or several members are supplied - */ - public static String selected(Map values) { - validate(values); - return values.entrySet().stream() - .filter(entry -> Objects.nonNull(entry.getValue())) - .map(Map.Entry::getKey) - .findFirst() - .orElseThrow( - () -> new GraphQlOneOfViolationException("exactly one value required, none supplied")); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlOneOfPolicy.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlOneOfPolicy.java deleted file mode 100644 index 228405fe..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlOneOfPolicy.java +++ /dev/null @@ -1,35 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.schema; - -/** - * The September 2025 {@code @oneOf} input rules the platform enforces (design §7.5). - * - *

{@code @oneOf} lets a schema express "exactly one of these selectors" instead of leaving it to - * a hand-written validator that each resolver has to remember. The rules are stated here once so - * the schema gate and the runtime validator cannot disagree about what the directive means. - */ -public final class GraphQlOneOfPolicy { - - /** Directive that marks an input object as one-of. */ - public static final String DIRECTIVE_NAME = "oneOf"; - - /** Exactly this many members must be supplied with a non-null value. */ - public static final int REQUIRED_PRESENT_MEMBERS = 1; - - private GraphQlOneOfPolicy() {} - - /** - * Whether the supplied member count satisfies the directive. - * - * @param presentMembers number of members supplied with a non-null value - */ - public static boolean satisfied(long presentMembers) { - return presentMembers == REQUIRED_PRESENT_MEMBERS; - } - - /** Why a member count was rejected, without naming any value. */ - public static String violationMessage(long presentMembers) { - return presentMembers == 0 - ? "exactly one value required, none supplied" - : "exactly one value required, " + presentMembers + " supplied"; - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlOneOfSchemaGate.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlOneOfSchemaGate.java deleted file mode 100644 index 73de6cca..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlOneOfSchemaGate.java +++ /dev/null @@ -1,77 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.schema; - -import graphql.language.InputObjectTypeDefinition; -import graphql.language.InputValueDefinition; -import graphql.language.NonNullType; -import graphql.schema.idl.SchemaParser; -import graphql.schema.idl.TypeDefinitionRegistry; -import java.util.ArrayList; -import java.util.List; -import java.util.TreeSet; - -/** - * Startup gate for {@code @oneOf} input object declarations. - * - *

The specification requires every member of a one-of input to be nullable and to declare no - * default value. Both rules exist because "exactly one is supplied" would otherwise be undecidable: - * a non-null member is always supplied, and a member with a default is always present after - * coercion. A schema that breaks either rule cannot be validated at runtime, so it is rejected at - * build time instead. - */ -public final class GraphQlOneOfSchemaGate { - - private GraphQlOneOfSchemaGate() {} - - /** - * Verifies every {@code @oneOf} input object in an SDL document. - * - * @throws GraphQlOneOfViolationException when a member is non-null or declares a default value - */ - public static void verify(String sdl) { - verify(new SchemaParser().parse(sdl)); - } - - /** - * Verifies every {@code @oneOf} input object in a parsed schema. - * - * @throws GraphQlOneOfViolationException when a member is non-null or declares a default value - */ - public static void verify(TypeDefinitionRegistry registry) { - List problems = new ArrayList<>(); - - for (String typeName : - new TreeSet<>(registry.getTypesMap(InputObjectTypeDefinition.class).keySet())) { - InputObjectTypeDefinition definition = - registry.getTypesMap(InputObjectTypeDefinition.class).get(typeName); - if (!definition.hasDirective(GraphQlOneOfPolicy.DIRECTIVE_NAME)) { - continue; - } - for (InputValueDefinition member : definition.getInputValueDefinitions()) { - String coordinate = typeName + "." + member.getName(); - if (member.getType() instanceof NonNullType) { - problems.add(coordinate + " must be nullable in a @oneOf input"); - } - if (member.getDefaultValue() != null) { - problems.add(coordinate + " must not declare a default value in a @oneOf input"); - } - } - } - - if (!problems.isEmpty()) { - throw new GraphQlOneOfViolationException("invalid @oneOf input declaration", problems); - } - } - - /** Names of the {@code @oneOf} input objects in a parsed schema, in deterministic order. */ - public static List oneOfInputTypes(TypeDefinitionRegistry registry) { - return new TreeSet<>(registry.getTypesMap(InputObjectTypeDefinition.class).keySet()) - .stream() - .filter( - typeName -> - registry - .getTypesMap(InputObjectTypeDefinition.class) - .get(typeName) - .hasDirective(GraphQlOneOfPolicy.DIRECTIVE_NAME)) - .toList(); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlOneOfViolationException.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlOneOfViolationException.java deleted file mode 100644 index 3bf90c36..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlOneOfViolationException.java +++ /dev/null @@ -1,41 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.schema; - -import java.util.List; - -/** - * Raised when a {@code @oneOf} input object does not carry exactly one non-null member. - * - *

Carries the member names that were supplied, never their values: a rejected selector - * can hold an account number or an external reference, and this message is client-visible. - */ -public class GraphQlOneOfViolationException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - private final transient List suppliedFields; - - /** - * Creates the failure. - * - * @param message content-free description - */ - public GraphQlOneOfViolationException(String message) { - this(message, List.of()); - } - - /** - * Creates the failure naming the supplied member fields. - * - * @param message content-free description - * @param suppliedFields names of the members that were supplied - */ - public GraphQlOneOfViolationException(String message, List suppliedFields) { - super(message + (suppliedFields.isEmpty() ? "" : ": " + suppliedFields)); - this.suppliedFields = List.copyOf(suppliedFields); - } - - /** Names of the supplied members. */ - public List suppliedFields() { - return suppliedFields; - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlSchemaAssembler.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlSchemaAssembler.java deleted file mode 100644 index 1869a247..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlSchemaAssembler.java +++ /dev/null @@ -1,39 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.schema; - -import java.util.Comparator; -import java.util.List; - -/** - * Assembles module-owned SDL fragments into one schema, deterministically. - * - *

Fragments are sorted by owning module and path before parsing. Filesystem and classpath - * enumeration order is not stable across machines or packaging formats, and an unstable order would - * both move the schema hash and change which of two conflicting declarations "wins" — so the order - * is imposed here rather than inherited from discovery. - */ -public final class GraphQlSchemaAssembler { - - private static final Comparator DETERMINISTIC_ORDER = - Comparator.comparing(GraphQlSchemaResource::orderingKey); - - private GraphQlSchemaAssembler() {} - - /** The Stable assembler. */ - public static GraphQlSchemaAssembler defaults() { - return new GraphQlSchemaAssembler(); - } - - /** - * Orders, parses, attributes and merges the given fragments. - * - * @throws GraphQlSchemaAssemblyException when a fragment cannot be parsed or a declaration is - * duplicated - */ - public GraphQlSchemaAssemblyResult assemble(List resources) { - if (resources == null) { - throw new GraphQlSchemaAssemblyException("schema resources are required"); - } - List ordered = resources.stream().sorted(DETERMINISTIC_ORDER).toList(); - return GraphQlSchemaAssemblyResult.parseAndValidate(ordered); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlSchemaAssemblyException.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlSchemaAssemblyException.java deleted file mode 100644 index eb225625..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlSchemaAssemblyException.java +++ /dev/null @@ -1,52 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.schema; - -import java.util.List; - -/** - * Raised when SDL fragments cannot be assembled into one valid schema. - * - *

Carries the attributed problems — which coordinate, declared by which resource — so a - * duplicate type or a parse failure names the file that caused it instead of only the merged - * result. - */ -public class GraphQlSchemaAssemblyException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - private final transient List problems; - - /** - * Creates the failure with a single problem description. - * - * @param message attributed problem description - */ - public GraphQlSchemaAssemblyException(String message) { - this(List.of(message)); - } - - /** - * Creates the failure with every attributed problem found during assembly. - * - * @param problems attributed problem descriptions, at least one - */ - public GraphQlSchemaAssemblyException(List problems) { - super("GraphQL schema assembly failed: " + problems); - this.problems = List.copyOf(problems); - } - - /** - * Creates the failure from an underlying parser or schema problem. - * - * @param message attributed problem description - * @param cause the underlying failure - */ - public GraphQlSchemaAssemblyException(String message, Throwable cause) { - super("GraphQL schema assembly failed: " + message, cause); - this.problems = List.of(message); - } - - /** Attributed problems, in deterministic order. */ - public List problems() { - return problems; - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlSchemaAssemblyResult.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlSchemaAssemblyResult.java deleted file mode 100644 index fc09a237..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlSchemaAssemblyResult.java +++ /dev/null @@ -1,189 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.schema; - -import graphql.language.Document; -import graphql.language.EnumTypeDefinition; -import graphql.language.InputObjectTypeDefinition; -import graphql.language.InterfaceTypeDefinition; -import graphql.language.ObjectTypeDefinition; -import graphql.language.TypeDefinition; -import graphql.language.UnionTypeDefinition; -import graphql.parser.Parser; -import graphql.schema.idl.ScalarInfo; -import graphql.schema.idl.SchemaParser; -import graphql.schema.idl.TypeDefinitionRegistry; -import graphql.schema.idl.errors.SchemaProblem; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -/** - * The outcome of assembling every SDL fragment into one schema. - * - *

Assembly is deliberately stricter than "the merge did not throw". A duplicate type, field, - * directive or scalar declaration is rejected with the resource that declared it, because the - * merged result would otherwise pick a winner silently and the external contract would depend on - * classpath order. The canonical SDL is produced by printing the parsed AST of the ordered - * fragments, so formatting and comment changes never move the schema hash. - */ -public final class GraphQlSchemaAssemblyResult { - - private final TypeDefinitionRegistry registry; - private final List ownership; - private final String canonicalSdl; - - private GraphQlSchemaAssemblyResult( - TypeDefinitionRegistry registry, - List ownership, - String canonicalSdl) { - this.registry = registry; - this.ownership = List.copyOf(ownership); - this.canonicalSdl = canonicalSdl; - } - - /** - * Parses, attributes and merges already-ordered fragments. - * - * @throws GraphQlSchemaAssemblyException when a fragment fails to parse or a declaration is - * duplicated across fragments - */ - public static GraphQlSchemaAssemblyResult parseAndValidate(List ordered) { - if (ordered == null || ordered.isEmpty()) { - throw new GraphQlSchemaAssemblyException("no GraphQL schema resources were discovered"); - } - - List problems = new ArrayList<>(); - Map declarations = new LinkedHashMap<>(); - List ownership = new ArrayList<>(); - StringBuilder canonical = new StringBuilder(); - TypeDefinitionRegistry merged = new TypeDefinitionRegistry(); - - for (GraphQlSchemaResource resource : ordered) { - TypeDefinitionRegistry fragment = parseFragment(resource); - recordDeclarations(resource, fragment, declarations, ownership, problems); - canonical.append(printCanonical(resource)).append('\n'); - try { - merged.merge(fragment); - } catch (SchemaProblem ex) { - problems.add("merge failed for " + resource.logicalPath() + ": " + ex.getErrors()); - } - } - - if (!problems.isEmpty()) { - throw new GraphQlSchemaAssemblyException(List.copyOf(problems)); - } - return new GraphQlSchemaAssemblyResult(merged, ownership, canonical.toString()); - } - - /** The merged type definition registry, ready for runtime wiring. */ - public TypeDefinitionRegistry registry() { - return registry; - } - - /** Which resource declared each coordinate, in assembly order. */ - public List ownership() { - return ownership; - } - - /** Canonical SDL text: the parsed AST of every ordered fragment, printed deterministically. */ - public String canonicalSdl() { - return canonicalSdl; - } - - /** SHA-256 of {@link #canonicalSdl()}. */ - public GraphQlSchemaHash schemaHash() { - return GraphQlSchemaHash.sha256(canonicalSdl); - } - - private static TypeDefinitionRegistry parseFragment(GraphQlSchemaResource resource) { - try { - return new SchemaParser().parse(resource.sdl()); - } catch (SchemaProblem | graphql.parser.InvalidSyntaxException ex) { - throw new GraphQlSchemaAssemblyException( - "cannot parse " + resource.logicalModule() + ":" + resource.logicalPath(), ex); - } - } - - private static String printCanonical(GraphQlSchemaResource resource) { - Document document = Parser.parse(resource.sdl()); - return graphql.language.AstPrinter.printAst(document); - } - - private static void recordDeclarations( - GraphQlSchemaResource resource, - TypeDefinitionRegistry fragment, - Map declarations, - List ownership, - List problems) { - - fragment - .types() - .forEach( - (name, definition) -> { - claim(name, resource, declarations, ownership, problems); - fieldCoordinates(name, definition) - .forEach( - coordinate -> claim(coordinate, resource, declarations, ownership, problems)); - }); - fragment.scalars().keySet().stream() - // Every parsed fragment reports the specification scalars, so only custom scalars can - // meaningfully be declared twice. - .filter(name -> !ScalarInfo.isGraphqlSpecifiedScalar(name)) - .forEach(name -> claim("scalar " + name, resource, declarations, ownership, problems)); - fragment - .getDirectiveDefinitions() - .keySet() - .forEach(name -> claim("@" + name, resource, declarations, ownership, problems)); - } - - private static List fieldCoordinates(String typeName, TypeDefinition definition) { - List coordinates = new ArrayList<>(); - if (definition instanceof ObjectTypeDefinition object) { - object - .getFieldDefinitions() - .forEach(field -> coordinates.add(typeName + "." + field.getName())); - } else if (definition instanceof InterfaceTypeDefinition iface) { - iface - .getFieldDefinitions() - .forEach(field -> coordinates.add(typeName + "." + field.getName())); - } else if (definition instanceof InputObjectTypeDefinition input) { - input - .getInputValueDefinitions() - .forEach(field -> coordinates.add(typeName + "." + field.getName())); - } else if (definition instanceof EnumTypeDefinition enumType) { - enumType - .getEnumValueDefinitions() - .forEach(value -> coordinates.add(typeName + "." + value.getName())); - } else if (definition instanceof UnionTypeDefinition union) { - union - .getMemberTypes() - .forEach( - member -> - coordinates.add(typeName + "." + graphql.language.AstPrinter.printAst(member))); - } - return coordinates; - } - - private static void claim( - String coordinate, - GraphQlSchemaResource resource, - Map declarations, - List ownership, - List problems) { - - GraphQlSchemaOwnership owner = - new GraphQlSchemaOwnership(coordinate, resource.logicalModule(), resource.logicalPath()); - GraphQlSchemaOwnership existing = declarations.putIfAbsent(coordinate, owner); - if (existing != null) { - problems.add( - "duplicate declaration of " - + coordinate - + ": " - + existing.describe() - + " and " - + owner.describe()); - return; - } - ownership.add(owner); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlSchemaContract.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlSchemaContract.java deleted file mode 100644 index 24907e27..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlSchemaContract.java +++ /dev/null @@ -1,46 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.schema; - -import java.util.Objects; - -/** - * The full identity of a deployed schema contract (design §8). - * - *

A schema hash alone is not enough to decide compatibility. Identical SDL bytes can still mean - * a different external contract if the breaking-change policy, a scalar's coercion or a directive's - * meaning moved underneath it — so all four parts are mandatory and {@link #matches} compares all - * four. {@link #sameSchemaBytes} is available for cache keying but is explicitly not a - * compatibility verdict. - * - * @param schemaHash SHA-256 of the canonical SDL - * @param breakingPolicyVersion version of the breaking-change rules in force - * @param scalarManifestVersion version of the approved scalar set and their coercions - * @param directiveManifestVersion version of the approved directive set and their meanings - */ -public record GraphQlSchemaContract( - GraphQlSchemaHash schemaHash, - GraphQlContractVersion breakingPolicyVersion, - GraphQlContractVersion scalarManifestVersion, - GraphQlContractVersion directiveManifestVersion) { - - public GraphQlSchemaContract { - Objects.requireNonNull(schemaHash, "schemaHash is required"); - Objects.requireNonNull(breakingPolicyVersion, "breakingPolicyVersion is required"); - Objects.requireNonNull(scalarManifestVersion, "scalarManifestVersion is required"); - Objects.requireNonNull(directiveManifestVersion, "directiveManifestVersion is required"); - } - - /** Whether the whole contract — SDL and every governing policy version — is identical. */ - public boolean matches(GraphQlSchemaContract other) { - return other != null && equals(other); - } - - /** - * Whether only the canonical SDL bytes are identical. - * - *

Enough to key a parse cache; never enough to conclude a client-visible contract is - * unchanged. - */ - public boolean sameSchemaBytes(GraphQlSchemaContract other) { - return other != null && schemaHash.equals(other.schemaHash); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlSchemaHash.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlSchemaHash.java deleted file mode 100644 index 6b71fd3e..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlSchemaHash.java +++ /dev/null @@ -1,46 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.schema; - -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.HexFormat; -import java.util.regex.Pattern; - -/** - * SHA-256 of the canonical SDL bytes, as lowercase hexadecimal. - * - *

Used to key the preparsed document cache, to bind a persisted operation to the schema it was - * approved against, and to report the deployed schema through the actuator. Formatting is fixed to - * lowercase hex so the same schema never produces two different keys. - * - * @param value 64-character lowercase hexadecimal digest - */ -public record GraphQlSchemaHash(String value) { - - private static final Pattern PATTERN = Pattern.compile("[0-9a-f]{64}"); - - public GraphQlSchemaHash { - if (value == null || !PATTERN.matcher(value).matches()) { - throw new IllegalArgumentException("schema hash must be lowercase SHA-256 hexadecimal"); - } - } - - /** - * Hashes canonical SDL text. - * - * @param canonicalSdl assembled SDL in its canonical, deterministic form - */ - public static GraphQlSchemaHash sha256(String canonicalSdl) { - if (canonicalSdl == null) { - throw new IllegalArgumentException("canonical SDL is required"); - } - try { - byte[] digest = - MessageDigest.getInstance("SHA-256") - .digest(canonicalSdl.getBytes(StandardCharsets.UTF_8)); - return new GraphQlSchemaHash(HexFormat.of().formatHex(digest)); - } catch (NoSuchAlgorithmException ex) { - throw new IllegalStateException("SHA-256 is required for the schema contract", ex); - } - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlSchemaMappingException.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlSchemaMappingException.java deleted file mode 100644 index a808ab5f..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlSchemaMappingException.java +++ /dev/null @@ -1,34 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.schema; - -import java.util.List; - -/** - * Raised when schema-to-resolver mapping inspection finds an issue the active policy treats as - * fatal. - * - *

Thrown during startup so an unmapped field, an unknown resolver or a forbidden scalar stops - * the deployment instead of degrading to silent nulls at request time. - */ -public class GraphQlSchemaMappingException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - private final transient List issues; - - /** - * Creates the failure. - * - * @param issues the fatal issues, attributed to their schema coordinates - */ - public GraphQlSchemaMappingException(List issues) { - super( - "GraphQL schema mapping inspection failed: " - + issues.stream().map(GraphQlMappingIssue::describe).toList()); - this.issues = List.copyOf(issues); - } - - /** The fatal issues. */ - public List issues() { - return issues; - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlSchemaOwnership.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlSchemaOwnership.java deleted file mode 100644 index 3062ccea..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlSchemaOwnership.java +++ /dev/null @@ -1,29 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.schema; - -/** - * Which resource declared a given schema coordinate. - * - *

The assembled schema is a merge of many modules' fragments, so every diagnostic downstream — a - * duplicate declaration, an unmapped field, a breaking change — needs to point back at the file - * that owns the coordinate rather than at the merged whole. - * - * @param coordinate type name, or {@code TypeName.fieldName} - * @param logicalModule module that declared it - * @param logicalPath resource path that declared it - */ -public record GraphQlSchemaOwnership(String coordinate, String logicalModule, String logicalPath) { - - public GraphQlSchemaOwnership { - if (coordinate == null || coordinate.isBlank()) { - throw new IllegalArgumentException("owned coordinate is required"); - } - if (logicalModule == null || logicalPath == null) { - throw new IllegalArgumentException("owning module and path are required"); - } - } - - /** Human-readable attribution, free of request or credential content. */ - public String describe() { - return coordinate + " (" + logicalModule + ":" + logicalPath + ")"; - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlSchemaResource.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlSchemaResource.java deleted file mode 100644 index 4960c6cf..00000000 Binary files a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlSchemaResource.java and /dev/null differ diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/security/GraphQlClientProfileResolver.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/security/GraphQlClientProfileResolver.java deleted file mode 100644 index d8057441..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/security/GraphQlClientProfileResolver.java +++ /dev/null @@ -1,57 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.security; - -import dev.caskeleton.adapter.inbound.graphql.api.GraphQlClientProfile; -import java.util.Map; -import java.util.Set; - -/** - * Resolves the client profile from trusted credential metadata. - * - *

Never from a variable, an extension or a header the caller controls: the profile selects the - * cost, page-size and introspection limits, so a caller that could name its own profile could grant - * itself the admin budget. - */ -public final class GraphQlClientProfileResolver { - - private final Map profilesByCredentialClaim; - private final GraphQlClientProfile anonymousProfile; - - /** - * Creates a resolver. - * - * @param profilesByCredentialClaim mapping from a verified credential claim value to a profile - * @param anonymousProfile profile used for callers with no credential - */ - public GraphQlClientProfileResolver( - Map profilesByCredentialClaim, - GraphQlClientProfile anonymousProfile) { - if (anonymousProfile == null) { - throw new IllegalArgumentException("anonymous client profile is required"); - } - this.profilesByCredentialClaim = Map.copyOf(profilesByCredentialClaim); - this.anonymousProfile = anonymousProfile; - } - - /** - * Resolves the profile for a verified claim value. - * - * @param verifiedClaimValue claim value taken from the verified credential, or {@code null} - * @throws GraphQlAuthenticationException when the claim names no registered profile - */ - public GraphQlClientProfile resolve(String verifiedClaimValue) { - if (verifiedClaimValue == null) { - return anonymousProfile; - } - GraphQlClientProfile profile = profilesByCredentialClaim.get(verifiedClaimValue); - if (profile == null) { - throw new GraphQlAuthenticationException( - "credential names no registered GraphQL client profile"); - } - return profile; - } - - /** Registered claim values, for startup reporting. */ - public Set registeredClaims() { - return profilesByCredentialClaim.keySet(); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/security/GraphQlContextCleanup.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/security/GraphQlContextCleanup.java deleted file mode 100644 index 3ed876be..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/security/GraphQlContextCleanup.java +++ /dev/null @@ -1,62 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.security; - -import java.util.ArrayDeque; -import java.util.Deque; - -/** - * Clears request-scoped state when execution finishes. - * - *

On a pooled or virtual-thread executor, state left behind is not merely stale — the next - * request on that thread inherits another caller's actor and tenant. Cleanup therefore runs on - * every path, and each registered action runs even if an earlier one throws. - */ -public final class GraphQlContextCleanup { - - private final Deque actions = new ArrayDeque<>(); - - /** Creates an empty cleanup scope. */ - public static GraphQlContextCleanup create() { - return new GraphQlContextCleanup(); - } - - /** Registers an action to run when the request finishes. */ - public GraphQlContextCleanup register(Runnable action) { - if (action == null) { - throw new IllegalArgumentException("cleanup action is required"); - } - actions.push(action); - return this; - } - - /** - * Runs every registered action, in reverse registration order. - * - *

A failing action never prevents the others from running. The first failure is rethrown once - * everything has been attempted, with every later failure attached to it as suppressed — losing - * them would mean a second broken cleanup is invisible until the first one is fixed, which is - * exactly when nobody is looking for it. - */ - public void close() { - RuntimeException firstFailure = null; - while (!actions.isEmpty()) { - Runnable action = actions.pop(); - try { - action.run(); - } catch (RuntimeException failure) { - if (firstFailure == null) { - firstFailure = failure; - } else { - firstFailure.addSuppressed(failure); - } - } - } - if (firstFailure != null) { - throw firstFailure; - } - } - - /** How many actions are still pending. */ - public int pending() { - return actions.size(); - } -} diff --git a/src/adapter/inbound/graphql/src/main/resources/META-INF/spring.factories b/src/adapter/inbound/graphql/src/main/resources/META-INF/spring.factories index bc2a2210..bacb2583 100644 --- a/src/adapter/inbound/graphql/src/main/resources/META-INF/spring.factories +++ b/src/adapter/inbound/graphql/src/main/resources/META-INF/spring.factories @@ -1,4 +1,2 @@ -org.springframework.boot.autoconfigure.AutoConfigurationImportFilter=\ -dev.caskeleton.adapter.inbound.graphql.autoconfigure.GraphQlOffAutoConfigurationImportFilter org.springframework.boot.EnvironmentPostProcessor=\ dev.caskeleton.adapter.inbound.graphql.autoconfigure.GraphQlActivationEnvironmentPostProcessor diff --git a/src/app-bootstrap/src/main/resources/config/graphql.yml b/src/adapter/inbound/graphql/src/main/resources/config/graphql.yml similarity index 56% rename from src/app-bootstrap/src/main/resources/config/graphql.yml rename to src/adapter/inbound/graphql/src/main/resources/config/graphql.yml index 5044fb80..38b2e160 100644 --- a/src/app-bootstrap/src/main/resources/config/graphql.yml +++ b/src/adapter/inbound/graphql/src/main/resources/config/graphql.yml @@ -1,14 +1,15 @@ -# GraphQL 트랜스포트 스위치. +# GraphQL capability 설정 기본값. # -# application.yml 이 spring.config.import 로 취합한다. 이 파일의 값은 application.yml 보다 -# 낮고 application-{profile}.yml 보다도 낮으므로, 배포별 오버라이드는 그대로 우선한다. +# 이 모듈이 직접 읽는다(GraphQlActivationEnvironmentPostProcessor). 우선순위는 가장 낮아서 +# application*.yml, 환경 변수, 시스템 속성이 항상 이긴다. 환경 변수는 APP_GRAPHQL_* 이고 설정 트리는 +# backend.graphql.* 라서, 이 파일이 둘을 잇는다. 이 모듈을 빌드에서 빼면 이 파일도 함께 빠진다. backend: graphql: - # true | false — publishes /graphql, including the route Spring GraphQL would publish itself. - enabled: ${APP_GRAPHQL_ENABLED:false} - # Required when the switch above is true, and must match the runtime environment - # (local->LOCAL, dev->DEV, prod->PRODUCTION_INTERNAL|PRODUCTION_PUBLIC). Replaces the - # production boolean and environment enum, which could disagree with each other. + # true | false — 모듈이 있으면 켜진다. false 로 끄면 Spring GraphQL 자신의 자동 설정도 빠져서 + # /graphql 이 열리지 않는다. + enabled: ${APP_GRAPHQL_ENABLED:true} + # 켠 상태에서 필수이고 runtime 환경과 맞아야 한다 + # (local->LOCAL, dev->DEV, prod->PRODUCTION_INTERNAL|PRODUCTION_PUBLIC). deployment-mode: ${APP_GRAPHQL_DEPLOYMENT_MODE:} execution-profile: ${APP_GRAPHQL_EXECUTION_PROFILE:BLOCKING_MVC} validation-policy-version: ${APP_GRAPHQL_VALIDATION_POLICY_VERSION:v1} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/GraphQlProductionClassesTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/GraphQlProductionClassesTest.java new file mode 100644 index 00000000..177c5bf9 --- /dev/null +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/GraphQlProductionClassesTest.java @@ -0,0 +1,35 @@ +package dev.caskeleton.adapter.inbound.graphql; + +import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses; + +import com.tngtech.archunit.core.domain.JavaClasses; +import com.tngtech.archunit.core.importer.ClassFileImporter; +import com.tngtech.archunit.core.importer.ImportOption; +import org.junit.jupiter.api.Test; + +/** + * Contract suites, fixtures and in-memory stand-ins live in test fixtures, not in the jar a service + * runs: an in-memory registry is a working bean until the second instance starts, and a + * credential-free test context mints an authenticated actor. + */ +class GraphQlProductionClassesTest { + + @Test + void productionClassesCarryNoTestOnlyTypes() { + // given + JavaClasses production = + new ClassFileImporter() + .withImportOption(new ImportOption.DoNotIncludeTests()) + .withImportOption( + location -> + !location.contains("testFixtures") && !location.contains("test-fixtures")) + .importPackages("dev.caskeleton.adapter.inbound.graphql"); + + // when & then + noClasses() + .should() + .haveNameMatching(".*(\\.testkit\\.|InMemory|ForTests|TestContext|Fixture).*") + .because("test-only types belong to src/testFixtures/java") + .check(production); + } +} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/GraphQlTransportBoundaryArchitectureTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/GraphQlTransportBoundaryArchitectureTest.java new file mode 100644 index 00000000..296748ae --- /dev/null +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/GraphQlTransportBoundaryArchitectureTest.java @@ -0,0 +1,221 @@ +package dev.caskeleton.adapter.inbound.graphql; + +import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes; +import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.methods; +import static org.assertj.core.api.Assertions.assertThat; + +import com.tngtech.archunit.core.domain.JavaClass; +import com.tngtech.archunit.core.domain.JavaClasses; +import com.tngtech.archunit.core.domain.JavaMethod; +import com.tngtech.archunit.core.domain.JavaModifier; +import com.tngtech.archunit.core.domain.JavaType; +import com.tngtech.archunit.core.importer.ClassFileImporter; +import com.tngtech.archunit.core.importer.ImportOption; +import com.tngtech.archunit.lang.ArchCondition; +import com.tngtech.archunit.lang.ArchRule; +import com.tngtech.archunit.lang.ConditionEvents; +import com.tngtech.archunit.lang.SimpleConditionEvent; +import graphql.schema.DataFetcher; +import graphql.schema.DataFetchingEnvironment; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.graphql.data.method.annotation.BatchMapping; +import org.springframework.graphql.data.method.annotation.QueryMapping; +import org.springframework.graphql.data.method.annotation.SchemaMapping; +import org.springframework.stereotype.Controller; + +/** + * The two GraphQL transport rules that used to run at every boot, checked at build time instead. + * + *

{@code GraphQlPlatformAutoConfiguration} reflected over every {@code @Controller} on startup. + * The persistence-access half of that check is covered by the whole-repository inbound adapter + * rules; these two were covered by nothing else. + */ +class GraphQlTransportBoundaryArchitectureTest { + + private static final String GRAPHQL = "dev.caskeleton.adapter.inbound.graphql.."; + + private static final List NON_TRANSPORT_PACKAGES = + List.of( + "dev.caskeleton.domain.", + "dev.caskeleton.adapter.outbound.", + "jakarta.persistence.", + "javax.persistence.", + "org.hibernate.", + "org.springframework.data.", + "org.springframework.jdbc.", + "com.mongodb.", + "org.bson.", + "java.sql.", + "javax.sql.", + "software.amazon.awssdk.", + "com.amazonaws.", + "io.grpc.", + "org.apache.kafka."); + + private static final Set PERSISTENCE_ANNOTATIONS = + Set.of("Entity", "Embeddable", "MappedSuperclass", "Document", "Table"); + + /** Rule 1: a resolver signature carries transport types only, generic arguments included. */ + static final ArchRule RESOLVERS_USE_ONLY_TRANSPORT_TYPES = + methods() + .that() + .areMetaAnnotatedWith(SchemaMapping.class) + .or() + .areMetaAnnotatedWith(BatchMapping.class) + .and() + .areDeclaredInClassesThat() + .resideInAPackage(GRAPHQL) + .should(useOnlyTransportTypes()) + .because( + "a resolver that returns or binds an entity, a domain object or a raw Map couples the" + + " GraphQL contract to the model behind it"); + + /** Rule 2: a hand-written DataFetcher bypasses argument binding, so only wiring code has one. */ + static final ArchRule RAW_DATA_FETCHERS_STAY_IN_INFRASTRUCTURE = + classes() + .that() + .resideInAPackage(GRAPHQL) + .and() + .implement(DataFetcher.class) + .and() + .doNotHaveModifier(JavaModifier.ABSTRACT) + .should() + .resideInAnyPackage("..graphql.scalar..", "..graphql.schema..", "..graphql.execution..") + .because("annotated controllers are the API; raw fetchers are for scalar/schema wiring") + // No raw fetcher exists today, and that is the state this rule protects. + .allowEmptyShould(true); + + private static JavaClasses graphql; + + @BeforeAll + static void importGraphQlProductionCode() { + graphql = + new ClassFileImporter() + .withImportOption(ImportOption.Predefined.DO_NOT_INCLUDE_TESTS) + .importPackages("dev.caskeleton.adapter.inbound.graphql"); + assertThat(graphql).isNotEmpty(); + } + + @Test + void resolversUseOnlyTransportTypes() { + RESOLVERS_USE_ONLY_TRANSPORT_TYPES.check(graphql); + } + + @Test + void rawDataFetchersStayInInfrastructurePackages() { + RAW_DATA_FETCHERS_STAY_IN_INFRASTRUCTURE.check(graphql); + } + + @Test + void theTransportRuleRejectsMapsEntitiesAndDriverTypesInsideGenerics() { + // given + JavaClasses fixture = + new ClassFileImporter().importClasses(LeakingResolver.class, OrderEntity.class); + + // when + List violations = + RESOLVERS_USE_ONLY_TRANSPORT_TYPES.evaluate(fixture).getFailureReport().getDetails(); + + // then + assertThat(violations) + .hasSize(3) + .anyMatch(detail -> detail.contains("order()") && detail.contains(Map.class.getName())) + .anyMatch(detail -> detail.contains("orders()") && detail.contains("OrderEntity")) + .anyMatch( + detail -> detail.contains("since(") && detail.contains(Timestamp.class.getName())); + } + + @Test + void theDataFetcherRuleRejectsARawFetcherOutsideInfrastructure() { + // given + JavaClasses fixture = new ClassFileImporter().importClasses(RawFetcher.class); + + // when + List violations = + RAW_DATA_FETCHERS_STAY_IN_INFRASTRUCTURE.evaluate(fixture).getFailureReport().getDetails(); + + // then + assertThat(violations).singleElement().asString().contains(RawFetcher.class.getName()); + } + + private static ArchCondition useOnlyTransportTypes() { + return new ArchCondition<>("use only transport types in their signature") { + @Override + public void check(JavaMethod method, ConditionEvents events) { + List signature = new ArrayList<>(method.getParameterTypes()); + signature.add(method.getReturnType()); + for (JavaType type : signature) { + for (JavaClass raw : type.getAllInvolvedRawTypes()) { + String reason = nonTransportReason(raw); + if (reason != null) { + events.add( + SimpleConditionEvent.violated( + method, method.getFullName() + " uses " + raw.getName() + ": " + reason)); + } + } + } + } + }; + } + + private static String nonTransportReason(JavaClass type) { + if (type.isAssignableTo(Map.class)) { + return "an unrestricted Map bypasses the typed GraphQL contract"; + } + boolean persistenceMapped = + type.getAnnotations().stream() + .anyMatch(a -> PERSISTENCE_ANNOTATIONS.contains(a.getRawType().getSimpleName())); + if (persistenceMapped) { + return "a persistence-mapped type is not a GraphQL wire type"; + } + return NON_TRANSPORT_PACKAGES.stream() + .filter(type.getName()::startsWith) + .findFirst() + .map(prefix -> "types under " + prefix + " are not GraphQL wire types") + .orElse(null); + } + + /** Stands in for JPA's or Spring Data's mapping annotation, matched by simple name. */ + @Retention(RetentionPolicy.RUNTIME) + @interface Entity {} + + @Entity + static final class OrderEntity {} + + /** Breaks rule 1 three ways: a raw Map, an entity inside a List, a driver type as argument. */ + @Controller + static final class LeakingResolver { + + @QueryMapping + Map order() { + return Map.of(); + } + + @QueryMapping + List orders() { + return List.of(); + } + + @SchemaMapping + String since(Timestamp createdAt) { + return createdAt.toString(); + } + } + + /** Breaks rule 2: a hand-written fetcher in a non-infrastructure package. */ + static final class RawFetcher implements DataFetcher { + + @Override + public String get(DataFetchingEnvironment environment) { + return "raw"; + } + } +} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/TransportHandlerFactoryTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/TransportHandlerFactoryTest.java deleted file mode 100644 index c93f6b4d..00000000 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/TransportHandlerFactoryTest.java +++ /dev/null @@ -1,105 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedCapability; -import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedCapabilityDisabledException; -import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedFeatureFlags; -import dev.caskeleton.adapter.inbound.graphql.advanced.rsocket.GraphQlRSocketHandlerFactory; -import dev.caskeleton.adapter.inbound.graphql.advanced.rsocket.GraphQlRSocketProperties; -import dev.caskeleton.adapter.inbound.graphql.advanced.rsocket.GraphQlRSocketRoutePolicy; -import dev.caskeleton.adapter.inbound.graphql.advanced.sse.GraphQlSseConnectionPolicy; -import dev.caskeleton.adapter.inbound.graphql.advanced.sse.GraphQlSseHandlerFactory; -import dev.caskeleton.adapter.inbound.graphql.advanced.sse.GraphQlSseProperties; -import java.util.Set; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * Whether each transport model may exist at all, and what it is installed with. - * - *

WebSocket transport is deliberately absent: graphql-transport-ws connection state and close - * semantics are owned by the websocket leaf. This leaf keeps only the SSE and RSocket models that - * do not duplicate another inbound adapter. - */ -class TransportHandlerFactoryTest { - - private static GraphQlSseHandlerFactory sse(GraphQlAdvancedFeatureFlags flags) { - return new GraphQlSseHandlerFactory( - flags, GraphQlSseProperties.defaults(), GraphQlSseConnectionPolicy.standard()); - } - - private static GraphQlRSocketHandlerFactory rsocket( - GraphQlAdvancedFeatureFlags flags, boolean transportEnabled) { - return new GraphQlRSocketHandlerFactory( - flags, - new GraphQlRSocketProperties( - transportEnabled, - Set.of("graphql"), - Set.of("message/x.rsocket.routing.v0"), - transportEnabled ? Set.of("internal-gateway") : Set.of()), - new GraphQlRSocketRoutePolicy(Set.of("graphql"))); - } - - @Test - @DisplayName("no modelled transport exists until its capability is named") - void noTransportExistsUntilNamed() { - GraphQlAdvancedFeatureFlags off = GraphQlAdvancedFeatureFlags.disabled(); - - assertThat(sse(off).enabled()).isFalse(); - assertThat(rsocket(off, false).enabled()).isFalse(); - } - - @Test - @DisplayName("asking a disabled transport for its settings is refused, not answered emptily") - void disabledTransportRefusesRatherThanAnswering() { - GraphQlAdvancedFeatureFlags off = GraphQlAdvancedFeatureFlags.disabled(); - - assertThatThrownBy(() -> sse(off).settings()) - .isInstanceOf(GraphQlAdvancedCapabilityDisabledException.class); - assertThatThrownBy(() -> rsocket(off, false).settings()) - .isInstanceOf(GraphQlAdvancedCapabilityDisabledException.class); - } - - @Test - @DisplayName("SSE says how many connections a client will hold before it is enabled") - void sseReportsItsConnectionCost() { - GraphQlSseHandlerFactory factory = - sse(GraphQlAdvancedFeatureFlags.enabling(GraphQlAdvancedCapability.SSE_SUBSCRIPTION)); - - assertThat(factory.connectionsRequiredFor(20)).isEqualTo(20); - assertThat(factory.settings().heartbeatInterval()).isLessThan(factory.settings().idleTimeout()); - } - - @Test - @DisplayName("RSocket needs the transport switch as well as the capability") - void rsocketNeedsBothGates() { - GraphQlAdvancedFeatureFlags named = - GraphQlAdvancedFeatureFlags.enabling(GraphQlAdvancedCapability.RSOCKET); - - assertThat(rsocket(named, false).enabled()).isFalse(); - assertThat(rsocket(named, true).enabled()).isTrue(); - } - - @Test - @DisplayName("an experimental transport with no named consumer is refused") - void unnamedConsumerIsRefused() { - assertThatThrownBy( - () -> - new GraphQlRSocketHandlerFactory.GraphQlRSocketHandlerSettings( - new GraphQlRSocketRoutePolicy(Set.of("graphql")), Set.of(), Set.of())) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("nobody will notice breaking"); - } - - @Test - @DisplayName("enabling SSE does not enable RSocket") - void capabilitiesAreIndependent() { - GraphQlAdvancedFeatureFlags onlySse = - GraphQlAdvancedFeatureFlags.enabling(GraphQlAdvancedCapability.SSE_SUBSCRIPTION); - - assertThat(sse(onlySse).enabled()).isTrue(); - assertThat(rsocket(onlySse, true).enabled()).isFalse(); - } -} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/admin/GraphQlPersistedOperationRemovalGateTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/admin/GraphQlPersistedOperationRemovalGateTest.java deleted file mode 100644 index 4a1c7c94..00000000 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/admin/GraphQlPersistedOperationRemovalGateTest.java +++ /dev/null @@ -1,224 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.admin; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.graphql.advanced.persisted.GraphQlPersistedOperation; -import dev.caskeleton.adapter.inbound.graphql.advanced.persisted.GraphQlPersistedOperationId; -import dev.caskeleton.adapter.inbound.graphql.advanced.persisted.GraphQlPersistedOperationNotFoundException; -import dev.caskeleton.adapter.inbound.graphql.advanced.persisted.GraphQlPersistedOperationStatus; -import dev.caskeleton.adapter.inbound.graphql.advanced.persisted.InMemoryGraphQlPersistedOperationRegistry; -import java.time.Clock; -import java.time.Duration; -import java.time.Instant; -import java.time.ZoneOffset; -import java.util.Set; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -/** G4 persisted operation admin, usage and block plane (Advanced plan Task 4). */ -@Tag("graphql-advanced") -class GraphQlPersistedOperationRemovalGateTest { - - private static final Instant NOW = Instant.parse("2026-08-12T00:00:00Z"); - private static final Clock CLOCK = Clock.fixed(NOW, ZoneOffset.UTC); - - @Test - void recentUsageBlocksRemoval() { - var gate = new GraphQlPersistedOperationRemovalGate(Duration.ofDays(30)); - var usage = new GraphQlPersistedOperationUsage(NOW.minus(Duration.ofDays(1)), 12); - - assertThatThrownBy(() -> gate.verify(usage, NOW)) - .isInstanceOf(GraphQlPersistedOperationRemovalRejectedException.class); - } - - @Test - void anUnusedOperationPastTheQuietPeriodMayBeRemoved() { - var gate = new GraphQlPersistedOperationRemovalGate(Duration.ofDays(30)); - - assertThatCode(() -> gate.verify(GraphQlPersistedOperationUsage.unused(), NOW)) - .doesNotThrowAnyException(); - assertThatCode( - () -> - gate.verify( - new GraphQlPersistedOperationUsage(NOW.minus(Duration.ofDays(60)), 3), NOW)) - .doesNotThrowAnyException(); - } - - @Test - void applicationCredentialsCannotAdministerTheRegistry() { - var authorization = new GraphQlPersistedOperationAdminAuthorization(Set.of("release-manager")); - - assertThatThrownBy( - () -> - authorization.requireAdministrator( - GraphQlAdminPrincipal.operations("checkout-service"))) - .as("not an administrator") - .isInstanceOf(GraphQlPersistedOperationAdminDeniedException.class); - assertThatThrownBy( - () -> - authorization.requireAdministrator( - GraphQlAdminPrincipal.fromApplicationCredential("release-manager"))) - .as("an allowlisted name presented with a request-path credential is still refused") - .isInstanceOf(GraphQlPersistedOperationAdminDeniedException.class); - assertThatThrownBy(() -> authorization.requireAdministrator(null)) - .isInstanceOf(GraphQlPersistedOperationAdminDeniedException.class); - assertThatCode( - () -> - authorization.requireAdministrator( - GraphQlAdminPrincipal.operations("release-manager"))) - .doesNotThrowAnyException(); - } - - @Test - void blockingTakesEffectImmediatelyAndIsAudited() { - var registry = new InMemoryGraphQlPersistedOperationRegistry(); - registry.register( - GraphQlPersistedOperation.active( - "dangerous-v1", "Dangerous", "sha256:a", "query Dangerous { expensive }", "schema-a")); - var service = service(registry); - - service.block( - new GraphQlPersistedOperationBlockCommand( - new GraphQlPersistedOperationId("dangerous-v1"), - "release-manager", - "incident-4711", - "trace-1"), - ADMIN); - - assertThat( - registry.find(new GraphQlPersistedOperationId("dangerous-v1")).orElseThrow().status()) - .isEqualTo(GraphQlPersistedOperationStatus.BLOCKED); - assertThat(service.auditTrail()) - .singleElement() - .satisfies( - audit -> { - assertThat(audit.operator()).isEqualTo("release-manager"); - assertThat(audit.reason()).isEqualTo("incident-4711"); - assertThat(audit.before()).isEqualTo("BLOCK"); - assertThat(audit.after()).isEqualTo("BLOCKED"); - assertThat(audit.at()).isEqualTo(NOW); - }); - } - - @Test - void removalIsRefusedWhileTheOperationIsStillUsed() { - var registry = new InMemoryGraphQlPersistedOperationRegistry(); - registry.register( - GraphQlPersistedOperation.active( - "get-order-v1", "GetOrder", "sha256:a", "query GetOrder { order { id } }", "schema-a")); - var service = service(registry); - - assertThatThrownBy( - () -> - service.retireAndBlock( - new GraphQlPersistedOperationId("get-order-v1"), - new GraphQlPersistedOperationUsage(NOW.minus(Duration.ofDays(1)), 5), - ADMIN, - "cleanup", - "trace-1")) - .isInstanceOf(GraphQlPersistedOperationRemovalRejectedException.class); - assertThat(service.auditTrail()).isEmpty(); - } - - @Test - void deprecationKeepsAnOperationExecutableWhileClientsMigrate() { - var registry = new InMemoryGraphQlPersistedOperationRegistry(); - registry.register( - GraphQlPersistedOperation.active( - "get-order-v1", "GetOrder", "sha256:a", "query GetOrder { order { id } }", "schema-a")); - var service = service(registry); - - service.deprecate( - new GraphQlPersistedOperationId("get-order-v1"), ADMIN, "superseded", "trace-1"); - - assertThat( - registry - .find(new GraphQlPersistedOperationId("get-order-v1")) - .orElseThrow() - .status() - .executable()) - .isTrue(); - } - - @Test - void theAuditTrailCarriesNoVariablesOrCredentials() { - assertThat(GraphQlPersistedOperationAudit.class.getRecordComponents()) - .extracting(java.lang.reflect.RecordComponent::getName) - .containsExactly("operationId", "operator", "reason", "before", "after", "at", "traceId"); - } - - @Test - void aCommandForAnOperationThatDoesNotExistFailsAndIsNotAudited() { - var registry = new InMemoryGraphQlPersistedOperationRegistry(); - var service = service(registry); - - assertThatThrownBy( - () -> - service.block( - new GraphQlPersistedOperationBlockCommand( - new GraphQlPersistedOperationId("never-existed-v1"), - "release-manager", - "incident-4711", - "trace-1"), - ADMIN)) - .isInstanceOf(GraphQlPersistedOperationNotFoundException.class); - assertThat(service.auditTrail()) - .as("an incident response that changed nothing must not read as one that did") - .isEmpty(); - } - - @Test - void aBlockedOperationCannotBeMadeExecutableByDeprecatingIt() { - var registry = new InMemoryGraphQlPersistedOperationRegistry(); - registry.register( - GraphQlPersistedOperation.active( - "dangerous-v1", "Dangerous", "sha256:a", "query Dangerous { expensive }", "schema-a")); - var service = service(registry); - var id = new GraphQlPersistedOperationId("dangerous-v1"); - service.block( - new GraphQlPersistedOperationBlockCommand(id, "release-manager", "incident", "trace-1"), - ADMIN); - - assertThatThrownBy(() -> service.deprecate(id, ADMIN, "tidy-up", "trace-2")) - .as("leaving the emergency state must be deliberate, not a side effect") - .isInstanceOf( - dev.caskeleton.adapter.inbound.graphql.advanced.persisted - .GraphQlPersistedOperationConflictException.class); - assertThat(registry.find(id).orElseThrow().status().executable()).isFalse(); - } - - @Test - void unblockingIsItsOwnAuditedCommand() { - var registry = new InMemoryGraphQlPersistedOperationRegistry(); - registry.register( - GraphQlPersistedOperation.active( - "dangerous-v1", "Dangerous", "sha256:a", "query Dangerous { expensive }", "schema-a")); - var service = service(registry); - var id = new GraphQlPersistedOperationId("dangerous-v1"); - service.block( - new GraphQlPersistedOperationBlockCommand(id, "release-manager", "incident", "trace-1"), - ADMIN); - - service.unblock(id, ADMIN, "incident resolved", "trace-2"); - - assertThat(registry.find(id).orElseThrow().status().executable()).isTrue(); - assertThat(service.auditTrail()) - .hasSize(2) - .last() - .satisfies(audit -> assertThat(audit.before()).isEqualTo("UNBLOCK")); - } - - private static final GraphQlAdminPrincipal ADMIN = - GraphQlAdminPrincipal.operations("release-manager"); - - private static GraphQlPersistedOperationAdminService service( - InMemoryGraphQlPersistedOperationRegistry registry) { - return new GraphQlPersistedOperationAdminService( - new InMemoryGraphQlPersistedOperationAdminPort(registry), - new GraphQlPersistedOperationAdminAuthorization(Set.of("release-manager")), - new GraphQlPersistedOperationRemovalGate(Duration.ofDays(30)), - CLOCK); - } -} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/bootstrap/GraphQlAdvancedModuleGuardTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/bootstrap/GraphQlAdvancedModuleGuardTest.java deleted file mode 100644 index 19ff9a71..00000000 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/bootstrap/GraphQlAdvancedModuleGuardTest.java +++ /dev/null @@ -1,87 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -/** Advanced module boundary and feature flags (Advanced plan Task 1). */ -@Tag("graphql-advanced") -class GraphQlAdvancedModuleGuardTest { - - @Test - void disabledCapabilityCannotStart() { - var flags = GraphQlAdvancedFeatureFlags.disabled(); - var guard = new GraphQlAdvancedModuleGuard(flags); - - assertThatThrownBy(() -> guard.requireEnabled(GraphQlAdvancedCapability.PERSISTED_OPERATION)) - .isInstanceOf(GraphQlAdvancedCapabilityDisabledException.class); - } - - @Test - void anEnabledCapabilityStarts() { - var guard = - new GraphQlAdvancedModuleGuard( - GraphQlAdvancedFeatureFlags.enabling(GraphQlAdvancedCapability.PERSISTED_OPERATION)); - - assertThatCode(() -> guard.requireEnabled(GraphQlAdvancedCapability.PERSISTED_OPERATION)) - .doesNotThrowAnyException(); - assertThat(guard.enabled(GraphQlAdvancedCapability.WEBSOCKET_SUBSCRIPTION)).isFalse(); - } - - @Test - void experimentalCapabilitiesNeedApprovalInProduction() { - var flags = GraphQlAdvancedFeatureFlags.enabling(GraphQlAdvancedCapability.RSOCKET); - - assertThatCode( - () -> - new GraphQlAdvancedModuleGuard(flags, false) - .requireEnabled(GraphQlAdvancedCapability.RSOCKET)) - .doesNotThrowAnyException(); - assertThatThrownBy( - () -> - new GraphQlAdvancedModuleGuard(flags, true) - .requireEnabled(GraphQlAdvancedCapability.RSOCKET)) - .isInstanceOf(GraphQlAdvancedCapabilityDisabledException.class) - .hasMessageContaining("approval profile"); - assertThatCode( - () -> - new GraphQlAdvancedModuleGuard(flags.withExperimentalApproval(), true) - .requireEnabled(GraphQlAdvancedCapability.RSOCKET)) - .doesNotThrowAnyException(); - } - - @Test - void everyCapabilityDeclaresItsOwnFlagAndGrade() { - assertThat(GraphQlAdvancedCapability.PERSISTED_OPERATION.featureFlag()) - .isEqualTo("backend.graphql.advanced.persisted-operation"); - assertThat(GraphQlAdvancedCapability.RSOCKET.grade()) - .isEqualTo(GraphQlAdvancedCapabilityGrade.EXPERIMENTAL); - assertThat(GraphQlAdvancedCapability.WEBSOCKET_SUBSCRIPTION.grade()) - .isEqualTo(GraphQlAdvancedCapabilityGrade.ADVANCED_STABLE); - assertThat(GraphQlAdvancedDependencyRules.flaggedCapabilities()) - .hasSize(GraphQlAdvancedCapability.values().length); - } - - @Test - void nothingIsEnabledByDefault() { - assertThat(GraphQlAdvancedFeatureFlags.disabled().enabled()).isEmpty(); - assertThat(GraphQlAdvancedFeatureFlags.disabled().experimentalApprovedInProduction()).isFalse(); - } - - @Test - void stableModulesNeverDependOnAdvancedCapabilities() { - assertThatCode(GraphQlAdvancedDependencyRules::verifyStableDoesNotDependOnAdvanced) - .doesNotThrowAnyException(); - assertThat( - GraphQlAdvancedDependencyRules.advancedPackage( - "dev.caskeleton.adapter.inbound.graphql.advanced.persisted")) - .isTrue(); - assertThat( - GraphQlAdvancedDependencyRules.advancedPackage( - "dev.caskeleton.adapter.inbound.graphql.http")) - .isFalse(); - } -} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/chaining/GraphQlDataLoaderCycleDetectorTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/chaining/GraphQlDataLoaderCycleDetectorTest.java deleted file mode 100644 index dadb9412..00000000 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/chaining/GraphQlDataLoaderCycleDetectorTest.java +++ /dev/null @@ -1,111 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.chaining; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedCapability; -import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedCapabilityDisabledException; -import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedFeatureFlags; -import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedModuleGuard; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.Timeout; - -/** GraphQL Java 25 chained DataLoader opt-in (Advanced plan Task 11). */ -@Tag("graphql-advanced") -class GraphQlDataLoaderCycleDetectorTest { - - @Test - @Timeout(10) - void detectsLoaderDependencyCycle() { - var graph = - new GraphQlDataLoaderDependencyGraph() - .dependsOn("orders", "customers") - .dependsOn("customers", "orders"); - - assertThatThrownBy(() -> new GraphQlDataLoaderCycleDetector().verify(graph)) - .isInstanceOf(GraphQlDataLoaderDependencyCycleException.class); - } - - @Test - void anAcyclicGraphPasses() { - var graph = - new GraphQlDataLoaderDependencyGraph() - .dependsOn("orders", "customers") - .dependsOn("customers", "tenants"); - - assertThatCode(() -> new GraphQlDataLoaderCycleDetector().verify(graph)) - .doesNotThrowAnyException(); - assertThat(graph.loaders()).containsExactlyInAnyOrder("orders", "customers", "tenants"); - } - - @Test - void chainedDispatchIsOffByDefault() { - assertThat(GraphQlChainedDataLoaderPolicy.disabled().enabled()).isFalse(); - } - - @Test - void enablingChainedDispatchRequiresTheCapabilityFlag() { - var configurer = - new GraphQlChainedDispatchConfigurer( - new GraphQlAdvancedModuleGuard(GraphQlAdvancedFeatureFlags.disabled()), - new GraphQlDataLoaderCycleDetector()); - var graph = new GraphQlDataLoaderDependencyGraph().dependsOn("orders", "customers"); - - assertThatCode(() -> configurer.configure(GraphQlChainedDataLoaderPolicy.disabled(), graph)) - .doesNotThrowAnyException(); - assertThatThrownBy( - () -> configurer.configure(new GraphQlChainedDataLoaderPolicy(true, 4), graph)) - .isInstanceOf(GraphQlAdvancedCapabilityDisabledException.class); - } - - @Test - void aChainDeeperThanThePolicyAllowsIsRejected() { - var configurer = enabledConfigurer(); - var graph = - new GraphQlDataLoaderDependencyGraph() - .dependsOn("orders", "customers") - .dependsOn("customers", "tenants"); - - assertThat(configurer.depthOf(graph)).isEqualTo(2); - assertThatCode(() -> configurer.configure(new GraphQlChainedDataLoaderPolicy(true, 2), graph)) - .doesNotThrowAnyException(); - assertThatThrownBy( - () -> configurer.configure(new GraphQlChainedDataLoaderPolicy(true, 1), graph)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("depth"); - } - - @Test - void aCycleIsRejectedBeforeDepthIsEvenComputed() { - var configurer = enabledConfigurer(); - var cyclic = - new GraphQlDataLoaderDependencyGraph() - .dependsOn("orders", "customers") - .dependsOn("customers", "orders"); - - assertThatThrownBy( - () -> configurer.configure(new GraphQlChainedDataLoaderPolicy(true, 10), cyclic)) - .isInstanceOf(GraphQlDataLoaderDependencyCycleException.class); - } - - @Test - void dispatchMetricsMakeAChainingRegressionVisible() { - var metrics = new GraphQlChainedLoaderMetrics(); - metrics.recordDispatch(10, false); - metrics.recordDispatch(2, true); - - assertThat(metrics.dispatches()).isEqualTo(2); - assertThat(metrics.keysLoaded()).isEqualTo(12); - assertThat(metrics.chainedDispatches()).isEqualTo(1); - assertThat(metrics.averageBatchSize()).isEqualTo(6.0); - } - - private static GraphQlChainedDispatchConfigurer enabledConfigurer() { - return new GraphQlChainedDispatchConfigurer( - new GraphQlAdvancedModuleGuard( - GraphQlAdvancedFeatureFlags.enabling(GraphQlAdvancedCapability.DATALOADER_CHAINING)), - new GraphQlDataLoaderCycleDetector()); - } -} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/codegen/GraphQlGeneratedSourceBoundaryTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/codegen/GraphQlGeneratedSourceBoundaryTest.java deleted file mode 100644 index 1926a7cb..00000000 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/codegen/GraphQlGeneratedSourceBoundaryTest.java +++ /dev/null @@ -1,98 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.codegen; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.graphql.compat.GraphQlSchemaComparator; -import java.util.List; -import java.util.Set; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -/** Client and transport DTO code generation (Advanced plan Task 14). */ -@Tag("graphql-advanced") -class GraphQlGeneratedSourceBoundaryTest { - - @Test - void domainAndRepositoryGenerationAreForbidden() { - var boundary = GraphQlGeneratedSourceBoundary.standard(); - - assertThat(boundary.isAllowed("CLIENT_RESPONSE")).isTrue(); - assertThat(boundary.isAllowed("DOMAIN_ENTITY")).isFalse(); - assertThat(boundary.isAllowed("REPOSITORY")).isFalse(); - } - - @Test - void aProfileCannotAskForAForbiddenKind() { - assertThatThrownBy( - () -> - new GraphQlCodegenProfile( - "com.example.generated", - "build/generated/graphql", - Set.of("DOMAIN_ENTITY"), - List.of())) - .isInstanceOf(GraphQlCodegenBoundaryException.class); - } - - @Test - void generatedSourcesLiveApartFromHandWrittenOnes() { - var generator = new GraphQlTransportTypeGenerator(profile()); - - assertThat(generator.separatedFrom("src/main/java")).isTrue(); - assertThat(generator.transportTypes()).containsExactly("TRANSPORT_OUTPUT"); - } - - @Test - void customScalarsMustDeclareTheirGeneratedType() { - var mapping = - new GraphQlScalarMapping("BigDecimal", "java.math.BigDecimal", "bigdecimal-string"); - - assertThat(mapping.javaType()).isEqualTo("java.math.BigDecimal"); - assertThatThrownBy(() -> new GraphQlScalarMapping("BigDecimal", " ", "codec")) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void operationsAreValidatedAgainstTheSchemaAtBuildTime() { - var generator = new GraphQlClientOperationGenerator(profile()); - - assertThatCode( - () -> - generator.validateOperation( - "type Query { order: String }", "query GetOrder { order }")) - .doesNotThrowAnyException(); - assertThatThrownBy(() -> generator.validateOperation("type Query { order: String }", " ")) - .isInstanceOf(GraphQlCodegenBoundaryException.class); - assertThat(generator.generatedPackage()).isEqualTo("com.example.generated"); - } - - @Test - void additiveSchemaChangesThatBreakExhaustiveClientsAreReported() { - var report = - GraphQlSchemaComparator.compare("enum Status { NEW }", "enum Status { NEW SHIPPED }"); - - assertThat(report.breaking()).isFalse(); - assertThat(GraphQlGeneratedCompatibilityGate.generatedClientsUnaffected(report)).isFalse(); - assertThat(GraphQlGeneratedCompatibilityGate.generatedClientImpacts(report)).hasSize(1); - assertThat(GraphQlGeneratedCompatibilityGate.exhaustivenessRisk(report.changes().getFirst())) - .isTrue(); - } - - @Test - void aPurelyAdditiveNullableFieldDoesNotRequireRegeneration() { - var report = - GraphQlSchemaComparator.compare( - "type Query { a: String }", "type Query { a: String b: String }"); - - assertThat(GraphQlGeneratedCompatibilityGate.generatedClientsUnaffected(report)).isTrue(); - } - - private static GraphQlCodegenProfile profile() { - return new GraphQlCodegenProfile( - "com.example.generated", - "build/generated/graphql", - Set.of("CLIENT_REQUEST", "CLIENT_RESPONSE", "TRANSPORT_OUTPUT"), - List.of(new GraphQlScalarMapping("UUID", "java.util.UUID", "uuid-canonical"))); - } -} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/codegen/GraphQlOperationValidatorTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/codegen/GraphQlOperationValidatorTest.java deleted file mode 100644 index 09b90238..00000000 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/codegen/GraphQlOperationValidatorTest.java +++ /dev/null @@ -1,128 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.codegen; - -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -/** - * The validator has to read the operation it is validating. - * - *

It used to check that two strings were non-blank and then compare the schema with itself, - * which holds for every schema ever written. Every case below passed that check and became - * generated client code that fails against the very schema it was generated from. - */ -@Tag("graphql-advanced") -class GraphQlOperationValidatorTest { - - private static final String SDL = - """ - type Query { - order(id: ID!): Order - orders: [Order!]! - } - type Order { - id: ID! - total: Int! - } - """; - - @Test - void aValidOperationPasses() { - assertThatCode( - () -> - GraphQlOperationValidator.validate( - SDL, "query GetOrder($id: ID!) { order(id: $id) { id total } }", null)) - .doesNotThrowAnyException(); - } - - @Test - void aValidOperationUsingAFragmentPasses() { - assertThatCode( - () -> - GraphQlOperationValidator.validate( - SDL, - "query GetOrders { orders { ...OrderFields } } " - + "fragment OrderFields on Order { id total }", - null)) - .doesNotThrowAnyException(); - } - - @Test - void invalidSyntaxIsRejected() { - assertThatThrownBy( - () -> GraphQlOperationValidator.validate(SDL, "query GetOrder { order(id: }", null)) - .isInstanceOf(GraphQlCodegenBoundaryException.class) - .hasMessageContaining("does not parse"); - } - - @Test - void anUnknownFieldIsRejected() { - assertThatThrownBy( - () -> GraphQlOperationValidator.validate(SDL, "{ order(id: \"1\") { missing } }", null)) - .isInstanceOf(GraphQlCodegenBoundaryException.class); - } - - @Test - void anUnknownArgumentIsRejected() { - assertThatThrownBy( - () -> - GraphQlOperationValidator.validate( - SDL, "{ order(id: \"1\", nope: 1) { id } }", null)) - .isInstanceOf(GraphQlCodegenBoundaryException.class); - } - - @Test - void anUnknownTypeInAVariableIsRejected() { - assertThatThrownBy( - () -> - GraphQlOperationValidator.validate( - SDL, "query Q($id: Missing!) { order(id: $id) { id } }", null)) - .isInstanceOf(GraphQlCodegenBoundaryException.class); - } - - @Test - void anAmbiguousOperationIsRejected() { - String twoOperations = "query A { orders { id } } query B { orders { total } }"; - - assertThatThrownBy(() -> GraphQlOperationValidator.validate(SDL, twoOperations, null)) - .isInstanceOf(GraphQlCodegenBoundaryException.class) - .hasMessageContaining("declares 2 operations"); - assertThatCode(() -> GraphQlOperationValidator.validate(SDL, twoOperations, "B")) - .as("naming the operation resolves the ambiguity") - .doesNotThrowAnyException(); - assertThatThrownBy(() -> GraphQlOperationValidator.validate(SDL, twoOperations, "C")) - .hasMessageContaining("no operation named C"); - } - - @Test - void aDocumentWithNoOperationIsRejected() { - assertThatThrownBy( - () -> GraphQlOperationValidator.validate(SDL, "fragment F on Order { id }", null)) - .isInstanceOf(GraphQlCodegenBoundaryException.class) - .hasMessageContaining("declares no operation"); - } - - @Test - void aSchemaThatDoesNotCompileIsRejected() { - assertThatThrownBy( - () -> GraphQlOperationValidator.validate("type Query { a: Missing }", "{ a }", null)) - .isInstanceOf(GraphQlCodegenBoundaryException.class) - .hasMessageContaining("schema does not compile"); - } - - @Test - void thePlanDelegatesToTheValidator() { - GraphQlClientOperationGenerator plan = - new GraphQlClientOperationGenerator( - new GraphQlCodegenProfile( - "com.example.generated", - "build/generated/graphql", - java.util.Set.of("CLIENT_REQUEST"), - java.util.List.of())); - - assertThatThrownBy(() -> plan.validateOperation(SDL, "{ order(id: \"1\") { missing } }")) - .isInstanceOf(GraphQlCodegenBoundaryException.class); - } -} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/composition/GraphQlFederationCompositionGateTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/composition/GraphQlFederationCompositionGateTest.java deleted file mode 100644 index 5207e237..00000000 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/composition/GraphQlFederationCompositionGateTest.java +++ /dev/null @@ -1,112 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.composition; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.graphql.advanced.federation.GraphQlFederationEntityKey; -import java.time.Duration; -import java.util.List; -import java.util.Map; -import java.util.Set; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -/** Federation composition, deployment and failure gate (Advanced plan Task 13). */ -@Tag("graphql-advanced") -class GraphQlFederationCompositionGateTest { - - @Test - void compositionWithoutLatencyEvidenceIsRejected() { - var evidence = new GraphQlFederationReleaseEvidence(true, true, false, true); - - assertThatThrownBy(() -> new GraphQlFederationCompositionGate().verify(evidence)) - .isInstanceOf(GraphQlFederationReleaseRejectedException.class); - } - - @Test - void compositionSuccessAloneIsNotEnough() { - var gate = new GraphQlFederationCompositionGate(); - - assertThat(gate.missing(new GraphQlFederationReleaseEvidence(true, false, false, false))) - .containsExactly("entityContracts", "latency", "failureContracts"); - assertThatCode(() -> gate.verify(new GraphQlFederationReleaseEvidence(true, true, true, true))) - .doesNotThrowAnyException(); - } - - @Test - void aSubgraphContractNamesItsOwner() { - assertThatThrownBy( - () -> - new GraphQlSubgraphContract( - "orders", - " ", - "hash", - List.of(new GraphQlFederationEntityKey("Order", List.of("id"))))) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void anEntityKeyChangeIsDetectedAgainstTheDeployedContract() { - var deployed = - new GraphQlSubgraphContract( - "orders", - "orders-team", - "hash-a", - List.of(new GraphQlFederationEntityKey("Order", List.of("id")))); - var candidate = - new GraphQlSubgraphContract( - "orders", - "orders-team", - "hash-b", - List.of(new GraphQlFederationEntityKey("Order", List.of("id", "tenantKey")))); - - assertThat(candidate.entityKeysChangedFrom(deployed)).isTrue(); - assertThat(deployed.entityKeysChangedFrom(deployed)).isFalse(); - } - - @Test - void compositionResultsCarryEitherAHashOrProblems() { - assertThat(GraphQlFederationCompositionResult.composed("supergraph-1").composed()).isTrue(); - assertThat(GraphQlFederationCompositionResult.failed(List.of("key mismatch")).problems()) - .hasSize(1); - assertThatThrownBy(() -> new GraphQlFederationCompositionResult(true, null, List.of())) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> new GraphQlFederationCompositionResult(false, null, List.of())) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void crossSubgraphFanOutAndPerEntityCallsAreBudgeted() { - var budget = new GraphQlFederationLatencyBudget(Duration.ofMillis(400), 3, 0); - - assertThat(budget.within(Duration.ofMillis(300), 2, 0)).isTrue(); - assertThat(budget.within(Duration.ofMillis(300), 4, 0)).isFalse(); - assertThat(budget.within(Duration.ofMillis(300), 2, 1)).isFalse(); - assertThat(budget.within(Duration.ofMillis(500), 2, 0)).isFalse(); - } - - @Test - void usageMustBeKnownBeforeAnEntityFieldChanges() { - var usage = - new GraphQlFederationUsageReport( - Map.of("id", Set.of("checkout", "billing"), "note", Set.of())); - - assertThat(usage.consumersOf("id")).containsExactlyInAnyOrder("checkout", "billing"); - assertThat(usage.safeToChange("id")).isFalse(); - assertThat(usage.safeToChange("note")).isTrue(); - } - - @Test - void removalsDeployRouterFirstAndAdditionsSubgraphFirst() { - assertThat(GraphQlFederationDeploymentOrder.forChange(true)) - .isEqualTo(GraphQlFederationDeploymentOrder.ROUTER_FIRST); - assertThat(GraphQlFederationDeploymentOrder.forChange(false)) - .isEqualTo(GraphQlFederationDeploymentOrder.SUBGRAPH_FIRST); - assertThatThrownBy( - () -> - GraphQlFederationDeploymentOrder.verify( - true, GraphQlFederationDeploymentOrder.SUBGRAPH_FIRST)) - .isInstanceOf(GraphQlFederationReleaseRejectedException.class); - } -} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/federation/GraphQlFederationEntityResolverTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/federation/GraphQlFederationEntityResolverTest.java deleted file mode 100644 index 76acf48e..00000000 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/federation/GraphQlFederationEntityResolverTest.java +++ /dev/null @@ -1,125 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.federation; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedCapability; -import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedCapabilityDisabledException; -import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedFeatureFlags; -import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedModuleGuard; -import java.util.List; -import java.util.Map; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -/** Federation subgraph schema and entity resolution (Advanced plan Task 12). */ -@Tag("graphql-advanced") -class GraphQlFederationEntityResolverTest { - - @Test - void rejectsRepresentationMissingDeclaredKey() { - var key = new GraphQlFederationEntityKey("Order", List.of("id")); - var resolver = new GraphQlFederationEntityResolver(key); - - assertThatThrownBy(() -> resolver.validateRepresentation(Map.of("__typename", "Order"))) - .isInstanceOf(GraphQlFederationRepresentationException.class); - } - - @Test - void aRepresentationForAnotherEntityTypeIsRejected() { - var resolver = - new GraphQlFederationEntityResolver(new GraphQlFederationEntityKey("Order", List.of("id"))); - - assertThatThrownBy( - () -> resolver.validateRepresentation(Map.of("__typename", "Customer", "id", "c-1"))) - .isInstanceOf(GraphQlFederationRepresentationException.class); - assertThatCode( - () -> resolver.validateRepresentation(Map.of("__typename", "Order", "id", "o-1"))) - .doesNotThrowAnyException(); - } - - @Test - void aCompositeKeyRequiresEveryField() { - var resolver = - new GraphQlFederationEntityResolver( - new GraphQlFederationEntityKey("Order", List.of("id", "tenantKey"))); - - assertThatThrownBy(() -> resolver.validateRepresentation(Map.of("id", "o-1"))) - .isInstanceOf(GraphQlFederationRepresentationException.class); - assertThat( - new GraphQlFederationEntityKey("Order", List.of("id", "tenantKey")).directiveFields()) - .isEqualTo("id tenantKey"); - } - - @Test - void anEmptyEntityKeyIsRejected() { - assertThatThrownBy(() -> new GraphQlFederationEntityKey("Order", List.of())) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void entitiesAreResolvedAsOneBatchInRequestOrder() { - var batch = - new GraphQlFederationBatchResolver( - new GraphQlFederationEntityResolver( - new GraphQlFederationEntityKey("Order", List.of("id")))); - - var keys = - batch.validateAndExtractKeys( - List.of( - Map.of("__typename", "Order", "id", "o-1"), - Map.of("__typename", "Order", "id", "o-2"))); - - assertThat(keys).containsExactly(Map.of("id", "o-1"), Map.of("id", "o-2")); - } - - @Test - void federationIsOffByDefaultAndSingleSchemaRemainsTheDefault() { - var properties = GraphQlFederationProperties.disabled(); - var factory = - new GraphQlFederationSchemaFactory( - new GraphQlAdvancedModuleGuard(GraphQlAdvancedFeatureFlags.disabled()), properties); - - assertThat(factory.federationEnabled()).isFalse(); - assertThat(factory.entityResolvers()).isEmpty(); - } - - @Test - void configuredFederationStillRequiresTheCapabilityFlag() { - var properties = - new GraphQlFederationProperties( - true, "orders", List.of(new GraphQlFederationEntityKey("Order", List.of("id")))); - - assertThatThrownBy( - () -> - new GraphQlFederationSchemaFactory( - new GraphQlAdvancedModuleGuard(GraphQlAdvancedFeatureFlags.disabled()), - properties) - .entityResolvers()) - .isInstanceOf(GraphQlAdvancedCapabilityDisabledException.class); - - assertThat( - new GraphQlFederationSchemaFactory( - new GraphQlAdvancedModuleGuard( - GraphQlAdvancedFeatureFlags.enabling( - GraphQlAdvancedCapability.FEDERATION_SUBGRAPH)), - properties) - .entityResolvers()) - .hasSize(1); - } - - @Test - void thisRepositoryOwnsTheSubgraphAndNotTheRouter() { - assertThat(GraphQlFederationCapability.SUBGRAPH.ownedHere()).isTrue(); - assertThat(GraphQlFederationCapability.ROUTER.ownedHere()).isFalse(); - assertThat(GraphQlFederationCapability.SCHEMA_STITCHING.ownedHere()).isFalse(); - assertThat(GraphQlFederationCapability.activationGate()).contains("composition CI"); - } - - @Test - void anEnabledSubgraphMustDeclareANameAndAtLeastOneEntityKey() { - assertThatThrownBy(() -> new GraphQlFederationProperties(true, null, List.of())) - .isInstanceOf(IllegalArgumentException.class); - } -} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/get/GraphQlHttpGetOperationPolicyTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/get/GraphQlHttpGetOperationPolicyTest.java deleted file mode 100644 index 78e0b0d7..00000000 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/get/GraphQlHttpGetOperationPolicyTest.java +++ /dev/null @@ -1,100 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.get; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.graphql.http.GraphQlHttpProfile; -import java.util.Map; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -/** GraphQL over HTTP GET draft profile (Advanced plan Task 17). */ -@Tag("graphql-advanced") -class GraphQlHttpGetOperationPolicyTest { - - @Test - void mutationOverGetIsRejected() { - var policy = GraphQlHttpGetOperationPolicy.queryOnly(); - - assertThatThrownBy(() -> policy.verify("mutation")) - .isInstanceOf(GraphQlHttpGetRejectedException.class); - } - - @Test - void subscriptionsAreRejectedTooAndQueriesAccepted() { - var policy = GraphQlHttpGetOperationPolicy.queryOnly(); - - assertThatThrownBy(() -> policy.verify("subscription")) - .isInstanceOf(GraphQlHttpGetRejectedException.class); - assertThatCode(() -> policy.verify("query")).doesNotThrowAnyException(); - } - - @Test - void theUriBudgetIsEnforcedBeforeParsing() { - var parser = new GraphQlHttpGetRequestParser(GraphQlHttpGetProfile.conservative()); - - assertThatThrownBy(() -> parser.parse(Map.of("query", "query Ping { ping }"), 4_096)) - .isInstanceOf(GraphQlHttpGetRejectedException.class); - assertThat( - parser - .parse(Map.of("query", "query Ping { ping }", "operationName", "Ping"), 128) - .operationName()) - .isEqualTo("Ping"); - } - - @Test - void aMissingQueryParameterIsRejected() { - var parser = new GraphQlHttpGetRequestParser(GraphQlHttpGetProfile.conservative()); - - assertThatThrownBy(() -> parser.parse(Map.of(), 128)) - .isInstanceOf(GraphQlHttpGetRejectedException.class); - } - - @Test - void anActorSpecificResponseIsNeverSharedCached() { - var profile = GraphQlHttpGetProfile.conservative(); - - assertThat(GraphQlHttpGetCachePolicy.forRequest(true, profile)) - .isEqualTo(GraphQlHttpGetCachePolicy.NO_STORE); - assertThat(GraphQlHttpGetCachePolicy.forRequest(false, profile)) - .isEqualTo(GraphQlHttpGetCachePolicy.PRIVATE); - assertThat( - GraphQlHttpGetCachePolicy.forRequest( - false, new GraphQlHttpGetProfile(2_048, true, true))) - .isEqualTo(GraphQlHttpGetCachePolicy.SHARED); - assertThat(GraphQlHttpGetCachePolicy.NO_STORE.cacheControl()).isEqualTo("no-store"); - } - - @Test - void cookieAuthenticatedGetRequestsRequireCsrfProtection() { - var policy = new GraphQlHttpGetCsrfPolicy(true, new GraphQlHttpGetProfile(2_048, false, false)); - - assertThat(policy.csrfTokenRequired()).isTrue(); - assertThatThrownBy(() -> policy.verify(false)) - .isInstanceOf(GraphQlHttpGetRejectedException.class); - assertThatCode(() -> policy.verify(true)).doesNotThrowAnyException(); - } - - @Test - void theDraftReportRecordsWhatIsDeliberatelyNotAdopted() { - var report = GraphQlHttpDraftCompatibilityReport.current(); - - assertThat(report.draftStage()).isEqualTo("Stage 2 Draft"); - assertThat(report.supportedFeatures()).contains("POST"); - assertThat(report.deliberatelyUnsupported()) - .anySatisfy( - entry -> - assertThat(entry) - .contains(String.valueOf(GraphQlHttpProfile.DRAFT_PARTIAL_RESPONSE_STATUS))); - assertThat(report.asMap()).containsKeys("draftStage", "supported", "deliberatelyUnsupported"); - } - - @Test - void theStablePostContractIsUnaffectedByTheDraftProfile() { - assertThat(GraphQlHttpProfile.V1.usesDraftPartialResponseStatus()).isFalse(); - assertThatThrownBy(() -> GraphQlHttpProfile.V1.validateMethod("GET")) - .isInstanceOf( - dev.caskeleton.adapter.inbound.graphql.http.GraphQlHttpContractException.class); - } -} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/incremental/GraphQlIncrementalCompatibilityGateTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/incremental/GraphQlIncrementalCompatibilityGateTest.java deleted file mode 100644 index fffc3e06..00000000 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/incremental/GraphQlIncrementalCompatibilityGateTest.java +++ /dev/null @@ -1,118 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.incremental; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.graphql.cost.GraphQlRuntimeBudget; -import dev.caskeleton.adapter.inbound.graphql.cost.GraphQlRuntimeBudgetExceededException; -import dev.caskeleton.adapter.inbound.graphql.cost.GraphQlRuntimeBudgetTracker; -import dev.caskeleton.adapter.inbound.graphql.execution.GraphQlCancellation; -import java.util.List; -import java.util.Map; -import java.util.concurrent.atomic.AtomicBoolean; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -/** Incremental delivery experimental profile (Advanced plan Task 18). */ -@Tag("graphql-advanced") -class GraphQlIncrementalCompatibilityGateTest { - - @Test - void unsupportedRuntimeCannotEnableIncrementalDelivery() { - var gate = new GraphQlIncrementalCompatibilityGate(); - - assertThatThrownBy(() -> gate.verify(new GraphQlIncrementalDeliveryCapability(false, false))) - .isInstanceOf(GraphQlIncrementalDeliveryRejectedException.class); - } - - @Test - void bothTheEngineAndTheTransportMustSupportIt() { - var gate = new GraphQlIncrementalCompatibilityGate(); - - assertThatThrownBy(() -> gate.verify(new GraphQlIncrementalDeliveryCapability(true, false))) - .isInstanceOf(GraphQlIncrementalDeliveryRejectedException.class); - assertThatThrownBy(() -> gate.verify(new GraphQlIncrementalDeliveryCapability(false, true))) - .isInstanceOf(GraphQlIncrementalDeliveryRejectedException.class); - assertThatCode(() -> gate.verify(new GraphQlIncrementalDeliveryCapability(true, true))) - .doesNotThrowAnyException(); - assertThat(new GraphQlIncrementalDeliveryCapability(true, true).available()).isTrue(); - } - - @Test - void anIncrementalResponseRequiresClientNegotiation() { - var gate = new GraphQlIncrementalCompatibilityGate(); - - assertThatThrownBy(() -> gate.verifyClientNegotiation(false)) - .isInstanceOf(GraphQlIncrementalDeliveryRejectedException.class) - .hasMessageContaining("capability negotiation"); - assertThatCode(() -> gate.verifyClientNegotiation(true)).doesNotThrowAnyException(); - } - - @Test - void theProfileIsDisabledByDefaultAndVersionGated() { - var profile = GraphQlIncrementalDeliveryProfile.disabled(); - - assertThat(profile.enabled()).isFalse(); - assertThat(profile.profileVersion()).isEqualTo("experimental-v0"); - assertThatThrownBy(() -> new GraphQlIncrementalDeliveryProfile(" ", true, false)) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void patchesCarryTheirOwnPathAndErrors() { - var patch = - new GraphQlIncrementalPatch( - List.of("order", "payment"), - Map.of("status", "PAID"), - List.of(Map.of("message", "요청을 처리할 수 없습니다.")), - true); - - assertThat(patch.path()).containsExactly("order", "payment"); - assertThat(patch.errors()).hasSize(1); - assertThat(patch.hasNext()).isTrue(); - } - - @Test - void patchesConsumeTheSameRuntimeBudgetAsTheInitialResult() { - var tracker = new GraphQlRuntimeBudgetTracker(new GraphQlRuntimeBudget(1, 1_048_576)); - var policy = new GraphQlIncrementalTransportPolicy(tracker); - var patch = - new GraphQlIncrementalPatch(List.of("order"), Map.of("id", "o-1"), List.of(), false); - - policy.recordPatch(patch); - - assertThatThrownBy(() -> policy.recordPatch(patch)) - .isInstanceOf(GraphQlRuntimeBudgetExceededException.class); - } - - @Test - void anOverrunAfterTheInitialResultIsAPartialResponse() { - var tracker = new GraphQlRuntimeBudgetTracker(new GraphQlRuntimeBudget(1_000, 4)); - var policy = new GraphQlIncrementalTransportPolicy(tracker); - policy.markInitialResultSent(); - - assertThatThrownBy( - () -> - policy.recordPatch( - new GraphQlIncrementalPatch( - List.of("order"), Map.of("id", "o-1"), List.of(), false))) - .isInstanceOf(GraphQlRuntimeBudgetExceededException.class) - .satisfies( - failure -> - assertThat(((GraphQlRuntimeBudgetExceededException) failure).responseCommitted()) - .isTrue()); - } - - @Test - void aDisconnectStopsOutstandingPatches() { - var cancellation = new GraphQlIncrementalCancellation(GraphQlCancellation.create()); - AtomicBoolean patchStopped = new AtomicBoolean(); - cancellation.onCancel(() -> patchStopped.set(true)); - - assertThat(cancellation.mayContinue()).isTrue(); - cancellation.cancel(); - assertThat(patchStopped).isTrue(); - assertThat(cancellation.mayContinue()).isFalse(); - } -} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/GraphQlPersistedOperationInterceptorTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/GraphQlPersistedOperationInterceptorTest.java deleted file mode 100644 index 899dfe44..00000000 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/GraphQlPersistedOperationInterceptorTest.java +++ /dev/null @@ -1,161 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.persisted; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedCapability; -import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedFeatureFlags; -import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedModuleGuard; -import dev.caskeleton.adapter.inbound.graphql.policy.GraphQlClientPolicy; -import java.time.Duration; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -/** Persisted operation lookup and execution checks (Advanced plan Task 3). */ -@Tag("graphql-advanced") -class GraphQlPersistedOperationInterceptorTest { - - @Test - void blockedOperationIsRejectedBeforeExecution() { - var operation = - GraphQlPersistedOperation.active( - "dangerous-v1", - "Dangerous", - "sha256:a", - "query Dangerous { expensive }", - "schema-a") - .withStatus(GraphQlPersistedOperationStatus.BLOCKED); - - assertThatThrownBy(() -> GraphQlPersistedOperationPolicy.requireActive(operation)) - .isInstanceOf(GraphQlPersistedOperationRejectedException.class); - } - - @Test - void aSuppliedDocumentMustMatchTheApprovedOne() { - var operation = active(); - - assertThatCode( - () -> GraphQlPersistedOperationPolicy.requireDocumentMatch(operation, "sha256:a")) - .doesNotThrowAnyException(); - assertThatCode(() -> GraphQlPersistedOperationPolicy.requireDocumentMatch(operation, null)) - .doesNotThrowAnyException(); - assertThatThrownBy( - () -> GraphQlPersistedOperationPolicy.requireDocumentMatch(operation, "sha256:forged")) - .isInstanceOf(GraphQlPersistedOperationRejectedException.class); - } - - @Test - void theClientProfileMustBeAllowlisted() { - assertThatThrownBy( - () -> GraphQlPersistedOperationPolicy.requireClientAllowed(active(), "PUBLIC")) - .isInstanceOf(GraphQlPersistedOperationRejectedException.class); - assertThatCode( - () -> GraphQlPersistedOperationPolicy.requireClientAllowed(active(), "FIRST_PARTY")) - .doesNotThrowAnyException(); - } - - @Test - void aStaleSchemaHashStopsExecution() { - assertThatThrownBy( - () -> GraphQlPersistedOperationPolicy.requireSchemaMatch(active(), "schema-b")) - .isInstanceOf(GraphQlPersistedOperationRejectedException.class); - } - - @Test - void theStricterOfTheOperationAndClientLimitApplies() { - assertThat(GraphQlPersistedOperationPolicy.effectiveLimit(10_000, 5_000)).isEqualTo(5_000); - assertThat(GraphQlPersistedOperationPolicy.effectiveLimit(1_000, 5_000)).isEqualTo(1_000); - } - - @Test - void theInterceptorRunsEveryCheckAndRequiresTheCapabilityFlag() { - var registry = new InMemoryGraphQlPersistedOperationRegistry(); - registry.register(active()); - var lookup = new GraphQlPersistedOperationLookup(registry); - var request = - new GraphQlPersistedOperationRequest( - new GraphQlPersistedOperationId("get-order-v1"), "sha256:a", 100); - - var disabled = - new GraphQlPersistedOperationInterceptor( - new GraphQlAdvancedModuleGuard(GraphQlAdvancedFeatureFlags.disabled()), lookup); - assertThatThrownBy(() -> disabled.resolve(request, "FIRST_PARTY", "schema-a", clientPolicy())) - .isInstanceOf( - dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap - .GraphQlAdvancedCapabilityDisabledException.class); - - var enabled = - new GraphQlPersistedOperationInterceptor( - new GraphQlAdvancedModuleGuard( - GraphQlAdvancedFeatureFlags.enabling( - GraphQlAdvancedCapability.PERSISTED_OPERATION)), - lookup); - assertThat(enabled.resolve(request, "FIRST_PARTY", "schema-a", clientPolicy()).operationName()) - .isEqualTo("GetOrder"); - assertThat(enabled.effectiveComplexityLimit(active(), clientPolicy())).isEqualTo(10_000); - } - - @Test - void anUnknownIdIsRejectedWithoutRevealingWhatExists() { - var lookup = - new GraphQlPersistedOperationLookup(new InMemoryGraphQlPersistedOperationRegistry()); - - assertThatThrownBy(() -> lookup.require(new GraphQlPersistedOperationId("missing-v1"))) - .isInstanceOf(GraphQlPersistedOperationRejectedException.class) - .hasMessageNotContaining("missing-v1"); - } - - @Test - void oversizedVariablesAreRejectedAgainstTheStricterLimit() { - var request = - new GraphQlPersistedOperationRequest( - new GraphQlPersistedOperationId("get-order-v1"), "sha256:a", 70_000); - - assertThatThrownBy( - () -> - GraphQlPersistedOperationPolicy.requireVariablesWithinLimit( - active(), request, 65_536)) - .isInstanceOf(GraphQlPersistedOperationRejectedException.class); - } - - @Test - void theRegistryAndTheParseCacheStayDifferentThings() { - var operation = active(); - - assertThat(GraphQlPersistedPreparsedBridge.executable(operation)).isTrue(); - assertThat( - GraphQlPersistedPreparsedBridge.executable( - operation.withStatus(GraphQlPersistedOperationStatus.BLOCKED))) - .isFalse(); - assertThat( - GraphQlPersistedPreparsedBridge.cacheKey(operation, "policy-1", "FIRST_PARTY") - .schemaContractHash()) - .isEqualTo("schema-a"); - } - - private static GraphQlPersistedOperation active() { - return GraphQlPersistedOperation.active( - "get-order-v1", "GetOrder", "sha256:a", "query GetOrder { order { id } }", "schema-a"); - } - - private static GraphQlClientPolicy clientPolicy() { - return new GraphQlClientPolicy( - 65536, - 65536, - 12, - 500, - 50, - 50, - 1000, - 20, - 100, - 10_000, - 10_000, - 5_242_880, - Duration.ofSeconds(5), - false, - true, - true); - } -} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/GraphQlPersistedOperationRegistryTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/GraphQlPersistedOperationRegistryTest.java deleted file mode 100644 index 2ee7874d..00000000 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/GraphQlPersistedOperationRegistryTest.java +++ /dev/null @@ -1,98 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.persisted; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.util.Set; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -/** Approved operation model and registry (Advanced plan Task 2). */ -@Tag("graphql-advanced") -class GraphQlPersistedOperationRegistryTest { - - @Test - void sameIdWithDifferentDocumentIsConflict() { - var registry = new InMemoryGraphQlPersistedOperationRegistry(); - registry.register( - GraphQlPersistedOperation.active( - "get-order-v1", "GetOrder", "sha256:a", "query GetOrder { order { id } }", "schema-a")); - - assertThatThrownBy( - () -> - registry.register( - GraphQlPersistedOperation.active( - "get-order-v1", - "GetOrder", - "sha256:b", - "query GetOrder { order { status } }", - "schema-a"))) - .isInstanceOf(GraphQlPersistedOperationConflictException.class); - } - - @Test - void reRegisteringTheSameDocumentIsIdempotent() { - var registry = new InMemoryGraphQlPersistedOperationRegistry(); - var operation = - GraphQlPersistedOperation.active( - "get-order-v1", "GetOrder", "sha256:a", "query GetOrder { order { id } }", "schema-a"); - - registry.register(operation); - assertThatCode(() -> registry.register(operation)).doesNotThrowAnyException(); - assertThat(registry.size()).isEqualTo(1); - } - - @Test - void theRecordCarriesEverythingExecutionNeedsAndNoVariables() { - var operation = - GraphQlPersistedOperation.active( - "get-order-v1", "GetOrder", "sha256:a", "query GetOrder { order { id } }", "schema-a"); - - assertThat(operation.allowedClientProfiles()).containsExactly("FIRST_PARTY"); - assertThat(operation.maximumComplexity()).isPositive(); - assertThat(operation.maximumVariablesBytes()).isPositive(); - assertThat(GraphQlPersistedOperation.class.getRecordComponents()) - .extracting(java.lang.reflect.RecordComponent::getName) - .doesNotContain("variables", "credential", "actor"); - } - - @Test - void aBlockedOperationIsNotExecutableEvenThoughItStaysRegistered() { - var registry = new InMemoryGraphQlPersistedOperationRegistry(); - var id = new GraphQlPersistedOperationId("get-order-v1"); - registry.register( - GraphQlPersistedOperation.active( - "get-order-v1", "GetOrder", "sha256:a", "query GetOrder { order { id } }", "schema-a")); - - registry.apply(id, GraphQlPersistedOperationTransition.BLOCK); - - assertThat(registry.find(id)).isPresent(); - assertThat(registry.find(id).orElseThrow().status().executable()).isFalse(); - assertThat(GraphQlPersistedOperationStatus.DEPRECATED.executable()).isTrue(); - } - - @Test - void anOperationMustAllowAtLeastOneClientProfile() { - assertThatThrownBy( - () -> - new GraphQlPersistedOperation( - new GraphQlPersistedOperationId("get-order-v1"), - "GetOrder", - "sha256:a", - "query GetOrder { order { id } }", - "schema-a", - Set.of(), - 10_000, - 65_536, - GraphQlPersistedOperationStatus.ACTIVE)) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void operationIdsAreBounded() { - assertThatThrownBy(() -> new GraphQlPersistedOperationId("Get Order")) - .isInstanceOf(IllegalArgumentException.class); - assertThat(new GraphQlPersistedOperationId("get-order.v2").value()).isEqualTo("get-order.v2"); - } -} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/GraphQlPersistedOperationStorageDirectionTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/GraphQlPersistedOperationStorageDirectionTest.java deleted file mode 100644 index 6de6744c..00000000 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/GraphQlPersistedOperationStorageDirectionTest.java +++ /dev/null @@ -1,182 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.persisted; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.shared.opstore.OperationalRecord; -import dev.caskeleton.shared.opstore.OperationalRecordConflictException; -import dev.caskeleton.shared.opstore.OperationalRecordStorePort; -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import org.junit.jupiter.api.Test; - -/** - * Durable storage for persisted operations without inverting the dependency. - * - *

The registry is an inbound interface, so a Postgres or Redis adapter implementing it would - * point the dependency from infrastructure back at a transport boundary. Both sides depend on the - * neutral {@link OperationalRecordStorePort} instead, and this leaf owns only the translation. - */ -class GraphQlPersistedOperationStorageDirectionTest { - - private final FakeStore store = new FakeStore(); - private final OperationalStoreGraphQlPersistedOperationRegistry registry = - new OperationalStoreGraphQlPersistedOperationRegistry(store); - - @Test - void anOperationSurvivesAStoreRoundTripUnchanged() { - GraphQlPersistedOperation operation = operation(GraphQlPersistedOperationStatus.ACTIVE); - - registry.register(operation); - - assertThat(registry.find(operation.id())).contains(operation); - } - - @Test - void theStoredRecordCarriesNoGraphQlTypes() { - registry.register(operation(GraphQlPersistedOperationStatus.ACTIVE)); - - OperationalRecord stored = - store.find(GraphQlPersistedOperationRecordMapping.NAMESPACE, "op-1").orElseThrow(); - - assertThat(stored.value()) - .as("the store holds text it never has to understand") - .isInstanceOf(String.class); - assertThat(stored.namespace()).isEqualTo("graphql.persisted-operation"); - } - - @Test - void aDocumentContainingTheFramingCharactersStillRoundTrips() { - GraphQlPersistedOperation awkward = - new GraphQlPersistedOperation( - new GraphQlPersistedOperationId("op-2"), - "GetOrder", - "hash-2", - "query GetOrder { order { id } }\n# 12:not-a-frame\n", - "schema-1", - Set.of("first-party", "3:weird"), - 1_000, - 2_048, - GraphQlPersistedOperationStatus.ACTIVE); - - registry.register(awkward); - - assertThat(registry.find(awkward.id())) - .as("length framing means a value may contain anything, including a frame header") - .contains(awkward); - } - - @Test - void aTransitionThatLostTheRaceIsReportedRatherThanSilentlyDropped() { - GraphQlPersistedOperation operation = operation(GraphQlPersistedOperationStatus.ACTIVE); - registry.register(operation); - store.letAnotherWriterWinAfterTheNextRead("op-1"); - - assertThatThrownBy( - () -> registry.apply(operation.id(), GraphQlPersistedOperationTransition.BLOCK)) - .as("two admin planes a second apart must not resolve by arrival order in silence") - .isInstanceOf(GraphQlPersistedOperationConflictException.class); - } - - @Test - void aTransitionOnAnUnknownOperationFails() { - assertThatThrownBy( - () -> - registry.apply( - new GraphQlPersistedOperationId("never-registered"), - GraphQlPersistedOperationTransition.BLOCK)) - .isInstanceOf(GraphQlPersistedOperationNotFoundException.class); - } - - @Test - void reRegisteringADifferentDocumentUnderOneIdIsAConflict() { - registry.register(operation(GraphQlPersistedOperationStatus.ACTIVE)); - - assertThatThrownBy( - () -> - registry.register( - new GraphQlPersistedOperation( - new GraphQlPersistedOperationId("op-1"), - "GetOrder", - "hash-other", - "query GetOrder { somethingElse }", - "schema-1", - Set.of("first-party"), - 1_000, - 2_048, - GraphQlPersistedOperationStatus.ACTIVE))) - .isInstanceOf(GraphQlPersistedOperationConflictException.class); - } - - private static GraphQlPersistedOperation operation(GraphQlPersistedOperationStatus status) { - return new GraphQlPersistedOperation( - new GraphQlPersistedOperationId("op-1"), - "GetOrder", - "hash-1", - "query GetOrder { order { id } }", - "schema-1", - Set.of("first-party"), - 1_000, - 2_048, - status); - } - - /** A store that behaves like a real one: versioned, and unforgiving about stale writes. */ - private static final class FakeStore implements OperationalRecordStorePort { - - private final Map records = new HashMap<>(); - private String interleaveAfterRead; - - @Override - public Optional find(String namespace, String key) { - Optional found = Optional.ofNullable(records.get(namespace + '/' + key)); - String pending = interleaveAfterRead; - if (pending != null && pending.equals(key)) { - // The other admin plane's write lands here: after this caller read, before it writes. - interleaveAfterRead = null; - bump(namespace + '/' + key); - } - return found; - } - - @Override - public OperationalRecord compareAndSet(OperationalRecord record, long expectedVersion) { - String id = record.namespace() + '/' + record.key(); - long current = - records.containsKey(id) ? records.get(id).version() : OperationalRecord.ABSENT_VERSION; - if (current != expectedVersion) { - throw new OperationalRecordConflictException( - record.namespace(), record.key(), expectedVersion, current); - } - OperationalRecord stored = - new OperationalRecord(record.namespace(), record.key(), record.value(), current + 1); - records.put(id, stored); - return stored; - } - - @Override - public void compareAndRemove(String namespace, String key, long expectedVersion) { - String id = namespace + '/' + key; - OperationalRecord current = records.get(id); - long version = current == null ? OperationalRecord.ABSENT_VERSION : current.version(); - if (version != expectedVersion) { - throw new OperationalRecordConflictException(namespace, key, expectedVersion, version); - } - records.remove(id); - } - - void letAnotherWriterWinAfterTheNextRead(String key) { - interleaveAfterRead = key; - } - - private void bump(String id) { - OperationalRecord current = records.get(id); - records.put( - id, - new OperationalRecord( - current.namespace(), current.key(), current.value(), current.version() + 1)); - } - } -} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/release/GraphQlAdvancedReleaseGateTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/release/GraphQlAdvancedReleaseGateTest.java deleted file mode 100644 index b94c21b1..00000000 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/release/GraphQlAdvancedReleaseGateTest.java +++ /dev/null @@ -1,154 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.release; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedCapability; -import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedCapabilityGrade; -import dev.caskeleton.adapter.inbound.graphql.release.GraphQlCompatibilityMatrix; -import java.time.Instant; -import java.util.List; -import java.util.Map; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -/** Advanced capability promotion, soak and release gate (Advanced plan Task 19). */ -@Tag("graphql-advanced") -class GraphQlAdvancedReleaseGateTest { - - private static final Instant NOW = Instant.parse("2026-08-12T00:00:00Z"); - - @Test - void advancedCannotReleaseBeforeStableBaseline() { - var evidence = new GraphQlAdvancedReleaseEvidence(false, true, true, true, true); - - assertThatThrownBy(() -> new GraphQlAdvancedReleaseGate().verify(evidence)) - .isInstanceOf(GraphQlAdvancedReleaseException.class) - .hasMessageContaining("stable"); - } - - @Test - void everyKindOfCapabilityEvidenceIsRequired() { - var gate = new GraphQlAdvancedReleaseGate(); - - assertThatThrownBy( - () -> gate.verify(new GraphQlAdvancedReleaseEvidence(true, true, true, false, true))) - .isInstanceOf(GraphQlAdvancedReleaseException.class) - .hasMessageContaining("soak"); - assertThat(gate.missing(new GraphQlAdvancedReleaseEvidence(true, false, false, false, false))) - .containsExactly("capabilityContracts", "security", "soak", "compatibility"); - assertThatCode( - () -> gate.verify(new GraphQlAdvancedReleaseEvidence(true, true, true, true, true))) - .doesNotThrowAnyException(); - } - - @Test - void realtimeCapabilitiesRequireTheFullSoakSet() { - assertThat(GraphQlAdvancedSoakScenario.requiredForRealtime()) - .contains( - GraphQlAdvancedSoakScenario.BASELINE_1K_CONNECTIONS, - GraphQlAdvancedSoakScenario.SLOW_CONSUMER, - GraphQlAdvancedSoakScenario.AUTH_EXPIRY, - GraphQlAdvancedSoakScenario.CANCEL_STORM, - GraphQlAdvancedSoakScenario.GRACEFUL_DRAIN); - } - - @Test - void experimentalCapabilitiesStayExperimentalWithoutARecordedDecision() { - var promotion = - new GraphQlAdvancedPromotionDecision( - GraphQlAdvancedCapability.RSOCKET, - GraphQlAdvancedCapabilityGrade.EXPERIMENTAL, - GraphQlAdvancedCapabilityGrade.ADVANCED, - "ADR-0042", - "platform-team", - NOW, - List.of("soak")); - - assertThat(promotion.promotes()).isTrue(); - assertThatThrownBy(promotion::verify) - .isInstanceOf(GraphQlAdvancedReleaseException.class) - .hasMessageContaining("outstanding evidence"); - } - - @Test - void aPromotionRequiresAnOwnerAndADecisionRecord() { - assertThatThrownBy( - () -> - new GraphQlAdvancedPromotionDecision( - GraphQlAdvancedCapability.RSOCKET, - GraphQlAdvancedCapabilityGrade.EXPERIMENTAL, - GraphQlAdvancedCapabilityGrade.ADVANCED, - " ", - "platform-team", - NOW, - List.of())) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new GraphQlAdvancedPromotionDecision( - GraphQlAdvancedCapability.RSOCKET, - GraphQlAdvancedCapabilityGrade.EXPERIMENTAL, - GraphQlAdvancedCapabilityGrade.ADVANCED, - "ADR-0042", - " ", - NOW, - List.of())) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void aCleanPromotionIsAccepted() { - assertThatCode( - () -> - new GraphQlAdvancedPromotionDecision( - GraphQlAdvancedCapability.WEBSOCKET_SUBSCRIPTION, - GraphQlAdvancedCapabilityGrade.ADVANCED, - GraphQlAdvancedCapabilityGrade.ADVANCED_STABLE, - "ADR-0043", - "platform-team", - NOW, - List.of()) - .verify()) - .doesNotThrowAnyException(); - } - - @Test - void theCompatibilityMatrixExtendsTheStableOne() { - var stable = new GraphQlCompatibilityMatrix(21, "4.0.0", "2.0.0", "25.0", true); - var advanced = - new GraphQlAdvancedCompatibilityMatrix( - GraphQlAdvancedCapability.WEBSOCKET_SUBSCRIPTION, - stable, - Map.of("graphql-transport-ws", "1.0")); - - assertThat(advanced.supported()).isTrue(); - assertThat( - new GraphQlAdvancedCompatibilityMatrix( - GraphQlAdvancedCapability.WEBSOCKET_SUBSCRIPTION, stable, Map.of()) - .problems()) - .anySatisfy(problem -> assertThat(problem).contains("no verified protocol version")); - assertThat( - new GraphQlAdvancedCompatibilityMatrix( - GraphQlAdvancedCapability.WEBSOCKET_SUBSCRIPTION, - new GraphQlCompatibilityMatrix(17, "4.0.0", "2.0.0", "25.0", true), - Map.of("graphql-transport-ws", "1.0")) - .supported()) - .isFalse(); - } - - @Test - void everyReleasedCapabilityHasARunbook() { - var index = - new GraphQlAdvancedRunbookIndex() - .register( - GraphQlAdvancedCapability.WEBSOCKET_SUBSCRIPTION, "docs/runbooks/graphql-ws.md"); - - assertThat(index.require(GraphQlAdvancedCapability.WEBSOCKET_SUBSCRIPTION)) - .isEqualTo("docs/runbooks/graphql-ws.md"); - assertThatThrownBy(() -> index.require(GraphQlAdvancedCapability.FEDERATION_SUBGRAPH)) - .isInstanceOf(GraphQlAdvancedReleaseException.class) - .hasMessageContaining("runbook"); - } -} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/replay/GraphQlSnapshotLiveHandoffTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/replay/GraphQlSnapshotLiveHandoffTest.java deleted file mode 100644 index 6922d77d..00000000 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/replay/GraphQlSnapshotLiveHandoffTest.java +++ /dev/null @@ -1,153 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.replay; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.graphql.advanced.security.GraphQlWebSocketPrincipal; -import dev.caskeleton.adapter.inbound.graphql.advanced.subscription.GraphQlSubscriptionEvent; -import dev.caskeleton.adapter.inbound.graphql.pagination.GraphQlCursorException; -import dev.caskeleton.adapter.inbound.graphql.pagination.HmacGraphQlCursorCodec; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; -import org.reactivestreams.Publisher; - -/** Messaging-backed subscription replay extension (Advanced plan Task 10). */ -@Tag("graphql-advanced") -class GraphQlSnapshotLiveHandoffTest { - - @Test - void gapBetweenSnapshotAndLivePositionIsRejected() { - var handoff = - new GraphQlSnapshotLiveHandoff( - new GraphQlReplayPosition(10), new GraphQlReplayPosition(12)); - - assertThatThrownBy(handoff::verifyContiguous).isInstanceOf(GraphQlReplayGapException.class); - } - - @Test - void aContiguousHandoffIsAccepted() { - assertThatCode( - () -> - new GraphQlSnapshotLiveHandoff( - new GraphQlReplayPosition(10), new GraphQlReplayPosition(11)) - .verifyContiguous()) - .doesNotThrowAnyException(); - } - - @Test - void anOverlappingHandoffIsReportedAsDuplicating() { - var handoff = - new GraphQlSnapshotLiveHandoff(new GraphQlReplayPosition(10), new GraphQlReplayPosition(9)); - - assertThat(handoff.duplicates()).isTrue(); - assertThatCode(handoff::verifyContiguous).doesNotThrowAnyException(); - } - - @Test - void aPositionOutsideTheRetentionWindowIsHistoryLostNotAnEmptyStream() { - GraphQlReplaySource source = - new GraphQlReplaySource() { - @Override - public GraphQlReplayPosition earliestAvailable() { - return new GraphQlReplayPosition(100); - } - - @Override - public Publisher replayFrom(GraphQlReplayPosition position) { - requireAvailable(position); - return subscriber -> {}; - } - }; - - assertThat(source.available(new GraphQlReplayPosition(150))).isTrue(); - assertThatThrownBy(() -> source.replayFrom(new GraphQlReplayPosition(50))) - .isInstanceOf(GraphQlReplayHistoryLostException.class) - .hasMessage(GraphQlReplayHistoryLostException.CODE); - } - - @Test - void aResumeCursorIsSignedAndBoundToItsTenantActorAndSubscription() { - var codec = - new HmacGraphQlCursorCodec( - dev.caskeleton.adapter.inbound.graphql.pagination.GraphQlCursorFixtures - .rotatingKeyRing()); - var issuedTo = new GraphQlWebSocketPrincipal("actor-1", "tenant-1", null); - String cursor = - GraphQlSubscriptionCursor.issue( - codec, "order-events", issuedTo, new GraphQlReplayPosition(42)); - - assertThat(GraphQlSubscriptionCursor.resume(codec, cursor, "order-events", issuedTo).sequence()) - .isEqualTo(42); - assertThatThrownBy( - () -> - GraphQlSubscriptionCursor.resume( - codec, - cursor, - "order-events", - new GraphQlWebSocketPrincipal("actor-2", "tenant-1", null))) - .as("a resume cursor is bound to the actor it was issued to") - .isInstanceOf(GraphQlCursorException.class); - assertThatThrownBy( - () -> - GraphQlSubscriptionCursor.resume( - codec, - cursor, - "order-events", - new GraphQlWebSocketPrincipal("actor-1", "tenant-2", null))) - .as("the same actor identity in another tenant must not replay this history") - .isInstanceOf(GraphQlCursorException.class); - assertThatThrownBy( - () -> GraphQlSubscriptionCursor.resume(codec, cursor, "other-events", issuedTo)) - .as("and to the subscription it was issued for") - .isInstanceOf(GraphQlCursorException.class); - } - - @Test - void aFramedScopeCannotBeForgedByShiftingTheTenantActorSplit() { - var codec = - new HmacGraphQlCursorCodec( - dev.caskeleton.adapter.inbound.graphql.pagination.GraphQlCursorFixtures - .rotatingKeyRing()); - String cursor = - GraphQlSubscriptionCursor.issue( - codec, - "order-events", - new GraphQlWebSocketPrincipal("ab", "t", null), - new GraphQlReplayPosition(7)); - - assertThatThrownBy( - () -> - GraphQlSubscriptionCursor.resume( - codec, cursor, "order-events", new GraphQlWebSocketPrincipal("b", "ta", null))) - .as("plain concatenation would render both (t, ab) and (ta, b) as \"tab\"") - .isInstanceOf(GraphQlCursorException.class); - } - - @Test - void replayIsAuthorizedAgainstTheActorAndCurrentAccess() { - var principal = new GraphQlWebSocketPrincipal("actor-1", "tenant-1", null); - - assertThatCode(() -> GraphQlReplayAuthorization.verify("actor-1", "tenant-1", principal, true)) - .doesNotThrowAnyException(); - assertThatThrownBy( - () -> GraphQlReplayAuthorization.verify("actor-2", "tenant-1", principal, true)) - .isInstanceOf(GraphQlReplayAuthorizationException.class); - assertThatThrownBy( - () -> GraphQlReplayAuthorization.verify("actor-1", "tenant-2", principal, true)) - .as( - "the same actor fingerprint in another tenant is not the actor the cursor was issued to") - .isInstanceOf(GraphQlReplayAuthorizationException.class); - assertThatThrownBy( - () -> GraphQlReplayAuthorization.verify("actor-1", "tenant-1", principal, false)) - .isInstanceOf(GraphQlReplayAuthorizationException.class); - } - - @Test - void replayDurabilityIsNotClaimedByGraphQlItself() { - assertThat(GraphQlReplaySource.class.isInterface()).isTrue(); - assertThat(GraphQlReplayPosition.class.getRecordComponents()) - .extracting(java.lang.reflect.RecordComponent::getName) - .containsExactly("sequence"); - } -} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/rsocket/GraphQlRSocketRoutePolicyTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/rsocket/GraphQlRSocketRoutePolicyTest.java deleted file mode 100644 index 9a72838b..00000000 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/rsocket/GraphQlRSocketRoutePolicyTest.java +++ /dev/null @@ -1,95 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.rsocket; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedCapability; -import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedCapabilityDisabledException; -import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedFeatureFlags; -import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedModuleGuard; -import dev.caskeleton.adapter.inbound.graphql.error.GraphQlErrorContext; -import dev.caskeleton.adapter.inbound.graphql.error.GraphQlWireError; -import dev.caskeleton.adapter.inbound.graphql.policy.GraphQlOperationType; -import java.util.Set; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -/** RSocket experimental transport (Advanced plan Task 16). */ -@Tag("graphql-advanced") -class GraphQlRSocketRoutePolicyTest { - - @Test - void rejectsUnknownRoute() { - var policy = new GraphQlRSocketRoutePolicy(Set.of("graphql")); - - assertThatThrownBy(() -> policy.requireAllowed("admin.raw")) - .isInstanceOf(GraphQlRSocketRouteRejectedException.class); - } - - @Test - void queriesAreRequestResponseAndSubscriptionsAreRequestStream() { - assertThat(GraphQlRSocketCapability.forOperation(GraphQlOperationType.QUERY)) - .isEqualTo(GraphQlRSocketCapability.REQUEST_RESPONSE); - assertThat(GraphQlRSocketCapability.forOperation(GraphQlOperationType.MUTATION)) - .isEqualTo(GraphQlRSocketCapability.REQUEST_RESPONSE); - assertThat(GraphQlRSocketCapability.forOperation(GraphQlOperationType.SUBSCRIPTION)) - .isEqualTo(GraphQlRSocketCapability.REQUEST_STREAM); - assertThat(GraphQlRSocketCapability.publicTransport()).isFalse(); - } - - @Test - void anEnabledTransportMustNameItsConsumers() { - assertThatThrownBy( - () -> new GraphQlRSocketProperties(true, Set.of("graphql"), Set.of(), Set.of())) - .isInstanceOf(IllegalArgumentException.class); - assertThat(GraphQlRSocketProperties.disabled().enabled()).isFalse(); - } - - @Test - void productionActivationRequiresExperimentalApproval() { - var properties = - new GraphQlRSocketProperties( - true, - Set.of("graphql"), - Set.of("message/x.rsocket.authentication.v0"), - Set.of("pricing")); - var flags = GraphQlAdvancedFeatureFlags.enabling(GraphQlAdvancedCapability.RSOCKET); - - var production = - new GraphQlRSocketAdmission(new GraphQlAdvancedModuleGuard(flags, true), properties); - assertThatThrownBy(() -> production.accept("graphql", GraphQlOperationType.QUERY)) - .isInstanceOf(GraphQlAdvancedCapabilityDisabledException.class); - - var approved = - new GraphQlRSocketAdmission( - new GraphQlAdvancedModuleGuard(flags.withExperimentalApproval(), true), properties); - assertThat(approved.accept("graphql", GraphQlOperationType.QUERY)) - .isEqualTo(GraphQlRSocketCapability.REQUEST_RESPONSE); - assertThat(approved.enabled()).isTrue(); - } - - @Test - void metadataMimeTypesAndAuthenticationAreAllowlisted() { - var authentication = - new GraphQlRSocketAuthentication(Set.of("message/x.rsocket.authentication.v0")); - - assertThatCode( - () -> authentication.requireAllowedMetadata("message/x.rsocket.authentication.v0")) - .doesNotThrowAnyException(); - assertThatThrownBy(() -> authentication.requireAllowedMetadata("application/octet-stream")) - .isInstanceOf(GraphQlRSocketRouteRejectedException.class); - assertThatThrownBy(() -> authentication.requireAuthenticated(false)) - .isInstanceOf(GraphQlRSocketRouteRejectedException.class); - } - - @Test - void errorsAreMaskedExactlyAsOverHttp() { - GraphQlWireError error = - GraphQlRSocketErrorMapper.defaults() - .map(new RuntimeException("select secret from users"), GraphQlErrorContext.test()); - - assertThat(error.message()).isEqualTo(GraphQlWireError.OPAQUE_MESSAGE); - assertThat(error.extensions()).containsKey("executionId"); - } -} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/security/GraphQlWebSocketAuthenticationInterceptorTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/security/GraphQlWebSocketAuthenticationInterceptorTest.java deleted file mode 100644 index 78dd962d..00000000 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/security/GraphQlWebSocketAuthenticationInterceptorTest.java +++ /dev/null @@ -1,78 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.security; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.time.Instant; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -/** WebSocket authentication expiry and revocation lifecycle (Advanced plan Task 6). */ -@Tag("graphql-advanced") -class GraphQlWebSocketAuthenticationInterceptorTest { - - private static final Instant NOW = Instant.parse("2026-08-12T00:00:00Z"); - - @Test - void expiredCredentialClosesConnection() { - var expiry = new GraphQlWebSocketCredentialExpiry(Instant.parse("2026-08-12T00:00:00Z")); - - assertThat(expiry.isExpired(Instant.parse("2026-08-12T00:00:01Z"))).isTrue(); - } - - @Test - void aConnectionWithNoVerifiedIdentityIsRefused() { - var interceptor = - new GraphQlWebSocketAuthenticationInterceptor(new GraphQlWebSocketRevocationSignal()); - - assertThatThrownBy(() -> interceptor.onConnectionInit(null)) - .isInstanceOf(GraphQlWebSocketAuthenticationException.class) - .satisfies( - failure -> - assertThat(((GraphQlWebSocketAuthenticationException) failure).closeReason()) - .isEqualTo(GraphQlWebSocketCloseReason.AUTHENTICATION_FAILED)); - } - - @Test - void expiryAndRevocationBothCloseTheConnection() { - var revocation = new GraphQlWebSocketRevocationSignal(); - var interceptor = new GraphQlWebSocketAuthenticationInterceptor(revocation); - var principal = new GraphQlWebSocketPrincipal("actor-1", "tenant-1", NOW.plusSeconds(60)); - - assertThat(interceptor.closeReason(principal, NOW)).isEmpty(); - assertThat(interceptor.closeReason(principal, NOW.plusSeconds(61))) - .contains(GraphQlWebSocketCloseReason.CREDENTIAL_EXPIRED); - - revocation.revoke("actor-1"); - assertThat(interceptor.closeReason(principal, NOW)) - .contains(GraphQlWebSocketCloseReason.AUTHORIZATION_REVOKED); - revocation.clear("actor-1"); - assertThat(interceptor.closeReason(principal, NOW)).isEmpty(); - } - - @Test - void theIdentityIsPinnedForTheConnectionsWholeLife() { - var interceptor = - new GraphQlWebSocketAuthenticationInterceptor(new GraphQlWebSocketRevocationSignal()); - var connection = new GraphQlWebSocketPrincipal("actor-1", "tenant-1", null); - - assertThatThrownBy( - () -> - interceptor.requirePinnedIdentity( - connection, new GraphQlWebSocketPrincipal("actor-1", "tenant-2", null))) - .isInstanceOf(GraphQlWebSocketAuthenticationException.class); - } - - @Test - void thePrincipalCarriesFingerprintsRatherThanRawIdentifiers() { - assertThat(GraphQlWebSocketPrincipal.class.getRecordComponents()) - .extracting(java.lang.reflect.RecordComponent::getName) - .containsExactly("actorFingerprint", "tenantFingerprint", "expiresAt"); - } - - @Test - void sensitiveSubscriptionsCanReAuthorizePerEvent() { - assertThat(GraphQlSubscriptionAuthorizationPolicy.PER_EVENT.revalidatePerEvent()).isTrue(); - assertThat(GraphQlSubscriptionAuthorizationPolicy.ON_SUBSCRIBE.revalidatePerEvent()).isFalse(); - } -} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/springdata/GraphQlRepositoryExposureValidatorTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/springdata/GraphQlRepositoryExposureValidatorTest.java deleted file mode 100644 index abd19d39..00000000 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/springdata/GraphQlRepositoryExposureValidatorTest.java +++ /dev/null @@ -1,214 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.springdata; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.util.Set; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * The allowlist that stops a persistence annotation from publishing an API. - * - *

Spring's {@code @GraphQlRepository} registers a data fetcher for every annotated repository it - * finds. Without this, the set of exposed fields is whatever somebody annotated — a decision made - * in a persistence class, by whoever was working on persistence, and reviewed as a persistence - * change. - */ -class GraphQlRepositoryExposureValidatorTest { - - private static final GraphQlRepositoryExposure ORDERS = - new GraphQlRepositoryExposure("OrderRepository", "Query.orders"); - - private static GraphQlRepositoryAllowlist allowlistWith( - GraphQlRepositoryArgumentPolicy arguments, - GraphQlRepositoryPaginationPolicy pagination, - GraphQlRepositoryProjectionPolicy projection) { - return GraphQlRepositoryAllowlist.builder() - .expose(ORDERS, arguments, pagination, projection) - .build(); - } - - private static GraphQlRepositoryProjectionPolicy projection() { - return new GraphQlRepositoryProjectionPolicy( - Set.of("OrderSummaryProjection"), Set.of("OrderEntity")); - } - - @Test - @DisplayName("an unregistered repository is refused") - void unregisteredRepositoryIsRejected() { - GraphQlRepositoryExposureValidator validator = - new GraphQlRepositoryExposureValidator(GraphQlRepositoryAllowlist.empty()); - - assertThatThrownBy(() -> validator.verify(ORDERS)) - .isInstanceOf(GraphQlRepositoryExposureRejectedException.class) - .hasMessageContaining("not by an annotation on a persistence class"); - } - - @Test - @DisplayName("the same repository at an unregistered coordinate is still refused") - void coordinateIsPartOfTheDecision() { - // Spring binds a repository to whatever coordinate its return type matches, so the same - // repository reached from two fields is two exposures with two audiences. - GraphQlRepositoryExposureValidator validator = - new GraphQlRepositoryExposureValidator( - allowlistWith( - GraphQlRepositoryArgumentPolicy.none(), - new GraphQlRepositoryPaginationPolicy(true, 50), - projection())); - - assertThat(validator.verify(ORDERS)).isNotNull(); - assertThatThrownBy( - () -> - validator.verify( - new GraphQlRepositoryExposure("OrderRepository", "Query.allOrders"))) - .isInstanceOf(GraphQlRepositoryExposureRejectedException.class); - } - - @Test - @DisplayName("returning the entity is refused, however it is reached") - void entityReturnIsRefused() { - // The rule that keeps this compatibility path from becoming a database export: every column - // published, and a rename in the database a breaking change for every client. - GraphQlRepositoryExposureValidator validator = - new GraphQlRepositoryExposureValidator( - allowlistWith( - GraphQlRepositoryArgumentPolicy.none(), - new GraphQlRepositoryPaginationPolicy(true, 50), - projection())); - - assertThatThrownBy(() -> validator.verifyRequest(ORDERS, Set.of(), Set.of(), 10, "OrderEntity")) - .isInstanceOf(GraphQlRepositoryExposureRejectedException.class) - .hasMessageContaining("publishes the persistence model as an API"); - validator.verifyRequest(ORDERS, Set.of(), Set.of(), 10, "OrderSummaryProjection"); - } - - @Test - @DisplayName("a filter the coordinate did not register is refused") - void unregisteredFilterIsRefused() { - // A query-by-example fetcher derives its predicate from whatever arrives, and the binder - // resolves against the entity — so an un-allowlisted argument filters on columns the schema - // never published. - GraphQlRepositoryExposureValidator validator = - new GraphQlRepositoryExposureValidator( - allowlistWith( - new GraphQlRepositoryArgumentPolicy(Set.of("status"), Set.of("placedAt")), - new GraphQlRepositoryPaginationPolicy(true, 50), - projection())); - - validator.verifyRequest( - ORDERS, Set.of("status"), Set.of("placedAt"), 10, "OrderSummaryProjection"); - assertThatThrownBy( - () -> - validator.verifyRequest( - ORDERS, Set.of("internalCostBasis"), Set.of(), 10, "OrderSummaryProjection")) - .isInstanceOf(GraphQlRepositoryExposureRejectedException.class) - .hasMessageContaining("filter:internalCostBasis"); - } - - @Test - @DisplayName("filter and sort are allowlisted separately") - void filterAndSortAreSeparate() { - // They read alike and behave differently under load: a filter on an unindexed column is one - // slow query, a sort on one is a full table sort on every page. - GraphQlRepositoryExposureValidator validator = - new GraphQlRepositoryExposureValidator( - allowlistWith( - new GraphQlRepositoryArgumentPolicy(Set.of("status"), Set.of()), - new GraphQlRepositoryPaginationPolicy(true, 50), - projection())); - - assertThatThrownBy( - () -> - validator.verifyRequest( - ORDERS, Set.of("status"), Set.of("status"), 10, "OrderSummaryProjection")) - .isInstanceOf(GraphQlRepositoryExposureRejectedException.class) - .hasMessageContaining("sort:status"); - } - - @Test - @DisplayName("every violation is reported at once") - void violationsAreReportedTogether() { - GraphQlRepositoryExposureValidator validator = - new GraphQlRepositoryExposureValidator( - allowlistWith( - GraphQlRepositoryArgumentPolicy.none(), - new GraphQlRepositoryPaginationPolicy(true, 20), - projection())); - - assertThatThrownBy( - () -> validator.verifyRequest(ORDERS, Set.of("a"), Set.of("b"), 500, "OrderEntity")) - .isInstanceOf(GraphQlRepositoryExposureRejectedException.class) - .hasMessageContaining("filter:a") - .hasMessageContaining("sort:b") - .hasMessageContaining("page size 500") - .hasMessageContaining("not an approved projection"); - } - - @Test - @DisplayName("a page size beyond the coordinate's limit is refused") - void oversizedPageIsRefused() { - GraphQlRepositoryPaginationPolicy policy = new GraphQlRepositoryPaginationPolicy(true, 50); - - assertThat(policy.permits(50)).isTrue(); - assertThat(policy.permits(51)).isFalse(); - assertThat(policy.permits(0)).isFalse(); - } - - @Test - @DisplayName("a page size that turns a query into a bulk export is refused at configuration") - void bulkExportPageSizeIsRefused() { - assertThatThrownBy(() -> new GraphQlRepositoryPaginationPolicy(true, 5_000)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("designed for it"); - } - - @Test - @DisplayName("a coordinate with no approved projection is refused at configuration") - void projectionlessCoordinateIsRefused() { - // It could only return the entity, which is the one thing the policy exists to prevent. - assertThatThrownBy(() -> new GraphQlRepositoryProjectionPolicy(Set.of(), Set.of("OrderEntity"))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("this policy exists to prevent"); - } - - @Test - @DisplayName("two registrations for one coordinate are refused") - void duplicateRegistrationIsRefused() { - assertThatThrownBy( - () -> - GraphQlRepositoryAllowlist.builder() - .expose( - ORDERS, - GraphQlRepositoryArgumentPolicy.none(), - new GraphQlRepositoryPaginationPolicy(true, 20), - projection()) - .expose( - ORDERS, - GraphQlRepositoryArgumentPolicy.none(), - new GraphQlRepositoryPaginationPolicy(true, 200), - projection())) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("silently decide the coordinate's limits"); - } - - @Test - @DisplayName("nothing is exposed until a deployment says so") - void nothingIsExposedByDefault() { - GraphQlRepositoryAllowlist empty = GraphQlRepositoryAllowlist.empty(); - - assertThat(empty.size()).isZero(); - assertThat(empty.contains("OrderRepository")).isFalse(); - assertThat(new GraphQlRepositoryExposureValidator(empty).anyExposure()).isFalse(); - } - - @Test - @DisplayName("an exposure names a repository and a Type.field coordinate") - void exposureShapeIsChecked() { - assertThatThrownBy(() -> new GraphQlRepositoryExposure("OrderRepository", "orders")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("Type.field"); - assertThatThrownBy(() -> new GraphQlRepositoryExposure(" ", "Query.orders")) - .isInstanceOf(IllegalArgumentException.class); - } -} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/sse/GraphQlSseConnectionPolicyTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/sse/GraphQlSseConnectionPolicyTest.java deleted file mode 100644 index c66d4a6c..00000000 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/sse/GraphQlSseConnectionPolicyTest.java +++ /dev/null @@ -1,99 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.sse; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedCapability; -import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedCapabilityDisabledException; -import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedFeatureFlags; -import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedModuleGuard; -import dev.caskeleton.adapter.inbound.graphql.advanced.subscription.GraphQlSubscriptionTermination; -import java.time.Clock; -import java.time.Duration; -import java.time.Instant; -import java.time.ZoneOffset; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -/** SSE distinct-connection subscription transport (Advanced plan Task 9). */ -@Tag("graphql-advanced") -class GraphQlSseConnectionPolicyTest { - - private static final Instant NOW = Instant.parse("2026-08-12T00:00:00Z"); - private static final Clock CLOCK = Clock.fixed(NOW, ZoneOffset.UTC); - - @Test - void acceptsOnlySubscriptionOperation() { - var policy = GraphQlSseConnectionPolicy.standard(); - - assertThat(policy.supports("subscription")).isTrue(); - assertThat(policy.supports("query")).isFalse(); - } - - @Test - void aQueryOverSseIsRejected() { - assertThatThrownBy(() -> GraphQlSseConnectionPolicy.standard().requireSubscription("query")) - .isInstanceOf(GraphQlSseRejectedException.class); - } - - @Test - void oneConnectionPerSubscriptionIsExplicitInTheCapacityModel() { - assertThat(GraphQlSseConnectionPolicy.standard().connectionsRequiredFor(5)).isEqualTo(5); - } - - @Test - void theHeartbeatMustBeShorterThanTheIdleTimeout() { - assertThatThrownBy( - () -> - new GraphQlSseProperties( - Duration.ofMinutes(2), Duration.ofMinutes(1), Duration.ofHours(1))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("times out between beats"); - } - - @Test - void aKeepAliveIsDueOnceTheIntervalElapses() { - var heartbeat = new GraphQlSseHeartbeat(Duration.ofSeconds(15), NOW); - - assertThat(heartbeat.due(NOW.plusSeconds(14))).isFalse(); - assertThat(heartbeat.due(NOW.plusSeconds(15))).isTrue(); - heartbeat.recordWrite(NOW.plusSeconds(15)); - assertThat(heartbeat.due(NOW.plusSeconds(20))).isFalse(); - } - - @Test - void idleAndMaximumDurationBothEndTheStream() { - var termination = new GraphQlSseTermination(GraphQlSseProperties.defaults(), NOW); - - assertThat(termination.terminationReason(NOW.plusSeconds(10), NOW.plusSeconds(10))).isEmpty(); - assertThat(termination.terminationReason(NOW.plusSeconds(120), NOW)) - .contains(GraphQlSubscriptionTermination.COMPLETED); - assertThat( - termination.terminationReason( - NOW.plus(Duration.ofHours(2)), NOW.plus(Duration.ofHours(2)))) - .contains(GraphQlSubscriptionTermination.SERVER_DRAINING); - } - - @Test - void theCapabilityFlagGovernsWhetherSseServesAtAll() { - var disabled = - new GraphQlSseAdmission( - new GraphQlAdvancedModuleGuard(GraphQlAdvancedFeatureFlags.disabled()), - GraphQlSseProperties.defaults(), - CLOCK); - assertThatThrownBy(() -> disabled.open("subscription", "application/json")) - .isInstanceOf(GraphQlAdvancedCapabilityDisabledException.class); - - var enabled = - new GraphQlSseAdmission( - new GraphQlAdvancedModuleGuard( - GraphQlAdvancedFeatureFlags.enabling(GraphQlAdvancedCapability.SSE_SUBSCRIPTION)), - GraphQlSseProperties.defaults(), - CLOCK); - assertThatCode(() -> enabled.open("subscription", "application/json")) - .doesNotThrowAnyException(); - assertThatThrownBy(() -> enabled.open("subscription", "text/plain")) - .isInstanceOf(GraphQlSseRejectedException.class); - } -} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/subscription/GraphQlSubscriptionBufferPolicyTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/subscription/GraphQlSubscriptionBufferPolicyTest.java deleted file mode 100644 index 52139e00..00000000 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/subscription/GraphQlSubscriptionBufferPolicyTest.java +++ /dev/null @@ -1,116 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.subscription; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.util.Map; -import java.util.concurrent.atomic.AtomicBoolean; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -/** Subscription source SPI and bounded backpressure (Advanced plan Task 7). */ -@Tag("graphql-advanced") -class GraphQlSubscriptionBufferPolicyTest { - - @Test - void defaultPolicyTerminatesSlowConsumer() { - var policy = GraphQlSubscriptionBufferPolicy.defaultPolicy(); - - assertThat(policy.slowConsumerPolicy()).isEqualTo(GraphQlSlowConsumerPolicy.TERMINATE); - assertThat(policy.maximumBufferedEvents()).isGreaterThan(0); - } - - @Test - void aSlowConsumerIsTerminatedRatherThanSilentlyLosingEvents() { - var dispatcher = - new GraphQlSubscriptionDispatcher( - new GraphQlSubscriptionBufferPolicy(1, 1_048_576, GraphQlSlowConsumerPolicy.TERMINATE)); - - assertThat(dispatcher.offer(event(1))).isEmpty(); - assertThat(dispatcher.offer(event(2))).contains(GraphQlSubscriptionTermination.SLOW_CONSUMER); - assertThat(dispatcher.droppedEvents()).isZero(); - } - - @Test - void telemetryStreamsMayDropInstead() { - var dispatcher = - new GraphQlSubscriptionDispatcher( - new GraphQlSubscriptionBufferPolicy( - 1, 1_048_576, GraphQlSlowConsumerPolicy.DROP_ALLOWED_FOR_TELEMETRY)); - - assertThat(dispatcher.offer(event(1))).isEmpty(); - assertThat(dispatcher.offer(event(2))).isEmpty(); - assertThat(dispatcher.droppedEvents()).isEqualTo(1); - } - - @Test - void theByteBudgetBindsIndependentlyOfTheEventCount() { - // Room for a thousand events, but not for one event's worth of bytes. - var dispatcher = - new GraphQlSubscriptionDispatcher( - new GraphQlSubscriptionBufferPolicy(1_000, 4, GraphQlSlowConsumerPolicy.TERMINATE)); - - assertThat(event(1).approximateBytes()).isGreaterThan(4); - assertThat(dispatcher.offer(event(1))).contains(GraphQlSubscriptionTermination.SLOW_CONSUMER); - } - - @Test - void acknowledgingAnEventFreesItsBudget() { - var dispatcher = - new GraphQlSubscriptionDispatcher( - new GraphQlSubscriptionBufferPolicy(1, 1_048_576, GraphQlSlowConsumerPolicy.TERMINATE)); - var first = event(1); - dispatcher.offer(first); - - dispatcher.acknowledge(first); - - assertThat(dispatcher.bufferedEvents()).isZero(); - assertThat(dispatcher.bufferedBytes()).isZero(); - assertThat(dispatcher.offer(event(2))).isEmpty(); - } - - @Test - void cancellationReachesTheUpstreamSource() { - var cancellation = new GraphQlSubscriptionCancellation(); - AtomicBoolean sourceStopped = new AtomicBoolean(); - cancellation.onCancel(() -> sourceStopped.set(true)); - - cancellation.cancel(); - - assertThat(cancellation.cancelled()).isTrue(); - assertThat(sourceStopped).isTrue(); - } - - @Test - void aLateUpstreamRegistrationStopsImmediately() { - var cancellation = new GraphQlSubscriptionCancellation(); - cancellation.cancel(); - AtomicBoolean sourceStopped = new AtomicBoolean(); - - cancellation.onCancel(() -> sourceStopped.set(true)); - - assertThat(sourceStopped).isTrue(); - } - - @Test - void bufferBoundsMustBePositive() { - assertThatThrownBy( - () -> - new GraphQlSubscriptionBufferPolicy( - 0, 1_048_576, GraphQlSlowConsumerPolicy.TERMINATE)) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void eventsAreGraphQlDtosCarryingASourceSequence() { - var event = event(7); - - assertThat(event.sequence()).isEqualTo(7); - assertThat(event.payload()).containsKey("id"); - assertThat(event.approximateBytes()).isPositive(); - } - - private static GraphQlSubscriptionEvent event(long sequence) { - return new GraphQlSubscriptionEvent(Map.of("id", "o-" + sequence), sequence); - } -} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/subscription/GraphQlSubscriptionExecutionPolicyTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/subscription/GraphQlSubscriptionExecutionPolicyTest.java deleted file mode 100644 index f58b33a1..00000000 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/advanced/subscription/GraphQlSubscriptionExecutionPolicyTest.java +++ /dev/null @@ -1,198 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.subscription; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.time.Duration; -import java.time.Instant; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -/** Subscription ordering, cancellation and shutdown drain (Advanced plan Task 8). */ -@Tag("graphql-advanced") -class GraphQlSubscriptionExecutionPolicyTest { - - private static final Instant NOW = Instant.parse("2026-08-12T00:00:00Z"); - - @Test - void orderedProfileRequestsGraphQlJavaOrderingFlag() { - var policy = GraphQlSubscriptionExecutionPolicy.ordered(); - - assertThat(policy.profile()).isEqualTo(GraphQlSubscriptionOrderingProfile.ORDERED); - assertThat(policy.keepSourceOrder()).isTrue(); - } - - @Test - void lowLatencyDoesNotPromiseSourceOrder() { - var policy = GraphQlSubscriptionExecutionPolicy.lowLatency(); - - assertThat(policy.profile()).isEqualTo(GraphQlSubscriptionOrderingProfile.LOW_LATENCY); - assertThat(policy.keepSourceOrder()).isFalse(); - } - - @Test - void theProfileAndTheOrderingFlagCannotDisagree() { - assertThatThrownBy( - () -> - new GraphQlSubscriptionExecutionPolicy( - GraphQlSubscriptionOrderingProfile.ORDERED, false)) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void drainingRefusesNewSubscriptionsAndWaitsForExisting() { - var coordinator = new GraphQlSubscriptionDrainCoordinator(Duration.ofSeconds(30)); - var lease = coordinator.register(); - - coordinator.startDraining(NOW); - - assertThatThrownBy(coordinator::register) - .isInstanceOf(GraphQlSubscriptionDrainingException.class); - assertThat(coordinator.drained(NOW)).isFalse(); - lease.close(); - assertThat(coordinator.drained(NOW)).isTrue(); - assertThat(coordinator.phase()).isEqualTo(GraphQlSubscriptionDrainPhase.CLOSED); - } - - @Test - void aLeaseReleasedTwiceDoesNotDecrementSomeoneElsesSubscription() { - var coordinator = new GraphQlSubscriptionDrainCoordinator(Duration.ofSeconds(30)); - var first = coordinator.register(); - coordinator.register(); - - first.close(); - first.close(); - - assertThat(first.released()).isTrue(); - assertThat(coordinator.activeSubscriptions()) - .as("a double release must not drop the other subscription's claim") - .isEqualTo(1); - } - - @Test - void drainingWithNothingActiveClosesImmediately() { - var coordinator = new GraphQlSubscriptionDrainCoordinator(Duration.ofSeconds(30)); - - coordinator.startDraining(NOW); - - assertThat(coordinator.phase()).isEqualTo(GraphQlSubscriptionDrainPhase.CLOSED); - assertThat(coordinator.drained(NOW)).isTrue(); - } - - @Test - void aSecondDrainSignalCannotExtendTheWindowItBounds() { - var coordinator = new GraphQlSubscriptionDrainCoordinator(Duration.ofSeconds(30)); - coordinator.register(); - - coordinator.startDraining(NOW); - coordinator.startDraining(NOW.plusSeconds(60)); - - assertThat(coordinator.drained(NOW.plusSeconds(31))) - .as("the deadline is measured from the first signal, not the last") - .isTrue(); - } - - @Test - void noSubscriptionIsAdmittedAfterDrainingBeginsUnderContention() throws Exception { - var coordinator = new GraphQlSubscriptionDrainCoordinator(Duration.ofSeconds(30)); - var admitted = new java.util.concurrent.atomic.AtomicInteger(); - var refused = new java.util.concurrent.atomic.AtomicInteger(); - var start = new java.util.concurrent.CountDownLatch(1); - var done = new java.util.concurrent.CountDownLatch(33); - var leases = new java.util.concurrent.ConcurrentLinkedQueue(); - - for (int index = 0; index < 32; index++) { - Thread.ofVirtual() - .start( - () -> { - try { - start.await(); - leases.add(coordinator.register()); - admitted.incrementAndGet(); - } catch (GraphQlSubscriptionDrainingException refusal) { - refused.incrementAndGet(); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - } finally { - done.countDown(); - } - }); - } - Thread.ofVirtual() - .start( - () -> { - try { - start.await(); - coordinator.startDraining(NOW); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - } finally { - done.countDown(); - } - }); - - start.countDown(); - assertThat(done.await(10, java.util.concurrent.TimeUnit.SECONDS)).isTrue(); - - assertThat(admitted.get() + refused.get()).isEqualTo(32); - assertThat(coordinator.activeSubscriptions()) - .as( - "every admitted registration is counted; a lost increment is a subscription that " - + "streams while the node believes it has drained") - .isEqualTo(admitted.get()); - assertThat(coordinator.draining()).isTrue(); - - // The deadline is readable from every thread the moment draining is visible. - assertThatCode(() -> coordinator.drained(NOW)).doesNotThrowAnyException(); - leases.forEach(GraphQlSubscriptionLease::close); - assertThat(coordinator.drained(NOW)).isTrue(); - } - - @Test - void aStuckSubscriptionCannotDelayShutdownForever() { - var coordinator = new GraphQlSubscriptionDrainCoordinator(Duration.ofSeconds(30)); - coordinator.register(); - coordinator.startDraining(NOW); - - assertThat(coordinator.drained(NOW.plusSeconds(29))).isFalse(); - assertThat(coordinator.drained(NOW.plusSeconds(31))).isTrue(); - assertThat(coordinator.activeSubscriptions()).isEqualTo(1); - assertThat(coordinator.draining()).isTrue(); - } - - @Test - void registrationIsAllowedUntilDrainingStarts() { - var coordinator = new GraphQlSubscriptionDrainCoordinator(Duration.ofSeconds(1)); - - assertThatCode(coordinator::register).doesNotThrowAnyException(); - assertThat(coordinator.phase()).isEqualTo(GraphQlSubscriptionDrainPhase.ACCEPTING); - assertThat(coordinator.drained(NOW)).isFalse(); - } - - @Test - void theLifecycleStatesDistinguishAuthenticatingFromStreaming() { - assertThat(GraphQlSubscriptionState.STREAMING.deliverable()).isTrue(); - assertThat(GraphQlSubscriptionState.AUTHENTICATING.deliverable()).isFalse(); - assertThat(GraphQlSubscriptionState.acceptingSubscriptions()) - .containsExactlyInAnyOrder( - GraphQlSubscriptionState.READY, - GraphQlSubscriptionState.SUBSCRIBED, - GraphQlSubscriptionState.STREAMING); - } - - @Test - void metricsCountTerminationsByBoundedReason() { - var metrics = new GraphQlSubscriptionMetrics(); - metrics.recordOpened(); - metrics.recordDelivered(); - metrics.recordDropped(); - metrics.recordTermination(GraphQlSubscriptionTermination.SLOW_CONSUMER); - - assertThat(metrics.opened()).isEqualTo(1); - assertThat(metrics.eventsDelivered()).isEqualTo(1); - assertThat(metrics.eventsDropped()).isEqualTo(1); - assertThat(metrics.terminations(GraphQlSubscriptionTermination.SLOW_CONSUMER)).isEqualTo(1); - assertThat(metrics.terminations(GraphQlSubscriptionTermination.COMPLETED)).isZero(); - } -} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/api/GraphQlIdentifiersTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/api/GraphQlIdentifiersTest.java index de73f5a1..14743487 100644 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/api/GraphQlIdentifiersTest.java +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/api/GraphQlIdentifiersTest.java @@ -64,13 +64,4 @@ class GraphQlIdentifiersTest { void schemaCoordinateRendersACanonicalBoundedLabel() { assertThat(GraphQlSchemaCoordinate.parse("Query.orders").value()).isEqualTo("Query.orders"); } - - @Test - void clientProfileNameIsABoundedUppercaseCatalogName() { - assertThat(GraphQlClientProfileName.of("FIRST_PARTY").value()).isEqualTo("FIRST_PARTY"); - assertThat(GraphQlClientProfileName.designCatalog()) - .contains("PUBLIC", "PARTNER", "FIRST_PARTY", "ADMIN", "INTROSPECTION"); - assertThatThrownBy(() -> GraphQlClientProfileName.of("first-party")) - .isInstanceOf(IllegalArgumentException.class); - } } diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/architecture/GraphQlControllerInspectorTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/architecture/GraphQlControllerInspectorTest.java deleted file mode 100644 index d6e0f92c..00000000 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/architecture/GraphQlControllerInspectorTest.java +++ /dev/null @@ -1,117 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.architecture; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.graphql.architecture.fixture.compliant.OrderGraphQlController; -import dev.caskeleton.adapter.inbound.graphql.architecture.fixture.compliant.OrderView; -import java.lang.reflect.Method; -import java.util.Map; -import org.reactivestreams.Publisher; -import org.springframework.graphql.data.method.annotation.QueryMapping; -import org.springframework.graphql.data.method.annotation.SubscriptionMapping; - -/** Resolver return and input type inspection (Stable plan Task 23). */ -class GraphQlControllerInspectorTest { - - @org.junit.jupiter.api.Test - void mapReturnTypeIsRejected() throws Exception { - Method method = BadController.class.getDeclaredMethod("query"); - - assertThatThrownBy(() -> GraphQlControllerInspector.inspect(method)) - .isInstanceOf(GraphQlControllerContractException.class); - } - - @org.junit.jupiter.api.Test - void transportReturnTypesAreAccepted() throws Exception { - assertThatCode( - () -> - GraphQlControllerInspector.inspect( - OrderGraphQlController.class.getDeclaredMethod("order", String.class))) - .doesNotThrowAnyException(); - assertThat(GraphQlReturnTypePolicy.allowed(OrderView.class)).isTrue(); - } - - @org.junit.jupiter.api.Test - void persistenceMappedReturnTypesAreRejectedWithoutAJpaDependency() { - assertThat(GraphQlReturnTypePolicy.allowed(PersistedOrder.class)).isFalse(); - assertThat(GraphQlReturnTypePolicy.rejection(PersistedOrder.class)) - .contains("persistence-mapped type"); - } - - @org.junit.jupiter.api.Test - void inputBindingToAPersistenceTypeIsRejected() { - assertThat(GraphQlInputTypePolicy.allowed(PersistedOrder.class)).isFalse(); - assertThat(GraphQlInputTypePolicy.rejection(Map.class)) - .contains("bypasses GraphQL input validation"); - assertThat(GraphQlInputTypePolicy.allowed(String.class)).isTrue(); - } - - @org.junit.jupiter.api.Test - void publisherIsAllowedOnlyOnSubscriptions() throws Exception { - assertThatThrownBy( - () -> - GraphQlControllerInspector.inspect( - BadController.class.getDeclaredMethod("streamingQuery"))) - .isInstanceOf(GraphQlControllerContractException.class) - // A stream, specifically. The rule used to say "Publisher", which also covered `Mono` — - // a single-value container Spring for GraphQL supports on queries. - .hasMessageContaining("multi-value publisher outside a subscription"); - - assertThatCode( - () -> - GraphQlControllerInspector.inspect( - GoodSubscriptionController.class.getDeclaredMethod("orderEvents"))) - .doesNotThrowAnyException(); - } - - @org.junit.jupiter.api.Test - void violationsReportTheSchemaCoordinateAndJavaMethod() throws Exception { - Method method = BadController.class.getDeclaredMethod("query"); - - assertThat(GraphQlControllerInspector.violations(method)) - .singleElement() - .asString() - .contains("BadController#query"); - assertThat(GraphQlControllerInspector.coordinateOf(method)).isEqualTo("BadController#query"); - assertThat(GraphQlControllerInspector.isResolver(method)).isTrue(); - } - - /** A resolver written the way the boundary forbids. */ - static class BadController { - - @QueryMapping - Map query() { - return Map.of(); - } - - @QueryMapping - Publisher streamingQuery() { - return subscriber -> {}; - } - } - - /** A subscription resolver, where a publisher is the correct return type. */ - static class GoodSubscriptionController { - - @SubscriptionMapping - Publisher orderEvents() { - return subscriber -> {}; - } - } - - /** - * Stands in for a JPA entity without adding a JPA dependency to an inbound adapter. - * - *

The rule matches the annotation's simple name as well as the known fully qualified ones, - * which is what lets this leaf forbid persistence types without depending on them. - */ - @Entity - static class PersistedOrder {} - - /** A persistence mapping annotation standing in for {@code jakarta.persistence.Entity}. */ - @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME) - @java.lang.annotation.Target(java.lang.annotation.ElementType.TYPE) - @interface Entity {} -} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/architecture/GraphQlGeneratedResolverBoundaryTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/architecture/GraphQlGeneratedResolverBoundaryTest.java deleted file mode 100644 index 62b18a7b..00000000 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/architecture/GraphQlGeneratedResolverBoundaryTest.java +++ /dev/null @@ -1,114 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.architecture; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedCapability; -import dev.caskeleton.adapter.inbound.graphql.architecture.fixture.compliant.FindOrderUseCase; -import dev.caskeleton.adapter.inbound.graphql.architecture.fixture.compliant.OrderView; -import dev.caskeleton.adapter.inbound.graphql.architecture.fixture.violating.OrderRepository; -import dev.caskeleton.adapter.inbound.graphql.release.GraphQlStableCapabilityManifest; -import java.util.Arrays; -import java.util.List; -import java.util.Optional; -import org.junit.jupiter.api.Test; -import org.springframework.graphql.data.method.annotation.QueryMapping; - -/** - * A resolver reaches storage through an application use case, or not at all. - * - *

The platform used to ship an Advanced capability that allowlisted Spring Data repositories to - * back GraphQL fields directly, with tests fixing that as correct behaviour. An allowlist does not - * change what the code does: a controller was still calling a repository, which is the second - * canonical hard-stop in {@code AGENTS.md}. A capability flag can make a feature optional; it - * cannot make an architectural rule optional. - */ -class GraphQlGeneratedResolverBoundaryTest { - - @Test - void theRepositoryExposureCapabilityNoLongerExists() { - assertThat(Arrays.stream(GraphQlAdvancedCapability.values()).map(Enum::name)) - .as("an allowlisted repository exposure capability must not be offerable at all") - .doesNotContain("SPRING_DATA_COMPAT"); - assertThat(GraphQlStableCapabilityManifest.ADVANCED).doesNotContain("SPRING_DATA_COMPAT"); - } - - @Test - void repositoryAutoExposureIsDeclaredUnsupported() { - assertThat(GraphQlStableCapabilityManifest.UNSUPPORTED) - .as("removing the code is not enough; the manifest has to say the answer is no") - .contains("SPRING_DATA_REPOSITORY_AUTO_EXPOSURE"); - } - - @Test - void aGeneratedResolverBackedByARepositoryIsRefused() { - assertThatThrownBy( - () -> - GraphQlResolverBoundaryRules.assertNoPersistenceAccess( - List.of(GeneratedRepositoryResolver.class))) - .isInstanceOf(GraphQlControllerContractException.class) - .hasMessageContaining("OrderRepository"); - } - - @Test - void aGeneratedResolverBackedByARepositoryIsRefusedThroughAnyWrapper() { - List violations = - GraphQlResolverBoundaryRules.persistenceViolations( - List.of(GeneratedWrappedRepositoryResolver.class)); - - assertThat(violations) - .as("there is no allowlist left to consult, and a wrapper is not a loophole") - .isNotEmpty(); - } - - @Test - void aGeneratedResolverBackedByAUseCaseIsAccepted() { - assertThat( - GraphQlResolverBoundaryRules.persistenceViolations( - List.of(GeneratedUseCaseResolver.class))) - .isEmpty(); - } - - /** What a generated resolver must never look like. */ - @SuppressWarnings("unused") - static final class GeneratedRepositoryResolver { - - private final OrderRepository orders; - - GeneratedRepositoryResolver(OrderRepository orders) { - this.orders = orders; - } - - @QueryMapping - OrderView order(String id) { - return null; - } - } - - /** The same violation, tidied behind a container. */ - @SuppressWarnings("unused") - static final class GeneratedWrappedRepositoryResolver { - - private final Optional orders; - - GeneratedWrappedRepositoryResolver(Optional orders) { - this.orders = orders; - } - } - - /** The only shape a generated resolver may take. */ - @SuppressWarnings("unused") - static final class GeneratedUseCaseResolver { - - private final FindOrderUseCase findOrder; - - GeneratedUseCaseResolver(FindOrderUseCase findOrder) { - this.findOrder = findOrder; - } - - @QueryMapping - OrderView order(String id) { - return findOrder.find(id); - } - } -} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/architecture/GraphQlResolverBoundaryRulesTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/architecture/GraphQlResolverBoundaryRulesTest.java deleted file mode 100644 index e5adb01d..00000000 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/architecture/GraphQlResolverBoundaryRulesTest.java +++ /dev/null @@ -1,92 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.architecture; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.graphql.architecture.fixture.compliant.OrderGraphQlController; -import dev.caskeleton.adapter.inbound.graphql.architecture.fixture.violating.LeakyGraphQlController; -import dev.caskeleton.adapter.inbound.graphql.scalar.UuidScalar; -import java.util.List; -import org.junit.jupiter.api.Test; - -/** Resolver, DTO and repository boundary rules (Stable plan Task 12). */ -class GraphQlResolverBoundaryRulesTest { - - private static final String COMPLIANT_PACKAGE = - "dev.caskeleton.adapter.inbound.graphql.architecture.fixture.compliant"; - private static final String VIOLATING_PACKAGE = - "dev.caskeleton.adapter.inbound.graphql.architecture.fixture.violating"; - - @Test - void controllerMustNotDependOnEntityManager() { - assertThatCode(() -> GraphQlResolverBoundaryRules.assertNoPersistenceAccess(COMPLIANT_PACKAGE)) - .doesNotThrowAnyException(); - } - - @Test - void repositoryInjectionIntoAResolverIsRejected() { - assertThatThrownBy( - () -> GraphQlResolverBoundaryRules.assertNoPersistenceAccess(VIOLATING_PACKAGE)) - .isInstanceOf(GraphQlControllerContractException.class) - .hasMessageContaining("OrderRepository"); - } - - @Test - void persistenceInfrastructureTypesAreDetectedByName() { - assertThat(GraphQlResolverBoundaryRules.FORBIDDEN_TYPE_NAMES) - .contains("EntityManager", "MongoTemplate", "JdbcTemplate", "DataSource"); - assertThat(GraphQlResolverBoundaryRules.FORBIDDEN_TYPE_SUFFIXES) - .containsExactlyInAnyOrder("Repository", "Dao"); - assertThat(GraphQlResolverBoundaryRules.forbidden(String.class)).isFalse(); - } - - @Test - void aRuleCannotPassByScanningNothing() { - assertThatThrownBy( - () -> GraphQlResolverBoundaryRules.assertNoPersistenceAccess("dev.caskeleton.absent")) - .isInstanceOf(GraphQlControllerContractException.class) - .hasMessageContaining("vacuously"); - } - - @Test - void compliantResolversUseTransportTypesOnly() { - assertThatCode(() -> GraphQlTransportTypeRules.assertTransportTypesOnly(COMPLIANT_PACKAGE)) - .doesNotThrowAnyException(); - } - - @Test - void mapReturnTypeAndTransactionOnAResolverAreRejected() { - assertThatThrownBy(() -> GraphQlTransportTypeRules.assertTransportTypesOnly(VIOLATING_PACKAGE)) - .isInstanceOf(GraphQlControllerContractException.class) - .hasMessageContaining("Map") - .hasMessageContaining("transaction"); - } - - @Test - void rawDataFetchersAreRestrictedToInfrastructurePackages() { - assertThatCode( - () -> - GraphQlTransportTypeRules.assertRawDataFetcherIsInfrastructureOnly( - List.of(OrderGraphQlController.class, UuidScalar.class))) - .doesNotThrowAnyException(); - assertThat(GraphQlTransportTypeRules.infrastructure(UuidScalar.class)).isTrue(); - assertThat(GraphQlTransportTypeRules.infrastructure(LeakyGraphQlController.class)).isFalse(); - } - - @Test - void transactionRuleNamesTheOffendingResolver() throws NoSuchMethodException { - assertThatThrownBy( - () -> - GraphQlControllerTransactionRule.assertNoTransaction( - LeakyGraphQlController.class.getDeclaredMethod("order"))) - .isInstanceOf(GraphQlControllerContractException.class) - .hasMessageContaining("LeakyGraphQlController#order"); - - assertThatCode( - () -> - GraphQlControllerTransactionRule.assertNoTransaction( - OrderGraphQlController.class.getDeclaredMethod("order", String.class))) - .doesNotThrowAnyException(); - } -} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/architecture/GraphQlResolverGenericBoundaryTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/architecture/GraphQlResolverGenericBoundaryTest.java deleted file mode 100644 index 68b6e280..00000000 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/architecture/GraphQlResolverGenericBoundaryTest.java +++ /dev/null @@ -1,189 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.architecture; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.adapter.inbound.graphql.architecture.fixture.compliant.OrderView; -import dev.caskeleton.adapter.inbound.graphql.architecture.fixture.violating.OrderRepository; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.CompletableFuture; -import java.util.stream.Stream; -import org.junit.jupiter.api.Test; -import org.reactivestreams.Publisher; -import org.springframework.graphql.data.method.annotation.QueryMapping; -import org.springframework.graphql.data.method.annotation.SubscriptionMapping; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; - -/** - * What the boundary rules could not see, and what they wrongly refused. - * - *

Both failures came from inspecting the erased type. {@code List} reports {@code - * List} and passed every persistence rule; {@code Mono} reports {@code Mono}, which is a - * {@code Publisher}, and was refused on a query that Spring for GraphQL supports. One rule was - * blind, the other was superstitious, and both looked correct from the signature. - */ -class GraphQlResolverGenericBoundaryTest { - - @Test - void aRepositoryHiddenInsideAGenericIsFound() { - assertThat(GraphQlTypeGraph.referencedTypes(fieldType("repositories"))) - .contains(OrderRepository.class); - assertThat(GraphQlTypeGraph.referencedTypes(fieldType("maybeRepository"))) - .contains(OrderRepository.class); - assertThat(GraphQlTypeGraph.referencedTypes(fieldType("asyncRepository"))) - .contains(OrderRepository.class); - } - - @Test - void aGenericConstructorInjectionOfARepositoryIsAViolation() { - List violations = - GraphQlResolverBoundaryRules.persistenceViolations(List.of(GenericLeak.class)); - - assertThat(violations) - .as("Optional is an injected repository however it is wrapped") - .anySatisfy(violation -> assertThat(violation).contains("OrderRepository")); - } - - @Test - void aCompliantResolverWithGenericsIsNotAViolation() { - assertThat(GraphQlResolverBoundaryRules.persistenceViolations(List.of(GenericCompliant.class))) - .isEmpty(); - } - - @Test - void aQueryMayCompleteAsynchronouslyWithASingleValue() { - assertThat(GraphQlControllerInspector.violations(method(AsyncResolvers.class, "monoQuery"))) - .as("Spring for GraphQL supports Mono on a query; the platform must not refuse it") - .isEmpty(); - assertThat(GraphQlControllerInspector.violations(method(AsyncResolvers.class, "futureQuery"))) - .isEmpty(); - } - - @Test - void aQueryMayNotEmitAStream() { - assertThat(GraphQlControllerInspector.violations(method(AsyncResolvers.class, "fluxQuery"))) - .anySatisfy( - violation -> - assertThat(violation).contains("multi-value publisher outside a subscription")); - assertThat(GraphQlControllerInspector.violations(method(AsyncResolvers.class, "streamQuery"))) - .isNotEmpty(); - } - - @Test - void aSubscriptionMayEmitAStream() { - assertThat( - GraphQlControllerInspector.violations(method(AsyncResolvers.class, "fluxSubscription"))) - .isEmpty(); - } - - @Test - void theAsyncShapeIsClassifiedByWhatItYields() { - assertThat(GraphQlAsyncReturnShape.of(Mono.class)) - .isEqualTo(GraphQlAsyncReturnShape.SINGLE_VALUE); - assertThat(GraphQlAsyncReturnShape.of(CompletableFuture.class)) - .isEqualTo(GraphQlAsyncReturnShape.SINGLE_VALUE); - assertThat(GraphQlAsyncReturnShape.of(Flux.class)) - .isEqualTo(GraphQlAsyncReturnShape.MULTI_VALUE); - assertThat(GraphQlAsyncReturnShape.of(Publisher.class)) - .isEqualTo(GraphQlAsyncReturnShape.MULTI_VALUE); - assertThat(GraphQlAsyncReturnShape.of(OrderView.class)) - .isEqualTo(GraphQlAsyncReturnShape.SYNCHRONOUS); - } - - @Test - void repositoryEvidenceNamesTheStrongestReason() { - assertThat(GraphQlResolverBoundaryRules.repositoryEvidence(OrderRepository.class)) - .isEqualTo("is a repository-named interface"); - assertThat(GraphQlResolverBoundaryRules.repositoryEvidence(OrderView.class)).isNull(); - } - - @Test - void aConcreteClassIsNotARepositoryJustBecauseOfItsName() { - assertThat(GraphQlResolverBoundaryRules.repositoryEvidence(OrderRepositoryView.class)) - .as("a value object outside a persistence package must not be refused on its name alone") - .isNull(); - } - - @Test - void theRecursiveScanReachesSubPackages() { - List> classes = - GraphQlResolverBoundaryRules.classesIn( - "dev.caskeleton.adapter.inbound.graphql.architecture.fixture"); - - assertThat(classes) - .as("the scan used to list direct children only, so every nested package went unchecked") - .contains(OrderRepository.class, OrderView.class); - } - - private static java.lang.reflect.Type fieldType(String name) { - try { - return GenericLeak.class.getDeclaredField(name).getGenericType(); - } catch (NoSuchFieldException ex) { - throw new AssertionError(ex); - } - } - - private static java.lang.reflect.Method method(Class type, String name) { - for (java.lang.reflect.Method candidate : type.getDeclaredMethods()) { - if (candidate.getName().equals(name)) { - return candidate; - } - } - throw new AssertionError("no method " + name); - } - - /** A value object whose name ends in Repository but which is not one. */ - record OrderRepositoryView(String id) {} - - @SuppressWarnings("unused") - static final class GenericLeak { - - private final List repositories = List.of(); - private final Optional maybeRepository = Optional.empty(); - private final Mono asyncRepository = Mono.empty(); - - GenericLeak(Optional injected) { - // Constructor injection through a wrapper is the shape the erased check could not see. - } - } - - @SuppressWarnings("unused") - static final class GenericCompliant { - - private final List views = List.of(); - - GenericCompliant(Mono asyncView) { - // A transport type in a container is still a transport type. - } - } - - @SuppressWarnings("unused") - static final class AsyncResolvers { - - @QueryMapping - Mono monoQuery() { - return Mono.empty(); - } - - @QueryMapping - CompletableFuture futureQuery() { - return CompletableFuture.completedFuture(null); - } - - @QueryMapping - Flux fluxQuery() { - return Flux.empty(); - } - - @QueryMapping - Stream streamQuery() { - return Stream.of(); - } - - @SubscriptionMapping - Flux fluxSubscription() { - return Flux.empty(); - } - } -} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/architecture/fixture/compliant/FindOrderUseCase.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/architecture/fixture/compliant/FindOrderUseCase.java deleted file mode 100644 index 8bb61d73..00000000 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/architecture/fixture/compliant/FindOrderUseCase.java +++ /dev/null @@ -1,12 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.architecture.fixture.compliant; - -/** Application use case a compliant resolver is allowed to depend on. */ -public interface FindOrderUseCase { - - /** - * Finds one order view. - * - * @param orderId external order identity - */ - OrderView find(String orderId); -} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/architecture/fixture/compliant/OrderGraphQlController.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/architecture/fixture/compliant/OrderGraphQlController.java deleted file mode 100644 index a38b669a..00000000 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/architecture/fixture/compliant/OrderGraphQlController.java +++ /dev/null @@ -1,31 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.architecture.fixture.compliant; - -import org.springframework.graphql.data.method.annotation.Argument; -import org.springframework.graphql.data.method.annotation.QueryMapping; -import org.springframework.stereotype.Controller; - -/** A resolver that stays inside the transport boundary: use case in, read model out. */ -@Controller -public class OrderGraphQlController { - - private final FindOrderUseCase findOrder; - - /** - * Creates the resolver. - * - * @param findOrder the Application use case this resolver delegates to - */ - public OrderGraphQlController(FindOrderUseCase findOrder) { - this.findOrder = findOrder; - } - - /** - * Resolves {@code Query.order}. - * - * @param id external order identity - */ - @QueryMapping - public OrderView order(@Argument String id) { - return findOrder.find(id); - } -} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/architecture/fixture/compliant/OrderView.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/architecture/fixture/compliant/OrderView.java deleted file mode 100644 index be295c28..00000000 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/architecture/fixture/compliant/OrderView.java +++ /dev/null @@ -1,9 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.architecture.fixture.compliant; - -/** - * Transport read model a compliant resolver returns. - * - * @param id external order identity - * @param status order status - */ -public record OrderView(String id, String status) {} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/architecture/fixture/violating/LeakyGraphQlController.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/architecture/fixture/violating/LeakyGraphQlController.java deleted file mode 100644 index b8584add..00000000 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/architecture/fixture/violating/LeakyGraphQlController.java +++ /dev/null @@ -1,33 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.architecture.fixture.violating; - -import java.util.Map; -import org.springframework.graphql.data.method.annotation.QueryMapping; -import org.springframework.stereotype.Controller; - -/** - * A resolver that breaks the boundary in three ways at once, used to prove the rules bite. - * - *

It injects a repository, returns an unrestricted map, and opens a transaction in transport - * code. - */ -@Controller -public class LeakyGraphQlController { - - private final OrderRepository orderRepository; - - /** - * Creates the resolver. - * - * @param orderRepository the repository this resolver must not have - */ - public LeakyGraphQlController(OrderRepository orderRepository) { - this.orderRepository = orderRepository; - } - - /** Resolves {@code Query.order} the wrong way. */ - @QueryMapping - @Transactional - public Map order() { - return Map.of("id", orderRepository.findById("o-1")); - } -} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/architecture/fixture/violating/OrderRepository.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/architecture/fixture/violating/OrderRepository.java deleted file mode 100644 index 38bac70c..00000000 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/architecture/fixture/violating/OrderRepository.java +++ /dev/null @@ -1,12 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.architecture.fixture.violating; - -/** Stand-in for a persistence repository a resolver must not reach for directly. */ -public interface OrderRepository { - - /** - * Loads an order row. - * - * @param id primary key - */ - Object findById(String id); -} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/architecture/fixture/violating/Transactional.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/architecture/fixture/violating/Transactional.java deleted file mode 100644 index f91fec9c..00000000 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/architecture/fixture/violating/Transactional.java +++ /dev/null @@ -1,17 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.architecture.fixture.violating; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * A transaction annotation standing in for Spring's or Jakarta's. - * - *

This leaf has no transaction library on its classpath — an inbound adapter should not — so the - * fixture declares its own. That is also the case the rule must catch: the boundary is violated by - * any annotation named {@code Transactional} on transport code, whoever declares it. - */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE, ElementType.METHOD}) -public @interface Transactional {} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlCapabilityActivationTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlCapabilityActivationTest.java new file mode 100644 index 00000000..4126caf2 --- /dev/null +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlCapabilityActivationTest.java @@ -0,0 +1,62 @@ +package dev.caskeleton.adapter.inbound.graphql.autoconfigure; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Arrays; +import org.junit.jupiter.api.Test; +import org.springframework.boot.WebApplicationType; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.annotation.Configuration; +import org.springframework.graphql.ExecutionGraphQlService; +import org.springframework.graphql.execution.GraphQlSource; +import org.springframework.util.ClassUtils; + +/** + * The capability as an application gets it: this module on the classpath, auto-configuration on. + * + *

A real {@code SpringApplication}, because the module's settings and its explicit-off exclusion + * arrive through its environment post-processor, which a context runner never calls. + */ +class GraphQlCapabilityActivationTest { + + @Test + void presentModuleIsOnWithTheModesItNeeds() { + try (ConfigurableApplicationContext context = start("--APP_GRAPHQL_DEPLOYMENT_MODE=LOCAL")) { + assertThat(context.getBeanNamesForType(GraphQlPlatformSettings.class)).hasSize(1); + assertThat(context.getBeanNamesForType(GraphQlSource.class)).hasSize(1); + assertThat(context.getBeanNamesForType(ExecutionGraphQlService.class)).hasSize(1); + } + } + + @Test + void switchedOffHoldsNeitherThePlatformNorTheFrameworksGraphQl() { + try (ConfigurableApplicationContext context = start("--APP_GRAPHQL_ENABLED=false")) { + assertThat(context.getBeanNamesForType(GraphQlSource.class)).isEmpty(); + assertThat(context.getBeanNamesForType(ExecutionGraphQlService.class)).isEmpty(); + assertThat( + Arrays.stream(context.getBeanDefinitionNames()) + .map(name -> context.getBeanFactory().getType(name, false)) + .filter(type -> type != null && type != Application.class) + .map(ClassUtils::getUserClass) + .map(Class::getName) + .filter( + name -> + name.startsWith("dev.caskeleton.adapter.inbound.graphql.") + || name.startsWith("org.springframework.boot.graphql."))) + .isEmpty(); + } + } + + private static ConfigurableApplicationContext start(String... arguments) { + return new SpringApplicationBuilder(Application.class) + .web(WebApplicationType.NONE) + .logStartupInfo(false) + .run(arguments); + } + + @Configuration(proxyBeanMethods = false) + @EnableAutoConfiguration + static class Application {} +} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlDeploymentModeContractTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlDeploymentModeContractTest.java index 6440c0ec..ae6d2b8e 100644 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlDeploymentModeContractTest.java +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlDeploymentModeContractTest.java @@ -1,9 +1,12 @@ package dev.caskeleton.adapter.inbound.graphql.autoconfigure; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlPlatformWebInterceptor; import dev.caskeleton.adapter.inbound.graphql.security.GraphQlAuthorizationPolicy; +import dev.caskeleton.shared.runtime.RuntimeEnvironment; +import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -54,6 +57,46 @@ class GraphQlDeploymentModeContractTest { .isEqualTo(mode.production()); } + @ParameterizedTest + @EnumSource(GraphQlDeploymentMode.class) + @DisplayName("every mode is permitted by exactly one runtime environment") + void everyModeBelongsToExactlyOneRuntime(GraphQlDeploymentMode mode) { + assertThat(Arrays.stream(RuntimeEnvironment.values()).filter(mode::permittedIn)) + .as( + "a mode no runtime accepts is dead configuration, and one that several accept is the " + + "ambiguity the collapse removed") + .hasSize(1); + } + + @Test + @DisplayName("a prod runtime refuses a development mode, naming what it permits") + void aProdRuntimeRefusesADevelopmentMode() { + Throwable failure = + catchThrowable( + () -> + new GraphQlPlatformStartupValidator() + .validateRuntimeEnvironment(GraphQlDeploymentMode.LOCAL, List.of("prod"))); + + assertThat(failure) + .isInstanceOf(GraphQlPlatformConfigurationException.class) + .hasMessageContaining("backend.graphql.deployment-mode=LOCAL") + .hasMessageContaining("[PRODUCTION_INTERNAL, PRODUCTION_PUBLIC]"); + } + + @Test + @DisplayName("the context refuses a mode that does not match its runtime profile") + void theContextRefusesAModeForAnotherRuntime() { + runner + .withPropertyValues("backend.graphql.deployment-mode=DEV", "spring.profiles.active=local") + .run( + context -> + assertThat(context) + .hasFailed() + .getFailure() + .rootCause() + .hasMessageContaining("not permitted in the local runtime")); + } + @Test @DisplayName("an absent mode is refused, by name") void anAbsentModeIsRefusedByName() { diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlDeploymentModeRegistryParityTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlDeploymentModeRegistryParityTest.java new file mode 100644 index 00000000..30f39de6 --- /dev/null +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlDeploymentModeRegistryParityTest.java @@ -0,0 +1,49 @@ +package dev.caskeleton.adapter.inbound.graphql.autoconfigure; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Arrays; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.junit.jupiter.api.Test; + +/** + * The registry lists exactly the deployment modes the enum can bind. + * + *

A mode the registry documents but the enum cannot bind fails at startup with a type-conversion + * error; a mode the enum has but the registry omits is one no operator is told about. Which runtime + * accepts each mode is held by {@code GraphQlDeploymentModeContractTest}. + */ +class GraphQlDeploymentModeRegistryParityTest { + + private static final Pattern ALLOWED_VALUES = + Pattern.compile( + "name: APP_GRAPHQL_DEPLOYMENT_MODE.*?allowed_values: \\[([^\\]]*)\\]", Pattern.DOTALL); + + @Test + void theRegistryListsExactlyTheModesTheEnumHas() throws IOException { + String registry = Files.readString(repositoryRoot().resolve("docs/registries/env-keys.yaml")); + Matcher matcher = ALLOWED_VALUES.matcher(registry); + assertThat(matcher.find()).isTrue(); + + assertThat(Arrays.stream(matcher.group(1).split(",")).map(String::trim)) + .as("the registry is what an operator sets APP_GRAPHQL_DEPLOYMENT_MODE from") + .containsExactlyInAnyOrderElementsOf( + Arrays.stream(GraphQlDeploymentMode.values()).map(Enum::name).toList()); + } + + private static Path repositoryRoot() { + Path candidate = Path.of("").toAbsolutePath(); + while (candidate != null + && !Files.isRegularFile(candidate.resolve("src/config/architecture/modules.json"))) { + candidate = candidate.getParent(); + } + if (candidate == null) { + throw new IllegalStateException("could not locate the repository root from the test cwd"); + } + return candidate; + } +} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPlatformAutoConfigurationTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPlatformAutoConfigurationTest.java index 989d7a4c..1a24d1b1 100644 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPlatformAutoConfigurationTest.java +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPlatformAutoConfigurationTest.java @@ -208,13 +208,9 @@ class GraphQlPlatformAutoConfigurationTest { .contains("backend.graphql.console.introspection-enabled") .contains("backend.graphql.limits.maximum-page-size") .contains("backend.graphql.limits.maximum-complexity") - .contains("backend.graphql.cursor.key-ids") - .contains("backend.graphql.unsupported.multipart-upload") - .contains("backend.graphql.unsupported.http-array-batch") - .contains("backend.graphql.unsupported.request-wide-transaction") - .contains("backend.graphql.unsupported.repository-auto-exposure") - .contains("backend.graphql.unsupported.response-cache") - .contains("backend.graphql.unsupported.advanced-capabilities-on-stable-starter") + // Keys that only failed the boot or were echoed back unused were removed (2026-09-25). + .doesNotContain("backend.graphql.cursor.key-ids") + .doesNotContain("backend.graphql.unsupported.multipart-upload") .contains("backend.graphql.unbridged-blocking-resolvers"); } diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPlatformStartupValidatorTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPlatformStartupValidatorTest.java index c9610f02..d5173bec 100644 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPlatformStartupValidatorTest.java +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPlatformStartupValidatorTest.java @@ -5,7 +5,6 @@ import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; import dev.caskeleton.adapter.inbound.graphql.execution.GraphQlExecutionProfile; -import dev.caskeleton.adapter.inbound.graphql.schema.GraphQlSchemaHash; import java.util.Set; import org.junit.jupiter.api.Test; @@ -13,17 +12,12 @@ import org.junit.jupiter.api.Test; class GraphQlPlatformStartupValidatorTest { @Test - void productionRejectsGraphiqlButDoesNotPretendCursorSigningIsWired() { - var properties = - GraphQlPlatformSettings.productionDefaults() - .withGraphiqlEnabled(true) - .withCursorKeyIds(Set.of()); + void productionRejectsGraphiql() { + var properties = GraphQlPlatformSettings.productionDefaults().withGraphiqlEnabled(true); assertThatThrownBy(() -> new GraphQlPlatformStartupValidator().validate(properties)) .isInstanceOf(GraphQlPlatformConfigurationException.class) .hasMessageContaining("GraphiQL"); - assertThat(new GraphQlPlatformStartupValidator().problems(properties)) - .noneSatisfy(problem -> assertThat(problem).contains("cursor signing key")); } @Test @@ -40,51 +34,10 @@ class GraphQlPlatformStartupValidatorTest { var properties = GraphQlPlatformSettings.productionDefaults() .withGraphiqlEnabled(true) - .withCursorKeyIds(Set.of()) - .withUnsupportedCapability("multipart", true); + .withLimits( + new GraphQlPlatformSettings.Limits(0, 0, 1, 1, java.time.Duration.ofMinutes(1))); - assertThat(new GraphQlPlatformStartupValidator().problems(properties)).hasSize(2); - } - - @Test - void unsupportedCapabilitiesAreRefusedRatherThanIgnored() { - var validator = new GraphQlPlatformStartupValidator(); - - assertThat( - validator.problems( - GraphQlPlatformSettings.productionDefaults() - .withUnsupportedCapability("multipart", true))) - .anySatisfy(problem -> assertThat(problem).contains("Fileserver")); - assertThat( - validator.problems( - GraphQlPlatformSettings.productionDefaults() - .withUnsupportedCapability("arrayBatch", true))) - .anySatisfy(problem -> assertThat(problem).contains("array batching")); - assertThat( - validator.problems( - GraphQlPlatformSettings.productionDefaults() - .withUnsupportedCapability("requestWideTransaction", true))) - .anySatisfy(problem -> assertThat(problem).contains("request-wide database transactions")); - assertThat( - validator.problems( - GraphQlPlatformSettings.productionDefaults() - .withUnsupportedCapability("repositoryAutoExposure", true))) - .anySatisfy(problem -> assertThat(problem).contains("automatic repository exposure")); - assertThat( - validator.problems( - GraphQlPlatformSettings.productionDefaults() - .withUnsupportedCapability("responseCache", true))) - .anySatisfy(problem -> assertThat(problem).contains("response caching")); - } - - @Test - void theStableStarterMayNotActivateAdvancedCapabilities() { - assertThat( - new GraphQlPlatformStartupValidator() - .problems( - GraphQlPlatformSettings.productionDefaults() - .withUnsupportedCapability("advancedOnStableStarter", true))) - .anySatisfy(problem -> assertThat(problem).contains("Advanced capabilities")); + assertThat(new GraphQlPlatformStartupValidator().problems(properties)).hasSize(3); } @Test @@ -104,23 +57,4 @@ class GraphQlPlatformStartupValidatorTest { assertThat(GraphQlDeploymentMode.PRODUCTION_INTERNAL.graphiqlAllowed()).isFalse(); assertThat(GraphQlDeploymentMode.PRODUCTION_PUBLIC.introspectionAllowed()).isFalse(); } - - @Test - void theOperationsReportDisclosesHashesAndCapabilitiesOnly() { - var endpoint = - new GraphQlPlatformActuatorEndpoint( - GraphQlPlatformSettings.productionDefaults(), - GraphQlSchemaHash.sha256("type Query { ping: String! }"), - Set.of("HTTP_POST", "CURSOR_CONNECTION"), - 12, - 4); - - var report = endpoint.report(); - - assertThat(report.schemaHash()).hasSize(64); - assertThat(report.httpProfile()).isEqualTo("V1"); - assertThat(report.cursorKeyIds()).isEmpty(); - assertThat(endpoint.reportAsMap().keySet()) - .doesNotContain("sdl", "schema", "persistedDocuments", "cursorKeys", "secret"); - } } diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPolicyRequestPathTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPolicyRequestPathTest.java index c761bb3b..e9406d0d 100644 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPolicyRequestPathTest.java +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPolicyRequestPathTest.java @@ -2,11 +2,9 @@ package dev.caskeleton.adapter.inbound.graphql.autoconfigure; import static org.assertj.core.api.Assertions.assertThat; -import dev.caskeleton.adapter.inbound.graphql.mutation.GraphQlMutationIdempotencyInterceptor; import dev.caskeleton.adapter.inbound.graphql.pagination.GraphQlCursorCodec; import dev.caskeleton.adapter.inbound.graphql.pagination.GraphQlCursorKeyRing; import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlPlatformInstrumentation; -import java.util.Set; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.AutoConfigurations; @@ -25,16 +23,12 @@ import org.springframework.boot.test.context.runner.ApplicationContextRunner; * *

Cursor signing is not on the request path. {@code HmacGraphQlCursorCodec} and {@link * GraphQlCursorKeyRing} exist and are unit-tested; neither is ever constructed by the Stable - * platform. A declared {@code backend.graphql.cursor.key-ids} value is therefore metadata for a - * modelled capability, not a startup safety requirement and not evidence that a request is signed. + * platform. They are library API a service assembles itself; there is no configuration key. * - *

Mutation idempotency is not on the request path either. {@link - * GraphQlMutationIdempotencyInterceptor} is referenced by no configuration. - * - *

Both are honest {@code modelled} capabilities by this leaf's own grading table. Cursor signing - * still needs a separate design decision because {@link GraphQlCursorKeyRing#of} takes {@code - * Map} while the settings intentionally contain only key identities. Until a secret - * source and request-path wiring exist, startup must remain neutral about that capability. + *

That is an honest {@code modelled} capabilities by this leaf's own grading table. Cursor + * signing still needs a separate design decision because {@link GraphQlCursorKeyRing#of} takes + * {@code Map} while the settings intentionally contain only key identities. Until a + * secret source and request-path wiring exist, startup must remain neutral about that capability. */ class GraphQlPolicyRequestPathTest { @@ -58,48 +52,13 @@ class GraphQlPolicyRequestPathTest { } @Test - @DisplayName("a configured cursor key signs nothing, because no codec is ever built") - void aConfiguredCursorKeySignsNothing() { - runner - .withPropertyValues("backend.graphql.cursor.key-ids=cursor-key-1") - .run( - context -> { - assertThat(context).hasNotFailed(); - - assertThat(context.getBean(GraphQlPlatformSettings.class).cursor().keyIds()) - .as("the operator supplied it and the settings carry it") - .containsExactly("cursor-key-1"); - assertThat(context) - .as( - "and nothing signs with it: production refuses to start without a key that " - + "protects nothing, which is worse than not asking for one") - .doesNotHaveBean(GraphQlCursorCodec.class); - assertThat(context).doesNotHaveBean(GraphQlCursorKeyRing.class); - }); - } - - @Test - @DisplayName("mutation idempotency is modelled, not applied") - void mutationIdempotencyIsNotApplied() { + @DisplayName("cursor signing is a library: the auto-configuration builds no codec or key ring") + void noCursorCodecIsBuilt() { runner.run( - context -> - assertThat(context) - .as( - "no configuration references the interceptor, so a repeated mutation is a " - + "repeated mutation") - .doesNotHaveBean(GraphQlMutationIdempotencyInterceptor.class)); - } - - @Test - @DisplayName("the startup validator does not claim an unwired cursor signer protects production") - void theValidatorDoesNotDemandTheUnusedKey() { - GraphQlPlatformSettings production = - GraphQlPlatformSettings.productionDefaults().withCursorKeyIds(Set.of()); - - assertThat(new GraphQlPlatformStartupValidator().problems(production)) - .as( - "a modelled capability becomes a startup requirement only after its secret source and " - + "request-path wiring exist") - .noneSatisfy(problem -> assertThat(problem).contains("cursor signing key")); + context -> { + assertThat(context).hasNotFailed(); + assertThat(context).doesNotHaveBean(GraphQlCursorCodec.class); + assertThat(context).doesNotHaveBean(GraphQlCursorKeyRing.class); + }); } } diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/compat/GraphQlDeprecationGateTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/compat/GraphQlDeprecationGateTest.java deleted file mode 100644 index 00dbd912..00000000 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/compat/GraphQlDeprecationGateTest.java +++ /dev/null @@ -1,172 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.compat; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.time.Duration; -import java.time.Instant; -import org.junit.jupiter.api.Test; - -/** Schema usage observation and deprecation removal gate (Stable plan Task 11). */ -class GraphQlDeprecationGateTest { - - private static final Instant NOW = Instant.parse("2026-08-12T00:00:00Z"); - private static final Duration SUPPORT_WINDOW = Duration.ofDays(90); - - @Test - void unknownUsageBlocksRemoval() { - assertThat(GraphQlDeprecationGate.evaluate(GraphQlSchemaUsage.unknown()).allowed()).isFalse(); - } - - @Test - void unknownUsageIsNotTreatedAsZeroUsage() { - GraphQlRemovalDecision decision = GraphQlDeprecationGate.evaluate(GraphQlSchemaUsage.unknown()); - - assertThat(decision.reasons()) - .singleElement() - .asString() - .contains("unknown") - .contains("cannot be treated as zero usage"); - } - - @Test - void observedUsageBlocksRemoval() { - assertThat( - GraphQlDeprecationGate.evaluate( - GraphQlSchemaUsage.observedUsed(12, NOW.minus(Duration.ofDays(1)))) - .allowed()) - .isFalse(); - } - - @Test - void fullyEvidencedRemovalIsAllowed() { - GraphQlRemovalDecision decision = - new GraphQlDeprecationGate(SUPPORT_WINDOW).evaluate(fullyEvidenced(), NOW); - - assertThat(decision.allowed()).isTrue(); - assertThat(decision.reasons()).isEmpty(); - } - - @Test - void supportWindowMustHaveElapsed() { - GraphQlRemovalRequest tooEarly = - new GraphQlRemovalRequest( - "Order.legacyTotal", - GraphQlSchemaUsage.observedUnused(NOW.minus(Duration.ofDays(120))), - NOW.minus(Duration.ofDays(10)), - 0, - approval(), - false); - - GraphQlRemovalDecision decision = - new GraphQlDeprecationGate(SUPPORT_WINDOW).evaluate(tooEarly, NOW); - - assertThat(decision.allowed()).isFalse(); - assertThat(decision.reasons()) - .anySatisfy(reason -> assertThat(reason).contains("support window")); - } - - @Test - void neverDeprecatedElementCannotBeRemoved() { - GraphQlRemovalRequest request = - new GraphQlRemovalRequest( - "Order.legacyTotal", - GraphQlSchemaUsage.observedUnused(NOW.minus(Duration.ofDays(120))), - null, - 0, - approval(), - false); - - assertThat(new GraphQlDeprecationGate(SUPPORT_WINDOW).evaluate(request, NOW).reasons()) - .anySatisfy(reason -> assertThat(reason).contains("@deprecated")); - } - - @Test - void persistedOperationReferencesBlockRemoval() { - GraphQlRemovalRequest request = - new GraphQlRemovalRequest( - "Order.legacyTotal", - GraphQlSchemaUsage.observedUnused(NOW.minus(Duration.ofDays(120))), - NOW.minus(Duration.ofDays(120)), - 2, - approval(), - false); - - assertThat(new GraphQlDeprecationGate(SUPPORT_WINDOW).evaluate(request, NOW).reasons()) - .anySatisfy(reason -> assertThat(reason).contains("persisted operations")); - } - - @Test - void missingClientOwnerApprovalBlocksRemoval() { - GraphQlRemovalRequest request = - new GraphQlRemovalRequest( - "Order.legacyTotal", - GraphQlSchemaUsage.observedUnused(NOW.minus(Duration.ofDays(120))), - NOW.minus(Duration.ofDays(120)), - 0, - null, - false); - - assertThat(new GraphQlDeprecationGate(SUPPORT_WINDOW).evaluate(request, NOW).reasons()) - .anySatisfy(reason -> assertThat(reason).contains("approval")); - } - - @Test - void requiredInputElementCannotUseTheDeprecationShortcut() { - GraphQlRemovalRequest request = - new GraphQlRemovalRequest( - "CreateOrderInput.customerId", - GraphQlSchemaUsage.observedUnused(NOW.minus(Duration.ofDays(120))), - NOW.minus(Duration.ofDays(120)), - 0, - approval(), - true); - - assertThat(new GraphQlDeprecationGate(SUPPORT_WINDOW).evaluate(request, NOW).reasons()) - .anySatisfy(reason -> assertThat(reason).contains("nullable or give it a default")); - } - - @Test - void everyBlockingReasonIsReportedTogether() { - GraphQlRemovalRequest request = - new GraphQlRemovalRequest( - "Order.legacyTotal", GraphQlSchemaUsage.unknown(), null, 3, null, true); - - assertThat(new GraphQlDeprecationGate(SUPPORT_WINDOW).evaluate(request, NOW).reasons()) - .hasSize(5); - } - - @Test - void approvalRecordsOwnerAndReasonWithoutSecrets() { - GraphQlClientOwnerApproval approval = approval(); - - assertThat(approval.describe()).contains("checkout-team").contains("migrated to totalAmount"); - assertThatThrownBy(() -> new GraphQlClientOwnerApproval(" ", "reason", NOW)) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> new GraphQlClientOwnerApproval("owner\ntoken", "reason", NOW)) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void usageStatesAreDistinguishedAtConstruction() { - assertThat(GraphQlSchemaUsage.unknown().measured()).isFalse(); - assertThat(GraphQlSchemaUsage.observedUnused(NOW).provenUnused()).isTrue(); - assertThatThrownBy(() -> GraphQlSchemaUsage.observedUsed(0, null)) - .isInstanceOf(IllegalArgumentException.class); - } - - private static GraphQlRemovalRequest fullyEvidenced() { - return new GraphQlRemovalRequest( - "Order.legacyTotal", - GraphQlSchemaUsage.observedUnused(NOW.minus(Duration.ofDays(120))), - NOW.minus(Duration.ofDays(120)), - 0, - approval(), - false); - } - - private static GraphQlClientOwnerApproval approval() { - return new GraphQlClientOwnerApproval( - "checkout-team", "migrated to totalAmount", NOW.minus(Duration.ofDays(1))); - } -} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/compat/GraphQlSchemaComparatorTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/compat/GraphQlSchemaComparatorTest.java deleted file mode 100644 index 5dbaee0a..00000000 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/compat/GraphQlSchemaComparatorTest.java +++ /dev/null @@ -1,343 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.compat; - -import static org.assertj.core.api.Assertions.assertThat; - -import org.junit.jupiter.api.Test; - -/** Schema compatibility diff and breaking policy (Stable plan Task 10). */ -class GraphQlSchemaComparatorTest { - - @Test - void aFieldRemovedFromATypeExtensionIsBreaking() { - GraphQlCompatibilityReport report = - GraphQlSchemaComparator.compare( - "type Query { a: String } extend type Query { b: String }", "type Query { a: String }"); - - assertThat(report.changesOf(GraphQlChangeKind.OUTPUT_FIELD_REMOVED)) - .as("a field an extension contributed is on the wire like any other") - .hasSize(1); - } - - @Test - void aFieldAddedByATypeExtensionIsReported() { - GraphQlCompatibilityReport report = - GraphQlSchemaComparator.compare( - "type Query { a: String }", "type Query { a: String } extend type Query { b: String }"); - - assertThat(report.changesOf(GraphQlChangeKind.OUTPUT_FIELD_ADDED_NULLABLE)).hasSize(1); - } - - @Test - void anExtensionThatStrengthensAnInputIsBreaking() { - GraphQlCompatibilityReport report = - GraphQlSchemaComparator.compare( - "input OrderFilter { status: String } extend input OrderFilter { region: String }", - "input OrderFilter { status: String } extend input OrderFilter { region: String! }"); - - assertThat(report.changesOf(GraphQlChangeKind.INPUT_FIELD_STRENGTHENED)).hasSize(1); - } - - @Test - void anEnumValueRemovedFromAnExtensionIsReported() { - GraphQlCompatibilityReport report = - GraphQlSchemaComparator.compare( - "enum Status { NEW } extend enum Status { ARCHIVED }", "enum Status { NEW }"); - - assertThat(report.changesOf(GraphQlChangeKind.ENUM_VALUE_REMOVED)).hasSize(1); - } - - @Test - void aUnionMemberRemovedFromAnExtensionIsReported() { - GraphQlCompatibilityReport report = - GraphQlSchemaComparator.compare( - "type A { a: String } type B { b: String } union Result = A extend union Result = B", - "type A { a: String } type B { b: String } union Result = A"); - - assertThat(report.changesOf(GraphQlChangeKind.UNION_MEMBER_REMOVED)).hasSize(1); - } - - @Test - void rewordingAScalarsDescriptionIsNotACoercionChange() { - GraphQlCompatibilityReport report = - GraphQlSchemaComparator.compare( - "\"An ISO-8601 instant.\" scalar Instant type Query { at: Instant }", - "\"An instant, in ISO-8601.\" scalar Instant type Query { at: Instant }"); - - assertThat(report.changesOf(GraphQlChangeKind.SCALAR_DECLARATION_CHANGED)) - .as( - "prose is not a coercion; a review triggered by an edited sentence trains people to " - + "approve the report without reading it") - .isEmpty(); - } - - @Test - void requiredArgumentAdditionIsBreaking() { - GraphQlCompatibilityReport report = - GraphQlSchemaComparator.compare( - "type Query { order: String }", "type Query { order(id: ID!): String }"); - - assertThat(report.breaking()).isTrue(); - } - - @Test - void optionalArgumentAdditionIsCompatible() { - GraphQlCompatibilityReport report = - GraphQlSchemaComparator.compare( - "type Query { order: String }", "type Query { order(id: ID): String }"); - - assertThat(report.breaking()).isFalse(); - assertThat(report.changesOf(GraphQlChangeKind.ARGUMENT_ADDED_OPTIONAL)).hasSize(1); - } - - @Test - void requiredArgumentWithDefaultIsCompatible() { - GraphQlCompatibilityReport report = - GraphQlSchemaComparator.compare( - "type Query { orders: String }", "type Query { orders(first: Int! = 20): String }"); - - assertThat(report.breaking()).isFalse(); - } - - @Test - void fieldAndTypeRemovalAreBreaking() { - assertThat( - GraphQlSchemaComparator.compare( - "type Query { a: String b: String }", "type Query { a: String }") - .changesOf(GraphQlChangeKind.OUTPUT_FIELD_REMOVED)) - .hasSize(1); - assertThat( - GraphQlSchemaComparator.compare( - "type Query { a: String } type Order { id: ID! }", "type Query { a: String }") - .changesOf(GraphQlChangeKind.TYPE_REMOVED)) - .hasSize(1); - } - - @Test - void outputNullabilityDirectionDecidesTheVerdict() { - GraphQlCompatibilityReport relaxed = - GraphQlSchemaComparator.compare("type Query { a: String! }", "type Query { a: String }"); - GraphQlCompatibilityReport strengthened = - GraphQlSchemaComparator.compare("type Query { a: String }", "type Query { a: String! }"); - - assertThat(relaxed.breaking()).isTrue(); - assertThat(relaxed.changesOf(GraphQlChangeKind.OUTPUT_FIELD_NULLABILITY_RELAXED)).hasSize(1); - - assertThat(strengthened.breaking()).isFalse(); - assertThat(strengthened.reviewRequired()).isTrue(); - } - - @Test - void inputNullabilityDirectionIsTheOppositeOfOutput() { - GraphQlCompatibilityReport strengthened = - GraphQlSchemaComparator.compare( - "input OrderInput { note: String }", "input OrderInput { note: String! }"); - GraphQlCompatibilityReport relaxed = - GraphQlSchemaComparator.compare( - "input OrderInput { note: String! }", "input OrderInput { note: String }"); - - assertThat(strengthened.changesOf(GraphQlChangeKind.INPUT_FIELD_STRENGTHENED)).hasSize(1); - assertThat(strengthened.breaking()).isTrue(); - - assertThat(relaxed.changesOf(GraphQlChangeKind.INPUT_FIELD_RELAXED)).hasSize(1); - assertThat(relaxed.breaking()).isFalse(); - assertThat(relaxed.reviewRequired()).isTrue(); - } - - @Test - void requiredInputFieldAdditionAndRemovalAreBreaking() { - assertThat( - GraphQlSchemaComparator.compare( - "input OrderInput { id: ID! }", "input OrderInput { id: ID! note: String! }") - .changesOf(GraphQlChangeKind.INPUT_FIELD_ADDED_REQUIRED)) - .hasSize(1); - assertThat( - GraphQlSchemaComparator.compare( - "input OrderInput { id: ID! note: String }", "input OrderInput { id: ID! }") - .changesOf(GraphQlChangeKind.INPUT_FIELD_REMOVED)) - .hasSize(1); - } - - @Test - void enumAndUnionAdditionsAreAdditiveWithGeneratedClientReview() { - GraphQlCompatibilityReport enumReport = - GraphQlSchemaComparator.compare("enum Status { NEW }", "enum Status { NEW SHIPPED }"); - GraphQlCompatibilityReport unionReport = - GraphQlSchemaComparator.compare( - "type A { a: String } type B { b: String } union Result = A", - "type A { a: String } type B { b: String } union Result = A | B"); - - assertThat(enumReport.breaking()).isFalse(); - assertThat(enumReport.changesOf(GraphQlChangeKind.ENUM_VALUE_ADDED)) - .singleElement() - .satisfies( - change -> - assertThat(change.generatedClientImpact()) - .isEqualTo(GraphQlCompatibilityImpact.REVIEW_REQUIRED)); - - assertThat(unionReport.breaking()).isFalse(); - assertThat(unionReport.changesOf(GraphQlChangeKind.UNION_MEMBER_ADDED)).hasSize(1); - } - - @Test - void enumValueAndUnionMemberRemovalAreBreaking() { - assertThat( - GraphQlSchemaComparator.compare("enum Status { NEW SHIPPED }", "enum Status { NEW }") - .breaking()) - .isTrue(); - assertThat( - GraphQlSchemaComparator.compare( - "type A { a: String } type B { b: String } union Result = A | B", - "type A { a: String } type B { b: String } union Result = A") - .breaking()) - .isTrue(); - } - - @Test - void aChangedScalarDeclarationIsReportedForReviewRatherThanCalledACoercionChange() { - GraphQlCompatibilityReport report = - GraphQlSchemaComparator.compare( - "scalar Amount @specifiedBy(url: \"https://example.test/v1\")", - "scalar Amount @specifiedBy(url: \"https://example.test/v2\")"); - - // The SDL cannot tell us whether the Coercing implementation changed: swapping the codec while - // leaving the SDL alone was invisible, and editing a description was reported as breaking. - // Coercion compatibility is the scalar manifest's codec version, not this. - assertThat(report.changesOf(GraphQlChangeKind.SCALAR_DECLARATION_CHANGED)).hasSize(1); - assertThat(report.reviewRequired()).isTrue(); - } - - @Test - void aTypeThatChangedKindIsBreaking() { - GraphQlCompatibilityReport report = - GraphQlSchemaComparator.compare( - "type Filter { status: String }", "input Filter { status: String }"); - - assertThat(report.changesOf(GraphQlChangeKind.TYPE_KIND_CHANGED)).hasSize(1); - assertThat(report.breaking()).isTrue(); - } - - @Test - void removingAnInputDefaultIsBreaking() { - GraphQlCompatibilityReport report = - GraphQlSchemaComparator.compare( - "input Page { size: Int! = 20 }", "input Page { size: Int! }"); - - assertThat(report.changesOf(GraphQlChangeKind.INPUT_DEFAULT_REMOVED)).hasSize(1); - assertThat(report.breaking()).isTrue(); - } - - @Test - void changingAnInputDefaultNeedsReview() { - GraphQlCompatibilityReport report = - GraphQlSchemaComparator.compare( - "input Page { size: Int! = 20 }", "input Page { size: Int! = 100 }"); - - assertThat(report.changesOf(GraphQlChangeKind.INPUT_DEFAULT_CHANGED)).hasSize(1); - } - - @Test - void addingAnInputDefaultIsAcceptingButChangesGeneratedModels() { - GraphQlCompatibilityReport report = - GraphQlSchemaComparator.compare( - "input Page { size: Int! }", "input Page { size: Int! = 20 }"); - - assertThat(report.changesOf(GraphQlChangeKind.INPUT_DEFAULT_ADDED)).hasSize(1); - assertThat(report.breaking()).isFalse(); - } - - @Test - void aChangeToAppliedDirectivesIsReported() { - GraphQlCompatibilityReport report = - GraphQlSchemaComparator.compare( - "type Query { legacy: String }", - "type Query { legacy: String @deprecated(reason: \"use modern\") }"); - - assertThat(report.changesOf(GraphQlChangeKind.APPLIED_DIRECTIVE_CHANGED)) - .as("comparing directive definitions alone could never see this") - .hasSize(1); - } - - @Test - void aChangeToATypeLevelAppliedDirectiveIsReported() { - GraphQlCompatibilityReport report = - GraphQlSchemaComparator.compare( - "input Choice @oneOf { a: Int b: Int }", "input Choice { a: Int b: Int }"); - - assertThat(report.changesOf(GraphQlChangeKind.APPLIED_DIRECTIVE_CHANGED)).hasSize(1); - } - - @Test - void directiveSemanticsChangeRequiresBehaviouralReview() { - GraphQlCompatibilityReport report = - GraphQlSchemaComparator.compare( - "directive @audit on FIELD_DEFINITION", - "directive @audit(reason: String) on FIELD_DEFINITION"); - - assertThat(report.changesOf(GraphQlChangeKind.DIRECTIVE_CHANGED)).hasSize(1); - assertThat(report.breaking()).isFalse(); - assertThat(report.reviewRequired()).isTrue(); - } - - @Test - void everyChangeReportsCoordinateImpactAndReason() { - GraphQlSchemaChange change = - GraphQlSchemaComparator.compare( - "type Query { order: String }", "type Query { order(id: ID!): String }") - .changes() - .getFirst(); - - assertThat(change.coordinate()).isEqualTo("Query.order(id)"); - assertThat(change.kind()).isEqualTo(GraphQlChangeKind.ARGUMENT_ADDED_REQUIRED); - assertThat(change.wireImpact()).isEqualTo(GraphQlCompatibilityImpact.BREAKING); - assertThat(change.reason()).isNotBlank(); - assertThat(change.describe()).contains("Query.order(id)").contains("BREAKING"); - } - - @Test - void comparisonOrderIsDeterministic() { - String previous = "type Query { a: String b: String c: String }"; - String candidate = "type Query { a: String }"; - - assertThat(GraphQlSchemaComparator.compare(previous, candidate).changes()) - .extracting(GraphQlSchemaChange::coordinate) - .containsExactly("Query.b", "Query.c"); - } - - @Test - void identicalSchemasProduceNoChanges() { - assertThat( - GraphQlSchemaComparator.compare("type Query { a: String }", "type Query { a: String }") - .changes()) - .isEmpty(); - assertThat(GraphQlCompatibilityReport.identical().breaking()).isFalse(); - } - - @Test - void stablePolicyRejectsBreakingChangesAndReportsReviewNotices() { - GraphQlCompatibilityPolicy policy = GraphQlCompatibilityPolicy.stableV1(); - GraphQlCompatibilityReport breaking = - GraphQlSchemaComparator.compare("type Query { a: String! }", "type Query { a: String }"); - GraphQlCompatibilityReport additive = - GraphQlSchemaComparator.compare("enum Status { NEW }", "enum Status { NEW SHIPPED }"); - - assertThat(policy.permits(breaking)).isFalse(); - assertThat(policy.rejections(breaking)).hasSize(1); - assertThat(policy.version().value()).isEqualTo("stable-v1"); - - assertThat(policy.permits(additive)).isTrue(); - assertThat(policy.reviewNotices(additive)).hasSize(1); - } - - @Test - void anExplicitBreakingReleasePolicyCanAcceptBreakingChanges() { - GraphQlCompatibilityPolicy policy = - GraphQlCompatibilityPolicy.breakingRelease( - dev.caskeleton.adapter.inbound.graphql.schema.GraphQlContractVersion.of("stable-v2")); - - assertThat( - policy.permits( - GraphQlSchemaComparator.compare( - "type Query { a: String! }", "type Query { a: String }"))) - .isTrue(); - } -} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlParserLimitPolicyTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlParserLimitPolicyTest.java deleted file mode 100644 index 24838abc..00000000 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlParserLimitPolicyTest.java +++ /dev/null @@ -1,100 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.cost; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import graphql.parser.ParserOptions; -import org.junit.jupiter.api.Test; - -/** Parser character, token and grammar limits (Stable plan Task 30). */ -class GraphQlParserLimitPolicyTest { - - @Test - void rejectsDocumentBeforeParserWhenCharacterBudgetIsExceeded() { - var limits = new GraphQlParserLimits(32, 20, 40, 8); - var policy = new GraphQlParserLimitPolicy(limits); - - assertThatThrownBy(() -> policy.verifyDocument("query TooLong { " + "x".repeat(64) + " }")) - .isInstanceOf(GraphQlParserRejectedException.class) - .hasMessageContaining("CHARACTERS"); - } - - @Test - void rejectionUsesAStableRequestErrorCodeAndNoDocumentText() { - var policy = new GraphQlParserLimitPolicy(new GraphQlParserLimits(16, 20, 40, 8)); - String document = "query Secret { card(number: \"4111111111111111\") }"; - - assertThatThrownBy(() -> policy.verifyDocument(document)) - .isInstanceOf(GraphQlParserRejectedException.class) - .hasMessageContaining(GraphQlParserRejectedException.CODE) - .hasMessageNotContaining("4111"); - } - - @Test - void tokenWhitespaceAndGrammarBudgetsAreEnforcedToo() { - var policy = new GraphQlParserLimitPolicy(new GraphQlParserLimits(1024, 20, 40, 8)); - - assertThatThrownBy(() -> policy.verifyParsedCounts(21, 10, 4)) - .isInstanceOf(GraphQlParserRejectedException.class) - .hasMessageContaining("TOKENS"); - assertThatThrownBy(() -> policy.verifyParsedCounts(10, 41, 4)) - .isInstanceOf(GraphQlParserRejectedException.class) - .hasMessageContaining("WHITESPACE_TOKENS"); - assertThatThrownBy(() -> policy.verifyParsedCounts(10, 10, 9)) - .isInstanceOf(GraphQlParserRejectedException.class) - .hasMessageContaining("GRAMMAR_RULE_DEPTH"); - assertThatCode(() -> policy.verifyParsedCounts(10, 10, 4)).doesNotThrowAnyException(); - } - - @Test - void allLimitsMustBePositive() { - assertThatThrownBy(() -> new GraphQlParserLimits(0, 20, 40, 8)) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void limitsMapExactlyOntoParserOptions() { - var limits = new GraphQlParserLimits(4096, 1000, 2000, 64); - - ParserOptions options = GraphQlParserOptionsFactory.create(limits); - - assertThat(options.getMaxCharacters()).isEqualTo(4096); - assertThat(options.getMaxTokens()).isEqualTo(1000); - assertThat(options.getMaxWhitespaceTokens()).isEqualTo(2000); - assertThat(options.getMaxRuleDepth()).isEqualTo(64); - assertThat(options.isRedactTokenParserErrorMessages()).isTrue(); - } - - @Test - void platformLimitsAreSmallerThanTheLibraryCeilings() { - var derived = GraphQlParserLimits.from(new GraphQlClientPolicyFixture().policy()); - - assertThat(derived.maxCharacters()).isLessThan(ParserOptions.MAX_QUERY_CHARACTERS); - assertThat(derived.maxTokens()).isLessThan(ParserOptions.MAX_QUERY_TOKENS); - } - - /** Minimal client policy fixture for limit derivation. */ - static final class GraphQlClientPolicyFixture { - - dev.caskeleton.adapter.inbound.graphql.policy.GraphQlClientPolicy policy() { - return new dev.caskeleton.adapter.inbound.graphql.policy.GraphQlClientPolicy( - 65536, - 65536, - 12, - 500, - 50, - 50, - 1000, - 20, - 100, - 10000, - 10000, - 5_242_880, - java.time.Duration.ofSeconds(5), - false, - false, - true); - } - } -} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlRuntimeBudgetTrackerTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlRuntimeBudgetTrackerTest.java deleted file mode 100644 index 6f775534..00000000 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/cost/GraphQlRuntimeBudgetTrackerTest.java +++ /dev/null @@ -1,107 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.cost; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.graphql.execution.GraphQlCancellation; -import org.junit.jupiter.api.Test; - -/** Runtime response node and byte budget (Stable plan Task 33). */ -class GraphQlRuntimeBudgetTrackerTest { - - @Test - void rejectsTheNodeThatCrossesTheBudget() { - var tracker = new GraphQlRuntimeBudgetTracker(new GraphQlRuntimeBudget(2, 1024)); - tracker.recordNode(); - tracker.recordNode(); - - assertThatThrownBy(tracker::recordNode) - .isInstanceOf(GraphQlRuntimeBudgetExceededException.class) - .hasMessageContaining("nodes"); - } - - @Test - void nodesAndBytesAreLimitedIndependently() { - var tracker = new GraphQlRuntimeBudgetTracker(new GraphQlRuntimeBudget(1_000, 16)); - tracker.recordNode(); - - assertThatThrownBy(() -> tracker.recordBytes(17)) - .isInstanceOf(GraphQlRuntimeBudgetExceededException.class) - .hasMessageContaining("bytes"); - assertThat(tracker.nodeCount()).isEqualTo(1); - } - - @Test - void anEstimateThatPassedDoesNotExemptTheRuntimeBudget() { - var calculator = - new GraphQlComplexityCalculator( - GraphQlCostCatalog.of( - new GraphQlFieldCostDescriptor( - "Query.orders", 1, GraphQlResolverWeight.PROPERTY, true)), - 1, - 100); - var estimate = calculator.connectionCost("Query.orders", 1, null, 1); - var tracker = new GraphQlRuntimeBudgetTracker(new GraphQlRuntimeBudget(2, 1024)); - - assertThat(estimate.within(10_000)).isTrue(); - tracker.recordNode(); - tracker.recordNode(); - assertThatThrownBy(tracker::recordNode) - .isInstanceOf(GraphQlRuntimeBudgetExceededException.class); - } - - @Test - void exceedingTheBudgetCancelsInFlightWork() { - GraphQlCancellation cancellation = GraphQlCancellation.create(); - var tracker = new GraphQlRuntimeBudgetTracker(new GraphQlRuntimeBudget(1, 1024), cancellation); - tracker.recordNode(); - - assertThatThrownBy(tracker::recordNode) - .isInstanceOf(GraphQlRuntimeBudgetExceededException.class); - assertThat(cancellation.cancelled()).isTrue(); - } - - @Test - void anOverrunAfterCommitIsClassifiedAsAPartialResponse() { - var tracker = new GraphQlRuntimeBudgetTracker(new GraphQlRuntimeBudget(1_000, 8)); - tracker.markResponseCommitted(); - - assertThatThrownBy(() -> tracker.recordBytes(9)) - .isInstanceOf(GraphQlRuntimeBudgetExceededException.class) - .satisfies( - failure -> { - var budgetFailure = (GraphQlRuntimeBudgetExceededException) failure; - assertThat(budgetFailure.responseCommitted()).isTrue(); - assertThat(budgetFailure.code()) - .isEqualTo(GraphQlRuntimeBudgetExceededException.PARTIAL_RESPONSE_CODE); - }); - } - - @Test - void anOverrunBeforeCommitCanStillReplaceTheResponse() { - var tracker = new GraphQlRuntimeBudgetTracker(new GraphQlRuntimeBudget(1_000, 8)); - - assertThatThrownBy(() -> tracker.recordBytes(9)) - .satisfies( - failure -> - assertThat(((GraphQlRuntimeBudgetExceededException) failure).code()) - .isEqualTo(GraphQlRuntimeBudgetExceededException.CODE)); - } - - @Test - void budgetErrorsCarryNoResponseDataOrVariableValues() { - var tracker = new GraphQlRuntimeBudgetTracker(new GraphQlRuntimeBudget(1, 1)); - - assertThatThrownBy(() -> tracker.recordBytes(4111111111111111L)) - .hasMessageNotContaining("4111") - .hasMessage("response bytes exceeded"); - } - - @Test - void budgetsMustBePositive() { - assertThatThrownBy(() -> new GraphQlRuntimeBudget(0, 1024)) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> new GraphQlRuntimeBudget(1, 0)) - .isInstanceOf(IllegalArgumentException.class); - } -} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlErrorCodeCatalogTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlErrorCodeCatalogTest.java index 9a839b48..d0623af3 100644 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlErrorCodeCatalogTest.java +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlErrorCodeCatalogTest.java @@ -4,8 +4,6 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import dev.caskeleton.adapter.inbound.graphql.cost.GraphQlComplexityRejectedException; -import dev.caskeleton.adapter.inbound.graphql.cost.GraphQlParserRejectedException; -import dev.caskeleton.adapter.inbound.graphql.cost.GraphQlRuntimeBudgetExceededException; import dev.caskeleton.adapter.inbound.graphql.cost.GraphQlStructuralLimitException; import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlBatchTimeoutException; import dev.caskeleton.adapter.inbound.graphql.execution.GraphQlAnonymousOperationException; @@ -53,12 +51,7 @@ class GraphQlErrorCodeCatalogTest { @Test void modelledOnlyCapabilityCodesDoNotPretendToBeShippedWireCodes() { assertThat(GraphQlErrorCode.platformCodes()) - .doesNotContain( - GraphQlParserRejectedException.CODE, - GraphQlRuntimeBudgetExceededException.CODE, - GraphQlRuntimeBudgetExceededException.PARTIAL_RESPONSE_CODE, - GraphQlBatchTimeoutException.CODE, - GraphQlCursorException.CODE); + .doesNotContain(GraphQlBatchTimeoutException.CODE, GraphQlCursorException.CODE); } @Test diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlExceptionResolverTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlExceptionResolverTest.java index e1d76250..fab11570 100644 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlExceptionResolverTest.java +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlExceptionResolverTest.java @@ -3,8 +3,6 @@ package dev.caskeleton.adapter.inbound.graphql.error; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import dev.caskeleton.adapter.inbound.graphql.http.GraphQlHttpOutcome; -import java.util.List; import org.junit.jupiter.api.Test; /** Exception resolution, masking and partial data (Stable plan Task 25). */ @@ -73,51 +71,6 @@ class GraphQlExceptionResolverTest { .isEqualTo(GraphQlWireError.OPAQUE_MESSAGE); } - @Test - void parseAndValidationFailuresUseARequestMapperNotAFetcherResolver() { - GraphQlWireError error = - GraphQlRequestErrorMapper.map(GraphQlHttpOutcome.PARSE_ERROR, GraphQlErrorContext.test()); - - assertThat(error.path()).isEmpty(); - assertThat(error.extensions()) - .containsEntry("code", GraphQlErrorCode.REQUEST_ERROR) - .containsEntry("category", GraphQlErrorCategory.REQUEST.name()); - assertThatThrownBy( - () -> - GraphQlRequestErrorMapper.map( - GraphQlHttpOutcome.FIELD_ERROR, GraphQlErrorContext.test())) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void validationMessagesAreMaskedWhenTheyWouldDisclose() { - assertThat( - GraphQlRequestErrorMapper.mapValidation( - List.of("Field 'ghost' is undefined"), GraphQlErrorContext.test()) - .message()) - .contains("ghost"); - assertThat( - GraphQlRequestErrorMapper.mapValidation( - List.of("caused by org.hibernate.QueryException"), GraphQlErrorContext.test()) - .message()) - .isEqualTo(GraphQlWireError.OPAQUE_MESSAGE); - } - - @Test - void subscriptionFailuresUseADedicatedResolver() { - GraphQlSubscriptionExceptionResolver resolver = GraphQlSubscriptionExceptionResolver.defaults(); - - assertThat( - resolver.resolveStreamFailure( - new RuntimeException("mongodb://cluster/internal"), GraphQlErrorContext.test())) - .singleElement() - .satisfies(error -> assertThat(error.message()).isEqualTo(GraphQlWireError.OPAQUE_MESSAGE)); - assertThat(resolver.credentialExpired(GraphQlErrorContext.test()).extensions()) - .containsEntry("category", GraphQlErrorCategory.AUTHORIZATION.name()); - assertThat(resolver.serverDraining(GraphQlErrorContext.test()).extensions()) - .containsEntry("retryable", true); - } - /** A deliberately modelled business failure. */ static final class OrderNotFoundException extends RuntimeException { diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlNullPropagationContractTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlNullPropagationContractTest.java deleted file mode 100644 index 19807dec..00000000 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlNullPropagationContractTest.java +++ /dev/null @@ -1,97 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.error; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.util.List; -import org.junit.jupiter.api.Test; - -/** Golden null-propagation and partial-response contract (Stable plan Task 26). */ -class GraphQlNullPropagationContractTest { - - @Test - void nullableChildPreservesParent() { - GraphQlPartialResponseFixture response = GraphQlPartialResponseFixture.nullableChildFailure(); - - assertThat(response.dataPath("order.id")).isEqualTo("o-1"); - assertThat(response.dataPath("order.payment")).isNull(); - } - - @Test - void nonNullChildNullsTheNearestNullableAncestor() { - GraphQlPartialResponseFixture response = GraphQlPartialResponseFixture.nonNullChildFailure(); - - assertThat(response.dataPath("order")).isNull(); - assertThat(response.errorPaths()).containsExactly(List.of("order", "total")); - } - - @Test - void siblingFieldsSurviveAFieldFailure() { - GraphQlPartialResponseFixture response = GraphQlPartialResponseFixture.siblingFieldFailure(); - - assertThat(response.dataPath("stableField")).isEqualTo("ok"); - assertThat(response.dataPath("failingField")).isNull(); - assertThat(response.errors()).hasSize(1); - } - - @Test - void everyFixtureErrorIsMasked() { - List fixtures = - List.of( - GraphQlPartialResponseFixture.nullableChildFailure(), - GraphQlPartialResponseFixture.nonNullChildFailure(), - GraphQlPartialResponseFixture.siblingFieldFailure()); - - assertThat(fixtures) - .allSatisfy( - fixture -> - assertThat(fixture.errors()) - .allSatisfy( - error -> - assertThat(GraphQlInternalErrorMasker.discloses(error.message())) - .isFalse())); - } - - @Test - void addingNonNullRequiresAnExplicitContractFixture() { - assertThat(GraphQlNullabilityContract.nonNull("Order.id").boundary()) - .isEqualTo(GraphQlFailureBoundary.PARENT); - assertThatThrownBy( - () -> - new GraphQlNullabilityContract( - "Order.id", true, GraphQlFailureBoundary.FIELD, false)) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void externalEnrichmentFieldsDefaultToNullable() { - GraphQlNullabilityContract enrichment = GraphQlNullabilityContract.enrichment("Order.payment"); - - assertThat(enrichment.nonNull()).isFalse(); - assertThat(enrichment.boundary()).isEqualTo(GraphQlFailureBoundary.FIELD); - assertThatThrownBy( - () -> - new GraphQlNullabilityContract( - "Order.payment", true, GraphQlFailureBoundary.PARENT, true)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("cannot promise non-null"); - } - - @Test - void authorizationCannotSilentlyRedactANonNullField() { - assertThat(GraphQlNullabilityContract.nullable("Order.note").redactableByAuthorization()) - .isTrue(); - assertThat(GraphQlNullabilityContract.nonNull("Order.id").redactableByAuthorization()) - .isFalse(); - } - - @Test - void listAndElementNullabilityAreTestedIndependently() { - GraphQlNullabilityContract listItself = GraphQlNullabilityContract.nonNull("Order.items"); - GraphQlNullabilityContract element = GraphQlNullabilityContract.nullable("OrderItem.name"); - - assertThat(listItself.nonNull()).isTrue(); - assertThat(element.nonNull()).isFalse(); - assertThat(element.boundary()).isEqualTo(GraphQlFailureBoundary.FIELD); - } -} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/execution/GraphQlExecutionProfileValidatorTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/execution/GraphQlExecutionProfileValidatorTest.java deleted file mode 100644 index e5a57d0d..00000000 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/execution/GraphQlExecutionProfileValidatorTest.java +++ /dev/null @@ -1,134 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.execution; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.graphql.policy.GraphQlOperationType; -import dev.caskeleton.adapter.inbound.graphql.policy.ResolverExecutionType; -import org.junit.jupiter.api.Test; - -/** Execution profile and resolver catalog validation (Stable plan Task 21). */ -class GraphQlExecutionProfileValidatorTest { - - @Test - void reactiveProfileRejectsBlockingDescriptor() { - var descriptor = - new GraphQlResolverDescriptor("Order.total", ResolverExecutionType.BLOCKING, false); - - assertThatThrownBy( - () -> - GraphQlExecutionProfileValidator.validate( - GraphQlExecutionProfile.REACTIVE_WEBFLUX, descriptor)) - .isInstanceOf(GraphQlExecutionProfileException.class); - } - - @Test - void reactiveProfileAcceptsABridgedBlockingResolver() { - var bridged = - new GraphQlResolverDescriptor("Order.total", ResolverExecutionType.BLOCKING, true); - - assertThatCode( - () -> - GraphQlExecutionProfileValidator.validate( - GraphQlExecutionProfile.REACTIVE_WEBFLUX, bridged)) - .doesNotThrowAnyException(); - } - - @Test - void blockingProfileAcceptsReactiveOnlyThroughAnExplicitAdapter() { - var unadapted = - new GraphQlResolverDescriptor("Order.customer", ResolverExecutionType.REACTIVE, false); - var adapted = - new GraphQlResolverDescriptor("Order.customer", ResolverExecutionType.REACTIVE, true); - - assertThatThrownBy( - () -> - GraphQlExecutionProfileValidator.validate( - GraphQlExecutionProfile.BLOCKING_MVC, unadapted)) - .isInstanceOf(GraphQlExecutionProfileException.class) - .hasMessageContaining("explicit adapter"); - assertThatCode( - () -> - GraphQlExecutionProfileValidator.validate( - GraphQlExecutionProfile.BLOCKING_MVC, adapted)) - .doesNotThrowAnyException(); - } - - @Test - void mixedProfileIsNotAnAnythingGoesProfile() { - var unbridged = - new GraphQlResolverDescriptor("Order.total", ResolverExecutionType.BLOCKING, false); - - assertThatThrownBy( - () -> - GraphQlExecutionProfileValidator.validate( - GraphQlExecutionProfile.MIXED_CONTROLLED, unbridged)) - .isInstanceOf(GraphQlExecutionProfileException.class) - .hasMessageContaining("declare a bridge"); - } - - @Test - void streamRequiresASubscriptionAndAPublisherReturnType() { - assertThatThrownBy( - () -> - new GraphQlResolverDescriptor( - "Query.orders", - ResolverExecutionType.STREAM, - false, - GraphQlOperationType.QUERY, - true)) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new GraphQlResolverDescriptor( - "Subscription.orderEvents", - ResolverExecutionType.STREAM, - false, - GraphQlOperationType.SUBSCRIPTION, - false)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("Publisher"); - - assertThatCode(() -> GraphQlResolverDescriptor.subscription("Subscription.orderEvents")) - .doesNotThrowAnyException(); - } - - @Test - void unknownResolverDescriptorsFailStartup() { - GraphQlResolverCatalog catalog = new GraphQlResolverCatalog(); - - assertThatThrownBy(() -> catalog.require("Order.total")) - .isInstanceOf(GraphQlExecutionProfileException.class) - .hasMessageContaining("unregistered resolver"); - } - - @Test - void catalogEntriesUseBoundedSchemaCoordinates() { - assertThatThrownBy( - () -> - new GraphQlResolverDescriptor( - "Order/" + java.util.UUID.randomUUID(), ResolverExecutionType.BLOCKING, false)) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void catalogRejectsDuplicateCoordinatesAndValidatesEveryEntry() { - GraphQlResolverCatalog catalog = new GraphQlResolverCatalog(); - catalog.register( - new GraphQlResolverDescriptor("Order.total", ResolverExecutionType.BLOCKING, false)); - - assertThatThrownBy( - () -> - catalog.register( - new GraphQlResolverDescriptor( - "Order.total", ResolverExecutionType.ASYNC, false))) - .isInstanceOf(IllegalArgumentException.class); - assertThat(catalog.coordinates()).containsExactly("Order.total"); - - assertThatCode(() -> catalog.validateAll(GraphQlExecutionProfile.BLOCKING_MVC)) - .doesNotThrowAnyException(); - assertThatThrownBy(() -> catalog.validateAll(GraphQlExecutionProfile.REACTIVE_WEBFLUX)) - .isInstanceOf(GraphQlExecutionProfileException.class); - } -} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/execution/GraphQlOperationNamePolicyTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/execution/GraphQlOperationNamePolicyTest.java deleted file mode 100644 index 6a694631..00000000 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/execution/GraphQlOperationNamePolicyTest.java +++ /dev/null @@ -1,106 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.execution; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.graphql.api.GraphQlClientProfileName; -import dev.caskeleton.adapter.inbound.graphql.api.GraphQlOperationName; -import dev.caskeleton.adapter.inbound.graphql.context.GraphQlRequestContext; -import dev.caskeleton.adapter.inbound.graphql.testkit.GraphQlRequestContexts; -import org.junit.jupiter.api.Test; - -/** Production operation-name policy (Stable plan Task 34). */ -class GraphQlOperationNamePolicyTest { - - @Test - void productionFirstPartyRejectsAnonymousOperation() { - var policy = GraphQlOperationNamePolicy.production(); - var client = GraphQlClientProfileName.of("FIRST_PARTY"); - - assertThatThrownBy(() -> policy.verify(client, new GraphQlOperationSelection(null, 1, false))) - .isInstanceOf(GraphQlAnonymousOperationException.class); - } - - @Test - void localToleratesASingleAnonymousOperation() { - assertThatCode( - () -> - GraphQlOperationNamePolicy.local() - .verify( - GraphQlClientProfileName.of("FIRST_PARTY"), - new GraphQlOperationSelection(null, 1, false))) - .doesNotThrowAnyException(); - } - - @Test - void aMultiOperationDocumentAlwaysRequiresAName() { - assertThatThrownBy( - () -> - GraphQlOperationNamePolicy.local() - .verify( - GraphQlClientProfileName.of("ADMIN"), - new GraphQlOperationSelection(null, 2, false))) - .isInstanceOf(GraphQlAnonymousOperationException.class) - .hasMessageContaining("multi-operation"); - } - - @Test - void operationNamesAreValidatedAgainstTheBoundedPattern() { - var policy = GraphQlOperationNamePolicy.production(); - - assertThatCode( - () -> - policy.verify( - GraphQlClientProfileName.of("FIRST_PARTY"), - new GraphQlOperationSelection("GetOrder", 1, false))) - .doesNotThrowAnyException(); - assertThatThrownBy( - () -> - policy.verify( - GraphQlClientProfileName.of("FIRST_PARTY"), - new GraphQlOperationSelection("Get Order", 1, false))) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void observationUsesTheNameOrABoundedAnonymousFallback() { - var policy = GraphQlOperationNamePolicy.production(); - - assertThat(policy.observationName(new GraphQlOperationSelection("GetOrder", 1, false))) - .isEqualTo("GetOrder"); - assertThat(policy.observationName(new GraphQlOperationSelection(null, 1, false))) - .isEqualTo(GraphQlOperationName.ANONYMOUS_OBSERVATION_VALUE); - } - - @Test - void persistedOperationNamesMustMatchTheRegistry() { - var policy = GraphQlOperationNamePolicy.production(); - - assertThatCode( - () -> - policy.verifyPersistedName( - "GetOrder", new GraphQlOperationSelection("GetOrder", 1, true))) - .doesNotThrowAnyException(); - assertThatThrownBy( - () -> - policy.verifyPersistedName( - "GetOrder", new GraphQlOperationSelection("GetOtherOrder", 1, true))) - .isInstanceOf(GraphQlAnonymousOperationException.class); - } - - @Test - void theInterceptorPinsTheOperationIdentityOntoTheContext() { - var interceptor = new GraphQlOperationNameInterceptor(GraphQlOperationNamePolicy.production()); - GraphQlRequestContext context = GraphQlRequestContexts.testContext("tenant-a"); - - GraphQlRequestContext bound = - interceptor.apply( - context, - GraphQlClientProfileName.of("FIRST_PARTY"), - new GraphQlOperationSelection("GetOrder", 1, false)); - - assertThat(bound.operationId().value()).isEqualTo("getorder"); - assertThat(context.operationId().value()).isEqualTo("pending"); - } -} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/execution/GraphQlTimeoutPolicyTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/execution/GraphQlTimeoutPolicyTest.java index 5ec3d244..5a5cfefb 100644 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/execution/GraphQlTimeoutPolicyTest.java +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/execution/GraphQlTimeoutPolicyTest.java @@ -3,26 +3,12 @@ package dev.caskeleton.adapter.inbound.graphql.execution; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import dev.caskeleton.adapter.inbound.graphql.api.GraphQlClientProfile; -import dev.caskeleton.adapter.inbound.graphql.api.GraphQlOperationId; -import dev.caskeleton.adapter.inbound.graphql.context.ActorRef; -import dev.caskeleton.adapter.inbound.graphql.context.GraphQlDeadline; -import dev.caskeleton.adapter.inbound.graphql.context.GraphQlRequestContext; -import dev.caskeleton.adapter.inbound.graphql.context.TenantContext; -import java.time.Clock; import java.time.Duration; -import java.time.Instant; -import java.time.ZoneOffset; -import java.util.Locale; -import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.Test; /** Layered timeout, resolver budget and cancellation contract (Stable plan Task 22). */ class GraphQlTimeoutPolicyTest { - private static final Clock CLOCK = - Clock.fixed(Instant.parse("2026-08-12T00:00:00Z"), ZoneOffset.UTC); - @Test void childBudgetCannotExceedParent() { GraphQlTimeoutPolicy policy = new GraphQlTimeoutPolicy(Duration.ofSeconds(2)); @@ -54,79 +40,4 @@ class GraphQlTimeoutPolicyTest { assertThat(GraphQlTimeoutPolicy.TIMEOUT_ERROR_CODE).isEqualTo("REQUEST_TIMEOUT"); assertThat(new GraphQlRequestCancelledException().code()).isEqualTo("REQUEST_TIMEOUT"); } - - @Test - void cancellationReachesRegisteredWorkExactlyOnce() { - GraphQlCancellation cancellation = GraphQlCancellation.create(); - AtomicInteger cancelled = new AtomicInteger(); - cancellation.onCancel(cancelled::incrementAndGet); - - cancellation.cancel(); - cancellation.cancel(); - - assertThat(cancellation.cancelled()).isTrue(); - assertThat(cancelled).hasValue(1); - assertThatThrownBy(cancellation::requireActive) - .isInstanceOf(GraphQlRequestCancelledException.class); - } - - @Test - void workRegisteredAfterCancellationStopsImmediately() { - GraphQlCancellation cancellation = GraphQlCancellation.create(); - cancellation.cancel(); - AtomicInteger cancelled = new AtomicInteger(); - - cancellation.onCancel(cancelled::incrementAndGet); - - assertThat(cancelled).hasValue(1); - } - - @Test - void downstreamDeadlinesAreClampedByWhatRemainsOfTheRequest() { - GraphQlDeadlinePropagator propagator = new GraphQlDeadlinePropagator(CLOCK); - GraphQlRequestContext context = context(Duration.ofSeconds(2)); - - assertThat(propagator.dataLoaderBatchTimeout(context, Duration.ofSeconds(10))) - .isEqualTo(Duration.ofSeconds(2)); - assertThat(propagator.resolverBudget(context, "Order.total", Duration.ofSeconds(10)).budget()) - .isEqualTo(Duration.ofSeconds(2)); - assertThat(propagator.downstreamDeadline(context, Duration.ofSeconds(10)).value()) - .isEqualTo(Instant.parse("2026-08-12T00:00:02Z")); - } - - @Test - void anExpiredRequestBudgetCancelsInsteadOfDerivingANewOne() { - GraphQlDeadlinePropagator propagator = new GraphQlDeadlinePropagator(CLOCK); - GraphQlRequestContext expired = - new GraphQlRequestContext( - ActorRef.anonymous(), - TenantContext.system("platform"), - new GraphQlClientProfile("first-party"), - Locale.ROOT, - new GraphQlOperationId("ping"), - "trace-1", - new GraphQlDeadline(CLOCK.instant())); - - assertThatThrownBy(() -> propagator.requestPolicy(expired)) - .isInstanceOf(GraphQlRequestCancelledException.class); - } - - @Test - void subscriptionLifetimeIsNotGovernedByTheRequestBudget() { - GraphQlDeadlinePropagator propagator = new GraphQlDeadlinePropagator(CLOCK); - - assertThat(propagator.subscriptionDeadline(Duration.ofHours(2)).value()) - .isEqualTo(Instant.parse("2026-08-12T02:00:00Z")); - } - - private static GraphQlRequestContext context(Duration budget) { - return new GraphQlRequestContext( - ActorRef.authenticated("user-1"), - TenantContext.fromAuthenticatedCredential("tenant-a"), - new GraphQlClientProfile("first-party"), - Locale.ROOT, - new GraphQlOperationId("ping"), - "trace-1", - GraphQlDeadline.after(budget, CLOCK)); - } } diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlAcceptNegotiationTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlAcceptNegotiationTest.java deleted file mode 100644 index 43a11b86..00000000 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlAcceptNegotiationTest.java +++ /dev/null @@ -1,126 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.http; - -import static org.assertj.core.api.Assertions.assertThat; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.CsvSource; - -/** - * Content negotiation must answer with something the client asked for. - * - *

The previous implementation walked the server's own preference list and returned the first - * producible type named anywhere in the header. That reads {@code q} as decoration, so a client - * writing {@code application/graphql-response+json;q=0} — a refusal, not a preference — was sent - * exactly the media type it had refused. - */ -class GraphQlAcceptNegotiationTest { - - @Test - void anExplicitRefusalIsNotAPreference() { - String accept = "application/graphql-response+json;q=0, application/json;q=1"; - - assertThat(GraphQlMediaTypes.negotiateResponseContentType(accept)) - .isEqualTo(GraphQlMediaTypes.APPLICATION_JSON); - } - - @Test - void theClientRankingDecidesRatherThanTheServerPreference() { - String accept = "application/json;q=0.9, application/graphql-response+json;q=0.1"; - - assertThat(GraphQlMediaTypes.negotiateResponseContentType(accept)) - .as("the server prefers graphql-response+json; the client does not, and the client wins") - .isEqualTo(GraphQlMediaTypes.APPLICATION_JSON); - } - - @Test - void aConcreteTypeOutranksAWildcardOfEqualQuality() { - String accept = "*/*, application/json"; - - assertThat(GraphQlMediaTypes.negotiateResponseContentType(accept)) - .as("equal quality, so the more specific entry is the one the client meant") - .isEqualTo(GraphQlMediaTypes.APPLICATION_JSON); - } - - @Test - void aWildcardAcceptanceDoesNotOverrideANamedRefusal() { - String accept = "*/*, application/graphql-response+json;q=0"; - - assertThat(GraphQlMediaTypes.negotiateResponseContentType(accept)) - .isEqualTo(GraphQlMediaTypes.APPLICATION_JSON); - } - - @Test - void refusingEverythingProducibleLeavesNothingToSend() { - String accept = "application/graphql-response+json;q=0, application/json;q=0"; - - assertThat(GraphQlMediaTypes.negotiateResponseContentType(accept)).isNull(); - } - - @Test - void anAbsentHeaderMeansNoConstraint() { - assertThat(GraphQlMediaTypes.negotiateResponseContentType(null)) - .isEqualTo(GraphQlMediaTypes.GRAPHQL_RESPONSE_JSON); - assertThat(GraphQlMediaTypes.negotiateResponseContentType(" ")) - .isEqualTo(GraphQlMediaTypes.GRAPHQL_RESPONSE_JSON); - } - - @ParameterizedTest - @CsvSource({ - "'text/html', ", - "'text/*', ", - "'application/xml, text/plain', ", - "'*/*', application/graphql-response+json", - "'application/*', application/graphql-response+json", - "'application/json;charset=utf-8', application/json", - "'APPLICATION/JSON', application/json", - }) - void negotiationFollowsTheHeader(String accept, String expected) { - assertThat(GraphQlMediaTypes.negotiateResponseContentType(accept)).isEqualTo(expected); - } - - @Test - void aMalformedEntryIsDroppedRatherThanFailingTheRequest() { - assertThat(GraphQlMediaTypes.negotiateResponseContentType("garbage, application/json")) - .isEqualTo(GraphQlMediaTypes.APPLICATION_JSON); - assertThat(GraphQlMediaTypes.negotiateResponseContentType("application/json;q=notanumber")) - .as("an unparseable quality falls back to the default rather than dropping the entry") - .isEqualTo(GraphQlMediaTypes.APPLICATION_JSON); - } - - @Test - void anOutOfRangeQualityDoesNotOutrankAnHonestOne() { - String accept = "application/graphql-response+json;q=5, application/json;q=1"; - - assertThat(GraphQlMediaTypes.negotiateResponseContentType(accept)) - .as("q=5 is meaningless; it must not beat a well-formed q=1") - .isEqualTo(GraphQlMediaTypes.GRAPHQL_RESPONSE_JSON); - } - - @Test - void parsingRanksByQualityThenSpecificityThenOrder() { - var entries = GraphQlAcceptHeader.parse("*/*;q=0.5, application/json;q=0.5, text/html;q=0.9"); - - assertThat(entries).hasSize(3); - assertThat(entries.get(0).subtype()).isEqualTo("html"); - assertThat(entries.get(1).subtype()).as("equal quality, higher specificity").isEqualTo("json"); - assertThat(entries.get(2).specificity()).isZero(); - } - - @Test - void aRefusedEntryNeverAppearsInTheRanking() { - var entries = GraphQlAcceptHeader.parse("application/json;q=0, text/html"); - - assertThat(entries) - .singleElement() - .satisfies(entry -> assertThat(entry.subtype()).isEqualTo("html")); - } - - @Test - void theProfileTurnsAnUnsatisfiableHeaderIntoNotAcceptable() { - org.assertj.core.api.Assertions.assertThatThrownBy( - () -> GraphQlHttpProfile.V1.negotiateResponseContentType("text/html")) - .isInstanceOf(GraphQlHttpContractException.class) - .hasMessageContaining("no acceptable GraphQL response media type"); - } -} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlHttpProfileTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlHttpProfileTest.java deleted file mode 100644 index 84172419..00000000 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlHttpProfileTest.java +++ /dev/null @@ -1,78 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.http; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import org.junit.jupiter.api.Test; - -/** Stable HTTP V1 profile and media contract (Stable plan Task 15). */ -class GraphQlHttpProfileTest { - - @Test - void stableProfileRejectsGet() { - assertThatThrownBy(() -> GraphQlHttpProfile.V1.validateMethod("GET")) - .isInstanceOf(GraphQlHttpContractException.class); - } - - @Test - void stableProfileAcceptsPostJson() { - assertThatCode( - () -> { - GraphQlHttpProfile.V1.validateMethod("POST"); - GraphQlHttpProfile.V1.validateContentType("application/json; charset=utf-8"); - }) - .doesNotThrowAnyException(); - } - - @Test - void stableProfileRejectsMultipartAndArrayBatch() { - assertThatThrownBy(() -> GraphQlHttpProfile.V1.rejectUnsupportedTransportFeatures(true, false)) - .isInstanceOf(GraphQlHttpContractException.class) - .hasMessageContaining("Fileserver"); - assertThatThrownBy(() -> GraphQlHttpProfile.V1.rejectUnsupportedTransportFeatures(false, true)) - .isInstanceOf(GraphQlHttpContractException.class) - .hasMessageContaining("array batching"); - assertThatThrownBy(() -> GraphQlHttpProfile.V1.validateContentType("multipart/form-data")) - .isInstanceOf(GraphQlHttpContractException.class); - } - - @Test - void graphqlResponseMediaTypeIsPreferredAndLegacyJsonStaysSupported() { - assertThat(GraphQlHttpProfile.V1.negotiateResponseContentType(null)) - .isEqualTo(GraphQlMediaTypes.GRAPHQL_RESPONSE_JSON); - assertThat( - GraphQlHttpProfile.V1.negotiateResponseContentType( - "application/json, application/graphql-response+json")) - .isEqualTo(GraphQlMediaTypes.GRAPHQL_RESPONSE_JSON); - assertThat(GraphQlHttpProfile.V1.negotiateResponseContentType("application/json")) - .isEqualTo(GraphQlMediaTypes.LEGACY_RESPONSE_JSON); - assertThat(GraphQlHttpProfile.V1.negotiateResponseContentType("*/*")) - .isEqualTo(GraphQlMediaTypes.GRAPHQL_RESPONSE_JSON); - } - - @Test - void unacceptableAcceptHeaderIsRejected() { - assertThatThrownBy(() -> GraphQlHttpProfile.V1.negotiateResponseContentType("text/html")) - .isInstanceOf(GraphQlHttpContractException.class); - } - - @Test - void requestErrorsAreModelledSeparatelyFromExecutionErrors() { - assertThat(GraphQlHttpOutcome.PARSE_ERROR.requestError()).isTrue(); - assertThat(GraphQlHttpOutcome.VALIDATION_ERROR.requestError()).isTrue(); - assertThat(GraphQlHttpOutcome.VARIABLE_COERCION_ERROR.requestError()).isTrue(); - assertThat(GraphQlHttpOutcome.FIELD_ERROR.requestError()).isFalse(); - assertThat(GraphQlHttpOutcome.SUCCESS.requestError()).isFalse(); - } - - @Test - void draftPartialResponseStatusIsNotAdoptedInStable() { - assertThat(GraphQlHttpProfile.V1.usesDraftPartialResponseStatus()).isFalse(); - assertThat(GraphQlHttpProfile.DRAFT_PARTIAL_RESPONSE_STATUS).isEqualTo(294); - for (GraphQlHttpOutcome outcome : GraphQlHttpOutcome.values()) { - assertThat(GraphQlHttpStatusMapper.V1.status(outcome)) - .isNotEqualTo(GraphQlHttpProfile.DRAFT_PARTIAL_RESPONSE_STATUS); - } - } -} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlHttpStatusMapperTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlHttpStatusMapperTest.java deleted file mode 100644 index b537c44f..00000000 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlHttpStatusMapperTest.java +++ /dev/null @@ -1,96 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.http; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.util.List; -import java.util.Map; -import org.junit.jupiter.api.Test; - -/** HTTP request-error and execution-error status mapping (Stable plan Task 17). */ -class GraphQlHttpStatusMapperTest { - - @Test - void fieldErrorUsesHttp200() { - assertThat(GraphQlHttpStatusMapper.V1.status(GraphQlHttpOutcome.FIELD_ERROR)).isEqualTo(200); - } - - @Test - void preExecutionFailuresUseBounded4xxStatuses() { - assertThat(GraphQlHttpStatusMapper.V1.status(GraphQlHttpOutcome.MALFORMED_REQUEST)) - .isEqualTo(400); - assertThat(GraphQlHttpStatusMapper.V1.status(GraphQlHttpOutcome.PARSE_ERROR)).isEqualTo(400); - assertThat(GraphQlHttpStatusMapper.V1.status(GraphQlHttpOutcome.VALIDATION_ERROR)) - .isEqualTo(400); - assertThat(GraphQlHttpStatusMapper.V1.status(GraphQlHttpOutcome.VARIABLE_COERCION_ERROR)) - .isEqualTo(400); - assertThat(GraphQlHttpStatusMapper.V1.status(GraphQlHttpOutcome.UNSUPPORTED_METHOD)) - .isEqualTo(405); - assertThat(GraphQlHttpStatusMapper.V1.status(GraphQlHttpOutcome.NOT_ACCEPTABLE)).isEqualTo(406); - assertThat(GraphQlHttpStatusMapper.V1.status(GraphQlHttpOutcome.REQUEST_TOO_LARGE)) - .isEqualTo(413); - assertThat(GraphQlHttpStatusMapper.V1.status(GraphQlHttpOutcome.UNSUPPORTED_MEDIA_TYPE)) - .isEqualTo(415); - } - - @Test - void partialDataSurvivesAFieldError() { - GraphQlHttpResponse response = - GraphQlHttpResponseFactory.preferredV1() - .fieldError( - Map.of("order", Map.of("id", "o-1")), - List.of(Map.of("message", "요청을 처리할 수 없습니다."))); - - assertThat(response.status()).isEqualTo(200); - assertThat(response.partial()).isTrue(); - assertThat(response.data()).containsKey("order"); - assertThat(response.errors()).hasSize(1); - } - - @Test - void legacyJsonClientsKeepReceiving200ForRequestErrors() { - GraphQlHttpResponse preferred = - GraphQlHttpResponseFactory.v1(GraphQlMediaTypes.GRAPHQL_RESPONSE_JSON) - .requestError(GraphQlHttpOutcome.PARSE_ERROR, List.of(Map.of("message", "parse"))); - GraphQlHttpResponse legacy = - GraphQlHttpResponseFactory.v1(GraphQlMediaTypes.LEGACY_RESPONSE_JSON) - .requestError(GraphQlHttpOutcome.PARSE_ERROR, List.of(Map.of("message", "parse"))); - - assertThat(preferred.status()).isEqualTo(400); - assertThat(preferred.contentType()).isEqualTo(GraphQlMediaTypes.GRAPHQL_RESPONSE_JSON); - assertThat(legacy.status()).isEqualTo(200); - assertThat(legacy.contentType()).isEqualTo(GraphQlMediaTypes.LEGACY_RESPONSE_JSON); - } - - @Test - void statusMappingIsVersionedByProfile() { - assertThat(GraphQlHttpStatusMapper.values()).containsExactly(GraphQlHttpStatusMapper.V1); - assertThat( - GraphQlHttpStatusMapper.V1.status( - GraphQlHttpOutcome.FIELD_ERROR, GraphQlHttpResponsePolicy.legacy())) - .isEqualTo(200); - } - - @Test - void aNonRequestErrorCannotBeReportedAsOne() { - assertThatThrownBy( - () -> - GraphQlHttpResponseFactory.preferredV1() - .requestError(GraphQlHttpOutcome.FIELD_ERROR, List.of())) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void transportViolationsBecomeAResponseWithTheMandatedStatus() { - GraphQlHttpResponse response = - GraphQlHttpResponseFactory.preferredV1() - .requestError( - new GraphQlHttpContractException( - "POST required", GraphQlHttpOutcome.UNSUPPORTED_METHOD)); - - assertThat(response.status()).isEqualTo(405); - assertThat(response.errors()) - .singleElement() - .satisfies(error -> assertThat(error).containsKey("extensions")); - } -} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlRequestEnvelopeValidatorTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlRequestEnvelopeValidatorTest.java index de92d9ab..0e5595da 100644 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlRequestEnvelopeValidatorTest.java +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlRequestEnvelopeValidatorTest.java @@ -3,6 +3,7 @@ package dev.caskeleton.adapter.inbound.graphql.http; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; import dev.caskeleton.adapter.inbound.graphql.policy.GraphQlClientPolicy; import java.nio.charset.StandardCharsets; @@ -61,15 +62,33 @@ class GraphQlRequestEnvelopeValidatorTest { } @Test - void onlyRegisteredExtensionKeysAreAccepted() { + void stableDefaultsRegisterNoExtensionKey() { + assertThat(GraphQlExtensionsPolicy.stableDefaults().allowedKeys()).isEmpty(); + } + + @Test + void stableDefaultsRejectAnIdempotencyKeyExtensionAsUnregistered() { + // given GraphQlExtensionsPolicy policy = GraphQlExtensionsPolicy.stableDefaults(); - assertThat(policy.allowedKeys()).containsExactly(GraphQlExtensionsPolicy.IDEMPOTENCY_KEY); - assertThatCode(() -> policy.verify(Map.of("idempotencyKey", "request-1"))) - .doesNotThrowAnyException(); - assertThatThrownBy(() -> policy.verify(Map.of("debugMode", true))) + // when + Throwable thrown = catchThrowable(() -> policy.verify(Map.of("idempotencyKey", "request-1"))); + + // then + assertThat(thrown) .isInstanceOf(GraphQlRequestFormatException.class) - .hasMessageContaining("debugMode"); + .hasMessage("unregistered GraphQL extensions key(s): [idempotencyKey]"); + } + + @Test + void aRegisteredExtensionKeyDoesNotThrow() { + // given + GraphQlExtensionsPolicy policy = + GraphQlExtensionsPolicy.allowing(GraphQlExtensionsPolicy.PERSISTED_QUERY); + + // when & then + assertThatCode(() -> policy.verify(Map.of(GraphQlExtensionsPolicy.PERSISTED_QUERY, Map.of()))) + .doesNotThrowAnyException(); } @Test @@ -124,11 +143,8 @@ class GraphQlRequestEnvelopeValidatorTest { 20, 100, 10000, - 10000, - 5_242_880, Duration.ofSeconds(5), false, - false, namedOperationRequired); } } diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/moduleboundary/GraphQlBuildModel.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/moduleboundary/GraphQlBuildModel.java deleted file mode 100644 index aca33a89..00000000 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/moduleboundary/GraphQlBuildModel.java +++ /dev/null @@ -1,293 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.moduleboundary; - -import java.io.IOException; -import java.io.UncheckedIOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.TreeMap; -import java.util.TreeSet; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.stream.Stream; - -/** - * Reads a GraphQL platform source tree and reports where it disagrees with the declared module map. - * - *

This deliberately works on source text rather than on compiled classes. An import that a - * boundary forbids has usually been erased by the compiler — a constant is inlined, a type is only - * named in a signature that is not retained — so a bytecode scan would report a boundary as clean - * while the source that a reviewer reads still crosses it. - * - *

It lives in the test source set on purpose. Scanning a checkout is build-time work: a running - * application has no source tree to scan, and a runtime scan would fail exactly in the packaged - * environments where nothing is wrong. - * - *

Every entry point refuses to report success on an empty scan. A boundary rule that passes - * because it found no files is the failure mode this whole model exists to prevent. - */ -public final class GraphQlBuildModel { - - /** - * Import prefixes that make a module framework bound. - * - *

{@code jakarta} covers servlet and validation, {@code io.micrometer} covers observation: - * both bind a module to a runtime just as firmly as Spring does. - */ - public static final Pattern FRAMEWORK_IMPORT = - Pattern.compile("^(org\\.springframework|graphql|reactor|io\\.micrometer|jakarta)\\."); - - private static final Pattern IMPORT_STATEMENT = - Pattern.compile("^\\s*import\\s+(?:static\\s+)?([\\w.]+)\\s*;", Pattern.MULTILINE); - - private static final Pattern PACKAGE_STATEMENT = - Pattern.compile("^\\s*package\\s+([\\w.]+)\\s*;", Pattern.MULTILINE); - - private GraphQlBuildModel() {} - - /** - * Scans every source root the platform's module map governs. - * - *

Both {@code src/main/java} and {@code src/testFixtures/java}, because the module map is - * about package boundaries and those hold regardless of which artifact a package ships in. The - * testkit moved to test fixtures so it would stop shipping in the production jar; scanning only - * main would have quietly stopped checking its edges at the same moment, which is the wrong half - * of that change to keep. - */ - public static GraphQlSourceGraph scanPlatformSources() { - return scan(platformSourceRoots()); - } - - /** Scans this leaf's production sources only. */ - public static GraphQlSourceGraph scanMainSources() { - return scan(mainSourceRoot()); - } - - /** - * Scans a Java source root — the directory that directly contains the {@code dev} package folder. - * - * @throws IllegalStateException when the root holds no platform source at all - */ - public static GraphQlSourceGraph scan(Path sourceRoot) { - return scan(List.of(sourceRoot)); - } - - /** - * Scans several Java source roots as one platform. - * - * @throws IllegalStateException when the roots hold no platform source at all - */ - public static GraphQlSourceGraph scan(List sourceRoots) { - Map> edges = new TreeMap<>(); - Map> frameworkImports = new TreeMap<>(); - Set packages = new TreeSet<>(); - int fileCount = 0; - - List files = new ArrayList<>(); - for (Path sourceRoot : sourceRoots) { - files.addAll(javaFilesUnder(sourceRoot)); - } - for (Path file : files) { - String source = read(file); - String packageName = declaredPackage(source).orElse(null); - if (packageName == null || !GraphQlModuleBoundary.insidePlatform(packageName)) { - continue; - } - fileCount++; - packages.add(packageName); - String moduleId = GraphQlModuleBoundary.moduleIdForPackage(packageName).orElse(null); - if (moduleId == null) { - // An unregistered package still has to appear in `packages` so the rule can name it, but it - // owns no module identity and therefore contributes no edges. - continue; - } - edges.computeIfAbsent(moduleId, key -> new TreeSet<>()); - frameworkImports.computeIfAbsent(moduleId, key -> new TreeSet<>()); - - Matcher matcher = IMPORT_STATEMENT.matcher(source); - while (matcher.find()) { - String imported = matcher.group(1); - if (GraphQlModuleBoundary.insidePlatform(imported)) { - importedModule(imported) - .filter(target -> !target.equals(moduleId)) - .ifPresent(target -> edges.get(moduleId).add(target)); - } else if (FRAMEWORK_IMPORT.matcher(imported).find()) { - frameworkImports.get(moduleId).add(imported); - } - } - } - - if (fileCount == 0) { - throw new IllegalStateException( - "no GraphQL platform source was found under " - + sourceRoots.stream().map(root -> root.toAbsolutePath().toString()).toList() - + "; a boundary rule must never pass by scanning nothing"); - } - return new GraphQlSourceGraph(edges, frameworkImports, packages, fileCount); - } - - /** Packages that hold source but were never given a module identity. */ - public static List undeclaredPackages(GraphQlSourceGraph graph) { - return graph.packages().stream() - .filter(packageName -> GraphQlModuleBoundary.moduleIdForPackage(packageName).isEmpty()) - .sorted() - .toList(); - } - - /** Declared modules whose package holds no source, so the declaration describes nothing. */ - public static List declaredButAbsentModules(GraphQlSourceGraph graph) { - List absent = new ArrayList<>(); - GraphQlModuleBoundary.packagesById() - .forEach( - (moduleId, packageName) -> { - boolean present = - graph.packages().stream() - .anyMatch( - scanned -> - scanned.equals(packageName) || scanned.startsWith(packageName + ".")); - if (!present) { - absent.add(moduleId + " (" + packageName + ")"); - } - }); - absent.sort(String::compareTo); - return List.copyOf(absent); - } - - /** Imports that cross a module boundary the declaration does not allow. */ - public static List undeclaredEdges(GraphQlSourceGraph graph) { - List violations = new ArrayList<>(); - graph - .moduleEdges() - .forEach( - (from, targets) -> - targets.stream() - .filter(to -> !GraphQlModuleBoundary.edgeAllowed(from, to)) - .forEach(to -> violations.add(from + " -> " + to))); - violations.sort(String::compareTo); - return List.copyOf(violations); - } - - /** Stable modules that import an Advanced capability, in any direction-breaking form. */ - public static List stableToAdvancedImports(GraphQlSourceGraph graph) { - Set stable = GraphQlStableModule.moduleIds(); - Set advanced = GraphQlAdvancedModule.moduleIds(); - List violations = new ArrayList<>(); - graph - .moduleEdges() - .forEach( - (from, targets) -> { - if (!stable.contains(from)) { - return; - } - targets.stream() - .filter(advanced::contains) - .forEach(to -> violations.add(from + " -> " + to)); - }); - violations.sort(String::compareTo); - return List.copyOf(violations); - } - - /** Framework imports found in modules declared {@link GraphQlModulePurity#CORE}. */ - public static List frameworkImportsInCoreModules(GraphQlSourceGraph graph) { - Set core = GraphQlModuleBoundary.coreModuleIds(); - List violations = new ArrayList<>(); - graph - .frameworkImports() - .forEach( - (moduleId, imports) -> { - if (!core.contains(moduleId)) { - return; - } - imports.forEach(imported -> violations.add(moduleId + " imports " + imported)); - }); - violations.sort(String::compareTo); - return List.copyOf(violations); - } - - /** - * Locates this leaf's production source root. - * - * @throws IllegalStateException when it cannot be found, rather than returning a path that would - * scan to zero files - */ - /** - * Every source root the module map governs: production plus test fixtures. - * - * @throws IllegalStateException when the production root cannot be found - */ - public static List platformSourceRoots() { - Path main = mainSourceRoot(); - Path fixtures = main.getParent().getParent().resolve("testFixtures").resolve("java"); - return Files.isDirectory(fixtures) ? List.of(main, fixtures) : List.of(main); - } - - public static Path mainSourceRoot() { - String packagePath = GraphQlModuleBoundary.PACKAGE_ROOT.replace('.', '/'); - for (Path directory = Path.of("").toAbsolutePath(); - directory != null; - directory = directory.getParent()) { - Path candidate = directory.resolve("src").resolve("main").resolve("java"); - if (Files.isDirectory(candidate.resolve(packagePath))) { - return candidate; - } - } - throw new IllegalStateException( - "cannot locate src/main/java/" - + packagePath - + " from " - + Path.of("").toAbsolutePath() - + "; the module boundary rules have nothing to check"); - } - - private static Optional importedModule(String importedType) { - int lastDot = importedType.lastIndexOf('.'); - if (lastDot < 0) { - return Optional.empty(); - } - // A static import names a member, so peel qualifiers until one resolves to a declared module. - for (String candidate = importedType.substring(0, lastDot); - candidate.length() >= GraphQlModuleBoundary.PACKAGE_ROOT.length(); - candidate = candidate.substring(0, Math.max(candidate.lastIndexOf('.'), 0))) { - Optional moduleId = GraphQlModuleBoundary.moduleIdForPackage(candidate); - if (moduleId.isPresent()) { - return moduleId; - } - if (candidate.lastIndexOf('.') < 0) { - break; - } - } - return Optional.empty(); - } - - private static Optional declaredPackage(String source) { - Matcher matcher = PACKAGE_STATEMENT.matcher(source); - return matcher.find() ? Optional.of(matcher.group(1)) : Optional.empty(); - } - - private static List javaFilesUnder(Path root) { - if (!Files.isDirectory(root)) { - throw new IllegalStateException("source root does not exist: " + root.toAbsolutePath()); - } - try (Stream files = Files.walk(root)) { - return files - .filter(Files::isRegularFile) - .filter(path -> path.getFileName().toString().endsWith(".java")) - .sorted() - .toList(); - } catch (IOException ex) { - throw new UncheckedIOException(ex); - } - } - - private static String read(Path file) { - try { - return Files.readString(file); - } catch (IOException ex) { - throw new UncheckedIOException(ex); - } - } -} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/moduleboundary/GraphQlModuleBoundaryTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/moduleboundary/GraphQlModuleBoundaryTest.java deleted file mode 100644 index d324b1bc..00000000 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/moduleboundary/GraphQlModuleBoundaryTest.java +++ /dev/null @@ -1,190 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.moduleboundary; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.graphql.advanced.bootstrap.GraphQlAdvancedDependencyRules; -import java.io.IOException; -import java.io.UncheckedIOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.stream.Stream; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -/** - * The machine check behind the "bounded packages instead of Gradle leaves" decision. - * - *

Splitting the platform into sub-packages of one leaf buys nothing unless the split is - * enforced, and a Gradle dependency gate cannot see inside a leaf. So this test does what the gate - * cannot: it scans the real production tree and compares it against the declared module map. - * - *

The negative fixtures matter as much as the positive assertions. A boundary test that has - * never been shown to fail is indistinguishable from one that scans the wrong directory, and this - * leaf has already lost a boundary model once by making it invisible to Git. Each rule therefore - * gets a synthetic tree that must be rejected. - */ -class GraphQlModuleBoundaryTest { - - private static final String ROOT = GraphQlModuleBoundary.PACKAGE_ROOT; - - private static GraphQlSourceGraph production; - - @BeforeAll - static void scanProductionTree() { - production = GraphQlBuildModel.scanPlatformSources(); - } - - @Test - void theScanActuallyReadsTheProductionTree() { - assertThat(production.fileCount()) - .as("the platform is a few hundred files; a scan far below that is reading the wrong tree") - .isGreaterThan(300); - assertThat(production.packages()).contains(ROOT, ROOT + ".runtime", ROOT + ".advanced.sse"); - } - - @Test - void everyProductionPackageHasADeclaredModuleIdentity() { - assertThat(GraphQlBuildModel.undeclaredPackages(production)) - .as("add the package to GraphQlStableModule or GraphQlAdvancedModule before shipping it") - .isEmpty(); - } - - @Test - void everyDeclaredModuleExistsInTheProductionTree() { - assertThat(GraphQlBuildModel.declaredButAbsentModules(production)) - .as("a declared module with no source describes nothing and hides a rename") - .isEmpty(); - } - - @Test - void everyCrossModuleImportIsADeclaredEdge() { - assertThat(GraphQlBuildModel.undeclaredEdges(production)).isEmpty(); - } - - @Test - void stableModulesNeverImportAnAdvancedCapability() { - assertThat(GraphQlBuildModel.stableToAdvancedImports(production)).isEmpty(); - assertThatCode(GraphQlAdvancedDependencyRules::verifyStableDoesNotDependOnAdvanced) - .as("the declared edges and the scanned tree must agree on the direction") - .doesNotThrowAnyException(); - } - - @Test - void coreModulesStayFrameworkFree() { - assertThat(GraphQlBuildModel.frameworkImportsInCoreModules(production)) - .as("a CORE module may not bind to Spring, GraphQL Java, Reactor, Micrometer or Jakarta") - .isEmpty(); - } - - @Test - void frameworkBoundModulesAreTheOnlyOnesThatTouchTheFramework() { - var frameworkBound = - production.frameworkImports().entrySet().stream() - .filter(entry -> !entry.getValue().isEmpty()) - .map(Map.Entry::getKey) - .collect(Collectors.toSet()); - - assertThat(frameworkBound) - .as( - "keep GraphQlModulePurity honest: these are the modules that actually import Spring etc") - .containsExactlyInAnyOrder( - "root", - "advanced.codegen", - "architecture", - "autoconfigure", - "compat", - "cost", - "runtime", - "scalar", - "schema"); - } - - @Test - void aStableModuleImportingAnAdvancedCapabilityIsRejected(@TempDir Path tree) { - writeType(tree, ROOT + ".policy", "LeakyPolicy", ROOT + ".advanced.persisted.SomeRegistry"); - - var graph = GraphQlBuildModel.scan(tree); - - assertThat(GraphQlBuildModel.stableToAdvancedImports(graph)) - .containsExactly("policy -> advanced.persisted"); - assertThat(GraphQlBuildModel.undeclaredEdges(graph)) - .containsExactly("policy -> advanced.persisted"); - } - - @Test - void aFrameworkImportInACoreModuleIsRejected(@TempDir Path tree) { - writeType( - tree, ROOT + ".execution", "BoundExecution", "org.springframework.stereotype.Component"); - - var graph = GraphQlBuildModel.scan(tree); - - assertThat(GraphQlBuildModel.frameworkImportsInCoreModules(graph)) - .containsExactly("execution imports org.springframework.stereotype.Component"); - } - - @Test - void aPackageWithNoDeclaredModuleIsRejected(@TempDir Path tree) { - writeType(tree, ROOT + ".unregistered", "SurpriseCapability"); - - var graph = GraphQlBuildModel.scan(tree); - - assertThat(GraphQlBuildModel.undeclaredPackages(graph)).containsExactly(ROOT + ".unregistered"); - } - - @Test - void anUndeclaredEdgeBetweenTwoDeclaredModulesIsRejected(@TempDir Path tree) { - writeType( - tree, ROOT + ".api", "ApiReachingIntoSchema", ROOT + ".schema.GraphQlSchemaAssembler"); - - var graph = GraphQlBuildModel.scan(tree); - - assertThat(GraphQlBuildModel.undeclaredEdges(graph)).containsExactly("api -> schema"); - assertThat(GraphQlBuildModel.stableToAdvancedImports(graph)) - .as("an undeclared Stable edge is not a Stable->Advanced violation") - .isEmpty(); - } - - @Test - void aScanThatFindsNothingFailsInsteadOfPassing(@TempDir Path empty) { - assertThatThrownBy(() -> GraphQlBuildModel.scan(empty)) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("must never pass by scanning nothing"); - } - - @Test - void theRootModuleOwnsOnlyTheRootPackage() { - assertThat(GraphQlModuleBoundary.moduleIdForPackage(ROOT)).contains("root"); - assertThat(GraphQlModuleBoundary.moduleIdForPackage(ROOT + ".http.negotiation")) - .as("a descendant belongs to the module that owns its nearest declared ancestor") - .contains("http"); - assertThat(GraphQlModuleBoundary.moduleIdForPackage(ROOT + ".advanced.sse")) - .as("the longest declared prefix wins, so this is advanced.sse and not advanced") - .contains("advanced.sse"); - assertThat(GraphQlModuleBoundary.moduleIdForPackage(ROOT + ".unregistered")).isEmpty(); - assertThat(GraphQlModuleBoundary.moduleIdForPackage("dev.caskeleton.adapter.inbound.web")) - .isEmpty(); - } - - private static void writeType( - Path sourceRoot, String packageName, String typeName, String... imports) { - Path directory = sourceRoot.resolve(packageName.replace('.', '/')); - String body = - Stream.concat( - Stream.of("package " + packageName + ";", ""), - Stream.concat( - Stream.of(imports).map(imported -> "import " + imported + ";"), - Stream.of("", "final class " + typeName + " {}"))) - .collect(Collectors.joining("\n")); - try { - Files.createDirectories(directory); - Files.writeString(directory.resolve(typeName + ".java"), body + "\n"); - } catch (IOException ex) { - throw new UncheckedIOException(ex); - } - } -} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/moduleboundary/GraphQlSourceGraph.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/moduleboundary/GraphQlSourceGraph.java deleted file mode 100644 index 143beb79..00000000 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/moduleboundary/GraphQlSourceGraph.java +++ /dev/null @@ -1,30 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.moduleboundary; - -import java.util.Map; -import java.util.Set; - -/** - * What a scan of a GraphQL platform source tree actually found. - * - *

Everything here is observed, never declared: {@link GraphQlStableModule} and {@link - * GraphQlAdvancedModule} say what the module map is supposed to be, and this record says what the - * checkout is. The boundary rules are the comparison between the two. - * - * @param moduleEdges module identifier to the module identifiers it imports, self-edges excluded - * @param frameworkImports module identifier to the framework imports it uses, empty when pure - * @param packages every package that contained at least one Java file - * @param fileCount how many Java files were read, so a rule can refuse to pass on an empty scan - */ -public record GraphQlSourceGraph( - Map> moduleEdges, - Map> frameworkImports, - Set packages, - int fileCount) { - - /** Canonicalises the collections so callers cannot mutate a scan result. */ - public GraphQlSourceGraph { - moduleEdges = Map.copyOf(moduleEdges); - frameworkImports = Map.copyOf(frameworkImports); - packages = Set.copyOf(packages); - } -} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/mutation/GraphQlMutationIdempotencyContextTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/mutation/GraphQlMutationIdempotencyContextTest.java deleted file mode 100644 index 7c3df320..00000000 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/mutation/GraphQlMutationIdempotencyContextTest.java +++ /dev/null @@ -1,318 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.mutation; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.graphql.context.ActorRef; -import dev.caskeleton.adapter.inbound.graphql.context.GraphQlIdentityFingerprinter; -import dev.caskeleton.adapter.inbound.graphql.context.GraphQlRequestContext; -import dev.caskeleton.adapter.inbound.graphql.context.TenantContext; -import dev.caskeleton.adapter.inbound.graphql.http.GraphQlExtensionsPolicy; -import dev.caskeleton.adapter.inbound.graphql.testkit.GraphQlRequestContexts; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import org.junit.jupiter.api.Test; - -/** Mutation idempotency scope and fingerprint (Stable plan Task 43). */ -class GraphQlMutationIdempotencyContextTest { - - /** - * One generator for the whole class, declared before the keys that draw from it. - * - *

Static initialisers run in textual order, so a generator declared below the two key - * constants would still be null when they are built. Seeding a fresh {@code SecureRandom} per - * call is also what SpotBugs reports as {@code DMI_RANDOM_USED_ONLY_ONCE}. - */ - private static final java.security.SecureRandom KEYS = new java.security.SecureRandom(); - - private static final String TENANT = "tenant-fingerprint"; - private static final String VERSION = "v1"; - private static final GraphQlMutationCoordinate CREATE = - new GraphQlMutationCoordinate("Mutation.createOrder"); - - // Two rings standing for one deployment before and after a rotation. Both secrets are generated - // here rather than written down, so nothing in this file is a key anyone could reuse. - private static final GraphQlIdentityFingerprinter FIRST_KEY = - GraphQlIdentityFingerprinter.single("k1", randomKey()); - private static final GraphQlIdentityFingerprinter ROTATED_KEY = - GraphQlIdentityFingerprinter.single("k2", randomKey()); - - private static byte[] randomKey() { - byte[] secret = new byte[32]; - KEYS.nextBytes(secret); - return secret; - } - - @Test - void sameKeyWithDifferentFingerprintIsConflict() { - var first = context(CREATE, new GraphQlMutationFingerprint("sha256:a")); - - assertThatThrownBy(() -> first.assertCompatible(new GraphQlMutationFingerprint("sha256:b"))) - .isInstanceOf(GraphQlIdempotencyConflictException.class); - } - - @Test - void sameKeyWithTheSameFingerprintIsARetry() { - var context = - context( - CREATE, GraphQlMutationFingerprint.of(Map.of("customerId", "c-1", "total", "10.00"))); - - assertThatCode( - () -> - context.assertCompatible( - GraphQlMutationFingerprint.of(Map.of("total", "10.00", "customerId", "c-1")))) - .doesNotThrowAnyException(); - } - - @Test - void theScopeCoversActorTenantMutationVersionAndKey() { - String scope = context(CREATE, new GraphQlMutationFingerprint("sha256:a")).scope(); - - assertThat(scope) - .contains("actor-fingerprint") - .contains(TENANT) - .contains("Mutation.createOrder") - .contains(VERSION) - .contains("request-1"); - } - - @Test - void theSameKeyInADifferentTenantIsADifferentScope() { - var tenantA = context(CREATE, new GraphQlMutationFingerprint("sha256:a")); - var tenantB = - GraphQlMutationIdempotencyContext.of( - "actor-fingerprint", - "other-tenant-fingerprint", - CREATE, - VERSION, - new GraphQlIdempotencyKey("request-1"), - new GraphQlMutationFingerprint("sha256:a")); - - assertThat(tenantA.scope()) - .as("one service account acting for two tenants must not share an idempotency namespace") - .isNotEqualTo(tenantB.scope()); - } - - @Test - void theSameKeyUnderADifferentContractVersionIsADifferentScope() { - var v1 = context(CREATE, new GraphQlMutationFingerprint("sha256:a")); - var v2 = - GraphQlMutationIdempotencyContext.of( - "actor-fingerprint", - TENANT, - CREATE, - "v2", - new GraphQlIdempotencyKey("request-1"), - new GraphQlMutationFingerprint("sha256:a")); - - assertThat(v1.scope()).isNotEqualTo(v2.scope()); - } - - @Test - void theSameKeyOnADifferentMutationIsADifferentScope() { - var create = context(CREATE, new GraphQlMutationFingerprint("sha256:a")); - var cancel = - context( - new GraphQlMutationCoordinate("Mutation.cancelOrder"), - new GraphQlMutationFingerprint("sha256:a")); - - assertThatThrownBy(() -> GraphQlMutationIdempotencyInterceptor.verifyRetry(create, cancel)) - .isInstanceOf(GraphQlIdempotencyConflictException.class); - } - - @Test - void aSeparatorInsideAValueCannotForgeADifferentScope() { - var honest = - GraphQlMutationIdempotencyContext.of( - "actor", - TENANT, - CREATE, - VERSION, - new GraphQlIdempotencyKey("request-0001"), - new GraphQlMutationFingerprint("sha256:a")); - var crafted = - GraphQlMutationIdempotencyContext.of( - "actor|" + TENANT, - TENANT, - CREATE, - VERSION, - new GraphQlIdempotencyKey("request-0001"), - new GraphQlMutationFingerprint("sha256:a")); - - assertThat(honest.scope()).isNotEqualTo(crafted.scope()); - } - - @Test - void twoDifferentInputsNeverShareAFingerprint() { - // The pair the previous canonical form collided on: joining `key=value;` made these identical. - var packed = GraphQlMutationFingerprint.of(Map.of("a", "b;c=d")); - var split = GraphQlMutationFingerprint.of(Map.of("a", "b", "c", "d")); - - assertThat(packed).isNotEqualTo(split); - } - - @Test - void aStringAndANumberWithTheSameTextAreDifferentInputs() { - assertThat(GraphQlMutationFingerprint.of(Map.of("total", "1"))) - .isNotEqualTo(GraphQlMutationFingerprint.of(Map.of("total", 1))); - } - - @Test - void equivalentNumbersFingerprintIdentically() { - assertThat(GraphQlMutationFingerprint.of(Map.of("total", new java.math.BigDecimal("1.0")))) - .as("1, 1.0 and 1e0 are the same value and a client library may send any of them") - .isEqualTo(GraphQlMutationFingerprint.of(Map.of("total", 1))); - } - - @Test - void nestedMapsAreSortedRecursively() { - Map first = new LinkedHashMap<>(); - first.put("filter", new LinkedHashMap<>(Map.of("status", "OPEN", "owner", "o-1"))); - Map second = new LinkedHashMap<>(); - second.put("filter", new LinkedHashMap<>(Map.of("owner", "o-1", "status", "OPEN"))); - - assertThat(GraphQlMutationFingerprint.of(first)) - .isEqualTo(GraphQlMutationFingerprint.of(second)); - } - - @Test - void listOrderIsPartOfTheInput() { - assertThat(GraphQlMutationFingerprint.of(Map.of("ids", List.of("a", "b")))) - .as("a list is a sequence; two orders are two different requests") - .isNotEqualTo(GraphQlMutationFingerprint.of(Map.of("ids", List.of("b", "a")))); - } - - @Test - void anExplicitNullIsNotAnAbsentField() { - Map explicitNull = new LinkedHashMap<>(); - explicitNull.put("note", null); - - assertThat(GraphQlMutationFingerprint.of(explicitNull)) - .isNotEqualTo(GraphQlMutationFingerprint.of(Map.of())); - } - - @Test - void onlyAMutationCoordinateCanCarryAnIdempotencyScope() { - assertThatThrownBy(() -> new GraphQlMutationCoordinate("Query.order")) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void idempotencyKeysAreLengthBounded() { - assertThatThrownBy(() -> new GraphQlIdempotencyKey("short")) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> new GraphQlIdempotencyKey("x".repeat(129))) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void theInterceptorDerivesTheScopeFromTheIdempotencyExtension() { - GraphQlRequestContext context = GraphQlRequestContexts.testContext("tenant-a"); - - var derived = - GraphQlMutationIdempotencyInterceptor.from( - context, - FIRST_KEY, - CREATE, - VERSION, - Map.of(GraphQlExtensionsPolicy.IDEMPOTENCY_KEY, "request-1"), - Map.of("customerId", "c-1")); - - assertThat(derived) - .hasValueSatisfying( - scope -> { - assertThat(scope.key().value()).isEqualTo("request-1"); - assertThat(scope.actorFingerprint()).isEqualTo(FIRST_KEY.actor(context.actor())); - assertThat(scope.tenantFingerprint()).isEqualTo(FIRST_KEY.tenant(context.tenant())); - assertThat(scope.contractVersion()).isEqualTo(VERSION); - }); - assertThat( - GraphQlMutationIdempotencyInterceptor.from( - context, FIRST_KEY, CREATE, VERSION, Map.of(), Map.of())) - .isEmpty(); - } - - @Test - void rotatingTheFingerprintKeyChangesTheStoredScope() { - GraphQlRequestContext context = GraphQlRequestContexts.testContext("tenant-a"); - - String first = derivedScope(context, FIRST_KEY); - String rotated = derivedScope(context, ROTATED_KEY); - - assertThat(first) - .as( - "an unkeyed digest of a guessable actor is recovered by digesting the guesses, and a " - + "deployment that suspects its stored scopes have been read has no way to change " - + "them unless the fingerprint depends on a key it controls") - .isNotEqualTo(rotated); - } - - @Test - void anActorAndATenantOfTheSameNameDoNotShareAFingerprint() { - assertThat(FIRST_KEY.actor(ActorRef.authenticated("acme"))) - .as("a service account and a tenant that happen to share a name are two identities") - .isNotEqualTo(FIRST_KEY.tenant(TenantContext.fromAuthenticatedCredential("acme"))); - } - - @Test - void derivingAScopeWithoutAFingerprintKeyIsRefused() { - GraphQlRequestContext context = GraphQlRequestContexts.testContext("tenant-a"); - - assertThatThrownBy( - () -> - GraphQlMutationIdempotencyInterceptor.from( - context, - null, - CREATE, - VERSION, - Map.of(GraphQlExtensionsPolicy.IDEMPOTENCY_KEY, "request-1"), - Map.of("customerId", "c-1"))) - .as("a deployment with no key must not silently fall back to a recoverable digest") - .isInstanceOf(IllegalArgumentException.class); - } - - private static String derivedScope( - GraphQlRequestContext context, GraphQlIdentityFingerprinter fingerprinter) { - return GraphQlMutationIdempotencyInterceptor.from( - context, - fingerprinter, - CREATE, - VERSION, - Map.of(GraphQlExtensionsPolicy.IDEMPOTENCY_KEY, "request-1"), - Map.of("customerId", "c-1")) - .orElseThrow() - .scope(); - } - - @Test - void fingerprintsAndScopesNeverCarryRawInputOrActor() { - var fingerprint = GraphQlMutationFingerprint.of(Map.of("card", "4111111111111111")); - - assertThat(fingerprint.value()).startsWith("sha256:").doesNotContain("4111"); - assertThat(context(CREATE, fingerprint).scope()).doesNotContain("4111"); - } - - @Test - void anAtomicMutationIsExactlyOneUseCase() { - assertThatCode(() -> GraphQlMutationContractValidator.requireSingleUseCase(CREATE, 1)) - .doesNotThrowAnyException(); - assertThatThrownBy(() -> GraphQlMutationContractValidator.requireSingleUseCase(CREATE, 2)) - .isInstanceOf(GraphQlMutationContractException.class); - assertThatThrownBy(() -> GraphQlMutationContractValidator.requireSingleUseCase(CREATE, 0)) - .as("zero means the resolver never went through the Application at all") - .isInstanceOf(GraphQlMutationContractException.class); - } - - private static GraphQlMutationIdempotencyContext context( - GraphQlMutationCoordinate coordinate, GraphQlMutationFingerprint fingerprint) { - return GraphQlMutationIdempotencyContext.of( - "actor-fingerprint", - TENANT, - coordinate, - VERSION, - new GraphQlIdempotencyKey("request-1"), - fingerprint); - } -} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/mutation/GraphQlMutationResultMapperTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/mutation/GraphQlMutationResultMapperTest.java index 07354656..ded2370e 100644 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/mutation/GraphQlMutationResultMapperTest.java +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/mutation/GraphQlMutationResultMapperTest.java @@ -3,6 +3,7 @@ package dev.caskeleton.adapter.inbound.graphql.mutation; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; import java.util.List; import org.junit.jupiter.api.Test; @@ -89,19 +90,25 @@ class GraphQlMutationResultMapperTest { } @Test - void requiredExpectedVersionAndIdempotencyAreEnforced() { - assertThatThrownBy( - () -> GraphQlMutationContractValidator.requireExpectedVersion(CREATE_ORDER, true, null)) + void missingRequiredExpectedVersionIsRejected() { + // when + Throwable thrown = + catchThrowable( + () -> + GraphQlMutationContractValidator.requireExpectedVersion(CREATE_ORDER, true, null)); + + // then + assertThat(thrown) .isInstanceOf(GraphQlMutationContractException.class) - .hasMessageContaining("expectedVersion"); + .hasMessage("Mutation.createOrder requires an expectedVersion"); + } + + @Test + void suppliedRequiredExpectedVersionDoesNotThrow() { assertThatCode( () -> GraphQlMutationContractValidator.requireExpectedVersion( CREATE_ORDER, true, new GraphQlExpectedVersion(3))) .doesNotThrowAnyException(); - assertThatThrownBy( - () -> GraphQlMutationContractValidator.requireIdempotency(CREATE_ORDER, true, null)) - .isInstanceOf(GraphQlMutationContractException.class) - .hasMessageContaining("idempotency key"); } } diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlMetricCardinalityPolicyTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlMetricCardinalityPolicyTest.java index 8a0a51af..976474dd 100644 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlMetricCardinalityPolicyTest.java +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/observation/GraphQlMetricCardinalityPolicyTest.java @@ -133,14 +133,6 @@ class GraphQlMetricCardinalityPolicyTest { assertThat(GraphQlSensitiveAttributeFilter.sensitive("graphql.outcome")).isFalse(); } - @Test - void theProfilerIsNeverExposedInAResponse() { - assertThat(GraphQlProfilerAccessPolicy.forEnvironment("local").profilerEnabled()).isTrue(); - assertThat(GraphQlProfilerAccessPolicy.forEnvironment("prod").profilerEnabled()).isFalse(); - assertThat(GraphQlProfilerAccessPolicy.values()) - .allSatisfy(policy -> assertThat(policy.exposedInResponseExtensions()).isFalse()); - } - @Test void anUnregisteredOperationNameCollapsesToTheBoundedLabel() { Map tags = diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/pagination/GraphQlConnectionAssemblerTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/pagination/GraphQlConnectionAssemblerTest.java index 4381f766..09b63d6f 100644 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/pagination/GraphQlConnectionAssemblerTest.java +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/pagination/GraphQlConnectionAssemblerTest.java @@ -127,21 +127,6 @@ class GraphQlConnectionAssemblerTest { private static GraphQlClientPolicy clientPolicy() { return new GraphQlClientPolicy( - 65536, - 65536, - 12, - 500, - 50, - 50, - 1000, - 20, - 100, - 10000, - 10000, - 5_242_880, - Duration.ofSeconds(5), - false, - false, - true); + 65536, 65536, 12, 500, 50, 50, 1000, 20, 100, 10000, Duration.ofSeconds(5), false, true); } } diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/policy/GraphQlClientPolicyTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/policy/GraphQlClientPolicyTest.java index 1e949dcb..cb3dbed2 100644 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/policy/GraphQlClientPolicyTest.java +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/policy/GraphQlClientPolicyTest.java @@ -3,11 +3,10 @@ package dev.caskeleton.adapter.inbound.graphql.policy; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import dev.caskeleton.adapter.inbound.graphql.api.GraphQlClientProfile; import java.time.Duration; import org.junit.jupiter.api.Test; -/** Client policy and environment manifest contract (Stable plan Task 4). */ +/** Client policy contract. */ class GraphQlClientPolicyTest { @Test @@ -25,11 +24,8 @@ class GraphQlClientPolicyTest { 100, 20, 10000, - 10000, - 5_242_880, Duration.ofSeconds(5), false, - false, true)) .isInstanceOf(IllegalArgumentException.class); } @@ -52,65 +48,15 @@ class GraphQlClientPolicyTest { } @Test - void productionProfileCanRequireNamedAndPersistedOnlyOperations() { + void productionProfileCanRequireNamedOperations() { GraphQlClientPolicy publicProfile = new GraphQlClientPolicy( - 8192, - 8192, - 8, - 200, - 20, - 20, - 100, - 20, - 50, - 5000, - 5000, - 1_048_576, - Duration.ofSeconds(2), - false, - true, - true); + 8192, 8192, 8, 200, 20, 20, 100, 20, 50, 5000, Duration.ofSeconds(2), false, true); - assertThat(publicProfile.persistedOperationOnly()).isTrue(); assertThat(publicProfile.namedOperationRequired()).isTrue(); assertThat(publicProfile.introspectionAllowed()).isFalse(); } - @Test - void manifestRejectsDuplicateClientProfiles() { - GraphQlClientProfile profile = new GraphQlClientProfile("first-party"); - GraphQlClientPolicy policy = policy(65536, 20, 100, Duration.ofSeconds(5)); - - assertThatThrownBy( - () -> - GraphQlClientPolicyManifest.builder() - .policy(profile, policy) - .policy(profile, policy)) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void manifestFailsClosedForAnUnknownProfile() { - GraphQlClientPolicyManifest manifest = - GraphQlClientPolicyManifest.builder() - .policy( - new GraphQlClientProfile("first-party"), - policy(65536, 20, 100, Duration.ofSeconds(5))) - .build(); - - assertThat(manifest.profiles()).containsExactly(new GraphQlClientProfile("first-party")); - assertThatThrownBy(() -> manifest.require(new GraphQlClientProfile("unregistered"))) - .isInstanceOf(GraphQlUnknownClientProfileException.class); - } - - @Test - void policyViolationDescribesTheLimitWithoutRequestContent() { - GraphQlPolicyViolation violation = GraphQlPolicyViolation.of("MAX_DEPTH", 14, 12); - - assertThat(violation.describe()).isEqualTo("MAX_DEPTH exceeded: 14 > 12"); - } - private static GraphQlClientPolicy policy( int documentBytes, int defaultPageSize, int maxPageSize, Duration executionTime) { return new GraphQlClientPolicy( @@ -124,11 +70,8 @@ class GraphQlClientPolicyTest { defaultPageSize, maxPageSize, 10000, - 10000, - 5_242_880, executionTime, false, - false, true); } } diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/policy/GraphQlOperationPolicyTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/policy/GraphQlOperationPolicyTest.java deleted file mode 100644 index 996dae72..00000000 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/policy/GraphQlOperationPolicyTest.java +++ /dev/null @@ -1,102 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.policy; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.graphql.api.GraphQlOperationName; -import dev.caskeleton.adapter.inbound.graphql.api.GraphQlSchemaCoordinate; -import org.junit.jupiter.api.Test; - -/** Operation policy and execution-type catalog contract (Stable plan Task 5). */ -class GraphQlOperationPolicyTest { - - @Test - void rejectsStreamQuery() { - assertThatThrownBy( - () -> - new GraphQlOperationPolicy( - new GraphQlOperationName("GetOrder"), - GraphQlOperationType.QUERY, - ResolverExecutionType.STREAM, - false)) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void rejectsSubscriptionWithoutAStreamResolver() { - assertThatThrownBy( - () -> - new GraphQlOperationPolicy( - new GraphQlOperationName("OnOrderChanged"), - GraphQlOperationType.SUBSCRIPTION, - ResolverExecutionType.BLOCKING, - false)) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void rejectsIdempotencyAndExpectedVersionOutsideMutations() { - assertThatThrownBy( - () -> - new GraphQlOperationPolicy( - new GraphQlOperationName("GetOrder"), - GraphQlOperationType.QUERY, - ResolverExecutionType.BLOCKING, - true)) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new GraphQlOperationPolicy( - new GraphQlOperationName("GetOrder"), - GraphQlOperationType.QUERY, - ResolverExecutionType.BLOCKING, - false, - true)) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void mutationMayRequireIdempotencyAndExpectedVersion() { - GraphQlOperationPolicy policy = - new GraphQlOperationPolicy( - new GraphQlOperationName("UpdateOrder"), - GraphQlOperationType.MUTATION, - ResolverExecutionType.BLOCKING, - true, - true); - - assertThat(policy.idempotencyRequired()).isTrue(); - assertThat(policy.expectedVersionRequired()).isTrue(); - } - - @Test - void catalogRejectsDuplicateOperationNames() { - GraphQlOperationCatalog catalog = new GraphQlOperationCatalog(); - GraphQlOperationPolicy policy = - new GraphQlOperationPolicy( - new GraphQlOperationName("GetOrder"), - GraphQlOperationType.QUERY, - ResolverExecutionType.BLOCKING, - false); - catalog.register(policy, GraphQlSchemaCoordinate.parse("Query.order")); - - assertThatThrownBy(() -> catalog.register(policy, GraphQlSchemaCoordinate.parse("Query.order"))) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void catalogResolvesPolicyAndCoordinateAndFailsClosedOtherwise() { - GraphQlOperationCatalog catalog = new GraphQlOperationCatalog(); - GraphQlOperationName name = new GraphQlOperationName("GetOrder"); - catalog.register( - new GraphQlOperationPolicy( - name, GraphQlOperationType.QUERY, ResolverExecutionType.BLOCKING, false), - GraphQlSchemaCoordinate.parse("Query.order")); - - assertThat(catalog.require(name).operationType()).isEqualTo(GraphQlOperationType.QUERY); - assertThat(catalog.coordinateOf(name).value()).isEqualTo("Query.order"); - assertThat(catalog.contains(name)).isTrue(); - assertThatThrownBy(() -> catalog.require(new GraphQlOperationName("Missing"))) - .isInstanceOf(GraphQlUnknownOperationException.class); - } -} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/release/GraphQlReleaseGateTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/release/GraphQlReleaseGateTest.java deleted file mode 100644 index b01b35f9..00000000 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/release/GraphQlReleaseGateTest.java +++ /dev/null @@ -1,165 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.release; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.time.Duration; -import java.time.Instant; -import java.util.Map; -import java.util.Set; -import org.junit.jupiter.api.Test; - -/** Stable release gate and evidence (Stable plan Task 48). */ -class GraphQlReleaseGateTest { - - private static final Instant NOW = Instant.parse("2026-08-12T00:00:00Z"); - - @Test - void missingFaultEvidenceBlocksStableRelease() { - var evidence = - GraphQlReleaseEvidence.builder() - .schemaPassed(true) - .contractsPassed(true) - .performancePassed(true) - .faultPassed(false) - .compatibilityPassed(true) - .build(); - - assertThatThrownBy(() -> new GraphQlReleaseGate().verify(evidence)) - .isInstanceOf(GraphQlReleaseException.class) - .hasMessageContaining("fault"); - } - - @Test - void everyKindOfEvidenceIsRequired() { - var gate = new GraphQlReleaseGate(); - - assertThat(gate.missing(GraphQlReleaseEvidence.builder().build())) - .containsExactly("schema", "contracts", "performance", "fault", "compatibility"); - assertThatCode(() -> gate.verify(complete())).doesNotThrowAnyException(); - assertThat(complete().complete()).isTrue(); - } - - @Test - void anOverrideMustNameAnApproverReasonAndExpiry() { - assertThatThrownBy( - () -> new GraphQlReleaseOverride(" ", "incident", Set.of("fault"), NOW.plusSeconds(60))) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new GraphQlReleaseOverride( - "release-manager", "incident", Set.of(), NOW.plusSeconds(60))) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> new GraphQlReleaseOverride("release-manager", "incident", Set.of("fault"), null)) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void anExpiredOrUncoveringOverrideStillBlocksTheRelease() { - var gate = new GraphQlReleaseGate(); - var incomplete = - GraphQlReleaseEvidence.builder() - .schemaPassed(true) - .contractsPassed(true) - .performancePassed(true) - .faultPassed(false) - .compatibilityPassed(true) - .build(); - - var expired = - new GraphQlReleaseOverride( - "release-manager", "incident", Set.of("fault"), NOW.minus(Duration.ofDays(1))); - var wrongScope = - new GraphQlReleaseOverride( - "release-manager", "incident", Set.of("performance"), NOW.plus(Duration.ofDays(1))); - var valid = - new GraphQlReleaseOverride( - "release-manager", "incident", Set.of("fault"), NOW.plus(Duration.ofDays(1))); - - assertThatThrownBy(() -> gate.verify(incomplete, expired, NOW)) - .isInstanceOf(GraphQlReleaseException.class) - .hasMessageContaining("expired"); - assertThatThrownBy(() -> gate.verify(incomplete, wrongScope, NOW)) - .isInstanceOf(GraphQlReleaseException.class) - .hasMessageContaining("does not cover"); - assertThatCode(() -> gate.verify(incomplete, valid, NOW)).doesNotThrowAnyException(); - } - - @Test - void theRequiredScenarioListsCoverLoadAndFaultSeparately() { - assertThat(GraphQlPerformanceScenario.required()) - .contains( - GraphQlPerformanceScenario.WIDE_ALIAS_QUERY, - GraphQlPerformanceScenario.EVENT_LOOP_BLOCKING_DETECTION, - GraphQlPerformanceScenario.JPA_POOL_SATURATION); - assertThat(GraphQlFaultScenario.required()) - .contains(GraphQlFaultScenario.CANCELLATION_LEAK, GraphQlFaultScenario.ERROR_MASKING); - } - - @Test - void theCompatibilityMatrixRejectsAnUnsupportedCombination() { - assertThat(new GraphQlCompatibilityMatrix(21, "4.0.0", "2.0.0", "25.0", true).supported()) - .isTrue(); - assertThat(new GraphQlCompatibilityMatrix(17, "4.0.0", "2.0.0", "25.0", true).problems()) - .anySatisfy(problem -> assertThat(problem).contains("Java 17")); - assertThat(new GraphQlCompatibilityMatrix(21, "4.0.0", "1.3.0", "25.0", true).problems()) - .anySatisfy(problem -> assertThat(problem).contains("Spring for GraphQL")); - assertThat(new GraphQlCompatibilityMatrix(21, "4.0.0", "2.0.0", "25.0", false).problems()) - .anySatisfy(problem -> assertThat(problem).contains("Spring Boot BOM")); - } - - @Test - void theCapabilityManifestSeparatesStableFromAdvancedAndUnsupported() { - assertThat(GraphQlStableCapabilityManifest.stable("HTTP_POST")).isTrue(); - assertThatThrownBy( - () -> GraphQlStableCapabilityManifest.requireStable("GRAPHQL_MULTIPART_UPLOAD")) - .isInstanceOf(GraphQlReleaseException.class) - .hasMessageContaining("not supported"); - assertThatThrownBy( - () -> GraphQlStableCapabilityManifest.requireStable("WEBSOCKET_SUBSCRIPTION")) - .isInstanceOf(GraphQlReleaseException.class) - .hasMessageContaining("Advanced plan"); - assertThatThrownBy(() -> GraphQlStableCapabilityManifest.requireStable("MADE_UP")) - .isInstanceOf(GraphQlReleaseException.class); - } - - @Test - void theReleaseReportIsMachineReadableAndDisclosesNoSchema() { - Map report = - new GraphQlReleaseReportWriter(new GraphQlReleaseGate()) - .write( - complete(), - new GraphQlCompatibilityMatrix(21, "4.0.0", "2.0.0", "25.0", true), - "a".repeat(64)); - - assertThat(report).containsEntry("verdict", "PASS"); - assertThat(report.get("missingEvidence")) - .asInstanceOf(org.assertj.core.api.InstanceOfAssertFactories.LIST) - .isEmpty(); - assertThat(report).doesNotContainKeys("sdl", "schema", "persistedDocuments", "cursorKeys"); - } - - @Test - void aBlockedReleaseIsReportedAsBlocked() { - Map report = - new GraphQlReleaseReportWriter(new GraphQlReleaseGate()) - .write( - GraphQlReleaseEvidence.builder().schemaPassed(true).build(), - new GraphQlCompatibilityMatrix(21, "4.0.0", "2.0.0", "25.0", true), - "a".repeat(64)); - - assertThat(report).containsEntry("verdict", "BLOCKED"); - } - - private static GraphQlReleaseEvidence complete() { - return GraphQlReleaseEvidence.builder() - .schemaPassed(true) - .contractsPassed(true) - .performancePassed(true) - .faultPassed(true) - .compatibilityPassed(true) - .build(); - } -} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlDocumentAuthorizationHandlerTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlDocumentAuthorizationHandlerTest.java new file mode 100644 index 00000000..a162f338 --- /dev/null +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlDocumentAuthorizationHandlerTest.java @@ -0,0 +1,133 @@ +package dev.caskeleton.adapter.inbound.graphql.runtime; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; + +import dev.caskeleton.adapter.inbound.graphql.api.GraphQlClientProfile; +import dev.caskeleton.adapter.inbound.graphql.api.GraphQlSchemaCoordinate; +import dev.caskeleton.adapter.inbound.graphql.cost.GraphQlDocumentShapeAnalyzer; +import dev.caskeleton.adapter.inbound.graphql.cost.GraphQlStructuralLimitException; +import dev.caskeleton.adapter.inbound.graphql.policy.GraphQlClientPolicy; +import dev.caskeleton.adapter.inbound.graphql.security.GraphQlAuthorizationDeniedException; +import dev.caskeleton.adapter.inbound.graphql.security.GraphQlAuthorizationInterceptor; +import dev.caskeleton.adapter.inbound.graphql.security.GraphQlAuthorizationPolicy; +import dev.caskeleton.adapter.inbound.graphql.testkit.GraphQlRequestContexts; +import graphql.parser.Parser; +import java.time.Duration; +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +/** + * The authorization stage walks the document before the cost stage has judged it. + * + *

So the walk itself has to be bounded: a small document whose fragments each spread the next + * one twice doubles the work per level, and expanding every spread turns 1.6 KB into 2^40 visits on + * the request thread. Bounding it must not cost coverage — a field reached only through a fragment + * that was already expanded elsewhere is still authorized. + */ +class GraphQlDocumentAuthorizationHandlerTest { + + private static final GraphQlAuthorizationPolicy ADMIN_REPORT_FOR_ADMINS_ONLY = + GraphQlAuthorizationPolicy.builder() + .denyByDefault(false) + .allow( + GraphQlSchemaCoordinate.parse("Query.adminReport"), new GraphQlClientProfile("admin")) + .build(); + + @Test + void exponentialFragmentFanOutIsAuthorizedWithinTheTimeBound() { + // given + GraphQlDocumentAuthorizationHandler handler = + handler(new GraphQlDocumentShapeAnalyzer(), false); + GraphQlExecutionContext selected = selected(doublingFragments(40)); + + // when + GraphQlExecutionContext authorized = + assertTimeoutPreemptively(Duration.ofSeconds(2), () -> handler.handle(selected)); + + // then + assertThat(authorized).isSameAs(selected); + } + + @ParameterizedTest + @ValueSource( + strings = { + "query Q { ...A ...B } fragment A on Query { health } " + + "fragment B on Query { ...A adminReport }", + "query Q { ...A ...A } fragment A on Query { ...B } fragment B on Query { adminReport }", + "query Q { ...A ... on Query { ...A ...B } } fragment A on Query { health } " + + "fragment B on Query { ... on Query { adminReport } }" + }) + void aProtectedFieldBehindAnAlreadyExpandedFragmentIsStillDenied(String document) { + // given + GraphQlDocumentAuthorizationHandler handler = + handler(new GraphQlDocumentShapeAnalyzer(), false); + GraphQlExecutionContext selected = selected(document); + + // when + Throwable thrown = catchThrowable(() -> handler.handle(selected)); + + // then + assertThat(thrown) + .isInstanceOf(GraphQlAuthorizationDeniedException.class) + .hasMessage("GraphQL authorization denied: COORDINATE_NOT_AUTHORIZED"); + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void aDocumentBeyondTheTraversalBudgetIsRejectedAsTooComplex(boolean introspectionAllowed) { + // given + GraphQlDocumentAuthorizationHandler handler = + handler(new GraphQlDocumentShapeAnalyzer(3), introspectionAllowed); + GraphQlExecutionContext selected = selected("query Q { a b c d }"); + + // when + Throwable thrown = catchThrowable(() -> handler.handle(selected)); + + // then + assertThat(thrown) + .isInstanceOf(GraphQlStructuralLimitException.class) + .extracting( + failure -> ((GraphQlStructuralLimitException) failure).code(), + failure -> ((GraphQlStructuralLimitException) failure).limitName()) + .containsExactly(GraphQlStructuralLimitException.CODE, "DOCUMENT_TRAVERSAL"); + } + + private static GraphQlDocumentAuthorizationHandler handler( + GraphQlDocumentShapeAnalyzer analyzer, boolean introspectionAllowed) { + return new GraphQlDocumentAuthorizationHandler( + new GraphQlAuthorizationInterceptor(ADMIN_REPORT_FOR_ADMINS_ONLY), + analyzer, + GraphQlClientPolicy.defaults(100, 10_000, introspectionAllowed)); + } + + private static GraphQlExecutionContext selected(String document) { + GraphQlExecutionContext starting = + GraphQlExecutionContext.starting( + new GraphQlExecutionRequest(document, "Q", Map.of(), document.length(), 0), + GraphQlRequestContexts.testContext("tenant-a"), + null, + Parser.parse(document)); + return new GraphQlOperationSelectionHandler(GraphQlClientPolicy.defaults(100, 10_000, false)) + .handle(starting); + } + + /** {@code F0} spreads {@code F1} twice, and so on: {@code levels} levels, 2^levels leaf paths. */ + private static String doublingFragments(int levels) { + StringBuilder document = new StringBuilder("query Q { ...F0 }"); + for (int level = 0; level < levels; level++) { + document + .append(" fragment F") + .append(level) + .append(" on Query { ...F") + .append(level + 1) + .append(" ...F") + .append(level + 1) + .append(" }"); + } + return document.append(" fragment F").append(levels).append(" on Query { health }").toString(); + } +} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlMappingInspectionGateTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlMappingInspectionGateTest.java deleted file mode 100644 index c5aef664..00000000 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlMappingInspectionGateTest.java +++ /dev/null @@ -1,70 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.schema; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.util.List; -import org.junit.jupiter.api.Test; - -/** Schema mapping inspection fail-fast gate (Stable plan Task 9). */ -class GraphQlMappingInspectionGateTest { - - @Test - void stableProfileRejectsUnmappedField() { - assertThatThrownBy( - () -> - GraphQlMappingInspectionGate.stable() - .verify(List.of(GraphQlMappingIssue.unmapped("Order.total")))) - .isInstanceOf(GraphQlSchemaMappingException.class); - } - - @Test - void stableProfileRejectsEveryBlockingMismatch() { - GraphQlMappingInspectionGate gate = GraphQlMappingInspectionGate.stable(); - - assertThatThrownBy( - () -> gate.verify(List.of(GraphQlMappingIssue.unknownResolver("Order.ghost")))) - .isInstanceOf(GraphQlSchemaMappingException.class); - assertThatThrownBy( - () -> gate.verify(List.of(GraphQlMappingIssue.argumentMismatch("Query.order")))) - .isInstanceOf(GraphQlSchemaMappingException.class); - assertThatThrownBy( - () -> gate.verify(List.of(GraphQlMappingIssue.nullabilityMismatch("Order.status")))) - .isInstanceOf(GraphQlSchemaMappingException.class); - } - - @Test - void localProfileWarnsButStillRejectsForbiddenScalarAndUnknownResolver() { - GraphQlMappingInspectionGate gate = GraphQlMappingInspectionGate.local(); - - assertThatCode(() -> gate.verify(List.of(GraphQlMappingIssue.unmapped("Order.total")))) - .doesNotThrowAnyException(); - assertThat(gate.advisory(List.of(GraphQlMappingIssue.unmapped("Order.total")))).hasSize(1); - - assertThatThrownBy(() -> gate.verify(List.of(GraphQlMappingIssue.forbiddenScalar("Upload")))) - .isInstanceOf(GraphQlSchemaMappingException.class); - assertThatThrownBy( - () -> gate.verify(List.of(GraphQlMappingIssue.unknownResolver("Order.ghost")))) - .isInstanceOf(GraphQlSchemaMappingException.class); - } - - @Test - void issueIdentifiesCoordinateAndOwningResourceWithoutRequestContent() { - GraphQlMappingIssue issue = - GraphQlMappingIssue.unmapped("Order.total") - .ownedBy( - new GraphQlSchemaOwnership("Order.total", "order", "graphql/order/order.graphqls")); - - assertThat(issue.describe()) - .isEqualTo("UNMAPPED_FIELD Order.total (order:graphql/order/order.graphqls)"); - assertThat(issue.owningResource()).isEqualTo("order:graphql/order/order.graphqls"); - } - - @Test - void cleanInspectionPasses() { - assertThatCode(() -> GraphQlMappingInspectionGate.stable().verify(List.of())) - .doesNotThrowAnyException(); - assertThat(GraphQlMappingInspectionGate.stable().policy()).isEqualTo(GraphQlMappingPolicy.FAIL); - } -} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlOneOfInputValidatorTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlOneOfInputValidatorTest.java deleted file mode 100644 index 0608ec65..00000000 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlOneOfInputValidatorTest.java +++ /dev/null @@ -1,131 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.schema; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import graphql.schema.idl.SchemaParser; -import java.util.HashMap; -import java.util.Map; -import org.junit.jupiter.api.Test; - -/** September 2025 {@code @oneOf} input contract (Stable plan Task 14). */ -class GraphQlOneOfInputValidatorTest { - - private static final String ONE_OF_SDL = - """ - directive @oneOf on INPUT_OBJECT - input OrderSelector @oneOf { - id: ID - orderNumber: String - externalReference: String - } - """; - - @Test - void rejectsTwoValues() { - assertThatThrownBy( - () -> GraphQlOneOfInputValidator.validate(Map.of("id", "o-1", "orderNumber", "N-1"))) - .isInstanceOf(GraphQlOneOfViolationException.class); - } - - @Test - void rejectsZeroValues() { - Map allNull = new HashMap<>(); - allNull.put("id", null); - allNull.put("orderNumber", null); - - assertThatThrownBy(() -> GraphQlOneOfInputValidator.validate(allNull)) - .isInstanceOf(GraphQlOneOfViolationException.class); - assertThatThrownBy(() -> GraphQlOneOfInputValidator.validate(Map.of())) - .isInstanceOf(GraphQlOneOfViolationException.class); - } - - @Test - void acceptsExactlyOneNonNullValue() { - Map selector = new HashMap<>(); - selector.put("id", "o-1"); - selector.put("orderNumber", null); - - assertThatCode(() -> GraphQlOneOfInputValidator.validate(selector)).doesNotThrowAnyException(); - assertThat(GraphQlOneOfInputValidator.selected(selector)).isEqualTo("id"); - } - - @Test - void validationErrorsNameMembersButNeverTheirValues() { - String secret = "4111-1111-1111-1111"; - - assertThatThrownBy( - () -> - GraphQlOneOfInputValidator.validate( - Map.of("id", secret, "externalReference", secret))) - .isInstanceOf(GraphQlOneOfViolationException.class) - .hasMessageContaining("id") - .hasMessageContaining("externalReference") - .hasMessageNotContaining(secret); - } - - @Test - void schemaGateAcceptsNullableMembersWithoutDefaults() { - assertThatCode(() -> GraphQlOneOfSchemaGate.verify(ONE_OF_SDL)).doesNotThrowAnyException(); - assertThat(GraphQlOneOfSchemaGate.oneOfInputTypes(new SchemaParser().parse(ONE_OF_SDL))) - .containsExactly("OrderSelector"); - } - - @Test - void schemaGateRejectsNonNullMember() { - String sdl = - """ - directive @oneOf on INPUT_OBJECT - input OrderSelector @oneOf { - id: ID! - orderNumber: String - } - """; - - assertThatThrownBy(() -> GraphQlOneOfSchemaGate.verify(sdl)) - .isInstanceOf(GraphQlOneOfViolationException.class) - .hasMessageContaining("OrderSelector.id") - .hasMessageContaining("nullable"); - } - - @Test - void schemaGateRejectsMemberDefaultValue() { - String sdl = - """ - directive @oneOf on INPUT_OBJECT - input OrderSelector @oneOf { - id: ID - orderNumber: String = "N-1" - } - """; - - assertThatThrownBy(() -> GraphQlOneOfSchemaGate.verify(sdl)) - .isInstanceOf(GraphQlOneOfViolationException.class) - .hasMessageContaining("OrderSelector.orderNumber") - .hasMessageContaining("default value"); - } - - @Test - void ordinaryInputObjectsAreUnaffected() { - String sdl = - """ - directive @oneOf on INPUT_OBJECT - input CreateOrderInput { - customerId: ID! - note: String = "none" - } - """; - - assertThatCode(() -> GraphQlOneOfSchemaGate.verify(sdl)).doesNotThrowAnyException(); - } - - @Test - void policyStatesTheRuleOnce() { - assertThat(GraphQlOneOfPolicy.DIRECTIVE_NAME).isEqualTo("oneOf"); - assertThat(GraphQlOneOfPolicy.satisfied(1)).isTrue(); - assertThat(GraphQlOneOfPolicy.satisfied(0)).isFalse(); - assertThat(GraphQlOneOfPolicy.satisfied(2)).isFalse(); - assertThat(GraphQlOneOfPolicy.violationMessage(0)).contains("none supplied"); - } -} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlSchemaAssemblerTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlSchemaAssemblerTest.java deleted file mode 100644 index ea0d6ba9..00000000 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlSchemaAssemblerTest.java +++ /dev/null @@ -1,124 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.schema; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.util.List; -import org.junit.jupiter.api.Test; - -/** Deterministic SDL discovery and assembly contract (Stable plan Task 8). */ -class GraphQlSchemaAssemblerTest { - - @Test - void duplicateRootTypeFailsAssembly() { - var resources = - List.of( - GraphQlSchemaResource.memory("a", "type Query { a: String }"), - GraphQlSchemaResource.memory("b", "type Query { b: String }")); - - assertThatThrownBy(() -> GraphQlSchemaAssembler.defaults().assemble(resources)) - .isInstanceOf(GraphQlSchemaAssemblyException.class); - } - - @Test - void modulesExtendSharedRootTypesWithoutColliding() { - var resources = - List.of( - GraphQlSchemaResource.classpath( - "platform", "graphql/common/root.graphqls", "type Query { ping: String! }"), - GraphQlSchemaResource.classpath( - "order", - "graphql/order/order-query.graphqls", - "extend type Query { order(id: ID!): Order }\ntype Order { id: ID! }")); - - GraphQlSchemaAssemblyResult result = GraphQlSchemaAssembler.defaults().assemble(resources); - - assertThat(result.registry().hasType(new graphql.language.TypeName("Order"))).isTrue(); - assertThat(result.ownership()) - .extracting(GraphQlSchemaOwnership::coordinate) - .contains("Query", "Query.ping", "Order", "Order.id"); - } - - @Test - void assemblyOrderIsIndependentOfDiscoveryOrder() { - var first = - GraphQlSchemaResource.classpath( - "order", "graphql/order/order.graphqls", "type Order { id: ID! }"); - var second = - GraphQlSchemaResource.classpath( - "platform", "graphql/common/root.graphqls", "type Query { ping: String! }"); - - String forward = - GraphQlSchemaAssembler.defaults().assemble(List.of(first, second)).canonicalSdl(); - String reversed = - GraphQlSchemaAssembler.defaults().assemble(List.of(second, first)).canonicalSdl(); - - assertThat(forward).isEqualTo(reversed); - } - - @Test - void canonicalSdlIgnoresFormattingSoTheSchemaHashIsStable() { - var compact = List.of(GraphQlSchemaResource.memory("a", "type Query { ping: String! }")); - var spaced = - List.of( - GraphQlSchemaResource.memory( - "a", "type Query {\n\n # a comment\n ping: String!\n}\n")); - - assertThat(GraphQlSchemaAssembler.defaults().assemble(compact).schemaHash()) - .isEqualTo(GraphQlSchemaAssembler.defaults().assemble(spaced).schemaHash()); - } - - @Test - void duplicateFieldDirectiveAndScalarDeclarationsAreRejected() { - assertThatThrownBy( - () -> - GraphQlSchemaAssembler.defaults() - .assemble( - List.of( - GraphQlSchemaResource.memory("a", "scalar UUID"), - GraphQlSchemaResource.memory("b", "scalar UUID")))) - .isInstanceOf(GraphQlSchemaAssemblyException.class); - - assertThatThrownBy( - () -> - GraphQlSchemaAssembler.defaults() - .assemble( - List.of( - GraphQlSchemaResource.memory( - "a", "directive @audit on FIELD_DEFINITION"), - GraphQlSchemaResource.memory( - "b", "directive @audit on FIELD_DEFINITION")))) - .isInstanceOf(GraphQlSchemaAssemblyException.class); - } - - @Test - void onlyApprovedSchemaResourcesAreLoaded() { - assertThat(GraphQlSchemaResource.isSchemaResource("graphql/order/order.graphqls")).isTrue(); - assertThat(GraphQlSchemaResource.isSchemaResource("classpath:/graphql/order/order.gqls")) - .isTrue(); - assertThat(GraphQlSchemaResource.isSchemaResource("graphql/order/order.txt")).isFalse(); - assertThat(GraphQlSchemaResource.isSchemaResource("other/order.graphqls")).isFalse(); - - assertThatThrownBy( - () -> - GraphQlSchemaResource.classpath( - "order", "other/order.graphqls", "type Query { a: String }")) - .isInstanceOf(GraphQlSchemaAssemblyException.class); - } - - @Test - void unparseableFragmentNamesTheOwningResource() { - assertThatThrownBy( - () -> - GraphQlSchemaAssembler.defaults() - .assemble(List.of(GraphQlSchemaResource.memory("broken", "type Query {")))) - .isInstanceOf(GraphQlSchemaAssemblyException.class) - .hasMessageContaining("broken"); - } - - @Test - void emptyDiscoveryFailsClosed() { - assertThatThrownBy(() -> GraphQlSchemaAssembler.defaults().assemble(List.of())) - .isInstanceOf(GraphQlSchemaAssemblyException.class); - } -} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlSchemaContractTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlSchemaContractTest.java deleted file mode 100644 index a2dc5037..00000000 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/schema/GraphQlSchemaContractTest.java +++ /dev/null @@ -1,74 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.schema; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.util.Locale; -import org.junit.jupiter.api.Test; - -/** Schema contract fingerprint and policy versioning (Stable plan Task 6). */ -class GraphQlSchemaContractTest { - - @Test - void sameCanonicalSdlProducesSameHash() { - assertThat(GraphQlSchemaHash.sha256("type Query { ping: String! }").value()) - .isEqualTo(GraphQlSchemaHash.sha256("type Query { ping: String! }").value()); - } - - @Test - void hashIsLowercaseHexadecimal() { - String value = GraphQlSchemaHash.sha256("type Query { ping: String! }").value(); - - assertThat(value).hasSize(64).matches("[0-9a-f]{64}"); - assertThatThrownBy(() -> new GraphQlSchemaHash(value.toUpperCase(Locale.ROOT))) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void differentSdlProducesDifferentHash() { - assertThat(GraphQlSchemaHash.sha256("type Query { ping: String! }")) - .isNotEqualTo(GraphQlSchemaHash.sha256("type Query { ping: String }")); - } - - @Test - void schemaHashAloneIsNotACompatibilityDecision() { - GraphQlSchemaHash hash = GraphQlSchemaHash.sha256("type Query { ping: String! }"); - GraphQlSchemaContract deployed = - new GraphQlSchemaContract( - hash, - GraphQlContractVersion.of("stable-v1"), - GraphQlContractVersion.of("scalar-v1"), - GraphQlContractVersion.of("directive-v1")); - GraphQlSchemaContract sameSdlNewScalarCoercion = - new GraphQlSchemaContract( - hash, - GraphQlContractVersion.of("stable-v1"), - GraphQlContractVersion.of("scalar-v2"), - GraphQlContractVersion.of("directive-v1")); - - assertThat(deployed.sameSchemaBytes(sameSdlNewScalarCoercion)).isTrue(); - assertThat(deployed.matches(sameSdlNewScalarCoercion)).isFalse(); - } - - @Test - void everyPolicyVersionIsMandatory() { - GraphQlSchemaHash hash = GraphQlSchemaHash.sha256("type Query { ping: String! }"); - - assertThatThrownBy( - () -> - new GraphQlSchemaContract( - hash, - null, - GraphQlContractVersion.of("scalar-v1"), - GraphQlContractVersion.of("directive-v1"))) - .isInstanceOf(NullPointerException.class); - assertThatThrownBy( - () -> - new GraphQlSchemaContract( - hash, - GraphQlContractVersion.of("stable-v1"), - GraphQlContractVersion.of("scalar-v1"), - null)) - .isInstanceOf(NullPointerException.class); - } -} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/security/GraphQlAuthenticationContextFactoryTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/security/GraphQlAuthenticationContextFactoryTest.java index 28de2c12..9d5d8dab 100644 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/security/GraphQlAuthenticationContextFactoryTest.java +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/security/GraphQlAuthenticationContextFactoryTest.java @@ -15,7 +15,6 @@ import java.time.Duration; import java.time.Instant; import java.time.ZoneOffset; import java.util.Locale; -import java.util.Map; import org.junit.jupiter.api.Test; /** Authentication context factory contract (Stable plan Task 27). */ @@ -83,20 +82,6 @@ class GraphQlAuthenticationContextFactoryTest { .isInstanceOf(GraphQlAuthenticationException.class); } - @Test - void clientProfileComesFromTrustedCredentialMetadata() { - GraphQlClientProfileResolver resolver = - new GraphQlClientProfileResolver( - Map.of("checkout-app", new GraphQlClientProfile("first-party")), - new GraphQlClientProfile("public")); - - assertThat(resolver.resolve("checkout-app").value()).isEqualTo("first-party"); - assertThat(resolver.resolve(null).value()).isEqualTo("public"); - assertThatThrownBy(() -> resolver.resolve("unknown-app")) - .isInstanceOf(GraphQlAuthenticationException.class); - assertThat(resolver.registeredClaims()).containsExactly("checkout-app"); - } - @Test void theOperationIdentityIsRefinedOnlyAfterParsing() { GraphQlRequestContext context = GraphQlRequestContexts.testContext("tenant-a"); diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/security/GraphQlCancellationAggregationTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/security/GraphQlCancellationAggregationTest.java deleted file mode 100644 index 8b6c4aa9..00000000 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/security/GraphQlCancellationAggregationTest.java +++ /dev/null @@ -1,153 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.security; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.graphql.advanced.subscription.GraphQlSubscriptionCancellation; -import dev.caskeleton.adapter.inbound.graphql.execution.GraphQlCancellation; -import java.util.ArrayList; -import java.util.List; -import org.junit.jupiter.api.Test; - -/** - * One broken cleanup must not become several leaks. - * - *

Both loops used to abandon the remaining work at the first failure. On the request path that - * left request-scoped state bound to a pooled thread; on the subscription path it left the Kafka - * consumer, the polling task and the nested publishers running for a client that had gone. In each - * case the hooks that would have prevented the leak were the ones never reached, and the failure - * that stopped them was the only thing anybody saw. - */ -class GraphQlCancellationAggregationTest { - - @Test - void everyCleanupRunsEvenWhenOneThrows() { - List ran = new ArrayList<>(); - var cleanup = - GraphQlContextCleanup.create() - .register(() -> ran.add("first")) - .register( - () -> { - ran.add("second"); - throw new IllegalStateException("second failed"); - }) - .register(() -> ran.add("third")); - - assertThatThrownBy(cleanup::close).isInstanceOf(IllegalStateException.class); - - assertThat(ran).containsExactly("third", "second", "first"); - assertThat(cleanup.pending()).isZero(); - } - - @Test - void laterFailuresAreAttachedToTheFirstRatherThanDropped() { - var cleanup = - GraphQlContextCleanup.create() - .register( - () -> { - throw new IllegalStateException("registered-first"); - }) - .register( - () -> { - throw new IllegalArgumentException("registered-second"); - }); - - assertThatThrownBy(cleanup::close) - .isInstanceOf(IllegalArgumentException.class) - .satisfies( - thrown -> - assertThat(thrown.getSuppressed()) - .as("a second broken cleanup stays invisible until the first one is fixed") - .hasSize(1) - .allSatisfy( - suppressed -> - assertThat(suppressed).isInstanceOf(IllegalStateException.class))); - } - - @Test - void aFailingRequestListenerNeverStopsTheOtherWorkFromStopping() { - List stopped = new ArrayList<>(); - var cancellation = GraphQlCancellation.create(); - cancellation.onCancel(() -> stopped.add("statement")); - cancellation.onCancel( - () -> { - stopped.add("downstream-call"); - throw new IllegalStateException("the downstream client refused to close"); - }); - cancellation.onCancel(() -> stopped.add("publisher")); - - assertThatThrownBy(cancellation::cancel).isInstanceOf(IllegalStateException.class); - - assertThat(stopped) - .as("a deadline that reaches only the first listener is not a cancellation") - .containsExactlyInAnyOrder("statement", "downstream-call", "publisher"); - assertThat(cancellation.cancelled()).isTrue(); - } - - @Test - void aRequestListenerFailingLateIsAttachedToTheFirstFailure() { - var cancellation = GraphQlCancellation.create(); - cancellation.onCancel( - () -> { - throw new IllegalStateException("registered-first"); - }); - cancellation.onCancel( - () -> { - throw new IllegalArgumentException("registered-second"); - }); - - assertThatThrownBy(cancellation::cancel) - .isInstanceOf(IllegalStateException.class) - .satisfies( - thrown -> - assertThat(thrown.getSuppressed()) - .hasSize(1) - .allSatisfy( - suppressed -> - assertThat(suppressed).isInstanceOf(IllegalArgumentException.class))); - } - - @Test - void aRequestListenerRegisteredAfterCancellationStillRunsExactlyOnce() { - List stopped = new ArrayList<>(); - var cancellation = GraphQlCancellation.create(); - cancellation.cancel(); - - cancellation.onCancel(() -> stopped.add("late")); - cancellation.cancel(); - - assertThat(stopped).containsExactly("late"); - } - - @Test - void aFailingUpstreamHookNeverStopsTheOthersFromStopping() { - List stopped = new ArrayList<>(); - var cancellation = new GraphQlSubscriptionCancellation(); - cancellation.onCancel(() -> stopped.add("consumer")); - cancellation.onCancel( - () -> { - stopped.add("polling-task"); - throw new IllegalStateException("polling task refused to stop"); - }); - cancellation.onCancel(() -> stopped.add("nested-publisher")); - - assertThatThrownBy(cancellation::cancel).isInstanceOf(IllegalStateException.class); - - assertThat(stopped) - .as("the hooks after the failing one are exactly the leaks it was supposed to prevent") - .containsExactlyInAnyOrder("consumer", "polling-task", "nested-publisher"); - assertThat(cancellation.cancelled()).isTrue(); - } - - @Test - void aHookRegisteredAfterCancellationStillRunsExactlyOnce() { - List stopped = new ArrayList<>(); - var cancellation = new GraphQlSubscriptionCancellation(); - cancellation.cancel(); - - cancellation.onCancel(() -> stopped.add("late")); - cancellation.cancel(); - - assertThat(stopped).containsExactly("late"); - } -} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/security/GraphQlTenantIsolationPolicyTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/security/GraphQlTenantIsolationPolicyTest.java index 2a7480f5..160c8169 100644 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/security/GraphQlTenantIsolationPolicyTest.java +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/security/GraphQlTenantIsolationPolicyTest.java @@ -12,7 +12,6 @@ import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.Test; /** Tenant isolation and context propagation (Stable plan Task 29). */ @@ -89,24 +88,6 @@ class GraphQlTenantIsolationPolicyTest { .containsEntry(GraphQlRequestContext.CONTEXT_KEY, context); } - @Test - void cleanupRunsEveryActionEvenWhenOneFails() { - AtomicInteger cleaned = new AtomicInteger(); - GraphQlContextCleanup cleanup = - GraphQlContextCleanup.create() - .register(cleaned::incrementAndGet) - .register( - () -> { - cleaned.incrementAndGet(); - throw new IllegalStateException("cleanup failed"); - }) - .register(cleaned::incrementAndGet); - - assertThatThrownBy(cleanup::close).isInstanceOf(IllegalStateException.class); - assertThat(cleaned).hasValue(3); - assertThat(cleanup.pending()).isZero(); - } - @Test void diagnosticsNeverCarryARawTenantIdentifier() { GraphQlTenantIsolationException failure = diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/testkit/GraphQlCrossModuleContractSuiteTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/testkit/GraphQlCrossModuleContractSuiteTest.java deleted file mode 100644 index 45dcba9b..00000000 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/testkit/GraphQlCrossModuleContractSuiteTest.java +++ /dev/null @@ -1,174 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.testkit; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.graphql.api.GraphQlClientProfile; -import dev.caskeleton.adapter.inbound.graphql.api.GraphQlSchemaCoordinate; -import dev.caskeleton.adapter.inbound.graphql.execution.GraphQlCancellation; -import dev.caskeleton.adapter.inbound.graphql.http.GraphQlExecutionOutcome; -import dev.caskeleton.adapter.inbound.graphql.pagination.GraphQlConnectionPolicy; -import dev.caskeleton.adapter.inbound.graphql.schema.GraphQlMappingIssue; -import dev.caskeleton.adapter.inbound.graphql.schema.GraphQlSchemaResource; -import dev.caskeleton.adapter.inbound.graphql.security.GraphQlAuthorizationDecision; -import dev.caskeleton.adapter.inbound.graphql.security.GraphQlAuthorizationPolicy; -import java.util.List; -import java.util.Map; -import java.util.Set; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -/** Cross-module contract suites replayed through the real transport (Stable plan Task 47). */ -@Tag("graphql-contract") -class GraphQlCrossModuleContractSuiteTest { - - @Test - void fieldFailureKeepsSiblingDataAndHttp200() { - var fixture = GraphQlContractFixture.standard(); - try { - var response = fixture.executeHttp("query Contract { stableField failingField }"); - - assertThat(response.status()).isEqualTo(200); - assertThat(response.data()).containsKey("stableField"); - assertThat(response.errors()).isNotEmpty(); - } finally { - fixture.close(); - } - } - - @Test - void theHttpContractSuitePassesAgainstTheRealTransport() { - var fixture = GraphQlContractFixture.standard(); - try { - assertThatCode(() -> GraphQlHttpContractSuite.verify(fixture)).doesNotThrowAnyException(); - } finally { - fixture.close(); - } - } - - @Test - void theHttpContractSuiteCatchesATransportThatDiscardsPartialData() { - var fixture = - GraphQlContractFixture.withExecutor( - (envelope, context) -> - GraphQlExecutionOutcome.partial(Map.of(), List.of(Map.of("message", "failed")))); - try { - assertThatThrownBy(() -> GraphQlHttpContractSuite.verify(fixture)) - .isInstanceOf(GraphQlContractViolation.class) - .hasMessageContaining("sibling data"); - } finally { - fixture.close(); - } - } - - @Test - void theSchemaSuiteRunsAssemblyMappingAndCompatibilityTogether() { - var resources = - List.of( - GraphQlSchemaResource.classpath( - "platform", "graphql/common/root.graphqls", "type Query { ping: String }")); - - assertThatCode(() -> GraphQlSchemaContractSuite.verify(resources, null, List.of())) - .doesNotThrowAnyException(); - assertThatThrownBy( - () -> - GraphQlSchemaContractSuite.verify( - resources, "type Query { ping: String! }", List.of())) - .isInstanceOf(GraphQlContractViolation.class); - assertThatThrownBy( - () -> - GraphQlSchemaContractSuite.verify( - resources, null, List.of(GraphQlMappingIssue.unmapped("Query.ping")))) - .isInstanceOf(GraphQlContractViolation.class); - } - - @Test - void theSecuritySuiteChecksBypassesRatherThanTheHappyPath() { - var coordinate = GraphQlSchemaCoordinate.parse("Query.order"); - var policy = - GraphQlAuthorizationPolicy.builder() - .allow(coordinate, new GraphQlClientProfile("admin")) - .hideFromIntrospection(coordinate) - .build(); - - assertThatCode( - () -> - GraphQlSecurityContractSuite.verify( - policy, - (context, objectType, objectId) -> GraphQlAuthorizationDecision.allow(), - GraphQlRequestContexts.testContext("tenant-a"), - coordinate)) - .doesNotThrowAnyException(); - } - - @Test - void theDataLoaderSuiteDetectsAnNPlusOneRegression() { - assertThatCode( - () -> - GraphQlDataLoaderContractSuite.verify( - List.of("a", "b"), Map.of("a", "value"), Set.of("b"), 1)) - .doesNotThrowAnyException(); - assertThatThrownBy( - () -> - GraphQlDataLoaderContractSuite.verify( - List.of("a", "b"), Map.of("a", "1", "b", "2"), Set.of(), 2)) - .isInstanceOf(GraphQlContractViolation.class) - .hasMessageContaining("N+1"); - } - - @Test - void thePaginationSuiteRejectsATamperedCursor() { - assertThatCode( - () -> - GraphQlPaginationContractSuite.verify( - dev.caskeleton.adapter.inbound.graphql.pagination.GraphQlCursorFixtures - .assembler(), - new GraphQlConnectionPolicy(20, 100, false))) - .doesNotThrowAnyException(); - } - - @Test - void storageEvidenceThatWasNeverExecutedIsNotAPass() { - var jpa = new GraphQlJpaIntegrationFixture(2, 100); - var mongo = new GraphQlMongoIntegrationFixture(2, 100); - - assertThatThrownBy(() -> jpa.verify(GraphQlStorageIntegrationEvidence.notExecuted("GetOrder"))) - .isInstanceOf(GraphQlContractViolation.class) - .hasMessageContaining("not a pass"); - assertThatThrownBy( - () -> mongo.verify(GraphQlStorageIntegrationEvidence.notExecuted("GetOrder"))) - .isInstanceOf(GraphQlContractViolation.class); - assertThatCode(() -> jpa.verify(new GraphQlStorageIntegrationEvidence("GetOrder", 2, 50, true))) - .doesNotThrowAnyException(); - assertThatThrownBy( - () -> jpa.verify(new GraphQlStorageIntegrationEvidence("GetOrder", 21, 50, true))) - .isInstanceOf(GraphQlContractViolation.class) - .hasMessageContaining("statements"); - } - - @Test - void theDownstreamFailureSuiteChecksPartialDataMaskingAndCancellation() { - var cancellation = GraphQlCancellation.create(); - - assertThatCode( - () -> - GraphQlDownstreamFailureFixture.verifyPartialFailure( - GraphQlExecutionOutcome.partial( - Map.of("order", Map.of("id", "o-1")), - List.of(Map.of("message", "요청을 처리할 수 없습니다."))), - cancellation)) - .doesNotThrowAnyException(); - assertThat(cancellation.cancelled()).isTrue(); - - assertThatThrownBy( - () -> - GraphQlDownstreamFailureFixture.verifyPartialFailure( - GraphQlExecutionOutcome.partial( - Map.of("order", Map.of("id", "o-1")), - List.of(Map.of("message", "select * from orders failed"))), - GraphQlCancellation.create())) - .isInstanceOf(GraphQlContractViolation.class) - .hasMessageContaining("disclose"); - } -} diff --git a/src/adapter/inbound/graphql/src/testFixtures/java/dev/caskeleton/adapter/inbound/graphql/advanced/admin/InMemoryGraphQlPersistedOperationAdminPort.java b/src/adapter/inbound/graphql/src/testFixtures/java/dev/caskeleton/adapter/inbound/graphql/advanced/admin/InMemoryGraphQlPersistedOperationAdminPort.java deleted file mode 100644 index e154f3bc..00000000 --- a/src/adapter/inbound/graphql/src/testFixtures/java/dev/caskeleton/adapter/inbound/graphql/advanced/admin/InMemoryGraphQlPersistedOperationAdminPort.java +++ /dev/null @@ -1,64 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.admin; - -import dev.caskeleton.adapter.inbound.graphql.advanced.persisted.GraphQlPersistedOperation; -import dev.caskeleton.adapter.inbound.graphql.advanced.persisted.GraphQlPersistedOperationId; -import dev.caskeleton.adapter.inbound.graphql.advanced.persisted.GraphQlPersistedOperationRegistry; -import dev.caskeleton.adapter.inbound.graphql.advanced.persisted.GraphQlPersistedOperationTransition; -import java.util.List; -import java.util.Objects; -import java.util.concurrent.CopyOnWriteArrayList; - -/** - * A single-instance admin port, for tests and development. - * - *

Serialises every command on one lock so the registry change and the audit entry cannot - * interleave, and appends to a thread-safe list. That is as close to atomic as one JVM gets, and it - * is deliberately not a production implementation: a lock inside one instance says nothing about - * the other instances, and neither the registry nor the trail survives a restart. The Advanced - * release gate requires durable evidence for exactly this reason. - */ -public final class InMemoryGraphQlPersistedOperationAdminPort - implements GraphQlPersistedOperationAdminPort { - - private final GraphQlPersistedOperationRegistry registry; - private final List auditTrail = new CopyOnWriteArrayList<>(); - private final Object commandLock = new Object(); - - /** - * Creates the port. - * - * @param registry the operation store this port mutates - */ - public InMemoryGraphQlPersistedOperationAdminPort(GraphQlPersistedOperationRegistry registry) { - this.registry = Objects.requireNonNull(registry, "registry is required"); - } - - @Override - public GraphQlPersistedOperation register( - GraphQlPersistedOperation operation, GraphQlPersistedOperationAudit audit) { - synchronized (commandLock) { - registry.register(operation); - // Appended only after the mutation succeeded: a rejected registration must not leave a - // record saying it happened. - auditTrail.add(audit); - return operation; - } - } - - @Override - public GraphQlPersistedOperation apply( - GraphQlPersistedOperationId operationId, - GraphQlPersistedOperationTransition transition, - GraphQlPersistedOperationAudit audit) { - synchronized (commandLock) { - GraphQlPersistedOperation updated = registry.apply(operationId, transition); - auditTrail.add(audit); - return updated; - } - } - - @Override - public List auditTrail() { - return List.copyOf(auditTrail); - } -} diff --git a/src/adapter/inbound/graphql/src/testFixtures/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/InMemoryGraphQlPersistedOperationRegistry.java b/src/adapter/inbound/graphql/src/testFixtures/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/InMemoryGraphQlPersistedOperationRegistry.java deleted file mode 100644 index a6858e01..00000000 --- a/src/adapter/inbound/graphql/src/testFixtures/java/dev/caskeleton/adapter/inbound/graphql/advanced/persisted/InMemoryGraphQlPersistedOperationRegistry.java +++ /dev/null @@ -1,59 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.advanced.persisted; - -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.ConcurrentHashMap; - -/** - * An in-memory registry, for tests and single-instance development. - * - *

Not a production implementation: it is neither durable nor shared, so a block applied during - * an incident would survive neither a restart nor the other instances. The Advanced release gate - * requires durable registry evidence for exactly this reason. - */ -public final class InMemoryGraphQlPersistedOperationRegistry - implements GraphQlPersistedOperationRegistry { - - private final Map operations = - new ConcurrentHashMap<>(); - - @Override - public void register(GraphQlPersistedOperation operation) { - GraphQlPersistedOperation existing = operations.putIfAbsent(operation.id(), operation); - if (existing != null && !existing.documentHash().equals(operation.documentHash())) { - throw new GraphQlPersistedOperationConflictException(operation.id().value()); - } - } - - @Override - public Optional find(GraphQlPersistedOperationId id) { - return Optional.ofNullable(operations.get(id)); - } - - @Override - public GraphQlPersistedOperation apply( - GraphQlPersistedOperationId id, GraphQlPersistedOperationTransition transition) { - // compute, not computeIfPresent: an absent id has to become a failure rather than silence, and - // the transition check has to happen inside the map's per-key lock so two concurrent admins - // cannot both read ACTIVE and both apply a transition from it. - GraphQlPersistedOperation updated = - operations.compute( - id, - (key, existing) -> { - if (existing == null) { - return null; - } - transition.verify(id, existing.status()); - return existing.withStatus(transition.target()); - }); - if (updated == null) { - throw new GraphQlPersistedOperationNotFoundException(id.value()); - } - return updated; - } - - /** How many operations are registered. */ - public int size() { - return operations.size(); - } -} diff --git a/src/adapter/inbound/graphql/src/testFixtures/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlPartialResponseFixture.java b/src/adapter/inbound/graphql/src/testFixtures/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlPartialResponseFixture.java deleted file mode 100644 index 6e736814..00000000 --- a/src/adapter/inbound/graphql/src/testFixtures/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlPartialResponseFixture.java +++ /dev/null @@ -1,115 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.error; - -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -/** - * A golden partial response, used to pin null-propagation behaviour. - * - *

Null propagation is easy to change by accident — one {@code !} added to a schema field moves - * the boundary — and impossible to notice from a passing unit test, because the field simply - * disappears from {@code data}. These fixtures make the expected shape explicit so a change has to - * be deliberate. - */ -public final class GraphQlPartialResponseFixture { - - private final Map data; - private final List errors; - - private GraphQlPartialResponseFixture(Map data, List errors) { - this.data = data; - this.errors = List.copyOf(errors); - } - - /** - * A nullable child failed: the parent survives with the child nulled. - * - *

{@code order.payment} is nullable, so the payment dependency being down costs the payment - * field and nothing else. - */ - public static GraphQlPartialResponseFixture nullableChildFailure() { - Map order = new LinkedHashMap<>(); - order.put("id", "o-1"); - order.put("payment", null); - return new GraphQlPartialResponseFixture( - Map.of("order", order), - List.of( - GraphQlWireError.of( - "결제 정보를 조회할 수 없습니다.", - GraphQlErrorCode.of(GraphQlErrorCode.DEPENDENCY_UNAVAILABLE), - GraphQlErrorCategory.DEPENDENCY, - GraphQlErrorContext.field( - "exec-1", List.of("order", "payment"), "Order.payment")))); - } - - /** - * A non-null child failed: the error climbs to the nearest nullable ancestor. - * - *

{@code Order.total} is non-null, so the whole {@code order} becomes null — the cost of the - * stronger promise. - */ - public static GraphQlPartialResponseFixture nonNullChildFailure() { - Map data = new LinkedHashMap<>(); - data.put("order", null); - return new GraphQlPartialResponseFixture( - data, - List.of( - GraphQlWireError.of( - GraphQlWireError.OPAQUE_MESSAGE, - GraphQlErrorCode.of(GraphQlErrorCode.INTERNAL_ERROR), - GraphQlErrorCategory.INTERNAL, - GraphQlErrorContext.field("exec-2", List.of("order", "total"), "Order.total")))); - } - - /** A sibling field failed while the rest of the selection resolved. */ - public static GraphQlPartialResponseFixture siblingFieldFailure() { - Map data = new LinkedHashMap<>(); - data.put("stableField", "ok"); - data.put("failingField", null); - return new GraphQlPartialResponseFixture( - data, - List.of( - GraphQlWireError.of( - GraphQlWireError.OPAQUE_MESSAGE, - GraphQlErrorCode.of(GraphQlErrorCode.INTERNAL_ERROR), - GraphQlErrorCategory.INTERNAL, - GraphQlErrorContext.field( - "exec-3", List.of("failingField"), "Query.failingField")))); - } - - /** The fixture's {@code data}. */ - public Map data() { - return data; - } - - /** The fixture's errors. */ - public List errors() { - return errors; - } - - /** Error paths, for asserting where propagation stopped. */ - public List> errorPaths() { - List> paths = new ArrayList<>(); - errors.forEach(error -> paths.add(error.path())); - return List.copyOf(paths); - } - - /** - * Reads a dotted path out of {@code data}. - * - * @param path dotted path, for example {@code order.payment} - * @return the value, or {@code null} when the path is absent or nulled - */ - public Object dataPath(String path) { - Object current = data; - for (String segment : path.split("\\.", -1)) { - if (!(current instanceof Map map)) { - return null; - } - current = map.get(segment); - } - return current; - } -} diff --git a/src/adapter/inbound/graphql/src/testFixtures/java/dev/caskeleton/adapter/inbound/graphql/testkit/GraphQlContractFixture.java b/src/adapter/inbound/graphql/src/testFixtures/java/dev/caskeleton/adapter/inbound/graphql/testkit/GraphQlContractFixture.java deleted file mode 100644 index 9d00d1e8..00000000 --- a/src/adapter/inbound/graphql/src/testFixtures/java/dev/caskeleton/adapter/inbound/graphql/testkit/GraphQlContractFixture.java +++ /dev/null @@ -1,166 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.testkit; - -import dev.caskeleton.adapter.inbound.graphql.error.GraphQlErrorCategory; -import dev.caskeleton.adapter.inbound.graphql.error.GraphQlErrorCode; -import dev.caskeleton.adapter.inbound.graphql.error.GraphQlErrorContext; -import dev.caskeleton.adapter.inbound.graphql.error.GraphQlWireError; -import dev.caskeleton.adapter.inbound.graphql.http.GraphQlExecutionOutcome; -import dev.caskeleton.adapter.inbound.graphql.http.GraphQlHttpContractException; -import dev.caskeleton.adapter.inbound.graphql.http.GraphQlHttpExecutor; -import dev.caskeleton.adapter.inbound.graphql.http.GraphQlHttpProfile; -import dev.caskeleton.adapter.inbound.graphql.http.GraphQlHttpRequestEnvelope; -import dev.caskeleton.adapter.inbound.graphql.http.GraphQlHttpResponse; -import dev.caskeleton.adapter.inbound.graphql.http.GraphQlHttpResponseFactory; -import dev.caskeleton.adapter.inbound.graphql.http.GraphQlMediaTypes; -import dev.caskeleton.adapter.inbound.graphql.http.GraphQlRequestEnvelopeValidator; -import dev.caskeleton.adapter.inbound.graphql.policy.GraphQlClientPolicy; -import java.time.Duration; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -/** - * Drives one operation through the platform's real HTTP response policies (Stable plan Task 47). - * - *

Runs the actual method and media-type checks, envelope validation and status mapping rather - * than asserting against a hand-built response. A contract test that constructs the response it - * then asserts on proves nothing about the contract. - * - *

What it deliberately is not is a transport. The route belongs to Spring's {@code - * GraphQlHttpHandler}, and the platform's policies reach a real request through {@code - * GraphQlPlatformWebInterceptor} and {@code GraphQlPlatformInstrumentation}. This fixture executes - * nothing and owns no threads: it composes the pure policies, so it can never become the second - * execution path that the custom MVC and WebFlux adapters had turned into. - * - *

The execution seam is a stub, because the point is the response and error contract, not any - * particular resolver. - */ -public final class GraphQlContractFixture { - - private final GraphQlHttpProfile profile; - private final GraphQlRequestEnvelopeValidator validator; - private final GraphQlHttpExecutor executor; - - private GraphQlContractFixture( - GraphQlHttpProfile profile, - GraphQlRequestEnvelopeValidator validator, - GraphQlHttpExecutor executor) { - this.profile = profile; - this.validator = validator; - this.executor = executor; - } - - /** - * The standard fixture: one stable field, one failing field. - * - *

Enough to exercise partial data, the 200 contract for field errors and error masking - * together. - */ - public static GraphQlContractFixture standard() { - return withExecutor( - (envelope, context) -> { - if (envelope.query().contains("failingField")) { - Map data = new LinkedHashMap<>(); - data.put("stableField", "ok"); - data.put("failingField", null); - return GraphQlExecutionOutcome.partial( - data, - List.of( - GraphQlWireError.of( - GraphQlWireError.OPAQUE_MESSAGE, - GraphQlErrorCode.of(GraphQlErrorCode.INTERNAL_ERROR), - GraphQlErrorCategory.INTERNAL, - GraphQlErrorContext.field( - "exec-contract", List.of("failingField"), "Query.failingField")) - .toWireMap())); - } - return GraphQlExecutionOutcome.success(Map.of("stableField", "ok")); - }); - } - - /** A fixture with a caller-supplied execution seam. */ - public static GraphQlContractFixture withExecutor(GraphQlHttpExecutor executor) { - return new GraphQlContractFixture( - GraphQlHttpProfile.V1, GraphQlRequestEnvelopeValidator.forPolicy(clientPolicy()), executor); - } - - /** Runs a document through the response contract. */ - public GraphQlContractResponse executeHttp(String document) { - return executeHttp(document, GraphQlMediaTypes.GRAPHQL_RESPONSE_JSON); - } - - /** Runs a document, negotiating an explicit response media type. */ - public GraphQlContractResponse executeHttp(String document, String accept) { - return executeHttp("POST", document, accept); - } - - /** Runs a document with an explicit HTTP method, for transport rejection cases. */ - public GraphQlContractResponse executeHttp(String method, String document, String accept) { - GraphQlHttpResponse response = - respond( - method, - accept, - new GraphQlHttpRequestEnvelope( - document, operationNameOf(document), Map.of(), Map.of())); - return new GraphQlContractResponse( - response.status(), response.contentType(), response.data(), response.errors()); - } - - /** - * Releases fixture resources; the fixture owns none, so this exists for symmetry with callers. - */ - public void close() { - // No executor, no threads, no route: there is deliberately nothing to release. - } - - /** - * Applies the platform's HTTP response contract to one exchange. - * - *

A client-caused failure never propagates as an exception: it becomes the response the - * profile mandates, which is the property the contract suite is checking. - */ - private GraphQlHttpResponse respond( - String method, String accept, GraphQlHttpRequestEnvelope envelope) { - - GraphQlHttpResponseFactory responses = GraphQlHttpResponseFactory.preferredV1(); - try { - profile.validateMethod(method); - profile.validateContentType(GraphQlMediaTypes.APPLICATION_JSON); - responses = GraphQlHttpResponseFactory.v1(profile.negotiateResponseContentType(accept)); - validator.validateEnvelope(envelope); - - GraphQlExecutionOutcome outcome = - executor.execute(envelope, GraphQlRequestContexts.testContext("tenant-a")); - return outcome.failed() - ? responses.fieldError(outcome.data(), outcome.errors()) - : responses.success(outcome.data()); - } catch (GraphQlHttpContractException failure) { - return responses.requestError(failure); - } - } - - private static String operationNameOf(String document) { - String[] tokens = document.strip().split("\\s+", 3); - return tokens.length >= 2 ? tokens[1].replaceAll("[^A-Za-z0-9_].*$", "") : null; - } - - private static GraphQlClientPolicy clientPolicy() { - return new GraphQlClientPolicy( - 65536, - 65536, - 12, - 500, - 50, - 50, - 1000, - 20, - 100, - 10_000, - 10_000, - 5_242_880, - Duration.ofSeconds(5), - false, - false, - true); - } -} diff --git a/src/adapter/inbound/graphql/src/testFixtures/java/dev/caskeleton/adapter/inbound/graphql/testkit/GraphQlContractResponse.java b/src/adapter/inbound/graphql/src/testFixtures/java/dev/caskeleton/adapter/inbound/graphql/testkit/GraphQlContractResponse.java deleted file mode 100644 index 4cb9d863..00000000 --- a/src/adapter/inbound/graphql/src/testFixtures/java/dev/caskeleton/adapter/inbound/graphql/testkit/GraphQlContractResponse.java +++ /dev/null @@ -1,33 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.testkit; - -import java.util.List; -import java.util.Map; - -/** - * A transport-independent view of one GraphQL response, for assertions. - * - *

The same shape whether the operation ran through execution, MVC or the reactive transport, so - * one contract suite can be replayed across all of them instead of being rewritten per transport. - * - * @param status HTTP status - * @param contentType negotiated response media type - * @param data resolved data, possibly partial - * @param errors GraphQL errors - */ -public record GraphQlContractResponse( - int status, String contentType, Map data, List> errors) { - - public GraphQlContractResponse { - // Partial data legitimately contains nulled fields, which Map.copyOf refuses to hold. - data = - data == null - ? Map.of() - : java.util.Collections.unmodifiableMap(new java.util.LinkedHashMap<>(data)); - errors = errors == null ? List.of() : List.copyOf(errors); - } - - /** Whether data resolved alongside errors. */ - public boolean partial() { - return !data.isEmpty() && !errors.isEmpty(); - } -} diff --git a/src/adapter/inbound/graphql/src/testFixtures/java/dev/caskeleton/adapter/inbound/graphql/testkit/GraphQlContractViolation.java b/src/adapter/inbound/graphql/src/testFixtures/java/dev/caskeleton/adapter/inbound/graphql/testkit/GraphQlContractViolation.java deleted file mode 100644 index 29bcdc48..00000000 --- a/src/adapter/inbound/graphql/src/testFixtures/java/dev/caskeleton/adapter/inbound/graphql/testkit/GraphQlContractViolation.java +++ /dev/null @@ -1,32 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.testkit; - -import java.util.List; - -/** - * Raised when a contract suite finds a violation. - * - *

A plain exception rather than a test-framework assertion, so the suites can be reused from any - * module and from a release gate that is not a test at all. - */ -public class GraphQlContractViolation extends RuntimeException { - - private static final long serialVersionUID = 1L; - - private final transient List violations; - - /** - * Creates the failure. - * - * @param suite the suite that found the violations - * @param violations what failed - */ - public GraphQlContractViolation(String suite, List violations) { - super(suite + " contract violated: " + violations); - this.violations = List.copyOf(violations); - } - - /** The violations found. */ - public List violations() { - return violations; - } -} diff --git a/src/adapter/inbound/graphql/src/testFixtures/java/dev/caskeleton/adapter/inbound/graphql/testkit/GraphQlDataLoaderContractSuite.java b/src/adapter/inbound/graphql/src/testFixtures/java/dev/caskeleton/adapter/inbound/graphql/testkit/GraphQlDataLoaderContractSuite.java deleted file mode 100644 index d095344d..00000000 --- a/src/adapter/inbound/graphql/src/testFixtures/java/dev/caskeleton/adapter/inbound/graphql/testkit/GraphQlDataLoaderContractSuite.java +++ /dev/null @@ -1,70 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.testkit; - -import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlBatchResult; -import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlBatchResultMapper; -import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlBatchValue; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * The DataLoader contract: batching, ordering, missing keys and per-key failures (Stable plan Task - * 47). - * - *

The N+1 check is a query count assertion, because that is the only way the regression - * is visible: a resolver that issues one query per parent returns exactly the same data as one that - * batches. - */ -public final class GraphQlDataLoaderContractSuite { - - private GraphQlDataLoaderContractSuite() {} - - /** - * Verifies the loader contract. - * - * @param keys the requested keys, in order - * @param loaded values the loader returned - * @param failedKeys keys the loader failed on - * @param observedQueryCount how many queries the loader actually issued - * @throws GraphQlContractViolation listing every failed expectation - */ - public static void verify( - List keys, - Map loaded, - Set failedKeys, - int observedQueryCount) { - - List violations = new ArrayList<>(); - GraphQlBatchResult result = - new GraphQlBatchResultMapper().map(keys, loaded, failedKeys, "LOAD_FAILED"); - - if (result.values().size() != keys.size()) { - violations.add("a batch must produce exactly one result per requested key"); - } - if (!new ArrayList<>(result.values().keySet()).equals(keys)) { - violations.add("a batch must preserve the requested key order"); - } - if (observedQueryCount > 1) { - violations.add( - "N+1 regression: " - + observedQueryCount - + " queries were issued for one batch of " - + keys.size()); - } - for (String key : keys) { - GraphQlBatchValue value = result.values().get(key); - boolean expectedFailure = failedKeys.contains(key); - if (expectedFailure != value.failed()) { - violations.add("key outcome for a failed key must be Failed, not null"); - } - if (!expectedFailure && !loaded.containsKey(key) && value.resolved()) { - violations.add("a missing key must not be reported as resolved"); - } - } - - if (!violations.isEmpty()) { - throw new GraphQlContractViolation("DataLoader", violations); - } - } -} diff --git a/src/adapter/inbound/graphql/src/testFixtures/java/dev/caskeleton/adapter/inbound/graphql/testkit/GraphQlDownstreamFailureFixture.java b/src/adapter/inbound/graphql/src/testFixtures/java/dev/caskeleton/adapter/inbound/graphql/testkit/GraphQlDownstreamFailureFixture.java deleted file mode 100644 index 70cae2c5..00000000 --- a/src/adapter/inbound/graphql/src/testFixtures/java/dev/caskeleton/adapter/inbound/graphql/testkit/GraphQlDownstreamFailureFixture.java +++ /dev/null @@ -1,58 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.testkit; - -import dev.caskeleton.adapter.inbound.graphql.error.GraphQlInternalErrorMasker; -import dev.caskeleton.adapter.inbound.graphql.execution.GraphQlCancellation; -import dev.caskeleton.adapter.inbound.graphql.http.GraphQlExecutionOutcome; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.concurrent.atomic.AtomicBoolean; - -/** - * Drives a dependency failure and asserts what the client sees (Stable plan Task 47). - * - *

Three things at once, because they fail together in practice: sibling data must survive, the - * message must not disclose the dependency, and the timeout must actually cancel the work rather - * than only releasing the caller. - */ -public final class GraphQlDownstreamFailureFixture { - - private GraphQlDownstreamFailureFixture() {} - - /** - * Verifies the behaviour of a partial failure. - * - * @param outcome what execution produced when the dependency failed - * @param cancellation the request cancellation signal - * @throws GraphQlContractViolation listing every failed expectation - */ - public static void verifyPartialFailure( - GraphQlExecutionOutcome outcome, GraphQlCancellation cancellation) { - - List violations = new ArrayList<>(); - - if (outcome.data() == null || outcome.data().isEmpty()) { - violations.add("a dependency failure must not discard the data that did resolve"); - } - if (!outcome.failed()) { - violations.add("a dependency failure must be reported in errors"); - } - for (Map error : outcome.errors()) { - Object message = error.get("message"); - if (message instanceof String text && GraphQlInternalErrorMasker.discloses(text)) { - violations.add("a client-visible error must not disclose the dependency"); - } - } - - AtomicBoolean downstreamStopped = new AtomicBoolean(); - cancellation.onCancel(() -> downstreamStopped.set(true)); - cancellation.cancel(); - if (!downstreamStopped.get()) { - violations.add("a timeout must cancel in-flight downstream work"); - } - - if (!violations.isEmpty()) { - throw new GraphQlContractViolation("Downstream failure", violations); - } - } -} diff --git a/src/adapter/inbound/graphql/src/testFixtures/java/dev/caskeleton/adapter/inbound/graphql/testkit/GraphQlHttpContractSuite.java b/src/adapter/inbound/graphql/src/testFixtures/java/dev/caskeleton/adapter/inbound/graphql/testkit/GraphQlHttpContractSuite.java deleted file mode 100644 index 43e87cf7..00000000 --- a/src/adapter/inbound/graphql/src/testFixtures/java/dev/caskeleton/adapter/inbound/graphql/testkit/GraphQlHttpContractSuite.java +++ /dev/null @@ -1,62 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.testkit; - -import dev.caskeleton.adapter.inbound.graphql.http.GraphQlMediaTypes; -import java.util.ArrayList; -import java.util.List; - -/** - * The HTTP transport contract, replayable against any transport (Stable plan Task 47). - * - *

The rule worth a suite of its own: a field error is HTTP 200 with whatever data resolved. It - * is easy to break by "improving" error handling into a 500, and the breakage looks like better - * hygiene until a client loses half a working response. - */ -public final class GraphQlHttpContractSuite { - - private GraphQlHttpContractSuite() {} - - /** - * Verifies the transport contract against a fixture. - * - * @throws GraphQlContractViolation listing every failed expectation - */ - public static void verify(GraphQlContractFixture fixture) { - List violations = new ArrayList<>(); - - GraphQlContractResponse partial = - fixture.executeHttp("query Contract { stableField failingField }"); - if (partial.status() != 200) { - violations.add("a field error must stay HTTP 200 but was " + partial.status()); - } - if (!partial.data().containsKey("stableField")) { - violations.add("sibling data must survive a field error"); - } - if (partial.errors().isEmpty()) { - violations.add("a field error must be reported in errors"); - } - if (!GraphQlMediaTypes.GRAPHQL_RESPONSE_JSON.equals(partial.contentType())) { - violations.add("the preferred response media type must be negotiated"); - } - - GraphQlContractResponse legacy = - fixture.executeHttp( - "query Contract { stableField }", GraphQlMediaTypes.LEGACY_RESPONSE_JSON); - if (!GraphQlMediaTypes.LEGACY_RESPONSE_JSON.equals(legacy.contentType())) { - violations.add("legacy application/json clients must stay supported"); - } - - GraphQlContractResponse rejected = - fixture.executeHttp( - "GET", "query Contract { stableField }", GraphQlMediaTypes.GRAPHQL_RESPONSE_JSON); - if (rejected.status() != 405) { - violations.add("a non-POST request must be rejected with 405 but was " + rejected.status()); - } - if (rejected.errors().isEmpty()) { - violations.add("a rejected request must explain itself in errors"); - } - - if (!violations.isEmpty()) { - throw new GraphQlContractViolation("HTTP", violations); - } - } -} diff --git a/src/adapter/inbound/graphql/src/testFixtures/java/dev/caskeleton/adapter/inbound/graphql/testkit/GraphQlJpaIntegrationFixture.java b/src/adapter/inbound/graphql/src/testFixtures/java/dev/caskeleton/adapter/inbound/graphql/testkit/GraphQlJpaIntegrationFixture.java deleted file mode 100644 index b35547b5..00000000 --- a/src/adapter/inbound/graphql/src/testFixtures/java/dev/caskeleton/adapter/inbound/graphql/testkit/GraphQlJpaIntegrationFixture.java +++ /dev/null @@ -1,70 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.testkit; - -import java.util.ArrayList; -import java.util.List; - -/** - * Asserts JPA statement counts for one operation (Stable plan Task 47). - * - *

Counts rather than timings, and against a real PostgreSQL rather than an in-memory substitute: - * an N+1 is invisible in latency on ten rows, and H2 does not reproduce PostgreSQL's planner, its - * locking or its examined-row accounting. - * - *

Evidence that was never executed fails the assertion. "We did not run it" must not read the - * same as "it passed". - */ -public final class GraphQlJpaIntegrationFixture { - - private final int maximumStatements; - private final long maximumExaminedRows; - - /** - * Creates the fixture. - * - * @param maximumStatements statements the operation may issue - * @param maximumExaminedRows rows the engine may examine - */ - public GraphQlJpaIntegrationFixture(int maximumStatements, long maximumExaminedRows) { - if (maximumStatements < 1 || maximumExaminedRows < 1) { - throw new IllegalArgumentException("integration budgets must be positive"); - } - this.maximumStatements = maximumStatements; - this.maximumExaminedRows = maximumExaminedRows; - } - - /** - * Verifies one run's evidence. - * - * @throws GraphQlContractViolation when the run was not executed or exceeded a budget - */ - public void verify(GraphQlStorageIntegrationEvidence evidence) { - List violations = new ArrayList<>(); - - if (!evidence.executed()) { - violations.add( - evidence.operationName() - + " has no executed PostgreSQL evidence; an unexecuted run is not a pass"); - } else { - if (evidence.statementCount() > maximumStatements) { - violations.add( - evidence.operationName() - + " issued " - + evidence.statementCount() - + " statements, above the budget of " - + maximumStatements); - } - if (evidence.examinedRows() > maximumExaminedRows) { - violations.add( - evidence.operationName() - + " examined " - + evidence.examinedRows() - + " rows, above the budget of " - + maximumExaminedRows); - } - } - - if (!violations.isEmpty()) { - throw new GraphQlContractViolation("JPA integration", violations); - } - } -} diff --git a/src/adapter/inbound/graphql/src/testFixtures/java/dev/caskeleton/adapter/inbound/graphql/testkit/GraphQlMongoIntegrationFixture.java b/src/adapter/inbound/graphql/src/testFixtures/java/dev/caskeleton/adapter/inbound/graphql/testkit/GraphQlMongoIntegrationFixture.java deleted file mode 100644 index 6425b2c7..00000000 --- a/src/adapter/inbound/graphql/src/testFixtures/java/dev/caskeleton/adapter/inbound/graphql/testkit/GraphQlMongoIntegrationFixture.java +++ /dev/null @@ -1,67 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.testkit; - -import java.util.ArrayList; -import java.util.List; - -/** - * Asserts MongoDB query counts and examined documents for one operation (Stable plan Task 47). - * - *

Examined documents matter more here than elsewhere: a query that returns ten documents after - * scanning a million is correct and unusable, and only the examined count distinguishes it from an - * indexed one. - */ -public final class GraphQlMongoIntegrationFixture { - - private final int maximumQueries; - private final long maximumExaminedDocuments; - - /** - * Creates the fixture. - * - * @param maximumQueries queries the operation may issue - * @param maximumExaminedDocuments documents the engine may examine - */ - public GraphQlMongoIntegrationFixture(int maximumQueries, long maximumExaminedDocuments) { - if (maximumQueries < 1 || maximumExaminedDocuments < 1) { - throw new IllegalArgumentException("integration budgets must be positive"); - } - this.maximumQueries = maximumQueries; - this.maximumExaminedDocuments = maximumExaminedDocuments; - } - - /** - * Verifies one run's evidence. - * - * @throws GraphQlContractViolation when the run was not executed or exceeded a budget - */ - public void verify(GraphQlStorageIntegrationEvidence evidence) { - List violations = new ArrayList<>(); - - if (!evidence.executed()) { - violations.add( - evidence.operationName() - + " has no executed MongoDB evidence; an unexecuted run is not a pass"); - } else { - if (evidence.statementCount() > maximumQueries) { - violations.add( - evidence.operationName() - + " issued " - + evidence.statementCount() - + " queries, above the budget of " - + maximumQueries); - } - if (evidence.examinedRows() > maximumExaminedDocuments) { - violations.add( - evidence.operationName() - + " examined " - + evidence.examinedRows() - + " documents, above the budget of " - + maximumExaminedDocuments); - } - } - - if (!violations.isEmpty()) { - throw new GraphQlContractViolation("MongoDB integration", violations); - } - } -} diff --git a/src/adapter/inbound/graphql/src/testFixtures/java/dev/caskeleton/adapter/inbound/graphql/testkit/GraphQlPaginationContractSuite.java b/src/adapter/inbound/graphql/src/testFixtures/java/dev/caskeleton/adapter/inbound/graphql/testkit/GraphQlPaginationContractSuite.java deleted file mode 100644 index 89ef04a0..00000000 --- a/src/adapter/inbound/graphql/src/testFixtures/java/dev/caskeleton/adapter/inbound/graphql/testkit/GraphQlPaginationContractSuite.java +++ /dev/null @@ -1,69 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.testkit; - -import dev.caskeleton.adapter.inbound.graphql.pagination.GraphQlConnection; -import dev.caskeleton.adapter.inbound.graphql.pagination.GraphQlConnectionAssembler; -import dev.caskeleton.adapter.inbound.graphql.pagination.GraphQlConnectionPolicy; -import dev.caskeleton.adapter.inbound.graphql.pagination.GraphQlConnectionRequest; -import dev.caskeleton.adapter.inbound.graphql.pagination.GraphQlCursorException; -import dev.caskeleton.adapter.inbound.graphql.pagination.GraphQlKeysetWindow; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -/** - * The pagination contract: page bounds, cursor binding and tamper rejection (Stable plan Task 47). - * - *

The tamper check is the one that matters most. A cursor is the only request parameter clients - * are told to treat as opaque, which means it is the one most likely to be edited by anyone curious - * enough to Base64-decode it. - */ -public final class GraphQlPaginationContractSuite { - - private GraphQlPaginationContractSuite() {} - - /** - * Verifies the pagination contract. - * - * @param assembler the connection assembler under test - * @param policy the page-size policy - * @throws GraphQlContractViolation listing every failed expectation - */ - public static void verify(GraphQlConnectionAssembler assembler, GraphQlConnectionPolicy policy) { - - List violations = new ArrayList<>(); - - GraphQlConnection page = - assembler.forward( - new GraphQlKeysetWindow<>(List.of("a", "b", "c"), 2, false), - value -> Map.of("id", value)); - if (page.edges().size() != 2) { - violations.add("the look-ahead row must not be returned to the client"); - } - if (!page.pageInfo().hasNextPage()) { - violations.add("the look-ahead row must set hasNextPage"); - } - if (page.totalCount().isPresent()) { - violations.add("totalCount must be opt-in rather than always computed"); - } - - try { - policy.effectivePageSize(GraphQlConnectionRequest.forward(policy.maxPageSize() + 1, null)); - violations.add("a page size above the maximum must be rejected"); - } catch (RuntimeException expected) { - // The rejection is the expected outcome. - } - - String cursor = page.edges().getFirst().cursor(); - String tampered = cursor.substring(0, cursor.length() - 2) + "AA"; - try { - assembler.decodeRequestCursor(GraphQlConnectionRequest.forward(2, tampered)); - violations.add("a tampered cursor must be rejected"); - } catch (GraphQlCursorException expected) { - // The rejection is the expected outcome. - } - - if (!violations.isEmpty()) { - throw new GraphQlContractViolation("Pagination", violations); - } - } -} diff --git a/src/adapter/inbound/graphql/src/testFixtures/java/dev/caskeleton/adapter/inbound/graphql/testkit/GraphQlSchemaContractSuite.java b/src/adapter/inbound/graphql/src/testFixtures/java/dev/caskeleton/adapter/inbound/graphql/testkit/GraphQlSchemaContractSuite.java deleted file mode 100644 index ffbbb9b1..00000000 --- a/src/adapter/inbound/graphql/src/testFixtures/java/dev/caskeleton/adapter/inbound/graphql/testkit/GraphQlSchemaContractSuite.java +++ /dev/null @@ -1,65 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.testkit; - -import dev.caskeleton.adapter.inbound.graphql.compat.GraphQlCompatibilityPolicy; -import dev.caskeleton.adapter.inbound.graphql.compat.GraphQlSchemaComparator; -import dev.caskeleton.adapter.inbound.graphql.schema.GraphQlMappingInspectionGate; -import dev.caskeleton.adapter.inbound.graphql.schema.GraphQlMappingIssue; -import dev.caskeleton.adapter.inbound.graphql.schema.GraphQlOneOfSchemaGate; -import dev.caskeleton.adapter.inbound.graphql.schema.GraphQlSchemaAssembler; -import dev.caskeleton.adapter.inbound.graphql.schema.GraphQlSchemaAssemblyResult; -import dev.caskeleton.adapter.inbound.graphql.schema.GraphQlSchemaResource; -import java.util.ArrayList; -import java.util.List; - -/** - * The schema contract: assembly, mapping, {@code @oneOf} and compatibility (Stable plan Task 47). - * - *

Runs the same gates a deployment runs, against a candidate schema, so a breaking change is - * caught in CI rather than at the client. - */ -public final class GraphQlSchemaContractSuite { - - private GraphQlSchemaContractSuite() {} - - /** - * Verifies a candidate schema against the deployed one. - * - * @param resources the candidate schema's fragments - * @param deployedSdl the currently deployed canonical SDL, or {@code null} for a first release - * @param mappingIssues issues the mapping inspection reported - * @throws GraphQlContractViolation listing every failed expectation - */ - public static GraphQlSchemaAssemblyResult verify( - List resources, - String deployedSdl, - List mappingIssues) { - - List violations = new ArrayList<>(); - GraphQlSchemaAssemblyResult assembled = GraphQlSchemaAssembler.defaults().assemble(resources); - - try { - GraphQlOneOfSchemaGate.verify(assembled.registry()); - } catch (RuntimeException ex) { - violations.add("@oneOf declaration is invalid: " + ex.getMessage()); - } - - try { - GraphQlMappingInspectionGate.stable().verify(mappingIssues); - } catch (RuntimeException ex) { - violations.add("schema mapping inspection failed: " + ex.getMessage()); - } - - if (deployedSdl != null) { - var report = GraphQlSchemaComparator.compare(deployedSdl, assembled.canonicalSdl()); - var policy = GraphQlCompatibilityPolicy.stableV1(); - if (!policy.permits(report)) { - violations.addAll(policy.rejections(report)); - } - } - - if (!violations.isEmpty()) { - throw new GraphQlContractViolation("Schema", violations); - } - return assembled; - } -} diff --git a/src/adapter/inbound/graphql/src/testFixtures/java/dev/caskeleton/adapter/inbound/graphql/testkit/GraphQlSecurityContractSuite.java b/src/adapter/inbound/graphql/src/testFixtures/java/dev/caskeleton/adapter/inbound/graphql/testkit/GraphQlSecurityContractSuite.java deleted file mode 100644 index 4b3e34ac..00000000 --- a/src/adapter/inbound/graphql/src/testFixtures/java/dev/caskeleton/adapter/inbound/graphql/testkit/GraphQlSecurityContractSuite.java +++ /dev/null @@ -1,71 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.testkit; - -import dev.caskeleton.adapter.inbound.graphql.api.GraphQlSchemaCoordinate; -import dev.caskeleton.adapter.inbound.graphql.context.GraphQlRequestContext; -import dev.caskeleton.adapter.inbound.graphql.security.GraphQlAuthorizationPolicy; -import dev.caskeleton.adapter.inbound.graphql.security.GraphQlBatchContext; -import dev.caskeleton.adapter.inbound.graphql.security.GraphQlObjectAuthorizationPort; -import dev.caskeleton.adapter.inbound.graphql.security.GraphQlTenantIsolationPolicy; -import java.util.ArrayList; -import java.util.List; -import java.util.Set; - -/** - * The security contract: actor, tenant, field and object isolation (Stable plan Task 47). - * - *

Checks the bypasses rather than the happy path. Authorization that works for a permitted - * caller tells you nothing; what matters is that a hidden field still checks, a tenant cannot be - * named by the client, and a batch load does not become an isolation hole. - */ -public final class GraphQlSecurityContractSuite { - - private GraphQlSecurityContractSuite() {} - - /** - * Verifies the security contract. - * - * @param policy the coordinate authorization rules - * @param objectAuthorization the Application object-authorization port - * @param deniedContext a context that must be denied by {@code deniedCoordinate} - * @param deniedCoordinate a coordinate the context must not be allowed to execute - * @throws GraphQlContractViolation listing every failed expectation - */ - public static void verify( - GraphQlAuthorizationPolicy policy, - GraphQlObjectAuthorizationPort objectAuthorization, - GraphQlRequestContext deniedContext, - GraphQlSchemaCoordinate deniedCoordinate) { - - List violations = new ArrayList<>(); - - if (policy.authorize(deniedContext, deniedCoordinate).allowed()) { - violations.add(deniedCoordinate.value() + " must not be authorized for this client profile"); - } - if (policy.hiddenFromIntrospection(deniedCoordinate) - && policy.authorize(deniedContext, deniedCoordinate).allowed()) { - violations.add("hiding a coordinate from introspection must not authorize it"); - } - - try { - GraphQlTenantIsolationPolicy.rejectTenantArgument( - java.util.Map.of("tenantId", "tenant-b"), Set.of("tenantId")); - violations.add("a tenant argument must be rejected"); - } catch (RuntimeException expected) { - // The rejection is the expected outcome. - } - - GraphQlBatchContext batch = GraphQlBatchContext.from(deniedContext); - if (batch.cacheScope().contains(deniedContext.tenant().value())) { - violations.add("a batch cache scope must not contain a raw tenant identifier"); - } - - var decisions = objectAuthorization.authorizeAll(deniedContext, "Order", List.of("o-1", "o-2")); - if (decisions.size() != 2) { - violations.add("object authorization must answer for every requested key"); - } - - if (!violations.isEmpty()) { - throw new GraphQlContractViolation("Security", violations); - } - } -} diff --git a/src/adapter/inbound/graphql/src/testFixtures/java/dev/caskeleton/adapter/inbound/graphql/testkit/GraphQlStorageIntegrationEvidence.java b/src/adapter/inbound/graphql/src/testFixtures/java/dev/caskeleton/adapter/inbound/graphql/testkit/GraphQlStorageIntegrationEvidence.java deleted file mode 100644 index 62cdf862..00000000 --- a/src/adapter/inbound/graphql/src/testFixtures/java/dev/caskeleton/adapter/inbound/graphql/testkit/GraphQlStorageIntegrationEvidence.java +++ /dev/null @@ -1,30 +0,0 @@ -package dev.caskeleton.adapter.inbound.graphql.testkit; - -/** - * Measurements one storage integration run produced. - * - *

Statement and examined-row counts, because those are the numbers that make an N+1 or a missing - * index visible. A latency figure alone hides both on a small dataset. - * - * @param operationName the operation that was executed - * @param statementCount statements the operation issued - * @param examinedRows rows or documents the storage engine examined - * @param executed whether the run actually happened against a real datastore - */ -public record GraphQlStorageIntegrationEvidence( - String operationName, int statementCount, long examinedRows, boolean executed) { - - public GraphQlStorageIntegrationEvidence { - if (operationName == null || operationName.isBlank()) { - throw new IllegalArgumentException("operation name is required"); - } - if (statementCount < 0 || examinedRows < 0) { - throw new IllegalArgumentException("integration counts cannot be negative"); - } - } - - /** Evidence that has not been produced yet; never counts as a pass. */ - public static GraphQlStorageIntegrationEvidence notExecuted(String operationName) { - return new GraphQlStorageIntegrationEvidence(operationName, 0, 0, false); - } -} diff --git a/src/adapter/inbound/grpc/CLAUDE.md b/src/adapter/inbound/grpc/CLAUDE.md index f5c45faa..fecafa09 100644 --- a/src/adapter/inbound/grpc/CLAUDE.md +++ b/src/adapter/inbound/grpc/CLAUDE.md @@ -15,7 +15,7 @@ Package root: `dev.caskeleton.adapter.inbound.grpc`. ## Responsibility -- gRPC 전송 인프라만: 서버 수명주기(`GrpcServerRunner`), 타입드 설정(`GrpcServerProperties`), +- gRPC 전송 인프라만: 서버 수명주기(`GrpcServerRunner`), 타입드 설정(`GrpcServerSettings`), feature 인증 정책 경계, 프로토콜 에러 매핑(`GrpcStatusMapper` + `GrpcExceptionHandlingInterceptor`), 그리고 `.proto` 없이도 부팅하는 최소 표면(standard health, 명시적으로 켠 경우에만 reflection). @@ -45,7 +45,7 @@ Package root: `dev.caskeleton.adapter.inbound.grpc`. | key | default | 의미 | |---|---|---| -| `enabled` | `false` | `true`를 명시해야만 관련 빈과 listener가 생긴다 | +| `enabled` | `true` | 모듈이 있으면 켜진다. `false`면 관련 빈과 listener가 생기지 않는다 | | `port` | `9090` | 바인딩 TCP 포트. `0` 이면 ephemeral 포트(테스트) | | `bindAddress` | `127.0.0.1` | P1 insecure listener 바인드. loopback 주소만 허용한다 | | `allowInsecureLocal` | `false` | local plaintext 위험을 명시적으로 승인하는 개발용 override | diff --git a/src/adapter/inbound/grpc/README.md b/src/adapter/inbound/grpc/README.md index 22e3e513..07ed6de9 100644 --- a/src/adapter/inbound/grpc/README.md +++ b/src/adapter/inbound/grpc/README.md @@ -9,6 +9,25 @@ --- +## 제공하는 것 · 추가할 한 줄 · 설정 키 + +- 제공: io.grpc Netty 서버(`GrpcServerRunner`, SmartLifecycle), health·(선택) reflection 서비스, + `@GrpcExposedService` 서비스만 노출, 인증 정책 강제, 에러 매핑 인터셉터. 진입점은 모듈 자신의 + `AutoConfiguration.imports`에 있는 `GrpcServerConfig`이고 설정 바인딩도 그 안에서 한다. +- 추가할 한 줄(기본 조립에는 없다): + + ```groovy + // app-bootstrap/build.gradle + runtimeOnly project(':adapter:inbound:grpc') // gRPC 서버 + ``` + + 이 줄을 지우면 서버, 포트, 설정 바인딩이 모두 함께 빠진다. +- 켜기와 끄기: 모듈이 있으면 켜진다. `ca-skeleton.grpc.enabled=false`로만 끈다. +- 필요한 설정: 전용 `APP_*` env 키는 registry에 없다. 켜진 상태에서 지금 구현이 받는 listener는 + loopback plaintext뿐이라 `ca-skeleton.grpc.allow-insecure-local=true`(env + `CA_SKELETON_GRPC_ALLOW_INSECURE_LOCAL=true`)를 명시해야 기동한다. 선택: `ca-skeleton.grpc.port` + (기본 9090), `.bind-address`(기본 127.0.0.1), `.reflection-enabled`, `.shutdown-grace-seconds`. + ## 왜 self-managed Netty 인가 - **third-party grpc-spring-boot starter 를 쓰지 않는다.** `GrpcServerRunner` 가 io.grpc Netty @@ -21,7 +40,7 @@ - **graceful shutdown.** `shutdownGraceSeconds` 동안 in-flight RPC 를 기다린 뒤 `shutdownNow()`. 종료 진입 시 health 를 `enterTerminalState()`(NOT_SERVING)로 뒤집어 로드밸런서가 드레이닝을 인지하게 한다. -- **fail-closed local insecure bind.** 기본은 서버 비활성·reflection 비활성이다. 현재 구현의 +- **fail-closed local insecure bind.** 모듈이 있으면 서버가 켜지지만 reflection은 비활성이다. 현재 구현의 plaintext credential은 `allowInsecureLocal=true`를 명시하고 실제 loopback 주소에 바인딩할 때만 허용한다. wildcard/외부 주소의 insecure 시작은 실패한다. 이 제약의 운영적 의미는 명확하다: **현재 어댑터는 local/same-Pod sidecar 전용**이다. diff --git a/src/adapter/inbound/grpc/build.gradle b/src/adapter/inbound/grpc/build.gradle index 956a7c4f..888f5b6e 100644 --- a/src/adapter/inbound/grpc/build.gradle +++ b/src/adapter/inbound/grpc/build.gradle @@ -1,7 +1,6 @@ plugins { id 'ca.spring-library' id 'ca.spring-config' - id 'ca.strict-qualification' } String grpcVersion = libs.versions.grpc.get() @@ -46,12 +45,12 @@ dependencies { testImplementation "io.grpc:grpc-stub:${grpcVersion}" } -extensions.getByName('strictQualification').register( - 'grpcTransportQualificationTest', - sourceSets.test, - [ - 'dev.caskeleton.adapter.inbound.grpc.GrpcSafeActivationTest', +strictTestLanes { + lane('grpcTransportQualificationTest') { + description = 'Runs exact no-skip gRPC conditional transport wire evidence.' + requires 'dev.caskeleton.adapter.inbound.grpc.GrpcSafeActivationTest', 'dev.caskeleton.adapter.inbound.grpc.GrpcP1BoundaryWireTest' - ], - 'Runs exact no-skip gRPC conditional transport wire evidence.' -) + rejectSkipped = true + jvmArgs '-Duser.timezone=UTC' + } +} diff --git a/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcServerConfig.java b/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcServerConfig.java index 25fe7ade..9e421352 100644 --- a/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcServerConfig.java +++ b/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcServerConfig.java @@ -3,24 +3,28 @@ package dev.caskeleton.adapter.inbound.grpc; import io.grpc.BindableService; import io.grpc.protobuf.services.HealthStatusManager; import org.springframework.beans.factory.ObjectProvider; +import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; /** - * Wires the gRPC transport machinery only when {@code ca-skeleton.grpc.enabled=true} is explicit. - * All collaborators are plain objects composed here, mirroring the clean DI style used across the - * skeleton. A feature service is exposed only when its {@link BindableService} bean carries {@link - * GrpcExposedService}; unrelated services in the same context remain private. See README. + * Wires the gRPC transport machinery. Registered through this module's own {@code + * AutoConfiguration.imports}: on when the module is present, off with {@code + * ca-skeleton.grpc.enabled=false}. The plaintext listener still refuses to start unless {@code + * ca-skeleton.grpc.allow-insecure-local=true} is explicit. + * + *

All collaborators are plain objects composed here, mirroring the clean DI style used across + * the skeleton. A feature service is exposed only when its {@link BindableService} bean carries + * {@link GrpcExposedService}; unrelated services in the same context remain private. See README. */ -@Configuration(proxyBeanMethods = false) +@AutoConfiguration @ConditionalOnProperty( prefix = "ca-skeleton.grpc", name = "enabled", havingValue = "true", - matchIfMissing = false) -@EnableConfigurationProperties(GrpcServerProperties.class) + matchIfMissing = true) +@EnableConfigurationProperties(GrpcServerSettings.class) public class GrpcServerConfig { @Bean @@ -42,7 +46,7 @@ public class GrpcServerConfig { GrpcServerRunner grpcServerRunner( @GrpcExposedService ObjectProvider services, ObjectProvider authenticationPolicies, - GrpcServerProperties properties, + GrpcServerSettings properties, GrpcExceptionHandlingInterceptor exceptionInterceptor, GrpcStatusMapper statusMapper, HealthStatusManager healthStatusManager) { diff --git a/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcServerRunner.java b/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcServerRunner.java index 94b448f3..d9f5931a 100644 --- a/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcServerRunner.java +++ b/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcServerRunner.java @@ -36,7 +36,7 @@ public class GrpcServerRunner implements SmartLifecycle { private final List services; private final ObjectProvider authenticationPolicies; - private final GrpcServerProperties properties; + private final GrpcServerSettings properties; private final GrpcExceptionHandlingInterceptor exceptionInterceptor; private final GrpcStatusMapper statusMapper; private final HealthStatusManager healthStatusManager; @@ -45,7 +45,7 @@ public class GrpcServerRunner implements SmartLifecycle { public GrpcServerRunner( List services, ObjectProvider authenticationPolicies, - GrpcServerProperties properties, + GrpcServerSettings properties, GrpcExceptionHandlingInterceptor exceptionInterceptor, GrpcStatusMapper statusMapper, HealthStatusManager healthStatusManager) { diff --git a/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcServerProperties.java b/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcServerSettings.java similarity index 92% rename from src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcServerProperties.java rename to src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcServerSettings.java index 0a306682..d1ad8fc0 100644 --- a/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcServerProperties.java +++ b/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcServerSettings.java @@ -16,10 +16,13 @@ import org.springframework.validation.annotation.Validated; */ @ConfigurationProperties(prefix = "ca-skeleton.grpc", ignoreUnknownFields = false) @Validated -public class GrpcServerProperties { +public class GrpcServerSettings { - /** Whether to start the gRPC server at all. Activation must always be explicit. */ - private boolean enabled; + /** + * Whether to start the gRPC server at all. On when the module is present; {@code false} turns it + * off. The plaintext listener itself still needs {@link #allowInsecureLocal}. + */ + private boolean enabled = true; /** TCP port the gRPC server binds to. Set to {@code 0} to bind an ephemeral port (tests). */ @Min(0) diff --git a/src/adapter/inbound/grpc/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/src/adapter/inbound/grpc/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports new file mode 100644 index 00000000..7f2be6b2 --- /dev/null +++ b/src/adapter/inbound/grpc/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports @@ -0,0 +1 @@ +dev.caskeleton.adapter.inbound.grpc.GrpcServerConfig diff --git a/src/adapter/inbound/grpc/src/test/java/dev/caskeleton/adapter/inbound/grpc/GrpcSafeActivationTest.java b/src/adapter/inbound/grpc/src/test/java/dev/caskeleton/adapter/inbound/grpc/GrpcSafeActivationTest.java index 14c00ce6..e46857f5 100644 --- a/src/adapter/inbound/grpc/src/test/java/dev/caskeleton/adapter/inbound/grpc/GrpcSafeActivationTest.java +++ b/src/adapter/inbound/grpc/src/test/java/dev/caskeleton/adapter/inbound/grpc/GrpcSafeActivationTest.java @@ -6,6 +6,7 @@ import io.grpc.BindableService; import io.grpc.ServerServiceDefinition; import io.grpc.protobuf.services.HealthStatusManager; import org.junit.jupiter.api.Test; +import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -13,23 +14,45 @@ import org.springframework.context.annotation.Configuration; class GrpcSafeActivationTest { private final ApplicationContextRunner contextRunner = - new ApplicationContextRunner().withUserConfiguration(GrpcServerConfig.class); + new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(GrpcServerConfig.class)); @Test - void defaultsKeepTheTransportAndReflectionDisabled() { - GrpcServerProperties properties = new GrpcServerProperties(); + void defaultsTurnTheTransportOnAndKeepReflectionAndPlaintextOff() { + GrpcServerSettings properties = new GrpcServerSettings(); - assertThat(properties.isEnabled()).isFalse(); + assertThat(properties.isEnabled()).isTrue(); assertThat(properties.isReflectionEnabled()).isFalse(); + assertThat(properties.isAllowInsecureLocal()).isFalse(); } @Test - void missingActivationPropertyCreatesNoGrpcRuntimeBeansOrListener() { + void theServerIsRegisteredInTheModulesOwnImportsFile() throws java.io.IOException { + try (java.io.InputStream imports = + getClass() + .getClassLoader() + .getResourceAsStream( + "META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports")) { + assertThat(imports).isNotNull(); + assertThat(new String(imports.readAllBytes(), java.nio.charset.StandardCharsets.UTF_8)) + .contains(GrpcServerConfig.class.getName()); + } + } + + @Test + void presentWithoutTheSwitchIsOnAndStillRefusesAnImplicitPlaintextListener() { contextRunner .withPropertyValues("ca-skeleton.grpc.port=0") + .run(context -> assertRootCauseContains(context.getStartupFailure(), "insecure")); + } + + @Test + void switchedOffCreatesNoGrpcRuntimeBeansOrListener() { + contextRunner + .withPropertyValues("ca-skeleton.grpc.enabled=false", "ca-skeleton.grpc.port=0") .run( context -> { - assertThat(context).doesNotHaveBean(GrpcServerProperties.class); + assertThat(context).doesNotHaveBean(GrpcServerSettings.class); assertThat(context).doesNotHaveBean(GrpcServerRunner.class); assertThat(context).doesNotHaveBean(HealthStatusManager.class); assertThat(context).doesNotHaveBean(GrpcExceptionHandlingInterceptor.class); diff --git a/src/adapter/inbound/web-advanced/CLAUDE.md b/src/adapter/inbound/web-advanced/CLAUDE.md new file mode 100644 index 00000000..538dfff0 --- /dev/null +++ b/src/adapter/inbound/web-advanced/CLAUDE.md @@ -0,0 +1,49 @@ +# adapter:inbound:web-advanced — opt-in web library + +## Registered identity + +- Module ID: `adapter-inbound-web-advanced` +- Gradle path: `:adapter:inbound:web-advanced` +- Focused test (derived from Gradle path): `./gradlew :adapter:inbound:web-advanced:test --console=plain` +- Registry SSOT: `src/config/architecture/modules.json`. + +Package root: `dev.caskeleton.adapter.inbound.web.advanced`. What it provides, the one line a +service adds and the settings are in [README.md](README.md). + +## Responsibility + +- Web library code that the servlet production path does not reach: streaming, virtual-thread + admission, JSON Patch / Merge Patch, CBOR/XML codecs, OpenAPI 3.2 generator and breaking-change + policy, URI/method policy, versioning, operation/budget/contract catalogs, security-context + bridge, idempotent response codec, route inventory. +- The three switched MVC capabilities (virtual threads, NDJSON, JSON sequence), each an + `@AutoConfiguration` listed in this leaf's `AutoConfiguration.imports` and off by default. + +## Rules + +- Not in any default composition. `app-bootstrap` and `sample-portfolio` main must not depend on it; + `app-bootstrap` takes it `testRuntimeOnly` so the whole-repository ArchUnit import reads it. +- It depends on `adapter:inbound:web` (the `core` vocabulary), never the reverse. +- No component-scannable stereotype. A consuming application may scan the adapter packages + (`sample-portfolio` scans `dev.caskeleton.adapter.inbound.web`), so a + `@Configuration`/`@Component` here would be created whatever its switch says. Switched wiring is + `@AutoConfiguration` + an imports line; imported helpers carry no stereotype + (`MvcStreamingSupportConfiguration`). +- No setting that no code reads, no gate or evidence type in `main` that only tests call — the + release gate and OpenAPI promotion report were removed for exactly that + (`docs/capability-status.md`). +- One generation per feature. Nothing here may re-implement what the production web path already + does another way: forwarded headers (`server.forward-headers-strategy`), CORS/CSRF + (`CorsSettings`/`SecurityConfig`), cache headers (`CacheControlFilter`), the JSON mapper (Boot's + `JsonMapper`), OpenAPI customization (`OpenApiContractConfig`). Those duplicates and the WebFlux + `functional` package were removed on 2026-09-25 (`docs/capability-status.md`). +- Inbound adapter rules from `adapter:inbound:web` apply: no repository access, no business rules, + no DTO leaking into `application-core`/`domain-core`. + +## Test + +```bash +cd src +./gradlew :adapter:inbound:web-advanced:check --console=plain +./gradlew :adapter:inbound:web-advanced:webAdvancedTest --console=plain +``` diff --git a/src/adapter/inbound/web-advanced/README.md b/src/adapter/inbound/web-advanced/README.md new file mode 100644 index 00000000..483dcd00 --- /dev/null +++ b/src/adapter/inbound/web-advanced/README.md @@ -0,0 +1,69 @@ +# adapter-inbound-web-advanced + +**라이브러리 API — 서비스의 어댑터 leaf에서 `implementation`으로 받아 직접 호출; 기본 조립에 없음.** + +`adapter:inbound:web` 에 있던 코드 중 servlet 운영 경로가 닿지 않는 것만 모은 opt-in leaf 다. +`app-bootstrap`·`sample-portfolio` 는 이 leaf 에 의존하지 않는다. 패키지 루트는 +`dev.caskeleton.adapter.inbound.web.advanced` (web 과 겹치는 패키지 없음). + +## 추가할 한 줄 + +서비스의 어댑터 leaf `build.gradle`: + +```groovy +implementation project(':adapter:inbound:web-advanced') +``` + +registry(`src/config/architecture/modules.json`)의 그 leaf `allowed_dependencies` 에 +`adapter-inbound-web-advanced` 를 더한다. 서비스 코드가 타입을 직접 부르므로 `runtimeOnly` 로는 안 된다 +(AGENTS.md capability 규칙의 라이브러리형 예외). + +## 제공하는 것 + +### 설정으로 켜는 것 (자기 `AutoConfiguration.imports`, 기본 off) + +| 기능 | 켜는 설정 | 만드는 bean | +| --- | --- | --- | +| MVC virtual thread 실행기 + admission 제한 | `backend.web.advanced.mvc-virtual-threads.enabled=true`, `admission-limit`, `database-pool-size`, `outbound-bulkhead`, `admission-wait` | `applicationTaskExecutor`, `VirtualThreadAdmissionGuard`, `VirtualThreadProfile` | +| NDJSON 스트리밍 | `backend.web.advanced.ndjson.enabled=true` | `mvcNdjsonWriter` + 공유 `WebStreamPolicy`·`WebStreamRegistry`·`StreamRecordEncoder` | +| JSON text sequence (RFC 7464) | `backend.web.advanced.json-sequence.enabled=true` | `mvcJsonSequenceWriter` + 같은 공유 bean | + +virtual thread 실행기는 `TaskDecorator` bean 을 요구한다(요청 상관관계 전파). 조립 순서는 +`TaskExecutionAutoConfiguration` 앞이다. 스트리밍 두 기능은 Boot 의 `JsonMapper` bean 으로 레코드를 +쓴다(별도 mapper 없음). + +### 라이브러리 (설정 없음, 직접 호출) + +| 패키지 | 주요 타입 | +| --- | --- | +| `patch` | `JsonMergePatchApplier`, `JsonPatchApplier`, `PatchFieldAuthorization`, `JsonPointerAuthorization` | +| `codec` | `WebCborMapperFactory`, `WebXmlMapperFactory`, `RepresentationNegotiationPolicy` (백엔드 jar 는 서비스가 추가) | +| `stream`, `stream.encoding`, `stream.replay` | `WebStreamRegistry`, `WebStreamDrainCoordinator`, `StreamRecordEncoder`, `MessagingReplayBridge` | +| `openapi` | `WebOpenApi32Generator`, `WebOpenApiBreakingPolicy` | +| `http` | `WebUriPolicy`, `WebMethodPolicy` | +| `versioning` | `PathApiVersionResolver`, `ApiDeprecationPolicy` | +| `operation`, `budget`, `contract` | `InMemoryWebOperationCatalog`, `WebRequestBudget`, `WebWireTypeManifest` | +| `security` | `WebSecurityContextBridge` (인증 결과 → `ActorContext`/`TenantContext`, 요청 입력의 tenant 거부) | +| `idempotency` | `JsonIdempotentResponseCodec` | +| `admin.route` | `WebRouteInventory` | + +## env 키 + +없다. 위 세 설정은 서비스가 자기 `application.yml` 에 둔다. 이 leaf 는 env key registry 에 키를 +추가하지 않는다. + +## 테스트 + +```bash +cd src +./gradlew :adapter:inbound:web-advanced:check # 컴파일·테스트·포맷·스타일 +./gradlew :adapter:inbound:web-advanced:webAdvancedTest # @Tag("web-advanced") 묶음, 0건이면 실패 +``` + +지원 표와 거부 규칙은 `docs/web/advanced-capabilities.md`. + +## 없는 것 + +운영 web 경로가 이미 다른 방식으로 하는 기능(forwarded header, CORS/CSRF, cache header, JSON mapper, +OpenAPI customizer)과 WebFlux `functional` 은 2026-09-25 에 지웠다. 무엇을 대신 쓰는지는 +`docs/web/advanced-capabilities.md` 의 "Removed on 2026-09-25", 복구 경로는 `docs/capability-status.md`. diff --git a/src/adapter/inbound/web-advanced/build.gradle b/src/adapter/inbound/web-advanced/build.gradle new file mode 100644 index 00000000..a6f42767 --- /dev/null +++ b/src/adapter/inbound/web-advanced/build.gradle @@ -0,0 +1,40 @@ +plugins { + id 'ca.spring-library' + id 'ca.spring-config' +} + +// Opt-in web library. The packages the servlet production path never reaches: streaming, virtual +// thread admission, JSON Patch, CBOR/XML codecs, OpenAPI 3.2, versioning, operation/budget/contract +// catalogs. They were inside `adapter:inbound:web`, which every service ships, so every service +// carried them. +// +// Not in the default composition. A service that wants one of them takes this leaf as +// `implementation` in its own adapter leaf and calls the types directly; the three switched MVC +// capabilities publish their own AutoConfiguration.imports and stay off until their property is set. +// +// Package root `dev.caskeleton.adapter.inbound.web.advanced` — its own package, the same way +// `web-fileserver` owns `web.fileserver`, so no package is split across two jars. +dependencies { + implementation project(':adapter:inbound:web') + implementation project(':application-core') + implementation project(':shared-contract') + implementation 'org.springframework.boot:spring-boot-starter-web' + implementation 'org.springframework.boot:spring-boot-starter-validation' + implementation libs.springdoc.openapi.starter.webmvc.api + // Compile-only on purpose: on the runtime classpath Boot registers an XML/CBOR mapper and an XML + // message converter for every request. The deployment that uses a codec adds the backend itself; + // `WebRepresentation.available()` reports its absence. + compileOnly 'tools.jackson.dataformat:jackson-dataformat-cbor' + compileOnly 'tools.jackson.dataformat:jackson-dataformat-xml' + testImplementation 'tools.jackson.dataformat:jackson-dataformat-cbor' + testImplementation 'tools.jackson.dataformat:jackson-dataformat-xml' +} + +strictTestLanes { + // Selects the tagged tests `test` already runs, and fails closed when the tag selects nothing. + lane('webAdvancedTest') { + tag = 'web-advanced' + description = 'Runs every web Advanced capability contract.' + jvmArgs '-Duser.timezone=UTC' + } +} diff --git a/src/adapter/inbound/web-advanced/gradle.lockfile b/src/adapter/inbound/web-advanced/gradle.lockfile new file mode 100644 index 00000000..b5df12b3 --- /dev/null +++ b/src/adapter/inbound/web-advanced/gradle.lockfile @@ -0,0 +1,185 @@ +# 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. +biz.aQute.bnd:biz.aQute.bnd.annotation:7.1.0=compileClasspath,testCompileClasspath +ch.qos.logback:logback-classic:1.5.38=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +ch.qos.logback:logback-core:1.5.38=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +com.fasterxml.jackson.core:jackson-annotations:2.21=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +com.fasterxml.jackson.core:jackson-core:2.21.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +com.fasterxml.jackson.core:jackson-databind:2.21.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:2.21.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.21.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +com.fasterxml.jackson:jackson-bom:2.21.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +com.fasterxml.woodstox:woodstox-core:7.1.1=compileClasspath,testCompileClasspath,testRuntimeClasspath +com.fasterxml:classmate:1.7.3=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,testAnnotationProcessor +com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,testAnnotationProcessor +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.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_annotations:2.38.0=compileClasspath,testCompileClasspath +com.google.errorprone:error_prone_annotations:2.41.0=spotbugs +com.google.errorprone:error_prone_annotations:2.47.0=checkstyle +com.google.errorprone:error_prone_annotations:2.49.0=annotationProcessor,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.5.0-jre=annotationProcessor,testAnnotationProcessor +com.google.guava:guava:33.6.0-jre=checkstyle +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.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins +com.jayway.jsonpath:json-path:2.10.0=testCompileClasspath,testRuntimeClasspath +com.nimbusds:nimbus-jose-jwt:10.4=runtimeClasspath,testRuntimeClasspath +com.puppycrawl.tools:checkstyle:13.5.0=checkstyle +com.vaadin.external.google:android-json:0.0.20131108.vaadin1=testCompileClasspath,testRuntimeClasspath +commons-beanutils:commons-beanutils:1.11.0=checkstyle +commons-collections:commons-collections:3.2.2=checkstyle +commons-io:commons-io:2.21.0=spotbugs +commons-logging:commons-logging:1.3.6=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +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 +io.micrometer:micrometer-commons:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +io.micrometer:micrometer-observation:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +io.swagger.core.v3:swagger-annotations-jakarta:2.2.38=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +io.swagger.core.v3:swagger-core-jakarta:2.2.38=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +io.swagger.core.v3:swagger-models-jakarta:2.2.38=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +jakarta.activation:jakarta.activation-api:2.1.4=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +jakarta.annotation:jakarta.annotation-api:3.0.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +jakarta.validation:jakarta.validation-api:3.1.1=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +jakarta.xml.bind:jakarta.xml.bind-api:4.0.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +javax.inject:javax.inject:1=annotationProcessor,testAnnotationProcessor +jaxen:jaxen:2.0.6=spotbugs +net.bytebuddy:byte-buddy-agent:1.17.8=testCompileClasspath,testRuntimeClasspath +net.bytebuddy:byte-buddy:1.17.8=testCompileClasspath,testRuntimeClasspath +net.minidev:accessors-smart:2.6.0=testCompileClasspath,testRuntimeClasspath +net.minidev:json-smart:2.6.0=testCompileClasspath,testRuntimeClasspath +net.sf.saxon:Saxon-HE:12.9=checkstyle,spotbugs +org.antlr:antlr4-runtime:4.13.2=checkstyle +org.apache.bcel:bcel:6.12.0=spotbugs +org.apache.commons:commons-lang3:3.20.0=checkstyle,compileClasspath,runtimeClasspath,spotbugs,testCompileClasspath,testRuntimeClasspath +org.apache.commons:commons-text:1.15.0=spotbugs +org.apache.commons:commons-text:1.3=checkstyle +org.apache.httpcomponents:httpclient:4.5.13=checkstyle +org.apache.httpcomponents:httpcore:4.4.16=checkstyle +org.apache.logging.log4j:log4j-api:2.25.5=compileClasspath,runtimeClasspath,spotbugs,testCompileClasspath,testRuntimeClasspath +org.apache.logging.log4j:log4j-core:2.25.5=spotbugs +org.apache.logging.log4j:log4j-to-slf4j:2.25.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.apache.maven.doxia:doxia-core:1.12.0=checkstyle +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.tomcat.embed:tomcat-embed-core:11.0.24=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.apache.tomcat.embed:tomcat-embed-el:11.0.24=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.apache.tomcat.embed:tomcat-embed-websocket:11.0.24=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.apache.xbean:xbean-reflect:3.7=checkstyle +org.apiguardian:apiguardian-api:1.1.2=testCompileClasspath +org.assertj:assertj-core:3.27.7=testCompileClasspath,testRuntimeClasspath +org.awaitility:awaitility:4.3.0=testCompileClasspath,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.3.0=checkstyle +org.codehaus.woodstox:stax2-api:4.2.2=compileClasspath,testCompileClasspath,testRuntimeClasspath +org.dom4j:dom4j:2.2.0=spotbugs +org.hamcrest:hamcrest:3.0=testCompileClasspath,testRuntimeClasspath +org.hibernate.validator:hibernate-validator:9.0.1.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.javassist:javassist:3.28.0-GA=checkstyle +org.jboss.logging:jboss-logging:3.6.3.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,compileClasspath,runtimeClasspath,testAnnotationProcessor,testCompileClasspath,testRuntimeClasspath +org.junit.jupiter:junit-jupiter-api:6.0.3=testCompileClasspath,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-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.1.0=spotbugs +org.mockito:mockito-core:5.20.0=mockitoAgent,testCompileClasspath,testRuntimeClasspath +org.mockito:mockito-junit-jupiter:5.20.0=testCompileClasspath,testRuntimeClasspath +org.objenesis:objenesis:3.3=testRuntimeClasspath +org.openapitools:jackson-databind-nullable:0.2.6=runtimeClasspath,testRuntimeClasspath +org.opentest4j:opentest4j:1.3.0=testCompileClasspath,testRuntimeClasspath +org.osgi:org.osgi.annotation.bundle:2.0.0=compileClasspath,testCompileClasspath +org.osgi:org.osgi.annotation.versioning:1.1.2=compileClasspath,testCompileClasspath +org.osgi:org.osgi.resource:1.0.0=compileClasspath,testCompileClasspath +org.osgi:org.osgi.service.serviceloader:1.0.0=compileClasspath,testCompileClasspath +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.ow2.asm:asm:9.7.1=testCompileClasspath,testRuntimeClasspath +org.pcollections:pcollections:4.0.1=annotationProcessor,testAnnotationProcessor +org.reflections:reflections:0.10.2=checkstyle +org.skyscreamer:jsonassert:1.5.3=testCompileClasspath,testRuntimeClasspath +org.slf4j:jul-to-slf4j:2.0.18=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.slf4j:slf4j-api:2.0.18=compileClasspath,runtimeClasspath,spotbugs,spotbugsSlf4j,testCompileClasspath,testRuntimeClasspath +org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j +org.slf4j:slf4j-simple:2.0.18=checkstyle +org.springdoc:springdoc-openapi-starter-common:3.0.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springdoc:springdoc-openapi-starter-webmvc-api:3.0.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-autoconfigure:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-configuration-processor:4.0.8=annotationProcessor +org.springframework.boot:spring-boot-http-converter:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-jackson:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-resttestclient:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-security-oauth2-resource-server:4.0.8=runtimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-security:4.0.8=runtimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-servlet:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-jackson-test:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-jackson:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-logging:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-oauth2-resource-server:4.0.8=runtimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-security:4.0.8=runtimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-test:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-tomcat-runtime:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-tomcat:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-validation:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-web:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-webmvc-test:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-webmvc:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-test-autoconfigure:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-test:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-tomcat:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-validation:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-web-server:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-webmvc-test:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-webmvc:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.security:spring-security-config:7.0.7=runtimeClasspath,testRuntimeClasspath +org.springframework.security:spring-security-core:7.0.7=runtimeClasspath,testRuntimeClasspath +org.springframework.security:spring-security-crypto:7.0.7=runtimeClasspath,testRuntimeClasspath +org.springframework.security:spring-security-oauth2-core:7.0.7=runtimeClasspath,testRuntimeClasspath +org.springframework.security:spring-security-oauth2-jose:7.0.7=runtimeClasspath,testRuntimeClasspath +org.springframework.security:spring-security-oauth2-resource-server:7.0.7=runtimeClasspath,testRuntimeClasspath +org.springframework.security:spring-security-web:7.0.7=runtimeClasspath,testRuntimeClasspath +org.springframework.session:spring-session-core:4.0.5=runtimeClasspath,testRuntimeClasspath +org.springframework:spring-aop:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-beans:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-context:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-core:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-expression:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-test:7.0.9=testCompileClasspath,testRuntimeClasspath +org.springframework:spring-web:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-webmvc:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.xmlresolver:xmlresolver:5.3.3=checkstyle,spotbugs +org.xmlunit:xmlunit-core:2.10.4=testCompileClasspath,testRuntimeClasspath +org.yaml:snakeyaml:2.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +tools.jackson.core:jackson-core:3.1.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +tools.jackson.core:jackson-databind:3.1.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +tools.jackson.dataformat:jackson-dataformat-cbor:3.1.5=compileClasspath,testCompileClasspath,testRuntimeClasspath +tools.jackson.dataformat:jackson-dataformat-xml:3.1.5=compileClasspath,testCompileClasspath,testRuntimeClasspath +tools.jackson:jackson-bom:3.1.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +empty= diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/admin/route/RouteInventoryMismatchException.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/admin/route/RouteInventoryMismatchException.java similarity index 90% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/admin/route/RouteInventoryMismatchException.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/admin/route/RouteInventoryMismatchException.java index 669018e7..7f3d96e0 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/admin/route/RouteInventoryMismatchException.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/admin/route/RouteInventoryMismatchException.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.inbound.web.admin.route; +package dev.caskeleton.adapter.inbound.web.advanced.admin.route; /** * The routes this deployment actually serves are not the routes it declared. diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/admin/route/WebRouteContract.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/admin/route/WebRouteContract.java similarity index 92% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/admin/route/WebRouteContract.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/admin/route/WebRouteContract.java index da2bb43f..d2e41686 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/admin/route/WebRouteContract.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/admin/route/WebRouteContract.java @@ -1,9 +1,9 @@ -package dev.caskeleton.adapter.inbound.web.admin.route; +package dev.caskeleton.adapter.inbound.web.advanced.admin.route; +import dev.caskeleton.adapter.inbound.web.advanced.core.WebRouteId; +import dev.caskeleton.adapter.inbound.web.advanced.operation.HttpMethodSemantic; import dev.caskeleton.adapter.inbound.web.core.ApiMajorVersion; import dev.caskeleton.adapter.inbound.web.core.WebOperationName; -import dev.caskeleton.adapter.inbound.web.core.WebRouteId; -import dev.caskeleton.adapter.inbound.web.operation.HttpMethodSemantic; import java.time.Instant; import java.util.List; import java.util.Objects; diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/admin/route/WebRouteInventory.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/admin/route/WebRouteInventory.java similarity index 96% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/admin/route/WebRouteInventory.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/admin/route/WebRouteInventory.java index 84f36600..cba9fa2e 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/admin/route/WebRouteInventory.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/admin/route/WebRouteInventory.java @@ -1,7 +1,7 @@ -package dev.caskeleton.adapter.inbound.web.admin.route; +package dev.caskeleton.adapter.inbound.web.advanced.admin.route; +import dev.caskeleton.adapter.inbound.web.advanced.operation.WebOperationCatalog; import dev.caskeleton.adapter.inbound.web.core.WebOperationName; -import dev.caskeleton.adapter.inbound.web.operation.WebOperationCatalog; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/budget/WebBudgetCatalog.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/budget/WebBudgetCatalog.java similarity index 97% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/budget/WebBudgetCatalog.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/budget/WebBudgetCatalog.java index 4359ce72..12bc3c55 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/budget/WebBudgetCatalog.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/budget/WebBudgetCatalog.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.inbound.web.budget; +package dev.caskeleton.adapter.inbound.web.advanced.budget; import java.util.LinkedHashMap; import java.util.Map; diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/budget/WebBudgetProfileName.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/budget/WebBudgetProfileName.java similarity index 95% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/budget/WebBudgetProfileName.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/budget/WebBudgetProfileName.java index 65a4d2c3..d27685f2 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/budget/WebBudgetProfileName.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/budget/WebBudgetProfileName.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.inbound.web.budget; +package dev.caskeleton.adapter.inbound.web.advanced.budget; import java.util.regex.Pattern; diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/budget/WebRequestBudget.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/budget/WebRequestBudget.java similarity index 99% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/budget/WebRequestBudget.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/budget/WebRequestBudget.java index 476086f9..3654f713 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/budget/WebRequestBudget.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/budget/WebRequestBudget.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.inbound.web.budget; +package dev.caskeleton.adapter.inbound.web.advanced.budget; import java.time.Duration; diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/codec/CodecBudget.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/codec/CodecBudget.java similarity index 100% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/codec/CodecBudget.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/codec/CodecBudget.java diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/codec/RepresentationNegotiationPolicy.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/codec/RepresentationNegotiationPolicy.java similarity index 100% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/codec/RepresentationNegotiationPolicy.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/codec/RepresentationNegotiationPolicy.java diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/codec/SecureXmlInputFactory.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/codec/SecureXmlInputFactory.java similarity index 100% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/codec/SecureXmlInputFactory.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/codec/SecureXmlInputFactory.java diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/codec/WebCborMapperFactory.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/codec/WebCborMapperFactory.java similarity index 100% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/codec/WebCborMapperFactory.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/codec/WebCborMapperFactory.java diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/codec/WebRepresentation.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/codec/WebRepresentation.java similarity index 100% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/codec/WebRepresentation.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/codec/WebRepresentation.java diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/codec/WebXmlMapperFactory.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/codec/WebXmlMapperFactory.java similarity index 100% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/codec/WebXmlMapperFactory.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/codec/WebXmlMapperFactory.java diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/contract/WebEnumValue.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/contract/WebEnumValue.java similarity index 95% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/contract/WebEnumValue.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/contract/WebEnumValue.java index 87d4837e..0bbc6e9e 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/contract/WebEnumValue.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/contract/WebEnumValue.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.inbound.web.contract; +package dev.caskeleton.adapter.inbound.web.advanced.contract; import java.util.Objects; import java.util.regex.Pattern; diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/contract/WebWireType.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/contract/WebWireType.java similarity index 95% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/contract/WebWireType.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/contract/WebWireType.java index ff70b7a9..a5f1dea3 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/contract/WebWireType.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/contract/WebWireType.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.inbound.web.contract; +package dev.caskeleton.adapter.inbound.web.advanced.contract; /** * The Java types whose JSON representation the platform fixes rather than inherits. diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/contract/WebWireTypeManifest.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/contract/WebWireTypeManifest.java similarity index 98% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/contract/WebWireTypeManifest.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/contract/WebWireTypeManifest.java index 3458946b..739365e5 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/contract/WebWireTypeManifest.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/contract/WebWireTypeManifest.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.inbound.web.contract; +package dev.caskeleton.adapter.inbound.web.advanced.contract; import java.util.EnumMap; import java.util.Map; diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/contract/WireTypeRule.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/contract/WireTypeRule.java similarity index 93% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/contract/WireTypeRule.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/contract/WireTypeRule.java index 79e01fc9..f097e783 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/contract/WireTypeRule.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/contract/WireTypeRule.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.inbound.web.contract; +package dev.caskeleton.adapter.inbound.web.advanced.contract; import java.util.Objects; diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/core/WebRouteId.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/core/WebRouteId.java similarity index 94% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/core/WebRouteId.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/core/WebRouteId.java index be49ad42..1110b5df 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/core/WebRouteId.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/core/WebRouteId.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.inbound.web.core; +package dev.caskeleton.adapter.inbound.web.advanced.core; /** * The identity of a registered route. diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/CanonicalPath.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/http/CanonicalPath.java similarity index 93% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/CanonicalPath.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/http/CanonicalPath.java index a456725d..b806d6ef 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/CanonicalPath.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/http/CanonicalPath.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.inbound.web.http; +package dev.caskeleton.adapter.inbound.web.advanced.http; import java.util.Objects; diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/WebMethodPolicy.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/http/WebMethodPolicy.java similarity index 96% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/WebMethodPolicy.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/http/WebMethodPolicy.java index 996f869c..0844bd91 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/WebMethodPolicy.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/http/WebMethodPolicy.java @@ -1,6 +1,6 @@ -package dev.caskeleton.adapter.inbound.web.http; +package dev.caskeleton.adapter.inbound.web.advanced.http; -import dev.caskeleton.adapter.inbound.web.operation.HttpMethodSemantic; +import dev.caskeleton.adapter.inbound.web.advanced.operation.HttpMethodSemantic; import java.util.EnumSet; import java.util.Locale; import java.util.Optional; diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/WebUriPolicy.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/http/WebUriPolicy.java similarity index 98% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/WebUriPolicy.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/http/WebUriPolicy.java index b6adcfee..276ef7cc 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/WebUriPolicy.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/http/WebUriPolicy.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.inbound.web.http; +package dev.caskeleton.adapter.inbound.web.advanced.http; import java.util.Locale; diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/idempotency/JsonIdempotentResponseCodec.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/idempotency/JsonIdempotentResponseCodec.java similarity index 95% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/idempotency/JsonIdempotentResponseCodec.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/idempotency/JsonIdempotentResponseCodec.java index e6563e02..ddd9af35 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/idempotency/JsonIdempotentResponseCodec.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/idempotency/JsonIdempotentResponseCodec.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.inbound.web.idempotency; +package dev.caskeleton.adapter.inbound.web.advanced.idempotency; import dev.caskeleton.application.idempotency.IdempotentResponseCodec; import dev.caskeleton.shared.error.MappingException; diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcDisconnectDetector.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcDisconnectDetector.java similarity index 100% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcDisconnectDetector.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcDisconnectDetector.java diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcJsonSequenceConfiguration.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcJsonSequenceConfiguration.java similarity index 92% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcJsonSequenceConfiguration.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcJsonSequenceConfiguration.java index fb85cd1c..c4c48e26 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcJsonSequenceConfiguration.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcJsonSequenceConfiguration.java @@ -2,15 +2,15 @@ package dev.caskeleton.adapter.inbound.web.advanced.mvc; import dev.caskeleton.adapter.inbound.web.advanced.stream.encoding.StreamFraming; import dev.caskeleton.adapter.inbound.web.advanced.stream.encoding.StreamRecordEncoder; +import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; /** Wires RFC 7464 JSON text-sequence streaming independently of NDJSON. */ -@Configuration(proxyBeanMethods = false) +@AutoConfiguration @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) @ConditionalOnProperty( prefix = "backend.web.advanced.json-sequence", diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamWriter.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamWriter.java similarity index 100% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamWriter.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamWriter.java diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamingExecutorConfiguration.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamingExecutorConfiguration.java similarity index 91% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamingExecutorConfiguration.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamingExecutorConfiguration.java index 7d99248f..9994d46b 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamingExecutorConfiguration.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamingExecutorConfiguration.java @@ -2,15 +2,15 @@ package dev.caskeleton.adapter.inbound.web.advanced.mvc; import dev.caskeleton.adapter.inbound.web.advanced.stream.encoding.StreamFraming; import dev.caskeleton.adapter.inbound.web.advanced.stream.encoding.StreamRecordEncoder; +import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; /** Wires servlet-side NDJSON streaming only. */ -@Configuration(proxyBeanMethods = false) +@AutoConfiguration @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) @ConditionalOnProperty( prefix = "backend.web.advanced.ndjson", diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamingSupportConfiguration.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamingSupportConfiguration.java similarity index 59% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamingSupportConfiguration.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamingSupportConfiguration.java index b3fd78aa..a1a3de5d 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamingSupportConfiguration.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamingSupportConfiguration.java @@ -3,13 +3,17 @@ package dev.caskeleton.adapter.inbound.web.advanced.mvc; import dev.caskeleton.adapter.inbound.web.advanced.stream.WebStreamPolicy; import dev.caskeleton.adapter.inbound.web.advanced.stream.WebStreamRegistry; import dev.caskeleton.adapter.inbound.web.advanced.stream.encoding.StreamRecordEncoder; -import dev.caskeleton.adapter.inbound.web.json.WebObjectMapperFactory; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; +import tools.jackson.databind.json.JsonMapper; -/** Shared bounded streaming infrastructure imported only by a concrete streaming capability. */ -@Configuration(proxyBeanMethods = false) +/** + * Shared bounded streaming infrastructure imported only by a concrete streaming capability. + * + *

Not annotated {@code @Configuration}: {@code @Import} processes its bean methods anyway, and + * an annotated class would also be found by a consuming application's component scan and create + * these beans with every streaming switch off. + */ class MvcStreamingSupportConfiguration { @Bean @@ -24,9 +28,10 @@ class MvcStreamingSupportConfiguration { return new WebStreamRegistry(1_000); } + /** Records are written with Boot's {@code JsonMapper}, the one every other response uses. */ @Bean @ConditionalOnMissingBean - StreamRecordEncoder streamRecordEncoder(WebStreamPolicy policy) { - return new StreamRecordEncoder(WebObjectMapperFactory.standard(), policy); + StreamRecordEncoder streamRecordEncoder(WebStreamPolicy policy, JsonMapper jsonMapper) { + return new StreamRecordEncoder(jsonMapper, policy); } } diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/VirtualThreadMvcConfiguration.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/VirtualThreadMvcConfiguration.java similarity index 90% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/VirtualThreadMvcConfiguration.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/VirtualThreadMvcConfiguration.java index 9bec0eae..52a54df4 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/VirtualThreadMvcConfiguration.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/VirtualThreadMvcConfiguration.java @@ -4,12 +4,12 @@ import dev.caskeleton.adapter.inbound.web.advanced.virtualthread.VirtualThreadAd import dev.caskeleton.adapter.inbound.web.advanced.virtualthread.VirtualThreadProfile; import java.util.concurrent.Executor; import java.util.concurrent.Executors; +import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; import org.springframework.core.task.AsyncTaskExecutor; import org.springframework.core.task.TaskDecorator; import org.springframework.core.task.support.TaskExecutorAdapter; @@ -26,7 +26,10 @@ import org.springframework.core.task.support.TaskExecutorAdapter; * combination cannot be configured. This configuration then cannot produce the executor without * also producing the guard, because both are in it. */ -@Configuration(proxyBeanMethods = false) +// Before Boot's task execution auto-configuration, whose own applicationTaskExecutor backs off +// when this one exists. As a scanned @Configuration it used to win by being user configuration. +@AutoConfiguration( + beforeName = "org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration") @EnableConfigurationProperties(VirtualThreadSettings.class) @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) @ConditionalOnProperty( diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/VirtualThreadSettings.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/VirtualThreadSettings.java similarity index 100% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/VirtualThreadSettings.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/VirtualThreadSettings.java diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/openapi/OpenApiDeepCopy.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/openapi/OpenApiDeepCopy.java similarity index 100% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/openapi/OpenApiDeepCopy.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/openapi/OpenApiDeepCopy.java diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/openapi/OpenApiVersionLane.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/openapi/OpenApiVersionLane.java similarity index 100% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/openapi/OpenApiVersionLane.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/openapi/OpenApiVersionLane.java diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/openapi/WebOpenApi32Generator.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/openapi/WebOpenApi32Generator.java similarity index 96% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/openapi/WebOpenApi32Generator.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/openapi/WebOpenApi32Generator.java index ea237116..a7e702df 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/openapi/WebOpenApi32Generator.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/openapi/WebOpenApi32Generator.java @@ -18,8 +18,7 @@ import java.util.Set; * reason this class exists rather than a two-line customizer. Both documents come from the same * in-memory model, so a contributor that mutates it on the way to 3.2 changes the artifact that is * actually shipped — silently, and only in builds where the experimental lane happened to run. - * Copying is the only thing that makes the two independent; the snapshot-hash check in {@link - * OpenApi32CompatibilityReport} is what proves the copy held. + * Copying is the only thing that makes the two independent. * *

What 3.2 adds for this application is streaming description. 3.1 can say a response is {@code * text/event-stream} and cannot say what one event looks like, so a generator produces a client diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/openapi/WebOpenApiBreakingPolicy.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/openapi/WebOpenApiBreakingPolicy.java similarity index 99% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/openapi/WebOpenApiBreakingPolicy.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/openapi/WebOpenApiBreakingPolicy.java index c4357624..d54478d4 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/openapi/WebOpenApiBreakingPolicy.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/openapi/WebOpenApiBreakingPolicy.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.inbound.web.openapi; +package dev.caskeleton.adapter.inbound.web.advanced.openapi; import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.Operation; diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/openapi/WebOpenApiDiffResult.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/openapi/WebOpenApiDiffResult.java similarity index 95% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/openapi/WebOpenApiDiffResult.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/openapi/WebOpenApiDiffResult.java index 93dbfefd..31cf4a53 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/openapi/WebOpenApiDiffResult.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/openapi/WebOpenApiDiffResult.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.inbound.web.openapi; +package dev.caskeleton.adapter.inbound.web.advanced.openapi; import java.util.List; import java.util.Objects; diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operation/AdmissionProfileName.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/operation/AdmissionProfileName.java similarity index 94% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operation/AdmissionProfileName.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/operation/AdmissionProfileName.java index f333b4ea..53315092 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operation/AdmissionProfileName.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/operation/AdmissionProfileName.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.inbound.web.operation; +package dev.caskeleton.adapter.inbound.web.advanced.operation; import java.util.regex.Pattern; diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operation/AuthorizationProfileName.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/operation/AuthorizationProfileName.java similarity index 94% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operation/AuthorizationProfileName.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/operation/AuthorizationProfileName.java index 6a9b1ebf..2d3dbe95 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operation/AuthorizationProfileName.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/operation/AuthorizationProfileName.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.inbound.web.operation; +package dev.caskeleton.adapter.inbound.web.advanced.operation; import java.util.regex.Pattern; diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operation/CachePolicyName.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/operation/CachePolicyName.java similarity index 94% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operation/CachePolicyName.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/operation/CachePolicyName.java index d9715d2f..98156f04 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operation/CachePolicyName.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/operation/CachePolicyName.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.inbound.web.operation; +package dev.caskeleton.adapter.inbound.web.advanced.operation; import java.util.regex.Pattern; diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operation/HttpMethodSemantic.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/operation/HttpMethodSemantic.java similarity index 96% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operation/HttpMethodSemantic.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/operation/HttpMethodSemantic.java index 1d36292c..b4c980e3 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operation/HttpMethodSemantic.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/operation/HttpMethodSemantic.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.inbound.web.operation; +package dev.caskeleton.adapter.inbound.web.advanced.operation; /** * The HTTP method an operation is reached by, with the two properties that actually decide policy. diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operation/IdempotencyPolicy.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/operation/IdempotencyPolicy.java similarity index 91% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operation/IdempotencyPolicy.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/operation/IdempotencyPolicy.java index 3a0f6f57..77563933 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operation/IdempotencyPolicy.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/operation/IdempotencyPolicy.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.inbound.web.operation; +package dev.caskeleton.adapter.inbound.web.advanced.operation; /** * Whether an operation accepts, requires or refuses an idempotency key. diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operation/InMemoryWebOperationCatalog.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/operation/InMemoryWebOperationCatalog.java similarity index 97% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operation/InMemoryWebOperationCatalog.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/operation/InMemoryWebOperationCatalog.java index dc03e5d2..56919be2 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operation/InMemoryWebOperationCatalog.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/operation/InMemoryWebOperationCatalog.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.inbound.web.operation; +package dev.caskeleton.adapter.inbound.web.advanced.operation; import dev.caskeleton.adapter.inbound.web.core.WebOperationName; import java.util.Map; diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operation/MutationKind.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/operation/MutationKind.java similarity index 95% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operation/MutationKind.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/operation/MutationKind.java index 826c2609..16b1784d 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operation/MutationKind.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/operation/MutationKind.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.inbound.web.operation; +package dev.caskeleton.adapter.inbound.web.advanced.operation; /** * What an operation does to state, independent of the method it is reached by. diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operation/PreconditionPolicy.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/operation/PreconditionPolicy.java similarity index 92% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operation/PreconditionPolicy.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/operation/PreconditionPolicy.java index 916ad6ad..df70598a 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operation/PreconditionPolicy.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/operation/PreconditionPolicy.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.inbound.web.operation; +package dev.caskeleton.adapter.inbound.web.advanced.operation; /** * Whether an operation requires a conditional header before it will change state. diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operation/ResponseProfileName.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/operation/ResponseProfileName.java similarity index 94% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operation/ResponseProfileName.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/operation/ResponseProfileName.java index 1c17d83e..db4931db 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operation/ResponseProfileName.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/operation/ResponseProfileName.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.inbound.web.operation; +package dev.caskeleton.adapter.inbound.web.advanced.operation; import java.util.regex.Pattern; diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operation/WebOperationCatalog.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/operation/WebOperationCatalog.java similarity index 93% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operation/WebOperationCatalog.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/operation/WebOperationCatalog.java index 53572651..53f0c1cb 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operation/WebOperationCatalog.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/operation/WebOperationCatalog.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.inbound.web.operation; +package dev.caskeleton.adapter.inbound.web.advanced.operation; import dev.caskeleton.adapter.inbound.web.core.WebOperationName; diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operation/WebOperationProfile.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/operation/WebOperationProfile.java similarity index 97% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operation/WebOperationProfile.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/operation/WebOperationProfile.java index 225984be..614e4d68 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operation/WebOperationProfile.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/operation/WebOperationProfile.java @@ -1,6 +1,6 @@ -package dev.caskeleton.adapter.inbound.web.operation; +package dev.caskeleton.adapter.inbound.web.advanced.operation; -import dev.caskeleton.adapter.inbound.web.budget.WebBudgetProfileName; +import dev.caskeleton.adapter.inbound.web.advanced.budget.WebBudgetProfileName; import dev.caskeleton.adapter.inbound.web.core.WebOperationName; import java.util.Objects; diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonMergePatchApplier.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonMergePatchApplier.java similarity index 97% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonMergePatchApplier.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonMergePatchApplier.java index 2ef9b377..ce301568 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonMergePatchApplier.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonMergePatchApplier.java @@ -26,7 +26,7 @@ public final class JsonMergePatchApplier { private final PatchFieldAuthorization authorization; /** - * @param mapper the strict mapper the rest of the leaf uses + * @param mapper the service's JSON mapper (Boot's {@code JsonMapper} bean) * @param authorization which fields may be modified */ public JsonMergePatchApplier(ObjectMapper mapper, PatchFieldAuthorization authorization) { diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonMergePatchDocument.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonMergePatchDocument.java similarity index 97% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonMergePatchDocument.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonMergePatchDocument.java index 33388538..204ee75f 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonMergePatchDocument.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonMergePatchDocument.java @@ -38,7 +38,7 @@ public record JsonMergePatchDocument(ObjectNode root) { /** * Parse a body. * - * @param mapper the strict mapper + * @param mapper the service's JSON mapper (Boot's {@code JsonMapper} bean) * @param body the request body * @throws IllegalArgumentException if the body is not a JSON object */ diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchApplier.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchApplier.java similarity index 98% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchApplier.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchApplier.java index fb2af9a0..04a2e8ba 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchApplier.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchApplier.java @@ -30,7 +30,7 @@ public final class JsonPatchApplier { private final JsonPointerAuthorization authorization; /** - * @param mapper the strict mapper the rest of the leaf uses + * @param mapper the service's JSON mapper (Boot's {@code JsonMapper} bean) * @param authorization which pointers may be modified */ public JsonPatchApplier(ObjectMapper mapper, JsonPointerAuthorization authorization) { diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchDocument.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchDocument.java similarity index 97% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchDocument.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchDocument.java index 9a35af69..b461b6c0 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchDocument.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchDocument.java @@ -41,7 +41,7 @@ public record JsonPatchDocument(List operations) { /** * Parse a body. * - * @param mapper the strict mapper + * @param mapper the service's JSON mapper (Boot's {@code JsonMapper} bean) * @param body the request body */ public static JsonPatchDocument parse(ObjectMapper mapper, byte[] body) { diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchOperation.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchOperation.java similarity index 100% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchOperation.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchOperation.java diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchOperationKind.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchOperationKind.java similarity index 100% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchOperationKind.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchOperationKind.java diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchRejectedException.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchRejectedException.java similarity index 100% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchRejectedException.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchRejectedException.java diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchTestFailedException.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchTestFailedException.java similarity index 100% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchTestFailedException.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchTestFailedException.java diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPointerAuthorization.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPointerAuthorization.java similarity index 100% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPointerAuthorization.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPointerAuthorization.java diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/PatchAuthorizationException.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/PatchAuthorizationException.java similarity index 100% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/PatchAuthorizationException.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/PatchAuthorizationException.java diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/PatchFieldAuthorization.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/PatchFieldAuthorization.java similarity index 100% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/PatchFieldAuthorization.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/PatchFieldAuthorization.java diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/PatchMediaType.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/PatchMediaType.java similarity index 100% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/PatchMediaType.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/PatchMediaType.java diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/PatchResult.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/PatchResult.java similarity index 100% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/PatchResult.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/patch/PatchResult.java diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/security/AuthenticationView.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/security/AuthenticationView.java similarity index 97% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/security/AuthenticationView.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/security/AuthenticationView.java index 8f074d09..95c09730 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/security/AuthenticationView.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/security/AuthenticationView.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.inbound.web.security; +package dev.caskeleton.adapter.inbound.web.advanced.security; import java.util.Objects; import java.util.Optional; diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/security/SecurityIdentity.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/security/SecurityIdentity.java similarity index 92% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/security/SecurityIdentity.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/security/SecurityIdentity.java index ebacf4fc..e870ee14 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/security/SecurityIdentity.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/security/SecurityIdentity.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.inbound.web.security; +package dev.caskeleton.adapter.inbound.web.advanced.security; import dev.caskeleton.adapter.inbound.web.core.ActorContext; import dev.caskeleton.adapter.inbound.web.core.TenantContext; diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/security/UntrustedTenantInputException.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/security/UntrustedTenantInputException.java similarity index 93% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/security/UntrustedTenantInputException.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/security/UntrustedTenantInputException.java index ceb95d33..73dc786c 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/security/UntrustedTenantInputException.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/security/UntrustedTenantInputException.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.inbound.web.security; +package dev.caskeleton.adapter.inbound.web.advanced.security; /** * A tenant was proposed by request input rather than established by authentication. diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/security/WebActorContextResolver.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/security/WebActorContextResolver.java similarity index 94% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/security/WebActorContextResolver.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/security/WebActorContextResolver.java index 8bf20591..4e3e7c7a 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/security/WebActorContextResolver.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/security/WebActorContextResolver.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.inbound.web.security; +package dev.caskeleton.adapter.inbound.web.advanced.security; import dev.caskeleton.adapter.inbound.web.core.ActorContext; import java.util.Objects; diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/security/WebSecurityContextBridge.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/security/WebSecurityContextBridge.java similarity index 97% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/security/WebSecurityContextBridge.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/security/WebSecurityContextBridge.java index 6aaa56cb..bbb29312 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/security/WebSecurityContextBridge.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/security/WebSecurityContextBridge.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.inbound.web.security; +package dev.caskeleton.adapter.inbound.web.advanced.security; import java.util.Map; import java.util.Objects; diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/security/WebTenantContextResolver.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/security/WebTenantContextResolver.java similarity index 96% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/security/WebTenantContextResolver.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/security/WebTenantContextResolver.java index 8cf47c6f..14a83b1b 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/security/WebTenantContextResolver.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/security/WebTenantContextResolver.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.inbound.web.security; +package dev.caskeleton.adapter.inbound.web.advanced.security; import dev.caskeleton.adapter.inbound.web.core.TenantContext; import java.util.Locale; diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/StreamId.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/StreamId.java similarity index 100% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/StreamId.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/StreamId.java diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/StreamSequence.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/StreamSequence.java similarity index 100% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/StreamSequence.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/StreamSequence.java diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamDrainCoordinator.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamDrainCoordinator.java similarity index 100% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamDrainCoordinator.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamDrainCoordinator.java diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamErrorPolicy.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamErrorPolicy.java similarity index 100% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamErrorPolicy.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamErrorPolicy.java diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamEvidence.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamEvidence.java similarity index 100% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamEvidence.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamEvidence.java diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamPolicy.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamPolicy.java similarity index 100% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamPolicy.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamPolicy.java diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamRegistry.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamRegistry.java similarity index 100% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamRegistry.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamRegistry.java diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamSession.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamSession.java similarity index 100% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamSession.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamSession.java diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamTermination.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamTermination.java similarity index 100% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamTermination.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamTermination.java diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/encoding/JsonSequenceFraming.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/encoding/JsonSequenceFraming.java similarity index 100% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/encoding/JsonSequenceFraming.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/encoding/JsonSequenceFraming.java diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/encoding/NdjsonFraming.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/encoding/NdjsonFraming.java similarity index 100% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/encoding/NdjsonFraming.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/encoding/NdjsonFraming.java diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/encoding/NdjsonRecord.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/encoding/NdjsonRecord.java similarity index 77% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/encoding/NdjsonRecord.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/encoding/NdjsonRecord.java index a2f9ed41..72700719 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/encoding/NdjsonRecord.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/encoding/NdjsonRecord.java @@ -5,11 +5,9 @@ import java.util.Objects; /** * One line of an {@code application/x-ndjson} response. * - *

Separate from {@code WebStreamEnvelope} rather than reusing it, because the two answer - * different questions. The envelope is what the platform knows about an item; this is what goes on - * the wire, and it is flat and small on purpose — an NDJSON consumer parses one line at a time with - * no framing beyond the newline, so anything nested here is something a client has to unwrap before - * it can tell an item from a terminal record. + *

This is what goes on the wire, and it is flat and small on purpose — an NDJSON consumer parses + * one line at a time with no framing beyond the newline, so anything nested here is something a + * client has to unwrap before it can tell an item from a terminal record. * * @param the item type */ diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/encoding/StreamFraming.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/encoding/StreamFraming.java similarity index 100% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/encoding/StreamFraming.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/encoding/StreamFraming.java diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/encoding/StreamItemTooLargeException.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/encoding/StreamItemTooLargeException.java similarity index 100% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/encoding/StreamItemTooLargeException.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/encoding/StreamItemTooLargeException.java diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/encoding/StreamMediaType.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/encoding/StreamMediaType.java similarity index 100% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/encoding/StreamMediaType.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/encoding/StreamMediaType.java diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/encoding/StreamRecordEncoder.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/encoding/StreamRecordEncoder.java similarity index 90% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/encoding/StreamRecordEncoder.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/encoding/StreamRecordEncoder.java index 0500d947..449d4b78 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/encoding/StreamRecordEncoder.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/encoding/StreamRecordEncoder.java @@ -14,8 +14,7 @@ import tools.jackson.databind.ObjectMapper; * the check that stops one oversized item from being the whole response. * *

Compactness is not a preference here. NDJSON's record boundary is the newline, so a - * pretty-printed value breaks every record after it — {@link NdjsonFraming} refuses one, and this - * is where the mapper that would produce it is pinned. + * pretty-printed value breaks every record after it, so {@link NdjsonFraming} refuses one. */ public final class StreamRecordEncoder { @@ -23,7 +22,7 @@ public final class StreamRecordEncoder { private final WebStreamPolicy policy; /** - * @param mapper the strict mapper the rest of the leaf uses, configured not to indent + * @param mapper the service's JSON mapper; it must not indent * @param policy the per-item size bound */ public StreamRecordEncoder(ObjectMapper mapper, WebStreamPolicy policy) { diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/replay/GapAndDuplicateGuard.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/replay/GapAndDuplicateGuard.java similarity index 100% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/replay/GapAndDuplicateGuard.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/replay/GapAndDuplicateGuard.java diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/replay/MessagingReplayBridge.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/replay/MessagingReplayBridge.java similarity index 100% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/replay/MessagingReplayBridge.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/replay/MessagingReplayBridge.java diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/replay/ReplayCursorExpiredException.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/replay/ReplayCursorExpiredException.java similarity index 100% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/replay/ReplayCursorExpiredException.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/replay/ReplayCursorExpiredException.java diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/replay/WebStreamReplaySource.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/replay/WebStreamReplaySource.java similarity index 100% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/replay/WebStreamReplaySource.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/replay/WebStreamReplaySource.java diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/replay/WebStreamResumeCursor.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/replay/WebStreamResumeCursor.java similarity index 100% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/replay/WebStreamResumeCursor.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/replay/WebStreamResumeCursor.java diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/versioning/ApiDeprecationPolicy.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/versioning/ApiDeprecationPolicy.java similarity index 97% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/versioning/ApiDeprecationPolicy.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/versioning/ApiDeprecationPolicy.java index 4a54c62d..9808b86d 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/versioning/ApiDeprecationPolicy.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/versioning/ApiDeprecationPolicy.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.inbound.web.versioning; +package dev.caskeleton.adapter.inbound.web.advanced.versioning; import java.time.Instant; import java.util.Map; diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/versioning/ApiVersionCatalog.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/versioning/ApiVersionCatalog.java similarity index 97% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/versioning/ApiVersionCatalog.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/versioning/ApiVersionCatalog.java index db139737..3022f100 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/versioning/ApiVersionCatalog.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/versioning/ApiVersionCatalog.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.inbound.web.versioning; +package dev.caskeleton.adapter.inbound.web.advanced.versioning; import dev.caskeleton.adapter.inbound.web.core.ApiMajorVersion; import java.util.Comparator; diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/versioning/DeprecatedRoute.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/versioning/DeprecatedRoute.java similarity index 96% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/versioning/DeprecatedRoute.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/versioning/DeprecatedRoute.java index 161119cf..2a9bd7b9 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/versioning/DeprecatedRoute.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/versioning/DeprecatedRoute.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.inbound.web.versioning; +package dev.caskeleton.adapter.inbound.web.advanced.versioning; import java.net.URI; import java.time.Instant; diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/versioning/PathApiVersionResolver.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/versioning/PathApiVersionResolver.java similarity index 96% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/versioning/PathApiVersionResolver.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/versioning/PathApiVersionResolver.java index b4422262..64169882 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/versioning/PathApiVersionResolver.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/versioning/PathApiVersionResolver.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.inbound.web.versioning; +package dev.caskeleton.adapter.inbound.web.advanced.versioning; import dev.caskeleton.adapter.inbound.web.core.ApiMajorVersion; import java.util.Objects; diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/versioning/SunsetViolationException.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/versioning/SunsetViolationException.java similarity index 89% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/versioning/SunsetViolationException.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/versioning/SunsetViolationException.java index 582bc80f..08165370 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/versioning/SunsetViolationException.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/versioning/SunsetViolationException.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.inbound.web.versioning; +package dev.caskeleton.adapter.inbound.web.advanced.versioning; /** * A deprecation was declared in a way a client cannot act on. diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/versioning/UnsupportedApiVersionException.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/versioning/UnsupportedApiVersionException.java similarity index 95% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/versioning/UnsupportedApiVersionException.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/versioning/UnsupportedApiVersionException.java index 9dd5f14e..203aec51 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/versioning/UnsupportedApiVersionException.java +++ b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/versioning/UnsupportedApiVersionException.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.inbound.web.versioning; +package dev.caskeleton.adapter.inbound.web.advanced.versioning; /** * A request addressed a major version this deployment does not serve. diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/virtualthread/AdmissionRefusedException.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/virtualthread/AdmissionRefusedException.java similarity index 100% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/virtualthread/AdmissionRefusedException.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/virtualthread/AdmissionRefusedException.java diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/virtualthread/VirtualThreadAdmissionGuard.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/virtualthread/VirtualThreadAdmissionGuard.java similarity index 100% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/virtualthread/VirtualThreadAdmissionGuard.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/virtualthread/VirtualThreadAdmissionGuard.java diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/virtualthread/VirtualThreadProfile.java b/src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/virtualthread/VirtualThreadProfile.java similarity index 100% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/virtualthread/VirtualThreadProfile.java rename to src/adapter/inbound/web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/virtualthread/VirtualThreadProfile.java diff --git a/src/adapter/inbound/web-advanced/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/src/adapter/inbound/web-advanced/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports new file mode 100644 index 00000000..6e48eb88 --- /dev/null +++ b/src/adapter/inbound/web-advanced/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports @@ -0,0 +1,3 @@ +dev.caskeleton.adapter.inbound.web.advanced.mvc.MvcStreamingExecutorConfiguration +dev.caskeleton.adapter.inbound.web.advanced.mvc.MvcJsonSequenceConfiguration +dev.caskeleton.adapter.inbound.web.advanced.mvc.VirtualThreadMvcConfiguration diff --git a/src/adapter/inbound/web/src/main/resources/META-INF/web/wire-type-manifest.yaml b/src/adapter/inbound/web-advanced/src/main/resources/META-INF/web/wire-type-manifest.yaml similarity index 100% rename from src/adapter/inbound/web/src/main/resources/META-INF/web/wire-type-manifest.yaml rename to src/adapter/inbound/web-advanced/src/main/resources/META-INF/web/wire-type-manifest.yaml diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/admin/route/WebRouteInventoryTest.java b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/admin/route/WebRouteInventoryTest.java similarity index 93% rename from src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/admin/route/WebRouteInventoryTest.java rename to src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/admin/route/WebRouteInventoryTest.java index d5bad59c..e2f77916 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/admin/route/WebRouteInventoryTest.java +++ b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/admin/route/WebRouteInventoryTest.java @@ -1,15 +1,15 @@ -package dev.caskeleton.adapter.inbound.web.admin.route; +package dev.caskeleton.adapter.inbound.web.advanced.admin.route; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import dev.caskeleton.adapter.inbound.web.advanced.core.WebRouteId; +import dev.caskeleton.adapter.inbound.web.advanced.operation.HttpMethodSemantic; +import dev.caskeleton.adapter.inbound.web.advanced.operation.InMemoryWebOperationCatalog; +import dev.caskeleton.adapter.inbound.web.advanced.operation.WebOperationProfile; import dev.caskeleton.adapter.inbound.web.core.ApiMajorVersion; import dev.caskeleton.adapter.inbound.web.core.WebOperationName; -import dev.caskeleton.adapter.inbound.web.core.WebRouteId; -import dev.caskeleton.adapter.inbound.web.operation.HttpMethodSemantic; -import dev.caskeleton.adapter.inbound.web.operation.InMemoryWebOperationCatalog; -import dev.caskeleton.adapter.inbound.web.operation.WebOperationProfile; import java.time.Instant; import java.util.List; import java.util.Optional; diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/budget/WebRequestBudgetTest.java b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/budget/WebRequestBudgetTest.java similarity index 98% rename from src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/budget/WebRequestBudgetTest.java rename to src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/budget/WebRequestBudgetTest.java index 25f51374..e900e522 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/budget/WebRequestBudgetTest.java +++ b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/budget/WebRequestBudgetTest.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.inbound.web.budget; +package dev.caskeleton.adapter.inbound.web.advanced.budget; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/codec/RepresentationBackendScopeTest.java b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/codec/RepresentationBackendScopeTest.java similarity index 89% rename from src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/codec/RepresentationBackendScopeTest.java rename to src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/codec/RepresentationBackendScopeTest.java index c01bacbd..4fee3b9e 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/codec/RepresentationBackendScopeTest.java +++ b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/codec/RepresentationBackendScopeTest.java @@ -2,7 +2,6 @@ package dev.caskeleton.adapter.inbound.web.advanced.codec; import static org.assertj.core.api.Assertions.assertThat; -import dev.caskeleton.adapter.inbound.web.moduleboundary.WebBuildModel; import java.io.IOException; import java.io.UncheckedIOException; import java.nio.file.Files; @@ -38,9 +37,17 @@ class RepresentationBackendScopeTest { WebRepresentation.XML, "tools.jackson.dataformat:jackson-dataformat-xml"); private static String buildFile() { - Path leaf = WebBuildModel.mainSourceRoot().getParent().getParent().getParent(); - Path file = leaf.resolve("build.gradle"); - if (!Files.isRegularFile(file)) { + // Gradle runs a leaf's tests from the leaf directory; walking up keeps an IDE run working too. + Path file = null; + for (Path directory = Path.of("").toAbsolutePath(); + directory != null && file == null; + directory = directory.getParent()) { + if (Files.isDirectory( + directory.resolve("src/main/java/dev/caskeleton/adapter/inbound/web"))) { + file = directory.resolve("build.gradle"); + } + } + if (file == null || !Files.isRegularFile(file)) { throw new IllegalStateException( "cannot locate this leaf's build.gradle at " + file + "; the scope rule checks nothing"); } diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/codec/WebCodecMapperTest.java b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/codec/WebCodecMapperTest.java similarity index 100% rename from src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/codec/WebCodecMapperTest.java rename to src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/codec/WebCodecMapperTest.java diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/codec/WebCodecSecurityTest.java b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/codec/WebCodecSecurityTest.java similarity index 100% rename from src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/codec/WebCodecSecurityTest.java rename to src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/codec/WebCodecSecurityTest.java diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/contract/WebWireTypeManifestTest.java b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/contract/WebWireTypeManifestTest.java similarity index 98% rename from src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/contract/WebWireTypeManifestTest.java rename to src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/contract/WebWireTypeManifestTest.java index 649cc3fe..5171c32c 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/contract/WebWireTypeManifestTest.java +++ b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/contract/WebWireTypeManifestTest.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.inbound.web.contract; +package dev.caskeleton.adapter.inbound.web.advanced.contract; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; diff --git a/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/core/WebRouteIdTest.java b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/core/WebRouteIdTest.java new file mode 100644 index 00000000..7dfc0e89 --- /dev/null +++ b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/core/WebRouteIdTest.java @@ -0,0 +1,22 @@ +package dev.caskeleton.adapter.inbound.web.advanced.core; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +class WebRouteIdTest { + + @Test + @DisplayName("a route id is a non-blank, bounded template") + void aRouteIdIsANonBlankBoundedTemplate() { + assertThat(new WebRouteId("GET /api/v1/orders/{orderId}").value()) + .as("the template, not a resolved URI: one route, not the thousand URIs it serves") + .isEqualTo("GET /api/v1/orders/{orderId}"); + assertThatThrownBy(() -> new WebRouteId(" ")).isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new WebRouteId(null)).isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new WebRouteId("x".repeat(257))) + .isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/http/WebUriPolicyTest.java b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/http/WebUriPolicyTest.java similarity index 97% rename from src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/http/WebUriPolicyTest.java rename to src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/http/WebUriPolicyTest.java index 002fe95c..307b4c93 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/http/WebUriPolicyTest.java +++ b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/http/WebUriPolicyTest.java @@ -1,10 +1,10 @@ -package dev.caskeleton.adapter.inbound.web.http; +package dev.caskeleton.adapter.inbound.web.advanced.http; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import dev.caskeleton.adapter.inbound.web.operation.HttpMethodSemantic; +import dev.caskeleton.adapter.inbound.web.advanced.operation.HttpMethodSemantic; import java.util.Set; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcAdvancedConfigurationTest.java b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcAdvancedConfigurationTest.java similarity index 95% rename from src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcAdvancedConfigurationTest.java rename to src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcAdvancedConfigurationTest.java index 12751424..d0019692 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcAdvancedConfigurationTest.java +++ b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcAdvancedConfigurationTest.java @@ -10,6 +10,8 @@ import dev.caskeleton.adapter.inbound.web.advanced.virtualthread.VirtualThreadPr import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.jackson.autoconfigure.JacksonAutoConfiguration; import org.springframework.boot.test.context.runner.WebApplicationContextRunner; import org.springframework.core.task.AsyncTaskExecutor; import org.springframework.core.task.TaskDecorator; @@ -27,6 +29,10 @@ class MvcAdvancedConfigurationTest { private final WebApplicationContextRunner runner = new WebApplicationContextRunner() + // The stream encoder writes with Boot's JsonMapper, so the real Jackson + // auto-configuration + // supplies it here rather than a hand-built mapper. + .withConfiguration(AutoConfigurations.of(JacksonAutoConfiguration.class)) // The executor bean requires one. That is the point of // EVERY_TASK_EXECUTOR_BEAN_HAS_CONTEXT_DECORATOR: an executor that can be built without a // decorator is one that silently drops request_id and trace_id on every async hop. diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamingWiringTest.java b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamingWiringTest.java similarity index 97% rename from src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamingWiringTest.java rename to src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamingWiringTest.java index a3bd77e8..c9e600d1 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamingWiringTest.java +++ b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/MvcStreamingWiringTest.java @@ -11,7 +11,6 @@ import dev.caskeleton.adapter.inbound.web.advanced.stream.encoding.NdjsonRecord; import dev.caskeleton.adapter.inbound.web.advanced.stream.encoding.StreamFraming; import dev.caskeleton.adapter.inbound.web.advanced.stream.encoding.StreamItemTooLargeException; import dev.caskeleton.adapter.inbound.web.advanced.stream.encoding.StreamRecordEncoder; -import dev.caskeleton.adapter.inbound.web.json.WebObjectMapperFactory; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; @@ -23,6 +22,7 @@ import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; +import tools.jackson.databind.json.JsonMapper; /** * The servlet-side wiring: the registry, the record writers and the disconnect classifier. @@ -38,7 +38,7 @@ class MvcStreamingWiringTest { private static final Instant NOW = Instant.parse("2026-08-25T10:00:00Z"); private static StreamRecordEncoder encoder(WebStreamPolicy policy) { - return new StreamRecordEncoder(WebObjectMapperFactory.standard(), policy); + return new StreamRecordEncoder(JsonMapper.shared(), policy); } @Test diff --git a/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/WebAdvancedAutoConfigurationRegistrationTest.java b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/WebAdvancedAutoConfigurationRegistrationTest.java new file mode 100644 index 00000000..22bef4b1 --- /dev/null +++ b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/mvc/WebAdvancedAutoConfigurationRegistrationTest.java @@ -0,0 +1,52 @@ +package dev.caskeleton.adapter.inbound.web.advanced.mvc; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.boot.autoconfigure.AutoConfiguration; +import org.springframework.core.annotation.AnnotatedElementUtils; + +/** + * The switched capabilities reach an application through this leaf's own registration file. + * + *

Read from the source tree, not the classpath: the classpath holds every leaf's registration + * file, and this contract is about the one this jar ships. + */ +class WebAdvancedAutoConfigurationRegistrationTest { + + private static final Path IMPORTS = + Path.of( + "src/main/resources/META-INF/spring/" + + "org.springframework.boot.autoconfigure.AutoConfiguration.imports"); + + @Test + @DisplayName("the leaf registers exactly its three switched auto-configurations") + void registersExactlyTheSwitchedAutoConfigurations() throws IOException { + // when + List registered = + Files.readAllLines(IMPORTS, StandardCharsets.UTF_8).stream() + .map(String::strip) + .filter(line -> !line.isEmpty() && !line.startsWith("#")) + .toList(); + + // then + assertThat(registered) + .containsExactlyInAnyOrder( + MvcStreamingExecutorConfiguration.class.getName(), + MvcJsonSequenceConfiguration.class.getName(), + VirtualThreadMvcConfiguration.class.getName()) + .allSatisfy( + name -> + assertThat( + AnnotatedElementUtils.hasAnnotation( + Class.forName(name), AutoConfiguration.class)) + .as("%s is registered but not annotated @AutoConfiguration", name) + .isTrue()); + } +} diff --git a/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/openapi/OpenApiVersionLaneTest.java b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/openapi/OpenApiVersionLaneTest.java new file mode 100644 index 00000000..9232b1b8 --- /dev/null +++ b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/openapi/OpenApiVersionLaneTest.java @@ -0,0 +1,20 @@ +package dev.caskeleton.adapter.inbound.web.advanced.openapi; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +@Tag("web-advanced") +class OpenApiVersionLaneTest { + + @Test + @DisplayName("3.1 remains the release artifact") + void stableLaneIsTheReleaseArtifact() { + assertThat(OpenApiVersionLane.STABLE_3_1.releaseArtifact()).isTrue(); + assertThat(OpenApiVersionLane.STABLE_3_1.version()).isEqualTo("3.1.2"); + assertThat(OpenApiVersionLane.EXPERIMENTAL_3_2.releaseArtifact()).isFalse(); + assertThat(OpenApiVersionLane.EXPERIMENTAL_3_2.version()).isEqualTo("3.2.0"); + } +} diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/openapi/WebOpenApi32GeneratorTest.java b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/openapi/WebOpenApi32GeneratorTest.java similarity index 100% rename from src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/openapi/WebOpenApi32GeneratorTest.java rename to src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/openapi/WebOpenApi32GeneratorTest.java diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/openapi/WebOpenApiReleaseGateTest.java b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/openapi/WebOpenApiBreakingPolicyTest.java similarity index 77% rename from src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/openapi/WebOpenApiReleaseGateTest.java rename to src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/openapi/WebOpenApiBreakingPolicyTest.java index a71b8972..8403dd20 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/openapi/WebOpenApiReleaseGateTest.java +++ b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/openapi/WebOpenApiBreakingPolicyTest.java @@ -1,8 +1,6 @@ -package dev.caskeleton.adapter.inbound.web.openapi; +package dev.caskeleton.adapter.inbound.web.advanced.openapi; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; import io.swagger.v3.oas.models.Components; import io.swagger.v3.oas.models.OpenAPI; @@ -23,10 +21,9 @@ import org.junit.jupiter.api.Test; * diff that treats "added" or "removed" as one category waves one of them through, so both * directions are asserted. */ -class WebOpenApiReleaseGateTest { +class WebOpenApiBreakingPolicyTest { private final WebOpenApiBreakingPolicy policy = new WebOpenApiBreakingPolicy(); - private final WebOpenApiReleaseGate gate = new WebOpenApiReleaseGate(); @Test @DisplayName("removing a response field is breaking") @@ -96,21 +93,6 @@ class WebOpenApiReleaseGateTest { .containsExactly("enum value added: Status.HELD"); } - @Test - @DisplayName("a breaking change is blocked outside a major release and allowed inside one") - void aBreakingChangeIsBlockedOutsideAMajorRelease() { - OpenAPI released = documentWith(schema("Order", List.of("id", "total"), List.of())); - OpenAPI current = documentWith(schema("Order", List.of("id"), List.of())); - - assertThatThrownBy(() -> gate.evaluate(released, current, false)) - .isInstanceOf(WebOpenApiReleaseGate.OpenApiReleaseBlockedException.class) - .hasMessageContaining("Order.total"); - assertThatCode(() -> gate.evaluate(released, current, true)) - .as( - "a gate that refuses every breaking change gets bypassed, and a bypassed gate protects nothing") - .doesNotThrowAnyException(); - } - @Test @DisplayName("an identical document produces no diff") void anIdenticalDocumentProducesNoDiff() { @@ -124,18 +106,6 @@ class WebOpenApiReleaseGateTest { assertThat(WebOpenApiDiffResult.identical().changed()).isFalse(); } - @Test - @DisplayName("a document with no problem schema is refused") - void aDocumentWithNoProblemSchemaIsRefused() { - assertThatThrownBy( - () -> - gate.requireProblemInventoryMatches( - new OpenAPI(), - dev.caskeleton.adapter.inbound.web.error.ProblemCatalog.standard())) - .as("a client with no error contract has to guess") - .isInstanceOf(WebOpenApiReleaseGate.OpenApiReleaseBlockedException.class); - } - private static Schema schema(String name, List properties, List required) { ObjectSchema schema = new ObjectSchema(); schema.setName(name); diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/operation/WebOperationCatalogTest.java b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/operation/WebOperationCatalogTest.java similarity index 97% rename from src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/operation/WebOperationCatalogTest.java rename to src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/operation/WebOperationCatalogTest.java index 93b8a0dc..50125c00 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/operation/WebOperationCatalogTest.java +++ b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/operation/WebOperationCatalogTest.java @@ -1,10 +1,10 @@ -package dev.caskeleton.adapter.inbound.web.operation; +package dev.caskeleton.adapter.inbound.web.advanced.operation; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import dev.caskeleton.adapter.inbound.web.budget.WebBudgetProfileName; +import dev.caskeleton.adapter.inbound.web.advanced.budget.WebBudgetProfileName; import dev.caskeleton.adapter.inbound.web.core.WebOperationName; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonMergePatchApplierTest.java b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonMergePatchApplierTest.java similarity index 97% rename from src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonMergePatchApplierTest.java rename to src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonMergePatchApplierTest.java index 52635b74..2795f20c 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonMergePatchApplierTest.java +++ b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonMergePatchApplierTest.java @@ -3,12 +3,12 @@ package dev.caskeleton.adapter.inbound.web.advanced.patch; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import dev.caskeleton.adapter.inbound.web.json.WebObjectMapperFactory; import java.nio.charset.StandardCharsets; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; /** * RFC 7396, and the one ambiguity that forces a tree-based implementation. @@ -19,7 +19,7 @@ import tools.jackson.databind.ObjectMapper; @Tag("web-advanced") class JsonMergePatchApplierTest { - private static final ObjectMapper MAPPER = WebObjectMapperFactory.standard(); + private static final ObjectMapper MAPPER = JsonMapper.shared(); /** A target with a mandatory field and two optional ones. */ record Profile(String displayName, String description, String nickname) {} diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchApplierTest.java b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchApplierTest.java similarity index 98% rename from src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchApplierTest.java rename to src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchApplierTest.java index 0cfd3c3c..1b1c538f 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchApplierTest.java +++ b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/patch/JsonPatchApplierTest.java @@ -3,13 +3,13 @@ package dev.caskeleton.adapter.inbound.web.advanced.patch; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import dev.caskeleton.adapter.inbound.web.json.WebObjectMapperFactory; import java.nio.charset.StandardCharsets; import java.util.List; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; /** * RFC 6902, and the atomicity that {@code test} exists to exploit. @@ -20,7 +20,7 @@ import tools.jackson.databind.ObjectMapper; @Tag("web-advanced") class JsonPatchApplierTest { - private static final ObjectMapper MAPPER = WebObjectMapperFactory.standard(); + private static final ObjectMapper MAPPER = JsonMapper.shared(); /** A target with a scalar, a nested object and a list. */ record Profile(String displayName, int version, Address address, List tags) {} diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/release/WebAdvancedRollbackIT.java b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/release/WebAdvancedRollbackIT.java similarity index 55% rename from src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/release/WebAdvancedRollbackIT.java rename to src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/release/WebAdvancedRollbackIT.java index c75b7187..1624cf72 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/release/WebAdvancedRollbackIT.java +++ b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/release/WebAdvancedRollbackIT.java @@ -2,22 +2,15 @@ package dev.caskeleton.adapter.inbound.web.advanced.release; import static org.assertj.core.api.Assertions.assertThat; -import dev.caskeleton.adapter.inbound.web.advanced.WebAdvancedFeature; import dev.caskeleton.adapter.inbound.web.advanced.codec.RepresentationNegotiationPolicy; import dev.caskeleton.adapter.inbound.web.advanced.codec.WebRepresentation; -import dev.caskeleton.adapter.inbound.web.advanced.functional.FunctionalRouteRegistry; import dev.caskeleton.adapter.inbound.web.advanced.mvc.MvcJsonSequenceConfiguration; import dev.caskeleton.adapter.inbound.web.advanced.mvc.MvcStreamingExecutorConfiguration; import dev.caskeleton.adapter.inbound.web.advanced.mvc.VirtualThreadMvcConfiguration; -import dev.caskeleton.adapter.inbound.web.advanced.ratelimit.RateLimitDraftHeaderWriter; -import dev.caskeleton.adapter.inbound.web.advanced.ratelimit.RateLimitDraftProfile; import dev.caskeleton.adapter.inbound.web.advanced.stream.WebStreamPolicy; import dev.caskeleton.adapter.inbound.web.advanced.stream.WebStreamRegistry; import dev.caskeleton.adapter.inbound.web.advanced.stream.encoding.StreamRecordEncoder; import dev.caskeleton.adapter.inbound.web.advanced.virtualthread.VirtualThreadAdmissionGuard; -import dev.caskeleton.adapter.inbound.web.ratelimit.RateLimitDecision; -import java.time.Duration; -import java.time.Instant; import java.util.List; import java.util.Optional; import java.util.Set; @@ -31,13 +24,12 @@ import org.springframework.core.task.TaskDecorator; /** * Turning every Advanced capability off restores Stable behaviour exactly. * - *

The condition the promotion gate refuses to waive, asserted rather than asserted about. If - * disabling a feature does not restore Stable behaviour then the feature was never optional, and - * every deployment that chose not to enable it has it anyway — which makes the whole + *

If disabling a feature does not restore Stable behaviour then the feature was never optional, + * and every deployment that chose not to enable it has it anyway — which makes the whole * Advanced/Stable separation a naming convention. * - *

Two of the twelve capabilities change requests that do not use them. Those are the ones this - * matters most for, and they are the ones whose configurations are started here with nothing set. + *

Two of the capabilities change requests that do not use them. Those are the ones this matters + * most for, and they are the ones whose configurations are started here with nothing set. */ @Tag("web-advanced") class WebAdvancedRollbackIT { @@ -86,16 +78,6 @@ class WebAdvancedRollbackIT { .doesNotHaveBean(VirtualThreadAdmissionGuard.class)); } - @Test - @DisplayName("library-only capabilities do not manufacture runtime switches") - void libraryOnlyCapabilitiesHaveNoRuntimeSwitch() { - for (WebAdvancedFeature feature : WebAdvancedFeature.values()) { - if (feature.activationPath() == WebAdvancedFeature.ActivationPath.LIBRARY_ONLY) { - assertThat(feature.runtimeProperty()).isEmpty(); - } - } - } - @Test @DisplayName("with the codecs off, only JSON negotiates") void codecsOffLeaveOnlyJson() { @@ -111,46 +93,4 @@ class WebAdvancedRollbackIT { assertThat(stable.negotiate(List.of("application/xml"), produces, Optional.of("mobile-app"))) .isEmpty(); } - - @Test - @DisplayName("with the draft headers off, the response carries none of them") - void draftHeadersOffWriteNothing() { - // The Stable contract is the 429 and Retry-After. This capability is additive, so disabling it - // must leave the response byte-identical. - RateLimitDecision refused = - RateLimitDecision.refused( - 100, Instant.parse("2026-08-25T10:00:30Z"), Duration.ofSeconds(30)); - - assertThat( - new RateLimitDraftHeaderWriter(RateLimitDraftProfile.disabled()) - .write(refused, Instant.parse("2026-08-25T10:00:00Z"))) - .isEmpty(); - } - - @Test - @DisplayName("with functional routing off, an empty registry serves nothing") - void functionalRoutingOffServesNothing() { - // Not "an empty router": the adapter refuses to build one, so a deployment that enabled the - // capability and registered nothing fails at startup rather than serving 404s. - assertThat( - new FunctionalRouteRegistry( - new dev.caskeleton.adapter.inbound.web.operation.InMemoryWebOperationCatalog()) - .size()) - .isZero(); - } - - @Test - @DisplayName("every capability's promotion gate demands the rollback evidence") - void everyGateDemandsRollbackEvidence() { - // The machine-checked half of what this class demonstrates by hand. - for (WebAdvancedFeature feature : WebAdvancedFeature.values()) { - WebAdvancedPromotionGate gate = WebAdvancedPromotionGate.forFeature(feature); - assertThat(gate.rollbackValidated()).as("%s starts un-promotable", feature).isFalse(); - assertThat(gate.stableBehaviourUnchanged()).isFalse(); - assertThat(gate.blockers(feature, gate.requiredSuites(), gate.minimumSoak())) - .as("%s blocks on rollback and on Stable behaviour", feature) - .anyMatch(blocker -> blocker.contains("rollback not exercised")) - .anyMatch(blocker -> blocker.contains("every deployment has it")); - } - } } diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/release/WebStreamingSoakIT.java b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/release/WebStreamingSoakIT.java similarity index 100% rename from src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/release/WebStreamingSoakIT.java rename to src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/release/WebStreamingSoakIT.java diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/security/WebSecurityContextBridgeTest.java b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/security/WebSecurityContextBridgeTest.java similarity index 98% rename from src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/security/WebSecurityContextBridgeTest.java rename to src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/security/WebSecurityContextBridgeTest.java index 80279ced..8f5540bf 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/security/WebSecurityContextBridgeTest.java +++ b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/security/WebSecurityContextBridgeTest.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.inbound.web.security; +package dev.caskeleton.adapter.inbound.web.advanced.security; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamCoreTest.java b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamCoreTest.java similarity index 71% rename from src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamCoreTest.java rename to src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamCoreTest.java index 52283a6a..b8ab5593 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamCoreTest.java +++ b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamCoreTest.java @@ -3,7 +3,6 @@ package dev.caskeleton.adapter.inbound.web.advanced.stream; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import dev.caskeleton.adapter.inbound.web.error.ProblemCode; import java.time.Duration; import java.time.Instant; import org.junit.jupiter.api.DisplayName; @@ -24,48 +23,10 @@ class WebStreamCoreTest { private static final StreamId STREAM = new StreamId("orders-feed"); @Test - @DisplayName("a committed response never tries to change its HTTP status") - void committedResponseNeverChangesStatus() { - // Writing a problem document onto a committed response produces a body that is half stream and - // half JSON, which no client parses and every proxy caches as a success. - TerminationDecision decision = - WebStreamTerminationMapper.standard().mapFailure(true, new IllegalStateException("boom")); - - assertThat(decision.termination()).contains(WebStreamTermination.TERMINAL_ERROR_RECORD); - assertThat(decision.httpStatusChange()).isEmpty(); - } - - @Test - @DisplayName("an uncommitted failure is still an ordinary HTTP error") - void uncommittedFailureIsAnHttpError() { - TerminationDecision decision = - WebStreamTerminationMapper.standard().mapFailure(false, new IllegalStateException("boom")); - - assertThat(decision.httpStatusChange()).contains(ProblemCode.DEPENDENCY_FAILURE); - assertThat(decision.termination()).isEmpty(); - } - - @Test - @DisplayName("a decision is one or the other, never both and never neither") - void decisionsAreWellFormed() { - assertThatThrownBy( - () -> - new TerminationDecision( - java.util.Optional.of(WebStreamTermination.MAX_AGE), - java.util.Optional.of(ProblemCode.DEPENDENCY_FAILURE), - "x")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("never both and never neither"); - } - - @Test - @DisplayName("a connection that fails before the terminal record is an abrupt close") - void writeFailureIsAnAbruptClose() { - // Counting these as normal completions is how a rising rate of mid-stream failures stays - // invisible. - TerminationDecision decision = WebStreamTerminationMapper.standard().mapWriteFailure(); - - assertThat(decision.termination()).contains(WebStreamTermination.ABRUPT_CLOSE); + @DisplayName("only a terminal record tells the client the stream ended") + void onlyATerminalRecordTellsTheClient() { + // Counting an abrupt close as a normal completion is how a rising rate of mid-stream failures + // stays invisible. assertThat(WebStreamTermination.ABRUPT_CLOSE.clientWasTold()).isFalse(); assertThat(WebStreamTermination.NORMAL_COMPLETE.clientWasTold()).isTrue(); } @@ -197,18 +158,4 @@ class WebStreamCoreTest { .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("cannot tell the repeats apart"); } - - @Test - @DisplayName("an envelope says which of the three outcomes it is") - void envelopesAreThreeWay() { - assertThat(new WebStreamEnvelope.Item<>(STREAM, StreamSequence.first(), "x").terminal()) - .isFalse(); - assertThat(new WebStreamEnvelope.Complete(STREAM, StreamSequence.first()).terminal()) - .isTrue(); - assertThat( - new WebStreamEnvelope.Failure( - STREAM, StreamSequence.first(), ProblemCode.DEPENDENCY_FAILURE, "failed") - .terminal()) - .isTrue(); - } } diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamDrainTest.java b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamDrainTest.java similarity index 100% rename from src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamDrainTest.java rename to src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamDrainTest.java diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/stream/encoding/StreamFramingTest.java b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/stream/encoding/StreamFramingTest.java similarity index 100% rename from src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/stream/encoding/StreamFramingTest.java rename to src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/stream/encoding/StreamFramingTest.java diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/stream/replay/GapAndDuplicateGuardTest.java b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/stream/replay/GapAndDuplicateGuardTest.java similarity index 100% rename from src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/stream/replay/GapAndDuplicateGuardTest.java rename to src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/stream/replay/GapAndDuplicateGuardTest.java diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/stream/replay/MessagingReplayBridgeTest.java b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/stream/replay/MessagingReplayBridgeTest.java similarity index 100% rename from src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/stream/replay/MessagingReplayBridgeTest.java rename to src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/stream/replay/MessagingReplayBridgeTest.java diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/versioning/DeprecationHeaderWriterTest.java b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/versioning/ApiDeprecationPolicyTest.java similarity index 63% rename from src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/versioning/DeprecationHeaderWriterTest.java rename to src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/versioning/ApiDeprecationPolicyTest.java index c9b51117..7bb8c543 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/versioning/DeprecationHeaderWriterTest.java +++ b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/versioning/ApiDeprecationPolicyTest.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.inbound.web.versioning; +package dev.caskeleton.adapter.inbound.web.advanced.versioning; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; @@ -6,50 +6,17 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.net.URI; import java.time.Instant; -import java.util.Map; import java.util.Optional; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -/** A deprecation notice has to be actionable, parseable, and true. */ -class DeprecationHeaderWriterTest { +/** A deprecation has to be true: its sunset follows it and has not already passed. */ +class ApiDeprecationPolicyTest { private static final Instant DEPRECATED = Instant.parse("2026-08-01T00:00:00Z"); private static final Instant SUNSET = Instant.parse("2027-02-01T00:00:00Z"); private static final Instant NOW = Instant.parse("2026-08-13T00:00:00Z"); - private final DeprecationHeaderWriter writer = new DeprecationHeaderWriter(); - - @Test - @DisplayName("Sunset is an HTTP-date, not ISO 8601") - void sunsetIsAnHttpDate() { - Map headers = writer.headersFor(route(Optional.of(SUNSET))); - - assertThat(headers.get("Sunset")) - .as("RFC 8594 requires an IMF-fixdate; a client's parser rejects the ISO form") - .isEqualTo("Mon, 01 Feb 2027 00:00:00 GMT"); - assertThat(headers.get("Deprecation")).isEqualTo("Sat, 01 Aug 2026 00:00:00 GMT"); - } - - @Test - @DisplayName("the notice carries somewhere to go, not just an instruction to stop") - void theNoticeCarriesSomewhereToGo() { - Map headers = writer.headersFor(route(Optional.of(SUNSET))); - - assertThat(headers.get("Link")) - .contains("rel=\"deprecation\"") - .contains("https://docs.example.com/deprecations/orders-v1") - .contains("rel=\"successor-version\""); - } - - @Test - @DisplayName("a route with no committed sunset omits the header rather than inventing a date") - void aRouteWithNoCommittedSunsetOmitsTheHeader() { - Map headers = writer.headersFor(route(Optional.empty())); - - assertThat(headers).containsKeys("Deprecation", "Link").doesNotContainKey("Sunset"); - } - @Test @DisplayName("a sunset before the deprecation is refused at construction") void aSunsetBeforeTheDeprecationIsRefused() { @@ -90,7 +57,6 @@ class DeprecationHeaderWriterTest { assertThat(policy.deprecated("GET /api/v1/orders")).isTrue(); assertThat(policy.deprecated("GET /api/v1/other")).isFalse(); - assertThat(writer.headersFor(policy, "GET /api/v1/other")).isEmpty(); assertThatThrownBy(() -> policy.register(route(Optional.of(SUNSET)), NOW)) .isInstanceOf(SunsetViolationException.class); assertThatCode(() -> policy.registered()).doesNotThrowAnyException(); diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/versioning/PathApiVersionResolverTest.java b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/versioning/PathApiVersionResolverTest.java similarity index 98% rename from src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/versioning/PathApiVersionResolverTest.java rename to src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/versioning/PathApiVersionResolverTest.java index 9fe7484c..72595e03 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/versioning/PathApiVersionResolverTest.java +++ b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/versioning/PathApiVersionResolverTest.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.inbound.web.versioning; +package dev.caskeleton.adapter.inbound.web.advanced.versioning; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/virtualthread/VirtualThreadAdmissionTest.java b/src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/virtualthread/VirtualThreadAdmissionTest.java similarity index 100% rename from src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/virtualthread/VirtualThreadAdmissionTest.java rename to src/adapter/inbound/web-advanced/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/virtualthread/VirtualThreadAdmissionTest.java diff --git a/src/adapter/inbound/web-fileserver/build.gradle b/src/adapter/inbound/web-fileserver/build.gradle index 9c16517a..8849723e 100644 --- a/src/adapter/inbound/web-fileserver/build.gradle +++ b/src/adapter/inbound/web-fileserver/build.gradle @@ -10,11 +10,7 @@ plugins { // range and nginx helpers, tus and draft-12 upload surfaces and its HTTP authorization all compiled // into the leaf that any application with an HTTP API depends on. // -// The package keeps its name. It is still part of the web platform's module map — `WebStableModule` -// declares its twelve modules and their edges, and `WebBuildModel.platformSourceRoots()` scans this -// source root alongside the web leaf's, which is what that method's plural has always been for. A -// second copy of the map here would be a second answer to "is this edge declared", and the map is -// the one thing the platform must not have two of. +// The package keeps its name (`dev.caskeleton.adapter.inbound.web.fileserver`). // // It depends on `adapter:inbound:web` rather than the reverse: the fileserver modules import `core`, // `auth` and `observability`, nine times in total, and nothing outside them imports fileserver. @@ -27,16 +23,9 @@ dependencies { implementation 'org.springframework.boot:spring-boot-starter-web' implementation 'org.springframework.boot:spring-boot-starter-security' implementation 'org.springframework.boot:spring-boot-starter-validation' - // `spring-webflux`, not `spring-boot-starter-webflux`, for the reason the web leaf states in - // its own build file: the starter puts reactor-netty — a second embedded server — on the - // runtime classpath of an application that already has Tomcat. The reactive fileserver surface - // needs the types, not another server. - implementation 'org.springframework:spring-webflux' - implementation 'io.projectreactor:reactor-core' testImplementation project(':adapter:inbound:web') testImplementation testFixtures(project(':adapter:inbound:web')) testImplementation 'org.springframework.boot:spring-boot-starter-test' testImplementation 'org.springframework.security:spring-security-test' - testImplementation 'io.projectreactor:reactor-test' } diff --git a/src/adapter/inbound/web-fileserver/gradle.lockfile b/src/adapter/inbound/web-fileserver/gradle.lockfile index eea7f85d..8b0c6117 100644 --- a/src/adapter/inbound/web-fileserver/gradle.lockfile +++ b/src/adapter/inbound/web-fileserver/gradle.lockfile @@ -54,8 +54,6 @@ io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,testAnnota io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,testAnnotationProcessor io.micrometer:micrometer-commons:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath io.micrometer:micrometer-observation:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.projectreactor:reactor-core:3.8.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.projectreactor:reactor-test:3.8.7=testCompileClasspath,testRuntimeClasspath io.swagger.core.v3:swagger-annotations-jakarta:2.2.38=runtimeClasspath,testRuntimeClasspath io.swagger.core.v3:swagger-core-jakarta:2.2.38=runtimeClasspath,testRuntimeClasspath io.swagger.core.v3:swagger-models-jakarta:2.2.38=runtimeClasspath,testRuntimeClasspath @@ -127,7 +125,6 @@ org.ow2.asm:asm-util:9.10.1=spotbugs org.ow2.asm:asm:9.10.1=spotbugs org.ow2.asm:asm:9.7.1=testCompileClasspath,testRuntimeClasspath org.pcollections:pcollections:4.0.1=annotationProcessor,testAnnotationProcessor -org.reactivestreams:reactive-streams:1.0.4=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.reflections:reflections:0.10.2=checkstyle org.skyscreamer:jsonassert:1.5.3=testCompileClasspath,testRuntimeClasspath org.slf4j:jul-to-slf4j:2.0.18=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath @@ -181,7 +178,6 @@ org.springframework:spring-core:7.0.9=compileClasspath,runtimeClasspath,testComp org.springframework:spring-expression:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework:spring-test:7.0.9=testCompileClasspath,testRuntimeClasspath org.springframework:spring-web:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-webflux:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework:spring-webmvc:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.xmlresolver:xmlresolver:5.3.3=checkstyle,spotbugs org.xmlunit:xmlunit-core:2.10.4=testCompileClasspath,testRuntimeClasspath diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/config/FileserverHttpSurfaceConfiguration.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/config/FileserverHttpSurfaceConfiguration.java new file mode 100644 index 00000000..3249b9cc --- /dev/null +++ b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/config/FileserverHttpSurfaceConfiguration.java @@ -0,0 +1,29 @@ +package dev.caskeleton.adapter.inbound.web.fileserver.config; + +import dev.caskeleton.adapter.inbound.web.fileserver.controller.FileDownloadController; +import dev.caskeleton.adapter.inbound.web.fileserver.controller.FileUploadController; +import dev.caskeleton.adapter.inbound.web.fileserver.draft12.Draft12UploadController; +import dev.caskeleton.adapter.inbound.web.fileserver.lifecycle.FileLifecycleController; +import dev.caskeleton.adapter.inbound.web.fileserver.problem.FileserverExceptionHandler; +import dev.caskeleton.adapter.inbound.web.fileserver.tus.TusController; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; + +/** + * The public Fileserver HTTP surface, as one importable unit. + * + *

The Fileserver composition root imports this, so selecting the capability brings its routes + * without any application scanning this leaf. Each controller keeps its own property condition. The + * admin controller is not here: it belongs to the management context. + */ +@Configuration(proxyBeanMethods = false) +@Import({ + FileUploadController.class, + FileDownloadController.class, + TusController.class, + Draft12UploadController.class, + FileLifecycleController.class, + FileserverExceptionHandler.class, + MvcTransferExecutorConfiguration.class +}) +public class FileserverHttpSurfaceConfiguration {} diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/config/MvcTransferExecutorConfiguration.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/config/MvcTransferExecutorConfiguration.java index 766542bd..a8683f18 100644 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/config/MvcTransferExecutorConfiguration.java +++ b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/config/MvcTransferExecutorConfiguration.java @@ -18,11 +18,19 @@ import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; * correlation context; without it every transfer log line would be untraceable back to its request. */ @Configuration(proxyBeanMethods = false) -@ConditionalOnProperty(prefix = "app.fileserver-platform", name = "enabled", havingValue = "true") +@ConditionalOnProperty( + prefix = "app.fileserver-platform", + name = "enabled", + havingValue = "true", + matchIfMissing = true) public class MvcTransferExecutorConfiguration { @Bean(destroyMethod = "shutdown") - @ConditionalOnProperty(prefix = "app.fileserver-platform", name = "enabled", havingValue = "true") + @ConditionalOnProperty( + prefix = "app.fileserver-platform", + name = "enabled", + havingValue = "true", + matchIfMissing = true) public ThreadPoolTaskExecutor fileserverTransferExecutor( TransferExecutorProperties properties, TaskDecorator taskDecorator) { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); @@ -38,7 +46,11 @@ public class MvcTransferExecutorConfiguration { } @Bean - @ConditionalOnProperty(prefix = "app.fileserver-platform", name = "enabled", havingValue = "true") + @ConditionalOnProperty( + prefix = "app.fileserver-platform", + name = "enabled", + havingValue = "true", + matchIfMissing = true) public BlockingTransferExecutor blockingTransferExecutor( ThreadPoolTaskExecutor fileserverTransferExecutor, TransferExecutorProperties properties) { return new BlockingTransferExecutor(fileserverTransferExecutor, properties.awaitSeconds()); diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/controller/FileDownloadController.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/controller/FileDownloadController.java index ae1cb2e5..ddcb7f25 100644 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/controller/FileDownloadController.java +++ b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/controller/FileDownloadController.java @@ -42,7 +42,11 @@ import org.springframework.web.bind.annotation.RestController; */ @OwnsAbsoluteWebRoute @RestController -@ConditionalOnProperty(prefix = "app.fileserver-platform", name = "enabled", havingValue = "true") +@ConditionalOnProperty( + prefix = "app.fileserver-platform", + name = "enabled", + havingValue = "true", + matchIfMissing = true) public class FileDownloadController { private final DownloadApplicationService downloadService; diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/controller/FileUploadController.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/controller/FileUploadController.java index ac41e4d0..6883f9c9 100644 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/controller/FileUploadController.java +++ b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/controller/FileUploadController.java @@ -49,7 +49,11 @@ import org.springframework.web.multipart.MultipartFile; */ @OwnsAbsoluteWebRoute @RestController -@ConditionalOnProperty(prefix = "app.fileserver-platform", name = "enabled", havingValue = "true") +@ConditionalOnProperty( + prefix = "app.fileserver-platform", + name = "enabled", + havingValue = "true", + matchIfMissing = true) public class FileUploadController { private final SingleShotUploadService uploadService; diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/http/ZeroCopyEligibility.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/http/ZeroCopyEligibility.java index ab5cfca0..4520bc32 100644 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/http/ZeroCopyEligibility.java +++ b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/http/ZeroCopyEligibility.java @@ -1,8 +1,5 @@ package dev.caskeleton.adapter.inbound.web.fileserver.http; -import org.springframework.http.ZeroCopyHttpOutputMessage; -import org.springframework.http.server.reactive.ServerHttpResponse; - /** * Decides whether a response may be written with a kernel-level file transfer. * @@ -33,22 +30,12 @@ public final class ZeroCopyEligibility { return new ZeroCopyEligibility(false, Long.MAX_VALUE); } - public boolean isEligible(ServerHttpResponse response, long payloadBytes, boolean secure) { - return isEligible(supportsZeroCopy(response), payloadBytes, secure); - } - /** * Decides eligibility from already-resolved facts. * - *

Separating the capability probe from the policy keeps the policy testable without - * constructing a server response, and keeps the probe in exactly one place. + *

The caller probes the response; the policy stays testable without constructing one. */ public boolean isEligible(boolean responseCapable, long payloadBytes, boolean secure) { return enabled && responseCapable && !secure && payloadBytes >= minimumBytes; } - - /** True when the response implementation can hand a file straight to the kernel. */ - public static boolean supportsZeroCopy(ServerHttpResponse response) { - return response instanceof ZeroCopyHttpOutputMessage; - } } diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/lifecycle/FileLifecycleController.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/lifecycle/FileLifecycleController.java index 757f5f60..9ec89cf6 100644 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/lifecycle/FileLifecycleController.java +++ b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/lifecycle/FileLifecycleController.java @@ -39,7 +39,11 @@ import org.springframework.web.bind.annotation.RestController; */ @OwnsAbsoluteWebRoute @RestController -@ConditionalOnProperty(prefix = "app.fileserver-platform", name = "enabled", havingValue = "true") +@ConditionalOnProperty( + prefix = "app.fileserver-platform", + name = "enabled", + havingValue = "true", + matchIfMissing = true) public class FileLifecycleController { private final FileLifecycleService lifecycleService; diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/problem/FileserverExceptionHandler.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/problem/FileserverExceptionHandler.java index 0d71df15..49dc5455 100644 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/problem/FileserverExceptionHandler.java +++ b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/problem/FileserverExceptionHandler.java @@ -15,14 +15,18 @@ import org.springframework.web.bind.annotation.RestControllerAdvice; * *

It is ordered ahead of the base operational handler, whose catch-all would otherwise resolve * these to a generic internal error and lose the code. The status comes from the error code itself, - * so Spring MVC, Spring WebFlux, and the Nginx delegation path cannot drift apart. + * so Spring MVC and the Nginx delegation path cannot drift apart. * *

Two headers are part of the contract rather than decoration: {@code Retry-After} on a * retryable rejection, and the unsatisfied-range form of {@code Content-Range} on {@code 416}, * which is how a client learns the real representation length. */ @RestControllerAdvice -@ConditionalOnProperty(prefix = "app.fileserver-platform", name = "enabled", havingValue = "true") +@ConditionalOnProperty( + prefix = "app.fileserver-platform", + name = "enabled", + havingValue = "true", + matchIfMissing = true) @Order(Ordered.HIGHEST_PRECEDENCE) public class FileserverExceptionHandler { @@ -39,7 +43,7 @@ public class FileserverExceptionHandler { ResponseEntity.BodyBuilder response = ResponseEntity.status(problem.status()).contentType(MediaType.APPLICATION_PROBLEM_JSON); - // The header policy is shared with the reactive router; neither transport owns it. + // The header policy lives in FileserverProblemHeaders; this handler does not own it. FileserverProblemHeaders.of(failure).forEach(response::header); return response.body(problem); } diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/problem/FileserverProblemHeaders.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/problem/FileserverProblemHeaders.java index 8ed1b2d3..bbc0d182 100644 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/problem/FileserverProblemHeaders.java +++ b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/problem/FileserverProblemHeaders.java @@ -15,10 +15,9 @@ import java.util.Map; * have succeeded in a second. The unsatisfied-range form of {@code Content-Range} is how a client * learns the real representation length after a {@code 416}. * - *

The table lived inside the servlet advice, and the reactive router simply did not have one, so - * the same failure answered with different headers depending on which transport served it. A shared - * owner is the only arrangement in which that cannot silently happen again: neither transport - * decides anything, both ask. + *

The table once lived inside one handler while another path had none, so the same failure + * answered with different headers depending on which path served it. One owner keeps that from + * silently happening again: handlers ask, they do not decide. */ public final class FileserverProblemHeaders { @@ -42,8 +41,7 @@ public final class FileserverProblemHeaders { /** * Headers this failure must carry, in insertion order. * - *

Returned as plain strings so neither Spring MVC's nor WebFlux's header type appears in the - * shared policy — the two transports differ in how they apply headers, not in which ones apply. + *

Returned as plain strings so no framework header type appears in the shared policy. */ public static Map of(FileserverException failure) { Map headers = new LinkedHashMap<>(); diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/problem/FileserverProblemTitles.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/problem/FileserverProblemTitles.java index 222fb5f4..5b1658e5 100644 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/problem/FileserverProblemTitles.java +++ b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/problem/FileserverProblemTitles.java @@ -36,6 +36,7 @@ final class FileserverProblemTitles { Map.entry(FileserverErrorCode.INVALID_PATH, "Invalid path"), Map.entry(FileserverErrorCode.PATH_OUTSIDE_NAMESPACE, "Path outside namespace"), Map.entry(FileserverErrorCode.TRANSFER_ADMISSION_REJECTED, "Too many transfers"), + Map.entry(FileserverErrorCode.CHECKSUM_MISMATCH, "Checksum mismatch"), Map.entry(FileserverErrorCode.PARTIAL_WRITE, "Transfer did not complete"), Map.entry( FileserverErrorCode.AMBIGUOUS_COMPLETION, "Completion could not be confirmed"), diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/reactive/DataBufferByteChannel.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/reactive/DataBufferByteChannel.java deleted file mode 100644 index 3fe72b74..00000000 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/reactive/DataBufferByteChannel.java +++ /dev/null @@ -1,150 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.fileserver.reactive; - -import java.io.IOException; -import java.io.InterruptedIOException; -import java.nio.ByteBuffer; -import java.nio.channels.ReadableByteChannel; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.atomic.AtomicBoolean; -import org.reactivestreams.Subscriber; -import org.reactivestreams.Subscription; -import org.springframework.core.io.buffer.DataBuffer; -import org.springframework.core.io.buffer.DataBufferUtils; -import reactor.core.publisher.Flux; - -/** - * Bridges a reactive body into the blocking channel the content store expects. - * - *

Two properties matter and are enforced structurally rather than by discipline. First, every - * pooled {@link DataBuffer} this subscriber observes is copied and released inside {@code onNext}, - * so no buffer can survive a later cancellation or error path — there is no path where a pooled - * buffer is still owned by this class. Second, demand is replenished one item at a time as the - * reader consumes, so the number of buffers in flight never exceeds the configured prefetch no - * matter how fast the client sends. - */ -final class DataBufferByteChannel implements ReadableByteChannel, Subscriber { - - /** - * Sentinel meaning the upstream finished. - * - *

It is a distinct type rather than an empty buffer so termination is decided by what the - * queue holds, never by comparing buffer identities. - */ - private static final Object END_OF_STREAM = new Object(); - - private final BlockingQueue ready = new LinkedBlockingQueue<>(); - private final AtomicBoolean open = new AtomicBoolean(true); - private final int prefetch; - - private volatile Subscription subscription; - private volatile Throwable failure; - private ByteBuffer current; - - private DataBufferByteChannel(int prefetch) { - this.prefetch = prefetch; - } - - /** - * Subscribes to {@code body} and exposes it as a blocking channel bounded by {@code prefetch}. - */ - static DataBufferByteChannel subscribeTo(Flux body, int prefetch) { - if (prefetch < 1) { - throw new IllegalArgumentException("prefetch must be positive"); - } - DataBufferByteChannel channel = new DataBufferByteChannel(prefetch); - body.subscribe(channel); - return channel; - } - - @Override - public void onSubscribe(Subscription subscription) { - this.subscription = subscription; - subscription.request(prefetch); - } - - @Override - public void onNext(DataBuffer buffer) { - try { - ByteBuffer copy = ByteBuffer.allocate(buffer.readableByteCount()); - buffer.toByteBuffer(copy); - copy.rewind(); - ready.add(copy); - } finally { - DataBufferUtils.release(buffer); - } - } - - @Override - public void onError(Throwable throwable) { - this.failure = throwable; - ready.add(END_OF_STREAM); - } - - @Override - public void onComplete() { - ready.add(END_OF_STREAM); - } - - @Override - public int read(ByteBuffer destination) throws IOException { - if (!open.get()) { - throw new IOException("channel is closed"); - } - if (current == null || !current.hasRemaining()) { - current = nextChunk(); - if (current == null) { - return -1; - } - } - int transferred = Math.min(destination.remaining(), current.remaining()); - int limit = current.limit(); - current.limit(current.position() + transferred); - destination.put(current); - current.limit(limit); - return transferred; - } - - /** - * Waits for the next chunk and replenishes exactly one unit of demand. - * - *

Requesting only after a chunk has been consumed is what bounds the in-flight buffer count; - * an unconditional {@code request(Long.MAX_VALUE)} would let a fast client outrun the disk. - */ - private ByteBuffer nextChunk() throws IOException { - Object taken; - try { - taken = ready.take(); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - throw new InterruptedIOException("interrupted while waiting for the request body"); - } - if (!(taken instanceof ByteBuffer chunk)) { - if (failure != null) { - throw new IOException("request body failed", failure); - } - return null; - } - Subscription pending = subscription; - if (pending != null) { - pending.request(1); - } - return chunk; - } - - @Override - public boolean isOpen() { - return open.get(); - } - - @Override - public void close() { - if (open.compareAndSet(true, false)) { - Subscription current = subscription; - if (current != null) { - current.cancel(); - } - ready.clear(); - } - } -} diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/reactive/FileDownloadHandler.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/reactive/FileDownloadHandler.java deleted file mode 100644 index f23e90f6..00000000 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/reactive/FileDownloadHandler.java +++ /dev/null @@ -1,153 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.fileserver.reactive; - -import dev.caskeleton.adapter.inbound.web.fileserver.dto.UploadedFileResponse; -import dev.caskeleton.adapter.inbound.web.fileserver.http.HttpConditionalRequest; -import dev.caskeleton.adapter.inbound.web.fileserver.http.HttpDownloadDecision; -import dev.caskeleton.adapter.inbound.web.fileserver.http.HttpDownloadPlanner; -import dev.caskeleton.application.fileserver.api.ByteRange; -import dev.caskeleton.application.fileserver.api.FileId; -import dev.caskeleton.application.fileserver.api.security.RequestContext; -import dev.caskeleton.application.fileserver.download.DownloadApplicationService; -import dev.caskeleton.application.fileserver.download.DownloadDescriptor; -import dev.caskeleton.application.fileserver.download.DownloadRequest; -import java.nio.channels.ReadableByteChannel; -import java.time.Instant; -import java.time.ZonedDateTime; -import java.time.format.DateTimeFormatter; -import java.time.format.DateTimeParseException; -import java.util.Optional; -import org.springframework.core.io.buffer.DataBuffer; -import org.springframework.core.io.buffer.DataBufferUtils; -import org.springframework.core.io.buffer.DefaultDataBufferFactory; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.http.MediaType; -import org.springframework.web.reactive.function.server.ServerRequest; -import org.springframework.web.reactive.function.server.ServerResponse; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; - -/** - * Reactive counterpart of the MVC download endpoints. - * - *

The decision comes from the same application service the servlet path uses, so status codes - * and headers cannot drift. Content is read on the dedicated I/O scheduler in bounded chunks, and - * every emitted buffer is released on cancellation — a client that disconnects mid-transfer must - * not leak the pooled buffers already in flight. - */ -public final class FileDownloadHandler { - - private static final int CHUNK_BYTES = 64 * 1024; - - private final DownloadApplicationService downloadService; - private final ReactiveDownloadResponseWriter responseWriter; - private final HttpDownloadPlanner downloadPlanner; - private final FileserverIoScheduler ioScheduler; - - public FileDownloadHandler( - DownloadApplicationService downloadService, - ReactiveDownloadResponseWriter responseWriter, - HttpDownloadPlanner downloadPlanner, - FileserverIoScheduler ioScheduler) { - this.downloadService = downloadService; - this.responseWriter = responseWriter; - this.downloadPlanner = downloadPlanner; - this.ioScheduler = ioScheduler; - } - - public Mono describe(ServerRequest request) { - FileId fileId = FileId.parse(request.pathVariable("fileId")); - return Mono.fromCallable(() -> downloadService.describeFile(fileId, contextOf(request))) - .subscribeOn(ioScheduler.scheduler()) - .flatMap( - view -> - ServerResponse.ok() - .contentType(MediaType.APPLICATION_JSON) - .bodyValue(UploadedFileResponse.from(view))); - } - - public Mono download(ServerRequest request) { - FileId fileId = FileId.parse(request.pathVariable("fileId")); - boolean headOnly = HttpMethod.HEAD.equals(request.method()); - boolean inline = request.queryParam("inline").map(Boolean::parseBoolean).orElse(false); - RequestContext context = contextOf(request); - - HttpConditionalRequest conditional = conditionalOf(request, headOnly); - return Mono.fromCallable(() -> downloadService.describe(new DownloadRequest(fileId), context)) - .subscribeOn(ioScheduler.scheduler()) - .map(descriptor -> downloadPlanner.plan(descriptor, conditional, inline)) - .flatMap(this::respond); - } - - private Mono respond(HttpDownloadDecision decision) { - ServerResponse.BodyBuilder builder = - ServerResponse.status(decision.status()) - .headers(headers -> headers.putAll(responseWriter.headersFor(decision))); - if (!decision.bodyExpected()) { - return builder.build(); - } - if (decision.descriptor().representation().length() == 0) { - return builder.body(Flux.empty(), DataBuffer.class); - } - return builder.body(content(decision), DataBuffer.class); - } - - /** - * Streams the described bytes with bounded demand. - * - *

{@code readByteChannel} closes the channel and releases every buffer it emitted when the - * subscriber cancels, which is the behaviour a disconnecting client depends on. - */ - private Flux content(HttpDownloadDecision decision) { - ByteRange range = decision.payloadRange(); - return DataBufferUtils.readByteChannel( - () -> openContent(decision.descriptor(), range), - DefaultDataBufferFactory.sharedInstance, - CHUNK_BYTES) - .subscribeOn(ioScheduler.scheduler()); - } - - private ReadableByteChannel openContent(DownloadDescriptor descriptor, ByteRange range) { - return downloadService.openContent(descriptor, range); - } - - private static HttpConditionalRequest conditionalOf(ServerRequest request, boolean headOnly) { - HttpHeaders headers = request.headers().asHttpHeaders(); - return new HttpConditionalRequest( - header(headers, HttpHeaders.IF_MATCH), - header(headers, HttpHeaders.IF_NONE_MATCH), - date(headers, HttpHeaders.IF_MODIFIED_SINCE), - date(headers, HttpHeaders.IF_UNMODIFIED_SINCE), - header(headers, HttpHeaders.IF_RANGE), - header(headers, HttpHeaders.RANGE), - headOnly); - } - - private static Optional header(HttpHeaders headers, String name) { - String value = headers.getFirst(name); - return value == null || value.isBlank() ? Optional.empty() : Optional.of(value); - } - - /** A malformed HTTP-date is ignored rather than rejected, as RFC 9110 requires. */ - private static Optional date(HttpHeaders headers, String name) { - Optional raw = header(headers, name); - if (raw.isEmpty()) { - return Optional.empty(); - } - try { - return Optional.of( - ZonedDateTime.parse(raw.get(), DateTimeFormatter.RFC_1123_DATE_TIME).toInstant()); - } catch (DateTimeParseException malformed) { - return Optional.empty(); - } - } - - private static RequestContext contextOf(ServerRequest request) { - return request - .attribute(ReactiveFileserverAttributes.REQUEST_CONTEXT) - .filter(RequestContext.class::isInstance) - .map(RequestContext.class::cast) - .orElseThrow( - () -> new IllegalStateException("fileserver request context attribute is missing")); - } -} diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/reactive/FileUploadHandler.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/reactive/FileUploadHandler.java deleted file mode 100644 index 3696f24f..00000000 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/reactive/FileUploadHandler.java +++ /dev/null @@ -1,165 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.fileserver.reactive; - -import dev.caskeleton.adapter.inbound.web.fileserver.config.FileserverWebProperties; -import dev.caskeleton.adapter.inbound.web.fileserver.dto.BatchUploadItemResult; -import dev.caskeleton.adapter.inbound.web.fileserver.dto.BatchUploadResponse; -import dev.caskeleton.adapter.inbound.web.fileserver.dto.UploadedFileResponse; -import dev.caskeleton.adapter.inbound.web.fileserver.mapper.RawUploadRequestMapper; -import dev.caskeleton.adapter.inbound.web.fileserver.mapper.UploadIntent; -import dev.caskeleton.application.fileserver.api.FileState; -import dev.caskeleton.application.fileserver.api.error.FileserverException; -import dev.caskeleton.application.fileserver.api.security.RequestContext; -import dev.caskeleton.application.fileserver.api.transfer.UploadMode; -import dev.caskeleton.application.fileserver.upload.CreateUploadRequest; -import dev.caskeleton.application.fileserver.upload.FileView; -import dev.caskeleton.application.fileserver.upload.FinalizeUploadRequest; -import java.net.URI; -import java.time.Clock; -import java.util.List; -import java.util.Locale; -import java.util.Optional; -import java.util.OptionalLong; -import org.springframework.core.io.buffer.DataBuffer; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.codec.multipart.PartEvent; -import org.springframework.web.reactive.function.server.ServerRequest; -import org.springframework.web.reactive.function.server.ServerResponse; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; - -/** - * Reactive counterpart of the MVC upload endpoints. - * - *

It answers the same statuses and headers as the servlet path because both build their response - * from the same {@link FileView}. The body is never joined into a single buffer; each request is - * consumed as a bounded stream so a large upload does not scale with heap. - */ -public final class FileUploadHandler { - - private final ReactiveUploadApplicationService uploadService; - private final PartEventUploadReader partReader; - private final FileserverWebProperties properties; - private final Clock clock; - - public FileUploadHandler( - ReactiveUploadApplicationService uploadService, - PartEventUploadReader partReader, - FileserverWebProperties properties, - Clock clock) { - this.uploadService = uploadService; - this.partReader = partReader; - this.properties = properties; - this.clock = clock; - } - - /** Raw streaming upload; the whole request body is the file. */ - public Mono uploadRaw(ServerRequest request) { - UploadIntent intent = rawIntent(request); - RequestContext context = contextOf(request); - return uploadService - .upload( - createRequest(intent), - request.bodyToFlux(DataBuffer.class), - declaredLength(intent), - new FinalizeUploadRequest(intent.expectedSha256(), false), - context) - .flatMap(FileUploadHandler::created); - } - - /** Multipart single upload; only the first file part is consumed. */ - public Mono uploadMultipart(ServerRequest request) { - RequestContext context = contextOf(request); - return partReader - .forEachPart( - request.bodyToFlux(PartEvent.class), - (intent, content) -> uploadOne(intent, content, context)) - .next() - .flatMap(FileUploadHandler::created); - } - - /** Bounded multi-file upload; each part answers independently and none rolls back a sibling. */ - public Mono uploadBatch(ServerRequest request) { - RequestContext context = contextOf(request); - return partReader - .forEachPart( - request.bodyToFlux(PartEvent.class), - (intent, content) -> - uploadOne(intent, content, context) - .map(view -> BatchUploadItemResult.accepted(intent.originalFilename(), view)) - .onErrorResume( - FileserverException.class, - failure -> - Mono.just( - BatchUploadItemResult.rejected( - intent.originalFilename(), failure.code())))) - .collectList() - .flatMap( - results -> - ServerResponse.ok() - .contentType(MediaType.APPLICATION_JSON) - .bodyValue(new BatchUploadResponse(List.copyOf(results)))); - } - - private Mono uploadOne( - UploadIntent intent, Flux content, RequestContext context) { - return uploadService.upload( - createRequest(intent), - content, - declaredLength(intent), - new FinalizeUploadRequest(intent.expectedSha256(), false), - context); - } - - private CreateUploadRequest createRequest(UploadIntent intent) { - return new CreateUploadRequest( - properties.defaultNamespace(), - intent.originalFilename(), - intent.claimedMediaType(), - intent.declaredLength(), - intent.expectedSha256(), - UploadMode.SINGLE_SHOT, - clock.instant().plus(properties.uploadTtl())); - } - - /** READY is a finished object; anything still under verification is accepted, not created. */ - private static Mono created(FileView view) { - HttpStatus status = view.state() == FileState.READY ? HttpStatus.CREATED : HttpStatus.ACCEPTED; - return ServerResponse.status(status) - .location(URI.create("/v1/files/" + view.fileId().canonicalText())) - .contentType(MediaType.APPLICATION_JSON) - .bodyValue(UploadedFileResponse.from(view)); - } - - private static UploadIntent rawIntent(ServerRequest request) { - HttpHeaders headers = request.headers().asHttpHeaders(); - String filename = headers.getFirst(RawUploadRequestMapper.FILENAME_HEADER); - String digest = headers.getFirst(RawUploadRequestMapper.DIGEST_HEADER); - long declared = headers.getContentLength(); - return new UploadIntent( - filename == null || filename.isBlank() ? "upload.bin" : filename, - Optional.ofNullable(headers.getContentType()).map(Object::toString), - declared < 0 ? OptionalLong.empty() : OptionalLong.of(declared), - Optional.ofNullable(digest).map(value -> value.trim().toLowerCase(Locale.ROOT))); - } - - /** - * Context for one reactive request. - * - *

The reactive stack has no thread-bound security context, so the attribute the router filter - * publishes is the only correct source here. - */ - private static RequestContext contextOf(ServerRequest request) { - return request - .attribute(ReactiveFileserverAttributes.REQUEST_CONTEXT) - .filter(RequestContext.class::isInstance) - .map(RequestContext.class::cast) - .orElseThrow( - () -> new IllegalStateException("fileserver request context attribute is missing")); - } - - private static long declaredLength(UploadIntent intent) { - return intent.declaredLength().isPresent() ? intent.declaredLength().getAsLong() : -1; - } -} diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/reactive/FileserverIoScheduler.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/reactive/FileserverIoScheduler.java deleted file mode 100644 index 3f0512a9..00000000 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/reactive/FileserverIoScheduler.java +++ /dev/null @@ -1,36 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.fileserver.reactive; - -import reactor.core.scheduler.Scheduler; -import reactor.core.scheduler.Schedulers; - -/** - * The only place reactive Fileserver work is allowed to block. - * - *

The local content store is a blocking filesystem client. Running it on a Reactor Netty event - * loop would stall every other connection the loop owns, so all of it is offloaded here — a bounded - * pool with a bounded queue, which turns a filesystem stall into backpressure instead of an - * unbounded thread or task pile-up. - */ -public final class FileserverIoScheduler implements AutoCloseable { - - private static final int TTL_SECONDS = 60; - - private final Scheduler scheduler; - - public FileserverIoScheduler(int workers, int queueCapacity) { - if (workers < 1 || queueCapacity < 1) { - throw new IllegalArgumentException("workers and queueCapacity must be positive"); - } - this.scheduler = - Schedulers.newBoundedElastic(workers, queueCapacity, "fileserver-io", TTL_SECONDS, false); - } - - public Scheduler scheduler() { - return scheduler; - } - - @Override - public void close() { - scheduler.dispose(); - } -} diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/reactive/FileserverReactiveConfiguration.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/reactive/FileserverReactiveConfiguration.java deleted file mode 100644 index a2b8d686..00000000 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/reactive/FileserverReactiveConfiguration.java +++ /dev/null @@ -1,110 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.fileserver.reactive; - -import dev.caskeleton.adapter.inbound.web.fileserver.config.FileserverWebProperties; -import dev.caskeleton.adapter.inbound.web.fileserver.config.TransferExecutorProperties; -import dev.caskeleton.adapter.inbound.web.fileserver.http.HttpDownloadPlanner; -import dev.caskeleton.adapter.inbound.web.fileserver.problem.FileserverProblemFactory; -import dev.caskeleton.adapter.inbound.web.fileserver.security.FileserverRequestContextFactory; -import dev.caskeleton.application.fileserver.download.DownloadApplicationService; -import dev.caskeleton.application.fileserver.upload.SingleShotUploadService; -import java.time.Clock; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.reactive.function.server.RouterFunction; -import org.springframework.web.reactive.function.server.ServerResponse; - -/** - * Registers the reactive transport so it exists at runtime, not only in the source tree. - * - *

The router, the handlers and the part reader were written and tested, and nothing ever built - * them: no bean, no route, no dispatcher entry. A deployment that switched the platform on got the - * servlet transport and a set of classes that were never instantiated, while the support matrix - * advertised WebFlux as a supported profile. - * - *

The wiring lives in this module rather than in the composition root because {@code - * spring-webflux} is an {@code implementation} dependency here and deliberately invisible to {@code - * app-bootstrap} — the root cannot name {@link RouterFunction} at all, which is the mechanical - * reason the wiring was never written in the first place. - * - *

It stays inert in the shipped composition. This module also puts {@code DispatcherServlet} on - * the classpath, so Boot's application-type deduction resolves SERVLET and the condition below is - * false; a fork that removes the servlet stack and adds a reactive server gets working routes - * without touching this class. That is the honest support level, and the matrix says {@code - * Experimental} for exactly this reason. - */ -@Configuration(proxyBeanMethods = false) -@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE) -@ConditionalOnProperty(prefix = "app.fileserver-platform", name = "enabled", havingValue = "true") -public class FileserverReactiveConfiguration { - - /** - * Blocking storage work never runs on the event loop. - * - *

Bounded by the same transfer settings the servlet pool uses: an unbounded elastic scheduler - * would trade an event-loop stall for an unbounded thread count, which is the worse of the two. - */ - @Bean(destroyMethod = "close") - @ConditionalOnMissingBean - public FileserverIoScheduler fileserverIoScheduler(TransferExecutorProperties properties) { - return new FileserverIoScheduler(properties.maxSize(), properties.queueCapacity()); - } - - @Bean - @ConditionalOnMissingBean - public PartEventUploadReader fileserverPartEventUploadReader(FileserverWebProperties properties) { - return new PartEventUploadReader(properties.maxBatchParts()); - } - - @Bean - @ConditionalOnMissingBean - public ReactiveUploadApplicationService fileserverReactiveUploadService( - SingleShotUploadService uploadService, FileserverIoScheduler ioScheduler) { - return new ReactiveUploadApplicationService(uploadService, ioScheduler); - } - - @Bean - @ConditionalOnMissingBean - public ReactiveDownloadResponseWriter fileserverReactiveDownloadResponseWriter() { - return new ReactiveDownloadResponseWriter(); - } - - @Bean - @ConditionalOnMissingBean - public FileUploadHandler fileserverReactiveUploadHandler( - ReactiveUploadApplicationService uploadService, - PartEventUploadReader partReader, - FileserverWebProperties properties, - Clock clock) { - return new FileUploadHandler(uploadService, partReader, properties, clock); - } - - @Bean - @ConditionalOnMissingBean - public FileDownloadHandler fileserverReactiveDownloadHandler( - DownloadApplicationService downloadService, - ReactiveDownloadResponseWriter responseWriter, - HttpDownloadPlanner downloadPlanner, - FileserverIoScheduler ioScheduler) { - return new FileDownloadHandler(downloadService, responseWriter, downloadPlanner, ioScheduler); - } - - /** - * The routes themselves. - * - *

A {@link RouterFunction} bean is how WebFlux discovers routes; the factory existed but - * nothing ever called {@code routes()} on it. - */ - @Bean - public RouterFunction fileserverRoutes( - FileUploadHandler uploadHandler, - FileDownloadHandler downloadHandler, - FileserverProblemFactory problemFactory, - FileserverRequestContextFactory contextFactory) { - return new FileserverRouterFactory( - uploadHandler, downloadHandler, problemFactory, contextFactory::current) - .routes(); - } -} diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/reactive/FileserverRouterFactory.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/reactive/FileserverRouterFactory.java deleted file mode 100644 index f822e52c..00000000 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/reactive/FileserverRouterFactory.java +++ /dev/null @@ -1,75 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.fileserver.reactive; - -import dev.caskeleton.adapter.inbound.web.fileserver.problem.FileserverProblem; -import dev.caskeleton.adapter.inbound.web.fileserver.problem.FileserverProblemFactory; -import dev.caskeleton.adapter.inbound.web.fileserver.problem.FileserverProblemHeaders; -import dev.caskeleton.application.fileserver.api.error.FileserverException; -import dev.caskeleton.application.fileserver.api.security.RequestContext; -import java.util.function.Supplier; -import org.springframework.http.MediaType; -import org.springframework.web.reactive.function.server.RequestPredicates; -import org.springframework.web.reactive.function.server.RouterFunction; -import org.springframework.web.reactive.function.server.RouterFunctions; -import org.springframework.web.reactive.function.server.ServerResponse; -import reactor.core.publisher.Mono; - -/** - * Wires the reactive Fileserver routes and their failure translation. - * - *

The colon-verb paths are declared literally rather than nested under a prefix: {@code - * /v1/files:raw} is one path segment, and a nested route would silently turn it into {@code - * /v1/files/:raw}. - * - *

The failure filter lives here rather than in a global handler so the reactive routes translate - * Fileserver failures to exactly the same statuses and problem documents as the servlet advice. - */ -public final class FileserverRouterFactory { - - private final FileUploadHandler uploadHandler; - private final FileDownloadHandler downloadHandler; - private final FileserverProblemFactory problemFactory; - private final Supplier contextSupplier; - - public FileserverRouterFactory( - FileUploadHandler uploadHandler, - FileDownloadHandler downloadHandler, - FileserverProblemFactory problemFactory, - Supplier contextSupplier) { - this.uploadHandler = uploadHandler; - this.downloadHandler = downloadHandler; - this.problemFactory = problemFactory; - this.contextSupplier = contextSupplier; - } - - public RouterFunction routes() { - return RouterFunctions.route() - .POST("/v1/files:raw", uploadHandler::uploadRaw) - .POST("/v1/files:batch", uploadHandler::uploadBatch) - .POST("/v1/files", uploadHandler::uploadMultipart) - .GET("/v1/files/{fileId}/content", downloadHandler::download) - .route(RequestPredicates.HEAD("/v1/files/{fileId}/content"), downloadHandler::download) - .GET("/v1/files/{fileId}", downloadHandler::describe) - .before( - request -> { - request - .attributes() - .put(ReactiveFileserverAttributes.REQUEST_CONTEXT, contextSupplier.get()); - return request; - }) - .onError(FileserverException.class, this::toProblem) - .build(); - } - - private Mono toProblem( - Throwable throwable, org.springframework.web.reactive.function.server.ServerRequest request) { - FileserverException failure = (FileserverException) throwable; - FileserverProblem problem = - problemFactory.create(failure.context(), request.requestPath().value()); - ServerResponse.BodyBuilder builder = - ServerResponse.status(problem.status()).contentType(MediaType.APPLICATION_PROBLEM_JSON); - // Same table the servlet advice uses. Retry-After was missing here, so an identical failure - // told a servlet client to come back in a second and a reactive client nothing at all. - FileserverProblemHeaders.of(failure).forEach(builder::header); - return builder.bodyValue(problem); - } -} diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/reactive/PartEventUploadReader.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/reactive/PartEventUploadReader.java deleted file mode 100644 index 26ad0b57..00000000 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/reactive/PartEventUploadReader.java +++ /dev/null @@ -1,93 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.fileserver.reactive; - -import dev.caskeleton.adapter.inbound.web.fileserver.mapper.UploadIntent; -import dev.caskeleton.application.fileserver.api.error.FileTooLargeException; -import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode; -import dev.caskeleton.application.fileserver.api.error.FileserverFailureContext; -import java.util.Optional; -import java.util.OptionalLong; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.BiFunction; -import org.springframework.core.io.buffer.DataBuffer; -import org.springframework.core.io.buffer.DataBufferUtils; -import org.springframework.http.codec.multipart.FilePartEvent; -import org.springframework.http.codec.multipart.PartEvent; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; - -/** - * Reads a multipart body as a sequence of part events, one part at a time. - * - *

Sequential windowing is the contract, not an implementation detail: part events arrive on one - * stream, so consuming two windows concurrently would interleave the bytes of different files. The - * part-count ceiling is enforced as windows arrive, so an oversized batch is rejected before the - * remaining parts are read rather than after. - * - *

A non-file part is drained and released rather than ignored — an ignored window would leave - * its pooled buffers unreferenced and unreleased. - */ -public final class PartEventUploadReader { - - private static final String FALLBACK_FILENAME = "upload.bin"; - - private final int maxParts; - - public PartEventUploadReader(int maxParts) { - if (maxParts < 1) { - throw new IllegalArgumentException("maxParts must be positive"); - } - this.maxParts = maxParts; - } - - /** - * Applies {@code handler} to each file part, in order. - * - *

{@code concatMap} rather than {@code flatMap} is required: it subscribes to the next window - * only after the previous one terminates, which is what keeps parts from interleaving. - */ - public Flux forEachPart( - Flux events, BiFunction, Mono> handler) { - AtomicInteger seen = new AtomicInteger(); - return events - .windowUntil(PartEvent::isLast) - .concatMap( - window -> - window.switchOnFirst((signal, rest) -> onePart(signal.get(), rest, seen, handler))); - } - - private Flux onePart( - PartEvent first, - Flux rest, - AtomicInteger seen, - BiFunction, Mono> handler) { - if (first == null) { - return Flux.empty(); - } - if (seen.incrementAndGet() > maxParts) { - return drain(rest).thenMany(Flux.error(tooManyParts())); - } - if (!(first instanceof FilePartEvent filePart)) { - return drain(rest).thenMany(Flux.empty()); - } - return handler.apply(intentOf(filePart), rest.map(PartEvent::content)).flux(); - } - - private static Mono drain(Flux events) { - return events.doOnNext(event -> DataBufferUtils.release(event.content())).then(); - } - - private static UploadIntent intentOf(FilePartEvent part) { - String filename = part.filename(); - return new UploadIntent( - filename == null || filename.isBlank() ? FALLBACK_FILENAME : filename, - Optional.ofNullable(part.headers().getContentType()).map(Object::toString), - OptionalLong.empty(), - Optional.empty()); - } - - private static FileTooLargeException tooManyParts() { - return new FileTooLargeException( - "batch exceeds the configured maximum part count", - FileserverFailureContext.of(FileserverErrorCode.FILE_TOO_LARGE, false)); - } -} diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/reactive/ReactiveDownloadResponseWriter.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/reactive/ReactiveDownloadResponseWriter.java deleted file mode 100644 index 54e62a51..00000000 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/reactive/ReactiveDownloadResponseWriter.java +++ /dev/null @@ -1,48 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.fileserver.reactive; - -import dev.caskeleton.adapter.inbound.web.fileserver.http.HttpDownloadDecision; -import dev.caskeleton.adapter.inbound.web.fileserver.http.HttpDownloadOutcome; -import dev.caskeleton.application.fileserver.api.ByteRange; -import java.time.ZoneOffset; -import java.time.ZonedDateTime; -import java.time.format.DateTimeFormatter; -import org.springframework.http.HttpHeaders; - -/** Renders the shared HTTP download decision as WebFlux headers. */ -public final class ReactiveDownloadResponseWriter { - - public static final String CONTENT_TYPE_OPTIONS = "X-Content-Type-Options"; - private static final DateTimeFormatter HTTP_DATE = - DateTimeFormatter.RFC_1123_DATE_TIME.withZone(ZoneOffset.UTC); - - public HttpHeaders headersFor(HttpDownloadDecision decision) { - HttpHeaders headers = new HttpHeaders(); - headers.set(HttpHeaders.ETAG, decision.strongEtag()); - headers.set( - HttpHeaders.LAST_MODIFIED, - HTTP_DATE.format( - ZonedDateTime.ofInstant( - decision.descriptor().representation().publishedAt(), ZoneOffset.UTC))); - headers.set(HttpHeaders.ACCEPT_RANGES, "bytes"); - headers.set(HttpHeaders.CACHE_CONTROL, decision.cacheControl()); - headers.set(CONTENT_TYPE_OPTIONS, "nosniff"); - if (decision.outcome() == HttpDownloadOutcome.NOT_MODIFIED) { - return headers; - } - headers.set(HttpHeaders.CONTENT_TYPE, decision.descriptor().representation().mediaType()); - headers.set(HttpHeaders.CONTENT_DISPOSITION, decision.contentDisposition()); - headers.set(HttpHeaders.CONTENT_LENGTH, String.valueOf(decision.payloadLength())); - if (decision.isPartial()) { - ByteRange range = decision.singleRange(); - headers.set( - HttpHeaders.CONTENT_RANGE, - "bytes " - + range.startInclusive() - + "-" - + range.endInclusive() - + "/" - + decision.descriptor().representation().length()); - } - return headers; - } -} diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/reactive/ReactiveFileserverAttributes.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/reactive/ReactiveFileserverAttributes.java deleted file mode 100644 index 69b119fa..00000000 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/reactive/ReactiveFileserverAttributes.java +++ /dev/null @@ -1,19 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.fileserver.reactive; - -/** - * Names of the request attributes the reactive Fileserver routes rely on. - * - *

The reactive stack carries no thread-bound security context, so the caller identity has to - * travel with the exchange rather than through a holder. - */ -public final class ReactiveFileserverAttributes { - - /** - * Attribute holding the resolved {@code RequestContext}. - * - *

Published by the router filter, consumed by the handlers. - */ - public static final String REQUEST_CONTEXT = "dev.caskeleton.fileserver.reactive.requestContext"; - - private ReactiveFileserverAttributes() {} -} diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/reactive/ReactiveUploadApplicationService.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/reactive/ReactiveUploadApplicationService.java deleted file mode 100644 index 7f4caf1f..00000000 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/reactive/ReactiveUploadApplicationService.java +++ /dev/null @@ -1,58 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.fileserver.reactive; - -import dev.caskeleton.application.fileserver.api.security.RequestContext; -import dev.caskeleton.application.fileserver.upload.CreateUploadRequest; -import dev.caskeleton.application.fileserver.upload.FileView; -import dev.caskeleton.application.fileserver.upload.FinalizeUploadRequest; -import dev.caskeleton.application.fileserver.upload.SingleShotUploadService; -import java.io.IOException; -import java.io.UncheckedIOException; -import java.nio.channels.ReadableByteChannel; -import org.springframework.core.io.buffer.DataBuffer; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; - -/** - * Runs the blocking single-shot upload against a reactive body. - * - *

The whole body is never joined. Instead the reactive stream is turned into a bounded blocking - * channel and the upload is scheduled on the dedicated I/O pool, so a multi-gigabyte upload costs a - * fixed number of in-flight buffers and never touches an event-loop thread. - */ -public final class ReactiveUploadApplicationService { - - /** In-flight buffer ceiling; also the initial reactive demand. */ - static final int PREFETCH_BUFFERS = 8; - - private final SingleShotUploadService uploadService; - private final FileserverIoScheduler ioScheduler; - - public ReactiveUploadApplicationService( - SingleShotUploadService uploadService, FileserverIoScheduler ioScheduler) { - this.uploadService = uploadService; - this.ioScheduler = ioScheduler; - } - - public Mono upload( - CreateUploadRequest request, - Flux body, - long contentLength, - FinalizeUploadRequest finalizeRequest, - RequestContext context) { - return Mono.fromCallable(() -> transfer(request, body, contentLength, finalizeRequest, context)) - .subscribeOn(ioScheduler.scheduler()); - } - - private FileView transfer( - CreateUploadRequest request, - Flux body, - long contentLength, - FinalizeUploadRequest finalizeRequest, - RequestContext context) { - try (ReadableByteChannel channel = DataBufferByteChannel.subscribeTo(body, PREFETCH_BUFFERS)) { - return uploadService.upload(request, channel, contentLength, finalizeRequest, context); - } catch (IOException exception) { - throw new UncheckedIOException(exception); - } - } -} diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/tus/TusChecksumVerifier.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/tus/TusChecksumVerifier.java deleted file mode 100644 index 6dfb8a02..00000000 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/tus/TusChecksumVerifier.java +++ /dev/null @@ -1,53 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.fileserver.tus; - -import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode; -import dev.caskeleton.application.fileserver.api.error.FileserverFailureContext; -import dev.caskeleton.application.fileserver.api.error.IntegrityMismatchException; -import dev.caskeleton.application.fileserver.api.error.MalformedRequestException; -import java.util.Base64; -import java.util.HexFormat; -import java.util.Locale; -import java.util.Set; - -/** - * Verifies a tus {@code Upload-Checksum} against the digest the server computed. - * - *

The client value is only ever compared with the server's own digest; it never replaces it. A - * checksum the server did not compute proves nothing, and accepting one would let a client declare - * corrupt bytes to be intact. - */ -public final class TusChecksumVerifier { - - private static final Set SUPPORTED = Set.of("sha256"); - - /** - * Compares a checksum header with the server digest. - * - * @param header the raw {@code algorithm base64value} pair - * @param serverDigestHex the lowercase hex digest the server computed over the same bytes - */ - public void verify(String header, String serverDigestHex) { - String[] parts = header.trim().split(" ", 2); - if (parts.length != 2) { - throw MalformedRequestException.of("Upload-Checksum must be an algorithm and a base64 value"); - } - String algorithm = parts[0].toLowerCase(Locale.ROOT); - if (!SUPPORTED.contains(algorithm)) { - throw MalformedRequestException.of("unsupported checksum algorithm"); - } - byte[] claimed; - try { - claimed = Base64.getDecoder().decode(parts[1].trim()); - } catch (IllegalArgumentException malformed) { - throw new MalformedRequestException( - "Upload-Checksum value is not valid base64", - malformed, - FileserverFailureContext.of(FileserverErrorCode.BAD_REQUEST, false)); - } - if (!HexFormat.of().formatHex(claimed).equals(serverDigestHex)) { - throw new IntegrityMismatchException( - "client checksum does not match the server-computed digest", - FileserverFailureContext.of(FileserverErrorCode.INTEGRITY_MISMATCH, false)); - } - } -} diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/tus/TusController.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/tus/TusController.java index 2f9e601c..3f828295 100644 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/tus/TusController.java +++ b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/tus/TusController.java @@ -59,7 +59,6 @@ public class TusController { private final UploadApplicationService uploadService; private final FinalizeUploadService finalizeService; private final TusRequestParser parser; - private final TusChecksumVerifier checksumVerifier; private final FileserverRequestContextFactory contextFactory; private final BlockingTransferExecutor transferExecutor; private final FileserverWebProperties webProperties; @@ -70,7 +69,6 @@ public class TusController { UploadApplicationService uploadService, FinalizeUploadService finalizeService, TusRequestParser parser, - TusChecksumVerifier checksumVerifier, FileserverRequestContextFactory contextFactory, BlockingTransferExecutor transferExecutor, FileserverWebProperties webProperties, @@ -79,7 +77,6 @@ public class TusController { this.uploadService = uploadService; this.finalizeService = finalizeService; this.parser = parser; - this.checksumVerifier = checksumVerifier; this.contextFactory = contextFactory; this.transferExecutor = transferExecutor; this.webProperties = webProperties; @@ -160,6 +157,7 @@ public class TusController { UploadId id = UploadId.parse(uploadId); long expectedOffset = parser.requiredOffset(request); + Optional expectedChunkSha256 = parser.expectedChunkSha256(request); RequestContext context = contextFactory.current(); InputStream body = request.getInputStream(); long declared = request.getContentLengthLong(); @@ -168,10 +166,12 @@ public class TusController { transferExecutor.call( () -> uploadService.append( - id, expectedOffset, Channels.newChannel(body), declared, context)); - parser - .checksum(request) - .ifPresent(header -> checksumVerifier.verify(header, appended.sha256Snapshot())); + id, + expectedOffset, + Channels.newChannel(body), + declared, + expectedChunkSha256, + context)); UploadSessionView session = uploadService.status(id, context); if (isComplete(session, appended)) { diff --git a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/tus/TusRequestParser.java b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/tus/TusRequestParser.java index 98385b93..eede3df8 100644 --- a/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/tus/TusRequestParser.java +++ b/src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/tus/TusRequestParser.java @@ -8,6 +8,7 @@ import dev.caskeleton.application.fileserver.api.error.UnsupportedMediaTypeExcep import jakarta.servlet.http.HttpServletRequest; import java.nio.charset.StandardCharsets; import java.util.Base64; +import java.util.HexFormat; import java.util.LinkedHashMap; import java.util.Locale; import java.util.Map; @@ -27,6 +28,7 @@ import java.util.OptionalLong; public final class TusRequestParser { private static final String FILENAME_KEY = "filename"; + private static final String SHA256 = "sha256"; private final TusProperties properties; @@ -117,10 +119,33 @@ public final class TusRequestParser { return decoded; } - /** {@code Upload-Checksum} as {@code algorithm base64value}, when present. */ - public Optional checksum(HttpServletRequest request) { + /** + * Hex SHA-256 the client asserted for this request's bytes, from {@code Upload-Checksum}. + * + *

Only parsed here, before the body is read. The comparison happens where the bytes are + * written, against the server's digest of this request alone, so a mismatch is rolled back before + * the offset commits; the client value never replaces the server's digest. + */ + public Optional expectedChunkSha256(HttpServletRequest request) { String header = request.getHeader(TusHeaders.UPLOAD_CHECKSUM); - return header == null || header.isBlank() ? Optional.empty() : Optional.of(header.trim()); + if (header == null || header.isBlank()) { + return Optional.empty(); + } + String[] parts = header.trim().split(" ", 2); + if (parts.length != 2) { + throw MalformedRequestException.of("Upload-Checksum must be an algorithm and a base64 value"); + } + if (!SHA256.equals(parts[0].toLowerCase(Locale.ROOT))) { + throw MalformedRequestException.of("unsupported checksum algorithm"); + } + try { + return Optional.of(HexFormat.of().formatHex(Base64.getDecoder().decode(parts[1].trim()))); + } catch (IllegalArgumentException malformed) { + throw new MalformedRequestException( + "Upload-Checksum value is not valid base64", + malformed, + FileserverFailureContext.of(FileserverErrorCode.BAD_REQUEST, false)); + } } private static long parseNonNegative(String raw) { diff --git a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/http/ZeroCopyEligibilityTest.java b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/http/ZeroCopyEligibilityTest.java index 7edac704..6a5c844c 100644 --- a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/http/ZeroCopyEligibilityTest.java +++ b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/http/ZeroCopyEligibilityTest.java @@ -3,7 +3,6 @@ package dev.caskeleton.adapter.inbound.web.fileserver.http; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; -import org.springframework.mock.http.server.reactive.MockServerHttpResponse; class ZeroCopyEligibilityTest { @@ -33,12 +32,4 @@ class ZeroCopyEligibilityTest { void theDisabledProfileNeverTakesTheOptimization() { assertThat(ZeroCopyEligibility.disabled().isEligible(true, Long.MAX_VALUE, false)).isFalse(); } - - @Test - void theCapabilityProbeReadsTheResponseImplementation() { - assertThat(ZeroCopyEligibility.supportsZeroCopy(new MockServerHttpResponse())) - .isEqualTo( - new MockServerHttpResponse() - instanceof org.springframework.http.ZeroCopyHttpOutputMessage); - } } diff --git a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/problem/FileserverProblemHeaderParityTest.java b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/problem/FileserverProblemHeaderParityTest.java index 05ec0556..c801ef2f 100644 --- a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/problem/FileserverProblemHeaderParityTest.java +++ b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/problem/FileserverProblemHeaderParityTest.java @@ -11,12 +11,12 @@ import java.util.Map; import org.junit.jupiter.api.Test; /** - * The response contract must not depend on which transport happened to serve the request. + * The failure headers come from one table, {@link FileserverProblemHeaders}. * - *

The servlet advice owned a {@code Retry-After} table and the reactive router had none, so the - * same rejection told one client to come back in a second and the other nothing at all. A client - * that cannot tell a temporary refusal from a permanent one either retries immediately — turning a - * saturation signal into a stampede — or abandons work that would have succeeded. + *

A private {@code Retry-After} table in a handler is how two paths once told the same rejection + * different things. A client that cannot tell a temporary refusal from a permanent one either + * retries immediately — turning a saturation signal into a stampede — or abandons work that would + * have succeeded. */ class FileserverProblemHeaderParityTest { @@ -57,23 +57,11 @@ class FileserverProblemHeaderParityTest { assertThat(headers).containsEntry("Content-Range", "bytes */4096"); } - /** - * Both transports read this one table, which is what makes parity structural. - * - *

Asserting that the servlet advice and the reactive router each emit the same headers would - * need two running servers; asserting that neither of them owns a table is cheaper and catches - * the reintroduction of a private copy, which is how the drift happened the first time. - */ + /** The servlet advice reads the shared table rather than keeping its own copy. */ @Test - void neitherTransportKeepsItsOwnRetryAfterTable() throws Exception { + void theAdviceKeepsNoRetryAfterTableOfItsOwn() { assertThat(declaredFieldNames(FileserverExceptionHandler.class)) .noneMatch(name -> name.toUpperCase(java.util.Locale.ROOT).contains("RETRY")); - assertThat( - declaredFieldNames( - Class.forName( - "dev.caskeleton.adapter.inbound.web.fileserver.reactive" - + ".FileserverRouterFactory"))) - .noneMatch(name -> name.toUpperCase(java.util.Locale.ROOT).contains("RETRY")); } private static java.util.List declaredFieldNames(Class type) { diff --git a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/reactive/DataBufferReleaseTest.java b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/reactive/DataBufferReleaseTest.java deleted file mode 100644 index 59ba9b0f..00000000 --- a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/reactive/DataBufferReleaseTest.java +++ /dev/null @@ -1,93 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.fileserver.reactive; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.web.fileserver.testkit.CountingDataBufferFactory; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.channels.ReadableByteChannel; -import java.nio.charset.StandardCharsets; -import java.util.concurrent.atomic.AtomicLong; -import org.junit.jupiter.api.Test; -import org.springframework.core.io.buffer.DataBuffer; -import reactor.core.publisher.Flux; - -class DataBufferReleaseTest { - - private final CountingDataBufferFactory buffers = new CountingDataBufferFactory(); - - @Test - void everyObservedBufferIsReleasedOnceTheBodyIsFullyRead() throws Exception { - ReadableByteChannel channel = - DataBufferByteChannel.subscribeTo(Flux.just(buffers.wrap("abc"), buffers.wrap("def")), 8); - - assertThat(drain(channel)).isEqualTo("abcdef"); - assertThat(buffers.releasedCount()).isEqualTo(buffers.allocatedCount()); - } - - @Test - void closingEarlyStillLeavesNoBufferRetained() throws Exception { - ReadableByteChannel channel = - DataBufferByteChannel.subscribeTo( - Flux.just(buffers.wrap("abc"), buffers.wrap("def"), buffers.wrap("ghi")), 8); - - ByteBuffer first = ByteBuffer.allocate(3); - channel.read(first); - channel.close(); - - assertThat(buffers.releasedCount()).isEqualTo(buffers.allocatedCount()); - } - - @Test - void anUpstreamFailureSurfacesAsAnIoFailureRatherThanASilentTruncation() { - ReadableByteChannel channel = - DataBufferByteChannel.subscribeTo( - Flux.concat( - Flux.just(buffers.wrap("abc")), - Flux.error(new IllegalStateException("connection reset"))), - 8); - - assertThatThrownBy(() -> drain(channel)) - .isInstanceOf(IOException.class) - .hasMessageContaining("request body failed"); - } - - @Test - void inFlightBuffersNeverExceedThePrefetch() throws Exception { - AtomicLong maxOutstanding = new AtomicLong(); - AtomicLong outstanding = new AtomicLong(); - Flux body = - Flux.range(0, 64) - .map(index -> buffers.wrap("chunk" + index)) - .doOnNext( - buffer -> maxOutstanding.accumulateAndGet(outstanding.incrementAndGet(), Math::max)) - .doOnNext(buffer -> outstanding.decrementAndGet()); - - ReadableByteChannel channel = DataBufferByteChannel.subscribeTo(body, 4); - drain(channel); - - assertThat(maxOutstanding.get()).isLessThanOrEqualTo(4); - } - - @Test - void aClosedChannelRefusesFurtherReads() throws Exception { - ReadableByteChannel channel = - DataBufferByteChannel.subscribeTo(Flux.just(buffers.wrap("abc")), 8); - channel.close(); - - assertThat(channel.isOpen()).isFalse(); - assertThatThrownBy(() -> channel.read(ByteBuffer.allocate(3))).isInstanceOf(IOException.class); - } - - private static String drain(ReadableByteChannel channel) throws IOException { - ByteBuffer buffer = ByteBuffer.allocate(64); - StringBuilder received = new StringBuilder(); - while (channel.read(buffer) >= 0) { - buffer.flip(); - received.append(StandardCharsets.UTF_8.decode(buffer)); - buffer.clear(); - } - return received.toString(); - } -} diff --git a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/reactive/PartEventUploadReaderTest.java b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/reactive/PartEventUploadReaderTest.java deleted file mode 100644 index 5f903c9e..00000000 --- a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/reactive/PartEventUploadReaderTest.java +++ /dev/null @@ -1,90 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.fileserver.reactive; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.adapter.inbound.web.fileserver.testkit.CountingDataBufferFactory; -import dev.caskeleton.application.fileserver.api.error.FileTooLargeException; -import java.nio.charset.StandardCharsets; -import java.util.List; -import org.junit.jupiter.api.Test; -import org.springframework.core.io.buffer.DataBuffer; -import org.springframework.core.io.buffer.DataBufferUtils; -import org.springframework.http.MediaType; -import org.springframework.http.codec.multipart.FilePartEvent; -import org.springframework.http.codec.multipart.FormPartEvent; -import org.springframework.http.codec.multipart.PartEvent; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; -import reactor.test.StepVerifier; - -class PartEventUploadReaderTest { - - private final CountingDataBufferFactory buffers = new CountingDataBufferFactory(); - - @Test - void partsAreReadSequentiallyAndNeverInterleave() { - PartEventUploadReader reader = new PartEventUploadReader(16); - - List collected = - reader - .forEachPart( - Flux.concat(filePart("a.txt", "aaa"), filePart("b.txt", "bbb")), - (intent, content) -> - content - .map(PartEventUploadReaderTest::text) - .collectList() - .map(chunks -> intent.originalFilename() + "=" + String.join("", chunks))) - .collectList() - .block(); - - assertThat(collected).containsExactly("a.txt=aaa", "b.txt=bbb"); - } - - @Test - void anOversizedBatchIsRejectedAsSoonAsTheLimitIsCrossed() { - PartEventUploadReader reader = new PartEventUploadReader(1); - - StepVerifier.create( - reader.forEachPart( - Flux.concat(filePart("a.txt", "aaa"), filePart("b.txt", "bbb")), - (intent, content) -> release(content).then(Mono.just(intent.originalFilename())))) - .expectNext("a.txt") - .expectError(FileTooLargeException.class) - .verify(); - } - - @Test - void aNonFilePartIsDrainedRatherThanLeftUnreleased() { - PartEventUploadReader reader = new PartEventUploadReader(16); - - List collected = - reader - .forEachPart( - Flux.concat( - FormPartEvent.create("note", "hello").cast(PartEvent.class), - filePart("a.txt", "aaa")), - (intent, content) -> release(content).then(Mono.just(intent.originalFilename()))) - .collectList() - .block(); - - assertThat(collected).containsExactly("a.txt"); - assertThat(buffers.releasedCount()).isEqualTo(buffers.allocatedCount()); - } - - /** Drains and releases a part body, which is what a real handler's channel bridge does. */ - private static Mono release(Flux content) { - return content.doOnNext(DataBufferUtils::release).then(); - } - - private Flux filePart(String filename, String payload) { - DataBuffer buffer = buffers.wrap(payload); - return FilePartEvent.create("files", filename, MediaType.TEXT_PLAIN, Flux.just(buffer)) - .cast(PartEvent.class); - } - - private static String text(DataBuffer buffer) { - byte[] bytes = new byte[buffer.readableByteCount()]; - buffer.read(bytes); - return new String(bytes, StandardCharsets.UTF_8); - } -} diff --git a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/reactive/ReactiveFileserverContractTest.java b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/reactive/ReactiveFileserverContractTest.java deleted file mode 100644 index 905fd6a5..00000000 --- a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/reactive/ReactiveFileserverContractTest.java +++ /dev/null @@ -1,211 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.fileserver.reactive; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.adapter.inbound.web.fileserver.dto.UploadedFileResponse; -import dev.caskeleton.adapter.inbound.web.fileserver.mapper.RawUploadRequestMapper; -import dev.caskeleton.adapter.inbound.web.fileserver.problem.FileserverProblemFactory; -import dev.caskeleton.adapter.inbound.web.fileserver.testkit.CountingDataBufferFactory; -import dev.caskeleton.adapter.inbound.web.fileserver.testkit.FileserverWebFixtures; -import dev.caskeleton.adapter.inbound.web.fileserver.testkit.RecordingUploadService; -import dev.caskeleton.adapter.inbound.web.fileserver.testkit.StubDownloadService; -import dev.caskeleton.application.fileserver.api.FileState; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Test; -import org.springframework.core.io.buffer.DataBuffer; -import org.springframework.http.MediaType; -import org.springframework.test.web.reactive.server.WebTestClient; -import reactor.core.publisher.Flux; - -class ReactiveFileserverContractTest { - - private final CountingDataBufferFactory buffers = new CountingDataBufferFactory(); - private final RecordingUploadService uploadService = new RecordingUploadService(); - private final StubDownloadService downloadService = new StubDownloadService(); - private final FileserverIoScheduler ioScheduler = new FileserverIoScheduler(4, 32); - - private final WebTestClient client = WebTestClient.bindToRouterFunction(routes()).build(); - - @AfterEach - void closeScheduler() { - ioScheduler.close(); - } - - @Test - void rawUploadConsumesTheStreamWithoutJoiningTheWholeBody() { - client - .post() - .uri("/v1/files:raw") - .contentType(MediaType.APPLICATION_OCTET_STREAM) - .header(RawUploadRequestMapper.FILENAME_HEADER, "large.bin") - .body(Flux.just(buffers.wrap("abc"), buffers.wrap("def")), DataBuffer.class) - .exchange() - .expectStatus() - .isCreated() - .expectHeader() - .exists("Location") - .expectBody() - .jsonPath("$.state") - .isEqualTo("READY"); - - assertThat(uploadService.receivedBodies()).containsExactly("abcdef"); - assertThat(buffers.releasedCount()).isEqualTo(buffers.allocatedCount()); - } - - @Test - void aStillVerifyingUploadIsAcceptedRatherThanCreated() { - uploadService.answerWith(FileState.VERIFYING); - - client - .post() - .uri("/v1/files:raw") - .contentType(MediaType.APPLICATION_OCTET_STREAM) - .header(RawUploadRequestMapper.FILENAME_HEADER, "large.bin") - .body(Flux.just(buffers.wrap("abc")), DataBuffer.class) - .exchange() - .expectStatus() - .isAccepted(); - } - - @Test - void rangeHeadersMatchTheServletContract() { - client - .get() - .uri(contentUrl()) - .header("Range", "bytes=2-4") - .exchange() - .expectStatus() - .isEqualTo(206) - .expectHeader() - .valueEquals("Content-Range", "bytes 2-4/10") - .expectHeader() - .valueEquals("Content-Length", "3") - .expectHeader() - .valueEquals("Accept-Ranges", "bytes") - .expectBody(byte[].class) - .isEqualTo(new byte[] {2, 3, 4}); - } - - @Test - void aFullGetCarriesTheSameValidatorsAsTheServletPath() { - client - .get() - .uri(contentUrl()) - .exchange() - .expectStatus() - .isOk() - .expectHeader() - .valueEquals("ETag", downloadService.strongEtag()) - .expectHeader() - .valueEquals("Cache-Control", "private, no-store") - .expectBody(byte[].class) - .isEqualTo(new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}); - } - - @Test - void aMatchingValidatorIsNotModifiedAndOpensNothing() { - client - .get() - .uri(contentUrl()) - .header("If-None-Match", downloadService.strongEtag()) - .exchange() - .expectStatus() - .isNotModified(); - - assertThat(downloadService.neverOpened()).isTrue(); - } - - @Test - void anUnsatisfiableRangeIsAProblemDocumentCarryingTheRealLength() { - client - .get() - .uri(contentUrl()) - .header("Range", "bytes=50-60") - .exchange() - .expectStatus() - .isEqualTo(416) - .expectHeader() - .valueEquals("Content-Range", "bytes */10") - .expectHeader() - .contentType(MediaType.APPLICATION_PROBLEM_JSON); - } - - @Test - void aNonReadyFileIsAConflictProblemDocument() { - downloadService.fileInState(FileState.VERIFYING); - - client - .get() - .uri(contentUrl()) - .exchange() - .expectStatus() - .isEqualTo(409) - .expectBody() - .jsonPath("$.code") - .isEqualTo("FILE_NOT_READY"); - - assertThat(downloadService.neverOpened()).isTrue(); - } - - @Test - void headCarriesTheSameHeadersWithoutABody() { - byte[] body = - client - .head() - .uri(contentUrl()) - .exchange() - .expectStatus() - .isOk() - .expectHeader() - .valueEquals("ETag", downloadService.strongEtag()) - .expectHeader() - .valueEquals("Content-Length", "10") - .expectBody(byte[].class) - .returnResult() - .getResponseBody(); - - assertThat(body) - .satisfiesAnyOf(value -> assertThat(value).isNull(), value -> assertThat(value).isEmpty()); - } - - @Test - void theMetadataEndpointReportsTheDescriptor() { - client - .get() - .uri("/v1/files/" + StubDownloadService.anyFileId().canonicalText()) - .exchange() - .expectStatus() - .isOk() - .expectBody(UploadedFileResponse.class) - .value(response -> assertThat(response.state()).isEqualTo("READY")); - } - - private org.springframework.web.reactive.function.server.RouterFunction< - org.springframework.web.reactive.function.server.ServerResponse> - routes() { - ReactiveUploadApplicationService reactiveUpload = - new ReactiveUploadApplicationService(uploadService, ioScheduler); - FileUploadHandler uploadHandler = - new FileUploadHandler( - reactiveUpload, - new PartEventUploadReader(16), - FileserverWebFixtures.properties(), - FileserverWebFixtures.clock()); - FileDownloadHandler downloadHandler = - new FileDownloadHandler( - downloadService, - new ReactiveDownloadResponseWriter(), - downloadService.httpPlanner(), - ioScheduler); - return new FileserverRouterFactory( - uploadHandler, - downloadHandler, - new FileserverProblemFactory(), - () -> FileserverWebFixtures.requestContext()) - .routes(); - } - - private static String contentUrl() { - return "/v1/files/" + StubDownloadService.anyFileId().canonicalText() + "/content"; - } -} diff --git a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/testkit/InMemoryUploadApplicationService.java b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/testkit/InMemoryUploadApplicationService.java index 8463f38d..57ba5f60 100644 --- a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/testkit/InMemoryUploadApplicationService.java +++ b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/testkit/InMemoryUploadApplicationService.java @@ -5,6 +5,7 @@ import dev.caskeleton.application.fileserver.api.UploadId; import dev.caskeleton.application.fileserver.api.error.FileNotFoundException; import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode; import dev.caskeleton.application.fileserver.api.error.FileserverFailureContext; +import dev.caskeleton.application.fileserver.api.error.IntegrityMismatchException; import dev.caskeleton.application.fileserver.api.error.UploadExpiredException; import dev.caskeleton.application.fileserver.api.error.UploadOffsetMismatchException; import dev.caskeleton.application.fileserver.api.security.RequestContext; @@ -23,6 +24,7 @@ import java.security.NoSuchAlgorithmException; import java.util.HexFormat; import java.util.LinkedHashMap; import java.util.Map; +import java.util.Optional; import java.util.UUID; /** @@ -30,7 +32,8 @@ import java.util.UUID; * *

The protocol adapters are only worth testing against something that actually enforces the * offset rule, so this fake rejects a mismatched offset without mutating the buffer, exactly as the - * production service does. + * production service does. A chunk checksum is likewise compared with the digest of that chunk + * alone, and a mismatch is rejected before the bytes are kept. */ public final class InMemoryUploadApplicationService implements UploadApplicationService { @@ -67,14 +70,25 @@ public final class InMemoryUploadApplicationService implements UploadApplication long expectedOffset, ReadableByteChannel content, long contentLength, + Optional expectedChunkSha256, RequestContext context) { requireNotExpired(uploadId); Session session = require(uploadId); if (expectedOffset != session.buffer.size()) { throw UploadOffsetMismatchException.of(uploadId, expectedOffset, session.buffer.size()); } - long appended = drainInto(content, session.buffer); - return new AppendUploadResult(session.buffer.size(), appended, digestOf(session)); + ByteArrayOutputStream chunk = new ByteArrayOutputStream(); + long appended = drainInto(content, chunk); + if (expectedChunkSha256.isPresent() + && !sha256Hex(chunk.toByteArray()).equalsIgnoreCase(expectedChunkSha256.get())) { + throw new IntegrityMismatchException( + "chunk checksum mismatch", + FileserverFailureContext.forUpload( + FileserverErrorCode.CHECKSUM_MISMATCH, uploadId, false, false, false)); + } + session.buffer.writeBytes(chunk.toByteArray()); + return new AppendUploadResult( + session.buffer.size(), appended, sha256Hex(session.buffer.toByteArray())); } @Override @@ -114,10 +128,9 @@ public final class InMemoryUploadApplicationService implements UploadApplication return appended; } - private static String digestOf(Session session) { + private static String sha256Hex(byte[] bytes) { try { - return HexFormat.of() - .formatHex(MessageDigest.getInstance("SHA-256").digest(session.buffer.toByteArray())); + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); } catch (NoSuchAlgorithmException impossible) { throw new IllegalStateException("SHA-256 is required by the platform", impossible); } diff --git a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/tus/TusProtocolContractTest.java b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/tus/TusProtocolContractTest.java index 4e5f8aef..14acdc95 100644 --- a/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/tus/TusProtocolContractTest.java +++ b/src/adapter/inbound/web-fileserver/src/test/java/dev/caskeleton/adapter/inbound/web/fileserver/tus/TusProtocolContractTest.java @@ -20,8 +20,10 @@ import java.security.MessageDigest; import java.util.Base64; import java.util.HexFormat; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.setup.MockMvcBuilders; class TusProtocolContractTest { @@ -41,7 +43,6 @@ class TusProtocolContractTest { uploads, finalizeService, new TusRequestParser(TUS), - new TusChecksumVerifier(), FileserverWebFixtures.contextFactory(), FileserverWebFixtures.transferExecutor(), FileserverWebFixtures.properties(), @@ -146,26 +147,46 @@ class TusProtocolContractTest { } @Test - void aMatchingChecksumIsAcceptedAndAMismatchIsRejected() throws Exception { + void chunksCarryingTheirOwnCorrectChecksumAreAllAccepted() throws Exception { + // given String location = create(6); + appendWithChecksum(location, 0, "abc", base64Sha256("abc")).andExpect(status().isNoContent()); - mvc.perform( - patch(location) - .header(TusHeaders.RESUMABLE, "1.0.0") - .header(TusHeaders.UPLOAD_OFFSET, "0") - .header(TusHeaders.UPLOAD_CHECKSUM, "sha256 " + base64Sha256("abc")) - .contentType(TusHeaders.OFFSET_OCTET_STREAM) - .content("abc")) - .andExpect(status().isNoContent()); + // when + ResultActions second = appendWithChecksum(location, 3, "def", base64Sha256("def")); - mvc.perform( - patch(location) - .header(TusHeaders.RESUMABLE, "1.0.0") - .header(TusHeaders.UPLOAD_OFFSET, "3") - .header(TusHeaders.UPLOAD_CHECKSUM, "sha256 " + base64Sha256("wrong")) - .contentType(TusHeaders.OFFSET_OCTET_STREAM) - .content("def")) - .andExpect(status().is(422)); + // then + second + .andExpect(status().isNoContent()) + .andExpect(header().string(TusHeaders.UPLOAD_OFFSET, "6")); + } + + @Test + @DisplayName("a chunk whose Upload-Checksum does not match its own bytes answers 460") + void aChunkWhoseChecksumDoesNotMatchAnswersChecksumMismatch() throws Exception { + // given + String location = create(6); + appendAt(location, 0, "abc"); + + // when + ResultActions rejected = appendWithChecksum(location, 3, "def", base64Sha256("xyz")); + + // then + rejected.andExpect(status().is(460)); + } + + @Test + void aChunkRejectedForItsChecksumDoesNotAdvanceTheOffset() throws Exception { + // given + String location = create(6); + appendAt(location, 0, "abc"); + + // when + appendWithChecksum(location, 3, "def", base64Sha256("xyz")); + + // then + mvc.perform(head(location).header(TusHeaders.RESUMABLE, "1.0.0")) + .andExpect(header().string(TusHeaders.UPLOAD_OFFSET, "3")); } @Test @@ -234,6 +255,17 @@ class TusProtocolContractTest { .andExpect(status().isNoContent()); } + private ResultActions appendWithChecksum( + String location, long offset, String payload, String base64Digest) throws Exception { + return mvc.perform( + patch(location) + .header(TusHeaders.RESUMABLE, "1.0.0") + .header(TusHeaders.UPLOAD_OFFSET, String.valueOf(offset)) + .header(TusHeaders.UPLOAD_CHECKSUM, "sha256 " + base64Digest) + .contentType(TusHeaders.OFFSET_OCTET_STREAM) + .content(payload)); + } + private static UploadId uploadIdOf(String location) { return UploadId.parse(location.substring(location.lastIndexOf('/') + 1)); } diff --git a/src/adapter/inbound/web-notification/build.gradle b/src/adapter/inbound/web-notification/build.gradle new file mode 100644 index 00000000..dafbda8c --- /dev/null +++ b/src/adapter/inbound/web-notification/build.gradle @@ -0,0 +1,27 @@ +plugins { + id 'ca.spring-library' + id 'ca.spring-config' +} + +// The Notification capability's HTTP surface: submission, template publication and the provider +// callback endpoint. +// +// It was the `web.notification` package inside `adapter:inbound:web`, which is why every application +// with an HTTP API resolved `application-notification`. It depends on `adapter:inbound:web` rather +// than the reverse, the same shape as `adapter:inbound:web-fileserver`. The package keeps its name +// (`dev.caskeleton.adapter.inbound.web.notification`). +// +// Selected through `:composition:notification-platform`, never on its own: the callback endpoint +// needs the `ProviderCallbackIngress` bridge that composition provides. +dependencies { + implementation project(':adapter:inbound:web') + implementation project(':application-core') + implementation project(':application-notification') + implementation project(':shared-contract') + + implementation 'org.springframework.boot:spring-boot-starter-web' + implementation 'org.springframework.boot:spring-boot-starter-security' + implementation 'org.springframework.boot:spring-boot-starter-validation' + + testImplementation 'org.springframework.boot:spring-boot-starter-test' +} diff --git a/src/adapter/inbound/web-notification/gradle.lockfile b/src/adapter/inbound/web-notification/gradle.lockfile new file mode 100644 index 00000000..5d75c35b --- /dev/null +++ b/src/adapter/inbound/web-notification/gradle.lockfile @@ -0,0 +1,181 @@ +# 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. +biz.aQute.bnd:biz.aQute.bnd.annotation:7.1.0=compileClasspath,testCompileClasspath +ch.qos.logback:logback-classic:1.5.38=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +ch.qos.logback:logback-core:1.5.38=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +com.fasterxml.jackson.core:jackson-annotations:2.21=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +com.fasterxml.jackson.core:jackson-core:2.21.5=runtimeClasspath,testRuntimeClasspath +com.fasterxml.jackson.core:jackson-databind:2.21.5=runtimeClasspath,testRuntimeClasspath +com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:2.21.5=runtimeClasspath,testRuntimeClasspath +com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.21.5=runtimeClasspath,testRuntimeClasspath +com.fasterxml.jackson:jackson-bom:2.21.5=runtimeClasspath,testRuntimeClasspath +com.fasterxml:classmate:1.7.3=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,testAnnotationProcessor +com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,testAnnotationProcessor +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.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_annotations:2.38.0=compileClasspath,testCompileClasspath +com.google.errorprone:error_prone_annotations:2.41.0=spotbugs +com.google.errorprone:error_prone_annotations:2.47.0=checkstyle +com.google.errorprone:error_prone_annotations:2.49.0=annotationProcessor,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.5.0-jre=annotationProcessor,testAnnotationProcessor +com.google.guava:guava:33.6.0-jre=checkstyle +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.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins +com.jayway.jsonpath:json-path:2.10.0=testCompileClasspath,testRuntimeClasspath +com.nimbusds:nimbus-jose-jwt:10.4=runtimeClasspath,testRuntimeClasspath +com.puppycrawl.tools:checkstyle:13.5.0=checkstyle +com.vaadin.external.google:android-json:0.0.20131108.vaadin1=testCompileClasspath,testRuntimeClasspath +commons-beanutils:commons-beanutils:1.11.0=checkstyle +commons-collections:commons-collections:3.2.2=checkstyle +commons-io:commons-io:2.21.0=spotbugs +commons-logging:commons-logging:1.3.6=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +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 +io.micrometer:micrometer-commons:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +io.micrometer:micrometer-observation:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +io.swagger.core.v3:swagger-annotations-jakarta:2.2.38=runtimeClasspath,testRuntimeClasspath +io.swagger.core.v3:swagger-core-jakarta:2.2.38=runtimeClasspath,testRuntimeClasspath +io.swagger.core.v3:swagger-models-jakarta:2.2.38=runtimeClasspath,testRuntimeClasspath +jakarta.activation:jakarta.activation-api:2.1.4=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +jakarta.annotation:jakarta.annotation-api:3.0.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +jakarta.validation:jakarta.validation-api:3.1.1=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +jakarta.xml.bind:jakarta.xml.bind-api:4.0.5=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +javax.inject:javax.inject:1=annotationProcessor,testAnnotationProcessor +jaxen:jaxen:2.0.6=spotbugs +net.bytebuddy:byte-buddy-agent:1.17.8=testCompileClasspath,testRuntimeClasspath +net.bytebuddy:byte-buddy:1.17.8=testCompileClasspath,testRuntimeClasspath +net.minidev:accessors-smart:2.6.0=testCompileClasspath,testRuntimeClasspath +net.minidev:json-smart:2.6.0=testCompileClasspath,testRuntimeClasspath +net.sf.saxon:Saxon-HE:12.9=checkstyle,spotbugs +org.antlr:antlr4-runtime:4.13.2=checkstyle +org.apache.bcel:bcel:6.12.0=spotbugs +org.apache.commons:commons-lang3:3.20.0=checkstyle,runtimeClasspath,spotbugs,testRuntimeClasspath +org.apache.commons:commons-text:1.15.0=spotbugs +org.apache.commons:commons-text:1.3=checkstyle +org.apache.httpcomponents:httpclient:4.5.13=checkstyle +org.apache.httpcomponents:httpcore:4.4.16=checkstyle +org.apache.logging.log4j:log4j-api:2.25.5=compileClasspath,runtimeClasspath,spotbugs,testCompileClasspath,testRuntimeClasspath +org.apache.logging.log4j:log4j-core:2.25.5=spotbugs +org.apache.logging.log4j:log4j-to-slf4j:2.25.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.apache.maven.doxia:doxia-core:1.12.0=checkstyle +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.tomcat.embed:tomcat-embed-core:11.0.24=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.apache.tomcat.embed:tomcat-embed-el:11.0.24=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.apache.tomcat.embed:tomcat-embed-websocket:11.0.24=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.apache.xbean:xbean-reflect:3.7=checkstyle +org.apiguardian:apiguardian-api:1.1.2=testCompileClasspath +org.assertj:assertj-core:3.27.7=testCompileClasspath,testRuntimeClasspath +org.awaitility:awaitility:4.3.0=testCompileClasspath,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.3.0=checkstyle +org.dom4j:dom4j:2.2.0=spotbugs +org.hamcrest:hamcrest:3.0=testCompileClasspath,testRuntimeClasspath +org.hibernate.validator:hibernate-validator:9.0.1.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.javassist:javassist:3.28.0-GA=checkstyle +org.jboss.logging:jboss-logging:3.6.3.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,compileClasspath,runtimeClasspath,testAnnotationProcessor,testCompileClasspath,testRuntimeClasspath +org.junit.jupiter:junit-jupiter-api:6.0.3=testCompileClasspath,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-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.1.0=spotbugs +org.mockito:mockito-core:5.20.0=mockitoAgent,testCompileClasspath,testRuntimeClasspath +org.mockito:mockito-junit-jupiter:5.20.0=testCompileClasspath,testRuntimeClasspath +org.objenesis:objenesis:3.3=testRuntimeClasspath +org.openapitools:jackson-databind-nullable:0.2.6=runtimeClasspath,testRuntimeClasspath +org.opentest4j:opentest4j:1.3.0=testCompileClasspath,testRuntimeClasspath +org.osgi:org.osgi.annotation.bundle:2.0.0=compileClasspath,testCompileClasspath +org.osgi:org.osgi.annotation.versioning:1.1.2=compileClasspath,testCompileClasspath +org.osgi:org.osgi.resource:1.0.0=compileClasspath,testCompileClasspath +org.osgi:org.osgi.service.serviceloader:1.0.0=compileClasspath,testCompileClasspath +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.ow2.asm:asm:9.7.1=testCompileClasspath,testRuntimeClasspath +org.pcollections:pcollections:4.0.1=annotationProcessor,testAnnotationProcessor +org.reflections:reflections:0.10.2=checkstyle +org.skyscreamer:jsonassert:1.5.3=testCompileClasspath,testRuntimeClasspath +org.slf4j:jul-to-slf4j:2.0.18=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.slf4j:slf4j-api:2.0.18=compileClasspath,runtimeClasspath,spotbugs,spotbugsSlf4j,testCompileClasspath,testRuntimeClasspath +org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j +org.slf4j:slf4j-simple:2.0.18=checkstyle +org.springdoc:springdoc-openapi-starter-common:3.0.0=runtimeClasspath,testRuntimeClasspath +org.springdoc:springdoc-openapi-starter-webmvc-api:3.0.0=runtimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-autoconfigure:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-configuration-processor:4.0.8=annotationProcessor +org.springframework.boot:spring-boot-http-converter:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-jackson:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-resttestclient:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-security-oauth2-resource-server:4.0.8=runtimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-security:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-servlet:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-jackson-test:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-jackson:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-logging:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-oauth2-resource-server:4.0.8=runtimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-security:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-test:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-tomcat-runtime:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-tomcat:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-validation:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-web:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-webmvc-test:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-webmvc:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-test-autoconfigure:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-test:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-tomcat:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-validation:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-web-server:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-webmvc-test:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-webmvc:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.security:spring-security-config:7.0.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.security:spring-security-core:7.0.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.security:spring-security-crypto:7.0.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.security:spring-security-oauth2-core:7.0.7=runtimeClasspath,testRuntimeClasspath +org.springframework.security:spring-security-oauth2-jose:7.0.7=runtimeClasspath,testRuntimeClasspath +org.springframework.security:spring-security-oauth2-resource-server:7.0.7=runtimeClasspath,testRuntimeClasspath +org.springframework.security:spring-security-web:7.0.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.session:spring-session-core:4.0.5=runtimeClasspath,testRuntimeClasspath +org.springframework:spring-aop:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-beans:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-context:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-core:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-expression:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-test:7.0.9=testCompileClasspath,testRuntimeClasspath +org.springframework:spring-web:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-webmvc:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.xmlresolver:xmlresolver:5.3.3=checkstyle,spotbugs +org.xmlunit:xmlunit-core:2.10.4=testCompileClasspath,testRuntimeClasspath +org.yaml:snakeyaml:2.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +tools.jackson.core:jackson-core:3.1.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +tools.jackson.core:jackson-databind:3.1.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +tools.jackson:jackson-bom:3.1.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +empty= diff --git a/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/NotificationWebAutoConfiguration.java b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/NotificationWebAutoConfiguration.java new file mode 100644 index 00000000..a017b1fe --- /dev/null +++ b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/NotificationWebAutoConfiguration.java @@ -0,0 +1,35 @@ +package dev.caskeleton.adapter.inbound.web.notification; + +import dev.caskeleton.adapter.inbound.web.notification.platform.callback.CallbackMvcSecurityConfiguration; +import dev.caskeleton.adapter.inbound.web.notification.platform.callback.CallbackRequestConfiguration; +import dev.caskeleton.adapter.inbound.web.notification.platform.callback.NotificationCallbackMvcController; +import dev.caskeleton.adapter.inbound.web.notification.platform.submission.NotificationSubmissionController; +import dev.caskeleton.adapter.inbound.web.notification.platform.submission.NotificationTemplateController; +import org.springframework.boot.autoconfigure.AutoConfiguration; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; +import org.springframework.context.annotation.Import; + +/** + * The Notification HTTP surface, registered by this leaf rather than found by a component scan. + * + *

Gated by the platform capability switch as a whole. The callback endpoint used to carry only + * its own {@code callbacks.enabled} condition, so a deployment that turned callbacks on and the + * platform off got a controller whose ingress bean did not exist and a context that would not + * start. The callback classes keep their own switch underneath this one. + */ +@AutoConfiguration +@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) +@ConditionalOnProperty( + prefix = "ca-skeleton.notification.platform", + name = "enabled", + havingValue = "true", + matchIfMissing = true) +@Import({ + NotificationSubmissionController.class, + NotificationTemplateController.class, + CallbackRequestConfiguration.class, + CallbackMvcSecurityConfiguration.class, + NotificationCallbackMvcController.class +}) +public class NotificationWebAutoConfiguration {} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/CallbackMvcSecurityConfiguration.java b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/CallbackMvcSecurityConfiguration.java similarity index 100% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/CallbackMvcSecurityConfiguration.java rename to src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/CallbackMvcSecurityConfiguration.java diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/CallbackRequestConfiguration.java b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/CallbackRequestConfiguration.java similarity index 85% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/CallbackRequestConfiguration.java rename to src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/CallbackRequestConfiguration.java index d018e426..0d7e94a3 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/CallbackRequestConfiguration.java +++ b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/CallbackRequestConfiguration.java @@ -11,10 +11,9 @@ import org.springframework.context.annotation.Configuration; /** * The two beans the callback endpoints need, and neither of which existed. * - *

{@code NotificationCallbackMvcController}, {@code NotificationCallbackWebFluxHandler} and - * {@code CallbackWebFluxConfiguration} all take {@code CallbackRequestFactory} as a constructor - * argument, and it was produced nowhere in production code — the only instantiation in the - * repository was inside a test. So the documented, env-registered switch {@code + *

{@code NotificationCallbackMvcController} takes {@code CallbackRequestFactory} as a + * constructor argument, and it was produced nowhere in production code — the only instantiation in + * the repository was inside a test. So the documented, env-registered switch {@code * APP_NOTIFICATION_PLATFORM_CALLBACKS_ENABLED=true} did not enable callbacks; it made the * application fail to start on an unsatisfied dependency. An operator following the configuration * reference got a deployment that would not boot. @@ -50,7 +49,7 @@ public class CallbackRequestConfiguration { } /** - * Builds the canonical callback request both transports share. + * Builds the canonical callback request the controller verifies. * * @param urlResolver the external URL resolver * @param clock the clock timestamps are read from diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/CallbackRequestFactory.java b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/CallbackRequestFactory.java similarity index 71% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/CallbackRequestFactory.java rename to src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/CallbackRequestFactory.java index 9ec65cbe..e4c9a507 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/CallbackRequestFactory.java +++ b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/CallbackRequestFactory.java @@ -15,8 +15,7 @@ import java.util.Optional; /** * Builds the raw callback transport record owned by the inbound HTTP adapter. * - *

Both servlet and reactive endpoints use this so provider verification sees the same canonical - * bytes and URL regardless of which web stack received the call. + *

Provider verification sees the canonical bytes and the URL the provider actually called. */ public final class CallbackRequestFactory { @@ -51,24 +50,4 @@ public final class CallbackRequestFactory { body, clock.instant()); } - - /** Build from an already-resolved external URL, used by the reactive endpoint. */ - public ProviderCallbackHttpRequest create( - String provider, - String profile, - String externalUrl, - String method, - Optional contentType, - Map> headers, - byte[] body) { - return new ProviderCallbackHttpRequest( - new ProviderId(provider), - new ProviderProfileId(profile), - externalUrl, - method, - contentType, - headers, - body, - clock.instant()); - } } diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/ExternalRequestUrlResolver.java b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/ExternalRequestUrlResolver.java similarity index 100% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/ExternalRequestUrlResolver.java rename to src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/ExternalRequestUrlResolver.java diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/NotificationCallbackMvcController.java b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/NotificationCallbackMvcController.java similarity index 93% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/NotificationCallbackMvcController.java rename to src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/NotificationCallbackMvcController.java index f2d5c83e..6e9140c4 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/NotificationCallbackMvcController.java +++ b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/NotificationCallbackMvcController.java @@ -26,10 +26,7 @@ import org.springframework.web.bind.annotation.RestController; *

The response is a bare {@code 204}: no body, no diagnostics. A provider only needs to know the * event is recorded, and an error body would be a channel for leaking what the platform knows. * - *

Registered only in a servlet application and only when callbacks are enabled. An annotated - * controller is also honoured by WebFlux, so without the servlet condition a reactive deployment - * would map both this and the functional router onto the same path — and a provider signature would - * then be verified twice against two different canonical URLs. + *

Registered only in a servlet application and only when callbacks are enabled. */ @OwnsAbsoluteWebRoute @RestController diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/ProviderCallbackHttpRequest.java b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/ProviderCallbackHttpRequest.java similarity index 100% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/ProviderCallbackHttpRequest.java rename to src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/ProviderCallbackHttpRequest.java diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/ProviderCallbackIngress.java b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/ProviderCallbackIngress.java similarity index 100% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/ProviderCallbackIngress.java rename to src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/ProviderCallbackIngress.java diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationSubmissionController.java b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationSubmissionController.java similarity index 99% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationSubmissionController.java rename to src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationSubmissionController.java index 04c51005..f984c7c2 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationSubmissionController.java +++ b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationSubmissionController.java @@ -40,7 +40,8 @@ import org.springframework.web.bind.annotation.RestController; @ConditionalOnProperty( prefix = "ca-skeleton.notification.platform", name = "enabled", - havingValue = "true") + havingValue = "true", + matchIfMissing = true) @RequestMapping("/notifications") public class NotificationSubmissionController { diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationTemplateController.java b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationTemplateController.java similarity index 99% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationTemplateController.java rename to src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationTemplateController.java index 30ef1f78..d05b742e 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationTemplateController.java +++ b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationTemplateController.java @@ -43,7 +43,8 @@ import org.springframework.web.bind.annotation.RestController; @ConditionalOnProperty( prefix = "ca-skeleton.notification.platform", name = "enabled", - havingValue = "true") + havingValue = "true", + matchIfMissing = true) @RequestMapping("/notification-templates") public class NotificationTemplateController { diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationVariableCoercion.java b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationVariableCoercion.java similarity index 100% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationVariableCoercion.java rename to src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationVariableCoercion.java diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/PublishTemplateHttpRequest.java b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/PublishTemplateHttpRequest.java similarity index 100% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/PublishTemplateHttpRequest.java rename to src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/PublishTemplateHttpRequest.java diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/PublishTemplateHttpResponse.java b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/PublishTemplateHttpResponse.java similarity index 100% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/PublishTemplateHttpResponse.java rename to src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/PublishTemplateHttpResponse.java diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/SubmitNotificationHttpRequest.java b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/SubmitNotificationHttpRequest.java similarity index 100% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/SubmitNotificationHttpRequest.java rename to src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/SubmitNotificationHttpRequest.java diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/SubmitNotificationHttpResponse.java b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/SubmitNotificationHttpResponse.java similarity index 100% rename from src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/SubmitNotificationHttpResponse.java rename to src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/SubmitNotificationHttpResponse.java diff --git a/src/adapter/inbound/web-notification/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/src/adapter/inbound/web-notification/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports new file mode 100644 index 00000000..bf3aae9b --- /dev/null +++ b/src/adapter/inbound/web-notification/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports @@ -0,0 +1 @@ +dev.caskeleton.adapter.inbound.web.notification.NotificationWebAutoConfiguration diff --git a/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/NotificationRoutePrefixTest.java b/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/NotificationRoutePrefixTest.java new file mode 100644 index 00000000..771c7cd3 --- /dev/null +++ b/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/NotificationRoutePrefixTest.java @@ -0,0 +1,40 @@ +package dev.caskeleton.adapter.inbound.web.notification; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.adapter.inbound.web.config.PresentationWebConfig; +import dev.caskeleton.adapter.inbound.web.notification.platform.callback.NotificationCallbackMvcController; +import dev.caskeleton.adapter.inbound.web.notification.platform.submission.NotificationSubmissionController; +import dev.caskeleton.adapter.inbound.web.notification.platform.submission.NotificationTemplateController; +import dev.caskeleton.adapter.inbound.web.settings.PresentationSettings; +import java.util.function.Predicate; +import org.junit.jupiter.api.Test; +import org.springframework.web.servlet.config.annotation.PathMatchConfigurer; + +/** + * The provider callback URL is absolute; the submission API follows the presentation prefix. + * + *

Providers are configured with the callback URL once, out of band, so a presentation prefix + * that moved it would silently break every provider. Moved here from the web leaf's own test with + * the controllers it names. + */ +class NotificationRoutePrefixTest { + + @Test + void theCallbackEndpointKeepsItsAbsoluteRouteAndTheSubmissionApiIsPrefixed() { + InspectablePathMatchConfigurer configurer = new InspectablePathMatchConfigurer(); + new PresentationWebConfig(new PresentationSettings("/v1")).configurePathMatch(configurer); + Predicate> prefixed = configurer.prefix("/v1"); + + assertThat(prefixed.test(NotificationCallbackMvcController.class)).isFalse(); + assertThat(prefixed.test(NotificationSubmissionController.class)).isTrue(); + assertThat(prefixed.test(NotificationTemplateController.class)).isTrue(); + } + + private static final class InspectablePathMatchConfigurer extends PathMatchConfigurer { + + Predicate> prefix(String path) { + return getPathPrefixes().get(path); + } + } +} diff --git a/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/NotificationWebAutoConfigurationTest.java b/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/NotificationWebAutoConfigurationTest.java new file mode 100644 index 00000000..620e4268 --- /dev/null +++ b/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/NotificationWebAutoConfigurationTest.java @@ -0,0 +1,84 @@ +package dev.caskeleton.adapter.inbound.web.notification; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.adapter.inbound.web.notification.platform.callback.NotificationCallbackMvcController; +import dev.caskeleton.adapter.inbound.web.notification.platform.submission.NotificationSubmissionController; +import dev.caskeleton.adapter.inbound.web.notification.platform.submission.NotificationTemplateController; +import dev.caskeleton.application.notification.platform.port.in.AcceptNotificationUseCase; +import dev.caskeleton.application.notification.platform.port.in.PublishNotificationTemplateUseCase; +import org.junit.jupiter.api.Test; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.test.context.runner.ReactiveWebApplicationContextRunner; +import org.springframework.boot.test.context.runner.WebApplicationContextRunner; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** The HTTP surface is registered only by its own auto-configuration, behind the master switch. */ +class NotificationWebAutoConfigurationTest { + + private final WebApplicationContextRunner servlet = + new WebApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(NotificationWebAutoConfiguration.class)) + .withUserConfiguration(UseCases.class); + + @Test + void nothingIsRegisteredWhileThePlatformIsOff() { + servlet + .withPropertyValues("ca-skeleton.notification.platform.enabled=false") + .run( + context -> + assertThat(context) + .hasNotFailed() + .doesNotHaveBean(NotificationSubmissionController.class) + .doesNotHaveBean(NotificationTemplateController.class) + .doesNotHaveBean(NotificationCallbackMvcController.class)); + } + + @Test + void theSubmissionSurfaceRegistersWithThePlatformAndTheCallbackEndpointStaysOnItsOwnSwitch() { + servlet + .withPropertyValues("ca-skeleton.notification.platform.enabled=true") + .run( + context -> + assertThat(context) + .hasNotFailed() + .hasSingleBean(NotificationSubmissionController.class) + .hasSingleBean(NotificationTemplateController.class) + .doesNotHaveBean(NotificationCallbackMvcController.class)); + } + + @Test + void theServletControllersNeverRegisterInAReactiveApplication() { + new ReactiveWebApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(NotificationWebAutoConfiguration.class)) + .withUserConfiguration(UseCases.class) + .withPropertyValues( + "ca-skeleton.notification.platform.enabled=true", + "ca-skeleton.notification.platform.callbacks.enabled=true") + .run( + context -> + assertThat(context) + .hasNotFailed() + .doesNotHaveBean(NotificationSubmissionController.class) + .doesNotHaveBean(NotificationCallbackMvcController.class)); + } + + @Configuration(proxyBeanMethods = false) + static class UseCases { + + @Bean + AcceptNotificationUseCase acceptNotificationUseCase() { + return command -> { + throw new UnsupportedOperationException("not called"); + }; + } + + @Bean + PublishNotificationTemplateUseCase publishNotificationTemplateUseCase() { + return command -> { + throw new UnsupportedOperationException("not called"); + }; + } + } +} diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/CallbackRequestConfigurationTest.java b/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/CallbackRequestConfigurationTest.java similarity index 100% rename from src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/CallbackRequestConfigurationTest.java rename to src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/CallbackRequestConfigurationTest.java diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/NotificationCallbackMvcControllerTest.java b/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/NotificationCallbackMvcControllerTest.java similarity index 100% rename from src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/NotificationCallbackMvcControllerTest.java rename to src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/NotificationCallbackMvcControllerTest.java diff --git a/src/adapter/inbound/web/CLAUDE.md b/src/adapter/inbound/web/CLAUDE.md index 967343a5..e44f7092 100644 --- a/src/adapter/inbound/web/CLAUDE.md +++ b/src/adapter/inbound/web/CLAUDE.md @@ -22,6 +22,17 @@ Package root: `dev.caskeleton.adapter.inbound.web`. - Transport-owned OpenAPI customization that keeps `ApiError.details` as `type: object` without leaking Swagger dependencies into `shared-contract`. +Every service ships this leaf, so it holds only what the servlet production path reaches: its +`AutoConfiguration.imports` roots (`WebAdapterAutoConfiguration` imports the beans and binds the +settings; `app-bootstrap` no longer scans this leaf), and the types +`app-bootstrap`, `sample-portfolio`, `web-fileserver` and `composition:fileserver-platform` name — +plus their transitive references. Library code that no production path reaches (streaming, virtual +threads, patch, codecs, OpenAPI 3.2, URI/method policy, versioning, operation, budget, contract, +security-context bridge, `JsonIdempotentResponseCodec`, route inventory) lives in the opt-in leaf +`adapter:inbound:web-advanced`. A new type that nothing on the +production path uses belongs there, not here. This leaf never depends on it (Gradle registry + +ArchUnit `WEB-ARCH-ADV`). + ## Allowed - `:application-core` diff --git a/src/adapter/inbound/web/README.md b/src/adapter/inbound/web/README.md index 61af8289..eb5a2390 100644 --- a/src/adapter/inbound/web/README.md +++ b/src/adapter/inbound/web/README.md @@ -1,6 +1,12 @@ # adapter-web — 설계 결정 참조 -인바운드 HTTP / 보안 어댑터 모듈. 패키지 루트: `dev.caskeleton.adapter.web`. +인바운드 HTTP / 보안 어댑터 모듈. 패키지 루트: `dev.caskeleton.adapter.inbound.web`. + +모든 서비스에 들어가는 leaf 이므로 servlet 운영 경로가 실제로 쓰는 코드만 둔다. 운영 경로가 닿지 않는 +라이브러리형 패키지(streaming, virtual thread, patch, codec, OpenAPI 3.2, URI/method policy, +versioning, operation, budget, contract, security-context bridge, `JsonIdempotentResponseCodec`, +route inventory)는 opt-in leaf `adapter:inbound:web-advanced` 에 있다 +([README](../web-advanced/README.md)). 허용/금지 의존, 경계 계약(B1~B8), 스키마/직렬화 계약(S1~S5), 비즈니스 규칙 검증 계약(C1~C8), 테스트 명령 같은 **모듈 규칙**은 [CLAUDE.md](CLAUDE.md) 가 SSOT 다. 이 문서는 코드 주석에서 @@ -199,10 +205,8 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML | `AccessDeniedException` | `SecurityErrorClassifier` 결정(예: `AUTHZ_INSUFFICIENT_PERMISSION`) | 분류기 결정 | 메서드-시큐리티 거부가 컨트롤러를 빠져나오면 여기 도달. 필터 계층 `EnvelopeAccessDeniedHandler` 와 **동일한 세분화 코드**를 내도록 무상태 classifier 에 위임 | | `PreconditionFailedException` | `PRECONDITION_FAILED` | 412 | D15: `If-Match` 불일치 쓰기 = 낙관적 동시성 충돌 → 412 (raw 409/500 금지) | | `PageValidationException` | `VALIDATION_FAILED` | 400 | D18/D20/D21: 계약 범위 밖 페이지/정렬/필터 파라미터. field + reasonCode 를 details 로 | -| `CursorException` | `VALIDATION_FAILED` | 400 | D22: 변조/만료/손상 커서. 조언 "첫 페이지 재요청", details field="cursor" code="CURSOR_INVALID" | -| `IdempotencyInFlightException` | `IDEMPOTENT_IN_FLIGHT` | 409 (retryable=false) | 대기 후에도 원본 처리 중. 진단정보(scope/principal)는 클라이언트 미도달 | +| `IdempotencyInFlightException` | `IDEMPOTENT_IN_FLIGHT` | 409 (retryable=false) | 같은 scope 의 다른 시도가 아직 처리 중(executor 는 기다리지 않는다). 진단정보(scope digest)는 클라이언트 미도달 | | `IdempotencyRequestMismatchException` | `IDEMPOTENT_REQUEST_MISMATCH` | 422 | D8: `Idempotency-Key` 를 다른 본문으로 재사용. fingerprint/scope 노출 금지 | -| `IdempotencyScopeMissingException` | `VALIDATION_FAILED` | 400 | §실패모드: 해석 가능한 scope 없는 키(예: 미인증 호출자)는 전역 충돌 대신 400 거부 | | `PersistenceFailureException` | `ex.errorCode()` (사전분류 `DB_*`) | 코드 결정 | adapter-persistence translator 가 SQLState→`DB_*` 로 이미 분류. 클라이언트 메시지는 category-derived 안전 문자열, **절대 `ex.getMessage()` 아님**(SQLState/제약명 담음, 서버 로그 전용) | | `DependencyFailureException` | `ex.errorCode()` (사전분류 `DEPENDENCY_*`) | 코드 결정 | adapter-outbound `OutboundHttpErrorMapper` 가 upstream 실패를 분류. 클라이언트 메시지는 per-code 고정 문자열(error-codes.yaml), **절대 `ex.getMessage()` 아님**. retryable + `retry_after_seconds` 있으면 `RetryAfterAdvisor` 로 `Retry-After` 부착 | | `HttpRequestMethodNotSupportedException` | `METHOD_NOT_ALLOWED` | 405 | D12: 405 는 지원 메서드를 나열한 `Allow` 헤더 필수 | @@ -416,20 +420,6 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML --- -## cursor - -### CursorCodec -- 불투명·서명·시간 제한 페이지네이션 커서 코덱(D22, AIP158-C5). -- **SEAM(producer-only)**: HMAC 키와 회전 정책은 이 영역의 책임. 해당 브랜치가 이 - 저장소에 없어 프로덕션 키 wiring 은 `planned`. 코덱은 주입된 키를 받고 테스트/로컬용 `withDevKey()` 팩토리 - 제공(프로덕션 금지). encode/decode 메커니즘·opacity·무결성 검사·TTL 은 여기 구현. -- `DEFAULT_TTL`: D22 의 24h TTL 은 프로젝트 내부 숫자(AIP-158 은 opacity 만 고정, TTL 미고정). - -### CursorException -- 불투명 페이지네이션 커서 검증 실패 시 발생(D22). - ---- - ## conditional ### ETags @@ -458,7 +448,5 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML 첫 committed 결과가 복구되고 side effect가 한 번만 실행되는지 검증한다. ### JsonIdempotentResponseCodec -- Jackson 기반 `IdempotentResponseCodec`: application executor가 저장/replay하는 결과의 **JSON 표현만** - web 어댑터가 소유한다. -- (역)직렬화 실패는 `MappingException`으로 surface 되어 base handler가 raw 500 대신 - `MAPPING_FAILED` 400으로 라우팅한다. +- `adapter:inbound:web-advanced` 로 옮겼다(운영 경로 호출자 0). sample 은 자기 codec + (`PosterImagePublicationReservationCodec`)을 쓰고, response-loss fixture 는 fixture 안의 익명 codec 을 쓴다. diff --git a/src/adapter/inbound/web/build.gradle b/src/adapter/inbound/web/build.gradle index bfa19d16..0a1cac61 100644 --- a/src/adapter/inbound/web/build.gradle +++ b/src/adapter/inbound/web/build.gradle @@ -6,16 +6,15 @@ plugins { } // Shared test code as a Gradle test-fixtures variant — ADR-BUILD-001. -// The inbound HTTP API execution platform design models itself as 23 Stable Gradle modules under -// modules/web. This repository's fail-closed module registry outranks that layout, so those modules -// are packages here and WebModuleBoundaryTest enforces the design's module dependency table. The -// full mapping, and the three other places the design's assumptions were adapted, are in +// The template's HTTP stack is servlet (Spring MVC) on virtual threads; there is no WebFlux twin. +// How the original platform design was adapted to this repository is in // docs/web/repository-adaptation.md. // HTTP / web adapters. Depends on application and shared operational contracts. dependencies { implementation project(':application-core') - implementation project(':application-notification') + // No `application-notification`. The notification HTTP surface is + // `adapter:inbound:web-notification`, which depends on this leaf rather than living inside it. // `PresentationWebConfigTest` names the capability controllers as the examples of an absolute // platform route the presentation prefix must not touch. Test scope only: the production graph // has no edge to the capability, which is the whole point of the split. @@ -36,42 +35,12 @@ dependencies { // never a hand-maintained stale schema). The release-blocking drift gate is // owned by feature-contract-verification-test-suite (planned). implementation libs.springdoc.openapi.starter.webmvc.api - // The two Advanced representations, compile-only on purpose. They were `implementation` first, - // on the reasoning that a missing backend would surface as a NoClassDefFoundError at the first - // request that negotiated one. That reasoning was wrong about what the jars do: Spring Boot's - // Jackson auto-configuration registers an `xmlMapper` and a `cborMapper` the moment each - // backend is on the runtime classpath, and Spring registers a message converter for XML with - // it. So every deployment got three ObjectMapper beans — which broke `@Autowired ObjectMapper` - // in the composition root with an ambiguity — and, worse, silently began parsing - // `application/xml` request bodies. An Advanced capability that is off by default had turned - // XML deserialization on for everybody, which is the opposite of what the flag promises and an - // XXE surface nobody chose. - // - // Compile-only keeps the factories compiling and their tests running while leaving the runtime - // classpath to the deployment that enables the capability. `WebRepresentation.available()` is - // what turns the absent backend into a sentence instead of a NoClassDefFoundError. - compileOnly 'tools.jackson.dataformat:jackson-dataformat-cbor' - compileOnly 'tools.jackson.dataformat:jackson-dataformat-xml' - testImplementation 'tools.jackson.dataformat:jackson-dataformat-cbor' - testImplementation 'tools.jackson.dataformat:jackson-dataformat-xml' - // Fileserver reactive transport. Only the WebFlux framework and Reactor core are declared — - // deliberately not spring-boot-starter-webflux, which would put a second embedded server - // (reactor-netty) on the runtime classpath. DispatcherServlet stays present, so Spring Boot's - // WebApplicationType deduction keeps resolving SERVLET; the reactive handlers are wired only - // when the fileserver reactive profile is selected. - implementation 'org.springframework:spring-webflux' - implementation 'io.projectreactor:reactor-core' testImplementation 'org.springframework.security:spring-security-test' - testImplementation 'io.projectreactor:reactor-test' } tasks.named('test') { useJUnitPlatform { excludeTags 'security-boundary' - // The parity gate compares recordings written by three lanes. In `test` alone only one of - // them exists, and a gate that fails because the others have not run yet is a gate people - // learn to ignore. It runs from `webCrossStackParityTest`, which depends on all three. - excludeTags 'web-parity' } } @@ -93,28 +62,6 @@ auxiliarySourceSets { compilesAgainst 'main', 'testFixtures' inherits 'implementation' } - // Reactor Netty is the Stable WebFlux server baseline and it cannot share a source set with - // Tomcat: Spring Boot deduces one application type from the classpath, so with both servers - // present the reactive gate would start a servlet container and certify nothing reactive. - // Nothing is inherited: the leaf's own `implementation` carries spring-boot-starter-web, and - // inheriting it would put Tomcat back on this lane's classpath. Boot then deduces a servlet - // application, starts a servlet container, and the reactive gate certifies the servlet stack. - // The Nginx lane runs the platform behind a real reverse proxy in a container. Its own source - // set because it is the only lane that needs Docker: folding it into `test` would make every - // developer's `check` depend on a container runtime, and the usual outcome of that is an - // @Disabled that nobody notices has been there for months. - sourceSet('nginxProxyTest') { - compilesAgainst 'main', 'testFixtures' - inherits 'implementation' - } - sourceSet('webfluxContractTest') { - compilesAgainst 'main', 'testFixtures' - // Inherits nothing. The default is to extend `testImplementation`, which extends the leaf's - // own `implementation` and therefore carries spring-boot-starter-web — and with Tomcat on - // the classpath Boot deduces a servlet application, starts a servlet container, and the - // reactive gate certifies the servlet stack while reporting itself green. - inherits() - } } // ArchUnit is declared after the testkit source set exists, because `testFixturesImplementation` is @@ -123,6 +70,8 @@ dependencies { // The fixtures speak the application's ports, so they compile against it directly. Under the // old source set this arrived through testImplementation inheritance. testFixturesImplementation project(':application-core') + // The response-loss fixture drives the real executor over the port owner's shared fake store. + testFixturesImplementation testFixtures(project(':application-core')) testFixturesImplementation project(':shared-contract') // Declared rather than inherited: the `testkit` source set extended testImplementation, so the @@ -144,7 +93,6 @@ dependencies { testFixturesImplementation 'tools.jackson.core:jackson-databind' testFixturesImplementation 'org.springframework.security:spring-security-core' testFixturesImplementation 'org.springframework.security:spring-security-web' - testFixturesImplementation 'io.projectreactor:reactor-core' testFixturesImplementation libs.archunit.junit5 testImplementation libs.archunit.junit5 @@ -162,54 +110,9 @@ dependencies { // The root build adds the launcher to `test` only; a custom lane has to say so itself, or the // executor starts and finds no JUnit Platform. jettyCompatTestRuntimeOnly 'org.junit.platform:junit-platform-launcher' - - // The reactive lane: reactor-netty in, Tomcat out. The exclusion is what makes the lane mean - // something — Boot picks the servlet stack when both are present. - webfluxContractTestImplementation('org.springframework.boot:spring-boot-starter-webflux') { - exclude group: 'org.springframework.boot', module: 'spring-boot-starter-tomcat' - } - webfluxContractTestImplementation('org.springframework.boot:spring-boot-starter-test') { - exclude group: 'org.springframework.boot', module: 'spring-boot-starter-tomcat' - } - webfluxContractTestImplementation 'org.springframework.boot:spring-boot-starter-validation' - webfluxContractTestImplementation 'io.projectreactor:reactor-test' - // Explicit because this lane inherits nothing: the platform's auto-configuration references - // ObjectMapper, and without Jackson the condition evaluation fails before a server starts. - webfluxContractTestImplementation 'org.springframework.boot:spring-boot-starter-jackson' - webfluxContractTestImplementation 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310' - webfluxContractTestImplementation project(':application-core') - webfluxContractTestImplementation project(':shared-contract') - webfluxContractTestRuntimeOnly 'org.junit.platform:junit-platform-launcher' - - // The Nginx lane. Testcontainers starts the proxy; the application runs in this JVM on a - // random port and the container reaches it through the host gateway. - nginxProxyTestImplementation 'org.springframework.boot:spring-boot-starter-test' - nginxProxyTestImplementation 'org.springframework.boot:spring-boot-starter-web' - nginxProxyTestImplementation 'org.springframework.boot:spring-boot-starter-security' - nginxProxyTestImplementation 'org.springframework.boot:spring-boot-starter-validation' - nginxProxyTestImplementation 'org.testcontainers:testcontainers' - nginxProxyTestImplementation 'org.testcontainers:testcontainers-junit-jupiter' - nginxProxyTestRuntimeOnly 'org.junit.platform:junit-platform-launcher' } strictTestLanes { - // A release compatibility gate that is not wired to a task is a document. - lane('webFluxContractTest') { - system() - sourceSet = 'webfluxContractTest' - description = 'Runs the Stable HTTP system contract against a real Reactor Netty.' - jvmArgs '-Duser.timezone=UTC' - requires( - 'dev.caskeleton.adapter.inbound.web.testkit.budget.ReactiveWebBudgetIT', - 'dev.caskeleton.adapter.inbound.web.testkit.contract.ReactiveContractRecordingIT', - 'dev.caskeleton.adapter.inbound.web.testkit.fault.ReactiveCommitThenConnectionResetIT', - 'dev.caskeleton.adapter.inbound.web.testkit.operation.ReactiveOperationHttpIT', - 'dev.caskeleton.adapter.inbound.web.testkit.order.WebFluxPipelineOrderIT', - 'dev.caskeleton.adapter.inbound.web.testkit.streaming.WebFluxSseContractIT', - 'dev.caskeleton.adapter.inbound.web.testkit.throttle.ReactiveWebThrottleIT', - 'dev.caskeleton.adapter.inbound.web.testkit.webflux.ReactorNettyWebContractIT') - } - // Docker-gated, and it says so rather than skipping. A lane that quietly passes when the // container runtime is missing is a lane that has been certifying nothing since whenever Docker // last broke. @@ -235,57 +138,15 @@ strictTestLanes { requires('dev.caskeleton.adapter.inbound.web.testkit.performance.JettyLoadAndShutdownIT') } - lane('webFluxPerformanceTest') { - performance() - sourceSet = 'webfluxContractTest' - description = 'Runs Reactor Netty load, resource-bound, slow-client and graceful-shutdown checks.' - jvmArgs '-Duser.timezone=UTC' - requires('dev.caskeleton.adapter.inbound.web.testkit.performance.ReactorNettyLoadAndShutdownIT') - } - - lane('webNginxProxyTest') { - integration() - sourceSet = 'nginxProxyTest' - description = 'Runs the proxy, prefix and spoofing contract behind a real Nginx.' - jvmArgs '-Duser.timezone=UTC' - } - lane('webJettyCompatTest') { system() sourceSet = 'jettyCompatTest' description = 'Runs the Stable HTTP system contract against a real Jetty instead of Tomcat.' jvmArgs '-Duser.timezone=UTC' requires( - 'dev.caskeleton.adapter.inbound.web.testkit.budget.JettyWebBudgetIT', - 'dev.caskeleton.adapter.inbound.web.testkit.contract.JettyContractRecordingIT', 'dev.caskeleton.adapter.inbound.web.testkit.fault.JettyCommitThenConnectionResetIT', 'dev.caskeleton.adapter.inbound.web.testkit.mvc.JettyWebContractIT', - 'dev.caskeleton.adapter.inbound.web.testkit.operation.JettyOperationHttpIT', - 'dev.caskeleton.adapter.inbound.web.testkit.order.JettyPipelineOrderIT', - 'dev.caskeleton.adapter.inbound.web.testkit.throttle.JettyWebThrottleIT') - } - - // The cross-stack gate. It depends on every recording lane rather than tolerating a missing one: - // a parity check that compares whatever happens to be present would report agreement across a - // matrix with a hole in it. - lane('webCrossStackParityTest') { - tag = 'web-parity' - description = 'Compares the wire contract recorded by Tomcat, Jetty and Reactor Netty.' - jvmArgs '-Duser.timezone=UTC' - dependsOn 'systemTest', 'webJettyCompatTest', 'webFluxContractTest' - } - - // The Advanced lane. Every capability is off unless a deployment names it, so none of them is - // exercised by anything a production deployment runs — which makes a lane that runs them all the - // only place a break is noticed before whoever enables it notices. - // - // They also run inside `test`, deliberately. They are ordinary unit tests, and excluding them - // from the PR gate to make this lane look meaningful would mean the PR gate stopped covering a - // fifth of the leaf. - lane('webAdvancedTest') { - tag = 'web-advanced' - description = 'Runs every web Advanced capability contract.' - jvmArgs '-Duser.timezone=UTC' + 'dev.caskeleton.adapter.inbound.web.testkit.order.JettyPipelineOrderIT') } } diff --git a/src/adapter/inbound/web/gradle.lockfile b/src/adapter/inbound/web/gradle.lockfile index 379b208f..490d6cee 100644 --- a/src/adapter/inbound/web/gradle.lockfile +++ b/src/adapter/inbound/web/gradle.lockfile @@ -1,140 +1,106 @@ # 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. -biz.aQute.bnd:biz.aQute.bnd.annotation:7.1.0=compileClasspath,jettyCompatTestCompileClasspath,nginxProxyTestCompileClasspath,performanceTestCompileClasspath,systemTestCompileClasspath,testCompileClasspath,testkitCompileClasspath,webfluxContractTestCompileClasspath -ch.qos.logback:logback-classic:1.5.38=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -ch.qos.logback:logback-core:1.5.38=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -com.fasterxml.jackson.core:jackson-annotations:2.21=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -com.fasterxml.jackson.core:jackson-core:2.21.5=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -com.fasterxml.jackson.core:jackson-databind:2.21.5=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:2.21.5=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.21.5=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -com.fasterxml.jackson:jackson-bom:2.21.5=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -com.fasterxml.woodstox:woodstox-core:7.1.1=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -com.fasterxml:classmate:1.7.3=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,jettyCompatTestAnnotationProcessor,nginxProxyTestAnnotationProcessor,performanceTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor,testkitAnnotationProcessor,webfluxContractTestAnnotationProcessor -com.github.docker-java:docker-java-api:3.7.1=nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath -com.github.docker-java:docker-java-transport-zerodep:3.7.1=nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath -com.github.docker-java:docker-java-transport:3.7.1=nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath -com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,jettyCompatTestAnnotationProcessor,nginxProxyTestAnnotationProcessor,performanceTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor,testkitAnnotationProcessor,webfluxContractTestAnnotationProcessor +biz.aQute.bnd:biz.aQute.bnd.annotation:7.1.0=compileClasspath,jettyCompatTestCompileClasspath,performanceTestCompileClasspath,systemTestCompileClasspath,testCompileClasspath +ch.qos.logback:logback-classic:1.5.38=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +ch.qos.logback:logback-core:1.5.38=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +com.fasterxml.jackson.core:jackson-annotations:2.21=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +com.fasterxml.jackson.core:jackson-core:2.21.5=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +com.fasterxml.jackson.core:jackson-databind:2.21.5=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:2.21.5=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.21.5=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +com.fasterxml.jackson:jackson-bom:2.21.5=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +com.fasterxml:classmate:1.7.3=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,jettyCompatTestAnnotationProcessor,performanceTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,jettyCompatTestAnnotationProcessor,performanceTestAnnotationProcessor,systemTestAnnotationProcessor,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,jettyCompatTestAnnotationProcessor,nginxProxyTestAnnotationProcessor,performanceTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor,testkitAnnotationProcessor,webfluxContractTestAnnotationProcessor -com.google.auto.value:auto-value-annotations:1.9=annotationProcessor,jettyCompatTestAnnotationProcessor,nginxProxyTestAnnotationProcessor,performanceTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor,testkitAnnotationProcessor,webfluxContractTestAnnotationProcessor -com.google.auto:auto-common:1.2.2=annotationProcessor,jettyCompatTestAnnotationProcessor,nginxProxyTestAnnotationProcessor,performanceTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor,testkitAnnotationProcessor,webfluxContractTestAnnotationProcessor +com.google.auto.service:auto-service-annotations:1.0.1=annotationProcessor,jettyCompatTestAnnotationProcessor,performanceTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.auto.value:auto-value-annotations:1.9=annotationProcessor,jettyCompatTestAnnotationProcessor,performanceTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.auto:auto-common:1.2.2=annotationProcessor,jettyCompatTestAnnotationProcessor,performanceTestAnnotationProcessor,systemTestAnnotationProcessor,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,jettyCompatTestAnnotationProcessor,nginxProxyTestAnnotationProcessor,performanceTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor,testkitAnnotationProcessor,webfluxContractTestAnnotationProcessor -com.google.errorprone:error_prone_annotations:2.38.0=compileClasspath,jettyCompatTestCompileClasspath,nginxProxyTestCompileClasspath,performanceTestCompileClasspath,systemTestCompileClasspath,testCompileClasspath,testkitCompileClasspath,webfluxContractTestCompileClasspath +com.google.errorprone:error_prone_annotation:2.49.0=annotationProcessor,jettyCompatTestAnnotationProcessor,performanceTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.errorprone:error_prone_annotations:2.38.0=compileClasspath,jettyCompatTestCompileClasspath,performanceTestCompileClasspath,systemTestCompileClasspath,testCompileClasspath com.google.errorprone:error_prone_annotations:2.41.0=spotbugs com.google.errorprone:error_prone_annotations:2.47.0=checkstyle -com.google.errorprone:error_prone_annotations:2.49.0=annotationProcessor,jettyCompatTestAnnotationProcessor,nginxProxyTestAnnotationProcessor,performanceTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor,testkitAnnotationProcessor,webfluxContractTestAnnotationProcessor -com.google.errorprone:error_prone_check_api:2.49.0=annotationProcessor,jettyCompatTestAnnotationProcessor,nginxProxyTestAnnotationProcessor,performanceTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor,testkitAnnotationProcessor,webfluxContractTestAnnotationProcessor -com.google.errorprone:error_prone_core:2.49.0=annotationProcessor,jettyCompatTestAnnotationProcessor,nginxProxyTestAnnotationProcessor,performanceTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor,testkitAnnotationProcessor,webfluxContractTestAnnotationProcessor -com.google.googlejavaformat:google-java-format:1.35.0=annotationProcessor,jettyCompatTestAnnotationProcessor,nginxProxyTestAnnotationProcessor,performanceTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor,testkitAnnotationProcessor,webfluxContractTestAnnotationProcessor -com.google.guava:failureaccess:1.0.3=annotationProcessor,checkstyle,jettyCompatTestAnnotationProcessor,nginxProxyTestAnnotationProcessor,performanceTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor,testkitAnnotationProcessor,webfluxContractTestAnnotationProcessor -com.google.guava:guava:33.5.0-jre=annotationProcessor,jettyCompatTestAnnotationProcessor,nginxProxyTestAnnotationProcessor,performanceTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor,testkitAnnotationProcessor,webfluxContractTestAnnotationProcessor +com.google.errorprone:error_prone_annotations:2.49.0=annotationProcessor,jettyCompatTestAnnotationProcessor,performanceTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.errorprone:error_prone_check_api:2.49.0=annotationProcessor,jettyCompatTestAnnotationProcessor,performanceTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.errorprone:error_prone_core:2.49.0=annotationProcessor,jettyCompatTestAnnotationProcessor,performanceTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.googlejavaformat:google-java-format:1.35.0=annotationProcessor,jettyCompatTestAnnotationProcessor,performanceTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.guava:failureaccess:1.0.3=annotationProcessor,checkstyle,jettyCompatTestAnnotationProcessor,performanceTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.guava:guava:33.5.0-jre=annotationProcessor,jettyCompatTestAnnotationProcessor,performanceTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor com.google.guava:guava:33.6.0-jre=checkstyle -com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,checkstyle,jettyCompatTestAnnotationProcessor,nginxProxyTestAnnotationProcessor,performanceTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor,testkitAnnotationProcessor,webfluxContractTestAnnotationProcessor -com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,jettyCompatTestAnnotationProcessor,nginxProxyTestAnnotationProcessor,performanceTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor,testkitAnnotationProcessor,webfluxContractTestAnnotationProcessor -com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,jettyCompatTestAnnotationProcessor,nginxProxyTestAnnotationProcessor,performanceTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor,testkitAnnotationProcessor,webfluxContractTestAnnotationProcessor +com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,checkstyle,jettyCompatTestAnnotationProcessor,performanceTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,jettyCompatTestAnnotationProcessor,performanceTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,jettyCompatTestAnnotationProcessor,performanceTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins -com.jayway.jsonpath:json-path:2.10.0=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -com.nimbusds:nimbus-jose-jwt:10.4=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +com.jayway.jsonpath:json-path:2.10.0=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +com.nimbusds:nimbus-jose-jwt:10.4=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath com.puppycrawl.tools:checkstyle:13.5.0=checkstyle -com.tngtech.archunit:archunit-junit5-api:1.3.0=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -com.tngtech.archunit:archunit-junit5-engine-api:1.3.0=jettyCompatTestRuntimeClasspath,nginxProxyTestRuntimeClasspath,performanceTestRuntimeClasspath,systemTestRuntimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitRuntimeClasspath -com.tngtech.archunit:archunit-junit5-engine:1.3.0=jettyCompatTestRuntimeClasspath,nginxProxyTestRuntimeClasspath,performanceTestRuntimeClasspath,systemTestRuntimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitRuntimeClasspath -com.tngtech.archunit:archunit-junit5:1.3.0=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -com.tngtech.archunit:archunit:1.3.0=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -com.vaadin.external.google:android-json:0.0.20131108.vaadin1=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath +com.tngtech.archunit:archunit-junit5-api:1.3.0=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +com.tngtech.archunit:archunit-junit5-engine-api:1.3.0=jettyCompatTestRuntimeClasspath,performanceTestRuntimeClasspath,systemTestRuntimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +com.tngtech.archunit:archunit-junit5-engine:1.3.0=jettyCompatTestRuntimeClasspath,performanceTestRuntimeClasspath,systemTestRuntimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +com.tngtech.archunit:archunit-junit5:1.3.0=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +com.tngtech.archunit:archunit:1.3.0=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +com.vaadin.external.google:android-json:0.0.20131108.vaadin1=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath commons-beanutils:commons-beanutils:1.11.0=checkstyle -commons-codec:commons-codec:1.19.0=nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath commons-collections:commons-collections:3.2.2=checkstyle -commons-io:commons-io:2.20.0=nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath commons-io:commons-io:2.21.0=spotbugs -commons-logging:commons-logging:1.3.6=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath +commons-logging:commons-logging:1.3.6=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath info.picocli:picocli:4.7.7=checkstyle -io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,jettyCompatTestAnnotationProcessor,nginxProxyTestAnnotationProcessor,performanceTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor,testkitAnnotationProcessor,webfluxContractTestAnnotationProcessor -io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,jettyCompatTestAnnotationProcessor,nginxProxyTestAnnotationProcessor,performanceTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor,testkitAnnotationProcessor,webfluxContractTestAnnotationProcessor -io.micrometer:micrometer-commons:1.16.7=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -io.micrometer:micrometer-observation:1.16.7=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -io.netty:netty-buffer:4.2.17.Final=webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -io.netty:netty-codec-base:4.2.17.Final=webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -io.netty:netty-codec-classes-quic:4.2.17.Final=webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -io.netty:netty-codec-compression:4.2.17.Final=webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -io.netty:netty-codec-dns:4.2.17.Final=webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -io.netty:netty-codec-http2:4.2.17.Final=webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -io.netty:netty-codec-http3:4.2.17.Final=webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -io.netty:netty-codec-http:4.2.17.Final=webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -io.netty:netty-codec-native-quic:4.2.17.Final=webfluxContractTestRuntimeClasspath -io.netty:netty-codec-socks:4.2.17.Final=webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -io.netty:netty-common:4.2.17.Final=webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -io.netty:netty-handler-proxy:4.2.17.Final=webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -io.netty:netty-handler:4.2.17.Final=webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -io.netty:netty-resolver-dns-classes-macos:4.2.17.Final=webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -io.netty:netty-resolver-dns-native-macos:4.2.17.Final=webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -io.netty:netty-resolver-dns:4.2.17.Final=webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -io.netty:netty-resolver:4.2.17.Final=webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -io.netty:netty-transport-classes-epoll:4.2.17.Final=webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -io.netty:netty-transport-native-epoll:4.2.17.Final=webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -io.netty:netty-transport-native-unix-common:4.2.17.Final=webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -io.netty:netty-transport:4.2.17.Final=webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -io.projectreactor.netty:reactor-netty-core:1.3.7=webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -io.projectreactor.netty:reactor-netty-http:1.3.7=webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -io.projectreactor:reactor-core:3.8.7=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -io.projectreactor:reactor-test:3.8.7=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -io.swagger.core.v3:swagger-annotations-jakarta:2.2.38=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -io.swagger.core.v3:swagger-core-jakarta:2.2.38=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -io.swagger.core.v3:swagger-models-jakarta:2.2.38=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -jakarta.activation:jakarta.activation-api:2.1.4=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -jakarta.annotation:jakarta.annotation-api:3.0.0=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath +io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,jettyCompatTestAnnotationProcessor,performanceTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,jettyCompatTestAnnotationProcessor,performanceTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +io.micrometer:micrometer-commons:1.16.7=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +io.micrometer:micrometer-observation:1.16.7=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +io.swagger.core.v3:swagger-annotations-jakarta:2.2.38=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +io.swagger.core.v3:swagger-core-jakarta:2.2.38=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +io.swagger.core.v3:swagger-models-jakarta:2.2.38=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +jakarta.activation:jakarta.activation-api:2.1.4=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +jakarta.annotation:jakarta.annotation-api:3.0.0=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath jakarta.enterprise:jakarta.enterprise.cdi-api:4.1.0=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath jakarta.enterprise:jakarta.enterprise.lang-model:4.1.0=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath jakarta.inject:jakarta.inject-api:2.0.1=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath jakarta.interceptor:jakarta.interceptor-api:2.2.0=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath -jakarta.servlet:jakarta.servlet-api:6.1.0=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestRuntimeClasspath,performanceTestRuntimeClasspath,systemTestRuntimeClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +jakarta.servlet:jakarta.servlet-api:6.1.0=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestRuntimeClasspath,systemTestRuntimeClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath jakarta.transaction:jakarta.transaction-api:2.0.1=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath -jakarta.validation:jakarta.validation-api:3.1.1=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath +jakarta.validation:jakarta.validation-api:3.1.1=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath jakarta.websocket:jakarta.websocket-api:2.2.0=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath jakarta.websocket:jakarta.websocket-client-api:2.2.0=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath -jakarta.xml.bind:jakarta.xml.bind-api:4.0.5=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -javax.inject:javax.inject:1=annotationProcessor,jettyCompatTestAnnotationProcessor,nginxProxyTestAnnotationProcessor,performanceTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor,testkitAnnotationProcessor,webfluxContractTestAnnotationProcessor +jakarta.xml.bind:jakarta.xml.bind-api:4.0.5=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +javax.inject:javax.inject:1=annotationProcessor,jettyCompatTestAnnotationProcessor,performanceTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor jaxen:jaxen:2.0.6=spotbugs -net.bytebuddy:byte-buddy-agent:1.17.8=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -net.bytebuddy:byte-buddy:1.17.8=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -net.java.dev.jna:jna:5.18.1=nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath -net.minidev:accessors-smart:2.6.0=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -net.minidev:json-smart:2.6.0=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath +net.bytebuddy:byte-buddy-agent:1.17.8=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +net.bytebuddy:byte-buddy:1.17.8=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +net.minidev:accessors-smart:2.6.0=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +net.minidev:json-smart:2.6.0=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath net.sf.saxon:Saxon-HE:12.9=checkstyle,spotbugs org.antlr:antlr4-runtime:4.13.2=checkstyle org.apache.bcel:bcel:6.12.0=spotbugs -org.apache.commons:commons-compress:1.28.0=nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath -org.apache.commons:commons-lang3:3.20.0=checkstyle,compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,spotbugs,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +org.apache.commons:commons-lang3:3.20.0=checkstyle,compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,spotbugs,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.apache.commons:commons-text:1.15.0=spotbugs org.apache.commons:commons-text:1.3=checkstyle org.apache.httpcomponents:httpclient:4.5.13=checkstyle org.apache.httpcomponents:httpcore:4.4.16=checkstyle -org.apache.logging.log4j:log4j-api:2.25.5=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,spotbugs,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath +org.apache.logging.log4j:log4j-api:2.25.5=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,spotbugs,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.apache.logging.log4j:log4j-core:2.25.5=spotbugs -org.apache.logging.log4j:log4j-to-slf4j:2.25.5=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath +org.apache.logging.log4j:log4j-to-slf4j:2.25.5=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.apache.maven.doxia:doxia-core:1.12.0=checkstyle 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.tomcat.embed:tomcat-embed-core:11.0.24=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.apache.tomcat.embed:tomcat-embed-el:11.0.24=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -org.apache.tomcat.embed:tomcat-embed-websocket:11.0.24=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +org.apache.tomcat.embed:tomcat-embed-core:11.0.24=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.apache.tomcat.embed:tomcat-embed-el:11.0.24=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.apache.tomcat.embed:tomcat-embed-websocket:11.0.24=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.apache.xbean:xbean-reflect:3.7=checkstyle -org.apiguardian:apiguardian-api:1.1.2=jettyCompatTestCompileClasspath,nginxProxyTestCompileClasspath,performanceTestCompileClasspath,systemTestCompileClasspath,testCompileClasspath,testFixturesCompileClasspath,testkitCompileClasspath,webfluxContractTestCompileClasspath -org.assertj:assertj-core:3.27.7=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -org.awaitility:awaitility:4.3.0=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath +org.apiguardian:apiguardian-api:1.1.2=jettyCompatTestCompileClasspath,performanceTestCompileClasspath,systemTestCompileClasspath,testCompileClasspath,testFixturesCompileClasspath +org.assertj:assertj-core:3.27.7=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.awaitility:awaitility:4.3.0=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,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.3.0=checkstyle -org.codehaus.woodstox:stax2-api:4.2.2=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath org.dom4j:dom4j:2.2.0=spotbugs org.eclipse.jetty.compression:jetty-compression-common:12.1.12=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath org.eclipse.jetty.compression:jetty-compression-gzip:12.1.12=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath @@ -166,112 +132,97 @@ org.eclipse.jetty:jetty-server:12.1.12=jettyCompatTestCompileClasspath,jettyComp org.eclipse.jetty:jetty-session:12.1.12=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath org.eclipse.jetty:jetty-util:12.1.12=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath org.eclipse.jetty:jetty-xml:12.1.12=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath -org.hamcrest:hamcrest:3.0=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -org.hibernate.validator:hibernate-validator:9.0.1.Final=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath +org.hamcrest:hamcrest:3.0=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.hibernate.validator:hibernate-validator:9.0.1.Final=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.javassist:javassist:3.28.0-GA=checkstyle -org.jboss.logging:jboss-logging:3.6.3.Final=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -org.jetbrains:annotations:17.0.0=nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath -org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,compileClasspath,jettyCompatTestAnnotationProcessor,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestAnnotationProcessor,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestAnnotationProcessor,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestAnnotationProcessor,systemTestCompileClasspath,systemTestRuntimeClasspath,testAnnotationProcessor,testCompileClasspath,testFixturesAnnotationProcessor,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitAnnotationProcessor,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestAnnotationProcessor,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -org.junit.jupiter:junit-jupiter-api:6.0.3=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -org.junit.jupiter:junit-jupiter-engine:6.0.3=jettyCompatTestRuntimeClasspath,nginxProxyTestRuntimeClasspath,performanceTestRuntimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath,testkitRuntimeClasspath,webfluxContractTestRuntimeClasspath -org.junit.jupiter:junit-jupiter-params:6.0.3=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -org.junit.jupiter:junit-jupiter:6.0.3=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -org.junit.platform:junit-platform-commons:6.0.3=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -org.junit.platform:junit-platform-engine:6.0.3=jettyCompatTestRuntimeClasspath,nginxProxyTestRuntimeClasspath,performanceTestRuntimeClasspath,systemTestRuntimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitRuntimeClasspath,webfluxContractTestRuntimeClasspath -org.junit.platform:junit-platform-launcher:6.0.3=jettyCompatTestRuntimeClasspath,nginxProxyTestRuntimeClasspath,performanceTestRuntimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath,testkitRuntimeClasspath,webfluxContractTestRuntimeClasspath -org.junit:junit-bom:6.0.3=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath +org.jboss.logging:jboss-logging:3.6.3.Final=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,compileClasspath,jettyCompatTestAnnotationProcessor,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestAnnotationProcessor,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestAnnotationProcessor,systemTestCompileClasspath,systemTestRuntimeClasspath,testAnnotationProcessor,testCompileClasspath,testFixturesAnnotationProcessor,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.junit.jupiter:junit-jupiter-api:6.0.3=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.junit.jupiter:junit-jupiter-engine:6.0.3=jettyCompatTestRuntimeClasspath,performanceTestRuntimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath +org.junit.jupiter:junit-jupiter-params:6.0.3=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.junit.jupiter:junit-jupiter:6.0.3=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.junit.platform:junit-platform-commons:6.0.3=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.junit.platform:junit-platform-engine:6.0.3=jettyCompatTestRuntimeClasspath,performanceTestRuntimeClasspath,systemTestRuntimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.junit.platform:junit-platform-launcher:6.0.3=jettyCompatTestRuntimeClasspath,performanceTestRuntimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath +org.junit:junit-bom:6.0.3=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.junit:junit-bom:6.1.0=spotbugs -org.mockito:mockito-core:5.20.0=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,mockitoAgent,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -org.mockito:mockito-junit-jupiter:5.20.0=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -org.objenesis:objenesis:3.3=jettyCompatTestRuntimeClasspath,nginxProxyTestRuntimeClasspath,performanceTestRuntimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath,testkitRuntimeClasspath,webfluxContractTestRuntimeClasspath -org.openapitools:jackson-databind-nullable:0.2.6=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.opentest4j:opentest4j:1.3.0=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -org.osgi:org.osgi.annotation.bundle:2.0.0=compileClasspath,jettyCompatTestCompileClasspath,nginxProxyTestCompileClasspath,performanceTestCompileClasspath,systemTestCompileClasspath,testCompileClasspath,testkitCompileClasspath,webfluxContractTestCompileClasspath -org.osgi:org.osgi.annotation.versioning:1.1.2=compileClasspath,jettyCompatTestCompileClasspath,nginxProxyTestCompileClasspath,performanceTestCompileClasspath,systemTestCompileClasspath,testCompileClasspath,testkitCompileClasspath,webfluxContractTestCompileClasspath -org.osgi:org.osgi.resource:1.0.0=compileClasspath,jettyCompatTestCompileClasspath,nginxProxyTestCompileClasspath,performanceTestCompileClasspath,systemTestCompileClasspath,testCompileClasspath,testkitCompileClasspath,webfluxContractTestCompileClasspath -org.osgi:org.osgi.service.serviceloader:1.0.0=compileClasspath,jettyCompatTestCompileClasspath,nginxProxyTestCompileClasspath,performanceTestCompileClasspath,systemTestCompileClasspath,testCompileClasspath,testkitCompileClasspath,webfluxContractTestCompileClasspath +org.mockito:mockito-core:5.20.0=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,mockitoAgent,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.mockito:mockito-junit-jupiter:5.20.0=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.objenesis:objenesis:3.3=jettyCompatTestRuntimeClasspath,performanceTestRuntimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath +org.openapitools:jackson-databind-nullable:0.2.6=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.opentest4j:opentest4j:1.3.0=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.osgi:org.osgi.annotation.bundle:2.0.0=compileClasspath,jettyCompatTestCompileClasspath,performanceTestCompileClasspath,systemTestCompileClasspath,testCompileClasspath +org.osgi:org.osgi.annotation.versioning:1.1.2=compileClasspath,jettyCompatTestCompileClasspath,performanceTestCompileClasspath,systemTestCompileClasspath,testCompileClasspath +org.osgi:org.osgi.resource:1.0.0=compileClasspath,jettyCompatTestCompileClasspath,performanceTestCompileClasspath,systemTestCompileClasspath,testCompileClasspath +org.osgi:org.osgi.service.serviceloader:1.0.0=compileClasspath,jettyCompatTestCompileClasspath,performanceTestCompileClasspath,systemTestCompileClasspath,testCompileClasspath org.ow2.asm:asm-analysis:9.10.1=spotbugs org.ow2.asm:asm-commons:9.10.1=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,spotbugs org.ow2.asm:asm-tree:9.10.1=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,spotbugs org.ow2.asm:asm-util:9.10.1=spotbugs org.ow2.asm:asm:9.10.1=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,spotbugs -org.ow2.asm:asm:9.7.1=nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -org.pcollections:pcollections:4.0.1=annotationProcessor,jettyCompatTestAnnotationProcessor,nginxProxyTestAnnotationProcessor,performanceTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor,testkitAnnotationProcessor,webfluxContractTestAnnotationProcessor -org.reactivestreams:reactive-streams:1.0.4=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath +org.ow2.asm:asm:9.7.1=performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.pcollections:pcollections:4.0.1=annotationProcessor,jettyCompatTestAnnotationProcessor,performanceTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor org.reflections:reflections:0.10.2=checkstyle -org.rnorth.duct-tape:duct-tape:1.0.8=nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath -org.skyscreamer:jsonassert:1.5.3=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -org.slf4j:jul-to-slf4j:2.0.18=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -org.slf4j:slf4j-api:2.0.18=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,spotbugs,spotbugsSlf4j,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath +org.skyscreamer:jsonassert:1.5.3=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.slf4j:jul-to-slf4j:2.0.18=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.slf4j:slf4j-api:2.0.18=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,spotbugs,spotbugsSlf4j,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j org.slf4j:slf4j-simple:2.0.18=checkstyle -org.springdoc:springdoc-openapi-starter-common:3.0.0=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.springdoc:springdoc-openapi-starter-webmvc-api:3.0.0=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.springframework.boot:spring-boot-autoconfigure:4.0.8=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath +org.springdoc:springdoc-openapi-starter-common:3.0.0=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springdoc:springdoc-openapi-starter-webmvc-api:3.0.0=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-autoconfigure:4.0.8=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-configuration-processor:4.0.8=annotationProcessor -org.springframework.boot:spring-boot-http-codec:4.0.8=webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -org.springframework.boot:spring-boot-http-converter:4.0.8=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.springframework.boot:spring-boot-jackson:4.0.8=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath +org.springframework.boot:spring-boot-http-converter:4.0.8=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-jackson:4.0.8=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-jetty:4.0.8=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath -org.springframework.boot:spring-boot-netty:4.0.8=webfluxContractTestRuntimeClasspath -org.springframework.boot:spring-boot-reactor-netty:4.0.8=webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -org.springframework.boot:spring-boot-reactor:4.0.8=webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -org.springframework.boot:spring-boot-resttestclient:4.0.8=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.springframework.boot:spring-boot-security-oauth2-resource-server:4.0.8=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.springframework.boot:spring-boot-security:4.0.8=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.springframework.boot:spring-boot-servlet:4.0.8=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.springframework.boot:spring-boot-starter-jackson-test:4.0.8=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.springframework.boot:spring-boot-starter-jackson:4.0.8=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath +org.springframework.boot:spring-boot-resttestclient:4.0.8=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-security-oauth2-resource-server:4.0.8=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-security:4.0.8=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-servlet:4.0.8=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-jackson-test:4.0.8=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-jackson:4.0.8=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-starter-jetty-runtime:4.0.8=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath org.springframework.boot:spring-boot-starter-jetty:4.0.8=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath -org.springframework.boot:spring-boot-starter-logging:4.0.8=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -org.springframework.boot:spring-boot-starter-oauth2-resource-server:4.0.8=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.springframework.boot:spring-boot-starter-reactor-netty:4.0.8=webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -org.springframework.boot:spring-boot-starter-security:4.0.8=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.springframework.boot:spring-boot-starter-test:4.0.8=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -org.springframework.boot:spring-boot-starter-tomcat-runtime:4.0.8=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.springframework.boot:spring-boot-starter-tomcat:4.0.8=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.springframework.boot:spring-boot-starter-validation:4.0.8=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -org.springframework.boot:spring-boot-starter-web:4.0.8=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.springframework.boot:spring-boot-starter-webflux:4.0.8=webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -org.springframework.boot:spring-boot-starter-webmvc-test:4.0.8=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.springframework.boot:spring-boot-starter-webmvc:4.0.8=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.springframework.boot:spring-boot-starter:4.0.8=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -org.springframework.boot:spring-boot-test-autoconfigure:4.0.8=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -org.springframework.boot:spring-boot-test:4.0.8=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -org.springframework.boot:spring-boot-tomcat:4.0.8=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.springframework.boot:spring-boot-validation:4.0.8=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -org.springframework.boot:spring-boot-web-server:4.0.8=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -org.springframework.boot:spring-boot-webflux:4.0.8=webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -org.springframework.boot:spring-boot-webmvc-test:4.0.8=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.springframework.boot:spring-boot-webmvc:4.0.8=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.springframework.boot:spring-boot:4.0.8=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -org.springframework.security:spring-security-config:7.0.7=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.springframework.security:spring-security-core:7.0.7=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.springframework.security:spring-security-crypto:7.0.7=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.springframework.security:spring-security-oauth2-core:7.0.7=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.springframework.security:spring-security-oauth2-jose:7.0.7=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.springframework.security:spring-security-oauth2-resource-server:7.0.7=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.springframework.security:spring-security-test:7.0.7=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.springframework.security:spring-security-web:7.0.7=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.springframework.session:spring-session-core:4.0.5=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.springframework:spring-aop:7.0.9=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -org.springframework:spring-beans:7.0.9=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -org.springframework:spring-context:7.0.9=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -org.springframework:spring-core:7.0.9=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -org.springframework:spring-expression:7.0.9=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -org.springframework:spring-test:7.0.9=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -org.springframework:spring-web:7.0.9=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -org.springframework:spring-webflux:7.0.9=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -org.springframework:spring-webmvc:7.0.9=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.testcontainers:testcontainers-junit-jupiter:2.0.5=nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath -org.testcontainers:testcontainers:2.0.5=nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath +org.springframework.boot:spring-boot-starter-logging:4.0.8=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-oauth2-resource-server:4.0.8=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-security:4.0.8=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-test:4.0.8=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-tomcat-runtime:4.0.8=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-tomcat:4.0.8=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-validation:4.0.8=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-web:4.0.8=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-webmvc-test:4.0.8=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-webmvc:4.0.8=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter:4.0.8=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-test-autoconfigure:4.0.8=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-test:4.0.8=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-tomcat:4.0.8=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-validation:4.0.8=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-web-server:4.0.8=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-webmvc-test:4.0.8=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-webmvc:4.0.8=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot:4.0.8=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework.security:spring-security-config:7.0.7=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework.security:spring-security-core:7.0.7=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework.security:spring-security-crypto:7.0.7=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework.security:spring-security-oauth2-core:7.0.7=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework.security:spring-security-oauth2-jose:7.0.7=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework.security:spring-security-oauth2-resource-server:7.0.7=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework.security:spring-security-test:7.0.7=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.security:spring-security-web:7.0.7=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework.session:spring-session-core:4.0.5=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework:spring-aop:7.0.9=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework:spring-beans:7.0.9=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework:spring-context:7.0.9=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework:spring-core:7.0.9=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework:spring-expression:7.0.9=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework:spring-test:7.0.9=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework:spring-web:7.0.9=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework:spring-webmvc:7.0.9=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.xmlresolver:xmlresolver:5.3.3=checkstyle,spotbugs -org.xmlunit:xmlunit-core:2.10.4=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -org.yaml:snakeyaml:2.5=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -tools.jackson.core:jackson-core:3.1.5=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -tools.jackson.core:jackson-databind:3.1.5=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath -tools.jackson.dataformat:jackson-dataformat-cbor:3.1.5=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -tools.jackson.dataformat:jackson-dataformat-xml:3.1.5=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -tools.jackson:jackson-bom:3.1.5=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,nginxProxyTestCompileClasspath,nginxProxyTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath,webfluxContractTestCompileClasspath,webfluxContractTestRuntimeClasspath +org.xmlunit:xmlunit-core:2.10.4=jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.yaml:snakeyaml:2.5=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +tools.jackson.core:jackson-core:3.1.5=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +tools.jackson.core:jackson-databind:3.1.5=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +tools.jackson:jackson-bom:3.1.5=compileClasspath,jettyCompatTestCompileClasspath,jettyCompatTestRuntimeClasspath,performanceTestCompileClasspath,performanceTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath empty= diff --git a/src/adapter/inbound/web/src/jettyCompatTest/java/dev/caskeleton/adapter/inbound/web/testkit/budget/JettyWebBudgetIT.java b/src/adapter/inbound/web/src/jettyCompatTest/java/dev/caskeleton/adapter/inbound/web/testkit/budget/JettyWebBudgetIT.java deleted file mode 100644 index cac69e5a..00000000 --- a/src/adapter/inbound/web/src/jettyCompatTest/java/dev/caskeleton/adapter/inbound/web/testkit/budget/JettyWebBudgetIT.java +++ /dev/null @@ -1,30 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.testkit.budget; - -import dev.caskeleton.webtestkit.BudgetFixtureApplication; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.web.server.LocalServerPort; -import org.springframework.test.context.ActiveProfiles; - -/** - * Budget enforcement on Jetty. - * - *

Containers impose bounds of their own — on the request line, on header size, on how a body is - * fed to a filter — and they differ. Running the same contract on the second one is what tells us - * whether a refusal came from the platform or from Tomcat. - */ -@SpringBootTest( - classes = BudgetFixtureApplication.class, - webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, - // The budget handler is gated on this property. Turning it on here rather than defaulting it - // on keeps the production default off: a control that is on by default is one nobody notices. - properties = "backend.web.budgets.enabled=true") -@ActiveProfiles("web-contract") -class JettyWebBudgetIT extends WebBudgetContract { - - @LocalServerPort private int port; - - @Override - protected HttpBudgetFixture fixture() { - return new HttpBudgetFixture(port); - } -} diff --git a/src/adapter/inbound/web/src/jettyCompatTest/java/dev/caskeleton/adapter/inbound/web/testkit/contract/JettyContractRecordingIT.java b/src/adapter/inbound/web/src/jettyCompatTest/java/dev/caskeleton/adapter/inbound/web/testkit/contract/JettyContractRecordingIT.java deleted file mode 100644 index 366f2581..00000000 --- a/src/adapter/inbound/web/src/jettyCompatTest/java/dev/caskeleton/adapter/inbound/web/testkit/contract/JettyContractRecordingIT.java +++ /dev/null @@ -1,26 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.testkit.contract; - -import dev.caskeleton.webtestkit.ContractFixtureApplication; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.web.server.LocalServerPort; -import org.springframework.test.context.ActiveProfiles; - -/** Records the wire contract as the second servlet container serves it. */ -@SpringBootTest( - classes = ContractFixtureApplication.class, - webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -@ActiveProfiles("web-contract") -class JettyContractRecordingIT extends WebPlatformContractRecording { - - @LocalServerPort private int port; - - @Override - protected WebContractFixture fixture() { - return new WebContractFixture(port); - } - - @Override - protected String laneName() { - return "jetty"; - } -} diff --git a/src/adapter/inbound/web/src/jettyCompatTest/java/dev/caskeleton/adapter/inbound/web/testkit/operation/JettyOperationHttpIT.java b/src/adapter/inbound/web/src/jettyCompatTest/java/dev/caskeleton/adapter/inbound/web/testkit/operation/JettyOperationHttpIT.java deleted file mode 100644 index c6df351c..00000000 --- a/src/adapter/inbound/web/src/jettyCompatTest/java/dev/caskeleton/adapter/inbound/web/testkit/operation/JettyOperationHttpIT.java +++ /dev/null @@ -1,27 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.testkit.operation; - -import dev.caskeleton.webtestkit.ContractFixtureApplication; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.web.server.LocalServerPort; -import org.springframework.test.context.ActiveProfiles; - -/** - * The operation resource contract on Jetty. - * - *

Containers differ in how they normalise a {@code Location} and whether they keep a {@code - * Content-Location} on a 200. Those are exactly the headers this contract turns on, so running it - * on the second servlet container is not redundancy. - */ -@SpringBootTest( - classes = ContractFixtureApplication.class, - webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -@ActiveProfiles("web-contract") -class JettyOperationHttpIT extends OperationHttpContract { - - @LocalServerPort private int port; - - @Override - protected HttpOperationFixture fixture() { - return new HttpOperationFixture(port); - } -} diff --git a/src/adapter/inbound/web/src/jettyCompatTest/java/dev/caskeleton/adapter/inbound/web/testkit/throttle/JettyWebThrottleIT.java b/src/adapter/inbound/web/src/jettyCompatTest/java/dev/caskeleton/adapter/inbound/web/testkit/throttle/JettyWebThrottleIT.java deleted file mode 100644 index a635453a..00000000 --- a/src/adapter/inbound/web/src/jettyCompatTest/java/dev/caskeleton/adapter/inbound/web/testkit/throttle/JettyWebThrottleIT.java +++ /dev/null @@ -1,41 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.testkit.throttle; - -import dev.caskeleton.webtestkit.ThrottleFixtureApplication; -import org.junit.jupiter.api.AfterEach; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.web.server.LocalServerPort; -import org.springframework.test.context.ActiveProfiles; - -/** - * Quota and capacity refusals on the second servlet container. - * - *

Real, because the capacity case needs one request to genuinely occupy a slot while another - * arrives. A mock dispatcher runs them one after the other, so the second never meets a full - * service and the 503 case would pass without ever having been exercised. - */ -@SpringBootTest( - classes = ThrottleFixtureApplication.class, - webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -@ActiveProfiles("web-contract") -class JettyWebThrottleIT extends WebThrottleHttpContract { - - @LocalServerPort private int port; - - private HttpThrottleFixture fixture; - - @Override - protected HttpThrottleFixture fixture() { - if (fixture == null) { - fixture = new HttpThrottleFixture(port); - } - return fixture; - } - - @AfterEach - void closeFixture() { - if (fixture != null) { - fixture.close(); - fixture = null; - } - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/admin/platform/WebPlatformSnapshot.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/admin/platform/WebPlatformSnapshot.java deleted file mode 100644 index 810d8a12..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/admin/platform/WebPlatformSnapshot.java +++ /dev/null @@ -1,50 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.admin.platform; - -import java.util.List; -import java.util.Map; -import java.util.Objects; - -/** - * What the platform is actually configured to do, as an operator can read it. - * - *

Read from the running objects, never from the configuration that was supposed to produce them. - * Every incident where a control was "enabled" and did nothing comes down to the same gap: the - * property was set, the bean was not created, and the only thing anyone could inspect was the - * property. A snapshot built from the beans reports the second fact. - * - * @param transport which stack is serving, "servlet" or "reactive" - * @param apiVersions the API major versions being served - * @param problemCodes every failure code this deployment can publish - * @param budgetProfiles the registered request budgets, by name - * @param admissionProfiles the registered admission profiles, by name - * @param cacheProfiles the registered cache profiles, by name - * @param installedControls which platform controls are actually wired, by name - */ -public record WebPlatformSnapshot( - String transport, - List apiVersions, - List problemCodes, - Map budgetProfiles, - Map admissionProfiles, - List cacheProfiles, - Map installedControls) { - - public WebPlatformSnapshot { - Objects.requireNonNull(transport, "transport"); - apiVersions = List.copyOf(apiVersions); - problemCodes = List.copyOf(problemCodes); - budgetProfiles = Map.copyOf(budgetProfiles); - admissionProfiles = Map.copyOf(admissionProfiles); - cacheProfiles = List.copyOf(cacheProfiles); - installedControls = Map.copyOf(installedControls); - } - - /** The controls that are declared but not wired. */ - public List uninstalledControls() { - return installedControls.entrySet().stream() - .filter(entry -> !entry.getValue()) - .map(Map.Entry::getKey) - .sorted() - .toList(); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/admin/platform/WebPlatformStartupValidator.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/admin/platform/WebPlatformStartupValidator.java deleted file mode 100644 index 1824b36b..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/admin/platform/WebPlatformStartupValidator.java +++ /dev/null @@ -1,62 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.admin.platform; - -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; - -/** - * Refuses to start when a declared control is not actually wired. - * - *

At startup, because the alternative is finding out from an incident. A control that is - * configured and not installed behaves exactly like one that is working right up until the moment - * it is needed — the rate limiter that never limits, the budget that never bounds, the problem - * catalog that nothing consults. This session found the third of those by accident, through a - * parity recording; a startup check is what finds the next one on purpose. - * - *

Fail-closed. A validator that logged a warning would be read by nobody: the deployment starts, - * the dashboards are green, and the warning scrolls past in the first thirty seconds of a log - * nobody keeps. - */ -public final class WebPlatformStartupValidator { - - private final List required; - - /** - * A validator over the controls this deployment claims. - * - * @param required the controls that must be wired - */ - public WebPlatformStartupValidator(List required) { - this.required = List.copyOf(Objects.requireNonNull(required, "required")); - } - - /** - * Refuses a snapshot that is missing a required control. - * - * @param snapshot what the running platform reports - * @throws IllegalStateException naming every missing control at once - */ - public void validate(WebPlatformSnapshot snapshot) { - Objects.requireNonNull(snapshot, "snapshot"); - List missing = new ArrayList<>(); - for (String control : required) { - if (!Boolean.TRUE.equals(snapshot.installedControls().get(control))) { - missing.add(control); - } - } - if (!missing.isEmpty()) { - // Every one at once. Reporting the first sends an operator through as many restarts as there - // are problems, and each restart is a deploy. - throw new IllegalStateException( - "the web platform declares controls that are not wired: " - + missing - + ". A configured-but-uninstalled control is indistinguishable from a working one" - + " until the moment it is needed, so startup fails here rather than in production."); - } - if (snapshot.problemCodes().isEmpty()) { - throw new IllegalStateException( - "no problem catalog is installed; every failure would be answered by the framework's" - + " own document, which carries no code for a client to branch on"); - } - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/admin/route/SpringMvcRouteInventoryCollector.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/admin/route/SpringMvcRouteInventoryCollector.java deleted file mode 100644 index 8865cb34..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/admin/route/SpringMvcRouteInventoryCollector.java +++ /dev/null @@ -1,138 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.admin.route; - -import dev.caskeleton.adapter.inbound.web.core.ApiMajorVersion; -import dev.caskeleton.adapter.inbound.web.core.WebOperationName; -import dev.caskeleton.adapter.inbound.web.core.WebRouteId; -import dev.caskeleton.adapter.inbound.web.operation.HttpMethodSemantic; -import dev.caskeleton.adapter.inbound.web.versioning.ApiDeprecationPolicy; -import java.util.List; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; -import org.springframework.web.method.HandlerMethod; -import org.springframework.web.servlet.mvc.method.RequestMappingInfo; -import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; - -/** - * Reads the routes Spring MVC actually registered. - * - *

From the handler mapping rather than from annotations. The mapping is what the dispatcher will - * consult, so it is the only source that reflects path prefixes, conditional registration and any - * programmatic mapping — an annotation scan describes what the code says and the mapping describes - * what the deployment serves, and the gate has to be about the second. - * - *

A mapping with no path or no method is skipped rather than guessed at: Spring permits both, - * and inventing "GET" or "/" for them would put a route in the manifest that nobody can call. - */ -public final class SpringMvcRouteInventoryCollector { - - private final ApiDeprecationPolicy deprecationPolicy; - - /** - * A collector that annotates routes with their deprecation state. - * - * @param deprecationPolicy the registered deprecations - */ - public SpringMvcRouteInventoryCollector(ApiDeprecationPolicy deprecationPolicy) { - this.deprecationPolicy = Objects.requireNonNull(deprecationPolicy, "deprecationPolicy"); - } - - /** - * Collects every registered route. - * - * @param mapping the dispatcher's handler mapping - * @param defaultVersion the version to record for a path that carries none - */ - public WebRouteInventory collect( - RequestMappingHandlerMapping mapping, ApiMajorVersion defaultVersion) { - Objects.requireNonNull(mapping, "mapping"); - Objects.requireNonNull(defaultVersion, "defaultVersion"); - WebRouteInventory inventory = new WebRouteInventory(); - for (var entry : mapping.getHandlerMethods().entrySet()) { - RequestMappingInfo info = entry.getKey(); - HandlerMethod handler = entry.getValue(); - Set patterns = patternsOf(info); - Set methods = - info.getMethodsCondition().getMethods(); - if (patterns.isEmpty() || methods.isEmpty()) { - continue; - } - for (String pattern : patterns) { - for (var method : methods) { - HttpMethodSemantic semantic = semanticOf(method.name()); - if (semantic == null) { - continue; - } - inventory.add(contract(info, handler, pattern, semantic, defaultVersion)); - } - } - } - return inventory; - } - - private WebRouteContract contract( - RequestMappingInfo info, - HandlerMethod handler, - String pattern, - HttpMethodSemantic method, - ApiMajorVersion defaultVersion) { - String routeKey = method.name() + " " + pattern; - var deprecation = deprecationPolicy.find(routeKey); - return new WebRouteContract( - new WebRouteId(routeKey), - operationName(handler), - versionOf(pattern, defaultVersion), - method, - pattern, - List.copyOf(mediaTypes(info.getConsumesCondition().getConsumableMediaTypes())), - List.copyOf(mediaTypes(info.getProducesCondition().getProducibleMediaTypes())), - deprecation.isPresent(), - deprecation.flatMap(route -> route.sunsetAt())); - } - - /** - * The operation name for a handler. - * - *

Derived from the controller and method names, lower-cased and hyphen-joined, because a - * handler that has not declared one still needs an identity the inventory can report — and the - * catalog check will then refuse it, which is the intended outcome for an unregistered route. - */ - private WebOperationName operationName(HandlerMethod handler) { - String type = handler.getBeanType().getSimpleName().replace("Controller", ""); - String raw = (type + "." + handler.getMethod().getName()).toLowerCase(java.util.Locale.ROOT); - String normalised = raw.replaceAll("[^a-z0-9.-]", "-"); - return new WebOperationName(normalised.length() >= 3 ? normalised : "route." + normalised); - } - - private ApiMajorVersion versionOf(String pattern, ApiMajorVersion defaultVersion) { - var matcher = java.util.regex.Pattern.compile("^/api/v([1-9][0-9]*)(?:/|$)").matcher(pattern); - return matcher.find() - ? new ApiMajorVersion(Integer.parseInt(matcher.group(1))) - : defaultVersion; - } - - private static Set patternsOf(RequestMappingInfo info) { - if (info.getPathPatternsCondition() != null) { - return info.getPathPatternsCondition().getPatternValues(); - } - return Set.of(); - } - - private static List mediaTypes(Set types) { - return types.stream().map(Object::toString).sorted().toList(); - } - - private static HttpMethodSemantic semanticOf(String name) { - for (HttpMethodSemantic candidate : HttpMethodSemantic.values()) { - if (candidate.name().equals(name)) { - return candidate; - } - } - return null; - } - - /** The optional deprecation for a route key, exposed for a diagnostic. */ - public Optional deprecationFor(String routeKey) { - return deprecationPolicy.find(routeKey); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/admission/AdmissionDecision.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/admission/AdmissionDecision.java deleted file mode 100644 index 91364220..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/admission/AdmissionDecision.java +++ /dev/null @@ -1,59 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.admission; - -import java.time.Duration; -import java.util.Objects; -import java.util.Optional; - -/** - * Whether the service has room to run this request now. - * - *

Distinct from a quota decision in what it means and in what it is answered with. A quota is - * about the caller and is 429; this is about the service and is 503. The permit is carried here - * rather than returned separately so that releasing it is impossible to forget in one branch and - * not another. - * - * @param admitted whether the request may run - * @param permit what to close when it finishes, present only when admitted - * @param retryAfter how long to wait, present only when refused - * @param waited how long the request queued before this decision - */ -public record AdmissionDecision( - boolean admitted, - Optional permit, - Optional retryAfter, - Duration waited) { - - public AdmissionDecision { - Objects.requireNonNull(permit, "permit"); - Objects.requireNonNull(retryAfter, "retryAfter"); - Objects.requireNonNull(waited, "waited"); - if (admitted != permit.isPresent()) { - throw new IllegalArgumentException( - "an admitted request holds a permit and a refused one does not; anything else leaks" - + " capacity or releases what it never took"); - } - if (admitted == retryAfter.isPresent()) { - throw new IllegalArgumentException("only a refused request is told when to come back"); - } - } - - /** - * The request may run. - * - * @param permit what to close when it finishes - * @param waited how long it queued - */ - public static AdmissionDecision admitted(AdmissionPermit permit, Duration waited) { - return new AdmissionDecision(true, Optional.of(permit), Optional.empty(), waited); - } - - /** - * The service has no room. - * - * @param retryAfter how long to wait - * @param waited how long it queued before being turned away - */ - public static AdmissionDecision refused(Duration retryAfter, Duration waited) { - return new AdmissionDecision(false, Optional.empty(), Optional.of(retryAfter), waited); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/admission/AdmissionPermit.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/admission/AdmissionPermit.java deleted file mode 100644 index 178b4490..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/admission/AdmissionPermit.java +++ /dev/null @@ -1,21 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.admission; - -/** - * The right to occupy one execution slot, given up when closed. - * - *

{@link AutoCloseable} so the release is a {@code try}-with-resources rather than a {@code - * finally} somebody has to remember. A permit that is not released is capacity the service never - * gets back, and the symptom — throughput decaying towards zero over hours — is one of the harder - * ones to attribute. - * - *

{@code close} is idempotent in every implementation here. A double release would return - * capacity that was never taken, which is the same bug in the opposite direction and admits more - * concurrent work than the profile allows. - */ -@FunctionalInterface -public interface AdmissionPermit extends AutoCloseable { - - /** Gives the slot back. Calling twice releases nothing extra. */ - @Override - void close(); -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/admission/AdmissionProfile.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/admission/AdmissionProfile.java deleted file mode 100644 index 16681817..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/admission/AdmissionProfile.java +++ /dev/null @@ -1,80 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.admission; - -import dev.caskeleton.adapter.inbound.web.operation.AdmissionProfileName; -import java.time.Duration; -import java.util.Objects; - -/** - * How much of the service one class of work may occupy. - * - *

Separate profiles for separate work is the point. A single global limit sized for cheap reads - * lets a burst of expensive writes fill it and starve everything; sized for the writes, it is no - * limit at all for the reads. The design asks for at least a write profile and an expensive-query - * profile, and the factories below are those. - * - * @param name the profile's identity - * @param maxConcurrent how many may run at once - * @param maxQueued how many may wait - * @param maxQueueWait how long one may wait before being turned away - */ -public record AdmissionProfile( - AdmissionProfileName name, int maxConcurrent, int maxQueued, Duration maxQueueWait) { - - public AdmissionProfile { - Objects.requireNonNull(name, "name"); - Objects.requireNonNull(maxQueueWait, "maxQueueWait"); - if (maxConcurrent <= 0) { - throw new IllegalArgumentException("a profile that admits nothing is not a profile"); - } - if (maxQueued < 0) { - throw new IllegalArgumentException("a negative queue is not a queue"); - } - // An unbounded queue is the failure this whole mechanism exists to prevent. It converts an - // overload into unbounded latency and memory growth: every caller is accepted, none is served - // in time, and the ones still waiting have long since given up and retried. - if (maxQueued > 10 * maxConcurrent) { - throw new IllegalArgumentException( - "a queue of " - + maxQueued - + " against " - + maxConcurrent - + " concurrent is effectively unbounded: everything is accepted, nothing is served" - + " in time, and the far end has already retried"); - } - if (maxQueueWait.isNegative()) { - throw new IllegalArgumentException("a negative queue wait is not a wait"); - } - if (maxQueueWait.compareTo(Duration.ofSeconds(10)) > 0) { - throw new IllegalArgumentException( - "a queue wait over 10s outlives the client that is waiting; refusing quickly is the" - + " kinder answer and the one that sheds load"); - } - } - - /** - * Global writes: few at once, a short queue, a short wait. - * - *

Writes contend on the same rows and the same connections, so more concurrency past a point - * buys nothing and costs lock contention. - */ - public static AdmissionProfile globalWrite() { - return new AdmissionProfile( - new AdmissionProfileName("global-write"), 32, 64, Duration.ofMillis(250)); - } - - /** - * Expensive queries: fewer still, and turned away rather than queued for long. - * - *

An expensive query that has been waiting is worse than one refused: by the time it runs the - * caller has usually gone, and the work is spent on a response nobody reads. - */ - public static AdmissionProfile expensiveQuery() { - return new AdmissionProfile( - new AdmissionProfileName("expensive-query"), 8, 8, Duration.ofMillis(100)); - } - - /** Ordinary reads: generous, because they are cheap and mostly bounded by IO. */ - public static AdmissionProfile standard() { - return new AdmissionProfile(AdmissionProfileName.standard(), 256, 256, Duration.ofMillis(500)); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/admission/SemaphoreAdmissionController.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/admission/SemaphoreAdmissionController.java deleted file mode 100644 index d00ff806..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/admission/SemaphoreAdmissionController.java +++ /dev/null @@ -1,118 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.admission; - -import dev.caskeleton.adapter.inbound.web.operation.AdmissionProfileName; -import java.time.Duration; -import java.util.Map; -import java.util.Objects; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.Semaphore; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; - -/** - * Bounded concurrency with a bounded queue, per profile. - * - *

A {@link Semaphore} per profile rather than one shared pool, so a saturated write profile - * cannot refuse a read. The queue is a separate counter rather than the semaphore's own waiter - * list, because the semaphore's list is unbounded: without the counter a spike parks every request - * thread on {@code tryAcquire} and the bounded-queue requirement is satisfied only on paper. - * - *

The two bounds do different jobs. Concurrency decides how much work runs; the queue decides - * how much hope is kept. A queue longer than the clients' own timeouts is worse than no queue — - * every slot is filled with a request whose caller has already given up and retried, so the service - * does the work twice and answers neither in time. - */ -public final class SemaphoreAdmissionController implements WebAdmissionController { - - private record Gate(AdmissionProfile profile, Semaphore permits, AtomicInteger queued) {} - - private final Map gates = new ConcurrentHashMap<>(); - - /** - * A controller over the given profiles. - * - * @param profiles what may run, and how much of it - */ - public SemaphoreAdmissionController(AdmissionProfile... profiles) { - Objects.requireNonNull(profiles, "profiles"); - for (AdmissionProfile profile : profiles) { - // Fair, so a request that has been queued longest goes next. Unfair acquisition is faster - // and starves the unlucky: under sustained load a few requests wait past every timeout while - // arrivals behind them are served, and the latency tail stops resembling the median at all. - gates.put( - profile.name(), - new Gate(profile, new Semaphore(profile.maxConcurrent(), true), new AtomicInteger())); - } - } - - /** A controller over the three standard profiles. */ - public static SemaphoreAdmissionController standard() { - return new SemaphoreAdmissionController( - AdmissionProfile.standard(), - AdmissionProfile.globalWrite(), - AdmissionProfile.expensiveQuery()); - } - - @Override - public AdmissionDecision admit(AdmissionProfileName profileName) { - Objects.requireNonNull(profileName, "profileName"); - Gate gate = gates.get(profileName); - if (gate == null) { - throw new IllegalArgumentException( - "no admission profile named " - + profileName - + "; an operation whose profile is unregistered would run with no bound at all"); - } - - // Fast path: a free slot is taken without ever joining the queue, so an idle service adds no - // queue accounting to the common case. - if (gate.permits().tryAcquire()) { - return AdmissionDecision.admitted(permitFor(gate), Duration.ZERO); - } - - int queueDepth = gate.queued().incrementAndGet(); - try { - if (queueDepth > gate.profile().maxQueued()) { - return AdmissionDecision.refused(retryAfterFor(gate), Duration.ZERO); - } - long startedAt = System.nanoTime(); - boolean acquired = - gate.permits().tryAcquire(gate.profile().maxQueueWait().toNanos(), TimeUnit.NANOSECONDS); - Duration waited = Duration.ofNanos(System.nanoTime() - startedAt); - return acquired - ? AdmissionDecision.admitted(permitFor(gate), waited) - : AdmissionDecision.refused(retryAfterFor(gate), waited); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - return AdmissionDecision.refused(retryAfterFor(gate), Duration.ZERO); - } finally { - gate.queued().decrementAndGet(); - } - } - - /** How many slots the profile currently has free. */ - public int availablePermits(AdmissionProfileName profileName) { - Gate gate = gates.get(profileName); - return gate == null ? 0 : gate.permits().availablePermits(); - } - - private static AdmissionPermit permitFor(Gate gate) { - AtomicBoolean released = new AtomicBoolean(); - return () -> { - // Guarded, because a double release hands back a slot that was never taken and quietly - // raises the concurrency bound above what the profile allows. - if (released.compareAndSet(false, true)) { - gate.permits().release(); - } - }; - } - - private static Duration retryAfterFor(Gate gate) { - // The queue wait, not a fixed second: it is the timescale on which this profile actually - // drains, so it is the honest answer to "when should I come back". - return gate.profile().maxQueueWait().isZero() - ? Duration.ofMillis(100) - : gate.profile().maxQueueWait(); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/admission/WebAdmissionController.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/admission/WebAdmissionController.java deleted file mode 100644 index b14a7024..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/admission/WebAdmissionController.java +++ /dev/null @@ -1,21 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.admission; - -import dev.caskeleton.adapter.inbound.web.operation.AdmissionProfileName; - -/** - * Decides whether the service has room to run a request now. - * - *

Load shedding, not rate limiting. This looks only at what the service is currently doing and - * knows nothing about who is calling; the limiter looks only at the caller and knows nothing about - * the service's state. Keeping them apart is what lets a well-behaved caller be told 503 during a - * spike and an abusive one be told 429 while the service is idle. - */ -public interface WebAdmissionController { - - /** - * Asks for a slot, waiting up to the profile's queue budget. - * - * @param profile which class of work this is - */ - AdmissionDecision admit(AdmissionProfileName profile); -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/WebAdvancedFeature.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/WebAdvancedFeature.java deleted file mode 100644 index 749e4704..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/WebAdvancedFeature.java +++ /dev/null @@ -1,58 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.advanced; - -import java.util.Optional; - -/** - * Advanced web capabilities tracked by release evidence. - * - *

The catalog distinguishes capabilities this leaf can activate itself from library-only - * capabilities that require an adopter-owned composition. A catalog entry is not a promise that a - * property exists. - */ -public enum WebAdvancedFeature { - MVC_VIRTUAL_THREADS( - ActivationPath.RUNTIME_PROPERTY, "backend.web.advanced.mvc-virtual-threads.enabled", true), - WEBFLUX_BLOCKING_BRIDGE(ActivationPath.LIBRARY_ONLY, null, true), - JSON_MERGE_PATCH(ActivationPath.LIBRARY_ONLY, null, false), - JSON_PATCH(ActivationPath.LIBRARY_ONLY, null, false), - SSE(ActivationPath.LIBRARY_ONLY, null, false), - NDJSON(ActivationPath.RUNTIME_PROPERTY, "backend.web.advanced.ndjson.enabled", false), - JSON_SEQUENCE( - ActivationPath.RUNTIME_PROPERTY, "backend.web.advanced.json-sequence.enabled", false), - FUNCTIONAL_WEBFLUX(ActivationPath.LIBRARY_ONLY, null, false), - CBOR(ActivationPath.LIBRARY_ONLY, null, false), - XML(ActivationPath.LIBRARY_ONLY, null, false), - OPENAPI_32(ActivationPath.LIBRARY_ONLY, null, false), - RATELIMIT_DRAFT_HEADERS(ActivationPath.LIBRARY_ONLY, null, false); - - private final ActivationPath activationPath; - private final String runtimeProperty; - private final boolean affectsUnrelatedRequests; - - WebAdvancedFeature( - ActivationPath activationPath, String runtimeProperty, boolean affectsUnrelatedRequests) { - this.activationPath = activationPath; - this.runtimeProperty = runtimeProperty; - this.affectsUnrelatedRequests = affectsUnrelatedRequests; - } - - /** Whether this leaf owns a runtime switch or only reusable library code. */ - public ActivationPath activationPath() { - return activationPath; - } - - /** Concrete activation property, only for capabilities this leaf actually wires. */ - public Optional runtimeProperty() { - return Optional.ofNullable(runtimeProperty); - } - - /** Whether enabling this changes behaviour for requests that do not use it. */ - public boolean affectsUnrelatedRequests() { - return affectsUnrelatedRequests; - } - - public enum ActivationPath { - RUNTIME_PROPERTY, - LIBRARY_ONLY - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/blockingbridge/BlockingBridgeBudget.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/blockingbridge/BlockingBridgeBudget.java deleted file mode 100644 index 9548f669..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/blockingbridge/BlockingBridgeBudget.java +++ /dev/null @@ -1,97 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.advanced.blockingbridge; - -import java.time.Duration; -import java.util.Map; -import java.util.Objects; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.Semaphore; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.LongAdder; - -/** - * The bounded pool the bridge offloads into, and what it observed. - * - *

Separate from the bridge itself so the accounting can be asserted without a Reactor pipeline. - * The number that matters — the peak concurrency actually reached — is invisible from throughput - * and from latency; a bridge whose bound is not applied looks exactly like one whose bound is - * generous, right up until the pool is the heap. - */ -public final class BlockingBridgeBudget { - - private static final String UNREGISTERED = ""; - - private final BlockingBridgeProfile profile; - private final Semaphore permits; - private final AtomicInteger inFlight = new AtomicInteger(); - private final AtomicInteger peakConcurrency = new AtomicInteger(); - private final Map rejectionsByOperation = new ConcurrentHashMap<>(); - - public BlockingBridgeBudget(BlockingBridgeProfile profile) { - this.profile = Objects.requireNonNull(profile, "profile"); - this.permits = new Semaphore(profile.maxConcurrency(), true); - } - - /** The profile. */ - public BlockingBridgeProfile profile() { - return profile; - } - - /** - * Take a slot, or refuse. - * - * @param operation which registered operation - * @throws BlockingBridgeRejectedException if unregistered or no slot became free in time - */ - public void acquire(String operation) throws InterruptedException { - Objects.requireNonNull(operation, "operation"); - if (!profile.registered(operation)) { - record(operation); - throw new BlockingBridgeRejectedException( - operation, BlockingBridgeRejectedException.Reason.NOT_REGISTERED); - } - Duration timeout = profile.queueTimeout(); - if (!permits.tryAcquire(timeout.toMillis(), TimeUnit.MILLISECONDS)) { - record(operation); - throw new BlockingBridgeRejectedException( - operation, BlockingBridgeRejectedException.Reason.QUEUE_TIMEOUT); - } - int current = inFlight.incrementAndGet(); - peakConcurrency.accumulateAndGet(current, Math::max); - } - - /** Give the slot back. */ - public void release() { - inFlight.decrementAndGet(); - permits.release(); - } - - /** How many are running now. */ - public int inFlight() { - return inFlight.get(); - } - - /** The most that ever ran at once. Must never exceed the configured bound. */ - public int peakConcurrency() { - return peakConcurrency.get(); - } - - /** How many offloads this operation had refused. */ - public long rejectionsFor(String operation) { - LongAdder counter = rejectionsByOperation.get(operation); - return counter == null ? 0L : counter.sum(); - } - - /** Refusals of operations nobody registered, under one key rather than one key each. */ - public long unregisteredRejections() { - return rejectionsFor(UNREGISTERED); - } - - private void record(String operation) { - // Only registered names become keys. An unregistered one is counted under a single sentinel, - // because the caller supplies that string and a map keyed on it grows with whatever is passed - // — which is the same unbounded-cardinality problem a metric tagged with client input has. - String key = profile.registered(operation) ? operation : UNREGISTERED; - rejectionsByOperation.computeIfAbsent(key, ignored -> new LongAdder()).increment(); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/blockingbridge/BlockingBridgeProfile.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/blockingbridge/BlockingBridgeProfile.java deleted file mode 100644 index d2b88181..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/blockingbridge/BlockingBridgeProfile.java +++ /dev/null @@ -1,50 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.advanced.blockingbridge; - -import java.time.Duration; -import java.util.Objects; -import java.util.Set; - -/** - * Which blocking operations may be offloaded, and how much of the offload pool each may use. - * - *

The registration is the point. Reactor's {@code boundedElastic()} is available from anywhere - * and unbounded in practice — it grows to ten times the CPU count *per scheduler* and queues - * without limit beyond that — so a controller that calls it has silently opted the whole - * application into an unbounded thread pool. Every such call site is invisible until the pool is - * the thing consuming the heap. - * - *

A registered set makes the offloads enumerable. The concurrency bound makes them survivable: - * without it, a slow dependency's callers accumulate on the pool and starve the fast ones, which - * looks like the fast dependency having failed. - * - * @param registeredOperations the operations permitted to offload - * @param maxConcurrency how many may run at once - * @param queueTimeout how long a caller waits for a slot before being refused - */ -public record BlockingBridgeProfile( - Set registeredOperations, int maxConcurrency, Duration queueTimeout) { - - public BlockingBridgeProfile { - registeredOperations = - Set.copyOf(Objects.requireNonNull(registeredOperations, "registeredOperations")); - Objects.requireNonNull(queueTimeout, "queueTimeout"); - if (registeredOperations.isEmpty()) { - throw new IllegalArgumentException( - "a bridge with no registered operation refuses everything; if nothing blocks, do not " - + "enable the bridge"); - } - if (maxConcurrency < 1) { - throw new IllegalArgumentException("an offload pool of zero runs nothing"); - } - if (queueTimeout.isNegative() || queueTimeout.isZero()) { - throw new IllegalArgumentException( - "an unbounded queue wait means a slow dependency's callers accumulate until the heap " - + "does, and the fast dependencies starve behind them"); - } - } - - /** Whether an operation may use the bridge. */ - public boolean registered(String operation) { - return operation != null && registeredOperations.contains(operation); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/blockingbridge/BlockingBridgeRejectedException.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/blockingbridge/BlockingBridgeRejectedException.java deleted file mode 100644 index ec04122d..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/blockingbridge/BlockingBridgeRejectedException.java +++ /dev/null @@ -1,47 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.advanced.blockingbridge; - -import java.util.Objects; - -/** - * A blocking offload was refused. - * - *

Two reasons, kept apart because they mean different things to whoever is looking. An - * unregistered operation is a programming error found at runtime — somebody called the bridge from - * a path nobody declared. A full pool is a capacity signal. - */ -public final class BlockingBridgeRejectedException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - private final transient String operation; - private final transient Reason reason; - - public BlockingBridgeRejectedException(String operation, Reason reason) { - super("blocking offload refused for '" + operation + "': " + reason); - this.operation = Objects.requireNonNull(operation, "operation"); - this.reason = Objects.requireNonNull(reason, "reason"); - } - - /** Which operation. */ - public String operation() { - return operation; - } - - /** Why. */ - public Reason reason() { - return reason; - } - - /** Why an offload was refused. */ - public enum Reason { - - /** Nobody declared this operation. A bug, not a capacity signal. */ - NOT_REGISTERED, - - /** The bounded pool is full. */ - CAPACITY_EXHAUSTED, - - /** No slot became available within the queue timeout. */ - QUEUE_TIMEOUT - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/functional/FunctionalRoutePolicyValidator.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/functional/FunctionalRoutePolicyValidator.java deleted file mode 100644 index 7c0ab0e2..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/functional/FunctionalRoutePolicyValidator.java +++ /dev/null @@ -1,53 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.advanced.functional; - -import dev.caskeleton.adapter.inbound.web.operation.WebOperationCatalog; -import dev.caskeleton.adapter.inbound.web.operation.WebOperationProfile; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; - -/** - * Checks that a functional route carries the same guarantees an annotated controller would. - * - *

The catalog lookup does most of the work — it throws for an unregistered operation — but two - * things it cannot check are checked here, because they are properties of the *route* rather than - * of the operation. - * - *

The method has to match. A catalog entry declares an operation as, say, a mutation with an - * idempotency policy; registering it behind a GET gives a read the write's policy and, worse, gives - * a write no read caching restrictions. Nothing downstream re-derives the method from the route. - */ -public final class FunctionalRoutePolicyValidator { - - private final WebOperationCatalog catalog; - - public FunctionalRoutePolicyValidator(WebOperationCatalog catalog) { - this.catalog = Objects.requireNonNull(catalog, "catalog"); - } - - /** - * Validate a route. - * - * @throws IllegalStateException listing everything wrong with it - */ - public void validate(RegisteredRoute route) { - Objects.requireNonNull(route, "route"); - // Throws for an unregistered operation, which is the check that matters most and the one a raw - // RouterFunction bean skips entirely. - WebOperationProfile profile = catalog.require(route.operationName()); - List faults = new ArrayList<>(); - if (profile.method() != route.method()) { - faults.add( - "the route is a " - + route.method() - + " but the operation is declared as a " - + profile.method() - + "; the profile's idempotency, precondition and cache policies were chosen for the " - + "declared method and nothing downstream re-derives it from the route"); - } - if (!faults.isEmpty()) { - throw new IllegalStateException( - "functional route " + route.routeKey() + " does not match its operation: " + faults); - } - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/functional/FunctionalRouteRegistry.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/functional/FunctionalRouteRegistry.java deleted file mode 100644 index bffdbebb..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/functional/FunctionalRouteRegistry.java +++ /dev/null @@ -1,60 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.advanced.functional; - -import dev.caskeleton.adapter.inbound.web.operation.WebOperationCatalog; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; - -/** - * The functional routes this deployment serves. - * - *

Every route goes through {@link #register}, and {@link #register} goes through the operation - * catalog. That is the whole design: a functional route that skipped this would be a {@code - * RouterFunction} bean, which Spring picks up and serves with no profile at all. - * - *

Duplicate detection is here rather than left to the router. Spring's {@code RouterFunctions} - * resolves the first match, so two registrations for the same method and pattern give one of them - * silently — and which one depends on registration order, which depends on bean order. - */ -public final class FunctionalRouteRegistry { - - private final FunctionalRoutePolicyValidator validator; - private final Map routes = new LinkedHashMap<>(); - - public FunctionalRouteRegistry(WebOperationCatalog catalog) { - this.validator = new FunctionalRoutePolicyValidator(Objects.requireNonNull(catalog, "catalog")); - } - - /** - * Register a route. - * - * @throws IllegalStateException if its operation is unregistered, its method disagrees with the - * operation, or the same method and pattern are already claimed - */ - public void register(RegisteredRoute route) { - Objects.requireNonNull(route, "route"); - validator.validate(route); - RegisteredRoute previous = routes.putIfAbsent(route.routeKey(), route); - if (previous != null) { - throw new IllegalStateException( - "two functional routes claim " - + route.routeKey() - + "; the router resolves the first match, so which one serves depends on bean " - + "ordering: " - + previous.handlerName() - + " and " - + route.handlerName()); - } - } - - /** Every registered route, in registration order. */ - public List routes() { - return List.copyOf(routes.values()); - } - - /** How many are registered. */ - public int size() { - return routes.size(); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/functional/RegisteredRoute.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/functional/RegisteredRoute.java deleted file mode 100644 index bbc4cf9a..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/functional/RegisteredRoute.java +++ /dev/null @@ -1,45 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.advanced.functional; - -import dev.caskeleton.adapter.inbound.web.core.WebOperationName; -import dev.caskeleton.adapter.inbound.web.operation.HttpMethodSemantic; -import java.util.Objects; - -/** - * One functional route, tied to a catalog operation. - * - *

The operation name is not optional and not derived. A functional route is a lambda registered - * against a path — there is no annotation for a scanner to find and no class name to infer from, so - * a route without a declared operation has no budget, no authorization profile, no idempotency - * policy and no cache policy, and nothing anywhere will say so. It will simply serve. - * - *

That is the entire difference between the annotated and functional styles as far as this leaf - * is concerned, and it is why {@code RouterFunction} beans are not registered directly. - * - * @param pattern the path pattern - * @param method the HTTP method - * @param operationName the catalog operation this route serves - * @param handlerName a stable name for logs and metrics - */ -public record RegisteredRoute( - String pattern, HttpMethodSemantic method, WebOperationName operationName, String handlerName) { - - public RegisteredRoute { - Objects.requireNonNull(pattern, "pattern"); - Objects.requireNonNull(method, "method"); - Objects.requireNonNull(operationName, "operationName"); - Objects.requireNonNull(handlerName, "handlerName"); - if (!pattern.startsWith("/")) { - throw new IllegalArgumentException("a route pattern is an absolute path: " + pattern); - } - if (handlerName.isBlank()) { - throw new IllegalArgumentException( - "a functional handler is a lambda, so it has no class name to fall back on in a log; " - + "the name has to be given"); - } - } - - /** The route's identity for duplicate detection. */ - public String routeKey() { - return method.name() + " " + pattern; - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/functional/WebFunctionalHandlerAdapter.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/functional/WebFunctionalHandlerAdapter.java deleted file mode 100644 index 300ecb8d..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/functional/WebFunctionalHandlerAdapter.java +++ /dev/null @@ -1,102 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.advanced.functional; - -import dev.caskeleton.adapter.inbound.web.operation.HttpMethodSemantic; -import java.util.List; -import java.util.Objects; -import java.util.function.Function; -import org.springframework.http.HttpMethod; -import org.springframework.web.reactive.function.server.HandlerFunction; -import org.springframework.web.reactive.function.server.RequestPredicate; -import org.springframework.web.reactive.function.server.RequestPredicates; -import org.springframework.web.reactive.function.server.RouterFunction; -import org.springframework.web.reactive.function.server.RouterFunctions; -import org.springframework.web.reactive.function.server.ServerResponse; - -/** - * Builds the {@link RouterFunction} from routes the registry has already validated. - * - *

Deliberately the only way a functional route reaches Spring in this leaf. A {@code - * RouterFunction} bean is picked up and served with no operation profile at all — no budget, no - * authorization profile, no idempotency policy — and nothing anywhere reports it. Building the - * router here, from the registry, means every route has been through {@link - * FunctionalRoutePolicyValidator} before it can be reachable. - * - *

Routes are composed in registration order and the registry has already refused duplicates. - * That ordering matters: {@code RouterFunctions} resolves the first match, so two routes for one - * method and pattern would make bean ordering decide which one serves. - */ -public final class WebFunctionalHandlerAdapter { - - private final FunctionalRouteRegistry registry; - private final Function> handlers; - - /** - * @param registry the validated routes - * @param handlers resolves a route to the handler that serves it - */ - public WebFunctionalHandlerAdapter( - FunctionalRouteRegistry registry, - Function> handlers) { - this.registry = Objects.requireNonNull(registry, "registry"); - this.handlers = Objects.requireNonNull(handlers, "handlers"); - } - - /** - * The composed router. - * - * @throws IllegalStateException when no route is registered, or a route has no handler - */ - public RouterFunction build() { - List routes = registry.routes(); - if (routes.isEmpty()) { - // Refused rather than returning an empty router. An empty one is a bean that serves nothing - // and looks installed, which is indistinguishable from a registry nobody populated. - throw new IllegalStateException( - "no functional route is registered; an empty router is a bean that serves nothing and" - + " looks installed"); - } - RouterFunction composed = null; - for (RegisteredRoute route : routes) { - RouterFunction single = - RouterFunctions.route(predicate(route), handler(route)); - composed = composed == null ? single : composed.and(single); - } - return composed; - } - - private HandlerFunction handler(RegisteredRoute route) { - HandlerFunction handler = handlers.apply(route); - if (handler == null) { - // A route with no handler would be a 404 that looks like a routing bug rather than a wiring - // one, and it would only appear when somebody called it. - throw new IllegalStateException( - "functional route " - + route.routeKey() - + " has no handler; '" - + route.handlerName() - + "' resolved to nothing"); - } - return handler; - } - - private static RequestPredicate predicate(RegisteredRoute route) { - return RequestPredicates.method(httpMethod(route.method())) - .and(RequestPredicates.path(route.pattern())); - } - - private static HttpMethod httpMethod(HttpMethodSemantic method) { - // An exhaustive switch rather than a name lookup or a map. The catalog's method vocabulary and - // Spring's are separate enums, so valueOf() across them turns adding a member to one into a - // runtime failure in the other — and a map with a computed default evaluates that default - // eagerly, which makes every lookup throw. - return switch (method) { - case GET -> HttpMethod.GET; - case HEAD -> HttpMethod.HEAD; - case OPTIONS -> HttpMethod.OPTIONS; - case POST -> HttpMethod.POST; - case PUT -> HttpMethod.PUT; - case PATCH -> HttpMethod.PATCH; - case DELETE -> HttpMethod.DELETE; - }; - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/openapi/OpenApi32CompatibilityReport.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/openapi/OpenApi32CompatibilityReport.java deleted file mode 100644 index 5b81c84b..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/openapi/OpenApi32CompatibilityReport.java +++ /dev/null @@ -1,72 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.advanced.openapi; - -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; - -/** - * What differs between the Stable 3.1 document and the experimental 3.2 one, and whether 3.2 may be - * promoted. - * - *

The invariant that matters more than any difference: generating 3.2 must not change the 3.1 - * snapshot. They are produced from the same model, so a contributor that mutates the shared model - * on the way to 3.2 changes the artifact that is actually shipped — and the 3.1 snapshot check - * would catch it only if somebody thought to run it in the same build. - * - * @param stableSnapshotHash the 3.1 snapshot's hash before generation - * @param stableSnapshotHashAfter its hash afterwards - * @param streamingDescriptionDifferences where the two documents describe streaming differently - * @param matrix which tools have been shown to read the 3.2 output - */ -public record OpenApi32CompatibilityReport( - String stableSnapshotHash, - String stableSnapshotHashAfter, - List streamingDescriptionDifferences, - OpenApiToolchainMatrix matrix) { - - public OpenApi32CompatibilityReport { - Objects.requireNonNull(stableSnapshotHash, "stableSnapshotHash"); - Objects.requireNonNull(stableSnapshotHashAfter, "stableSnapshotHashAfter"); - streamingDescriptionDifferences = - List.copyOf( - Objects.requireNonNull( - streamingDescriptionDifferences, "streamingDescriptionDifferences")); - Objects.requireNonNull(matrix, "matrix"); - } - - /** Whether generating 3.2 left the shipped artifact alone. */ - public boolean stableArtifactUnchanged() { - return stableSnapshotHash.equals(stableSnapshotHashAfter); - } - - /** - * Why 3.2 may not be promoted yet. - * - *

A list rather than a boolean, and it is never empty of its own accord: promotion also - * requires an ADR, which is not a machine-checkable condition and is therefore stated here as a - * blocker that a human removes. - * - * @param adrAccepted whether the promotion ADR has been accepted - */ - public List promotionBlockers(boolean adrAccepted) { - List blockers = new ArrayList<>(); - if (!stableArtifactUnchanged()) { - blockers.add( - "generating 3.2 changed the 3.1 snapshot, so the two share mutable state and the shipped " - + "artifact depends on whether the experimental lane ran"); - } - if (!matrix.complete()) { - blockers.addAll(matrix.gaps()); - } - if (!adrAccepted) { - blockers.add( - "no accepted promotion ADR; 3.2 stays experimental regardless of how green the matrix is"); - } - return List.copyOf(blockers); - } - - /** Whether 3.2 may become the release artifact. */ - public boolean promotable(boolean adrAccepted) { - return promotionBlockers(adrAccepted).isEmpty(); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/openapi/OpenApiToolchainMatrix.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/openapi/OpenApiToolchainMatrix.java deleted file mode 100644 index 72ae00a5..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/openapi/OpenApiToolchainMatrix.java +++ /dev/null @@ -1,81 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.advanced.openapi; - -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; - -/** - * Which tools have been shown to read a generated document. - * - *

Four distinct kinds of tool, because they fail differently and passing one says nothing about - * the others. A parser reads the document and reports errors. A linter applies style rules and will - * happily accept a document a parser rejects. A generator produces client code, and this is where - * an unsupported construct usually surfaces — not as an error but as a generated method with the - * wrong signature. A compile check on that generated code is the only step that catches it. - * - *

"OpenAPI 3.2 works" is therefore not a statement anybody can make. "This document is read - * correctly by these four tools at these versions" is. - */ -public final class OpenApiToolchainMatrix { - - private final Map> results = new LinkedHashMap<>(); - - /** Record a result. */ - public OpenApiToolchainMatrix record(ToolKind kind, String toolVersion, boolean passed) { - Objects.requireNonNull(kind, "kind"); - Objects.requireNonNull(toolVersion, "toolVersion"); - results.computeIfAbsent(kind, key -> new LinkedHashMap<>()).put(toolVersion, passed); - return this; - } - - /** Whether every kind has at least one passing tool. */ - public boolean complete() { - for (ToolKind kind : ToolKind.values()) { - Map forKind = results.get(kind); - if (forKind == null || forKind.values().stream().noneMatch(Boolean::booleanValue)) { - return false; - } - } - return true; - } - - /** What is missing, for the compatibility report. */ - public List gaps() { - return java.util.Arrays.stream(ToolKind.values()) - .filter( - kind -> { - Map forKind = results.get(kind); - return forKind == null || forKind.values().stream().noneMatch(Boolean::booleanValue); - }) - .map(kind -> kind.name() + ": no passing tool recorded") - .toList(); - } - - /** Everything recorded, for the report. */ - public Map> results() { - Map> copy = new LinkedHashMap<>(); - results.forEach((kind, byVersion) -> copy.put(kind, Map.copyOf(byVersion))); - return Map.copyOf(copy); - } - - /** The kinds of tool that have to be checked separately. */ - public enum ToolKind { - - /** Reads the document and reports structural errors. */ - PARSER, - - /** Applies style rules; accepts documents a parser rejects. */ - LINTER, - - /** Produces client code. Where unsupported constructs usually surface. */ - GENERATOR, - - /** - * Compiles the generated client. - * - *

The only step that catches a generator emitting a wrong-but-syntactically-valid signature. - */ - CLIENT_COMPILE - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/ratelimit/RateLimitDraftHeaderWriter.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/ratelimit/RateLimitDraftHeaderWriter.java deleted file mode 100644 index 064bc2a2..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/ratelimit/RateLimitDraftHeaderWriter.java +++ /dev/null @@ -1,73 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.advanced.ratelimit; - -import dev.caskeleton.adapter.inbound.web.ratelimit.RateLimitDecision; -import java.time.Duration; -import java.time.Instant; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Objects; - -/** - * Writes the draft {@code RateLimit} headers, when they are turned on. - * - *

Additive only. This writer never touches the status, never touches {@code Retry-After}, and - * returns an empty map when disabled — so a deployment that turns it off behaves exactly as a - * Stable one, which is the property the rollback test asserts. - * - *

The reset value is a delta in seconds rather than a timestamp. Both drafts specify a delta, - * and the reason is clock skew: a client whose clock is two minutes fast reads an absolute reset - * time as already past and retries immediately, which is the behaviour the header exists to - * prevent. - */ -public final class RateLimitDraftHeaderWriter { - - private final RateLimitDraftProfile profile; - - public RateLimitDraftHeaderWriter(RateLimitDraftProfile profile) { - this.profile = Objects.requireNonNull(profile, "profile"); - } - - /** - * The headers for a decision. - * - * @param decision the Stable rate-limit decision - * @param now the current instant, for the reset delta - */ - public Map write(RateLimitDecision decision, Instant now) { - Objects.requireNonNull(decision, "decision"); - Objects.requireNonNull(now, "now"); - if (!profile.enabled()) { - return Map.of(); - } - long resetSeconds = secondsUntil(decision.resetAt(), now); - Map headers = new LinkedHashMap<>(); - if (profile.version().structured()) { - headers.put( - "RateLimit", - "limit=" - + decision.limit() - + ", remaining=" - + decision.remaining() - + ", reset=" - + resetSeconds); - headers.put("RateLimit-Policy", "q=" + decision.limit() + ";w=" + profile.windowSeconds()); - } else { - headers.put("RateLimit-Limit", Long.toString(decision.limit())); - headers.put("RateLimit-Remaining", Long.toString(decision.remaining())); - headers.put("RateLimit-Reset", Long.toString(resetSeconds)); - } - return Map.copyOf(headers); - } - - /** Which draft is being emitted, for the response artifact and the compatibility report. */ - public String draftLabel() { - return profile.version().label(); - } - - private static long secondsUntil(Instant resetAt, Instant now) { - long seconds = Duration.between(now, resetAt).toSeconds(); - // Never negative. A reset already in the past reads as "retry now" to a client that clamps and - // as an enormous unsigned number to one that does not. - return Math.max(seconds, 0L); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/ratelimit/RateLimitDraftProfile.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/ratelimit/RateLimitDraftProfile.java deleted file mode 100644 index 25ef35f4..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/ratelimit/RateLimitDraftProfile.java +++ /dev/null @@ -1,36 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.advanced.ratelimit; - -import java.util.Objects; - -/** - * Whether draft rate-limit headers are emitted, and under which draft. - * - *

Off by default, and additive when on. The Stable contract is the 429 status and the {@code - * Retry-After} header; both are standardised, both are what a correct client acts on, and neither - * changes when this is enabled. These headers are extra information for clients that know to look. - * - * @param enabled whether the headers are written - * @param version which draft - * @param windowSeconds the quota window, needed for the policy field - */ -public record RateLimitDraftProfile( - boolean enabled, RateLimitDraftVersion version, long windowSeconds) { - - public RateLimitDraftProfile { - Objects.requireNonNull(version, "version"); - if (enabled && windowSeconds < 1) { - throw new IllegalArgumentException( - "the policy field states the window, and a window of zero describes no policy"); - } - } - - /** Off. */ - public static RateLimitDraftProfile disabled() { - return new RateLimitDraftProfile(false, RateLimitDraftVersion.DRAFT_11, 0); - } - - /** On, under a named draft. */ - public static RateLimitDraftProfile enabled(RateLimitDraftVersion version, long windowSeconds) { - return new RateLimitDraftProfile(true, version, windowSeconds); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/ratelimit/RateLimitDraftVersion.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/ratelimit/RateLimitDraftVersion.java deleted file mode 100644 index 52717388..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/ratelimit/RateLimitDraftVersion.java +++ /dev/null @@ -1,41 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.advanced.ratelimit; - -/** - * Which draft of the IETF RateLimit header field specification is being emitted. - * - *

Named in the response and in the test artifacts, because the drafts are not compatible with - * each other and a client written against one silently misreads another. Draft 07 used separate - * {@code RateLimit-Limit}, {@code RateLimit-Remaining} and {@code RateLimit-Reset} fields; draft 11 - * folds them into one structured {@code RateLimit} field with a companion {@code RateLimit-Policy}. - * A client reading {@code RateLimit-Remaining} against a draft-11 server finds nothing and - * concludes it has no quota information — or, worse, treats the absent field as zero. - * - *

This is why the whole thing is Advanced and experimental: the header is not standardised, so - * emitting it is a promise the platform cannot keep across a version bump. - */ -public enum RateLimitDraftVersion { - - /** draft-ietf-httpapi-ratelimit-headers-07: three separate fields. */ - DRAFT_07("draft-07", false), - - /** draft-ietf-httpapi-ratelimit-headers-11: one structured field plus a policy field. */ - DRAFT_11("draft-11", true); - - private final String label; - private final boolean structured; - - RateLimitDraftVersion(String label, boolean structured) { - this.label = label; - this.structured = structured; - } - - /** The version, as it appears in a report. */ - public String label() { - return label; - } - - /** Whether this draft uses the single structured field. */ - public boolean structured() { - return structured; - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/release/WebAdvancedPromotionGate.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/release/WebAdvancedPromotionGate.java deleted file mode 100644 index 05981626..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/release/WebAdvancedPromotionGate.java +++ /dev/null @@ -1,138 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.advanced.release; - -import dev.caskeleton.adapter.inbound.web.advanced.WebAdvancedFeature; -import java.time.Duration; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; -import java.util.Set; - -/** - * What one web Advanced capability must show before production. - * - *

Per capability, because they fail in unrelated ways and at unrelated scales. Streaming fails - * at connection count; virtual threads fail when a synchronized block pins a carrier under load; - * XML fails on one crafted document. Evidence for any of them is not evidence for the others. - * - *

{@code stableBehaviourUnchanged} is the one condition every capability shares, and it is what - * the rollback test exists to establish. If turning the feature off does not restore Stable - * behaviour exactly, then the feature was never optional and every deployment has it. - * - * @param requiredSuites the suites that must have passed - * @param minimumSoak how long it must run under production-like load - * @param securityReviewed whether a security review was done, where the capability needs one - * @param rollbackValidated whether disabling it was actually exercised - * @param stableBehaviourUnchanged whether Stable behaviour is identical with the feature off - */ -public record WebAdvancedPromotionGate( - Set requiredSuites, - Duration minimumSoak, - boolean securityReviewed, - boolean rollbackValidated, - boolean stableBehaviourUnchanged) { - - public WebAdvancedPromotionGate { - requiredSuites = Set.copyOf(Objects.requireNonNull(requiredSuites, "requiredSuites")); - Objects.requireNonNull(minimumSoak, "minimumSoak"); - if (requiredSuites.isEmpty()) { - throw new IllegalArgumentException( - "a gate requiring no suite passes everything, which is worse than no gate because it " - + "reads as one"); - } - if (minimumSoak.isNegative() || minimumSoak.isZero()) { - throw new IllegalArgumentException( - "a zero soak promotes on the strength of a green build; every failure mode these " - + "capabilities have needs load or time to appear"); - } - } - - /** The gate for a capability, with the suites its own failure modes need. */ - public static WebAdvancedPromotionGate forFeature(WebAdvancedFeature feature) { - Objects.requireNonNull(feature, "feature"); - return new WebAdvancedPromotionGate(suitesFor(feature), soakFor(feature), false, false, false); - } - - private static Set suitesFor(WebAdvancedFeature feature) { - return switch (feature) { - case MVC_VIRTUAL_THREADS -> - Set.of("web:test", "webCrossStackParityTest", "virtual-thread-admission", "pinning-jfr"); - case WEBFLUX_BLOCKING_BRIDGE -> - Set.of("web:test", "blocking-bridge-bounded", "event-loop-guard"); - case JSON_MERGE_PATCH, JSON_PATCH -> Set.of("web:test", "patch-security", "patch-atomicity"); - case SSE, NDJSON, JSON_SEQUENCE -> - Set.of( - "web:test", - "streaming-soak-10k", - "slow-consumer-bounded", - "cancellation-propagation", - "pod-drain"); - case FUNCTIONAL_WEBFLUX -> Set.of("web:test", "functional-route-parity"); - case CBOR, XML -> Set.of("web:test", "codec-security", "codec-budget"); - case OPENAPI_32 -> Set.of("web:test", "openapi-32-toolchain-matrix"); - case RATELIMIT_DRAFT_HEADERS -> Set.of("web:test", "ratelimit-draft-headers"); - }; - } - - private static Duration soakFor(WebAdvancedFeature feature) { - // Longer where the failure needs sustained load: streaming holds connections, and virtual - // threads only pin under contention that a short run does not produce. - return switch (feature) { - case SSE, NDJSON, JSON_SEQUENCE -> Duration.ofHours(24); - case MVC_VIRTUAL_THREADS, WEBFLUX_BLOCKING_BRIDGE -> Duration.ofHours(24); - default -> Duration.ofHours(8); - }; - } - - /** Whether this capability needs a security review before it ships. */ - public static boolean needsSecurityReview(WebAdvancedFeature feature) { - // Each of these takes attacker-supplied bytes into a new parser or lets a caller address - // arbitrary parts of a resource. - return feature == WebAdvancedFeature.XML - || feature == WebAdvancedFeature.CBOR - || feature == WebAdvancedFeature.JSON_PATCH - || feature == WebAdvancedFeature.JSON_MERGE_PATCH; - } - - /** - * Why this may not be promoted yet. - * - * @param feature which capability - * @param passedSuites which suites actually passed - * @param observedSoak how long it ran under production-like load - */ - public List blockers( - WebAdvancedFeature feature, Set passedSuites, Duration observedSoak) { - Objects.requireNonNull(feature, "feature"); - Objects.requireNonNull(passedSuites, "passedSuites"); - Objects.requireNonNull(observedSoak, "observedSoak"); - List blockers = new ArrayList<>(); - List missing = - requiredSuites.stream().filter(suite -> !passedSuites.contains(suite)).sorted().toList(); - if (!missing.isEmpty()) { - blockers.add("suites not passed: " + missing); - } - if (observedSoak.compareTo(minimumSoak) < 0) { - blockers.add("soak " + observedSoak + " is short of the required " + minimumSoak); - } - if (needsSecurityReview(feature) && !securityReviewed) { - blockers.add( - "no security review; this capability takes attacker-supplied bytes into a parser or " - + "lets a caller address arbitrary parts of a resource"); - } - if (!rollbackValidated) { - blockers.add("rollback not exercised; a flag nobody has turned off is not known to turn off"); - } - if (!stableBehaviourUnchanged) { - blockers.add( - "Stable behaviour is not identical with the feature off, so the feature was never " - + "optional and every deployment has it"); - } - return List.copyOf(blockers); - } - - /** Whether promotion may proceed. */ - public boolean promotable( - WebAdvancedFeature feature, Set passedSuites, Duration observedSoak) { - return blockers(feature, passedSuites, observedSoak).isEmpty(); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/release/WebAdvancedReleaseManifest.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/release/WebAdvancedReleaseManifest.java deleted file mode 100644 index ec4533d0..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/release/WebAdvancedReleaseManifest.java +++ /dev/null @@ -1,90 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.advanced.release; - -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; - -/** - * The evidence a release claims to have, and the evidence a release needs. - * - *

Two separate things, deliberately, because the gap between them is the finding. A manifest - * that only listed what was collected would always look complete — it lists what it lists. The - * required set is written down independently so that missing evidence is a diff rather than an - * absence nobody notices. - */ -public final class WebAdvancedReleaseManifest { - - /** Evidence every Advanced release must carry, whatever is enabled. */ - public static final List REQUIRED = - List.of( - "stable-release-baseline", - "streaming-soak-10k", - "slow-consumer-bounded", - "cancellation-propagation", - "patch-security", - "codec-security", - "rollback-disabled-profile"); - - private final Map evidence; - - private WebAdvancedReleaseManifest(Map evidence) { - this.evidence = Map.copyOf(evidence); - } - - /** Start an empty manifest. */ - public static Builder builder() { - return new Builder(); - } - - /** Whether a named piece of evidence was recorded. */ - public boolean has(String name) { - return evidence.containsKey(name); - } - - /** Where a piece of evidence came from. */ - public java.util.Optional reference(String name) { - return java.util.Optional.ofNullable(evidence.get(name)); - } - - /** What is required and absent. */ - public List missing() { - return REQUIRED.stream().filter(name -> !has(name)).toList(); - } - - /** Whether the manifest is complete. */ - public boolean complete() { - return missing().isEmpty(); - } - - /** Collects evidence references. */ - public static final class Builder { - - private final Map evidence = new LinkedHashMap<>(); - - private Builder() {} - - /** - * Record one piece of evidence. - * - * @param name what it is - * @param reference where to find it — a workflow run, a report path, a review link - */ - public Builder record(String name, String reference) { - Objects.requireNonNull(name, "name"); - Objects.requireNonNull(reference, "reference"); - if (reference.isBlank()) { - throw new IllegalArgumentException( - "evidence needs somewhere to look; a name with no reference is a claim, and a manifest " - + "of claims is what this exists instead of"); - } - evidence.put(name, reference); - return this; - } - - /** Freeze it. */ - public WebAdvancedReleaseManifest build() { - return new WebAdvancedReleaseManifest(evidence); - } - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/TerminationDecision.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/TerminationDecision.java deleted file mode 100644 index 498a44c8..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/TerminationDecision.java +++ /dev/null @@ -1,43 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.advanced.stream; - -import dev.caskeleton.adapter.inbound.web.error.ProblemCode; -import java.util.Objects; -import java.util.Optional; - -/** - * What to do about a failure, given whether the response has been committed. - * - *

Exactly one of the two is present, and the invariant is checked. A decision carrying both - * would let a caller write a problem document *and* a terminal record, which is the half-stream - * half-JSON body that started this. - * - * @param termination how the stream ends, absent when the response can still become an HTTP error - * @param httpStatusChange the problem code to answer with, absent once committed - * @param safeMessage client-safe text for the terminal record - */ -public record TerminationDecision( - Optional termination, - Optional httpStatusChange, - String safeMessage) { - - public TerminationDecision { - Objects.requireNonNull(termination, "termination"); - Objects.requireNonNull(httpStatusChange, "httpStatusChange"); - Objects.requireNonNull(safeMessage, "safeMessage"); - if (termination.isPresent() == httpStatusChange.isPresent()) { - throw new IllegalArgumentException( - "a failure is answered either as an HTTP problem or as a terminal stream record, never " - + "both and never neither"); - } - } - - /** Nothing was written yet, so this can still be an ordinary error response. */ - public static TerminationDecision problem(ProblemCode code, String safeMessage) { - return new TerminationDecision(Optional.empty(), Optional.of(code), safeMessage); - } - - /** The response is committed; the failure goes into the stream. */ - public static TerminationDecision stream(WebStreamTermination how, String safeMessage) { - return new TerminationDecision(Optional.of(how), Optional.empty(), safeMessage); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebPartialResponseException.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebPartialResponseException.java deleted file mode 100644 index 48cbcd06..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebPartialResponseException.java +++ /dev/null @@ -1,41 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.advanced.stream; - -import java.util.Objects; - -/** - * A stream failed after its headers were written. - * - *

Distinct from every other failure in the leaf because the usual remedy is unavailable: the - * status is already 200 and cannot be changed. Throwing this rather than a general exception is how - * the error handler knows not to try — an exception handler that attempts to write a problem - * document onto a committed response produces a body that is half stream and half JSON, which no - * client can parse. - */ -public final class WebPartialResponseException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - private final transient StreamId streamId; - private final transient long deliveredCount; - - /** - * @param streamId which stream - * @param deliveredCount how many items the client already has - * @param cause what failed - */ - public WebPartialResponseException(StreamId streamId, long deliveredCount, Throwable cause) { - super("stream failed after " + deliveredCount + " items were already delivered", cause); - this.streamId = Objects.requireNonNull(streamId, "streamId"); - this.deliveredCount = deliveredCount; - } - - /** Which stream. */ - public StreamId streamId() { - return streamId; - } - - /** How many items the client already has, which is what makes this unrecoverable. */ - public long deliveredCount() { - return deliveredCount; - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamEnvelope.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamEnvelope.java deleted file mode 100644 index 58a14b28..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamEnvelope.java +++ /dev/null @@ -1,68 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.advanced.stream; - -import dev.caskeleton.adapter.inbound.web.error.ProblemCode; -import java.util.Objects; - -/** - * What can appear on a stream. - * - *

Sealed and three-way, because the client has to be able to tell three outcomes apart and the - * transport cannot tell it. Once response headers are written the HTTP status is fixed at 200, so a - * stream that ends because a dependency failed and one that ends because it finished look the same - * at the transport layer — both are a closed connection after a 200. The difference has to be *in - * the stream*, which is what {@link Failure} and {@link Complete} are for. - * - *

A client that sees neither has been cut off mid-stream. That is the third outcome and it is - * the one that must not be silently treated as completion. - * - * @param the item type - */ -public sealed interface WebStreamEnvelope { - - /** Which stream this belongs to. */ - StreamId streamId(); - - /** One item. */ - record Item(StreamId streamId, StreamSequence sequence, T data) - implements WebStreamEnvelope { - - public Item { - Objects.requireNonNull(streamId, "streamId"); - Objects.requireNonNull(sequence, "sequence"); - Objects.requireNonNull(data, "data"); - } - } - - /** - * The stream ended because something failed. - * - *

Carries a catalog code rather than a status, because the status is already sent. The message - * is client-safe text — a stream error reaches the client with no problem-detail sanitiser in the - * path, so whatever is put here is what the client sees. - */ - record Failure(StreamId streamId, StreamSequence sequence, ProblemCode code, String message) - implements WebStreamEnvelope { - - public Failure { - Objects.requireNonNull(streamId, "streamId"); - Objects.requireNonNull(sequence, "sequence"); - Objects.requireNonNull(code, "code"); - Objects.requireNonNull(message, "message"); - } - } - - /** The stream ended because it finished. */ - record Complete(StreamId streamId, StreamSequence lastSequence) - implements WebStreamEnvelope { - - public Complete { - Objects.requireNonNull(streamId, "streamId"); - Objects.requireNonNull(lastSequence, "lastSequence"); - } - } - - /** Whether this envelope ends the stream. */ - default boolean terminal() { - return this instanceof Failure || this instanceof Complete; - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamTerminationMapper.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamTerminationMapper.java deleted file mode 100644 index 5317b9e5..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/stream/WebStreamTerminationMapper.java +++ /dev/null @@ -1,53 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.advanced.stream; - -import dev.caskeleton.adapter.inbound.web.error.ProblemCode; -import java.util.Objects; - -/** - * Decides how a stream failure is reported, based on whether anything has been written yet. - * - *

The whole class is one branch, and the branch is the contract. Before commit a stream failure - * is an ordinary error and gets an RFC 9457 problem document with a real status. After commit the - * status is 200 and cannot be changed — attempting it produces a response whose body is a stream - * followed by a JSON object, which no client parses and every proxy caches as a success. - * - *

The message is deliberately generic. A terminal stream record reaches the client without the - * problem-detail sanitiser in the path, so an exception message put here goes straight out. - */ -public final class WebStreamTerminationMapper { - - private static final String COMMITTED_MESSAGE = - "the stream ended early because a dependency failed"; - - /** The standard mapper. Stateless; there is nothing to configure. */ - public static WebStreamTerminationMapper standard() { - return new WebStreamTerminationMapper(); - } - - /** - * Map a failure. - * - * @param responseCommitted whether any byte of the response has been written - * @param failure what went wrong - */ - public TerminationDecision mapFailure(boolean responseCommitted, Throwable failure) { - Objects.requireNonNull(failure, "failure"); - if (!responseCommitted) { - return TerminationDecision.problem(ProblemCode.DEPENDENCY_FAILURE, COMMITTED_MESSAGE); - } - return TerminationDecision.stream( - WebStreamTermination.TERMINAL_ERROR_RECORD, COMMITTED_MESSAGE); - } - - /** - * Map a failure that could not even write a terminal record. - * - *

Separate because the client learns nothing at all: it sees a connection closed after a 200. - * Counting these as normal completions is how a rising rate of mid-stream failures stays - * invisible. - */ - public TerminationDecision mapWriteFailure() { - return TerminationDecision.stream( - WebStreamTermination.ABRUPT_CLOSE, "the connection failed before the stream could end"); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/webflux/ControlledBlockingBridge.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/webflux/ControlledBlockingBridge.java deleted file mode 100644 index ee140492..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/webflux/ControlledBlockingBridge.java +++ /dev/null @@ -1,70 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.advanced.webflux; - -import dev.caskeleton.adapter.inbound.web.advanced.blockingbridge.BlockingBridgeBudget; -import java.util.Objects; -import java.util.concurrent.Callable; -import reactor.core.publisher.Mono; -import reactor.core.scheduler.Scheduler; - -/** - * Runs a registered blocking operation off the event loop, under a bound. - * - *

The permit is acquired **inside** the callable, not at assembly. Acquiring outside would take - * a slot when the pipeline is built rather than when it is subscribed, so a {@code Mono} that was - * assembled and never subscribed would hold one for ever, and a request cancelled between the two - * would leak one. Assembly-time side effects are the classic Reactor bug and this is the shape it - * takes here. - * - *

The release is in the same {@code finally} as the work, and deliberately **not** in a {@code - * doFinally}. A {@code doFinally} sees the subscriber's cancel signal, which arrives while the - * callable is still blocked on a thread — releasing there hands the permit to another caller while - * the first is still holding the database connection it was supposed to be accounting for, and the - * bound then permits more concurrent work than it says. - * - *

The consequence is that cancellation does not interrupt the blocking call, and this cannot be - * fixed here: a thread blocked in a JDBC driver does not respond to interruption. Pretending - * otherwise would give callers a cancellation that returns immediately while the work carries on. - * The permit is held until the call actually finishes, which is the honest accounting. - */ -public final class ControlledBlockingBridge { - - private final Scheduler scheduler; - private final BlockingBridgeBudget budget; - - /** - * @param scheduler where blocking work runs; must not be the event loop - * @param budget the registration list and the concurrency bound - */ - public ControlledBlockingBridge(Scheduler scheduler, BlockingBridgeBudget budget) { - this.scheduler = Objects.requireNonNull(scheduler, "scheduler"); - this.budget = Objects.requireNonNull(budget, "budget"); - } - - /** The budget, so a caller can read what it observed. */ - public BlockingBridgeBudget budget() { - return budget; - } - - /** - * Offload one call. - * - * @param registeredOperation the operation's registered name - * @param work the blocking call - * @param its result - */ - public Mono execute(String registeredOperation, Callable work) { - Objects.requireNonNull(registeredOperation, "registeredOperation"); - Objects.requireNonNull(work, "work"); - return Mono.fromCallable( - () -> { - // Throws before the counter moves, so a refusal never reaches the release below. - budget.acquire(registeredOperation); - try { - return work.call(); - } finally { - budget.release(); - } - }) - .subscribeOn(scheduler); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/webflux/SlowConsumerClosedException.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/webflux/SlowConsumerClosedException.java deleted file mode 100644 index 85717796..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/webflux/SlowConsumerClosedException.java +++ /dev/null @@ -1,32 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.advanced.webflux; - -/** - * A consumer fell far enough behind that the stream was closed rather than buffered further. - * - *

The default policy, and the reason it is the default: backpressure protects the reactive - * pipeline from a fast producer, and it does nothing at all about a consumer that reads slowly for - * an hour. Whatever the pipeline holds on that consumer's behalf is held in this process's heap, - * and a hundred such consumers is a hundred backlogs. - * - *

Closing is recoverable for the client — it reconnects, with a resume cursor where the route - * supports one. Buffering is not recoverable for the server. - */ -public final class SlowConsumerClosedException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - private final transient int bufferLimit; - - public SlowConsumerClosedException(int bufferLimit) { - super( - "the consumer fell more than " - + bufferLimit - + " items behind; closing rather than holding its backlog in the server's heap"); - this.bufferLimit = bufferLimit; - } - - /** The bound that was reached. */ - public int bufferLimit() { - return bufferLimit; - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/webflux/WebFluxDisconnectDetector.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/webflux/WebFluxDisconnectDetector.java deleted file mode 100644 index 31fa7e1b..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/webflux/WebFluxDisconnectDetector.java +++ /dev/null @@ -1,72 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.advanced.webflux; - -import dev.caskeleton.adapter.inbound.web.advanced.stream.WebStreamEvidence; -import dev.caskeleton.adapter.inbound.web.advanced.stream.WebStreamTermination; -import java.time.Instant; -import java.util.Objects; -import java.util.function.Supplier; -import reactor.core.publisher.Flux; - -/** - * Records how a reactive stream ended, from the signals Reactor already provides. - * - *

The reactive stack is the easier of the two here, and it is worth saying why: a client that - * goes away produces a **cancel** signal, which arrives without anything having to be written - * first. The servlet stack has no equivalent — there the disconnect is only discovered by a write - * that throws, which is why MVC needs a heartbeat to probe for it and this does not. - * - *

The trap on this side is the opposite one. Cancellation is easy to observe and easy to *not - * propagate*: a `doOnCancel` that records the termination and nothing else leaves the upstream - * subscription live, so the source keeps producing for a client that is gone. Reactor propagates - * cancellation upstream by default, and the way to break that is to bridge through something that - * does not — a sink, an executor, a blocking call. That is what the blocking bridge's cancellation - * handling is for. - */ -public final class WebFluxDisconnectDetector { - - private WebFluxDisconnectDetector() {} - - /** - * Attach termination recording to a stream. - * - * @param source the stream - * @param evidence what to record into - * @param now supplies the current instant - * @param the element type - */ - public static Flux observe( - Flux source, WebStreamEvidence evidence, Supplier now) { - Objects.requireNonNull(source, "source"); - Objects.requireNonNull(evidence, "evidence"); - Objects.requireNonNull(now, "now"); - return source - .doOnCancel( - () -> evidence.recordTermination(WebStreamTermination.CLIENT_DISCONNECTED, now.get())) - .doOnComplete( - () -> evidence.recordTermination(WebStreamTermination.NORMAL_COMPLETE, now.get())) - .doOnError(failure -> evidence.recordTermination(classify(failure), now.get())); - } - - /** - * Classify a reactive failure. - * - *

A slow consumer that overflowed is not a server fault and not a client disconnect — it is - * the shedding bound working, and counting it as either makes the bound invisible in the metrics - * that would show it firing. - */ - public static WebStreamTermination classify(Throwable failure) { - Objects.requireNonNull(failure, "failure"); - for (Throwable current = failure; current != null; current = current.getCause()) { - if (current instanceof SlowConsumerClosedException) { - return WebStreamTermination.CLIENT_DISCONNECTED; - } - if (current instanceof java.io.IOException) { - return WebStreamTermination.CLIENT_DISCONNECTED; - } - if (current.getCause() == current) { - break; - } - } - return WebStreamTermination.TERMINAL_ERROR_RECORD; - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/webflux/WebFluxSseAdapter.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/webflux/WebFluxSseAdapter.java deleted file mode 100644 index 64cb4db2..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/webflux/WebFluxSseAdapter.java +++ /dev/null @@ -1,117 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.advanced.webflux; - -import dev.caskeleton.adapter.inbound.web.advanced.stream.StreamId; -import dev.caskeleton.adapter.inbound.web.advanced.stream.StreamSequence; -import dev.caskeleton.adapter.inbound.web.advanced.stream.WebStreamEnvelope; -import dev.caskeleton.adapter.inbound.web.advanced.stream.WebStreamPolicy; -import java.util.Objects; -import org.springframework.http.codec.ServerSentEvent; -import reactor.core.publisher.Flux; - -/** - * Turns a stream of envelopes into a bounded SSE response. - * - *

Three bounds, applied in an order that matters. - * - *

**The bound is {@code onBackpressureBuffer} followed by {@code onBackpressureError}, and both - * halves are load-bearing.** {@code onBackpressureBuffer(n)} on its own does not close anything: it - * propagates demand upstream, so a subscriber that stops requesting simply stops the source, the - * buffer never fills and the bound never fires. That is correct behaviour for a well-behaved source - * and useless as a slow-consumer policy, because the sources this carries push whether or not - * anybody asked. {@code onBackpressureError} is what turns "the subscriber is behind" into a - * terminal signal. The buffer in front of it is what stops a single slow moment from closing a - * healthy stream. - * - *

The merge prefetch is set to the same number so merge's own queue is not a second, larger - * backlog sitting behind the configured one — its default is 256, which would make a configured - * bound of 8 describe nothing. - * - *

**Overflow is an error, not a drop.** Dropping an item silently produces a gap the client - * cannot see, because the positions either side of it are both valid. Closing the connection is - * recoverable — the client reconnects, with a resume cursor where the route supports one. - * - *

**The age bound is last**, so it applies to the merged stream. A stream kept alive only by its - * own heartbeats should still reach its maximum age. - * - *

The heartbeat is infinite, so merging it would mean a finished source never completes — the - * connection would be held for the full maximum age emitting keepalives after the last item. The - * stream therefore ends at the terminal envelope rather than at the source's completion, and a - * source that completes without emitting one has a terminal envelope supplied for it. A client that - * receives neither has been cut off, and that must stay distinguishable from a clean end. - */ -public final class WebFluxSseAdapter { - - private final WebStreamPolicy policy; - - public WebFluxSseAdapter(WebStreamPolicy policy) { - this.policy = Objects.requireNonNull(policy, "policy"); - } - - /** - * Adapt a source. - * - * @param source the envelopes to deliver - * @param the item type - */ - public Flux>> adapt(Flux> source) { - Objects.requireNonNull(source, "source"); - int bound = policy.maxBufferedItems(); - java.util.concurrent.atomic.AtomicReference streamId = - new java.util.concurrent.atomic.AtomicReference<>(); - java.util.concurrent.atomic.AtomicLong lastSequence = - new java.util.concurrent.atomic.AtomicLong(); - Flux>> data = - source - .doOnNext( - envelope -> { - streamId.set(envelope.streamId()); - if (envelope instanceof WebStreamEnvelope.Item item) { - lastSequence.set(item.sequence().value()); - } - }) - // Subscribed only if the source finished without a terminal of its own, because - // takeUntil below stops at the first one it sees. - .concatWith(Flux.defer(() -> defensiveTerminal(streamId.get(), lastSequence.get()))) - .map(WebFluxSseAdapter::toEvent); - return Flux.merge(bound, data, WebFluxSseHeartbeat.>events(policy)) - .onBackpressureBuffer(bound) - .onBackpressureError() - .onErrorMap( - reactor.core.Exceptions::isOverflow, overflow -> new SlowConsumerClosedException(bound)) - .takeUntil(event -> isTerminal(event)) - .take(policy.maxStreamAge()); - } - - private static Flux> defensiveTerminal(StreamId streamId, long last) { - if (streamId == null) { - // The source produced nothing at all, so there is no stream identity to name. Completing - // silently is the only option left, and it is why a caller should emit its own terminal. - return Flux.empty(); - } - return Flux.just( - new WebStreamEnvelope.Complete<>(streamId, new StreamSequence(Math.max(last, 1)))); - } - - private static boolean isTerminal(ServerSentEvent> event) { - WebStreamEnvelope envelope = event.data(); - return envelope != null && envelope.terminal(); - } - - private static ServerSentEvent> toEvent(WebStreamEnvelope envelope) { - String name = - switch (envelope) { - case WebStreamEnvelope.Item ignored -> "item"; - case WebStreamEnvelope.Failure ignored -> "error"; - case WebStreamEnvelope.Complete ignored -> "complete"; - }; - ServerSentEvent.Builder> event = - ServerSentEvent.>builder().event(name).data(envelope); - if (envelope instanceof WebStreamEnvelope.Item item) { - // The SSE id is what the client sends back as Last-Event-ID. Setting it on items only is - // deliberate: a client that resumed from a terminal event's id would ask to continue a - // stream that had already ended. - event.id(Long.toString(item.sequence().value())); - } - return event.build(); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/webflux/WebFluxSseHeartbeat.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/webflux/WebFluxSseHeartbeat.java deleted file mode 100644 index 77d744ec..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/webflux/WebFluxSseHeartbeat.java +++ /dev/null @@ -1,40 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.advanced.webflux; - -import dev.caskeleton.adapter.inbound.web.advanced.stream.WebStreamPolicy; -import java.time.Duration; -import java.util.Objects; -import org.springframework.http.codec.ServerSentEvent; -import reactor.core.publisher.Flux; - -/** - * A keepalive event stream to merge into a stream that may go quiet. - * - *

SSE comments would be lighter than named events, but they are invisible to {@code - * EventSource.onmessage} and to most client libraries' event handlers — so a client cannot - * distinguish "the server is alive and quiet" from "the connection is dead" without also watching - * the raw byte stream. A named event costs a few bytes and is observable by the client that needs - * it. - * - *

The interval is the policy's, and the policy refuses a heartbeat at or above the idle timeout. - * A server that times out its own healthy streams between beats is the failure that produces. - */ -public final class WebFluxSseHeartbeat { - - /** The event name the heartbeat is published under. */ - public static final String EVENT_NAME = "heartbeat"; - - private WebFluxSseHeartbeat() {} - - /** - * The keepalive stream. - * - * @param policy supplies the interval - * @param the data type of the stream it will be merged into - */ - public static Flux> events(WebStreamPolicy policy) { - Objects.requireNonNull(policy, "policy"); - Duration interval = policy.heartbeatInterval(); - return Flux.interval(interval, interval) - .map(tick -> ServerSentEvent.builder().event(EVENT_NAME).comment("keepalive").build()); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/webflux/WebFluxStreamAdmission.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/webflux/WebFluxStreamAdmission.java deleted file mode 100644 index be63236a..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/webflux/WebFluxStreamAdmission.java +++ /dev/null @@ -1,124 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.advanced.webflux; - -import dev.caskeleton.adapter.inbound.web.advanced.stream.StreamId; -import dev.caskeleton.adapter.inbound.web.advanced.stream.WebStreamRegistry; -import dev.caskeleton.adapter.inbound.web.advanced.stream.WebStreamSession; -import dev.caskeleton.adapter.inbound.web.advanced.stream.WebStreamTermination; -import java.time.Instant; -import java.util.Objects; -import java.util.concurrent.atomic.AtomicBoolean; -import reactor.core.Disposable; - -/** - * Admits a reactive stream into the node's registry, and releases the slot when it ends. - * - *

Reactive streams are cheap in threads and not in everything else — each holds a connection, a - * subscription and whatever the source keeps for it. A node with ten thousand of them is idle by - * every thread metric and out of file descriptors. - * - *

The release is idempotent because Reactor can deliver more than one terminal signal to the - * handlers attached here: a cancel racing a complete is normal at the moment a client disconnects - * from a finishing stream. Releasing twice would return a slot that was already returned, and the - * registry would drift below the real count until it admitted more streams than it has capacity - * for. - */ -public final class WebFluxStreamAdmission { - - private final WebStreamRegistry registry; - - public WebFluxStreamAdmission(WebStreamRegistry registry) { - this.registry = Objects.requireNonNull(registry, "registry"); - } - - /** - * Try to admit a stream. - * - * @return the admitted session's release handle, or empty when the node is full - */ - public java.util.Optional admit( - StreamId streamId, Instant now, Disposable subscription) { - Objects.requireNonNull(streamId, "streamId"); - Objects.requireNonNull(now, "now"); - ReactiveSession session = new ReactiveSession(streamId, now, subscription); - if (!registry.register(session)) { - return java.util.Optional.empty(); - } - return java.util.Optional.of(new Admitted(session)); - } - - /** How many streams this node holds. */ - public int activeStreams() { - return registry.activeStreams(); - } - - /** A handle that returns the slot exactly once. */ - public final class Admitted { - - private final ReactiveSession session; - private final AtomicBoolean released = new AtomicBoolean(); - - private Admitted(ReactiveSession session) { - this.session = session; - } - - /** The registered session. */ - public WebStreamSession session() { - return session; - } - - /** Return the slot. Safe to call more than once; only the first call counts. */ - public void release() { - if (released.compareAndSet(false, true)) { - registry.deregister(session.streamId()); - } - } - } - - /** A registry entry backed by a Reactor subscription. */ - private static final class ReactiveSession implements WebStreamSession { - - private final StreamId streamId; - private final Instant startedAt; - private final Disposable subscription; - private final AtomicBoolean reconnectRequested = new AtomicBoolean(); - - ReactiveSession(StreamId streamId, Instant startedAt, Disposable subscription) { - this.streamId = streamId; - this.startedAt = startedAt; - this.subscription = subscription; - } - - @Override - public StreamId streamId() { - return streamId; - } - - @Override - public Instant startedAt() { - return startedAt; - } - - @Override - public void requestReconnect() { - // Recorded rather than acted on. There is no in-band way to ask a reactive SSE consumer to - // reconnect without emitting into its stream, and the drain's own terminal event is what - // does that — this flag is what lets the drain tell an asked stream from an unasked one. - reconnectRequested.set(true); - } - - @Override - public void forceClose(WebStreamTermination reason) { - Objects.requireNonNull(reason, "reason"); - if (subscription != null && !subscription.isDisposed()) { - // Disposing propagates cancellation upstream, which is the point: the source must stop - // producing for a stream nobody is reading. - subscription.dispose(); - } - } - - @Override - public boolean open() { - return subscription == null || !subscription.isDisposed(); - } - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/webflux/WebFluxStreamWriter.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/webflux/WebFluxStreamWriter.java deleted file mode 100644 index f88258c1..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/webflux/WebFluxStreamWriter.java +++ /dev/null @@ -1,70 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.advanced.webflux; - -import dev.caskeleton.adapter.inbound.web.advanced.stream.WebStreamPolicy; -import dev.caskeleton.adapter.inbound.web.advanced.stream.encoding.NdjsonRecord; -import dev.caskeleton.adapter.inbound.web.advanced.stream.encoding.StreamFraming; -import dev.caskeleton.adapter.inbound.web.advanced.stream.encoding.StreamRecordEncoder; -import java.util.Objects; -import org.springframework.core.io.buffer.DataBuffer; -import org.springframework.core.io.buffer.DataBufferFactory; -import reactor.core.publisher.Flux; - -/** - * Writes NDJSON or JSON-seq as a reactive body. - * - *

Buffers are released on cancellation and on error, not only on the happy path. A {@code - * DataBuffer} from a pooled factory is reference-counted: one that is allocated and never released - * is a leak that Netty reports as a warning nobody reads, and the symptom is a heap that grows with - * the number of streams that were cancelled rather than with the number that are open. - * `doOnDiscard` is the hook that covers the cancellation path, which is exactly the path a - * long-lived stream normally takes. - * - *

The framing itself is shared with the servlet writer. Two implementations of "one JSON value - * then a newline" would be two chances to disagree about whether the last record gets one. - */ -public final class WebFluxStreamWriter { - - private final StreamRecordEncoder encoder; - private final StreamFraming framing; - private final WebStreamPolicy policy; - - public WebFluxStreamWriter( - StreamRecordEncoder encoder, StreamFraming framing, WebStreamPolicy policy) { - this.encoder = Objects.requireNonNull(encoder, "encoder"); - this.framing = Objects.requireNonNull(framing, "framing"); - this.policy = Objects.requireNonNull(policy, "policy"); - } - - /** The media type to set on the response. */ - public String mediaType() { - return framing.mediaType(); - } - - /** - * Write a stream of records as buffers. - * - * @param records the source, terminal record included - * @param buffers the response's buffer factory - * @param the item type - */ - public Flux write(Flux> records, DataBufferFactory buffers) { - Objects.requireNonNull(records, "records"); - Objects.requireNonNull(buffers, "buffers"); - return records - .onBackpressureBuffer(policy.maxBufferedItems()) - // The pair, not the buffer alone: onBackpressureBuffer propagates demand and never closes - // anything by itself, so a subscriber that stops requesting would just stop the source. - .onBackpressureError() - .onErrorMap( - reactor.core.Exceptions::isOverflow, - overflow -> new SlowConsumerClosedException(policy.maxBufferedItems())) - .map(record -> buffers.wrap(encode(record))) - // Covers cancellation, which for a long-lived stream is how it usually ends. Without it the - // heap grows with the number of streams that were cancelled. - .doOnDiscard(DataBuffer.class, org.springframework.core.io.buffer.DataBufferUtils::release); - } - - private byte[] encode(Object record) { - return framing == StreamFraming.NDJSON ? encoder.ndjson(record) : encoder.jsonSequence(record); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/budget/WebBudgetExceededException.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/budget/WebBudgetExceededException.java deleted file mode 100644 index 7c429e0e..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/budget/WebBudgetExceededException.java +++ /dev/null @@ -1,56 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.budget; - -import java.util.Objects; - -/** - * A request or response crossed a declared bound. - * - *

Carries which bound, because the answer differs: an oversized body is 413 and the caller can - * fix it, an execution overrun is 503 and the caller cannot, and a response that grew past its - * bound is the platform's own fault. A single "too big" exception would have the error mapper - * guess, and it would guess 413 for all three. - * - * @see WebBudgetViolation - */ -public final class WebBudgetExceededException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - private final transient WebBudgetViolation violation; - private final long observed; - private final long allowed; - - /** - * A crossed bound. - * - * @param violation which bound - * @param observed what was measured - * @param allowed what the profile permits - */ - public WebBudgetExceededException(WebBudgetViolation violation, long observed, long allowed) { - super( - Objects.requireNonNull(violation, "violation") - + ": observed " - + observed - + ", allowed " - + allowed); - this.violation = violation; - this.observed = observed; - this.allowed = allowed; - } - - /** Which bound was crossed. */ - public WebBudgetViolation violation() { - return violation; - } - - /** What was measured. */ - public long observed() { - return observed; - } - - /** What the profile permits. */ - public long allowed() { - return allowed; - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/budget/WebBudgetMeter.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/budget/WebBudgetMeter.java deleted file mode 100644 index 219b3382..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/budget/WebBudgetMeter.java +++ /dev/null @@ -1,89 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.budget; - -import java.util.Objects; -import java.util.concurrent.atomic.AtomicLong; - -/** - * A running byte count that fails the moment it crosses its bound. - * - *

Counting as bytes arrive, rather than measuring what arrived, is the whole point. Reading a - * body into memory to check its size means a caller can exhaust the heap with a request the - * platform was going to reject anyway — the check becomes the vulnerability it was added to - * prevent. The same applies on the way out: a response is refused as it is written, not after it - * has been assembled. - * - *

{@code AtomicLong} because a reactive response is written from whichever thread the pipeline - * is on, and two writes racing on a plain {@code long} would both read a total below the bound. - */ -public final class WebBudgetMeter { - - private final WebBudgetViolation violation; - private final long limit; - private final AtomicLong counted = new AtomicLong(); - - /** - * A meter for one dimension. - * - * @param violation what to report when the bound is crossed - * @param limit the bound - */ - public WebBudgetMeter(WebBudgetViolation violation, long limit) { - this.violation = Objects.requireNonNull(violation, "violation"); - if (limit <= 0) { - throw new IllegalArgumentException("a budget of " + limit + " bytes admits nothing"); - } - this.limit = limit; - } - - /** - * Counts bytes and refuses the moment the bound is crossed. - * - * @param byteCount how many bytes just moved - * @throws WebBudgetExceededException when the running total exceeds the bound - */ - public void add(long byteCount) { - if (byteCount <= 0) { - return; - } - long total = counted.addAndGet(byteCount); - if (total > limit) { - throw new WebBudgetExceededException(violation, total, limit); - } - } - - /** - * Refuses a declared size before a single byte is read. - * - *

{@code Content-Length} is a claim, not a measurement, so it is checked *as well as* the - * running count and never instead of it. Believing it alone would let a chunked request, or a - * lying one, walk straight past the bound. - * - * @param declared the value the caller declared, or -1 when it declared none - */ - public void declared(long declared) { - if (declared > limit) { - throw new WebBudgetExceededException(violation, declared, limit); - } - } - - /** - * Forgets everything counted so far. - * - *

Called when a response buffer is discarded. Those bytes never left the server, so a meter - * that kept counting them would refuse the small error document that is about to replace them — - * and the caller would get the container's own error page instead of the platform's. - */ - public void reset() { - counted.set(0); - } - - /** How many bytes have moved. */ - public long counted() { - return counted.get(); - } - - /** The bound. */ - public long limit() { - return limit; - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/budget/WebBudgetOutcome.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/budget/WebBudgetOutcome.java deleted file mode 100644 index df6334d8..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/budget/WebBudgetOutcome.java +++ /dev/null @@ -1,40 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.budget; - -/** - * The message a crossed bound is published with. - * - *

Only the message. An earlier draft also had a violation-to-status table here, and it was wrong - * within a day: {@code ProblemCatalog} already pins a status to every code, this table said - * something different for two of them, and {@code requireStatusAgreement} refused the response — - * turning a 400 into a 500. The status now comes from the catalog by way of the code, so there is - * one table and nothing to keep in sync. - * - *

What is left is genuinely this module's: a budget is arithmetic, and its message should not - * need a catalog to be testable. - */ -public final class WebBudgetOutcome { - - private WebBudgetOutcome() {} - - /** - * A message safe to publish. - * - *

The limit is included and the observed value is not. The limit is public API — a client - * needs it to comply — while the observed value can restate content the caller sent, and echoing - * a request back is how a size error becomes a reflection gadget. - */ - public static String detailFor(WebBudgetViolation violation, long allowed) { - return switch (violation) { - case URI_TOO_LONG -> "the request URI exceeds " + allowed + " bytes"; - case HEADERS_TOO_LARGE -> "the request headers exceed " + allowed + " bytes"; - case BODY_TOO_LARGE -> "the request body exceeds " + allowed + " bytes"; - case TOO_MANY_QUERY_PARAMETERS -> - "the request carries more than " + allowed + " query parameters"; - case JSON_TOO_DEEP -> "the request body nests deeper than " + allowed + " levels"; - case ARRAY_TOO_LARGE -> "an array in the request body exceeds " + allowed + " elements"; - case TOO_MANY_MULTIPART_PARTS -> "the request carries more than " + allowed + " parts"; - case EXECUTION_TIME_EXCEEDED -> "the operation exceeded its time budget"; - case RESPONSE_TOO_LARGE -> "the response exceeded its size budget"; - }; - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/budget/WebBudgetViolation.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/budget/WebBudgetViolation.java deleted file mode 100644 index 5ccabea1..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/budget/WebBudgetViolation.java +++ /dev/null @@ -1,39 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.budget; - -/** - * Which bound a request exceeded, named so the response can be honest without being useful to an - * attacker. - * - *

The axis is reported; the numbers are not. Telling a caller "the body limit is 262144 bytes" - * turns probing into a single request, and the caller who legitimately hit the limit does not need - * the exact figure to know they sent too much. - */ -public enum WebBudgetViolation { - - /** The request URI was longer than the profile allows. */ - URI_TOO_LONG, - - /** The header block was larger than the profile allows. */ - HEADERS_TOO_LARGE, - - /** More query parameters than the profile allows. */ - TOO_MANY_QUERY_PARAMETERS, - - /** The request body was larger than the profile allows. */ - BODY_TOO_LARGE, - - /** The JSON document nested deeper than the profile allows. */ - JSON_TOO_DEEP, - - /** A JSON array held more elements than the profile allows. */ - ARRAY_TOO_LARGE, - - /** The multipart body held more parts than the profile allows. */ - TOO_MANY_MULTIPART_PARTS, - - /** The operation ran past its deadline. */ - EXECUTION_TIME_EXCEEDED, - - /** The response would be larger than the profile allows. */ - RESPONSE_TOO_LARGE -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/cache/WebCacheHeaders.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/cache/WebCacheHeaders.java deleted file mode 100644 index b71cd1d4..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/cache/WebCacheHeaders.java +++ /dev/null @@ -1,28 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.cache; - -import java.util.Objects; -import java.util.Optional; - -/** - * The cache headers one policy produces. - * - *

Rendered once, here, rather than assembled per controller. {@code Cache-Control} is a - * directive list whose meaning changes with what is and is not present, and a response that - * assembles it by appending strings ends up with combinations nobody chose — {@code no-cache} and - * {@code max-age} together, or {@code public} on a response that also says {@code no-store}. - * - * @param cacheControl the {@code Cache-Control} value - * @param vary the {@code Vary} value, or empty when nothing varies - */ -public record WebCacheHeaders(String cacheControl, Optional vary) { - - public WebCacheHeaders { - Objects.requireNonNull(cacheControl, "cacheControl"); - Objects.requireNonNull(vary, "vary"); - if (cacheControl.isBlank()) { - throw new IllegalArgumentException( - "a blank Cache-Control is not a policy; it leaves every cache to guess, and they guess" - + " differently"); - } - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/cache/WebCachePolicy.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/cache/WebCachePolicy.java deleted file mode 100644 index 31b21401..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/cache/WebCachePolicy.java +++ /dev/null @@ -1,72 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.cache; - -import java.time.Duration; -import java.util.Objects; -import java.util.Optional; - -/** - * One named caching decision. - * - *

Named, because "how long may this be cached" is a decision somebody has to make on purpose. A - * controller that sets its own headers makes it implicitly, differently each time, and usually only - * for the endpoints whose author happened to think about it — leaving the rest to whatever a proxy - * decides in the absence of any directive, which is not nothing. - * - *

The constructor refuses the combinations that are self-contradictory or unsafe. The one worth - * naming is {@code sharedCacheAllowed} on a response that requires authorization: a shared cache - * storing it will serve it to the next caller who asks for the same URL, and that caller is not the - * one who authenticated. - * - * @param name the profile's identity - * @param cacheControl the rendered directive list - * @param vary which request headers change the representation - * @param sharedCacheAllowed whether a proxy may store it - * @param freshness how long it stays fresh, when it does - */ -public record WebCachePolicy( - String name, - String cacheControl, - WebVaryPolicy vary, - boolean sharedCacheAllowed, - Optional freshness) { - - public WebCachePolicy { - Objects.requireNonNull(name, "name"); - Objects.requireNonNull(cacheControl, "cacheControl"); - Objects.requireNonNull(vary, "vary"); - Objects.requireNonNull(freshness, "freshness"); - if (name.isBlank()) { - throw new IllegalArgumentException("a cache policy needs a name to be referenced by"); - } - if (cacheControl.contains("no-store") && freshness.isPresent()) { - throw new IllegalArgumentException( - "no-store and a freshness lifetime contradict each other: one says never keep this, the" - + " other says how long to keep it"); - } - if (cacheControl.contains("public") && !sharedCacheAllowed) { - throw new IllegalArgumentException( - "a policy marked public is telling shared caches to store it; sharedCacheAllowed must" - + " say the same thing"); - } - if (cacheControl.contains("private") && sharedCacheAllowed) { - throw new IllegalArgumentException( - "a policy marked private forbids shared caches; sharedCacheAllowed must say the same"); - } - } - - /** The headers this policy produces. */ - public WebCacheHeaders headers() { - return new WebCacheHeaders(cacheControl, Optional.ofNullable(vary.headerValue())); - } - - /** - * Whether this policy may be applied to a response that required authorization. - * - *

The check the design asks for. Storing an authorized response in a shared cache is - * occasionally right — a catalogue behind a login that is identical for everyone — but it is - * never right by default, so it takes a profile that says so explicitly. - */ - public boolean safeForAuthorizedResponse() { - return !sharedCacheAllowed; - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/cache/WebCachePolicyCatalog.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/cache/WebCachePolicyCatalog.java deleted file mode 100644 index b09aadbd..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/cache/WebCachePolicyCatalog.java +++ /dev/null @@ -1,120 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.cache; - -import java.time.Duration; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; - -/** - * The cache profiles this API publishes. - * - *

A closed catalog rather than free-form headers, for the same reason {@code ProblemCode} is - * closed: the set of caching decisions an API makes is small, and each one is a review. Four - * profiles cover what a JSON API actually needs, and an endpoint that fits none of them is an - * endpoint whose caching nobody has thought about yet. - */ -public final class WebCachePolicyCatalog { - - private final Map profiles; - - private WebCachePolicyCatalog(Map profiles) { - this.profiles = profiles; - } - - /** - * Anything a caller must not find in a cache: personal data, tokens, one-time values. - * - *

{@code no-store}, not {@code no-cache}. They are routinely confused and mean opposite - * things: {@code no-cache} permits storing the response and requires revalidating before reuse, - * so the document does sit in the cache and on the disk behind it. {@code no-store} is the one - * that says do not write this down. - */ - public static WebCachePolicy sensitive() { - return new WebCachePolicy( - "sensitive", "private, no-store", WebVaryPolicy.none(), false, Optional.empty()); - } - - /** - * Content addressed by a digest or a version, which by construction cannot change. - * - *

{@code immutable} suppresses the revalidation a browser would otherwise do on reload. It is - * only honest for a URL whose content genuinely cannot change; on anything else it strands - * clients on a stale copy for a year with no way to invalidate it. - */ - public static WebCachePolicy immutableAsset() { - return new WebCachePolicy( - "immutable-asset", - "public, max-age=31536000, immutable", - WebVaryPolicy.varyingOn(Set.of("accept-encoding")), - true, - Optional.of(Duration.ofDays(365))); - } - - /** - * Shared content that changes, served with a validator. - * - *

{@code max-age=0, must-revalidate} rather than {@code no-cache}: they behave the same way - * for a compliant cache, and this spelling keeps the entry storable and revalidatable, which is - * what makes a 304 possible at all. - */ - public static WebCachePolicy revalidated() { - return new WebCachePolicy( - "revalidated", - "public, max-age=0, must-revalidate", - WebVaryPolicy.varyingOn(Set.of("accept", "accept-encoding", "accept-language")), - true, - Optional.of(Duration.ZERO)); - } - - /** - * A per-caller response a browser may keep briefly but no proxy may store. - * - *

The right default for an authenticated read: the caller's own back button works, and nothing - * between them and the server keeps a copy. - */ - public static WebCachePolicy browserPrivate() { - return new WebCachePolicy( - "browser-private", - "private, max-age=30", - WebVaryPolicy.varyingOn(Set.of("accept", "accept-language")), - false, - Optional.ofNullable(Duration.ofSeconds(30))); - } - - /** The four published profiles. */ - public static WebCachePolicyCatalog standard() { - Map profiles = new LinkedHashMap<>(); - for (WebCachePolicy policy : - new WebCachePolicy[] {sensitive(), immutableAsset(), revalidated(), browserPrivate()}) { - profiles.put(policy.name(), policy); - } - return new WebCachePolicyCatalog(Map.copyOf(profiles)); - } - - /** - * The named profile. - * - * @throws IllegalArgumentException when no profile has that name - */ - public WebCachePolicy require(String name) { - Objects.requireNonNull(name, "name"); - WebCachePolicy policy = profiles.get(name); - if (policy == null) { - throw new IllegalArgumentException( - "no cache profile named " - + name - + "; the published set is " - + profiles.keySet() - + ", and an endpoint that fits none of them needs a reviewed profile, not" - + " hand-written headers"); - } - return policy; - } - - /** Every published profile. */ - public Map registered() { - return profiles; - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/cache/WebVaryPolicy.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/cache/WebVaryPolicy.java deleted file mode 100644 index 19c1f5e8..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/cache/WebVaryPolicy.java +++ /dev/null @@ -1,90 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.cache; - -import java.util.List; -import java.util.Locale; -import java.util.Objects; -import java.util.Set; -import java.util.SortedSet; -import java.util.TreeSet; - -/** - * Which request headers a cache must key on. - * - *

{@code Vary} is one of the few headers where both mistakes are expensive and neither is - * visible in testing. Omit a header that changes the representation and a shared cache serves one - * caller's document to another — a German page to an English reader, or worse, one tenant's data to - * another. List a header that does not change it, or one that is effectively unique per client, and - * the cache stops hitting entirely while still paying to store everything. - * - *

So the set is closed. A header is admitted only if the platform can say what it changes, and - * the ones that are always wrong are refused by name rather than by review. - */ -public final class WebVaryPolicy { - - /** - * Headers that must never appear in {@code Vary}. - * - *

Each is effectively unique per client, so keying on it gives every caller a private cache - * entry — all of the storage cost of caching and none of the sharing. - */ - private static final Set NEVER_VARY = - Set.of("user-agent", "cookie", "referer", "authorization", "date", "host"); - - // Ordered as well as unique. `Vary` order carries no meaning to a cache, but a header whose - // text changes between two servers serving the same route is a difference an operator has to - // chase, and a set built from Set.of() renders in whatever order the hash happened to produce. - private final List ordered; - private final Set membership; - - private WebVaryPolicy(List ordered) { - this.ordered = ordered; - this.membership = Set.copyOf(ordered); - } - - /** A policy that varies on nothing. */ - public static WebVaryPolicy none() { - return new WebVaryPolicy(List.of()); - } - - /** - * A policy over the named headers. - * - * @param headerNames the headers that change the representation - * @throws IllegalArgumentException when a header is one that must never be varied on - */ - public static WebVaryPolicy varyingOn(Set headerNames) { - Objects.requireNonNull(headerNames, "headerNames"); - SortedSet normalized = new TreeSet<>(); - for (String name : headerNames) { - Objects.requireNonNull(name, "header name"); - String lower = name.toLowerCase(Locale.ROOT); - if (NEVER_VARY.contains(lower)) { - throw new IllegalArgumentException( - "Vary must not include " - + name - + ": it is effectively unique per client, so every caller would get a private" - + " cache entry and the cache would stop being one"); - } - if (lower.isBlank()) { - throw new IllegalArgumentException("a blank header name is not a header"); - } - normalized.add(lower); - } - return new WebVaryPolicy(List.copyOf(normalized)); - } - - /** The headers, lowercased. */ - public Set headerNames() { - return membership; - } - - /** The {@code Vary} header value, or null when nothing varies. */ - public String headerValue() { - return ordered.isEmpty() ? null : String.join(", ", ordered); - } - - /** Whether a header is one that may never be varied on. */ - public static boolean forbidden(String headerName) { - return headerName != null && NEVER_VARY.contains(headerName.toLowerCase(Locale.ROOT)); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/conditional/ConditionalReadDecision.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/conditional/ConditionalReadDecision.java deleted file mode 100644 index a5bfb5ad..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/conditional/ConditionalReadDecision.java +++ /dev/null @@ -1,17 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.conditional; - -/** - * What a conditional read should answer. - * - *

Two outcomes, and the platform never invents a third. A validator that matches means the - * client already holds the representation and the response is a 304 with no body; anything else is - * the full representation. There is no "probably unchanged". - */ -public enum ConditionalReadDecision { - - /** The client's validator matched: answer 304 and write no body. */ - NOT_MODIFIED, - - /** No validator matched: answer the full representation. */ - SERVE_REPRESENTATION -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/conditional/ConditionalReadEvaluator.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/conditional/ConditionalReadEvaluator.java deleted file mode 100644 index de3d8495..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/conditional/ConditionalReadEvaluator.java +++ /dev/null @@ -1,69 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.conditional; - -import java.util.List; -import java.util.Objects; - -/** - * Decides whether a {@code GET} or {@code HEAD} may be answered with a 304. - * - *

Weak comparison, per RFC 9110. A read is asking "is what I hold still good enough to render", - * and a weak validator answers that: two representations that differ only in whitespace are the - * same to a reader. Using strong comparison here would send a full body for every cosmetic - * difference, which is the caching bug that makes people turn conditional requests off. - * - *

{@code If-None-Match: *} matches whenever a representation exists at all, which is what makes - * it useful on a read of a resource whose validator the client has never seen. - */ -public final class ConditionalReadEvaluator { - - /** - * Evaluates a conditional read. - * - * @param ifNoneMatchHeader the raw {@code If-None-Match} header, or null - * @param currentTag the resource's current validator, or null when it has none - */ - public ConditionalReadDecision evaluate(String ifNoneMatchHeader, EntityTag currentTag) { - if (ifNoneMatchHeader == null || ifNoneMatchHeader.isBlank()) { - return ConditionalReadDecision.SERVE_REPRESENTATION; - } - if (EntityTagCodec.isWildcard(ifNoneMatchHeader)) { - return currentTag == null - ? ConditionalReadDecision.SERVE_REPRESENTATION - : ConditionalReadDecision.NOT_MODIFIED; - } - if (currentTag == null) { - return ConditionalReadDecision.SERVE_REPRESENTATION; - } - List candidates = EntityTagCodec.parseList(ifNoneMatchHeader); - boolean matched = candidates.stream().anyMatch(currentTag::matchesWeakly); - return matched - ? ConditionalReadDecision.NOT_MODIFIED - : ConditionalReadDecision.SERVE_REPRESENTATION; - } - - /** - * Whether a 304 may be answered. - * - * @param ifNoneMatchHeader the raw header - * @param currentTag the current validator - */ - public boolean notModified(String ifNoneMatchHeader, EntityTag currentTag) { - return evaluate(ifNoneMatchHeader, currentTag) == ConditionalReadDecision.NOT_MODIFIED; - } - - /** - * The validator a response carries. - * - *

Separate from the application's own version so the two cannot be assumed to be the same - * type. A storage ETag, a provider ETag and an optimistic-lock revision are all validators of - * something, and treating one as interchangeable with another is how a client's conditional write - * is compared against a value the resource does not have. - * - * @param applicationVersion the application's own version marker - * @param strong whether the mapping is byte-exact - */ - public EntityTag toEntityTag(String applicationVersion, boolean strong) { - Objects.requireNonNull(applicationVersion, "applicationVersion"); - return strong ? EntityTag.strong(applicationVersion) : EntityTag.weak(applicationVersion); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/conditional/EntityTag.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/conditional/EntityTag.java deleted file mode 100644 index 0b35c91c..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/conditional/EntityTag.java +++ /dev/null @@ -1,83 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.conditional; - -import java.util.Objects; - -/** - * One entity tag, and whether it is strong or weak. - * - *

The distinction is not decorative. A weak validator says "semantically equivalent" — a - * response whose whitespace or compression differs may share one — so it is sound for a cached read - * and unsound for a conditional write. Using a weak tag for {@code If-Match} means two writers - * whose representations differ only cosmetically both pass the precondition, and the second - * overwrites the first. - * - *

The value excludes the quotes and the {@code W/} prefix; those are wire syntax, and keeping - * them in the value is how a comparison ends up matching {@code "v1"} against {@code v1}. - * - * @param value the opaque validator, without quotes - * @param weak whether this is a weak validator - */ -public record EntityTag(String value, boolean weak) { - - public EntityTag { - Objects.requireNonNull(value, "value"); - if (value.isBlank()) { - throw new IllegalArgumentException("an entity tag needs a value"); - } - if (value.length() > 256) { - throw new IllegalArgumentException("entity tag is longer than any validator needs to be"); - } - if (value.indexOf('"') >= 0) { - throw new IllegalArgumentException( - "an entity tag value excludes its quotes; keeping them is how a comparison matches" - + " the wrong thing"); - } - for (int index = 0; index < value.length(); index++) { - char character = value.charAt(index); - if (character < 0x21 || character == 0x7F) { - throw new IllegalArgumentException("entity tag carries a character the wire cannot hold"); - } - } - } - - /** - * A strong validator: byte-for-byte identity, and the only kind a write may be conditioned on. - */ - public static EntityTag strong(String value) { - return new EntityTag(value, false); - } - - /** A weak validator: semantic equivalence, sound for a cached read. */ - public static EntityTag weak(String value) { - return new EntityTag(value, true); - } - - /** The wire form, with quotes and the weakness prefix. */ - public String toHeaderValue() { - return (weak ? "W/" : "") + '"' + value + '"'; - } - - /** - * Whether this tag matches another strongly. - * - *

Strong comparison: both must be strong and the values equal. Required for {@code If-Match}. - */ - public boolean matchesStrongly(EntityTag other) { - return other != null && !weak && !other.weak && value.equals(other.value); - } - - /** - * Whether this tag matches another weakly. - * - *

Weak comparison: the values are equal whatever their strength. Sufficient for {@code - * If-None-Match} on a read. - */ - public boolean matchesWeakly(EntityTag other) { - return other != null && value.equals(other.value); - } - - @Override - public String toString() { - return toHeaderValue(); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/conditional/EntityTagCodec.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/conditional/EntityTagCodec.java deleted file mode 100644 index 331e6345..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/conditional/EntityTagCodec.java +++ /dev/null @@ -1,72 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.conditional; - -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; - -/** - * Reads and writes the {@code ETag}, {@code If-Match} and {@code If-None-Match} header syntax. - * - *

Parsing is strict and returns nothing rather than guessing. A malformed validator that is - * treated as "no validator" turns a conditional request into an unconditional one, which is how a - * lost update happens with the precondition header present in the request log. - * - *

{@code *} is a distinct answer rather than a tag, because it means "any current - * representation" and no comparison against a value can express that. - */ -public final class EntityTagCodec { - - /** The wildcard, which matches any existing representation. */ - public static final String WILDCARD = "*"; - - private EntityTagCodec() {} - - /** - * Parses a single {@code ETag} header value. - * - * @param headerValue the raw header, or null - * @return the tag, or empty when the header is absent or malformed - */ - public static Optional parseSingle(String headerValue) { - if (headerValue == null) { - return Optional.empty(); - } - String candidate = headerValue.trim(); - boolean weak = false; - if (candidate.startsWith("W/")) { - weak = true; - candidate = candidate.substring(2); - } - if (candidate.length() < 2 || !candidate.startsWith("\"") || !candidate.endsWith("\"")) { - return Optional.empty(); - } - String value = candidate.substring(1, candidate.length() - 1); - try { - return Optional.of(new EntityTag(value, weak)); - } catch (IllegalArgumentException malformed) { - return Optional.empty(); - } - } - - /** - * Parses a comma-separated {@code If-Match} or {@code If-None-Match} list. - * - * @param headerValue the raw header, or null - * @return every tag that parsed; a malformed entry is dropped rather than failing the list - */ - public static List parseList(String headerValue) { - if (headerValue == null || headerValue.isBlank()) { - return List.of(); - } - List tags = new ArrayList<>(); - for (String entry : headerValue.split(",", -1)) { - parseSingle(entry).ifPresent(tags::add); - } - return List.copyOf(tags); - } - - /** Whether a header value is the wildcard. */ - public static boolean isWildcard(String headerValue) { - return headerValue != null && WILDCARD.equals(headerValue.trim()); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/conditional/HttpPrecondition.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/conditional/HttpPrecondition.java deleted file mode 100644 index 519b2079..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/conditional/HttpPrecondition.java +++ /dev/null @@ -1,42 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.conditional; - -import java.util.List; -import java.util.Objects; - -/** - * The conditional headers a mutation arrived with. - * - *

Held as a value so the evaluator has one argument rather than four, and so "no precondition" - * is a state somebody constructed rather than four nulls that might mean anything. - * - * @param ifMatch the {@code If-Match} tags, empty when the header was absent - * @param ifMatchWildcard whether {@code If-Match: *} was sent - * @param ifNoneMatchWildcard whether {@code If-None-Match: *} was sent - */ -public record HttpPrecondition( - List ifMatch, boolean ifMatchWildcard, boolean ifNoneMatchWildcard) { - - public HttpPrecondition { - Objects.requireNonNull(ifMatch, "ifMatch"); - ifMatch = List.copyOf(ifMatch); - } - - /** No conditional header was sent. */ - public static HttpPrecondition none() { - return new HttpPrecondition(List.of(), false, false); - } - - /** Reads the two headers off a request. */ - public static HttpPrecondition of(String ifMatchHeader, String ifNoneMatchHeader) { - boolean ifMatchWildcard = EntityTagCodec.isWildcard(ifMatchHeader); - return new HttpPrecondition( - ifMatchWildcard ? List.of() : EntityTagCodec.parseList(ifMatchHeader), - ifMatchWildcard, - EntityTagCodec.isWildcard(ifNoneMatchHeader)); - } - - /** Whether any precondition was supplied. */ - public boolean present() { - return !ifMatch.isEmpty() || ifMatchWildcard || ifNoneMatchWildcard; - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/conditional/MutationPreconditionEvaluator.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/conditional/MutationPreconditionEvaluator.java deleted file mode 100644 index dfd6b5da..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/conditional/MutationPreconditionEvaluator.java +++ /dev/null @@ -1,73 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.conditional; - -import dev.caskeleton.adapter.inbound.web.operation.PreconditionPolicy; -import java.util.Objects; - -/** - * Decides whether a mutation's preconditions hold. - * - *

Strong comparison, and this is where the strong/weak distinction earns its keep. A weak - * validator means "semantically equivalent", so two writers whose representations differ only - * cosmetically would both pass {@code If-Match} and the second would overwrite the first. RFC 9110 - * requires strong comparison here and so does correctness. - * - *

The 412/409 split is the design's and is easy to collapse. A 412 means a precondition the - * client supplied no longer holds — re-read and retry. A 409 means the business state conflicts and - * no conditional header was involved — retrying the same request will not help. Answering both with - * 409 loses the "re-read and retry" instruction; answering both with 412 tells a client to retry - * something that cannot succeed. - */ -public final class MutationPreconditionEvaluator { - - /** - * Evaluates a mutation's preconditions. - * - * @param policy whether this operation requires, accepts or ignores a precondition - * @param precondition what the request supplied - * @param currentTag the resource's current validator, or null when the resource does not exist - */ - public PreconditionDecision evaluate( - PreconditionPolicy policy, HttpPrecondition precondition, EntityTag currentTag) { - Objects.requireNonNull(policy, "policy"); - Objects.requireNonNull(precondition, "precondition"); - - if (precondition.ifNoneMatchWildcard()) { - // Create-only: the caller is saying "only if it does not exist yet". - return currentTag == null - ? PreconditionDecision.PROCEED - : PreconditionDecision.PRECONDITION_FAILED; - } - - if (precondition.ifMatchWildcard()) { - // Update-only: the caller is saying "only if it exists", whatever its version. - return currentTag == null - ? PreconditionDecision.PRECONDITION_FAILED - : PreconditionDecision.PROCEED; - } - - if (!precondition.ifMatch().isEmpty()) { - if (currentTag == null) { - return PreconditionDecision.PRECONDITION_FAILED; - } - boolean matched = precondition.ifMatch().stream().anyMatch(currentTag::matchesStrongly); - return matched ? PreconditionDecision.PROCEED : PreconditionDecision.PRECONDITION_FAILED; - } - - return policy == PreconditionPolicy.REQUIRED - ? PreconditionDecision.PRECONDITION_REQUIRED - : PreconditionDecision.PROCEED; - } - - /** - * Evaluates and throws rather than returning, for a call site that only handles the happy path. - * - * @throws WebPreconditionFailedException when the mutation must not run - */ - public void requireSatisfied( - PreconditionPolicy policy, HttpPrecondition precondition, EntityTag currentTag) { - PreconditionDecision decision = evaluate(policy, precondition, currentTag); - if (decision != PreconditionDecision.PROCEED) { - throw new WebPreconditionFailedException(decision); - } - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/conditional/PreconditionDecision.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/conditional/PreconditionDecision.java deleted file mode 100644 index 7fdf339f..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/conditional/PreconditionDecision.java +++ /dev/null @@ -1,21 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.conditional; - -/** - * What a conditional mutation should do. - * - *

{@link #PRECONDITION_REQUIRED} is separate from {@link #PRECONDITION_FAILED} because they tell - * a client different things. Failed means "somebody else changed it, re-read and retry"; required - * means "you did not send a precondition and this operation will not guess" — a 428, and a client - * that retries the same request unchanged will get the same answer forever. - */ -public enum PreconditionDecision { - - /** Every precondition held: the mutation may run. */ - PROCEED, - - /** A precondition was supplied and no longer holds: 412. */ - PRECONDITION_FAILED, - - /** The operation requires a precondition and none was supplied: 428. */ - PRECONDITION_REQUIRED -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/conditional/WebPreconditionFailedException.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/conditional/WebPreconditionFailedException.java deleted file mode 100644 index 4b41fd8f..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/conditional/WebPreconditionFailedException.java +++ /dev/null @@ -1,37 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.conditional; - -import java.util.Objects; - -/** - * A conditional mutation must not run. - * - *

Carries the decision rather than a status, so the transport maps it and the evaluator does not - * have to know about HTTP numbers. The two outcomes are genuinely different answers — 412 says - * re-read and retry, 428 says supply a precondition — and collapsing them into one exception would - * put the choice back at the call site. - * - *

Named {@code Web...} because this leaf already has a {@code PreconditionFailedException} from - * the pre-existing conditional package; two types with one name in one leaf is an import a reader - * has to check. - */ -public final class WebPreconditionFailedException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - private final PreconditionDecision decision; - - /** - * Creates the failure. - * - * @param decision which precondition outcome occurred - */ - public WebPreconditionFailedException(PreconditionDecision decision) { - super("the request's precondition was not satisfied: " + decision); - this.decision = Objects.requireNonNull(decision, "decision"); - } - - /** Which outcome occurred, so the transport can choose 412 or 428. */ - public PreconditionDecision decision() { - return decision; - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/cursor/CursorCodec.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/cursor/CursorCodec.java deleted file mode 100644 index c18becee..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/cursor/CursorCodec.java +++ /dev/null @@ -1,100 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.cursor; - -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.time.Duration; -import java.time.Instant; -import java.util.Base64; -import javax.crypto.Mac; -import javax.crypto.spec.SecretKeySpec; - -/** - * Opaque, signed, time-bounded pagination cursor codec. A cursor is {@code base64url(iat + ":" + - * payload)} plus an HMAC-SHA256 signature, so it is URL-safe, tamper-evident, and expires after a - * fixed TTL (24h). Clients MUST treat the token as opaque. See README for the design rationale. - */ -public final class CursorCodec { - - /** Default cursor TTL (24h). */ - public static final Duration DEFAULT_TTL = Duration.ofHours(24); - - private static final String HMAC_ALGORITHM = "HmacSHA256"; - private static final char SEP = '.'; - private static final Base64.Encoder ENC = Base64.getUrlEncoder().withoutPadding(); - private static final Base64.Decoder DEC = Base64.getUrlDecoder(); - - private final byte[] key; - private final Duration ttl; - - public CursorCodec(byte[] key, Duration ttl) { - if (key == null || key.length < 16) { - throw new IllegalArgumentException("cursor HMAC key must be at least 16 bytes"); - } - this.key = key.clone(); - this.ttl = ttl; - } - - /** Dev / test factory — NOT for production. */ - public static CursorCodec withDevKey() { - return new CursorCodec( - "ca-skeleton-dev-cursor-key-0001".getBytes(StandardCharsets.UTF_8), DEFAULT_TTL); - } - - /** Encodes an opaque payload string + issue instant into a signed URL-safe token. */ - public String encode(String payload, Instant issuedAt) { - String body = issuedAt.getEpochSecond() + ":" + payload; - String b64Body = ENC.encodeToString(body.getBytes(StandardCharsets.UTF_8)); - return b64Body + SEP + ENC.encodeToString(sign(b64Body)); - } - - /** - * Verifies signature + TTL and returns the original payload, or throws {@link CursorException}. - */ - public String decode(String token, Instant now) { - if (token == null || token.isBlank()) { - throw new CursorException("cursor token is missing"); - } - int dot = token.lastIndexOf(SEP); - if (dot <= 0 || dot == token.length() - 1) { - throw new CursorException("cursor token is malformed"); - } - String b64Body = token.substring(0, dot); - byte[] presented; - byte[] expected; - String body; - try { - presented = DEC.decode(token.substring(dot + 1)); - expected = sign(b64Body); - body = new String(DEC.decode(b64Body), StandardCharsets.UTF_8); - } catch (IllegalArgumentException e) { - throw new CursorException("cursor token is malformed"); - } - if (!MessageDigest.isEqual(expected, presented)) { - throw new CursorException("cursor token signature is invalid"); - } - int colon = body.indexOf(':'); - if (colon < 0) { - throw new CursorException("cursor token payload is malformed"); - } - long issuedAtEpoch; - try { - issuedAtEpoch = Long.parseLong(body.substring(0, colon)); - } catch (NumberFormatException e) { - throw new CursorException("cursor token payload is malformed"); - } - if (now.getEpochSecond() - issuedAtEpoch > ttl.toSeconds()) { - throw new CursorException("cursor token has expired"); - } - return body.substring(colon + 1); - } - - private byte[] sign(String data) { - try { - Mac mac = Mac.getInstance(HMAC_ALGORITHM); - mac.init(new SecretKeySpec(key, HMAC_ALGORITHM)); - return mac.doFinal(data.getBytes(StandardCharsets.UTF_8)); - } catch (Exception e) { - throw new IllegalStateException("HMAC computation failed", e); - } - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/cursor/CursorException.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/cursor/CursorException.java deleted file mode 100644 index 2d5ccd57..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/cursor/CursorException.java +++ /dev/null @@ -1,15 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.cursor; - -/** - * Raised when an opaque pagination cursor fails verification — tampered HMAC signature, malformed - * encoding, or expired TTL. Controllers map it to 400 VALIDATION_FAILED and advise re-requesting - * the first page. - */ -public class CursorException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - public CursorException(String message) { - super(message); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/BudgetProblemMapper.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/BudgetProblemMapper.java deleted file mode 100644 index fa09a2bb..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/BudgetProblemMapper.java +++ /dev/null @@ -1,76 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.error; - -import dev.caskeleton.adapter.inbound.web.budget.WebBudgetExceededException; -import dev.caskeleton.adapter.inbound.web.budget.WebBudgetOutcome; -import dev.caskeleton.adapter.inbound.web.budget.WebBudgetViolation; -import java.net.URI; -import java.util.List; -import java.util.Objects; - -/** - * Turns a crossed budget into the published problem document. - * - *

Here rather than in {@code budget} because the code vocabulary is here, and {@code budget} is - * a CORE module: a bound is arithmetic and stays testable without a catalog. Here rather than in - * each stack's filter because the two filters must answer identically, and a status that disagreed - * with its own body would be caught by {@code requireStatusAgreement} only after shipping. - */ -public final class BudgetProblemMapper { - - private final WebProblemFactory problems; - - /** - * A mapper over the problem catalog. - * - * @param problems the problem document factory - */ - public BudgetProblemMapper(WebProblemFactory problems) { - this.problems = Objects.requireNonNull(problems, "problems"); - } - - /** The problem code a violation is published as. */ - public static ProblemCode codeFor(WebBudgetViolation violation) { - return switch (violation) { - case URI_TOO_LONG, HEADERS_TOO_LARGE, BODY_TOO_LARGE -> ProblemCode.REQUEST_TOO_LARGE; - // Not REQUEST_TOO_LARGE: the document is a fine size and its shape is what the profile - // refuses. A client told "too large" would compress it and try again. - case TOO_MANY_QUERY_PARAMETERS, JSON_TOO_DEEP, ARRAY_TOO_LARGE, TOO_MANY_MULTIPART_PARTS -> - ProblemCode.VALIDATION_FAILED; - case EXECUTION_TIME_EXCEEDED -> ProblemCode.DEPENDENCY_TIMEOUT; - case RESPONSE_TOO_LARGE -> ProblemCode.RESPONSE_TOO_LARGE; - }; - } - - /** - * The status a violation is answered with. - * - *

Derived from the catalog rather than restated. The catalog is where a code's status is - * decided, and any second copy of that decision is a copy that will disagree. - * - * @param violation which bound was crossed - */ - public int statusFor(WebBudgetViolation violation) { - return problems.statusFor(codeFor(violation)); - } - - /** - * The problem document for a crossed budget. - * - * @param exceeded what was crossed - * @param instance the URI of this occurrence - * @param traceId the correlation identifier - */ - public WebProblem problemFor(WebBudgetExceededException exceeded, URI instance, String traceId) { - Objects.requireNonNull(exceeded, "exceeded"); - WebBudgetViolation violation = exceeded.violation(); - WebProblem problem = - problems.create( - codeFor(violation), - WebBudgetOutcome.detailFor(violation, exceeded.allowed()), - instance, - traceId, - List.of()); - problems.requireStatusAgreement(statusFor(violation), problem); - return problem; - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/GlobalExceptionHandler.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/GlobalExceptionHandler.java index 4d032215..3878ca10 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/GlobalExceptionHandler.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/GlobalExceptionHandler.java @@ -2,13 +2,11 @@ package dev.caskeleton.adapter.inbound.web.error; import dev.caskeleton.adapter.inbound.web.auth.SecurityErrorClassifier; import dev.caskeleton.adapter.inbound.web.conditional.PreconditionFailedException; -import dev.caskeleton.adapter.inbound.web.cursor.CursorException; import dev.caskeleton.adapter.inbound.web.http.ApiHeaders; import dev.caskeleton.adapter.inbound.web.observability.RetryAfterAdvisor; import dev.caskeleton.adapter.inbound.web.pagination.PageValidationException; import dev.caskeleton.application.idempotency.IdempotencyInFlightException; import dev.caskeleton.application.idempotency.IdempotencyRequestMismatchException; -import dev.caskeleton.application.idempotency.IdempotencyScopeMissingException; import dev.caskeleton.shared.error.AdapterDisabledException; import dev.caskeleton.shared.error.ApiErrorCode; import dev.caskeleton.shared.error.DependencyFailureException; @@ -173,19 +171,6 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { OperationalError.VALIDATION_FAILED, "Pagination parameter is invalid", details); } - /** - * Handles a tampered / expired / malformed opaque cursor → 400 VALIDATION_FAILED advising the - * client to re-request the first page. - */ - @ExceptionHandler(CursorException.class) - public ResponseEntity> handleCursor(CursorException ex) { - Map details = Map.of("field", "cursor", "code", "CURSOR_INVALID"); - return ErrorResponseFactory.envelope( - OperationalError.VALIDATION_FAILED, - "Cursor is invalid or expired; re-request the first page", - details); - } - /** * Handles a duplicate request whose original is still in flight → 409 IDEMPOTENT_IN_FLIGHT with a * fixed client-safe message. See README for the design rationale. @@ -211,19 +196,6 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { null); } - /** - * Handles an idempotency key applied without a resolvable scope → 400 VALIDATION_FAILED. See - * README for the design rationale. - */ - @ExceptionHandler(IdempotencyScopeMissingException.class) - public ResponseEntity> handleIdempotencyScopeMissing( - IdempotencyScopeMissingException ex) { - return ErrorResponseFactory.envelope( - OperationalError.VALIDATION_FAILED, - "Idempotency key cannot be applied to this request", - null); - } - /** * Handles a pre-classified {@link PersistenceFailureException}: its {@link * PersistenceFailureException#errorCode()} sets the envelope code/status; the client message is a diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/ProblemCatalog.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/ProblemCatalog.java deleted file mode 100644 index 90a8aaa0..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/ProblemCatalog.java +++ /dev/null @@ -1,183 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.error; - -import java.net.URI; -import java.util.EnumMap; -import java.util.Map; -import java.util.Objects; - -/** - * The one mapping from a problem code to its wire meaning and HTTP status. - * - *

Registered once and consulted everywhere, because the alternative is each handler choosing a - * status. A platform where one controller answers a conflict with 409 and another with 400 has no - * error contract at all, and a client cannot write retry logic against it. - * - *

{@code DEPENDENCY_FAILURE} is pinned to 502 and {@code DEPENDENCY_TIMEOUT} to 504 rather than - * letting either be chosen per call. The distinction matters to a caller: a 504 says the request - * may still be running behind the gateway, and a 502 says it is not. - * - *

The catalog is complete by construction: a code with no definition is refused at build time - * rather than discovered when that failure first occurs in production. - */ -public final class ProblemCatalog { - - /** The stable namespace every problem type URI is published under. */ - public static final String TYPE_PREFIX = "https://problems.caskeleton.dev/web/"; - - private final Map definitions; - - /** - * Creates a catalog. - * - * @param definitions the definition for each code - * @throws IllegalArgumentException when a code has no definition - */ - public ProblemCatalog(Map definitions) { - Objects.requireNonNull(definitions, "definitions"); - EnumMap copy = new EnumMap<>(ProblemCode.class); - copy.putAll(definitions); - for (ProblemCode code : ProblemCode.values()) { - if (!copy.containsKey(code)) { - throw new IllegalArgumentException( - "problem catalog is missing a definition for " - + code - + "; an undefined code becomes a status somebody picks at the call site"); - } - } - this.definitions = Map.copyOf(copy); - } - - /** The platform's published catalog. */ - public static ProblemCatalog standard() { - EnumMap definitions = new EnumMap<>(ProblemCode.class); - definitions.put( - ProblemCode.MALFORMED_REQUEST, - new ProblemDefinition( - URI.create(TYPE_PREFIX + "malformed-request"), "Malformed request", 400, 256)); - definitions.put( - ProblemCode.BINDING_FAILED, - new ProblemDefinition( - URI.create(TYPE_PREFIX + "binding-failed"), "Request could not be bound", 400, 256)); - definitions.put( - ProblemCode.VALIDATION_FAILED, - new ProblemDefinition( - URI.create(TYPE_PREFIX + "validation-failed"), "Request failed validation", 422, 256)); - definitions.put( - ProblemCode.AUTHENTICATION_REQUIRED, - new ProblemDefinition( - URI.create(TYPE_PREFIX + "authentication-required"), - "Authentication required", - 401, - 128)); - definitions.put( - ProblemCode.ACCESS_DENIED, - new ProblemDefinition( - URI.create(TYPE_PREFIX + "access-denied"), "Access denied", 403, 128)); - definitions.put( - ProblemCode.RESOURCE_NOT_FOUND, - new ProblemDefinition( - URI.create(TYPE_PREFIX + "resource-not-found"), "Resource not found", 404, 128)); - definitions.put( - ProblemCode.RESOURCE_CONFLICT, - new ProblemDefinition( - URI.create(TYPE_PREFIX + "resource-conflict"), "Resource conflict", 409, 256)); - definitions.put( - ProblemCode.PRECONDITION_FAILED, - new ProblemDefinition( - URI.create(TYPE_PREFIX + "precondition-failed"), "Precondition failed", 412, 256)); - definitions.put( - ProblemCode.IDEMPOTENCY_KEY_REQUIRED, - new ProblemDefinition( - URI.create(TYPE_PREFIX + "idempotency-key-required"), - "Idempotency key required", - 400, - 256)); - definitions.put( - ProblemCode.IDEMPOTENCY_KEY_REUSED, - new ProblemDefinition( - URI.create(TYPE_PREFIX + "idempotency-key-reused"), - "Idempotency key reused", - 422, - 256)); - definitions.put( - ProblemCode.IDEMPOTENCY_REQUEST_IN_PROGRESS, - new ProblemDefinition( - URI.create(TYPE_PREFIX + "idempotency-request-in-progress"), - "Request already in progress", - 409, - 256)); - definitions.put( - ProblemCode.RATE_LIMITED, - new ProblemDefinition( - URI.create(TYPE_PREFIX + "rate-limited"), "Rate limit exceeded", 429, 128)); - definitions.put( - ProblemCode.ADMISSION_REJECTED, - new ProblemDefinition( - URI.create(TYPE_PREFIX + "admission-rejected"), "Service is shedding load", 503, 128)); - definitions.put( - ProblemCode.DEPENDENCY_FAILURE, - new ProblemDefinition( - URI.create(TYPE_PREFIX + "dependency-failure"), "A dependency failed", 502, 128)); - definitions.put( - ProblemCode.DEPENDENCY_TIMEOUT, - new ProblemDefinition( - URI.create(TYPE_PREFIX + "dependency-timeout"), "A dependency timed out", 504, 128)); - definitions.put( - ProblemCode.METHOD_NOT_ALLOWED, - new ProblemDefinition( - URI.create(TYPE_PREFIX + "method-not-allowed"), "Method not allowed", 405, 128)); - definitions.put( - ProblemCode.NOT_ACCEPTABLE, - new ProblemDefinition( - URI.create(TYPE_PREFIX + "not-acceptable"), "No acceptable representation", 406, 128)); - definitions.put( - ProblemCode.RESOURCE_GONE, - new ProblemDefinition( - URI.create(TYPE_PREFIX + "resource-gone"), "Resource is gone", 410, 128)); - definitions.put( - ProblemCode.REQUEST_TOO_LARGE, - new ProblemDefinition( - URI.create(TYPE_PREFIX + "request-too-large"), - "Request exceeds a size bound", - 413, - 128)); - definitions.put( - ProblemCode.UNSUPPORTED_MEDIA_TYPE, - new ProblemDefinition( - URI.create(TYPE_PREFIX + "unsupported-media-type"), - "Unsupported media type", - 415, - 128)); - definitions.put( - ProblemCode.RESPONSE_TOO_LARGE, - new ProblemDefinition( - URI.create(TYPE_PREFIX + "response-too-large"), - "Response exceeds a size bound", - 500, - 128)); - definitions.put( - ProblemCode.INTERNAL_ERROR, - new ProblemDefinition( - URI.create(TYPE_PREFIX + "internal-error"), "Internal error", 500, 128)); - return new ProblemCatalog(definitions); - } - - /** - * The definition for a code. - * - * @throws IllegalArgumentException when the code is not defined - */ - public ProblemDefinition require(ProblemCode code) { - Objects.requireNonNull(code, "code"); - ProblemDefinition definition = definitions.get(code); - if (definition == null) { - throw new IllegalArgumentException("undefined problem code: " + code); - } - return definition; - } - - /** Every definition, for rendering the published catalog document. */ - public Map definitions() { - return definitions; - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/ProblemCode.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/ProblemCode.java deleted file mode 100644 index 56418a5e..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/ProblemCode.java +++ /dev/null @@ -1,81 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.error; - -/** - * The stable vocabulary of failures this API reports. - * - *

A code rather than a message is what a client can branch on. A message is written for a human, - * gets reworded, gets translated, and a client that matched on its text breaks silently. These - * names are part of the published contract and change only with the API major version. - * - *

The list is deliberately closed. A controller that needs a failure this enum cannot express is - * a controller inventing a contract, and the review that adds a constant here is the review that - * decides what status it maps to and what a client should do about it. - */ -public enum ProblemCode { - - /** The request was not valid JSON, or not parseable at the transport level at all. */ - MALFORMED_REQUEST, - - /** The document parsed but could not be bound to the request model. */ - BINDING_FAILED, - - /** The request bound but violated a declared constraint. */ - VALIDATION_FAILED, - - /** No credentials, or credentials that could not be verified. */ - AUTHENTICATION_REQUIRED, - - /** Verified credentials that are not permitted to do this. */ - ACCESS_DENIED, - - /** The addressed resource does not exist, or the caller may not know that it does. */ - RESOURCE_NOT_FOUND, - - /** The request conflicts with the resource's current state. */ - RESOURCE_CONFLICT, - - /** A conditional header was supplied and no longer holds. */ - PRECONDITION_FAILED, - - /** The operation requires an idempotency key and none was supplied. */ - IDEMPOTENCY_KEY_REQUIRED, - - /** The idempotency key was already used for a different request. */ - IDEMPOTENCY_KEY_REUSED, - - /** The same idempotency key is being processed right now. */ - IDEMPOTENCY_REQUEST_IN_PROGRESS, - - /** The caller exceeded its rate allowance. */ - RATE_LIMITED, - - /** The service refused the request to protect itself, rather than because of the caller. */ - ADMISSION_REJECTED, - - /** A dependency this operation needs failed. */ - DEPENDENCY_FAILURE, - - /** A dependency this operation needs did not answer in time. */ - DEPENDENCY_TIMEOUT, - - /** The method is not served by this resource. */ - METHOD_NOT_ALLOWED, - - /** No representation the caller accepts can be produced. */ - NOT_ACCEPTABLE, - - /** The resource existed and has been permanently removed. */ - RESOURCE_GONE, - - /** The request exceeded a declared size bound. */ - REQUEST_TOO_LARGE, - - /** The request body's media type is not one this operation reads. */ - UNSUPPORTED_MEDIA_TYPE, - - /** The response would exceed a declared size bound. */ - RESPONSE_TOO_LARGE, - - /** Something failed that the platform cannot describe more precisely without leaking. */ - INTERNAL_ERROR -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/ProblemDefinition.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/ProblemDefinition.java deleted file mode 100644 index 5b23ad28..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/ProblemDefinition.java +++ /dev/null @@ -1,34 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.error; - -import java.net.URI; -import java.util.Objects; - -/** - * What one {@link ProblemCode} means on the wire. - * - *

The status lives here, once, so that the HTTP status and the {@code status} member of the body - * cannot disagree — they are read from the same field. RFC 9457 allows both to be present and says - * nothing about what a client should do when they differ, which in practice means the client picks - * one and the operator debugs the other. - * - * @param type the stable URI identifying the problem kind - * @param title the short human-readable summary, which does not change per occurrence - * @param status the HTTP status this code is always reported with - * @param maxDetailLength how much per-occurrence detail this code may carry - */ -public record ProblemDefinition(URI type, String title, int status, int maxDetailLength) { - - public ProblemDefinition { - Objects.requireNonNull(type, "type"); - Objects.requireNonNull(title, "title"); - if (title.isBlank()) { - throw new IllegalArgumentException("problem title is required"); - } - if (status < 400 || status > 599) { - throw new IllegalArgumentException("a problem status must be 4xx or 5xx, was " + status); - } - if (maxDetailLength <= 0 || maxDetailLength > 2048) { - throw new IllegalArgumentException("problem detail bound out of range: " + maxDetailLength); - } - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/ProblemStatusMismatchException.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/ProblemStatusMismatchException.java deleted file mode 100644 index 3a36c4f3..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/ProblemStatusMismatchException.java +++ /dev/null @@ -1,28 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.error; - -/** - * The response status and the body's {@code status} member disagreed. - * - *

Thrown before serialization rather than logged, because a body that says 409 on a 500 response - * is a contract violation a client cannot recover from: it will branch on one of them, and which - * one is not something this platform gets to decide. - */ -public final class ProblemStatusMismatchException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - /** - * Creates the failure. - * - * @param responseStatus the status the response is being written with - * @param bodyStatus the status the problem body declares - */ - public ProblemStatusMismatchException(int responseStatus, int bodyStatus) { - super( - "problem body declares status " - + bodyStatus - + " while the response is being written with " - + responseStatus - + "; a client will branch on one of them and cannot be told which"); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/SafeProblemDetailExtensions.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/SafeProblemDetailExtensions.java deleted file mode 100644 index f9b31963..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/SafeProblemDetailExtensions.java +++ /dev/null @@ -1,53 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.error; - -import java.util.Set; - -/** - * The only extension members a problem body may carry. - * - *

RFC 9457 allows arbitrary extensions and this platform allows two. The reason is the same one - * that closes {@link ProblemCode}: an open extension set means each handler decides what an error - * looks like, and the sanitising rules then have as many holes as there are handlers. Somebody adds - * {@code cause} "just for debugging" and the exception message ships to every caller. - * - *

Both allowed members are safe by construction rather than by review. {@code traceId} names a - * log entry, not a person; {@code errors} is a list of {@link ValidationIssue}, which has no field - * for the submitted value. - */ -public final class SafeProblemDetailExtensions { - - /** The correlation identifier an operator searches for. */ - public static final String TRACE_ID = "traceId"; - - /** The field-level validation issues. */ - public static final String ERRORS = "errors"; - - private static final Set ALLOWED = Set.of(TRACE_ID, ERRORS); - - private SafeProblemDetailExtensions() {} - - /** Whether an extension member may appear in a problem body. */ - public static boolean allowed(String member) { - return member != null && ALLOWED.contains(member); - } - - /** Every allowed extension member. */ - public static Set allowed() { - return ALLOWED; - } - - /** - * Refuses an extension the platform does not publish. - * - * @throws IllegalArgumentException when the member is not allowed - */ - public static void requireAllowed(String member) { - if (!allowed(member)) { - throw new IllegalArgumentException( - "problem extension '" - + member - + "' is not published; an open extension set is how an exception message ships to" - + " every caller"); - } - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/ThrottleProblemWriter.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/ThrottleProblemWriter.java deleted file mode 100644 index c0c84b9e..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/ThrottleProblemWriter.java +++ /dev/null @@ -1,78 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.error; - -import java.net.URI; -import java.time.Duration; -import java.util.List; -import java.util.Objects; - -/** - * Renders the two refusals that mean "not now" — a spent quota and a full service. - * - *

Both in one place because the pair is only useful if it stays distinguishable, and the way - * that is lost is one of them being written by hand somewhere. A 429 tells the caller its own rate - * is the problem; a 503 tells it the rate is fine and the service is not. Answering either with the - * other sends the caller looking in the wrong place. - */ -public final class ThrottleProblemWriter { - - private final WebProblemFactory problems; - - /** - * A writer over the problem catalog. - * - * @param problems the problem document factory - */ - public ThrottleProblemWriter(WebProblemFactory problems) { - this.problems = Objects.requireNonNull(problems, "problems"); - } - - /** - * The caller's quota is spent. - * - * @param instance the URI of this occurrence - * @param traceId the correlation identifier - */ - public WebProblem quotaExhausted(URI instance, String traceId) { - return problems.create( - ProblemCode.RATE_LIMITED, - "the quota for this caller is exhausted", - instance, - traceId, - List.of()); - } - - /** - * The service has no capacity. - * - * @param instance the URI of this occurrence - * @param traceId the correlation identifier - */ - public WebProblem capacityExhausted(URI instance, String traceId) { - // Deliberately says nothing about the caller. A 503 that reads like a rate limit is the reason - // clients back off individually during an incident instead of retrying when capacity returns. - return problems.create( - ProblemCode.ADMISSION_REJECTED, - "the service is shedding load and did not run this request", - instance, - traceId, - List.of()); - } - - /** The status a quota refusal carries. */ - public int quotaStatus() { - return problems.statusFor(ProblemCode.RATE_LIMITED); - } - - /** The status a capacity refusal carries. */ - public int capacityStatus() { - return problems.statusFor(ProblemCode.ADMISSION_REJECTED); - } - - /** The {@code Retry-After} value for a duration, in whole seconds and never zero. */ - public static String retryAfterSeconds(Duration retryAfter) { - // Rounded up, and floored at one. RFC 9110 counts in seconds, so a sub-second wait rendered - // honestly is "0" — which tells a client to retry immediately, the opposite of the intent. - long seconds = Math.max(1, (retryAfter.toMillis() + 999) / 1000); - return Long.toString(seconds); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/ValidationIssue.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/ValidationIssue.java deleted file mode 100644 index 1ee96422..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/ValidationIssue.java +++ /dev/null @@ -1,33 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.error; - -import java.util.Objects; - -/** - * One field-level reason a request was refused. - * - *

The pointer is a JSON Pointer into the request document, not a Java property path. A client - * that sent {@code {"order":{"lines":[...]}}} can act on {@code /order/lines/0/quantity}; it cannot - * act on {@code createOrder.arg0.lines[0].quantity}, which also happens to disclose the signature - * of an internal method. - * - *

There is no {@code rejectedValue}. Echoing what the caller sent back into an error body is how - * a password typed into the wrong field ends up in a log aggregator. - * - * @param pointer JSON Pointer to the offending member of the request document - * @param code the stable, machine-readable reason - * @param message the human-readable reason, carrying no submitted content - */ -public record ValidationIssue(String pointer, String code, String message) { - - public ValidationIssue { - Objects.requireNonNull(pointer, "pointer"); - Objects.requireNonNull(code, "code"); - Objects.requireNonNull(message, "message"); - if (!pointer.isEmpty() && !pointer.startsWith("/")) { - throw new IllegalArgumentException("pointer must be a JSON Pointer: " + pointer); - } - if (code.isBlank()) { - throw new IllegalArgumentException("validation issue code is required"); - } - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/WebProblem.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/WebProblem.java deleted file mode 100644 index b7df48bd..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/WebProblem.java +++ /dev/null @@ -1,55 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.error; - -import java.net.URI; -import java.util.List; -import java.util.Objects; - -/** - * The RFC 9457 body this API answers a failure with. - * - *

The member set is fixed. RFC 9457 permits arbitrary extension members, and permitting them - * here would mean every controller could add one — at which point the error contract is whatever - * each handler felt like, and the sanitising rules have as many holes as there are call sites. The - * two extensions this platform does carry, {@code traceId} and {@code errors}, are declared members - * with declared rules. - * - *

{@code traceId} is present so an operator can find the request; it is safe to publish because - * it identifies a log entry rather than a person. Nothing else about the failure's internals — the - * exception, the query, the host — appears anywhere in this record, and {@link WebProblemSanitizer} - * is what keeps that true for the one free-text member. - * - * @param type the stable URI identifying the problem kind - * @param title the short summary for this kind of problem - * @param status the HTTP status, equal to the one on the response - * @param detail what went wrong this time, sanitised and bounded - * @param instance the URI of the specific occurrence - * @param code the stable machine-readable code - * @param traceId the correlation identifier an operator can search for - * @param errors the field-level issues, empty when the failure is not field-level - */ -public record WebProblem( - URI type, - String title, - int status, - String detail, - URI instance, - ProblemCode code, - String traceId, - List errors) { - - public WebProblem { - Objects.requireNonNull(type, "type"); - Objects.requireNonNull(title, "title"); - Objects.requireNonNull(detail, "detail"); - Objects.requireNonNull(code, "code"); - Objects.requireNonNull(traceId, "traceId"); - Objects.requireNonNull(errors, "errors"); - if (status < 400 || status > 599) { - throw new IllegalArgumentException("a problem status must be 4xx or 5xx, was " + status); - } - errors = List.copyOf(errors); - } - - /** The media type this body is served as. */ - public static final String MEDIA_TYPE = "application/problem+json"; -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/WebProblemFactory.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/WebProblemFactory.java deleted file mode 100644 index 37259f3a..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/WebProblemFactory.java +++ /dev/null @@ -1,79 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.error; - -import java.net.URI; -import java.util.List; -import java.util.Objects; - -/** - * The only way a problem body is built. - * - *

Single entry point on purpose. Every rule this platform has about error responses — the status - * comes from the catalog, the detail is sanitised and bounded, the extension set is closed — is a - * rule that a controller constructing its own body would bypass. Making the factory the only - * constructor means the rules are structural rather than remembered. - */ -public final class WebProblemFactory { - - private final ProblemCatalog catalog; - private final WebProblemSanitizer sanitizer; - - /** - * Creates a factory. - * - * @param catalog the code-to-status mapping - * @param sanitizer the free-text reducer - */ - public WebProblemFactory(ProblemCatalog catalog, WebProblemSanitizer sanitizer) { - this.catalog = Objects.requireNonNull(catalog, "catalog"); - this.sanitizer = Objects.requireNonNull(sanitizer, "sanitizer"); - } - - /** A factory over the published catalog. */ - public static WebProblemFactory standard() { - return new WebProblemFactory(ProblemCatalog.standard(), new WebProblemSanitizer()); - } - - /** - * Builds a problem body. - * - * @param code the stable failure code - * @param detail what went wrong this time; sanitised before it is used - * @param instance the URI of this occurrence - * @param traceId the correlation identifier - * @param errors the field-level issues, empty when the failure is not field-level - */ - public WebProblem create( - ProblemCode code, String detail, URI instance, String traceId, List errors) { - Objects.requireNonNull(code, "code"); - Objects.requireNonNull(traceId, "traceId"); - ProblemDefinition definition = catalog.require(code); - return new WebProblem( - definition.type(), - definition.title(), - definition.status(), - sanitizer.sanitize(detail, definition.maxDetailLength()), - instance, - code, - traceId, - errors == null ? List.of() : errors); - } - - /** The status a code is always answered with. */ - public int statusFor(ProblemCode code) { - return catalog.require(code).status(); - } - - /** - * Refuses a response whose status does not match the body it carries. - * - *

Called on the way out, before serialization, by every transport adapter. - * - * @throws ProblemStatusMismatchException when the two disagree - */ - public void requireStatusAgreement(int responseStatus, WebProblem problem) { - Objects.requireNonNull(problem, "problem"); - if (responseStatus != problem.status()) { - throw new ProblemStatusMismatchException(responseStatus, problem.status()); - } - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/WebProblemSanitizer.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/WebProblemSanitizer.java deleted file mode 100644 index 2ae0b9ba..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/WebProblemSanitizer.java +++ /dev/null @@ -1,85 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.error; - -import java.util.List; -import java.util.Locale; -import java.util.regex.Pattern; - -/** - * Reduces free text to something safe to publish in an error body. - * - *

Allowlist-shaped rather than a list of things to remove. A denylist of "stack traces, SQL, - * hostnames, tokens" has to anticipate every shape an internal detail can take, and the one it - * misses is published to every caller. What survives here is a single line of bounded, printable - * text with no fragment that looks like an internal identifier. - * - *

The specific patterns are the ones observed to leak in practice: a package-qualified class - * name, a stack frame, a URL, a file path, and anything that looks like a bearer credential. - */ -public final class WebProblemSanitizer { - - /** What is left when nothing survives sanitising. */ - public static final String REDACTED = "The request could not be completed."; - - private static final Pattern STACK_FRAME = Pattern.compile("(?m)^\\s*at\\s+\\S+.*$"); - private static final Pattern QUALIFIED_TYPE = - Pattern.compile("\\b(?:[a-z][a-z0-9_]*\\.){2,}[A-Z][A-Za-z0-9_$]*\\b"); - private static final Pattern URL = Pattern.compile("\\b[a-zA-Z][a-zA-Z0-9+.-]*://\\S+"); - private static final Pattern FILE_PATH = Pattern.compile("(?:/[A-Za-z0-9_.-]+){2,}"); - - /** - * A credential keyword and whatever follows it. - * - *

The trailing {@code [:=\\s]*\\S*} is the part that matters. An earlier version anchored on - * the keyword alone, which removed the word {@code Bearer} and published the token after it — a - * redaction that reads as if it worked. - */ - private static final Pattern CREDENTIAL = - Pattern.compile("(?i)\\b(?:bearer|basic|token|secret|password|apikey)\\b[:=]?\\s*\\S*"); - - private static final Pattern SQL = - Pattern.compile("(?i)\\b(?:select|insert|update|delete|drop|from|where)\\s+\\S+"); - private static final Pattern CONTROL = Pattern.compile("[\\p{Cntrl}]+"); - private static final Pattern WHITESPACE = Pattern.compile("\\s{2,}"); - - private static final List REMOVALS = - List.of(STACK_FRAME, QUALIFIED_TYPE, URL, CREDENTIAL, SQL, FILE_PATH); - - /** - * Sanitises and bounds one free-text detail. - * - * @param input the raw text, possibly an exception message - * @param maxLength the catalog's bound for this problem code - * @return safe, single-line, bounded text, never null - */ - public String sanitize(String input, int maxLength) { - if (maxLength <= 0) { - throw new IllegalArgumentException("detail bound must be positive"); - } - if (input == null || input.isBlank()) { - return REDACTED; - } - String working = input; - for (Pattern removal : REMOVALS) { - working = removal.matcher(working).replaceAll(" "); - } - working = CONTROL.matcher(working).replaceAll(" "); - working = WHITESPACE.matcher(working).replaceAll(" ").trim(); - if (working.isEmpty()) { - return REDACTED; - } - if (working.length() > maxLength) { - // Truncated rather than rejected: the surviving prefix is still useful to a caller, and a - // bound that throws would turn a long message into a second failure. - working = working.substring(0, maxLength).trim(); - } - return working.isEmpty() ? REDACTED : working; - } - - /** Whether text would survive sanitising unchanged, for asserting a message is already safe. */ - public boolean alreadySafe(String input, int maxLength) { - return input != null - && !input.isBlank() - && sanitize(input, maxLength) - .equals(input.trim().toLowerCase(Locale.ROOT).isEmpty() ? REDACTED : input.trim()); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/WebResourceNotVisibleException.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/WebResourceNotVisibleException.java deleted file mode 100644 index d356abf4..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/WebResourceNotVisibleException.java +++ /dev/null @@ -1,37 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.error; - -import java.util.Objects; - -/** - * The addressed resource is absent, or the caller may not know that it exists. - * - *

One exception for both, deliberately. Distinguishing them over the wire turns a guessable - * identifier into an oracle: an attacker enumerating ids learns which ones are real from the - * difference between 403 and 404, and for an operation resource that is a list of what other - * tenants are running. - * - *

Thrown rather than returned so that a controller cannot accidentally answer a bare 404. A - * status with no body is a failure a client cannot branch on, and it is what {@code - * ResponseEntity.notFound().build()} produces in one keystroke. - */ -public final class WebResourceNotVisibleException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - private final transient String resourceKind; - - /** - * A resource the caller may not see. - * - * @param resourceKind what kind of thing was addressed, for the published detail - */ - public WebResourceNotVisibleException(String resourceKind) { - super("no such " + Objects.requireNonNull(resourceKind, "resourceKind") + " is visible"); - this.resourceKind = resourceKind; - } - - /** What kind of thing was addressed. */ - public String resourceKind() { - return resourceKind; - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/evidence/WebApplicationEvidence.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/evidence/WebApplicationEvidence.java deleted file mode 100644 index 09b83722..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/evidence/WebApplicationEvidence.java +++ /dev/null @@ -1,44 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.evidence; - -/** - * What is known about the application's own work, independent of the HTTP exchange. - * - *

This is the axis a retry decision is made from. {@link #APPLICATION_UNKNOWN} is the reason the - * whole model exists: a call that entered the application and whose outcome was never observed is - * not a failure and not a success, and reporting it as either is how a duplicate charge happens. - * - *

{@link #APPLICATION_UNKNOWN} is therefore terminal on this axis. Nothing later in the request - * can turn it back into a definite answer, because the information that would settle it is on the - * other side of a connection that is already gone; only reconciliation against the durable record - * can, and that happens outside this request. - */ -public enum WebApplicationEvidence implements WebEvidenceAxis { - - /** The application was never entered, so no business state can have changed. */ - NOT_STARTED(10), - - /** The application was entered; whether it committed is not yet known. */ - APPLICATION_STARTED(20), - - /** The application ran and its transaction rolled back: definitely no business state changed. */ - APPLICATION_ROLLED_BACK(30), - - /** The application committed: business state definitely changed. */ - APPLICATION_COMMITTED(40), - - /** - * The application was entered and its outcome was never observed. Terminal, and not a failure. - */ - APPLICATION_UNKNOWN(50); - - private final int rank; - - WebApplicationEvidence(int rank) { - this.rank = rank; - } - - @Override - public int rank() { - return rank; - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/evidence/WebEvidenceAxis.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/evidence/WebEvidenceAxis.java deleted file mode 100644 index 2b2d95ea..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/evidence/WebEvidenceAxis.java +++ /dev/null @@ -1,15 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.evidence; - -/** - * One position on a monotonic evidence axis, with its order stated rather than implied. - * - *

The rank is declared per constant instead of taken from {@code ordinal()}. Ordinal ties the - * ordering rule to the order somebody happened to type the constants in, so inserting a stage in - * the middle — which is exactly what happens when a new admission step is added — silently changes - * which transitions count as backwards. A declared rank makes that edit visible. - */ -public interface WebEvidenceAxis { - - /** Where this value sits on its axis; higher is later, and gaps are allowed. */ - int rank(); -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/evidence/WebExecutionEvidence.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/evidence/WebExecutionEvidence.java deleted file mode 100644 index 9d50db0a..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/evidence/WebExecutionEvidence.java +++ /dev/null @@ -1,57 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.evidence; - -import java.util.Objects; - -/** - * The three independent axes of what is known about one request, read together. - * - *

Three fields rather than one state machine, and that is the design decision this record exists - * to hold. A single linear status has to pick an order between "the application committed" and "the - * response was written", and whichever it picks becomes wrong for the case that matters: a - * committed write whose response never left. Keeping the axes apart means the pair {@code - * (APPLICATION_COMMITTED, CLIENT_OBSERVATION_UNKNOWN)} is directly representable, which is exactly - * the situation a retry policy has to be able to see. - * - * @param requestPhase how far admission got - * @param applicationEvidence what is known about the application's own work - * @param responseEvidence how much of the response this process wrote - */ -public record WebExecutionEvidence( - WebRequestPhase requestPhase, - WebApplicationEvidence applicationEvidence, - WebResponseEvidence responseEvidence) { - - public WebExecutionEvidence { - Objects.requireNonNull(requestPhase, "requestPhase"); - Objects.requireNonNull(applicationEvidence, "applicationEvidence"); - Objects.requireNonNull(responseEvidence, "responseEvidence"); - } - - /** - * Whether an automatic retry of a mutation would be safe. - * - *

Safe means one thing only: this platform can prove no business state changed. Both {@link - * WebApplicationEvidence#APPLICATION_STARTED} and {@link - * WebApplicationEvidence#APPLICATION_UNKNOWN} therefore say no — a call that entered the - * application and was not observed to roll back may have committed. - */ - public boolean safeToRetryMutation() { - return applicationEvidence == WebApplicationEvidence.NOT_STARTED - || applicationEvidence == WebApplicationEvidence.APPLICATION_ROLLED_BACK; - } - - /** - * Whether the exchange needs reconciliation rather than a verdict. - * - *

True when the application committed but the response cannot be shown to have reached the - * client, and true when the application's own outcome was never observed. In both cases the - * durable record is the only thing that can settle what happened. - */ - public boolean requiresReconciliation() { - if (applicationEvidence == WebApplicationEvidence.APPLICATION_UNKNOWN) { - return true; - } - return applicationEvidence == WebApplicationEvidence.APPLICATION_COMMITTED - && responseEvidence != WebResponseEvidence.RESPONSE_WRITE_COMPLETED_LOCALLY; - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/evidence/WebExecutionEvidenceTracker.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/evidence/WebExecutionEvidenceTracker.java deleted file mode 100644 index 3a6dc3e2..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/evidence/WebExecutionEvidenceTracker.java +++ /dev/null @@ -1,125 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.evidence; - -import java.util.Objects; -import java.util.concurrent.atomic.AtomicReference; - -/** - * Accumulates the three evidence axes for one request, forwards only. - * - *

Monotonic because the alternative loses the fact that matters. If a later stage could reset an - * axis, a response-write failure arriving after a commit could overwrite {@code - * APPLICATION_COMMITTED} with something weaker, and the request would be reported as safe to retry. - * Every transition therefore takes the maximum of the current and the requested value, per axis, - * and a backwards request is silently a no-op rather than an error — the caller is a filter or an - * interceptor reporting what it saw, and making it responsible for ordering would put the ordering - * rule in the least reliable place. - * - *

The axes advance independently. Marking the application committed says nothing about the - * response, and marking the response written says nothing about the application. - * - *

Updated through a compare-and-set loop because a request can be completed by a container - * thread while an async dispatch is still reporting on another. - */ -public final class WebExecutionEvidenceTracker { - - private final AtomicReference current; - - private WebExecutionEvidenceTracker(WebExecutionEvidence initial) { - this.current = new AtomicReference<>(initial); - } - - /** A tracker for a request the container has just handed over. */ - public static WebExecutionEvidenceTracker received() { - return new WebExecutionEvidenceTracker( - new WebExecutionEvidence( - WebRequestPhase.HTTP_RECEIVED, - WebApplicationEvidence.NOT_STARTED, - WebResponseEvidence.NOT_COMMITTED)); - } - - /** What is known right now. */ - public WebExecutionEvidence snapshot() { - return current.get(); - } - - /** Advances the admission axis, never backwards. */ - public void markPhase(WebRequestPhase phase) { - Objects.requireNonNull(phase, "phase"); - advance( - existing -> - new WebExecutionEvidence( - later(existing.requestPhase(), phase), - existing.applicationEvidence(), - existing.responseEvidence())); - } - - /** Records that the application was entered. */ - public void markApplicationStarted() { - markApplication(WebApplicationEvidence.APPLICATION_STARTED); - } - - /** Records that the application's transaction rolled back. */ - public void markApplicationRolledBack() { - markApplication(WebApplicationEvidence.APPLICATION_ROLLED_BACK); - } - - /** Records that the application committed. */ - public void markApplicationCommitted() { - markApplication(WebApplicationEvidence.APPLICATION_COMMITTED); - } - - /** Records that the application's outcome was never observed. */ - public void markApplicationUnknown() { - markApplication(WebApplicationEvidence.APPLICATION_UNKNOWN); - } - - /** Records that status and headers are on the wire. */ - public void markResponseHeadersCommitted() { - markResponse(WebResponseEvidence.RESPONSE_HEADERS_COMMITTED); - } - - /** Records that some body bytes were written. */ - public void markResponsePartiallyWritten() { - markResponse(WebResponseEvidence.RESPONSE_PARTIALLY_WRITTEN); - } - - /** - * Records that this process finished writing the response. - * - *

Named for what it proves. The client may still have received nothing. - */ - public void markLocalResponseWriteCompleted() { - markResponse(WebResponseEvidence.RESPONSE_WRITE_COMPLETED_LOCALLY); - } - - /** Records that even the local write could not be confirmed. */ - public void markClientObservationUnknown() { - markResponse(WebResponseEvidence.CLIENT_OBSERVATION_UNKNOWN); - } - - private void markApplication(WebApplicationEvidence evidence) { - advance( - existing -> - new WebExecutionEvidence( - existing.requestPhase(), - later(existing.applicationEvidence(), evidence), - existing.responseEvidence())); - } - - private void markResponse(WebResponseEvidence evidence) { - advance( - existing -> - new WebExecutionEvidence( - existing.requestPhase(), - existing.applicationEvidence(), - later(existing.responseEvidence(), evidence))); - } - - private void advance(java.util.function.UnaryOperator transition) { - current.updateAndGet(transition); - } - - private static & WebEvidenceAxis> E later(E existing, E requested) { - return requested.rank() > existing.rank() ? requested : existing; - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/evidence/WebRequestPhase.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/evidence/WebRequestPhase.java deleted file mode 100644 index ea8eed7e..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/evidence/WebRequestPhase.java +++ /dev/null @@ -1,44 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.evidence; - -/** - * How far a request travelled through the platform's own admission stages. - * - *

This axis answers "what did we do with the bytes", and nothing else. It does not say whether - * the application ran and it does not say whether a response reached anybody — those are separate - * axes, because collapsing them is what produces the answer "the request succeeded" for a call that - * committed a payment and then failed to reply. - * - *

The order of the constants is the order of the stages, and the tracker refuses to move - * backwards through it. - */ -public enum WebRequestPhase implements WebEvidenceAxis { - - /** The container handed the platform a request; nothing has been read from it yet. */ - HTTP_RECEIVED(10), - - /** URI, headers and forwarded facts were normalised into a trusted external view. */ - REQUEST_NORMALIZED(20), - - /** A route template was matched, so the operation identity is known. */ - ROUTE_SELECTED(30), - - /** The body was parsed and bound to a typed request model. */ - REQUEST_BOUND(40), - - /** Transport-level semantic validation passed. */ - REQUEST_VALIDATED(50), - - /** Every admission gate — budget, rate limit, idempotency — allowed the request through. */ - REQUEST_ADMITTED(60); - - private final int rank; - - WebRequestPhase(int rank) { - this.rank = rank; - } - - @Override - public int rank() { - return rank; - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/evidence/WebResponseEvidence.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/evidence/WebResponseEvidence.java deleted file mode 100644 index 269ab58d..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/evidence/WebResponseEvidence.java +++ /dev/null @@ -1,46 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.evidence; - -/** - * How much of the response this process managed to write. - * - *

Every constant here describes what happened on this side of the socket. That is the - * whole point of the axis: a server can complete a write, flush it and close cleanly while the - * client behind an intermediary receives nothing, so no value here may be read as "the client saw - * it". - * - *

{@link #RESPONSE_WRITE_COMPLETED_LOCALLY} is named the way it is for that reason — an earlier - * shape of this model called it {@code RESPONSE_SENT}, and a reader who saw that constant next to a - * committed application reasonably concluded the exchange was complete. {@link - * #CLIENT_OBSERVATION_UNKNOWN} is the honest terminal state when even the local write could not be - * confirmed. - */ -public enum WebResponseEvidence implements WebEvidenceAxis { - - /** Nothing has been written; the response can still be replaced entirely. */ - NOT_COMMITTED(10), - - /** Status and headers are on the wire, so the status code can no longer be changed. */ - RESPONSE_HEADERS_COMMITTED(20), - - /** Some body bytes were written; a failure from here cannot be reported as a clean error. */ - RESPONSE_PARTIALLY_WRITTEN(30), - - /** - * This process finished writing the response. It does not mean the client received it. - */ - RESPONSE_WRITE_COMPLETED_LOCALLY(40), - - /** The write could not be confirmed locally either: the exchange's fate is unknown. */ - CLIENT_OBSERVATION_UNKNOWN(50); - - private final int rank; - - WebResponseEvidence(int rank) { - this.rank = rank; - } - - @Override - public int rank() { - return rank; - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/ExternalOrigin.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/ExternalOrigin.java deleted file mode 100644 index 1e1f5432..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/ExternalOrigin.java +++ /dev/null @@ -1,51 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.http; - -import java.util.Locale; -import java.util.Objects; - -/** - * The scheme, host and port a client actually addressed. - * - *

A configured value wherever one exists, because the alternative is deriving it from a request - * header. A password-reset link built from {@code Host} points wherever the caller said, and the - * caller receiving that link is the attacker who set the header. - * - * @param scheme the external scheme, lower case - * @param host the external host, lower case - * @param port the external port - */ -public record ExternalOrigin(String scheme, String host, int port) { - - public ExternalOrigin { - Objects.requireNonNull(scheme, "scheme"); - Objects.requireNonNull(host, "host"); - scheme = scheme.toLowerCase(Locale.ROOT); - host = host.toLowerCase(Locale.ROOT); - if (!scheme.equals("http") && !scheme.equals("https")) { - throw new IllegalArgumentException("external scheme must be http or https, was " + scheme); - } - if (host.isBlank()) { - throw new IllegalArgumentException("external host is required"); - } - if (port < 1 || port > 65535) { - throw new IllegalArgumentException("external port out of range: " + port); - } - } - - /** An https origin on the default port. */ - public static ExternalOrigin https(String host) { - return new ExternalOrigin("https", host, 443); - } - - /** The origin as a client would type it, with a default port left implicit. */ - public String value() { - boolean defaultPort = - (scheme.equals("https") && port == 443) || (scheme.equals("http") && port == 80); - return defaultPort ? scheme + "://" + host : scheme + "://" + host + ":" + port; - } - - @Override - public String toString() { - return value(); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/ExternalPrefix.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/ExternalPrefix.java deleted file mode 100644 index 7a345f29..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/ExternalPrefix.java +++ /dev/null @@ -1,63 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.http; - -import java.util.Objects; - -/** - * The path prefix a gateway mounts this service under. - * - *

A type rather than a string because the mistake it prevents is applying it twice. A service - * behind {@code /api} that both reads {@code X-Forwarded-Prefix} and prepends its own configured - * prefix emits {@code /api/api/orders/1}, and the {@code Location} header that comes back is a 404 - * the client cannot diagnose. - * - *

Normalised at construction: no trailing slash, no traversal, always absolute or empty. - * - * @param value the prefix, empty or beginning with a slash and never ending in one - */ -public record ExternalPrefix(String value) { - - public ExternalPrefix { - Objects.requireNonNull(value, "value"); - value = value.trim(); - while (value.endsWith("/")) { - value = value.substring(0, value.length() - 1); - } - if (!value.isEmpty()) { - if (!value.startsWith("/")) { - throw new IllegalArgumentException("external prefix must be absolute: " + value); - } - if (value.contains("..") || value.contains("//")) { - throw new IllegalArgumentException("external prefix is not canonical: " + value); - } - } - } - - /** No prefix; the service is mounted at the root. */ - public static ExternalPrefix none() { - return new ExternalPrefix(""); - } - - /** Whether this prefix adds anything. */ - public boolean empty() { - return value.isEmpty(); - } - - /** - * Whether a path already begins with this prefix. - * - *

Segment-aware: {@code /apiary/x} does not start with {@code /api}, even though the string - * does. Getting that wrong is how a legitimate path is mistaken for an already-prefixed one and - * silently loses a segment. - */ - public boolean alreadyApplied(String path) { - if (empty() || path == null) { - return false; - } - return path.equals(value) || path.startsWith(value + "/"); - } - - @Override - public String toString() { - return value; - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/ExternalUriBuilder.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/ExternalUriBuilder.java deleted file mode 100644 index df45ae6b..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/ExternalUriBuilder.java +++ /dev/null @@ -1,80 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.http; - -import java.util.Objects; - -/** - * Builds the absolute and relative URLs this API hands back. - * - *

Two rules, both of which exist because getting them wrong is silent. - * - *

The prefix is applied exactly once. A service behind a gateway that both receives {@code - * X-Forwarded-Prefix} and prepends its own configured prefix emits {@code /api/api/orders/1}, and - * the client follows a {@code Location} into a 404 it cannot diagnose. {@link - * ExternalPrefix#alreadyApplied} is segment-aware, so {@code /apiary} is not mistaken for an - * already-prefixed {@code /api} path. - * - *

The origin is never taken from a raw header. It comes from {@link ExternalUriPolicy}, which - * prefers what the deployment configured — a reset link built from {@code Host} points wherever the - * caller said it should. - */ -public final class ExternalUriBuilder { - - private final ExternalOrigin origin; - private final ExternalPrefix prefix; - - /** - * A builder for one request's external view. - * - * @param origin the resolved external origin - * @param prefix the resolved external prefix - */ - public ExternalUriBuilder(ExternalOrigin origin, ExternalPrefix prefix) { - this.origin = Objects.requireNonNull(origin, "origin"); - this.prefix = Objects.requireNonNull(prefix, "prefix"); - } - - /** - * The absolute URL for an application path. - * - * @param applicationPath an absolute application path, as the routes declare it - */ - public String absolute(String applicationPath) { - return origin.value() + relative(applicationPath); - } - - /** - * The path a client should use, prefixed exactly once. - * - * @param applicationPath an absolute application path - */ - public String relative(String applicationPath) { - Objects.requireNonNull(applicationPath, "applicationPath"); - if (!applicationPath.startsWith("/")) { - throw new IllegalArgumentException("application path must be absolute: " + applicationPath); - } - if (prefix.empty() || prefix.alreadyApplied(applicationPath)) { - return applicationPath; - } - return prefix.value() + applicationPath; - } - - /** - * The {@code Location} value for a created or accepted resource. - * - *

Absolute, because RFC 9110 permits a relative one and intermediaries have historically - * disagreed about what it is relative to. - */ - public String location(String applicationPath) { - return absolute(applicationPath); - } - - /** The resolved origin, for a test or a diagnostic. */ - public ExternalOrigin origin() { - return origin; - } - - /** The resolved prefix. */ - public ExternalPrefix prefix() { - return prefix; - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/ExternalUriPolicy.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/ExternalUriPolicy.java deleted file mode 100644 index 61b0716a..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/ExternalUriPolicy.java +++ /dev/null @@ -1,88 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.http; - -import dev.caskeleton.adapter.inbound.web.proxy.NormalizedForwardedHeaders; -import java.util.Objects; -import java.util.Optional; - -/** - * Where the external origin comes from, and who is allowed to influence it. - * - *

A configured origin wins over a forwarded one, always. That ordering is the point: a - * deployment that has written down its public address is stating a fact no request can change, - * while a forwarded header is a fact a proxy asserts and a misconfigured proxy asserts wrongly. - * Preferring the configuration means a security-sensitive URL — a reset link, a callback — is built - * from the deployment's own answer. - * - *

With no configured origin the forwarded value is used, because a service behind a gateway has - * no other way to know its public name. That is why the forwarded value must already have passed - * the trusted-peer check before it reaches here. - * - * @param configuredOrigin the deployment's own public origin, when it has one - * @param configuredPrefix the deployment's own mount prefix - * @param allowForwardedOrigin whether a trusted proxy may supply the origin at all - */ -public record ExternalUriPolicy( - Optional configuredOrigin, - ExternalPrefix configuredPrefix, - boolean allowForwardedOrigin) { - - public ExternalUriPolicy { - Objects.requireNonNull(configuredOrigin, "configuredOrigin"); - Objects.requireNonNull(configuredPrefix, "configuredPrefix"); - } - - /** A deployment that states its own origin and ignores whatever a proxy says. */ - public static ExternalUriPolicy configured(ExternalOrigin origin, ExternalPrefix prefix) { - return new ExternalUriPolicy(Optional.of(origin), prefix, false); - } - - /** A deployment behind a gateway that has to learn its public name from it. */ - public static ExternalUriPolicy fromTrustedProxy(ExternalPrefix prefix) { - return new ExternalUriPolicy(Optional.empty(), prefix, true); - } - - /** - * The origin to build URLs from. - * - * @param forwarded what a trusted proxy said, already normalised - * @param serverOrigin what this process sees on its own socket - */ - public ExternalOrigin resolveOrigin( - NormalizedForwardedHeaders forwarded, ExternalOrigin serverOrigin) { - Objects.requireNonNull(forwarded, "forwarded"); - Objects.requireNonNull(serverOrigin, "serverOrigin"); - if (configuredOrigin.isPresent()) { - return configuredOrigin.get(); - } - if (!allowForwardedOrigin) { - return serverOrigin; - } - String scheme = forwarded.scheme().orElse(serverOrigin.scheme()); - String host = forwarded.host().orElse(serverOrigin.host()); - int port = - forwarded - .port() - .orElseGet( - () -> - forwarded.scheme().isPresent() - // The proxy changed the scheme without stating a port, so the server's own - // port is meaningless here — it is the internal one. - ? ("https".equals(scheme) ? 443 : 80) - : serverOrigin.port()); - return new ExternalOrigin(scheme, host, port); - } - - /** - * The prefix to apply. - * - *

The configured prefix wins for the same reason the origin does, and a forwarded prefix is - * only used when the deployment declared none. - */ - public ExternalPrefix resolvePrefix(NormalizedForwardedHeaders forwarded) { - Objects.requireNonNull(forwarded, "forwarded"); - if (!configuredPrefix.empty()) { - return configuredPrefix; - } - return forwarded.prefix().map(ExternalPrefix::new).orElseGet(ExternalPrefix::none); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/WebHeaderName.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/WebHeaderName.java deleted file mode 100644 index 30340076..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/WebHeaderName.java +++ /dev/null @@ -1,56 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.http; - -/** - * The header names the platform's own contracts are written in terms of. - * - *

Constants rather than literals because header names are compared in several places — the - * response contract, the sanitiser, the CORS expose list, the cache key — and a literal typo in one - * of them produces a rule that silently applies to nothing. A missing {@code Location} check is - * indistinguishable from a passing one. - */ -public final class WebHeaderName { - - /** Where a created or accepted resource can be read. */ - public static final String LOCATION = "Location"; - - /** The current validator for a resource representation. */ - public static final String ETAG = "ETag"; - - /** The validator a conditional read is asking about. */ - public static final String IF_NONE_MATCH = "If-None-Match"; - - /** The validator a conditional write requires to still hold. */ - public static final String IF_MATCH = "If-Match"; - - /** The caller-supplied key that makes a mutation safe to repeat. */ - public static final String IDEMPOTENCY_KEY = "Idempotency-Key"; - - /** How long a client should wait before repeating a refused request. */ - public static final String RETRY_AFTER = "Retry-After"; - - /** Which request dimensions a cached response varies by. */ - public static final String VARY = "Vary"; - - /** The cache directives a response carries. */ - public static final String CACHE_CONTROL = "Cache-Control"; - - /** The media type of the body. */ - public static final String CONTENT_TYPE = "Content-Type"; - - /** The declared length of the body. */ - public static final String CONTENT_LENGTH = "Content-Length"; - - /** The methods a resource serves. */ - public static final String ALLOW = "Allow"; - - /** When a deprecated resource stops being served. */ - public static final String SUNSET = "Sunset"; - - /** Whether a resource is deprecated. */ - public static final String DEPRECATION = "Deprecation"; - - /** Relations to other resources, including the deprecation notice. */ - public static final String LINK = "Link"; - - private WebHeaderName() {} -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/WebResponseContract.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/WebResponseContract.java deleted file mode 100644 index c1b27a15..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/WebResponseContract.java +++ /dev/null @@ -1,46 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.http; - -import java.util.Map; -import java.util.Objects; - -/** - * Checks a response against the status rules before it can be written. - * - *

Applied at construction of {@link WebSuccessResponse} rather than by a filter on the way out. - * A filter runs after the status and headers may already have been committed, at which point the - * only thing it can do about a violation is log it — and a rule that can only be reported after the - * fact is documentation, not enforcement. - */ -public final class WebResponseContract { - - /** - * Validates one response. - * - * @param status the HTTP status - * @param headers the response headers - * @param body the response body, or null - * @throws IllegalArgumentException when the combination is not allowed - */ - public void validate(int status, Map headers, Object body) { - Objects.requireNonNull(headers, "headers"); - if (WebStatusContract.forbidsBody(status) && body != null) { - throw new IllegalArgumentException( - "status " - + status - + " forbids a response body; some intermediaries drop it and some forward it, so the" - + " client's experience would depend on which proxy it went through"); - } - if (WebStatusContract.requiresLocation(status) - && !headers.containsKey(WebHeaderName.LOCATION)) { - throw new IllegalArgumentException( - "status " - + status - + " requires a Location header; without it the client is told something exists and" - + " not where"); - } - if (status == WebStatusContract.NOT_MODIFIED && !headers.containsKey(WebHeaderName.ETAG)) { - throw new IllegalArgumentException( - "304 must repeat the ETag it matched, or the next conditional read has no validator"); - } - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/WebStatusContract.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/WebStatusContract.java deleted file mode 100644 index 8943022b..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/WebStatusContract.java +++ /dev/null @@ -1,40 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.http; - -/** - * What each success status is allowed to carry. - * - *

The rules are RFC 9110's, restated as code because a comment cannot fail a build. A body on a - * {@code 204} is not merely wrong: some intermediaries drop it and some forward it, so the client's - * experience depends on which proxy it went through, which is the worst kind of bug to reproduce. - */ -public final class WebStatusContract { - - /** Created; the new resource must be locatable. */ - public static final int CREATED = 201; - - /** Accepted; the durable operation must be locatable. */ - public static final int ACCEPTED = 202; - - /** No content; nothing may be written. */ - public static final int NO_CONTENT = 204; - - /** Not modified; nothing may be written, and the validator must be repeated. */ - public static final int NOT_MODIFIED = 304; - - private WebStatusContract() {} - - /** Whether the status forbids a response body outright. */ - public static boolean forbidsBody(int status) { - return status == NO_CONTENT || status == NOT_MODIFIED || (status >= 100 && status < 200); - } - - /** Whether the status requires a {@code Location} header. */ - public static boolean requiresLocation(int status) { - return status == CREATED || status == ACCEPTED; - } - - /** Whether the status is a success. */ - public static boolean success(int status) { - return status >= 200 && status < 300; - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/WebSuccessResponse.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/WebSuccessResponse.java deleted file mode 100644 index 2b8811f3..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/WebSuccessResponse.java +++ /dev/null @@ -1,75 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.http; - -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -/** - * One success response: a status, its headers and the resource itself. - * - *

This type models the HTTP status, headers and resource before any composition-specific - * response body policy is applied. The shipped servlet application wraps JSON success bodies in the - * shared {@code Envelope}; the reusable problem-document fixtures deliberately do not. Keeping the - * HTTP response model free of either wrapper lets the composition root choose one wire contract - * without teaching status/header policy about that choice. - * - * @param the resource type - * @param status the HTTP status - * @param headers the response headers - * @param body the resource, or null when the status forbids one - */ -public record WebSuccessResponse(int status, Map headers, T body) { - - public WebSuccessResponse { - Objects.requireNonNull(headers, "headers"); - if (!WebStatusContract.success(status) && status != WebStatusContract.NOT_MODIFIED) { - throw new IllegalArgumentException("not a success status: " + status); - } - headers = Map.copyOf(new LinkedHashMap<>(headers)); - new WebResponseContract().validate(status, headers, body); - } - - /** A 200 carrying the resource. */ - public static WebSuccessResponse ok(T body) { - return new WebSuccessResponse<>(200, Map.of(), Objects.requireNonNull(body, "body")); - } - - /** A 201 whose new resource is locatable. */ - public static WebSuccessResponse created(String location, T body) { - return new WebSuccessResponse<>( - WebStatusContract.CREATED, Map.of(WebHeaderName.LOCATION, location), body); - } - - /** A 202 whose durable operation is locatable. */ - public static WebSuccessResponse accepted(String operationLocation, T body) { - return new WebSuccessResponse<>( - WebStatusContract.ACCEPTED, Map.of(WebHeaderName.LOCATION, operationLocation), body); - } - - /** A 204 with nothing in it. */ - public static WebSuccessResponse noContent() { - return new WebSuccessResponse<>(WebStatusContract.NO_CONTENT, Map.of(), null); - } - - /** A 304 repeating the validator the client already holds. */ - public static WebSuccessResponse notModified(String etag) { - return new WebSuccessResponse<>( - WebStatusContract.NOT_MODIFIED, Map.of(WebHeaderName.ETAG, etag), null); - } - - /** The {@code Location} header, when the status carries one. */ - public Optional location() { - return Optional.ofNullable(headers.get(WebHeaderName.LOCATION)); - } - - /** - * The same response with the body removed, for answering {@code HEAD}. - * - *

Headers are kept exactly. A {@code HEAD} whose headers differ from the {@code GET} it - * describes defeats the only reason a client sends one. - */ - public WebSuccessResponse asHeadResponse() { - return new WebSuccessResponse<>(status, headers, null); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/json/BoundedJsonFactory.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/json/BoundedJsonFactory.java deleted file mode 100644 index e35af8b4..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/json/BoundedJsonFactory.java +++ /dev/null @@ -1,45 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.json; - -import java.util.Objects; -import tools.jackson.core.StreamReadConstraints; -import tools.jackson.core.StreamReadFeature; -import tools.jackson.core.json.JsonFactory; -import tools.jackson.core.json.JsonFactoryBuilder; - -/** - * Builds the reader whose limits are enforced before a document is materialised. - * - *

The constraints go on the {@code JsonFactory} rather than being checked after parsing, and - * that placement is the whole point. A depth limit applied to a parsed tree has already paid for - * the tree; a nesting bomb is cheap to send and expensive to hold, so the only limit that helps is - * one the streaming parser refuses to exceed. - * - *

Jackson 3 ({@code tools.jackson}), not Jackson 2. Both are on this classpath, and Spring - * Framework 7's {@code JacksonJsonHttpMessageConverter} takes a {@code tools.jackson} mapper — so a - * strict Jackson 2 mapper would be a bean the framework never consults, which is a control that - * exists and reads nothing. - */ -public final class BoundedJsonFactory { - - private BoundedJsonFactory() {} - - /** - * A factory bounded by a profile. - * - * @param profile the limits and strictness to apply - */ - public static JsonFactory create(WebJsonProfile profile) { - Objects.requireNonNull(profile, "profile"); - JsonFactoryBuilder builder = - JsonFactory.builder() - .streamReadConstraints( - StreamReadConstraints.builder() - .maxNestingDepth(profile.maxDepth()) - .maxStringLength(profile.maxStringBytes()) - .build()); - if (profile.rejectDuplicateKeys()) { - builder.enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION); - } - return builder.build(); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/json/WebJsonDecodingException.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/json/WebJsonDecodingException.java deleted file mode 100644 index 7f3fd014..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/json/WebJsonDecodingException.java +++ /dev/null @@ -1,36 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.json; - -/** - * A request body that could not be read under the strict profile. - * - *

Its own type so the error translator can tell a malformed document (400) from a well-formed - * document that violates a transport rule (422) without inspecting Jackson's exception hierarchy at - * the call site. The distinction is the design's, and it is only usable if it survives the throw. - * - *

The message never carries the offending content. A parse failure message that quotes the body - * is how a request body reaches a log that the body's own classification says it must not. - */ -public final class WebJsonDecodingException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - private final boolean malformed; - - /** - * Creates a decoding failure. - * - * @param message what went wrong, naming no content - * @param malformed true when the document is not valid JSON at all, false when it parsed but - * violated a declared rule - * @param cause the underlying reader failure - */ - public WebJsonDecodingException(String message, boolean malformed, Throwable cause) { - super(message, cause); - this.malformed = malformed; - } - - /** Whether the document was not valid JSON, which is a 400 rather than a 422. */ - public boolean malformed() { - return malformed; - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/json/WebJsonProfile.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/json/WebJsonProfile.java deleted file mode 100644 index 61269036..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/json/WebJsonProfile.java +++ /dev/null @@ -1,51 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.json; - -/** - * Which strictness the JSON reader applies, as one reviewable value. - * - *

Every flag here defaults to lenient in Jackson, and every lenient default is a way for two - * parties to disagree about what a document meant. A duplicate key means the last one wins and the - * client believes the first one did; an unknown property means a typo'd field name is silently - * dropped and the request "succeeds" without doing what was asked; a trailing token means a - * concatenated second document is ignored. - * - * @param rejectUnknownProperties whether a property the model does not declare fails the request - * @param rejectDuplicateKeys whether a repeated JSON key fails the request - * @param rejectTrailingTokens whether content after the first document fails the request - * @param caseSensitiveEnums whether an enum value must match its declared spelling exactly - * @param rejectScalarCoercion whether number-to-string and empty-string-to-null are refused - * @param maxDepth deepest accepted nesting - * @param maxArrayElements most elements accepted in one array - * @param maxStringBytes longest accepted string - */ -public record WebJsonProfile( - boolean rejectUnknownProperties, - boolean rejectDuplicateKeys, - boolean rejectTrailingTokens, - boolean caseSensitiveEnums, - boolean rejectScalarCoercion, - int maxDepth, - int maxArrayElements, - int maxStringBytes) { - - public WebJsonProfile { - if (maxDepth <= 0 || maxArrayElements <= 0 || maxStringBytes <= 0) { - throw new IllegalArgumentException("json profile limits must be positive"); - } - } - - /** Everything strict. The profile a mutation is read with. */ - public static WebJsonProfile strict() { - return new WebJsonProfile(true, true, true, true, true, 64, 100_000, 1_048_576); - } - - /** - * Strict except for unknown properties. - * - *

For reading a document this service did not author — a provider callback, a stored replay — - * where an added field is the other party evolving their contract, not a client mistake. - */ - public static WebJsonProfile tolerantOfUnknownProperties() { - return new WebJsonProfile(false, true, true, true, true, 64, 100_000, 1_048_576); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/json/WebObjectMapperFactory.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/json/WebObjectMapperFactory.java deleted file mode 100644 index b1beacf0..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/json/WebObjectMapperFactory.java +++ /dev/null @@ -1,111 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.json; - -import java.util.Objects; -import tools.jackson.databind.DeserializationFeature; -import tools.jackson.databind.MapperFeature; -import tools.jackson.databind.ObjectMapper; -import tools.jackson.databind.cfg.CoercionAction; -import tools.jackson.databind.cfg.CoercionInputShape; -import tools.jackson.databind.cfg.EnumFeature; -import tools.jackson.databind.json.JsonMapper; -import tools.jackson.databind.type.LogicalType; - -/** - * The strict reader the platform reads request bodies with. - * - *

A factory rather than a bean definition because the same strictness has to be applied by the - * MVC converter, the WebFlux codec, the idempotency replay decoder and the contract tests, and four - * independently configured mappers is four chances for one of them to be lenient. The one that is - * lenient is the one an attacker finds. - * - *

Built on Jackson 3 ({@code tools.jackson}) because that is the mapper Spring Framework 7's - * message converter actually takes. An earlier version of this class used {@code com.fasterxml}, - * which is also on this classpath — the mapper was correct, strict, unit tested, and never - * consulted by the framework for a single request. - * - *

Coercion is switched off explicitly rather than left to Jackson's defaults. Implicit - * number-to-string means {@code {"quantity": "5"}} and {@code {"quantity": 5}} are the same request - * to this service and different requests to the next one; implicit empty-string-to-null means a - * client that sends {@code ""} for a required field gets a null-pointer failure deep in the - * application instead of a validation error at the boundary. - */ -public final class WebObjectMapperFactory { - - private WebObjectMapperFactory() {} - - /** The mapper for reading a mutation request body. */ - public static ObjectMapper standard() { - return create(WebJsonProfile.strict()); - } - - /** The Jackson 3 {@code JsonMapper} Spring's message converter is configured with. */ - public static JsonMapper standardJsonMapper() { - return jsonMapper(WebJsonProfile.strict()); - } - - /** - * A mapper configured by a profile. - * - * @param profile the strictness and limits to apply - */ - public static ObjectMapper create(WebJsonProfile profile) { - return jsonMapper(profile); - } - - /** The Jackson 3 mapper the framework is configured with. */ - public static JsonMapper jsonMapper(WebJsonProfile profile) { - Objects.requireNonNull(profile, "profile"); - JsonMapper.Builder builder = - JsonMapper.builder(BoundedJsonFactory.create(profile)) - // Jackson 3 already writes dates as ISO strings by default and moved the date and - // enum switches out of SerializationFeature, so the wire manifest's RFC 3339 rule needs - // no override here — only the enum strictness does. - .enable(EnumFeature.FAIL_ON_NUMBERS_FOR_ENUMS) - .configure( - DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, - profile.rejectUnknownProperties()) - .configure( - DeserializationFeature.FAIL_ON_TRAILING_TOKENS, profile.rejectTrailingTokens()) - .configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS, !profile.caseSensitiveEnums()) - .configure( - MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, !profile.caseSensitiveEnums()) - .disable(DeserializationFeature.ACCEPT_FLOAT_AS_INT) - .enable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES); - - if (profile.rejectScalarCoercion()) { - refuseImplicitCoercion(builder); - } - return builder.build(); - } - - /** - * Turns off the shape conversions Jackson performs silently. - * - *

Configured per logical type rather than globally because the defaults differ by type and a - * single global switch would leave the ones it does not cover. - */ - private static void refuseImplicitCoercion(JsonMapper.Builder builder) { - builder.withCoercionConfigDefaults( - config -> - config - .setCoercion(CoercionInputShape.EmptyString, CoercionAction.Fail) - .setCoercion(CoercionInputShape.EmptyArray, CoercionAction.Fail) - .setCoercion(CoercionInputShape.EmptyObject, CoercionAction.Fail)); - for (LogicalType type : - new LogicalType[] {LogicalType.Integer, LogicalType.Float, LogicalType.Boolean}) { - builder.withCoercionConfig( - type, - config -> - config - .setCoercion(CoercionInputShape.String, CoercionAction.Fail) - .setCoercion(CoercionInputShape.EmptyString, CoercionAction.Fail)); - } - builder.withCoercionConfig( - LogicalType.Textual, - config -> - config - .setCoercion(CoercionInputShape.Integer, CoercionAction.Fail) - .setCoercion(CoercionInputShape.Float, CoercionAction.Fail) - .setCoercion(CoercionInputShape.Boolean, CoercionAction.Fail)); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/moduleboundary/WebModuleBoundary.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/moduleboundary/WebModuleBoundary.java deleted file mode 100644 index 70b8727c..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/moduleboundary/WebModuleBoundary.java +++ /dev/null @@ -1,108 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.moduleboundary; - -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Optional; -import java.util.Set; - -/** - * The declared module map of the web platform: identities, purity grades and allowed edges. - * - *

This type is the read side of {@link WebStableModule}. It answers the two questions every - * boundary check needs — "which module owns this package?" and "is this edge declared?" — so the - * rules never re-implement package-prefix arithmetic. - * - *

Note what it deliberately does not do: it never reads the source tree. Scanning the checkout - * is build-time work and lives in the test source set, because a running application cannot - * meaningfully react to its own source layout and a runtime scan only fails in the environments - * where the sources are absent. - */ -public final class WebModuleBoundary { - - /** The package that carries the whole platform. */ - public static final String PACKAGE_ROOT = deriveRootPackage(); - - private WebModuleBoundary() {} - - /** Every declared module identifier. */ - public static Set allModuleIds() { - return WebStableModule.moduleIds(); - } - - /** Every declared dependency edge, in deterministic order. */ - public static Map> dependencyEdges() { - return WebStableModule.dependencyEdges(); - } - - /** Every module that must not reference a framework type. */ - public static Set coreModuleIds() { - return WebStableModule.coreModuleIds(); - } - - /** The declared package of every module, keyed by identifier. */ - public static Map packagesById() { - return Map.copyOf(new LinkedHashMap<>(WebStableModule.packagesById())); - } - - /** - * The module owning a package. - * - *

Ownership is by longest declared package prefix, so {@code ...web.fileserver.controller} - * belongs to {@code fileserver.controller} rather than to a hypothetical {@code fileserver} - * module. - * - *

A module whose package is the platform root would own the root package itself and nothing - * below it. Letting it absorb descendants would make every possible package "declared", and the - * unregistered-package rule — the one that forces a new sub-package to be given an identity and - * an edge set before it can ship — would silently never fire. - * - * @param packageName a fully qualified package name - * @return the owning module identifier, or empty when the package is outside the platform or - * belongs to no declared module - */ - public static Optional moduleIdForPackage(String packageName) { - if (packageName == null || !insidePlatform(packageName)) { - return Optional.empty(); - } - String best = null; - String bestPackage = null; - for (Map.Entry candidate : packagesById().entrySet()) { - String candidatePackage = candidate.getValue(); - boolean owns = - candidatePackage.equals(PACKAGE_ROOT) - ? packageName.equals(PACKAGE_ROOT) - : matches(packageName, candidatePackage); - if (!owns) { - continue; - } - if (bestPackage == null || candidatePackage.length() > bestPackage.length()) { - best = candidate.getKey(); - bestPackage = candidatePackage; - } - } - return Optional.ofNullable(best); - } - - /** Whether a package name belongs to the platform at all. */ - public static boolean insidePlatform(String packageName) { - return packageName != null && matches(packageName, PACKAGE_ROOT); - } - - /** Whether an edge between two declared modules is allowed. */ - public static boolean edgeAllowed(String from, String to) { - if (from == null || to == null || from.equals(to)) { - return true; - } - Set allowed = dependencyEdges().get(from); - return allowed != null && allowed.contains(to); - } - - private static boolean matches(String packageName, String candidate) { - return packageName.equals(candidate) || packageName.startsWith(candidate + "."); - } - - private static String deriveRootPackage() { - String self = WebModuleBoundary.class.getPackageName(); - return self.substring(0, self.lastIndexOf('.')); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/moduleboundary/WebModulePurity.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/moduleboundary/WebModulePurity.java deleted file mode 100644 index 6cfcb639..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/moduleboundary/WebModulePurity.java +++ /dev/null @@ -1,21 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.moduleboundary; - -/** - * Whether a web platform module may reference Servlet, Spring, Reactor or Jackson types. - * - *

The design this leaf implements states the split as a hard constraint: {@code web-core-api} - * must not depend on Servlet, Spring MVC, Spring WebFlux or Reactor. That rule is what keeps the - * HTTP semantics portable — a budget, a problem code or a cursor is a decision, and a decision that - * needs a servlet container to evaluate cannot be unit tested, cannot be reused by the WebFlux - * transport, and cannot be promoted to its own Gradle leaf later. - * - *

So purity is declared per module and checked against the real imports rather than trusted. - */ -public enum WebModulePurity { - - /** Java standard library only: no Spring, Servlet, Reactor, Jackson, Micrometer or Jakarta. */ - CORE, - - /** May bind to the framework, because it is the transport seam that has to. */ - FRAMEWORK_BOUND -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/moduleboundary/WebStableModule.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/moduleboundary/WebStableModule.java deleted file mode 100644 index d25a724b..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/moduleboundary/WebStableModule.java +++ /dev/null @@ -1,540 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.moduleboundary; - -import java.util.Arrays; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Set; -import java.util.TreeMap; -import java.util.stream.Collectors; - -/** - * The Stable web platform modules, their purity grade and their allowed internal dependencies. - * - *

The design (`docs/superpowers/specs/2026-08-13-web-inbound-http-api-execution-platform-design` - * in the web package) models this platform as 23 Gradle modules under {@code modules/web}. This - * repository's fail-closed module registry owns the leaf list, so those modules are sub-packages of - * one registered leaf instead — the same resolution the JPA and GraphQL platforms reached. The - * design-module to package mapping is in {@code docs/web/repository-adaptation.md}. - * - *

That choice is only honest if the boundaries are machine checked, so this enum is the declared - * identity: each constant names a module, the package that carries it, whether it may touch the - * framework, and exactly which other modules it may import. {@code WebModuleBoundaryTest} scans the - * real source tree and fails when the tree and this declaration disagree in either direction — an - * undeclared edge, or a package with no declared identity. - * - *

Declaring the edge set is also what keeps the leaf split reversible: each constant is already - * shaped like a leaf specification, so promoting a module to its own Gradle path is a registry edit - * rather than an archaeology exercise. - */ -public enum WebStableModule { - - /** - * The operator's view of what the platform is actually running, and the startup check on it. - * - *

Sub-package of {@code admin} rather than its own module: it is the same audience and the - * same exposure decision as the route inventory that already lives there. - */ - ADMIN_PLATFORM("admin.platform", "admin.platform", WebModulePurity.CORE), - - /** The runtime route inventory and its release-gate comparison. */ - ADMIN_ROUTE( - "admin.route", - "admin.route", - WebModulePurity.FRAMEWORK_BOUND, - "core", - "operation", - "versioning"), - - /** - * Load shedding: bounded concurrency, a bounded queue, and the 503 that follows. - * - *

CORE, and separate from {@code ratelimit} on purpose. This module knows what the service is - * doing and nothing about who is calling; that separation is what keeps a capacity 503 from being - * reported as a quota 429. - */ - ADMISSION("admission", "admission", WebModulePurity.CORE, "operation"), - - /** Authenticated principal, entry point and denial writers for the HTTP boundary. */ - AUTH("auth", "auth", WebModulePurity.FRAMEWORK_BOUND, "error", "observability", "settings"), - - /** Permission evaluation and method security wiring. */ - AUTHZ("authz", "authz", WebModulePurity.FRAMEWORK_BOUND, "auth"), - - /** Request and response hard bounds, their named profiles and the catalog that holds them. */ - BUDGET("budget", "budget", WebModulePurity.CORE), - - /** ETag values and precondition failures: conditional request semantics, no transport. */ - CONDITIONAL("conditional", "conditional", WebModulePurity.CORE, "operation"), - - /** - * Identifiers, request context and the value types every other module is allowed to speak. - * - *

The design's {@code web-core-api}: no Servlet, Spring MVC, WebFlux, Reactor or Jackson, so - * an HTTP semantic can be exercised by a unit test and reused by either transport. - */ - CORE("core", "core", WebModulePurity.CORE), - - /** The fixed JSON representation of every type whose default rendering is wrong for an API. */ - CONTRACT("contract", "contract", WebModulePurity.CORE), - - /** - * The published cache profiles, their directives and the {@code Vary} rule. - * - *

CORE: a caching decision is a set of directives, not a framework call. Keeping it free of - * Spring is what lets the same profile be applied by the servlet writer, the reactive writer and - * the OpenAPI document without three renderings of it. - */ - CACHE("cache", "cache", WebModulePurity.CORE), - - /** Spring configuration classes that assemble the transport. */ - CONFIG("config", "config", WebModulePurity.FRAMEWORK_BOUND, "core", "settings"), - - /** Skeleton controllers shipped by the platform itself. */ - CONTROLLER("controller", "controller", WebModulePurity.FRAMEWORK_BOUND, "observability"), - - /** Opaque keyset cursor encoding and its failure type. */ - CURSOR("cursor", "cursor", WebModulePurity.CORE), - - /** Response envelope advice. */ - ENVELOPE("envelope", "envelope", WebModulePurity.FRAMEWORK_BOUND, "observability"), - - /** Error translation: the single place a failure becomes an HTTP status and a body. */ - ERROR( - "error", - "error", - WebModulePurity.FRAMEWORK_BOUND, - "admission", - "auth", - "budget", - "conditional", - "cursor", - "http", - "observability", - "pagination"), - - /** The three-axis execution evidence model: admission, application and response. */ - EVIDENCE("evidence", "evidence", WebModulePurity.CORE), - - /** File server admin endpoints. */ - FILESERVER_ADMIN( - "fileserver.admin", - "fileserver.admin", - WebModulePurity.FRAMEWORK_BOUND, - "core", - "fileserver.dto", - "fileserver.security"), - - /** File server transport configuration. */ - FILESERVER_CONFIG("fileserver.config", "fileserver.config", WebModulePurity.FRAMEWORK_BOUND), - - /** File server HTTP controllers. */ - FILESERVER_CONTROLLER( - "fileserver.controller", - "fileserver.controller", - WebModulePurity.FRAMEWORK_BOUND, - "core", - "fileserver.config", - "fileserver.dto", - "fileserver.http", - "fileserver.mapper", - "fileserver.nginx", - "fileserver.security"), - - /** tus draft-12 resumable upload surface. */ - FILESERVER_DRAFT12( - "fileserver.draft12", - "fileserver.draft12", - WebModulePurity.FRAMEWORK_BOUND, - "core", - "fileserver.config", - "fileserver.security"), - - /** File server wire DTOs. */ - FILESERVER_DTO("fileserver.dto", "fileserver.dto", WebModulePurity.FRAMEWORK_BOUND), - - /** File server HTTP header and range helpers. */ - FILESERVER_HTTP("fileserver.http", "fileserver.http", WebModulePurity.FRAMEWORK_BOUND), - - /** File server lifecycle endpoints. */ - FILESERVER_LIFECYCLE( - "fileserver.lifecycle", - "fileserver.lifecycle", - WebModulePurity.FRAMEWORK_BOUND, - "core", - "fileserver.dto", - "fileserver.security"), - - /** File server DTO mapping. */ - FILESERVER_MAPPER("fileserver.mapper", "fileserver.mapper", WebModulePurity.FRAMEWORK_BOUND), - - /** Nginx offload headers for the file server. */ - FILESERVER_NGINX( - "fileserver.nginx", "fileserver.nginx", WebModulePurity.FRAMEWORK_BOUND, "fileserver.http"), - - /** File server problem responses. */ - FILESERVER_PROBLEM( - "fileserver.problem", - "fileserver.problem", - WebModulePurity.FRAMEWORK_BOUND, - "fileserver.http", - "observability"), - - /** Reactive file server surface. */ - FILESERVER_REACTIVE( - "fileserver.reactive", - "fileserver.reactive", - WebModulePurity.FRAMEWORK_BOUND, - "fileserver.config", - "fileserver.dto", - "fileserver.http", - "fileserver.mapper", - "fileserver.problem", - "fileserver.security"), - - /** File server authorization at the HTTP boundary. */ - FILESERVER_SECURITY( - "fileserver.security", - "fileserver.security", - WebModulePurity.FRAMEWORK_BOUND, - "auth", - "observability"), - - /** tus resumable upload surface. */ - FILESERVER_TUS( - "fileserver.tus", - "fileserver.tus", - WebModulePurity.FRAMEWORK_BOUND, - "core", - "fileserver.config", - "fileserver.security"), - - /** Servlet filters: the ordered entry seam of the request path. */ - FILTER( - "filter", "filter", WebModulePurity.FRAMEWORK_BOUND, "auth", "core", "http", "observability"), - - /** Header names and HTTP constants shared across the platform. */ - HTTP("http", "http", WebModulePurity.CORE, "operation", "proxy"), - - /** - * JSON codec bridge for application-owned idempotency replay. - * - *

Claiming, scope, fingerprint and replay policy live at the application use-case boundary. - * The web adapter owns only serialization because that is a wire-format concern. - */ - IDEMPOTENCY("idempotency", "idempotency", WebModulePurity.FRAMEWORK_BOUND), - - /** Notification provider callback intake. */ - NOTIFICATION_CALLBACK( - "notification.platform.callback", - "notification.platform.callback", - WebModulePurity.FRAMEWORK_BOUND, - "core"), - - /** Reactive notification provider callback intake. */ - NOTIFICATION_CALLBACK_REACTIVE( - "notification.platform.callback.reactive", - "notification.platform.callback.reactive", - WebModulePurity.FRAMEWORK_BOUND, - "notification.platform.callback"), - - /** Notification submission endpoints. */ - NOTIFICATION_SUBMISSION( - "notification.platform.submission", - "notification.platform.submission", - WebModulePurity.FRAMEWORK_BOUND, - "observability"), - - /** The declared module map itself: identities, purity grades and allowed edges. */ - MODULE_BOUNDARY("moduleboundary", "moduleboundary", WebModulePurity.CORE), - - /** Operation profiles: what an operation does to state and which policies govern it. */ - OPERATION("operation", "operation", WebModulePurity.CORE, "budget", "core"), - - /** The strict JSON reader: the one place a request body's leniency is decided. */ - JSON("json", "json", WebModulePurity.FRAMEWORK_BOUND, "contract"), - - /** - * The servlet transport: the filters, the context holder and the auto-configuration root. - * - *

The design's {@code web-mvc} and {@code web-spring-boot-starter-mvc} together. They are one - * module here because the split in the design is a packaging boundary — an adopter choosing MVC - * takes both — and two packages that always ship together buy a boundary nobody can violate. - */ - MVC( - "mvc", - "mvc", - WebModulePurity.FRAMEWORK_BOUND, - "admin.platform", - "admission", - "budget", - "contract", - "core", - "error", - "evidence", - "http", - "json", - "operation", - "operationasync", - "ratelimit", - "validation"), - - /** - * Durable long-running operations: the polled resource, its lifecycle and the store port. - * - *

FRAMEWORK_BOUND only because it names {@code error}'s problem document, which is. Nothing - * here touches a servlet, a scheduler or a persistence type — an operation that a client polls - * must outlive the process that accepted it, and a process-local future would not. - */ - OPERATION_ASYNC( - "operationasync", "operationasync", WebModulePurity.FRAMEWORK_BOUND, "core", "error"), - - /** The published OpenAPI document, its platform components and the release gate. */ - OPENAPI("openapi", "openapi", WebModulePurity.FRAMEWORK_BOUND, "error"), - - /** Correlation identifiers, MDC keys, header sanitising and response metadata. */ - OBSERVABILITY("observability", "observability", WebModulePurity.FRAMEWORK_BOUND), - - /** Page and sort request values with their validation failure. */ - PAGINATION("pagination", "pagination", WebModulePurity.CORE), - - /** Trusted proxy policy and forwarded header normalisation. */ - PROXY("proxy", "proxy", WebModulePurity.CORE), - - /** Client identity resolution and the edge rate limit transport bridge. */ - RATELIMIT( - "ratelimit", "ratelimit", WebModulePurity.FRAMEWORK_BOUND, "auth", "core", "error", "http"), - - /** - * Transport validation: the 400/422 split and the mapping into publishable issues. - * - *

Framework bound because Bean Validation and Jackson are where the failures come from, not - * because the decision needs them. - */ - VALIDATION("validation", "validation", WebModulePurity.FRAMEWORK_BOUND, "error", "json"), - - /** - * The reactive transport: the Reactor Context filter, the blocking guard and its root. - * - *

The design's {@code web-webflux} and {@code web-spring-boot-starter-webflux}. It declares no - * edge to {@code mvc}: the two transports are mutually exclusive, and an edge between them would - * make the reactive starter compile against servlet types. - */ - WEBFLUX( - "webflux", - "webflux", - WebModulePurity.FRAMEWORK_BOUND, - "admission", - "budget", - "core", - "error", - "evidence", - "http", - "json", - "operation", - "operationasync", - "ratelimit", - "validation"), - - /** - * The bridge from a verified authentication to the platform's actor and tenant. - * - *

CORE: it holds no Spring Security type. That is what keeps token verification out of the web - * layer — there is nothing here to verify a token with. - */ - SECURITY("security", "security", WebModulePurity.CORE, "core"), - - /** Path major versioning, the served version catalog and the deprecation notice. */ - VERSIONING("versioning", "versioning", WebModulePurity.CORE, "core", "http"), - - /** Bound configuration properties for the transport. */ - SETTINGS("settings", "settings", WebModulePurity.FRAMEWORK_BOUND), - - /** - * The Advanced capabilities, each behind its own feature flag. - * - *

One module rather than the design's eleven Gradle modules, for the reason the Stable - * platform is one leaf: the registry owns the leaf list and a directory layout is not worth - * eleven entries in it. What the design wanted from the separation — that Stable never depends on - * Advanced — is enforced by ArchUnit, which a flag cannot do and a module boundary can. - */ - ADVANCED("advanced", "advanced", WebModulePurity.CORE, "core", "error", "operation"), - - /** - * The Advanced pieces that must name a framework type. - * - *

Separated from {@code advanced} rather than relaxing its purity, because most of Advanced is - * pure policy and only the patch appliers, the codec factories and the negotiation seam are not. - * Jackson's tree model is the reason: a merge patch's null-means-delete has no representation in - * a Java object, so the applier has to work on nodes. - */ - ADVANCED_PATCH( - "advanced-patch", "advanced.patch", WebModulePurity.FRAMEWORK_BOUND, "advanced", "error"), - - /** The CBOR and XML representations, and the negotiation that gates them. */ - ADVANCED_CODEC( - "advanced-codec", "advanced.codec", WebModulePurity.FRAMEWORK_BOUND, "advanced", "error"), - - /** The stream framing writers, which serialize and therefore bind to Jackson. */ - ADVANCED_STREAM_ENCODING( - "advanced-stream-encoding", - "advanced.stream.encoding", - WebModulePurity.FRAMEWORK_BOUND, - "advanced", - "advanced-stream"), - - /** The streaming core: envelopes, evidence, policy, termination, registry and drain. */ - ADVANCED_STREAM("advanced-stream", "advanced.stream", WebModulePurity.CORE, "advanced", "error"), - - /** - * Functional WebFlux routes, checked against the operation catalog. - * - *

{@code FRAMEWORK_BOUND} because the router it builds is Spring's. The validation above it is - * pure and could have stayed so, but splitting a four-class package to keep one of them - * frameworkless would trade a real boundary for a nominal one. - */ - ADVANCED_FUNCTIONAL( - "advanced-functional", - "advanced.functional", - WebModulePurity.FRAMEWORK_BOUND, - "advanced", - "core", - "operation"), - - /** The virtual-thread execution profile and the admission limit it must not remove. */ - ADVANCED_VIRTUAL_THREAD( - "advanced-virtual-thread", "advanced.virtualthread", WebModulePurity.CORE, "advanced"), - - /** The bounded blocking offload for WebFlux. */ - ADVANCED_BLOCKING_BRIDGE( - "advanced-blocking-bridge", "advanced.blockingbridge", WebModulePurity.CORE, "advanced"), - - /** - * The parallel OpenAPI 3.2 lane. - * - *

{@code FRAMEWORK_BOUND} because generating a document means holding swagger's model, and - * copying it faithfully means using swagger's own serializer. The edge to the stream encoding is - * the streaming media types: the 3.2 difference this lane exists to report is the per-item schema - * on exactly those responses, so the generator has to know which they are. - */ - ADVANCED_OPENAPI( - "advanced-openapi", - "advanced.openapi", - WebModulePurity.FRAMEWORK_BOUND, - "advanced", - "advanced-stream-encoding"), - - /** The draft RateLimit response headers. */ - ADVANCED_RATELIMIT( - "advanced-ratelimit", "advanced.ratelimit", WebModulePurity.CORE, "advanced", "ratelimit"), - - /** The promotion gate and the release evidence manifest. */ - ADVANCED_RELEASE("advanced-release", "advanced.release", WebModulePurity.CORE, "advanced"), - - /** - * The servlet execution of the Advanced capabilities: SSE emitters, the streaming writers, the - * disconnect detector and the virtual-thread executor. - * - *

Separated from the pure Advanced modules for the reason Stable's {@code mvc} is separated - * from its policy modules: this is where the framework actually is. Everything above it decides; - * this writes bytes to a servlet response. - */ - ADVANCED_MVC( - "advanced-mvc", - "advanced.mvc", - WebModulePurity.FRAMEWORK_BOUND, - "advanced", - "advanced-stream", - "advanced-stream-encoding", - "advanced-virtual-thread", - "core", - "error", - "evidence", - "json"), - - /** The reactive execution of the same capabilities, plus the bounded blocking offload. */ - ADVANCED_WEBFLUX( - "advanced-webflux", - "advanced.webflux", - WebModulePurity.FRAMEWORK_BOUND, - "advanced", - "advanced-blocking-bridge", - "advanced-stream", - "advanced-stream-encoding", - "core", - "error", - "evidence", - "json"); - - private final String id; - private final String packageSuffix; - private final WebModulePurity purity; - - /** - * Populated only from {@link Set#of}, which is genuinely immutable. Error Prone's {@code - * ImmutableEnumChecker} recognises Guava's {@code ImmutableSet} but not the JDK's unmodifiable - * factories, and this leaf has no Guava dependency to add for one field. - */ - @SuppressWarnings("ImmutableEnumChecker") - private final Set allowedDependencies; - - WebStableModule( - String id, String packageSuffix, WebModulePurity purity, String... allowedDependencies) { - this.id = id; - this.packageSuffix = packageSuffix; - this.purity = purity; - this.allowedDependencies = Set.of(allowedDependencies); - } - - /** The module identifier used on both sides of a declared dependency edge. */ - public String id() { - return id; - } - - /** The fully qualified package that carries this module, including its sub-packages. */ - public String packageName() { - return packageSuffix.isEmpty() - ? WebModuleBoundary.PACKAGE_ROOT - : WebModuleBoundary.PACKAGE_ROOT + "." + packageSuffix; - } - - /** Whether this module may reference framework types. */ - public WebModulePurity purity() { - return purity; - } - - /** The module identifiers this module is allowed to import. */ - public Set allowedDependencies() { - return allowedDependencies; - } - - /** Every declared Stable module identifier. */ - public static Set moduleIds() { - return Arrays.stream(values()).map(WebStableModule::id).collect(Collectors.toUnmodifiableSet()); - } - - /** Every declared Stable module that must not reference a framework type. */ - public static Set coreModuleIds() { - return Arrays.stream(values()) - .filter(module -> module.purity() == WebModulePurity.CORE) - .map(WebStableModule::id) - .collect(Collectors.toUnmodifiableSet()); - } - - /** Every declared Stable dependency edge, in deterministic order. */ - public static Map> dependencyEdges() { - Map> edges = new TreeMap<>(); - for (WebStableModule module : values()) { - edges.put(module.id(), module.allowedDependencies()); - } - return Map.copyOf(edges); - } - - /** The declared package of every Stable module, keyed by identifier. */ - public static Map packagesById() { - Map packages = new LinkedHashMap<>(); - for (WebStableModule module : values()) { - packages.put(module.id(), module.packageName()); - } - return Map.copyOf(packages); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebAdapterAutoConfiguration.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebAdapterAutoConfiguration.java new file mode 100644 index 00000000..d1de21b5 --- /dev/null +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebAdapterAutoConfiguration.java @@ -0,0 +1,73 @@ +package dev.caskeleton.adapter.inbound.web.mvc.autoconfigure; + +import dev.caskeleton.adapter.inbound.web.auth.JwtDecoderConfig; +import dev.caskeleton.adapter.inbound.web.auth.JwtToAuthenticatedPrincipalConverter; +import dev.caskeleton.adapter.inbound.web.auth.RedisSessionWebConfig; +import dev.caskeleton.adapter.inbound.web.auth.SecurityConfig; +import dev.caskeleton.adapter.inbound.web.authz.AuthorizationAdapter; +import dev.caskeleton.adapter.inbound.web.authz.MethodSecurityConfig; +import dev.caskeleton.adapter.inbound.web.authz.RolePermissionPolicy; +import dev.caskeleton.adapter.inbound.web.authz.RolePermissionRegistry; +import dev.caskeleton.adapter.inbound.web.config.JacksonNullableConfig; +import dev.caskeleton.adapter.inbound.web.config.OpenApiContractConfig; +import dev.caskeleton.adapter.inbound.web.config.PresentationWebConfig; +import dev.caskeleton.adapter.inbound.web.controller.HealthcheckController; +import dev.caskeleton.adapter.inbound.web.envelope.EnvelopeBodyAdvice; +import dev.caskeleton.adapter.inbound.web.error.GlobalExceptionHandler; +import dev.caskeleton.adapter.inbound.web.filter.CacheControlFilter; +import dev.caskeleton.adapter.inbound.web.filter.RequestLoggingFilter; +import dev.caskeleton.adapter.inbound.web.observability.MdcCorrelationIdPortAdapter; +import dev.caskeleton.adapter.inbound.web.ratelimit.EdgeRateLimitTransportSettings; +import dev.caskeleton.adapter.inbound.web.ratelimit.RateLimitWebConfig; +import dev.caskeleton.adapter.inbound.web.settings.CorsSettings; +import dev.caskeleton.adapter.inbound.web.settings.PresentationSettings; +import dev.caskeleton.adapter.inbound.web.settings.SecuritySettings; +import org.springframework.boot.autoconfigure.AutoConfiguration; +import org.springframework.boot.autoconfigure.AutoConfigureOrder; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Import; +import org.springframework.core.Ordered; + +/** + * The HTTP adapter this leaf ships: security, error envelope, filters, health endpoint and their + * settings. + * + *

These used to be found by the composition root's component scan of the whole {@code + * dev.caskeleton} tree. Registering them here means an application gets them from this module being + * on its classpath, and its own scan never has to reach into adapter packages. + * + *

First among auto-configurations, which is where a scanned user configuration used to sit: the + * security filter chain and JWT decoder have to be defined before Spring Boot's own security + * auto-configurations decide whether to back off, and {@link GlobalExceptionHandler} before {@link + * WebMvcPlatformAutoConfiguration} offers its default. + */ +@AutoConfiguration +@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE) +@EnableConfigurationProperties({ + CorsSettings.class, + EdgeRateLimitTransportSettings.class, + PresentationSettings.class, + RolePermissionPolicy.class, + SecuritySettings.class, + WebMvcPlatformSettings.class +}) +@Import({ + JwtDecoderConfig.class, + JwtToAuthenticatedPrincipalConverter.class, + RedisSessionWebConfig.class, + SecurityConfig.class, + AuthorizationAdapter.class, + MethodSecurityConfig.class, + RolePermissionRegistry.class, + JacksonNullableConfig.class, + OpenApiContractConfig.class, + PresentationWebConfig.class, + HealthcheckController.class, + EnvelopeBodyAdvice.class, + GlobalExceptionHandler.class, + CacheControlFilter.class, + RequestLoggingFilter.class, + MdcCorrelationIdPortAdapter.class, + RateLimitWebConfig.class +}) +public class WebAdapterAutoConfiguration {} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebMvcPlatformAutoConfiguration.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebMvcPlatformAutoConfiguration.java index 823015dd..cbf06433 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebMvcPlatformAutoConfiguration.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebMvcPlatformAutoConfiguration.java @@ -1,25 +1,10 @@ package dev.caskeleton.adapter.inbound.web.mvc.autoconfigure; -import dev.caskeleton.adapter.inbound.web.budget.WebBudgetCatalog; -import dev.caskeleton.adapter.inbound.web.budget.WebBudgetProfileName; -import dev.caskeleton.adapter.inbound.web.budget.WebRequestBudget; -import dev.caskeleton.adapter.inbound.web.contract.WebWireTypeManifest; import dev.caskeleton.adapter.inbound.web.error.GlobalExceptionHandler; -import dev.caskeleton.adapter.inbound.web.error.ProblemCatalog; -import dev.caskeleton.adapter.inbound.web.error.WebProblemFactory; -import dev.caskeleton.adapter.inbound.web.error.WebProblemSanitizer; -import dev.caskeleton.adapter.inbound.web.http.WebMethodPolicy; -import dev.caskeleton.adapter.inbound.web.http.WebUriPolicy; import dev.caskeleton.adapter.inbound.web.mvc.context.WebMvcRequestContextArgumentResolver; -import dev.caskeleton.adapter.inbound.web.mvc.filter.WebMvcEvidenceFilter; import dev.caskeleton.adapter.inbound.web.mvc.filter.WebMvcRequestIdFilter; -import dev.caskeleton.adapter.inbound.web.operation.InMemoryWebOperationCatalog; -import dev.caskeleton.adapter.inbound.web.operation.WebOperationCatalog; -import dev.caskeleton.adapter.inbound.web.validation.WebValidationExceptionMapper; -import dev.caskeleton.adapter.inbound.web.validation.WebValidationIssueMapper; import dev.caskeleton.shared.tracing.SpanErrorRecorder; import java.util.List; -import org.springframework.beans.factory.ListableBeanFactory; import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; @@ -37,13 +22,12 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; * corrected onto: the condition lives here and everything else is imported, so "off" means no beans * rather than beans that happen not to be called. * - *

{@link ConditionalOnWebApplication} with {@code SERVLET} is what keeps this starter and the - * WebFlux one mutually exclusive at the type level — a reactive application cannot accidentally - * activate the servlet filters even if both artifacts are on the classpath. + *

Three beans: the {@code Envelope} error handler, the request-id filter, and the argument + * resolver that lets a controller declare {@code WebRequestContext}. HTTP errors are the {@code + * Envelope} this handler writes; {@code spring.mvc.problemdetails.enabled} stays false. * - *

Every bean is {@link ConditionalOnMissingBean}. An adopter that registers its own operation - * catalog gets theirs; the platform supplies the one that would otherwise be missing rather than - * the one that must be used. + *

Every bean is {@link ConditionalOnMissingBean}: the platform supplies the one that would + * otherwise be missing rather than the one that must be used. */ @AutoConfiguration @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) @@ -55,29 +39,6 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @EnableConfigurationProperties(WebMvcPlatformSettings.class) public class WebMvcPlatformAutoConfiguration { - /** The catalog of registered operations; empty until routes register themselves. */ - @Bean - @ConditionalOnMissingBean(WebOperationCatalog.class) - public InMemoryWebOperationCatalog webOperationCatalog() { - return new InMemoryWebOperationCatalog(); - } - - /** The registered request budget profiles, with the conservative standard profile present. */ - @Bean - @ConditionalOnMissingBean - public WebBudgetCatalog webBudgetCatalog() { - WebBudgetCatalog catalog = new WebBudgetCatalog(); - catalog.register(WebBudgetProfileName.standard(), WebRequestBudget.standard()); - return catalog; - } - - /** The published problem catalog. */ - @Bean - @ConditionalOnMissingBean - public ProblemCatalog webProblemCatalog() { - return ProblemCatalog.standard(); - } - /** * The shipped envelope error handler. * @@ -91,55 +52,6 @@ public class WebMvcPlatformAutoConfiguration { return new GlobalExceptionHandler(spanErrorRecorderProvider); } - /** - * The builder used by the optional RFC problem-document surface and its release tooling. - * - *

The shipped servlet application pins {@code spring.mvc.problemdetails.enabled=false} and - * publishes the shared {@code Envelope} contract instead. Keeping the factory available does not - * activate that second wire contract: {@code WebMvcProblemExceptionHandler} is explicitly gated - * on the problem-details switch. - */ - @Bean - @ConditionalOnMissingBean - public WebProblemFactory webProblemFactory(ProblemCatalog catalog) { - return new WebProblemFactory(catalog, new WebProblemSanitizer()); - } - - /** The 400/422 classifier. */ - @Bean - @ConditionalOnMissingBean - public WebValidationExceptionMapper webValidationExceptionMapper() { - return new WebValidationExceptionMapper(); - } - - /** The Bean Validation to JSON Pointer mapper. */ - @Bean - @ConditionalOnMissingBean - public WebValidationIssueMapper webValidationIssueMapper() { - return new WebValidationIssueMapper(); - } - - /** The fixed JSON representation of the types whose defaults are wrong for an API. */ - @Bean - @ConditionalOnMissingBean - public WebWireTypeManifest webWireTypeManifest() { - return WebWireTypeManifest.standard(); - } - - /** The one accepted path spelling. */ - @Bean - @ConditionalOnMissingBean - public WebUriPolicy webUriPolicy() { - return WebUriPolicy.standard(); - } - - /** The method allowlist. */ - @Bean - @ConditionalOnMissingBean - public WebMethodPolicy webMethodPolicy() { - return WebMethodPolicy.standard(); - } - /** Assigns the correlation identifiers, validating anything a caller proposed. */ @Bean @ConditionalOnMissingBean @@ -149,21 +61,6 @@ public class WebMvcPlatformAutoConfiguration { org.springframework.core.Ordered.HIGHEST_PRECEDENCE + 10); } - /** Attaches one evidence tracker per logical request. */ - @Bean - @ConditionalOnMissingBean - public WebMvcEvidenceFilter webMvcEvidenceFilter() { - return new WebMvcEvidenceFilter(); - } - - /** Fails startup if a mandatory servlet control is not actually present in the bean graph. */ - @Bean - @ConditionalOnMissingBean(WebMvcPlatformStartupCheck.class) - public WebMvcPlatformStartupCheck webMvcPlatformStartupCheck( - ListableBeanFactory beans, ProblemCatalog problems) { - return new WebMvcPlatformStartupCheck(beans, problems); - } - /** Lets a controller declare the request context instead of the servlet request. */ @Bean @ConditionalOnMissingBean(name = "webMvcRequestContextConfigurer") diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebMvcPlatformStartupCheck.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebMvcPlatformStartupCheck.java deleted file mode 100644 index 1395c162..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebMvcPlatformStartupCheck.java +++ /dev/null @@ -1,59 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.mvc.autoconfigure; - -import dev.caskeleton.adapter.inbound.web.admin.platform.WebPlatformSnapshot; -import dev.caskeleton.adapter.inbound.web.admin.platform.WebPlatformStartupValidator; -import dev.caskeleton.adapter.inbound.web.error.GlobalExceptionHandler; -import dev.caskeleton.adapter.inbound.web.error.ProblemCatalog; -import dev.caskeleton.adapter.inbound.web.mvc.error.WebMvcProblemExceptionHandler; -import dev.caskeleton.adapter.inbound.web.mvc.filter.WebMvcEvidenceFilter; -import dev.caskeleton.adapter.inbound.web.mvc.filter.WebMvcRequestIdFilter; -import java.util.List; -import java.util.Map; -import org.springframework.beans.factory.ListableBeanFactory; -import org.springframework.beans.factory.SmartInitializingSingleton; - -/** - * Fails servlet startup when a mandatory web control exists in configuration but not in the bean - * graph. - */ -public final class WebMvcPlatformStartupCheck implements SmartInitializingSingleton { - - static final List REQUIRED_CONTROLS = - List.of("problemHandler", "requestIdFilter", "evidenceFilter"); - - private final ListableBeanFactory beans; - private final ProblemCatalog problems; - - public WebMvcPlatformStartupCheck(ListableBeanFactory beans, ProblemCatalog problems) { - this.beans = beans; - this.problems = problems; - } - - @Override - public void afterSingletonsInstantiated() { - Map controls = - Map.of( - "problemHandler", - hasBean(GlobalExceptionHandler.class) || hasBean(WebMvcProblemExceptionHandler.class), - "requestIdFilter", - hasBean(WebMvcRequestIdFilter.class), - "evidenceFilter", - hasBean(WebMvcEvidenceFilter.class)); - - WebPlatformSnapshot snapshot = - new WebPlatformSnapshot( - "servlet", - List.of(), - problems.definitions().keySet().stream().map(Enum::name).sorted().toList(), - Map.of(), - Map.of(), - List.of(), - controls); - - new WebPlatformStartupValidator(REQUIRED_CONTROLS).validate(snapshot); - } - - private boolean hasBean(Class type) { - return beans.getBeanNamesForType(type, false, false).length > 0; - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/budget/BoundedHttpServletRequest.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/budget/BoundedHttpServletRequest.java deleted file mode 100644 index 37c6eaaa..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/budget/BoundedHttpServletRequest.java +++ /dev/null @@ -1,115 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.mvc.budget; - -import dev.caskeleton.adapter.inbound.web.budget.WebBudgetMeter; -import jakarta.servlet.ReadListener; -import jakarta.servlet.ServletInputStream; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletRequestWrapper; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.util.Objects; - -/** - * A request whose body cannot exceed its budget. - * - *

Wrapping the stream rather than reading the body first is the requirement, not a refinement: a - * check that reads the body to measure it hands an attacker the heap exhaustion the check exists to - * prevent. Here the bound is crossed while the bytes are still arriving, and the read fails at that - * byte. - * - *

{@code getReader} shares the same meter through the same stream, so a handler that reads text - * is bounded exactly like one that reads bytes. A wrapper that bounded only {@code getInputStream} - * would be bypassed by every {@code @RequestBody String}. - */ -public final class BoundedHttpServletRequest extends HttpServletRequestWrapper { - - private final WebBudgetMeter meter; - private ServletInputStream boundedStream; - private BufferedReader boundedReader; - - /** - * A bounded view of one request. - * - * @param request the request being served - * @param meter the body budget - */ - public BoundedHttpServletRequest(HttpServletRequest request, WebBudgetMeter meter) { - super(request); - this.meter = Objects.requireNonNull(meter, "meter"); - // Refused before a byte is read when the caller declared an oversized body. Cheap, honest, and - // never trusted on its own — a chunked or lying request has no Content-Length to check. - meter.declared(request.getContentLengthLong()); - } - - @Override - public ServletInputStream getInputStream() throws IOException { - if (boundedStream == null) { - boundedStream = new BoundedServletInputStream(super.getInputStream(), meter); - } - return boundedStream; - } - - @Override - public BufferedReader getReader() throws IOException { - if (boundedReader == null) { - Charset charset = - getCharacterEncoding() == null - ? StandardCharsets.UTF_8 - : Charset.forName(getCharacterEncoding()); - boundedReader = new BufferedReader(new InputStreamReader(getInputStream(), charset)); - } - return boundedReader; - } - - private static final class BoundedServletInputStream extends ServletInputStream { - - private final ServletInputStream delegate; - private final WebBudgetMeter meter; - - private BoundedServletInputStream(ServletInputStream delegate, WebBudgetMeter meter) { - this.delegate = delegate; - this.meter = meter; - } - - @Override - public int read() throws IOException { - int value = delegate.read(); - if (value != -1) { - meter.add(1); - } - return value; - } - - @Override - public int read(byte[] buffer, int offset, int length) throws IOException { - int read = delegate.read(buffer, offset, length); - if (read > 0) { - meter.add(read); - } - return read; - } - - @Override - public boolean isFinished() { - return delegate.isFinished(); - } - - @Override - public boolean isReady() { - return delegate.isReady(); - } - - @Override - public void setReadListener(ReadListener readListener) { - delegate.setReadListener(readListener); - } - - @Override - public void close() throws IOException { - delegate.close(); - } - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/budget/BoundedHttpServletResponse.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/budget/BoundedHttpServletResponse.java deleted file mode 100644 index 8ba1739a..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/budget/BoundedHttpServletResponse.java +++ /dev/null @@ -1,151 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.mvc.budget; - -import dev.caskeleton.adapter.inbound.web.budget.WebBudgetMeter; -import jakarta.servlet.ServletOutputStream; -import jakarta.servlet.WriteListener; -import jakarta.servlet.http.HttpServletResponse; -import jakarta.servlet.http.HttpServletResponseWrapper; -import java.io.IOException; -import java.io.PrintWriter; -import java.nio.charset.StandardCharsets; -import java.util.Objects; - -/** - * A response that cannot exceed its budget. - * - *

What happens on the way out depends on whether the response has been committed, and the two - * cases are genuinely different: - * - *

    - *
  • Not yet committed — nothing has reached the client, so the overrun can still be answered as - * a problem document. That is the good case and the platform should reach it. - *
  • Already committed — the status and part of the body are on the wire. There is no way to - * take them back and no way to send a different status, so the only honest end is to stop - * writing and let the connection die mid-document. A truncated response the client rejects is - * better than a silently short one it accepts as complete. - *
- */ -public final class BoundedHttpServletResponse extends HttpServletResponseWrapper { - - private final WebBudgetMeter meter; - private ServletOutputStream boundedStream; - private PrintWriter boundedWriter; - - /** - * A bounded view of one response. - * - * @param response the response being written - * @param meter the response budget - */ - public BoundedHttpServletResponse(HttpServletResponse response, WebBudgetMeter meter) { - super(response); - this.meter = Objects.requireNonNull(meter, "meter"); - } - - /** Whether the overrun can still be answered with a problem document. */ - public boolean canStillAnswer() { - return !isCommitted(); - } - - /** - * Discards the buffered response and everything counted for it. - * - *

Both, together. {@code reset} on its own leaves the meter holding the count of bytes that - * were just thrown away, so the small problem document replacing them is refused for a budget the - * client never received a byte of. - */ - @Override - public void reset() { - super.reset(); - meter.reset(); - boundedStream = null; - boundedWriter = null; - } - - @Override - public void resetBuffer() { - super.resetBuffer(); - meter.reset(); - } - - @Override - public void setContentLengthLong(long length) { - // The one chance to refuse before writing anything: a handler that knows its size says so - // here, and an oversized answer is turned into a problem while the response is still empty. - meter.declared(length); - super.setContentLengthLong(length); - } - - @Override - public void setContentLength(int length) { - meter.declared(length); - super.setContentLength(length); - } - - @Override - public ServletOutputStream getOutputStream() throws IOException { - if (boundedStream == null) { - boundedStream = new BoundedServletOutputStream(super.getOutputStream(), meter); - } - return boundedStream; - } - - @Override - public PrintWriter getWriter() throws IOException { - if (boundedWriter == null) { - boundedWriter = new PrintWriter(new java.io.OutputStreamWriter(getOutputStream(), charset())); - } - return boundedWriter; - } - - private java.nio.charset.Charset charset() { - return getCharacterEncoding() == null - ? StandardCharsets.UTF_8 - : java.nio.charset.Charset.forName(getCharacterEncoding()); - } - - private static final class BoundedServletOutputStream extends ServletOutputStream { - - private final ServletOutputStream delegate; - private final WebBudgetMeter meter; - - private BoundedServletOutputStream(ServletOutputStream delegate, WebBudgetMeter meter) { - this.delegate = delegate; - this.meter = meter; - } - - @Override - public void write(int value) throws IOException { - meter.add(1); - delegate.write(value); - } - - @Override - public void write(byte[] buffer, int offset, int length) throws IOException { - // Counted before the write, not after: counting after would put the byte that crosses the - // bound on the wire and only then refuse. - meter.add(length); - delegate.write(buffer, offset, length); - } - - @Override - public boolean isReady() { - return delegate.isReady(); - } - - @Override - public void setWriteListener(WriteListener writeListener) { - delegate.setWriteListener(writeListener); - } - - @Override - public void flush() throws IOException { - delegate.flush(); - } - - @Override - public void close() throws IOException { - delegate.close(); - } - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/budget/WebMvcBudgetExceptionHandler.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/budget/WebMvcBudgetExceptionHandler.java deleted file mode 100644 index ea75c7ef..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/budget/WebMvcBudgetExceptionHandler.java +++ /dev/null @@ -1,84 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.mvc.budget; - -import dev.caskeleton.adapter.inbound.web.budget.WebBudgetExceededException; -import dev.caskeleton.adapter.inbound.web.error.BudgetProblemMapper; -import dev.caskeleton.adapter.inbound.web.error.WebProblem; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; -import java.net.URI; -import java.util.Objects; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; -import org.springframework.core.Ordered; -import org.springframework.core.annotation.Order; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.ExceptionHandler; -import org.springframework.web.bind.annotation.RestControllerAdvice; - -/** - * Answers a budget crossed inside the handler. - * - *

Needed alongside the filter, not instead of it, because the two catch different moments. The - * filter sees the cheap dimensions before dispatch and the response overrun after; a body bound - * crossed while the handler is reading the stream is thrown *inside* the dispatcher, which resolves - * it into a 500 before the filter's catch is ever reached. That is how the first draft of this - * feature answered 500 to an oversized chunked body while its unit tests were green. - * - *

Both paths produce the document through the same {@link BudgetProblemMapper}, so which one - * fired is invisible to a client. - */ -@RestControllerAdvice -// Mirrors every condition on the auto-configuration that supplies its WebProblemFactory. Only -// half of them was not enough: the all-off deployment is not a servlet application at all, so the -// factory is absent while the property condition still matched, and the context failed to start on -// an unsatisfied dependency. -@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) -// Gated on a property rather than on the BudgetProblemMapper bean, for the same reason: on a -// component-scanned type @ConditionalOnBean is evaluated before the configuration that declares -// the bean has necessarily run, so the handler disappears without a word. -@ConditionalOnProperty(prefix = "backend.web.budgets", name = "enabled", havingValue = "true") -@Order(Ordered.HIGHEST_PRECEDENCE) -public class WebMvcBudgetExceptionHandler { - - private final BudgetProblemMapper problems; - - /** - * A handler over the budget problem mapper. - * - * @param problems renders a crossed bound as a problem document - */ - public WebMvcBudgetExceptionHandler(BudgetProblemMapper problems) { - this.problems = Objects.requireNonNull(problems, "problems"); - } - - /** - * Publishes a crossed bound. - * - *

The response is reset first, and that is load-bearing for the response-overrun case. That - * violation is thrown while the message converter is writing, so without the reset this advice - * would serialize the problem document back through a meter already over its limit — the write - * fails again and the client gets the container's own error page with no problem document at all. - * Resetting discards the partial body the client never received and, with it, the count of those - * bytes. - * - *

Once the response has committed there is nothing to reset and no status left to send. The - * exception is rethrown so the connection ends mid-document: a client that sees a truncated - * response knows something went wrong, and one that sees a short but well-formed one does not. - */ - @ExceptionHandler(WebBudgetExceededException.class) - public ResponseEntity handle( - WebBudgetExceededException exceeded, - HttpServletRequest request, - HttpServletResponse response) { - if (response.isCommitted()) { - throw exceeded; - } - response.reset(); - WebProblem problem = - problems.problemFor(exceeded, URI.create(request.getRequestURI()), "0".repeat(32)); - return ResponseEntity.status(problem.status()) - .contentType(MediaType.valueOf(WebProblem.MEDIA_TYPE)) - .body(problem); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/budget/WebMvcBudgetFilter.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/budget/WebMvcBudgetFilter.java deleted file mode 100644 index d35a927c..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/budget/WebMvcBudgetFilter.java +++ /dev/null @@ -1,122 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.mvc.budget; - -import dev.caskeleton.adapter.inbound.web.budget.WebBudgetExceededException; -import dev.caskeleton.adapter.inbound.web.budget.WebBudgetMeter; -import dev.caskeleton.adapter.inbound.web.budget.WebBudgetViolation; -import dev.caskeleton.adapter.inbound.web.budget.WebRequestBudget; -import dev.caskeleton.adapter.inbound.web.error.BudgetProblemMapper; -import dev.caskeleton.adapter.inbound.web.error.WebProblem; -import jakarta.servlet.FilterChain; -import jakarta.servlet.ServletException; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.net.URI; -import java.nio.charset.StandardCharsets; -import java.util.Collections; -import java.util.Objects; -import org.springframework.web.filter.OncePerRequestFilter; -import tools.jackson.databind.json.JsonMapper; - -/** - * Enforces the request and response budgets on the servlet stack. - * - *

Ordered before anything that reads the request, because a bound applied after the body has - * been parsed has already lost. The cheap dimensions — URI, headers, query count — are checked up - * front from values the container has already parsed; the expensive ones are enforced by the - * wrappers as bytes move. - */ -public final class WebMvcBudgetFilter extends OncePerRequestFilter { - - private final WebRequestBudget budget; - private final BudgetProblemMapper problems; - private final JsonMapper mapper; - - /** - * A filter over one budget. - * - * @param budget the bounds to enforce - * @param problems renders a crossed bound as a problem document - * @param mapper serializes that document - */ - public WebMvcBudgetFilter( - WebRequestBudget budget, BudgetProblemMapper problems, JsonMapper mapper) { - this.budget = Objects.requireNonNull(budget, "budget"); - this.problems = Objects.requireNonNull(problems, "problems"); - this.mapper = Objects.requireNonNull(mapper, "mapper"); - } - - @Override - protected void doFilterInternal( - HttpServletRequest request, HttpServletResponse response, FilterChain chain) - throws ServletException, IOException { - BoundedHttpServletResponse bounded = - new BoundedHttpServletResponse( - response, - new WebBudgetMeter(WebBudgetViolation.RESPONSE_TOO_LARGE, budget.maxResponseBytes())); - try { - checkCheapDimensions(request); - chain.doFilter( - new BoundedHttpServletRequest( - request, - new WebBudgetMeter(WebBudgetViolation.BODY_TOO_LARGE, budget.maxBodyBytes())), - bounded); - } catch (WebBudgetExceededException exceeded) { - if (!bounded.canStillAnswer()) { - // Committed. There is no status left to send and no way to retract what went out, so the - // response ends here, truncated. A client sees a broken document rather than a short one - // it would have accepted as whole. - throw new IOException("response budget exceeded after commit", exceeded); - } - writeProblem(request, response, exceeded); - } - } - - private void checkCheapDimensions(HttpServletRequest request) { - String uri = request.getRequestURI(); - String query = request.getQueryString(); - int uriBytes = - uri.getBytes(StandardCharsets.UTF_8).length - + (query == null ? 0 : query.getBytes(StandardCharsets.UTF_8).length + 1); - if (uriBytes > budget.maxUriBytes()) { - throw new WebBudgetExceededException( - WebBudgetViolation.URI_TOO_LONG, uriBytes, budget.maxUriBytes()); - } - - long headerBytes = 0; - for (String name : Collections.list(request.getHeaderNames())) { - for (String value : Collections.list(request.getHeaders(name))) { - // ": " and CRLF, so the measurement is of the wire form rather than of the parsed values. - headerBytes += name.length() + (value == null ? 0 : value.length()) + 4; - } - } - if (headerBytes > budget.maxHeaderBytes()) { - throw new WebBudgetExceededException( - WebBudgetViolation.HEADERS_TOO_LARGE, headerBytes, budget.maxHeaderBytes()); - } - - int parameters = request.getParameterMap().size(); - if (parameters > budget.maxQueryParameters()) { - throw new WebBudgetExceededException( - WebBudgetViolation.TOO_MANY_QUERY_PARAMETERS, parameters, budget.maxQueryParameters()); - } - } - - private void writeProblem( - HttpServletRequest request, HttpServletResponse response, WebBudgetExceededException exceeded) - throws IOException { - WebProblem problem = - problems.problemFor( - exceeded, - URI.create(request.getRequestURI()), - // The filter runs before the context resolver, so there is no trace id to borrow yet. - // A zero trace is honest about that; inventing one would put an identifier in a log - // that correlates with nothing. - "0".repeat(32)); - response.reset(); - response.setStatus(problems.statusFor(exceeded.violation())); - response.setContentType(WebProblem.MEDIA_TYPE); - response.setCharacterEncoding(StandardCharsets.UTF_8.name()); - response.getWriter().write(mapper.writeValueAsString(problem)); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/error/WebMvcProblemExceptionHandler.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/error/WebMvcProblemExceptionHandler.java deleted file mode 100644 index 8ff0fd06..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/error/WebMvcProblemExceptionHandler.java +++ /dev/null @@ -1,174 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.mvc.error; - -import dev.caskeleton.adapter.inbound.web.error.ProblemCode; -import dev.caskeleton.adapter.inbound.web.error.ValidationIssue; -import dev.caskeleton.adapter.inbound.web.error.WebProblem; -import dev.caskeleton.adapter.inbound.web.error.WebProblemFactory; -import dev.caskeleton.adapter.inbound.web.error.WebResourceNotVisibleException; -import dev.caskeleton.adapter.inbound.web.validation.WebValidationExceptionMapper; -import jakarta.servlet.http.HttpServletRequest; -import java.net.URI; -import java.util.List; -import java.util.Objects; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; -import org.springframework.core.Ordered; -import org.springframework.core.annotation.Order; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.http.converter.HttpMessageNotReadableException; -import org.springframework.web.HttpMediaTypeNotSupportedException; -import org.springframework.web.HttpRequestMethodNotSupportedException; -import org.springframework.web.bind.MethodArgumentNotValidException; -import org.springframework.web.bind.annotation.ExceptionHandler; -import org.springframework.web.bind.annotation.RestControllerAdvice; -import org.springframework.web.servlet.resource.NoResourceFoundException; - -/** - * Turns the framework's own transport failures into the platform's problem documents. - * - *

This is the piece that was missing, and its absence was invisible in the way that matters: - * {@code WebProblemFactory} and {@code ProblemCatalog} existed, were fully unit-tested, and were - * reached by nothing on the framework-error path. Spring answered a failed {@code @Valid} with its - * own {@code ProblemDetail} — RFC 9457-shaped, so it looked right — carrying no {@code code} field - * and a 400 where the platform's own 400/422 split says 422. Every client branching on {@code - * ProblemCode} would have found nothing to branch on, and no test of the catalog would ever have - * noticed. - * - *

Ordered ahead of Spring's {@code ResponseEntityExceptionHandler}, which handles all of these - * types and would otherwise win. - */ -@RestControllerAdvice -@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) -// The repository's shipped servlet contract is the Envelope contract and pins this switch false. -// Setting it true is therefore an explicit opt-in to the reusable RFC problem-document surface -// used by the cross-stack contract fixtures; the two error contracts can no longer activate -// implicitly in the same servlet application. -@ConditionalOnProperty( - prefix = "spring.mvc.problemdetails", - name = "enabled", - havingValue = "true", - matchIfMissing = false) -@Order(Ordered.HIGHEST_PRECEDENCE + 10) -public class WebMvcProblemExceptionHandler { - - private final WebProblemFactory problems; - private final WebValidationExceptionMapper validationMapper; - - /** - * A handler over the problem catalog. - * - * @param problems the problem document factory - */ - public WebMvcProblemExceptionHandler(WebProblemFactory problems) { - this.problems = Objects.requireNonNull(problems, "problems"); - this.validationMapper = new WebValidationExceptionMapper(); - } - - /** A bound request that violated a declared constraint: 422. */ - @ExceptionHandler(MethodArgumentNotValidException.class) - public ResponseEntity handleValidation( - MethodArgumentNotValidException failure, HttpServletRequest request) { - // 422, not 400. The document parsed and bound perfectly; what is wrong is what it says. A - // client told 400 looks for a syntax error it will not find. - List issues = - failure.getBindingResult().getFieldErrors().stream() - .map( - error -> - new ValidationIssue( - // RFC 6901 pointer, so a client can locate the field in the document it - // sent rather than parse a Java property path. - "/" + error.getField().replace('.', '/'), - error.getCode() == null ? "INVALID" : error.getCode(), - error.getDefaultMessage() == null - ? "is invalid" - : error.getDefaultMessage())) - .toList(); - return answer(ProblemCode.VALIDATION_FAILED, "the request failed validation", request, issues); - } - - /** A document that could not be read or could not be bound: 400. */ - @ExceptionHandler(HttpMessageNotReadableException.class) - public ResponseEntity handleUnreadable( - HttpMessageNotReadableException failure, HttpServletRequest request) { - // The split between "did not parse" and "parsed but would not bind" is the validation mapper's - // decision, not this handler's, so both stacks reach the same conclusion from the same code. - ProblemCode code = - validationMapper.find(failure.getMostSpecificCause()).orElse(ProblemCode.MALFORMED_REQUEST); - return answer(code, "the request body could not be read", request, List.of()); - } - - /** A media type this operation does not read: 415. */ - @ExceptionHandler(HttpMediaTypeNotSupportedException.class) - public ResponseEntity handleMediaType( - HttpMediaTypeNotSupportedException failure, HttpServletRequest request) { - return answer( - ProblemCode.UNSUPPORTED_MEDIA_TYPE, - "this operation does not read that media type", - request, - List.of()); - } - - /** A method this resource does not serve: 405. */ - @ExceptionHandler(HttpRequestMethodNotSupportedException.class) - public ResponseEntity handleMethod( - HttpRequestMethodNotSupportedException failure, HttpServletRequest request) { - WebProblem problem = - problems.create( - ProblemCode.METHOD_NOT_ALLOWED, - "this resource does not serve that method", - URI.create(request.getRequestURI()), - traceIdOf(request), - List.of()); - ResponseEntity.BodyBuilder builder = - ResponseEntity.status(problem.status()) - .contentType(MediaType.valueOf(WebProblem.MEDIA_TYPE)); - if (failure.getSupportedHttpMethods() != null) { - // RFC 9110 requires Allow on a 405. Omitting it leaves the client with no way to discover - // what the resource does serve except by guessing. - builder.header( - "Allow", - failure.getSupportedHttpMethods().stream() - .map(Object::toString) - .collect(java.util.stream.Collectors.joining(", "))); - } - return builder.body(problem); - } - - /** The resource is absent, or the caller may not know it exists: 404 either way. */ - @ExceptionHandler(WebResourceNotVisibleException.class) - public ResponseEntity handleNotVisible( - WebResourceNotVisibleException failure, HttpServletRequest request) { - return answer( - ProblemCode.RESOURCE_NOT_FOUND, - "no such " + failure.resourceKind() + " is visible", - request, - List.of()); - } - - /** Nothing is served at that path: 404. */ - @ExceptionHandler(NoResourceFoundException.class) - public ResponseEntity handleMissing( - NoResourceFoundException failure, HttpServletRequest request) { - return answer( - ProblemCode.RESOURCE_NOT_FOUND, "no resource is served at that path", request, List.of()); - } - - private ResponseEntity answer( - ProblemCode code, String detail, HttpServletRequest request, List issues) { - WebProblem problem = - problems.create( - code, detail, URI.create(request.getRequestURI()), traceIdOf(request), issues); - return ResponseEntity.status(problem.status()) - .contentType(MediaType.valueOf(WebProblem.MEDIA_TYPE)) - .body(problem); - } - - private static String traceIdOf(HttpServletRequest request) { - Object traceId = request.getAttribute("webTraceId"); - // A zero trace rather than a generated one. An identifier that correlates with nothing is - // worse than an obviously absent one: it sends an investigator looking for a trace that was - // never recorded. - return traceId == null ? "0".repeat(32) : traceId.toString(); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/filter/WebMvcEvidenceFilter.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/filter/WebMvcEvidenceFilter.java deleted file mode 100644 index 250ebee6..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/filter/WebMvcEvidenceFilter.java +++ /dev/null @@ -1,114 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.mvc.filter; - -import dev.caskeleton.adapter.inbound.web.evidence.WebExecutionEvidenceTracker; -import jakarta.servlet.FilterChain; -import jakarta.servlet.ServletException; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; -import java.io.IOException; -import org.springframework.core.Ordered; -import org.springframework.web.filter.OncePerRequestFilter; - -/** - * Attaches one evidence tracker to one logical request. - * - *

"Logical" is the word that matters. A servlet request that starts an async response is - * dispatched through the filter chain more than once, and a tracker created per dispatch would - * throw away what the first pass recorded — including, in the case this whole model exists for, - * that the application already committed. - * - *

{@link OncePerRequestFilter} alone does not solve that: its default is to skip async - * dispatches entirely, which would leave the redispatch with no tracker at all. So the filter opts - * into async dispatches and reuses the tracker it finds, which is why {@link - * #shouldNotFilterAsyncDispatch()} returns false. - * - *

The filter never touches the request body. Reading it here would consume the stream the - * controller is about to bind from, and buffering it to avoid that would put every request's body - * in memory to serve a concern that does not need it. - */ -public final class WebMvcEvidenceFilter extends OncePerRequestFilter implements Ordered { - - /** Where the tracker lives for the duration of the logical request. */ - public static final String EVIDENCE_ATTRIBUTE = - WebMvcEvidenceFilter.class.getName() + ".evidence"; - - private final int order; - - /** A filter at the platform's default position, just inside request-id assignment. */ - public WebMvcEvidenceFilter() { - this(Ordered.HIGHEST_PRECEDENCE + 20); - } - - /** - * A filter at an explicit position. - * - * @param order the filter order - */ - public WebMvcEvidenceFilter(int order) { - this.order = order; - } - - @Override - protected void doFilterInternal( - HttpServletRequest request, HttpServletResponse response, FilterChain chain) - throws IOException, ServletException { - WebExecutionEvidenceTracker tracker = existingTracker(request); - if (tracker == null) { - request.setAttribute(EVIDENCE_ATTRIBUTE, WebExecutionEvidenceTracker.received()); - } - chain.doFilter(request, response); - } - - /** - * Runs on async dispatches too. - * - *

The base class skips them by default. Skipping would mean the redispatch has no tracker, so - * whatever recorded evidence during the async completion would be writing to nothing. - */ - @Override - protected boolean shouldNotFilterAsyncDispatch() { - return false; - } - - /** - * Runs on error dispatches too. - * - *

An error dispatch is where a failed response is written, and the response axis is precisely - * what needs recording there. - */ - @Override - protected boolean shouldNotFilterErrorDispatch() { - return false; - } - - @Override - public int getOrder() { - return order; - } - - /** - * The tracker for a request, or null when this filter has not run. - * - * @param request the current request - */ - public static WebExecutionEvidenceTracker existingTracker(HttpServletRequest request) { - Object attribute = request.getAttribute(EVIDENCE_ATTRIBUTE); - return attribute instanceof WebExecutionEvidenceTracker tracker ? tracker : null; - } - - /** - * The tracker for a request. - * - * @throws IllegalStateException when the filter is not installed, rather than silently returning - * a fresh tracker whose evidence nothing else can see - */ - public static WebExecutionEvidenceTracker requireTracker(HttpServletRequest request) { - WebExecutionEvidenceTracker tracker = existingTracker(request); - if (tracker == null) { - throw new IllegalStateException( - "no execution evidence tracker on this request; WebMvcEvidenceFilter is not installed," - + " and a fresh tracker here would record evidence nothing else reads"); - } - return tracker; - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/operation/OperationHttpController.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/operation/OperationHttpController.java deleted file mode 100644 index d89619ea..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/operation/OperationHttpController.java +++ /dev/null @@ -1,107 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.mvc.operation; - -import dev.caskeleton.adapter.inbound.web.core.OwnsAbsoluteWebRoute; -import dev.caskeleton.adapter.inbound.web.core.WebRequestContext; -import dev.caskeleton.adapter.inbound.web.error.WebResourceNotVisibleException; -import dev.caskeleton.adapter.inbound.web.operationasync.OperationId; -import dev.caskeleton.adapter.inbound.web.operationasync.OperationQueryService; -import dev.caskeleton.adapter.inbound.web.operationasync.OperationResource; -import dev.caskeleton.adapter.inbound.web.operationasync.OperationResponse; -import dev.caskeleton.adapter.inbound.web.operationasync.OperationResponseMapper; -import dev.caskeleton.adapter.inbound.web.operationasync.OperationStatus; -import java.net.URI; -import java.util.Objects; -import java.util.Optional; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.DeleteMapping; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -/** - * The polled operation resource, on the servlet stack. - * - *

The route is the platform's, not an application's: the whole point of a durable operation is - * that one shape of receipt works for every long-running endpoint. An application that published - * its own polling route per operation would make every client learn a new one. - */ -@OwnsAbsoluteWebRoute -@RestController -// Gated, because the durable operation store only exists when a persistence adapter provides one. -// Without the gate this controller is component-scanned into every deployment and the context -// fails to start with an unsatisfied dependency — which is exactly what happened, and what the -// all-adapters-off startup contract caught. -@ConditionalOnProperty( - prefix = "app.web-platform.durable-operations", - name = "enabled", - havingValue = "true") -@RequestMapping(OperationHttpController.BASE_PATH) -public class OperationHttpController { - - /** Where operations are published. */ - public static final String BASE_PATH = "/api/v1/operations"; - - private final OperationQueryService operations; - - /** - * A controller over the query service. - * - * @param operations reads and cancels operations - */ - public OperationHttpController(OperationQueryService operations) { - this.operations = Objects.requireNonNull(operations, "operations"); - } - - /** The URI a 202 receipt points at. */ - public static URI locationOf(String operationId) { - return URI.create(BASE_PATH + "/" + new OperationId(operationId).value()); - } - - /** Reads one operation. */ - @GetMapping(path = "/{operationId}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity get( - @PathVariable String operationId, WebRequestContext context) { - Optional resource = operations.find(new OperationId(operationId), context); - if (resource.isEmpty()) { - // Thrown, not returned. `notFound().build()` is a status with no body, which is a failure a - // client cannot branch on; the exception reaches the platform's problem handler and comes - // out as a document like every other failure. - // - // 404 for both "absent" and "not yours": distinguishing them turns a guessable id into an - // oracle for what other callers are running. - throw new WebResourceNotVisibleException("operation"); - } - OperationResource operation = resource.get(); - ResponseEntity.BodyBuilder builder = ResponseEntity.ok(); - operation - .retryAfter() - .ifPresent(after -> builder.header("Retry-After", Long.toString(after.toSeconds()))); - if (operation.status() == OperationStatus.SUCCEEDED) { - operation - .resultLocation() - .ifPresent(location -> builder.header("Content-Location", location.toString())); - } - return builder.body(OperationResponseMapper.from(operation)); - } - - /** - * Requests cancellation. - * - *

202 rather than 204: cancellation is a request, and a worker mid-flight may still finish. - * Answering 204 would tell the client the work has stopped when only the intent is recorded. - */ - @DeleteMapping("/{operationId}") - public ResponseEntity cancel(@PathVariable String operationId, WebRequestContext context) { - Optional outcome = operations.cancel(new OperationId(operationId), context); - if (outcome.isEmpty()) { - throw new WebResourceNotVisibleException("operation"); - } - // A second cancel, and a cancel of work that already finished, both land here. 409 would - // invite a retry that can never succeed; 202 says the same true thing every time — the - // request was received and the operation's state is what it is. - return ResponseEntity.accepted().header("Location", BASE_PATH + "/" + operationId).build(); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/throttle/WebMvcThrottleFilter.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/throttle/WebMvcThrottleFilter.java deleted file mode 100644 index 132e294e..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/throttle/WebMvcThrottleFilter.java +++ /dev/null @@ -1,136 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.mvc.throttle; - -import dev.caskeleton.adapter.inbound.web.admission.AdmissionDecision; -import dev.caskeleton.adapter.inbound.web.admission.AdmissionPermit; -import dev.caskeleton.adapter.inbound.web.admission.WebAdmissionController; -import dev.caskeleton.adapter.inbound.web.core.WebRequestContext; -import dev.caskeleton.adapter.inbound.web.error.ThrottleProblemWriter; -import dev.caskeleton.adapter.inbound.web.error.WebProblem; -import dev.caskeleton.adapter.inbound.web.operation.WebOperationProfile; -import dev.caskeleton.adapter.inbound.web.ratelimit.RateLimitDecision; -import dev.caskeleton.adapter.inbound.web.ratelimit.RateLimitFailurePolicy; -import dev.caskeleton.adapter.inbound.web.ratelimit.RateLimitProfileName; -import dev.caskeleton.adapter.inbound.web.ratelimit.WebRateLimiter; -import jakarta.servlet.FilterChain; -import jakarta.servlet.ServletException; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.net.URI; -import java.nio.charset.StandardCharsets; -import java.util.Objects; -import java.util.function.Function; -import org.springframework.web.filter.OncePerRequestFilter; -import tools.jackson.databind.json.JsonMapper; - -/** - * Applies the caller's quota and then the service's capacity, in that order. - * - *

Quota first, deliberately. Charging a caller's quota is cheap and refusing on it costs the - * service nothing; taking an admission slot occupies capacity that a caller who was about to be - * rate-limited anyway should never have held. The reverse order lets an abusive caller consume - * slots on its way to being told 429. - * - *

One filter for both, because the release of the admission permit has to wrap the rest of the - * chain. Split across two filters, the permit's {@code finally} would live in the outer one and the - * acquisition in the inner, which is the shape that leaks capacity the first time somebody reorders - * them. - */ -public final class WebMvcThrottleFilter extends OncePerRequestFilter { - - private final WebRateLimiter limiter; - private final WebAdmissionController admission; - private final Function profiles; - private final Function contexts; - private final RateLimitFailurePolicy failurePolicy; - private final ThrottleProblemWriter problems; - private final JsonMapper mapper; - - /** - * A filter over one limiter and one admission controller. - * - * @param limiter the caller quota - * @param admission the service capacity - * @param profiles resolves the operation profile for a request - * @param contexts resolves the request context - * @param failurePolicy what to do when the limiter's store is unreachable - * @param problems renders the refusals - * @param mapper serializes them - */ - public WebMvcThrottleFilter( - WebRateLimiter limiter, - WebAdmissionController admission, - Function profiles, - Function contexts, - RateLimitFailurePolicy failurePolicy, - ThrottleProblemWriter problems, - JsonMapper mapper) { - this.limiter = Objects.requireNonNull(limiter, "limiter"); - this.admission = Objects.requireNonNull(admission, "admission"); - this.profiles = Objects.requireNonNull(profiles, "profiles"); - this.contexts = Objects.requireNonNull(contexts, "contexts"); - this.failurePolicy = Objects.requireNonNull(failurePolicy, "failurePolicy"); - this.problems = Objects.requireNonNull(problems, "problems"); - this.mapper = Objects.requireNonNull(mapper, "mapper"); - } - - @Override - protected void doFilterInternal( - HttpServletRequest request, HttpServletResponse response, FilterChain chain) - throws ServletException, IOException { - WebOperationProfile profile = profiles.apply(request); - WebRequestContext context = contexts.apply(request); - - RateLimitDecision quota = evaluateQuota(context); - if (!quota.allowed()) { - write( - response, - problems.quotaStatus(), - problems.quotaExhausted(URI.create(request.getRequestURI()), context.traceId().value()), - ThrottleProblemWriter.retryAfterSeconds(quota.retryAfter().orElseThrow())); - return; - } - - AdmissionDecision admitted = admission.admit(profile.admission()); - if (!admitted.admitted()) { - write( - response, - problems.capacityStatus(), - problems.capacityExhausted( - URI.create(request.getRequestURI()), context.traceId().value()), - ThrottleProblemWriter.retryAfterSeconds(admitted.retryAfter().orElseThrow())); - return; - } - - // try-with-resources rather than a finally block: the permit is released on every exit, - // including the ones a later edit adds. - try (AdmissionPermit permit = admitted.permit().orElseThrow()) { - chain.doFilter(request, response); - } - } - - private RateLimitDecision evaluateQuota(WebRequestContext context) { - try { - return limiter.evaluate(context, RateLimitProfileName.standard()); - } catch (RuntimeException limiterUnavailable) { - if (failurePolicy == RateLimitFailurePolicy.FAIL_CLOSED) { - return RateLimitDecision.refused( - 1, context.receivedAt().plusSeconds(1), java.time.Duration.ofSeconds(1)); - } - // Fail open: the limiter's store is down and this operation's profile says serving is the - // lesser harm. The decision is the profile's, made at review time, not this filter's. - return RateLimitDecision.allowed(1, 1, context.receivedAt().plusSeconds(1)); - } - } - - private void write( - HttpServletResponse response, int status, WebProblem problem, String retryAfter) - throws IOException { - response.reset(); - response.setStatus(status); - response.setContentType(WebProblem.MEDIA_TYPE); - response.setCharacterEncoding(StandardCharsets.UTF_8.name()); - response.setHeader("Retry-After", retryAfter); - response.getWriter().write(mapper.writeValueAsString(problem)); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/reactive/BoundedCallbackBodyReader.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/reactive/BoundedCallbackBodyReader.java deleted file mode 100644 index f62c1744..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/reactive/BoundedCallbackBodyReader.java +++ /dev/null @@ -1,48 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.notification.platform.callback.reactive; - -import java.util.Objects; -import org.springframework.core.io.buffer.DataBuffer; -import org.springframework.core.io.buffer.DataBufferUtils; -import org.springframework.web.reactive.function.server.ServerRequest; -import reactor.core.publisher.Mono; - -/** - * Reads the raw body with a hard ceiling and no buffer leaks. - * - *

Every {@link DataBuffer} is released on success, on error and on cancellation. A reactive - * endpoint that forgets the cancellation path leaks native memory exactly when it is under the load - * that caused the cancellation. - */ -public final class BoundedCallbackBodyReader { - - private final int maxBytes; - - public BoundedCallbackBodyReader(int maxBytes) { - if (maxBytes < 1) { - throw new IllegalArgumentException("maxBytes"); - } - this.maxBytes = maxBytes; - } - - /** Read at most the configured number of bytes. */ - public Mono read(ServerRequest request) { - Objects.requireNonNull(request, "request"); - return DataBufferUtils.join(request.bodyToFlux(DataBuffer.class), maxBytes) - .map( - buffer -> { - try { - byte[] bytes = new byte[buffer.readableByteCount()]; - buffer.read(bytes); - return bytes; - } finally { - DataBufferUtils.release(buffer); - } - }) - .defaultIfEmpty(new byte[0]); - } - - /** Configured ceiling. */ - public int maxBytes() { - return maxBytes; - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/reactive/CallbackWebFluxConfiguration.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/reactive/CallbackWebFluxConfiguration.java deleted file mode 100644 index 466b7dce..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/reactive/CallbackWebFluxConfiguration.java +++ /dev/null @@ -1,58 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.notification.platform.callback.reactive; - -import dev.caskeleton.adapter.inbound.web.notification.platform.callback.CallbackRequestFactory; -import dev.caskeleton.adapter.inbound.web.notification.platform.callback.ProviderCallbackIngress; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.reactive.function.server.RouterFunction; -import org.springframework.web.reactive.function.server.ServerResponse; - -/** - * Registers the reactive callback transport, and only it. - * - *

This configuration is {@code REACTIVE}-only and the servlet controller carries the matching - * {@code SERVLET} condition, so exactly one of the two is ever registered — by construction rather - * than by convention. Both on the same path would mean a provider signature is verified twice - * against two different canonical URLs, a failure that shows up only in production and only for - * signed providers, and reads like a credential problem. - * - *

The body ceiling is read as a property rather than through the platform settings type: that - * type belongs to the outbound notification adapter, which this inbound adapter must not depend on. - */ -@Configuration(proxyBeanMethods = false) -@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE) -@ConditionalOnProperty( - prefix = "ca-skeleton.notification.platform.callbacks", - name = "enabled", - havingValue = "true") -public class CallbackWebFluxConfiguration { - - /** Bounded body reader; the ceiling applies before any provider adapter is consulted. */ - @Bean - @ConditionalOnMissingBean - public BoundedCallbackBodyReader notificationCallbackBodyReader( - @Value("${ca-skeleton.notification.platform.callbacks.max-body-bytes:65508}") int maxBytes) { - return new BoundedCallbackBodyReader(maxBytes); - } - - /** Reactive handler. */ - @Bean - @ConditionalOnMissingBean - public NotificationCallbackWebFluxHandler notificationCallbackWebFluxHandler( - ProviderCallbackIngress ingestion, - CallbackRequestFactory requestFactory, - BoundedCallbackBodyReader bodyReader) { - return new NotificationCallbackWebFluxHandler(ingestion, requestFactory, bodyReader); - } - - /** Functional route for the callback path. */ - @Bean - public RouterFunction notificationCallbackRoutes( - NotificationCallbackWebFluxHandler handler) { - return new CallbackWebFluxRouter(handler).routes(); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/reactive/CallbackWebFluxRouter.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/reactive/CallbackWebFluxRouter.java deleted file mode 100644 index cdabab9d..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/reactive/CallbackWebFluxRouter.java +++ /dev/null @@ -1,30 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.notification.platform.callback.reactive; - -import java.util.Objects; -import org.springframework.web.reactive.function.server.RequestPredicates; -import org.springframework.web.reactive.function.server.RouterFunction; -import org.springframework.web.reactive.function.server.RouterFunctions; -import org.springframework.web.reactive.function.server.ServerResponse; - -/** - * Routes the reactive callback path. - * - *

Kept separate from the servlet controller so that only one of the two is ever registered; two - * endpoints on the same path would mean a provider's signature is verified twice against two - * different canonical URLs. - */ -public final class CallbackWebFluxRouter { - - private final NotificationCallbackWebFluxHandler handler; - - public CallbackWebFluxRouter(NotificationCallbackWebFluxHandler handler) { - this.handler = Objects.requireNonNull(handler, "handler"); - } - - /** Router function for the callback path. */ - public RouterFunction routes() { - return RouterFunctions.route( - RequestPredicates.POST("/internal/notification/callbacks/{provider}/{profile}"), - handler::handle); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/reactive/NotificationCallbackWebFluxHandler.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/reactive/NotificationCallbackWebFluxHandler.java deleted file mode 100644 index afcdbb47..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/reactive/NotificationCallbackWebFluxHandler.java +++ /dev/null @@ -1,85 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.notification.platform.callback.reactive; - -import dev.caskeleton.adapter.inbound.web.notification.platform.callback.CallbackRequestFactory; -import dev.caskeleton.adapter.inbound.web.notification.platform.callback.ProviderCallbackIngress; -import dev.caskeleton.application.notification.platform.api.error.CallbackValidationException; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import org.springframework.core.io.buffer.DataBufferLimitException; -import org.springframework.http.HttpStatus; -import org.springframework.web.reactive.function.server.ServerRequest; -import org.springframework.web.reactive.function.server.ServerResponse; -import reactor.core.publisher.Mono; -import reactor.core.scheduler.Schedulers; - -/** - * Reactive callback endpoint. - * - *

Ingestion is blocking — it writes to the database — so it runs on {@code boundedElastic} and - * never on the event loop. Running it inline would stall every other connection the loop is - * serving. - * - *

It shares the canonicalisation and the ingestion service with the servlet endpoint, so a - * deployment can switch web stacks without changing what a provider signature is checked against. - */ -public final class NotificationCallbackWebFluxHandler { - - private final ProviderCallbackIngress ingestion; - private final CallbackRequestFactory requestFactory; - private final BoundedCallbackBodyReader bodyReader; - - public NotificationCallbackWebFluxHandler( - ProviderCallbackIngress ingestion, - CallbackRequestFactory requestFactory, - BoundedCallbackBodyReader bodyReader) { - this.ingestion = Objects.requireNonNull(ingestion, "ingestion"); - this.requestFactory = Objects.requireNonNull(requestFactory, "requestFactory"); - this.bodyReader = Objects.requireNonNull(bodyReader, "bodyReader"); - } - - /** Handle one callback. */ - public Mono handle(ServerRequest request) { - String provider = request.pathVariable("provider"); - String profile = request.pathVariable("profile"); - - return bodyReader - .read(request) - .flatMap( - body -> - Mono.fromCallable( - () -> - ingestion.ingest( - requestFactory.create( - provider, - profile, - request.uri().toString(), - request.method().name(), - request.headers().contentType().map(Object::toString), - headers(request), - body))) - .subscribeOn(Schedulers.boundedElastic())) - .then(ServerResponse.noContent().build()) - .onErrorResume( - DataBufferLimitException.class, - failure -> ServerResponse.status(HttpStatus.CONTENT_TOO_LARGE).build()) - .onErrorResume( - CallbackValidationException.class, - failure -> ServerResponse.status(HttpStatus.BAD_REQUEST).build()); - } - - private static Map> headers(ServerRequest request) { - Map> headers = new java.util.LinkedHashMap<>(); - request - .headers() - .asHttpHeaders() - .forEach((name, values) -> headers.put(name, List.copyOf(values))); - return Map.copyOf(headers); - } - - /** Content type of a request, if declared. */ - public static Optional contentType(ServerRequest request) { - return request.headers().contentType().map(Object::toString); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/WebAccessLogEvent.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/WebAccessLogEvent.java deleted file mode 100644 index 7a8ab4e5..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/WebAccessLogEvent.java +++ /dev/null @@ -1,65 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.observability; - -import java.time.Duration; -import java.time.Instant; -import java.util.Objects; - -/** - * One line of the access log, structured. - * - *

A record rather than a format string, so what is logged is decided once and by a type. The - * classic access-log failure is that the format grows a field somebody needed for one investigation - * — a query string, a header, a body excerpt — and it is then written for every request forever, - * into a store with a different retention policy and a wider audience than anybody considered. - * - *

What is deliberately absent: the query string, request and response bodies, headers, and the - * raw tenant identifier. Each is available at the point of logging and each is a leak. The trace id - * is here so that an investigation can reach the detail through a system that was designed to hold - * it. - * - * @param requestId this request's identifier - * @param traceId the correlation identifier - * @param method the HTTP method - * @param routeTemplate the matched template, never the resolved path - * @param status the response status - * @param problemCode the failure code when there was one, else null - * @param operationName the operation invoked - * @param apiVersion the API major version served - * @param clientProfile a bounded label for the kind of client - * @param duration how long it took - * @param requestBytes bytes read from the request - * @param responseBytes bytes written to the response - * @param at when the request completed - */ -public record WebAccessLogEvent( - String requestId, - String traceId, - String method, - String routeTemplate, - int status, - String problemCode, - String operationName, - int apiVersion, - String clientProfile, - Duration duration, - long requestBytes, - long responseBytes, - Instant at) { - - public WebAccessLogEvent { - Objects.requireNonNull(requestId, "requestId"); - Objects.requireNonNull(traceId, "traceId"); - Objects.requireNonNull(method, "method"); - Objects.requireNonNull(routeTemplate, "routeTemplate"); - Objects.requireNonNull(operationName, "operationName"); - Objects.requireNonNull(duration, "duration"); - Objects.requireNonNull(at, "at"); - if (routeTemplate.contains("?")) { - // A query string in the route field is the most common way personal data reaches an access - // log: search terms, email addresses, tokens that a client put in a query parameter. - throw new IllegalArgumentException( - "the access log records a route template, not a URL; a query string here is how search" - + " terms and tokens end up in a log with a different retention policy"); - } - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/WebAccessLogger.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/WebAccessLogger.java deleted file mode 100644 index fd84d9ed..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/WebAccessLogger.java +++ /dev/null @@ -1,19 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.observability; - -/** - * Where one completed request is recorded. - * - *

A port so the destination is a deployment decision. What is not negotiable is the shape: the - * event is a {@link WebAccessLogEvent}, so no implementation can add a field the type does not - * have. - * - *

Called exactly once per logical request. On the servlet stack that means checking the - * dispatcher type, because an async request passes through the filter chain twice and a second line - * makes every percentile computed from this data wrong. - */ -@FunctionalInterface -public interface WebAccessLogger { - - /** Records one completed request. */ - void record(WebAccessLogEvent event); -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/WebAuditAction.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/WebAuditAction.java deleted file mode 100644 index 9a305646..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/WebAuditAction.java +++ /dev/null @@ -1,41 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.observability; - -/** - * The operations that are audited rather than merely logged. - * - *

A closed set, and short on purpose. These are the actions where the question later is not - * "what did the system do" but "who decided this" — an operator reaching past a safety rail. They - * are separated from the access log because they need different retention, a different audience, - * and a guarantee that a log-level change cannot switch them off. - * - *

Everything here has the same shape: a human overrode a control the platform put in place. That - * is the membership test, not severity. - */ -public enum WebAuditAction { - - /** A resource removed past whatever protection normally prevents it. */ - ADMIN_FORCE_DELETE, - - /** Failed work pushed back onto a queue by hand. */ - ADMIN_REDRIVE, - - /** A grant or a role changed. */ - PERMISSION_CHANGE, - - /** - * An API's retirement date moved. - * - *

Audited because it is a promise to third parties. Moving a sunset date earlier breaks - * integrations that planned around it, and the record of who moved it is what makes that - * answerable. - */ - SUNSET_CHANGE, - - /** - * An idempotency record cleared or bypassed. - * - *

The one whose consequence is least obvious: clearing a record makes a retry execute again, - * so an operator doing this is authorising a possible duplicate write. - */ - IDEMPOTENCY_OVERRIDE -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/WebAuditEvent.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/WebAuditEvent.java deleted file mode 100644 index 7118a824..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/WebAuditEvent.java +++ /dev/null @@ -1,55 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.observability; - -import java.time.Instant; -import java.util.Map; -import java.util.Objects; - -/** - * A record of somebody overriding a control. - * - *

Unlike an access-log line, this one names the actor and the resource. That is the whole point: - * the question an audit answers is who did this to what, and an anonymised audit record answers - * nothing. The constructor therefore requires both, rather than letting an event be written without - * them and discovered to be useless during an investigation. - * - *

The reason is required for the same purpose. An override with no stated reason is a decision - * nobody can evaluate afterwards, and "it was needed at the time" is what every one of them looks - * like a year later. - * - * @param action what was overridden - * @param actor who did it - * @param resource what it was done to - * @param reason why, as given at the time - * @param traceId the request that carried it - * @param at when - * @param detail additional bounded facts about the override - */ -public record WebAuditEvent( - WebAuditAction action, - String actor, - String resource, - String reason, - String traceId, - Instant at, - Map detail) { - - public WebAuditEvent { - Objects.requireNonNull(action, "action"); - Objects.requireNonNull(traceId, "traceId"); - Objects.requireNonNull(at, "at"); - Objects.requireNonNull(detail, "detail"); - if (actor == null || actor.isBlank()) { - throw new IllegalArgumentException( - "an audit event without an actor answers nothing; the question it exists for is who did" - + " this"); - } - if (resource == null || resource.isBlank()) { - throw new IllegalArgumentException("an audit event must name what was acted on"); - } - if (reason == null || reason.isBlank()) { - throw new IllegalArgumentException( - "an override with no stated reason cannot be evaluated later, only inherited"); - } - detail = Map.copyOf(detail); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/WebAuditPublisher.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/WebAuditPublisher.java deleted file mode 100644 index 43cca5eb..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/WebAuditPublisher.java +++ /dev/null @@ -1,17 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.observability; - -/** - * Where audit events go. - * - *

A separate port from {@link WebAccessLogger}, and separate on purpose rather than as layering. - * An audit trail needs a retention period measured in years, a restricted audience, and an - * append-only destination; an access log needs none of those and is routinely sampled, rotated and - * shipped to whatever the observability vendor is this year. One port for both would mean one of - * those two sets of requirements silently applies to the other. - */ -@FunctionalInterface -public interface WebAuditPublisher { - - /** Records one override. */ - void publish(WebAuditEvent event); -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/WebMetricCardinalityPolicy.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/WebMetricCardinalityPolicy.java deleted file mode 100644 index 3c8f5520..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/WebMetricCardinalityPolicy.java +++ /dev/null @@ -1,112 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.observability; - -import java.util.Locale; -import java.util.Objects; -import java.util.Set; - -/** - * Which tags a metric may carry. - * - *

An allowlist, not a denylist. A metric's cost is the product of its tags' cardinalities, so a - * single tag with one value per user turns one time series into millions — and the failure is not - * an error anywhere. It is a monitoring bill, then a slow dashboard, then a metrics backend that - * starts dropping series, at which point the alert that was supposed to fire does not. - * - *

A denylist would have to anticipate every high-cardinality name anyone will ever invent. - * {@code userId} is obvious; {@code sessionRef}, {@code correlation}, {@code batchId} are not, and - * each one only has to be forgotten once. - * - *

Secrecy rides along for free. A tag value reaches the metrics backend, the dashboards and - * usually a third-party SaaS, and it is not redacted on the way — so an idempotency key or a token - * in a tag is an unencrypted export of it. - */ -public final class WebMetricCardinalityPolicy { - - /** - * The complete set of tags a metric may carry. - * - *

Every one is bounded by something the deployment controls: the routing table, the HTTP spec, - * the problem catalog, the operation registry. None grows with traffic. - */ - private static final Set ALLOWED = - Set.of( - // Bounded by the routing table. The *template*, never the resolved path: "/orders/{id}" - // is one series and "/orders/8a1f…" is one per order. - "routeTemplate", - "http.method", - "http.status", - "outcome", - "apiVersion", - "operationName", - "problemCode", - "clientProfile"); - - private WebMetricCardinalityPolicy() {} - - /** The standard policy. */ - public static WebMetricCardinalityPolicy standard() { - return new WebMetricCardinalityPolicy(); - } - - /** Whether a tag may be recorded. */ - public boolean allowed(String name) { - return name != null && ALLOWED.contains(name); - } - - /** The complete allowlist. */ - public Set allowedTags() { - return ALLOWED; - } - - /** - * Refuses a tag that is not on the allowlist. - * - * @param name the tag being recorded - * @throws IllegalArgumentException when it is not allowed - */ - public void require(String name) { - if (!allowed(name)) { - throw new IllegalArgumentException( - "metric tag '" - + name - + "' is not on the allowlist " - + ALLOWED - + "; an unbounded tag multiplies every series that carries it, and the failure is a" - + " metrics backend dropping data rather than an error anyone sees"); - } - } - - /** - * Whether a name looks like something that must never be a tag. - * - *

Advisory, for diagnostics and for the message a reviewer reads. The allowlist is what - * actually enforces the rule; this only explains why a particular name was refused. - */ - public static boolean obviouslyUnbounded(String name) { - if (name == null) { - return false; - } - String lower = name.toLowerCase(Locale.ROOT); - return lower.contains("id") - || lower.contains("url") - || lower.contains("uri") - || lower.contains("path") - || lower.contains("query") - || lower.contains("key") - || lower.contains("token") - || lower.contains("cookie") - || lower.contains("body") - || lower.contains("tenant") - || lower.contains("user"); - } - - @Override - public boolean equals(Object other) { - return other instanceof WebMetricCardinalityPolicy; - } - - @Override - public int hashCode() { - return Objects.hash(ALLOWED); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/WebObservationConvention.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/WebObservationConvention.java deleted file mode 100644 index de2b95f4..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/WebObservationConvention.java +++ /dev/null @@ -1,72 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.observability; - -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Objects; - -/** - * Builds the tag set for one observation, refusing anything off the allowlist. - * - *

A builder rather than a map the caller assembles, because the allowlist has to be applied at - * the point of construction. Checked afterwards, a forbidden tag has already been written by - * whoever built the map — and reviewing every call site is the process this class exists to - * replace. - */ -public final class WebObservationConvention { - - private final WebMetricCardinalityPolicy policy; - private final Map tags = new LinkedHashMap<>(); - - /** - * A convention over one policy. - * - * @param policy which tags are allowed - */ - public WebObservationConvention(WebMetricCardinalityPolicy policy) { - this.policy = Objects.requireNonNull(policy, "policy"); - } - - /** A convention over the standard policy. */ - public static WebObservationConvention standard() { - return new WebObservationConvention(WebMetricCardinalityPolicy.standard()); - } - - /** - * Adds a tag. - * - * @throws IllegalArgumentException when the tag is not on the allowlist - */ - public WebObservationConvention tag(String name, String value) { - policy.require(name); - Objects.requireNonNull(value, "value"); - tags.put(name, value); - return this; - } - - /** - * The route template, never the resolved path. - * - *

Separate from {@link #tag} because this is the one that gets it wrong in practice: the - * resolved path is what is easiest to reach for and it produces one series per resource. - * - * @param template a path with its variables still as placeholders - */ - public WebObservationConvention routeTemplate(String template) { - Objects.requireNonNull(template, "template"); - if (!template.contains("{") && template.chars().anyMatch(Character::isDigit)) { - // Not proof, but the cheapest signal that a resolved path slipped through: templates carry - // braces, and a digit-bearing segment with none is almost always an identifier. - throw new IllegalArgumentException( - "routeTemplate '" - + template - + "' looks like a resolved path rather than a template; one series per resource is" - + " how a metrics backend starts dropping data"); - } - return tag("routeTemplate", template); - } - - /** The tags collected so far. */ - public Map tags() { - return Map.copyOf(tags); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/openapi/CursorSchemaContributor.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/openapi/CursorSchemaContributor.java deleted file mode 100644 index 1be7552f..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/openapi/CursorSchemaContributor.java +++ /dev/null @@ -1,47 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.openapi; - -import io.swagger.v3.oas.models.media.ArraySchema; -import io.swagger.v3.oas.models.media.BooleanSchema; -import io.swagger.v3.oas.models.media.ObjectSchema; -import io.swagger.v3.oas.models.media.Schema; -import io.swagger.v3.oas.models.media.StringSchema; -import java.util.List; - -/** - * Renders the cursor page envelope into the published document. - * - *

The cursor is a string with no declared structure, and that is the contract rather than an - * omission. Publishing its shape would invite a client to construct one, and a constructed cursor - * skips the signature that makes it tamper-evident — at which point a caller can page into rows the - * query was scoped away from. - */ -public final class CursorSchemaContributor { - - private CursorSchemaContributor() {} - - /** The schema name the document publishes. */ - public static final String SCHEMA_NAME = "CursorPage"; - - /** - * The page envelope. - * - *

This is the one wrapper the platform publishes, and it is not the global response envelope - * the design forbids: it carries pagination state that has nowhere else to live, applies only to - * collection responses, and adds no second status. - */ - public static Schema schema() { - ObjectSchema page = new ObjectSchema(); - page.description("A page of results with an opaque continuation cursor."); - page.addProperty("items", new ArraySchema().items(new ObjectSchema())); - page.addProperty( - "nextCursor", - new StringSchema() - .description( - "Opaque and signed. Its structure is deliberately unpublished: a client that" - + " constructs one skips the signature that keeps it tamper-evident.")); - page.addProperty("hasMore", new BooleanSchema()); - page.required(List.of("items", "hasMore")); - page.additionalProperties(false); - return page; - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/openapi/ProblemSchemaContributor.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/openapi/ProblemSchemaContributor.java deleted file mode 100644 index 4be10e76..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/openapi/ProblemSchemaContributor.java +++ /dev/null @@ -1,88 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.openapi; - -import dev.caskeleton.adapter.inbound.web.error.ProblemCatalog; -import dev.caskeleton.adapter.inbound.web.error.ProblemCode; -import io.swagger.v3.oas.models.media.ArraySchema; -import io.swagger.v3.oas.models.media.ObjectSchema; -import io.swagger.v3.oas.models.media.Schema; -import io.swagger.v3.oas.models.media.StringSchema; -import java.util.Arrays; -import java.util.List; -import java.util.Objects; - -/** - * Renders the RFC 9457 problem body into the published document. - * - *

The {@code code} enum is generated from {@link ProblemCode} rather than written out. A - * hand-maintained list drifts the moment a code is added, and it drifts in the direction that - * matters: a client generator produces a sealed enum from the document, so a code the document - * omits becomes a deserialisation failure in every generated client the first time the service - * returns it. - */ -public final class ProblemSchemaContributor { - - private ProblemSchemaContributor() {} - - /** The schema name the document publishes. */ - public static final String SCHEMA_NAME = "Problem"; - - /** The validation issue schema name. */ - public static final String ISSUE_SCHEMA_NAME = "ValidationIssue"; - - /** The problem body, with its member set closed to what the platform actually sends. */ - public static Schema schema() { - ObjectSchema problem = new ObjectSchema(); - problem.description( - "RFC 9457 problem details. The member set is closed: the platform sends no extension" - + " beyond traceId and errors."); - problem.addProperty("type", new StringSchema().format("uri")); - problem.addProperty("title", new StringSchema()); - problem.addProperty( - "status", - new io.swagger.v3.oas.models.media.IntegerSchema() - .minimum(java.math.BigDecimal.valueOf(400)) - .maximum(java.math.BigDecimal.valueOf(599))); - problem.addProperty("detail", new StringSchema()); - problem.addProperty("instance", new StringSchema().format("uri")); - problem.addProperty("code", codeSchema()); - problem.addProperty("traceId", new StringSchema()); - problem.addProperty( - "errors", - new ArraySchema().items(new Schema<>().$ref("#/components/schemas/" + ISSUE_SCHEMA_NAME))); - problem.required(List.of("type", "title", "status", "code", "traceId")); - problem.additionalProperties(false); - return problem; - } - - /** The field-level issue schema, with no member for the submitted value. */ - public static Schema issueSchema() { - ObjectSchema issue = new ObjectSchema(); - issue.description( - "One field-level reason. There is deliberately no rejectedValue member: echoing submitted" - + " content back is how a password typed into the wrong field reaches a log."); - issue.addProperty("pointer", new StringSchema().description("RFC 6901 JSON Pointer")); - issue.addProperty("code", new StringSchema()); - issue.addProperty("message", new StringSchema()); - issue.required(List.of("pointer", "code", "message")); - issue.additionalProperties(false); - return issue; - } - - /** Every published problem code, generated from the enum. */ - public static Schema codeSchema() { - StringSchema code = new StringSchema(); - Arrays.stream(ProblemCode.values()).map(Enum::name).sorted().forEach(code::addEnumItemObject); - return code; - } - - /** - * Confirms the document's code list is the runtime catalog's. - * - * @param catalog the runtime catalog - * @return the codes the document would publish - */ - public static List publishedCodes(ProblemCatalog catalog) { - Objects.requireNonNull(catalog, "catalog"); - return catalog.definitions().keySet().stream().map(Enum::name).sorted().toList(); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/openapi/WebOpenApiCustomizer.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/openapi/WebOpenApiCustomizer.java deleted file mode 100644 index 55096eda..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/openapi/WebOpenApiCustomizer.java +++ /dev/null @@ -1,74 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.openapi; - -import io.swagger.v3.oas.models.Components; -import io.swagger.v3.oas.models.OpenAPI; -import java.util.Objects; - -/** - * Merges the platform components into the document springdoc generated from the routes. - * - *

Merged rather than replaced. springdoc knows the paths, the request bodies and the response - * types because it reads the handler methods; the platform knows the problem body, the cursor page - * and the security scheme because they are its own contracts. Each contributes what it can see, and - * neither overwrites the other. - * - *

An existing schema is left alone. A deployment that published its own {@code Problem} has made - * a decision, and silently replacing it would change a contract clients already hold. - */ -public final class WebOpenApiCustomizer { - - private final WebOpenApiProfile profile; - - /** - * A customizer over a profile. - * - * @param profile the platform's document identity and components - */ - public WebOpenApiCustomizer(WebOpenApiProfile profile) { - this.profile = Objects.requireNonNull(profile, "profile"); - } - - /** A customizer over the platform defaults. */ - public static WebOpenApiCustomizer standard() { - return new WebOpenApiCustomizer(WebOpenApiProfile.standard()); - } - - /** - * Adds the platform components to a document. - * - * @param api the document springdoc built - * @return the same document, for chaining - */ - public OpenAPI customise(OpenAPI api) { - Objects.requireNonNull(api, "api"); - api.setOpenapi(WebOpenApiProfile.OPENAPI_VERSION); - Components existing = api.getComponents(); - if (existing == null) { - api.setComponents(profile.components()); - return api; - } - Components platform = profile.components(); - if (platform.getSchemas() != null) { - platform - .getSchemas() - .forEach( - (name, schema) -> { - if (existing.getSchemas() == null || !existing.getSchemas().containsKey(name)) { - existing.addSchemas(name, schema); - } - }); - } - if (platform.getSecuritySchemes() != null) { - platform - .getSecuritySchemes() - .forEach( - (name, scheme) -> { - if (existing.getSecuritySchemes() == null - || !existing.getSecuritySchemes().containsKey(name)) { - existing.addSecuritySchemes(name, scheme); - } - }); - } - return api; - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/openapi/WebOpenApiProfile.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/openapi/WebOpenApiProfile.java deleted file mode 100644 index 71a65f7a..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/openapi/WebOpenApiProfile.java +++ /dev/null @@ -1,72 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.openapi; - -import io.swagger.v3.oas.models.Components; -import io.swagger.v3.oas.models.OpenAPI; -import io.swagger.v3.oas.models.info.Info; -import io.swagger.v3.oas.models.security.SecurityScheme; -import java.util.Objects; - -/** - * Builds the platform's share of the published OpenAPI document. - * - *

The document is the approved contract artifact, so the parts of it that are platform-wide — - * the problem body, the cursor page, the bearer scheme — are generated from the same values the - * runtime uses rather than written into a YAML file next to them. Two hand-maintained copies of a - * contract disagree, and the copy a client reads is the one that is wrong. - * - *

3.1.2 rather than 3.0: the wire manifest represents a 64-bit integer as a string and a - * nullable field as a union, and 3.0 cannot express either without vendor extensions that no - * generator agrees on. - */ -public final class WebOpenApiProfile { - - /** The OpenAPI version this platform publishes. */ - public static final String OPENAPI_VERSION = "3.1.2"; - - private final String title; - private final String version; - - private WebOpenApiProfile(String title, String version) { - this.title = Objects.requireNonNull(title, "title"); - this.version = Objects.requireNonNull(version, "version"); - } - - /** The platform defaults. */ - public static WebOpenApiProfile standard() { - return new WebOpenApiProfile("Inbound HTTP API", "1.0.0"); - } - - /** - * A profile with an explicit identity. - * - * @param title the document title - * @param version the document version - */ - public static WebOpenApiProfile of(String title, String version) { - return new WebOpenApiProfile(title, version); - } - - /** The document, carrying the platform-wide components. */ - public OpenAPI generate() { - OpenAPI api = new OpenAPI(); - api.setOpenapi(OPENAPI_VERSION); - api.setInfo(new Info().title(title).version(version)); - api.setComponents(components()); - return api; - } - - /** The platform-wide components, for contributing into a document springdoc built. */ - public Components components() { - return new Components() - .addSchemas(ProblemSchemaContributor.SCHEMA_NAME, ProblemSchemaContributor.schema()) - .addSchemas( - ProblemSchemaContributor.ISSUE_SCHEMA_NAME, ProblemSchemaContributor.issueSchema()) - .addSchemas(CursorSchemaContributor.SCHEMA_NAME, CursorSchemaContributor.schema()) - .addSecuritySchemes( - "bearerAuth", - new SecurityScheme() - .type(SecurityScheme.Type.HTTP) - .scheme("bearer") - .bearerFormat("JWT")); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/openapi/WebOpenApiReleaseGate.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/openapi/WebOpenApiReleaseGate.java deleted file mode 100644 index aaf4da55..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/openapi/WebOpenApiReleaseGate.java +++ /dev/null @@ -1,100 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.openapi; - -import dev.caskeleton.adapter.inbound.web.error.ProblemCatalog; -import io.swagger.v3.oas.models.OpenAPI; -import java.util.List; -import java.util.Objects; - -/** - * The release decision: may this document ship against the approved one? - * - *

A breaking change is not forbidden — it is forbidden outside a major version release. That - * distinction is what keeps the gate usable: a gate that refuses every breaking change gets - * bypassed the first time a real one is needed, and a bypassed gate protects nothing. - * - *

The problem-code check is here rather than in the diff because it compares the document to the - * runtime, not to the previous document. A code the runtime can return and the document - * does not publish becomes a deserialisation failure in every generated client the first time it - * happens, and no amount of comparing documents to each other would notice. - */ -public final class WebOpenApiReleaseGate { - - private final WebOpenApiBreakingPolicy breakingPolicy; - - /** A gate over the platform's breaking policy. */ - public WebOpenApiReleaseGate() { - this(new WebOpenApiBreakingPolicy()); - } - - /** - * A gate over an explicit policy. - * - * @param breakingPolicy decides which changes break a client - */ - public WebOpenApiReleaseGate(WebOpenApiBreakingPolicy breakingPolicy) { - this.breakingPolicy = Objects.requireNonNull(breakingPolicy, "breakingPolicy"); - } - - /** - * Evaluates the current document against the released one. - * - * @param released the approved snapshot - * @param current the document this build produces - * @param majorVersionRelease whether this build is a major version release - * @throws OpenApiReleaseBlockedException when a breaking change ships outside a major release - */ - public WebOpenApiDiffResult evaluate( - OpenAPI released, OpenAPI current, boolean majorVersionRelease) { - WebOpenApiDiffResult diff = breakingPolicy.diff(released, current); - if (diff.hasBreaking() && !majorVersionRelease) { - throw new OpenApiReleaseBlockedException( - "breaking API changes outside a major version release: " + diff.breaking()); - } - return diff; - } - - /** - * Refuses a document whose problem codes are not the runtime's. - * - * @param document the document about to be published - * @param catalog the runtime problem catalog - * @throws OpenApiReleaseBlockedException when the two disagree in either direction - */ - public void requireProblemInventoryMatches(OpenAPI document, ProblemCatalog catalog) { - Objects.requireNonNull(document, "document"); - Objects.requireNonNull(catalog, "catalog"); - List runtime = ProblemSchemaContributor.publishedCodes(catalog); - var schema = - document.getComponents() == null || document.getComponents().getSchemas() == null - ? null - : document.getComponents().getSchemas().get(ProblemSchemaContributor.SCHEMA_NAME); - if (schema == null || schema.getProperties() == null) { - throw new OpenApiReleaseBlockedException( - "the document publishes no Problem schema, so a client has no error contract"); - } - var codeSchema = (io.swagger.v3.oas.models.media.Schema) schema.getProperties().get("code"); - if (codeSchema == null || codeSchema.getEnum() == null) { - throw new OpenApiReleaseBlockedException("the Problem schema publishes no code enum"); - } - List published = codeSchema.getEnum().stream().map(String::valueOf).sorted().toList(); - if (!published.equals(runtime)) { - throw new OpenApiReleaseBlockedException( - "the published problem codes are not the runtime's; a code the runtime returns and the" - + " document omits is a deserialisation failure in every generated client. published=" - + published - + " runtime=" - + runtime); - } - } - - /** The release was refused. */ - public static final class OpenApiReleaseBlockedException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - /** Creates the failure. */ - public OpenApiReleaseBlockedException(String message) { - super(message); - } - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operationasync/OperationAccessPolicy.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operationasync/OperationAccessPolicy.java deleted file mode 100644 index 1bc8022b..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operationasync/OperationAccessPolicy.java +++ /dev/null @@ -1,42 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.operationasync; - -import dev.caskeleton.adapter.inbound.web.core.WebRequestContext; -import dev.caskeleton.application.operation.DurableOperation; -import java.util.Objects; - -/** - * Who may see an operation. - * - *

Object-level, not route-level. Being allowed to call {@code GET /operations/{id}} says nothing - * about being allowed to see *this* operation, and a route-level check alone turns a guessable id - * into a way to read somebody else's work — including, for a failed one, its problem detail. - * - *

Absent and forbidden are answered identically on purpose. Telling an unauthorised caller that - * an operation exists is itself the disclosure: it turns id enumeration into a working oracle for - * what other tenants are running. - */ -public final class OperationAccessPolicy { - - private OperationAccessPolicy() {} - - /** - * Whether this request may see this operation. - * - * @param operation the stored operation - * @param context the request asking - */ - public static boolean mayAccess(DurableOperation operation, WebRequestContext context) { - Objects.requireNonNull(operation, "operation"); - Objects.requireNonNull(context, "context"); - if (!context.actor().authenticated()) { - return false; - } - if (!operation.principal().equals(context.actor().subject())) { - return false; - } - String tenant = operation.tenantId(); - return tenant == null - ? context.tenant().value().isEmpty() - : context.tenant().value().filter(tenant::equals).isPresent(); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operationasync/OperationId.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operationasync/OperationId.java deleted file mode 100644 index ee641d0b..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operationasync/OperationId.java +++ /dev/null @@ -1,29 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.operationasync; - -import java.util.Objects; -import java.util.regex.Pattern; - -/** - * The identity of one durable operation, as it appears in a URL. - * - * @param value the identifier - */ -public record OperationId(String value) { - - // URL-safe and bounded. The identifier is handed back in a Location header and polled by clients - // for as long as the operation lives, so anything that needs escaping is a defect that only - // shows up in whichever client escapes it differently. - private static final Pattern GRAMMAR = Pattern.compile("[A-Za-z0-9._~-]{1,128}"); - - public OperationId { - Objects.requireNonNull(value, "value"); - if (!GRAMMAR.matcher(value).matches()) { - throw new IllegalArgumentException("an operation id must match [A-Za-z0-9._~-]{1,128}"); - } - } - - @Override - public String toString() { - return value; - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operationasync/OperationProgress.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operationasync/OperationProgress.java deleted file mode 100644 index 1c2a0d2d..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operationasync/OperationProgress.java +++ /dev/null @@ -1,50 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.operationasync; - -import java.util.Objects; -import java.util.Optional; - -/** - * How far a running operation has got. - * - *

Both counts are optional because most operations honestly cannot say. A platform that demands - * a percentage gets one invented, and an invented percentage is worse than no percentage: clients - * build progress bars on it and users read a lie. - * - * @param completedUnits work finished so far - * @param totalUnits work expected in total, when it is known ahead of time - * @param phase a short label for the current stage, when the operation has stages - */ -public record OperationProgress( - long completedUnits, Optional totalUnits, Optional phase) { - - public OperationProgress { - Objects.requireNonNull(totalUnits, "totalUnits"); - Objects.requireNonNull(phase, "phase"); - if (completedUnits < 0) { - throw new IllegalArgumentException("completed units cannot be negative"); - } - if (totalUnits.isPresent() && totalUnits.get() < completedUnits) { - throw new IllegalArgumentException( - "an operation cannot have completed more units than it has: " - + completedUnits - + " of " - + totalUnits.get()); - } - phase.ifPresent( - value -> { - if (value.isBlank()) { - throw new IllegalArgumentException("a phase label that is blank is not a label"); - } - }); - } - - /** Progress with no total and no phase. */ - public static OperationProgress of(long completedUnits) { - return new OperationProgress(completedUnits, Optional.empty(), Optional.empty()); - } - - /** The completed fraction, when a total is known. */ - public Optional fraction() { - return totalUnits.map(total -> total == 0 ? 1.0 : (double) completedUnits / total); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operationasync/OperationQueryService.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operationasync/OperationQueryService.java deleted file mode 100644 index 1f957db5..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operationasync/OperationQueryService.java +++ /dev/null @@ -1,82 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.operationasync; - -import dev.caskeleton.adapter.inbound.web.core.WebRequestContext; -import dev.caskeleton.application.operation.DurableOperation; -import dev.caskeleton.application.operation.DurableOperationId; -import dev.caskeleton.application.operation.DurableOperationStorePort; -import dev.caskeleton.application.transaction.TransactionPort; -import java.time.Clock; -import java.util.Objects; -import java.util.Optional; - -/** - * Reads and cancels operations on behalf of an authenticated request. - * - *

The authorization check lives here rather than in each controller so the servlet and reactive - * routes cannot disagree about it. Two copies of an access rule is one copy that eventually gets a - * fix the other does not. - */ -public final class OperationQueryService { - - private final DurableOperationStorePort store; - private final TransactionPort transactions; - private final OperationResourceFactory resources; - private final Clock clock; - - /** - * A service over the operation store. - * - * @param store where operations live - * @param transactions owns the write boundary for cancellation - * @param resources projects a stored operation into its polled document - * @param clock the clock expiry is judged against - */ - public OperationQueryService( - DurableOperationStorePort store, - TransactionPort transactions, - OperationResourceFactory resources, - Clock clock) { - this.store = Objects.requireNonNull(store, "store"); - this.transactions = Objects.requireNonNull(transactions, "transactions"); - this.resources = Objects.requireNonNull(resources, "resources"); - this.clock = Objects.requireNonNull(clock, "clock"); - } - - /** - * The operation this request may see, or empty. - * - * @param operationId the identity being polled - * @param context the request asking - */ - public Optional find(OperationId operationId, WebRequestContext context) { - Objects.requireNonNull(operationId, "operationId"); - Objects.requireNonNull(context, "context"); - return store - .find( - new DurableOperationId(operationId.value()), context.actor().subject(), clock.instant()) - .filter(operation -> OperationAccessPolicy.mayAccess(operation, context)) - .map(operation -> resources.resourceFor(operation, context.traceId().value())); - } - - /** - * Cancels an operation this request may see. - * - * @return empty when the caller may not see it, otherwise whether this call cancelled it - */ - public Optional cancel(OperationId operationId, WebRequestContext context) { - Objects.requireNonNull(operationId, "operationId"); - Objects.requireNonNull(context, "context"); - DurableOperationId id = new DurableOperationId(operationId.value()); - Optional operation = - store - .find(id, context.actor().subject(), clock.instant()) - .filter(candidate -> OperationAccessPolicy.mayAccess(candidate, context)); - if (operation.isEmpty()) { - return Optional.empty(); - } - // The store decides, not this check: between the read above and the cancel below the operation - // can finish, and only the store's own state predicate can refuse that race atomically. - return Optional.of( - transactions.inWrite(() -> store.cancel(id, context.actor().subject(), clock.instant()))); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operationasync/OperationResource.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operationasync/OperationResource.java deleted file mode 100644 index 37a69e38..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operationasync/OperationResource.java +++ /dev/null @@ -1,159 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.operationasync; - -import dev.caskeleton.adapter.inbound.web.error.WebProblem; -import java.net.URI; -import java.time.Duration; -import java.time.Instant; -import java.util.Objects; -import java.util.Optional; - -/** - * The published state of one durable operation. - * - *

Durable is the whole point. A {@code CompletableFuture} or an {@code @Async} handle is a - * process-local object: it disappears when the node that made it restarts, and the client polling - * for it gets a 404 for work that is still running somewhere. This record is what a client polls, - * and everything in it survives the process. - * - *

The constructor refuses the incoherent combinations rather than trusting callers, because each - * one is a specific broken client experience: a SUCCEEDED operation with nowhere to read the result - * is a success a caller cannot use, and a FAILED one with no problem document is an error with no - * explanation. - * - * @param operationId the identity clients poll - * @param status where in the lifecycle it is - * @param createdAt when it was accepted - * @param startedAt when a worker picked it up - * @param completedAt when it reached a terminal state - * @param progress how far it has got, when that is knowable - * @param resultLocation where a successful result is read from - * @param problem why it failed, sanitised for publication - * @param retryAfter how long a poller should wait before asking again - * @param expiresAt when this record stops being available - */ -public record OperationResource( - OperationId operationId, - OperationStatus status, - Instant createdAt, - Optional startedAt, - Optional completedAt, - Optional progress, - Optional resultLocation, - Optional problem, - Optional retryAfter, - Instant expiresAt) { - - public OperationResource { - Objects.requireNonNull(operationId, "operationId"); - Objects.requireNonNull(status, "status"); - Objects.requireNonNull(createdAt, "createdAt"); - Objects.requireNonNull(startedAt, "startedAt"); - Objects.requireNonNull(completedAt, "completedAt"); - Objects.requireNonNull(progress, "progress"); - Objects.requireNonNull(resultLocation, "resultLocation"); - Objects.requireNonNull(problem, "problem"); - Objects.requireNonNull(retryAfter, "retryAfter"); - Objects.requireNonNull(expiresAt, "expiresAt"); - - if (status == OperationStatus.SUCCEEDED && resultLocation.isEmpty()) { - throw new IllegalArgumentException( - "a SUCCEEDED operation must say where its result is; a success the caller cannot read is" - + " indistinguishable from a lost one"); - } - if (status == OperationStatus.FAILED && problem.isEmpty()) { - throw new IllegalArgumentException( - "a FAILED operation must carry a problem document; an unexplained failure gives the" - + " caller nothing to branch on and nothing to report"); - } - if (status != OperationStatus.FAILED && problem.isPresent()) { - throw new IllegalArgumentException( - "only a FAILED operation carries a problem document, was " + status); - } - if (status.terminal() && completedAt.isEmpty()) { - throw new IllegalArgumentException("a " + status + " operation must say when it finished"); - } - if (!status.terminal() && completedAt.isPresent()) { - throw new IllegalArgumentException( - "a " + status + " operation has not finished, so it has no completion time"); - } - if (status == OperationStatus.PENDING && startedAt.isPresent()) { - throw new IllegalArgumentException("a PENDING operation has not started"); - } - if (status == OperationStatus.RUNNING && startedAt.isEmpty()) { - throw new IllegalArgumentException("a RUNNING operation must say when it started"); - } - if (!expiresAt.isAfter(createdAt)) { - throw new IllegalArgumentException("an operation that expires when it is created is not one"); - } - startedAt.ifPresent( - started -> { - if (started.isBefore(createdAt)) { - throw new IllegalArgumentException("an operation cannot start before it was accepted"); - } - }); - completedAt.ifPresent( - completed -> { - if (completed.isBefore(createdAt)) { - throw new IllegalArgumentException("an operation cannot finish before it was accepted"); - } - }); - } - - /** A freshly accepted operation. */ - public static OperationResource pending( - OperationId operationId, Instant createdAt, Instant expiresAt, Duration retryAfter) { - return new OperationResource( - operationId, - OperationStatus.PENDING, - createdAt, - Optional.empty(), - Optional.empty(), - Optional.empty(), - Optional.empty(), - Optional.empty(), - Optional.ofNullable(retryAfter), - expiresAt); - } - - /** An operation a worker has picked up. */ - public OperationResource running(Instant startedAt, OperationProgress progress) { - return new OperationResource( - operationId, - OperationStatus.RUNNING, - createdAt, - Optional.of(startedAt), - Optional.empty(), - Optional.ofNullable(progress), - Optional.empty(), - Optional.empty(), - retryAfter, - expiresAt); - } - - /** - * A finished operation and where to read its result. - * - * @param operationId the identity - * @param completedAt when it finished - * @param resultLocation where the result is read from - */ - public static OperationResource succeeded( - OperationId operationId, Instant completedAt, Optional resultLocation) { - return new OperationResource( - operationId, - OperationStatus.SUCCEEDED, - completedAt, - Optional.of(completedAt), - Optional.of(completedAt), - Optional.empty(), - resultLocation, - Optional.empty(), - Optional.empty(), - completedAt.plus(Duration.ofDays(1))); - } - - /** Whether a poller should stop polling. */ - public boolean finished() { - return status.terminal(); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operationasync/OperationResourceFactory.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operationasync/OperationResourceFactory.java deleted file mode 100644 index 441aaca5..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operationasync/OperationResourceFactory.java +++ /dev/null @@ -1,112 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.operationasync; - -import dev.caskeleton.adapter.inbound.web.error.ProblemCode; -import dev.caskeleton.adapter.inbound.web.error.WebProblemFactory; -import dev.caskeleton.application.operation.DurableOperation; -import dev.caskeleton.application.operation.DurableOperationState; -import dev.caskeleton.application.operation.OperationFailure; -import java.net.URI; -import java.time.Duration; -import java.util.List; -import java.util.Locale; -import java.util.Objects; -import java.util.Optional; - -/** - * Projects a stored operation into the document a client polls. - * - *

A projection rather than a shared type, because the registry does not let the JPA adapter see - * a web type and does not let this leaf see a persistence one. The application owns {@link - * DurableOperation}; this leaf owns what an operation looks like over HTTP, including the problem - * document, which is an HTTP concept and has no business being persisted. - * - *

That split is also what keeps the stored failure publishable. {@link OperationFailure} carries - * a code and an already-safe message; turning it into a {@code WebProblem} here runs it through the - * same catalog and the same sanitiser as every synchronous error, so an async failure cannot - * publish something a synchronous one would have redacted. - */ -public final class OperationResourceFactory { - - private final WebProblemFactory problems; - private final URI resultBase; - private final Duration pollInterval; - - /** - * A factory for one API. - * - * @param problems the problem document factory - * @param resultBase the prefix a successful result is read from - * @param pollInterval what an unfinished operation advertises as {@code Retry-After} - */ - public OperationResourceFactory( - WebProblemFactory problems, URI resultBase, Duration pollInterval) { - this.problems = Objects.requireNonNull(problems, "problems"); - this.resultBase = Objects.requireNonNull(resultBase, "resultBase"); - this.pollInterval = Objects.requireNonNull(pollInterval, "pollInterval"); - if (pollInterval.isZero() || pollInterval.isNegative()) { - throw new IllegalArgumentException( - "a poll interval of zero invites a client to spin as fast as it can"); - } - } - - /** - * The polled document for one stored operation. - * - * @param operation the stored operation - * @param traceId the correlation identifier of the poll - */ - public OperationResource resourceFor(DurableOperation operation, String traceId) { - Objects.requireNonNull(operation, "operation"); - Objects.requireNonNull(traceId, "traceId"); - OperationId operationId = new OperationId(operation.operationId().value()); - return new OperationResource( - operationId, - statusOf(operation.state()), - operation.submittedAt(), - operation.startedAt(), - operation.completedAt(), - operation.progress().map(OperationResourceFactory::progressOf), - operation.resultReference().map(reference -> resultBase.resolve(reference)), - operation.failure().map(failure -> problemOf(failure, operationId, traceId)), - operation.finished() ? Optional.empty() : Optional.of(pollInterval), - operation.expiresAt()); - } - - private static OperationStatus statusOf(DurableOperationState state) { - return switch (state) { - case PENDING -> OperationStatus.PENDING; - case RUNNING -> OperationStatus.RUNNING; - case SUCCEEDED -> OperationStatus.SUCCEEDED; - case FAILED -> OperationStatus.FAILED; - case CANCELED -> OperationStatus.CANCELED; - case EXPIRED -> OperationStatus.EXPIRED; - }; - } - - private static OperationProgress progressOf( - dev.caskeleton.application.operation.OperationProgressSnapshot snapshot) { - return new OperationProgress( - snapshot.completedUnits(), snapshot.totalUnits(), snapshot.phase()); - } - - private dev.caskeleton.adapter.inbound.web.error.WebProblem problemOf( - OperationFailure failure, OperationId operationId, String traceId) { - return problems.create( - codeOf(failure), - failure.detail(), - URI.create("/operations/" + operationId.value()), - traceId, - List.of()); - } - - private static ProblemCode codeOf(OperationFailure failure) { - // An unrecognised code becomes INTERNAL_ERROR rather than being echoed. The catalog is the - // published vocabulary; a worker that invents a code must not be able to extend it by writing - // a row, and a client branching on codes must never see one that is not in the contract. - try { - return ProblemCode.valueOf(failure.code().toUpperCase(Locale.ROOT)); - } catch (IllegalArgumentException unknown) { - return ProblemCode.INTERNAL_ERROR; - } - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operationasync/OperationResponse.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operationasync/OperationResponse.java deleted file mode 100644 index c3c340fe..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operationasync/OperationResponse.java +++ /dev/null @@ -1,56 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.operationasync; - -import dev.caskeleton.adapter.inbound.web.error.WebProblem; -import java.time.Instant; -import java.util.Objects; - -/** - * The wire form of a polled operation. - * - *

Separate from {@link OperationResource} because a record built to enforce invariants and a - * record built to be serialized want different things. The resource keeps {@code Optional} fields, - * which is right for a type whose constructor refuses incoherent combinations and wrong for a JSON - * document, where an absent field should simply be absent. - * - *

Nulls here therefore mean "not applicable yet", and the mapper is the only thing that produces - * them — after the resource has already refused the combinations that would make a null wrong. - * - * @param operationId the identity - * @param status where in the lifecycle it is - * @param createdAt when it was accepted - * @param startedAt when a worker picked it up, or null - * @param completedAt when it finished, or null - * @param progress how far it has got, or null - * @param resultLocation where the result is read, or null - * @param problem why it failed, or null - * @param retryAfterSeconds how long to wait before polling again, or null when finished - * @param expiresAt when the record stops being available - */ -public record OperationResponse( - String operationId, - String status, - Instant createdAt, - Instant startedAt, - Instant completedAt, - ProgressResponse progress, - String resultLocation, - WebProblem problem, - Long retryAfterSeconds, - Instant expiresAt) { - - public OperationResponse { - Objects.requireNonNull(operationId, "operationId"); - Objects.requireNonNull(status, "status"); - Objects.requireNonNull(createdAt, "createdAt"); - Objects.requireNonNull(expiresAt, "expiresAt"); - } - - /** - * The wire form of progress. - * - * @param completedUnits work finished - * @param totalUnits work expected, or null when unknown - * @param phase the current stage, or null - */ - public record ProgressResponse(long completedUnits, Long totalUnits, String phase) {} -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operationasync/OperationResponseMapper.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operationasync/OperationResponseMapper.java deleted file mode 100644 index 00453ac2..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operationasync/OperationResponseMapper.java +++ /dev/null @@ -1,43 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.operationasync; - -import java.util.Objects; - -/** - * Turns a resource into its wire form. - * - *

A separate step rather than serialization annotations on the resource, so the type that - * enforces the lifecycle invariants stays free of any opinion about JSON. It also means the wire - * shape can change for a new API major version without touching the invariants. - */ -public final class OperationResponseMapper { - - private OperationResponseMapper() {} - - /** - * The wire form of a resource. - * - * @param resource the polled operation - */ - public static OperationResponse from(OperationResource resource) { - Objects.requireNonNull(resource, "resource"); - return new OperationResponse( - resource.operationId().value(), - resource.status().name(), - resource.createdAt(), - resource.startedAt().orElse(null), - resource.completedAt().orElse(null), - resource - .progress() - .map( - progress -> - new OperationResponse.ProgressResponse( - progress.completedUnits(), - progress.totalUnits().orElse(null), - progress.phase().orElse(null))) - .orElse(null), - resource.resultLocation().map(Object::toString).orElse(null), - resource.problem().orElse(null), - resource.retryAfter().map(java.time.Duration::toSeconds).orElse(null), - resource.expiresAt()); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operationasync/OperationStatus.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operationasync/OperationStatus.java deleted file mode 100644 index fd905407..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operationasync/OperationStatus.java +++ /dev/null @@ -1,40 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.operationasync; - -/** - * The lifecycle of a durable operation. - * - *

Six states rather than "done / not done", because a client polling an operation has to decide - * something different for each of them: keep waiting, read the result, show an error, stop because - * somebody cancelled, or start over because the record aged out. Collapsing any two of them moves - * that decision into guesswork. - */ -public enum OperationStatus { - - /** Accepted and durable, not yet picked up by a worker. */ - PENDING, - - /** A worker holds the lease and is executing. */ - RUNNING, - - /** Finished; the result is retrievable. */ - SUCCEEDED, - - /** Finished; it will not be retried and the reason is published as a problem document. */ - FAILED, - - /** Stopped on request before it finished. */ - CANCELED, - - /** - * The record aged out before the client read it. - * - *

Distinct from FAILED on purpose: the operation may well have succeeded, and the honest thing - * to tell a client is that the answer is no longer available — not that the work failed. - */ - EXPIRED; - - /** Whether no further state change is possible. */ - public boolean terminal() { - return this == SUCCEEDED || this == FAILED || this == CANCELED || this == EXPIRED; - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/pagination/FilterFieldCatalog.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/pagination/FilterFieldCatalog.java deleted file mode 100644 index 8563a0c0..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/pagination/FilterFieldCatalog.java +++ /dev/null @@ -1,79 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.pagination; - -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Set; - -/** - * Which fields may be filtered, and with which operators. - * - *

Per field rather than globally. A field can be safe to compare for equality and disastrous to - * range-scan: {@code status eq OPEN} uses an index, {@code createdAt gte …} without one reads the - * table, and a single global operator list cannot express the difference. Pairing them here means - * the registration that publishes a field also states what may be done to it. - */ -public final class FilterFieldCatalog { - - private final Map fields; - - private FilterFieldCatalog(Map fields) { - this.fields = Map.copyOf(fields); - } - - /** A catalog over the registered fields. */ - public static FilterFieldCatalog of(FilterableField... fields) { - Objects.requireNonNull(fields, "fields"); - Map byName = new LinkedHashMap<>(); - for (FilterableField field : fields) { - if (byName.putIfAbsent(field.externalName(), field) != null) { - throw new IllegalArgumentException("duplicate filter field: " + field.externalName()); - } - } - return new FilterFieldCatalog(byName); - } - - /** - * The field and operator a client named. - * - * @throws UnsupportedQueryVocabularyException when the field is unpublished or the operator is - * not one that field allows - */ - public FilterableField resolve(String externalName, String operator) { - FilterableField field = externalName == null ? null : fields.get(externalName); - if (field == null) { - throw new UnsupportedQueryVocabularyException("filter field"); - } - if (!field.allowedOperators().contains(operator)) { - throw new UnsupportedQueryVocabularyException("filter operator for this field"); - } - return field; - } - - /** Every published field name. */ - public Set publishedNames() { - return fields.keySet(); - } - - /** - * One filterable field. - * - * @param externalName the name a client sends - * @param internalName the query descriptor the storage layer resolves - * @param allowedOperators the operators this field supports, which is an index decision - */ - public record FilterableField( - String externalName, String internalName, Set allowedOperators) { - - public FilterableField { - Objects.requireNonNull(externalName, "externalName"); - Objects.requireNonNull(internalName, "internalName"); - Objects.requireNonNull(allowedOperators, "allowedOperators"); - if (allowedOperators.isEmpty()) { - throw new IllegalArgumentException( - "a filterable field with no operator cannot be filtered: " + externalName); - } - allowedOperators = Set.copyOf(allowedOperators); - } - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/pagination/FilterFingerprint.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/pagination/FilterFingerprint.java deleted file mode 100644 index 1c81d239..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/pagination/FilterFingerprint.java +++ /dev/null @@ -1,70 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.pagination; - -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.Base64; -import java.util.Map; -import java.util.Objects; -import java.util.TreeMap; - -/** - * A stable digest of the filter and sort a page was produced under. - * - *

What a cursor is bound to. Without it a cursor minted under {@code status=OPEN} can be - * replayed against {@code status=CLOSED} and page through rows the second query was supposed to - * exclude — which, when the filter is a tenant or an owner, is a data leak rather than a paging - * bug. - * - *

Canonical before hashing: keys sorted, separators that cannot occur in a value. Two requests - * that mean the same filter must produce the same fingerprint whatever order the query string - * happened to be in, and two that mean different filters must not collide because a value contained - * the separator. - */ -public final class FilterFingerprint { - - private static final char PAIR_SEPARATOR = '\u001f'; - private static final char KEY_VALUE_SEPARATOR = '\u001e'; - - private FilterFingerprint() {} - - /** - * The fingerprint of one collection query. - * - * @param queryProfile the operation the page belongs to - * @param sort the sort expression, already resolved against the catalog - * @param filters the filter values, already resolved against the catalog - * @param vocabularyFingerprint the catalog's own fingerprint, so a vocabulary change invalidates - */ - public static String of( - String queryProfile, String sort, Map filters, String vocabularyFingerprint) { - Objects.requireNonNull(queryProfile, "queryProfile"); - Objects.requireNonNull(sort, "sort"); - Objects.requireNonNull(filters, "filters"); - Objects.requireNonNull(vocabularyFingerprint, "vocabularyFingerprint"); - StringBuilder canonical = new StringBuilder(); - canonical.append(queryProfile).append(PAIR_SEPARATOR).append(sort); - // A TreeMap so ?a=1&b=2 and ?b=2&a=1 are the same filter, which they are. - new TreeMap<>(filters) - .forEach( - (key, value) -> - canonical - .append(PAIR_SEPARATOR) - .append(key) - .append(KEY_VALUE_SEPARATOR) - .append(value)); - canonical.append(PAIR_SEPARATOR).append(vocabularyFingerprint); - return digest(canonical.toString()); - } - - private static String digest(String canonical) { - try { - MessageDigest sha256 = MessageDigest.getInstance("SHA-256"); - return Base64.getUrlEncoder() - .withoutPadding() - .encodeToString(sha256.digest(canonical.getBytes(StandardCharsets.UTF_8))); - } catch (NoSuchAlgorithmException impossible) { - throw new IllegalStateException("SHA-256 is required by every JVM", impossible); - } - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/pagination/FilterOperatorCatalog.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/pagination/FilterOperatorCatalog.java deleted file mode 100644 index 6db733f4..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/pagination/FilterOperatorCatalog.java +++ /dev/null @@ -1,87 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.pagination; - -import java.util.LinkedHashSet; -import java.util.Objects; -import java.util.Set; - -/** - * The comparison operators this API publishes. - * - *

An operator is not a value, it is a piece of the query's structure, so an unregistered one is - * a caller writing query logic. The set is also deliberately small: every operator here has an - * index strategy behind it, and adding {@code contains} or {@code regex} without one turns a filter - * into a table scan a caller can trigger at will. - */ -public final class FilterOperatorCatalog { - - /** Equality. */ - public static final String EQUALS = "eq"; - - /** Inequality. */ - public static final String NOT_EQUALS = "ne"; - - /** Strictly greater. */ - public static final String GREATER_THAN = "gt"; - - /** Greater or equal. */ - public static final String GREATER_OR_EQUAL = "gte"; - - /** Strictly less. */ - public static final String LESS_THAN = "lt"; - - /** Less or equal. */ - public static final String LESS_OR_EQUAL = "lte"; - - /** Membership in a bounded set. */ - public static final String IN = "in"; - - /** Prefix match, which an index can serve. */ - public static final String STARTS_WITH = "startsWith"; - - private final Set operators; - - private FilterOperatorCatalog(Set operators) { - this.operators = Set.copyOf(operators); - } - - /** The operators the platform publishes by default. */ - public static FilterOperatorCatalog standard() { - return new FilterOperatorCatalog( - new LinkedHashSet<>( - java.util.List.of( - EQUALS, - NOT_EQUALS, - GREATER_THAN, - GREATER_OR_EQUAL, - LESS_THAN, - LESS_OR_EQUAL, - IN, - STARTS_WITH))); - } - - /** A narrower catalog. */ - public static FilterOperatorCatalog of(Set operators) { - Objects.requireNonNull(operators, "operators"); - if (operators.isEmpty()) { - throw new IllegalArgumentException("a filter catalog with no operator filters nothing"); - } - return new FilterOperatorCatalog(operators); - } - - /** - * The operator a client named. - * - * @throws UnsupportedQueryVocabularyException when it is not published - */ - public String resolve(String operator) { - if (operator == null || !operators.contains(operator)) { - throw new UnsupportedQueryVocabularyException("filter operator"); - } - return operator; - } - - /** Every published operator. */ - public Set published() { - return operators; - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/pagination/HmacWebCursorCodec.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/pagination/HmacWebCursorCodec.java deleted file mode 100644 index ab102fa1..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/pagination/HmacWebCursorCodec.java +++ /dev/null @@ -1,135 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.pagination; - -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.time.Instant; -import java.util.Base64; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Objects; -import javax.crypto.Mac; -import javax.crypto.spec.SecretKeySpec; - -/** - * The signed, versioned cursor codec. - * - *

Base64 is encoding, not protection, and treating it as protection is the mistake this class - * exists to prevent: a base64 cursor is a cursor a caller can decode, edit and re-encode, which - * turns "continue where you left off" into "start wherever I say". The MAC is what makes the token - * opaque in the sense that matters. - * - *

The MAC covers the version, the query profile, the filter fingerprint, the position and the - * issue time. Leaving any of them out would let a valid signature be replayed somewhere it does not - * belong — most damagingly the fingerprint, whose absence lets a cursor minted under one filter - * page through a result set the new filter was supposed to exclude. - * - *

Comparison is constant-time. A byte-by-byte MAC check leaks, through timing, how much of a - * forged signature was right, which is enough to construct one given enough attempts. - */ -public final class HmacWebCursorCodec implements WebCursorCodec { - - private static final Base64.Encoder ENCODER = Base64.getUrlEncoder().withoutPadding(); - private static final Base64.Decoder DECODER = Base64.getUrlDecoder(); - private static final char FIELD_SEPARATOR = '.'; - - /** A cursor older than this is refused; a scan that paused for a day is not resumable. */ - private static final java.time.Duration MAX_AGE = java.time.Duration.ofHours(1); - - private final WebCursorKeyRing keyRing; - private final java.time.Clock clock; - - /** - * A codec over a key ring. - * - * @param keyRing the active signing key and the retired verification keys - * @param clock the clock the issue time and expiry are read from - */ - public HmacWebCursorCodec(WebCursorKeyRing keyRing, java.time.Clock clock) { - this.keyRing = Objects.requireNonNull(keyRing, "keyRing"); - this.clock = Objects.requireNonNull(clock, "clock"); - } - - @Override - public String encode(WebCursorPayload payload) { - Objects.requireNonNull(payload, "payload"); - String body = ENCODER.encodeToString(payload.canonicalForm().getBytes(StandardCharsets.UTF_8)); - String keyId = keyRing.activeKeyId(); - String signature = sign(keyRing.activeKey(), keyId + FIELD_SEPARATOR + body); - return keyId + FIELD_SEPARATOR + body + FIELD_SEPARATOR + signature; - } - - @Override - public WebCursorPayload decode( - String cursor, String expectedProfile, String expectedFingerprint) { - Objects.requireNonNull(expectedProfile, "expectedProfile"); - Objects.requireNonNull(expectedFingerprint, "expectedFingerprint"); - if (cursor == null || cursor.isBlank() || cursor.length() > 4096) { - throw new WebCursorException(); - } - String[] parts = cursor.split("\\.", -1); - if (parts.length != 3) { - throw new WebCursorException(); - } - SecretKeySpec key = keyRing.verificationKey(parts[0]).orElseThrow(WebCursorException::new); - String expectedSignature = sign(key, parts[0] + FIELD_SEPARATOR + parts[1]); - if (!MessageDigest.isEqual( - expectedSignature.getBytes(StandardCharsets.UTF_8), - parts[2].getBytes(StandardCharsets.UTF_8))) { - throw new WebCursorException(); - } - WebCursorPayload payload = parse(parts[1]); - if (payload.version() != WebCursorPayload.CURRENT_VERSION) { - throw new WebCursorException(); - } - if (!payload.queryProfile().equals(expectedProfile) - || !payload.filterFingerprint().equals(expectedFingerprint)) { - throw new WebCursorException(); - } - if (payload.issuedAt().plus(MAX_AGE).isBefore(clock.instant())) { - throw new WebCursorException(); - } - return payload; - } - - private WebCursorPayload parse(String encodedBody) { - String canonical; - try { - canonical = new String(DECODER.decode(encodedBody), StandardCharsets.UTF_8); - } catch (IllegalArgumentException malformedEncoding) { - throw new WebCursorException(); - } - String[] fields = canonical.split("\\u001f", -1); - if (fields.length < 4) { - throw new WebCursorException(); - } - Map sortValues = new LinkedHashMap<>(); - for (int index = 3; index < fields.length - 1; index++) { - String[] pair = fields[index].split("\\u001e", -1); - if (pair.length != 2) { - throw new WebCursorException(); - } - sortValues.put(pair[0], pair[1]); - } - try { - return new WebCursorPayload( - Integer.parseInt(fields[0]), - fields[1], - fields[2], - sortValues, - Instant.ofEpochMilli(Long.parseLong(fields[fields.length - 1]))); - } catch (RuntimeException malformed) { - throw new WebCursorException(); - } - } - - private static String sign(SecretKeySpec key, String data) { - try { - Mac mac = Mac.getInstance(WebCursorKeyRing.ALGORITHM); - mac.init(key); - return ENCODER.encodeToString(mac.doFinal(data.getBytes(StandardCharsets.UTF_8))); - } catch (java.security.GeneralSecurityException unusableKey) { - // The ring validated the key at construction, so this is a broken JVM rather than input. - throw new IllegalStateException("cursor signing is unavailable", unusableKey); - } - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/pagination/InMemoryCollectionQueryCatalog.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/pagination/InMemoryCollectionQueryCatalog.java deleted file mode 100644 index 697cf50a..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/pagination/InMemoryCollectionQueryCatalog.java +++ /dev/null @@ -1,93 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.pagination; - -import java.util.Map; -import java.util.Objects; -import java.util.Set; - -/** - * The three query vocabularies an operation publishes, held together. - * - *

Together because they are checked together and because a keyset cursor is bound to all three: - * a cursor issued for one sort order, filter set and projection cannot be replayed against another, - * or it would page through a different result set than the one it describes. - * - *

The standard instance is deliberately minimal — an {@code id} sort that is a unique - * tie-breaker and nothing else. A default that published more would make the safe-by-default case - * the one where a deployment ships fields it never reviewed. - */ -public final class InMemoryCollectionQueryCatalog { - - private final SortFieldCatalog sortFields; - private final FilterFieldCatalog filterFields; - private final FilterOperatorCatalog filterOperators; - private final ProjectionProfileCatalog projections; - - /** - * A catalog over explicit vocabularies. - * - * @param sortFields the sortable fields - * @param filterFields the filterable fields and their operators - * @param filterOperators the operators this deployment publishes at all - * @param projections the named field sets - */ - public InMemoryCollectionQueryCatalog( - SortFieldCatalog sortFields, - FilterFieldCatalog filterFields, - FilterOperatorCatalog filterOperators, - ProjectionProfileCatalog projections) { - this.sortFields = Objects.requireNonNull(sortFields, "sortFields"); - this.filterFields = Objects.requireNonNull(filterFields, "filterFields"); - this.filterOperators = Objects.requireNonNull(filterOperators, "filterOperators"); - this.projections = Objects.requireNonNull(projections, "projections"); - if (!sortFields.hasUniqueTieBreaker()) { - // Without one, two rows that compare equal on every sort key have no defined order, so a - // keyset page boundary either repeats a row or skips one — silently, and only under load. - throw new IllegalArgumentException( - "a collection query catalog needs at least one unique tie-breaker sort field"); - } - } - - /** The platform's minimal catalog: sort by id, no filters, a default projection. */ - public static InMemoryCollectionQueryCatalog standard() { - return new InMemoryCollectionQueryCatalog( - SortFieldCatalog.of(new SortField("id", "id", true)), - FilterFieldCatalog.of(), - FilterOperatorCatalog.standard(), - ProjectionProfileCatalog.of(Map.of("default", Set.of("id")))); - } - - /** The sortable fields. */ - public SortFieldCatalog sortFields() { - return sortFields; - } - - /** The filterable fields. */ - public FilterFieldCatalog filterFields() { - return filterFields; - } - - /** The published operators. */ - public FilterOperatorCatalog filterOperators() { - return filterOperators; - } - - /** The named projections. */ - public ProjectionProfileCatalog projections() { - return projections; - } - - /** - * A stable fingerprint of this catalog's vocabulary. - * - *

Bound into a cursor so a cursor issued before a field was added or removed is refused rather - * than paging through a result set with a different shape. - */ - public String vocabularyFingerprint() { - return String.join( - "|", - String.join(",", sortFields.publishedNames()), - String.join(",", filterFields.publishedNames()), - String.join(",", filterOperators.published()), - String.join(",", projections.publishedNames())); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/pagination/ProjectionProfileCatalog.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/pagination/ProjectionProfileCatalog.java deleted file mode 100644 index cd71b9d3..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/pagination/ProjectionProfileCatalog.java +++ /dev/null @@ -1,55 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.pagination; - -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Set; - -/** - * The named field sets a client may ask a collection to return. - * - *

Named profiles rather than an arbitrary field list. A caller-composed projection is a caller - * deciding which columns the query reads, which defeats covering indexes and — more importantly — - * makes "which fields is this actor allowed to see" a question answered per request rather than per - * profile. A profile is reviewed once and authorised once. - */ -public final class ProjectionProfileCatalog { - - private final Map> profiles; - - private ProjectionProfileCatalog(Map> profiles) { - this.profiles = Map.copyOf(profiles); - } - - /** A catalog over the registered profiles. */ - public static ProjectionProfileCatalog of(Map> profiles) { - Objects.requireNonNull(profiles, "profiles"); - Map> copy = new LinkedHashMap<>(); - profiles.forEach( - (name, fields) -> { - if (fields == null || fields.isEmpty()) { - throw new IllegalArgumentException("projection profile " + name + " selects nothing"); - } - copy.put(name, Set.copyOf(fields)); - }); - return new ProjectionProfileCatalog(copy); - } - - /** - * The fields a profile selects. - * - * @throws UnsupportedQueryVocabularyException when the profile is not published - */ - public Set resolve(String profileName) { - Set fields = profileName == null ? null : profiles.get(profileName); - if (fields == null) { - throw new UnsupportedQueryVocabularyException("projection profile"); - } - return fields; - } - - /** Every published profile name. */ - public Set publishedNames() { - return profiles.keySet(); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/pagination/SortField.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/pagination/SortField.java deleted file mode 100644 index 3e56c25c..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/pagination/SortField.java +++ /dev/null @@ -1,29 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.pagination; - -import java.util.Objects; - -/** - * A sortable field, as the API names it and as the storage layer names it. - * - *

Two names on purpose. The external one is a published contract that must survive a schema - * rename; the internal one is a query descriptor the storage layer understands. Keeping them in one - * value is what lets the pair be reviewed together — a mapping split across two files drifts, and - * the drift shows up as a 500 on a sort nobody tested. - * - *

The internal name never reaches a query as caller-supplied text: it is chosen from this - * catalog, so the only strings that can be sorted by are ones somebody registered. - * - * @param externalName the name a client sends - * @param internalName the query descriptor the storage layer resolves - * @param uniqueTieBreaker whether this field alone orders the result set deterministically - */ -public record SortField(String externalName, String internalName, boolean uniqueTieBreaker) { - - public SortField { - Objects.requireNonNull(externalName, "externalName"); - Objects.requireNonNull(internalName, "internalName"); - if (externalName.isBlank() || internalName.isBlank()) { - throw new IllegalArgumentException("a sort field needs both names"); - } - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/pagination/SortFieldCatalog.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/pagination/SortFieldCatalog.java deleted file mode 100644 index bb559644..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/pagination/SortFieldCatalog.java +++ /dev/null @@ -1,66 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.pagination; - -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Set; - -/** - * The sort fields this API publishes. - * - *

An allowlist, and the reason is the oldest one in the book: a sort name that reaches a query - * is a fragment of that query. Passing {@code ?sort=} straight through to an ORDER BY, a JPQL - * string or a Mongo field path lets a caller order by a column the API never exposed, and in the - * string-concatenation case lets them write the clause. - * - *

Registering a field is therefore how it becomes sortable, and the internal name is chosen by - * the registration rather than derived from the request. - */ -public final class SortFieldCatalog { - - private final Map fields; - - private SortFieldCatalog(Map fields) { - this.fields = Map.copyOf(fields); - } - - /** A catalog over the registered fields. */ - public static SortFieldCatalog of(SortField... fields) { - Objects.requireNonNull(fields, "fields"); - Map byName = new LinkedHashMap<>(); - for (SortField field : fields) { - if (byName.putIfAbsent(field.externalName(), field) != null) { - throw new IllegalArgumentException("duplicate sort field: " + field.externalName()); - } - } - return new SortFieldCatalog(byName); - } - - /** - * The field a client named. - * - * @throws UnsupportedQueryVocabularyException when it is not published - */ - public SortField resolve(String externalName) { - SortField field = externalName == null ? null : fields.get(externalName); - if (field == null) { - throw new UnsupportedQueryVocabularyException("sort field"); - } - return field; - } - - /** Whether a name is published. */ - public boolean published(String externalName) { - return externalName != null && fields.containsKey(externalName); - } - - /** Every published name, for the OpenAPI document. */ - public Set publishedNames() { - return fields.keySet(); - } - - /** Whether any published field can order the result set deterministically on its own. */ - public boolean hasUniqueTieBreaker() { - return fields.values().stream().anyMatch(SortField::uniqueTieBreaker); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/pagination/UnsupportedQueryVocabularyException.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/pagination/UnsupportedQueryVocabularyException.java deleted file mode 100644 index 34d281c8..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/pagination/UnsupportedQueryVocabularyException.java +++ /dev/null @@ -1,30 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.pagination; - -/** - * A request used a sort field, filter operator or projection the API does not publish. - * - *

Its own type so the error translator answers all of them with one 400, and so the message can - * be built in one place that knows not to echo the rejected value. A message that quotes {@code - * drop_table; --} back to the caller is a reflected-content vector in an error body. - */ -public final class UnsupportedQueryVocabularyException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - private final String vocabulary; - - /** - * Creates the failure. - * - * @param vocabulary which vocabulary was violated, for the problem detail - */ - public UnsupportedQueryVocabularyException(String vocabulary) { - super("unsupported " + vocabulary + "; only registered values are accepted"); - this.vocabulary = vocabulary; - } - - /** Which vocabulary was violated. */ - public String vocabulary() { - return vocabulary; - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/pagination/WebCollectionRequest.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/pagination/WebCollectionRequest.java deleted file mode 100644 index b220a509..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/pagination/WebCollectionRequest.java +++ /dev/null @@ -1,55 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.pagination; - -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -/** - * One collection request, after every value has been checked against the catalogs. - * - *

Nothing here is caller text. The sort is a resolved {@link SortField}, the filters are keyed - * by resolved field names, and the cursor has already been verified against this exact query. That - * is the contract with the storage layer: what it receives cannot contain a fragment of a query, - * because none of it survived the parser as a string the caller chose. - * - *

{@code totalCount} is opt-in. Counting is a second query over the whole filtered set, so a - * platform that computes it by default makes every list endpoint twice as expensive to serve a - * number most clients render and ignore. - * - * @param queryProfile the operation this request belongs to - * @param sort the resolved sort field - * @param descending whether the scan runs backwards - * @param filters resolved internal field name to value - * @param pageSize how many rows this page may return - * @param cursor the verified continuation position, empty for the first page - * @param filterFingerprint the digest a continuation cursor is bound to - * @param includeTotalCount whether the caller asked for, and the profile permits, a total - */ -public record WebCollectionRequest( - String queryProfile, - SortField sort, - boolean descending, - Map filters, - int pageSize, - Optional cursor, - String filterFingerprint, - boolean includeTotalCount) { - - public WebCollectionRequest { - Objects.requireNonNull(queryProfile, "queryProfile"); - Objects.requireNonNull(sort, "sort"); - Objects.requireNonNull(filters, "filters"); - Objects.requireNonNull(cursor, "cursor"); - Objects.requireNonNull(filterFingerprint, "filterFingerprint"); - if (pageSize < 1) { - throw new IllegalArgumentException("page size must be positive"); - } - filters = Map.copyOf(new LinkedHashMap<>(filters)); - } - - /** Whether this is a continuation rather than a first page. */ - public boolean continuation() { - return cursor.isPresent(); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/pagination/WebCollectionRequestParser.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/pagination/WebCollectionRequestParser.java deleted file mode 100644 index 2d1bf71b..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/pagination/WebCollectionRequestParser.java +++ /dev/null @@ -1,135 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.pagination; - -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -/** - * Turns query parameters into a checked collection request. - * - *

The order of the checks matters and is the reason this is one class rather than a chain of - * small ones. The fingerprint is computed from the resolved sort and filters, and the cursor is - * then verified against that fingerprint — so a cursor cannot be validated before the platform - * knows which query it is being replayed into. Doing it the other way round is how a cursor from - * one filter gets accepted under another. - * - *

Every failure is a stable exception the error translator maps to a 400. None of them echo the - * rejected value. - */ -public final class WebCollectionRequestParser { - - private final InMemoryCollectionQueryCatalog catalog; - private final WebPageSizePolicy pageSizePolicy; - private final WebCursorCodec cursorCodec; - - /** - * A parser for one deployment's vocabulary. - * - * @param catalog the published sort, filter and projection vocabulary - * @param pageSizePolicy the page bounds - * @param cursorCodec the signed cursor codec - */ - public WebCollectionRequestParser( - InMemoryCollectionQueryCatalog catalog, - WebPageSizePolicy pageSizePolicy, - WebCursorCodec cursorCodec) { - this.catalog = Objects.requireNonNull(catalog, "catalog"); - this.pageSizePolicy = Objects.requireNonNull(pageSizePolicy, "pageSizePolicy"); - this.cursorCodec = Objects.requireNonNull(cursorCodec, "cursorCodec"); - } - - /** - * Parses one collection request. - * - * @param queryProfile the operation being served - * @param sortParameter the requested sort, {@code -name} for descending, null for the default - * @param rawFilters the requested filters, keyed by external field name - * @param requestedPageSize the requested page size, null for the default - * @param rawCursor the continuation cursor, null for the first page - * @param requestTotalCount whether the caller asked for a total - * @param totalCountPermitted whether the operation profile permits one - */ - public WebCollectionRequest parse( - String queryProfile, - String sortParameter, - Map rawFilters, - Integer requestedPageSize, - String rawCursor, - boolean requestTotalCount, - boolean totalCountPermitted) { - Objects.requireNonNull(queryProfile, "queryProfile"); - Map filters = rawFilters == null ? Map.of() : rawFilters; - - boolean descending = sortParameter != null && sortParameter.startsWith("-"); - String sortName = sortParameter == null ? defaultSortName() : stripDirection(sortParameter); - SortField sort = catalog.sortFields().resolve(sortName); - - Map resolvedFilters = new LinkedHashMap<>(); - filters.forEach( - (name, value) -> { - // Every filter arrives as field and operator; the operator decides what the storage layer - // is allowed to do with the field, so both are resolved before the value is kept. - String[] parts = name.split("\\.", 2); - String field = parts[0]; - String operator = parts.length == 2 ? parts[1] : FilterOperatorCatalog.EQUALS; - catalog.filterOperators().resolve(operator); - var resolved = catalog.filterFields().resolve(field, operator); - resolvedFilters.put(resolved.internalName() + "." + operator, value); - }); - - int pageSize = pageSizePolicy.resolve(requestedPageSize); - String fingerprint = - FilterFingerprint.of( - queryProfile, - (descending ? "-" : "") + sort.internalName(), - resolvedFilters, - catalog.vocabularyFingerprint()); - - Optional cursor = - rawCursor == null || rawCursor.isBlank() - ? Optional.empty() - : Optional.of(cursorCodec.decode(rawCursor, queryProfile, fingerprint)); - - if (requestTotalCount && !totalCountPermitted) { - throw new UnsupportedQueryVocabularyException("total count profile"); - } - - return new WebCollectionRequest( - queryProfile, - sort, - descending, - resolvedFilters, - pageSize, - cursor, - fingerprint, - requestTotalCount && totalCountPermitted); - } - - /** - * The cursor for the next page of a request. - * - * @param request the request the page answered - * @param lastRowSortValues the sort key values of the last row, ending with the tie-breaker - * @param issuedAt when the cursor is minted - */ - public String nextCursor( - WebCollectionRequest request, - Map lastRowSortValues, - java.time.Instant issuedAt) { - Objects.requireNonNull(request, "request"); - return cursorCodec.encode( - WebCursorPayload.current( - request.queryProfile(), request.filterFingerprint(), lastRowSortValues, issuedAt)); - } - - private String defaultSortName() { - return catalog.sortFields().publishedNames().iterator().next(); - } - - private static String stripDirection(String sortParameter) { - return sortParameter.startsWith("-") || sortParameter.startsWith("+") - ? sortParameter.substring(1) - : sortParameter; - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/pagination/WebCursorCodec.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/pagination/WebCursorCodec.java deleted file mode 100644 index 8bfea2f9..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/pagination/WebCursorCodec.java +++ /dev/null @@ -1,29 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.pagination; - -/** - * Turns a cursor position into an opaque token and back. - * - *

An interface so a deployment can substitute a different signing scheme without the collection - * parser knowing. What it may not substitute is the check: {@link #decode} takes the query profile - * and filter fingerprint it expects, so an implementation cannot quietly stop verifying that the - * cursor belongs to this query. - */ -public interface WebCursorCodec { - - /** - * Mints an opaque cursor. - * - * @param payload where the page stopped and which query it stopped in - */ - String encode(WebCursorPayload payload); - - /** - * Reads a cursor, refusing one that does not belong to this query. - * - * @param cursor the token a client sent back - * @param expectedProfile the query profile the current request belongs to - * @param expectedFingerprint the filter and vocabulary fingerprint of the current request - * @throws WebCursorException when the cursor is malformed, unsigned, or from another query - */ - WebCursorPayload decode(String cursor, String expectedProfile, String expectedFingerprint); -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/pagination/WebCursorException.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/pagination/WebCursorException.java deleted file mode 100644 index 43e9006f..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/pagination/WebCursorException.java +++ /dev/null @@ -1,19 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.pagination; - -/** - * A cursor could not be trusted. - * - *

One exception for every reason — bad encoding, unknown version, wrong profile, changed filter, - * failed MAC — and deliberately so. Telling a caller which check failed tells them how to get - * closer: "bad MAC" says the structure parsed, "unknown version" says the signature verified. The - * only useful answer is that the cursor is not valid here. - */ -public final class WebCursorException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - /** Creates the failure. */ - public WebCursorException() { - super("the cursor is not valid for this query"); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/pagination/WebCursorKeyRing.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/pagination/WebCursorKeyRing.java deleted file mode 100644 index afb1197b..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/pagination/WebCursorKeyRing.java +++ /dev/null @@ -1,77 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.pagination; - -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import javax.crypto.spec.SecretKeySpec; - -/** - * The signing keys, with one active for minting and the rest kept for verification. - * - *

A ring rather than a key because rotation is otherwise a breaking change: every cursor a - * client is holding was signed with the old key, and replacing the key outright turns all of them - * into refusals mid-scan. Keeping retired keys verifiable lets a rotation happen without the API - * appearing to break. - * - *

There is no default key. A hard-coded signing secret is a signature anybody who has read the - * source can forge, and a "development default" is the one that ships. - */ -public final class WebCursorKeyRing { - - /** HMAC-SHA256: the MAC needs to be unforgeable, not fast. */ - public static final String ALGORITHM = "HmacSHA256"; - - private final String activeKeyId; - private final Map keys; - - private WebCursorKeyRing(String activeKeyId, Map keys) { - this.activeKeyId = activeKeyId; - this.keys = Map.copyOf(keys); - } - - /** - * A ring with one active key and any number of retired ones. - * - * @param activeKeyId which key new cursors are signed with - * @param keysById every key that may verify, including the active one - */ - public static WebCursorKeyRing of(String activeKeyId, Map keysById) { - Objects.requireNonNull(activeKeyId, "activeKeyId"); - Objects.requireNonNull(keysById, "keysById"); - if (!keysById.containsKey(activeKeyId)) { - throw new IllegalArgumentException("the active key must be in the ring: " + activeKeyId); - } - Map specs = new LinkedHashMap<>(); - keysById.forEach( - (id, material) -> { - Objects.requireNonNull(material, "key material for " + id); - if (material.length < 32) { - throw new IllegalArgumentException( - "cursor signing key " + id + " is shorter than the 256-bit MAC it produces"); - } - specs.put(id, new SecretKeySpec(material.clone(), ALGORITHM)); - }); - return new WebCursorKeyRing(activeKeyId, specs); - } - - /** The key new cursors are signed with. */ - public String activeKeyId() { - return activeKeyId; - } - - /** The active signing key. */ - public SecretKeySpec activeKey() { - return keys.get(activeKeyId); - } - - /** A key by id, when the ring still holds it. */ - public Optional verificationKey(String keyId) { - return keyId == null ? Optional.empty() : Optional.ofNullable(keys.get(keyId)); - } - - /** How many keys can verify. */ - public int size() { - return keys.size(); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/pagination/WebCursorPayload.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/pagination/WebCursorPayload.java deleted file mode 100644 index 03442249..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/pagination/WebCursorPayload.java +++ /dev/null @@ -1,79 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.pagination; - -import java.time.Instant; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Objects; - -/** - * What a cursor actually says: where the last page stopped, and what query it stopped in. - * - *

The position alone is not enough, and that is the whole reason this record has five - * components. A cursor that only carried sort values could be replayed against a different sort - * order, a different filter, or a different projection — and each of those pages through a - * different result set than the cursor describes. Under a changed filter, that is a caller reading - * rows the new query was scoped away from. - * - *

So the query profile and a filter fingerprint are authenticated alongside the position, and - * decoding checks all of them. - * - * @param version the cursor format version, so a format change is a refusal rather than a misparse - * @param queryProfile which registered query this cursor belongs to - * @param filterFingerprint a digest of the filter and vocabulary the page was produced under - * @param sortValues the last row's sort key values, in sort order, ending with the tie-breaker - * @param issuedAt when the cursor was minted - */ -public record WebCursorPayload( - int version, - String queryProfile, - String filterFingerprint, - Map sortValues, - Instant issuedAt) { - - /** The only format this platform mints. */ - public static final int CURRENT_VERSION = 1; - - public WebCursorPayload { - Objects.requireNonNull(queryProfile, "queryProfile"); - Objects.requireNonNull(filterFingerprint, "filterFingerprint"); - Objects.requireNonNull(sortValues, "sortValues"); - Objects.requireNonNull(issuedAt, "issuedAt"); - if (version < 1) { - throw new IllegalArgumentException("cursor version must be positive"); - } - if (queryProfile.isBlank()) { - throw new IllegalArgumentException("a cursor belongs to a named query profile"); - } - if (sortValues.isEmpty()) { - throw new IllegalArgumentException("a cursor with no position cannot continue a scan"); - } - // LinkedHashMap: the order is the sort order, and a cursor whose keys reorder describes a - // different position. - sortValues = java.util.Collections.unmodifiableMap(new LinkedHashMap<>(sortValues)); - } - - /** A cursor in the current format. */ - public static WebCursorPayload current( - String queryProfile, - String filterFingerprint, - Map sortValues, - Instant issuedAt) { - return new WebCursorPayload( - CURRENT_VERSION, queryProfile, filterFingerprint, sortValues, issuedAt); - } - - /** The canonical bytes the MAC is computed over. */ - public String canonicalForm() { - StringBuilder canonical = new StringBuilder(); - canonical - .append(version) - .append('\u001f') - .append(queryProfile) - .append('\u001f') - .append(filterFingerprint); - sortValues.forEach( - (key, value) -> canonical.append('\u001f').append(key).append('\u001e').append(value)); - canonical.append('\u001f').append(issuedAt.toEpochMilli()); - return canonical.toString(); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/pagination/WebPageSizePolicy.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/pagination/WebPageSizePolicy.java deleted file mode 100644 index 46c0f5b9..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/pagination/WebPageSizePolicy.java +++ /dev/null @@ -1,61 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.pagination; - -/** - * How many rows one page may return. - * - *

A hard maximum rather than a default a caller can raise. {@code ?limit=1000000} is the - * cheapest denial of service an API offers: one request, one query, and the response is assembled - * in memory before a byte is written. Clamping silently would be friendlier and worse — a client - * that asked for 1000 and got 200 pages incorrectly, because it believes the short page is the last - * one. - * - * @param defaultSize the page size a request that names none gets - * @param maximumSize the largest page any request may ask for - */ -public record WebPageSizePolicy(int defaultSize, int maximumSize) { - - /** The platform's Standard profile. */ - public static final int STANDARD_DEFAULT = 50; - - /** The platform's hard ceiling. */ - public static final int STANDARD_MAXIMUM = 200; - - public WebPageSizePolicy { - if (defaultSize < 1) { - throw new IllegalArgumentException("default page size must be positive"); - } - if (maximumSize < defaultSize) { - throw new IllegalArgumentException("the maximum page size cannot be below the default"); - } - if (maximumSize > STANDARD_MAXIMUM) { - throw new IllegalArgumentException( - "page maximum exceeds the platform ceiling of " + STANDARD_MAXIMUM); - } - } - - /** The Standard profile: 50 by default, never more than 200. */ - public static WebPageSizePolicy standard() { - return new WebPageSizePolicy(STANDARD_DEFAULT, STANDARD_MAXIMUM); - } - - /** - * The size for a requested limit. - * - * @param requested what the client asked for, null when it asked for nothing - * @throws IllegalArgumentException when the request is above the maximum or not positive - */ - public int resolve(Integer requested) { - if (requested == null) { - return defaultSize; - } - if (requested < 1) { - throw new IllegalArgumentException("page size must be positive"); - } - if (requested > maximumSize) { - // Refused rather than clamped: a client that asked for 1000 and silently got 200 believes the - // short page is the last one and stops paging. - throw new IllegalArgumentException("page size exceeds the maximum of " + maximumSize); - } - return requested; - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/proxy/ForwardedHeaderSanitizer.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/proxy/ForwardedHeaderSanitizer.java deleted file mode 100644 index b9f52ddf..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/proxy/ForwardedHeaderSanitizer.java +++ /dev/null @@ -1,72 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.proxy; - -import java.net.InetAddress; -import java.util.Map; -import java.util.Objects; - -/** - * Decides whether a request's forwarded headers may be believed, and normalises them if so. - * - *

The topology this assumes is the one the design states: a trusted proxy strips whatever - * forwarded headers a client sent and sets authoritative ones itself. That assumption is what makes - * "trusted peer" sufficient — the peer is trusted to have overwritten, not merely to have appended, - * so the value cannot be a client's with a proxy's added on top. - * - *

A direct-access deployment configures {@link TrustedProxyPolicy#trustNobody()} and gets {@link - * NormalizedForwardedHeaders#none()} for every request, including ones that carry the headers. The - * server's own socket is then the only source, which is correct when nothing is in front of it. - */ -public final class ForwardedHeaderSanitizer { - - private final TrustedProxyPolicy trustedProxyPolicy; - private final boolean refuseUntrusted; - - /** - * A sanitiser that refuses forwarded headers from an untrusted peer. - * - * @param trustedProxyPolicy which peers may set them - */ - public ForwardedHeaderSanitizer(TrustedProxyPolicy trustedProxyPolicy) { - this(trustedProxyPolicy, true); - } - - /** - * A sanitiser with an explicit decision about untrusted peers. - * - * @param trustedProxyPolicy which peers may set them - * @param refuseUntrusted true to fail the request, false to ignore the headers silently - */ - public ForwardedHeaderSanitizer(TrustedProxyPolicy trustedProxyPolicy, boolean refuseUntrusted) { - this.trustedProxyPolicy = Objects.requireNonNull(trustedProxyPolicy, "trustedProxyPolicy"); - this.refuseUntrusted = refuseUntrusted; - } - - /** - * Normalises the forwarded headers of one request. - * - * @param peerAddress the address the connection actually came from - * @param headers the request headers - * @return the trusted external view, or {@link NormalizedForwardedHeaders#none()} - * @throws UntrustedForwardedHeaderException when an untrusted peer sent forwarded headers and - * this sanitiser is configured to refuse them - */ - public NormalizedForwardedHeaders normalize(String peerAddress, Map headers) { - Objects.requireNonNull(headers, "headers"); - boolean forwarded = NormalizedForwardedHeaders.present(headers); - boolean trusted = trustedProxyPolicy.isTrusted(peerAddress); - if (forwarded && !trusted) { - if (refuseUntrusted) { - throw new UntrustedForwardedHeaderException(String.valueOf(peerAddress)); - } - return NormalizedForwardedHeaders.none(); - } - return trusted - ? NormalizedForwardedHeaders.fromTrustedHeaders(headers) - : NormalizedForwardedHeaders.none(); - } - - /** Normalises using a resolved peer address. */ - public NormalizedForwardedHeaders normalize(InetAddress peer, Map headers) { - return normalize(peer == null ? null : peer.getHostAddress(), headers); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/proxy/NormalizedForwardedHeaders.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/proxy/NormalizedForwardedHeaders.java deleted file mode 100644 index 086d1b88..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/proxy/NormalizedForwardedHeaders.java +++ /dev/null @@ -1,158 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.proxy; - -import java.util.Locale; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -/** - * What a trusted proxy said the request looked like from outside, after normalisation. - * - *

Only four facts survive: scheme, host, port and prefix. Everything else a forwarded header can - * carry — the original path, a query string, a chain of intermediaries — is discarded, because this - * value is consumed to build absolute URLs and anything kept here becomes something a caller can - * influence in a {@code Location} header. - * - *

The client address is separate and deliberately not part of URL construction: it is used for - * rate limiting and audit, where a wrong value has a different consequence than a wrong link. - * - * @param scheme the external scheme, lower case - * @param host the external host, lower case, without a port - * @param port the external port - * @param prefix the external path prefix, empty or beginning with a slash - * @param clientAddress the address the proxy says the request came from - */ -public record NormalizedForwardedHeaders( - Optional scheme, - Optional host, - Optional port, - Optional prefix, - Optional clientAddress) { - - /** The standard forwarded header names, in the spellings a proxy actually sets. */ - public static final String X_FORWARDED_PROTO = "X-Forwarded-Proto"; - - /** The external host. */ - public static final String X_FORWARDED_HOST = "X-Forwarded-Host"; - - /** The external port. */ - public static final String X_FORWARDED_PORT = "X-Forwarded-Port"; - - /** The external path prefix. */ - public static final String X_FORWARDED_PREFIX = "X-Forwarded-Prefix"; - - /** The originating client. */ - public static final String X_FORWARDED_FOR = "X-Forwarded-For"; - - /** RFC 7239's single header. */ - public static final String FORWARDED = "Forwarded"; - - public NormalizedForwardedHeaders { - Objects.requireNonNull(scheme, "scheme"); - Objects.requireNonNull(host, "host"); - Objects.requireNonNull(port, "port"); - Objects.requireNonNull(prefix, "prefix"); - Objects.requireNonNull(clientAddress, "clientAddress"); - } - - /** Nothing was forwarded; the server's own view of the request is authoritative. */ - public static NormalizedForwardedHeaders none() { - return new NormalizedForwardedHeaders( - Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty()); - } - - /** - * Reads the headers a trusted proxy set. - * - *

Only called after the peer has been established as trusted. Every value is validated anyway: - * a trusted proxy is trusted to be honest, not to be correct, and a misconfigured Nginx - * forwarding an empty host would otherwise produce {@code https:///reset}. - * - * @param headers the request headers, keyed case-insensitively by the caller - */ - public static NormalizedForwardedHeaders fromTrustedHeaders(Map headers) { - Objects.requireNonNull(headers, "headers"); - return new NormalizedForwardedHeaders( - first(headers, X_FORWARDED_PROTO) - .map(value -> value.toLowerCase(Locale.ROOT)) - .filter(value -> value.equals("http") || value.equals("https")), - first(headers, X_FORWARDED_HOST) - .map(value -> value.toLowerCase(Locale.ROOT)) - .map(NormalizedForwardedHeaders::hostWithoutPort) - .filter(NormalizedForwardedHeaders::plausibleHost), - first(headers, X_FORWARDED_PORT).flatMap(NormalizedForwardedHeaders::parsePort), - first(headers, X_FORWARDED_PREFIX).flatMap(NormalizedForwardedHeaders::normalizePrefix), - first(headers, X_FORWARDED_FOR).map(NormalizedForwardedHeaders::firstHop)); - } - - /** Whether a header map carries any forwarded header at all. */ - public static boolean present(Map headers) { - if (headers == null) { - return false; - } - return headers.keySet().stream() - .map(name -> name.toLowerCase(Locale.ROOT)) - .anyMatch(name -> name.equals("forwarded") || name.startsWith("x-forwarded-")); - } - - private static Optional first(Map headers, String name) { - return headers.entrySet().stream() - .filter(entry -> entry.getKey().equalsIgnoreCase(name)) - .map(Map.Entry::getValue) - .filter(value -> value != null && !value.isBlank()) - .map(String::trim) - .findFirst(); - } - - /** - * The first hop of a comma-separated chain. - * - *

The first, not the last. A proxy appends, so the leftmost entry is the originating client — - * and it is also the one a client can forge, which is why this is only read from a trusted peer - * that has been configured to overwrite rather than append. - */ - private static String firstHop(String value) { - int comma = value.indexOf(','); - return (comma < 0 ? value : value.substring(0, comma)).trim(); - } - - private static String hostWithoutPort(String value) { - if (value.startsWith("[")) { - int close = value.indexOf(']'); - return close > 0 ? value.substring(0, close + 1) : value; - } - int colon = value.indexOf(':'); - return colon < 0 ? value : value.substring(0, colon); - } - - private static boolean plausibleHost(String value) { - return !value.isBlank() - && value.length() <= 253 - && value - .chars() - .noneMatch(character -> character <= 0x20 || character == '/' || character == '\\'); - } - - private static Optional parsePort(String value) { - try { - int port = Integer.parseInt(value); - return port >= 1 && port <= 65535 ? Optional.of(port) : Optional.empty(); - } catch (NumberFormatException notANumber) { - return Optional.empty(); - } - } - - private static Optional normalizePrefix(String value) { - String prefix = value.trim(); - while (prefix.endsWith("/")) { - prefix = prefix.substring(0, prefix.length() - 1); - } - if (prefix.isEmpty()) { - return Optional.empty(); - } - if (!prefix.startsWith("/") || prefix.contains("..") || prefix.contains("//")) { - return Optional.empty(); - } - return Optional.of(prefix); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/proxy/TrustedProxyPolicy.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/proxy/TrustedProxyPolicy.java deleted file mode 100644 index f39d3d99..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/proxy/TrustedProxyPolicy.java +++ /dev/null @@ -1,161 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.proxy; - -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Objects; - -/** - * Which peers are allowed to tell this service what the request looked like from outside. - * - *

An allowlist of CIDR ranges, and empty by default. Forwarded headers are the only way a - * service behind a proxy can know its own external scheme, host and client address — and they are - * plain request headers, so any caller that can reach the port can set them. A deployment that - * trusts them from everybody lets a client choose the IP its rate limit is keyed on, the host its - * password-reset link points at, and whether the request "arrived over HTTPS". - * - *

Empty means trust nobody, which is the safe direction: a direct-access deployment reads its - * own socket and is correct, while a proxied deployment that forgot to configure this gets wrong - * URLs rather than a forgeable trust boundary. - */ -public final class TrustedProxyPolicy { - - private final List ranges; - - private TrustedProxyPolicy(List ranges) { - this.ranges = List.copyOf(ranges); - } - - /** Trusts nobody; forwarded headers are ignored wherever they came from. */ - public static TrustedProxyPolicy trustNobody() { - return new TrustedProxyPolicy(List.of()); - } - - /** - * Trusts the given CIDR ranges. - * - * @param cidrs ranges in {@code a.b.c.d/len} form - */ - public static TrustedProxyPolicy of(String... cidrs) { - Objects.requireNonNull(cidrs, "cidrs"); - List parsed = new ArrayList<>(); - for (String cidr : cidrs) { - parsed.add(CidrRange.parse(cidr)); - } - return new TrustedProxyPolicy(parsed); - } - - /** Whether a peer may set forwarded headers. */ - public boolean isTrusted(InetAddress peer) { - if (peer == null || ranges.isEmpty()) { - return false; - } - return ranges.stream().anyMatch(range -> range.contains(peer)); - } - - /** Whether a peer address may set forwarded headers. */ - public boolean isTrusted(String peerAddress) { - if (peerAddress == null || peerAddress.isBlank()) { - return false; - } - try { - // Parsed as a literal only. Resolving a name here would let a caller point a DNS record at a - // trusted range and be believed. - return isTrusted(InetAddress.getByName(peerAddress.trim())); - } catch (UnknownHostException unresolvable) { - return false; - } - } - - /** Whether this policy trusts anybody at all. */ - public boolean trustsAnybody() { - return !ranges.isEmpty(); - } - - /** - * One CIDR range, matched on raw address bytes so IPv4 and IPv6 use the same code. - * - *

A class rather than a record: the network is a byte array, and a record component that is an - * array gets identity equality and a useless {@code toString}, which is exactly the trap - * ErrorProne's {@code ArrayRecordComponent} names. The array is defensively copied on the way in - * and never handed back out, so this one is genuinely immutable. - */ - private static final class CidrRange { - - private final byte[] network; - private final int prefixLength; - - private CidrRange(byte[] network, int prefixLength) { - this.network = network.clone(); - this.prefixLength = prefixLength; - } - - static CidrRange parse(String cidr) { - Objects.requireNonNull(cidr, "cidr"); - int slash = cidr.indexOf('/'); - if (slash < 0) { - throw new IllegalArgumentException("a trusted proxy range needs a prefix length: " + cidr); - } - String address = cidr.substring(0, slash).trim(); - int prefixLength; - try { - prefixLength = Integer.parseInt(cidr.substring(slash + 1).trim()); - } catch (NumberFormatException notANumber) { - throw new IllegalArgumentException("invalid prefix length in " + cidr, notANumber); - } - byte[] network; - try { - network = InetAddress.getByName(address).getAddress(); - } catch (UnknownHostException unresolvable) { - throw new IllegalArgumentException("invalid address in " + cidr, unresolvable); - } - if (prefixLength < 0 || prefixLength > network.length * 8) { - throw new IllegalArgumentException("prefix length out of range in " + cidr); - } - return new CidrRange(network, prefixLength); - } - - boolean contains(InetAddress candidate) { - byte[] address = candidate.getAddress(); - if (address.length != network.length) { - // An IPv4 peer never matches an IPv6 range and vice versa: the byte lengths differ, so the - // comparison is not even attempted. Note that this is not the same as refusing IPv4-mapped - // forms — the JDK canonicalises ::ffff:10.0.0.1 to an Inet4Address before it reaches here, - // so a mapped trusted address stays trusted. That is correct: the peer address comes from - // the socket, not from a header, so a caller cannot choose which form it arrives in. - return false; - } - int fullBytes = prefixLength / 8; - for (int index = 0; index < fullBytes; index++) { - if (address[index] != network[index]) { - return false; - } - } - int remainingBits = prefixLength % 8; - if (remainingBits == 0) { - return true; - } - int mask = 0xFF << (8 - remainingBits); - return (address[fullBytes] & mask) == (network[fullBytes] & mask); - } - - @Override - public boolean equals(Object other) { - return other instanceof CidrRange range - && prefixLength == range.prefixLength - && Arrays.equals(network, range.network); - } - - @Override - public int hashCode() { - return Arrays.hashCode(network) * 31 + prefixLength; - } - - @Override - public String toString() { - return prefixLength + "-bit range"; - } - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/proxy/UntrustedForwardedHeaderException.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/proxy/UntrustedForwardedHeaderException.java deleted file mode 100644 index e1b3b88b..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/proxy/UntrustedForwardedHeaderException.java +++ /dev/null @@ -1,30 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.proxy; - -/** - * A peer that is not a configured proxy sent a forwarded header. - * - *

Refused rather than ignored, and the difference matters. Ignoring means the request is served - * with the server's own view, which is usually right — so the attempt leaves no trace and the same - * client keeps probing. Refusing makes the attempt a visible 400 and a log line, which is what an - * operator needs to see that somebody is trying to choose their own client address. - * - *

The message names the peer and nothing else. Echoing the header value would put - * attacker-chosen content into the log line that reports the attack. - */ -public final class UntrustedForwardedHeaderException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - /** - * Creates the failure. - * - * @param peerAddress the peer that sent the header - */ - public UntrustedForwardedHeaderException(String peerAddress) { - super( - "forwarded headers were sent by " - + peerAddress - + ", which is not a configured trusted proxy; believing them would let a caller choose" - + " its own client address, host and scheme"); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/ratelimit/RateLimitDecision.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/ratelimit/RateLimitDecision.java deleted file mode 100644 index 30294e19..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/ratelimit/RateLimitDecision.java +++ /dev/null @@ -1,65 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.ratelimit; - -import java.time.Duration; -import java.time.Instant; -import java.util.Objects; -import java.util.Optional; - -/** - * What a limiter decided about one request. - * - *

Carries the window state as well as the verdict, because a caller that is refused needs to - * know when to come back and a caller that is allowed needs to know how close it is. A bare boolean - * produces clients that either retry immediately in a loop or back off far longer than necessary, - * and both are worse for the service than telling them. - * - * @param allowed whether the request may proceed - * @param limit the quota for the window - * @param remaining how much of it is left - * @param resetAt when the window rolls over - * @param retryAfter how long to wait, present only when refused - */ -public record RateLimitDecision( - boolean allowed, long limit, long remaining, Instant resetAt, Optional retryAfter) { - - public RateLimitDecision { - Objects.requireNonNull(resetAt, "resetAt"); - Objects.requireNonNull(retryAfter, "retryAfter"); - if (limit <= 0) { - throw new IllegalArgumentException("a quota of " + limit + " admits nothing"); - } - if (remaining < 0) { - throw new IllegalArgumentException("remaining quota cannot be negative"); - } - if (allowed && retryAfter.isPresent()) { - throw new IllegalArgumentException("an allowed request has nothing to wait for"); - } - if (!allowed && retryAfter.isEmpty()) { - throw new IllegalArgumentException( - "a refused request must say how long to wait; without it every client invents its own" - + " backoff and the impatient ones set the load"); - } - } - - /** - * A request inside its quota. - * - * @param limit the quota for the window - * @param remaining how much is left after this request - * @param resetAt when the window rolls over - */ - public static RateLimitDecision allowed(long limit, long remaining, Instant resetAt) { - return new RateLimitDecision(true, limit, remaining, resetAt, Optional.empty()); - } - - /** - * A request over its quota. - * - * @param limit the quota for the window - * @param resetAt when the window rolls over - * @param retryAfter how long to wait - */ - public static RateLimitDecision refused(long limit, Instant resetAt, Duration retryAfter) { - return new RateLimitDecision(false, limit, 0, resetAt, Optional.of(retryAfter)); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/ratelimit/RateLimitFailurePolicy.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/ratelimit/RateLimitFailurePolicy.java deleted file mode 100644 index 5e05dc2c..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/ratelimit/RateLimitFailurePolicy.java +++ /dev/null @@ -1,30 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.ratelimit; - -/** - * What to do when the limiter's own store is unreachable. - * - *

An explicit choice per operation, because there is no answer that is right for all of them and - * the default is always wrong for half. It is declared on the operation profile so the decision is - * made by whoever knows what the endpoint does, at review time, rather than by whatever the limiter - * happened to do when Redis went away. - */ -public enum RateLimitFailurePolicy { - - /** - * Serve the request when the limiter cannot answer. - * - *

Right for reads and for anything whose worst case is load. Wrong for anything a quota is - * protecting from abuse rather than from volume: a login endpoint that fails open turns a Redis - * outage into an open brute-force window. - */ - FAIL_OPEN, - - /** - * Refuse the request when the limiter cannot answer. - * - *

Right where exceeding the quota is worse than being unavailable — sending messages, moving - * money, anything that costs per call. It converts a dependency outage into a total outage of - * that endpoint, which is the price of the guarantee. - */ - FAIL_CLOSED -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/ratelimit/RateLimitProfileName.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/ratelimit/RateLimitProfileName.java deleted file mode 100644 index 34928384..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/ratelimit/RateLimitProfileName.java +++ /dev/null @@ -1,32 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.ratelimit; - -import java.util.Objects; -import java.util.regex.Pattern; - -/** - * The name of a quota profile. - * - * @param value the profile name - */ -public record RateLimitProfileName(String value) { - - private static final Pattern GRAMMAR = Pattern.compile("[a-z][a-z0-9-]{0,63}"); - - public RateLimitProfileName { - Objects.requireNonNull(value, "value"); - if (!GRAMMAR.matcher(value).matches()) { - throw new IllegalArgumentException( - "a rate limit profile name must match [a-z][a-z0-9-]{0,63}"); - } - } - - /** The profile every operation gets unless it declares another. */ - public static RateLimitProfileName standard() { - return new RateLimitProfileName("standard"); - } - - @Override - public String toString() { - return value; - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/ratelimit/WebRateLimiter.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/ratelimit/WebRateLimiter.java deleted file mode 100644 index 2d51bee6..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/ratelimit/WebRateLimiter.java +++ /dev/null @@ -1,25 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.ratelimit; - -import dev.caskeleton.adapter.inbound.web.core.WebRequestContext; - -/** - * A per-caller quota over a period of time. - * - *

A quota, not a capacity check. The two are routinely conflated and answer differently: - * exhausting a quota is the caller's own doing and is 429; running out of capacity is the service's - * state and is 503. A client told 429 knows to slow down; told 503 it knows the problem is not its - * rate. Merging them tells every client the wrong thing half the time. - * - * @see dev.caskeleton.adapter.inbound.web.admission.WebAdmissionController for the capacity half - */ -@FunctionalInterface -public interface WebRateLimiter { - - /** - * Charges one request against a quota. - * - * @param context who is asking and for what - * @param profile which quota applies - */ - RateLimitDecision evaluate(WebRequestContext context, RateLimitProfileName profile); -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/security/CorsProfile.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/security/CorsProfile.java deleted file mode 100644 index 5679e864..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/security/CorsProfile.java +++ /dev/null @@ -1,88 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.security; - -import java.time.Duration; -import java.util.Locale; -import java.util.Objects; -import java.util.Set; - -/** - * Which cross-origin callers may reach this API, and with what. - * - *

CORS is a browser-enforced relaxation of the same-origin policy, which means every entry here - * is a permission granted to a page the operator does not control. The validator refuses the - * combinations that grant more than anyone intends. - * - * @param allowedOrigins exact origins, or the single wildcard - * @param allowedMethods methods a preflight may approve - * @param allowedHeaders request headers a preflight may approve - * @param exposedHeaders response headers script may read - * @param allowCredentials whether cookies and TLS client certs may be sent - * @param maxAge how long a browser may cache the preflight - */ -public record CorsProfile( - Set allowedOrigins, - Set allowedMethods, - Set allowedHeaders, - Set exposedHeaders, - boolean allowCredentials, - Duration maxAge) { - - /** The wildcard origin. */ - public static final String ANY_ORIGIN = "*"; - - public CorsProfile { - Objects.requireNonNull(allowedOrigins, "allowedOrigins"); - Objects.requireNonNull(allowedMethods, "allowedMethods"); - Objects.requireNonNull(allowedHeaders, "allowedHeaders"); - Objects.requireNonNull(exposedHeaders, "exposedHeaders"); - Objects.requireNonNull(maxAge, "maxAge"); - allowedOrigins = Set.copyOf(allowedOrigins); - allowedMethods = Set.copyOf(allowedMethods); - allowedHeaders = Set.copyOf(allowedHeaders); - exposedHeaders = Set.copyOf(exposedHeaders); - if (maxAge.isNegative()) { - throw new IllegalArgumentException("a negative preflight cache age is not an age"); - } - } - - /** - * A profile for a browser front end on a known origin. - * - * @param origins the exact origins the front end is served from - */ - public static CorsProfile credentialedFrontEnd(Set origins) { - return new CorsProfile( - origins, - Set.of("GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"), - Set.of("Content-Type", "Idempotency-Key", "If-Match", "If-None-Match"), - Set.of("ETag", "Location", "Retry-After"), - true, - Duration.ofMinutes(10)); - } - - /** A profile for a public read-only API that carries no credentials. */ - public static CorsProfile publicReadOnly() { - return new CorsProfile( - Set.of(ANY_ORIGIN), - Set.of("GET", "HEAD"), - Set.of("Content-Type"), - Set.of("ETag"), - false, - Duration.ofMinutes(10)); - } - - /** Whether the wildcard origin is allowed. */ - public boolean allowsAnyOrigin() { - return allowedOrigins.contains(ANY_ORIGIN); - } - - /** Whether an origin is permitted, matched exactly and case-sensitively on host. */ - public boolean permits(String origin) { - if (origin == null) { - return false; - } - // Exact match, never a suffix or prefix test. "endsWith(\".example.com\")" is the classic - // mistake and it admits "evil-example.com" and "example.com.attacker.net" alike. - return allowsAnyOrigin() || allowedOrigins.contains(origin.toLowerCase(Locale.ROOT)); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/security/CsrfProfile.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/security/CsrfProfile.java deleted file mode 100644 index 428ba0ac..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/security/CsrfProfile.java +++ /dev/null @@ -1,44 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.security; - -import java.util.Objects; - -/** - * Whether CSRF protection applies, and why. - * - *

The rationale is a field rather than a comment because "CSRF is disabled here" is a claim that - * has to survive a review a year later. A profile that carries the threat-model reason it was - * disabled can be re-examined; a boolean cannot, and the usual outcome is that nobody dares change - * it and nobody can say why it is that way. - * - * @param enabled whether a CSRF token is required for unsafe methods - * @param rationale why, in terms of what a browser will and will not attach - */ -public record CsrfProfile(boolean enabled, String rationale) { - - public CsrfProfile { - Objects.requireNonNull(rationale, "rationale"); - if (rationale.isBlank()) { - throw new IllegalArgumentException( - "a CSRF decision without a stated reason cannot be reviewed, only inherited"); - } - } - - /** Required, because the browser attaches the credential by itself. */ - public static CsrfProfile required() { - return new CsrfProfile( - true, - "the credential is attached by the browser without the page asking, so a cross-site" - + " request authenticates on its own"); - } - - /** - * Not required, on the stated grounds that no browser attaches this credential. - * - *

Named for what it is — a reviewed exemption, not an absence. It applies only to a mode where - * nothing is ambiently attached, which the resolver enforces rather than trusting the caller to - * check. - */ - public static CsrfProfile explicitlyReviewed(String threatModel) { - return new CsrfProfile(false, threatModel); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/security/WebCorsPolicyValidator.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/security/WebCorsPolicyValidator.java deleted file mode 100644 index c634486d..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/security/WebCorsPolicyValidator.java +++ /dev/null @@ -1,96 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.security; - -import java.net.URI; -import java.util.Locale; -import java.util.Objects; - -/** - * Refuses CORS profiles that grant more than anyone means to grant. - * - *

At construction, not per request. Every rule here describes a configuration that a browser - * will happily honour and that no test of the API's own behaviour would ever notice — the API - * answers normally, and the only observable difference is which foreign pages can read the answer. - * A misconfiguration that is invisible in testing has to be refused at startup or it ships. - */ -public final class WebCorsPolicyValidator { - - /** - * Refuses an unsafe profile. - * - * @param profile the profile to check - * @throws IllegalStateException when the profile grants more than it should - */ - public void validate(CorsProfile profile) { - Objects.requireNonNull(profile, "profile"); - - if (profile.allowCredentials() && profile.allowsAnyOrigin()) { - // The one every browser already refuses, which is exactly why it must be refused here too: - // the deployment appears to work in testing against a same-origin front end and fails only - // for the cross-origin callers it was configured for, with a console error nobody sees. - throw new IllegalStateException( - "credentialed CORS requires an exact origin allowlist: '*' with credentials would let" - + " any page on the internet make authenticated requests as the visiting user"); - } - - for (String origin : profile.allowedOrigins()) { - if (CorsProfile.ANY_ORIGIN.equals(origin)) { - continue; - } - requireExactOrigin(origin); - } - - if (profile.allowCredentials() && profile.allowedHeaders().contains("*")) { - throw new IllegalStateException( - "a credentialed profile must name the headers it accepts: '*' is not honoured with" - + " credentials by browsers, so the deployment fails only for real callers"); - } - - if (profile.allowedMethods().isEmpty()) { - throw new IllegalStateException( - "a CORS profile that approves no method rejects every preflight, which reads to a client" - + " as the endpoint being broken rather than as a policy"); - } - } - - private static void requireExactOrigin(String origin) { - if (origin.isBlank()) { - throw new IllegalStateException("a blank origin is not an origin"); - } - if (origin.contains("*")) { - // Checked before parsing: a wildcard makes the value an invalid URI, so leaving this until - // after URI.create reports it as a malformed origin and hides what is actually wrong. - // - // A wildcard anywhere but as the whole value is not a wildcard at all — it is a literal - // asterisk in a hostname, and it matches nothing while reading as though it matches a family. - throw new IllegalStateException( - "origin " - + origin - + " contains a wildcard; CORS matches origins exactly, so this" - + " matches nothing while appearing to match a family of hosts"); - } - if (!origin.equals(origin.toLowerCase(Locale.ROOT))) { - // Origins are compared as strings against what the browser sends, which is lowercase. An - // uppercase entry simply never matches, and the failure looks like the allowlist being - // ignored rather than being wrong. - throw new IllegalStateException( - "origin " - + origin - + " must be lowercase; a browser sends it lowercase and it would" - + " never match"); - } - URI parsed; - try { - parsed = URI.create(origin); - } catch (IllegalArgumentException malformed) { - throw new IllegalStateException("origin " + origin + " is not a URI", malformed); - } - if (parsed.getScheme() == null || parsed.getHost() == null) { - throw new IllegalStateException( - "origin " + origin + " must be scheme://host[:port]; a bare host never matches"); - } - if (parsed.getPath() != null && !parsed.getPath().isEmpty()) { - throw new IllegalStateException( - "origin " + origin + " must carry no path; an origin is scheme, host and port only"); - } - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/security/WebCredentialMode.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/security/WebCredentialMode.java deleted file mode 100644 index 2efd1eca..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/security/WebCredentialMode.java +++ /dev/null @@ -1,42 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.security; - -/** - * How a caller proves who it is. - * - *

This is the single fact CSRF protection turns on, so it is a declared mode rather than - * something inferred per request. CSRF exists because browsers attach some credentials - * automatically: a cookie travels with a cross-site request whether or not the page meant to send - * it, and an {@code Authorization} header does not. Everything else about CSRF follows from that - * one distinction, and getting it wrong in either direction is expensive — protection omitted where - * cookies are used is a working attack, and protection demanded where they are not breaks every - * non-browser client for no gain. - */ -public enum WebCredentialMode { - - /** A session cookie the browser attaches on its own. */ - SESSION_COOKIE, - - /** A cookie minted by a backend-for-frontend, attached the same way. */ - BFF_COOKIE, - - /** - * Both a cookie and a bearer token are accepted. - * - *

The dangerous one, and the reason this enum has five members rather than two. A cookie the - * endpoint merely *accepts* is enough: an attacker's cross-site form omits the header and the - * browser supplies the cookie, so the request authenticates. Reasoning about the header path and - * concluding CSRF is unnecessary is the mistake this constant exists to make visible. - */ - COOKIE_AND_BEARER, - - /** Only an {@code Authorization} header, which no browser attaches by itself. */ - AUTHORIZATION_HEADER_ONLY, - - /** mTLS or a signed service credential; no browser is involved at all. */ - SERVICE_TO_SERVICE; - - /** Whether a browser attaches this credential without the page asking. */ - public boolean ambientlyAttached() { - return this == SESSION_COOKIE || this == BFF_COOKIE || this == COOKIE_AND_BEARER; - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/security/WebCsrfPolicyResolver.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/security/WebCsrfPolicyResolver.java deleted file mode 100644 index 348a0596..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/security/WebCsrfPolicyResolver.java +++ /dev/null @@ -1,43 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.security; - -import java.util.Objects; - -/** - * Derives the CSRF requirement from how the caller authenticates. - * - *

Derived, never configured. A per-endpoint CSRF switch is a switch somebody eventually turns - * off to unbreak a client, and the endpoint that gets it turned off is usually the one where it - * mattered. Here the answer follows from the credential mode, so disabling protection requires - * changing what the endpoint accepts — which is a decision a reviewer will notice. - */ -public final class WebCsrfPolicyResolver { - - /** - * The CSRF profile for a credential mode. - * - * @param mode how the caller authenticates - */ - public CsrfProfile resolve(WebCredentialMode mode) { - Objects.requireNonNull(mode, "mode"); - return mode.ambientlyAttached() - ? CsrfProfile.required() - : CsrfProfile.explicitlyReviewed(reviewedThreatModelFor(mode)); - } - - private static String reviewedThreatModelFor(WebCredentialMode mode) { - return switch (mode) { - case AUTHORIZATION_HEADER_ONLY -> - "the endpoint accepts no cookie, so a cross-site request carries no credential and" - + " authenticates as nobody; the exemption ends the moment a cookie is accepted"; - case SERVICE_TO_SERVICE -> - "the caller is not a browser and the credential is a client certificate or a signed" - + " token that no user agent attaches on its own"; - // Unreachable while ambientlyAttached() and this switch agree. Stated as a failure rather - // than a default so that adding a mode to the enum without deciding this cannot compile - // into a silent exemption. - case SESSION_COOKIE, BFF_COOKIE, COOKIE_AND_BEARER -> - throw new IllegalStateException( - mode + " is ambiently attached and cannot be exempt from CSRF"); - }; - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/validation/TransportValidationException.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/validation/TransportValidationException.java deleted file mode 100644 index 65ab7a8a..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/validation/TransportValidationException.java +++ /dev/null @@ -1,48 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.validation; - -import dev.caskeleton.adapter.inbound.web.error.ValidationIssue; -import java.util.List; - -/** - * A request that parsed and bound cleanly but violates a transport-level rule. - * - *

Its own type because the status depends on it. A document that is not JSON is a 400 — the - * client's message was unintelligible. A document that was understood and is not acceptable is a - * 422, and the difference tells a client whether to fix its serialiser or its data. - * - *

Transport validation is deliberately narrow: shape, ranges, cross-field consistency, anything - * decidable from the request alone. It must not reach a database, an HTTP client or a broker. A - * rule that needs to look something up is a business rule, it belongs in the application, and - * enforcing it here would put a query on the path of every malformed request an attacker sends. - */ -public final class TransportValidationException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - private final transient List issues; - - /** - * Creates a failure with no field-level detail. - * - * @param message what was wrong, carrying no submitted content - */ - public TransportValidationException(String message) { - this(message, List.of()); - } - - /** - * Creates a failure with field-level detail. - * - * @param message what was wrong, carrying no submitted content - * @param issues the field-level issues - */ - public TransportValidationException(String message, List issues) { - super(message); - this.issues = List.copyOf(issues); - } - - /** The field-level issues, empty when the failure is not field-level. */ - public List issues() { - return issues; - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/validation/WebInputPointer.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/validation/WebInputPointer.java deleted file mode 100644 index dc30f22b..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/validation/WebInputPointer.java +++ /dev/null @@ -1,66 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.validation; - -import java.util.List; -import java.util.Objects; - -/** - * Builds the JSON Pointer that names the offending member of a request document. - * - *

A pointer into the document the client sent, never a path through the Java model. The client - * can act on {@code /order/lines/0/quantity}; it cannot act on {@code - * createOrder.arg0.lines[0].quantity}, which additionally publishes the shape of an internal method - * signature to anybody who sends a bad request. - * - *

Segments are escaped per RFC 6901. A field literally named {@code a/b} would otherwise produce - * a pointer that addresses a nested member that does not exist. - */ -public final class WebInputPointer { - - /** The pointer to the document root, used when a failure is not field-level. */ - public static final String ROOT = ""; - - private WebInputPointer() {} - - /** - * A pointer from ordered path segments. - * - * @param segments the member names and array indexes, outermost first - */ - public static String of(List segments) { - Objects.requireNonNull(segments, "segments"); - if (segments.isEmpty()) { - return ROOT; - } - StringBuilder pointer = new StringBuilder(); - for (String segment : segments) { - pointer.append('/').append(escape(Objects.requireNonNull(segment, "segment"))); - } - return pointer.toString(); - } - - /** - * Converts a Bean Validation property path into a pointer. - * - *

Bean Validation reports {@code lines[0].quantity}; a client needs {@code /lines/0/quantity}. - * The leading method and argument segments that Jakarta adds for a method-level constraint are - * dropped, because they name a Java signature rather than anything the client sent. - * - * @param propertyPath the Bean Validation path - */ - public static String fromPropertyPath(String propertyPath) { - if (propertyPath == null || propertyPath.isBlank()) { - return ROOT; - } - String working = propertyPath.replace("[", ".").replace("]", ""); - List segments = - java.util.Arrays.stream(working.split("\\.")) - .filter(segment -> !segment.isBlank()) - .filter(segment -> !segment.matches("arg\\d+")) - .toList(); - return of(segments); - } - - private static String escape(String segment) { - return segment.replace("~", "~0").replace("/", "~1"); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/validation/WebValidationExceptionMapper.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/validation/WebValidationExceptionMapper.java deleted file mode 100644 index cdefe589..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/validation/WebValidationExceptionMapper.java +++ /dev/null @@ -1,78 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.validation; - -import dev.caskeleton.adapter.inbound.web.error.ProblemCode; -import dev.caskeleton.adapter.inbound.web.json.WebJsonDecodingException; -import java.util.Optional; -import tools.jackson.core.JacksonException; -import tools.jackson.databind.exc.InvalidFormatException; -import tools.jackson.databind.exc.MismatchedInputException; -import tools.jackson.databind.exc.UnrecognizedPropertyException; - -/** - * Decides whether a rejected request is a 400 or a 422. - * - *

The split is the design's and it is a real distinction rather than a stylistic one. A 400 says - * "I could not understand your message"; a 422 says "I understood it and it is not acceptable". A - * client acts on them differently: the first is a bug in how it builds requests, the second is a - * problem with the data a user typed. Collapsing both into 400 — which is the common shortcut — - * means a client cannot tell a serialisation bug from a rejected form. - * - *

Everything that fails before or during binding is a 400. That includes an unknown enum value - * and a string where a number belongs: those are decided by the shape of the document, not by its - * meaning, and the strict mapper refuses them at parse time. - * - *

An unmapped failure throws rather than defaulting. A default here would quietly answer some - * future exception with somebody's guess at a status, and the guess would be wrong in exactly the - * cases nobody anticipated. - */ -public final class WebValidationExceptionMapper { - - /** - * The problem code for a rejected request. - * - * @param failure the failure raised while reading or validating the request - * @throws IllegalArgumentException when the failure has no declared mapping - */ - public ProblemCode codeFor(Throwable failure) { - return find(failure) - .orElseThrow( - () -> - new IllegalArgumentException( - "unmapped validation failure: " - + (failure == null ? "null" : failure.getClass().getName()) - + "; a default status here would be a guess published to a client", - failure)); - } - - /** The problem code for a failure, when one is declared. */ - public Optional find(Throwable failure) { - if (failure == null) { - return Optional.empty(); - } - if (failure instanceof TransportValidationException) { - return Optional.of(ProblemCode.VALIDATION_FAILED); - } - if (failure instanceof WebJsonDecodingException decoding) { - return Optional.of( - decoding.malformed() ? ProblemCode.MALFORMED_REQUEST : ProblemCode.BINDING_FAILED); - } - // An unrecognised property and a wrong scalar shape are decided by the document's structure, - // so they are read failures rather than semantic ones. - if (failure instanceof UnrecognizedPropertyException - || failure instanceof InvalidFormatException) { - return Optional.of(ProblemCode.BINDING_FAILED); - } - if (failure instanceof MismatchedInputException) { - return Optional.of(ProblemCode.BINDING_FAILED); - } - if (failure instanceof JacksonException) { - return Optional.of(ProblemCode.MALFORMED_REQUEST); - } - return Optional.empty(); - } - - /** Whether a failure is one this mapper can classify. */ - public boolean handles(Throwable failure) { - return find(failure).isPresent(); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/validation/WebValidationIssueMapper.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/validation/WebValidationIssueMapper.java deleted file mode 100644 index 2ca25890..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/validation/WebValidationIssueMapper.java +++ /dev/null @@ -1,95 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.validation; - -import dev.caskeleton.adapter.inbound.web.error.ValidationIssue; -import jakarta.validation.ConstraintViolation; -import java.util.List; -import java.util.Objects; -import java.util.Set; -import java.util.stream.Collectors; - -/** - * Turns Bean Validation violations into the platform's field-level issues. - * - *

Three things change on the way across, and each is a leak that would otherwise be published. - * The property path becomes a JSON Pointer, so a client can act on it and the internal method - * signature stays private. The constraint annotation becomes a stable code, so a client can branch - * on {@code must-be-positive} rather than on a message that gets reworded or translated. And the - * invalid value is dropped entirely — {@code ConstraintViolation} carries it, and echoing it back - * is how a password typed into the wrong field reaches a log aggregator. - * - *

Issues are sorted by pointer so two identical failures produce byte-identical bodies. An error - * response whose member order varies between runs cannot be asserted in a contract test, and a - * client that caches by response hash sees churn that is not there. - */ -public final class WebValidationIssueMapper { - - /** - * Maps a set of violations. - * - * @param violations the Bean Validation result - */ - public List toIssues(Set> violations) { - Objects.requireNonNull(violations, "violations"); - return violations.stream() - .map(this::toIssue) - .sorted( - java.util.Comparator.comparing(ValidationIssue::pointer) - .thenComparing(ValidationIssue::code)) - .collect(Collectors.toUnmodifiableList()); - } - - /** Maps one violation. */ - public ValidationIssue toIssue(ConstraintViolation violation) { - Objects.requireNonNull(violation, "violation"); - String pointer = - WebInputPointer.fromPropertyPath( - violation.getPropertyPath() == null ? "" : violation.getPropertyPath().toString()); - return new ValidationIssue(pointer, codeFor(violation), safeMessage(violation)); - } - - /** - * The stable code for a constraint. - * - *

Derived from the annotation type rather than the message: {@code @NotBlank} is {@code - * must-not-be-blank} in every locale and after every reword. - */ - private String codeFor(ConstraintViolation violation) { - if (violation.getConstraintDescriptor() == null - || violation.getConstraintDescriptor().getAnnotation() == null) { - return "invalid"; - } - String annotation = - violation.getConstraintDescriptor().getAnnotation().annotationType().getSimpleName(); - return switch (annotation) { - case "NotNull" -> "must-not-be-null"; - case "NotBlank" -> "must-not-be-blank"; - case "NotEmpty" -> "must-not-be-empty"; - case "Size" -> "size-out-of-range"; - case "Min", "Positive", "PositiveOrZero" -> "must-be-at-least"; - case "Max", "Negative", "NegativeOrZero" -> "must-be-at-most"; - case "Pattern" -> "must-match-pattern"; - case "Email" -> "must-be-email"; - case "Past", "PastOrPresent" -> "must-be-in-the-past"; - case "Future", "FutureOrPresent" -> "must-be-in-the-future"; - default -> hyphenate(annotation); - }; - } - - /** - * The message, with the submitted value never interpolated in. - * - *

A Bean Validation message template can contain {@code ${validatedValue}}. Any message that - * still holds an interpolation marker, or that is absent, is replaced rather than published. - */ - private String safeMessage(ConstraintViolation violation) { - String message = violation.getMessage(); - if (message == null || message.isBlank() || message.contains("${")) { - return "value is not acceptable"; - } - return message; - } - - private static String hyphenate(String annotation) { - return annotation.replaceAll("([a-z])([A-Z])", "$1-$2").toLowerCase(java.util.Locale.ROOT); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/versioning/DeprecationHeaderWriter.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/versioning/DeprecationHeaderWriter.java deleted file mode 100644 index 2a99176f..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/versioning/DeprecationHeaderWriter.java +++ /dev/null @@ -1,70 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.versioning; - -import dev.caskeleton.adapter.inbound.web.http.WebHeaderName; -import java.time.Instant; -import java.time.ZoneOffset; -import java.time.format.DateTimeFormatter; -import java.util.LinkedHashMap; -import java.util.Locale; -import java.util.Map; -import java.util.Objects; - -/** - * Renders the deprecation notice a response carries. - * - *

Headers rather than a body field, because the notice has to reach a client that is not reading - * the body: a cache, a generated SDK, a monitoring probe. Putting it in the payload also means - * every response shape has to carry it, which is how it ends up on some routes and not others. - * - *

{@code Sunset} is an HTTP-date per RFC 8594 — not ISO 8601, which is what a developer writes - * by hand and what a client's date parser then rejects. Rendering it here, once, from an {@code - * Instant} is what keeps the format out of every call site. - */ -public final class DeprecationHeaderWriter { - - /** RFC 8594 requires an IMF-fixdate, in GMT, in the C locale. */ - private static final DateTimeFormatter HTTP_DATE = - DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US) - .withZone(ZoneOffset.UTC); - - /** - * The headers a deprecated route's response carries. - * - * @param route the registered deprecation - * @return header name to value, in a deterministic order - */ - public Map headersFor(DeprecatedRoute route) { - Objects.requireNonNull(route, "route"); - Map headers = new LinkedHashMap<>(); - // RFC 9745 spells the Deprecation value as an HTTP-date too, so a client parses one format. - headers.put(WebHeaderName.DEPRECATION, HTTP_DATE.format(route.deprecatedAt())); - route - .sunsetAt() - .ifPresent(sunset -> headers.put(WebHeaderName.SUNSET, HTTP_DATE.format(sunset))); - StringBuilder link = new StringBuilder(); - link.append('<').append(route.documentation()).append(">; rel=\"deprecation\""); - route - .successor() - .ifPresent( - successor -> - link.append(", <").append(successor).append(">; rel=\"successor-version\"")); - headers.put(WebHeaderName.LINK, link.toString()); - return Map.copyOf(headers); - } - - /** - * The headers for a route, or none when it is not deprecated. - * - * @param policy the registered deprecations - * @param routeTemplate the route being served - */ - public Map headersFor(ApiDeprecationPolicy policy, String routeTemplate) { - Objects.requireNonNull(policy, "policy"); - return policy.find(routeTemplate).map(this::headersFor).orElseGet(Map::of); - } - - /** Renders an instant the way {@code Sunset} and {@code Deprecation} require. */ - public String httpDate(Instant instant) { - return HTTP_DATE.format(Objects.requireNonNull(instant, "instant")); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/webflux/autoconfigure/WebFluxPlatformAutoConfiguration.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/webflux/autoconfigure/WebFluxPlatformAutoConfiguration.java deleted file mode 100644 index 7a694093..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/webflux/autoconfigure/WebFluxPlatformAutoConfiguration.java +++ /dev/null @@ -1,128 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.webflux.autoconfigure; - -import dev.caskeleton.adapter.inbound.web.budget.WebBudgetCatalog; -import dev.caskeleton.adapter.inbound.web.budget.WebBudgetProfileName; -import dev.caskeleton.adapter.inbound.web.budget.WebRequestBudget; -import dev.caskeleton.adapter.inbound.web.error.ProblemCatalog; -import dev.caskeleton.adapter.inbound.web.error.WebProblemFactory; -import dev.caskeleton.adapter.inbound.web.error.WebProblemSanitizer; -import dev.caskeleton.adapter.inbound.web.http.WebMethodPolicy; -import dev.caskeleton.adapter.inbound.web.http.WebUriPolicy; -import dev.caskeleton.adapter.inbound.web.operation.InMemoryWebOperationCatalog; -import dev.caskeleton.adapter.inbound.web.operation.WebOperationCatalog; -import dev.caskeleton.adapter.inbound.web.validation.WebValidationExceptionMapper; -import dev.caskeleton.adapter.inbound.web.webflux.context.WebFluxRequestContextFilter; -import dev.caskeleton.adapter.inbound.web.webflux.guard.BlockingDependencyGuard; -import java.time.Clock; -import java.time.Duration; -import org.springframework.boot.autoconfigure.AutoConfiguration; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.core.Ordered; - -/** - * Wires the web platform into a reactive application. - * - *

{@link ConditionalOnWebApplication} with {@code REACTIVE} is the other half of the mutual - * exclusion the MVC starter declares with {@code SERVLET}. Spring Boot deduces exactly one - * application type, so the two roots can never both activate — which is a stronger guarantee than a - * startup check, because it holds before any bean is created. - * - *

The shared policy beans are declared here as well as in the MVC root rather than being pulled - * from a common configuration. Importing a shared configuration would make the servlet types it - * transitively references resolvable from the reactive starter, which is the dependency the design - * forbids; duplicating six {@code @Bean} methods is the cheaper of the two costs. - */ -@AutoConfiguration -@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE) -@ConditionalOnProperty( - prefix = "backend.web.webflux", - name = "enabled", - havingValue = "true", - matchIfMissing = true) -@EnableConfigurationProperties(WebFluxPlatformSettings.class) -public class WebFluxPlatformAutoConfiguration { - - /** Establishes the request context in the Reactor Context, never a thread-local. */ - @Bean - @ConditionalOnMissingBean - public WebFluxRequestContextFilter webFluxRequestContextFilter(WebFluxPlatformSettings settings) { - return new WebFluxRequestContextFilter( - Clock.systemUTC(), - Duration.ofSeconds(settings.requestBudgetSeconds()), - settings.trustInboundRequestId(), - Ordered.HIGHEST_PRECEDENCE + 10); - } - - /** Refuses a registered blocking dependency reached from an event-loop thread. */ - @Bean - @ConditionalOnMissingBean - @ConditionalOnProperty( - prefix = "backend.web.webflux", - name = "blocking-guard-enabled", - havingValue = "true", - matchIfMissing = true) - public BlockingDependencyGuard blockingDependencyGuard() { - return BlockingDependencyGuard.reactorNetty(); - } - - /** The catalog of registered operations. */ - @Bean - @ConditionalOnMissingBean(WebOperationCatalog.class) - public InMemoryWebOperationCatalog webOperationCatalog() { - return new InMemoryWebOperationCatalog(); - } - - /** The registered request budget profiles. */ - @Bean - @ConditionalOnMissingBean - public WebBudgetCatalog webBudgetCatalog() { - WebBudgetCatalog catalog = new WebBudgetCatalog(); - catalog.register(WebBudgetProfileName.standard(), WebRequestBudget.standard()); - return catalog; - } - - /** The published problem catalog. */ - @Bean - @ConditionalOnMissingBean - public ProblemCatalog webProblemCatalog() { - return ProblemCatalog.standard(); - } - - /** - * The builder used when the reusable problem-document contract is explicitly selected. - * - *

The factory itself is policy data and can exist without publishing that wire shape. The - * reactive exception handler is what activates the contract, and it is opt-in under the same - * cross-stack fixture switch as the servlet handler. - */ - @Bean - @ConditionalOnMissingBean - public WebProblemFactory webProblemFactory(ProblemCatalog catalog) { - return new WebProblemFactory(catalog, new WebProblemSanitizer()); - } - - /** The 400/422 classifier. */ - @Bean - @ConditionalOnMissingBean - public WebValidationExceptionMapper webValidationExceptionMapper() { - return new WebValidationExceptionMapper(); - } - - /** The one accepted path spelling. */ - @Bean - @ConditionalOnMissingBean - public WebUriPolicy webUriPolicy() { - return WebUriPolicy.standard(); - } - - /** The method allowlist. */ - @Bean - @ConditionalOnMissingBean - public WebMethodPolicy webMethodPolicy() { - return WebMethodPolicy.standard(); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/webflux/autoconfigure/WebFluxPlatformSettings.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/webflux/autoconfigure/WebFluxPlatformSettings.java deleted file mode 100644 index 5a2fc1b0..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/webflux/autoconfigure/WebFluxPlatformSettings.java +++ /dev/null @@ -1,42 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.webflux.autoconfigure; - -import org.springframework.boot.context.properties.ConfigurationProperties; - -/** - * The bound settings of the reactive web platform. - * - *

Named {@code Settings} rather than the design's {@code Properties} to satisfy this - * repository's naming convention, which requires every {@code @ConfigurationProperties} type to end - * in {@code Settings} or {@code Policy}. - * - *

{@code blockingGuardEnabled} defaults to on. A guard that has to be switched on is a guard the - * deployments that never read the documentation do not have, and those are the deployments where a - * blocking call on the event loop is most likely to have been written. - * - * @param enabled whether the platform's reactive wiring is installed at all - * @param trustInboundRequestId whether a caller may choose its own request id - * @param blockingGuardEnabled whether a blocking dependency on an event-loop thread fails - * @param requestBudgetSeconds how long a request may run before its deadline expires - */ -@ConfigurationProperties(prefix = "backend.web.webflux") -public record WebFluxPlatformSettings( - Boolean enabled, - Boolean trustInboundRequestId, - Boolean blockingGuardEnabled, - Integer requestBudgetSeconds) { - - public WebFluxPlatformSettings { - enabled = enabled == null || enabled; - trustInboundRequestId = trustInboundRequestId != null && trustInboundRequestId; - blockingGuardEnabled = blockingGuardEnabled == null || blockingGuardEnabled; - requestBudgetSeconds = requestBudgetSeconds == null ? 10 : requestBudgetSeconds; - if (requestBudgetSeconds <= 0) { - throw new IllegalArgumentException("request budget must be positive"); - } - } - - /** The defaults a deployment that configures nothing runs with. */ - public static WebFluxPlatformSettings defaults() { - return new WebFluxPlatformSettings(null, null, null, null); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/webflux/budget/BoundedServerWebExchange.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/webflux/budget/BoundedServerWebExchange.java deleted file mode 100644 index 81757850..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/webflux/budget/BoundedServerWebExchange.java +++ /dev/null @@ -1,79 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.webflux.budget; - -import dev.caskeleton.adapter.inbound.web.budget.WebBudgetMeter; -import dev.caskeleton.adapter.inbound.web.budget.WebBudgetViolation; -import dev.caskeleton.adapter.inbound.web.budget.WebRequestBudget; -import java.util.Objects; -import org.reactivestreams.Publisher; -import org.springframework.core.io.buffer.DataBuffer; -import org.springframework.http.server.reactive.ServerHttpRequest; -import org.springframework.http.server.reactive.ServerHttpRequestDecorator; -import org.springframework.http.server.reactive.ServerHttpResponse; -import org.springframework.http.server.reactive.ServerHttpResponseDecorator; -import org.springframework.web.server.ServerWebExchange; -import org.springframework.web.server.ServerWebExchangeDecorator; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; - -/** - * An exchange whose request and response bodies are bounded as they stream. - * - *

Both sides are counted in {@code doOnNext} on the buffers, so nothing is held to be measured. - * That is not an optimisation here — a reactive body may legitimately never exist in full at any - * one moment, and a bound that required it to would have to buffer the very request it is trying to - * refuse. - */ -public final class BoundedServerWebExchange extends ServerWebExchangeDecorator { - - private final WebBudgetMeter requestMeter; - private final WebBudgetMeter responseMeter; - - /** - * A bounded view of one exchange. - * - * @param delegate the exchange being served - * @param budget the bounds to enforce - */ - public BoundedServerWebExchange(ServerWebExchange delegate, WebRequestBudget budget) { - super(delegate); - Objects.requireNonNull(budget, "budget"); - this.requestMeter = - new WebBudgetMeter(WebBudgetViolation.BODY_TOO_LARGE, budget.maxBodyBytes()); - this.responseMeter = - new WebBudgetMeter(WebBudgetViolation.RESPONSE_TOO_LARGE, budget.maxResponseBytes()); - } - - @Override - public ServerHttpRequest getRequest() { - return new ServerHttpRequestDecorator(super.getRequest()) { - @Override - public Flux getBody() { - return super.getBody().doOnNext(buffer -> requestMeter.add(buffer.readableByteCount())); - } - }; - } - - @Override - public ServerHttpResponse getResponse() { - return new ServerHttpResponseDecorator(super.getResponse()) { - @Override - public Mono writeWith(Publisher body) { - // Counted before the buffer is handed on, so the write that would cross the bound never - // reaches the socket. - return super.writeWith( - Flux.from(body).doOnNext(buffer -> responseMeter.add(buffer.readableByteCount()))); - } - - @Override - public Mono writeAndFlushWith( - Publisher> body) { - return super.writeAndFlushWith( - Flux.from(body) - .map( - part -> - Flux.from(part) - .doOnNext(buffer -> responseMeter.add(buffer.readableByteCount())))); - } - }; - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/webflux/budget/WebFluxBudgetFilter.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/webflux/budget/WebFluxBudgetFilter.java deleted file mode 100644 index 172eca76..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/webflux/budget/WebFluxBudgetFilter.java +++ /dev/null @@ -1,122 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.webflux.budget; - -import dev.caskeleton.adapter.inbound.web.budget.WebBudgetExceededException; -import dev.caskeleton.adapter.inbound.web.budget.WebBudgetMeter; -import dev.caskeleton.adapter.inbound.web.budget.WebBudgetViolation; -import dev.caskeleton.adapter.inbound.web.budget.WebRequestBudget; -import dev.caskeleton.adapter.inbound.web.error.BudgetProblemMapper; -import dev.caskeleton.adapter.inbound.web.error.WebProblem; -import java.net.URI; -import java.nio.charset.StandardCharsets; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import org.springframework.core.io.buffer.DataBuffer; -import org.springframework.http.HttpStatusCode; -import org.springframework.http.MediaType; -import org.springframework.web.server.ServerWebExchange; -import org.springframework.web.server.WebFilter; -import org.springframework.web.server.WebFilterChain; -import reactor.core.publisher.Mono; -import tools.jackson.databind.json.JsonMapper; - -/** - * Enforces the request and response budgets on the reactive stack. - * - *

The reactive stack makes the streaming requirement unavoidable rather than merely advisable: a - * body here is a {@code Flux} that may never be fully in memory at once, so there is no - * "measure it then decide" to be tempted by. The meter runs in {@code doOnNext} on the buffers as - * they pass. - * - *

The reason this is not simply the servlet filter with different types is the response half. - * Once a reactive response is committed the pipeline is already emitting, and the only truthful end - * to an overrun is to fail the publisher — which drops the connection mid-document rather than - * finishing a short one the client would accept. - */ -public final class WebFluxBudgetFilter implements WebFilter { - - private final WebRequestBudget budget; - private final BudgetProblemMapper problems; - private final JsonMapper mapper; - - /** - * A filter over one budget. - * - * @param budget the bounds to enforce - * @param problems renders a crossed bound as a problem document - * @param mapper serializes that document - */ - public WebFluxBudgetFilter( - WebRequestBudget budget, BudgetProblemMapper problems, JsonMapper mapper) { - this.budget = Objects.requireNonNull(budget, "budget"); - this.problems = Objects.requireNonNull(problems, "problems"); - this.mapper = Objects.requireNonNull(mapper, "mapper"); - } - - @Override - public Mono filter(ServerWebExchange exchange, WebFilterChain chain) { - try { - checkCheapDimensions(exchange); - } catch (WebBudgetExceededException exceeded) { - return writeProblem(exchange, exceeded); - } - return chain - .filter(new BoundedServerWebExchange(exchange, budget)) - .onErrorResume( - WebBudgetExceededException.class, - exceeded -> - exchange.getResponse().isCommitted() - // Nothing left to say: the status went out long ago. Propagating ends the - // response mid-document, which is the only signal left that it is incomplete. - ? Mono.error(exceeded) - : writeProblem(exchange, exceeded)); - } - - private void checkCheapDimensions(ServerWebExchange exchange) { - String path = exchange.getRequest().getURI().getRawPath(); - String query = exchange.getRequest().getURI().getRawQuery(); - int uriBytes = - path.getBytes(StandardCharsets.UTF_8).length - + (query == null ? 0 : query.getBytes(StandardCharsets.UTF_8).length + 1); - if (uriBytes > budget.maxUriBytes()) { - throw new WebBudgetExceededException( - WebBudgetViolation.URI_TOO_LONG, uriBytes, budget.maxUriBytes()); - } - - long headerBytes = 0; - for (Map.Entry> header : exchange.getRequest().getHeaders().headerSet()) { - for (String value : header.getValue()) { - headerBytes += header.getKey().length() + (value == null ? 0 : value.length()) + 4; - } - } - if (headerBytes > budget.maxHeaderBytes()) { - throw new WebBudgetExceededException( - WebBudgetViolation.HEADERS_TOO_LARGE, headerBytes, budget.maxHeaderBytes()); - } - - int parameters = exchange.getRequest().getQueryParams().size(); - if (parameters > budget.maxQueryParameters()) { - throw new WebBudgetExceededException( - WebBudgetViolation.TOO_MANY_QUERY_PARAMETERS, parameters, budget.maxQueryParameters()); - } - - new WebBudgetMeter(WebBudgetViolation.BODY_TOO_LARGE, budget.maxBodyBytes()) - .declared(exchange.getRequest().getHeaders().getContentLength()); - } - - private Mono writeProblem(ServerWebExchange exchange, WebBudgetExceededException exceeded) { - WebProblem problem = - problems.problemFor( - exceeded, URI.create(exchange.getRequest().getURI().getRawPath()), "0".repeat(32)); - exchange - .getResponse() - .setStatusCode(HttpStatusCode.valueOf(problems.statusFor(exceeded.violation()))); - exchange.getResponse().getHeaders().setContentType(MediaType.valueOf(WebProblem.MEDIA_TYPE)); - DataBuffer body = - exchange - .getResponse() - .bufferFactory() - .wrap(mapper.writeValueAsString(problem).getBytes(StandardCharsets.UTF_8)); - return exchange.getResponse().writeWith(Mono.just(body)); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/webflux/context/WebFluxRequestContextAccessor.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/webflux/context/WebFluxRequestContextAccessor.java deleted file mode 100644 index d2ffecb9..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/webflux/context/WebFluxRequestContextAccessor.java +++ /dev/null @@ -1,73 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.webflux.context; - -import dev.caskeleton.adapter.inbound.web.core.WebRequestContext; -import dev.caskeleton.adapter.inbound.web.evidence.WebExecutionEvidenceTracker; -import reactor.core.publisher.Mono; -import reactor.util.context.Context; -import reactor.util.context.ContextView; - -/** - * Reads and writes the request context in the Reactor Context. - * - *

The Reactor Context, never a {@code ThreadLocal}. A reactive chain hops threads between every - * operator, so a thread-local is not merely unreliable here — it is actively dangerous, because the - * value it returns belongs to whichever request last ran on that thread. An actor read from a - * thread-local on an event loop is an authorization decision made with somebody else's identity. - * - *

{@link #require} fails the request rather than substituting an anonymous actor. The design - * says so explicitly and the reason is the same: a context loss is a bug in the wiring, and - * answering it with "anonymous" turns that bug into a silent authorization change. - */ -public final class WebFluxRequestContextAccessor { - - /** The Reactor Context key the request context lives under. */ - public static final Class CONTEXT_KEY = WebRequestContext.class; - - /** The Reactor Context key the evidence tracker lives under. */ - public static final Class EVIDENCE_KEY = - WebExecutionEvidenceTracker.class; - - private WebFluxRequestContextAccessor() {} - - /** Puts a request context and its tracker into a Reactor Context. */ - public static Context write( - Context context, WebRequestContext requestContext, WebExecutionEvidenceTracker tracker) { - return context.put(CONTEXT_KEY, requestContext).put(EVIDENCE_KEY, tracker); - } - - /** - * The request context in the current chain. - * - *

Errors rather than completing empty. An empty {@code Mono} here would let a downstream - * {@code switchIfEmpty} quietly supply a default actor. - */ - public static Mono require() { - return Mono.deferContextual( - contextView -> - contextView.hasKey(CONTEXT_KEY) - ? Mono.just(contextView.get(CONTEXT_KEY)) - : Mono.error(contextLost())); - } - - /** The evidence tracker in the current chain. */ - public static Mono requireTracker() { - return Mono.deferContextual( - contextView -> - contextView.hasKey(EVIDENCE_KEY) - ? Mono.just(contextView.get(EVIDENCE_KEY)) - : Mono.error(contextLost())); - } - - /** The request context in a context view, when one is present. */ - public static java.util.Optional find(ContextView contextView) { - return contextView.hasKey(CONTEXT_KEY) - ? java.util.Optional.of(contextView.get(CONTEXT_KEY)) - : java.util.Optional.empty(); - } - - private static IllegalStateException contextLost() { - return new IllegalStateException( - "the web request context is not in the Reactor Context; substituting an anonymous actor" - + " here would turn a wiring bug into a silent authorization change"); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/webflux/context/WebFluxRequestContextFilter.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/webflux/context/WebFluxRequestContextFilter.java deleted file mode 100644 index 88a2668d..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/webflux/context/WebFluxRequestContextFilter.java +++ /dev/null @@ -1,147 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.webflux.context; - -import dev.caskeleton.adapter.inbound.web.core.ActorContext; -import dev.caskeleton.adapter.inbound.web.core.ApiMajorVersion; -import dev.caskeleton.adapter.inbound.web.core.ExternalRequestContext; -import dev.caskeleton.adapter.inbound.web.core.TenantContext; -import dev.caskeleton.adapter.inbound.web.core.WebOperationName; -import dev.caskeleton.adapter.inbound.web.core.WebRequestContext; -import dev.caskeleton.adapter.inbound.web.core.WebRequestId; -import dev.caskeleton.adapter.inbound.web.core.WebTraceId; -import dev.caskeleton.adapter.inbound.web.evidence.WebExecutionEvidenceTracker; -import java.time.Clock; -import java.time.Duration; -import java.time.Instant; -import java.util.Locale; -import java.util.Objects; -import java.util.UUID; -import java.util.regex.Pattern; -import org.springframework.core.Ordered; -import org.springframework.http.server.reactive.ServerHttpRequest; -import org.springframework.web.server.ServerWebExchange; -import org.springframework.web.server.WebFilter; -import org.springframework.web.server.WebFilterChain; -import reactor.core.publisher.Mono; - -/** - * Establishes the request context and evidence tracker for a reactive request. - * - *

Written into the Reactor Context rather than an exchange attribute or a thread-local, because - * the Reactor Context is the only one of the three that follows the chain across the thread hops a - * reactive pipeline makes. - * - *

The identifiers are validated before use for the same reason they are in the servlet filter: - * they reach log lines, and a newline in one splits a log entry so the caller writes the second - * half. - */ -public final class WebFluxRequestContextFilter implements WebFilter, Ordered { - - /** The header a client may propose a request id in. */ - public static final String REQUEST_ID_HEADER = "X-Request-Id"; - - /** The W3C trace context header. */ - public static final String TRACEPARENT_HEADER = "traceparent"; - - private static final Pattern SAFE_IDENTIFIER = Pattern.compile("[A-Za-z0-9._-]{1,128}"); - private static final Pattern TRACEPARENT = - Pattern.compile("[0-9a-f]{2}-([0-9a-f]{32})-[0-9a-f]{16}-[0-9a-f]{2}"); - - private final Clock clock; - private final Duration requestBudget; - private final boolean trustInboundRequestId; - private final int order; - - /** A filter with the platform defaults. */ - public WebFluxRequestContextFilter() { - this(Clock.systemUTC(), Duration.ofSeconds(10), false, Ordered.HIGHEST_PRECEDENCE + 10); - } - - /** - * A filter with explicit policy. - * - * @param clock the clock the deadline is computed from - * @param requestBudget how long a request may run - * @param trustInboundRequestId whether a caller may choose its own request id - * @param order the filter order - */ - public WebFluxRequestContextFilter( - Clock clock, Duration requestBudget, boolean trustInboundRequestId, int order) { - this.clock = Objects.requireNonNull(clock, "clock"); - this.requestBudget = Objects.requireNonNull(requestBudget, "requestBudget"); - this.trustInboundRequestId = trustInboundRequestId; - this.order = order; - } - - @Override - public Mono filter(ServerWebExchange exchange, WebFilterChain chain) { - ServerHttpRequest request = exchange.getRequest(); - Instant receivedAt = clock.instant(); - WebRequestId requestId = resolveRequestId(request); - WebRequestContext context = - new WebRequestContext( - requestId, - resolveTraceId(request), - operationName(request), - new ApiMajorVersion(1), - ActorContext.anonymous(), - TenantContext.none(), - Locale.ENGLISH, - receivedAt, - receivedAt.plus(requestBudget), - externalRequest(request)); - WebExecutionEvidenceTracker tracker = WebExecutionEvidenceTracker.received(); - - exchange.getResponse().getHeaders().set(REQUEST_ID_HEADER, requestId.value()); - return chain - .filter(exchange) - .contextWrite( - reactorContext -> - WebFluxRequestContextAccessor.write(reactorContext, context, tracker)); - } - - @Override - public int getOrder() { - return order; - } - - private WebRequestId resolveRequestId(ServerHttpRequest request) { - if (trustInboundRequestId) { - String proposed = request.getHeaders().getFirst(REQUEST_ID_HEADER); - if (proposed != null && SAFE_IDENTIFIER.matcher(proposed.trim()).matches()) { - return new WebRequestId(proposed.trim()); - } - } - return new WebRequestId(UUID.randomUUID().toString()); - } - - private WebTraceId resolveTraceId(ServerHttpRequest request) { - String traceparent = request.getHeaders().getFirst(TRACEPARENT_HEADER); - if (traceparent != null) { - var matcher = TRACEPARENT.matcher(traceparent.trim()); - if (matcher.matches()) { - return new WebTraceId(matcher.group(1)); - } - } - return new WebTraceId(UUID.randomUUID().toString().replace("-", "")); - } - - /** - * A low-cardinality operation name before routing has happened. - * - *

The method, not the path. A path here would be the raw URI, which carries identifiers and - * would make this the unbounded tag the whole naming rule exists to prevent; the routed operation - * name replaces it once a handler is selected. - */ - private WebOperationName operationName(ServerHttpRequest request) { - String method = request.getMethod().name().toLowerCase(Locale.ROOT); - return new WebOperationName("http." + method); - } - - private ExternalRequestContext externalRequest(ServerHttpRequest request) { - var uri = request.getURI(); - String scheme = uri.getScheme() == null ? "http" : uri.getScheme(); - int port = uri.getPort() > 0 ? uri.getPort() : ("https".equalsIgnoreCase(scheme) ? 443 : 80); - String host = uri.getHost() == null ? "localhost" : uri.getHost(); - return new ExternalRequestContext(scheme, host, port, ""); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/webflux/error/WebFluxProblemExceptionHandler.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/webflux/error/WebFluxProblemExceptionHandler.java deleted file mode 100644 index cd6a2c44..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/webflux/error/WebFluxProblemExceptionHandler.java +++ /dev/null @@ -1,164 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.webflux.error; - -import dev.caskeleton.adapter.inbound.web.error.ProblemCode; -import dev.caskeleton.adapter.inbound.web.error.ValidationIssue; -import dev.caskeleton.adapter.inbound.web.error.WebProblem; -import dev.caskeleton.adapter.inbound.web.error.WebProblemFactory; -import dev.caskeleton.adapter.inbound.web.error.WebResourceNotVisibleException; -import dev.caskeleton.adapter.inbound.web.validation.WebValidationExceptionMapper; -import java.net.URI; -import java.util.List; -import java.util.Objects; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; -import org.springframework.core.Ordered; -import org.springframework.core.annotation.Order; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.ExceptionHandler; -import org.springframework.web.bind.annotation.RestControllerAdvice; -import org.springframework.web.bind.support.WebExchangeBindException; -import org.springframework.web.server.MethodNotAllowedException; -import org.springframework.web.server.ServerWebExchange; -import org.springframework.web.server.ServerWebInputException; -import org.springframework.web.server.UnsupportedMediaTypeStatusException; - -/** - * The reactive twin, mapping the framework's failures to the same catalog. - * - *

A twin rather than a shared class because the exception types genuinely differ: WebFlux raises - * {@code WebExchangeBindException} where MVC raises {@code MethodArgumentNotValidException}, and - * {@code ServerWebInputException} where MVC raises {@code HttpMessageNotReadableException}. There - * is no common supertype that means "the body would not bind". - * - *

What is shared is everything that decides the answer: the catalog, the validation mapper, and - * the codes. So the two handlers cannot disagree about what a failure is called or what status it - * carries — only about which framework exception led there. {@code CrossStackParityTest} is what - * keeps that promise honest. - */ -@RestControllerAdvice -@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE) -// The problem-document contract is reusable but not implicit. The same explicit switch used by the -// servlet fixture selects it here so cross-stack parity is a deliberate test surface rather than a -// second response contract that happens to be active. -@ConditionalOnProperty( - prefix = "spring.mvc.problemdetails", - name = "enabled", - havingValue = "true", - matchIfMissing = false) -@Order(Ordered.HIGHEST_PRECEDENCE + 10) -public class WebFluxProblemExceptionHandler { - - private final WebProblemFactory problems; - private final WebValidationExceptionMapper validationMapper; - - /** - * A handler over the problem catalog. - * - * @param problems the problem document factory - */ - public WebFluxProblemExceptionHandler(WebProblemFactory problems) { - this.problems = Objects.requireNonNull(problems, "problems"); - this.validationMapper = new WebValidationExceptionMapper(); - } - - /** A bound request that violated a declared constraint: 422. */ - @ExceptionHandler(WebExchangeBindException.class) - public ResponseEntity handleValidation( - WebExchangeBindException failure, ServerWebExchange exchange) { - List issues = - failure.getFieldErrors().stream() - .map( - error -> - new ValidationIssue( - "/" + error.getField().replace('.', '/'), - error.getCode() == null ? "INVALID" : error.getCode(), - error.getDefaultMessage() == null - ? "is invalid" - : error.getDefaultMessage())) - .toList(); - return answer(ProblemCode.VALIDATION_FAILED, "the request failed validation", exchange, issues); - } - - /** - * A document that could not be read or could not be bound: 400. - * - *

Declared after the bind handler because {@code WebExchangeBindException} extends {@code - * ServerWebInputException}; without the more specific handler present, every validation failure - * would land here and be published as 400 with the wrong code. - */ - @ExceptionHandler(ServerWebInputException.class) - public ResponseEntity handleUnreadable( - ServerWebInputException failure, ServerWebExchange exchange) { - ProblemCode code = - validationMapper.find(failure.getMostSpecificCause()).orElse(ProblemCode.MALFORMED_REQUEST); - return answer(code, "the request body could not be read", exchange, List.of()); - } - - /** A media type this operation does not read: 415. */ - @ExceptionHandler(UnsupportedMediaTypeStatusException.class) - public ResponseEntity handleMediaType( - UnsupportedMediaTypeStatusException failure, ServerWebExchange exchange) { - return answer( - ProblemCode.UNSUPPORTED_MEDIA_TYPE, - "this operation does not read that media type", - exchange, - List.of()); - } - - /** A method this resource does not serve: 405. */ - @ExceptionHandler(MethodNotAllowedException.class) - public ResponseEntity handleMethod( - MethodNotAllowedException failure, ServerWebExchange exchange) { - WebProblem problem = - problems.create( - ProblemCode.METHOD_NOT_ALLOWED, - "this resource does not serve that method", - URI.create(exchange.getRequest().getURI().getRawPath()), - traceIdOf(exchange), - List.of()); - ResponseEntity.BodyBuilder builder = - ResponseEntity.status(problem.status()) - .contentType(MediaType.valueOf(WebProblem.MEDIA_TYPE)); - if (!failure.getSupportedMethods().isEmpty()) { - // RFC 9110 requires Allow on a 405, and the servlet handler sets it too. A header present on - // one stack and absent on the other is precisely what the parity recording catches. - builder.header( - "Allow", - failure.getSupportedMethods().stream() - .map(Object::toString) - .collect(java.util.stream.Collectors.joining(", "))); - } - return builder.body(problem); - } - - /** The resource is absent, or the caller may not know it exists: 404 either way. */ - @ExceptionHandler(WebResourceNotVisibleException.class) - public ResponseEntity handleNotVisible( - WebResourceNotVisibleException failure, ServerWebExchange exchange) { - return answer( - ProblemCode.RESOURCE_NOT_FOUND, - "no such " + failure.resourceKind() + " is visible", - exchange, - List.of()); - } - - private ResponseEntity answer( - ProblemCode code, String detail, ServerWebExchange exchange, List issues) { - WebProblem problem = - problems.create( - code, - detail, - URI.create(exchange.getRequest().getURI().getRawPath()), - traceIdOf(exchange), - issues); - return ResponseEntity.status(problem.status()) - .contentType(MediaType.valueOf(WebProblem.MEDIA_TYPE)) - .body(problem); - } - - private static String traceIdOf(ServerWebExchange exchange) { - Object traceId = exchange.getAttributes().get("webTraceId"); - return traceId == null ? "0".repeat(32) : traceId.toString(); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/webflux/guard/BlockingCallDetectedException.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/webflux/guard/BlockingCallDetectedException.java deleted file mode 100644 index 1afebbb6..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/webflux/guard/BlockingCallDetectedException.java +++ /dev/null @@ -1,26 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.webflux.guard; - -/** - * A blocking dependency was called from an event-loop thread. - * - *

Thrown rather than logged, and that is the decision worth defending. A blocking call on an - * event loop does not fail — it succeeds, slowly, while holding one of a handful of threads that - * serve every connection the process has. The symptom is a service that is fine under test and - * collapses under concurrency, and by then the cause is several layers away from the stack trace. - * - *

Failing the one request that did it turns an invisible capacity bug into a visible defect on - * the change that introduced it. - */ -public final class BlockingCallDetectedException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - /** - * Creates the failure. - * - * @param message which dependency was called and on which thread - */ - public BlockingCallDetectedException(String message) { - super(message); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/webflux/guard/BlockingDependencyGuard.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/webflux/guard/BlockingDependencyGuard.java deleted file mode 100644 index b467ec7a..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/webflux/guard/BlockingDependencyGuard.java +++ /dev/null @@ -1,79 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.webflux.guard; - -import java.util.Objects; -import java.util.function.Predicate; - -/** - * Refuses a registered blocking dependency when it is reached from an event-loop thread. - * - *

The guard exists because the mistake is silent. Calling a blocking JPA repository from a - * WebFlux handler works: the query returns, the response is written, the test passes. What it also - * does is occupy one of {@code 2 * cores} threads that serve every connection in the process, so - * the service degrades under concurrency in a way that no single request reproduces. - * - *

Thread identity is a predicate rather than a hard-coded name so the same guard covers Reactor - * Netty's {@code reactor-http-nio-*}, a custom loop group and a test harness. Matching on names is - * itself a compromise — there is no portable "am I on an event loop" question to ask — and the - * predicate is the seam that keeps that compromise in one place. - * - *

The Stable profile has no escape hatch. The design puts the controlled blocking bridge in the - * Advanced module, because a bridge available by default is one that gets used by default. - */ -public final class BlockingDependencyGuard { - - /** - * Reactor Netty's event-loop threads, which is the Stable server baseline. - * - *

Three prefixes because the name is not stable across versions. Spring Boot names the server - * loop group {@code webflux-http-*}; a standalone Reactor Netty client or server uses {@code - * reactor-http-*} and {@code reactor-tcp-*}. The first version of this predicate matched only the - * {@code reactor-} forms, so on the actual Stable runtime the guard never fired — a control that - * exists, has a passing unit test, and is reached by nothing. The real-container gate is what - * found it, which is the argument for having that gate. - */ - public static final Predicate REACTOR_NETTY_EVENT_LOOP = - name -> - name != null - && (name.startsWith("reactor-http-") - || name.startsWith("reactor-tcp-") - || name.startsWith("webflux-http-")); - - private final Predicate eventLoopThread; - - /** - * A guard for a specific notion of "event-loop thread". - * - * @param eventLoopThread decides, from a thread name, whether blocking there is forbidden - */ - public BlockingDependencyGuard(Predicate eventLoopThread) { - this.eventLoopThread = Objects.requireNonNull(eventLoopThread, "eventLoopThread"); - } - - /** A guard for the Stable Reactor Netty baseline. */ - public static BlockingDependencyGuard reactorNetty() { - return new BlockingDependencyGuard(REACTOR_NETTY_EVENT_LOOP); - } - - /** - * Refuses the call when the current thread is an event loop. - * - * @param dependency what was about to be called, named for the failure message - * @throws BlockingCallDetectedException when the current thread must not block - */ - public void check(String dependency) { - String threadName = Thread.currentThread().getName(); - if (eventLoopThread.test(threadName)) { - throw new BlockingCallDetectedException( - "blocking dependency '" - + dependency - + "' was called on event-loop thread '" - + threadName - + "'; this succeeds slowly while holding a thread that serves every connection"); - } - } - - /** Whether the current thread is one this guard forbids blocking on. */ - public boolean onEventLoop() { - return eventLoopThread.test(Thread.currentThread().getName()); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/webflux/operation/ReactiveOperationHttpController.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/webflux/operation/ReactiveOperationHttpController.java deleted file mode 100644 index 9c730abe..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/webflux/operation/ReactiveOperationHttpController.java +++ /dev/null @@ -1,108 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.webflux.operation; - -import dev.caskeleton.adapter.inbound.web.core.OwnsAbsoluteWebRoute; -import dev.caskeleton.adapter.inbound.web.core.WebRequestContext; -import dev.caskeleton.adapter.inbound.web.error.WebResourceNotVisibleException; -import dev.caskeleton.adapter.inbound.web.operationasync.OperationId; -import dev.caskeleton.adapter.inbound.web.operationasync.OperationQueryService; -import dev.caskeleton.adapter.inbound.web.operationasync.OperationResource; -import dev.caskeleton.adapter.inbound.web.operationasync.OperationResponse; -import dev.caskeleton.adapter.inbound.web.operationasync.OperationResponseMapper; -import dev.caskeleton.adapter.inbound.web.operationasync.OperationStatus; -import java.util.Objects; -import java.util.Optional; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.DeleteMapping; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; -import reactor.core.publisher.Mono; -import reactor.core.scheduler.Scheduler; - -/** - * The polled operation resource, on the reactive stack. - * - *

Same route, same statuses, same disclosure rule as the servlet controller — those come from - * {@link OperationQueryService}, which both call. What differs is only what has to: the store is - * blocking, so every read is pushed off the event loop. - */ -@OwnsAbsoluteWebRoute -@RestController -// Gated, because the durable operation store only exists when a persistence adapter provides one. -// Without the gate this controller is component-scanned into every deployment and the context -// fails to start with an unsatisfied dependency — which is exactly what happened, and what the -// all-adapters-off startup contract caught. -@ConditionalOnProperty( - prefix = "app.web-platform.durable-operations", - name = "enabled", - havingValue = "true") -@RequestMapping(ReactiveOperationHttpController.BASE_PATH) -public class ReactiveOperationHttpController { - - /** Where operations are published. */ - public static final String BASE_PATH = "/api/v1/operations"; - - private final OperationQueryService operations; - private final Scheduler blockingScheduler; - - /** - * A controller over the query service. - * - * @param operations reads and cancels operations - * @param blockingScheduler where the blocking store is allowed to run - */ - public ReactiveOperationHttpController( - OperationQueryService operations, Scheduler blockingScheduler) { - this.operations = Objects.requireNonNull(operations, "operations"); - this.blockingScheduler = Objects.requireNonNull(blockingScheduler, "blockingScheduler"); - } - - /** Reads one operation. */ - @GetMapping(path = "/{operationId}", produces = MediaType.APPLICATION_JSON_VALUE) - public Mono> get( - @PathVariable String operationId, WebRequestContext context) { - return Mono.fromCallable(() -> operations.find(new OperationId(operationId), context)) - .subscribeOn(blockingScheduler) - .map(ReactiveOperationHttpController::answer); - } - - /** Requests cancellation. */ - @DeleteMapping("/{operationId}") - public Mono> cancel( - @PathVariable String operationId, WebRequestContext context) { - return Mono.fromCallable(() -> operations.cancel(new OperationId(operationId), context)) - .subscribeOn(blockingScheduler) - .map(outcome -> cancelAnswer(outcome.isPresent(), operationId)); - } - - private static ResponseEntity cancelAnswer(boolean visible, String operationId) { - if (!visible) { - throw new WebResourceNotVisibleException("operation"); - } - // A second cancel, and a cancel of work that already finished, both land here. 409 would - // invite a retry that can never succeed; 202 says the same true thing every time. - return ResponseEntity.accepted().header("Location", BASE_PATH + "/" + operationId).build(); - } - - private static ResponseEntity answer(Optional resource) { - if (resource.isEmpty()) { - // Thrown rather than returned, for the same reason as on the servlet side: a bare 404 is a - // failure with nothing in it for a client to branch on. - throw new WebResourceNotVisibleException("operation"); - } - OperationResource operation = resource.get(); - ResponseEntity.BodyBuilder builder = ResponseEntity.ok(); - operation - .retryAfter() - .ifPresent(after -> builder.header("Retry-After", Long.toString(after.toSeconds()))); - if (operation.status() == OperationStatus.SUCCEEDED) { - operation - .resultLocation() - .ifPresent(location -> builder.header("Content-Location", location.toString())); - } - return builder.body(OperationResponseMapper.from(operation)); - } -} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/webflux/throttle/WebFluxThrottleFilter.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/webflux/throttle/WebFluxThrottleFilter.java deleted file mode 100644 index 58b92107..00000000 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/webflux/throttle/WebFluxThrottleFilter.java +++ /dev/null @@ -1,142 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.webflux.throttle; - -import dev.caskeleton.adapter.inbound.web.admission.AdmissionDecision; -import dev.caskeleton.adapter.inbound.web.admission.AdmissionPermit; -import dev.caskeleton.adapter.inbound.web.admission.WebAdmissionController; -import dev.caskeleton.adapter.inbound.web.core.WebRequestContext; -import dev.caskeleton.adapter.inbound.web.error.ThrottleProblemWriter; -import dev.caskeleton.adapter.inbound.web.error.WebProblem; -import dev.caskeleton.adapter.inbound.web.operation.WebOperationProfile; -import dev.caskeleton.adapter.inbound.web.ratelimit.RateLimitDecision; -import dev.caskeleton.adapter.inbound.web.ratelimit.RateLimitFailurePolicy; -import dev.caskeleton.adapter.inbound.web.ratelimit.RateLimitProfileName; -import dev.caskeleton.adapter.inbound.web.ratelimit.WebRateLimiter; -import java.net.URI; -import java.nio.charset.StandardCharsets; -import java.time.Duration; -import java.util.Objects; -import java.util.function.Function; -import org.springframework.core.io.buffer.DataBuffer; -import org.springframework.http.HttpStatusCode; -import org.springframework.http.MediaType; -import org.springframework.web.server.ServerWebExchange; -import org.springframework.web.server.WebFilter; -import org.springframework.web.server.WebFilterChain; -import reactor.core.publisher.Mono; -import reactor.core.scheduler.Scheduler; -import tools.jackson.databind.json.JsonMapper; - -/** - * The reactive quota-then-capacity filter. - * - *

Same order and same answers as the servlet one; two things differ and both are forced by the - * stack. - * - *

The limiter is a network call, so it runs on the blocking scheduler rather than the event - * loop. And the admission permit is released in {@code doFinally} rather than a try-with-resources: - * the request is not finished when {@code filter} returns, it is finished when the returned - * publisher terminates. Releasing at the end of the method would hand the slot back while the - * request is still running, and the concurrency bound would mean nothing at all — a mistake that is - * invisible until the service is under enough load for it to matter. - */ -public final class WebFluxThrottleFilter implements WebFilter { - - private final WebRateLimiter limiter; - private final WebAdmissionController admission; - private final Function profiles; - private final Function contexts; - private final RateLimitFailurePolicy failurePolicy; - private final ThrottleProblemWriter problems; - private final JsonMapper mapper; - private final Scheduler blockingScheduler; - - /** - * A filter over one limiter and one admission controller. - * - * @param limiter the caller quota - * @param admission the service capacity - * @param profiles resolves the operation profile for an exchange - * @param contexts resolves the request context - * @param failurePolicy what to do when the limiter's store is unreachable - * @param problems renders the refusals - * @param mapper serializes them - * @param blockingScheduler where the limiter is allowed to block - */ - public WebFluxThrottleFilter( - WebRateLimiter limiter, - WebAdmissionController admission, - Function profiles, - Function contexts, - RateLimitFailurePolicy failurePolicy, - ThrottleProblemWriter problems, - JsonMapper mapper, - Scheduler blockingScheduler) { - this.limiter = Objects.requireNonNull(limiter, "limiter"); - this.admission = Objects.requireNonNull(admission, "admission"); - this.profiles = Objects.requireNonNull(profiles, "profiles"); - this.contexts = Objects.requireNonNull(contexts, "contexts"); - this.failurePolicy = Objects.requireNonNull(failurePolicy, "failurePolicy"); - this.problems = Objects.requireNonNull(problems, "problems"); - this.mapper = Objects.requireNonNull(mapper, "mapper"); - this.blockingScheduler = Objects.requireNonNull(blockingScheduler, "blockingScheduler"); - } - - @Override - public Mono filter(ServerWebExchange exchange, WebFilterChain chain) { - WebOperationProfile profile = profiles.apply(exchange); - WebRequestContext context = contexts.apply(exchange); - - return Mono.fromCallable(() -> evaluateQuota(context)) - .subscribeOn(blockingScheduler) - .flatMap( - quota -> { - if (!quota.allowed()) { - return write( - exchange, - problems.quotaStatus(), - problems.quotaExhausted( - URI.create(exchange.getRequest().getURI().getRawPath()), - context.traceId().value()), - quota.retryAfter().orElseThrow()); - } - AdmissionDecision admitted = admission.admit(profile.admission()); - if (!admitted.admitted()) { - return write( - exchange, - problems.capacityStatus(), - problems.capacityExhausted( - URI.create(exchange.getRequest().getURI().getRawPath()), - context.traceId().value()), - admitted.retryAfter().orElseThrow()); - } - AdmissionPermit permit = admitted.permit().orElseThrow(); - return chain.filter(exchange).doFinally(signal -> permit.close()); - }); - } - - private RateLimitDecision evaluateQuota(WebRequestContext context) { - try { - return limiter.evaluate(context, RateLimitProfileName.standard()); - } catch (RuntimeException limiterUnavailable) { - return failurePolicy == RateLimitFailurePolicy.FAIL_CLOSED - ? RateLimitDecision.refused(1, context.receivedAt().plusSeconds(1), Duration.ofSeconds(1)) - : RateLimitDecision.allowed(1, 1, context.receivedAt().plusSeconds(1)); - } - } - - private Mono write( - ServerWebExchange exchange, int status, WebProblem problem, Duration retryAfter) { - exchange.getResponse().setStatusCode(HttpStatusCode.valueOf(status)); - exchange.getResponse().getHeaders().setContentType(MediaType.valueOf(WebProblem.MEDIA_TYPE)); - exchange - .getResponse() - .getHeaders() - .set("Retry-After", ThrottleProblemWriter.retryAfterSeconds(retryAfter)); - DataBuffer body = - exchange - .getResponse() - .bufferFactory() - .wrap(mapper.writeValueAsString(problem).getBytes(StandardCharsets.UTF_8)); - return exchange.getResponse().writeWith(Mono.just(body)); - } -} diff --git a/src/adapter/inbound/web/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/src/adapter/inbound/web/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports index 447164ed..72e65cb6 100644 --- a/src/adapter/inbound/web/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports +++ b/src/adapter/inbound/web/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports @@ -1,2 +1,2 @@ +dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebAdapterAutoConfiguration dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebMvcPlatformAutoConfiguration -dev.caskeleton.adapter.inbound.web.webflux.autoconfigure.WebFluxPlatformAutoConfiguration diff --git a/src/adapter/inbound/web/src/main/resources/META-INF/web/problem-catalog.yaml b/src/adapter/inbound/web/src/main/resources/META-INF/web/problem-catalog.yaml deleted file mode 100644 index f5d40ef0..00000000 --- a/src/adapter/inbound/web/src/main/resources/META-INF/web/problem-catalog.yaml +++ /dev/null @@ -1,99 +0,0 @@ -# The published problem catalog: every failure this API reports, with its stable type URI and the -# HTTP status it is always answered with. -# -# This is the rendering of ProblemCatalog.standard(). ProblemCatalogTest asserts the two agree, -# because a client author reads this file and a document that drifts from the code is quoted as if -# it were true. -# -# DEPENDENCY_FAILURE is 502 and DEPENDENCY_TIMEOUT is 504 rather than either being chosen per call: -# a 504 tells a caller the request may still be running behind the gateway, and a 502 tells it the -# request is not. -problems: - MALFORMED_REQUEST: - type: https://problems.caskeleton.dev/web/malformed-request - title: Malformed request - status: 400 - BINDING_FAILED: - type: https://problems.caskeleton.dev/web/binding-failed - title: Request could not be bound - status: 400 - VALIDATION_FAILED: - type: https://problems.caskeleton.dev/web/validation-failed - title: Request failed validation - status: 422 - AUTHENTICATION_REQUIRED: - type: https://problems.caskeleton.dev/web/authentication-required - title: Authentication required - status: 401 - ACCESS_DENIED: - type: https://problems.caskeleton.dev/web/access-denied - title: Access denied - status: 403 - RESOURCE_NOT_FOUND: - type: https://problems.caskeleton.dev/web/resource-not-found - title: Resource not found - status: 404 - RESOURCE_CONFLICT: - type: https://problems.caskeleton.dev/web/resource-conflict - title: Resource conflict - status: 409 - PRECONDITION_FAILED: - type: https://problems.caskeleton.dev/web/precondition-failed - title: Precondition failed - status: 412 - IDEMPOTENCY_KEY_REQUIRED: - type: https://problems.caskeleton.dev/web/idempotency-key-required - title: Idempotency key required - status: 400 - IDEMPOTENCY_KEY_REUSED: - type: https://problems.caskeleton.dev/web/idempotency-key-reused - title: Idempotency key reused - status: 422 - IDEMPOTENCY_REQUEST_IN_PROGRESS: - type: https://problems.caskeleton.dev/web/idempotency-request-in-progress - title: Request already in progress - status: 409 - RATE_LIMITED: - type: https://problems.caskeleton.dev/web/rate-limited - title: Rate limit exceeded - status: 429 - ADMISSION_REJECTED: - type: https://problems.caskeleton.dev/web/admission-rejected - title: Service is shedding load - status: 503 - DEPENDENCY_FAILURE: - type: https://problems.caskeleton.dev/web/dependency-failure - title: A dependency failed - status: 502 - DEPENDENCY_TIMEOUT: - type: https://problems.caskeleton.dev/web/dependency-timeout - title: A dependency timed out - status: 504 - METHOD_NOT_ALLOWED: - type: https://problems.caskeleton.dev/web/method-not-allowed - title: Method not allowed - status: 405 - NOT_ACCEPTABLE: - type: https://problems.caskeleton.dev/web/not-acceptable - title: No acceptable representation - status: 406 - RESOURCE_GONE: - type: https://problems.caskeleton.dev/web/resource-gone - title: Resource is gone - status: 410 - REQUEST_TOO_LARGE: - type: https://problems.caskeleton.dev/web/request-too-large - title: Request exceeds a size bound - status: 413 - UNSUPPORTED_MEDIA_TYPE: - type: https://problems.caskeleton.dev/web/unsupported-media-type - title: Unsupported media type - status: 415 - RESPONSE_TOO_LARGE: - type: https://problems.caskeleton.dev/web/response-too-large - title: Response exceeds a size bound - status: 500 - INTERNAL_ERROR: - type: https://problems.caskeleton.dev/web/internal-error - title: Internal error - status: 500 diff --git a/src/adapter/inbound/web/src/nginxProxyTest/java/dev/caskeleton/adapter/inbound/web/testkit/proxy/NginxProxyContractIT.java b/src/adapter/inbound/web/src/nginxProxyTest/java/dev/caskeleton/adapter/inbound/web/testkit/proxy/NginxProxyContractIT.java deleted file mode 100644 index 7960ff4e..00000000 --- a/src/adapter/inbound/web/src/nginxProxyTest/java/dev/caskeleton/adapter/inbound/web/testkit/proxy/NginxProxyContractIT.java +++ /dev/null @@ -1,186 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.testkit.proxy; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.Map; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.web.server.LocalServerPort; -import org.springframework.test.context.ActiveProfiles; -import org.testcontainers.junit.jupiter.Testcontainers; - -/** - * The platform behind a real reverse proxy. - * - *

Everything here is about the seam between two systems, and the seam is exactly what a unit - * test of either side cannot reach. The application's forwarded-header handling has thorough unit - * coverage and it is all conditional on what the proxy actually sends; the proxy configuration is a - * file nothing verifies. A spoofed host that the application correctly refuses is worthless if the - * proxy passes the client's value through under a header name the application trusts, and no test - * on either side alone would notice. - */ -@SpringBootTest( - classes = ProxyFixtureApplication.class, - webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -@ActiveProfiles("web-contract") -@Testcontainers -class NginxProxyContractIT { - - private static NginxProxyHarness proxy; - - @LocalServerPort private int port; - - @BeforeAll - static void requireDocker() { - // Stated rather than skipped. A lane that quietly passes without a container runtime has been - // certifying nothing since whenever Docker last broke, and nobody finds out. - org.junit.jupiter.api.Assertions.assertTrue( - NginxProxyHarness.dockerAvailable(), - "this lane needs a container runtime; it certifies Nginx's own behaviour and cannot be" - + " simulated"); - } - - @AfterAll - static void stopProxy() { - if (proxy != null) { - proxy.close(); - proxy = null; - } - } - - private NginxProxyHarness proxy() { - if (proxy == null) { - proxy = new NginxProxyHarness(port); - } - return proxy; - } - - @Test - @DisplayName("an attacker cannot override the forwarded host") - void attackerCannotOverrideForwardedHost() { - // The header is set by the proxy, not added to. Appending would leave the application to pick - // between two values, and the conventional pick is the first — the attacker's. - NginxProxyHarness.Response response = - proxy() - .get( - "/dev-api" + ProxyFixtureController.EXTERNAL_URI_PATH, - Map.of("X-Forwarded-Host", "evil.example")); - - assertThat(response.status()).isEqualTo(200); - assertThat(response.body()).startsWith("https://hyeonworks.com"); - assertThat(response.body()).doesNotContain("evil.example"); - } - - @Test - @DisplayName("an attacker cannot override the forwarded scheme") - void attackerCannotDowngradeTheForwardedScheme() { - // A downgraded scheme is how an absolute link in a Location header becomes plaintext, and the - // browser follows it before anything notices. - NginxProxyHarness.Response response = - proxy() - .get( - "/api" + ProxyFixtureController.EXTERNAL_URI_PATH, - Map.of("X-Forwarded-Proto", "http")); - - assertThat(response.body()).startsWith("https://"); - } - - @Test - @DisplayName("an attacker cannot forge the client address") - void attackerCannotForgeTheClientAddress() { - // The address the rate limiter and the audit log key on. A client that could set it would be - // able to spend somebody else's quota and sign somebody else's actions. - NginxProxyHarness.Response response = - proxy() - .get( - "/api" + ProxyFixtureController.CLIENT_ADDRESS_PATH, - Map.of("X-Forwarded-For", "203.0.113.9")); - - assertThat(response.body()).isNotEqualTo("203.0.113.9"); - } - - @Test - @DisplayName("a client-sent RFC 7239 Forwarded header is cleared") - void standardForwardedHeaderIsCleared() { - // The header everyone forgets. A framework that prefers RFC 7239 over the X- headers would - // take the client's word over the proxy's, and every X-Forwarded-* rule above would be intact - // and irrelevant. - NginxProxyHarness.Response response = - proxy() - .get( - "/api" + ProxyFixtureController.EXTERNAL_URI_PATH, - Map.of("Forwarded", "host=evil.example;proto=http")); - - assertThat(response.body()).startsWith("https://hyeonworks.com"); - assertThat(response.body()).doesNotContain("evil.example"); - } - - @Test - @DisplayName("each public prefix maps to the application path exactly once") - void prefixIsAppliedExactlyOnce() { - // Applied twice and every route 404s; stripped twice and the external URLs the application - // publishes lose the prefix, so the links it hands out do not resolve. - assertThat(proxy().get("/api" + ProxyFixtureController.ARRIVED_PATH, Map.of()).body()) - .isEqualTo(ProxyFixtureController.ARRIVED_PATH); - assertThat(proxy().get("/dev-api" + ProxyFixtureController.ARRIVED_PATH, Map.of()).body()) - .isEqualTo(ProxyFixtureController.ARRIVED_PATH); - } - - @Test - @DisplayName("the published URI carries the prefix the request came in on") - void publishedUriCarriesTheIncomingPrefix() { - assertThat(proxy().get("/api" + ProxyFixtureController.EXTERNAL_URI_PATH, Map.of()).body()) - .isEqualTo("https://hyeonworks.com/api/v1/result"); - assertThat(proxy().get("/dev-api" + ProxyFixtureController.EXTERNAL_URI_PATH, Map.of()).body()) - .isEqualTo("https://hyeonworks.com/dev-api/v1/result"); - } - - @Test - @DisplayName("a client cannot inject its own prefix") - void clientCannotInjectAPrefix() { - // X-Forwarded-Prefix is set per location, so a client's value is replaced. Left to accumulate, - // it is a path-traversal primitive in every link the application publishes. - NginxProxyHarness.Response response = - proxy() - .get( - "/api" + ProxyFixtureController.EXTERNAL_URI_PATH, - Map.of("X-Forwarded-Prefix", "/evil")); - - assertThat(response.body()).isEqualTo("https://hyeonworks.com/api/v1/result"); - } - - @Test - @DisplayName("a body within the proxy's limit reaches the application") - void bodyWithinTheProxyLimitArrives() { - NginxProxyHarness.Response response = - proxy().post("/api" + ProxyFixtureController.ECHO_PATH, 1024); - - assertThat(response.status()).isEqualTo(200); - assertThat(response.body()).isEqualTo("1024"); - } - - @Test - @DisplayName("a body over the proxy's limit is refused at the proxy") - void oversizedBodyIsRefusedAtTheProxy() { - // The layering the design asks to be written down: this one never reaches the application, so - // the client gets Nginx's HTML rather than a problem document. That is the consequence of - // setting the edge limit below the application's, and it is why the manifest in - // docs/web/repository-adaptation.md §8 says where each bound belongs. - NginxProxyHarness.Response response = - proxy().post("/api" + ProxyFixtureController.ECHO_PATH, 3 * 1024 * 1024); - - assertThat(response.status()).isEqualTo(413); - } - - @Test - @DisplayName("an unknown prefix is not proxied at all") - void unknownPrefixIsNotProxied() { - // Only the declared prefixes are routed. A catch-all location would expose the application's - // whole path space under a name nobody published. - assertThat(proxy().get("/internal" + ProxyFixtureController.ARRIVED_PATH, Map.of()).status()) - .isEqualTo(404); - } -} diff --git a/src/adapter/inbound/web/src/nginxProxyTest/java/dev/caskeleton/adapter/inbound/web/testkit/proxy/NginxProxyHarness.java b/src/adapter/inbound/web/src/nginxProxyTest/java/dev/caskeleton/adapter/inbound/web/testkit/proxy/NginxProxyHarness.java deleted file mode 100644 index 1c659d3b..00000000 --- a/src/adapter/inbound/web/src/nginxProxyTest/java/dev/caskeleton/adapter/inbound/web/testkit/proxy/NginxProxyHarness.java +++ /dev/null @@ -1,151 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.testkit.proxy; - -import java.io.IOException; -import java.io.InputStream; -import java.net.HttpURLConnection; -import java.net.URI; -import java.nio.charset.StandardCharsets; -import java.util.Map; -import org.testcontainers.containers.GenericContainer; -import org.testcontainers.images.builder.Transferable; -import org.testcontainers.utility.DockerImageName; - -/** - * A real Nginx in front of the application under test. - * - *

Real, because every property this lane checks is a property of Nginx's own behaviour. "{@code - * proxy_set_header} replaces rather than appends" and "a trailing slash on {@code proxy_pass} - * strips the location prefix" are facts about the proxy; asserting them against a hand-written stub - * would be asserting what the author already believed. - * - *

The application runs in this JVM. Starting it in a container too would need an image built per - * run, and it would put the thing under test behind a second layer whose failures look identical to - * the proxy's. - */ -public final class NginxProxyHarness implements AutoCloseable { - - private static final DockerImageName IMAGE = DockerImageName.parse("nginx:1.27-alpine"); - - private final GenericContainer nginx; - - /** - * Starts Nginx pointed at a locally running application. - * - * @param applicationPort the port the application is listening on - */ - @SuppressWarnings("resource") - public NginxProxyHarness(int applicationPort) { - // `host.docker.internal` is not resolvable on stock Linux Docker, so the host gateway is added - // explicitly. Without it the lane fails with a connection refused inside the container, which - // reads as an Nginx configuration error and is not one. - this.nginx = - new GenericContainer<>(IMAGE) - .withExposedPorts(8080) - .withExtraHost("host.docker.internal", "host-gateway") - .withCopyToContainer( - Transferable.of(configuration(applicationPort)), "/etc/nginx/nginx.conf") - .withCopyToContainer( - Transferable.of(resource("nginx/proxy_headers.conf")), - "/etc/nginx/proxy_headers.conf"); - nginx.start(); - } - - /** The base URL callers reach the proxy on. */ - public String baseUrl() { - return "http://" + nginx.getHost() + ":" + nginx.getMappedPort(8080); - } - - /** - * Sends one request through the proxy. - * - * @param path the path, including its public prefix - * @param headers headers the client sends, including any it is trying to spoof - */ - public Response get(String path, Map headers) { - return send("GET", path, headers, null); - } - - /** - * Posts a body of the given size through the proxy. - * - * @param path the path, including its public prefix - * @param bodyBytes how large a body to send - */ - public Response post(String path, int bodyBytes) { - return send( - "POST", path, Map.of("Content-Type", "application/octet-stream"), new byte[bodyBytes]); - } - - private Response send(String method, String path, Map headers, byte[] body) { - try { - HttpURLConnection connection = - (HttpURLConnection) URI.create(baseUrl() + path).toURL().openConnection(); - connection.setRequestMethod(method); - connection.setConnectTimeout(10_000); - connection.setReadTimeout(30_000); - headers.forEach(connection::setRequestProperty); - if (body != null) { - connection.setDoOutput(true); - connection.setFixedLengthStreamingMode(body.length); - try (java.io.OutputStream out = connection.getOutputStream()) { - out.write(body); - } catch (IOException refusedMidWrite) { - // Nginx can refuse an oversized body before the client finishes sending it. That is the - // intended behaviour, and the response still carries the status. - } - } - try { - int status = connection.getResponseCode(); - String text; - try (InputStream stream = - status >= 400 ? connection.getErrorStream() : connection.getInputStream()) { - text = stream == null ? "" : new String(stream.readAllBytes(), StandardCharsets.UTF_8); - } - return new Response(status, text.trim()); - } finally { - connection.disconnect(); - } - } catch (IOException e) { - throw new IllegalStateException(method + " " + path + " through the proxy failed", e); - } - } - - @Override - public void close() { - nginx.stop(); - } - - /** Whether a container runtime is available. */ - public static boolean dockerAvailable() { - try { - return org.testcontainers.DockerClientFactory.instance().isDockerAvailable(); - } catch (RuntimeException unavailable) { - return false; - } - } - - private static String configuration(int applicationPort) { - return resource("nginx/nginx.conf") - .replace("APPLICATION_HOST", "host.docker.internal") - .replace("APPLICATION_PORT", Integer.toString(applicationPort)); - } - - private static String resource(String name) { - try (InputStream stream = NginxProxyHarness.class.getClassLoader().getResourceAsStream(name)) { - if (stream == null) { - throw new IllegalStateException(name + " is missing from the lane's resources"); - } - return new String(stream.readAllBytes(), StandardCharsets.UTF_8); - } catch (IOException e) { - throw new IllegalStateException(name + " could not be read", e); - } - } - - /** - * One response, as the client saw it. - * - * @param status the HTTP status - * @param body the response body - */ - public record Response(int status, String body) {} -} diff --git a/src/adapter/inbound/web/src/nginxProxyTest/java/dev/caskeleton/adapter/inbound/web/testkit/proxy/ProxyFixtureApplication.java b/src/adapter/inbound/web/src/nginxProxyTest/java/dev/caskeleton/adapter/inbound/web/testkit/proxy/ProxyFixtureApplication.java deleted file mode 100644 index cc0a876b..00000000 --- a/src/adapter/inbound/web/src/nginxProxyTest/java/dev/caskeleton/adapter/inbound/web/testkit/proxy/ProxyFixtureApplication.java +++ /dev/null @@ -1,37 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.testkit.proxy; - -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.web.SecurityFilterChain; - -/** - * The application Nginx proxies to. - * - *

It binds on all interfaces rather than loopback, because the proxy reaches it from inside a - * container network. A loopback-only bind is the first thing that makes this lane fail with a - * connection refused that looks like a configuration error in Nginx. - */ -// @Configuration, not @TestConfiguration: this source set is never on the application's runtime -// classpath, so nothing here can be component-scanned into a deployment — and @TestConfiguration -// types are not accepted by @SpringBootTest(classes = ...). -@Configuration(proxyBeanMethods = false) -@EnableAutoConfiguration -@Import(ProxyFixtureController.class) -public class ProxyFixtureApplication { - - /** - * Every fixture route is open. - * - *

The leaf carries the security starter. This is a fixture in the test tree and reaches no - * deployment. - */ - @Bean - SecurityFilterChain proxyFixtureSecurity(HttpSecurity http) throws Exception { - return http.csrf(csrf -> csrf.disable()) - .authorizeHttpRequests(requests -> requests.anyRequest().permitAll()) - .build(); - } -} diff --git a/src/adapter/inbound/web/src/nginxProxyTest/resources/nginx/nginx.conf b/src/adapter/inbound/web/src/nginxProxyTest/resources/nginx/nginx.conf deleted file mode 100644 index e03af04d..00000000 --- a/src/adapter/inbound/web/src/nginxProxyTest/resources/nginx/nginx.conf +++ /dev/null @@ -1,45 +0,0 @@ -# The reverse proxy the platform is actually deployed behind. -# -# Two properties matter here and neither can be tested without a real nginx: -# -# 1. Forwarded headers a client sends are DISCARDED, not merged. `proxy_set_header` replaces the -# header outright, so `X-Forwarded-Host: evil.example` from a client never reaches the -# application. A proxy that appended instead would leave the application to decide which of -# two values to trust, and the conventional choice is the first one — the attacker's. -# -# 2. Each public prefix maps to the application path exactly once. `/api/` and `/dev-api/` both -# proxy to the same upstream root, and the trailing slash on `proxy_pass` is what strips the -# prefix. Without it the application sees `/api/api/v1/...` and every route 404s; stripped -# twice, the prefix vanishes from the external URLs the application publishes. -events {} - -http { - # nginx resolves `upstream` names once at startup. The application under test binds a random - # port, so the address is templated in before the file is copied into the container. - upstream application { - server APPLICATION_HOST:APPLICATION_PORT; - } - - server { - listen 8080; - server_name hyeonworks.com; - - # Refused here rather than in the application. A request line long enough to matter should - # never occupy an application thread, and nginx answers it before one is allocated. - large_client_header_buffers 4 8k; - client_max_body_size 2m; - proxy_read_timeout 30s; - - location /api/ { - include /etc/nginx/proxy_headers.conf; - proxy_set_header X-Forwarded-Prefix /api; - proxy_pass http://application/; - } - - location /dev-api/ { - include /etc/nginx/proxy_headers.conf; - proxy_set_header X-Forwarded-Prefix /dev-api; - proxy_pass http://application/; - } - } -} diff --git a/src/adapter/inbound/web/src/nginxProxyTest/resources/nginx/proxy_headers.conf b/src/adapter/inbound/web/src/nginxProxyTest/resources/nginx/proxy_headers.conf deleted file mode 100644 index 8ade88cf..00000000 --- a/src/adapter/inbound/web/src/nginxProxyTest/resources/nginx/proxy_headers.conf +++ /dev/null @@ -1,22 +0,0 @@ -# The authoritative forwarded headers, included by every location. -# -# Included rather than declared once at the server level, because nginx's inheritance rule for -# array directives is replacement, not merging: a single `proxy_set_header` inside a `location` -# discards every `proxy_set_header` inherited from `server`. A configuration that sets the security -# headers at the server level and then adds one per-location header silently sends none of the -# security headers — and the only symptom is the application quietly trusting the client again. -# -# Every line SETS, never adds. An inbound X-Forwarded-For from a client is replaced by -# $remote_addr, and an inbound X-Forwarded-Host by this deployment's public name. -proxy_set_header Host $host; -proxy_set_header X-Real-IP $remote_addr; -proxy_set_header X-Forwarded-For $remote_addr; -proxy_set_header X-Forwarded-Host hyeonworks.com; -# This deployment terminates TLS at the edge, so the scheme the application sees is a fact about -# the edge and not about the connection nginx opened to the upstream. -proxy_set_header X-Forwarded-Proto https; -proxy_set_header X-Forwarded-Port 443; -# `Forwarded` is the standardised header and clients send it too. Clearing it is required: a -# framework that reads RFC 7239 in preference to the X- headers would otherwise take the client's -# word over the proxy's, leaving every rule above intact and irrelevant. -proxy_set_header Forwarded ""; diff --git a/src/adapter/inbound/web/src/systemTest/java/dev/caskeleton/adapter/inbound/web/testkit/budget/TomcatWebBudgetIT.java b/src/adapter/inbound/web/src/systemTest/java/dev/caskeleton/adapter/inbound/web/testkit/budget/TomcatWebBudgetIT.java deleted file mode 100644 index 3e5d8011..00000000 --- a/src/adapter/inbound/web/src/systemTest/java/dev/caskeleton/adapter/inbound/web/testkit/budget/TomcatWebBudgetIT.java +++ /dev/null @@ -1,30 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.testkit.budget; - -import dev.caskeleton.webtestkit.BudgetFixtureApplication; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.web.server.LocalServerPort; -import org.springframework.test.context.ActiveProfiles; - -/** - * Budget enforcement on the servlet default, over a real socket. - * - *

A real socket is the only place chunked transfer and a truncated response exist. MockMvc has - * neither, so it would report the two hardest cases in this contract as passing without having - * exercised them. - */ -@SpringBootTest( - classes = BudgetFixtureApplication.class, - webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, - // The budget handler is gated on this property. Turning it on here rather than defaulting it - // on keeps the production default off: a control that is on by default is one nobody notices. - properties = "backend.web.budgets.enabled=true") -@ActiveProfiles("web-contract") -class TomcatWebBudgetIT extends WebBudgetContract { - - @LocalServerPort private int port; - - @Override - protected HttpBudgetFixture fixture() { - return new HttpBudgetFixture(port); - } -} diff --git a/src/adapter/inbound/web/src/systemTest/java/dev/caskeleton/adapter/inbound/web/testkit/contract/TomcatContractRecordingIT.java b/src/adapter/inbound/web/src/systemTest/java/dev/caskeleton/adapter/inbound/web/testkit/contract/TomcatContractRecordingIT.java deleted file mode 100644 index 625c9680..00000000 --- a/src/adapter/inbound/web/src/systemTest/java/dev/caskeleton/adapter/inbound/web/testkit/contract/TomcatContractRecordingIT.java +++ /dev/null @@ -1,26 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.testkit.contract; - -import dev.caskeleton.webtestkit.ContractFixtureApplication; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.web.server.LocalServerPort; -import org.springframework.test.context.ActiveProfiles; - -/** Records the wire contract as the servlet default serves it. */ -@SpringBootTest( - classes = ContractFixtureApplication.class, - webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -@ActiveProfiles("web-contract") -class TomcatContractRecordingIT extends WebPlatformContractRecording { - - @LocalServerPort private int port; - - @Override - protected WebContractFixture fixture() { - return new WebContractFixture(port); - } - - @Override - protected String laneName() { - return "tomcat"; - } -} diff --git a/src/adapter/inbound/web/src/systemTest/java/dev/caskeleton/adapter/inbound/web/testkit/operation/TomcatOperationHttpIT.java b/src/adapter/inbound/web/src/systemTest/java/dev/caskeleton/adapter/inbound/web/testkit/operation/TomcatOperationHttpIT.java deleted file mode 100644 index 39207a76..00000000 --- a/src/adapter/inbound/web/src/systemTest/java/dev/caskeleton/adapter/inbound/web/testkit/operation/TomcatOperationHttpIT.java +++ /dev/null @@ -1,26 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.testkit.operation; - -import dev.caskeleton.webtestkit.ContractFixtureApplication; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.web.server.LocalServerPort; -import org.springframework.test.context.ActiveProfiles; - -/** - * The operation resource contract on the servlet default, over a real socket. - * - *

Real, because every assertion here is about a response header, and MockMvc reports headers the - * container is free to drop or rewrite. - */ -@SpringBootTest( - classes = ContractFixtureApplication.class, - webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -@ActiveProfiles("web-contract") -class TomcatOperationHttpIT extends OperationHttpContract { - - @LocalServerPort private int port; - - @Override - protected HttpOperationFixture fixture() { - return new HttpOperationFixture(port); - } -} diff --git a/src/adapter/inbound/web/src/systemTest/java/dev/caskeleton/adapter/inbound/web/testkit/throttle/TomcatWebThrottleIT.java b/src/adapter/inbound/web/src/systemTest/java/dev/caskeleton/adapter/inbound/web/testkit/throttle/TomcatWebThrottleIT.java deleted file mode 100644 index 3efaf4e3..00000000 --- a/src/adapter/inbound/web/src/systemTest/java/dev/caskeleton/adapter/inbound/web/testkit/throttle/TomcatWebThrottleIT.java +++ /dev/null @@ -1,41 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.testkit.throttle; - -import dev.caskeleton.webtestkit.ThrottleFixtureApplication; -import org.junit.jupiter.api.AfterEach; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.web.server.LocalServerPort; -import org.springframework.test.context.ActiveProfiles; - -/** - * Quota and capacity refusals on the servlet default, over a real socket. - * - *

Real, because the capacity case needs one request to genuinely occupy a slot while another - * arrives. A mock dispatcher runs them one after the other, so the second never meets a full - * service and the 503 case would pass without ever having been exercised. - */ -@SpringBootTest( - classes = ThrottleFixtureApplication.class, - webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -@ActiveProfiles("web-contract") -class TomcatWebThrottleIT extends WebThrottleHttpContract { - - @LocalServerPort private int port; - - private HttpThrottleFixture fixture; - - @Override - protected HttpThrottleFixture fixture() { - if (fixture == null) { - fixture = new HttpThrottleFixture(port); - } - return fixture; - } - - @AfterEach - void closeFixture() { - if (fixture != null) { - fixture.close(); - fixture = null; - } - } -} diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/admin/platform/WebPlatformStartupValidatorTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/admin/platform/WebPlatformStartupValidatorTest.java deleted file mode 100644 index 409278c8..00000000 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/admin/platform/WebPlatformStartupValidatorTest.java +++ /dev/null @@ -1,139 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.admin.platform; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.util.List; -import java.util.Map; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * The check that would have caught this session's worst defect at startup. - * - *

The problem catalog existed, was fully tested, and was reached by nothing on the framework's - * error path — found by accident, weeks of work later, through a cross-stack parity recording. - * Every case here is the same shape: a control that is configured and not wired behaves exactly - * like one that works, right up until it is needed. - */ -class WebPlatformStartupValidatorTest { - - private static final List REQUIRED = - List.of("problemHandler", "budgetFilter", "throttleFilter"); - - @Test - @DisplayName("a fully wired platform starts") - void fullyWiredPlatformStarts() { - assertThatCode( - () -> - new WebPlatformStartupValidator(REQUIRED) - .validate( - snapshot( - Map.of( - "problemHandler", - true, - "budgetFilter", - true, - "throttleFilter", - true)))) - .doesNotThrowAnyException(); - } - - @Test - @DisplayName("a declared control that is not wired fails startup") - void uninstalledControlFailsStartup() { - assertThatThrownBy( - () -> - new WebPlatformStartupValidator(REQUIRED) - .validate( - snapshot( - Map.of( - "problemHandler", - true, - "budgetFilter", - false, - "throttleFilter", - true)))) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("budgetFilter"); - } - - @Test - @DisplayName("a control absent from the snapshot entirely fails startup") - void absentControlFailsStartup() { - // Absent and false must behave the same. A control missing from the map is a control nobody - // even attempted to wire, which is worse than one that failed to. - assertThatThrownBy( - () -> - new WebPlatformStartupValidator(REQUIRED) - .validate(snapshot(Map.of("problemHandler", true)))) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("budgetFilter") - .hasMessageContaining("throttleFilter"); - } - - @Test - @DisplayName("every missing control is named at once") - void everyMissingControlIsNamedAtOnce() { - // Reporting the first would send an operator through one restart per problem, and each restart - // is a deploy. - assertThatThrownBy( - () -> - new WebPlatformStartupValidator(REQUIRED) - .validate( - snapshot( - Map.of( - "problemHandler", - false, - "budgetFilter", - false, - "throttleFilter", - false)))) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("problemHandler") - .hasMessageContaining("budgetFilter") - .hasMessageContaining("throttleFilter"); - } - - @Test - @DisplayName("an empty problem catalog fails startup") - void emptyProblemCatalogFailsStartup() { - // The specific defect this session found: without a catalog the framework answers with its - // own document, which is RFC 9457-shaped and carries no code. - assertThatThrownBy( - () -> - new WebPlatformStartupValidator(List.of()) - .validate( - new WebPlatformSnapshot( - "servlet", - List.of(1), - List.of(), - Map.of(), - Map.of(), - List.of(), - Map.of()))) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("no problem catalog"); - } - - @Test - @DisplayName("the snapshot names which controls are not wired") - void snapshotNamesUninstalledControls() { - assertThat( - snapshot(Map.of("problemHandler", true, "budgetFilter", false, "throttleFilter", false)) - .uninstalledControls()) - .containsExactly("budgetFilter", "throttleFilter"); - } - - private static WebPlatformSnapshot snapshot(Map controls) { - return new WebPlatformSnapshot( - "servlet", - List.of(1), - List.of("VALIDATION_FAILED", "INTERNAL_ERROR"), - Map.of("standard", "8MiB body"), - Map.of("global-write", "32 concurrent"), - List.of("sensitive", "revalidated"), - controls); - } -} diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/blockingbridge/BlockingBridgeBudgetTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/blockingbridge/BlockingBridgeBudgetTest.java deleted file mode 100644 index 44aff52f..00000000 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/blockingbridge/BlockingBridgeBudgetTest.java +++ /dev/null @@ -1,143 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.advanced.blockingbridge; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.time.Duration; -import java.util.List; -import java.util.Set; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -/** - * Offloading blocking work off the event loop, without the offload becoming the problem. - * - *

Reactor's {@code boundedElastic()} is available from anywhere and unbounded in practice, so a - * controller that calls it has silently opted the whole application into an unbounded pool. Every - * such call site is invisible until the pool is the thing consuming the heap. - */ -@Tag("web-advanced") -class BlockingBridgeBudgetTest { - - private static BlockingBridgeProfile profile(int concurrency) { - return new BlockingBridgeProfile( - Set.of("jpa.read", "jpa.write"), concurrency, Duration.ofMillis(100)); - } - - @Test - @DisplayName("an unregistered operation cannot use the bridge") - void unregisteredOperationIsRefused() { - // The registration is what makes the offloads enumerable. - BlockingBridgeBudget budget = new BlockingBridgeBudget(profile(4)); - - assertThatThrownBy(() -> budget.acquire("legacy.soap.call")) - .isInstanceOf(BlockingBridgeRejectedException.class) - .extracting(failure -> ((BlockingBridgeRejectedException) failure).reason()) - .isEqualTo(BlockingBridgeRejectedException.Reason.NOT_REGISTERED); - } - - @Test - @DisplayName("concurrency never exceeds the configured bound") - void concurrencyIsBounded() throws Exception { - // Invisible from throughput and from latency: a bridge whose bound is not applied looks - // exactly like one whose bound is generous, until the pool is the heap. - int bound = 4; - BlockingBridgeBudget budget = - new BlockingBridgeBudget( - new BlockingBridgeProfile(Set.of("jpa.read"), bound, Duration.ofSeconds(5))); - - try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) { - List> futures = new java.util.ArrayList<>(); - for (int i = 0; i < 64; i++) { - futures.add( - executor.submit( - () -> { - budget.acquire("jpa.read"); - try { - Thread.sleep(5); - } finally { - budget.release(); - } - return null; - })); - } - for (Future future : futures) { - future.get(30, TimeUnit.SECONDS); - } - } - - assertThat(budget.peakConcurrency()).isLessThanOrEqualTo(bound); - assertThat(budget.inFlight()).isZero(); - } - - @Test - @DisplayName("a caller that cannot get a slot in time is refused, not queued") - void queueTimeoutRefuses() throws Exception { - // A slow dependency's callers otherwise accumulate until the heap does, and the fast - // dependencies starve behind them. - BlockingBridgeBudget budget = - new BlockingBridgeBudget( - new BlockingBridgeProfile(Set.of("jpa.read"), 1, Duration.ofMillis(20))); - CountDownLatch hold = new CountDownLatch(1); - CountDownLatch holding = new CountDownLatch(1); - - try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) { - Future holder = - executor.submit( - () -> { - budget.acquire("jpa.read"); - holding.countDown(); - hold.await(); - budget.release(); - return null; - }); - assertThat(holding.await(10, TimeUnit.SECONDS)).isTrue(); - - assertThatThrownBy(() -> budget.acquire("jpa.read")) - .isInstanceOf(BlockingBridgeRejectedException.class) - .extracting(failure -> ((BlockingBridgeRejectedException) failure).reason()) - .isEqualTo(BlockingBridgeRejectedException.Reason.QUEUE_TIMEOUT); - assertThat(budget.rejectionsFor("jpa.read")).isOne(); - hold.countDown(); - holder.get(10, TimeUnit.SECONDS); - } - } - - @Test - @DisplayName("refusals of unregistered operations do not become map keys") - void unregisteredRefusalsDoNotGrowTheMap() throws Exception { - // The caller supplies the string, and a map keyed on it grows with whatever is passed — the - // same unbounded-cardinality problem a metric tagged with client input has. - BlockingBridgeBudget budget = new BlockingBridgeBudget(profile(4)); - for (int i = 0; i < 100; i++) { - String name = "unknown." + i; - assertThatThrownBy(() -> budget.acquire(name)) - .isInstanceOf(BlockingBridgeRejectedException.class); - } - - assertThat(budget.unregisteredRejections()).isEqualTo(100); - assertThat(budget.rejectionsFor("unknown.7")).isZero(); - } - - @Test - @DisplayName("a bridge with no registered operation is refused at construction") - void emptyRegistrationIsRefused() { - assertThatThrownBy(() -> new BlockingBridgeProfile(Set.of(), 4, Duration.ofSeconds(1))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("do not enable the bridge"); - } - - @Test - @DisplayName("an unbounded queue wait is refused") - void unboundedQueueWaitIsRefused() { - assertThatThrownBy(() -> new BlockingBridgeProfile(Set.of("a"), 4, Duration.ZERO)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("the fast dependencies starve behind them"); - } -} diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/functional/FunctionalRouteRegistryTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/functional/FunctionalRouteRegistryTest.java deleted file mode 100644 index 4e3860d9..00000000 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/functional/FunctionalRouteRegistryTest.java +++ /dev/null @@ -1,178 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.advanced.functional; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.web.budget.WebBudgetProfileName; -import dev.caskeleton.adapter.inbound.web.core.WebOperationName; -import dev.caskeleton.adapter.inbound.web.operation.AdmissionProfileName; -import dev.caskeleton.adapter.inbound.web.operation.AuthorizationProfileName; -import dev.caskeleton.adapter.inbound.web.operation.CachePolicyName; -import dev.caskeleton.adapter.inbound.web.operation.HttpMethodSemantic; -import dev.caskeleton.adapter.inbound.web.operation.IdempotencyPolicy; -import dev.caskeleton.adapter.inbound.web.operation.InMemoryWebOperationCatalog; -import dev.caskeleton.adapter.inbound.web.operation.MutationKind; -import dev.caskeleton.adapter.inbound.web.operation.PreconditionPolicy; -import dev.caskeleton.adapter.inbound.web.operation.ResponseProfileName; -import dev.caskeleton.adapter.inbound.web.operation.WebOperationCatalog; -import dev.caskeleton.adapter.inbound.web.operation.WebOperationProfile; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -/** - * A functional route is a lambda registered against a path. - * - *

There is no annotation for a scanner to find and no class name to infer from, so a route - * without a declared operation has no budget, no authorization profile and no idempotency policy — - * and nothing anywhere will say so. It will simply serve. - */ -@Tag("web-advanced") -class FunctionalRouteRegistryTest { - - private static final WebOperationName READ = new WebOperationName("items.read"); - - private static WebOperationCatalog catalog(HttpMethodSemantic method, MutationKind kind) { - InMemoryWebOperationCatalog catalog = new InMemoryWebOperationCatalog(); - catalog.register( - new WebOperationProfile( - READ, - method, - kind, - WebBudgetProfileName.standard(), - AuthorizationProfileName.standard(), - IdempotencyPolicy.FORBIDDEN, - PreconditionPolicy.NONE, - CachePolicyName.standard(), - AdmissionProfileName.standard(), - ResponseProfileName.standard())); - return catalog; - } - - private static RegisteredRoute route(HttpMethodSemantic method, WebOperationName operation) { - return new RegisteredRoute("/api/v1/items/{id}", method, operation, "itemsReadHandler"); - } - - @Test - @DisplayName("a route whose operation is not in the catalog is refused") - void unregisteredOperationIsRefused() { - // A raw RouterFunction bean skips this check entirely, which is why they are not registered - // directly. - FunctionalRouteRegistry registry = - new FunctionalRouteRegistry(catalog(HttpMethodSemantic.GET, MutationKind.READ_ONLY)); - - assertThatThrownBy( - () -> - registry.register( - route(HttpMethodSemantic.GET, new WebOperationName("unregistered.operation")))) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("a registered operation with a matching method is accepted") - void matchingRouteIsAccepted() { - FunctionalRouteRegistry registry = - new FunctionalRouteRegistry(catalog(HttpMethodSemantic.GET, MutationKind.READ_ONLY)); - registry.register(route(HttpMethodSemantic.GET, READ)); - - assertThat(registry.size()).isOne(); - assertThat(registry.routes()) - .singleElement() - .extracting(RegisteredRoute::handlerName) - .isEqualTo("itemsReadHandler"); - } - - @Test - @DisplayName("a route whose method disagrees with its operation is refused") - void methodMismatchIsRefused() { - // The profile's idempotency, precondition and cache policies were chosen for the declared - // method, and nothing downstream re-derives it from the route. - FunctionalRouteRegistry registry = - new FunctionalRouteRegistry(catalog(HttpMethodSemantic.POST, MutationKind.CREATE)); - - assertThatThrownBy(() -> registry.register(route(HttpMethodSemantic.GET, READ))) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("nothing downstream re-derives it"); - } - - @Test - @DisplayName("two routes claiming the same method and path are refused") - void duplicateRouteIsRefused() { - // The router resolves the first match, so which one serves depends on bean ordering. - FunctionalRouteRegistry registry = - new FunctionalRouteRegistry(catalog(HttpMethodSemantic.GET, MutationKind.READ_ONLY)); - registry.register(route(HttpMethodSemantic.GET, READ)); - - assertThatThrownBy( - () -> - registry.register( - new RegisteredRoute( - "/api/v1/items/{id}", HttpMethodSemantic.GET, READ, "otherHandler"))) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("depends on bean ordering"); - } - - @Test - @DisplayName("a handler must be named, because a lambda has no class name for a log") - void handlerMustBeNamed() { - assertThatThrownBy( - () -> new RegisteredRoute("/api/v1/items", HttpMethodSemantic.GET, READ, " ")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("no class name to fall back on"); - } - - @Test - @DisplayName("the router is built only from validated routes") - void routerIsBuiltFromValidatedRoutes() { - // The adapter is the only way a functional route reaches Spring. A RouterFunction bean would - // be picked up and served with no operation profile at all. - FunctionalRouteRegistry registry = - new FunctionalRouteRegistry(catalog(HttpMethodSemantic.GET, MutationKind.READ_ONLY)); - registry.register(route(HttpMethodSemantic.GET, READ)); - - assertThat( - new WebFunctionalHandlerAdapter( - registry, - r -> - request -> - org.springframework.web.reactive.function.server.ServerResponse.ok() - .build()) - .build()) - .isNotNull(); - } - - @Test - @DisplayName("an empty registry produces no router rather than an empty one") - void emptyRegistryIsRefused() { - // An empty router is a bean that serves nothing and looks installed, which is - // indistinguishable from a registry nobody populated. - FunctionalRouteRegistry registry = - new FunctionalRouteRegistry(catalog(HttpMethodSemantic.GET, MutationKind.READ_ONLY)); - - assertThatThrownBy(() -> new WebFunctionalHandlerAdapter(registry, r -> null).build()) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("looks installed"); - } - - @Test - @DisplayName("a route with no handler fails at build rather than at first request") - void routeWithoutAHandlerFailsAtBuild() { - // Otherwise it is a 404 that looks like a routing bug rather than a wiring one, and it only - // appears when somebody calls it. - FunctionalRouteRegistry registry = - new FunctionalRouteRegistry(catalog(HttpMethodSemantic.GET, MutationKind.READ_ONLY)); - registry.register(route(HttpMethodSemantic.GET, READ)); - - assertThatThrownBy(() -> new WebFunctionalHandlerAdapter(registry, r -> null).build()) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("resolved to nothing"); - } - - @Test - @DisplayName("a relative route pattern is refused") - void relativePatternIsRefused() { - assertThatThrownBy(() -> new RegisteredRoute("api/v1/items", HttpMethodSemantic.GET, READ, "h")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("absolute path"); - } -} diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/openapi/OpenApi32CompatibilityReportTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/openapi/OpenApi32CompatibilityReportTest.java deleted file mode 100644 index 84cb49ce..00000000 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/openapi/OpenApi32CompatibilityReportTest.java +++ /dev/null @@ -1,110 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.advanced.openapi; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.adapter.inbound.web.advanced.openapi.OpenApiToolchainMatrix.ToolKind; -import java.util.List; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -/** - * Generating 3.2 alongside 3.1, without either changing the other. - * - *

The value of an API description is entirely in what consumes it, so a document in a version a - * client generator does not understand is worse than no document — it produces a client that - * compiles and is wrong. - */ -@Tag("web-advanced") -class OpenApi32CompatibilityReportTest { - - private static OpenApiToolchainMatrix fullMatrix() { - return new OpenApiToolchainMatrix() - .record(ToolKind.PARSER, "swagger-parser-2.1", true) - .record(ToolKind.LINTER, "spectral-6", true) - .record(ToolKind.GENERATOR, "openapi-generator-7", true) - .record(ToolKind.CLIENT_COMPILE, "java-17", true); - } - - @Test - @DisplayName("3.1 remains the release artifact") - void stableLaneIsTheReleaseArtifact() { - assertThat(OpenApiVersionLane.STABLE_3_1.releaseArtifact()).isTrue(); - assertThat(OpenApiVersionLane.STABLE_3_1.version()).isEqualTo("3.1.2"); - assertThat(OpenApiVersionLane.EXPERIMENTAL_3_2.releaseArtifact()).isFalse(); - assertThat(OpenApiVersionLane.EXPERIMENTAL_3_2.version()).isEqualTo("3.2.0"); - } - - @Test - @DisplayName("generating 3.2 must leave the 3.1 snapshot untouched") - void generatingDoesNotMutateTheStableSnapshot() { - // They are produced from the same model, so a contributor that mutates it on the way to 3.2 - // changes the artifact that is actually shipped. - OpenApi32CompatibilityReport clean = - new OpenApi32CompatibilityReport("sha256:aaa", "sha256:aaa", List.of(), fullMatrix()); - OpenApi32CompatibilityReport mutated = - new OpenApi32CompatibilityReport("sha256:aaa", "sha256:bbb", List.of(), fullMatrix()); - - assertThat(clean.stableArtifactUnchanged()).isTrue(); - assertThat(mutated.stableArtifactUnchanged()).isFalse(); - assertThat(mutated.promotionBlockers(true)) - .anyMatch(blocker -> blocker.contains("share mutable state")); - } - - @Test - @DisplayName("each kind of tool is checked separately") - void everyToolKindIsCheckedSeparately() { - // A linter accepts documents a parser rejects, and a generator emits a wrong-but-valid - // signature that only a compile catches. - OpenApiToolchainMatrix partial = - new OpenApiToolchainMatrix() - .record(ToolKind.PARSER, "swagger-parser-2.1", true) - .record(ToolKind.LINTER, "spectral-6", true); - - assertThat(partial.complete()).isFalse(); - assertThat(partial.gaps()) - .anyMatch(gap -> gap.startsWith("GENERATOR")) - .anyMatch(gap -> gap.startsWith("CLIENT_COMPILE")); - assertThat(fullMatrix().complete()).isTrue(); - } - - @Test - @DisplayName("a failing tool does not count as a passing one") - void failingToolDoesNotCount() { - OpenApiToolchainMatrix failed = - new OpenApiToolchainMatrix() - .record(ToolKind.PARSER, "swagger-parser-2.1", true) - .record(ToolKind.LINTER, "spectral-6", true) - .record(ToolKind.GENERATOR, "openapi-generator-7", false) - .record(ToolKind.CLIENT_COMPILE, "java-17", true); - - assertThat(failed.complete()).isFalse(); - } - - @Test - @DisplayName("3.2 stays experimental without an accepted ADR, however green the matrix is") - void adrIsRequiredRegardlessOfTheMatrix() { - OpenApi32CompatibilityReport report = - new OpenApi32CompatibilityReport("sha256:aaa", "sha256:aaa", List.of(), fullMatrix()); - - assertThat(report.promotable(false)).isFalse(); - assertThat(report.promotionBlockers(false)) - .singleElement() - .asString() - .contains("no accepted promotion ADR"); - assertThat(report.promotable(true)).isTrue(); - } - - @Test - @DisplayName("streaming description differences are recorded separately") - void streamingDifferencesAreRecorded() { - OpenApi32CompatibilityReport report = - new OpenApi32CompatibilityReport( - "sha256:aaa", - "sha256:aaa", - List.of("text/event-stream responses gain an itemSchema in 3.2"), - fullMatrix()); - - assertThat(report.streamingDescriptionDifferences()).hasSize(1); - } -} diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/ratelimit/RateLimitDraftHeaderWriterTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/ratelimit/RateLimitDraftHeaderWriterTest.java deleted file mode 100644 index ded314b6..00000000 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/ratelimit/RateLimitDraftHeaderWriterTest.java +++ /dev/null @@ -1,108 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.advanced.ratelimit; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.web.ratelimit.RateLimitDecision; -import java.time.Duration; -import java.time.Instant; -import java.util.Map; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -/** - * Draft headers, which are additive and never the contract. - * - *

The Stable contract is the 429 and {@code Retry-After}; both are standardised and neither - * changes when this is on. - */ -@Tag("web-advanced") -class RateLimitDraftHeaderWriterTest { - - private static final Instant NOW = Instant.parse("2026-08-25T10:00:00Z"); - - private static RateLimitDecision refused() { - return RateLimitDecision.refused(100, NOW.plusSeconds(30), Duration.ofSeconds(30)); - } - - @Test - @DisplayName("nothing is written unless the profile is explicitly enabled") - void nothingIsWrittenUnlessEnabled() { - // A deployment that turns it off behaves exactly as a Stable one, which is what the rollback - // test asserts. - assertThat( - new RateLimitDraftHeaderWriter(RateLimitDraftProfile.disabled()).write(refused(), NOW)) - .isEmpty(); - } - - @Test - @DisplayName("draft 11 writes one structured field plus a policy field") - void draft11WritesStructuredFields() { - Map headers = - new RateLimitDraftHeaderWriter( - RateLimitDraftProfile.enabled(RateLimitDraftVersion.DRAFT_11, 60)) - .write(refused(), NOW); - - assertThat(headers).containsKeys("RateLimit", "RateLimit-Policy"); - assertThat(headers.get("RateLimit")).isEqualTo("limit=100, remaining=0, reset=30"); - assertThat(headers.get("RateLimit-Policy")).isEqualTo("q=100;w=60"); - } - - @Test - @DisplayName("draft 07 writes the three separate fields instead") - void draft07WritesSeparateFields() { - // A client written against one draft silently misreads the other, which is why the version is - // named rather than assumed. - Map headers = - new RateLimitDraftHeaderWriter( - RateLimitDraftProfile.enabled(RateLimitDraftVersion.DRAFT_07, 60)) - .write(refused(), NOW); - - assertThat(headers).containsKeys("RateLimit-Limit", "RateLimit-Remaining", "RateLimit-Reset"); - assertThat(headers).doesNotContainKey("RateLimit"); - } - - @Test - @DisplayName("reset is a delta, not a timestamp") - void resetIsADelta() { - // A client whose clock is two minutes fast reads an absolute reset time as already past and - // retries immediately, which is the behaviour the header exists to prevent. - Map headers = - new RateLimitDraftHeaderWriter( - RateLimitDraftProfile.enabled(RateLimitDraftVersion.DRAFT_07, 60)) - .write(refused(), NOW.plusSeconds(10)); - - assertThat(headers.get("RateLimit-Reset")).isEqualTo("20"); - } - - @Test - @DisplayName("a reset already in the past is clamped to zero") - void pastResetIsClamped() { - // Otherwise it reads as an enormous unsigned number to a client that does not clamp. - Map headers = - new RateLimitDraftHeaderWriter( - RateLimitDraftProfile.enabled(RateLimitDraftVersion.DRAFT_07, 60)) - .write(refused(), NOW.plusSeconds(300)); - - assertThat(headers.get("RateLimit-Reset")).isEqualTo("0"); - } - - @Test - @DisplayName("the draft version is recorded for the response artifact") - void draftVersionIsRecorded() { - assertThat( - new RateLimitDraftHeaderWriter( - RateLimitDraftProfile.enabled(RateLimitDraftVersion.DRAFT_11, 60)) - .draftLabel()) - .isEqualTo("draft-11"); - } - - @Test - @DisplayName("enabling without a window is refused") - void enablingWithoutAWindowIsRefused() { - assertThatThrownBy(() -> new RateLimitDraftProfile(true, RateLimitDraftVersion.DRAFT_11, 0)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("describes no policy"); - } -} diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/release/WebAdvancedReleaseTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/release/WebAdvancedReleaseTest.java deleted file mode 100644 index d948e3bc..00000000 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/release/WebAdvancedReleaseTest.java +++ /dev/null @@ -1,174 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.advanced.release; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.web.advanced.WebAdvancedFeature; -import java.time.Duration; -import java.util.Set; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -/** What the release has to be able to show, and what it has to be able to undo. */ -@Tag("web-advanced") -class WebAdvancedReleaseTest { - - @Test - @DisplayName("the catalog distinguishes wired properties from library-only capabilities") - void activationPathsAreHonest() { - assertThat(WebAdvancedFeature.MVC_VIRTUAL_THREADS.runtimeProperty()) - .contains("backend.web.advanced.mvc-virtual-threads.enabled"); - assertThat(WebAdvancedFeature.NDJSON.runtimeProperty()) - .contains("backend.web.advanced.ndjson.enabled"); - assertThat(WebAdvancedFeature.JSON_SEQUENCE.runtimeProperty()) - .contains("backend.web.advanced.json-sequence.enabled"); - - assertThat(WebAdvancedFeature.JSON_MERGE_PATCH.runtimeProperty()).isEmpty(); - assertThat(WebAdvancedFeature.SSE.runtimeProperty()).isEmpty(); - assertThat(WebAdvancedFeature.CBOR.runtimeProperty()).isEmpty(); - - assertThat( - java.util.Arrays.stream(WebAdvancedFeature.values()) - .filter( - feature -> - feature.activationPath() - == WebAdvancedFeature.ActivationPath.RUNTIME_PROPERTY) - .count()) - .isEqualTo(3); - } - - @Test - @DisplayName("the capabilities that change unrelated requests are identified") - void processWideCapabilitiesAreIdentified() { - assertThat(WebAdvancedFeature.MVC_VIRTUAL_THREADS.affectsUnrelatedRequests()).isTrue(); - assertThat(WebAdvancedFeature.WEBFLUX_BLOCKING_BRIDGE.affectsUnrelatedRequests()).isTrue(); - assertThat(WebAdvancedFeature.CBOR.affectsUnrelatedRequests()).isFalse(); - } - - @Test - @DisplayName("streaming and virtual threads soak longer than a codec does") - void soakScalesWithTheFailureMode() { - assertThat(WebAdvancedPromotionGate.forFeature(WebAdvancedFeature.SSE).minimumSoak()) - .isEqualTo(Duration.ofHours(24)); - assertThat( - WebAdvancedPromotionGate.forFeature(WebAdvancedFeature.MVC_VIRTUAL_THREADS) - .minimumSoak()) - .isEqualTo(Duration.ofHours(24)); - assertThat(WebAdvancedPromotionGate.forFeature(WebAdvancedFeature.CBOR).minimumSoak()) - .isEqualTo(Duration.ofHours(8)); - } - - @Test - @DisplayName("each capability requires the suites its own failures need") - void suitesMatchTheFailureMode() { - assertThat(WebAdvancedPromotionGate.forFeature(WebAdvancedFeature.SSE).requiredSuites()) - .contains("streaming-soak-10k", "slow-consumer-bounded", "pod-drain"); - assertThat( - WebAdvancedPromotionGate.forFeature(WebAdvancedFeature.MVC_VIRTUAL_THREADS) - .requiredSuites()) - .contains("virtual-thread-admission", "pinning-jfr"); - assertThat(WebAdvancedPromotionGate.forFeature(WebAdvancedFeature.XML).requiredSuites()) - .contains("codec-security"); - } - - @Test - @DisplayName("the parser and patch capabilities need a security review") - void parsersAndPatchesNeedASecurityReview() { - // Each takes attacker-supplied bytes into a new parser, or lets a caller address arbitrary - // parts of a resource. - assertThat(WebAdvancedPromotionGate.needsSecurityReview(WebAdvancedFeature.XML)).isTrue(); - assertThat(WebAdvancedPromotionGate.needsSecurityReview(WebAdvancedFeature.JSON_PATCH)) - .isTrue(); - assertThat(WebAdvancedPromotionGate.needsSecurityReview(WebAdvancedFeature.SSE)).isFalse(); - } - - @Test - @DisplayName("promotion is blocked until rollback restores Stable behaviour exactly") - void rollbackMustRestoreStableBehaviour() { - // If turning the feature off does not restore Stable behaviour, the feature was never optional - // and every deployment has it. - WebAdvancedPromotionGate gate = - new WebAdvancedPromotionGate(Set.of("web:test"), Duration.ofHours(8), true, true, false); - - assertThat(gate.blockers(WebAdvancedFeature.SSE, Set.of("web:test"), Duration.ofHours(9))) - .singleElement() - .asString() - .contains("every deployment has it"); - } - - @Test - @DisplayName("blockers are listed, not collapsed to a boolean") - void blockersAreEnumerated() { - WebAdvancedPromotionGate gate = - new WebAdvancedPromotionGate( - Set.of("web:test", "codec-security"), Duration.ofHours(8), false, false, false); - - assertThat(gate.blockers(WebAdvancedFeature.XML, Set.of("web:test"), Duration.ofHours(1))) - .hasSize(5) - .anyMatch(line -> line.contains("codec-security")) - .anyMatch(line -> line.contains("short of the required")) - .anyMatch(line -> line.contains("no security review")) - .anyMatch(line -> line.contains("rollback not exercised")); - } - - @Test - @DisplayName("a fully satisfied gate promotes") - void satisfiedGatePromotes() { - WebAdvancedPromotionGate gate = - new WebAdvancedPromotionGate(Set.of("web:test"), Duration.ofHours(8), true, true, true); - - assertThat(gate.promotable(WebAdvancedFeature.SSE, Set.of("web:test"), Duration.ofHours(8))) - .isTrue(); - } - - @Test - @DisplayName("the manifest reports what is required and absent, not just what is present") - void manifestReportsWhatIsMissing() { - // A manifest that only listed what was collected would always look complete: it lists what it - // lists. - WebAdvancedReleaseManifest manifest = - WebAdvancedReleaseManifest.builder() - .record("stable-release-baseline", "run/1") - .record("streaming-soak-10k", "run/2") - .build(); - - assertThat(manifest.has("stable-release-baseline")).isTrue(); - assertThat(manifest.reference("streaming-soak-10k")).contains("run/2"); - assertThat(manifest.complete()).isFalse(); - assertThat(manifest.missing()) - .contains("slow-consumer-bounded", "patch-security", "rollback-disabled-profile"); - } - - @Test - @DisplayName("a complete manifest carries every required piece") - void completeManifestCarriesEverything() { - WebAdvancedReleaseManifest.Builder builder = WebAdvancedReleaseManifest.builder(); - WebAdvancedReleaseManifest.REQUIRED.forEach(name -> builder.record(name, "run/" + name)); - - assertThat(builder.build().complete()).isTrue(); - assertThat(builder.build().missing()).isEmpty(); - } - - @Test - @DisplayName("evidence without a reference is refused") - void referencelessEvidenceIsRefused() { - // A name with no reference is a claim, and a manifest of claims is what this exists instead of. - assertThatThrownBy(() -> WebAdvancedReleaseManifest.builder().record("patch-security", " ")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("manifest of claims"); - } - - @Test - @DisplayName("a gate requiring no suite or no soak is refused") - void emptyGateIsRefused() { - assertThatThrownBy( - () -> new WebAdvancedPromotionGate(Set.of(), Duration.ofHours(1), true, true, true)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("reads as one"); - assertThatThrownBy( - () -> new WebAdvancedPromotionGate(Set.of("a"), Duration.ZERO, true, true, true)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("needs load or time to appear"); - } -} diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/webflux/WebFluxStreamingTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/webflux/WebFluxStreamingTest.java deleted file mode 100644 index f200ed3e..00000000 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/advanced/webflux/WebFluxStreamingTest.java +++ /dev/null @@ -1,309 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.advanced.webflux; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.adapter.inbound.web.advanced.blockingbridge.BlockingBridgeBudget; -import dev.caskeleton.adapter.inbound.web.advanced.blockingbridge.BlockingBridgeProfile; -import dev.caskeleton.adapter.inbound.web.advanced.blockingbridge.BlockingBridgeRejectedException; -import dev.caskeleton.adapter.inbound.web.advanced.stream.StreamId; -import dev.caskeleton.adapter.inbound.web.advanced.stream.StreamSequence; -import dev.caskeleton.adapter.inbound.web.advanced.stream.WebStreamEnvelope; -import dev.caskeleton.adapter.inbound.web.advanced.stream.WebStreamEvidence; -import dev.caskeleton.adapter.inbound.web.advanced.stream.WebStreamPolicy; -import dev.caskeleton.adapter.inbound.web.advanced.stream.WebStreamRegistry; -import dev.caskeleton.adapter.inbound.web.advanced.stream.WebStreamTermination; -import java.time.Duration; -import java.time.Instant; -import java.util.Set; -import java.util.concurrent.atomic.AtomicBoolean; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; -import org.springframework.http.codec.ServerSentEvent; -import reactor.core.Disposable; -import reactor.core.publisher.Flux; -import reactor.core.publisher.FluxSink; -import reactor.core.scheduler.Schedulers; -import reactor.test.StepVerifier; - -/** - * The reactive side, where a disconnect arrives as a cancel signal rather than as a failed write. - * - *

Which makes the detection easy and the propagation the thing to get wrong. - */ -@Tag("web-advanced") -class WebFluxStreamingTest { - - private static final Instant NOW = Instant.parse("2026-08-25T10:00:00Z"); - private static final StreamId STREAM = new StreamId("orders-feed"); - - private static WebStreamPolicy policy(int buffer) { - return new WebStreamPolicy( - Duration.ofSeconds(15), Duration.ofSeconds(60), Duration.ofMinutes(30), buffer, 262_144); - } - - private static WebStreamEnvelope item(long sequence) { - return new WebStreamEnvelope.Item<>(STREAM, new StreamSequence(sequence), "payload"); - } - - /** - * A source that pushes regardless of demand, which is the only kind that can overflow a buffer. - * - *

Two sources that look like they would and do not. {@code Flux.range} honours demand, so a - * slow consumer merely slows it down. {@code Flux.interval} honours it too — it stalls when - * nothing has been requested — so a chain built on either simply goes quiet, and a test written - * against one passes with the bound removed. - * - *

What a real event feed does is push: something happened, so an item exists, whether or not - * anybody asked for it. {@code OverflowStrategy.IGNORE} is that, and it is what makes the bound - * the thing that decides. - */ - private static Flux> unpaced() { - return Flux.create( - sink -> { - for (long sequence = 1; sequence <= 1_000; sequence++) { - sink.next(item(sequence)); - } - sink.complete(); - }, - FluxSink.OverflowStrategy.IGNORE); - } - - @Test - @DisplayName("a slow consumer is closed rather than buffered without limit") - void slowConsumerIsClosed() { - // Backpressure protects the pipeline from a fast producer. It does nothing about a consumer - // that reads slowly for an hour, and whatever the pipeline holds for it is this process's heap. - Flux>> stream = - new WebFluxSseAdapter(policy(8)).adapt(unpaced()); - - StepVerifier.create(stream, 0) - .thenRequest(8) - .expectNextCount(8) - .expectError(SlowConsumerClosedException.class) - .verify(Duration.ofSeconds(10)); - } - - @Test - @DisplayName("overflow closes the stream instead of dropping an item") - void overflowDoesNotDropSilently() { - // DROP_OLDEST is the tempting setting and it produces a gap the client cannot see, because the - // positions either side of it are both valid. - Flux>> stream = - new WebFluxSseAdapter(policy(4)).adapt(unpaced()); - - StepVerifier.create(stream, 0) - .thenRequest(4) - .expectNextCount(4) - .expectErrorSatisfies( - failure -> - assertThat(failure) - .isInstanceOf(SlowConsumerClosedException.class) - .hasMessageContaining("rather than holding its backlog")) - .verify(Duration.ofSeconds(10)); - } - - @Test - @DisplayName("a source that finishes ends the stream instead of heartbeating to its max age") - void finishedSourceEndsTheStream() { - // The heartbeat is infinite, so merging it without a terminal condition holds the connection - // for the full maximum age after the last item — thirty minutes of keepalives on a stream that - // finished. - StepVerifier.create( - new WebFluxSseAdapter(policy(16)) - .adapt( - Flux.just( - item(1), new WebStreamEnvelope.Complete<>(STREAM, new StreamSequence(1))))) - .expectNextCount(2) - .verifyComplete(); - } - - @Test - @DisplayName("a source that forgets its terminal envelope has one supplied") - void missingTerminalIsSupplied() { - // A client that receives neither terminal envelope has been cut off, and that has to stay - // distinguishable from a clean end. - StepVerifier.create(new WebFluxSseAdapter(policy(16)).adapt(Flux.just(item(1), item(2)))) - .expectNextCount(2) - .assertNext( - event -> { - assertThat(event.event()).isEqualTo("complete"); - assertThat(event.data()).isInstanceOf(WebStreamEnvelope.Complete.class); - }) - .verifyComplete(); - } - - @Test - @DisplayName("only items carry an SSE id, so a resume never continues a finished stream") - void onlyItemsCarryAnId() { - Flux>> stream = - new WebFluxSseAdapter(policy(16)) - .adapt( - Flux.just( - item(41), new WebStreamEnvelope.Complete<>(STREAM, new StreamSequence(41)))); - - StepVerifier.create(stream) - .assertNext( - event -> { - assertThat(event.event()).isEqualTo("item"); - assertThat(event.id()).isEqualTo("41"); - }) - .assertNext( - event -> { - assertThat(event.event()).isEqualTo("complete"); - assertThat(event.id()).isNull(); - }) - .verifyComplete(); - } - - @Test - @DisplayName("a cancel is recorded as the client leaving, not as a fault") - void cancelIsRecordedAsADisconnect() { - WebStreamEvidence evidence = new WebStreamEvidence(STREAM, NOW); - Flux observed = - WebFluxDisconnectDetector.observe(Flux.interval(Duration.ofMillis(5)), evidence, () -> NOW); - - StepVerifier.create(observed).expectNextCount(2).thenCancel().verify(Duration.ofSeconds(10)); - - assertThat(evidence.termination()).contains(WebStreamTermination.CLIENT_DISCONNECTED); - } - - @Test - @DisplayName("a completion is recorded as a completion") - void completionIsRecorded() { - WebStreamEvidence evidence = new WebStreamEvidence(STREAM, NOW); - - StepVerifier.create(WebFluxDisconnectDetector.observe(Flux.just(1, 2), evidence, () -> NOW)) - .expectNextCount(2) - .verifyComplete(); - - assertThat(evidence.termination()).contains(WebStreamTermination.NORMAL_COMPLETE); - } - - @Test - @DisplayName("a slow-consumer close is not counted as a server fault") - void slowConsumerIsNotAServerFault() { - // It is the shedding bound working. Counting it as a fault makes the bound invisible in the - // metric that would show it firing. - assertThat(WebFluxDisconnectDetector.classify(new SlowConsumerClosedException(8))) - .isEqualTo(WebStreamTermination.CLIENT_DISCONNECTED); - assertThat(WebFluxDisconnectDetector.classify(new IllegalStateException("dependency down"))) - .isEqualTo(WebStreamTermination.TERMINAL_ERROR_RECORD); - } - - @Test - @DisplayName("a node at its ceiling refuses a reactive stream too") - void reactiveAdmissionIsBounded() { - WebFluxStreamAdmission admission = new WebFluxStreamAdmission(new WebStreamRegistry(1)); - - assertThat(admission.admit(new StreamId("first"), NOW, null)).isPresent(); - assertThat(admission.admit(new StreamId("second"), NOW, null)).isEmpty(); - } - - @Test - @DisplayName("releasing a slot twice does not return it twice") - void releaseIsIdempotent() { - // A cancel racing a complete is normal at the moment a client disconnects from a finishing - // stream. Releasing twice drifts the count below the truth until the node admits more streams - // than it has capacity for. - WebStreamRegistry registry = new WebStreamRegistry(1); - WebFluxStreamAdmission admission = new WebFluxStreamAdmission(registry); - WebFluxStreamAdmission.Admitted admitted = - admission.admit(new StreamId("feed"), NOW, null).orElseThrow(); - - admitted.release(); - admitted.release(); - - assertThat(registry.activeStreams()).isZero(); - assertThat(admission.admit(new StreamId("next"), NOW, null)).isPresent(); - assertThat(admission.admit(new StreamId("third"), NOW, null)).isEmpty(); - } - - @Test - @DisplayName("forcing a reactive stream closed disposes its subscription") - void forceCloseDisposesUpstream() { - // The source must stop producing for a stream nobody is reading. - AtomicBoolean disposed = new AtomicBoolean(); - Disposable subscription = - new Disposable() { - @Override - public void dispose() { - disposed.set(true); - } - - @Override - public boolean isDisposed() { - return disposed.get(); - } - }; - WebFluxStreamAdmission admission = new WebFluxStreamAdmission(new WebStreamRegistry(2)); - - admission - .admit(new StreamId("feed"), NOW, subscription) - .orElseThrow() - .session() - .forceClose(WebStreamTermination.ABRUPT_CLOSE); - - assertThat(disposed).isTrue(); - } - - @Test - @DisplayName("blocking work runs off the event loop and stays inside its bound") - void blockingWorkIsOffLoopAndBounded() { - BlockingBridgeBudget budget = - new BlockingBridgeBudget( - new BlockingBridgeProfile(Set.of("jpa.read"), 4, Duration.ofSeconds(5))); - ControlledBlockingBridge bridge = - new ControlledBlockingBridge(Schedulers.boundedElastic(), budget); - - Flux names = - Flux.range(0, 32) - .flatMap( - index -> bridge.execute("jpa.read", () -> Thread.currentThread().getName()), 32); - - StepVerifier.create(names.collectList()) - .assertNext( - all -> { - assertThat(all).hasSize(32); - assertThat(all).noneMatch(name -> name.startsWith("reactor-http-")); - }) - .expectComplete() - .verify(Duration.ofSeconds(30)); - assertThat(budget.peakConcurrency()).isLessThanOrEqualTo(4); - assertThat(budget.inFlight()).isZero(); - } - - @Test - @DisplayName("an unregistered operation cannot reach the offload pool") - void unregisteredOperationIsRefused() { - ControlledBlockingBridge bridge = - new ControlledBlockingBridge( - Schedulers.boundedElastic(), - new BlockingBridgeBudget( - new BlockingBridgeProfile(Set.of("jpa.read"), 4, Duration.ofSeconds(1)))); - - StepVerifier.create(bridge.execute("legacy.soap.call", () -> "x")) - .expectError(BlockingBridgeRejectedException.class) - .verify(Duration.ofSeconds(10)); - } - - @Test - @DisplayName("a Mono that is assembled and never subscribed takes no permit") - void assemblyTakesNoPermit() { - // Acquiring at assembly rather than at subscription holds a slot for ever on a pipeline that - // was built and discarded, which is the classic Reactor side-effect bug. - BlockingBridgeBudget budget = - new BlockingBridgeBudget( - new BlockingBridgeProfile(Set.of("jpa.read"), 1, Duration.ofMillis(50))); - ControlledBlockingBridge bridge = - new ControlledBlockingBridge(Schedulers.boundedElastic(), budget); - - bridge.execute("jpa.read", () -> "never subscribed"); - bridge.execute("jpa.read", () -> "also never subscribed"); - - assertThat(budget.inFlight()).isZero(); - StepVerifier.create(bridge.execute("jpa.read", () -> "subscribed")) - .expectNext("subscribed") - .verifyComplete(); - } -} diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/cache/WebCachePolicyTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/cache/WebCachePolicyTest.java deleted file mode 100644 index 26adae97..00000000 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/cache/WebCachePolicyTest.java +++ /dev/null @@ -1,143 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.cache; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.time.Duration; -import java.util.Optional; -import java.util.Set; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * Each case is a way a caching decision goes wrong without anybody noticing. - * - *

Cache bugs are invisible in a test that calls the endpoint once. They appear as one caller - * seeing another's data, or as a cache that costs storage and never hits, and both look fine from - * the server's own logs. - */ -class WebCachePolicyTest { - - @Test - @DisplayName("a sensitive response is private and never stored") - void sensitiveResponseIsPrivateNoStore() { - assertThat(WebCachePolicyCatalog.standard().require("sensitive").headers().cacheControl()) - .isEqualTo("private, no-store"); - } - - @Test - @DisplayName("no-store, not no-cache, is what keeps a response off disk") - void sensitiveUsesNoStoreRatherThanNoCache() { - // The confusion this asserts against is the common one: no-cache permits storing and requires - // revalidation, so the document still lands in the cache and on the disk behind it. - String cacheControl = - WebCachePolicyCatalog.standard().require("sensitive").headers().cacheControl(); - - assertThat(cacheControl).contains("no-store"); - assertThat(cacheControl).doesNotContain("no-cache"); - } - - @Test - @DisplayName("only a policy that says so may hold an authorized response in a shared cache") - void authorizedResponsesNeedAnExplicitSharedProfile() { - assertThat(WebCachePolicyCatalog.standard().require("sensitive").safeForAuthorizedResponse()) - .isTrue(); - assertThat( - WebCachePolicyCatalog.standard().require("browser-private").safeForAuthorizedResponse()) - .isTrue(); - // Storable by a proxy, which will serve it to whoever asks for the URL next. - assertThat(WebCachePolicyCatalog.standard().require("revalidated").safeForAuthorizedResponse()) - .isFalse(); - } - - @Test - @DisplayName("Vary refuses headers that are unique per client") - void varyRefusesPerClientHeaders() { - // Keying on any of these gives every caller a private entry: all the storage cost of a cache, - // none of the sharing. - assertThatThrownBy(() -> WebVaryPolicy.varyingOn(Set.of("User-Agent"))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("unique per client"); - assertThatThrownBy(() -> WebVaryPolicy.varyingOn(Set.of("Cookie"))) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> WebVaryPolicy.varyingOn(Set.of("Authorization"))) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("Vary is case-insensitive about header names") - void varyNormalisesCase() { - assertThat(WebVaryPolicy.varyingOn(Set.of("Accept-Language")).headerNames()) - .containsExactly("accept-language"); - assertThat(WebVaryPolicy.forbidden("USER-AGENT")).isTrue(); - } - - @Test - @DisplayName("a policy that varies on nothing emits no Vary at all") - void noVaryMeansNoHeader() { - // An empty `Vary:` is not the same as no Vary, and some intermediaries treat it as `Vary: *`. - assertThat(WebCachePolicyCatalog.standard().require("sensitive").headers().vary()).isEmpty(); - } - - @Test - @DisplayName("a shared profile varies on what actually changes the representation") - void sharedProfileVariesOnNegotiatedHeaders() { - assertThat(WebCachePolicyCatalog.standard().require("revalidated").headers().vary()) - .contains("accept, accept-encoding, accept-language"); - } - - @Test - @DisplayName("no-store with a freshness lifetime is refused") - void noStoreCannotHaveFreshness() { - assertThatThrownBy( - () -> - new WebCachePolicy( - "broken", - "private, no-store", - WebVaryPolicy.none(), - false, - Optional.of(Duration.ofMinutes(5)))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("contradict"); - } - - @Test - @DisplayName("public directives and the shared-cache flag must agree") - void publicAndSharedFlagMustAgree() { - assertThatThrownBy( - () -> - new WebCachePolicy( - "broken", "public, max-age=60", WebVaryPolicy.none(), false, Optional.empty())) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new WebCachePolicy( - "broken", "private, max-age=60", WebVaryPolicy.none(), true, Optional.empty())) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("an unnamed profile is refused rather than answered with a default") - void unknownProfileIsRefused() { - // Returning a default would let a typo silently pick the wrong caching for an endpoint. - assertThatThrownBy(() -> WebCachePolicyCatalog.standard().require("no-such-profile")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("published set"); - } - - @Test - @DisplayName("immutable is only claimed where the URL cannot change") - void immutableIsScopedToAddressedContent() { - WebCachePolicy asset = WebCachePolicyCatalog.standard().require("immutable-asset"); - - assertThat(asset.cacheControl()).contains("immutable"); - assertThat(asset.freshness()).contains(Duration.ofDays(365)); - // Nothing else claims it: a year of unrevalidatable staleness on a changing resource has no - // remedy short of changing the URL. - assertThat( - WebCachePolicyCatalog.standard().registered().values().stream() - .filter(policy -> policy.cacheControl().contains("immutable")) - .count()) - .isOne(); - } -} diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/conditional/ConditionalReadEvaluatorTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/conditional/ConditionalReadEvaluatorTest.java deleted file mode 100644 index 3063ff9b..00000000 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/conditional/ConditionalReadEvaluatorTest.java +++ /dev/null @@ -1,88 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.conditional; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** A read asks "is what I hold still good enough to render", which weak comparison answers. */ -class ConditionalReadEvaluatorTest { - - private final ConditionalReadEvaluator evaluator = new ConditionalReadEvaluator(); - - @Test - @DisplayName("a matching validator answers 304") - void aMatchingValidatorAnswers304() { - assertThat(evaluator.evaluate("\"v1\"", EntityTag.strong("v1"))) - .isEqualTo(ConditionalReadDecision.NOT_MODIFIED); - assertThat(evaluator.notModified("\"v0\", \"v1\"", EntityTag.strong("v1"))).isTrue(); - } - - @Test - @DisplayName("a read matches weakly, so a cosmetic difference still hits the cache") - void aReadMatchesWeakly() { - assertThat(evaluator.notModified("W/\"v1\"", EntityTag.strong("v1"))) - .as("strong comparison here sends a full body for every whitespace difference") - .isTrue(); - assertThat(evaluator.notModified("\"v1\"", EntityTag.weak("v1"))).isTrue(); - } - - @Test - @DisplayName("no validator, no header, or no match serves the representation") - void noMatchServesTheRepresentation() { - assertThat(evaluator.evaluate(null, EntityTag.strong("v1"))) - .isEqualTo(ConditionalReadDecision.SERVE_REPRESENTATION); - assertThat(evaluator.evaluate("\"v2\"", EntityTag.strong("v1"))) - .isEqualTo(ConditionalReadDecision.SERVE_REPRESENTATION); - assertThat(evaluator.evaluate("\"v1\"", null)) - .isEqualTo(ConditionalReadDecision.SERVE_REPRESENTATION); - } - - @Test - @DisplayName("the wildcard matches whenever a representation exists") - void theWildcardMatchesWheneverARepresentationExists() { - assertThat(evaluator.notModified("*", EntityTag.strong("v1"))).isTrue(); - assertThat(evaluator.notModified("*", null)).isFalse(); - } - - @Test - @DisplayName("a malformed validator is not silently treated as no validator") - void aMalformedValidatorIsDropped() { - // A malformed entry is dropped from the list rather than turning the whole request - // unconditional, so a client sending one bad tag among good ones still gets its 304. - assertThat(EntityTagCodec.parseList("garbage, \"v1\"")).hasSize(1); - assertThat(EntityTagCodec.parseSingle("v1")) - .as("an unquoted value is not a validator") - .isEmpty(); - assertThat(EntityTagCodec.parseSingle(null)).isEmpty(); - } - - @Test - @DisplayName("the wire form round-trips including weakness") - void theWireFormRoundTrips() { - assertThat(EntityTag.strong("v1").toHeaderValue()).isEqualTo("\"v1\""); - assertThat(EntityTag.weak("v1").toHeaderValue()).isEqualTo("W/\"v1\""); - assertThat(EntityTagCodec.parseSingle("W/\"v1\"")).contains(EntityTag.weak("v1")); - } - - @Test - @DisplayName("a tag value keeps its quotes out and its control characters out") - void aTagValueIsClean() { - assertThatThrownBy(() -> EntityTag.strong("has\"quote")) - .as("keeping the quotes in the value is how a comparison matches the wrong thing") - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> EntityTag.strong("")).isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> EntityTag.strong("a".repeat(257))) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("an application version is not assumed to be a storage ETag") - void anApplicationVersionIsNotAssumedToBeAStorageEtag() { - assertThat(evaluator.toEntityTag("7", true).weak()).isFalse(); - assertThat(evaluator.toEntityTag("7", false).weak()) - .as("a revision, a storage ETag and a provider ETag validate different things") - .isTrue(); - } -} diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/conditional/MutationPreconditionEvaluatorTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/conditional/MutationPreconditionEvaluatorTest.java deleted file mode 100644 index 3449f0cf..00000000 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/conditional/MutationPreconditionEvaluatorTest.java +++ /dev/null @@ -1,99 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.conditional; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.web.operation.PreconditionPolicy; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** A write asks "is this still the thing I read", which only strong comparison answers. */ -class MutationPreconditionEvaluatorTest { - - private final MutationPreconditionEvaluator evaluator = new MutationPreconditionEvaluator(); - - @Test - @DisplayName("a matching strong If-Match proceeds and a mismatch is 412") - void aMatchingStrongIfMatchProceeds() { - assertThat(evaluate("\"v1\"", null, EntityTag.strong("v1"))) - .isEqualTo(PreconditionDecision.PROCEED); - assertThat(evaluate("\"v0\"", null, EntityTag.strong("v1"))) - .isEqualTo(PreconditionDecision.PRECONDITION_FAILED); - } - - @Test - @DisplayName("a weak validator never satisfies If-Match") - void aWeakValidatorNeverSatisfiesIfMatch() { - assertThat(evaluate("W/\"v1\"", null, EntityTag.strong("v1"))) - .as( - "two writers whose representations differ cosmetically would both pass, and the second" - + " would overwrite the first") - .isEqualTo(PreconditionDecision.PRECONDITION_FAILED); - assertThat(evaluate("\"v1\"", null, EntityTag.weak("v1"))) - .isEqualTo(PreconditionDecision.PRECONDITION_FAILED); - } - - @Test - @DisplayName("create-only If-None-Match star fails against an existing resource") - void createOnlyFailsAgainstAnExistingResource() { - assertThat(evaluate(null, "*", EntityTag.strong("v1"))) - .isEqualTo(PreconditionDecision.PRECONDITION_FAILED); - assertThat(evaluate(null, "*", null)).isEqualTo(PreconditionDecision.PROCEED); - } - - @Test - @DisplayName("update-only If-Match star fails against a missing resource") - void updateOnlyFailsAgainstAMissingResource() { - assertThat(evaluate("*", null, null)).isEqualTo(PreconditionDecision.PRECONDITION_FAILED); - assertThat(evaluate("*", null, EntityTag.strong("v1"))).isEqualTo(PreconditionDecision.PROCEED); - } - - @Test - @DisplayName("a required precondition that was not supplied is 428, not 412") - void aRequiredPreconditionThatWasNotSuppliedIs428() { - assertThat( - evaluator.evaluate( - PreconditionPolicy.REQUIRED, HttpPrecondition.none(), EntityTag.strong("v1"))) - .as("412 would tell a client to retry something that cannot succeed unchanged") - .isEqualTo(PreconditionDecision.PRECONDITION_REQUIRED); - assertThat( - evaluator.evaluate( - PreconditionPolicy.OPTIONAL, HttpPrecondition.none(), EntityTag.strong("v1"))) - .isEqualTo(PreconditionDecision.PROCEED); - } - - @Test - @DisplayName("the throwing form carries which outcome occurred") - void theThrowingFormCarriesTheOutcome() { - assertThatCode( - () -> - evaluator.requireSatisfied( - PreconditionPolicy.OPTIONAL, - HttpPrecondition.of("\"v1\"", null), - EntityTag.strong("v1"))) - .doesNotThrowAnyException(); - - assertThatThrownBy( - () -> - evaluator.requireSatisfied( - PreconditionPolicy.REQUIRED, HttpPrecondition.none(), EntityTag.strong("v1"))) - .isInstanceOf(WebPreconditionFailedException.class) - .extracting(failure -> ((WebPreconditionFailedException) failure).decision()) - .isEqualTo(PreconditionDecision.PRECONDITION_REQUIRED); - } - - @Test - @DisplayName("no precondition supplied is a distinguishable state") - void noPreconditionSuppliedIsDistinguishable() { - assertThat(HttpPrecondition.none().present()).isFalse(); - assertThat(HttpPrecondition.of("\"v1\"", null).present()).isTrue(); - assertThat(HttpPrecondition.of("*", null).ifMatchWildcard()).isTrue(); - assertThat(HttpPrecondition.of(null, "*").ifNoneMatchWildcard()).isTrue(); - } - - private PreconditionDecision evaluate(String ifMatch, String ifNoneMatch, EntityTag current) { - return evaluator.evaluate( - PreconditionPolicy.OPTIONAL, HttpPrecondition.of(ifMatch, ifNoneMatch), current); - } -} diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/config/PresentationWebConfigTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/config/PresentationWebConfigTest.java index fe12aa84..f4ad64d9 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/config/PresentationWebConfigTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/config/PresentationWebConfigTest.java @@ -9,11 +9,7 @@ import dev.caskeleton.adapter.inbound.web.fileserver.controller.FileUploadContro import dev.caskeleton.adapter.inbound.web.fileserver.draft12.Draft12UploadController; import dev.caskeleton.adapter.inbound.web.fileserver.lifecycle.FileLifecycleController; import dev.caskeleton.adapter.inbound.web.fileserver.tus.TusController; -import dev.caskeleton.adapter.inbound.web.mvc.operation.OperationHttpController; -import dev.caskeleton.adapter.inbound.web.notification.platform.callback.NotificationCallbackMvcController; -import dev.caskeleton.adapter.inbound.web.notification.platform.submission.NotificationSubmissionController; import dev.caskeleton.adapter.inbound.web.settings.PresentationSettings; -import dev.caskeleton.adapter.inbound.web.webflux.operation.ReactiveOperationHttpController; import java.util.List; import java.util.function.Predicate; import org.junit.jupiter.api.Test; @@ -36,10 +32,7 @@ class PresentationWebConfigTest { FileLifecycleController.class, FileserverAdminController.class, FileDownloadController.class, - FileUploadController.class, - OperationHttpController.class, - ReactiveOperationHttpController.class, - NotificationCallbackMvcController.class)) + FileUploadController.class)) .allMatch(controller -> !predicate.test(controller)); } @@ -51,7 +44,6 @@ class PresentationWebConfigTest { Predicate> predicate = configurer.prefix("/v1"); assertThat(predicate.test(HealthcheckController.class)).isTrue(); - assertThat(predicate.test(NotificationSubmissionController.class)).isTrue(); } private static final class InspectablePathMatchConfigurer extends PathMatchConfigurer { diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/core/WebIdentifierTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/core/WebIdentifierTest.java index 06441218..720e344c 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/core/WebIdentifierTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/core/WebIdentifierTest.java @@ -51,18 +51,6 @@ class WebIdentifierTest { assertThatThrownBy(() -> new ApiMajorVersion(-1)).isInstanceOf(IllegalArgumentException.class); } - @Test - @DisplayName("a route id is a non-blank, bounded template") - void aRouteIdIsANonBlankBoundedTemplate() { - assertThat(new WebRouteId("GET /api/v1/orders/{orderId}").value()) - .as("the template, not a resolved URI: one route, not the thousand URIs it serves") - .isEqualTo("GET /api/v1/orders/{orderId}"); - assertThatThrownBy(() -> new WebRouteId(" ")).isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> new WebRouteId(null)).isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> new WebRouteId("x".repeat(257))) - .isInstanceOf(IllegalArgumentException.class); - } - @Test @DisplayName("request and trace identifiers are non-blank and bounded") void requestAndTraceIdentifiersAreBounded() { diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/cursor/CursorCodecTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/cursor/CursorCodecTest.java deleted file mode 100644 index 17818d69..00000000 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/cursor/CursorCodecTest.java +++ /dev/null @@ -1,57 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.cursor; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; - -import java.nio.charset.StandardCharsets; -import java.time.Duration; -import java.time.Instant; -import org.junit.jupiter.api.Test; - -class CursorCodecTest { - - private final CursorCodec codec = CursorCodec.withDevKey(); - private static final Instant T0 = Instant.parse("2026-06-02T00:00:00Z"); - - @Test - void roundTripsThePayload() { - String token = codec.encode("01HZX9-after", T0); - assertThat(codec.decode(token, T0.plusSeconds(60))).isEqualTo("01HZX9-after"); - } - - @Test - void tokenIsUrlSafeAndNotPlainlyThePayload() { - String token = codec.encode("offset=40", T0); - assertThat(token).doesNotContain("offset=40"); // opacity: not the raw payload - assertThat(token).matches("[A-Za-z0-9_.\\-]+"); // URL-safe (base64url + '.') - } - - @Test - void tamperedTokenIsRejected() { - String token = codec.encode("01HZX9", T0); - String tampered = token.substring(0, token.length() - 1) + (token.endsWith("A") ? "B" : "A"); - assertThatExceptionOfType(CursorException.class) - .isThrownBy(() -> codec.decode(tampered, T0.plusSeconds(1))); - } - - @Test - void expiredTokenIsRejectedAfterTtl() { - String token = codec.encode("01HZX9", T0); - assertThatExceptionOfType(CursorException.class) - .isThrownBy(() -> codec.decode(token, T0.plus(Duration.ofHours(24)).plusSeconds(1))); - } - - @Test - void malformedTokenIsRejected() { - assertThatExceptionOfType(CursorException.class) - .isThrownBy(() -> codec.decode("not-a-valid-token", T0)); - } - - @Test - void shortKeyIsRefused() { - assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy( - () -> - new CursorCodec("short".getBytes(StandardCharsets.UTF_8), CursorCodec.DEFAULT_TTL)); - } -} diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/GlobalExceptionHandlerTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/GlobalExceptionHandlerTest.java index d6102747..4e83d823 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/GlobalExceptionHandlerTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/GlobalExceptionHandlerTest.java @@ -8,7 +8,6 @@ import static org.mockito.Mockito.when; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.read.ListAppender; import dev.caskeleton.adapter.inbound.web.conditional.PreconditionFailedException; -import dev.caskeleton.adapter.inbound.web.cursor.CursorException; import dev.caskeleton.adapter.inbound.web.http.ApiHeaders; import dev.caskeleton.adapter.inbound.web.pagination.PageValidationException; import dev.caskeleton.shared.error.AdapterDisabledException; @@ -124,23 +123,18 @@ class GlobalExceptionHandlerTest { } @Test - void paginationAndCursorExceptionsUseSafeDetailsAndFixedMessages() { - String secret = "SECRET_CURSOR_OR_FILTER_VALUE"; + void paginationExceptionsUseSafeDetailsAndFixedMessages() { + String secret = "SECRET_FILTER_VALUE"; ResponseEntity> page = handler.handlePageValidation( new PageValidationException("size", "SIZE_EXCEEDS_MAX", secret)); - ResponseEntity> cursor = handler.handleCursor(new CursorException(secret)); assertThat(page.getBody()).isNotNull(); assertThat(page.getBody().error().message()).isEqualTo("Pagination parameter is invalid"); assertThat(page.getBody().error().details()) .isEqualTo(Map.of("field", "size", "code", "SIZE_EXCEEDS_MAX")); - assertThat(cursor.getBody()).isNotNull(); - assertThat(cursor.getBody().error().message()) - .isEqualTo("Cursor is invalid or expired; re-request the first page"); assertThat(page.getBody().error().toString()).doesNotContain(secret); - assertThat(cursor.getBody().error().toString()).doesNotContain(secret); } @Test diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/IdempotencyExceptionMappingTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/IdempotencyExceptionMappingTest.java index d1b1169d..6f1ef17f 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/IdempotencyExceptionMappingTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/IdempotencyExceptionMappingTest.java @@ -4,51 +4,64 @@ import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.application.idempotency.IdempotencyInFlightException; import dev.caskeleton.application.idempotency.IdempotencyRequestMismatchException; -import dev.caskeleton.application.idempotency.IdempotencyScope; -import dev.caskeleton.application.idempotency.IdempotencyScopeMissingException; import dev.caskeleton.shared.response.Envelope; import dev.caskeleton.shared.tracing.SpanErrorRecorder; import org.junit.jupiter.api.Test; -import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; class IdempotencyExceptionMappingTest { - private static final IdempotencyScope SCOPE = - IdempotencyScope.of("user-1", "key-1", "CreateWorkLogUseCase"); + private static final String SCOPE_DIAGNOSTIC = "CREATE_WORKLOG::v1::" + "a".repeat(64); private final GlobalExceptionHandler handler = new GlobalExceptionHandler(SpanErrorRecorder.NOOP); @Test - void inFlightMapsTo409ConflictNotRetryable() { - ResponseEntity> res = - handler.handleIdempotentInFlight(new IdempotencyInFlightException(SCOPE)); + void inFlightMapsToNonRetryable409ConflictWithFixedMessage() { + // given + IdempotencyInFlightException inFlight = + IdempotencyInFlightException.forScopeDigest(SCOPE_DIAGNOSTIC); - assertThat(res.getStatusCode()).isEqualTo(HttpStatus.CONFLICT); - assertThat(res.getBody().error().code()).isEqualTo("IDEMPOTENT_IN_FLIGHT"); - assertThat(res.getBody().error().category()).isEqualTo("CONFLICT"); - assertThat(res.getBody().error().retryable()).isFalse(); - // diagnostic (with scope/principal) must not leak into the client message - assertThat(res.getBody().error().message()).doesNotContain("user-1"); + // when + ResponseEntity> response = handler.handleIdempotentInFlight(inFlight); + + // then + assertThat(response) + .extracting( + r -> r.getStatusCode().value(), + r -> r.getBody().error().code(), + r -> r.getBody().error().category(), + r -> r.getBody().error().retryable(), + r -> r.getBody().error().message()) + .containsExactly( + 409, + "IDEMPOTENT_IN_FLIGHT", + "CONFLICT", + false, + "A previous identical request is still being processed, please poll for result"); } @Test - void mismatchMapsTo422ValidationNotRetryable() { - ResponseEntity> res = - handler.handleIdempotentMismatch(new IdempotencyRequestMismatchException(SCOPE)); + void mismatchMapsToNonRetryable422ValidationWithFixedMessage() { + // given + IdempotencyRequestMismatchException mismatch = + IdempotencyRequestMismatchException.forScopeDigest(SCOPE_DIAGNOSTIC); - assertThat(res.getStatusCode().value()).isEqualTo(422); - assertThat(res.getBody().error().code()).isEqualTo("IDEMPOTENT_REQUEST_MISMATCH"); - assertThat(res.getBody().error().category()).isEqualTo("VALIDATION"); - assertThat(res.getBody().error().retryable()).isFalse(); - } + // when + ResponseEntity> response = handler.handleIdempotentMismatch(mismatch); - @Test - void scopeMissingMapsTo400Validation() { - ResponseEntity> res = - handler.handleIdempotencyScopeMissing(new IdempotencyScopeMissingException("principal")); - - assertThat(res.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST); - assertThat(res.getBody().error().code()).isEqualTo("VALIDATION_FAILED"); + // then + assertThat(response) + .extracting( + r -> r.getStatusCode().value(), + r -> r.getBody().error().code(), + r -> r.getBody().error().category(), + r -> r.getBody().error().retryable(), + r -> r.getBody().error().message()) + .containsExactly( + 422, + "IDEMPOTENT_REQUEST_MISMATCH", + "VALIDATION", + false, + "Idempotency key reused with different request body"); } } diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/ProblemCatalogTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/ProblemCatalogTest.java deleted file mode 100644 index 515d315f..00000000 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/ProblemCatalogTest.java +++ /dev/null @@ -1,99 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.error; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.io.IOException; -import java.io.UncheckedIOException; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.EnumMap; -import java.util.Map; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** One code, one status, everywhere, and the published document says the same. */ -class ProblemCatalogTest { - - private final ProblemCatalog catalog = ProblemCatalog.standard(); - - @Test - @DisplayName("validation is 422 and a precondition is 412") - void validationIs422AndAPreconditionIs412() { - assertThat(catalog.require(ProblemCode.VALIDATION_FAILED).status()).isEqualTo(422); - assertThat(catalog.require(ProblemCode.PRECONDITION_FAILED).status()).isEqualTo(412); - assertThat(catalog.require(ProblemCode.MALFORMED_REQUEST).status()) - .as("a document that is not JSON is a 400, not a 422") - .isEqualTo(400); - } - - @Test - @DisplayName("a dependency failure and a dependency timeout are different statuses") - void aDependencyFailureAndTimeoutAreDifferentStatuses() { - assertThat(catalog.require(ProblemCode.DEPENDENCY_FAILURE).status()).isEqualTo(502); - assertThat(catalog.require(ProblemCode.DEPENDENCY_TIMEOUT).status()) - .as("504 tells a caller the request may still be running; 502 tells it the request is not") - .isEqualTo(504); - } - - @Test - @DisplayName("every code is defined, and a partial catalog is refused") - void everyCodeIsDefined() { - for (ProblemCode code : ProblemCode.values()) { - assertThat(catalog.require(code)).isNotNull(); - } - Map partial = new EnumMap<>(ProblemCode.class); - partial.put(ProblemCode.INTERNAL_ERROR, catalog.require(ProblemCode.INTERNAL_ERROR)); - - assertThatThrownBy(() -> new ProblemCatalog(partial)) - .as("an undefined code becomes a status somebody picks at the call site") - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("missing a definition"); - } - - @Test - @DisplayName("every status is a 4xx or 5xx and every type shares the published namespace") - void everyStatusIsAFailureAndEveryTypeIsNamespaced() { - catalog - .definitions() - .forEach( - (code, definition) -> { - assertThat(definition.status()).isBetween(400, 599); - assertThat(definition.type().toString()).startsWith(ProblemCatalog.TYPE_PREFIX); - assertThat(definition.title()).isNotBlank(); - }); - } - - @Test - @DisplayName("the published document says exactly what the catalog says") - void thePublishedDocumentSaysExactlyWhatTheCatalogSays() { - String yaml = readCatalogResource(); - - catalog - .definitions() - .forEach( - (code, definition) -> - assertThat(yaml) - .as("%s must appear in the published catalog", code) - .contains(code.name() + ":") - .contains("type: " + definition.type()) - .contains("status: " + definition.status())); - } - - private static String readCatalogResource() { - for (Path directory = Path.of("").toAbsolutePath(); - directory != null; - directory = directory.getParent()) { - Path candidate = directory.resolve("src/main/resources/META-INF/web/problem-catalog.yaml"); - if (Files.isRegularFile(candidate)) { - try { - return Files.readString(candidate, StandardCharsets.UTF_8); - } catch (IOException unreadable) { - throw new UncheckedIOException(unreadable); - } - } - } - throw new IllegalStateException("the published problem catalog is missing"); - } -} diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/TransportErrorHandlingTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/TransportErrorHandlingTest.java index 17860c0f..eb41e404 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/TransportErrorHandlingTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/TransportErrorHandlingTest.java @@ -10,7 +10,6 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import dev.caskeleton.adapter.inbound.web.conditional.PreconditionFailedException; -import dev.caskeleton.adapter.inbound.web.cursor.CursorException; import dev.caskeleton.adapter.inbound.web.envelope.EnvelopeBodyAdvice; import dev.caskeleton.adapter.inbound.web.pagination.PageValidationException; import dev.caskeleton.shared.tracing.SpanErrorRecorder; @@ -100,14 +99,6 @@ class TransportErrorHandlingTest { .andExpect(jsonPath("$.error.details.code").value("SIZE_EXCEEDS_MAX")); } - @Test - void badCursorIs400Validation() throws Exception { - mvc.perform(get("/t/bad-cursor")) - .andExpect(status().isBadRequest()) - .andExpect(jsonPath("$.error.code").value("VALIDATION_FAILED")) - .andExpect(jsonPath("$.error.details.code").value("CURSOR_INVALID")); - } - @RestController static class Probe { @@ -140,10 +131,5 @@ class TransportErrorHandlingTest { Map badPage() { throw new PageValidationException("size", "SIZE_EXCEEDS_MAX", "size must be <= 100"); } - - @GetMapping("/t/bad-cursor") - Map badCursor() { - throw new CursorException("cursor token signature is invalid"); - } } } diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/WebProblemFactoryTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/WebProblemFactoryTest.java deleted file mode 100644 index 58e1e305..00000000 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/WebProblemFactoryTest.java +++ /dev/null @@ -1,122 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.error; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.net.URI; -import java.util.List; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * The factory is the only door, and everything that goes through it comes out publishable. - * - *

Each case here is a real leak shape: a stack trace in an exception message, a - * package-qualified class name, a connection URL, a bearer token echoed from a header, a fragment - * of SQL. - */ -class WebProblemFactoryTest { - - private final WebProblemFactory factory = WebProblemFactory.standard(); - - @Test - @DisplayName("a stack trace is stripped and the stable code survives") - void aStackTraceIsStrippedAndTheStableCodeSurvives() { - WebProblem problem = - factory.create( - ProblemCode.INTERNAL_ERROR, - "java.lang.IllegalStateException: broke" - + NEWLINE - + " at internal.Service.run(Service.java:42)", - URI.create("/problems/p1"), - "trace-1", - List.of()); - - assertThat(problem.status()).isEqualTo(500); - assertThat(problem.detail()).doesNotContain("internal.Service"); - assertThat(problem.detail()).doesNotContain("Service.java"); - assertThat(problem.code()).isEqualTo(ProblemCode.INTERNAL_ERROR); - assertThat(problem.traceId()).isEqualTo("trace-1"); - } - - @Test - @DisplayName("a connection url, a credential and a query fragment are all removed") - void internalDetailsAreRemoved() { - WebProblemSanitizer sanitizer = new WebProblemSanitizer(); - - assertThat(sanitizer.sanitize("failed against jdbc://db-primary.internal:5432/orders", 256)) - .doesNotContain("db-primary.internal"); - assertThat(sanitizer.sanitize("Authorization: Bearer eyJhbGciOi", 256)) - .doesNotContain("eyJhbGciOi"); - assertThat(sanitizer.sanitize("select secret from users where id = 4", 256)) - .doesNotContain("users"); - assertThat(sanitizer.sanitize("/etc/secrets/app/token", 256)).doesNotContain("/etc/secrets"); - } - - @Test - @DisplayName("detail is bounded by the catalog and never empty") - void detailIsBoundedAndNeverEmpty() { - WebProblem problem = - factory.create( - ProblemCode.AUTHENTICATION_REQUIRED, - "x".repeat(1000), - URI.create("/problems/p2"), - "trace-2", - List.of()); - - assertThat(problem.detail()).hasSizeLessThanOrEqualTo(128); - assertThat( - factory - .create(ProblemCode.ACCESS_DENIED, null, URI.create("/p"), "t", List.of()) - .detail()) - .isEqualTo(WebProblemSanitizer.REDACTED); - assertThat(new WebProblemSanitizer().sanitize(" ", 64)) - .isEqualTo(WebProblemSanitizer.REDACTED); - } - - @Test - @DisplayName("a status disagreement fails before serialization") - void aStatusDisagreementFailsBeforeSerialization() { - WebProblem problem = - factory.create(ProblemCode.RESOURCE_CONFLICT, "conflict", URI.create("/p"), "t", List.of()); - - assertThatCode(() -> factory.requireStatusAgreement(409, problem)).doesNotThrowAnyException(); - assertThatThrownBy(() -> factory.requireStatusAgreement(500, problem)) - .as("a client will branch on one of them and cannot be told which") - .isInstanceOf(ProblemStatusMismatchException.class); - } - - @Test - @DisplayName("only the two published extensions are allowed") - void onlyThePublishedExtensionsAreAllowed() { - assertThat(SafeProblemDetailExtensions.allowed("traceId")).isTrue(); - assertThat(SafeProblemDetailExtensions.allowed("errors")).isTrue(); - assertThat(SafeProblemDetailExtensions.allowed("cause")) - .as("an open extension set is how an exception message ships to every caller") - .isFalse(); - assertThatThrownBy(() -> SafeProblemDetailExtensions.requireAllowed("stackTrace")) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("a validation issue points with a JSON Pointer and carries no submitted value") - void aValidationIssuePointsWithAJsonPointer() { - ValidationIssue issue = - new ValidationIssue("/order/lines/0/quantity", "must-be-positive", "must be positive"); - - assertThat(issue.pointer()).startsWith("/"); - assertThatThrownBy(() -> new ValidationIssue("createOrder.arg0.quantity", "c", "m")) - .as("a Java property path is unusable to a client and discloses an internal signature") - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("the factory reports the status a code is always answered with") - void theFactoryReportsTheStatusForACode() { - assertThat(factory.statusFor(ProblemCode.RATE_LIMITED)).isEqualTo(429); - assertThat(factory.statusFor(ProblemCode.VALIDATION_FAILED)).isEqualTo(422); - } - - private static final String NEWLINE = "\n"; -} diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/evidence/WebExecutionEvidenceTrackerTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/evidence/WebExecutionEvidenceTrackerTest.java deleted file mode 100644 index 9dc9f241..00000000 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/evidence/WebExecutionEvidenceTrackerTest.java +++ /dev/null @@ -1,156 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.evidence; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * The three axes stay three axes, and none of them runs backwards. - * - *

The case each of these protects is the same one: a request that committed and then failed to - * answer. A model that collapses the axes, or that lets a later stage lower an earlier verdict, - * reports that request as retryable — and the retry is a duplicate write. - */ -class WebExecutionEvidenceTrackerTest { - - @Test - @DisplayName("a completed local write never claims the client observed it") - void aCompletedLocalWriteNeverClaimsTheClientObservedIt() { - WebExecutionEvidenceTracker tracker = WebExecutionEvidenceTracker.received(); - tracker.markApplicationCommitted(); - tracker.markLocalResponseWriteCompleted(); - - WebExecutionEvidence evidence = tracker.snapshot(); - - assertThat(evidence.responseEvidence()) - .isEqualTo(WebResponseEvidence.RESPONSE_WRITE_COMPLETED_LOCALLY); - assertThat(evidence.responseEvidence()) - .as("no value on this axis may be read as proof the client received anything") - .isNotEqualTo(WebResponseEvidence.CLIENT_OBSERVATION_UNKNOWN); - } - - @Test - @DisplayName("the axes advance independently of one another") - void theAxesAdvanceIndependently() { - WebExecutionEvidenceTracker tracker = WebExecutionEvidenceTracker.received(); - - tracker.markApplicationCommitted(); - - assertThat(tracker.snapshot().requestPhase()) - .as("committing the application says nothing about how admission went") - .isEqualTo(WebRequestPhase.HTTP_RECEIVED); - assertThat(tracker.snapshot().responseEvidence()) - .as("committing the application says nothing about the response") - .isEqualTo(WebResponseEvidence.NOT_COMMITTED); - } - - @Test - @DisplayName("an evidence transition never runs backwards") - void anEvidenceTransitionNeverRunsBackwards() { - WebExecutionEvidenceTracker tracker = WebExecutionEvidenceTracker.received(); - tracker.markPhase(WebRequestPhase.REQUEST_ADMITTED); - tracker.markApplicationCommitted(); - tracker.markLocalResponseWriteCompleted(); - - tracker.markPhase(WebRequestPhase.ROUTE_SELECTED); - tracker.markApplicationStarted(); - tracker.markResponseHeadersCommitted(); - - WebExecutionEvidence evidence = tracker.snapshot(); - assertThat(evidence.requestPhase()).isEqualTo(WebRequestPhase.REQUEST_ADMITTED); - assertThat(evidence.applicationEvidence()) - .as("a late report must not lower a commit to started; that is a duplicate write") - .isEqualTo(WebApplicationEvidence.APPLICATION_COMMITTED); - assertThat(evidence.responseEvidence()) - .isEqualTo(WebResponseEvidence.RESPONSE_WRITE_COMPLETED_LOCALLY); - } - - @Test - @DisplayName("only a proven-untouched application is safe to retry") - void onlyAProvenUntouchedApplicationIsSafeToRetry() { - assertThat(evidenceWith(WebApplicationEvidence.NOT_STARTED).safeToRetryMutation()).isTrue(); - assertThat(evidenceWith(WebApplicationEvidence.APPLICATION_ROLLED_BACK).safeToRetryMutation()) - .isTrue(); - assertThat(evidenceWith(WebApplicationEvidence.APPLICATION_STARTED).safeToRetryMutation()) - .as("entered and unobserved may have committed") - .isFalse(); - assertThat(evidenceWith(WebApplicationEvidence.APPLICATION_UNKNOWN).safeToRetryMutation()) - .isFalse(); - assertThat(evidenceWith(WebApplicationEvidence.APPLICATION_COMMITTED).safeToRetryMutation()) - .isFalse(); - } - - @Test - @DisplayName("a commit whose response was not completed locally needs reconciliation") - void aCommitWhoseResponseWasNotCompletedNeedsReconciliation() { - WebExecutionEvidenceTracker tracker = WebExecutionEvidenceTracker.received(); - tracker.markApplicationCommitted(); - tracker.markResponseHeadersCommitted(); - - assertThat(tracker.snapshot().requiresReconciliation()).isTrue(); - - tracker.markLocalResponseWriteCompleted(); - assertThat(tracker.snapshot().requiresReconciliation()).isFalse(); - - WebExecutionEvidenceTracker unknown = WebExecutionEvidenceTracker.received(); - unknown.markApplicationUnknown(); - unknown.markLocalResponseWriteCompleted(); - assertThat(unknown.snapshot().requiresReconciliation()) - .as("an unobserved application outcome is never settled by a successful write") - .isTrue(); - } - - @Test - @DisplayName("concurrent reporters cannot lose the strongest evidence") - void concurrentReportersCannotLoseTheStrongestEvidence() throws Exception { - // A container thread can complete a request while an async dispatch is still reporting, so the - // transition has to be a CAS rather than a read-modify-write. - WebExecutionEvidenceTracker tracker = WebExecutionEvidenceTracker.received(); - int reporters = 32; - CountDownLatch start = new CountDownLatch(1); - ExecutorService pool = Executors.newFixedThreadPool(8); - List> reports = new ArrayList<>(reporters); - try { - for (int i = 0; i < reporters; i++) { - boolean strong = i % 2 == 0; - reports.add( - pool.submit( - () -> { - start.await(5, TimeUnit.SECONDS); - if (strong) { - tracker.markApplicationCommitted(); - } else { - tracker.markApplicationStarted(); - } - return null; - })); - } - start.countDown(); - // Each future is read rather than discarded: a reporter that threw would otherwise leave the - // assertion below passing on evidence nobody actually recorded. - for (Future report : reports) { - report.get(10, TimeUnit.SECONDS); - } - pool.shutdown(); - assertThat(pool.awaitTermination(10, TimeUnit.SECONDS)).isTrue(); - } finally { - pool.shutdownNow(); - } - - assertThat(tracker.snapshot().applicationEvidence()) - .isEqualTo(WebApplicationEvidence.APPLICATION_COMMITTED); - } - - private static WebExecutionEvidence evidenceWith(WebApplicationEvidence application) { - return new WebExecutionEvidence( - WebRequestPhase.REQUEST_ADMITTED, application, WebResponseEvidence.NOT_COMMITTED); - } -} diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/http/ExternalUriBuilderTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/http/ExternalUriBuilderTest.java deleted file mode 100644 index 3728ba0f..00000000 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/http/ExternalUriBuilderTest.java +++ /dev/null @@ -1,141 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.http; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.web.proxy.NormalizedForwardedHeaders; -import java.util.Map; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * A URL this API hands back is a URL a client will follow, so both ways of getting it wrong are - * silent: a doubled prefix produces a 404 the client cannot diagnose, and a header-derived host - * produces a link that points wherever the caller said. - */ -class ExternalUriBuilderTest { - - private static final ExternalOrigin SERVER = new ExternalOrigin("http", "10.0.0.4", 8080); - - @Test - @DisplayName("the prefix is applied exactly once") - void thePrefixIsAppliedExactlyOnce() { - ExternalUriBuilder builder = - new ExternalUriBuilder(ExternalOrigin.https("api.example.com"), new ExternalPrefix("/api")); - - assertThat(builder.relative("/v1/orders/1")).isEqualTo("/api/v1/orders/1"); - assertThat(builder.relative("/api/v1/orders/1")) - .as("a path the gateway already prefixed must not be prefixed again") - .isEqualTo("/api/v1/orders/1"); - assertThat(builder.absolute("/v1/orders/1")) - .isEqualTo("https://api.example.com/api/v1/orders/1"); - } - - @Test - @DisplayName("prefix matching is segment-aware") - void prefixMatchingIsSegmentAware() { - ExternalUriBuilder builder = - new ExternalUriBuilder(ExternalOrigin.https("api.example.com"), new ExternalPrefix("/api")); - - assertThat(builder.relative("/apiary/bees")) - .as("/apiary is not an already-prefixed /api path, and treating it as one loses a segment") - .isEqualTo("/api/apiary/bees"); - } - - @Test - @DisplayName("a configured origin beats anything a proxy says") - void aConfiguredOriginBeatsAnythingAProxySays() { - ExternalUriPolicy policy = - ExternalUriPolicy.configured( - ExternalOrigin.https("api.example.com"), ExternalPrefix.none()); - NormalizedForwardedHeaders hostile = - NormalizedForwardedHeaders.fromTrustedHeaders( - Map.of("X-Forwarded-Host", "evil.example", "X-Forwarded-Proto", "http")); - - assertThat(policy.resolveOrigin(hostile, SERVER).value()) - .as("a reset link must point where the deployment says, not where a header does") - .isEqualTo("https://api.example.com"); - } - - @Test - @DisplayName("a gateway deployment learns its public name from the trusted proxy") - void aGatewayDeploymentLearnsItsPublicNameFromTheProxy() { - ExternalUriPolicy policy = ExternalUriPolicy.fromTrustedProxy(ExternalPrefix.none()); - NormalizedForwardedHeaders forwarded = - NormalizedForwardedHeaders.fromTrustedHeaders( - Map.of("X-Forwarded-Host", "api.example.com", "X-Forwarded-Proto", "https")); - - ExternalOrigin resolved = policy.resolveOrigin(forwarded, SERVER); - - assertThat(resolved.value()).isEqualTo("https://api.example.com"); - assertThat(resolved.port()) - .as("the server's own 8080 is the internal port and means nothing externally") - .isEqualTo(443); - } - - @Test - @DisplayName("with no forwarded facts the server's own socket is used") - void withNoForwardedFactsTheServerSocketIsUsed() { - ExternalUriPolicy policy = ExternalUriPolicy.fromTrustedProxy(ExternalPrefix.none()); - - assertThat(policy.resolveOrigin(NormalizedForwardedHeaders.none(), SERVER).value()) - .isEqualTo("http://10.0.0.4:8080"); - } - - @Test - @DisplayName("a configured prefix beats a forwarded one") - void aConfiguredPrefixBeatsAForwardedOne() { - NormalizedForwardedHeaders forwarded = - NormalizedForwardedHeaders.fromTrustedHeaders(Map.of("X-Forwarded-Prefix", "/gateway")); - - assertThat( - ExternalUriPolicy.configured( - ExternalOrigin.https("api.example.com"), new ExternalPrefix("/api")) - .resolvePrefix(forwarded) - .value()) - .isEqualTo("/api"); - assertThat( - ExternalUriPolicy.fromTrustedProxy(ExternalPrefix.none()) - .resolvePrefix(forwarded) - .value()) - .isEqualTo("/gateway"); - } - - @Test - @DisplayName("a prefix is normalised and a traversing one is refused") - void aPrefixIsNormalisedAndATraversingOneIsRefused() { - assertThat(new ExternalPrefix("/api/").value()).isEqualTo("/api"); - assertThat(ExternalPrefix.none().empty()).isTrue(); - assertThatThrownBy(() -> new ExternalPrefix("api")) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> new ExternalPrefix("/../admin")) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("Location is absolute, and a relative application path is required") - void locationIsAbsolute() { - ExternalUriBuilder builder = - new ExternalUriBuilder(ExternalOrigin.https("api.example.com"), ExternalPrefix.none()); - - assertThat(builder.location("/v1/orders/1")) - .as( - "intermediaries have historically disagreed about what a relative Location is relative to") - .isEqualTo("https://api.example.com/v1/orders/1"); - assertThatThrownBy(() -> builder.relative("v1/orders/1")) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("a default port is implicit and a non-default one is not") - void aDefaultPortIsImplicit() { - assertThat(ExternalOrigin.https("api.example.com").value()) - .isEqualTo("https://api.example.com"); - assertThat(new ExternalOrigin("http", "api.example.com", 80).value()) - .isEqualTo("http://api.example.com"); - assertThat(new ExternalOrigin("https", "api.example.com", 8443).value()) - .isEqualTo("https://api.example.com:8443"); - assertThatThrownBy(() -> new ExternalOrigin("ftp", "h", 21)) - .isInstanceOf(IllegalArgumentException.class); - } -} diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/http/WebResponseContractTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/http/WebResponseContractTest.java deleted file mode 100644 index 81495ad1..00000000 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/http/WebResponseContractTest.java +++ /dev/null @@ -1,81 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.http; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.util.Map; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** The status rules are enforced where a response is built, not reported after it is written. */ -class WebResponseContractTest { - - private final WebResponseContract contract = new WebResponseContract(); - - @Test - @DisplayName("204 and 304 cannot carry a body") - void noContentCannotCarryABody() { - assertThatThrownBy(() -> contract.validate(204, Map.of(), "body")) - .as("some intermediaries drop it and some forward it, so behaviour depends on the proxy") - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> contract.validate(304, Map.of("ETag", "\"v1\""), "body")) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("201 and 202 require a Location") - void createdAndAcceptedRequireALocation() { - assertThatThrownBy(() -> contract.validate(201, Map.of(), new Object())) - .as("without it the client is told something exists and not where") - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> contract.validate(202, Map.of(), new Object())) - .isInstanceOf(IllegalArgumentException.class); - assertThatCode( - () -> contract.validate(201, Map.of("Location", "/api/v1/orders/1"), new Object())) - .doesNotThrowAnyException(); - } - - @Test - @DisplayName("304 must repeat the validator it matched") - void notModifiedMustRepeatTheValidator() { - assertThatThrownBy(() -> contract.validate(304, Map.of(), null)) - .as("otherwise the next conditional read has no validator to send") - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("the factories build only responses the contract allows") - void theFactoriesBuildOnlyAllowedResponses() { - assertThat(WebSuccessResponse.created("/api/v1/orders/1", "body").location()) - .contains("/api/v1/orders/1"); - assertThat(WebSuccessResponse.noContent().body()).isNull(); - assertThat(WebSuccessResponse.notModified("\"v1\"").headers()).containsKey("ETag"); - assertThat(WebSuccessResponse.ok("body").status()).isEqualTo(200); - } - - @Test - @DisplayName("a HEAD response keeps the GET headers exactly and drops only the body") - void aHeadResponseKeepsTheHeadersExactly() { - WebSuccessResponse get = - new WebSuccessResponse<>(200, Map.of("ETag", "\"v1\"", "Vary", "Accept"), "body"); - - WebSuccessResponse head = get.asHeadResponse(); - - assertThat(head.body()).isNull(); - assertThat(head.headers()) - .as("a HEAD whose headers differ from its GET defeats the only reason to send one") - .isEqualTo(get.headers()); - } - - @Test - @DisplayName("a non-success status is not a success response") - void aNonSuccessStatusIsNotASuccessResponse() { - assertThatThrownBy(() -> new WebSuccessResponse<>(500, Map.of(), "body")) - .isInstanceOf(IllegalArgumentException.class); - assertThat(WebStatusContract.forbidsBody(204)).isTrue(); - assertThat(WebStatusContract.requiresLocation(202)).isTrue(); - assertThat(WebStatusContract.success(204)).isTrue(); - assertThat(WebStatusContract.success(304)).isFalse(); - } -} diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/idempotency/InMemoryIdempotencyStore.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/idempotency/InMemoryIdempotencyStore.java deleted file mode 100644 index 6b411244..00000000 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/idempotency/InMemoryIdempotencyStore.java +++ /dev/null @@ -1,70 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.idempotency; - -import dev.caskeleton.application.idempotency.IdempotencyRecord; -import dev.caskeleton.application.idempotency.IdempotencyScope; -import dev.caskeleton.application.idempotency.IdempotencyStatus; -import dev.caskeleton.application.idempotency.IdempotencyStorePort; -import dev.caskeleton.application.idempotency.RequestFingerprint; -import dev.caskeleton.application.idempotency.StoredResponse; -import java.time.Instant; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.ConcurrentHashMap; - -/** - * A store with the one property the gate depends on: {@code tryBegin} is atomic. - * - *

Backed by {@code putIfAbsent} rather than a get-then-put, because a fake whose claim is not - * atomic would let the concurrency test pass while the real contract the JPA adapter must satisfy - * goes unstated. - */ -class InMemoryIdempotencyStore implements IdempotencyStorePort { - - // Keyed by the scope record, not by storageKey(): that string joins its four dimensions with - // "::" and escapes nothing, so a fake keyed on it would silently merge two scopes that the real - // adapter — which has a unique constraint per dimension column — keeps apart. - private final Map records = new ConcurrentHashMap<>(); - - @Override - public boolean tryBegin( - IdempotencyScope scope, RequestFingerprint fingerprint, Instant expiresAt) { - IdempotencyRecord claim = - new IdempotencyRecord( - scope, fingerprint, IdempotencyStatus.IN_FLIGHT, null, Instant.EPOCH, expiresAt); - return records.putIfAbsent(scope, claim) == null; - } - - @Override - public Optional find(IdempotencyScope scope, Instant now) { - return Optional.ofNullable(records.get(scope)).filter(record -> !record.isExpiredAt(now)); - } - - @Override - public void complete(IdempotencyScope scope, StoredResponse response) { - records.computeIfPresent( - scope, - (key, record) -> - new IdempotencyRecord( - record.scope(), - record.fingerprint(), - IdempotencyStatus.COMPLETED, - response, - record.createdAt(), - record.expiresAt())); - } - - @Override - public void discard(IdempotencyScope scope) { - records.remove(scope); - } - - /** Drops a record without going through the port, standing in for TTL expiry. */ - void expire(IdempotencyScope scope) { - records.remove(scope); - } - - /** How many records are held. */ - int size() { - return records.size(); - } -} diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/json/WebObjectMapperFactoryTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/json/WebObjectMapperFactoryTest.java deleted file mode 100644 index bbef1d7f..00000000 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/json/WebObjectMapperFactoryTest.java +++ /dev/null @@ -1,133 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.json; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.time.Instant; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import tools.jackson.databind.ObjectMapper; - -/** - * Every lenient Jackson default is a way for two parties to disagree about what a document meant. - * - *

Each case here is one of those disagreements, asserted from the rejecting side. A mapper test - * that only reads a well-formed document proves nothing about the mapper, because the default - * configuration reads that document too. - * - *

The mapper under test is a Jackson 3 ({@code tools.jackson}) one, because that is the type - * Spring Framework 7's message converter takes. An earlier version of this suite exercised a strict - * Jackson 2 mapper that was correct, green, and never consulted by the framework. - */ -class WebObjectMapperFactoryTest { - - private final ObjectMapper mapper = WebObjectMapperFactory.standard(); - - record CreateRequest(String title, int quantity) {} - - record Timestamped(Instant occurredAt) {} - - @Test - @DisplayName("a duplicate JSON key is refused") - void aDuplicateJsonKeyIsRefused() { - assertThatThrownBy( - () -> - mapper.readValue( - "{\"title\":\"a\",\"title\":\"b\",\"quantity\":1}", CreateRequest.class)) - .as("last-one-wins means the client believes the first one won") - .isInstanceOf(Exception.class); - } - - @Test - @DisplayName("an unknown property is refused") - void anUnknownPropertyIsRefused() { - assertThatThrownBy( - () -> - mapper.readValue( - "{\"title\":\"a\",\"quantity\":1,\"titel\":\"typo\"}", CreateRequest.class)) - .as("a dropped typo is a request that succeeds without doing what was asked") - .isInstanceOf(Exception.class); - } - - @Test - @DisplayName("a trailing token is refused") - void aTrailingTokenIsRefused() { - assertThatThrownBy( - () -> - mapper.readValue( - "{\"title\":\"a\",\"quantity\":1} {\"title\":\"b\"}", CreateRequest.class)) - .as("a concatenated second document must not be silently ignored") - .isInstanceOf(Exception.class); - } - - @Test - @DisplayName("a string is not silently read as a number") - void aStringIsNotSilentlyReadAsANumber() { - assertThatThrownBy( - () -> mapper.readValue("{\"title\":\"a\",\"quantity\":\"5\"}", CreateRequest.class)) - .as("otherwise the same request means two things to two services") - .isInstanceOf(Exception.class); - } - - @Test - @DisplayName("an empty string is not silently read as null") - void anEmptyStringIsNotSilentlyReadAsNull() { - assertThatThrownBy( - () -> mapper.readValue("{\"title\":\"a\",\"quantity\":\"\"}", CreateRequest.class)) - .as("a null-pointer deep in the application instead of a validation error at the boundary") - .isInstanceOf(Exception.class); - } - - @Test - @DisplayName("nesting past the profile depth is refused by the parser, not after") - void nestingPastTheProfileDepthIsRefusedByTheParser() { - WebJsonProfile shallow = new WebJsonProfile(true, true, true, true, true, 4, 100, 1024); - ObjectMapper bounded = WebObjectMapperFactory.create(shallow); - String deep = "{\"a\":".repeat(16) + "1" + "}".repeat(16); - - assertThatThrownBy(() -> bounded.readTree(deep)) - .as("a depth limit applied to a parsed tree has already paid for the tree") - .isInstanceOf(Exception.class); - } - - @Test - @DisplayName("an instant round-trips as an RFC 3339 string, never an epoch decimal") - void anInstantRoundTripsAsAnRfc3339String() throws Exception { - String json = mapper.writeValueAsString(new Timestamped(Instant.parse("2026-08-13T10:15:30Z"))); - - assertThat(json) - .as("the wire type manifest fixes this; a mapper default would render 1786...") - .contains("2026-08-13T10:15:30Z"); - assertThat(mapper.readValue(json, Timestamped.class).occurredAt()) - .isEqualTo(Instant.parse("2026-08-13T10:15:30Z")); - } - - @Test - @DisplayName("a well-formed document under the profile is accepted") - void aWellFormedDocumentIsAccepted() { - assertThatCode(() -> mapper.readValue("{\"title\":\"a\",\"quantity\":1}", CreateRequest.class)) - .as("the strictness must not be the kind that refuses everything") - .doesNotThrowAnyException(); - } - - @Test - @DisplayName("the tolerant profile accepts an added property and stays strict elsewhere") - void theTolerantProfileAcceptsAnAddedProperty() { - ObjectMapper tolerant = - WebObjectMapperFactory.create(WebJsonProfile.tolerantOfUnknownProperties()); - - assertThatCode( - () -> - tolerant.readValue( - "{\"title\":\"a\",\"quantity\":1,\"added\":true}", CreateRequest.class)) - .as("a provider evolving their callback is not a client mistake") - .doesNotThrowAnyException(); - assertThatThrownBy( - () -> - tolerant.readValue( - "{\"title\":\"a\",\"title\":\"b\",\"quantity\":1}", CreateRequest.class)) - .as("tolerance of added fields is not tolerance of ambiguity") - .isInstanceOf(Exception.class); - } -} diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/moduleboundary/WebBuildModel.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/moduleboundary/WebBuildModel.java deleted file mode 100644 index bb02637a..00000000 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/moduleboundary/WebBuildModel.java +++ /dev/null @@ -1,285 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.moduleboundary; - -import java.io.IOException; -import java.io.UncheckedIOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.TreeMap; -import java.util.TreeSet; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.stream.Stream; - -/** - * Reads a web platform source tree and reports where it disagrees with the declared module map. - * - *

This deliberately works on source text rather than on compiled classes. An import that a - * boundary forbids has usually been erased by the compiler — a constant is inlined, a type is only - * named in a signature that is not retained — so a bytecode scan would report a boundary as clean - * while the source a reviewer reads still crosses it. - * - *

It lives in the test source set on purpose. Scanning a checkout is build-time work: a running - * application has no source tree to scan, and a runtime scan would fail exactly in the packaged - * environments where nothing is wrong. - * - *

Every entry point refuses to report success on an empty scan. A boundary rule that passes - * because it found no files is the failure mode this whole model exists to prevent. - */ -public final class WebBuildModel { - - /** - * Import prefixes that make a module framework bound. - * - *

The design's constraint names Servlet, Spring MVC, Spring WebFlux and Reactor. The set here - * is wider on purpose: {@code jakarta} covers servlet and validation, {@code com.fasterxml} - * covers Jackson, {@code io.micrometer} covers observation. Each binds a module to a runtime just - * as firmly as Spring does, and a "core" module that can only be exercised with Jackson on the - * classpath is not the portable decision the split exists to protect. - */ - public static final Pattern FRAMEWORK_IMPORT = - Pattern.compile( - // `tools.jackson` is Jackson 3 and `com.fasterxml` is Jackson 2. Both are listed because - // this repository runs on Spring 7, whose message converters take Jackson 3 — so a CORE - // module could have imported a mapper without this detector noticing, which is a hole in - // exactly the check that is supposed to have none. - "^(org\\.springframework|jakarta|reactor|io\\.micrometer|com\\.fasterxml" - + "|tools\\.jackson|org\\.slf4j|io\\.swagger)\\."); - - private static final Pattern IMPORT_STATEMENT = - Pattern.compile("^\\s*import\\s+(?:static\\s+)?([\\w.]+)\\s*;", Pattern.MULTILINE); - - private static final Pattern PACKAGE_STATEMENT = - Pattern.compile("^\\s*package\\s+([\\w.]+)\\s*;", Pattern.MULTILINE); - - private WebBuildModel() {} - - /** Scans every source root the platform's module map governs. */ - public static WebSourceGraph scanPlatformSources() { - return scan(platformSourceRoots()); - } - - /** - * Scans a Java source root — the directory that directly contains the {@code dev} package folder. - * - * @throws IllegalStateException when the root holds no platform source at all - */ - public static WebSourceGraph scan(Path sourceRoot) { - return scan(List.of(sourceRoot)); - } - - /** - * Scans several Java source roots as one platform. - * - * @throws IllegalStateException when the roots hold no platform source at all - */ - public static WebSourceGraph scan(List sourceRoots) { - Map> edges = new TreeMap<>(); - Map> frameworkImports = new TreeMap<>(); - Set packages = new TreeSet<>(); - int fileCount = 0; - - List files = new ArrayList<>(); - for (Path sourceRoot : sourceRoots) { - files.addAll(javaFilesUnder(sourceRoot)); - } - for (Path file : files) { - String source = read(file); - String packageName = declaredPackage(source).orElse(null); - if (packageName == null || !WebModuleBoundary.insidePlatform(packageName)) { - continue; - } - fileCount++; - packages.add(packageName); - String moduleId = WebModuleBoundary.moduleIdForPackage(packageName).orElse(null); - if (moduleId == null) { - // An unregistered package still has to appear in `packages` so the rule can name it, but it - // owns no module identity and therefore contributes no edges. - continue; - } - edges.computeIfAbsent(moduleId, key -> new TreeSet<>()); - frameworkImports.computeIfAbsent(moduleId, key -> new TreeSet<>()); - - Matcher matcher = IMPORT_STATEMENT.matcher(source); - while (matcher.find()) { - String imported = matcher.group(1); - if (WebModuleBoundary.insidePlatform(imported)) { - importedModule(imported) - .filter(target -> !target.equals(moduleId)) - .ifPresent(target -> edges.get(moduleId).add(target)); - } else if (FRAMEWORK_IMPORT.matcher(imported).find()) { - frameworkImports.get(moduleId).add(imported); - } - } - } - - if (fileCount == 0) { - throw new IllegalStateException( - "no web platform source was found under " - + sourceRoots.stream().map(root -> root.toAbsolutePath().toString()).toList() - + "; a boundary rule must never pass by scanning nothing"); - } - return new WebSourceGraph(edges, frameworkImports, packages, fileCount); - } - - /** Packages that hold source but were never given a module identity. */ - public static List undeclaredPackages(WebSourceGraph graph) { - return graph.packages().stream() - .filter(packageName -> WebModuleBoundary.moduleIdForPackage(packageName).isEmpty()) - .sorted() - .toList(); - } - - /** Declared modules whose package holds no source, so the declaration describes nothing. */ - public static List declaredButAbsentModules(WebSourceGraph graph) { - List absent = new ArrayList<>(); - WebModuleBoundary.packagesById() - .forEach( - (moduleId, packageName) -> { - boolean present = - graph.packages().stream() - .anyMatch( - scanned -> - scanned.equals(packageName) || scanned.startsWith(packageName + ".")); - if (!present) { - absent.add(moduleId + " (" + packageName + ")"); - } - }); - absent.sort(String::compareTo); - return List.copyOf(absent); - } - - /** Imports that cross a module boundary the declaration does not allow. */ - public static List undeclaredEdges(WebSourceGraph graph) { - List violations = new ArrayList<>(); - graph - .moduleEdges() - .forEach( - (from, targets) -> - targets.stream() - .filter(to -> !WebModuleBoundary.edgeAllowed(from, to)) - .forEach(to -> violations.add(from + " -> " + to))); - violations.sort(String::compareTo); - return List.copyOf(violations); - } - - /** Framework imports found in modules declared {@link WebModulePurity#CORE}. */ - public static List frameworkImportsInCoreModules(WebSourceGraph graph) { - Set core = WebModuleBoundary.coreModuleIds(); - List violations = new ArrayList<>(); - graph - .frameworkImports() - .forEach( - (moduleId, imports) -> { - if (!core.contains(moduleId)) { - return; - } - imports.forEach(imported -> violations.add(moduleId + " imports " + imported)); - }); - violations.sort(String::compareTo); - return List.copyOf(violations); - } - - /** - * Every source root the module map governs. - * - *

Two, since the Fileserver capability's HTTP surface became `adapter:inbound:web-fileserver`. - * The module map did not move with it: `WebStableModule` still declares the twelve fileserver - * modules and their edges, because a second copy of the map in the second leaf would be a second - * answer to "is this edge declared", and one map with two source roots is what this method's - * plural has meant since it was written. - * - *

The sibling root is optional rather than required. A checkout that does not have it is a - * checkout where that leaf is absent, and the rules then govern what is present — the empty-scan - * guard in {@link #scan(List)} is what refuses a scan that found nothing at all. - */ - public static List platformSourceRoots() { - Path own = mainSourceRoot(); - Path sibling = - own.getParent() - .getParent() - .getParent() - .getParent() - .resolve("web-fileserver") - .resolve("src") - .resolve("main") - .resolve("java"); - return Files.isDirectory(sibling) ? List.of(own, sibling) : List.of(own); - } - - /** - * Locates this leaf's production source root. - * - * @throws IllegalStateException when it cannot be found, rather than returning a path that would - * scan to zero files - */ - public static Path mainSourceRoot() { - String packagePath = WebModuleBoundary.PACKAGE_ROOT.replace('.', '/'); - for (Path directory = Path.of("").toAbsolutePath(); - directory != null; - directory = directory.getParent()) { - Path candidate = directory.resolve("src").resolve("main").resolve("java"); - if (Files.isDirectory(candidate.resolve(packagePath))) { - return candidate; - } - } - throw new IllegalStateException( - "cannot locate src/main/java/" - + packagePath - + " from " - + Path.of("").toAbsolutePath() - + "; the module boundary rules have nothing to check"); - } - - private static Optional importedModule(String importedType) { - int lastDot = importedType.lastIndexOf('.'); - if (lastDot < 0) { - return Optional.empty(); - } - // A static import names a member, so peel qualifiers until one resolves to a declared module. - for (String candidate = importedType.substring(0, lastDot); - candidate.length() >= WebModuleBoundary.PACKAGE_ROOT.length(); - candidate = candidate.substring(0, Math.max(candidate.lastIndexOf('.'), 0))) { - Optional moduleId = WebModuleBoundary.moduleIdForPackage(candidate); - if (moduleId.isPresent()) { - return moduleId; - } - if (candidate.lastIndexOf('.') < 0) { - break; - } - } - return Optional.empty(); - } - - private static Optional declaredPackage(String source) { - Matcher matcher = PACKAGE_STATEMENT.matcher(source); - return matcher.find() ? Optional.of(matcher.group(1)) : Optional.empty(); - } - - private static List javaFilesUnder(Path root) { - if (!Files.isDirectory(root)) { - throw new IllegalStateException("source root does not exist: " + root.toAbsolutePath()); - } - try (Stream files = Files.walk(root)) { - return files - .filter(Files::isRegularFile) - .filter(path -> path.getFileName().toString().endsWith(".java")) - .sorted() - .toList(); - } catch (IOException ex) { - throw new UncheckedIOException(ex); - } - } - - private static String read(Path file) { - try { - return Files.readString(file); - } catch (IOException ex) { - throw new UncheckedIOException(ex); - } - } -} diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/moduleboundary/WebModuleBoundaryTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/moduleboundary/WebModuleBoundaryTest.java deleted file mode 100644 index e3738615..00000000 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/moduleboundary/WebModuleBoundaryTest.java +++ /dev/null @@ -1,131 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.moduleboundary; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.io.IOException; -import java.io.UncheckedIOException; -import java.nio.file.Files; -import java.nio.file.Path; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -/** - * The machine check behind the "bounded packages instead of Gradle leaves" decision. - * - *

The web design models this platform as 23 Gradle modules. This repository's registry owns the - * leaf list, so they are sub-packages of one leaf — and that substitution buys nothing unless the - * split is enforced. A Gradle dependency gate cannot see inside a leaf, so this test does what the - * gate cannot: it scans the real production tree and compares it against the declared module map. - * - *

The negative fixtures matter as much as the positive assertions. A boundary test that has - * never been shown to fail is indistinguishable from one that scans the wrong directory, so each - * rule gets a synthetic tree that must be rejected. - */ -class WebModuleBoundaryTest { - - private static final String ROOT = WebModuleBoundary.PACKAGE_ROOT; - - private static WebSourceGraph production; - - @BeforeAll - static void scanProductionTree() { - production = WebBuildModel.scanPlatformSources(); - } - - @Test - @DisplayName("the scan actually reads the production tree") - void theScanActuallyReadsTheProductionTree() { - assertThat(production.fileCount()) - .as("the leaf holds over a hundred files; a scan far below that is reading the wrong tree") - .isGreaterThan(100); - assertThat(production.packages()).contains(ROOT + ".error", ROOT + ".observability"); - } - - @Test - @DisplayName("every production package has a declared module identity") - void everyProductionPackageHasADeclaredModuleIdentity() { - assertThat(WebBuildModel.undeclaredPackages(production)) - .as("add the package to WebStableModule before shipping it") - .isEmpty(); - } - - @Test - @DisplayName("every declared module exists in the production tree") - void everyDeclaredModuleExistsInTheProductionTree() { - assertThat(WebBuildModel.declaredButAbsentModules(production)) - .as("a declared module with no source describes nothing and hides a rename") - .isEmpty(); - } - - @Test - @DisplayName("every cross-module import is a declared edge") - void everyCrossModuleImportIsADeclaredEdge() { - assertThat(WebBuildModel.undeclaredEdges(production)).isEmpty(); - } - - @Test - @DisplayName("core modules stay framework free") - void coreModulesStayFrameworkFree() { - assertThat(WebBuildModel.frameworkImportsInCoreModules(production)) - .as("a CORE module may not bind to Spring, Servlet, Reactor, Jackson or Micrometer") - .isEmpty(); - } - - @Test - @DisplayName("an undeclared cross-module import is rejected") - void anUndeclaredCrossModuleImportIsRejected(@TempDir Path tree) { - writeType(tree, ROOT + ".conditional", "LeakyEtags", ROOT + ".ratelimit.ClientIpResolver"); - - assertThat(WebBuildModel.undeclaredEdges(WebBuildModel.scan(tree))) - .containsExactly("conditional -> ratelimit"); - } - - @Test - @DisplayName("a framework import in a core module is rejected") - void aFrameworkImportInACoreModuleIsRejected(@TempDir Path tree) { - writeType(tree, ROOT + ".cursor", "LeakyCursor", "org.springframework.stereotype.Component"); - - assertThat(WebBuildModel.frameworkImportsInCoreModules(WebBuildModel.scan(tree))) - .containsExactly("cursor imports org.springframework.stereotype.Component"); - } - - @Test - @DisplayName("a package with no declared identity is rejected") - void aPackageWithNoDeclaredIdentityIsRejected(@TempDir Path tree) { - writeType(tree, ROOT + ".undeclared", "Stowaway", null); - - assertThat(WebBuildModel.undeclaredPackages(WebBuildModel.scan(tree))) - .containsExactly(ROOT + ".undeclared"); - } - - @Test - @DisplayName("a scan that finds nothing fails instead of passing") - void aScanThatFindsNothingFailsInsteadOfPassing(@TempDir Path tree) { - assertThatThrownBy(() -> WebBuildModel.scan(tree)) - .as("an empty scan is the way a boundary rule silently stops checking anything") - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("never pass by scanning nothing"); - } - - private static void writeType( - Path sourceRoot, String packageName, String typeName, String importedType) { - Path directory = sourceRoot.resolve(packageName.replace('.', '/')); - String body = - "package " - + packageName - + ";\n\n" - + (importedType == null ? "" : "import " + importedType + ";\n\n") - + "final class " - + typeName - + " {}\n"; - try { - Files.createDirectories(directory); - Files.writeString(directory.resolve(typeName + ".java"), body); - } catch (IOException unwritable) { - throw new UncheckedIOException(unwritable); - } - } -} diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/moduleboundary/WebSourceGraph.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/moduleboundary/WebSourceGraph.java deleted file mode 100644 index e6ff0865..00000000 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/moduleboundary/WebSourceGraph.java +++ /dev/null @@ -1,30 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.moduleboundary; - -import java.util.Map; -import java.util.Set; - -/** - * What a scan of a web platform source tree actually found. - * - *

Everything here is observed, never declared: {@link WebStableModule} says what the module map - * is supposed to be, and this record says what the checkout is. The boundary rules are the - * comparison between the two. - * - * @param moduleEdges module identifier to the module identifiers it imports, self-edges excluded - * @param frameworkImports module identifier to the framework imports it uses, empty when pure - * @param packages every package that contained at least one Java file - * @param fileCount how many Java files were read, so a rule can refuse to pass on an empty scan - */ -public record WebSourceGraph( - Map> moduleEdges, - Map> frameworkImports, - Set packages, - int fileCount) { - - /** Canonicalises the collections so callers cannot mutate a scan result. */ - public WebSourceGraph { - moduleEdges = Map.copyOf(moduleEdges); - frameworkImports = Map.copyOf(frameworkImports); - packages = Set.copyOf(packages); - } -} diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebAutoConfigurationRegistrationTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebAutoConfigurationRegistrationTest.java index 82652599..d2569c3d 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebAutoConfigurationRegistrationTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebAutoConfigurationRegistrationTest.java @@ -35,8 +35,8 @@ class WebAutoConfigurationRegistrationTest { /** The auto-configurations this leaf publishes. */ private static final List PUBLISHED_ROOTS = List.of( - "dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebMvcPlatformAutoConfiguration", - "dev.caskeleton.adapter.inbound.web.webflux.autoconfigure.WebFluxPlatformAutoConfiguration"); + "dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebAdapterAutoConfiguration", + "dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebMvcPlatformAutoConfiguration"); @Test @DisplayName("the shipped registration file names every root this leaf publishes") diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebMvcPlatformAutoConfigurationTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebMvcPlatformAutoConfigurationTest.java index 4790dbf7..0882f6c6 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebMvcPlatformAutoConfigurationTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebMvcPlatformAutoConfigurationTest.java @@ -2,15 +2,8 @@ package dev.caskeleton.adapter.inbound.web.mvc.autoconfigure; import static org.assertj.core.api.Assertions.assertThat; -import dev.caskeleton.adapter.inbound.web.budget.WebBudgetCatalog; -import dev.caskeleton.adapter.inbound.web.budget.WebBudgetProfileName; import dev.caskeleton.adapter.inbound.web.error.GlobalExceptionHandler; -import dev.caskeleton.adapter.inbound.web.error.WebProblemFactory; -import dev.caskeleton.adapter.inbound.web.http.WebMethodPolicy; -import dev.caskeleton.adapter.inbound.web.http.WebUriPolicy; -import dev.caskeleton.adapter.inbound.web.mvc.filter.WebMvcEvidenceFilter; import dev.caskeleton.adapter.inbound.web.mvc.filter.WebMvcRequestIdFilter; -import dev.caskeleton.adapter.inbound.web.operation.WebOperationCatalog; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.AutoConfigurations; @@ -35,27 +28,9 @@ class WebMvcPlatformAutoConfigurationTest { context -> assertThat(context) .hasNotFailed() - .hasSingleBean(WebProblemFactory.class) - .hasSingleBean(WebOperationCatalog.class) - .hasSingleBean(WebBudgetCatalog.class) - .hasSingleBean(WebUriPolicy.class) - .hasSingleBean(WebMethodPolicy.class) .hasSingleBean(GlobalExceptionHandler.class) .hasSingleBean(WebMvcRequestIdFilter.class) - .hasSingleBean(WebMvcEvidenceFilter.class) - .hasSingleBean(WebMvcPlatformStartupCheck.class)); - } - - @Test - @DisplayName("the standard budget profile is registered, so a route can resolve one") - void theStandardBudgetProfileIsRegistered() { - servlet.run( - context -> - assertThat( - context - .getBean(WebBudgetCatalog.class) - .require(WebBudgetProfileName.standard())) - .isNotNull()); + .hasBean("webMvcRequestContextConfigurer")); } @Test @@ -66,8 +41,8 @@ class WebMvcPlatformAutoConfigurationTest { .run( context -> assertThat(context) - .as("the two starters are mutually exclusive at the type level") - .doesNotHaveBean(WebMvcEvidenceFilter.class)); + .as("the servlet filters need a servlet application") + .doesNotHaveBean(WebMvcRequestIdFilter.class)); } @Test @@ -75,20 +50,20 @@ class WebMvcPlatformAutoConfigurationTest { void aNonWebApplicationGetsNoneOfItEither() { new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(WebMvcPlatformAutoConfiguration.class)) - .run(context -> assertThat(context).doesNotHaveBean(WebProblemFactory.class)); + .run(context -> assertThat(context).doesNotHaveBean(GlobalExceptionHandler.class)); } @Test - @DisplayName("the master switch turns everything off") - void theMasterSwitchTurnsEverythingOff() { + @DisplayName("enabled=false turns everything off") + void enabledFalseTurnsEverythingOff() { servlet .withPropertyValues("backend.web.mvc.enabled=false") .run( context -> assertThat(context) .as("off must mean no beans, not beans that happen not to be called") - .doesNotHaveBean(WebProblemFactory.class) - .doesNotHaveBean(WebMvcEvidenceFilter.class)); + .doesNotHaveBean(GlobalExceptionHandler.class) + .doesNotHaveBean(WebMvcRequestIdFilter.class)); } @Test @@ -104,11 +79,14 @@ class WebMvcPlatformAutoConfigurationTest { @DisplayName("an adopter bean replaces the platform default") void anAdopterBeanReplacesThePlatformDefault() { servlet - .withBean(WebUriPolicy.class, () -> WebUriPolicy.withMaxLength(512)) + .withBean( + "adopterRequestIdFilter", + WebMvcRequestIdFilter.class, + () -> new WebMvcRequestIdFilter(true, 0)) .run( context -> { - assertThat(context).hasSingleBean(WebUriPolicy.class); - assertThat(context.getBean(WebUriPolicy.class).canonicalize("/api/v1/x")).isNotNull(); + assertThat(context).hasSingleBean(WebMvcRequestIdFilter.class); + assertThat(context).hasBean("adopterRequestIdFilter"); }); } } diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebMvcPlatformStartupCheckTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebMvcPlatformStartupCheckTest.java deleted file mode 100644 index 338b8432..00000000 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebMvcPlatformStartupCheckTest.java +++ /dev/null @@ -1,22 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.mvc.autoconfigure; - -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.web.error.ProblemCatalog; -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.support.DefaultListableBeanFactory; - -class WebMvcPlatformStartupCheckTest { - - @Test - void missingMandatoryControlsFailTheActualStartupCheck() { - WebMvcPlatformStartupCheck check = - new WebMvcPlatformStartupCheck(new DefaultListableBeanFactory(), ProblemCatalog.standard()); - - assertThatThrownBy(check::afterSingletonsInstantiated) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("problemHandler") - .hasMessageContaining("requestIdFilter") - .hasMessageContaining("evidenceFilter"); - } -} diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/mvc/error/WebMvcProblemExceptionHandlerActivationTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/mvc/error/WebMvcProblemExceptionHandlerActivationTest.java deleted file mode 100644 index 647cff19..00000000 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/mvc/error/WebMvcProblemExceptionHandlerActivationTest.java +++ /dev/null @@ -1,48 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.mvc.error; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.adapter.inbound.web.error.ProblemCatalog; -import dev.caskeleton.adapter.inbound.web.error.WebProblemFactory; -import dev.caskeleton.adapter.inbound.web.error.WebProblemSanitizer; -import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.runner.WebApplicationContextRunner; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; - -class WebMvcProblemExceptionHandlerActivationTest { - - private final WebApplicationContextRunner runner = - new WebApplicationContextRunner().withUserConfiguration(Fixture.class); - - @Test - void problemHandlerIsNotPartOfTheDefaultServletContract() { - runner.run( - context -> - assertThat(context) - .hasNotFailed() - .doesNotHaveBean(WebMvcProblemExceptionHandler.class)); - } - - @Test - void problemHandlerIsExplicitlyOptedInByTheProblemDetailsSwitch() { - runner - .withPropertyValues("spring.mvc.problemdetails.enabled=true") - .run( - context -> - assertThat(context) - .hasNotFailed() - .hasSingleBean(WebMvcProblemExceptionHandler.class)); - } - - @Configuration(proxyBeanMethods = false) - @Import(WebMvcProblemExceptionHandler.class) - static class Fixture { - - @Bean - WebProblemFactory webProblemFactory() { - return new WebProblemFactory(ProblemCatalog.standard(), new WebProblemSanitizer()); - } - } -} diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/mvc/filter/WebMvcEvidenceFilterTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/mvc/filter/WebMvcEvidenceFilterTest.java deleted file mode 100644 index 0be7101f..00000000 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/mvc/filter/WebMvcEvidenceFilterTest.java +++ /dev/null @@ -1,78 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.mvc.filter; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.web.evidence.WebApplicationEvidence; -import dev.caskeleton.adapter.inbound.web.evidence.WebExecutionEvidenceTracker; -import jakarta.servlet.DispatcherType; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.springframework.mock.web.MockFilterChain; -import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.mock.web.MockHttpServletResponse; - -/** - * One logical request, one tracker — including across the async redispatch. - * - *

The case this protects is the one the whole evidence model exists for: an async response whose - * first pass recorded a commit. A tracker created per dispatch throws that away, and the request is - * then reported as safe to retry. - */ -class WebMvcEvidenceFilterTest { - - private final WebMvcEvidenceFilter filter = new WebMvcEvidenceFilter(); - - @Test - @DisplayName("an async redispatch keeps the tracker the first pass created") - void anAsyncRedispatchKeepsOneEvidenceTracker() throws Exception { - MockHttpServletRequest request = new MockHttpServletRequest(); - MockHttpServletResponse response = new MockHttpServletResponse(); - - filter.doFilter(request, response, new MockFilterChain()); - Object first = request.getAttribute(WebMvcEvidenceFilter.EVIDENCE_ATTRIBUTE); - ((WebExecutionEvidenceTracker) first).markApplicationCommitted(); - - request.setDispatcherType(DispatcherType.ASYNC); - filter.doFilter(request, response, new MockFilterChain()); - - assertThat(request.getAttribute(WebMvcEvidenceFilter.EVIDENCE_ATTRIBUTE)) - .as("a tracker per dispatch throws away the commit the first pass recorded") - .isSameAs(first); - assertThat(((WebExecutionEvidenceTracker) first).snapshot().applicationEvidence()) - .isEqualTo(WebApplicationEvidence.APPLICATION_COMMITTED); - } - - @Test - @DisplayName("the filter runs on async and error dispatches rather than skipping them") - void theFilterRunsOnAsyncAndErrorDispatches() { - assertThat(filter.getOrder()).isNegative(); - // OncePerRequestFilter skips both by default, which would leave the dispatch that actually - // writes the response with nothing to record into. - assertThat(new WebMvcEvidenceFilter(5).getOrder()).isEqualTo(5); - } - - @Test - @DisplayName("the filter never reads the request body") - void theFilterNeverReadsTheRequestBody() throws Exception { - MockHttpServletRequest request = new MockHttpServletRequest(); - request.setContent("{\"title\":\"a\"}".getBytes(java.nio.charset.StandardCharsets.UTF_8)); - - filter.doFilter(request, new MockHttpServletResponse(), new MockFilterChain()); - - assertThat(request.getInputStream().readAllBytes()) - .as("consuming the stream here would leave the controller nothing to bind from") - .isNotEmpty(); - } - - @Test - @DisplayName("requiring a tracker fails loudly when the filter is not installed") - void requiringATrackerFailsLoudlyWhenTheFilterIsNotInstalled() { - MockHttpServletRequest request = new MockHttpServletRequest(); - - assertThat(WebMvcEvidenceFilter.existingTracker(request)).isNull(); - assertThatThrownBy(() -> WebMvcEvidenceFilter.requireTracker(request)) - .as("a fresh tracker here would record evidence nothing else reads") - .isInstanceOf(IllegalStateException.class); - } -} diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/observability/WebObservabilityPolicyTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/observability/WebObservabilityPolicyTest.java deleted file mode 100644 index b6d0c36a..00000000 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/observability/WebObservabilityPolicyTest.java +++ /dev/null @@ -1,188 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.observability; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.time.Duration; -import java.time.Instant; -import java.util.Map; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * Ways telemetry becomes expensive or becomes a leak. - * - *

Neither failure produces an error. A high-cardinality tag shows up as a monitoring bill and - * then as a backend dropping series, at which point the alert that should have fired does not; a - * secret in a tag shows up as an unencrypted export of it to whichever SaaS the dashboards live in. - * Both are only catchable before the fact. - */ -class WebObservabilityPolicyTest { - - private final WebMetricCardinalityPolicy policy = WebMetricCardinalityPolicy.standard(); - - @Test - @DisplayName("high-cardinality and secret-bearing tags are refused") - void rejectsHighCardinalityAndSecrets() { - assertThat(policy.allowed("userId")).isFalse(); - assertThat(policy.allowed("http.url")).isFalse(); - assertThat(policy.allowed("idempotencyKey")).isFalse(); - assertThat(policy.allowed("operationName")).isTrue(); - } - - @Test - @DisplayName("the raw tenant identifier is not a tag") - void tenantIdentifierIsNotATag() { - // Bounded in principle and unbounded in practice, and it is the identifier a customer would - // least expect to find in a vendor's dashboard. - assertThat(policy.allowed("tenantId")).isFalse(); - assertThat(policy.allowed("tenant")).isFalse(); - } - - @Test - @DisplayName("resource identifiers and paths are not tags") - void resourceIdentifiersAreNotTags() { - assertThat(policy.allowed("resourceId")).isFalse(); - assertThat(policy.allowed("orderId")).isFalse(); - assertThat(policy.allowed("http.path")).isFalse(); - assertThat(policy.allowed("queryString")).isFalse(); - } - - @Test - @DisplayName("credentials are not tags") - void credentialsAreNotTags() { - assertThat(policy.allowed("token")).isFalse(); - assertThat(policy.allowed("cookie")).isFalse(); - assertThat(policy.allowed("authorization")).isFalse(); - } - - @Test - @DisplayName("the allowlist is exactly the eight bounded dimensions") - void allowlistIsClosed() { - // Pinned so that adding a tag is a deliberate edit here rather than something that happens in - // a call site nobody reviews for cardinality. - assertThat(policy.allowedTags()) - .containsExactlyInAnyOrder( - "routeTemplate", - "http.method", - "http.status", - "outcome", - "apiVersion", - "operationName", - "problemCode", - "clientProfile"); - } - - @Test - @DisplayName("a forbidden tag is refused at the point it is recorded") - void forbiddenTagIsRefusedWhenRecorded() { - // At construction, not on review. A tag checked after the map was built has already been - // written by whoever built it. - assertThatThrownBy(() -> WebObservationConvention.standard().tag("userId", "alice")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("allowlist"); - } - - @Test - @DisplayName("an allowed tag is recorded") - void allowedTagIsRecorded() { - Map tags = - WebObservationConvention.standard() - .tag("http.method", "GET") - .tag("http.status", "200") - .tag("operationName", "orders.list") - .tags(); - - assertThat(tags) - .containsEntry("http.method", "GET") - .containsEntry("operationName", "orders.list"); - } - - @Test - @DisplayName("a resolved path passed as a route template is refused") - void resolvedPathIsRefusedAsRouteTemplate() { - // The mistake that actually happens: the resolved path is what is easiest to reach for, and it - // produces one time series per resource. - assertThatThrownBy( - () -> WebObservationConvention.standard().routeTemplate("/api/v1/orders/40182")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("one series per resource"); - - assertThatCode( - () -> WebObservationConvention.standard().routeTemplate("/api/v1/orders/{orderId}")) - .doesNotThrowAnyException(); - } - - @Test - @DisplayName("an access log line records a template, never a URL with a query") - void accessLogRefusesAQueryString() { - // The most common way personal data reaches an access log: a search term or an email address - // that a client put in a query parameter. - assertThatThrownBy(() -> accessLogEvent("/api/v1/orders?q=alice%40example.com")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("query string"); - } - - @Test - @DisplayName("an audit event must name who, what and why") - void auditEventRequiresActorResourceAndReason() { - assertThatThrownBy(() -> auditEvent("", "order-1", "duplicate charge")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("who did this"); - assertThatThrownBy(() -> auditEvent("operator-1", "", "duplicate charge")) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> auditEvent("operator-1", "order-1", " ")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("cannot be evaluated later"); - } - - @Test - @DisplayName("a complete audit event is accepted") - void completeAuditEventIsAccepted() { - assertThatCode(() -> auditEvent("operator-1", "order-1", "duplicate charge, ticket OPS-42")) - .doesNotThrowAnyException(); - } - - @Test - @DisplayName("every audited action is an override of a control, not merely a severe one") - void auditedActionsAreOverrides() { - // The membership test for this enum. Severity is not it: a failed payment is severe and is not - // audited, because nobody overrode anything. - assertThat(WebAuditAction.values()) - .containsExactlyInAnyOrder( - WebAuditAction.ADMIN_FORCE_DELETE, - WebAuditAction.ADMIN_REDRIVE, - WebAuditAction.PERMISSION_CHANGE, - WebAuditAction.SUNSET_CHANGE, - WebAuditAction.IDEMPOTENCY_OVERRIDE); - } - - private static WebAccessLogEvent accessLogEvent(String routeTemplate) { - return new WebAccessLogEvent( - "req-1", - "0af7651916cd43dd8448eb211c80319c", - "GET", - routeTemplate, - 200, - null, - "orders.list", - 1, - "browser", - Duration.ofMillis(12), - 0, - 512, - Instant.parse("2026-08-25T10:00:00Z")); - } - - private static WebAuditEvent auditEvent(String actor, String resource, String reason) { - return new WebAuditEvent( - WebAuditAction.IDEMPOTENCY_OVERRIDE, - actor, - resource, - reason, - "0af7651916cd43dd8448eb211c80319c", - Instant.parse("2026-08-25T10:00:00Z"), - Map.of()); - } -} diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/openapi/WebOpenApiSnapshotTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/openapi/WebOpenApiSnapshotTest.java deleted file mode 100644 index 167eb701..00000000 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/openapi/WebOpenApiSnapshotTest.java +++ /dev/null @@ -1,125 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.openapi; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.adapter.inbound.web.error.ProblemCatalog; -import dev.caskeleton.adapter.inbound.web.error.ProblemCode; -import io.swagger.v3.oas.models.OpenAPI; -import io.swagger.v3.oas.models.media.Schema; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.Set; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** The published document says what the runtime does, because both are generated from it. */ -class WebOpenApiSnapshotTest { - - private final OpenAPI document = WebOpenApiProfile.standard().generate(); - - @Test - @DisplayName("the document is 3.1.2 and publishes the problem schema") - void theDocumentIs312AndPublishesTheProblemSchema() { - assertThat(document.getOpenapi()) - .as("3.0 cannot express a string-encoded 64-bit integer or a nullable union") - .isEqualTo("3.1.2"); - assertThat(document.getComponents().getSchemas()).containsKey("Problem"); - assertThat(document.getComponents().getSchemas()).containsKey("ValidationIssue"); - assertThat(document.getComponents().getSchemas()).containsKey("CursorPage"); - } - - @Test - @DisplayName("every runtime problem code appears in the document") - void everyRuntimeProblemCodeAppearsInTheDocument() { - Schema codeSchema = property(document.getComponents().getSchemas().get("Problem"), "code"); - - List published = codeSchema.getEnum().stream().map(String::valueOf).sorted().toList(); - - assertThat(published) - .as("a code the document omits is a deserialisation failure in every generated client") - .containsExactlyElementsOf( - Arrays.stream(ProblemCode.values()).map(Enum::name).sorted().toList()); - } - - @Test - @DisplayName("the validation issue schema has no member for the submitted value") - void theValidationIssueSchemaHasNoRejectedValue() { - Schema issue = document.getComponents().getSchemas().get("ValidationIssue"); - - assertThat(propertyNames(issue)) - .as("echoing submitted content is how a password in the wrong field reaches a log") - .containsExactlyInAnyOrder("pointer", "code", "message"); - assertThat(issue.getAdditionalProperties()).isEqualTo(false); - } - - @Test - @DisplayName("the cursor is opaque in the document as well as on the wire") - void theCursorIsOpaqueInTheDocument() { - Schema page = document.getComponents().getSchemas().get("CursorPage"); - - assertThat(propertyNames(page)).contains("nextCursor"); - assertThat(property(page, "nextCursor").getProperties()) - .as("publishing its structure invites a client to construct one and skip the signature") - .isNull(); - } - - @Test - @DisplayName("the customizer adds the platform components without overwriting an existing one") - void theCustomizerAddsWithoutOverwriting() { - OpenAPI springdoc = new OpenAPI(); - springdoc.setComponents( - new io.swagger.v3.oas.models.Components() - .addSchemas("Problem", new io.swagger.v3.oas.models.media.StringSchema())); - - WebOpenApiCustomizer.standard().customise(springdoc); - - assertThat(springdoc.getOpenapi()).isEqualTo("3.1.2"); - assertThat(springdoc.getComponents().getSchemas().get("Problem")) - .as("a deployment that published its own Problem made a decision") - .isInstanceOf(io.swagger.v3.oas.models.media.StringSchema.class); - assertThat(springdoc.getComponents().getSchemas()).containsKey("CursorPage"); - assertThat(springdoc.getComponents().getSecuritySchemes()).containsKey("bearerAuth"); - } - - @Test - @DisplayName("the release gate refuses a document whose codes are not the runtime's") - void theReleaseGateRefusesADocumentWhoseCodesAreNotTheRuntimes() { - WebOpenApiReleaseGate gate = new WebOpenApiReleaseGate(); - - org.assertj.core.api.Assertions.assertThatCode( - () -> gate.requireProblemInventoryMatches(document, ProblemCatalog.standard())) - .doesNotThrowAnyException(); - - OpenAPI trimmed = WebOpenApiProfile.standard().generate(); - Schema trimmedCodes = property(trimmed.getComponents().getSchemas().get("Problem"), "code"); - trimmedCodes.getEnum().removeIf(value -> "RATE_LIMITED".equals(String.valueOf(value))); - - org.assertj.core.api.Assertions.assertThatThrownBy( - () -> gate.requireProblemInventoryMatches(trimmed, ProblemCatalog.standard())) - .isInstanceOf(WebOpenApiReleaseGate.OpenApiReleaseBlockedException.class) - .hasMessageContaining("not the runtime's"); - } - - /** - * One property of a schema, typed. - * - *

{@code Schema.getProperties()} is a raw {@code Map} in io.swagger's model, so every access - * to it is an unchecked operation. Routing them all through one helper keeps the suppression to a - * single reviewed place instead of scattering it across the assertions. - */ - @SuppressWarnings("unchecked") - private static Schema property(Schema schema, String name) { - Map> properties = - (Map>) (Map) schema.getProperties(); - return properties.get(name); - } - - /** The property names of a schema, typed for the same reason. */ - @SuppressWarnings("unchecked") - private static Set propertyNames(Schema schema) { - Map> properties = - (Map>) (Map) schema.getProperties(); - return Set.copyOf(properties.keySet()); - } -} diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/operationasync/OperationAccessPolicyTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/operationasync/OperationAccessPolicyTest.java deleted file mode 100644 index 787e4a5f..00000000 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/operationasync/OperationAccessPolicyTest.java +++ /dev/null @@ -1,122 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.operationasync; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.adapter.inbound.web.core.ActorContext; -import dev.caskeleton.adapter.inbound.web.core.ApiMajorVersion; -import dev.caskeleton.adapter.inbound.web.core.ExternalRequestContext; -import dev.caskeleton.adapter.inbound.web.core.TenantContext; -import dev.caskeleton.adapter.inbound.web.core.WebOperationName; -import dev.caskeleton.adapter.inbound.web.core.WebRequestContext; -import dev.caskeleton.adapter.inbound.web.core.WebRequestId; -import dev.caskeleton.adapter.inbound.web.core.WebTraceId; -import dev.caskeleton.application.operation.DurableOperation; -import dev.caskeleton.application.operation.DurableOperationId; -import dev.caskeleton.application.operation.DurableOperationState; -import java.time.Instant; -import java.util.Locale; -import java.util.Optional; -import java.util.Set; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * Who can read somebody else's long-running work. - * - *

Each case is a caller who should be refused. An operation's polled document carries the result - * location and, when it failed, the problem detail, so a permissive check here leaks more than the - * fact that the work exists. - */ -class OperationAccessPolicyTest { - - private static final Instant NOW = Instant.parse("2026-08-25T10:00:00Z"); - - @Test - @DisplayName("the submitting principal may read it") - void ownerMayRead() { - assertThat(OperationAccessPolicy.mayAccess(operation("alice", null), context("alice", null))) - .isTrue(); - } - - @Test - @DisplayName("another principal may not") - void otherPrincipalMayNot() { - assertThat(OperationAccessPolicy.mayAccess(operation("alice", null), context("mallory", null))) - .isFalse(); - } - - @Test - @DisplayName("an anonymous caller may not, even with the right subject string") - void anonymousMayNot() { - // An unauthenticated context can still carry a subject — the header a caller supplied. Trusting - // it would let anyone read any operation by naming its owner. - WebRequestContext anonymous = - new WebRequestContext( - new WebRequestId("req-1"), - new WebTraceId("0af7651916cd43dd8448eb211c80319c"), - new WebOperationName("operations.get"), - new ApiMajorVersion(1), - ActorContext.anonymous(), - TenantContext.none(), - Locale.ENGLISH, - NOW, - NOW.plusSeconds(5), - new ExternalRequestContext("https", "api.example.com", 443, "")); - - assertThat(OperationAccessPolicy.mayAccess(operation("alice", null), anonymous)).isFalse(); - } - - @Test - @DisplayName("the same principal in another tenant may not") - void anotherTenantMayNot() { - // The subject matches. Only the tenant differs, which is exactly the cross-tenant read a - // principal-only check would allow. - assertThat(OperationAccessPolicy.mayAccess(operation("alice", "t-1"), context("alice", "t-2"))) - .isFalse(); - } - - @Test - @DisplayName("a tenant-scoped operation is not readable from an unscoped request") - void tenantScopedOperationNeedsATenant() { - assertThat(OperationAccessPolicy.mayAccess(operation("alice", "t-1"), context("alice", null))) - .isFalse(); - } - - @Test - @DisplayName("an unscoped operation is not readable from a tenant-scoped request") - void unscopedOperationIsNotReadableFromATenant() { - assertThat(OperationAccessPolicy.mayAccess(operation("alice", null), context("alice", "t-1"))) - .isFalse(); - } - - private static DurableOperation operation(String principal, String tenantId) { - return new DurableOperation( - new DurableOperationId("op-1"), - "reports.generate", - principal, - tenantId, - DurableOperationState.PENDING, - NOW, - Optional.empty(), - Optional.empty(), - Optional.empty(), - Optional.empty(), - Optional.empty(), - Optional.empty(), - NOW.plusSeconds(3600)); - } - - private static WebRequestContext context(String subject, String tenantId) { - return new WebRequestContext( - new WebRequestId("req-1"), - new WebTraceId("0af7651916cd43dd8448eb211c80319c"), - new WebOperationName("operations.get"), - new ApiMajorVersion(1), - ActorContext.authenticated(subject, Set.of()), - tenantId == null ? TenantContext.none() : TenantContext.resolved(tenantId), - Locale.ENGLISH, - NOW, - NOW.plusSeconds(5), - new ExternalRequestContext("https", "api.example.com", 443, "")); - } -} diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/operationasync/OperationResourceTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/operationasync/OperationResourceTest.java deleted file mode 100644 index 5ea653c8..00000000 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/operationasync/OperationResourceTest.java +++ /dev/null @@ -1,230 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.operationasync; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.web.error.ProblemCode; -import dev.caskeleton.adapter.inbound.web.error.WebProblemFactory; -import java.net.URI; -import java.time.Duration; -import java.time.Instant; -import java.util.List; -import java.util.Optional; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * Each case is a state a client could be handed that it cannot act on. - * - *

A polled operation is read by software, not a person, so every incoherent combination becomes - * a client branch that silently does nothing. The constructor is where they are refused, and these - * are the ones worth refusing. - */ -class OperationResourceTest { - - private static final OperationId ID = new OperationId("op-1"); - private static final Instant CREATED = Instant.parse("2026-08-25T10:00:00Z"); - private static final Instant EXPIRES = CREATED.plus(Duration.ofDays(1)); - - @Test - @DisplayName("a succeeded operation must say where its result is") - void succeededOperationRequiresResultLocation() { - assertThatThrownBy(() -> OperationResource.succeeded(ID, CREATED, Optional.empty())) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("where its result is"); - } - - @Test - @DisplayName("a succeeded operation with a result location is accepted") - void succeededOperationWithResultIsAccepted() { - OperationResource resource = - OperationResource.succeeded(ID, CREATED, Optional.of(URI.create("/results/op-1"))); - - assertThat(resource.status()).isEqualTo(OperationStatus.SUCCEEDED); - assertThat(resource.finished()).isTrue(); - } - - @Test - @DisplayName("a failed operation must carry a problem document") - void failedOperationRequiresProblem() { - assertThatThrownBy( - () -> - new OperationResource( - ID, - OperationStatus.FAILED, - CREATED, - Optional.of(CREATED), - Optional.of(CREATED), - Optional.empty(), - Optional.empty(), - Optional.empty(), - Optional.empty(), - EXPIRES)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("problem document"); - } - - @Test - @DisplayName("a problem document on a non-failed operation is refused") - void nonFailedOperationCannotCarryProblem() { - // A RUNNING operation carrying an error is the shape that makes a client show a failure for - // work that is still going. - assertThatThrownBy( - () -> - new OperationResource( - ID, - OperationStatus.RUNNING, - CREATED, - Optional.of(CREATED), - Optional.empty(), - Optional.empty(), - Optional.empty(), - Optional.of( - WebProblemFactory.standard() - .create( - ProblemCode.INTERNAL_ERROR, - "boom", - URI.create("/x"), - "0af7651916cd43dd8448eb211c80319c", - List.of())), - Optional.empty(), - EXPIRES)) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("a terminal operation must say when it finished") - void terminalOperationRequiresCompletionTime() { - assertThatThrownBy( - () -> - new OperationResource( - ID, - OperationStatus.CANCELED, - CREATED, - Optional.of(CREATED), - Optional.empty(), - Optional.empty(), - Optional.empty(), - Optional.empty(), - Optional.empty(), - EXPIRES)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("when it finished"); - } - - @Test - @DisplayName("an unfinished operation cannot claim a completion time") - void unfinishedOperationCannotHaveCompletionTime() { - assertThatThrownBy( - () -> - new OperationResource( - ID, - OperationStatus.RUNNING, - CREATED, - Optional.of(CREATED), - Optional.of(CREATED), - Optional.empty(), - Optional.empty(), - Optional.empty(), - Optional.empty(), - EXPIRES)) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("a pending operation has not started and a running one has") - void startTimeMatchesTheStatus() { - assertThatCode(() -> OperationResource.pending(ID, CREATED, EXPIRES, Duration.ofSeconds(1))) - .doesNotThrowAnyException(); - assertThatThrownBy( - () -> - new OperationResource( - ID, - OperationStatus.PENDING, - CREATED, - Optional.of(CREATED), - Optional.empty(), - Optional.empty(), - Optional.empty(), - Optional.empty(), - Optional.empty(), - EXPIRES)) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new OperationResource( - ID, - OperationStatus.RUNNING, - CREATED, - Optional.empty(), - Optional.empty(), - Optional.empty(), - Optional.empty(), - Optional.empty(), - Optional.empty(), - EXPIRES)) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("an operation cannot start before it was accepted") - void startCannotPrecedeCreation() { - assertThatThrownBy( - () -> - OperationResource.pending(ID, CREATED, EXPIRES, Duration.ofSeconds(1)) - .running(CREATED.minusSeconds(1), null)) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("an operation that expires when it is created is refused") - void expiryMustBeAfterCreation() { - assertThatThrownBy(() -> OperationResource.pending(ID, CREATED, CREATED, Duration.ofSeconds(1))) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("EXPIRED is terminal but is not a failure") - void expiredIsTerminalWithoutBeingAFailure() { - // The work may well have succeeded. Reporting it as FAILED would tell a client something - // untrue about the world rather than something true about the record. - assertThat(OperationStatus.EXPIRED.terminal()).isTrue(); - assertThatCode( - () -> - new OperationResource( - ID, - OperationStatus.EXPIRED, - CREATED, - Optional.empty(), - Optional.of(EXPIRES), - Optional.empty(), - Optional.empty(), - Optional.empty(), - Optional.empty(), - EXPIRES)) - .doesNotThrowAnyException(); - } - - @Test - @DisplayName("progress cannot exceed its own total") - void progressCannotExceedTotal() { - assertThatThrownBy(() -> new OperationProgress(11, Optional.of(10L), Optional.empty())) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("progress with no total reports no fraction rather than inventing one") - void progressWithoutTotalHasNoFraction() { - assertThat(OperationProgress.of(7).fraction()).isEmpty(); - assertThat(new OperationProgress(5, Optional.of(10L), Optional.empty()).fraction()) - .contains(0.5); - } - - @Test - @DisplayName("an operation id that would need escaping in a URL is refused") - void operationIdMustBeUrlSafe() { - assertThatThrownBy(() -> new OperationId("op 1/../etc")) - .isInstanceOf(IllegalArgumentException.class); - } -} diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/pagination/CollectionQueryCatalogTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/pagination/CollectionQueryCatalogTest.java deleted file mode 100644 index af94a221..00000000 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/pagination/CollectionQueryCatalogTest.java +++ /dev/null @@ -1,137 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.pagination; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.web.pagination.FilterFieldCatalog.FilterableField; -import java.util.Map; -import java.util.Set; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * A sort name that reaches a query is a fragment of that query. - * - *

Every rejection here keeps caller-supplied text out of a place where it would become query - * structure rather than a query value. - */ -class CollectionQueryCatalogTest { - - private final InMemoryCollectionQueryCatalog catalog = InMemoryCollectionQueryCatalog.standard(); - - @Test - @DisplayName("an unpublished sort field is refused") - void anUnpublishedSortFieldIsRefused() { - assertThatThrownBy(() -> catalog.sortFields().resolve("drop_table")) - .isInstanceOf(UnsupportedQueryVocabularyException.class); - assertThatThrownBy(() -> catalog.sortFields().resolve(null)) - .isInstanceOf(UnsupportedQueryVocabularyException.class); - } - - @Test - @DisplayName("the rejection never echoes the value the caller sent") - void theRejectionNeverEchoesTheValue() { - assertThatThrownBy(() -> catalog.sortFields().resolve("drop_table; --")) - .as("quoting it back is a reflected-content vector in an error body") - .hasMessageNotContaining("drop_table"); - } - - @Test - @DisplayName("a published field resolves to the internal descriptor the registration chose") - void aPublishedFieldResolvesToItsInternalDescriptor() { - SortField field = catalog.sortFields().resolve("id"); - - assertThat(field.internalName()) - .as("the internal name is chosen by the registration, never derived from the request") - .isEqualTo("id"); - assertThat(field.uniqueTieBreaker()).isTrue(); - assertThat(catalog.sortFields().published("id")).isTrue(); - assertThat(catalog.sortFields().published("secret")).isFalse(); - } - - @Test - @DisplayName("a catalog with no unique tie-breaker is refused") - void aCatalogWithNoUniqueTieBreakerIsRefused() { - assertThatThrownBy( - () -> - new InMemoryCollectionQueryCatalog( - SortFieldCatalog.of(new SortField("createdAt", "created_at", false)), - FilterFieldCatalog.of(), - FilterOperatorCatalog.standard(), - ProjectionProfileCatalog.of(Map.of("default", Set.of("id"))))) - .as( - "two rows equal on every sort key have no defined order, so a page boundary repeats or skips") - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("tie-breaker"); - } - - @Test - @DisplayName("an operator is allowed per field, not globally") - void anOperatorIsAllowedPerFieldNotGlobally() { - FilterFieldCatalog fields = - FilterFieldCatalog.of( - new FilterableField("status", "status", Set.of(FilterOperatorCatalog.EQUALS)), - new FilterableField( - "createdAt", - "created_at", - Set.of(FilterOperatorCatalog.GREATER_OR_EQUAL, FilterOperatorCatalog.LESS_THAN))); - - assertThatCode(() -> fields.resolve("status", FilterOperatorCatalog.EQUALS)) - .doesNotThrowAnyException(); - assertThatThrownBy(() -> fields.resolve("status", FilterOperatorCatalog.GREATER_THAN)) - .as("a field can be safe to compare and disastrous to range-scan") - .isInstanceOf(UnsupportedQueryVocabularyException.class); - assertThatThrownBy(() -> fields.resolve("secret", FilterOperatorCatalog.EQUALS)) - .isInstanceOf(UnsupportedQueryVocabularyException.class); - } - - @Test - @DisplayName("an unpublished operator and an empty operator set are refused") - void anUnpublishedOperatorIsRefused() { - assertThatThrownBy(() -> catalog.filterOperators().resolve("regex")) - .as("an operator with no index strategy is a table scan a caller can trigger at will") - .isInstanceOf(UnsupportedQueryVocabularyException.class); - assertThat(catalog.filterOperators().resolve("eq")).isEqualTo("eq"); - assertThatThrownBy(() -> FilterOperatorCatalog.of(Set.of())) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("a projection is a named profile, not a caller-composed field list") - void aProjectionIsANamedProfile() { - assertThat(catalog.projections().resolve("default")).containsExactly("id"); - assertThatThrownBy(() -> catalog.projections().resolve("id,secret")) - .as("a caller-composed projection makes field authorisation a per-request question") - .isInstanceOf(UnsupportedQueryVocabularyException.class); - assertThatThrownBy(() -> ProjectionProfileCatalog.of(Map.of("empty", Set.of()))) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("a duplicate registration is refused") - void aDuplicateRegistrationIsRefused() { - assertThatThrownBy( - () -> - SortFieldCatalog.of( - new SortField("id", "id", true), new SortField("id", "other", true))) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("the vocabulary fingerprint changes when the vocabulary does") - void theVocabularyFingerprintChangesWhenTheVocabularyDoes() { - InMemoryCollectionQueryCatalog wider = - new InMemoryCollectionQueryCatalog( - SortFieldCatalog.of( - new SortField("id", "id", true), new SortField("name", "name", false)), - FilterFieldCatalog.of(), - FilterOperatorCatalog.standard(), - ProjectionProfileCatalog.of(Map.of("default", Set.of("id")))); - - assertThat(wider.vocabularyFingerprint()) - .as( - "a cursor issued before a field was added must not page a differently shaped result set") - .isNotEqualTo(catalog.vocabularyFingerprint()); - } -} diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/pagination/HmacWebCursorCodecTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/pagination/HmacWebCursorCodecTest.java deleted file mode 100644 index 22fc35f5..00000000 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/pagination/HmacWebCursorCodecTest.java +++ /dev/null @@ -1,170 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.pagination; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.nio.charset.StandardCharsets; -import java.time.Clock; -import java.time.Instant; -import java.time.ZoneOffset; -import java.util.LinkedHashMap; -import java.util.Map; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * Base64 is encoding, not protection. - * - *

Every case here is a cursor a caller could construct if one of the authenticated fields were - * left out of the MAC — most damagingly the filter fingerprint, whose absence lets a cursor minted - * under one filter page through rows the new filter was supposed to exclude. - */ -class HmacWebCursorCodecTest { - - private static final Instant NOW = Instant.parse("2026-08-13T00:00:00Z"); - private static final String PROFILE = "orders.list"; - private static final String FINGERPRINT = "status=OPEN"; - - private final HmacWebCursorCodec codec = - new HmacWebCursorCodec(keyRing("k1"), Clock.fixed(NOW, ZoneOffset.UTC)); - - @Test - @DisplayName("a cursor round-trips and keeps its position") - void aCursorRoundTrips() { - String cursor = codec.encode(payload(NOW)); - - WebCursorPayload decoded = codec.decode(cursor, PROFILE, FINGERPRINT); - - assertThat(decoded.sortValues()) - .containsExactly(Map.entry("createdAt", "2026-08-01"), Map.entry("id", "42")); - assertThat(decoded.queryProfile()).isEqualTo(PROFILE); - assertThat(decoded.version()).isEqualTo(WebCursorPayload.CURRENT_VERSION); - } - - @Test - @DisplayName("a tampered cursor is refused") - void aTamperedCursorIsRefused() { - String cursor = codec.encode(payload(NOW)); - String[] parts = cursor.split("\\.", -1); - String tamperedBody = - java.util.Base64.getUrlEncoder() - .withoutPadding() - .encodeToString( - new String( - java.util.Base64.getUrlDecoder().decode(parts[1]), StandardCharsets.UTF_8) - .replace("42", "99") - .getBytes(StandardCharsets.UTF_8)); - - assertThatThrownBy( - () -> - codec.decode(parts[0] + "." + tamperedBody + "." + parts[2], PROFILE, FINGERPRINT)) - .as("an edited base64 body is how continue-where-you-left-off becomes start-wherever-I-say") - .isInstanceOf(WebCursorException.class); - } - - @Test - @DisplayName("a cursor from another query profile is refused") - void aCursorFromAnotherQueryProfileIsRefused() { - String cursor = codec.encode(payload(NOW)); - - assertThatThrownBy(() -> codec.decode(cursor, "documents.list", FINGERPRINT)) - .isInstanceOf(WebCursorException.class); - } - - @Test - @DisplayName("a cursor minted under a different filter is refused") - void aCursorMintedUnderADifferentFilterIsRefused() { - String cursor = codec.encode(payload(NOW)); - - assertThatThrownBy(() -> codec.decode(cursor, PROFILE, "status=CLOSED")) - .as("otherwise the cursor pages through rows the new filter was supposed to exclude") - .isInstanceOf(WebCursorException.class); - } - - @Test - @DisplayName("a cursor signed by an unknown key is refused") - void aCursorSignedByAnUnknownKeyIsRefused() { - String foreign = - new HmacWebCursorCodec(keyRing("other"), Clock.fixed(NOW, ZoneOffset.UTC)) - .encode(payload(NOW)); - - assertThatThrownBy(() -> codec.decode(foreign, PROFILE, FINGERPRINT)) - .isInstanceOf(WebCursorException.class); - } - - @Test - @DisplayName("a retired key still verifies, so rotation does not break a scan mid-page") - void aRetiredKeyStillVerifies() { - // k1 keeps the material the original ring used; that is what makes this a rotation rather than - // a different ring that happens to reuse a name. - WebCursorKeyRing rotated = WebCursorKeyRing.of("k2", Map.of("k1", key('k'), "k2", key('2'))); - String oldCursor = codec.encode(payload(NOW)); - - HmacWebCursorCodec afterRotation = - new HmacWebCursorCodec(rotated, Clock.fixed(NOW, ZoneOffset.UTC)); - - assertThat(rotated.activeKeyId()).isEqualTo("k2"); - assertThatCode(() -> afterRotation.decode(oldCursor, PROFILE, FINGERPRINT)) - .as("replacing the key outright turns every held cursor into a refusal mid-scan") - .doesNotThrowAnyException(); - } - - @Test - @DisplayName("an expired cursor is refused") - void anExpiredCursorIsRefused() { - String cursor = codec.encode(payload(NOW)); - HmacWebCursorCodec later = - new HmacWebCursorCodec(keyRing("k1"), Clock.fixed(NOW.plusSeconds(7200), ZoneOffset.UTC)); - - assertThatThrownBy(() -> later.decode(cursor, PROFILE, FINGERPRINT)) - .isInstanceOf(WebCursorException.class); - } - - @Test - @DisplayName("malformed input is refused without saying which check failed") - void malformedInputIsRefused() { - for (String bad : new String[] {"", "not-a-cursor", "a.b", "a.b.c.d", "k1.!!!.sig"}) { - assertThatThrownBy(() -> codec.decode(bad, PROFILE, FINGERPRINT)) - .as("naming the failed check tells a caller how to get closer") - .isInstanceOf(WebCursorException.class) - .hasMessage("the cursor is not valid for this query"); - } - assertThatThrownBy(() -> codec.decode(null, PROFILE, FINGERPRINT)) - .isInstanceOf(WebCursorException.class); - } - - @Test - @DisplayName("a short signing key is refused, and there is no default key") - void aShortSigningKeyIsRefused() { - assertThatThrownBy(() -> WebCursorKeyRing.of("k1", Map.of("k1", new byte[16]))) - .as("a key shorter than the MAC it produces adds no strength") - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> WebCursorKeyRing.of("absent", Map.of("k1", key('a')))) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("a cursor with no position is refused at construction") - void aCursorWithNoPositionIsRefused() { - assertThatThrownBy(() -> WebCursorPayload.current(PROFILE, FINGERPRINT, Map.of(), NOW)) - .isInstanceOf(IllegalArgumentException.class); - } - - private static WebCursorPayload payload(Instant issuedAt) { - Map sortValues = new LinkedHashMap<>(); - sortValues.put("createdAt", "2026-08-01"); - sortValues.put("id", "42"); - return WebCursorPayload.current(PROFILE, FINGERPRINT, sortValues, issuedAt); - } - - private static WebCursorKeyRing keyRing(String keyId) { - return WebCursorKeyRing.of(keyId, Map.of(keyId, key(keyId.charAt(0)))); - } - - private static byte[] key(char seed) { - byte[] material = new byte[32]; - java.util.Arrays.fill(material, (byte) seed); - return material; - } -} diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/pagination/WebCollectionRequestParserTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/pagination/WebCollectionRequestParserTest.java deleted file mode 100644 index 194055a2..00000000 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/pagination/WebCollectionRequestParserTest.java +++ /dev/null @@ -1,156 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.pagination; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.web.pagination.FilterFieldCatalog.FilterableField; -import java.time.Clock; -import java.time.Instant; -import java.time.ZoneOffset; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Set; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * The parser is where caller text stops being caller text. - * - *

The order of its checks is the substance: the fingerprint is computed from the resolved query - * and the cursor is verified against that, so a cursor cannot be accepted before the platform knows - * which query it is being replayed into. - */ -class WebCollectionRequestParserTest { - - private static final Instant NOW = Instant.parse("2026-08-13T00:00:00Z"); - private static final String PROFILE = "orders.list"; - - private final InMemoryCollectionQueryCatalog catalog = - new InMemoryCollectionQueryCatalog( - SortFieldCatalog.of( - new SortField("id", "id", true), new SortField("createdAt", "created_at", false)), - FilterFieldCatalog.of( - new FilterableField("status", "status", Set.of(FilterOperatorCatalog.EQUALS))), - FilterOperatorCatalog.standard(), - ProjectionProfileCatalog.of(Map.of("default", Set.of("id")))); - - private final WebCursorCodec codec = - new HmacWebCursorCodec( - WebCursorKeyRing.of("k1", Map.of("k1", key())), Clock.fixed(NOW, ZoneOffset.UTC)); - - private final WebCollectionRequestParser parser = - new WebCollectionRequestParser(catalog, WebPageSizePolicy.standard(), codec); - - @Test - @DisplayName("the default page size is 50 and the ceiling is 200") - void theDefaultPageSizeIs50AndTheCeilingIs200() { - assertThat(parse(null, Map.of(), null, null).pageSize()).isEqualTo(50); - assertThat(parse(null, Map.of(), 200, null).pageSize()).isEqualTo(200); - assertThatThrownBy(() -> parse(null, Map.of(), 201, null)) - .as("clamping silently makes a client read a short page as the last one") - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> parse(null, Map.of(), 0, null)) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("the sort resolves to an internal descriptor and a direction") - void theSortResolvesToAnInternalDescriptor() { - WebCollectionRequest ascending = parse("createdAt", Map.of(), null, null); - WebCollectionRequest descending = parse("-createdAt", Map.of(), null, null); - - assertThat(ascending.sort().internalName()).isEqualTo("created_at"); - assertThat(ascending.descending()).isFalse(); - assertThat(descending.descending()).isTrue(); - assertThatThrownBy(() -> parse("secret", Map.of(), null, null)) - .isInstanceOf(UnsupportedQueryVocabularyException.class); - } - - @Test - @DisplayName("a filter resolves through the catalog and never survives as caller text") - void aFilterResolvesThroughTheCatalog() { - WebCollectionRequest request = parse(null, Map.of("status.eq", "OPEN"), null, null); - - assertThat(request.filters()).containsExactly(Map.entry("status.eq", "OPEN")); - assertThatThrownBy(() -> parse(null, Map.of("secret.eq", "x"), null, null)) - .isInstanceOf(UnsupportedQueryVocabularyException.class); - assertThatThrownBy(() -> parse(null, Map.of("status.gt", "OPEN"), null, null)) - .as("the operator decides what the storage layer may do with the field") - .isInstanceOf(UnsupportedQueryVocabularyException.class); - } - - @Test - @DisplayName("a cursor from a different filter is refused by the parser") - void aCursorFromADifferentFilterIsRefused() { - WebCollectionRequest first = parse(null, Map.of("status.eq", "OPEN"), null, null); - String cursor = parser.nextCursor(first, lastRow(), NOW); - - assertThatCode(() -> parse(null, Map.of("status.eq", "OPEN"), null, cursor)) - .doesNotThrowAnyException(); - assertThatThrownBy(() -> parse(null, Map.of("status.eq", "CLOSED"), null, cursor)) - .as("a cursor replayed under a new filter pages through rows that filter excluded") - .isInstanceOf(WebCursorException.class); - } - - @Test - @DisplayName("a cursor from a different sort order is refused") - void aCursorFromADifferentSortOrderIsRefused() { - String cursor = parser.nextCursor(parse("createdAt", Map.of(), null, null), lastRow(), NOW); - - assertThatThrownBy(() -> parse("-createdAt", Map.of(), null, cursor)) - .isInstanceOf(WebCursorException.class); - } - - @Test - @DisplayName("the fingerprint does not depend on parameter order") - void theFingerprintDoesNotDependOnParameterOrder() { - Map oneOrder = new LinkedHashMap<>(); - oneOrder.put("status.eq", "OPEN"); - Map otherOrder = new LinkedHashMap<>(); - otherOrder.put("status.eq", "OPEN"); - - assertThat(parse(null, oneOrder, null, null).filterFingerprint()) - .as("?a=1&b=2 and ?b=2&a=1 are the same filter, so they must be the same page") - .isEqualTo(parse(null, otherOrder, null, null).filterFingerprint()); - } - - @Test - @DisplayName("a total count is refused unless the profile permits one") - void aTotalCountIsRefusedUnlessPermitted() { - assertThatThrownBy(() -> parser.parse(PROFILE, null, Map.of(), null, null, true, false)) - .as("counting is a second query over the whole filtered set") - .isInstanceOf(UnsupportedQueryVocabularyException.class); - assertThat(parser.parse(PROFILE, null, Map.of(), null, null, true, true).includeTotalCount()) - .isTrue(); - assertThat(parser.parse(PROFILE, null, Map.of(), null, null, false, true).includeTotalCount()) - .isFalse(); - } - - @Test - @DisplayName("a first page carries no cursor and a continuation does") - void aFirstPageCarriesNoCursor() { - WebCollectionRequest first = parse(null, Map.of(), null, null); - - assertThat(first.continuation()).isFalse(); - assertThat(parse(null, Map.of(), null, parser.nextCursor(first, lastRow(), NOW)).continuation()) - .isTrue(); - } - - private WebCollectionRequest parse( - String sort, Map filters, Integer pageSize, String cursor) { - return parser.parse(PROFILE, sort, filters, pageSize, cursor, false, false); - } - - private static Map lastRow() { - Map values = new LinkedHashMap<>(); - values.put("id", "42"); - return values; - } - - private static byte[] key() { - byte[] material = new byte[32]; - java.util.Arrays.fill(material, (byte) 'k'); - return material; - } -} diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/proxy/ForwardedHeaderSanitizerTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/proxy/ForwardedHeaderSanitizerTest.java deleted file mode 100644 index bc4a4a26..00000000 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/proxy/ForwardedHeaderSanitizerTest.java +++ /dev/null @@ -1,129 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.proxy; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.util.Map; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * Forwarded headers are plain request headers, so anybody who can reach the port can set them. - * - *

Each case here is a thing a caller gets to choose if the trust check is missing: the address - * its rate limit is keyed on, the host a password-reset link points at, and whether the request - * "arrived over HTTPS". - */ -class ForwardedHeaderSanitizerTest { - - private final ForwardedHeaderSanitizer sanitizer = - new ForwardedHeaderSanitizer(TrustedProxyPolicy.of("10.0.0.0/8")); - - @Test - @DisplayName("forwarded headers from an untrusted peer are refused") - void forwardedHeadersFromAnUntrustedPeerAreRefused() { - assertThatThrownBy( - () -> sanitizer.normalize("203.0.113.10", Map.of("X-Forwarded-Host", "evil.example"))) - .as("ignoring silently leaves the attempt invisible and the same client keeps probing") - .isInstanceOf(UntrustedForwardedHeaderException.class) - .hasMessageContaining("203.0.113.10"); - } - - @Test - @DisplayName("the refusal message never echoes the header value") - void theRefusalMessageNeverEchoesTheHeaderValue() { - assertThatThrownBy( - () -> - sanitizer.normalize("203.0.113.10", Map.of("X-Forwarded-Host", "attacker-chosen"))) - .as("attacker-chosen content in the log line that reports the attack") - .hasMessageNotContaining("attacker-chosen"); - } - - @Test - @DisplayName("a trusted proxy's headers are believed and normalised") - void aTrustedProxysHeadersAreBelieved() { - NormalizedForwardedHeaders normalized = - sanitizer.normalize( - "10.1.2.3", - Map.of( - "X-Forwarded-Proto", "HTTPS", - "X-Forwarded-Host", "API.Example.com:443", - "X-Forwarded-Port", "443", - "X-Forwarded-Prefix", "/gateway/", - "X-Forwarded-For", "203.0.113.7, 10.1.2.3")); - - assertThat(normalized.scheme()).contains("https"); - assertThat(normalized.host()) - .as("the port is not part of the host") - .contains("api.example.com"); - assertThat(normalized.port()).contains(443); - assertThat(normalized.prefix()).as("a trailing slash is normalised away").contains("/gateway"); - assertThat(normalized.clientAddress()) - .as("the leftmost hop is the originating client") - .contains("203.0.113.7"); - } - - @Test - @DisplayName("a trusted proxy is trusted to be honest, not to be correct") - void aTrustedProxyIsTrustedToBeHonestNotCorrect() { - NormalizedForwardedHeaders normalized = - sanitizer.normalize( - "10.1.2.3", - Map.of( - "X-Forwarded-Proto", "gopher", - "X-Forwarded-Host", "", - "X-Forwarded-Port", "70000", - "X-Forwarded-Prefix", "/../admin")); - - assertThat(normalized.scheme()) - .as("only http and https are schemes this platform builds") - .isEmpty(); - assertThat(normalized.host()).as("an empty host would produce https:///reset").isEmpty(); - assertThat(normalized.port()).isEmpty(); - assertThat(normalized.prefix()) - .as("a traversing prefix chooses where a Location points") - .isEmpty(); - } - - @Test - @DisplayName("a direct-access deployment trusts nobody and reads its own socket") - void aDirectAccessDeploymentTrustsNobody() { - ForwardedHeaderSanitizer direct = - new ForwardedHeaderSanitizer(TrustedProxyPolicy.trustNobody(), false); - - assertThat(direct.normalize("10.1.2.3", Map.of("X-Forwarded-Host", "evil.example"))) - .isEqualTo(NormalizedForwardedHeaders.none()); - assertThat(TrustedProxyPolicy.trustNobody().trustsAnybody()).isFalse(); - } - - @Test - @DisplayName("a request with no forwarded headers is untouched") - void aRequestWithNoForwardedHeadersIsUntouched() { - assertThat(sanitizer.normalize("203.0.113.10", Map.of("Accept", "application/json"))) - .isEqualTo(NormalizedForwardedHeaders.none()); - assertThat(NormalizedForwardedHeaders.present(Map.of("Accept", "application/json"))).isFalse(); - assertThat(NormalizedForwardedHeaders.present(Map.of("forwarded", "for=1.2.3.4"))).isTrue(); - } - - @Test - @DisplayName("an address family never matches the other family's range") - void anAddressFamilyNeverMatchesTheOtherFamilysRange() { - TrustedProxyPolicy ipv4 = TrustedProxyPolicy.of("10.0.0.0/8"); - - assertThat(ipv4.isTrusted("10.255.255.254")).isTrue(); - assertThat(ipv4.isTrusted("11.0.0.1")).isFalse(); - assertThat(ipv4.isTrusted("::ffff:10.0.0.1")) - .as( - "the JDK canonicalises an IPv4-mapped address to Inet4Address, so this *is* 10.0.0.1 —" - + " and that is safe here because the peer address comes from the socket, not from a" - + " header a caller can choose") - .isTrue(); - assertThat(ipv4.isTrusted("2001:db8::1")) - .as("a genuine IPv6 peer has no business matching an IPv4 range") - .isFalse(); - assertThat(TrustedProxyPolicy.of("2001:db8::/32").isTrusted("10.0.0.1")).isFalse(); - assertThat(ipv4.isTrusted((String) null)).isFalse(); - assertThatThrownBy(() -> TrustedProxyPolicy.of("10.0.0.0")) - .isInstanceOf(IllegalArgumentException.class); - } -} diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/security/WebCorsCsrfPolicyTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/security/WebCorsCsrfPolicyTest.java deleted file mode 100644 index e8d4107c..00000000 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/security/WebCorsCsrfPolicyTest.java +++ /dev/null @@ -1,176 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.security; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.time.Duration; -import java.util.Set; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * Cross-origin and cross-site settings that look fine and are not. - * - *

Every case here describes a configuration under which the API answers correctly and the only - * difference is who else can make it answer. None of them would fail a test of the endpoint's own - * behaviour, which is why they are refused at construction instead. - */ -class WebCorsCsrfPolicyTest { - - private final WebCorsPolicyValidator validator = new WebCorsPolicyValidator(); - private final WebCsrfPolicyResolver csrf = new WebCsrfPolicyResolver(); - - @Test - @DisplayName("a wildcard origin with credentials is refused") - void rejectsWildcardOriginWithCredentials() { - assertThatThrownBy( - () -> - validator.validate( - new CorsProfile( - Set.of("*"), - Set.of("GET", "POST"), - Set.of("Content-Type"), - Set.of(), - true, - Duration.ofMinutes(10)))) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("exact origin allowlist"); - } - - @Test - @DisplayName("a wildcard origin without credentials is fine") - void wildcardWithoutCredentialsIsAllowed() { - assertThatCode(() -> validator.validate(CorsProfile.publicReadOnly())) - .doesNotThrowAnyException(); - } - - @Test - @DisplayName("an origin carrying a path is refused") - void originWithPathIsRefused() { - // An origin is scheme, host and port. Adding a path produces an entry that never matches and - // reads as though the allowlist covers a route. - assertThatThrownBy( - () -> - validator.validate( - CorsProfile.credentialedFrontEnd(Set.of("https://app.example.com/admin")))) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("no path"); - } - - @Test - @DisplayName("a bare host without a scheme is refused") - void bareHostIsRefused() { - assertThatThrownBy( - () -> validator.validate(CorsProfile.credentialedFrontEnd(Set.of("app.example.com")))) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("scheme://host"); - } - - @Test - @DisplayName("a wildcard inside an origin is refused") - void wildcardInsideOriginIsRefused() { - // Reads as "any subdomain" and matches nothing at all, so the failure looks like the whole - // allowlist being ignored. - assertThatThrownBy( - () -> - validator.validate( - CorsProfile.credentialedFrontEnd(Set.of("https://*.example.com")))) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("matches nothing"); - } - - @Test - @DisplayName("an uppercase origin is refused") - void uppercaseOriginIsRefused() { - assertThatThrownBy( - () -> - validator.validate( - CorsProfile.credentialedFrontEnd(Set.of("https://App.Example.com")))) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("lowercase"); - } - - @Test - @DisplayName("origin matching is exact, not by suffix") - void originMatchingIsExact() { - CorsProfile profile = CorsProfile.credentialedFrontEnd(Set.of("https://app.example.com")); - - assertThat(profile.permits("https://app.example.com")).isTrue(); - // The two hosts a suffix check lets in. - assertThat(profile.permits("https://evil-app.example.com")).isFalse(); - assertThat(profile.permits("https://app.example.com.attacker.net")).isFalse(); - // And the scheme is part of it: http is a different origin from https. - assertThat(profile.permits("http://app.example.com")).isFalse(); - } - - @Test - @DisplayName("a credentialed profile may not accept wildcard headers") - void credentialedProfileCannotWildcardHeaders() { - assertThatThrownBy( - () -> - validator.validate( - new CorsProfile( - Set.of("https://app.example.com"), - Set.of("POST"), - Set.of("*"), - Set.of(), - true, - Duration.ofMinutes(10)))) - .isInstanceOf(IllegalStateException.class); - } - - @Test - @DisplayName("a session cookie requires CSRF protection") - void sessionCookieRequiresCsrf() { - assertThat(csrf.resolve(WebCredentialMode.SESSION_COOKIE).enabled()).isTrue(); - assertThat(csrf.resolve(WebCredentialMode.BFF_COOKIE).enabled()).isTrue(); - } - - @Test - @DisplayName("accepting both a cookie and a bearer token still requires CSRF") - void cookieAndBearerRequiresCsrf() { - // The case that gets reasoned away. The header path is safe and irrelevant: an attacker's - // cross-site form simply omits the header, the browser supplies the cookie, and the request - // authenticates. - assertThat(csrf.resolve(WebCredentialMode.COOKIE_AND_BEARER).enabled()).isTrue(); - } - - @Test - @DisplayName("a header-only credential is exempt, with the reason recorded") - void headerOnlyIsExemptWithAStatedReason() { - CsrfProfile profile = csrf.resolve(WebCredentialMode.AUTHORIZATION_HEADER_ONLY); - - assertThat(profile.enabled()).isFalse(); - // The reason is the point. "CSRF is off here" with no rationale is a line nobody dares change - // and nobody can justify a year later. - assertThat(profile.rationale()).contains("no cookie"); - } - - @Test - @DisplayName("a service-to-service credential is exempt, with the reason recorded") - void serviceToServiceIsExemptWithAStatedReason() { - CsrfProfile profile = csrf.resolve(WebCredentialMode.SERVICE_TO_SERVICE); - - assertThat(profile.enabled()).isFalse(); - assertThat(profile.rationale()).contains("not a browser"); - } - - @Test - @DisplayName("a CSRF decision with no stated reason is refused") - void csrfDecisionNeedsAReason() { - assertThatThrownBy(() -> new CsrfProfile(false, " ")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("cannot be reviewed"); - } - - @Test - @DisplayName("every credential mode is classified, so a new one cannot default to exempt") - void everyModeIsClassified() { - // A mode added to the enum without a decision here fails loudly rather than inheriting an - // exemption from a default branch. - for (WebCredentialMode mode : WebCredentialMode.values()) { - assertThat(csrf.resolve(mode).enabled()).isEqualTo(mode.ambientlyAttached()); - } - } -} diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/testkit/contract/CrossStackParityTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/testkit/contract/CrossStackParityTest.java deleted file mode 100644 index 5a6c1ba6..00000000 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/testkit/contract/CrossStackParityTest.java +++ /dev/null @@ -1,138 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.testkit.contract; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * The three transports must answer the same probe the same way. - * - *

Compared from recordings rather than in one process, because the stacks cannot coexist: Spring - * Boot deduces a single application type from the classpath, so Tomcat, Jetty and Reactor Netty - * each need their own source set. Each lane writes what it observed; this reads the files. - * - *

The indirection is also what makes the comparison mean something. A parity check that built - * both stacks from one test would be tempted into a shared helper, and a shared helper makes two - * stacks agree by construction rather than by both being right. - * - *

It fails when a recording is missing rather than comparing whatever happens to be present. A - * parity test that silently compares one lane to itself is the shape this whole exercise is - * supposed to prevent. That is also why it is tagged out of the ordinary {@code test} task and run - * by {@code webCrossStackParityTest}, which depends on all three recording lanes: in {@code test} - * alone the other two recordings do not exist yet, and a gate that fails for that reason teaches - * people to ignore it. - */ -@org.junit.jupiter.api.Tag("web-parity") -class CrossStackParityTest { - - private static final List LANES = List.of("tomcat", "jetty", "reactor-netty"); - - @Test - @DisplayName("every transport recorded the whole probe list") - void everyTransportRecorded() { - Map> recordings = readRecordings(); - - assertThat(recordings.keySet()) - .as( - "a missing recording means that lane did not run; comparing the rest would report" - + " parity across a matrix with a hole in it") - .containsExactlyInAnyOrderElementsOf(LANES); - recordings.forEach( - (lane, outcomes) -> - assertThat(outcomes.keySet()) - .as("%s did not record every probe", lane) - .containsExactlyInAnyOrderElementsOf( - WebPlatformContractSuite.probes().stream().map(WireProbe::name).toList())); - } - - @Test - @DisplayName("MVC and WebFlux expose the same problem and header contract") - void mvcAndWebFluxExposeSameProblemAndHeaderContract() { - Map> recordings = readRecordings(); - - Map tomcat = recordings.get("tomcat"); - Map reactive = recordings.get("reactor-netty"); - - // Compared as whole maps rather than probe by probe, so the failure message names every - // divergence at once instead of stopping at the first. - assertThat(normalize(reactive)) - .as("the reactive stack answers differently from the servlet stack") - .isEqualTo(normalize(tomcat)); - } - - @Test - @DisplayName("the two servlet containers agree with each other") - void servletContainersAgree() { - // Not implied by the test above. Container-specific behaviour — how a 405's Allow header is - // assembled, whether a bare status carries a content type — is exactly what differs between - // Tomcat and Jetty while both use the same platform code. - Map> recordings = readRecordings(); - - assertThat(normalize(recordings.get("jetty"))).isEqualTo(normalize(recordings.get("tomcat"))); - } - - @Test - @DisplayName("every failure carries a code on every transport") - void everyFailureCarriesACodeEverywhere() { - // The property the recording caught missing on the first run: Spring's own ProblemDetail is - // RFC 9457-shaped and carries no code, so it looks correct and gives a client nothing to - // branch on. - readRecordings() - .forEach( - (lane, outcomes) -> - outcomes.forEach( - (probe, outcome) -> { - if (outcome.status() >= 400) { - assertThat(outcome.problemCode()) - .as("%s answered %s with no problem code", lane, probe) - .isNotEmpty(); - assertThat(outcome.contentType()) - .as("%s answered %s without a problem document", lane, probe) - .isEqualTo("application/problem+json"); - } - })); - } - - private static Map normalize(Map outcomes) { - Map normalized = new TreeMap<>(); - outcomes.forEach((probe, outcome) -> normalized.put(probe, outcome.recorded())); - return normalized; - } - - private static Map> readRecordings() { - Path directory = WebContractFixture.recordingDirectory(); - Map> recordings = new LinkedHashMap<>(); - for (String lane : LANES) { - Path file = directory.resolve(lane + ".properties"); - if (!Files.exists(file)) { - continue; - } - recordings.put(lane, read(file)); - } - return recordings; - } - - private static Map read(Path file) { - Map outcomes = new LinkedHashMap<>(); - try { - for (String line : Files.readAllLines(file)) { - if (line.isBlank()) { - continue; - } - int equals = line.indexOf('='); - outcomes.put(line.substring(0, equals), WireOutcome.parse(line.substring(equals + 1))); - } - } catch (IOException e) { - throw new IllegalStateException("the recording at " + file + " could not be read", e); - } - return outcomes; - } -} diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/validation/WebValidationExceptionMapperTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/validation/WebValidationExceptionMapperTest.java deleted file mode 100644 index 7cca8a05..00000000 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/validation/WebValidationExceptionMapperTest.java +++ /dev/null @@ -1,125 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.validation; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.web.error.ProblemCode; -import dev.caskeleton.adapter.inbound.web.json.WebJsonDecodingException; -import dev.caskeleton.adapter.inbound.web.json.WebObjectMapperFactory; -import jakarta.validation.Validation; -import jakarta.validation.Validator; -import jakarta.validation.constraints.Min; -import jakarta.validation.constraints.NotBlank; -import java.util.List; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import tools.jackson.core.exc.StreamReadException; -import tools.jackson.databind.ObjectMapper; - -/** - * 400 means "I could not understand you"; 422 means "I understood and it is not acceptable". - * - *

Collapsing both into 400 is the common shortcut, and it leaves a client unable to tell a bug - * in its serialiser from a rejected form. - */ -class WebValidationExceptionMapperTest { - - private final WebValidationExceptionMapper mapper = new WebValidationExceptionMapper(); - - record CreateRequest(@NotBlank String title, @Min(1) int quantity) {} - - @Test - @DisplayName("malformed JSON is 400 and transport validation is 422") - void malformedJsonIs400AndTransportValidationIs422() { - assertThat(mapper.codeFor(new StreamReadException(null, "bad"))) - .isEqualTo(ProblemCode.MALFORMED_REQUEST); - assertThat(mapper.codeFor(new TransportValidationException("invalid title"))) - .isEqualTo(ProblemCode.VALIDATION_FAILED); - } - - @Test - @DisplayName("a real unknown property and a real scalar mismatch are binding failures") - void realReadFailuresAreBindingFailures() { - ObjectMapper strict = WebObjectMapperFactory.standard(); - - Throwable unknown = - catchFailure( - () -> - strict.readValue( - "{\"title\":\"a\",\"quantity\":1,\"typo\":1}", CreateRequest.class)); - Throwable mismatch = - catchFailure( - () -> strict.readValue("{\"title\":\"a\",\"quantity\":\"x\"}", CreateRequest.class)); - - assertThat(mapper.codeFor(unknown)).isEqualTo(ProblemCode.BINDING_FAILED); - assertThat(mapper.codeFor(mismatch)).isEqualTo(ProblemCode.BINDING_FAILED); - } - - @Test - @DisplayName("a decoding failure reports which side of the split it is on") - void aDecodingFailureReportsWhichSideOfTheSplit() { - assertThat(mapper.codeFor(new WebJsonDecodingException("not json", true, null))) - .isEqualTo(ProblemCode.MALFORMED_REQUEST); - assertThat(mapper.codeFor(new WebJsonDecodingException("bad shape", false, null))) - .isEqualTo(ProblemCode.BINDING_FAILED); - } - - @Test - @DisplayName("an unmapped failure throws rather than defaulting to a guess") - void anUnmappedFailureThrows() { - assertThat(mapper.handles(new IllegalStateException("who knows"))).isFalse(); - assertThatThrownBy(() -> mapper.codeFor(new IllegalStateException("who knows"))) - .as("a default status here would be a guess published to a client") - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("unmapped validation failure"); - assertThatThrownBy(() -> mapper.codeFor(null)).isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("bean validation becomes JSON Pointers and stable codes, never the submitted value") - void beanValidationBecomesPointersAndStableCodes() { - try (var factory = Validation.buildDefaultValidatorFactory()) { - Validator validator = factory.getValidator(); - var violations = validator.validate(new CreateRequest(" ", 0)); - - var issues = new WebValidationIssueMapper().toIssues(violations); - - assertThat(issues).hasSize(2); - assertThat(issues).extracting("pointer").containsExactly("/quantity", "/title"); - assertThat(issues) - .extracting("code") - .containsExactly("must-be-at-least", "must-not-be-blank"); - assertThat(issues) - .as("the submitted value must never be echoed back into an error body") - .noneMatch(issue -> issue.message().contains(" ")); - } - } - - @Test - @DisplayName("a property path becomes a JSON Pointer a client can act on") - void aPropertyPathBecomesAJsonPointer() { - assertThat(WebInputPointer.fromPropertyPath("lines[0].quantity")) - .isEqualTo("/lines/0/quantity"); - assertThat(WebInputPointer.fromPropertyPath("createOrder.arg0.title")) - .as("the argument segment names a Java signature, not anything the client sent") - .isEqualTo("/createOrder/title"); - assertThat(WebInputPointer.fromPropertyPath("")).isEqualTo(WebInputPointer.ROOT); - assertThat(WebInputPointer.of(List.of("a/b"))) - .as("a member named a/b must not address a nested member that does not exist") - .isEqualTo("/a~1b"); - } - - private static Throwable catchFailure(ThrowingCall call) { - try { - call.run(); - } catch (Exception failure) { - return failure; - } - throw new AssertionError("expected the strict mapper to refuse this document"); - } - - @FunctionalInterface - private interface ThrowingCall { - void run() throws Exception; - } -} diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/webflux/autoconfigure/WebFluxPlatformAutoConfigurationTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/webflux/autoconfigure/WebFluxPlatformAutoConfigurationTest.java deleted file mode 100644 index 10e95f13..00000000 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/webflux/autoconfigure/WebFluxPlatformAutoConfigurationTest.java +++ /dev/null @@ -1,112 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.webflux.autoconfigure; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.adapter.inbound.web.error.WebProblemFactory; -import dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebMvcPlatformAutoConfiguration; -import dev.caskeleton.adapter.inbound.web.mvc.filter.WebMvcEvidenceFilter; -import dev.caskeleton.adapter.inbound.web.webflux.context.WebFluxRequestContextFilter; -import dev.caskeleton.adapter.inbound.web.webflux.guard.BlockingDependencyGuard; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.springframework.boot.autoconfigure.AutoConfigurations; -import org.springframework.boot.test.context.runner.ApplicationContextRunner; -import org.springframework.boot.test.context.runner.ReactiveWebApplicationContextRunner; -import org.springframework.boot.test.context.runner.WebApplicationContextRunner; - -/** - * The reactive starter activates in a reactive application and nowhere else. - * - *

The mutual exclusion is asserted from both sides. Spring Boot deduces exactly one application - * type, so the two roots can never both activate — a stronger guarantee than a startup check, - * because it holds before any bean is created. Proving it means running each root under the other's - * application type. - */ -class WebFluxPlatformAutoConfigurationTest { - - private final ReactiveWebApplicationContextRunner reactive = - new ReactiveWebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(WebFluxPlatformAutoConfiguration.class)); - - @Test - @DisplayName("a reactive application gets the reactive wiring") - void aReactiveApplicationGetsTheReactiveWiring() { - reactive.run( - context -> - assertThat(context) - .hasNotFailed() - .hasSingleBean(WebFluxRequestContextFilter.class) - .hasSingleBean(BlockingDependencyGuard.class) - .hasSingleBean(WebProblemFactory.class)); - } - - @Test - @DisplayName("the reactive starter brings no servlet wiring") - void theReactiveStarterBringsNoServletWiring() { - reactive.run( - context -> - assertThat(context) - .as("the design forbids the reactive starter pulling MVC or servlet types in") - .doesNotHaveBean(WebMvcEvidenceFilter.class)); - } - - @Test - @DisplayName("both roots on the classpath still activate only one") - void bothRootsOnTheClasspathStillActivateOnlyOne() { - new ReactiveWebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of( - WebFluxPlatformAutoConfiguration.class, WebMvcPlatformAutoConfiguration.class)) - .run( - context -> - assertThat(context) - .hasSingleBean(WebFluxRequestContextFilter.class) - .doesNotHaveBean(WebMvcEvidenceFilter.class)); - - new WebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of( - WebFluxPlatformAutoConfiguration.class, WebMvcPlatformAutoConfiguration.class)) - .run( - context -> - assertThat(context) - .hasSingleBean(WebMvcEvidenceFilter.class) - .doesNotHaveBean(WebFluxRequestContextFilter.class)); - } - - @Test - @DisplayName("a non-web application gets neither") - void aNonWebApplicationGetsNeither() { - new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(WebFluxPlatformAutoConfiguration.class)) - .run(context -> assertThat(context).doesNotHaveBean(WebFluxRequestContextFilter.class)); - } - - @Test - @DisplayName("the master switch turns everything off") - void theMasterSwitchTurnsEverythingOff() { - reactive - .withPropertyValues("backend.web.webflux.enabled=false") - .run(context -> assertThat(context).doesNotHaveBean(WebFluxRequestContextFilter.class)); - } - - @Test - @DisplayName("the blocking guard is on unless a deployment turns it off") - void theBlockingGuardIsOnUnlessTurnedOff() { - assertThat(WebFluxPlatformSettings.defaults().blockingGuardEnabled()) - .as("a guard that must be switched on is one the least careful deployments do not have") - .isTrue(); - reactive - .withPropertyValues("backend.web.webflux.blocking-guard-enabled=false") - .run(context -> assertThat(context).doesNotHaveBean(BlockingDependencyGuard.class)); - } - - @Test - @DisplayName("a non-positive request budget is refused at binding time") - void aNonPositiveRequestBudgetIsRefused() { - assertThat(WebFluxPlatformSettings.defaults().requestBudgetSeconds()).isEqualTo(10); - org.assertj.core.api.Assertions.assertThatThrownBy( - () -> new WebFluxPlatformSettings(true, false, true, 0)) - .isInstanceOf(IllegalArgumentException.class); - } -} diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/webflux/context/WebFluxRequestContextAccessorTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/webflux/context/WebFluxRequestContextAccessorTest.java deleted file mode 100644 index a9023edb..00000000 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/webflux/context/WebFluxRequestContextAccessorTest.java +++ /dev/null @@ -1,93 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.webflux.context; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.adapter.inbound.web.core.ActorContext; -import dev.caskeleton.adapter.inbound.web.core.ApiMajorVersion; -import dev.caskeleton.adapter.inbound.web.core.ExternalRequestContext; -import dev.caskeleton.adapter.inbound.web.core.TenantContext; -import dev.caskeleton.adapter.inbound.web.core.WebOperationName; -import dev.caskeleton.adapter.inbound.web.core.WebRequestContext; -import dev.caskeleton.adapter.inbound.web.core.WebRequestId; -import dev.caskeleton.adapter.inbound.web.core.WebTraceId; -import dev.caskeleton.adapter.inbound.web.evidence.WebExecutionEvidenceTracker; -import java.time.Instant; -import java.util.Locale; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import reactor.core.publisher.Mono; -import reactor.test.StepVerifier; -import reactor.util.context.Context; - -/** A lost context fails the request instead of quietly becoming an anonymous actor. */ -class WebFluxRequestContextAccessorTest { - - private static final Instant NOW = Instant.parse("2026-08-13T00:00:00Z"); - - @Test - @DisplayName("the context is read back from the Reactor Context across a thread hop") - void theContextIsReadBackAcrossAThreadHop() { - WebRequestContext expected = context(); - - StepVerifier.create( - WebFluxRequestContextAccessor.require() - .publishOn(reactor.core.scheduler.Schedulers.boundedElastic()) - .contextWrite( - ctx -> - WebFluxRequestContextAccessor.write( - ctx, expected, WebExecutionEvidenceTracker.received()))) - .expectNext(expected) - .verifyComplete(); - } - - @Test - @DisplayName("a missing context errors rather than completing empty") - void aMissingContextErrorsRatherThanCompletingEmpty() { - StepVerifier.create(WebFluxRequestContextAccessor.require()) - .expectErrorSatisfies( - failure -> - assertThat(failure) - .as("an empty Mono lets a downstream switchIfEmpty supply a default actor") - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("silent authorization change")) - .verify(); - } - - @Test - @DisplayName("the evidence tracker travels with the context") - void theEvidenceTrackerTravelsWithTheContext() { - WebExecutionEvidenceTracker tracker = WebExecutionEvidenceTracker.received(); - - StepVerifier.create( - WebFluxRequestContextAccessor.requireTracker() - .contextWrite(ctx -> WebFluxRequestContextAccessor.write(ctx, context(), tracker))) - .expectNext(tracker) - .verifyComplete(); - } - - @Test - @DisplayName("a context view without the key reports absence rather than throwing") - void aContextViewWithoutTheKeyReportsAbsence() { - assertThat(WebFluxRequestContextAccessor.find(Context.empty())).isEmpty(); - assertThat( - WebFluxRequestContextAccessor.find( - WebFluxRequestContextAccessor.write( - Context.empty(), context(), WebExecutionEvidenceTracker.received()))) - .isPresent(); - StepVerifier.create(Mono.just(1)).expectNext(1).verifyComplete(); - } - - private static WebRequestContext context() { - return new WebRequestContext( - new WebRequestId("req-1"), - new WebTraceId("0af7651916cd43dd8448eb211c80319c"), - new WebOperationName("orders.list"), - new ApiMajorVersion(1), - ActorContext.anonymous(), - TenantContext.none(), - Locale.ENGLISH, - NOW, - NOW.plusSeconds(5), - new ExternalRequestContext("https", "api.example.com", 443, "")); - } -} diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/webflux/guard/BlockingDependencyGuardTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/webflux/guard/BlockingDependencyGuardTest.java deleted file mode 100644 index 6dd0ac4a..00000000 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/webflux/guard/BlockingDependencyGuardTest.java +++ /dev/null @@ -1,92 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.webflux.guard; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.util.concurrent.atomic.AtomicReference; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * The guard has to fail on the event loop and stay out of the way everywhere else. - * - *

Both halves matter. A guard that never fires is the silent capacity bug it was written to - * prevent; a guard that fires on a worker thread makes the controlled bridge impossible and gets - * switched off. - */ -class BlockingDependencyGuardTest { - - @Test - @DisplayName("a blocking call on a reactor http thread is refused") - void aBlockingCallOnAReactorHttpThreadIsRefused() throws Exception { - BlockingDependencyGuard guard = BlockingDependencyGuard.reactorNetty(); - AtomicReference caught = new AtomicReference<>(); - - Thread eventLoop = - new Thread( - () -> { - try { - guard.check("jpa"); - } catch (Throwable failure) { - caught.set(failure); - } - }, - "reactor-http-nio-1"); - eventLoop.start(); - eventLoop.join(5_000); - - assertThat(caught.get()) - .as( - "a blocking call here succeeds slowly while holding a thread that serves every connection") - .isInstanceOf(BlockingCallDetectedException.class); - assertThat(caught.get().getMessage()).contains("jpa").contains("reactor-http-nio-1"); - } - - @Test - @DisplayName("the same call on a worker thread is allowed") - void theSameCallOnAWorkerThreadIsAllowed() throws Exception { - BlockingDependencyGuard guard = BlockingDependencyGuard.reactorNetty(); - AtomicReference caught = new AtomicReference<>(); - - Thread worker = - new Thread( - () -> { - try { - guard.check("jpa"); - } catch (Throwable failure) { - caught.set(failure); - } - }, - "boundedElastic-1"); - worker.start(); - worker.join(5_000); - - assertThat(caught.get()) - .as( - "firing on a worker would make the controlled bridge impossible and get the guard switched off") - .isNull(); - } - - @Test - @DisplayName("the notion of an event loop is a predicate, not a hard-coded name") - void theNotionOfAnEventLoopIsAPredicate() { - BlockingDependencyGuard custom = - new BlockingDependencyGuard(name -> name.startsWith("custom-loop-")); - - assertThat(custom.onEventLoop()).isFalse(); - assertThatCode(() -> custom.check("mongo")).doesNotThrowAnyException(); - assertThatThrownBy(() -> new BlockingDependencyGuard(null)) - .isInstanceOf(NullPointerException.class); - } - - @Test - @DisplayName("both reactor loop families are covered") - void bothReactorLoopFamiliesAreCovered() { - assertThat(BlockingDependencyGuard.REACTOR_NETTY_EVENT_LOOP.test("reactor-http-nio-3")) - .isTrue(); - assertThat(BlockingDependencyGuard.REACTOR_NETTY_EVENT_LOOP.test("reactor-tcp-nio-1")).isTrue(); - assertThat(BlockingDependencyGuard.REACTOR_NETTY_EVENT_LOOP.test("main")).isFalse(); - assertThat(BlockingDependencyGuard.REACTOR_NETTY_EVENT_LOOP.test(null)).isFalse(); - } -} diff --git a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/HttpFixtureTimeouts.java b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/HttpFixtureTimeouts.java index 3a73b6a1..118b3327 100644 --- a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/HttpFixtureTimeouts.java +++ b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/HttpFixtureTimeouts.java @@ -4,17 +4,16 @@ package dev.caskeleton.adapter.inbound.web.testkit; * Socket budgets for the fixtures that drive a real server over a real socket. * *

One place, because the number is not a per-fixture judgement. None of these suites asserts - * latency — they assert the status, headers, problem code and body that came back — so the only - * requirement on a timeout is that it exceed the worst scheduling delay a healthy server can suffer - * on a loaded machine. Below that threshold the timeout stops being a safety net and becomes a - * second, invisible assertion about how busy the build host is. + * latency — they assert the status, headers and body that came back — so the only requirement on a + * timeout is that it exceed the worst scheduling delay a healthy server can suffer on a loaded + * machine. Below that threshold the timeout stops being a safety net and becomes a second, + * invisible assertion about how busy the build host is. * *

That is not hypothetical here. With {@code org.gradle.parallel=true} these lanes run while - * SpotBugs analyses a dozen leaves, and at five-second connects and ten-second reads {@code - * ReactiveContractRecordingIT} and {@code ReactiveWebThrottleIT} failed a full {@code ci} run with - * {@code SocketTimeoutException} and passed when run alone. A lane that starts real servers and - * fails under load is the kind of gate people learn to re-run, and a gate people re-run is not a - * gate. + * SpotBugs analyses a dozen leaves, and at five-second connects and ten-second reads two + * real-server lanes failed a full {@code ci} run with {@code SocketTimeoutException} and passed + * when run alone. A lane that starts real servers and fails under load is the kind of gate people + * learn to re-run, and a gate people re-run is not a gate. * *

A suite whose subject *is* a timeout — the fault lanes' client read budget, the performance * lanes' load measurements — does not use these. There the number is the contract, and it belongs diff --git a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/budget/BudgetFixtureController.java b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/budget/BudgetFixtureController.java deleted file mode 100644 index bc8392f0..00000000 --- a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/budget/BudgetFixtureController.java +++ /dev/null @@ -1,57 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.testkit.budget; - -import jakarta.servlet.http.HttpServletRequest; -import java.io.IOException; -import java.io.InputStream; -import java.util.concurrent.atomic.AtomicLong; -import org.springframework.boot.test.context.TestComponent; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -/** - * Routes that read a request body and produce a response of a requested size. - * - *

The echo route reads the stream itself rather than binding a {@code @RequestBody}, because the - * property under test is that the *stream* is bounded. A bound that only worked for a body Spring - * had already materialised would pass a binding-based fixture and fail in production for anything - * that streams. - */ -// @TestComponent for the same reason as the fixture applications: a plain @RestController in this -// package is scanned into the real application, publishing fixture routes in a deployment. -@RestController -@TestComponent -public class BudgetFixtureController { - - private final AtomicLong bytesRead = new AtomicLong(); - - /** Reads the body and reports how many bytes reached the handler. */ - @PostMapping(path = BudgetFixtureProtocol.ECHO_PATH, produces = MediaType.TEXT_PLAIN_VALUE) - public ResponseEntity echo(HttpServletRequest request) throws IOException { - long read = 0; - byte[] chunk = new byte[256]; - try (InputStream body = request.getInputStream()) { - int count; - while ((count = body.read(chunk)) != -1) { - read += count; - } - } - bytesRead.set(read); - return ResponseEntity.ok(Long.toString(read)); - } - - /** Produces a response of the requested size. */ - @GetMapping(path = BudgetFixtureProtocol.PRODUCE_PATH, produces = MediaType.TEXT_PLAIN_VALUE) - public ResponseEntity produce(@RequestParam int bytes) { - return ResponseEntity.ok("x".repeat(bytes)); - } - - /** How many bytes the last echo actually read. */ - @GetMapping(path = BudgetFixtureProtocol.BYTES_READ_PATH, produces = MediaType.TEXT_PLAIN_VALUE) - public String bytesRead() { - return Long.toString(bytesRead.get()); - } -} diff --git a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/budget/BudgetFixtureProtocol.java b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/budget/BudgetFixtureProtocol.java deleted file mode 100644 index f21f41ae..00000000 --- a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/budget/BudgetFixtureProtocol.java +++ /dev/null @@ -1,52 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.testkit.budget; - -import dev.caskeleton.adapter.inbound.web.budget.WebRequestBudget; -import java.time.Duration; - -/** - * The budget the fixture lanes enforce, and the routes they enforce it on. - * - *

Deliberately small. The platform's real bounds are megabytes, and a lane that had to push a - * megabyte over a loopback socket for every case would spend its time on the transfer rather than - * on the assertion. The behaviour under test is what happens at the boundary, not where the - * boundary is. - */ -public final class BudgetFixtureProtocol { - - private BudgetFixtureProtocol() {} - - /** The body bound the lanes test against. */ - public static final int MAX_BODY_BYTES = 1024; - - /** The response bound the lanes test against. */ - public static final int MAX_RESPONSE_BYTES = 2048; - - /** The URI bound the lanes test against. */ - public static final int MAX_URI_BYTES = 512; - - /** The query parameter bound the lanes test against. */ - public static final int MAX_QUERY_PARAMETERS = 8; - - /** Where a body is posted. */ - public static final String ECHO_PATH = "/api/v1/fixtures/budget/echo"; - - /** Where a response of a requested size is produced. */ - public static final String PRODUCE_PATH = "/api/v1/fixtures/budget/produce"; - - /** How many bytes of the last request body the handler actually read. */ - public static final String BYTES_READ_PATH = "/api/v1/fixtures/budget/bytes-read"; - - /** The budget the fixture applications install. */ - public static WebRequestBudget budget() { - return new WebRequestBudget( - MAX_URI_BYTES, - 8 * 1024, - MAX_QUERY_PARAMETERS, - MAX_BODY_BYTES, - 16, - 1000, - 8, - Duration.ofSeconds(10), - MAX_RESPONSE_BYTES); - } -} diff --git a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/budget/HttpBudgetFixture.java b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/budget/HttpBudgetFixture.java deleted file mode 100644 index 1db4fe0f..00000000 --- a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/budget/HttpBudgetFixture.java +++ /dev/null @@ -1,152 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.testkit.budget; - -import dev.caskeleton.adapter.inbound.web.testkit.HttpFixtureTimeouts; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.HttpURLConnection; -import java.net.URI; -import java.nio.charset.StandardCharsets; - -/** - * Drives the budget routes over a real socket. - * - *

Chunked transfer is available and used on purpose. A body sent with a declared {@code - * Content-Length} can be refused from the header alone, which proves the cheap check and nothing - * about the streaming one. Chunked sends the same bytes with nothing to declare, so only a meter - * that counts them can refuse it. - */ -public final class HttpBudgetFixture { - - /** - * One response, as the client saw it. - * - * @param status the HTTP status - * @param body the response body, possibly truncated - * @param contentType the response media type - * @param truncated whether the connection died before the body finished - */ - public record Response(int status, String body, String contentType, boolean truncated) { - - /** The problem code the body names, or null. */ - public String problemCode() { - int at = body.indexOf("\"code\":\""); - if (at < 0) { - return null; - } - int from = at + 8; - return body.substring(from, body.indexOf('"', from)); - } - } - - private final String baseUrl; - - /** - * A fixture against a running container. - * - * @param port the container's port - */ - public HttpBudgetFixture(int port) { - this.baseUrl = "http://localhost:" + port; - } - - /** Posts a body of the given size with a declared length. */ - public Response postBodyOfSize(int size) { - return post(BudgetFixtureProtocol.ECHO_PATH, size, false); - } - - /** Posts a body of the given size with no declared length. */ - public Response postChunkedBodyOfSize(int size) { - return post(BudgetFixtureProtocol.ECHO_PATH, size, true); - } - - /** Asks for a response of the given size. */ - public Response produceResponseOfSize(int size) { - return get(BudgetFixtureProtocol.PRODUCE_PATH + "?bytes=" + size); - } - - /** How many bytes of the last body reached the handler. */ - public long bytesReadByHandler() { - return Long.parseLong(get(BudgetFixtureProtocol.BYTES_READ_PATH).body().trim()); - } - - /** Requests a path with the given number of query parameters. */ - public Response getWithQueryParameters(int count) { - StringBuilder path = new StringBuilder(BudgetFixtureProtocol.PRODUCE_PATH + "?bytes=1"); - for (int index = 0; index < count; index++) { - path.append("&p").append(index).append("=1"); - } - return get(path.toString()); - } - - /** Requests a path of roughly the given length. */ - public Response getWithUriOfSize(int size) { - return get(BudgetFixtureProtocol.PRODUCE_PATH + "?bytes=1&pad=" + "y".repeat(size)); - } - - private Response get(String path) { - try { - HttpURLConnection connection = open(path, "GET"); - return read(connection); - } catch (IOException e) { - throw new IllegalStateException("GET " + path + " failed", e); - } - } - - private Response post(String path, int size, boolean chunked) { - try { - HttpURLConnection connection = open(path, "POST"); - connection.setDoOutput(true); - connection.setRequestProperty("Content-Type", "application/octet-stream"); - if (chunked) { - connection.setChunkedStreamingMode(256); - } else { - connection.setFixedLengthStreamingMode(size); - } - try (OutputStream out = connection.getOutputStream()) { - byte[] chunk = new byte[256]; - int remaining = size; - while (remaining > 0) { - int length = Math.min(remaining, chunk.length); - out.write(chunk, 0, length); - remaining -= length; - } - } catch (IOException refusedMidWrite) { - // The server rejected the body before the client finished sending it. That is the desired - // behaviour, not a failure: the response still carries the status and the problem. - } - return read(connection); - } catch (IOException e) { - throw new IllegalStateException("POST " + path + " failed", e); - } - } - - private HttpURLConnection open(String path, String method) throws IOException { - HttpURLConnection connection = - (HttpURLConnection) URI.create(baseUrl + path).toURL().openConnection(); - connection.setRequestMethod(method); - connection.setConnectTimeout(HttpFixtureTimeouts.CONNECT_MILLIS); - connection.setReadTimeout(HttpFixtureTimeouts.READ_MILLIS); - return connection; - } - - private static Response read(HttpURLConnection connection) throws IOException { - try { - int status = connection.getResponseCode(); - boolean truncated = false; - String body; - try (InputStream stream = - status >= 400 ? connection.getErrorStream() : connection.getInputStream()) { - body = stream == null ? "" : new String(stream.readAllBytes(), StandardCharsets.UTF_8); - } catch (IOException cutOff) { - // The response budget was crossed after commit, so the container dropped the connection - // mid-document. A truncated read is the signal, and it is the intended one. - body = ""; - truncated = true; - } - return new Response(status, body, connection.getContentType(), truncated); - } finally { - connection.disconnect(); - } - } -} diff --git a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/budget/ReactiveBudgetFixtureController.java b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/budget/ReactiveBudgetFixtureController.java deleted file mode 100644 index 386c505d..00000000 --- a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/budget/ReactiveBudgetFixtureController.java +++ /dev/null @@ -1,56 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.testkit.budget; - -import java.util.concurrent.atomic.AtomicLong; -import org.springframework.boot.test.context.TestComponent; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.server.ServerWebExchange; -import reactor.core.publisher.Mono; - -/** - * The same routes on the reactive stack, consuming the body as a stream of buffers. - * - *

Reducing over {@code getBody()} rather than binding a value, for the same reason as the - * servlet fixture: the bound must hold for a body that is never fully in memory. - */ -// @TestComponent for the same reason as the fixture applications: a plain @RestController in this -// package is scanned into the real application, publishing fixture routes in a deployment. -@RestController -@TestComponent -public class ReactiveBudgetFixtureController { - - private final AtomicLong bytesRead = new AtomicLong(); - - /** Reads the body and reports how many bytes reached the handler. */ - @PostMapping(path = BudgetFixtureProtocol.ECHO_PATH, produces = MediaType.TEXT_PLAIN_VALUE) - public Mono> echo(ServerWebExchange exchange) { - return exchange - .getRequest() - .getBody() - .reduce( - 0L, - (total, buffer) -> { - long size = buffer.readableByteCount(); - org.springframework.core.io.buffer.DataBufferUtils.release(buffer); - return total + size; - }) - .doOnNext(bytesRead::set) - .map(read -> ResponseEntity.ok(Long.toString(read))); - } - - /** Produces a response of the requested size. */ - @GetMapping(path = BudgetFixtureProtocol.PRODUCE_PATH, produces = MediaType.TEXT_PLAIN_VALUE) - public Mono> produce(@RequestParam int bytes) { - return Mono.just(ResponseEntity.ok("x".repeat(bytes))); - } - - /** How many bytes the last echo actually read. */ - @GetMapping(path = BudgetFixtureProtocol.BYTES_READ_PATH, produces = MediaType.TEXT_PLAIN_VALUE) - public Mono bytesRead() { - return Mono.fromSupplier(() -> Long.toString(bytesRead.get())); - } -} diff --git a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/budget/WebBudgetContract.java b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/budget/WebBudgetContract.java deleted file mode 100644 index 2077429a..00000000 --- a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/budget/WebBudgetContract.java +++ /dev/null @@ -1,135 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.testkit.budget; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.adapter.inbound.web.error.WebProblem; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * What every transport must do at a budget boundary. - * - *

The cases split along the line that matters: a bound crossed before anything was sent is a - * problem document the caller can act on, and a bound crossed after the response was committed can - * only be a broken connection. Getting the second one wrong is the dangerous half — a response - * silently cut short still looks like valid JSON if it happens to end at a brace. - */ -public abstract class WebBudgetContract { - - /** The lane's fixture. */ - protected abstract HttpBudgetFixture fixture(); - - @Test - @DisplayName("a body within the budget is served normally") - void bodyWithinBudgetIsAccepted() { - HttpBudgetFixture.Response response = - fixture().postBodyOfSize(BudgetFixtureProtocol.MAX_BODY_BYTES); - - assertThat(response.status()).isEqualTo(200); - } - - @Test - @DisplayName("a body one byte over the budget is refused with 413") - void bodyAboveLimitIsRejectedWith413() { - HttpBudgetFixture.Response response = - fixture().postBodyOfSize(BudgetFixtureProtocol.MAX_BODY_BYTES + 1); - - assertThat(response.status()).isEqualTo(413); - assertThat(response.problemCode()).isEqualTo("REQUEST_TOO_LARGE"); - assertThat(response.contentType()).contains(WebProblem.MEDIA_TYPE); - } - - @Test - @DisplayName("a chunked body over the budget is refused too") - void chunkedBodyAboveLimitIsRejected() { - // Nothing declared, so nothing to check up front. Only a meter counting the bytes as they - // arrive can refuse this, which is the point of counting rather than measuring. - HttpBudgetFixture.Response response = - fixture().postChunkedBodyOfSize(BudgetFixtureProtocol.MAX_BODY_BYTES * 4); - - assertThat(response.status()).isEqualTo(413); - assertThat(response.problemCode()).isEqualTo("REQUEST_TOO_LARGE"); - } - - @Test - @DisplayName("an oversized body never reaches the handler in full") - void oversizedBodyIsNotMaterialised() { - // The requirement the design states outright: a check that reads the body to measure it is - // the heap exhaustion it was added to prevent. The handler must never see more than the bound. - fixture().postChunkedBodyOfSize(BudgetFixtureProtocol.MAX_BODY_BYTES * 8); - - assertThat(fixture().bytesReadByHandler()) - .isLessThanOrEqualTo(BudgetFixtureProtocol.MAX_BODY_BYTES); - } - - @Test - @DisplayName("a response within the budget is served normally") - void responseWithinBudgetIsServed() { - HttpBudgetFixture.Response response = - fixture().produceResponseOfSize(BudgetFixtureProtocol.MAX_RESPONSE_BYTES / 2); - - assertThat(response.status()).isEqualTo(200); - assertThat(response.body()).hasSize(BudgetFixtureProtocol.MAX_RESPONSE_BYTES / 2); - } - - @Test - @DisplayName("an oversized response never reaches the client whole") - void oversizedResponseIsNotDeliveredWhole() { - // Either answer is correct and both are honest: refused with a problem while the response was - // still open, or cut off once it was not. What must never happen is a 200 carrying a body the - // client accepts as complete. - HttpBudgetFixture.Response response = - fixture().produceResponseOfSize(BudgetFixtureProtocol.MAX_RESPONSE_BYTES * 2); - - boolean refusedCleanly = response.status() >= 500 && response.problemCode() != null; - boolean cutOff = response.truncated() || response.body().isEmpty(); - assertThat(refusedCleanly || cutOff) - .as( - "an over-budget response must be refused or cut off, was status %d with %d bytes", - response.status(), response.body().length()) - .isTrue(); - // Not a disjunction that any short body satisfies: whatever did arrive must be inside the - // bound. Without this the case would pass for a platform that merely trimmed a few bytes. - assertThat(response.body().length()) - .isLessThanOrEqualTo(BudgetFixtureProtocol.MAX_RESPONSE_BYTES); - } - - @Test - @DisplayName("too many query parameters is a validation failure, not a size failure") - void tooManyQueryParametersIsAValidationFailure() { - // Not REQUEST_TOO_LARGE: the request is a fine size and its shape is what the profile refuses. - // Told "too large", a client would compress it and try again. - // - // 422 rather than 400 because that is what the platform's own split says and what - // ProblemCatalog pins VALIDATION_FAILED to — 400 is for a document that did not parse, and - // this one parsed perfectly. The status is read from the catalog rather than asserted as a - // literal anywhere in the production path, so there is one table and nothing to drift. - HttpBudgetFixture.Response response = - fixture().getWithQueryParameters(BudgetFixtureProtocol.MAX_QUERY_PARAMETERS + 4); - - assertThat(response.status()).isEqualTo(422); - assertThat(response.problemCode()).isEqualTo("VALIDATION_FAILED"); - } - - @Test - @DisplayName("a URI over the budget is refused") - void oversizedUriIsRejected() { - HttpBudgetFixture.Response response = - fixture().getWithUriOfSize(BudgetFixtureProtocol.MAX_URI_BYTES * 2); - - assertThat(response.status()).isEqualTo(413); - assertThat(response.problemCode()).isEqualTo("REQUEST_TOO_LARGE"); - } - - @Test - @DisplayName("a refusal says the limit and does not echo what was sent") - void refusalStatesTheLimitWithoutEchoingTheRequest() { - HttpBudgetFixture.Response response = - fixture().postBodyOfSize(BudgetFixtureProtocol.MAX_BODY_BYTES + 1); - - // The limit is public API — a client needs it to comply. The observed size is not, and a - // message that echoes the request is how a size error becomes a reflection gadget. - assertThat(response.body()).contains(Integer.toString(BudgetFixtureProtocol.MAX_BODY_BYTES)); - assertThat(response.body()).doesNotContain("observed"); - } -} diff --git a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/contract/WebContractFixture.java b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/contract/WebContractFixture.java deleted file mode 100644 index 32f06835..00000000 --- a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/contract/WebContractFixture.java +++ /dev/null @@ -1,150 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.testkit.contract; - -import dev.caskeleton.adapter.inbound.web.testkit.HttpFixtureTimeouts; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.HttpURLConnection; -import java.net.URI; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.TreeSet; - -/** - * Runs the probe list against one container and records the normalized outcomes. - * - *

Recording to a file rather than comparing in memory, because the two stacks cannot be in one - * JVM: Spring Boot deduces a single application type from the classpath, so Tomcat and Reactor - * Netty are mutually exclusive within a source set. Each lane records what it saw; a test in the - * default source set reads the recordings and compares them. - * - *

That indirection is also what makes the comparison honest. An in-memory parity check would - * have to build both stacks from the same test, which is exactly the situation where a shared - * helper makes them agree by construction rather than by both being correct. - */ -public final class WebContractFixture { - - /** Where recordings are written, relative to the leaf's build directory. */ - public static final String RECORDING_DIRECTORY = "web-contract-parity"; - - /** The headers a client branches on, and therefore the ones parity covers. */ - private static final List CONTRACT_HEADERS = - List.of("Location", "Content-Location", "ETag", "Retry-After", "Allow"); - - private final String baseUrl; - - /** - * A fixture against a running container. - * - * @param port the container's port - */ - public WebContractFixture(int port) { - this.baseUrl = "http://localhost:" + port; - } - - /** - * Runs every probe and records what came back. - * - * @param lane the lane's name, used as the recording's file name - */ - public Map runAndRecord(String lane) { - Map outcomes = new LinkedHashMap<>(); - for (WireProbe probe : WebPlatformContractSuite.probes()) { - outcomes.put(probe.name(), send(probe)); - } - write(lane, outcomes); - return outcomes; - } - - private void write(String lane, Map outcomes) { - StringBuilder recorded = new StringBuilder(); - outcomes.forEach( - (name, outcome) -> - recorded.append(name).append('=').append(outcome.recorded()).append('\n')); - try { - Path directory = recordingDirectory(); - Files.createDirectories(directory); - Files.writeString(directory.resolve(lane + ".properties"), recorded.toString()); - } catch (IOException e) { - throw new IllegalStateException( - "the parity recording for " + lane + " could not be written", e); - } - } - - /** Where recordings live. */ - public static Path recordingDirectory() { - // Resolved from the build directory rather than a temp path, so a recording survives to be - // read by the comparison test in another source set and another Gradle task. - return Path.of(System.getProperty("web.parity.dir", "build/" + RECORDING_DIRECTORY)); - } - - private WireOutcome send(WireProbe probe) { - try { - HttpURLConnection connection = - (HttpURLConnection) URI.create(baseUrl + probe.path()).toURL().openConnection(); - connection.setRequestMethod(probe.method()); - connection.setConnectTimeout(HttpFixtureTimeouts.CONNECT_MILLIS); - connection.setReadTimeout(HttpFixtureTimeouts.READ_MILLIS); - probe.headers().forEach(connection::setRequestProperty); - if (probe.body() != null) { - connection.setDoOutput(true); - try (OutputStream out = connection.getOutputStream()) { - out.write(probe.body().getBytes(StandardCharsets.UTF_8)); - } - } else if ("POST".equals(probe.method())) { - connection.setDoOutput(true); - connection.getOutputStream().close(); - } - try { - int status = connection.getResponseCode(); - String body; - try (InputStream stream = - status >= 400 ? connection.getErrorStream() : connection.getInputStream()) { - body = stream == null ? "" : new String(stream.readAllBytes(), StandardCharsets.UTF_8); - } - return new WireOutcome( - status, mediaTypeOf(connection), problemCodeOf(body), contractHeadersOf(connection)); - } finally { - connection.disconnect(); - } - } catch (IOException e) { - throw new IllegalStateException("probe " + probe.name() + " failed", e); - } - } - - private static String mediaTypeOf(HttpURLConnection connection) { - String contentType = connection.getContentType(); - if (contentType == null) { - return ""; - } - // Parameters stripped: one container writes "charset=UTF-8" and the other "charset=utf-8", - // and neither is a contract difference. - int semicolon = contentType.indexOf(';'); - return (semicolon < 0 ? contentType : contentType.substring(0, semicolon)).trim(); - } - - private static String problemCodeOf(String body) { - int at = body.indexOf("\"code\":\""); - if (at < 0) { - return ""; - } - int from = at + 8; - return body.substring(from, body.indexOf('"', from)); - } - - private static String contractHeadersOf(HttpURLConnection connection) { - // Names only, sorted. The values carry ids and timestamps that differ per run, and a parity - // check that compared them would be comparing entropy. - TreeSet present = new TreeSet<>(); - for (String name : CONTRACT_HEADERS) { - if (connection.getHeaderField(name) != null) { - present.add(name); - } - } - return String.join(",", present); - } -} diff --git a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/contract/WebPlatformContractRecording.java b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/contract/WebPlatformContractRecording.java deleted file mode 100644 index 4e883946..00000000 --- a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/contract/WebPlatformContractRecording.java +++ /dev/null @@ -1,71 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.testkit.contract; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.Map; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * Runs the probe list on one lane and records what the wire looked like. - * - *

Extended by each transport. The assertions here are the ones that can be made without seeing - * the other stack — that the platform answered at all, and that its problem documents are problem - * documents. The comparison between stacks is a separate test that reads the recordings, because - * the two stacks cannot be started in one JVM. - */ -public abstract class WebPlatformContractRecording { - - /** The lane's fixture. */ - protected abstract WebContractFixture fixture(); - - /** The lane's name in the recording. */ - protected abstract String laneName(); - - @Test - @DisplayName("every probe is answered and recorded") - void everyProbeIsAnsweredAndRecorded() { - Map outcomes = fixture().runAndRecord(laneName()); - - assertThat(outcomes).hasSameSizeAs(WebPlatformContractSuite.probes()); - // Nothing may reach the container's own error page. A 500 here means the platform did not - // answer, and a parity comparison of two identical 500s would report agreement. - assertThat(outcomes.values()).noneMatch(outcome -> outcome.status() >= 500); - } - - @Test - @DisplayName("every failure is a problem document with a code") - void everyFailureIsAProblemDocument() { - Map outcomes = fixture().runAndRecord(laneName()); - - outcomes.forEach( - (name, outcome) -> { - if (outcome.status() >= 400) { - assertThat(outcome.contentType()) - .as("%s answered %d without a problem document", name, outcome.status()) - .isEqualTo("application/problem+json"); - assertThat(outcome.problemCode()) - .as("%s answered %d with no code to branch on", name, outcome.status()) - .isNotEmpty(); - } - }); - } - - @Test - @DisplayName("a created resource is locatable") - void createdResourceIsLocatable() { - Map outcomes = fixture().runAndRecord(laneName()); - - assertThat(outcomes.get("create-201").status()).isEqualTo(201); - assertThat(outcomes.get("create-201").contractHeaders()).contains("Location"); - } - - @Test - @DisplayName("an accepted operation is locatable") - void acceptedOperationIsLocatable() { - Map outcomes = fixture().runAndRecord(laneName()); - - assertThat(outcomes.get("operation-accepted-202").status()).isEqualTo(202); - assertThat(outcomes.get("operation-accepted-202").contractHeaders()).contains("Location"); - } -} diff --git a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/contract/WebPlatformContractSuite.java b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/contract/WebPlatformContractSuite.java deleted file mode 100644 index 44670f56..00000000 --- a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/contract/WebPlatformContractSuite.java +++ /dev/null @@ -1,55 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.testkit.contract; - -import dev.caskeleton.adapter.inbound.web.testkit.operation.OperationFixtureSupport; -import java.util.List; -import java.util.Map; - -/** - * The probes whose answers must be identical on every transport. - * - *

One list, used by every lane. Two lanes that each described the contract in their own test - * class would be two descriptions, and the first divergence between them would read as a passing - * suite on both sides. - * - *

The probes span the dimensions the design names — status, headers, problem documents, - * conditional requests, idempotency, operations, cache and budgets — choosing for each the case - * where the two stacks are most likely to differ rather than the case that is easiest to write. - */ -public final class WebPlatformContractSuite { - - private WebPlatformContractSuite() {} - - /** The probes, in a fixed order so recordings from two lanes line up. */ - public static List probes() { - return List.of( - // A plain success: the baseline both stacks must agree on before anything else means - // anything. - WireProbe.postJson("create-201", "/api/v1/fixtures", "{\"name\":\"parity\"}"), - // 422 with a problem document. The 400/422 split is a platform decision, and a stack that - // let the framework answer would produce 400 here. - WireProbe.postJson("validation-422", "/api/v1/fixtures", "{\"name\":\"\"}"), - // Malformed JSON. Both stacks parse with different readers, so this is where a shared - // mapper either holds or quietly does not. - WireProbe.postJson("malformed-400", "/api/v1/fixtures", "{"), - // 404 for an operation that does not exist — and, crucially, the same 404 a caller gets - // for one belonging to somebody else. - WireProbe.get("operation-absent-404", "/api/v1/operations/op-absent"), - // A 202 receipt with a Location. The header is the whole point of the response. - WireProbe.postJson("operation-accepted-202", "/api/v1/fixtures/reports", null), - // An unsupported media type: the framework answers this one, so it is where the two - // stacks are most likely to diverge without anyone having written a line of code. - new WireProbe( - "unsupported-media-415", - "POST", - "/api/v1/fixtures", - Map.of("Content-Type", "text/plain"), - "parity"), - // A method the route does not serve. - new WireProbe("method-not-allowed-405", "DELETE", "/api/v1/fixtures", Map.of(), null)); - } - - /** The principal every probe runs as, where the fixture needs one. */ - public static String principal() { - return OperationFixtureSupport.PRINCIPAL; - } -} diff --git a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/contract/WireOutcome.java b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/contract/WireOutcome.java deleted file mode 100644 index c922466c..00000000 --- a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/contract/WireOutcome.java +++ /dev/null @@ -1,44 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.testkit.contract; - -import java.util.Objects; - -/** - * What a probe observed, reduced to the parts both stacks must agree on. - * - *

Reduced deliberately. A byte-for-byte comparison of two responses would fail on things that - * are allowed to differ — the {@code Server} header, header ordering, a trace id, a timestamp — and - * a parity test that fails for allowed reasons gets an exclusion added to it every week until it - * excludes the thing it was checking. - * - *

What remains is the contract: the status, the media type, the failure code, and whether the - * headers a client branches on were present. Everything a client can depend on, and nothing a - * container is entitled to vary. - * - * @param status the HTTP status - * @param contentType the response media type, without parameters - * @param problemCode the failure code when the body is a problem document, else empty - * @param contractHeaders the contract-bearing headers that were present, sorted and comma-joined - */ -public record WireOutcome( - int status, String contentType, String problemCode, String contractHeaders) { - - public WireOutcome { - Objects.requireNonNull(contentType, "contentType"); - Objects.requireNonNull(problemCode, "problemCode"); - Objects.requireNonNull(contractHeaders, "contractHeaders"); - } - - /** The recorded form: one line, stable across runs. */ - public String recorded() { - return status + "|" + contentType + "|" + problemCode + "|" + contractHeaders; - } - - /** Parses a recorded line. */ - public static WireOutcome parse(String recorded) { - String[] parts = recorded.split("\\|", -1); - if (parts.length != 4) { - throw new IllegalArgumentException("not a recorded outcome: " + recorded); - } - return new WireOutcome(Integer.parseInt(parts[0]), parts[1], parts[2], parts[3]); - } -} diff --git a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/contract/WireProbe.java b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/contract/WireProbe.java deleted file mode 100644 index a80bd489..00000000 --- a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/contract/WireProbe.java +++ /dev/null @@ -1,39 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.testkit.contract; - -import java.util.Map; -import java.util.Objects; - -/** - * One request whose answer both stacks must give identically. - * - *

A value rather than a method per case, so the probe list is data that can be recorded, - * replayed and compared. Parity asserted by two hand-written test classes is parity that holds - * until somebody edits one of them. - * - * @param name what this probe is called in the recording - * @param method the HTTP method - * @param path the request path - * @param headers headers to send - * @param body the request body, or null - */ -public record WireProbe( - String name, String method, String path, Map headers, String body) { - - public WireProbe { - Objects.requireNonNull(name, "name"); - Objects.requireNonNull(method, "method"); - Objects.requireNonNull(path, "path"); - Objects.requireNonNull(headers, "headers"); - headers = Map.copyOf(headers); - } - - /** A GET with no headers. */ - public static WireProbe get(String name, String path) { - return new WireProbe(name, "GET", path, Map.of(), null); - } - - /** A POST with a JSON body. */ - public static WireProbe postJson(String name, String path, String body) { - return new WireProbe(name, "POST", path, Map.of("Content-Type", "application/json"), body); - } -} diff --git a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/fault/FaultFixtureController.java b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/fault/FaultFixtureController.java index 8aef0858..8e374439 100644 --- a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/fault/FaultFixtureController.java +++ b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/fault/FaultFixtureController.java @@ -85,10 +85,9 @@ public class FaultFixtureController { return Integer.toString(sideEffects.get()); } - /** Clears the store and the counter between scenarios. */ + /** Zeroes the counter between scenarios; each scenario brings a fresh idempotency key. */ @DeleteMapping(FaultFixtureProtocol.SIDE_EFFECTS_PATH) public ResponseEntity reset() { - idempotency.clear(); sideEffects.set(0); return ResponseEntity.noContent().build(); } diff --git a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/fault/FaultFixtureIdempotency.java b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/fault/FaultFixtureIdempotency.java index e32fa7b7..e48e549d 100644 --- a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/fault/FaultFixtureIdempotency.java +++ b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/fault/FaultFixtureIdempotency.java @@ -1,15 +1,16 @@ package dev.caskeleton.adapter.inbound.web.testkit.fault; -import dev.caskeleton.adapter.inbound.web.idempotency.JsonIdempotentResponseCodec; -import dev.caskeleton.adapter.inbound.web.json.WebObjectMapperFactory; -import dev.caskeleton.application.idempotency.IdempotencyContext; import dev.caskeleton.application.idempotency.IdempotencyExecutor; -import dev.caskeleton.application.idempotency.IdempotencyScope; +import dev.caskeleton.application.idempotency.IdempotencyScopeDigest; +import dev.caskeleton.application.idempotency.IdempotentAction; +import dev.caskeleton.application.idempotency.IdempotentResponseCodec; import dev.caskeleton.application.idempotency.RequestFingerprint; +import dev.caskeleton.application.idempotency.testkit.InMemoryIdempotencyStore; +import dev.caskeleton.application.transaction.OperationId; import java.nio.charset.StandardCharsets; -import java.time.Clock; import java.time.Duration; import java.util.Objects; +import java.util.UUID; import java.util.function.Supplier; import tools.jackson.databind.json.JsonMapper; @@ -22,31 +23,53 @@ import tools.jackson.databind.json.JsonMapper; */ final class FaultFixtureIdempotency { - private static final String PRINCIPAL = "fixture"; - private static final String USE_CASE = "fault.transfers.create"; + private static final String OPERATION_CODE = "FAULT_TRANSFERS_CREATE"; - private final FaultFixtureStore store = new FaultFixtureStore(); - private final JsonMapper mapper = WebObjectMapperFactory.standardJsonMapper(); + private final JsonMapper mapper = JsonMapper.builder().build(); + // Never cleared: every scenario uses a fresh key, so earlier records cannot answer a later one. private final IdempotencyExecutor executor = - new IdempotencyExecutor(store, Clock.systemUTC(), Duration.ofHours(1)); + new IdempotencyExecutor( + new InMemoryIdempotencyStore(), + Duration.ofMinutes(1), + Duration.ofHours(1), + Duration.ofHours(1), + "fault-fixture-json", + 1); R execute(String rawKey, Object command, Class responseType, Supplier action) { Objects.requireNonNull(rawKey, "rawKey"); Objects.requireNonNull(responseType, "responseType"); - String canonicalCommand = mapper.writeValueAsString(command); - IdempotencyContext context = - IdempotencyContext.of( - IdempotencyScope.of(PRINCIPAL, rawKey.trim(), USE_CASE), - RequestFingerprint.ofSha256(canonicalCommand.getBytes(StandardCharsets.UTF_8))); + // A plain SHA-256 of the key stands in for the keyed HMAC production derives: the fixture has + // one principal and no secret, and the executor only needs an opaque 64-hex scope. + IdempotencyScopeDigest scope = + new IdempotencyScopeDigest( + RequestFingerprint.ofSha256(rawKey.trim().getBytes(StandardCharsets.UTF_8)).hex(), + 1, + OPERATION_CODE); + RequestFingerprint fingerprint = + RequestFingerprint.ofSha256( + mapper.writeValueAsString(command).getBytes(StandardCharsets.UTF_8)); + IdempotentResponseCodec codec = + new IdempotentResponseCodec<>() { + @Override + public String serialize(R result) { + return mapper.writeValueAsString(result); + } + + @Override + public R deserialize(String payload) { + return mapper.readValue(payload, responseType); + } + }; return executor.execute( - context, action, new JsonIdempotentResponseCodec<>(mapper, responseType)); + scope, + fingerprint, + executor.newAttempt(new OperationId(UUID.randomUUID().toString())), + () -> new IdempotentAction.Outcome.Success<>(action.get()), + codec); } String json(Object value) { return mapper.writeValueAsString(value); } - - void clear() { - store.clear(); - } } diff --git a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/fault/FaultFixtureStore.java b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/fault/FaultFixtureStore.java deleted file mode 100644 index 6a9d8fbe..00000000 --- a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/fault/FaultFixtureStore.java +++ /dev/null @@ -1,67 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.testkit.fault; - -import dev.caskeleton.application.idempotency.IdempotencyRecord; -import dev.caskeleton.application.idempotency.IdempotencyScope; -import dev.caskeleton.application.idempotency.IdempotencyStatus; -import dev.caskeleton.application.idempotency.IdempotencyStorePort; -import dev.caskeleton.application.idempotency.RequestFingerprint; -import dev.caskeleton.application.idempotency.StoredResponse; -import java.time.Instant; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.ConcurrentHashMap; - -/** - * The record store behind the fault fixtures. - * - *

In memory, because the property under test is what the transport does when a connection dies - * between the commit and the response — not how a row is written. A real datastore would add - * startup cost and a second failure mode to every lane without making the assertion any stronger. - * - *

{@code tryBegin} is {@code putIfAbsent} rather than get-then-put: the retry in these scenarios - * arrives while the first request may still be on the wire, so a non-atomic claim would let both - * attempts run and the lane would report a passing contract for a platform that double-executes. - */ -public final class FaultFixtureStore implements IdempotencyStorePort { - - private final Map records = new ConcurrentHashMap<>(); - - @Override - public boolean tryBegin( - IdempotencyScope scope, RequestFingerprint fingerprint, Instant expiresAt) { - return records.putIfAbsent( - scope, - new IdempotencyRecord( - scope, fingerprint, IdempotencyStatus.IN_FLIGHT, null, Instant.EPOCH, expiresAt)) - == null; - } - - @Override - public Optional find(IdempotencyScope scope, Instant now) { - return Optional.ofNullable(records.get(scope)).filter(record -> !record.isExpiredAt(now)); - } - - @Override - public void complete(IdempotencyScope scope, StoredResponse response) { - records.computeIfPresent( - scope, - (key, record) -> - new IdempotencyRecord( - record.scope(), - record.fingerprint(), - IdempotencyStatus.COMPLETED, - response, - record.createdAt(), - record.expiresAt())); - } - - @Override - public void discard(IdempotencyScope scope) { - records.remove(scope); - } - - /** Empties the store between scenarios. */ - public void clear() { - records.clear(); - } -} diff --git a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/fault/ReactiveFaultFixtureController.java b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/fault/ReactiveFaultFixtureController.java deleted file mode 100644 index 3184a054..00000000 --- a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/fault/ReactiveFaultFixtureController.java +++ /dev/null @@ -1,100 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.testkit.fault; - -import dev.caskeleton.adapter.inbound.web.http.ApiHeaders; -import java.util.concurrent.atomic.AtomicInteger; -import org.springframework.boot.test.context.TestComponent; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.DeleteMapping; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestHeader; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.server.ServerWebExchange; -import reactor.core.publisher.Mono; -import reactor.core.scheduler.Schedulers; - -/** Reactive twin of {@link FaultFixtureController}. */ -@RestController -@TestComponent -public class ReactiveFaultFixtureController { - - /** The request the fixture accepts. */ - public record Transfer(String to, int amount) {} - - /** What a successful create returns. */ - public record Receipt(String id) {} - - private final FaultFixtureIdempotency idempotency = new FaultFixtureIdempotency(); - private final AtomicInteger sideEffects = new AtomicInteger(); - - /** The idempotent create, optionally armed to lose its response. */ - @PostMapping( - path = FaultFixtureProtocol.CREATE_PATH, - consumes = MediaType.APPLICATION_JSON_VALUE, - produces = MediaType.APPLICATION_JSON_VALUE) - public Mono> create( - ServerWebExchange exchange, - @RequestBody Transfer transfer, - @RequestHeader(name = ApiHeaders.IDEMPOTENCY_KEY) String idempotencyKey, - @RequestHeader(name = FaultFixtureProtocol.FAULT_POINT_HEADER, required = false) - String faultPoint) { - WebFaultPoint armed = faultPoint == null ? null : WebFaultPoint.valueOf(faultPoint); - - Mono> answer = - Mono.fromCallable( - () -> { - Receipt receipt = - idempotency.execute( - idempotencyKey, - transfer, - Receipt.class, - () -> { - sideEffects.incrementAndGet(); - return new Receipt("t-" + sideEffects.get()); - }); - return ResponseEntity.status(201) - .contentType(MediaType.APPLICATION_JSON) - .body(idempotency.json(receipt)); - }) - .subscribeOn(Schedulers.boundedElastic()); - - if (armed == WebFaultPoint.BEFORE_APPLICATION_START) { - return Mono.delay(FaultFixtureProtocol.ARMED_STALL).then(answer); - } - if (armed == WebFaultPoint.AFTER_APPLICATION_COMMIT_BEFORE_RESPONSE_HEADERS) { - return answer.delayElement(FaultFixtureProtocol.ARMED_STALL); - } - if (armed == WebFaultPoint.AFTER_RESPONSE_HEADERS_BEFORE_BODY) { - return answer.flatMap( - response -> { - exchange.getResponse().setRawStatusCode(response.getStatusCode().value()); - exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON); - return exchange - .getResponse() - .setComplete() - .then(Mono.delay(FaultFixtureProtocol.ARMED_STALL)) - .then(Mono.empty()); - }); - } - return answer; - } - - /** How many times the side effect ran. */ - @GetMapping(path = FaultFixtureProtocol.SIDE_EFFECTS_PATH, produces = MediaType.TEXT_PLAIN_VALUE) - public Mono sideEffects() { - return Mono.fromSupplier(() -> Integer.toString(sideEffects.get())); - } - - /** Clears the store and the counter between scenarios. */ - @DeleteMapping(FaultFixtureProtocol.SIDE_EFFECTS_PATH) - public Mono> reset() { - return Mono.fromSupplier( - () -> { - idempotency.clear(); - sideEffects.set(0); - return ResponseEntity.noContent().build(); - }); - } -} diff --git a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/operation/HttpOperationFixture.java b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/operation/HttpOperationFixture.java deleted file mode 100644 index 9445a2e8..00000000 --- a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/operation/HttpOperationFixture.java +++ /dev/null @@ -1,115 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.testkit.operation; - -import dev.caskeleton.adapter.inbound.web.testkit.HttpFixtureTimeouts; -import java.io.IOException; -import java.io.InputStream; -import java.net.HttpURLConnection; -import java.net.URI; -import java.nio.charset.StandardCharsets; - -/** - * Drives the operation routes over a real socket. - * - *

Over a socket because the assertions are about headers a client actually receives — {@code - * Location}, {@code Retry-After}, {@code Content-Location} — and a mock dispatcher can report those - * correct while the container drops or rewrites them. - */ -public final class HttpOperationFixture { - - /** - * One response, as the client saw it. - * - * @param status the HTTP status - * @param body the response body - * @param location the {@code Location} header, or null - * @param retryAfter the {@code Retry-After} header, or null - * @param contentLocation the {@code Content-Location} header, or null - */ - public record Response( - int status, String body, String location, String retryAfter, String contentLocation) { - - /** A named header, or null. */ - public String header(String name) { - return switch (name) { - case "Location" -> location; - case "Retry-After" -> retryAfter; - case "Content-Location" -> contentLocation; - default -> null; - }; - } - } - - private final String baseUrl; - - /** - * A fixture against a running container. - * - * @param port the container's port - */ - public HttpOperationFixture(int port) { - this.baseUrl = "http://localhost:" + port; - } - - /** Empties the fixture store. */ - public void reset() { - send("DELETE", "/api/v1/fixtures/operations"); - } - - /** Submits work and returns the receipt. */ - public Response submit() { - return send("POST", "/api/v1/fixtures/reports"); - } - - /** Reads one operation. */ - public Response get(String operationId) { - return send("GET", "/api/v1/operations/" + operationId); - } - - /** Cancels one operation. */ - public Response cancel(String operationId) { - return send("DELETE", "/api/v1/operations/" + operationId); - } - - /** Drives an operation into a state. */ - public void transition(String operationId, String state) { - send("POST", "/api/v1/fixtures/operations/" + operationId + "/state?to=" + state); - } - - /** The operation id a receipt's {@code Location} names. */ - public static String operationIdOf(Response receipt) { - String location = receipt.location(); - return location == null ? null : location.substring(location.lastIndexOf('/') + 1); - } - - private Response send(String method, String path) { - try { - HttpURLConnection connection = - (HttpURLConnection) URI.create(baseUrl + path).toURL().openConnection(); - connection.setRequestMethod(method); - connection.setConnectTimeout(HttpFixtureTimeouts.CONNECT_MILLIS); - connection.setReadTimeout(HttpFixtureTimeouts.READ_MILLIS); - if ("POST".equals(method)) { - connection.setDoOutput(true); - connection.getOutputStream().close(); - } - try { - int status = connection.getResponseCode(); - String body; - try (InputStream stream = - status >= 400 ? connection.getErrorStream() : connection.getInputStream()) { - body = stream == null ? "" : new String(stream.readAllBytes(), StandardCharsets.UTF_8); - } - return new Response( - status, - body, - connection.getHeaderField("Location"), - connection.getHeaderField("Retry-After"), - connection.getHeaderField("Content-Location")); - } finally { - connection.disconnect(); - } - } catch (IOException e) { - throw new IllegalStateException(method + " " + path + " failed", e); - } - } -} diff --git a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/operation/OperationFixtureController.java b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/operation/OperationFixtureController.java deleted file mode 100644 index 0b5fcb17..00000000 --- a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/operation/OperationFixtureController.java +++ /dev/null @@ -1,84 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.testkit.operation; - -import dev.caskeleton.adapter.inbound.web.mvc.operation.OperationHttpController; -import dev.caskeleton.adapter.inbound.web.operationasync.OperationResponse; -import java.util.concurrent.atomic.AtomicInteger; -import org.springframework.boot.test.context.TestComponent; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.DeleteMapping; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -/** - * The operation routes as a real socket serves them, on the servlet stack. - * - *

It delegates to the real {@link OperationHttpController} rather than reimplementing it, so - * what the lane certifies is the shipped controller. Only the request context is supplied by the - * fixture: the contract app carries no authentication, and the resolver would otherwise produce an - * anonymous caller that the access policy correctly refuses — which would make every case a 404 and - * prove nothing. - */ -// @TestComponent for the same reason as the fixture applications: a plain @RestController in this -// package is scanned into the real application, publishing fixture routes in a deployment. -@RestController -@TestComponent -public class OperationFixtureController { - - private final OperationFixtureSupport support = new OperationFixtureSupport(); - private final OperationHttpController delegate = - new OperationHttpController(support.queryService()); - private final AtomicInteger submissions = new AtomicInteger(); - - /** Accepts work and hands back a receipt. */ - @PostMapping(path = "/api/v1/fixtures/reports", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity submit() { - String operationId = "op-" + submissions.incrementAndGet(); - support.submit(operationId); - // 202 with a Location, never 200 with a body. The work has not happened, and a 200 would tell - // a client it had. - return ResponseEntity.accepted() - .location(OperationHttpController.locationOf(operationId)) - .build(); - } - - /** Reads one operation through the shipped controller. */ - @GetMapping( - path = OperationHttpController.BASE_PATH + "/{operationId}", - produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity get(@PathVariable String operationId) { - return delegate.get(operationId, OperationFixtureSupport.context()); - } - - /** Cancels one operation through the shipped controller. */ - @DeleteMapping(OperationHttpController.BASE_PATH + "/{operationId}") - public ResponseEntity cancel(@PathVariable String operationId) { - return delegate.cancel(operationId, OperationFixtureSupport.context()); - } - - /** Drives an operation into the state a scenario needs. */ - @PostMapping("/api/v1/fixtures/operations/{operationId}/state") - public ResponseEntity transition( - @PathVariable String operationId, @RequestParam String to) { - switch (to) { - case "RUNNING" -> support.start(operationId); - case "SUCCEEDED" -> support.succeed(operationId, "reports/" + operationId); - case "FAILED" -> - support.fail(operationId, "DEPENDENCY_TIMEOUT", "the report source timed out"); - case "OTHER_PRINCIPAL" -> support.submitForAnotherPrincipal(operationId); - default -> throw new IllegalArgumentException("unknown fixture state " + to); - } - return ResponseEntity.noContent().build(); - } - - /** Empties the store between scenarios. */ - @DeleteMapping("/api/v1/fixtures/operations") - public ResponseEntity reset() { - support.reset(); - submissions.set(0); - return ResponseEntity.noContent().build(); - } -} diff --git a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/operation/OperationFixtureSupport.java b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/operation/OperationFixtureSupport.java deleted file mode 100644 index 99b7a2c3..00000000 --- a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/operation/OperationFixtureSupport.java +++ /dev/null @@ -1,166 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.testkit.operation; - -import dev.caskeleton.adapter.inbound.web.core.ActorContext; -import dev.caskeleton.adapter.inbound.web.core.ApiMajorVersion; -import dev.caskeleton.adapter.inbound.web.core.ExternalRequestContext; -import dev.caskeleton.adapter.inbound.web.core.TenantContext; -import dev.caskeleton.adapter.inbound.web.core.WebOperationName; -import dev.caskeleton.adapter.inbound.web.core.WebRequestContext; -import dev.caskeleton.adapter.inbound.web.core.WebRequestId; -import dev.caskeleton.adapter.inbound.web.core.WebTraceId; -import dev.caskeleton.adapter.inbound.web.error.WebProblemFactory; -import dev.caskeleton.adapter.inbound.web.operationasync.OperationQueryService; -import dev.caskeleton.adapter.inbound.web.operationasync.OperationResourceFactory; -import dev.caskeleton.application.idempotency.RequestFingerprint; -import dev.caskeleton.application.operation.DurableOperationId; -import dev.caskeleton.application.operation.DurableOperationSubmission; -import dev.caskeleton.application.operation.OperationFailure; -import dev.caskeleton.application.operation.OperationProgressSnapshot; -import dev.caskeleton.application.transaction.TransactionPort; -import java.net.URI; -import java.time.Clock; -import java.time.Duration; -import java.time.Instant; -import java.util.Locale; -import java.util.Optional; -import java.util.Set; -import java.util.function.Supplier; - -/** - * The store, the query service and the state transitions both operation fixtures drive. - * - *

Shared so the servlet and reactive fixtures put their operations into identical states. If - * each drove its own transitions, a difference between the two lanes' answers could be a difference - * in their fixtures rather than in the platform, which is the one thing a cross-container contract - * must not be ambiguous about. - */ -public final class OperationFixtureSupport { - - /** The principal every fixture request runs as. */ - public static final String PRINCIPAL = "fixture"; - - /** The worker every fixture transition runs as. */ - public static final String WORKER = "fixture-worker"; - - private static final TransactionPort DIRECT_TRANSACTIONS = - new TransactionPort() { - @Override - public T inWrite(Supplier action) { - return action.get(); - } - - @Override - public T inRootWrite(Supplier action) { - return action.get(); - } - - @Override - public T inRead(Supplier action) { - return action.get(); - } - - @Override - public T inNew(Supplier action) { - return action.get(); - } - }; - - private final TestDurableOperationStore store = new TestDurableOperationStore(); - private final OperationQueryService queryService; - - /** A support over a fresh store. */ - public OperationFixtureSupport() { - this.queryService = - new OperationQueryService( - store, - DIRECT_TRANSACTIONS, - new OperationResourceFactory( - WebProblemFactory.standard(), URI.create("/api/v1/"), Duration.ofSeconds(2)), - Clock.systemUTC()); - } - - /** The service the controllers are built on. */ - public OperationQueryService queryService() { - return queryService; - } - - /** Empties the store between scenarios. */ - public void reset() { - store.clear(); - } - - /** Records a PENDING operation. */ - public String submit(String operationId) { - store.submit( - new DurableOperationSubmission( - new DurableOperationId(operationId), - "reports.generate", - PRINCIPAL, - null, - new RequestFingerprint(fingerprintOf(operationId)), - "{}", - Instant.now(), - Duration.ofHours(1))); - return operationId; - } - - /** Moves an operation to RUNNING with progress. */ - public void start(String operationId) { - store.claimNext(WORKER, Duration.ofMinutes(5), Instant.now()); - store.reportProgress( - new DurableOperationId(operationId), - WORKER, - new OperationProgressSnapshot(3, Optional.of(10L), Optional.of("extracting"))); - } - - /** Moves an operation to SUCCEEDED. */ - public void succeed(String operationId, String resultReference) { - store.claimNext(WORKER, Duration.ofMinutes(5), Instant.now()); - store.succeed(new DurableOperationId(operationId), WORKER, resultReference, Instant.now()); - } - - /** Moves an operation to FAILED. */ - public void fail(String operationId, String code, String detail) { - store.claimNext(WORKER, Duration.ofMinutes(5), Instant.now()); - store.fail( - new DurableOperationId(operationId), - WORKER, - new OperationFailure(code, detail, false), - Instant.now()); - } - - /** Records an operation belonging to somebody else. */ - public void submitForAnotherPrincipal(String operationId) { - store.submit( - new DurableOperationSubmission( - new DurableOperationId(operationId), - "reports.generate", - "somebody-else", - null, - new RequestFingerprint(fingerprintOf(operationId)), - "{}", - Instant.now(), - Duration.ofHours(1))); - } - - /** The context every fixture request runs under. */ - public static WebRequestContext context() { - Instant now = Instant.now(); - return new WebRequestContext( - new WebRequestId("req-operation"), - new WebTraceId("0af7651916cd43dd8448eb211c80319c"), - new WebOperationName("operations.get"), - new ApiMajorVersion(1), - ActorContext.authenticated(PRINCIPAL, Set.of()), - TenantContext.none(), - Locale.ENGLISH, - now, - now.plusSeconds(60), - new ExternalRequestContext("http", "localhost", 80, "")); - } - - private static String fingerprintOf(String operationId) { - String hex = Integer.toHexString(operationId.hashCode()); - return (hex + "0".repeat(64)).substring(0, 64); - } -} diff --git a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/operation/OperationHttpContract.java b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/operation/OperationHttpContract.java deleted file mode 100644 index 2e8295c5..00000000 --- a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/operation/OperationHttpContract.java +++ /dev/null @@ -1,148 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.testkit.operation; - -import static org.assertj.core.api.Assertions.assertThat; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * The operation resource contract, asserted identically on every transport. - * - *

A client polling an operation cannot tell which container answered it, so the two stacks must - * not differ here. Writing the cases once and extending is what makes that true by construction - * rather than by two authors happening to agree. - */ -public abstract class OperationHttpContract { - - /** The lane's fixture. */ - protected abstract HttpOperationFixture fixture(); - - @BeforeEach - void resetFixture() { - fixture().reset(); - } - - @Test - @DisplayName("an accepted submission answers 202 with the operation's location") - void acceptedSubmissionHasOperationLocation() { - HttpOperationFixture.Response receipt = fixture().submit(); - - assertThat(receipt.status()).isEqualTo(202); - assertThat(receipt.header("Location")).startsWith("/api/v1/operations/"); - } - - @Test - @DisplayName("the location a receipt names is readable") - void theReceiptLocationResolves() { - // A 202 pointing at a 404 is worse than no Location at all: the client has nothing to poll and - // no way to tell that the work was ever accepted. - HttpOperationFixture.Response receipt = fixture().submit(); - - HttpOperationFixture.Response polled = - fixture().get(HttpOperationFixture.operationIdOf(receipt)); - - assertThat(polled.status()).isEqualTo(200); - assertThat(polled.body()).contains("\"status\":\"PENDING\""); - } - - @Test - @DisplayName("an unfinished operation tells the client how long to wait") - void unfinishedOperationCarriesRetryAfter() { - String operationId = HttpOperationFixture.operationIdOf(fixture().submit()); - - // Without it every client picks its own interval, and the impatient ones set the load. - assertThat(fixture().get(operationId).header("Retry-After")).isNotNull(); - } - - @Test - @DisplayName("a running operation reports its progress") - void runningOperationReportsProgress() { - String operationId = HttpOperationFixture.operationIdOf(fixture().submit()); - fixture().transition(operationId, "RUNNING"); - - HttpOperationFixture.Response polled = fixture().get(operationId); - - assertThat(polled.body()).contains("\"status\":\"RUNNING\""); - assertThat(polled.body()).contains("\"completedUnits\":3"); - assertThat(polled.body()).contains("\"phase\":\"extracting\""); - } - - @Test - @DisplayName("a succeeded operation says where the result is and stops asking to be polled") - void succeededOperationPublishesItsResult() { - String operationId = HttpOperationFixture.operationIdOf(fixture().submit()); - fixture().transition(operationId, "SUCCEEDED"); - - HttpOperationFixture.Response polled = fixture().get(operationId); - - assertThat(polled.body()).contains("\"status\":\"SUCCEEDED\""); - assertThat(polled.header("Content-Location")).contains("reports/" + operationId); - // A Retry-After on a finished operation would keep well-behaved clients polling for ever. - assertThat(polled.header("Retry-After")).isNull(); - } - - @Test - @DisplayName("a failed operation publishes a problem document, not a bare status") - void failedOperationPublishesAProblem() { - String operationId = HttpOperationFixture.operationIdOf(fixture().submit()); - fixture().transition(operationId, "FAILED"); - - HttpOperationFixture.Response polled = fixture().get(operationId); - - assertThat(polled.status()).isEqualTo(200); - assertThat(polled.body()).contains("\"status\":\"FAILED\""); - assertThat(polled.body()).contains("DEPENDENCY_TIMEOUT"); - assertThat(polled.header("Retry-After")).isNull(); - } - - @Test - @DisplayName("cancelling answers 202 and moves the operation to CANCELED") - void cancelIsAcceptedAndRecorded() { - String operationId = HttpOperationFixture.operationIdOf(fixture().submit()); - - // 202, not 204: a worker mid-flight may still finish, so only the intent is certain. - assertThat(fixture().cancel(operationId).status()).isEqualTo(202); - assertThat(fixture().get(operationId).body()).contains("\"status\":\"CANCELED\""); - } - - @Test - @DisplayName("cancelling twice is still 202 rather than a conflict") - void cancelIsIdempotent() { - String operationId = HttpOperationFixture.operationIdOf(fixture().submit()); - fixture().cancel(operationId); - - // 409 would invite a retry that can never change anything. - assertThat(fixture().cancel(operationId).status()).isEqualTo(202); - } - - @Test - @DisplayName("cancelling a finished operation does not rewrite its outcome") - void cancelNeverReversesASuccess() { - String operationId = HttpOperationFixture.operationIdOf(fixture().submit()); - fixture().transition(operationId, "SUCCEEDED"); - - fixture().cancel(operationId); - - assertThat(fixture().get(operationId).body()).contains("\"status\":\"SUCCEEDED\""); - } - - @Test - @DisplayName("an operation belonging to someone else is 404, not 403") - void anotherPrincipalsOperationIsIndistinguishableFromAbsent() { - fixture().transition("op-elsewhere", "OTHER_PRINCIPAL"); - - // 403 would confirm the operation exists, turning id enumeration into an oracle for what - // other callers are running. - assertThat(fixture().get("op-elsewhere").status()).isEqualTo(404); - assertThat(fixture().get("op-never-existed").status()).isEqualTo(404); - } - - @Test - @DisplayName("cancelling someone else's operation is 404 and changes nothing") - void anotherPrincipalsOperationCannotBeCancelled() { - fixture().transition("op-elsewhere", "OTHER_PRINCIPAL"); - - assertThat(fixture().cancel("op-elsewhere").status()).isEqualTo(404); - } -} diff --git a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/operation/ReactiveOperationFixtureController.java b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/operation/ReactiveOperationFixtureController.java deleted file mode 100644 index 60982e5e..00000000 --- a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/operation/ReactiveOperationFixtureController.java +++ /dev/null @@ -1,92 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.testkit.operation; - -import dev.caskeleton.adapter.inbound.web.operationasync.OperationResponse; -import dev.caskeleton.adapter.inbound.web.webflux.operation.ReactiveOperationHttpController; -import java.net.URI; -import java.util.concurrent.atomic.AtomicInteger; -import org.springframework.boot.test.context.TestComponent; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.DeleteMapping; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; -import reactor.core.publisher.Mono; -import reactor.core.scheduler.Schedulers; - -/** - * The same routes on the reactive stack, delegating to the shipped reactive controller. - * - *

Two fixtures rather than one because the controllers genuinely differ in return type; the - * states they serve come from the same {@link OperationFixtureSupport}, so a difference between the - * lanes is a difference in the platform. - */ -// @TestComponent for the same reason as the fixture applications: a plain @RestController in this -// package is scanned into the real application, publishing fixture routes in a deployment. -@RestController -@TestComponent -public class ReactiveOperationFixtureController { - - private final OperationFixtureSupport support = new OperationFixtureSupport(); - private final ReactiveOperationHttpController delegate = - new ReactiveOperationHttpController(support.queryService(), Schedulers.boundedElastic()); - private final AtomicInteger submissions = new AtomicInteger(); - - /** Accepts work and hands back a receipt. */ - @PostMapping(path = "/api/v1/fixtures/reports", produces = MediaType.APPLICATION_JSON_VALUE) - public Mono> submit() { - return Mono.fromSupplier( - () -> { - String operationId = "op-" + submissions.incrementAndGet(); - support.submit(operationId); - return ResponseEntity.accepted() - .location(URI.create(ReactiveOperationHttpController.BASE_PATH + "/" + operationId)) - .build(); - }); - } - - /** Reads one operation through the shipped controller. */ - @GetMapping( - path = ReactiveOperationHttpController.BASE_PATH + "/{operationId}", - produces = MediaType.APPLICATION_JSON_VALUE) - public Mono> get(@PathVariable String operationId) { - return delegate.get(operationId, OperationFixtureSupport.context()); - } - - /** Cancels one operation through the shipped controller. */ - @DeleteMapping(ReactiveOperationHttpController.BASE_PATH + "/{operationId}") - public Mono> cancel(@PathVariable String operationId) { - return delegate.cancel(operationId, OperationFixtureSupport.context()); - } - - /** Drives an operation into the state a scenario needs. */ - @PostMapping("/api/v1/fixtures/operations/{operationId}/state") - public Mono> transition( - @PathVariable String operationId, @RequestParam String to) { - return Mono.fromSupplier( - () -> { - switch (to) { - case "RUNNING" -> support.start(operationId); - case "SUCCEEDED" -> support.succeed(operationId, "reports/" + operationId); - case "FAILED" -> - support.fail(operationId, "DEPENDENCY_TIMEOUT", "the report source timed out"); - case "OTHER_PRINCIPAL" -> support.submitForAnotherPrincipal(operationId); - default -> throw new IllegalArgumentException("unknown fixture state " + to); - } - return ResponseEntity.noContent().build(); - }); - } - - /** Empties the store between scenarios. */ - @DeleteMapping("/api/v1/fixtures/operations") - public Mono> reset() { - return Mono.fromSupplier( - () -> { - support.reset(); - submissions.set(0); - return ResponseEntity.noContent().build(); - }); - } -} diff --git a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/operation/TestDurableOperationStore.java b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/operation/TestDurableOperationStore.java deleted file mode 100644 index 05b86a42..00000000 --- a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/operation/TestDurableOperationStore.java +++ /dev/null @@ -1,320 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.testkit.operation; - -import dev.caskeleton.application.idempotency.RequestFingerprint; -import dev.caskeleton.application.operation.DurableOperation; -import dev.caskeleton.application.operation.DurableOperationId; -import dev.caskeleton.application.operation.DurableOperationState; -import dev.caskeleton.application.operation.DurableOperationStorePort; -import dev.caskeleton.application.operation.DurableOperationSubmission; -import dev.caskeleton.application.operation.OperationFailure; -import dev.caskeleton.application.operation.OperationLease; -import dev.caskeleton.application.operation.OperationProgressSnapshot; -import java.time.Duration; -import java.time.Instant; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.ConcurrentHashMap; - -/** - * A store with the semantics the JPA adapter must also have. - * - *

Written to the same rules rather than to whatever makes the tests pass: a submission scope - * that already exists returns the existing operation, a lease is checked on every write, and a - * terminal operation is never reopened. A fake that was laxer than the adapter would let the - * transport tests certify behaviour the real store refuses. - * - *

A near-twin of the one in {@code application-core}'s tests, and deliberately not shared: this - * leaf cannot see another leaf's test sources, and publishing a testkit from {@code - * application-core} purely to share a fake would put a test artefact on the dependency graph of - * every consumer. The duplication is bounded and visible; the alternative is not. - */ -public final class TestDurableOperationStore implements DurableOperationStorePort { - - private record Scope(String tenant, String principal, String operationName, String hash) {} - - private final Map byId = new ConcurrentHashMap<>(); - private final Map byScope = new ConcurrentHashMap<>(); - private final Map payloads = new ConcurrentHashMap<>(); - - @Override - public DurableOperation submit(DurableOperationSubmission submission) { - Scope scope = - new Scope( - submission.tenantId() == null ? "" : submission.tenantId(), - submission.principal(), - submission.operationName(), - submission.fingerprint().hex()); - DurableOperationId existing = byScope.putIfAbsent(scope, submission.operationId()); - if (existing != null) { - return byId.get(existing); - } - DurableOperation operation = - new DurableOperation( - submission.operationId(), - submission.operationName(), - submission.principal(), - submission.tenantId(), - DurableOperationState.PENDING, - submission.submittedAt(), - Optional.empty(), - Optional.empty(), - Optional.empty(), - Optional.empty(), - Optional.empty(), - Optional.empty(), - submission.expiresAt()); - byId.put(submission.operationId(), operation); - payloads.put(submission.operationId(), submission.payload()); - return operation; - } - - @Override - public Optional find( - DurableOperationId operationId, String principal, Instant now) { - return Optional.ofNullable(byId.get(operationId)) - .filter(operation -> operation.principal().equals(principal)); - } - - @Override - public Optional claimNext( - String workerId, Duration leaseDuration, Instant now) { - return byId.values().stream() - .filter( - operation -> - operation.state() == DurableOperationState.PENDING - || (operation.state() == DurableOperationState.RUNNING - && operation.leaseExpiredAt(now))) - .filter(operation -> now.isBefore(operation.expiresAt())) - .min(Comparator.comparing(DurableOperation::submittedAt)) - .map( - operation -> { - DurableOperation claimed = - replace( - operation, - DurableOperationState.RUNNING, - Optional.of(operation.startedAt().orElse(now)), - Optional.empty(), - operation.progress(), - operation.resultReference(), - Optional.empty(), - Optional.of(new OperationLease(workerId, now, now.plus(leaseDuration)))); - byId.put(claimed.operationId(), claimed); - return new DurableOperationSubmission( - claimed.operationId(), - claimed.operationName(), - claimed.principal(), - claimed.tenantId(), - new RequestFingerprint("0".repeat(64)), - payloads.getOrDefault(claimed.operationId(), "{}"), - claimed.submittedAt(), - Duration.between(claimed.submittedAt(), claimed.expiresAt())); - }); - } - - @Override - public boolean heartbeat( - DurableOperationId operationId, String workerId, Duration leaseDuration, Instant now) { - DurableOperation operation = byId.get(operationId); - if (!holdsLease(operation, workerId, now)) { - return false; - } - byId.put( - operationId, - replace( - operation, - operation.state(), - operation.startedAt(), - operation.completedAt(), - operation.progress(), - operation.resultReference(), - Optional.empty(), - operation.lease().map(lease -> lease.extendedTo(now.plus(leaseDuration))))); - return true; - } - - @Override - public boolean reportProgress( - DurableOperationId operationId, String workerId, OperationProgressSnapshot progress) { - DurableOperation operation = byId.get(operationId); - if (operation == null || !ownedBy(operation, workerId)) { - return false; - } - byId.put( - operationId, - replace( - operation, - operation.state(), - operation.startedAt(), - operation.completedAt(), - Optional.of(progress), - operation.resultReference(), - Optional.empty(), - operation.lease())); - return true; - } - - @Override - public boolean succeed( - DurableOperationId operationId, - String workerId, - String resultReference, - Instant completedAt) { - DurableOperation operation = byId.get(operationId); - if (operation == null || !ownedBy(operation, workerId)) { - return false; - } - byId.put( - operationId, - replace( - operation, - DurableOperationState.SUCCEEDED, - operation.startedAt(), - Optional.of(completedAt), - operation.progress(), - Optional.of(resultReference), - Optional.empty(), - Optional.empty())); - return true; - } - - @Override - public boolean fail( - DurableOperationId operationId, - String workerId, - OperationFailure failure, - Instant completedAt) { - DurableOperation operation = byId.get(operationId); - if (operation == null || !ownedBy(operation, workerId)) { - return false; - } - byId.put( - operationId, - replace( - operation, - DurableOperationState.FAILED, - operation.startedAt(), - Optional.of(completedAt), - operation.progress(), - Optional.empty(), - Optional.of(failure), - Optional.empty())); - return true; - } - - @Override - public boolean cancel(DurableOperationId operationId, String principal, Instant canceledAt) { - DurableOperation operation = byId.get(operationId); - if (operation == null - || !operation.principal().equals(principal) - || !operation.state().cancellable()) { - return false; - } - byId.put( - operationId, - replace( - operation, - DurableOperationState.CANCELED, - operation.startedAt(), - Optional.of(canceledAt), - operation.progress(), - operation.resultReference(), - Optional.empty(), - Optional.empty())); - return true; - } - - @Override - public List reclaimExpiredLeases(Instant now) { - List reclaimed = new ArrayList<>(); - byId.forEach( - (id, operation) -> { - if (operation.state() == DurableOperationState.RUNNING && operation.leaseExpiredAt(now)) { - byId.put( - id, - replace( - operation, - DurableOperationState.PENDING, - operation.startedAt(), - Optional.empty(), - operation.progress(), - operation.resultReference(), - Optional.empty(), - Optional.empty())); - reclaimed.add(id); - } - }); - return List.copyOf(reclaimed); - } - - @Override - public List expireStaleOperations(Instant now) { - List expired = new ArrayList<>(); - byId.forEach( - (id, operation) -> { - if (!operation.state().terminal() && !now.isBefore(operation.expiresAt())) { - byId.put( - id, - replace( - operation, - DurableOperationState.EXPIRED, - operation.startedAt(), - Optional.of(now), - operation.progress(), - operation.resultReference(), - Optional.empty(), - Optional.empty())); - expired.add(id); - } - }); - return List.copyOf(expired); - } - - /** How many operations exist. */ - public int size() { - return byId.size(); - } - - /** Drops everything between scenarios. */ - public void clear() { - byId.clear(); - byScope.clear(); - payloads.clear(); - } - - private static boolean holdsLease(DurableOperation operation, String workerId, Instant now) { - return operation != null && ownedBy(operation, workerId) && !operation.leaseExpiredAt(now); - } - - private static boolean ownedBy(DurableOperation operation, String workerId) { - return operation.state() == DurableOperationState.RUNNING - && operation.lease().map(lease -> lease.workerId().equals(workerId)).orElse(false); - } - - private static DurableOperation replace( - DurableOperation operation, - DurableOperationState state, - Optional startedAt, - Optional completedAt, - Optional progress, - Optional resultReference, - Optional failure, - Optional lease) { - return new DurableOperation( - operation.operationId(), - operation.operationName(), - operation.principal(), - operation.tenantId(), - state, - operation.submittedAt(), - startedAt, - completedAt, - progress, - resultReference, - failure, - lease, - operation.expiresAt()); - } -} diff --git a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/proxy/ProxyFixtureController.java b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/proxy/ProxyFixtureController.java deleted file mode 100644 index 2a302238..00000000 --- a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/proxy/ProxyFixtureController.java +++ /dev/null @@ -1,101 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.testkit.proxy; - -import dev.caskeleton.adapter.inbound.web.http.ExternalOrigin; -import dev.caskeleton.adapter.inbound.web.http.ExternalPrefix; -import dev.caskeleton.adapter.inbound.web.http.ExternalUriBuilder; -import dev.caskeleton.adapter.inbound.web.http.ExternalUriPolicy; -import dev.caskeleton.adapter.inbound.web.proxy.ForwardedHeaderSanitizer; -import dev.caskeleton.adapter.inbound.web.proxy.NormalizedForwardedHeaders; -import dev.caskeleton.adapter.inbound.web.proxy.TrustedProxyPolicy; -import jakarta.servlet.http.HttpServletRequest; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.Map; -import org.springframework.boot.test.context.TestComponent; -import org.springframework.http.MediaType; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RestController; - -/** - * Reports what the platform concluded about the request's origin. - * - *

Reporting rather than asserting, so the lane can compare what a client sent with what the - * application ended up believing. The interesting cases are the ones where those differ: a client - * that sends {@code X-Forwarded-Host: evil.example} and an application that correctly reports - * {@code hyeonworks.com} is the proxy having done its job. - * - *

Every proxy in a container network is a private address, so the trust policy admits the RFC - * 1918 ranges. Narrower than the default of trusting whatever spoke last, wider than a single - * address nobody can predict. - */ -// @TestComponent for the same reason as the fixture applications: a plain @RestController in this -// package is scanned into the real application, publishing fixture routes in a deployment. -@RestController -@TestComponent -public class ProxyFixtureController { - - /** Reports the resolved external URI. */ - public static final String EXTERNAL_URI_PATH = "/v1/external-uri"; - - /** Reports the resolved client address. */ - public static final String CLIENT_ADDRESS_PATH = "/v1/client-address"; - - /** Echoes the application path the request arrived on. */ - public static final String ARRIVED_PATH = "/v1/arrived-path"; - - /** Accepts a body, so the proxy's own size limit is observable. */ - public static final String ECHO_PATH = "/v1/echo"; - - private final ForwardedHeaderSanitizer sanitizer = - new ForwardedHeaderSanitizer( - TrustedProxyPolicy.of("10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "127.0.0.0/8")); - - /** - * The absolute URI the platform would publish for a resource. - * - *

This is the value that ends up in a {@code Location} header, so it is the one an open - * redirect would come out of: an application that believed a client's forwarded host would mint - * links pointing at the attacker's domain and hand them to the browser. - */ - @GetMapping(path = EXTERNAL_URI_PATH, produces = MediaType.TEXT_PLAIN_VALUE) - public String externalUri(HttpServletRequest request) { - NormalizedForwardedHeaders forwarded = - sanitizer.normalize(request.getRemoteAddr(), headersOf(request)); - ExternalUriPolicy policy = ExternalUriPolicy.fromTrustedProxy(ExternalPrefix.none()); - ExternalOrigin origin = - policy.resolveOrigin( - forwarded, - new ExternalOrigin( - request.getScheme(), request.getServerName(), request.getServerPort())); - return new ExternalUriBuilder(origin, policy.resolvePrefix(forwarded)).absolute("/v1/result"); - } - - /** The client address the platform resolved. */ - @GetMapping(path = CLIENT_ADDRESS_PATH, produces = MediaType.TEXT_PLAIN_VALUE) - public String clientAddress(HttpServletRequest request) { - NormalizedForwardedHeaders forwarded = - sanitizer.normalize(request.getRemoteAddr(), headersOf(request)); - return forwarded.clientAddress().orElseGet(request::getRemoteAddr); - } - - /** The application path the request actually arrived on. */ - @GetMapping(path = ARRIVED_PATH, produces = MediaType.TEXT_PLAIN_VALUE) - public String arrivedPath(HttpServletRequest request) { - return request.getRequestURI(); - } - - /** Reports how many bytes of body arrived. */ - @PostMapping(path = ECHO_PATH, produces = MediaType.TEXT_PLAIN_VALUE) - public String echo(@RequestBody(required = false) byte[] body) { - return Integer.toString(body == null ? 0 : body.length); - } - - private static Map headersOf(HttpServletRequest request) { - Map headers = new LinkedHashMap<>(); - Collections.list(request.getHeaderNames()) - .forEach(name -> headers.put(name, request.getHeader(name))); - return headers; - } -} diff --git a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/throttle/CountingRateLimiter.java b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/throttle/CountingRateLimiter.java deleted file mode 100644 index 0e28707d..00000000 --- a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/throttle/CountingRateLimiter.java +++ /dev/null @@ -1,51 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.testkit.throttle; - -import dev.caskeleton.adapter.inbound.web.core.WebRequestContext; -import dev.caskeleton.adapter.inbound.web.ratelimit.RateLimitDecision; -import dev.caskeleton.adapter.inbound.web.ratelimit.RateLimitProfileName; -import dev.caskeleton.adapter.inbound.web.ratelimit.WebRateLimiter; -import java.time.Duration; -import java.time.Instant; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicReference; - -/** - * A quota that counts and can be told to fail. - * - *

Fixed window, not a token bucket. The lanes assert what a client is told when the quota is - * spent, and a window that refills mid-test would make the refusal flaky for reasons that have - * nothing to do with the transport. - * - *

The failure switch exists because a limiter's store being unreachable is the case with two - * defensible answers and no default, and both must be observable end to end. - */ -public final class CountingRateLimiter implements WebRateLimiter { - - private final AtomicInteger used = new AtomicInteger(); - private final AtomicReference failure = new AtomicReference<>(); - - @Override - public RateLimitDecision evaluate(WebRequestContext context, RateLimitProfileName profile) { - RuntimeException injected = failure.get(); - if (injected != null) { - throw injected; - } - Instant resetAt = Instant.now().plusSeconds(60); - int spent = used.incrementAndGet(); - return spent > ThrottleFixtureProtocol.QUOTA - ? RateLimitDecision.refused(ThrottleFixtureProtocol.QUOTA, resetAt, Duration.ofSeconds(1)) - : RateLimitDecision.allowed( - ThrottleFixtureProtocol.QUOTA, ThrottleFixtureProtocol.QUOTA - spent, resetAt); - } - - /** Refills the window. */ - public void reset() { - used.set(0); - failure.set(null); - } - - /** Makes every evaluation throw, as an unreachable store would. */ - public void breakStore() { - failure.set(new IllegalStateException("the rate limit store is unreachable")); - } -} diff --git a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/throttle/HttpThrottleFixture.java b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/throttle/HttpThrottleFixture.java deleted file mode 100644 index 10dc8b7b..00000000 --- a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/throttle/HttpThrottleFixture.java +++ /dev/null @@ -1,206 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.testkit.throttle; - -import dev.caskeleton.adapter.inbound.web.testkit.HttpFixtureTimeouts; -import java.io.IOException; -import java.io.InputStream; -import java.net.HttpURLConnection; -import java.net.URI; -import java.nio.charset.StandardCharsets; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - -/** - * Drives the throttle routes over a real socket. - * - *

The saturation helper starts a request that holds its slot and waits until it is genuinely - * running before the next call. Firing two requests and hoping the first arrives first is the shape - * that makes a 503 assertion flaky, and a flaky throttle test is one people learn to rerun. - */ -public final class HttpThrottleFixture implements AutoCloseable { - - /** - * One response, as the client saw it. - * - * @param status the HTTP status - * @param body the response body - * @param retryAfter the {@code Retry-After} header, or null - */ - public record Response(int status, String body, String retryAfter) { - - /** The problem code the body names, or null. */ - public String problemCode() { - int at = body.indexOf("\"code\":\""); - if (at < 0) { - return null; - } - int from = at + 8; - return body.substring(from, body.indexOf('"', from)); - } - } - - /** - * How long {@link #awaitSlotTaken} waits for the holder to occupy the single write slot. - * - *

A liveness guard, not an assertion: if the slot is never taken the scenario cannot run, and - * failing is better than hanging. Ten seconds was short enough that a loaded machine could trip - * it before the holder was scheduled. - */ - private static final long SLOT_TAKEN_DEADLINE_SECONDS = 40; - - /** - * How long the holding request is allowed to hold the slot. - * - *

Must stay comfortably above {@link #SLOT_TAKEN_DEADLINE_SECONDS}: if the holder gave up - * first, the slot would be free again while the scenario was still waiting to observe it taken, - * and the failure would name capacity rather than the fixture. - */ - private static final int HOLDER_TIMEOUT_MILLIS = 120_000; - - private final String baseUrl; - private final ExecutorService holders = Executors.newCachedThreadPool(); - - /** - * A fixture against a running container. - * - * @param port the container's port - */ - public HttpThrottleFixture(int port) { - this.baseUrl = "http://localhost:" + port; - } - - /** Refills the quota and releases any held slot. */ - public void reset() { - send("POST", ThrottleFixtureProtocol.RESET_PATH, HttpFixtureTimeouts.READ_MILLIS); - } - - /** Refills the quota, then makes the limiter's store unreachable. */ - public void breakLimiterStore() { - send( - "POST", - ThrottleFixtureProtocol.RESET_PATH + "?breakStore=true", - HttpFixtureTimeouts.READ_MILLIS); - } - - /** One call against the quota route. */ - public Response callQuotaRoute() { - return send("GET", ThrottleFixtureProtocol.QUOTA_PATH, HttpFixtureTimeouts.READ_MILLIS); - } - - /** Spends the whole quota, then calls once more. */ - public Response exhaustAndCall() { - for (int index = 0; index < ThrottleFixtureProtocol.QUOTA; index++) { - callQuotaRoute(); - } - return callQuotaRoute(); - } - - /** One call against the write route. */ - public Response callWriteRoute() { - return send("POST", ThrottleFixtureProtocol.WRITE_PATH, HttpFixtureTimeouts.READ_MILLIS); - } - - /** - * Occupies the single write slot, then calls the write route again. - * - *

The holder is confirmed to be inside the handler before the second call goes out, so the - * refusal is caused by the slot being taken rather than by whichever request happened to win. - */ - public Response saturateAndCallWrite() { - send("POST", ThrottleFixtureProtocol.RESET_PATH + "?arm=true", HttpFixtureTimeouts.READ_MILLIS); - CompletableFuture holder = - CompletableFuture.supplyAsync( - () -> - send( - "POST", - ThrottleFixtureProtocol.WRITE_PATH + "?hold=true", - HOLDER_TIMEOUT_MILLIS), - holders); - try { - awaitSlotTaken(holder); - // Refill the quota without letting go of the slot. Confirming the slot was taken cost - // several quota-charged probes, and the filter charges quota before it asks for capacity — - // so without this the next call is refused 429 and the 503 case never runs. - send( - "POST", - ThrottleFixtureProtocol.RESET_PATH + "?releaseHold=false", - HttpFixtureTimeouts.READ_MILLIS); - return callWriteRoute(); - } finally { - reset(); - try { - holder.get(SLOT_TAKEN_DEADLINE_SECONDS + 30, TimeUnit.SECONDS); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - } catch (ExecutionException | TimeoutException ignored) { - // The holder's own outcome is not what this scenario asserts. - } - } - } - - private void awaitSlotTaken(CompletableFuture holder) { - // Polled rather than slept: a fixed sleep is either too short on a loaded machine or wasted - // time on an idle one, and the first is a flaky failure nobody can reproduce. - long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(SLOT_TAKEN_DEADLINE_SECONDS); - while (System.nanoTime() < deadline) { - if (holder.isDone()) { - throw new IllegalStateException("the holding request returned before the slot was taken"); - } - // Refilled before every probe, not only after the loop. The filter charges quota before it - // asks for capacity, so each probe spends some — and on a machine loaded enough that the - // holder takes a while to occupy the slot, the quota runs out first and every remaining - // probe answers 429. The loop then never sees its 503 and fails on the deadline, which - // reads as a capacity bug and is a fixture bug. - send( - "POST", - ThrottleFixtureProtocol.RESET_PATH + "?releaseHold=false", - HttpFixtureTimeouts.READ_MILLIS); - Response probe = - send("POST", ThrottleFixtureProtocol.WRITE_PATH, HttpFixtureTimeouts.READ_MILLIS); - if (probe.status() == 503) { - return; - } - if (probe.status() == 429) { - throw new IllegalStateException( - "a probe was refused for quota immediately after a refill, so the refill is not " - + "refilling and this scenario cannot reach the capacity case"); - } - } - throw new IllegalStateException("the write slot was never taken"); - } - - @Override - public void close() { - holders.shutdownNow(); - } - - private Response send(String method, String path, int readTimeoutMillis) { - try { - HttpURLConnection connection = - (HttpURLConnection) URI.create(baseUrl + path).toURL().openConnection(); - connection.setRequestMethod(method); - connection.setConnectTimeout(HttpFixtureTimeouts.CONNECT_MILLIS); - connection.setReadTimeout(readTimeoutMillis); - if ("POST".equals(method)) { - connection.setDoOutput(true); - connection.getOutputStream().close(); - } - try { - int status = connection.getResponseCode(); - String body; - try (InputStream stream = - status >= 400 ? connection.getErrorStream() : connection.getInputStream()) { - body = stream == null ? "" : new String(stream.readAllBytes(), StandardCharsets.UTF_8); - } - return new Response(status, body, connection.getHeaderField("Retry-After")); - } finally { - connection.disconnect(); - } - } catch (IOException e) { - throw new IllegalStateException(method + " " + path + " failed", e); - } - } -} diff --git a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/throttle/ThrottleControlController.java b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/throttle/ThrottleControlController.java deleted file mode 100644 index f7ba0192..00000000 --- a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/throttle/ThrottleControlController.java +++ /dev/null @@ -1,61 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.testkit.throttle; - -import org.springframework.boot.test.context.TestComponent; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -/** - * The out-of-band control the lanes drive the fixture with. - * - *

Separate from the throttled routes because these must never be throttled themselves: a reset - * that the exhausted quota refuses would leave the fixture stuck, and every case after the first - * would fail for the wrong reason. - */ -// @TestComponent for the same reason as the fixture applications: a plain @RestController in this -// package is scanned into the real application, publishing fixture routes in a deployment. -@RestController -@TestComponent -public class ThrottleControlController { - - private final CountingRateLimiter limiter; - private final ThrottleFixtureController routes; - - /** - * A control over the fixture's limiter and routes. - * - * @param limiter the quota being driven - * @param routes the routes holding admission slots - */ - public ThrottleControlController(CountingRateLimiter limiter, ThrottleFixtureController routes) { - this.limiter = limiter; - this.routes = routes; - } - - /** - * Refills the quota, clears any injected failure, and optionally releases a held slot. - * - *

The two are separable because a lane driving the capacity case needs to refill the quota - * *without* letting go of the slot: the filter charges quota before it asks for capacity, so the - * probing that confirms the slot is taken spends quota too, and a 429 would arrive where the 503 - * was being tested. - */ - @PostMapping(ThrottleFixtureProtocol.RESET_PATH) - public ResponseEntity reset( - @RequestParam(name = "breakStore", defaultValue = "false") boolean breakStore, - @RequestParam(name = "arm", defaultValue = "false") boolean arm, - @RequestParam(name = "releaseHold", defaultValue = "true") boolean releaseHold) { - if (releaseHold) { - routes.releaseHold(); - } - limiter.reset(); - if (breakStore) { - limiter.breakStore(); - } - if (arm) { - routes.arm(); - } - return ResponseEntity.noContent().build(); - } -} diff --git a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/throttle/ThrottleFixtureController.java b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/throttle/ThrottleFixtureController.java deleted file mode 100644 index beed0cce..00000000 --- a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/throttle/ThrottleFixtureController.java +++ /dev/null @@ -1,62 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.testkit.throttle; - -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicReference; -import org.springframework.boot.test.context.TestComponent; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -/** - * A quota route and a write route that can hold its admission slot. - * - *

Holding is how a lane saturates capacity deterministically. Generating enough concurrent load - * to fill a real pool would make the refusal a matter of timing, and a test that observes 503 only - * sometimes is one nobody trusts when it fails. - */ -// @TestComponent for the same reason as the fixture applications: a plain @RestController in this -// package is scanned into the real application, publishing fixture routes in a deployment. -@RestController -@TestComponent -public class ThrottleFixtureController { - - private final AtomicReference release = - new AtomicReference<>(new CountDownLatch(0)); - - /** A read governed by the quota. */ - @GetMapping(path = ThrottleFixtureProtocol.QUOTA_PATH, produces = MediaType.TEXT_PLAIN_VALUE) - public ResponseEntity quotaRoute() { - return ResponseEntity.ok("ok"); - } - - /** A write that optionally holds its admission slot until released. */ - @PostMapping(path = ThrottleFixtureProtocol.WRITE_PATH, produces = MediaType.TEXT_PLAIN_VALUE) - public ResponseEntity writeRoute( - @RequestParam(name = ThrottleFixtureProtocol.HOLD_PARAM, defaultValue = "false") - boolean hold) { - if (hold) { - try { - // Bounded, so a lane that fails before releasing cannot hang the container's thread pool - // for the rest of the run. - release.get().await(30, TimeUnit.SECONDS); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - } - } - return ResponseEntity.ok("ok"); - } - - /** Arms a new hold. */ - public void arm() { - release.set(new CountDownLatch(1)); - } - - /** Releases whatever is holding a slot. */ - public void releaseHold() { - release.get().countDown(); - } -} diff --git a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/throttle/ThrottleFixtureProtocol.java b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/throttle/ThrottleFixtureProtocol.java deleted file mode 100644 index 38d22a19..00000000 --- a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/throttle/ThrottleFixtureProtocol.java +++ /dev/null @@ -1,28 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.testkit.throttle; - -/** - * The routes and quotas the throttle lanes use. - * - *

The quota is tiny and the write profile admits one at a time, because both refusals are about - * a boundary being crossed and neither gets truer at production scale. A lane sized realistically - * would spend minutes generating load to observe the same two responses. - */ -public final class ThrottleFixtureProtocol { - - private ThrottleFixtureProtocol() {} - - /** How many requests the fixture quota admits before refusing. */ - public static final int QUOTA = 3; - - /** A route governed by the quota. */ - public static final String QUOTA_PATH = "/api/v1/fixtures/throttle/quota"; - - /** A write route whose admission profile admits one request at a time. */ - public static final String WRITE_PATH = "/api/v1/fixtures/throttle/write"; - - /** Resets the quota and releases any held slot. */ - public static final String RESET_PATH = "/api/v1/fixtures/throttle/reset"; - - /** Tells the write route to hold its slot until released. */ - public static final String HOLD_PARAM = "hold"; -} diff --git a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/throttle/ThrottleFixtureSupport.java b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/throttle/ThrottleFixtureSupport.java deleted file mode 100644 index d46a1c83..00000000 --- a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/throttle/ThrottleFixtureSupport.java +++ /dev/null @@ -1,75 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.testkit.throttle; - -import dev.caskeleton.adapter.inbound.web.admission.AdmissionProfile; -import dev.caskeleton.adapter.inbound.web.admission.SemaphoreAdmissionController; -import dev.caskeleton.adapter.inbound.web.core.ActorContext; -import dev.caskeleton.adapter.inbound.web.core.ApiMajorVersion; -import dev.caskeleton.adapter.inbound.web.core.ExternalRequestContext; -import dev.caskeleton.adapter.inbound.web.core.TenantContext; -import dev.caskeleton.adapter.inbound.web.core.WebOperationName; -import dev.caskeleton.adapter.inbound.web.core.WebRequestContext; -import dev.caskeleton.adapter.inbound.web.core.WebRequestId; -import dev.caskeleton.adapter.inbound.web.core.WebTraceId; -import dev.caskeleton.adapter.inbound.web.operation.AdmissionProfileName; -import dev.caskeleton.adapter.inbound.web.operation.WebOperationProfile; -import java.time.Duration; -import java.time.Instant; -import java.util.Locale; -import java.util.Set; - -/** - * The profiles and the context both throttle fixtures use. - * - *

The write profile admits exactly one request. The production {@code global-write} profile - * admits thirty-two, which is right for a service and useless for a lane: filling it would take - * thirty-three concurrent connections and the result would still be a race. - */ -public final class ThrottleFixtureSupport { - - private ThrottleFixtureSupport() {} - - /** The write profile the lanes saturate. */ - public static AdmissionProfile writeProfile() { - return new AdmissionProfile( - new AdmissionProfileName("global-write"), 1, 1, Duration.ofMillis(50)); - } - - /** An admission controller over the fixture profiles. */ - public static SemaphoreAdmissionController admissionController() { - return new SemaphoreAdmissionController(AdmissionProfile.standard(), writeProfile()); - } - - /** The operation profile a path maps to. */ - public static WebOperationProfile profileFor(String path) { - if (path.startsWith(ThrottleFixtureProtocol.WRITE_PATH)) { - return new WebOperationProfile( - new WebOperationName("throttle.write"), - dev.caskeleton.adapter.inbound.web.operation.HttpMethodSemantic.POST, - dev.caskeleton.adapter.inbound.web.operation.MutationKind.CREATE, - dev.caskeleton.adapter.inbound.web.budget.WebBudgetProfileName.standard(), - dev.caskeleton.adapter.inbound.web.operation.AuthorizationProfileName.standard(), - dev.caskeleton.adapter.inbound.web.operation.IdempotencyPolicy.OPTIONAL, - dev.caskeleton.adapter.inbound.web.operation.PreconditionPolicy.NONE, - dev.caskeleton.adapter.inbound.web.operation.CachePolicyName.standard(), - writeProfile().name(), - dev.caskeleton.adapter.inbound.web.operation.ResponseProfileName.standard()); - } - return WebOperationProfile.readOnly("throttle.read"); - } - - /** The context every fixture request runs under. */ - public static WebRequestContext context() { - Instant now = Instant.now(); - return new WebRequestContext( - new WebRequestId("req-throttle"), - new WebTraceId("0af7651916cd43dd8448eb211c80319c"), - new WebOperationName("throttle.read"), - new ApiMajorVersion(1), - ActorContext.authenticated("fixture", Set.of()), - TenantContext.none(), - Locale.ENGLISH, - now, - now.plusSeconds(60), - new ExternalRequestContext("http", "localhost", 80, "")); - } -} diff --git a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/throttle/WebThrottleHttpContract.java b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/throttle/WebThrottleHttpContract.java deleted file mode 100644 index 4e74a199..00000000 --- a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/throttle/WebThrottleHttpContract.java +++ /dev/null @@ -1,122 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.testkit.throttle; - -import static org.assertj.core.api.Assertions.assertThat; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * The two refusals that mean "not now", and the requirement that they stay different. - * - *

Most of these cases exist to defend one distinction: a spent quota is the caller's doing and - * is 429; a full service is not and is 503. Collapsing them is easy — both are "too much traffic" - * from the server's side — and it tells every client the wrong thing half the time. A client told - * 429 during an incident slows itself down permanently; one told 503 for its own overuse keeps - * hammering and waits for a recovery that will not come. - */ -public abstract class WebThrottleHttpContract { - - /** The lane's fixture. */ - protected abstract HttpThrottleFixture fixture(); - - @BeforeEach - void resetFixture() { - fixture().reset(); - } - - @Test - @DisplayName("a request inside the quota is served") - void requestWithinQuotaIsServed() { - assertThat(fixture().callQuotaRoute().status()).isEqualTo(200); - } - - @Test - @DisplayName("exhausting the quota answers 429 with a Retry-After") - void quotaExhaustionReturns429AndRetryAfter() { - HttpThrottleFixture.Response response = fixture().exhaustAndCall(); - - assertThat(response.status()).isEqualTo(429); - assertThat(response.problemCode()).isEqualTo("RATE_LIMITED"); - assertThat(response.retryAfter()).isNotNull(); - } - - @Test - @DisplayName("Retry-After is never zero") - void retryAfterIsNeverZero() { - // RFC 9110 counts in seconds, so a sub-second wait rendered honestly is "0" — which tells the - // client to retry immediately, the opposite of what a refusal means. - assertThat(Integer.parseInt(fixture().exhaustAndCall().retryAfter())).isGreaterThanOrEqualTo(1); - } - - @Test - @DisplayName("a saturated write profile answers 503, not 429") - void saturatedWriteAdmissionReturns503() { - HttpThrottleFixture.Response response = fixture().saturateAndCallWrite(); - - assertThat(response.status()).isEqualTo(503); - assertThat(response.problemCode()).isEqualTo("ADMISSION_REJECTED"); - } - - @Test - @DisplayName("a capacity refusal does not blame the caller") - void capacityRefusalIsNotAQuotaRefusal() { - // The distinction this whole pair exists for. A 503 whose body reads like a rate limit sends - // a well-behaved client into a backoff it never needed to enter. - HttpThrottleFixture.Response response = fixture().saturateAndCallWrite(); - - assertThat(response.problemCode()).isNotEqualTo("RATE_LIMITED"); - assertThat(response.body()).doesNotContain("quota"); - } - - @Test - @DisplayName("a capacity refusal still says when to come back") - void capacityRefusalCarriesRetryAfter() { - assertThat(fixture().saturateAndCallWrite().retryAfter()).isNotNull(); - } - - @Test - @DisplayName("a request refused for capacity has still spent the caller's quota") - void capacityRefusalStillChargesQuota() { - // Stated rather than hidden, because it follows from charging quota before asking for - // capacity — and that order is deliberate: asking for capacity first lets a caller who is - // about to be rate-limited occupy a slot on its way to being told so. - // - // The cost is real. Under sustained overload every caller's quota drains on requests the - // service never ran, so they are eventually told 429 for a problem that was 503. An operator - // seeing 429 climb during an incident should read it as a symptom of the shedding, not as - // callers suddenly misbehaving. - fixture().saturateAndCallWrite(); - fixture().breakLimiterStore(); - - // With the limiter's store unreachable and the profile fail-open, the quota is out of the - // picture — so this asserts the capacity path alone still works after the earlier drain. - assertThat(fixture().callWriteRoute().status()).isEqualTo(200); - } - - @Test - @DisplayName("capacity is returned when the holding request finishes") - void capacityIsReleasedAfterTheRequestCompletes() { - // The failure this catches is a permit released on one exit path and not another: throughput - // decays towards zero over hours and nothing in the logs says why. - fixture().saturateAndCallWrite(); - - assertThat(fixture().callWriteRoute().status()).isEqualTo(200); - } - - @Test - @DisplayName("an unreachable limiter store serves the request when the profile says fail-open") - void failOpenServesWhenTheLimiterIsDown() { - // The profile's decision, made at review time. What must not happen is the limiter deciding - // it by whatever it does when the store throws. - fixture().breakLimiterStore(); - - assertThat(fixture().callQuotaRoute().status()).isEqualTo(200); - } - - @Test - @DisplayName("the quota refusal is a problem document, not a bare status") - void quotaRefusalIsAProblemDocument() { - assertThat(fixture().exhaustAndCall().body()).contains("\"type\"", "\"title\"", "\"status\""); - } -} diff --git a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/webflux/ReactiveContractFixtureController.java b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/webflux/ReactiveContractFixtureController.java deleted file mode 100644 index 5a5d402c..00000000 --- a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/adapter/inbound/web/testkit/webflux/ReactiveContractFixtureController.java +++ /dev/null @@ -1,73 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.testkit.webflux; - -import dev.caskeleton.adapter.inbound.web.webflux.context.WebFluxRequestContextAccessor; -import jakarta.validation.Valid; -import jakarta.validation.constraints.NotBlank; -import java.net.URI; -import org.springframework.boot.test.context.TestComponent; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.DeleteMapping; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; -import reactor.core.publisher.Mono; - -/** - * The reactive routes the Reactor Netty gate exercises. - * - *

Deliberately the same shape as the servlet fixture, so the two gates certify the same contract - * rather than two similar ones. The extra route is {@code /thread}: it reports the thread the - * handler ran on and the request id it read from the Reactor Context, which is the only way to show - * from outside that the context survived the hop onto an event loop. - */ -// @TestComponent for the same reason as the fixture applications: a plain @RestController in this -// package is scanned into the real application, publishing fixture routes in a deployment. -@RestController -@TestComponent -@RequestMapping("/api/v1/fixtures") -public class ReactiveContractFixtureController { - - /** A request body with one constraint, so a rejection is reachable. */ - public record FixtureRequest(@NotBlank String name) {} - - /** The resource, returned directly rather than inside an envelope. */ - public record FixtureResponse(String id, String name) {} - - /** What the handler observed about its own execution. */ - public record ExecutionReport(String threadName, String requestId) {} - - /** Creates; the new resource must be locatable. */ - @PostMapping( - consumes = MediaType.APPLICATION_JSON_VALUE, - produces = MediaType.APPLICATION_JSON_VALUE) - public Mono> create(@Valid @RequestBody FixtureRequest request) { - return Mono.just( - ResponseEntity.created(URI.create("/api/v1/fixtures/f1")) - .body(new FixtureResponse("f1", request.name()))); - } - - /** Reads; carries a validator so HEAD parity is observable. */ - @GetMapping(path = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE) - public Mono> read(@PathVariable String id) { - return Mono.just(ResponseEntity.ok().eTag("\"v1\"").body(new FixtureResponse(id, "fixture"))); - } - - /** Deletes; nothing may be written. */ - @DeleteMapping("/{id}") - public Mono> delete(@PathVariable String id) { - return Mono.just(ResponseEntity.noContent().build()); - } - - /** Reports the execution thread and the request id read from the Reactor Context. */ - @GetMapping(path = "/thread", produces = MediaType.APPLICATION_JSON_VALUE) - public Mono thread() { - return WebFluxRequestContextAccessor.require() - .map( - context -> - new ExecutionReport(Thread.currentThread().getName(), context.requestId().value())); - } -} diff --git a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/webtestkit/BudgetFixtureApplication.java b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/webtestkit/BudgetFixtureApplication.java deleted file mode 100644 index cb369399..00000000 --- a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/webtestkit/BudgetFixtureApplication.java +++ /dev/null @@ -1,72 +0,0 @@ -package dev.caskeleton.webtestkit; - -import dev.caskeleton.adapter.inbound.web.error.BudgetProblemMapper; -import dev.caskeleton.adapter.inbound.web.error.WebProblemFactory; -import dev.caskeleton.adapter.inbound.web.json.WebObjectMapperFactory; -import dev.caskeleton.adapter.inbound.web.mvc.budget.WebMvcBudgetExceptionHandler; -import dev.caskeleton.adapter.inbound.web.mvc.budget.WebMvcBudgetFilter; -import dev.caskeleton.adapter.inbound.web.testkit.budget.BudgetFixtureController; -import dev.caskeleton.adapter.inbound.web.testkit.budget.BudgetFixtureProtocol; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.web.servlet.FilterRegistrationBean; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.core.Ordered; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.web.SecurityFilterChain; - -/** - * A servlet application whose only purpose is to have small budgets. - * - *

Separate from the status-contract application on purpose. Installing a 1 KiB body bound there - * would silently constrain every other fixture in it, and a later contract case failing on size - * would look like a status bug. - */ -// Outside `dev.caskeleton.adapter.inbound.web`, which the composition root component-scans. -// A fixture application under that root is loaded into the real deployment: its permit-all -// SecurityFilterChain shadows the real one and the context fails to start with an unreachable -// filter chain. @TestConfiguration would exclude it from scanning but is not accepted by -// @SpringBootTest(classes = ...), so the package is what keeps it out. -@Configuration(proxyBeanMethods = false) -@EnableAutoConfiguration -@Import({BudgetFixtureController.class, WebMvcBudgetExceptionHandler.class}) -public class BudgetFixtureApplication { - - /** - * The budget filter, ahead of everything that reads the request. - * - *

{@code HIGHEST_PRECEDENCE} is the requirement rather than a preference: a bound applied - * after another filter has read the body has already let the body in. - */ - @Bean - FilterRegistrationBean budgetFilter() { - FilterRegistrationBean registration = - new FilterRegistrationBean<>( - new WebMvcBudgetFilter( - BudgetFixtureProtocol.budget(), - budgetProblemMapper(), - WebObjectMapperFactory.standardJsonMapper())); - registration.setOrder(Ordered.HIGHEST_PRECEDENCE); - return registration; - } - - /** Renders a bound crossed inside the handler. */ - @Bean - BudgetProblemMapper budgetProblemMapper() { - return new BudgetProblemMapper(WebProblemFactory.standard()); - } - - /** - * Every fixture route is open. - * - *

The leaf carries the security starter, so without this the lane answers 401 and proves - * nothing about budgets. It is a fixture in the test tree and reaches no deployment. - */ - @Bean - SecurityFilterChain budgetFixtureSecurity(HttpSecurity http) throws Exception { - return http.csrf(csrf -> csrf.disable()) - .authorizeHttpRequests(requests -> requests.anyRequest().permitAll()) - .build(); - } -} diff --git a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/webtestkit/ContractFixtureApplication.java b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/webtestkit/ContractFixtureApplication.java index 11d949b8..ef393a85 100644 --- a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/webtestkit/ContractFixtureApplication.java +++ b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/webtestkit/ContractFixtureApplication.java @@ -1,11 +1,8 @@ package dev.caskeleton.webtestkit; -import dev.caskeleton.adapter.inbound.web.error.ProblemCatalog; -import dev.caskeleton.adapter.inbound.web.error.WebProblemFactory; -import dev.caskeleton.adapter.inbound.web.mvc.error.WebMvcProblemExceptionHandler; +import dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebAdapterAutoConfiguration; import dev.caskeleton.adapter.inbound.web.testkit.fault.FaultFixtureController; import dev.caskeleton.adapter.inbound.web.testkit.mvc.ContractFixtureController; -import dev.caskeleton.adapter.inbound.web.testkit.operation.OperationFixtureController; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -23,7 +20,14 @@ import org.springframework.security.web.SecurityFilterChain; * *

Auto-configuration is left to Spring Boot's own import registry rather than a hand-written * list: the list would have to be updated every time Boot moves a class between packages, and a - * stale entry fails the gate for a reason that has nothing to do with the contract. + * stale entry fails the gate for a reason that has nothing to do with the contract. That registry + * includes this leaf's {@code WebMvcPlatformAutoConfiguration}, so errors are answered by the + * production {@code GlobalExceptionHandler} as an {@code Envelope}, exactly as a deployment would. + * + *

The one entry left out is this leaf's own {@link WebAdapterAutoConfiguration}: it is the whole + * adapter — the production security chain, its JWT settings, the request-logging filter and the + * composition-root pseudonymizer that filter needs — which is the "sum of the leaf" the paragraph + * above keeps out. Excluded by class, so a rename breaks compilation rather than the gate. */ // Outside `dev.caskeleton.adapter.inbound.web`, which the composition root component-scans. // A fixture application under that root is loaded into the real deployment: its permit-all @@ -31,29 +35,10 @@ import org.springframework.security.web.SecurityFilterChain; // filter chain. @TestConfiguration would exclude it from scanning but is not accepted by // @SpringBootTest(classes = ...), so the package is what keeps it out. @Configuration(proxyBeanMethods = false) -@EnableAutoConfiguration -@Import({ - ContractFixtureController.class, - FaultFixtureController.class, - OperationFixtureController.class, - WebMvcProblemExceptionHandler.class -}) +@EnableAutoConfiguration(exclude = WebAdapterAutoConfiguration.class) +@Import({ContractFixtureController.class, FaultFixtureController.class}) public class ContractFixtureApplication { - /** - * The problem catalog the exception handler publishes through. - * - *

Declared here because the gate is about what a client receives, and without it Spring's own - * {@code ProblemDetail} answers instead — RFC 9457-shaped, so it looks right, and carrying no - * {@code code} for a client to branch on. - */ - @Bean - WebProblemFactory contractProblemFactory() { - return new WebProblemFactory( - ProblemCatalog.standard(), - new dev.caskeleton.adapter.inbound.web.error.WebProblemSanitizer()); - } - /** * Every fixture route is open. * diff --git a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/webtestkit/PipelineOrderFixtureApplication.java b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/webtestkit/PipelineOrderFixtureApplication.java index ad8f6a08..e463b655 100644 --- a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/webtestkit/PipelineOrderFixtureApplication.java +++ b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/webtestkit/PipelineOrderFixtureApplication.java @@ -1,5 +1,6 @@ package dev.caskeleton.webtestkit; +import dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebAdapterAutoConfiguration; import dev.caskeleton.adapter.inbound.web.testkit.order.PipelineOrderFixtureController; import dev.caskeleton.adapter.inbound.web.testkit.order.WebPipelineRecorder; import dev.caskeleton.adapter.inbound.web.testkit.order.WebPipelineStage; @@ -40,7 +41,9 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; // filter chain. @TestConfiguration would exclude it from scanning but is not accepted by // @SpringBootTest(classes = ...), so the package is what keeps it out. @Configuration(proxyBeanMethods = false) -@EnableAutoConfiguration +// Not the adapter's own root: its security chain and filters would be stages this fixture did not +// declare, and the recorded order would be about them rather than the semantic pipeline. +@EnableAutoConfiguration(exclude = WebAdapterAutoConfiguration.class) @Import(PipelineOrderFixtureController.class) public class PipelineOrderFixtureApplication implements WebMvcConfigurer { diff --git a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/webtestkit/ThrottleFixtureApplication.java b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/webtestkit/ThrottleFixtureApplication.java deleted file mode 100644 index d6658e1e..00000000 --- a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/webtestkit/ThrottleFixtureApplication.java +++ /dev/null @@ -1,77 +0,0 @@ -package dev.caskeleton.webtestkit; - -import dev.caskeleton.adapter.inbound.web.error.ThrottleProblemWriter; -import dev.caskeleton.adapter.inbound.web.error.WebProblemFactory; -import dev.caskeleton.adapter.inbound.web.json.WebObjectMapperFactory; -import dev.caskeleton.adapter.inbound.web.mvc.throttle.WebMvcThrottleFilter; -import dev.caskeleton.adapter.inbound.web.ratelimit.RateLimitFailurePolicy; -import dev.caskeleton.adapter.inbound.web.testkit.throttle.CountingRateLimiter; -import dev.caskeleton.adapter.inbound.web.testkit.throttle.ThrottleControlController; -import dev.caskeleton.adapter.inbound.web.testkit.throttle.ThrottleFixtureController; -import dev.caskeleton.adapter.inbound.web.testkit.throttle.ThrottleFixtureProtocol; -import dev.caskeleton.adapter.inbound.web.testkit.throttle.ThrottleFixtureSupport; -import jakarta.servlet.http.HttpServletRequest; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.web.servlet.FilterRegistrationBean; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.core.Ordered; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.web.SecurityFilterChain; - -/** - * A servlet application with a tiny quota and a one-slot write profile. - * - *

The filter is registered for the throttled paths only. Registering it for everything would put - * the control route behind the very quota it exists to reset. - */ -// Outside `dev.caskeleton.adapter.inbound.web`, which the composition root component-scans. -// A fixture application under that root is loaded into the real deployment: its permit-all -// SecurityFilterChain shadows the real one and the context fails to start with an unreachable -// filter chain. @TestConfiguration would exclude it from scanning but is not accepted by -// @SpringBootTest(classes = ...), so the package is what keeps it out. -@Configuration(proxyBeanMethods = false) -@EnableAutoConfiguration -@Import({ThrottleFixtureController.class, ThrottleControlController.class}) -public class ThrottleFixtureApplication { - - /** The quota the lanes exhaust. */ - @Bean - CountingRateLimiter fixtureRateLimiter() { - return new CountingRateLimiter(); - } - - /** The throttle filter, on the throttled paths only. */ - @Bean - FilterRegistrationBean throttleFilter(CountingRateLimiter limiter) { - FilterRegistrationBean registration = - new FilterRegistrationBean<>( - new WebMvcThrottleFilter( - limiter, - ThrottleFixtureSupport.admissionController(), - (HttpServletRequest request) -> - ThrottleFixtureSupport.profileFor(request.getRequestURI()), - request -> ThrottleFixtureSupport.context(), - RateLimitFailurePolicy.FAIL_OPEN, - new ThrottleProblemWriter(WebProblemFactory.standard()), - WebObjectMapperFactory.standardJsonMapper())); - registration.addUrlPatterns( - ThrottleFixtureProtocol.QUOTA_PATH, ThrottleFixtureProtocol.WRITE_PATH); - registration.setOrder(Ordered.HIGHEST_PRECEDENCE); - return registration; - } - - /** - * Every fixture route is open. - * - *

The leaf carries the security starter, so without this the lane answers 401 and proves - * nothing about throttling. It is a fixture in the test tree and reaches no deployment. - */ - @Bean - SecurityFilterChain throttleFixtureSecurity(HttpSecurity http) throws Exception { - return http.csrf(csrf -> csrf.disable()) - .authorizeHttpRequests(requests -> requests.anyRequest().permitAll()) - .build(); - } -} diff --git a/src/adapter/inbound/web/src/testFixtures/resources/application-web-contract.yaml b/src/adapter/inbound/web/src/testFixtures/resources/application-web-contract.yaml index e5fcde1a..e7a8f90d 100644 --- a/src/adapter/inbound/web/src/testFixtures/resources/application-web-contract.yaml +++ b/src/adapter/inbound/web/src/testFixtures/resources/application-web-contract.yaml @@ -7,8 +7,9 @@ spring: main: banner-mode: "off" mvc: + # The shipped contract: errors are the Envelope GlobalExceptionHandler writes, not RFC 9457. problemdetails: - enabled: true + enabled: false server: error: include-stacktrace: never diff --git a/src/adapter/inbound/web/src/webfluxContractTest/java/dev/caskeleton/adapter/inbound/web/testkit/budget/ReactiveBudgetFixtureApplication.java b/src/adapter/inbound/web/src/webfluxContractTest/java/dev/caskeleton/adapter/inbound/web/testkit/budget/ReactiveBudgetFixtureApplication.java deleted file mode 100644 index 599a066e..00000000 --- a/src/adapter/inbound/web/src/webfluxContractTest/java/dev/caskeleton/adapter/inbound/web/testkit/budget/ReactiveBudgetFixtureApplication.java +++ /dev/null @@ -1,44 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.testkit.budget; - -import dev.caskeleton.adapter.inbound.web.error.BudgetProblemMapper; -import dev.caskeleton.adapter.inbound.web.error.WebProblemFactory; -import dev.caskeleton.adapter.inbound.web.json.WebObjectMapperFactory; -import dev.caskeleton.adapter.inbound.web.webflux.budget.WebFluxBudgetFilter; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.core.Ordered; -import org.springframework.core.annotation.Order; - -/** - * A reactive application with the same small budgets. - * - *

Lives in this lane rather than the shared testkit for the reason the reactive contract app - * does: this lane deliberately has no security starter on its classpath, so an application here - * cannot declare a permit-all chain and does not need one. - */ -// @Configuration, not @TestConfiguration: this source set is never on the application's runtime -// classpath, so nothing here can be component-scanned into a deployment — and @TestConfiguration -// types are not accepted by @SpringBootTest(classes = ...). -@Configuration(proxyBeanMethods = false) -@EnableAutoConfiguration -@Import(ReactiveBudgetFixtureController.class) -public class ReactiveBudgetFixtureApplication { - - /** - * The budget filter, ahead of everything that reads the request. - * - *

A {@code WebFilter} bean is ordered by {@code @Order} on the bean method; the precedence - * matters for the same reason as on the servlet side — a bound applied after another filter has - * consumed the body has already let the body in. - */ - @Bean - @Order(Ordered.HIGHEST_PRECEDENCE) - WebFluxBudgetFilter budgetFilter() { - return new WebFluxBudgetFilter( - BudgetFixtureProtocol.budget(), - new BudgetProblemMapper(WebProblemFactory.standard()), - WebObjectMapperFactory.standardJsonMapper()); - } -} diff --git a/src/adapter/inbound/web/src/webfluxContractTest/java/dev/caskeleton/adapter/inbound/web/testkit/budget/ReactiveWebBudgetIT.java b/src/adapter/inbound/web/src/webfluxContractTest/java/dev/caskeleton/adapter/inbound/web/testkit/budget/ReactiveWebBudgetIT.java deleted file mode 100644 index 4bfb455b..00000000 --- a/src/adapter/inbound/web/src/webfluxContractTest/java/dev/caskeleton/adapter/inbound/web/testkit/budget/ReactiveWebBudgetIT.java +++ /dev/null @@ -1,29 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.testkit.budget; - -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.web.server.LocalServerPort; -import org.springframework.test.context.ActiveProfiles; - -/** - * Budget enforcement on Reactor Netty. - * - *

The reactive stack is where the streaming requirement stops being advice: a body here is a - * publisher that may never be in memory whole, so a bound that needed to measure it would have to - * buffer the very request it exists to refuse. - */ -@SpringBootTest( - classes = ReactiveBudgetFixtureApplication.class, - webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, - // The budget handler is gated on this property. Turning it on here rather than defaulting it - // on keeps the production default off: a control that is on by default is one nobody notices. - properties = "backend.web.budgets.enabled=true") -@ActiveProfiles("web-contract") -class ReactiveWebBudgetIT extends WebBudgetContract { - - @LocalServerPort private int port; - - @Override - protected HttpBudgetFixture fixture() { - return new HttpBudgetFixture(port); - } -} diff --git a/src/adapter/inbound/web/src/webfluxContractTest/java/dev/caskeleton/adapter/inbound/web/testkit/contract/ReactiveContractRecordingIT.java b/src/adapter/inbound/web/src/webfluxContractTest/java/dev/caskeleton/adapter/inbound/web/testkit/contract/ReactiveContractRecordingIT.java deleted file mode 100644 index b7c13ca2..00000000 --- a/src/adapter/inbound/web/src/webfluxContractTest/java/dev/caskeleton/adapter/inbound/web/testkit/contract/ReactiveContractRecordingIT.java +++ /dev/null @@ -1,26 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.testkit.contract; - -import dev.caskeleton.adapter.inbound.web.testkit.webflux.ReactiveContractFixtureApplication; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.web.server.LocalServerPort; -import org.springframework.test.context.ActiveProfiles; - -/** Records the wire contract as Reactor Netty serves it. */ -@SpringBootTest( - classes = ReactiveContractFixtureApplication.class, - webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -@ActiveProfiles("web-contract") -class ReactiveContractRecordingIT extends WebPlatformContractRecording { - - @LocalServerPort private int port; - - @Override - protected WebContractFixture fixture() { - return new WebContractFixture(port); - } - - @Override - protected String laneName() { - return "reactor-netty"; - } -} diff --git a/src/adapter/inbound/web/src/webfluxContractTest/java/dev/caskeleton/adapter/inbound/web/testkit/fault/ReactiveCommitThenConnectionResetIT.java b/src/adapter/inbound/web/src/webfluxContractTest/java/dev/caskeleton/adapter/inbound/web/testkit/fault/ReactiveCommitThenConnectionResetIT.java deleted file mode 100644 index b7ec651a..00000000 --- a/src/adapter/inbound/web/src/webfluxContractTest/java/dev/caskeleton/adapter/inbound/web/testkit/fault/ReactiveCommitThenConnectionResetIT.java +++ /dev/null @@ -1,28 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.testkit.fault; - -import dev.caskeleton.adapter.inbound.web.testkit.webflux.ReactiveContractFixtureApplication; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.web.server.LocalServerPort; -import org.springframework.test.context.ActiveProfiles; - -/** - * The response-loss contract on Reactor Netty. - * - *

The reactive stack is where this guarantee is easiest to lose: the handler returns a publisher - * long before the response is written, so "the application committed" and "the client got an - * answer" are separated by a stretch of pipeline that has no equivalent in the servlet path. The - * assertions are the shared ones, so the two stacks are held to one contract rather than two. - */ -@SpringBootTest( - classes = ReactiveContractFixtureApplication.class, - webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -@ActiveProfiles("web-contract") -class ReactiveCommitThenConnectionResetIT extends IdempotencyResponseLossContract { - - @LocalServerPort private int port; - - @Override - protected ResponseLossFixture fixture() { - return new HttpResponseLossFixture(port); - } -} diff --git a/src/adapter/inbound/web/src/webfluxContractTest/java/dev/caskeleton/adapter/inbound/web/testkit/operation/ReactiveOperationHttpIT.java b/src/adapter/inbound/web/src/webfluxContractTest/java/dev/caskeleton/adapter/inbound/web/testkit/operation/ReactiveOperationHttpIT.java deleted file mode 100644 index 234ae235..00000000 --- a/src/adapter/inbound/web/src/webfluxContractTest/java/dev/caskeleton/adapter/inbound/web/testkit/operation/ReactiveOperationHttpIT.java +++ /dev/null @@ -1,27 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.testkit.operation; - -import dev.caskeleton.adapter.inbound.web.testkit.webflux.ReactiveContractFixtureApplication; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.web.server.LocalServerPort; -import org.springframework.test.context.ActiveProfiles; - -/** - * The operation resource contract on Reactor Netty. - * - *

The reactive controller builds its response inside a {@code map} rather than returning it - * directly, which is exactly where a conditional header is easiest to drop. The shared contract is - * what catches that without anybody having to remember to re-check it here. - */ -@SpringBootTest( - classes = ReactiveContractFixtureApplication.class, - webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -@ActiveProfiles("web-contract") -class ReactiveOperationHttpIT extends OperationHttpContract { - - @LocalServerPort private int port; - - @Override - protected HttpOperationFixture fixture() { - return new HttpOperationFixture(port); - } -} diff --git a/src/adapter/inbound/web/src/webfluxContractTest/java/dev/caskeleton/adapter/inbound/web/testkit/order/ReactivePipelineOrderFixtureApplication.java b/src/adapter/inbound/web/src/webfluxContractTest/java/dev/caskeleton/adapter/inbound/web/testkit/order/ReactivePipelineOrderFixtureApplication.java deleted file mode 100644 index 5d34c578..00000000 --- a/src/adapter/inbound/web/src/webfluxContractTest/java/dev/caskeleton/adapter/inbound/web/testkit/order/ReactivePipelineOrderFixtureApplication.java +++ /dev/null @@ -1,93 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.testkit.order; - -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.core.Ordered; -import org.springframework.core.annotation.Order; -import org.springframework.web.server.ServerWebExchange; -import org.springframework.web.server.WebFilter; -import org.springframework.web.server.WebFilterChain; -import reactor.core.publisher.Mono; - -/** - * The reactive pipeline fixture. - * - *

The reactive stack has no ASYNC redispatch — every request is asynchronous and the chain runs - * once — so the duplicate-observation hazard takes a different shape here. Completion is recorded - * in {@code doFinally} on the returned publisher, because the request is over when the publisher - * terminates and not when {@code filter} returns. Recording at the end of the method would log a - * completion for a response still being written, which is the same wrong number arrived at from the - * opposite direction. - */ -// @Configuration, not @TestConfiguration: this source set is never on the application's runtime -// classpath, so nothing here can be component-scanned into a deployment — and @TestConfiguration -// types are not accepted by @SpringBootTest(classes = ...). -@Configuration(proxyBeanMethods = false) -@EnableAutoConfiguration -@Import(ReactivePipelineOrderFixtureController.class) -public class ReactivePipelineOrderFixtureApplication { - - private final WebPipelineRecorder recorder = new WebPipelineRecorder(); - - /** The recorder the fixture writes to. */ - @Bean - WebPipelineRecorder pipelineRecorder() { - return recorder; - } - - /** The pre-routing stages, and the completion. */ - @Bean - @Order(Ordered.HIGHEST_PRECEDENCE) - WebFilter pipelineEdgeFilter() { - return (ServerWebExchange exchange, WebFilterChain chain) -> { - String path = exchange.getRequest().getURI().getRawPath(); - if (isControlRoute(path)) { - return chain.filter(exchange); - } - recorder.record(WebPipelineStage.FORWARDED_NORMALIZATION); - recorder.record(WebPipelineStage.CORS); - recorder.record(WebPipelineStage.TRACE); - recorder.record(WebPipelineStage.AUTHENTICATION); - recorder.record(WebPipelineStage.GLOBAL_ADMISSION); - return chain - .filter(exchange) - .doFinally( - signal -> { - recorder.record(WebPipelineStage.RESPONSE_OR_PROBLEM); - recorder.record(WebPipelineStage.OBSERVATION); - }); - }; - } - - /** - * The route-scoped stages. - * - *

Ordered after the edge filter and registered as a second filter rather than an interceptor, - * because WebFlux has no {@code HandlerInterceptor}. It reads the handler out of the exchange - * attributes, which are populated by the handler mapping — so, as on the servlet side, reaching - * this point is itself the evidence that the route was selected. - */ - @Bean - @Order(Ordered.HIGHEST_PRECEDENCE + 1) - WebFilter pipelineRouteFilter() { - return (ServerWebExchange exchange, WebFilterChain chain) -> { - String path = exchange.getRequest().getURI().getRawPath(); - if (isControlRoute(path)) { - return chain.filter(exchange); - } - return Mono.fromRunnable( - () -> { - recorder.record(WebPipelineStage.ROUTE_SELECTED); - recorder.record(WebPipelineStage.ROUTE_POLICY); - }) - .then(chain.filter(exchange)); - }; - } - - private static boolean isControlRoute(String path) { - return path.startsWith(PipelineOrderFixtureController.OBSERVED_PATH) - || path.startsWith(PipelineOrderFixtureController.RESET_PATH); - } -} diff --git a/src/adapter/inbound/web/src/webfluxContractTest/java/dev/caskeleton/adapter/inbound/web/testkit/order/ReactivePipelineOrderFixtureController.java b/src/adapter/inbound/web/src/webfluxContractTest/java/dev/caskeleton/adapter/inbound/web/testkit/order/ReactivePipelineOrderFixtureController.java deleted file mode 100644 index 914c6c98..00000000 --- a/src/adapter/inbound/web/src/webfluxContractTest/java/dev/caskeleton/adapter/inbound/web/testkit/order/ReactivePipelineOrderFixtureController.java +++ /dev/null @@ -1,87 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.testkit.order; - -import jakarta.validation.Valid; -import jakarta.validation.constraints.NotBlank; -import java.time.Duration; -import org.springframework.http.MediaType; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RestController; -import reactor.core.publisher.Mono; -import reactor.core.scheduler.Schedulers; - -/** - * The reactive routes the pipeline contract drives. - * - *

The "async" route defers onto another scheduler. On this stack every request is already - * asynchronous, so what this route adds is a thread hop between binding and the controller body — - * which is where a recorder tied to thread-local state, rather than to the request, would start - * losing or duplicating stages. - */ -@RestController -public class ReactivePipelineOrderFixtureController { - - /** A body with one constraint, so binding and validation genuinely happen. */ - public record PipelineRequest(@NotBlank String name) {} - - private final WebPipelineRecorder recorder; - - /** - * A controller over the recorder. - * - * @param recorder where stages are written - */ - public ReactivePipelineOrderFixtureController(WebPipelineRecorder recorder) { - this.recorder = recorder; - } - - /** Runs without a thread hop. */ - @PostMapping( - path = PipelineOrderFixtureController.SYNC_PATH, - consumes = MediaType.APPLICATION_JSON_VALUE, - produces = MediaType.APPLICATION_JSON_VALUE) - public Mono sync(@Valid @RequestBody PipelineRequest request) { - recorder.record(WebPipelineStage.BINDING_VALIDATION); - return Mono.fromSupplier( - () -> { - recorder.record(WebPipelineStage.CONTROLLER); - return "\"" + request.name() + "\""; - }); - } - - /** Runs after a thread hop and a delay. */ - @PostMapping( - path = PipelineOrderFixtureController.ASYNC_PATH, - consumes = MediaType.APPLICATION_JSON_VALUE, - produces = MediaType.APPLICATION_JSON_VALUE) - public Mono async(@Valid @RequestBody PipelineRequest request) { - recorder.record(WebPipelineStage.BINDING_VALIDATION); - return Mono.fromSupplier( - () -> { - recorder.record(WebPipelineStage.CONTROLLER); - return "\"" + request.name() + "\""; - }) - .delayElement(Duration.ofMillis(20)) - .subscribeOn(Schedulers.boundedElastic()); - } - - /** The stages observed so far. */ - @GetMapping( - path = PipelineOrderFixtureController.OBSERVED_PATH, - produces = MediaType.TEXT_PLAIN_VALUE) - public Mono observed() { - return Mono.fromSupplier( - () -> String.join(",", recorder.observed().stream().map(Enum::name).toList())); - } - - /** Clears the recorder. */ - @PostMapping(PipelineOrderFixtureController.RESET_PATH) - public Mono reset() { - return Mono.fromSupplier( - () -> { - recorder.reset(); - return ""; - }); - } -} diff --git a/src/adapter/inbound/web/src/webfluxContractTest/java/dev/caskeleton/adapter/inbound/web/testkit/order/WebFluxPipelineOrderIT.java b/src/adapter/inbound/web/src/webfluxContractTest/java/dev/caskeleton/adapter/inbound/web/testkit/order/WebFluxPipelineOrderIT.java deleted file mode 100644 index cc94256d..00000000 --- a/src/adapter/inbound/web/src/webfluxContractTest/java/dev/caskeleton/adapter/inbound/web/testkit/order/WebFluxPipelineOrderIT.java +++ /dev/null @@ -1,27 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.testkit.order; - -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.web.server.LocalServerPort; -import org.springframework.test.context.ActiveProfiles; - -/** - * Pipeline order on Reactor Netty. - * - *

Same contract, different hazard. There is no redispatch here, so the way to observe a request - * twice — or zero times — is to tie completion to the filter method returning rather than to the - * publisher terminating. The shared cases catch both shapes without either lane having to describe - * the other's. - */ -@SpringBootTest( - classes = ReactivePipelineOrderFixtureApplication.class, - webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -@ActiveProfiles("web-contract") -class WebFluxPipelineOrderIT extends WebPipelineOrderContract { - - @LocalServerPort private int port; - - @Override - protected HttpPipelineFixture fixture() { - return new HttpPipelineFixture(port); - } -} diff --git a/src/adapter/inbound/web/src/webfluxContractTest/java/dev/caskeleton/adapter/inbound/web/testkit/performance/ReactorNettyLoadAndShutdownIT.java b/src/adapter/inbound/web/src/webfluxContractTest/java/dev/caskeleton/adapter/inbound/web/testkit/performance/ReactorNettyLoadAndShutdownIT.java deleted file mode 100644 index 7ba4fa67..00000000 --- a/src/adapter/inbound/web/src/webfluxContractTest/java/dev/caskeleton/adapter/inbound/web/testkit/performance/ReactorNettyLoadAndShutdownIT.java +++ /dev/null @@ -1,68 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.testkit.performance; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.adapter.inbound.web.testkit.webflux.ReactiveContractFixtureApplication; -import java.time.Duration; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.web.server.LocalServerPort; -import org.springframework.boot.web.server.reactive.context.ReactiveWebServerApplicationContext; -import org.springframework.test.context.ActiveProfiles; - -/** - * Load, abuse and graceful shutdown on Reactor Netty. - * - *

The slow-client case means something different here and is worth running for that reason. An - * event-loop server does not allocate a thread per connection, so half-open connections cost it far - * less — but they still consume file descriptors and buffers, and "cheaper" is not "free". The - * bound is what is being checked, not the mechanism. - */ -@SpringBootTest( - classes = ReactiveContractFixtureApplication.class, - webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, - properties = "server.shutdown=graceful") -@ActiveProfiles("web-contract") -class ReactorNettyLoadAndShutdownIT extends WebLoadAndShutdownContract { - - @LocalServerPort private int port; - - @Autowired private ReactiveWebServerApplicationContext context; - - @Override - protected WebLoadFixture fixture() { - return new WebLoadFixture(port); - } - - @Override - protected String loadPath() { - return "/api/v1/fixtures/f1"; - } - - @Override - protected org.springframework.boot.web.server.WebServer webServer() { - return context.getWebServer(); - } - - @Test - @Tag("web-shutdown") - @DisplayName("graceful shutdown drains within the deployment's grace period") - void gracefulShutdownFinishesInFlightWork() { - // Last, and destructive: the context serves nothing afterwards. - WebLoadFixture fixture = fixture(); - assertThat(fixture.stillServing(loadPath())).isTrue(); - - GracefulShutdownProbe.Outcome outcome = - GracefulShutdownProbe.shutDown(webServer(), Duration.ofSeconds(10)); - - // Bounded on purpose. A shutdown that waits indefinitely for a connection to go idle is how a - // rolling deploy stalls with half the fleet drained — and it produces no error to alert on. - assertThat(outcome.took()).isLessThan(Duration.ofSeconds(15)); - assertThat(fixture.stillServing(loadPath())) - .as("the server accepted a new request after it was told to stop") - .isFalse(); - } -} diff --git a/src/adapter/inbound/web/src/webfluxContractTest/java/dev/caskeleton/adapter/inbound/web/testkit/streaming/ReactiveSseFixtureApplication.java b/src/adapter/inbound/web/src/webfluxContractTest/java/dev/caskeleton/adapter/inbound/web/testkit/streaming/ReactiveSseFixtureApplication.java deleted file mode 100644 index 7dc85dcc..00000000 --- a/src/adapter/inbound/web/src/webfluxContractTest/java/dev/caskeleton/adapter/inbound/web/testkit/streaming/ReactiveSseFixtureApplication.java +++ /dev/null @@ -1,81 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.testkit.streaming; - -import dev.caskeleton.adapter.inbound.web.advanced.stream.StreamId; -import dev.caskeleton.adapter.inbound.web.advanced.stream.StreamSequence; -import dev.caskeleton.adapter.inbound.web.advanced.stream.WebStreamEnvelope; -import dev.caskeleton.adapter.inbound.web.advanced.stream.WebStreamPolicy; -import dev.caskeleton.adapter.inbound.web.advanced.webflux.WebFluxSseAdapter; -import java.time.Duration; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.MediaType; -import org.springframework.http.codec.ServerSentEvent; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RestController; -import reactor.core.publisher.Flux; - -/** - * A reactive application that serves one SSE route through the Advanced adapter. - * - *

Exists so the adapter is exercised over a real socket rather than through {@code - * StepVerifier}. The two prove different things: the verifier proves the operator chain, and this - * proves that what reaches a client is an SSE stream a client can read — event names, ids, and a - * terminal event that actually arrives before the connection closes. - */ -@Configuration(proxyBeanMethods = false) -@EnableAutoConfiguration -public class ReactiveSseFixtureApplication { - - /** The stream every route here serves. */ - public static final StreamId STREAM = new StreamId("contract-feed"); - - /** How many items the finite route emits before completing. */ - public static final int ITEM_COUNT = 3; - - /** A short heartbeat so the keepalive is observable inside a test's patience. */ - static WebStreamPolicy policy() { - return new WebStreamPolicy( - Duration.ofMillis(200), Duration.ofSeconds(30), Duration.ofMinutes(5), 64, 262_144); - } - - // No @Bean for the controller below: a nested @RestController inside a @Configuration is - // registered by the configuration class itself, and declaring it again maps every route twice. - - /** Serves a finite stream and a quiet one. */ - @RestController - public static class ReactiveSseFixtureController { - - private final WebFluxSseAdapter adapter = new WebFluxSseAdapter(policy()); - - /** A stream that emits three items and then completes properly. */ - @GetMapping(path = "/contract/sse/finite", produces = MediaType.TEXT_EVENT_STREAM_VALUE) - public Flux>> finite() { - Flux> source = - Flux.range(1, ITEM_COUNT) - .map( - index -> - (WebStreamEnvelope) - new WebStreamEnvelope.Item<>( - STREAM, new StreamSequence(index), "item-" + index)) - .concatWith( - Flux.just( - new WebStreamEnvelope.Complete<>(STREAM, new StreamSequence(ITEM_COUNT)))); - return adapter.adapt(source); - } - - /** - * A stream that emits one item and then says nothing. - * - *

Never completes on its own, so what a client sees after the first item is entirely the - * heartbeat. That is the case a keepalive exists for and the one a finite stream cannot show. - */ - @GetMapping(path = "/contract/sse/quiet", produces = MediaType.TEXT_EVENT_STREAM_VALUE) - public Flux>> quiet() { - Flux> source = - Flux.>just( - new WebStreamEnvelope.Item<>(STREAM, StreamSequence.first(), "only")) - .concatWith(Flux.never()); - return adapter.adapt(source); - } - } -} diff --git a/src/adapter/inbound/web/src/webfluxContractTest/java/dev/caskeleton/adapter/inbound/web/testkit/streaming/WebFluxSseContractIT.java b/src/adapter/inbound/web/src/webfluxContractTest/java/dev/caskeleton/adapter/inbound/web/testkit/streaming/WebFluxSseContractIT.java deleted file mode 100644 index e1328f9d..00000000 --- a/src/adapter/inbound/web/src/webfluxContractTest/java/dev/caskeleton/adapter/inbound/web/testkit/streaming/WebFluxSseContractIT.java +++ /dev/null @@ -1,120 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.testkit.streaming; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.net.URI; -import java.net.http.HttpClient; -import java.net.http.HttpRequest; -import java.net.http.HttpResponse; -import java.time.Duration; -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Stream; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.web.server.LocalServerPort; - -/** - * The reactive SSE adapter over a real socket. - * - *

{@code StepVerifier} proves the operator chain assembles correctly. It cannot prove that what - * arrives at a client is a readable {@code text/event-stream} — the framing, the event names, the - * ids a client sends back as {@code Last-Event-ID}, and above all that the terminal event actually - * reaches the wire before the connection closes. That last one is the whole contract: a client that - * sees a closed connection with no terminal event has been cut off, and it must be able to tell. - * - *

Reactor Netty, not a mock exchange. Chunked framing, flush timing and connection close on - * completion are all server code. - */ -@SpringBootTest( - classes = ReactiveSseFixtureApplication.class, - webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -class WebFluxSseContractIT { - - @LocalServerPort private int port; - - @Test - @DisplayName("a finite stream ends with a complete event and then closes") - void finiteStreamEndsWithACompleteEvent() throws Exception { - List lines = read("/contract/sse/finite", Duration.ofSeconds(20)); - - // The connection closed on its own, which only happens because the adapter stops at the - // terminal envelope. Without takeUntil the heartbeat would hold it for the full maximum age. - assertThat(eventsIn(lines)).containsExactly("item", "item", "item", "complete"); - } - - @Test - @DisplayName("only items carry an id, so a resume never continues a finished stream") - void onlyItemsCarryAnId() throws Exception { - List lines = read("/contract/sse/finite", Duration.ofSeconds(20)); - - // The ids a browser's EventSource will send back as Last-Event-ID. A terminal event carrying - // one would have a client ask to continue a stream that had already ended. - assertThat(idsIn(lines)).containsExactly("1", "2", "3"); - } - - @Test - @DisplayName("the payload is the envelope, readable as JSON") - void payloadIsTheEnvelope() throws Exception { - List lines = read("/contract/sse/finite", Duration.ofSeconds(20)); - - assertThat(lines).anyMatch(line -> line.startsWith("data:") && line.contains("item-1")); - assertThat(lines).anyMatch(line -> line.startsWith("data:") && line.contains("contract-feed")); - } - - @Test - @DisplayName("a quiet stream is kept alive by heartbeats rather than going silent") - void quietStreamIsKeptAlive() throws Exception { - // On a socket a silent connection and a dead one are the same thing, and the heartbeat is what - // separates them. Read for long enough that several beats must have been due. - List lines = read("/contract/sse/quiet", Duration.ofSeconds(3)); - - assertThat(eventsIn(lines)).contains("item"); - assertThat(lines) - .as("the keepalive is a comment line, which is what SSE defines for one") - .anyMatch(line -> line.startsWith(":") || line.contains("heartbeat")); - } - - /** - * Reads the stream until it closes or the budget runs out. - * - *

A budget rather than a completion wait, because one of these routes never completes — and a - * test that waited for completion on it would hang rather than fail. - */ - private List read(String path, Duration budget) throws Exception { - HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build(); - HttpRequest request = - HttpRequest.newBuilder(URI.create("http://localhost:" + port + path)) - .header("Accept", "text/event-stream") - .timeout(budget) - .GET() - .build(); - List lines = new ArrayList<>(); - HttpResponse> response = - client.send(request, HttpResponse.BodyHandlers.ofLines()); - assertThat(response.statusCode()).isEqualTo(200); - assertThat(response.headers().firstValue("content-type").orElse("")) - .startsWith("text/event-stream"); - long deadline = System.nanoTime() + budget.toNanos(); - var iterator = response.body().iterator(); - while (System.nanoTime() < deadline && iterator.hasNext()) { - lines.add(iterator.next()); - } - return lines; - } - - private static List eventsIn(List lines) { - return lines.stream() - .filter(line -> line.startsWith("event:")) - .map(line -> line.substring("event:".length()).trim()) - .toList(); - } - - private static List idsIn(List lines) { - return lines.stream() - .filter(line -> line.startsWith("id:")) - .map(line -> line.substring("id:".length()).trim()) - .toList(); - } -} diff --git a/src/adapter/inbound/web/src/webfluxContractTest/java/dev/caskeleton/adapter/inbound/web/testkit/throttle/ReactiveThrottleFixtureApplication.java b/src/adapter/inbound/web/src/webfluxContractTest/java/dev/caskeleton/adapter/inbound/web/testkit/throttle/ReactiveThrottleFixtureApplication.java deleted file mode 100644 index c3eca519..00000000 --- a/src/adapter/inbound/web/src/webfluxContractTest/java/dev/caskeleton/adapter/inbound/web/testkit/throttle/ReactiveThrottleFixtureApplication.java +++ /dev/null @@ -1,62 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.testkit.throttle; - -import dev.caskeleton.adapter.inbound.web.error.ThrottleProblemWriter; -import dev.caskeleton.adapter.inbound.web.error.WebProblemFactory; -import dev.caskeleton.adapter.inbound.web.json.WebObjectMapperFactory; -import dev.caskeleton.adapter.inbound.web.ratelimit.RateLimitFailurePolicy; -import dev.caskeleton.adapter.inbound.web.webflux.throttle.WebFluxThrottleFilter; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.core.Ordered; -import org.springframework.web.server.ServerWebExchange; -import org.springframework.web.server.WebFilter; -import org.springframework.web.server.WebFilterChain; -import reactor.core.scheduler.Schedulers; - -/** - * The reactive throttle application. - * - *

The filter is wrapped in a path guard rather than registered for specific URLs, because a - * {@code WebFilter} has no URL patterns. Without the guard the control route would sit behind the - * quota it exists to reset, and every case after the first would fail for the wrong reason. - */ -// @Configuration, not @TestConfiguration: this source set is never on the application's runtime -// classpath, so nothing here can be component-scanned into a deployment — and @TestConfiguration -// types are not accepted by @SpringBootTest(classes = ...). -@Configuration(proxyBeanMethods = false) -@EnableAutoConfiguration -@Import({ThrottleFixtureController.class, ThrottleControlController.class}) -public class ReactiveThrottleFixtureApplication { - - /** The quota the lanes exhaust. */ - @Bean - CountingRateLimiter fixtureRateLimiter() { - return new CountingRateLimiter(); - } - - /** The throttle filter, applied to the throttled paths only. */ - @Bean - @org.springframework.core.annotation.Order(Ordered.HIGHEST_PRECEDENCE) - WebFilter throttleFilter(CountingRateLimiter limiter) { - WebFluxThrottleFilter throttle = - new WebFluxThrottleFilter( - limiter, - ThrottleFixtureSupport.admissionController(), - (ServerWebExchange exchange) -> - ThrottleFixtureSupport.profileFor(exchange.getRequest().getURI().getRawPath()), - exchange -> ThrottleFixtureSupport.context(), - RateLimitFailurePolicy.FAIL_OPEN, - new ThrottleProblemWriter(WebProblemFactory.standard()), - WebObjectMapperFactory.standardJsonMapper(), - Schedulers.boundedElastic()); - return (ServerWebExchange exchange, WebFilterChain chain) -> { - String path = exchange.getRequest().getURI().getRawPath(); - boolean throttled = - path.startsWith(ThrottleFixtureProtocol.QUOTA_PATH) - || path.startsWith(ThrottleFixtureProtocol.WRITE_PATH); - return throttled ? throttle.filter(exchange, chain) : chain.filter(exchange); - }; - } -} diff --git a/src/adapter/inbound/web/src/webfluxContractTest/java/dev/caskeleton/adapter/inbound/web/testkit/throttle/ReactiveWebThrottleIT.java b/src/adapter/inbound/web/src/webfluxContractTest/java/dev/caskeleton/adapter/inbound/web/testkit/throttle/ReactiveWebThrottleIT.java deleted file mode 100644 index 62e75401..00000000 --- a/src/adapter/inbound/web/src/webfluxContractTest/java/dev/caskeleton/adapter/inbound/web/testkit/throttle/ReactiveWebThrottleIT.java +++ /dev/null @@ -1,42 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.testkit.throttle; - -import org.junit.jupiter.api.AfterEach; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.web.server.LocalServerPort; -import org.springframework.test.context.ActiveProfiles; - -/** - * Quota and capacity refusals on Reactor Netty. - * - *

This lane is where the permit-release contract is actually at risk. A reactive request is not - * over when the filter method returns; it is over when the publisher terminates. A permit released - * at the wrong one of those two moments hands the slot back while the request is still running, and - * the concurrency bound stops bounding anything — invisibly, until the service is loaded enough for - * it to matter. - */ -@SpringBootTest( - classes = ReactiveThrottleFixtureApplication.class, - webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -@ActiveProfiles("web-contract") -class ReactiveWebThrottleIT extends WebThrottleHttpContract { - - @LocalServerPort private int port; - - private HttpThrottleFixture fixture; - - @Override - protected HttpThrottleFixture fixture() { - if (fixture == null) { - fixture = new HttpThrottleFixture(port); - } - return fixture; - } - - @AfterEach - void closeFixture() { - if (fixture != null) { - fixture.close(); - fixture = null; - } - } -} diff --git a/src/adapter/inbound/web/src/webfluxContractTest/java/dev/caskeleton/adapter/inbound/web/testkit/webflux/ReactiveContractFixtureApplication.java b/src/adapter/inbound/web/src/webfluxContractTest/java/dev/caskeleton/adapter/inbound/web/testkit/webflux/ReactiveContractFixtureApplication.java deleted file mode 100644 index 7e557f58..00000000 --- a/src/adapter/inbound/web/src/webfluxContractTest/java/dev/caskeleton/adapter/inbound/web/testkit/webflux/ReactiveContractFixtureApplication.java +++ /dev/null @@ -1,54 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.testkit.webflux; - -import dev.caskeleton.adapter.inbound.web.error.ProblemCatalog; -import dev.caskeleton.adapter.inbound.web.error.WebProblemFactory; -import dev.caskeleton.adapter.inbound.web.error.WebProblemSanitizer; -import dev.caskeleton.adapter.inbound.web.testkit.fault.ReactiveFaultFixtureController; -import dev.caskeleton.adapter.inbound.web.testkit.operation.ReactiveOperationFixtureController; -import dev.caskeleton.adapter.inbound.web.webflux.error.WebFluxProblemExceptionHandler; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; - -/** - * The smallest reactive application that can serve the contract fixtures. - * - *

No component scan and no security starter on this lane's classpath. Both are deliberate: the - * gate is about the status contract on the wire, and a default security chain answering 401 would - * make every assertion here fail for a reason that has nothing to do with the contract. - * - *

Declaring a permit-all chain instead was tried and is worse. Boot's reactive security - * auto-configuration and {@code @EnableWebFluxSecurity} each register {@code - * conversionServicePostProcessor}, so having both fails the context before a route runs, and having - * only the auto-configuration leaves its default chain in place. Removing the dependency removes - * the question. - * - *

It lives in this lane's source set rather than the shared testkit for the same reason: the - * servlet gate needs a security chain and this one needs no security at all, so a shared fixture - * would have to satisfy both. - */ -// @Configuration, not @TestConfiguration: this source set is never on the application's runtime -// classpath, so nothing here can be component-scanned into a deployment — and @TestConfiguration -// types are not accepted by @SpringBootTest(classes = ...). -@Configuration(proxyBeanMethods = false) -@EnableAutoConfiguration -@Import({ - ReactiveContractFixtureController.class, - ReactiveFaultFixtureController.class, - ReactiveOperationFixtureController.class, - WebFluxProblemExceptionHandler.class -}) -public class ReactiveContractFixtureApplication { - - /** - * The problem catalog the exception handler publishes through. - * - *

The same catalog the servlet gate uses. Two catalogs would make the parity recording agree - * about a contract neither stack actually shares with a deployment. - */ - @Bean - WebProblemFactory contractProblemFactory() { - return new WebProblemFactory(ProblemCatalog.standard(), new WebProblemSanitizer()); - } -} diff --git a/src/adapter/inbound/web/src/webfluxContractTest/java/dev/caskeleton/adapter/inbound/web/testkit/webflux/ReactorNettyWebContractIT.java b/src/adapter/inbound/web/src/webfluxContractTest/java/dev/caskeleton/adapter/inbound/web/testkit/webflux/ReactorNettyWebContractIT.java deleted file mode 100644 index c2717c7d..00000000 --- a/src/adapter/inbound/web/src/webfluxContractTest/java/dev/caskeleton/adapter/inbound/web/testkit/webflux/ReactorNettyWebContractIT.java +++ /dev/null @@ -1,128 +0,0 @@ -package dev.caskeleton.adapter.inbound.web.testkit.webflux; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.net.URI; -import java.net.http.HttpClient; -import java.net.http.HttpRequest; -import java.net.http.HttpResponse; -import java.time.Duration; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.web.server.LocalServerPort; -import org.springframework.context.ApplicationContext; -import org.springframework.test.context.ActiveProfiles; - -/** - * The Stable contract on a real Reactor Netty, over a real socket. - * - *

{@code WebTestClient.bindToController} is not enough to declare this Stable and the design - * says so: binding to a controller never starts a server, so it cannot show that the response left - * on an event loop, that a 204 wrote zero bytes, or that the Reactor Context survived the hop. Each - * of those is only observable from outside the process. - */ -@SpringBootTest( - classes = ReactiveContractFixtureApplication.class, - webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -@ActiveProfiles("web-contract") -class ReactorNettyWebContractIT { - - @LocalServerPort private int port; - - @Autowired private ApplicationContext context; - - private final HttpClient client = - HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build(); - - @Test - @DisplayName("the lane is actually running on Reactor Netty") - void theLaneIsActuallyRunningOnReactorNetty() { - // The context type is the observation, not a bean lookup: a reactive application produces a - // reactive context, and a servlet one does not. Asserting the class name keeps the check - // independent of where Boot happens to have moved the concrete type. - assertThat(context.getClass().getName()) - .as("with Tomcat on the classpath Boot would start a servlet container and certify nothing") - .contains("Reactive"); - } - - @Test - @DisplayName("201 carries a Location and 204 writes zero body bytes") - void statusContractHoldsOnReactorNetty() throws Exception { - HttpResponse created = - client.send( - HttpRequest.newBuilder(uri("/api/v1/fixtures")) - .POST(HttpRequest.BodyPublishers.ofString("{\"name\":\"x\"}")) - .header("Content-Type", "application/json") - .build(), - HttpResponse.BodyHandlers.ofString()); - assertThat(created.statusCode()).isEqualTo(201); - assertThat(created.headers().firstValue("Location")).isPresent(); - - HttpResponse deleted = - client.send( - HttpRequest.newBuilder(uri("/api/v1/fixtures/f1")).DELETE().build(), - HttpResponse.BodyHandlers.ofByteArray()); - assertThat(deleted.statusCode()).isEqualTo(204); - assertThat(deleted.body()).isEmpty(); - } - - @Test - @DisplayName("the handler runs on an event loop and still sees its request context") - void theHandlerRunsOnAnEventLoopAndStillSeesItsContext() throws Exception { - HttpResponse report = - client.send( - HttpRequest.newBuilder(uri("/api/v1/fixtures/thread")).GET().build(), - HttpResponse.BodyHandlers.ofString()); - - assertThat(report.statusCode()).isEqualTo(200); - // The name the running server actually uses, checked against the guard's own predicate rather - // than against a literal: a literal here would go stale the same way the predicate did. - String threadName = report.body().replaceAll(".*\"threadName\":\"([^\"]+)\".*", "$1"); - assertThat( - dev.caskeleton.adapter.inbound.web.webflux.guard.BlockingDependencyGuard - .REACTOR_NETTY_EVENT_LOOP - .test(threadName)) - .as( - "the handler ran on %s, which the blocking guard must recognise as an event loop", - threadName) - .isTrue(); - assertThat(report.body()) - .as("a thread-local would have returned whichever request last ran on this loop") - .contains("requestId"); - assertThat(report.body()).contains("requestId"); - assertThat(report.headers().firstValue("X-Request-Id")).isPresent(); - } - - @Test - @DisplayName("HEAD parity holds and a rejected body leaks no internals") - void headParityHoldsAndARejectedBodyLeaksNoInternals() throws Exception { - HttpResponse get = - client.send( - HttpRequest.newBuilder(uri("/api/v1/fixtures/f1")).GET().build(), - HttpResponse.BodyHandlers.ofString()); - HttpResponse head = - client.send( - HttpRequest.newBuilder(uri("/api/v1/fixtures/f1")) - .method("HEAD", HttpRequest.BodyPublishers.noBody()) - .build(), - HttpResponse.BodyHandlers.ofByteArray()); - assertThat(head.headers().firstValue("ETag")).isEqualTo(get.headers().firstValue("ETag")); - assertThat(head.body()).isEmpty(); - - HttpResponse rejected = - client.send( - HttpRequest.newBuilder(uri("/api/v1/fixtures")) - .POST(HttpRequest.BodyPublishers.ofString("{\"name\":\" \"}")) - .header("Content-Type", "application/json") - .build(), - HttpResponse.BodyHandlers.ofString()); - assertThat(rejected.statusCode()).isBetween(400, 499); - assertThat(rejected.body()).doesNotContain("Exception").doesNotContain("dev.caskeleton"); - } - - private URI uri(String path) { - return URI.create("http://localhost:" + port + path); - } -} diff --git a/src/adapter/inbound/websocket/CLAUDE.md b/src/adapter/inbound/websocket/CLAUDE.md index 2a51ee80..57f62c01 100644 --- a/src/adapter/inbound/websocket/CLAUDE.md +++ b/src/adapter/inbound/websocket/CLAUDE.md @@ -5,7 +5,7 @@ - Module ID: `adapter-inbound-websocket` - Gradle path: `:adapter:inbound:websocket` - Focused test: `./gradlew :adapter:inbound:websocket:test --console=plain` -- Runtime baseline: Java 21, Spring Boot 4.0.0 +- Runtime baseline: Java 21, Spring Boot 4.0.8 - Registry SSOT: `src/config/architecture/modules.json` Package root: `dev.caskeleton.adapter.inbound.websocket`. @@ -17,21 +17,25 @@ This leaf contains **two different scopes** and they must not be read as one dep 1. **Opt-in STOMP/SockJS channel** — `stomp/**` owns the Spring transport configuration, typed `app.websocket.*` settings, handshake principal/origin checks, destination policy, fixed client-safe STOMP `ERROR` mapping, and best-effort in-process event projection. -2. **WebSocket platform library** — the larger `core/protocol/handshake/outbound/resume/cluster/` - `presence/codec/servlet/...` packages provide reusable protocol, budget, backpressure, - lifecycle and qualification machinery. The shipped composition does **not** assemble - `PlatformWebSocketHandler` or expose this platform as a runtime endpoint. +2. **Servlet handler library** — `servlet/`, `outbound/`, `budget/` plus the two id records + `core/WebSocketConnectionId` and `protocol/WebSocketMessageId`. No settings keys, no Spring + configuration: a service's own adapter leaf constructs `PlatformWebSocketHandler` and registers + it. README "라이브러리 API" lists the entry points and the wiring. + +This leaf does not deduplicate commands and owns no storage SPI. The former `idempotency/` +package (command ledger, `WebSocketActorReference`, `WebSocketEndpointName`) was removed on +2026-09-25. A command that must run at most once goes through the application +`IdempotencyExecutor` inside its use case, with a scope that survives a reconnect (endpoint + actor ++ the client's own message id), never the connection id. The module itself is absent from both shipped runtime compositions. Being registered and tested -does not activate either scope. Adding the leaf to a future composition is a build-time decision; -enabling a concrete runtime still requires that composition to own the corresponding root wiring -and configuration. +does not activate either scope. ## Allowed - Registered dependency on `:domain-core` for the `@DomainEvent` marker. - Spring Boot WebSocket and validation starters, managed by the repository BOM. -- Test-only embedded Tomcat/SockJS/STOMP clients supplied by the repository test baseline. +- Test-only embedded Tomcat/Jetty/SockJS/STOMP clients and Testcontainers (Nginx lane). ## Forbidden @@ -42,62 +46,44 @@ and configuration. - Anonymous handshakes, arbitrary topic subscriptions, or client sends to broker destinations. - A production feature `@MessageMapping` in this skeleton leaf. - A module-local YAML file; composition roots own property values. +- Settings keys, flags or catalogs for behaviour no code in this leaf performs. A bound that the + handler does not enforce is not a field of `WebSocketConnectionBudget`. +- Reactive (WebFlux) WebSocket code: the template is servlet-only. ## Typed settings (`app.websocket.*`) There is one property tree and one operator env prefix: `app.websocket.*` ↔ `APP_WEBSOCKET_*`. -The default bootJar does not contain this leaf, so these values matter only in a composition that -adopts it. +They configure the STOMP channel only. The default bootJar does not contain this leaf, so these +values matter only in a composition that adopts it. | property | env | default / role | | --- | --- | --- | -| `app.websocket.enabled` | `APP_WEBSOCKET_ENABLED` | `false`; enables the legacy STOMP/SockJS channel | +| `app.websocket.enabled` | `APP_WEBSOCKET_ENABLED` | `true`; `false` turns the STOMP/SockJS channel off | | `app.websocket.endpoint` | `APP_WEBSOCKET_ENDPOINT` | `/ws` | | `app.websocket.allowed-origins` | `APP_WEBSOCKET_ALLOWED_ORIGINS` | `http://localhost:3000`; explicit origins only | | `app.websocket.broadcast-destination` | `APP_WEBSOCKET_BROADCAST_DESTINATION` | `/topic/events` | -| `app.websocket.platform.enabled` | `APP_WEBSOCKET_PLATFORM_ENABLED` | `false`; enables validation for an explicitly assembled platform runtime | -| `app.websocket.platform.node-id` | `APP_WEBSOCKET_PLATFORM_NODE_ID` | `local` | -| `app.websocket.platform.allowed-origins` | `APP_WEBSOCKET_PLATFORM_ALLOWED_ORIGINS` | empty by default | -| `app.websocket.platform.allow-missing-origin` | `APP_WEBSOCKET_PLATFORM_ALLOW_MISSING_ORIGIN` | `false` | -| `app.websocket.platform.max-frame-bytes` | `APP_WEBSOCKET_PLATFORM_MAX_FRAME_BYTES` | `65536` | -| `app.websocket.platform.max-message-bytes` | `APP_WEBSOCKET_PLATFORM_MAX_MESSAGE_BYTES` | `524288` | -| `app.websocket.platform.max-fragments` | `APP_WEBSOCKET_PLATFORM_MAX_FRAGMENTS` | `16` | -| `app.websocket.platform.max-buffered-outbound-bytes-per-connection` | `APP_WEBSOCKET_PLATFORM_MAX_BUFFERED_OUTBOUND_BYTES_PER_CONNECTION` | `1048576` | -| `app.websocket.platform.max-buffered-outbound-bytes-per-node` | `APP_WEBSOCKET_PLATFORM_MAX_BUFFERED_OUTBOUND_BYTES_PER_NODE` | `67108864` | -| `app.websocket.platform.max-connections-per-actor` | `APP_WEBSOCKET_PLATFORM_MAX_CONNECTIONS_PER_ACTOR` | `4` | -| `app.websocket.platform.ping-interval` | `APP_WEBSOCKET_PLATFORM_PING_INTERVAL` | `15s` | -| `app.websocket.platform.idle-timeout` | `APP_WEBSOCKET_PLATFORM_IDLE_TIMEOUT` | `45s` | -| `app.websocket.platform.max-connection-age` | `APP_WEBSOCKET_PLATFORM_MAX_CONNECTION_AGE` | `4h` | -| `app.websocket.platform.ticket-lifetime` | `APP_WEBSOCKET_PLATFORM_TICKET_LIFETIME` | `30s` | -| `app.websocket.advanced.sockjs.enabled` | `APP_WEBSOCKET_ADVANCED_SOCKJS_ENABLED` | `false` | -| `app.websocket.advanced.stomp.enabled` | `APP_WEBSOCKET_ADVANCED_STOMP_ENABLED` | `false` | -| `app.websocket.advanced.stomp.relay.enabled` | `APP_WEBSOCKET_ADVANCED_STOMP_RELAY_ENABLED` | `false` | -`WebSocketProperties` is `@Validated`. Invalid enabled settings fail context startup. Advanced -capabilities without a concrete runtime configuration do **not** get synthetic env keys merely -because they exist in `WebSocketAdvancedCapability`. +`WebSocketSettings` is `@Validated`. Invalid enabled settings fail context startup. ## Adopting this capability WebSocket is a **build-composition opt-in**, not a dormant feature inside the default bootJar. -1. Add `:adapter:inbound:websocket` to the consuming composition's runtime dependencies and add - the matching allowed edge in `config/architecture/modules.json`. +1. Add `:adapter:inbound:websocket` to the consuming composition's dependencies and add the + matching allowed edge in `config/architecture/modules.json`. 2. Keep settings registration with the capability root; do not add `dev.caskeleton.adapter.inbound.websocket` back to the shipped `@ConfigurationPropertiesScan`. -3. For the STOMP/SockJS channel, supply composition-owned configuration and explicitly enable - `app.websocket.enabled=true` with a non-wildcard origin allowlist. -4. Do **not** treat the larger platform library as deployed merely because the jar is present. - A composition must explicitly assemble its handler/lifecycle dependencies before the platform - runbook applies. -5. Run the leaf qualification lanes and the repository conditional-transport aggregate before - promoting the composition: +3. The STOMP/SockJS channel is registered by this leaf's own `AutoConfiguration.imports` and is on + whenever the leaf is on a servlet classpath; set a non-wildcard origin allowlist, and + `app.websocket.enabled=false` to turn it off. +4. For the handler library, follow README "라이브러리 API". The handler must be a bean so its + `SmartLifecycle` stop (1001 to every open connection) runs before the web server stops. +5. Run the leaf lanes and the repository conditional-transport aggregate before promoting the + composition: `./gradlew :adapter:inbound:websocket:test :adapter:inbound:websocket:systemTest :conditionalTransportQualification`. -6. Production adoption is not complete until the property namespace/env-registry contract is - registered in the composition SSOT; do not invent an unregistered `APP_*` switch locally. -## Inbound policy +## Inbound policy (STOMP) - The HTTP upgrade must already have a nonblank `Principal`; the adapter does not authenticate credentials itself. @@ -115,15 +101,16 @@ projection failures, invalid event types, null fields, and over-limit maps are d envelope contains only `type`, bounded string `fields`, and `occurredAt`. No current `sample-portfolio` feature publishes a WebSocket event or contributes a projector. -That is a future adoption example, not an existing runtime feature. ## Evidence and limits -The fast `test` lane covers settings, policy, protocol, budget and module-boundary behavior. -`WebSocketBoundaryQualificationTest` now lives in `systemTest`; it starts a random-port Tomcat -and crosses real SockJS/STOMP handshake, Origin, principal, subscription, server projection push, -application SEND, broker SEND rejection, and ERROR redaction. +| lane | what it proves | +| --- | --- | +| `test` | STOMP settings/policy, queue/writer/budget, handler size and overflow closes | +| `systemTest` | real Tomcat: STOMP boundary (`WebSocketBoundaryQualificationTest`), handler runtime and abuse contracts, context close sends 1001 | +| `websocketJettyTest` | the handler runtime contract on Jetty | +| `websocketNginxTest` | upgrade/forwarding behind a real Nginx (Docker required; fails without it) | +| `websocketTransportQualificationTest` | no-skip execution of the STOMP boundary test | The simple broker is local, single-process, best-effort R1 evidence only. Broker relay, -multi-node/durable delivery, rollback-safe publication, replay/resume, backpressure, and a versioned -domain projection catalog are P2 and are not claimed. +multi-node/durable delivery, rollback-safe publication and replay/resume are not provided. diff --git a/src/adapter/inbound/websocket/README.md b/src/adapter/inbound/websocket/README.md index 9862632b..3ac679e7 100644 --- a/src/adapter/inbound/websocket/README.md +++ b/src/adapter/inbound/websocket/README.md @@ -1,47 +1,145 @@ -# adapter-inbound-websocket — design rationale +# adapter-inbound-websocket -This leaf is conditional WebSocket/STOMP transport machinery. Module rules and executable settings -live in [CLAUDE.md](CLAUDE.md); this document records why the P1 boundary has this shape. +모듈 규칙(허용 의존, 설정 키, 테스트 명령)은 [CLAUDE.md](CLAUDE.md)가 SSOT다. 이 문서는 무엇을 +제공하는지, 어떻게 붙이는지, 왜 이런 모양인지를 적는다. -## Opt-in instead of accidental exposure +이 leaf는 두 가지를 제공한다. 서로 참조하지 않는다. -The leaf is built and tested but is not part of `app-bootstrap` or `sample-portfolio` production -runtime membership. Even after a future composition adds it, `app.websocket.enabled=false` -keeps its configuration and broadcaster absent. Enabling requires explicit non-wildcard origins, -so merely adding the artifact cannot expose a wildcard STOMP broker. +| | 무엇 | 켜는 방법 | +| --- | --- | --- | +| STOMP 채널 (`stomp/`) | STOMP-over-SockJS 서버 push. 설정 키 `app.websocket.*` | `runtimeOnly` 한 줄. servlet 앱에 모듈이 있으면 켜진다 | +| 라이브러리 API (`servlet/`, `outbound/`, `budget/`) | raw WebSocket 요청/응답 handler와 bounded 송신 큐 | 서비스의 어댑터 leaf가 직접 `new` 해서 등록. 설정 키 없음 | -## HTTP authentication before STOMP authorization +두 경로 모두 기본 bootJar(`app-bootstrap`)에는 들어 있지 않다. -The handshake interceptor accepts only a principal established by the HTTP boundary. It does not -interpret bearer tokens or invent a STOMP-only login mechanism. The inbound channel then applies a -small destination allowlist: subscribe only to the configured server topic, send only to -`/app/**`, and never let a client publish directly to `/topic/**`. +## STOMP 채널 -All processing failures pass through a custom `StompSubProtocolErrorHandler`. Clients receive one -fixed code and an empty body; exception messages, rejected destinations, and sentinels are not -reflected into the ERROR frame. +### 제공하는 것 -## Explicit projection instead of raw domain serialization +- `/ws`(설정 가능) SockJS endpoint, `/topic` simple broker, `/app` application prefix. +- HTTP 계층이 이미 인증한 `Principal`이 있어야 handshake가 통과한다. 이 leaf는 자격 증명을 직접 + 해석하지 않는다. +- SUBSCRIBE는 설정된 broadcast destination 하나만, SEND는 `/app/**`만 허용한다. 클라이언트가 + `/topic/**`으로 직접 보내는 것은 거부한다. +- 처리 실패는 모두 고정 코드 `WEBSOCKET_REQUEST_REJECTED`와 빈 본문의 ERROR 프레임이 된다. +- `LiveEventProjector` bean이 정확히 하나 있는 `@DomainEvent` 타입만 broadcast한다. 도메인 + 객체를 그대로 직렬화하지 않고, projector가 만든 bounded `Map`만 보낸다. -`@DomainEvent` is only a marker annotation. Treating every annotated object as a wire contract -would accidentally expose new fields whenever a domain record changed. The broadcaster therefore -requires exactly one `LiveEventProjector` for the event's exact class. Its output is validated as -a bounded `Map` and copied into the envelope. The domain object is never handed to -`SimpMessagingTemplate`. +### 추가할 한 줄 -Zero matching projectors mean “not a public live event”; duplicate projectors mean ambiguous -ownership. Both cases are dropped. This keeps the skeleton feature-agnostic without making every -future domain fact public by default. +```groovy +// app-bootstrap/build.gradle +runtimeOnly project(':adapter:inbound:websocket') // WebSocket (STOMP push) +``` -No current sample feature contributes a publisher or projector. A future adopter can add one in -its feature/composition work, then qualify the chosen public event contract. +`WebSocketConfig`가 모듈 자신의 `AutoConfiguration.imports`에 있다. servlet 앱에 모듈이 있으면 켜지고, +`APP_WEBSOCKET_ENABLED=false`로만 끈다. 이 줄을 지우면 endpoint, broker, 설정 바인딩이 모두 함께 +빠진다. 기본 조립에는 없다. -## Why the simple broker remains R1 +### env 키 -The in-memory `/topic` broker is useful for a real local protocol boundary test and best-effort UI -push. It is not durable, transactional, replayable, or cross-node. Publication can also precede a -surrounding transaction rollback. Durable delivery belongs to an outbox/relay design rather than -an inbound adapter dependency on outbound infrastructure. +| env | 기본값 | 뜻 | +| --- | --- | --- | +| `APP_WEBSOCKET_ENABLED` | `true` | `false`면 STOMP 채널을 끈다 | +| `APP_WEBSOCKET_ENDPOINT` | `/ws` | handshake 경로 | +| `APP_WEBSOCKET_ALLOWED_ORIGINS` | `http://localhost:3000` | 쉼표 구분 origin 목록. wildcard 금지 | +| `APP_WEBSOCKET_BROADCAST_DESTINATION` | `/topic/events` | 서버 push 대상. `/topic/` 아래 경로 하나 | -Broker relay, multi-node delivery, rollback-safe publication, replay/resume, backpressure, and a -versioned feature projection catalog remain explicit P2 work. +켠 상태에서 값이 잘못되면(wildcard origin, 정규화되지 않은 경로) 기동이 실패한다. + +### 한계 + +simple broker는 한 프로세스 안의 best-effort 전달이다. 영속·트랜잭션 연동·재전송·노드 간 전달이 +없고, 발행이 트랜잭션 rollback보다 먼저 일어날 수 있다. 이런 전달이 필요하면 outbox/relay로 +설계한다. + +## 라이브러리 API — 서비스의 어댑터 leaf에서 직접 조립 + +설정 키도 자동 설정도 없다. 서비스의 어댑터 leaf가 `implementation project(':adapter:inbound:websocket')`로 +받아 아래 타입을 직접 만든다(AGENTS.md capability 규칙의 라이브러리형 예외). + +| 진입점 | 역할 | +| --- | --- | +| `servlet.PlatformWebSocketHandler` | 텍스트 메시지 하나를 받아 `BiFunction>`에 넘기고, 응답을 연결별 큐로 보낸다. `SmartLifecycle`이라 context 종료 시 열린 연결을 1001로 닫는다 | +| `budget.WebSocketConnectionBudget(maxMessageBytes, maxBufferedOutboundBytes)` | 연결 하나의 수신 메시지 상한(UTF-8 바이트)과 미전송 버퍼 상한 | +| `outbound.GlobalBufferBudget(maxBufferedBytes)` | 노드 전체 미전송 바이트 상한. 모든 연결이 공유한다 | +| `outbound.OutboundQueue`, `outbound.SerializedOutboundWriter` | 우선순위·conflation·drop 정책을 가진 bounded 큐와 연결당 단일 writer. handler 없이 따로 쓸 수 있다 | + +동작: + +```text +client ──text──> container(whole message) ──> PlatformWebSocketHandler + ├─ > maxMessageBytes → close 1009 + └─ application.apply(id, text) + └─ reply → OutboundQueue → SerializedOutboundWriter → socket + └─ 큐가 가득 참(GUARANTEED) → close 1013 +context close ──> PlatformWebSocketHandler.stop() ──> 열린 연결 모두 close 1001 ──> web server graceful shutdown +``` + +조립 예: + +```java +@Configuration +@EnableWebSocket +class LiveSocketConfig implements WebSocketConfigurer { + + private final LiveCommandUseCase useCase; // 서비스의 application 포트 + + LiveSocketConfig(LiveCommandUseCase useCase) { + this.useCase = useCase; + } + + @Bean // bean이어야 SmartLifecycle로 종료 순서에 들어간다 + PlatformWebSocketHandler platformWebSocketHandler() { + return new PlatformWebSocketHandler( + new WebSocketConnectionBudget(64 * 1024, 1024 * 1024), + new GlobalBufferBudget(64L * 1024 * 1024), + (connection, text) -> useCase.handle(text)); // Optional: 응답 또는 empty + } + + @Override + public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { + registry + .addHandler(platformWebSocketHandler(), "/ws/v1/live") + .setAllowedOrigins("https://app.example.com"); + } + + @Bean // 컨테이너가 메시지를 버퍼에 모으므로 수신 상한과 idle timeout은 여기서 정한다 + ServletServerContainerFactoryBean webSocketContainer() { + ServletServerContainerFactoryBean container = new ServletServerContainerFactoryBean(); + container.setMaxTextMessageBufferSize(64 * 1024); + container.setMaxSessionIdleTimeout(90_000L); + return container; + } +} +``` + +서비스가 챙길 것: + +- **인증**: handler는 인증하지 않는다. upgrade 경로를 Spring Security 같은 HTTP 계층에서 막는다. +- **origin**: `setAllowedOrigins`에 정확한 origin만 쓴다. WebSocket handshake는 same-origin 정책과 + preflight의 보호를 받지 않는다. +- **수신 크기**: servlet API는 애플리케이션에 frame을 보여주지 않는다. 컨테이너가 메시지를 자기 + 버퍼(Tomcat 기본 8 KiB)에 모으고, 그보다 크면 컨테이너가 1009로 닫는다. 컨테이너 버퍼를 + `maxMessageBytes`와 같게 두면 두 상한이 일치한다. +- **idle timeout·연결 수명**: handler에는 없다. 컨테이너(`setMaxSessionIdleTimeout`)와 프록시의 read + timeout으로 정한다. +- **서버 주도 push 없음**: handler는 받은 메시지에 대한 응답만 보낸다. 임의 시점 push가 필요하면 + STOMP 채널을 쓴다. + +검증하는 lane: + +```bash +cd src +./gradlew :adapter:inbound:websocket:test # 큐·writer·budget·handler 단위 +./gradlew :adapter:inbound:websocket:systemTest # Tomcat 실제 소켓: echo·1009·순서·abuse·종료 1001 +./gradlew :adapter:inbound:websocket:websocketJettyTest # 같은 계약을 Jetty에서 +./gradlew :adapter:inbound:websocket:websocketNginxTest # 실제 Nginx 뒤에서. Docker 필요, 없으면 실패 +``` + +## 제거한 것 + +2026-09-25에 어느 Spring 설정에서도 닿지 않던 플랫폼 코드(`advanced/**`, handshake·session· +protocol catalog·codec·ordering·lifecycle·observability·admin·security·webflux 등)와 +`app.websocket.platform.*`·`app.websocket.advanced.sockjs.enabled` 설정 키를 지웠다. 목록과 복구 +커밋은 `docs/capability-status.md`의 "제거된 코드" 표에 있다. diff --git a/src/adapter/inbound/websocket/build.gradle b/src/adapter/inbound/websocket/build.gradle index 9694a84d..c3eabe36 100644 --- a/src/adapter/inbound/websocket/build.gradle +++ b/src/adapter/inbound/websocket/build.gradle @@ -3,11 +3,12 @@ plugins { id 'ca.spring-config' id 'java-test-fixtures' id 'ca.auxiliary-source-set' - id 'ca.strict-qualification' } // Shared test code as a Gradle test-fixtures variant — ADR-BUILD-001. -// Driving adapter: WebSocket (STOMP over SockJS) live-push channel (skeleton machinery, transport-only). +// Driving adapter: WebSocket (STOMP over SockJS) live-push channel (skeleton machinery, transport-only), +// plus the raw-WebSocket servlet handler library (`servlet`/`outbound`/`budget`) that a service +// assembles itself. README lists both. // // W1 live-bus: LiveEventStompBroadcaster forwards only explicitly allowlisted, bounded primitive // projections of domain-core @DomainEvent instances. The raw domain object is never serialized. @@ -17,48 +18,16 @@ plugins { // spring-websocket / spring-messaging / jackson versions are managed by the Spring Boot BOM, so no // explicit versions or module-scoped platform imports are needed (unlike the grpc adapter, whose // io.grpc coordinates the BOM does not manage). -description = 'Inbound adapter: WebSocket (STOMP over SockJS, skeleton machinery)' +description = 'Inbound adapter: WebSocket (STOMP over SockJS channel + servlet handler library)' dependencies { implementation project(':domain-core') - // Reaches the realtime ports — the cluster registry and the replay window — whose - // implementations are outbound adapters this leaf may not name. The registry entry - // permits this edge; the datastore is on the other side of it. - implementation project(':application-core') implementation 'org.springframework.boot:spring-boot-starter-websocket' - // The reactive runtime's types only — deliberately not spring-boot-starter-webflux, which - // would put a second embedded server on the runtime classpath and make Boot deduce a reactive - // application. The two runtimes are mutually exclusive at deployment; both must nonetheless - // compile here, because the platform ships bindings for each. - implementation 'org.springframework:spring-webflux' - implementation 'io.projectreactor:reactor-core' implementation 'org.springframework.boot:spring-boot-starter-validation' - // The two Advanced binary codecs, compile-only. They were `implementation` first, so that an - // enabled codec would fail at startup rather than at the first frame. What that missed is that - // both jars are load-bearing for Spring Boot's auto-configuration by their mere presence: with - // the CBOR backend on the runtime classpath Boot registers a `cborMapper` bean, and with - // protobuf-java on it Spring registers a Protobuf message converter. A composition root that - // adopted this leaf would acquire both without enabling either capability — and the sibling web - // leaf demonstrated the consequence, where three ObjectMapper beans broke every - // `@Autowired ObjectMapper` in the composition root. - // - // So the deployment that turns a codec on adds its backend. `WebSocketBinaryCodecBackend` turns - // the absent jar into a sentence rather than a NoClassDefFoundError from inside Jackson. - compileOnly 'tools.jackson.dataformat:jackson-dataformat-cbor' - // Pinned: no BOM manages it. The version matches what the toolchain already resolves for the - // annotation processor, so the runtime and the processor cannot drift onto two protobuf - // runtimes with different wire behaviour. - compileOnly libs.protobuf.java - testImplementation 'tools.jackson.dataformat:jackson-dataformat-cbor' - testImplementation libs.protobuf.java - } -// The platform's reusable ArchUnit rules ship in their own source set, consumed by this leaf's -// tests and available to the composition root. A rule pack that only its own fixture tests import -// is verified as library code and applied to nothing. auxiliarySourceSets { sourceSet('systemTest') { compilesAgainst 'main', 'testFixtures' @@ -90,11 +59,9 @@ dependencies { testFixturesImplementation 'org.springframework:spring-websocket' testFixturesImplementation 'org.springframework.boot:spring-boot-autoconfigure' testFixturesImplementation 'org.springframework.boot:spring-boot' - testFixturesImplementation libs.archunit.junit5 // No `testImplementation 'spring-boot-starter-test'` / `'spring-boot-starter-websocket'` here: // the root gives every non-platform leaf the former (src/build.gradle), and `testImplementation` - // extends `implementation`, which already carries the latter (:24). - testImplementation libs.archunit.junit5 + // extends `implementation`, which already carries the latter. jettyWebSocketTestImplementation('org.springframework.boot:spring-boot-starter-jetty') jettyWebSocketTestImplementation('org.springframework.boot:spring-boot-starter-test') { @@ -138,22 +105,11 @@ strictTestLanes { jvmArgs '-Duser.timezone=UTC' } - // The Advanced lane. Every capability is off unless a deployment names it, so nothing a - // production deployment runs exercises them — which makes this the only place a break is noticed - // before whoever enables it notices. They also run inside `test`: they are ordinary unit tests, - // and excluding them to make this lane look meaningful would stop the PR gate covering them. - lane('websocketAdvancedTest') { - tag = 'websocket-advanced' - description = 'Runs every WebSocket Advanced capability contract.' + lane('websocketTransportQualificationTest') { + sourceSet = 'systemTest' + description = 'Runs exact no-skip WebSocket conditional transport wire evidence.' + requires 'dev.caskeleton.adapter.inbound.websocket.stomp.WebSocketBoundaryQualificationTest' + rejectSkipped = true jvmArgs '-Duser.timezone=UTC' } } - -extensions.getByName('strictQualification').register( - 'websocketTransportQualificationTest', - sourceSets.systemTest, - [ - 'dev.caskeleton.adapter.inbound.websocket.stomp.WebSocketBoundaryQualificationTest' - ], - 'Runs exact no-skip WebSocket conditional transport wire evidence.' -) diff --git a/src/adapter/inbound/websocket/gradle.lockfile b/src/adapter/inbound/websocket/gradle.lockfile index d34500a4..b5b10c38 100644 --- a/src/adapter/inbound/websocket/gradle.lockfile +++ b/src/adapter/inbound/websocket/gradle.lockfile @@ -32,15 +32,10 @@ com.google.guava:guava:33.5.0-jre=annotationProcessor,jettyWebSocketTestAnnotati com.google.guava:guava:33.6.0-jre=checkstyle com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,checkstyle,jettyWebSocketTestAnnotationProcessor,nginxWebSocketTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,jettyWebSocketTestAnnotationProcessor,nginxWebSocketTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor -com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,compileClasspath,jettyWebSocketTestAnnotationProcessor,jettyWebSocketTestCompileClasspath,jettyWebSocketTestRuntimeClasspath,nginxWebSocketTestAnnotationProcessor,nginxWebSocketTestCompileClasspath,nginxWebSocketTestRuntimeClasspath,systemTestAnnotationProcessor,systemTestCompileClasspath,systemTestRuntimeClasspath,testAnnotationProcessor,testCompileClasspath,testFixturesAnnotationProcessor,testRuntimeClasspath +com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,jettyWebSocketTestAnnotationProcessor,nginxWebSocketTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins com.jayway.jsonpath:json-path:2.10.0=jettyWebSocketTestCompileClasspath,jettyWebSocketTestRuntimeClasspath,nginxWebSocketTestCompileClasspath,nginxWebSocketTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath com.puppycrawl.tools:checkstyle:13.5.0=checkstyle -com.tngtech.archunit:archunit-junit5-api:1.3.0=jettyWebSocketTestCompileClasspath,jettyWebSocketTestRuntimeClasspath,nginxWebSocketTestCompileClasspath,nginxWebSocketTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath -com.tngtech.archunit:archunit-junit5-engine-api:1.3.0=jettyWebSocketTestRuntimeClasspath,nginxWebSocketTestRuntimeClasspath,systemTestRuntimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath -com.tngtech.archunit:archunit-junit5-engine:1.3.0=jettyWebSocketTestRuntimeClasspath,nginxWebSocketTestRuntimeClasspath,systemTestRuntimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath -com.tngtech.archunit:archunit-junit5:1.3.0=jettyWebSocketTestCompileClasspath,jettyWebSocketTestRuntimeClasspath,nginxWebSocketTestCompileClasspath,nginxWebSocketTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath -com.tngtech.archunit:archunit:1.3.0=jettyWebSocketTestCompileClasspath,jettyWebSocketTestRuntimeClasspath,nginxWebSocketTestCompileClasspath,nginxWebSocketTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath com.vaadin.external.google:android-json:0.0.20131108.vaadin1=jettyWebSocketTestCompileClasspath,jettyWebSocketTestRuntimeClasspath,nginxWebSocketTestCompileClasspath,nginxWebSocketTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath commons-beanutils:commons-beanutils:1.11.0=checkstyle commons-codec:commons-codec:1.19.0=nginxWebSocketTestCompileClasspath,nginxWebSocketTestRuntimeClasspath @@ -53,7 +48,6 @@ io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,jettyWebSo io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,jettyWebSocketTestAnnotationProcessor,nginxWebSocketTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor io.micrometer:micrometer-commons:1.16.7=compileClasspath,jettyWebSocketTestCompileClasspath,jettyWebSocketTestRuntimeClasspath,nginxWebSocketTestCompileClasspath,nginxWebSocketTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath io.micrometer:micrometer-observation:1.16.7=compileClasspath,jettyWebSocketTestCompileClasspath,jettyWebSocketTestRuntimeClasspath,nginxWebSocketTestCompileClasspath,nginxWebSocketTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath -io.projectreactor:reactor-core:3.8.7=compileClasspath,jettyWebSocketTestCompileClasspath,jettyWebSocketTestRuntimeClasspath,nginxWebSocketTestCompileClasspath,nginxWebSocketTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath jakarta.activation:jakarta.activation-api:2.1.4=jettyWebSocketTestCompileClasspath,jettyWebSocketTestRuntimeClasspath,nginxWebSocketTestCompileClasspath,nginxWebSocketTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath jakarta.annotation:jakarta.annotation-api:3.0.0=compileClasspath,jettyWebSocketTestCompileClasspath,jettyWebSocketTestRuntimeClasspath,nginxWebSocketTestCompileClasspath,nginxWebSocketTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath jakarta.enterprise:jakarta.enterprise.cdi-api:4.1.0=jettyWebSocketTestCompileClasspath,jettyWebSocketTestRuntimeClasspath @@ -142,7 +136,7 @@ org.junit.jupiter:junit-jupiter-engine:6.0.3=jettyWebSocketTestRuntimeClasspath, org.junit.jupiter:junit-jupiter-params:6.0.3=jettyWebSocketTestCompileClasspath,jettyWebSocketTestRuntimeClasspath,nginxWebSocketTestCompileClasspath,nginxWebSocketTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.junit.jupiter:junit-jupiter:6.0.3=jettyWebSocketTestCompileClasspath,jettyWebSocketTestRuntimeClasspath,nginxWebSocketTestCompileClasspath,nginxWebSocketTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.junit.platform:junit-platform-commons:6.0.3=jettyWebSocketTestCompileClasspath,jettyWebSocketTestRuntimeClasspath,nginxWebSocketTestCompileClasspath,nginxWebSocketTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath -org.junit.platform:junit-platform-engine:6.0.3=jettyWebSocketTestRuntimeClasspath,nginxWebSocketTestRuntimeClasspath,systemTestRuntimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.junit.platform:junit-platform-engine:6.0.3=jettyWebSocketTestRuntimeClasspath,nginxWebSocketTestRuntimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath org.junit.platform:junit-platform-launcher:6.0.3=jettyWebSocketTestRuntimeClasspath,nginxWebSocketTestRuntimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath org.junit:junit-bom:6.0.3=jettyWebSocketTestCompileClasspath,jettyWebSocketTestRuntimeClasspath,nginxWebSocketTestCompileClasspath,nginxWebSocketTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.junit:junit-bom:6.1.0=spotbugs @@ -161,12 +155,11 @@ org.ow2.asm:asm-util:9.10.1=spotbugs org.ow2.asm:asm:9.10.1=jettyWebSocketTestCompileClasspath,jettyWebSocketTestRuntimeClasspath,spotbugs org.ow2.asm:asm:9.7.1=nginxWebSocketTestCompileClasspath,nginxWebSocketTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.pcollections:pcollections:4.0.1=annotationProcessor,jettyWebSocketTestAnnotationProcessor,nginxWebSocketTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor -org.reactivestreams:reactive-streams:1.0.4=compileClasspath,jettyWebSocketTestCompileClasspath,jettyWebSocketTestRuntimeClasspath,nginxWebSocketTestCompileClasspath,nginxWebSocketTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.reflections:reflections:0.10.2=checkstyle org.rnorth.duct-tape:duct-tape:1.0.8=nginxWebSocketTestCompileClasspath,nginxWebSocketTestRuntimeClasspath org.skyscreamer:jsonassert:1.5.3=jettyWebSocketTestCompileClasspath,jettyWebSocketTestRuntimeClasspath,nginxWebSocketTestCompileClasspath,nginxWebSocketTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.slf4j:jul-to-slf4j:2.0.18=compileClasspath,jettyWebSocketTestCompileClasspath,jettyWebSocketTestRuntimeClasspath,nginxWebSocketTestCompileClasspath,nginxWebSocketTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath -org.slf4j:slf4j-api:2.0.18=compileClasspath,jettyWebSocketTestCompileClasspath,jettyWebSocketTestRuntimeClasspath,nginxWebSocketTestCompileClasspath,nginxWebSocketTestRuntimeClasspath,runtimeClasspath,spotbugs,spotbugsSlf4j,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.slf4j:slf4j-api:2.0.18=compileClasspath,jettyWebSocketTestCompileClasspath,jettyWebSocketTestRuntimeClasspath,nginxWebSocketTestCompileClasspath,nginxWebSocketTestRuntimeClasspath,runtimeClasspath,spotbugs,spotbugsSlf4j,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j org.slf4j:slf4j-simple:2.0.18=checkstyle org.springframework.boot:spring-boot-autoconfigure:4.0.8=compileClasspath,jettyWebSocketTestCompileClasspath,jettyWebSocketTestRuntimeClasspath,nginxWebSocketTestCompileClasspath,nginxWebSocketTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath @@ -206,7 +199,6 @@ org.springframework:spring-expression:7.0.9=compileClasspath,jettyWebSocketTestC org.springframework:spring-messaging:7.0.9=compileClasspath,jettyWebSocketTestCompileClasspath,jettyWebSocketTestRuntimeClasspath,nginxWebSocketTestCompileClasspath,nginxWebSocketTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.springframework:spring-test:7.0.9=jettyWebSocketTestCompileClasspath,jettyWebSocketTestRuntimeClasspath,nginxWebSocketTestCompileClasspath,nginxWebSocketTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.springframework:spring-web:7.0.9=compileClasspath,jettyWebSocketTestCompileClasspath,jettyWebSocketTestRuntimeClasspath,nginxWebSocketTestCompileClasspath,nginxWebSocketTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath -org.springframework:spring-webflux:7.0.9=compileClasspath,jettyWebSocketTestCompileClasspath,jettyWebSocketTestRuntimeClasspath,nginxWebSocketTestCompileClasspath,nginxWebSocketTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.springframework:spring-webmvc:7.0.9=compileClasspath,jettyWebSocketTestCompileClasspath,jettyWebSocketTestRuntimeClasspath,nginxWebSocketTestCompileClasspath,nginxWebSocketTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.springframework:spring-websocket:7.0.9=compileClasspath,jettyWebSocketTestCompileClasspath,jettyWebSocketTestRuntimeClasspath,nginxWebSocketTestCompileClasspath,nginxWebSocketTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.testcontainers:testcontainers-junit-jupiter:2.0.5=nginxWebSocketTestCompileClasspath,nginxWebSocketTestRuntimeClasspath @@ -216,6 +208,5 @@ org.xmlunit:xmlunit-core:2.10.4=jettyWebSocketTestCompileClasspath,jettyWebSocke org.yaml:snakeyaml:2.5=compileClasspath,jettyWebSocketTestCompileClasspath,jettyWebSocketTestRuntimeClasspath,nginxWebSocketTestCompileClasspath,nginxWebSocketTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath tools.jackson.core:jackson-core:3.1.5=compileClasspath,jettyWebSocketTestCompileClasspath,jettyWebSocketTestRuntimeClasspath,nginxWebSocketTestCompileClasspath,nginxWebSocketTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath tools.jackson.core:jackson-databind:3.1.5=compileClasspath,jettyWebSocketTestCompileClasspath,jettyWebSocketTestRuntimeClasspath,nginxWebSocketTestCompileClasspath,nginxWebSocketTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath -tools.jackson.dataformat:jackson-dataformat-cbor:3.1.5=compileClasspath,jettyWebSocketTestCompileClasspath,jettyWebSocketTestRuntimeClasspath,nginxWebSocketTestCompileClasspath,nginxWebSocketTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath tools.jackson:jackson-bom:3.1.5=compileClasspath,jettyWebSocketTestCompileClasspath,jettyWebSocketTestRuntimeClasspath,nginxWebSocketTestCompileClasspath,nginxWebSocketTestRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath empty= diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/admin/WebSocketAdminOperations.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/admin/WebSocketAdminOperations.java deleted file mode 100644 index 2bb8a67f..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/admin/WebSocketAdminOperations.java +++ /dev/null @@ -1,52 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.admin; - -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketActorReference; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketConnectionId; -import java.time.Duration; - -/** - * What an operator may do to live connections. - * - *

Three operations, and every one of them is an override of a control the platform put in place - * — which is why they belong in an audit trail rather than an access log, and why each requires a - * stated reason. - * - *

Disconnecting by actor rather than only by connection is the operation that is actually - * needed. An incident response is "cut this account off", and doing that connection by connection - * means the operator races the client's reconnects. - */ -public interface WebSocketAdminOperations { - - /** What this node is currently doing. */ - WebSocketNodeSnapshot snapshot(); - - /** - * Closes one connection. - * - * @param connectionId which connection - * @param reason why, recorded in the audit trail - * @return whether this node held it - */ - boolean disconnect(WebSocketConnectionId connectionId, String reason); - - /** - * Closes every connection an actor holds on this node. - * - * @param actor whose connections - * @param reason why, recorded in the audit trail - * @return how many were closed - */ - int disconnectActor(WebSocketActorReference actor, String reason); - - /** - * Stops accepting new connections and drains the existing ones. - * - *

Bounded by {@code drainTimeout}, because a peer that has stopped reading will not finish - * draining and a deploy cannot wait for it. - * - * @param drainTimeout how long in-flight work is given - * @param reason why, recorded in the audit trail - * @return how many connections were asked to drain - */ - int drain(Duration drainTimeout, String reason); -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/admin/WebSocketNodeSnapshot.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/admin/WebSocketNodeSnapshot.java deleted file mode 100644 index 8c43e13e..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/admin/WebSocketNodeSnapshot.java +++ /dev/null @@ -1,60 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.admin; - -import java.util.List; -import java.util.Map; -import java.util.Objects; - -/** - * What one node is currently doing, as an operator can read it. - * - *

Node-scoped and it says so. During an incident the first question is "which node", and a - * snapshot that silently aggregated the fleet would answer it wrong — the operator drains a node - * and the number does not move, because the number was never about that node. - * - *

{@code droppedOutboundMessages} is the field that earns its place. Connection counts and - * buffered bytes both look healthy while a slow consumer quietly loses data; the drop count is the - * only number that says so. - * - * @param nodeId which node - * @param connectionsByEndpoint how many connections each endpoint holds here - * @param totalConnections how many this node holds - * @param bufferedOutboundBytes how much unsent data is held - * @param peakBufferedOutboundBytes the most ever held at once - * @param droppedOutboundMessages how many messages were discarded for slow consumers - * @param draining whether this node is shutting down - */ -public record WebSocketNodeSnapshot( - String nodeId, - Map connectionsByEndpoint, - int totalConnections, - long bufferedOutboundBytes, - long peakBufferedOutboundBytes, - long droppedOutboundMessages, - boolean draining) { - - public WebSocketNodeSnapshot { - Objects.requireNonNull(nodeId, "nodeId"); - Objects.requireNonNull(connectionsByEndpoint, "connectionsByEndpoint"); - connectionsByEndpoint = Map.copyOf(connectionsByEndpoint); - if (totalConnections < 0 || bufferedOutboundBytes < 0 || droppedOutboundMessages < 0) { - throw new IllegalArgumentException("snapshot counters cannot be negative"); - } - } - - /** Whether this node is losing outbound messages. */ - public boolean losingMessages() { - return droppedOutboundMessages > 0; - } - - /** - * The endpoints holding connections, busiest first. - * - *

Ordered because an operator reading a snapshot during an incident is looking for the - * outlier, and an unordered map makes them scan. - */ - public List> byBusiest() { - return connectionsByEndpoint.entrySet().stream() - .sorted(Map.Entry.comparingByValue().reversed()) - .toList(); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/WebSocketAdvancedCapability.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/WebSocketAdvancedCapability.java deleted file mode 100644 index b152eb8d..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/WebSocketAdvancedCapability.java +++ /dev/null @@ -1,81 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced; - -/** - * The Advanced capabilities tracked by promotion evidence. - * - *

This enum deliberately does not manufacture configuration property names. A catalog entry is - * not proof that a runtime implementation or feature flag exists. Concrete configuration classes - * own the flags for the capabilities that are actually wired today (STOMP, broker relay and - * SockJS); the remaining entries describe promotion/evidence scope only. - */ -public enum WebSocketAdvancedCapability { - - /** - * Resuming a session across a reconnect from a stored position. - * - *

Changes what a gap means: with resume, a client that missed messages can ask for them, so a - * gap becomes recoverable rather than a resynchronise. Without the replay store behind it the - * token is a promise the platform cannot keep. - */ - RESUME, - - /** A cluster-wide session index in Redis, so a node can find where an actor is connected. */ - CLUSTER_REDIS, - - /** Durable cross-node fan-out over the messaging platform. */ - CLUSTER_MESSAGING, - - /** Presence summaries derived from the cluster index. */ - PRESENCE, - - /** The STOMP 1.2 subprotocol, alongside the platform's own. */ - STOMP, - - /** A broker relay to RabbitMQ for STOMP destinations. */ - BROKER_RELAY_RABBIT, - - /** Protobuf as a wire codec. */ - CODEC_PROTOBUF, - - /** CBOR as a wire codec. */ - CODEC_CBOR, - - /** - * The {@code permessage-deflate} extension. - * - *

Per endpoint and never global. Compression on a connection that carries attacker-influenced - * data alongside secrets is the CRIME/BREACH shape, and the decision needs the endpoint's content - * in view. - */ - COMPRESSION, - - /** An outbound WebSocket client, for connecting to somebody else's endpoint. */ - OUTBOUND_CLIENT, - - /** SockJS fallback for clients that cannot use a raw WebSocket. */ - SOCKJS_COMPAT, - - /** HTTP/2 extended CONNECT. */ - HTTP2_COMPAT, - - /** HTTP/3 WebSocket, experimental. */ - HTTP3_EXPERIMENTAL, - - /** The GraphQL-over-WebSocket transport. */ - GRAPHQL_TRANSPORT; - - /** - * Whether this capability changes the platform's failure modes rather than adding beside them. - * - *

Read by the startup validator, which requires these to be named in the deployment's own - * configuration rather than inherited from a profile. Turning on a network dependency in the - * delivery path is not the same kind of decision as turning on a codec. - */ - public boolean altersFailureModes() { - return this == RESUME - || this == CLUSTER_REDIS - || this == CLUSTER_MESSAGING - || this == BROKER_RELAY_RABBIT - || this == HTTP3_EXPERIMENTAL; - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/client/NamedClientProfile.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/client/NamedClientProfile.java deleted file mode 100644 index f10afc9d..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/client/NamedClientProfile.java +++ /dev/null @@ -1,79 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.client; - -import java.net.URI; -import java.time.Duration; -import java.util.Objects; -import java.util.Optional; - -/** - * One outbound WebSocket connection this service makes to somebody else. - * - *

Named and declared, rather than opened wherever a URL happens to be in scope. An outbound - * WebSocket is a long-lived connection to a third party: it holds a thread or an event-loop - * registration for its whole life, it re-authenticates on every reconnect, and when the peer goes - * away it is this service's resource usage that changes, not the peer's. Naming them makes the set - * of such connections something an operator can enumerate. - * - *

The subprotocol is pinned rather than negotiated freely for the same reason it is pinned on - * the inbound side: a peer that answers with a subprotocol this client did not ask for has changed - * the message contract, and continuing means parsing its frames with the wrong reader. - * - * @param name the operator-facing identity - * @param uri where to connect - * @param subprotocol the one subprotocol offered, absent when none is - * @param connectTimeout how long the handshake may take - * @param idleTimeout how long a silent connection is kept - */ -public record NamedClientProfile( - String name, - URI uri, - Optional subprotocol, - Duration connectTimeout, - Duration idleTimeout) { - - public NamedClientProfile { - Objects.requireNonNull(name, "name"); - Objects.requireNonNull(uri, "uri"); - Objects.requireNonNull(subprotocol, "subprotocol"); - Objects.requireNonNull(connectTimeout, "connectTimeout"); - Objects.requireNonNull(idleTimeout, "idleTimeout"); - if (name.isBlank()) { - throw new IllegalArgumentException("an unnamed outbound connection cannot be found in a log"); - } - String scheme = uri.getScheme(); - if (scheme == null || !(scheme.equals("ws") || scheme.equals("wss"))) { - throw new IllegalArgumentException("not a WebSocket URI: " + uri); - } - if (connectTimeout.isNegative() || connectTimeout.isZero()) { - throw new IllegalArgumentException( - "an unbounded handshake holds a connection slot against a peer that is not answering"); - } - if (idleTimeout.isNegative() || idleTimeout.isZero()) { - throw new IllegalArgumentException( - "without an idle timeout a half-open connection to a vanished peer is indistinguishable " - + "from a quiet one, and is held forever"); - } - } - - /** Whether the transport is encrypted. */ - public boolean secure() { - return "wss".equals(uri.getScheme()); - } - - /** - * What this profile exposes before it is fit for anything but a developer's machine. - * - *

Reported rather than refused: connecting to a local peer over plaintext during development - * is legitimate, and the startup validator is where the deployment's profiles are in view. - */ - public Optional plaintextConcern() { - if (secure()) { - return Optional.empty(); - } - return Optional.of( - "outbound connection '" - + name - + "' is plaintext; its credentials and every message it carries are readable on the " - + "path"); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/client/NamedClientRegistry.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/client/NamedClientRegistry.java deleted file mode 100644 index 61d68c9d..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/client/NamedClientRegistry.java +++ /dev/null @@ -1,60 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.client; - -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -/** - * The outbound connections this service is allowed to make. - * - *

A closed set, resolved by name. The alternative — a client that takes a URI — makes the set of - * peers this service talks to a property of whatever string reached the call site, which is how a - * service ends up holding a connection to somewhere nobody intended and nobody can enumerate. - */ -public final class NamedClientRegistry { - - private final Map profiles; - - private NamedClientRegistry(Map profiles) { - this.profiles = Map.copyOf(profiles); - } - - /** Build a registry from declared profiles. */ - public static NamedClientRegistry of(List profiles) { - Objects.requireNonNull(profiles, "profiles"); - Map byName = new LinkedHashMap<>(); - for (NamedClientProfile profile : profiles) { - NamedClientProfile previous = byName.putIfAbsent(profile.name(), profile); - if (previous != null) { - throw new IllegalArgumentException( - "two outbound connections named '" - + profile.name() - + "'; whichever was registered last would silently win and the other peer would " - + "never be reached"); - } - } - return new NamedClientRegistry(byName); - } - - /** Resolve a name. Empty for anything undeclared, which the caller must treat as a refusal. */ - public Optional find(String name) { - return Optional.ofNullable(profiles.get(name)); - } - - /** Every declared name, for the startup report. */ - public List names() { - return profiles.keySet().stream().sorted().toList(); - } - - /** Every plaintext connection, for the startup validator to judge against the active profiles. */ - public List plaintextConcerns() { - return profiles.values().stream().flatMap(p -> p.plaintextConcern().stream()).sorted().toList(); - } - - /** How many connections are declared. */ - public int size() { - return profiles.size(); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/client/ReconnectPolicy.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/client/ReconnectPolicy.java deleted file mode 100644 index cb347961..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/client/ReconnectPolicy.java +++ /dev/null @@ -1,92 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.client; - -import java.time.Duration; -import java.util.Objects; -import java.util.OptionalLong; -import java.util.random.RandomGenerator; - -/** - * How an outbound client waits before trying again. - * - *

Not an HTTP retry policy. An HTTP retry re-sends one request; a WebSocket reconnect - * re-establishes a session, which means a handshake, an authentication, a resubscribe, and — if the - * peer is a service with many clients — it happens to every one of them at the same instant. That - * synchronised wave is the failure mode: a peer that restarts is met by its entire client - * population reconnecting in lockstep, which keeps it down. - * - *

Hence jitter, and hence bounded attempts. A client that retries forever against a peer that - * has been decommissioned is a permanent load source that nobody notices because each individual - * attempt looks reasonable. - * - * @param initialBackoff the first wait - * @param maxBackoff the ceiling the exponential growth stops at - * @param multiplier how fast the wait grows - * @param maxAttempts how many times to try before giving up, or empty for unbounded - * @param jitterRatio how much of each wait is randomised, 0.0 to 1.0 - */ -public record ReconnectPolicy( - Duration initialBackoff, - Duration maxBackoff, - double multiplier, - OptionalLong maxAttempts, - double jitterRatio) { - - public ReconnectPolicy { - Objects.requireNonNull(initialBackoff, "initialBackoff"); - Objects.requireNonNull(maxBackoff, "maxBackoff"); - Objects.requireNonNull(maxAttempts, "maxAttempts"); - if (initialBackoff.isNegative() || initialBackoff.isZero()) { - throw new IllegalArgumentException( - "a zero first backoff reconnects in a tight loop against a peer that just refused"); - } - if (maxBackoff.compareTo(initialBackoff) < 0) { - throw new IllegalArgumentException("the backoff ceiling is below its floor"); - } - if (multiplier < 1.0) { - throw new IllegalArgumentException( - "a multiplier below 1 shortens the wait as failures pile up"); - } - if (jitterRatio <= 0.0 || jitterRatio > 1.0) { - throw new IllegalArgumentException( - "jitter must be positive: without it every client of a restarted peer reconnects in " - + "lockstep and keeps it down"); - } - if (maxAttempts.isPresent() && maxAttempts.getAsLong() < 1) { - throw new IllegalArgumentException("a bounded policy must permit at least one attempt"); - } - } - - /** The conventional policy: 1s to 60s, doubling, full jitter, 20 attempts. */ - public static ReconnectPolicy conventional() { - return new ReconnectPolicy( - Duration.ofSeconds(1), Duration.ofSeconds(60), 2.0, OptionalLong.of(20), 1.0); - } - - /** Whether another attempt is permitted. */ - public boolean mayRetry(long attemptsSoFar) { - return maxAttempts.isEmpty() || attemptsSoFar < maxAttempts.getAsLong(); - } - - /** - * How long to wait before attempt {@code attempt}, counting from 1. - * - * @param attempt which attempt this is - * @param random the source of jitter, supplied so the calculation is testable - */ - public Duration backoffFor(long attempt, RandomGenerator random) { - Objects.requireNonNull(random, "random"); - if (attempt < 1) { - throw new IllegalArgumentException("attempts count from 1"); - } - double base = initialBackoff.toMillis() * Math.pow(multiplier, attempt - 1D); - long capped = (long) Math.min(base, (double) maxBackoff.toMillis()); - long jitterSpan = (long) (capped * jitterRatio); - if (jitterSpan <= 0) { - return Duration.ofMillis(capped); - } - // Subtracted rather than added, so the ceiling is a ceiling. Adding jitter on top of maxBackoff - // means the configured maximum is not the maximum, which is the kind of off-by-a-factor that - // only shows up when the peer stays down for an hour. - return Duration.ofMillis(capped - random.nextLong(jitterSpan + 1)); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/cluster/ExternalSessionIndex.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/cluster/ExternalSessionIndex.java deleted file mode 100644 index 51e1d958..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/cluster/ExternalSessionIndex.java +++ /dev/null @@ -1,52 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.cluster; - -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketActorReference; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketEndpointName; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketNodeId; -import java.time.Duration; -import java.time.Instant; -import java.util.List; - -/** - * A cluster-wide view of where actors are connected. - * - *

Two expiry mechanisms, and both are needed. A TTL on each entry removes what a node forgot to - * clean up; a node heartbeat removes everything a node held when it died. Neither covers the - * other's case — a TTL alone leaves a dead node's entries live until each one individually expires, - * and a heartbeat alone leaves a live node's stale entries for ever. - * - *

Nothing here is authoritative. The index says where a connection was last reported, and the - * node holding it is the only thing that knows whether it still exists. - */ -public interface ExternalSessionIndex { - - /** - * Records that a node holds connections for an actor. - * - * @param summary what the node observed - * @param timeToLive how long the entry survives without being refreshed - */ - void announce(ExternalSessionSummary summary, Duration timeToLive); - - /** Removes an actor's entry for one node. */ - void withdraw( - WebSocketActorReference actor, WebSocketEndpointName endpoint, WebSocketNodeId nodeId); - - /** - * Where an actor is reported connected. - * - * @param now the instant staleness is judged against - */ - List locate( - WebSocketActorReference actor, WebSocketEndpointName endpoint, Instant now); - - /** Records that a node is alive. */ - void heartbeat(WebSocketNodeId nodeId, Instant now); - - /** - * Removes everything held by nodes that have stopped reporting. - * - * @return the nodes whose entries were removed - */ - List evictDeadNodes(Duration heartbeatTimeout, Instant now); -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/cluster/ExternalSessionSummary.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/cluster/ExternalSessionSummary.java deleted file mode 100644 index 6a4e96a9..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/cluster/ExternalSessionSummary.java +++ /dev/null @@ -1,64 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.cluster; - -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketActorReference; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketEndpointName; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketNodeId; -import java.time.Duration; -import java.time.Instant; -import java.util.Objects; - -/** - * Where an actor is connected, as seen from outside the node holding the connection. - * - *

Every entry carries when it was observed, and callers are expected to use it. A cluster index - * is a cache of a fact owned by another machine: the node may have died, the connection may have - * closed, and nothing tells the index until a TTL expires. Treating an entry as current is how a - * message is routed to a node that stopped existing three minutes ago. - * - *

The index key is the actor's fingerprint, never a subject or tenant. Redis keys reach {@code - * MONITOR}, slow-log entries, `KEYS` output during an incident, and whatever backup the cluster - * takes — none of which have the access controls the application has. - * - * @param actor whose connection this is - * @param nodeId which node holds it - * @param endpoint which endpoint it connected to - * @param connectionCount how many connections that actor holds on that node - * @param observedAt when the holding node last said so - */ -public record ExternalSessionSummary( - WebSocketActorReference actor, - WebSocketNodeId nodeId, - WebSocketEndpointName endpoint, - int connectionCount, - Instant observedAt) { - - public ExternalSessionSummary { - Objects.requireNonNull(actor, "actor"); - Objects.requireNonNull(nodeId, "nodeId"); - Objects.requireNonNull(endpoint, "endpoint"); - Objects.requireNonNull(observedAt, "observedAt"); - if (connectionCount < 0) { - throw new IllegalArgumentException("a connection count cannot be negative"); - } - } - - /** - * The index key for an actor and endpoint. - * - *

Fingerprint only. A key carrying a subject is a subject in every Redis diagnostic anyone - * runs, and those run during incidents when the audience is widest. - */ - public static String indexKey(WebSocketActorReference actor, WebSocketEndpointName endpoint) { - return "ws:idx:" + endpoint.value() + ":" + actor.fingerprint(); - } - - /** - * Whether this entry is too old to act on. - * - * @param maximumAge how stale an entry may be before it is treated as absent - * @param now the current instant - */ - public boolean staleAt(Duration maximumAge, Instant now) { - return !now.isBefore(observedAt.plus(maximumAge)); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/cluster/FanoutDeduplicator.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/cluster/FanoutDeduplicator.java deleted file mode 100644 index f5ed4f9d..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/cluster/FanoutDeduplicator.java +++ /dev/null @@ -1,100 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.cluster; - -import java.time.Duration; -import java.time.Instant; -import java.util.Map; -import java.util.Objects; -import java.util.concurrent.ConcurrentHashMap; - -/** - * Refuses a message the receiving node has already delivered. - * - *

Necessary because durable fan-out is at-least-once by construction: a consumer that fails to - * acknowledge — a redeploy, a slow node, a broker rebalance — has its messages redelivered, and - * redelivery is normal operation rather than an error. Without deduplication a rolling restart - * shows every connected client a burst of repeated events, which for anything the client appends to - * a list is visible corruption. - * - *

Keyed by stream and position rather than by a message id, because the position is what the - * client actually orders on. A redelivery with a fresh message id and the same position is the case - * a message-id cache misses. - */ -public final class FanoutDeduplicator { - - private final Map highWaterMark = new ConcurrentHashMap<>(); - private final Map lastSeen = new ConcurrentHashMap<>(); - private final Duration retention; - - /** - * A deduplicator that forgets streams it has not seen for a while. - * - * @param retention how long a stream's position is remembered after its last message - */ - public FanoutDeduplicator(Duration retention) { - this.retention = Objects.requireNonNull(retention, "retention"); - if (retention.isZero() || retention.isNegative()) { - throw new IllegalArgumentException( - "a deduplicator that forgets immediately deduplicates nothing"); - } - } - - /** - * Whether this message should be delivered. - * - * @param envelope the message - * @param now the current instant - */ - public boolean shouldDeliver(FanoutEnvelope envelope, Instant now) { - Objects.requireNonNull(envelope, "envelope"); - if (envelope.expiredAt(now)) { - // Checked here as well as at publication. A message that sat through an outage is delivered - // late, and for ephemeral traffic late is indistinguishable from wrong. - return false; - } - if (!envelope.ordered()) { - // Nothing to deduplicate against. An unordered fan-out is best-effort by declaration, and - // inventing a key for it would silently drop legitimately repeated values. - return true; - } - String stream = envelope.streamId().orElseThrow(); - long position = envelope.sequence().orElseThrow(); - lastSeen.put(stream, now); - // compute(), so the read and the update are one step. An earlier version used merge() with - // Math::max and read the result back, which cannot distinguish "this raised the mark" from - // "this equalled it" — so a redelivery of the current position was delivered again, which is - // precisely the case redelivery produces most often. - boolean[] deliver = new boolean[1]; - highWaterMark.compute( - stream, - (id, mark) -> { - if (mark == null || position > mark) { - deliver[0] = true; - return position; - } - deliver[0] = false; - return mark; - }); - return deliver[0]; - } - - /** Forgets streams that have gone quiet, so the map does not grow with churn. */ - public int evictIdle(Instant now) { - int before = lastSeen.size(); - lastSeen - .entrySet() - .removeIf( - entry -> { - if (!now.isBefore(entry.getValue().plus(retention))) { - highWaterMark.remove(entry.getKey()); - return true; - } - return false; - }); - return before - lastSeen.size(); - } - - /** How many streams are being tracked. */ - public int trackedStreams() { - return highWaterMark.size(); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/cluster/FanoutEnvelope.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/cluster/FanoutEnvelope.java deleted file mode 100644 index 2e5d5c34..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/cluster/FanoutEnvelope.java +++ /dev/null @@ -1,75 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.cluster; - -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketActorReference; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketEndpointName; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageType; -import java.time.Instant; -import java.util.Objects; -import java.util.Optional; - -/** - * A message crossing nodes on its way to a connection. - * - *

Carries a reference and a type, not the business object. Two reasons, and the second is the - * one that bites later: a fan-out payload is serialized by whichever node published it and - * deserialized by whichever node holds the connection, so during a rolling deploy those are - * different versions of the code — the payload's shape becomes a wire contract between two - * deployments of the same service, and nobody writes it down. Keeping it an already-encoded - * document, encoded against the published catalog, makes it the same contract the client sees - * rather than a second private one. - * - *

The first reason is simpler: a business object on a bus is a business object in the bus's - * storage, its dead-letter queue, and its management console. - * - * @param targetActor whose connections should receive it - * @param endpoint which endpoint's connections - * @param type the published message type - * @param payload the encoded document, already valid against the catalog - * @param streamId the stream it belongs to, for an ordered delivery - * @param sequence its position on that stream - * @param publishedAt when the originating node published it - * @param expiresAt when it stops being worth delivering - */ -public record FanoutEnvelope( - WebSocketActorReference targetActor, - WebSocketEndpointName endpoint, - WebSocketMessageType type, - String payload, - Optional streamId, - Optional sequence, - Instant publishedAt, - Instant expiresAt) { - - public FanoutEnvelope { - Objects.requireNonNull(targetActor, "targetActor"); - Objects.requireNonNull(endpoint, "endpoint"); - Objects.requireNonNull(type, "type"); - Objects.requireNonNull(payload, "payload"); - Objects.requireNonNull(streamId, "streamId"); - Objects.requireNonNull(sequence, "sequence"); - Objects.requireNonNull(publishedAt, "publishedAt"); - Objects.requireNonNull(expiresAt, "expiresAt"); - if (!expiresAt.isAfter(publishedAt)) { - throw new IllegalArgumentException("a fan-out that expires when published delivers nothing"); - } - if (streamId.isPresent() != sequence.isPresent()) { - throw new IllegalArgumentException("a stream id and a sequence are meaningless apart"); - } - } - - /** - * Whether this message is still worth delivering. - * - *

Checked on the receiving node, not only on the sending one. A message that sat in a queue - * through an outage is delivered late to a client that has moved on, and for the ephemeral - * traffic fan-out carries — presence changes, live values — late is indistinguishable from wrong. - */ - public boolean expiredAt(Instant now) { - return !now.isBefore(expiresAt); - } - - /** Whether this message participates in an ordered stream. */ - public boolean ordered() { - return streamId.isPresent(); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/cluster/MessagingFanoutAdapter.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/cluster/MessagingFanoutAdapter.java deleted file mode 100644 index 0d107aa1..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/cluster/MessagingFanoutAdapter.java +++ /dev/null @@ -1,102 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.cluster; - -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketActorReference; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketEndpointName; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageType; -import dev.caskeleton.application.realtime.DurableFanoutPort; -import dev.caskeleton.application.realtime.DurableFanoutRecord; -import dev.caskeleton.application.realtime.RealtimeChannel; -import java.time.Instant; -import java.util.Objects; -import java.util.Optional; - -/** - * Publishes a {@link FanoutEnvelope} through the durable fan-out port, and reads one back. - * - *

Two representations of the same message, and they are separate on purpose. {@link - * FanoutEnvelope} is this leaf's vocabulary — it names an endpoint and a message type from the - * platform's catalog — while {@link DurableFanoutRecord} is what crosses the broker. Collapsing - * them would put transport types in {@code application-core}, and it would also mean a change to - * either one's shape was a change to the wire format between nodes. - * - *

The partition key is the actor's fingerprint. Keying on the endpoint would put a whole feed in - * one partition, which serialises every recipient behind the slowest and removes the parallelism - * the broker was chosen for; keying on the actor also gives per-recipient ordering, which is the - * only ordering this fan-out promises. - * - *

The expiry is carried and re-checked on receipt. A durable transport is exactly the one that - * can hold a message through an outage and deliver it afterwards, and the receiving node is the - * only place that knows what time it is when that happens. - */ -public final class MessagingFanoutAdapter { - - private final DurableFanoutPort fanout; - - public MessagingFanoutAdapter(DurableFanoutPort fanout) { - this.fanout = Objects.requireNonNull(fanout, "fanout"); - } - - /** - * Publish an envelope for whichever node holds its recipient. - * - * @throws dev.caskeleton.application.realtime.DurableFanoutUnavailableException when the - * transport would not accept it - */ - public void publish(FanoutEnvelope envelope) { - Objects.requireNonNull(envelope, "envelope"); - fanout.publish( - new DurableFanoutRecord( - new RealtimeChannel(envelope.endpoint().value()), - envelope.targetActor().fingerprint(), - envelope.payload(), - envelope.streamId(), - envelope.sequence(), - envelope.publishedAt(), - envelope.expiresAt())); - } - - /** - * Read a received record back into this leaf's vocabulary. - * - * @param record what arrived - * @param actor the recipient, resolved by the receiving node rather than carried on the wire - * @param type the catalog type the payload was encoded as - * @return the envelope, or empty when the record cannot be represented here - */ - public Optional receive( - DurableFanoutRecord record, WebSocketActorReference actor, WebSocketMessageType type) { - Objects.requireNonNull(record, "record"); - Objects.requireNonNull(actor, "actor"); - Objects.requireNonNull(type, "type"); - try { - return Optional.of( - new FanoutEnvelope( - actor, - new WebSocketEndpointName(record.channel().value()), - type, - record.payload(), - record.streamId(), - record.position(), - record.publishedAt(), - record.expiresAt())); - } catch (IllegalArgumentException unrepresentable) { - // A record whose channel is not an endpoint this build knows about. Dropped rather than - // raised: during a rolling deploy the other half of the cluster may be publishing for a feed - // this node has not learned yet, and failing the consumer would stop it processing the - // records it does understand. - Objects.requireNonNull(unrepresentable); - return Optional.empty(); - } - } - - /** - * Whether a received record should be delivered at all. - * - * @param record what arrived - * @param now the receiving node's clock - */ - public static boolean deliverable(DurableFanoutRecord record, Instant now) { - Objects.requireNonNull(record, "record"); - return !record.expiredAt(now); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/cluster/PortBackedExternalSessionIndex.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/cluster/PortBackedExternalSessionIndex.java deleted file mode 100644 index 300c9b38..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/cluster/PortBackedExternalSessionIndex.java +++ /dev/null @@ -1,108 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.cluster; - -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketActorReference; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketEndpointName; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketNodeId; -import dev.caskeleton.application.realtime.ActorFingerprint; -import dev.caskeleton.application.realtime.ConnectionRegistration; -import dev.caskeleton.application.realtime.ConnectionRegistryPort; -import dev.caskeleton.application.realtime.RealtimeChannel; -import dev.caskeleton.application.realtime.RealtimeNodeId; -import java.time.Duration; -import java.time.Instant; -import java.util.List; -import java.util.Objects; - -/** - * The cluster session index, on the application's connection registry. - * - *

This class is a translator and nothing else. The registry lives in an outbound adapter — Redis - * today — and this leaf may depend on {@code application-core} and no further, so the datastore is - * reached through a port and the transport's own vocabulary stops here. - * - *

That boundary is not ceremony. {@link WebSocketEndpointName} is a URL path, and a URL path - * changes when somebody renames a route; {@link RealtimeChannel} is a logical feed name that does - * not. Mapping between them here means renaming an endpoint does not invalidate every entry the - * cluster is holding, and the channel a deployment stores is a decision rather than a side effect - * of its routing table. - * - *

Nothing here fails loudly. The port degrades to "nothing found" by contract, and this - * preserves that: a lookup that returns empty makes the caller broadcast, which is correct, and an - * exception would turn a Redis blip into a failed delivery. - */ -public final class PortBackedExternalSessionIndex implements ExternalSessionIndex { - - private final ConnectionRegistryPort registry; - - public PortBackedExternalSessionIndex(ConnectionRegistryPort registry) { - this.registry = Objects.requireNonNull(registry, "registry"); - } - - @Override - public void announce(ExternalSessionSummary summary, Duration timeToLive) { - Objects.requireNonNull(summary, "summary"); - Objects.requireNonNull(timeToLive, "timeToLive"); - registry.announce( - new ConnectionRegistration( - fingerprint(summary.actor()), - nodeId(summary.nodeId()), - channel(summary.endpoint()), - summary.connectionCount(), - summary.observedAt()), - timeToLive); - } - - @Override - public void withdraw( - WebSocketActorReference actor, WebSocketEndpointName endpoint, WebSocketNodeId nodeId) { - registry.withdraw(fingerprint(actor), channel(endpoint), nodeId(nodeId)); - } - - @Override - public List locate( - WebSocketActorReference actor, WebSocketEndpointName endpoint, Instant now) { - Objects.requireNonNull(actor, "actor"); - Objects.requireNonNull(endpoint, "endpoint"); - Objects.requireNonNull(now, "now"); - return registry.locate(fingerprint(actor), channel(endpoint), now).stream() - .map( - registration -> - new ExternalSessionSummary( - actor, - new WebSocketNodeId(registration.nodeId().value()), - endpoint, - registration.connectionCount(), - registration.observedAt())) - .toList(); - } - - @Override - public void heartbeat(WebSocketNodeId nodeId, Instant now) { - registry.heartbeat(nodeId(nodeId), now); - } - - @Override - public List evictDeadNodes(Duration heartbeatTimeout, Instant now) { - return registry.evictSilentNodes(heartbeatTimeout, now).stream() - .map(evicted -> new WebSocketNodeId(evicted.value())) - .toList(); - } - - private static ActorFingerprint fingerprint(WebSocketActorReference actor) { - Objects.requireNonNull(actor, "actor"); - // The reference is already a hash of subject and tenant under a deployment salt, so this is a - // rename rather than a pseudonymisation. The port's type refuses anything that is not, which is - // what stops a later change here from passing a raw subject through. - return new ActorFingerprint(actor.fingerprint()); - } - - private static RealtimeNodeId nodeId(WebSocketNodeId nodeId) { - Objects.requireNonNull(nodeId, "nodeId"); - return new RealtimeNodeId(nodeId.value()); - } - - private static RealtimeChannel channel(WebSocketEndpointName endpoint) { - Objects.requireNonNull(endpoint, "endpoint"); - return new RealtimeChannel(endpoint.value()); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/cluster/ReplayCursor.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/cluster/ReplayCursor.java deleted file mode 100644 index 14045c87..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/cluster/ReplayCursor.java +++ /dev/null @@ -1,64 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.cluster; - -import java.util.Objects; - -/** - * Where a replay has got to on one stream. - * - *

Exclusive of {@code from} and inclusive of {@code through}, stated because an off-by-one here - * is a duplicate or a hole in somebody's history and neither announces itself. The client said it - * saw position N, so a replay starts at N+1. - * - * @param streamId which stream - * @param from the first position to deliver - * @param through the last position delivered so far - */ -public record ReplayCursor(String streamId, long from, long through) { - - public ReplayCursor { - Objects.requireNonNull(streamId, "streamId"); - if (streamId.isBlank()) { - throw new IllegalArgumentException("a cursor needs the stream it is on"); - } - if (from < 1) { - // Positions start at 1. A cursor from 0 asks for a message that never existed, and the - // source would answer with the first real one — silently shifting every position after it. - throw new IllegalArgumentException("replay starts at position 1, not " + from); - } - if (through < from - 1) { - throw new IllegalArgumentException("a cursor cannot have delivered less than nothing"); - } - } - - /** A cursor about to deliver its first message. */ - public static ReplayCursor startingAt(String streamId, long from) { - return new ReplayCursor(streamId, from, from - 1); - } - - /** The same cursor after delivering one position. */ - public ReplayCursor advancedTo(long position) { - if (position != through + 1) { - // Advancing by more than one would skip a position with nothing recording that it was - // skipped, which is the hole this type exists to make impossible. - throw new IllegalArgumentException( - "a cursor at " - + through - + " cannot advance to " - + position - + "; it would skip " - + (position - through - 1) - + " positions with nothing recording that it did"); - } - return new ReplayCursor(streamId, from, position); - } - - /** How many positions have been delivered. */ - public long delivered() { - return through - from + 1; - } - - /** Whether the cursor has reached a target position. */ - public boolean caughtUpTo(long target) { - return through >= target; - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/cluster/ReplayEventMapper.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/cluster/ReplayEventMapper.java deleted file mode 100644 index 4a1d8b21..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/cluster/ReplayEventMapper.java +++ /dev/null @@ -1,132 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.cluster; - -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageCatalog; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageType; -import java.time.Instant; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -/** - * Turns a broker message into a replay record, or refuses it. - * - *

The refusal is the point. A replay path that forwards whatever the broker holds is a path on - * which a message written by an older deployment, or by a producer that was never meant to reach - * this endpoint, arrives at a client as though the platform had published it. Retained messages - * outlive deployments by definition — that is what retention is — so "the producer and consumer - * agree" is exactly the assumption that does not hold here. - * - *

Every mapped record is therefore checked against the same catalog that governs live traffic: - * the type must be published, must be server-to-client, and must be at a schema major this - * deployment still serves. - */ -public final class ReplayEventMapper { - - /** Why a broker message could not become a replay record. */ - public enum Rejection { - - /** The message names a type this deployment does not publish. */ - UNKNOWN_TYPE, - - /** The type exists but is not something the server sends. */ - WRONG_DIRECTION, - - /** - * The type exists at a different major version. - * - *

The one that only happens on a replay path. A retained message from before a breaking - * change is still in the log, and forwarding it hands a client a document of a shape its - * current code cannot read. - */ - SCHEMA_MISMATCH, - - /** The message is missing a field the platform needs to place it. */ - MALFORMED - } - - /** - * The outcome of mapping one broker message. - * - * @param record the record, when it mapped - * @param rejection why it did not, when it did not - */ - public record Mapped(Optional record, Optional rejection) { - - public Mapped { - Objects.requireNonNull(record, "record"); - Objects.requireNonNull(rejection, "rejection"); - if (record.isPresent() == rejection.isPresent()) { - throw new IllegalArgumentException("a mapping either produced a record or a rejection"); - } - } - - static Mapped of(ReplayRecord record) { - return new Mapped(Optional.of(record), Optional.empty()); - } - - static Mapped rejected(Rejection rejection) { - return new Mapped(Optional.empty(), Optional.of(rejection)); - } - } - - private final WebSocketMessageCatalog catalog; - - /** - * A mapper over the published catalog. - * - * @param catalog which types this deployment publishes - */ - public ReplayEventMapper(WebSocketMessageCatalog catalog) { - this.catalog = Objects.requireNonNull(catalog, "catalog"); - } - - /** - * Maps one broker message. - * - * @param headers the broker's headers, from which the platform reads only what it declared - * @param payload the encoded document - */ - public Mapped map(Map headers, String payload) { - Objects.requireNonNull(headers, "headers"); - if (payload == null) { - return Mapped.rejected(Rejection.MALFORMED); - } - String streamId = headers.get("ws-stream-id"); - String rawType = headers.get("ws-message-type"); - String rawSequence = headers.get("ws-sequence"); - String rawOccurredAt = headers.get("ws-occurred-at"); - if (streamId == null || rawType == null || rawSequence == null || rawOccurredAt == null) { - return Mapped.rejected(Rejection.MALFORMED); - } - - WebSocketMessageType type; - long sequence; - Instant occurredAt; - try { - type = new WebSocketMessageType(rawType); - sequence = Long.parseLong(rawSequence); - occurredAt = Instant.ofEpochMilli(Long.parseLong(rawOccurredAt)); - } catch (RuntimeException malformed) { - return Mapped.rejected(Rejection.MALFORMED); - } - - var descriptor = catalog.find(type); - if (descriptor.isEmpty()) { - // A retained message naming a type this deployment no longer publishes. Forwarding it would - // deliver a shape the client's current code was never written against. - return Mapped.rejected(Rejection.UNKNOWN_TYPE); - } - if (!descriptor.get().direction().acceptsFromServer()) { - return Mapped.rejected(Rejection.WRONG_DIRECTION); - } - if (descriptor.get().schemaVersion().major() != type.version()) { - return Mapped.rejected(Rejection.SCHEMA_MISMATCH); - } - - try { - return Mapped.of(new ReplayRecord(streamId, sequence, type, payload, occurredAt)); - } catch (IllegalArgumentException malformed) { - return Mapped.rejected(Rejection.MALFORMED); - } - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/cluster/ReplayRecord.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/cluster/ReplayRecord.java deleted file mode 100644 index 186681a2..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/cluster/ReplayRecord.java +++ /dev/null @@ -1,37 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.cluster; - -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageType; -import java.time.Instant; -import java.util.Objects; - -/** - * One retained message, as the replay source holds it. - * - *

Deliberately not the broker's own message. A broker record carries headers, delivery counts, - * routing keys and whatever the producer put on it, and forwarding that to a client publishes the - * internal topology — the queue names, the retry counts, the fact that a message was redelivered - * eleven times. It also makes the client's contract whatever the broker happens to serialize, which - * changes when the broker is upgraded. - * - *

So a replay record is the platform's own shape, and mapping into it is where a broker message - * that does not fit gets rejected rather than passed through. - * - * @param streamId which stream it belongs to - * @param sequence its position on that stream - * @param type the published message type - * @param payload the encoded document - * @param occurredAt when it was produced - */ -public record ReplayRecord( - String streamId, long sequence, WebSocketMessageType type, String payload, Instant occurredAt) { - - public ReplayRecord { - Objects.requireNonNull(streamId, "streamId"); - Objects.requireNonNull(type, "type"); - Objects.requireNonNull(payload, "payload"); - Objects.requireNonNull(occurredAt, "occurredAt"); - if (sequence < 1) { - throw new IllegalArgumentException("stream positions start at 1, was " + sequence); - } - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/codec/BinaryCodecProfile.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/codec/BinaryCodecProfile.java deleted file mode 100644 index eea71a86..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/codec/BinaryCodecProfile.java +++ /dev/null @@ -1,44 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.codec; - -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketSchemaVersion; -import java.util.Objects; - -/** - * What every Advanced binary codec must agree with the Stable JSON one about. - * - *

The reason this is a shared type rather than two independent profiles: a second codec is only - * safe if it means the same thing. If Protobuf and JSON disagree about which message type a frame - * is, or which schema version it was written against, then a client that switches format has - * silently switched contract — and the disagreement shows up as a handler receiving a well-formed - * message it was not expecting, which reads as an application bug. - * - * @param messageTypeCarried whether the frame names its message type, as JSON does - * @param schemaVersion the catalog version this codec is bound to - * @param maxMessageBytes the ceiling on one decoded message - * @param unknownFieldAllowed whether a field the reader does not know is tolerated - */ -public record BinaryCodecProfile( - boolean messageTypeCarried, - WebSocketSchemaVersion schemaVersion, - int maxMessageBytes, - boolean unknownFieldAllowed) { - - public BinaryCodecProfile { - Objects.requireNonNull(schemaVersion, "schemaVersion"); - if (!messageTypeCarried) { - throw new IllegalArgumentException( - "a binary frame must name its message type as the JSON one does; without it the reader " - + "guesses from context and a client that switched format has switched contract"); - } - if (maxMessageBytes < 1) { - throw new IllegalArgumentException( - "a binary codec without a size ceiling decodes whatever arrives, and a length-prefixed " - + "format will happily allocate the length it was told"); - } - } - - /** Whether a frame of this size may be decoded at all. */ - public boolean withinBounds(int frameBytes) { - return frameBytes >= 0 && frameBytes <= maxMessageBytes; - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/codec/SchemaParity.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/codec/SchemaParity.java deleted file mode 100644 index ad22adb2..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/codec/SchemaParity.java +++ /dev/null @@ -1,105 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.codec; - -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageType; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.TreeSet; - -/** - * Whether an Advanced codec publishes the same message catalog as the Stable JSON one. - * - *

This is the check that makes a second codec safe rather than merely present. If the binary - * codec knows a type JSON does not, a client that switches format gains a message the platform was - * never reviewed as accepting; if JSON knows one the binary codec does not, a client that switches - * loses a message and the loss appears as a handler that stopped being called. - * - *

Neither shows up in a codec's own round-trip test, which is why this compares catalogs rather - * than encodings. - */ -public final class SchemaParity { - - private SchemaParity() {} - - /** - * Differences between two catalogs. - * - * @param jsonTypes the Stable JSON catalog's published types - * @param binaryTypes the Advanced codec's published types - */ - public static List differences( - Set jsonTypes, Set binaryTypes) { - Objects.requireNonNull(jsonTypes, "jsonTypes"); - Objects.requireNonNull(binaryTypes, "binaryTypes"); - List differences = new ArrayList<>(); - Set onlyJson = new TreeSet<>(); - Set onlyBinary = new TreeSet<>(); - jsonTypes.stream() - .filter(type -> !binaryTypes.contains(type)) - .forEach(type -> onlyJson.add(type.value())); - binaryTypes.stream() - .filter(type -> !jsonTypes.contains(type)) - .forEach(type -> onlyBinary.add(type.value())); - if (!onlyJson.isEmpty()) { - differences.add( - "published as JSON but not by the binary codec, so a client that switches format loses " - + "them: " - + onlyJson); - } - if (!onlyBinary.isEmpty()) { - differences.add( - "published by the binary codec but not as JSON, so a client that switches format gains " - + "messages the platform was not reviewed as accepting: " - + onlyBinary); - } - return List.copyOf(differences); - } - - /** - * Fail when the catalogs disagree. - * - * @param jsonTypes the Stable JSON catalog's published types - * @param binaryTypes the Advanced codec's published types - */ - public static void verify( - Set jsonTypes, Set binaryTypes) { - List differences = differences(jsonTypes, binaryTypes); - if (!differences.isEmpty()) { - throw new IllegalStateException( - "the binary codec and the JSON codec do not publish the same catalog: " + differences); - } - } - - /** - * Differences in what each catalog binds a type to. - * - *

Same types is not enough: two codecs can agree that {@code order.placed.v1} exists and - * disagree about what it decodes to, which produces a handler receiving a well-formed object of - * the wrong shape. - * - * @param jsonBindings the Stable JSON bindings - * @param binaryBindings the Advanced codec's bindings - */ - public static List bindingDifferences( - Map> jsonBindings, - Map> binaryBindings) { - Objects.requireNonNull(jsonBindings, "jsonBindings"); - Objects.requireNonNull(binaryBindings, "binaryBindings"); - List differences = new ArrayList<>(); - for (Map.Entry> binding : jsonBindings.entrySet()) { - Class other = binaryBindings.get(binding.getKey()); - if (other != null && !other.equals(binding.getValue())) { - differences.add( - binding.getKey().value() - + " decodes to " - + binding.getValue().getName() - + " as JSON and " - + other.getName() - + " in binary"); - } - } - return List.copyOf(differences); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/codec/WebSocketBinaryCodecBackend.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/codec/WebSocketBinaryCodecBackend.java deleted file mode 100644 index 89415fe0..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/codec/WebSocketBinaryCodecBackend.java +++ /dev/null @@ -1,64 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.codec; - -/** - * Whether a binary codec's format library is actually on the runtime classpath. - * - *

Both backends are compile-only in this leaf. That is not a packaging preference: each one is - * load-bearing for Spring Boot's auto-configuration by its mere presence. The CBOR backend makes - * Boot register a {@code cborMapper} bean; protobuf-java makes Spring register a Protobuf message - * converter. A composition root that adopted this leaf would acquire both without enabling either - * capability, which is the opposite of what an off-by-default flag promises. - * - *

The cost of that choice is this class. Without it, a deployment that names the capability and - * forgets the jar gets a {@code NoClassDefFoundError} thrown from inside a mapper builder, naming a - * Jackson or protobuf class and not the decision that caused it. - */ -public enum WebSocketBinaryCodecBackend { - - /** Jackson's CBOR backend. */ - CBOR( - "tools.jackson.dataformat.cbor.CBORMapper", - "tools.jackson.dataformat:jackson-dataformat-cbor"), - - /** The protobuf runtime. */ - PROTOBUF("com.google.protobuf.DynamicMessage", "com.google.protobuf:protobuf-java"); - - private final String probeClass; - private final String coordinate; - - WebSocketBinaryCodecBackend(String probeClass, String coordinate) { - this.probeClass = probeClass; - this.coordinate = coordinate; - } - - /** The Gradle coordinate a deployment adds to enable this codec. */ - public String coordinate() { - return coordinate; - } - - /** Whether the backend is present. */ - public boolean available() { - try { - Class.forName(probeClass, false, WebSocketBinaryCodecBackend.class.getClassLoader()); - return true; - } catch (ClassNotFoundException absent) { - return false; - } - } - - /** - * Refuse with a sentence rather than a {@code NoClassDefFoundError} naming a library class. - * - * @throws IllegalStateException when the backend is absent - */ - public void require() { - if (!available()) { - throw new IllegalStateException( - "this codec's capability is enabled but " - + coordinate - + " is not on the runtime classpath; it is compile-only here so that its presence" - + " stays a deployment's decision — on the classpath it registers a mapper bean and a" - + " message converter for every deployment, enabled or not"); - } - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/codec/cbor/CborCodecProfile.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/codec/cbor/CborCodecProfile.java deleted file mode 100644 index e1a7cd01..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/codec/cbor/CborCodecProfile.java +++ /dev/null @@ -1,53 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.codec.cbor; - -import dev.caskeleton.adapter.inbound.websocket.advanced.codec.BinaryCodecProfile; -import java.util.Objects; - -/** - * CBOR as a wire codec. - * - *

Enabled only where a client population actually asks for it. CBOR buys compactness over JSON, - * and pays for it with a second decode path reachable from an unauthenticated frame — which is the - * most expensive surface in the platform to add to for a saving that a deployment can usually get - * from compression instead. - * - *

Two settings decide whether two systems reading the same bytes agree. Canonical encoding fixes - * how a value is written, so the same message has one representation and a signature over it means - * something. The duplicate-key policy fixes what an invalid map does — RFC 8949 leaves that to the - * decoder, and a validator and an executor that resolve it differently will disagree about what the - * message said, with the attacker choosing both readings. - * - * @param binary the bounds and semantics shared with every other codec - * @param canonicalEncodingRequired whether values must be in RFC 8949 canonical form - * @param duplicateKeyPolicy what an invalid map does - */ -public record CborCodecProfile( - BinaryCodecProfile binary, - boolean canonicalEncodingRequired, - DuplicateKeyPolicy duplicateKeyPolicy) { - - public CborCodecProfile { - Objects.requireNonNull(binary, "binary"); - Objects.requireNonNull(duplicateKeyPolicy, "duplicateKeyPolicy"); - } - - /** The recommended shape: canonical, and duplicate keys refused. */ - public static CborCodecProfile strict(BinaryCodecProfile binary) { - return new CborCodecProfile(binary, true, DuplicateKeyPolicy.REJECT); - } - - /** - * Whether a message decoded under this profile can be relied on to mean one thing. - * - *

False when duplicate keys are resolved rather than refused: the bytes then have two readings - * and which one a component sees depends on which decoder it uses. - */ - public boolean unambiguous() { - return duplicateKeyPolicy == DuplicateKeyPolicy.REJECT; - } - - /** Whether a decoded message is within bounds. */ - public boolean withinBounds(int messageBytes) { - return binary.withinBounds(messageBytes); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/codec/cbor/DuplicateKeyPolicy.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/codec/cbor/DuplicateKeyPolicy.java deleted file mode 100644 index 39bf3a76..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/codec/cbor/DuplicateKeyPolicy.java +++ /dev/null @@ -1,21 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.codec.cbor; - -/** - * What to do with a CBOR map that names the same key twice. - * - *

RFC 8949 calls such a map invalid but does not require a decoder to reject it, and decoders - * differ: some keep the first value, some the last. That difference is exploitable whenever two - * systems read the same bytes — a validator that reads the first value and an executor that reads - * the last will disagree about what the message said, and the attacker chooses both. - */ -public enum DuplicateKeyPolicy { - - /** Refuse the message. The only setting that makes two decoders agree. */ - REJECT, - - /** Keep the first occurrence. Recorded so a deployment that needs it says so. */ - FIRST_WINS, - - /** Keep the last occurrence. */ - LAST_WINS -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/codec/cbor/WebSocketCborCodec.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/codec/cbor/WebSocketCborCodec.java deleted file mode 100644 index 2261b4f2..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/codec/cbor/WebSocketCborCodec.java +++ /dev/null @@ -1,166 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.codec.cbor; - -import dev.caskeleton.adapter.inbound.websocket.advanced.codec.BinaryCodecProfile; -import dev.caskeleton.adapter.inbound.websocket.advanced.codec.WebSocketBinaryCodecBackend; -import dev.caskeleton.adapter.inbound.websocket.codec.WebSocketDecodeException; -import dev.caskeleton.adapter.inbound.websocket.codec.WebSocketWireTypeManifest; -import dev.caskeleton.adapter.inbound.websocket.error.WebSocketFailureCategory; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageCatalog; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageDescriptor; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageFamily; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageType; -import java.util.Objects; -import tools.jackson.core.StreamReadConstraints; -import tools.jackson.core.StreamReadFeature; -import tools.jackson.databind.DeserializationFeature; -import tools.jackson.databind.MapperFeature; -import tools.jackson.dataformat.cbor.CBORFactory; -import tools.jackson.dataformat.cbor.CBORMapper; - -/** - * The CBOR wire codec, admitted through the same catalog as JSON and refused the same things. - * - *

The catalog is consulted before the parser, exactly as the JSON codec does it. That ordering - * is the security property: an unpublished type never reaches a decoder at all, so adding a second - * decode path does not add a second set of reachable types. - * - *

Duplicate map keys are refused rather than resolved. RFC 8949 calls such a map invalid and - * lets a decoder do as it likes, so two systems reading the same bytes can disagree about what the - * message said — a validator that keeps the first value and an executor that keeps the last, with - * the attacker choosing both readings. {@link CborCodecProfile#unambiguous()} states the same rule - * as a fact about the profile; this is where it is enforced. - * - *

Bounds are applied before parsing, not after. CBOR declares a collection's length ahead of its - * contents, so a frame well inside the transport limit can ask the decoder for an allocation far - * larger than the frame — a limit checked afterwards has already paid for it. - */ -public final class WebSocketCborCodec { - - private final CBORMapper mapper; - private final WebSocketMessageCatalog catalog; - private final WebSocketWireTypeManifest manifest; - private final CborCodecProfile profile; - - /** - * A codec over one catalog and manifest. - * - * @param catalog which types are published - * @param manifest which classes they decode to - * @param profile the bounds and the duplicate-key rule - */ - public WebSocketCborCodec( - WebSocketMessageCatalog catalog, - WebSocketWireTypeManifest manifest, - CborCodecProfile profile) { - // Before the mapper is built, so an absent backend is a sentence naming the missing coordinate - // rather than a NoClassDefFoundError thrown from inside CBORMapper.builder. - WebSocketBinaryCodecBackend.CBOR.require(); - this.catalog = Objects.requireNonNull(catalog, "catalog"); - this.manifest = Objects.requireNonNull(manifest, "manifest"); - this.profile = Objects.requireNonNull(profile, "profile"); - if (!profile.unambiguous()) { - // Refused at construction. A profile that resolves duplicate keys instead of rejecting them - // produces bytes with two readings, and which one a component sees depends on which decoder - // it happens to use. - throw new IllegalArgumentException( - "a CBOR codec whose duplicate-key policy is not REJECT decodes bytes that mean two" - + " different things to two readers"); - } - BinaryCodecProfile binary = profile.binary(); - this.mapper = - CBORMapper.builder( - CBORFactory.builder() - .streamReadConstraints( - StreamReadConstraints.builder() - .maxNestingDepth(32) - .maxDocumentLength(binary.maxMessageBytes()) - .maxStringLength(binary.maxMessageBytes()) - .maxNumberLength(64) - .build()) - .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) - .build()) - .configure( - DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, !binary.unknownFieldAllowed()) - .configure(DeserializationFeature.FAIL_ON_TRAILING_TOKENS, true) - .configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, true) - .configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, false) - .configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS, false) - .disable(DeserializationFeature.ACCEPT_FLOAT_AS_INT) - .build(); - } - - /** The profile this codec runs under. */ - public CborCodecProfile profile() { - return profile; - } - - /** - * Decodes one inbound frame. - * - * @param type the published type the envelope named - * @param family the family the envelope claimed - * @param payload the encoded frame - * @throws WebSocketDecodeException when anything about it is not exactly right - */ - public Object decodeFromClient( - WebSocketMessageType type, WebSocketMessageFamily family, byte[] payload) { - Objects.requireNonNull(type, "type"); - Objects.requireNonNull(family, "family"); - Objects.requireNonNull(payload, "payload"); - if (!profile.withinBounds(payload.length)) { - throw new WebSocketDecodeException( - WebSocketFailureCategory.TOO_LARGE, "the frame exceeds the codec's ceiling"); - } - WebSocketMessageDescriptor descriptor = - catalog - .admitFromClient(type, family) - .orElseThrow( - () -> - new WebSocketDecodeException( - WebSocketFailureCategory.UNKNOWN_TYPE, - "this endpoint does not accept " + type + " from a client")); - Class target = - manifest - .targetFor(descriptor.type()) - .orElseThrow( - () -> - new WebSocketDecodeException( - WebSocketFailureCategory.INTERNAL, - "the catalog publishes " - + type - + " but the manifest binds no class to it")); - try { - return mapper.readValue(payload, target); - } catch (RuntimeException malformed) { - // The parser's message names the class, the field and often the offending bytes. None of it - // goes to the peer; the category is what a client can act on. - throw new WebSocketDecodeException( - WebSocketFailureCategory.MALFORMED, "the payload is not a valid " + type + " document"); - } - } - - /** - * Encodes one outbound frame. - * - * @param type the published type - * @param value the document to send - */ - public byte[] encodeToClient(WebSocketMessageType type, Object value) { - Objects.requireNonNull(type, "type"); - Objects.requireNonNull(value, "value"); - if (!catalog.acceptsFromServer(type)) { - throw new WebSocketDecodeException( - WebSocketFailureCategory.INTERNAL, - "the catalog does not publish " + type + " from the server"); - } - byte[] encoded = mapper.writeValueAsBytes(value); - if (!profile.withinBounds(encoded.length)) { - // Checked on the way out too. An oversized outbound frame is a server defect rather than a - // client one, and discovering it at the socket means the frame is already half written. - throw new WebSocketDecodeException( - WebSocketFailureCategory.TOO_LARGE, - "the encoded " + type + " exceeds the codec's ceiling"); - } - return encoded; - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/codec/protobuf/DescriptorCompatibility.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/codec/protobuf/DescriptorCompatibility.java deleted file mode 100644 index 031df9b3..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/codec/protobuf/DescriptorCompatibility.java +++ /dev/null @@ -1,29 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.codec.protobuf; - -/** - * How a descriptor change relates to the descriptors already deployed. - * - *

Protobuf's wire format is forgiving in a way that hides the dangerous changes. Renaming a - * field is invisible on the wire and therefore safe; changing a field's number, or reusing a - * retired one, silently reinterprets old bytes as a different field. Nothing errors — the receiver - * reads a value of the right type in the wrong place. - */ -public enum DescriptorCompatibility { - - /** Old readers read new messages and new readers read old ones. */ - FULLY_COMPATIBLE, - - /** New readers read old messages. Safe when every writer is upgraded first. */ - BACKWARD_COMPATIBLE, - - /** Old readers read new messages. Safe when every reader is upgraded first. */ - FORWARD_COMPATIBLE, - - /** - * Old bytes decode to something different. - * - *

A changed or reused field number, or a changed wire type on an existing number. The receiver - * does not error; it reads the wrong field, which surfaces as a data bug somewhere far away. - */ - BREAKING -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/codec/protobuf/DescriptorCompatibilityGate.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/codec/protobuf/DescriptorCompatibilityGate.java deleted file mode 100644 index 57156efe..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/codec/protobuf/DescriptorCompatibilityGate.java +++ /dev/null @@ -1,79 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.codec.protobuf; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Objects; - -/** - * Refuses a descriptor change that would reinterpret bytes already on the wire. - * - *

Required rather than advisory. During any rolling deploy both descriptor versions are live at - * once, so a breaking change is not a future problem — it is a guaranteed present one for the - * duration of the rollout, and it produces wrong values rather than errors. - * - *

The gate works on field numbers and wire types, because those are what the format actually - * carries. Field names are absent from the encoding entirely, which is why renaming is free and why - * a gate that compared names would pass exactly the changes that matter. - */ -public final class DescriptorCompatibilityGate { - - private DescriptorCompatibilityGate() {} - - /** - * Compare two descriptor field maps. - * - * @param deployed field number to wire type, as currently deployed - * @param candidate field number to wire type, as proposed - */ - public static DescriptorCompatibility compare( - Map deployed, Map candidate) { - Objects.requireNonNull(deployed, "deployed"); - Objects.requireNonNull(candidate, "candidate"); - for (Map.Entry field : deployed.entrySet()) { - String proposed = candidate.get(field.getKey()); - if (proposed != null && !proposed.equals(field.getValue())) { - // Same number, different type. Old bytes decode as the new type without complaint. - return DescriptorCompatibility.BREAKING; - } - } - boolean removed = deployed.keySet().stream().anyMatch(number -> !candidate.containsKey(number)); - boolean added = candidate.keySet().stream().anyMatch(number -> !deployed.containsKey(number)); - if (removed && added) { - return DescriptorCompatibility.BREAKING; - } - if (added) { - return DescriptorCompatibility.BACKWARD_COMPATIBLE; - } - if (removed) { - return DescriptorCompatibility.FORWARD_COMPATIBLE; - } - return DescriptorCompatibility.FULLY_COMPATIBLE; - } - - /** - * Fail the build for a change that cannot be rolled out. - * - * @param deployed field number to wire type, as currently deployed - * @param candidate field number to wire type, as proposed - */ - public static void verify(Map deployed, Map candidate) { - DescriptorCompatibility verdict = compare(deployed, candidate); - if (verdict == DescriptorCompatibility.BREAKING) { - List details = new ArrayList<>(); - for (Map.Entry field : deployed.entrySet()) { - String proposed = candidate.get(field.getKey()); - if (proposed != null && !proposed.equals(field.getValue())) { - details.add("field " + field.getKey() + ": " + field.getValue() + " became " + proposed); - } - } - deployed.keySet().stream() - .filter(number -> !candidate.containsKey(number)) - .forEach(number -> details.add("field " + number + " removed")); - throw new IllegalStateException( - "the descriptor change reinterprets bytes already on the wire; during a rolling deploy " - + "both versions are live and the receiver reads the wrong field without erroring: " - + details); - } - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/codec/protobuf/ProtobufCodecProfile.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/codec/protobuf/ProtobufCodecProfile.java deleted file mode 100644 index 1ecc4856..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/codec/protobuf/ProtobufCodecProfile.java +++ /dev/null @@ -1,51 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.codec.protobuf; - -import dev.caskeleton.adapter.inbound.websocket.advanced.codec.BinaryCodecProfile; -import java.util.Objects; - -/** - * Protobuf as a wire codec, and the descriptors it is bound to. - * - *

The artifact is named because a Protobuf codec is only as compatible as the descriptor set it - * was generated from, and "the current one" is not a version anybody can compare against during an - * incident. - * - *

{@code maxMessageBytes} bounds the decoded message, and it is separate from the frame bound - * for the reason length-prefixed formats always need it: the frame carries a length, the decoder - * allocates it, and a frame within the transport limit can still declare a length far beyond it. - * - *

File bytes do not go in a Protobuf payload. A binary field is exactly as convenient for an - * attachment as it looks, and the result is a message the broker, the replay store and every - * in-memory queue must hold whole. The reference belongs on the wire and the bytes belong in object - * storage. - * - * @param descriptorArtifact the coordinates of the descriptor set this codec was generated from - * @param binary the bounds and semantics shared with every other codec - */ -public record ProtobufCodecProfile(String descriptorArtifact, BinaryCodecProfile binary) { - - /** Above this, a payload is an attachment pretending to be a message. */ - public static final int ATTACHMENT_THRESHOLD_BYTES = 256 * 1024; - - public ProtobufCodecProfile { - Objects.requireNonNull(descriptorArtifact, "descriptorArtifact"); - Objects.requireNonNull(binary, "binary"); - if (descriptorArtifact.isBlank()) { - throw new IllegalArgumentException( - "the descriptor artifact must be named; 'the current one' is not a version that can be " - + "compared against during an incident"); - } - if (binary.maxMessageBytes() > ATTACHMENT_THRESHOLD_BYTES) { - throw new IllegalArgumentException( - "a message ceiling above " - + ATTACHMENT_THRESHOLD_BYTES - + " bytes makes the codec an attachment transport; the broker, the replay store and " - + "every in-memory queue would each hold it whole"); - } - } - - /** Whether a decoded message is within bounds. */ - public boolean withinBounds(int messageBytes) { - return binary.withinBounds(messageBytes); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/codec/protobuf/WebSocketProtobufCodec.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/codec/protobuf/WebSocketProtobufCodec.java deleted file mode 100644 index 3b976197..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/codec/protobuf/WebSocketProtobufCodec.java +++ /dev/null @@ -1,159 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.codec.protobuf; - -import com.google.protobuf.CodedInputStream; -import com.google.protobuf.Descriptors; -import com.google.protobuf.DynamicMessage; -import com.google.protobuf.Message; -import dev.caskeleton.adapter.inbound.websocket.advanced.codec.WebSocketBinaryCodecBackend; -import dev.caskeleton.adapter.inbound.websocket.codec.WebSocketDecodeException; -import dev.caskeleton.adapter.inbound.websocket.error.WebSocketFailureCategory; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageCatalog; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageFamily; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageType; -import java.util.Map; -import java.util.Objects; - -/** - * The Protobuf wire codec, driven by descriptors rather than generated classes. - * - *

Descriptor-driven because a template has no {@code .proto} of its own and should not invent - * one. A deployment compiles its schema, supplies the resulting {@link Descriptors.Descriptor} per - * published message type, and this decodes into {@link DynamicMessage} — which is what protobuf's - * own tooling does when the schema is not known at build time. The alternative, generating a - * placeholder message so the codec has something to compile against, would ship a wire contract - * nobody chose. - * - *

Unknown fields are dropped rather than preserved. Protobuf's default is to - * retain them so an intermediary can round-trip a message it does not fully understand, and that is - * exactly wrong at a trust boundary: retaining means this server would re-emit bytes it never - * validated, and a field it cannot see is a field its authorization checks cannot consider. - * - *

The recursion limit is set below protobuf's default. Nested length-delimited - * fields are parsed recursively, so a small frame can drive deep recursion; the default of 100 is - * generous for a message that is supposed to be a transport envelope. - * - *

The catalog is consulted before the parser, as in every other codec here. An unpublished type - * never reaches a decoder, so a second decode path does not widen the set of reachable types. - */ -public final class WebSocketProtobufCodec { - - /** Deeper than any envelope and far below protobuf's default of 100. */ - private static final int MAX_RECURSION_DEPTH = 16; - - private final WebSocketMessageCatalog catalog; - private final Map descriptors; - private final ProtobufCodecProfile profile; - - /** - * A codec over one catalog and one descriptor set. - * - * @param catalog which types are published - * @param descriptors the compiled descriptor per published type - * @param profile the descriptor artifact this was built from, and the bounds - */ - public WebSocketProtobufCodec( - WebSocketMessageCatalog catalog, - Map descriptors, - ProtobufCodecProfile profile) { - WebSocketBinaryCodecBackend.PROTOBUF.require(); - this.catalog = Objects.requireNonNull(catalog, "catalog"); - this.descriptors = Map.copyOf(Objects.requireNonNull(descriptors, "descriptors")); - this.profile = Objects.requireNonNull(profile, "profile"); - if (this.descriptors.isEmpty()) { - throw new IllegalArgumentException( - "a Protobuf codec with no descriptor decodes nothing; a deployment that has not compiled" - + " its schema should not enable the capability"); - } - } - - /** The profile, including the descriptor artifact this was built from. */ - public ProtobufCodecProfile profile() { - return profile; - } - - /** - * Decodes one inbound frame. - * - * @param type the published type the envelope named - * @param family the family the envelope claimed - * @param payload the encoded frame - * @throws WebSocketDecodeException when anything about it is not exactly right - */ - public Message decodeFromClient( - WebSocketMessageType type, WebSocketMessageFamily family, byte[] payload) { - Objects.requireNonNull(type, "type"); - Objects.requireNonNull(family, "family"); - Objects.requireNonNull(payload, "payload"); - if (!profile.withinBounds(payload.length)) { - throw new WebSocketDecodeException( - WebSocketFailureCategory.TOO_LARGE, "the frame exceeds the codec's ceiling"); - } - if (catalog.admitFromClient(type, family).isEmpty()) { - throw new WebSocketDecodeException( - WebSocketFailureCategory.UNKNOWN_TYPE, - "this endpoint does not accept " + type + " from a client"); - } - Descriptors.Descriptor descriptor = descriptors.get(type); - if (descriptor == null) { - throw new WebSocketDecodeException( - WebSocketFailureCategory.INTERNAL, - "the catalog publishes " + type + " but no descriptor is compiled for it"); - } - try { - CodedInputStream input = CodedInputStream.newInstance(payload); - input.setRecursionLimit(MAX_RECURSION_DEPTH); - DynamicMessage.Builder builder = DynamicMessage.newBuilder(descriptor); - builder.mergeFrom(input); - // Checked explicitly. mergeFrom does not fail on a truncated frame that happens to end on a - // field boundary, and a message missing a required field would otherwise reach a handler - // that has no way to tell it apart from one where the field was legitimately absent. - input.checkLastTagWas(0); - DynamicMessage message = builder.build(); - if (!message.getUnknownFields().asMap().isEmpty()) { - // Not merely dropped — refused. A frame carrying fields this build does not know is either - // a newer peer or a probe, and both deserve an explicit answer rather than silent partial - // acceptance. - throw new WebSocketDecodeException( - WebSocketFailureCategory.MALFORMED, - "the payload carries fields this build does not publish for " + type); - } - return message; - } catch (java.io.IOException malformed) { - // The parser's message names field numbers and offsets. None of it goes to the peer. - throw new WebSocketDecodeException( - WebSocketFailureCategory.MALFORMED, "the payload is not a valid " + type + " message"); - } - } - - /** - * Encodes one outbound frame. - * - * @param type the published type - * @param message the message to send, built against this type's descriptor - */ - public byte[] encodeToClient(WebSocketMessageType type, Message message) { - Objects.requireNonNull(type, "type"); - Objects.requireNonNull(message, "message"); - if (!catalog.acceptsFromServer(type)) { - throw new WebSocketDecodeException( - WebSocketFailureCategory.INTERNAL, - "the catalog does not publish " + type + " from the server"); - } - Descriptors.Descriptor descriptor = descriptors.get(type); - if (descriptor == null || !descriptor.equals(message.getDescriptorForType())) { - // A message built against a different descriptor encodes to bytes the peer will decode as - // this type — field numbers collide across schemas, so the result is not a parse failure but - // a well-formed message with the wrong values. - throw new WebSocketDecodeException( - WebSocketFailureCategory.INTERNAL, - "the message was built against a different descriptor than " + type + " publishes"); - } - byte[] encoded = message.toByteArray(); - if (!profile.withinBounds(encoded.length)) { - throw new WebSocketDecodeException( - WebSocketFailureCategory.TOO_LARGE, - "the encoded " + type + " exceeds the codec's ceiling"); - } - return encoded; - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/compression/CompressionPolicy.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/compression/CompressionPolicy.java deleted file mode 100644 index 53e7902a..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/compression/CompressionPolicy.java +++ /dev/null @@ -1,91 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.compression; - -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketEndpointName; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -/** - * Whether one endpoint may compress, and how large a decompressed message may get. - * - *

Two bounds, and the second is the one that is usually missing. The frame size limit applies to - * what arrives on the wire; a compressed frame within that limit can inflate to hundreds of times - * its size, so a 64KB frame limit with a 1000:1 ratio is a 64MB allocation from a single frame that - * every inbound bound was satisfied with. The decompressed limit has to be checked during - * inflation, not after, or the allocation has already happened by the time it fails. - */ -public final class CompressionPolicy { - - private final Map contentClasses; - private final CompressionProfile profile; - private final long maxDecompressedBytes; - - /** - * @param profile the negotiated parameters - * @param maxDecompressedBytes the ceiling on one inflated message - * @param contentClasses what each endpoint carries - */ - public CompressionPolicy( - CompressionProfile profile, - long maxDecompressedBytes, - Map contentClasses) { - this.profile = Objects.requireNonNull(profile, "profile"); - this.contentClasses = Map.copyOf(Objects.requireNonNull(contentClasses, "contentClasses")); - if (profile.enabled() && maxDecompressedBytes < 1) { - throw new IllegalArgumentException( - "compression without a decompressed-size ceiling turns one frame inside the inbound " - + "limit into an allocation hundreds of times larger"); - } - this.maxDecompressedBytes = maxDecompressedBytes; - } - - /** The negotiated parameters. */ - public CompressionProfile profile() { - return profile; - } - - /** The ceiling on one inflated message. */ - public long maxDecompressedBytes() { - return maxDecompressedBytes; - } - - /** - * Whether this endpoint may negotiate the extension. - * - *

Refused for an endpoint that mixes a secret with attacker-influenced content, regardless of - * how the profile is configured. No parameter combination makes that combination safe: the leak - * is in the compressed length, which every setting produces. - */ - public boolean mayCompress(WebSocketEndpointName endpoint) { - if (!profile.enabled()) { - return false; - } - return contentClassOf(endpoint) - .map(kind -> kind != EndpointContentClass.SENSITIVE_WITH_ATTACKER_INFLUENCE) - // An undeclared endpoint does not compress. Defaulting the other way makes every endpoint - // somebody forgot to classify a candidate for the one failure this class prevents. - .orElse(false); - } - - /** What the endpoint was declared to carry. */ - public Optional contentClassOf(WebSocketEndpointName endpoint) { - return Optional.ofNullable(contentClasses.get(endpoint)); - } - - /** - * Whether inflation may continue. - * - * @param bytesSoFar how much has been produced already - */ - public boolean mayInflateFurther(long bytesSoFar) { - return bytesSoFar <= maxDecompressedBytes; - } - - /** The expansion ratio a frame of this size is allowed before the ceiling stops it. */ - public long permittedRatioFor(long compressedBytes) { - if (compressedBytes <= 0) { - throw new IllegalArgumentException("a frame has a positive size"); - } - return maxDecompressedBytes / compressedBytes; - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/compression/CompressionProfile.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/compression/CompressionProfile.java deleted file mode 100644 index ab594a1e..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/compression/CompressionProfile.java +++ /dev/null @@ -1,72 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.compression; - -/** - * RFC 7692 {@code permessage-deflate} parameters for one endpoint. - * - *

Off by default and per endpoint, never global. Compression on a connection that carries - * attacker-influenced data alongside a secret is the CRIME/BREACH shape: the compressed length of a - * message leaks how much the attacker's guess overlapped the secret, one byte at a time. Deciding - * that requires knowing what the endpoint carries, which is an endpoint-level fact. - * - *

The two {@code noContextTakeover} flags are the memory bound. With context takeover, each - * connection keeps a sliding window alive between messages — a 32KB window per direction per - * connection, so ten thousand connections is 640MB of window before a single message is buffered. - * Turning it off costs compression ratio and makes the memory cost per connection a constant rather - * than a function of how long it stays open. - * - * @param enabled whether the extension is offered at all - * @param serverNoContextTakeover whether the server resets its window between messages - * @param clientNoContextTakeover whether the client is required to reset its window - * @param maxWindowBits the window size exponent, 8 to 15 per the RFC - * @param minCompressBytes the size below which a message is sent uncompressed - */ -public record CompressionProfile( - boolean enabled, - boolean serverNoContextTakeover, - boolean clientNoContextTakeover, - int maxWindowBits, - int minCompressBytes) { - - public CompressionProfile { - if (enabled) { - if (maxWindowBits < 8 || maxWindowBits > 15) { - throw new IllegalArgumentException( - "permessage-deflate window bits must be 8..15 per RFC 7692 section 7.1.2: " - + maxWindowBits); - } - if (minCompressBytes < 0) { - throw new IllegalArgumentException("a negative compression threshold is not a size"); - } - } - } - - /** The default: nothing compressed. */ - public static CompressionProfile disabled() { - return new CompressionProfile(false, true, true, 15, 0); - } - - /** - * Compression with both windows reset between messages. - * - *

The only shape recommended for a connection whose message count is not known in advance, - * because it is the only one whose memory cost does not grow with connection lifetime. - */ - public static CompressionProfile boundedMemory(int maxWindowBits, int minCompressBytes) { - return new CompressionProfile(true, true, true, maxWindowBits, minCompressBytes); - } - - /** Bytes of sliding window one connection holds, both directions. */ - public long windowBytesPerConnection() { - if (!enabled) { - return 0L; - } - long window = 1L << maxWindowBits; - long directions = (serverNoContextTakeover ? 0 : 1) + (long) (clientNoContextTakeover ? 0 : 1); - return window * directions; - } - - /** Whether a message of this size is worth compressing. */ - public boolean shouldCompress(int messageBytes) { - return enabled && messageBytes >= minCompressBytes; - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/compression/EndpointContentClass.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/compression/EndpointContentClass.java deleted file mode 100644 index 69c730f3..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/compression/EndpointContentClass.java +++ /dev/null @@ -1,30 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.compression; - -/** - * What kind of data an endpoint's messages carry. - * - *

Declared per endpoint because it is the input to the one compression decision that cannot be - * made from configuration alone. The combination that matters is a secret and attacker-influenced - * text in the same compression context. - */ -public enum EndpointContentClass { - - /** Nothing sensitive and nothing the caller controls. Safe to compress. */ - PUBLIC_DATA, - - /** Content a caller can influence, with no secret alongside it. */ - ATTACKER_INFLUENCED, - - /** - * A secret — a token, a key, another user's data — with nothing attacker-controlled beside it. - */ - SENSITIVE, - - /** - * Both, in the same messages. - * - *

The CRIME/BREACH shape. Compressed length reveals how much a guess overlapped the secret, - * and an attacker who can inject a guess into each message recovers the secret a byte at a time. - */ - SENSITIVE_WITH_ATTACKER_INFLUENCE -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/graphql/GraphQlCloseCode.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/graphql/GraphQlCloseCode.java deleted file mode 100644 index fbeb4871..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/graphql/GraphQlCloseCode.java +++ /dev/null @@ -1,52 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.graphql; - -/** - * The close codes {@code graphql-transport-ws} defines for the transport layer. - * - *

Here rather than in the platform's {@code WebSocketCloseCode}, because these belong to one - * subprotocol. Two of them collide numerically with codes the platform already uses for unrelated - * reasons — 4401 is the platform's expired credential and 4408 its idle timeout — and merging the - * two vocabularies would make a close code ambiguous to whoever reads it in a log. - * - *

The specification assigns each of these a meaning the client acts on, which is why they are - * codes rather than a generic policy violation: a client that receives 4409 knows to pick a - * different operation id, and one that receives 4408 knows to send {@code connection_init} sooner. - */ -public enum GraphQlCloseCode { - - /** The connection was used before it was acknowledged. */ - UNAUTHORIZED(4401, "unauthorized"), - - /** {@code connection_init} did not arrive within the deadline. */ - INITIALISATION_TIMEOUT(4408, "connection initialisation timeout"), - - /** A live subscription already has this operation id. */ - SUBSCRIBER_ALREADY_EXISTS(4409, "subscriber already exists"), - - /** {@code connection_init} arrived more than once. */ - TOO_MANY_INITIALISATION_REQUESTS(4429, "too many initialisation requests"); - - private final int code; - private final String reason; - - GraphQlCloseCode(int code, String reason) { - this.code = code; - this.reason = reason; - } - - /** The numeric close code. */ - public int code() { - return code; - } - - /** - * The close reason. - * - *

Fixed text, never the client's own input. A close reason is echoed straight back over the - * wire, and reflecting what the client sent is how a close frame becomes an injection point into - * whatever reads the peer's logs. - */ - public String reason() { - return reason; - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/graphql/GraphQlTransportBridge.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/graphql/GraphQlTransportBridge.java deleted file mode 100644 index 0c6e8e8d..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/graphql/GraphQlTransportBridge.java +++ /dev/null @@ -1,163 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.graphql; - -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketConnectionContext; -import java.time.Duration; -import java.time.Instant; -import java.util.List; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.atomic.AtomicReference; -import java.util.function.BiConsumer; - -/** - * Carries {@code graphql-transport-ws} frames on the Stable connection runtime. - * - *

A transport bridge and nothing more. It moves opaque documents in both directions and enforces - * the two rules the subprotocol places on the transport itself — the ones a GraphQL engine cannot - * enforce because they are about the connection, not about a query. - * - *

{@code connection_init} must arrive first, once, within a deadline. The - * specification requires the server to close 4408 if it does not arrive in time and 4429 if it - * arrives twice. Both matter for the same reason: without them an unauthenticated socket can be - * held open indefinitely, which is a connection slot spent by anyone who can open a TCP connection. - * - *

A subscription id must be unique per connection. Reusing a live id is 4409, - * and the reason is not tidiness: the id is what routes {@code next} and {@code complete} frames - * back, so two subscriptions sharing one would interleave their results into a single client-side - * stream with nothing to separate them. - * - *

Everything else — what the document means, whether it validates, what an error looks like — is - * forwarded untouched. Reimplementing any of it would create a second definition of a GraphQL error - * that disagrees with the engine's the first time a resolver throws something unanticipated. - */ -public final class GraphQlTransportBridge { - - private final GraphQlTransportBridgePolicy policy; - private final Duration initDeadline; - private final Set liveSubscriptions = ConcurrentHashMap.newKeySet(); - private final AtomicReference acknowledgedAt = new AtomicReference<>(); - - /** - * @param policy the bridge's contract, which fixes what it does not own - * @param initDeadline how long a connection may stay unacknowledged - */ - public GraphQlTransportBridge(GraphQlTransportBridgePolicy policy, Duration initDeadline) { - this.policy = Objects.requireNonNull(policy, "policy"); - this.initDeadline = Objects.requireNonNull(initDeadline, "initDeadline"); - if (initDeadline.isNegative() || initDeadline.isZero()) { - throw new IllegalArgumentException( - "without an init deadline an unauthenticated socket is held for as long as the peer" - + " cares to hold it, which is a connection slot spent by anyone who can connect"); - } - } - - /** The contract this bridge runs under. */ - public GraphQlTransportBridgePolicy policy() { - return policy; - } - - /** - * Handle {@code connection_init}. - * - * @param at when it arrived - * @return empty when the connection is acknowledged, or the close code it earned - */ - public Optional onConnectionInit(Instant at) { - Objects.requireNonNull(at, "at"); - if (!acknowledgedAt.compareAndSet(null, at)) { - // 4429. A second init is not a retry: the first one already established the connection's - // parameters, and honouring a second would let a client change them mid-connection. - return Optional.of(GraphQlCloseCode.TOO_MANY_INITIALISATION_REQUESTS); - } - return Optional.empty(); - } - - /** - * Whether an unacknowledged connection has run out of time. - * - * @param now the current instant - * @param openedAt when the socket was accepted - */ - public Optional initTimeoutAt(Instant openedAt, Instant now) { - Objects.requireNonNull(openedAt, "openedAt"); - Objects.requireNonNull(now, "now"); - if (acknowledgedAt.get() != null) { - return Optional.empty(); - } - if (now.isBefore(openedAt.plus(initDeadline))) { - return Optional.empty(); - } - return Optional.of(GraphQlCloseCode.INITIALISATION_TIMEOUT); - } - - /** Whether the connection has been acknowledged. */ - public boolean acknowledged() { - return acknowledgedAt.get() != null; - } - - /** - * Handle {@code subscribe}. - * - * @param id the client-chosen operation id - * @return empty when the subscription may start, or the close code it earned - */ - public Optional onSubscribe(String id) { - Objects.requireNonNull(id, "id"); - if (!acknowledged()) { - // 4401. A subscribe before init is not merely early: nothing has authenticated the - // connection yet, so serving it would run an operation for a peer nobody identified. - return Optional.of(GraphQlCloseCode.UNAUTHORIZED); - } - if (!liveSubscriptions.add(id)) { - // 4409. The id routes next and complete frames back, so two live subscriptions sharing one - // interleave into a single client-side stream with nothing to separate them. - return Optional.of(GraphQlCloseCode.SUBSCRIBER_ALREADY_EXISTS); - } - return Optional.empty(); - } - - /** - * Handle {@code complete} from either side. - * - *

Releases the id for reuse, which the specification permits once the subscription has ended. - * Holding it would make a client that reuses ids sequentially fail on its second operation. - */ - public void onComplete(String id) { - liveSubscriptions.remove(Objects.requireNonNull(id, "id")); - } - - /** How many subscriptions are live on this connection. */ - public int liveSubscriptions() { - return liveSubscriptions.size(); - } - - /** - * Forward a frame to the GraphQL engine without interpreting it. - * - * @param context the Stable connection this frame arrived on - * @param payload the frame, exactly as received - * @param engine what to hand it to - */ - public void forward( - WebSocketConnectionContext context, - String payload, - BiConsumer engine) { - Objects.requireNonNull(context, "context"); - Objects.requireNonNull(payload, "payload"); - Objects.requireNonNull(engine, "engine"); - // Untouched. Parsing here to "validate" would be the start of a second GraphQL implementation, - // and it would disagree with the engine's the first time a resolver throws something this - // class did not anticipate. - engine.accept(context, payload); - } - - /** What this bridge enforces, as opposed to what it forwards. */ - public List enforcedByTheTransport() { - return List.of( - "connection_init arrives once, before anything else, within the deadline (4408, 4429)", - "subscribe arrives only after acknowledgement (4401)", - "an operation id is unique among live subscriptions (4409)"); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/graphql/GraphQlTransportBridgePolicy.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/graphql/GraphQlTransportBridgePolicy.java deleted file mode 100644 index 57b723ee..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/graphql/GraphQlTransportBridgePolicy.java +++ /dev/null @@ -1,71 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.graphql; - -import java.util.List; -import java.util.Objects; - -/** - * Carrying {@code graphql-transport-ws} frames on the Stable connection runtime. - * - *

A transport bridge and nothing else. The two false flags are the contract: this does not own - * GraphQL semantics, and it does not implement its own connection runtime. - * - *

The first matters because {@code graphql-transport-ws} has its own lifecycle — {@code - * connection_init}, {@code subscribe}, {@code next}, {@code complete}, {@code error} — that looks - * enough like a message protocol to reimplement by accident. Reimplementing it produces a second - * definition of what a GraphQL error is, and the two disagree the first time a resolver throws - * something the bridge did not anticipate. The GraphQL platform owns those semantics; this carries - * bytes. - * - *

The second matters because a bridge that opened its own connections would have its own - * heartbeat, its own queue bound, its own backpressure and its own security checks — none of which - * would be the ones the platform was reviewed with. - * - * @param subprotocol the negotiated subprotocol token - * @param ownsGraphQlSemantics always false - * @param usesStableConnectionRuntime always true - */ -public record GraphQlTransportBridgePolicy( - String subprotocol, boolean ownsGraphQlSemantics, boolean usesStableConnectionRuntime) { - - /** The subprotocol token defined by the graphql-ws specification. */ - public static final String SUBPROTOCOL = "graphql-transport-ws"; - - public GraphQlTransportBridgePolicy { - Objects.requireNonNull(subprotocol, "subprotocol"); - if (ownsGraphQlSemantics) { - throw new IllegalArgumentException( - "the bridge must not own GraphQL semantics: a second definition of what an error or a " - + "completed subscription is disagrees with the first the moment a resolver throws " - + "something it did not anticipate"); - } - if (!usesStableConnectionRuntime) { - throw new IllegalArgumentException( - "the bridge must reuse the Stable connection runtime: its own would have its own " - + "heartbeat, queue bound, backpressure and security checks, none of them the ones " - + "the platform was reviewed with"); - } - } - - /** The only shape this policy has. */ - public static GraphQlTransportBridgePolicy standard() { - return new GraphQlTransportBridgePolicy(SUBPROTOCOL, false, true); - } - - /** What the bridge forwards rather than interprets. */ - public List forwardedWithoutInterpretation() { - return List.of( - "connection_init and connection_ack", - "subscribe, next, complete and error", - "ping and pong at the graphql-ws layer", - "the GraphQL document, its variables and its extensions"); - } - - /** What it reuses from Stable rather than reimplementing. */ - public List reusedFromStable() { - return List.of( - "handshake admission: origin, authentication and connection budget", - "the outbound queue and its shedding bound", - "the heartbeat and the close orchestration", - "the connection evidence chain"); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/http2/Http2CompatibilityProfile.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/http2/Http2CompatibilityProfile.java deleted file mode 100644 index 29cd4cfc..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/http2/Http2CompatibilityProfile.java +++ /dev/null @@ -1,64 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.http2; - -import java.util.List; -import java.util.Objects; -import java.util.Set; - -/** - * WebSocket over HTTP/2 via RFC 8441 extended CONNECT. - * - *

The distinction this class exists to hold: the standard existing is not the same as the path - * supporting it. RFC 8441 has been published since 2018, and a request still fails if any single - * hop between the browser and the runtime does not implement extended CONNECT — a load balancer, an - * ingress controller, a corporate proxy. The failure is not a clean negotiation fallback; the - * intermediary sees a CONNECT it does not recognise and the connection dies. - * - *

So the profile is a list of hops somebody actually tested, not a boolean. Enabling it on the - * strength of "HTTP/2 is supported" is how a deployment discovers that its ingress is the one hop - * that is not, at the point where every client has already switched. - * - * @param enabled whether extended CONNECT is offered - * @param validatedClients client stacks an end-to-end test has passed against - * @param validatedProxies intermediaries an end-to-end test has passed through - */ -public record Http2CompatibilityProfile( - boolean enabled, Set validatedClients, Set validatedProxies) { - - public Http2CompatibilityProfile { - validatedClients = Set.copyOf(Objects.requireNonNull(validatedClients, "validatedClients")); - validatedProxies = Set.copyOf(Objects.requireNonNull(validatedProxies, "validatedProxies")); - if (enabled && (validatedClients.isEmpty() || validatedProxies.isEmpty())) { - throw new IllegalArgumentException( - "extended CONNECT cannot be enabled without a validated client and a validated proxy; " - + "one unsupporting hop kills the connection rather than negotiating a fallback"); - } - } - - /** The default. */ - public static Http2CompatibilityProfile disabled() { - return new Http2CompatibilityProfile(false, Set.of(), Set.of()); - } - - /** - * Whether a request arriving over this path may use extended CONNECT. - * - *

Both hops checked, and an unlisted hop is refused rather than assumed. The assumption is the - * whole failure: an untested intermediary is exactly the one that will not implement it. - */ - public boolean supports(String client, String proxy) { - return enabled && validatedClients.contains(client) && validatedProxies.contains(proxy); - } - - /** - * What a client that cannot use extended CONNECT does instead. - * - *

A classic HTTP/1.1 Upgrade, which every hop already handles. Keeping the fallback working is - * not optional: it is what every unlisted client uses, and it is what the listed ones fall back - * to when a proxy is swapped. - */ - public List fallbackPath() { - return List.of( - "HTTP/1.1 GET with Connection: Upgrade and Upgrade: websocket", - "the classic handshake must keep passing its own contract test while this is enabled"); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/http3/Http3ExperimentalProfile.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/http3/Http3ExperimentalProfile.java deleted file mode 100644 index e4b36721..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/http3/Http3ExperimentalProfile.java +++ /dev/null @@ -1,67 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.http3; - -import java.util.List; -import java.util.Objects; -import java.util.Set; - -/** - * WebSocket over HTTP/3 per RFC 9220. Experimental, and labelled so in the type. - * - *

"Experimental" here is a support statement, not a maturity opinion. RFC 9220 extends the RFC - * 8441 mechanism to HTTP/3, which means it inherits every hop-support problem HTTP/2 has and adds - * QUIC on top: a UDP transport that a meaningful fraction of corporate networks block outright, and - * whose implementations differ in ways that only appear under packet loss. - * - *

{@link #promotable(boolean, boolean)} refuses promotion without a rollback path. That is the - * one requirement that cannot be waived: an experimental transport whose failure mode is "the - * connection does not establish on this network" needs a way back to HTTP/1.1 that does not require - * a deploy, because the population that cannot connect is also the population that cannot be - * surveyed. - * - * @param enabled whether the experimental listener is started - * @param quicImplementation which QUIC stack is in use, named because they differ - * @param validatedClients client stacks an end-to-end test has passed against - */ -public record Http3ExperimentalProfile( - boolean enabled, String quicImplementation, Set validatedClients) { - - public Http3ExperimentalProfile { - Objects.requireNonNull(quicImplementation, "quicImplementation"); - validatedClients = Set.copyOf(Objects.requireNonNull(validatedClients, "validatedClients")); - if (enabled && quicImplementation.isBlank()) { - throw new IllegalArgumentException( - "the QUIC implementation must be named: they differ under packet loss, and 'HTTP/3' " - + "does not say which behaviour an incident is exhibiting"); - } - } - - /** The default. */ - public static Http3ExperimentalProfile disabled() { - return new Http3ExperimentalProfile(false, "none", Set.of()); - } - - /** Never true. Advertising this as stable support is the thing the type exists to prevent. */ - public boolean stableSupport() { - return false; - } - - /** - * Whether this may be promoted to production. - * - * @param rollbackWithoutDeploy whether HTTP/3 can be turned off without shipping a build - * @param fallbackValidated whether the HTTP/1.1 path is tested and working - */ - public boolean promotable(boolean rollbackWithoutDeploy, boolean fallbackValidated) { - return enabled && rollbackWithoutDeploy && fallbackValidated && !validatedClients.isEmpty(); - } - - /** What has to be recorded separately, because a single pass/fail hides all of it. */ - public List requiredMatrixDimensions() { - return List.of( - "QUIC implementation and version", - "browser and version", - "intermediary: CDN, ingress, corporate proxy", - "network: UDP permitted, UDP blocked, UDP rate-limited", - "behaviour under packet loss and under path migration"); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/presence/PortBackedPresenceStore.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/presence/PortBackedPresenceStore.java deleted file mode 100644 index a12323b2..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/presence/PortBackedPresenceStore.java +++ /dev/null @@ -1,98 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.presence; - -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketActorReference; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketEndpointName; -import dev.caskeleton.application.realtime.ActorFingerprint; -import dev.caskeleton.application.realtime.ConnectionRegistration; -import dev.caskeleton.application.realtime.ConnectionRegistryPort; -import dev.caskeleton.application.realtime.RealtimeChannel; -import java.time.Duration; -import java.time.Instant; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.function.Function; -import java.util.stream.Collectors; - -/** - * Presence, derived from the same registry that answers "where is this actor". - * - *

Derived rather than stored separately, and that is the decision worth stating. A second store - * for "who is online" would drift from the first, and the drift would be invisible: both would look - * plausible, both would be recent, and nothing would reconcile them. Here the two answers cannot - * disagree because there is only one answer. - * - *

The connection counts are summed across nodes. An actor with two browser tabs on different - * nodes is one person with two connections, not two presences, and reporting the highest single - * node's count would under-report them while reporting the entry count would over-report. - * - *

The observation time is the oldest of the contributing entries, not the newest. - * Taking the newest would let one freshly-refreshed node make an otherwise stale picture look - * current — which is exactly the case presence must not get wrong, because a stale entry reporting - * connections is a node that stopped reporting rather than a user who is there. - */ -public final class PortBackedPresenceStore implements PresenceStore { - - private final ConnectionRegistryPort registry; - private final WebSocketEndpointName endpoint; - private final Duration idleAfter; - private final Duration staleAfter; - - /** - * @param registry where connections are reported - * @param endpoint which feed presence is read for - * @param idleAfter how long without a refresh counts as idle rather than online - * @param staleAfter how old an observation may be before it means nothing - */ - public PortBackedPresenceStore( - ConnectionRegistryPort registry, - WebSocketEndpointName endpoint, - Duration idleAfter, - Duration staleAfter) { - this.registry = Objects.requireNonNull(registry, "registry"); - this.endpoint = Objects.requireNonNull(endpoint, "endpoint"); - this.idleAfter = Objects.requireNonNull(idleAfter, "idleAfter"); - this.staleAfter = Objects.requireNonNull(staleAfter, "staleAfter"); - if (idleAfter.compareTo(staleAfter) >= 0) { - throw new IllegalArgumentException( - "idleAfter must be shorter than staleAfter, otherwise nothing is ever idle and the" - + " distinction the two states exist for is silently unreachable"); - } - } - - @Override - public PresenceSummary presenceOf(WebSocketActorReference actor, Instant now) { - Objects.requireNonNull(actor, "actor"); - Objects.requireNonNull(now, "now"); - List reported = - registry.locate( - new ActorFingerprint(actor.fingerprint()), new RealtimeChannel(endpoint.value()), now); - if (reported.isEmpty()) { - // Nothing reported is not the same as nobody connected, and the classifier is what decides - // which. An empty result with a current clock is OFFLINE; the registry degrading to empty - // during an outage produces the same answer, which is the known limitation of deriving - // presence from a cache and the reason nothing security-relevant may depend on it. - return PresenceSummary.absent(actor, now); - } - int connections = reported.stream().mapToInt(ConnectionRegistration::connectionCount).sum(); - Instant oldest = - reported.stream() - .map(ConnectionRegistration::observedAt) - .min(Instant::compareTo) - .orElse(now); - return PresenceSummary.classify(actor, connections, oldest, idleAfter, staleAfter, now); - } - - @Override - public Map presenceOf( - List actors, Instant now) { - Objects.requireNonNull(actors, "actors"); - Objects.requireNonNull(now, "now"); - // One registry read per actor. The port has no batch lookup, and adding one that fanned out to - // per-key reads underneath would hide the cost rather than remove it — a caller rendering a - // thousand-row list should see that it is asking for a thousand reads. - return actors.stream() - .distinct() - .collect(Collectors.toMap(Function.identity(), actor -> presenceOf(actor, now))); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/presence/PresenceState.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/presence/PresenceState.java deleted file mode 100644 index ce252383..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/presence/PresenceState.java +++ /dev/null @@ -1,29 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.presence; - -/** - * What the cluster last observed about an actor's connections. - * - *

Four states rather than a boolean, because the two ways of not being online are not the same - * thing and the difference is the one that matters operationally. {@link #OFFLINE} is a fact the - * cluster reported: nothing is connected. {@link #STALE} is the absence of a fact: whatever last - * reported has stopped reporting, and the platform does not know. Collapsing them shows a user as - * offline during a Redis partition, when the truth is that everyone is still connected and the - * index went dark. - */ -public enum PresenceState { - - /** Connections exist and were reported recently. */ - ONLINE, - - /** Connections exist but nothing has been sent or received on them for a while. */ - IDLE, - - /** - * The observation is too old to act on. Says nothing about whether connections exist — only that - * the index stopped being updated. - */ - STALE, - - /** The cluster reported, recently, that nothing is connected. */ - OFFLINE -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/presence/PresenceStore.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/presence/PresenceStore.java deleted file mode 100644 index a4265033..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/presence/PresenceStore.java +++ /dev/null @@ -1,33 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.presence; - -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketActorReference; -import java.time.Instant; -import java.util.List; -import java.util.Map; - -/** - * Where presence summaries are read from. - * - *

Read-only by design. Presence is derived from the cluster session index rather than written - * separately: a second source of truth for "who is connected" would drift from the first, and the - * drift is invisible — both look plausible, and nothing reconciles them. - */ -public interface PresenceStore { - - /** - * Presence for one actor. - * - * @param actor whose presence - * @param now the instant freshness is judged against - */ - PresenceSummary presenceOf(WebSocketActorReference actor, Instant now); - - /** - * Presence for several actors at once. - * - *

Batched because the caller is almost always rendering a list, and asking per actor turns one - * screen into as many round trips as it has rows. - */ - Map presenceOf( - List actors, Instant now); -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/presence/PresenceSummary.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/presence/PresenceSummary.java deleted file mode 100644 index e029fbdc..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/presence/PresenceSummary.java +++ /dev/null @@ -1,112 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.presence; - -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketActorReference; -import java.time.Duration; -import java.time.Instant; -import java.util.Objects; - -/** - * Whether someone appears to be connected, and when that was last true. - * - *

The observation time is not decoration; it is the only honest part. Presence is derived from a - * cluster index that is itself a cache of facts owned by other machines, so it is always a - * statement about the past. A summary without a timestamp invites the reader to treat it as - * current, and it never is. - * - *

Nothing security-relevant may depend on this. "The user is online" is not evidence that a - * request came from them, that a session is valid, or that a payment may proceed — a stale entry - * says online for a node that died, and an attacker who can make a node stop reporting can - * therefore make the platform believe someone is present or absent at will. Presence answers - * "should I show a green dot", and that is the whole of it. - * - * @param actor whose presence this is, by fingerprint - * @param activeConnectionCount how many connections the cluster reported - * @param state the classification at the time it was read - * @param lastObservedAt when the underlying index entry was written - */ -public record PresenceSummary( - WebSocketActorReference actor, - int activeConnectionCount, - PresenceState state, - Instant lastObservedAt) { - - public PresenceSummary { - Objects.requireNonNull(actor, "actor"); - Objects.requireNonNull(state, "state"); - Objects.requireNonNull(lastObservedAt, "lastObservedAt"); - if (activeConnectionCount < 0) { - throw new IllegalArgumentException("a connection count cannot be negative"); - } - if (state == PresenceState.OFFLINE && activeConnectionCount > 0) { - throw new IllegalArgumentException( - "offline with live connections is a contradiction, and it is the shape a caller ends up " - + "with when it sets the state by hand instead of classifying"); - } - } - - /** - * Classify a raw observation. - * - *

Staleness is checked before anything else, deliberately. An old entry reporting three - * connections is a node that stopped reporting, not a user with three connections, and reading - * the count first is exactly how that becomes a green dot for a machine that is gone. - * - * @param actor whose presence - * @param activeConnectionCount connections reported by the index - * @param lastObservedAt when the index entry was written - * @param idleAfter how long without an observation refresh counts as idle rather than online - * @param staleAfter how old an observation may be before it means nothing - * @param now the current instant - */ - public static PresenceSummary classify( - WebSocketActorReference actor, - int activeConnectionCount, - Instant lastObservedAt, - Duration idleAfter, - Duration staleAfter, - Instant now) { - Objects.requireNonNull(idleAfter, "idleAfter"); - Objects.requireNonNull(staleAfter, "staleAfter"); - if (idleAfter.compareTo(staleAfter) >= 0) { - throw new IllegalArgumentException( - "idleAfter must be shorter than staleAfter, otherwise nothing is ever idle and the " - + "distinction the two states exist for is silently unreachable"); - } - Instant reference = Objects.requireNonNull(now, "now"); - PresenceState state; - if (!reference.isBefore(lastObservedAt.plus(staleAfter))) { - state = PresenceState.STALE; - } else if (activeConnectionCount == 0) { - state = PresenceState.OFFLINE; - } else if (!reference.isBefore(lastObservedAt.plus(idleAfter))) { - state = PresenceState.IDLE; - } else { - state = PresenceState.ONLINE; - } - // A stale observation keeps its reported count so an operator can see what the index last - // said, but callers are steered to appearsOnline() rather than to the number. - return new PresenceSummary( - actor, state == PresenceState.OFFLINE ? 0 : activeConnectionCount, state, lastObservedAt); - } - - /** Nobody is reported connected. */ - public static PresenceSummary absent(WebSocketActorReference actor, Instant observedAt) { - return new PresenceSummary(actor, 0, PresenceState.OFFLINE, observedAt); - } - - /** Whether the observation is recent enough to be worth anything. */ - public boolean fresh() { - return state != PresenceState.STALE; - } - - /** - * Whether to show the actor as present. - * - *

{@link PresenceState#IDLE} counts: the connection is there, the person is not typing. A UI - * that wants to distinguish the two should read {@link #state()} rather than have this method - * decide for it. - */ - public boolean appearsOnline() { - return state == PresenceState.ONLINE || state == PresenceState.IDLE; - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/release/AdvancedPromotionGate.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/release/AdvancedPromotionGate.java deleted file mode 100644 index e5b2b7f2..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/release/AdvancedPromotionGate.java +++ /dev/null @@ -1,120 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.release; - -import dev.caskeleton.adapter.inbound.websocket.advanced.WebSocketAdvancedCapability; -import java.time.Duration; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; -import java.util.Set; - -/** - * What one Advanced capability must show before it goes to production. - * - *

Per capability, not per release. They share a feature-flag mechanism and nothing else: resume - * adds a token and a store, the cluster fan-out adds a network dependency to the delivery path, - * compression changes the memory profile of every connection. Promoting them together means the - * evidence for the cheapest one is treated as evidence for the most dangerous. - * - *

{@code stableArtifactUnchanged} is the condition that catches the failure this whole - * separation exists for. If turning on an Advanced capability changed the Stable wire contract or - * its dependency graph, then Stable was not independent of it, and every deployment that did not - * enable the capability has been changed anyway. - * - * @param requiredSuites the test suites that must have passed - * @param minimumSoak how long it must run under real traffic before promotion - * @param rollbackValidated whether turning it off again was actually exercised - * @param stableArtifactUnchanged whether Stable's wire contract and dependency graph are untouched - */ -public record AdvancedPromotionGate( - Set requiredSuites, - Duration minimumSoak, - boolean rollbackValidated, - boolean stableArtifactUnchanged) { - - public AdvancedPromotionGate { - requiredSuites = Set.copyOf(Objects.requireNonNull(requiredSuites, "requiredSuites")); - Objects.requireNonNull(minimumSoak, "minimumSoak"); - if (requiredSuites.isEmpty()) { - throw new IllegalArgumentException( - "a gate requiring no suite passes everything, which is worse than no gate because it " - + "reads as one"); - } - if (minimumSoak.isNegative() || minimumSoak.isZero()) { - throw new IllegalArgumentException( - "a zero soak is a promotion on the strength of a green build; the failures these " - + "capabilities have are the ones that need hours of real traffic to appear"); - } - } - - /** The gate for a capability, with the suites its own failure modes need. */ - public static AdvancedPromotionGate forCapability(WebSocketAdvancedCapability capability) { - Objects.requireNonNull(capability, "capability"); - return new AdvancedPromotionGate(suitesFor(capability), soakFor(capability), false, false); - } - - private static Set suitesFor(WebSocketAdvancedCapability capability) { - return switch (capability) { - case RESUME -> - Set.of("websocket:test", "websocketJettyTest", "resume-history-loss", "resume-replay"); - case CLUSTER_REDIS, CLUSTER_MESSAGING, PRESENCE -> - Set.of("websocket:test", "multi-node-fanout", "node-loss", "index-partition"); - case STOMP, BROKER_RELAY_RABBIT -> - Set.of("websocket:test", "broker-outage", "broker-reconnect", "user-destination"); - case COMPRESSION -> Set.of("websocket:test", "decompression-bound", "memory-under-load"); - case HTTP2_COMPAT, HTTP3_EXPERIMENTAL -> - Set.of( - "websocket:test", "websocketNginxTest", "proxy-matrix", "classic-upgrade-fallback"); - default -> Set.of("websocket:test", "websocketJettyTest"); - }; - } - - private static Duration soakFor(WebSocketAdvancedCapability capability) { - // Longer where the failure needs time or a real population to appear: a fan-out duplicate - // needs a rebalance, a memory leak needs connections that stay open, a proxy incompatibility - // needs the client population that has that proxy. - return switch (capability) { - case CLUSTER_REDIS, CLUSTER_MESSAGING, COMPRESSION -> Duration.ofHours(24); - case HTTP2_COMPAT, HTTP3_EXPERIMENTAL -> Duration.ofDays(7); - default -> Duration.ofHours(8); - }; - } - - /** - * Why this capability may not be promoted yet. - * - *

Returns the reasons rather than a boolean, because "not yet" without a list is a gate - * somebody works around instead of satisfying. - * - * @param passedSuites which suites actually passed - * @param observedSoak how long it has run under real traffic - */ - public List blockers(Set passedSuites, Duration observedSoak) { - Objects.requireNonNull(passedSuites, "passedSuites"); - Objects.requireNonNull(observedSoak, "observedSoak"); - List blockers = new ArrayList<>(); - List missing = - requiredSuites.stream().filter(s -> !passedSuites.contains(s)).sorted().toList(); - if (!missing.isEmpty()) { - blockers.add("suites not passed: " + missing); - } - if (observedSoak.compareTo(minimumSoak) < 0) { - blockers.add("soak " + observedSoak + " is short of the required " + minimumSoak); - } - if (!rollbackValidated) { - blockers.add( - "rollback not exercised; a flag nobody has turned off is not known to turn off, and the " - + "moment it is needed is the worst time to find out"); - } - if (!stableArtifactUnchanged) { - blockers.add( - "the Stable wire contract or dependency graph changed, so Stable is not independent of " - + "this capability and deployments that did not enable it are affected anyway"); - } - return List.copyOf(blockers); - } - - /** Whether promotion may proceed. */ - public boolean promotable(Set passedSuites, Duration observedSoak) { - return blockers(passedSuites, observedSoak).isEmpty(); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/resume/PortBackedReplayAvailability.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/resume/PortBackedReplayAvailability.java deleted file mode 100644 index b2c47ec6..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/resume/PortBackedReplayAvailability.java +++ /dev/null @@ -1,42 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.resume; - -import dev.caskeleton.application.realtime.LiveEventReplayPort; -import java.util.Objects; -import java.util.Optional; - -/** - * Replay availability, read from the durable event log. - * - *

The distinction this preserves is the one {@link ReplayAvailability} exists for: a stream - * nobody has heard of and a stream whose history has aged out are different answers. The port's - * window returns no bounds for the first and a first position for the second, and mapping both to - * "0" — which is what a naive implementation does — would let a resume for a stream that never - * existed look like a complete replay of nothing. - * - *

A store that is unreachable answers empty, which the coordinator treats as "cannot resume" and - * turns into a resynchronise. That is the safe direction: the alternative is honouring a token - * whose position may have been evicted, which delivers a stream with a hole the client cannot see. - */ -public final class PortBackedReplayAvailability implements ReplayAvailability { - - private final LiveEventReplayPort replay; - - public PortBackedReplayAvailability(LiveEventReplayPort replay) { - this.replay = Objects.requireNonNull(replay, "replay"); - } - - @Override - public Optional earliestAvailable(String streamId) { - if (streamId == null || streamId.isBlank()) { - return Optional.empty(); - } - try { - return replay.window(streamId).earliestRetained(); - } catch (RuntimeException unavailable) { - // Degraded to "cannot resume". A resynchronise costs the client a re-read; honouring a token - // we cannot verify costs it a silent gap. - Objects.requireNonNull(unavailable); - return Optional.empty(); - } - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/resume/ReplayAvailability.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/resume/ReplayAvailability.java deleted file mode 100644 index 4f3fb38e..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/resume/ReplayAvailability.java +++ /dev/null @@ -1,35 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.resume; - -import java.util.Map; -import java.util.Optional; - -/** - * How far back each stream can still be replayed. - * - *

A port, because the answer lives wherever the messages were retained — a durable log, a - * bounded in-memory ring, a broker's own retention. What the coordinator needs from all of them is - * the same single fact: is position N still there. - */ -@FunctionalInterface -public interface ReplayAvailability { - - /** - * The oldest position still available on a stream, or empty when the stream is unknown. - * - *

A stream the source has never heard of is not the same as one whose history has aged out, - * and answering 0 for both would let a resume for a stream that no longer exists look like a - * complete replay of nothing. - */ - Optional earliestAvailable(String streamId); - - /** An availability that has nothing, for a deployment with no replay store wired. */ - static ReplayAvailability none() { - return streamId -> Optional.empty(); - } - - /** An availability backed by a fixed map, for tests and for a static retention window. */ - static ReplayAvailability of(Map earliestByStream) { - Map copy = Map.copyOf(earliestByStream); - return streamId -> Optional.ofNullable(copy.get(streamId)); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/resume/ResumeCoordinator.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/resume/ResumeCoordinator.java deleted file mode 100644 index 424ff3e1..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/resume/ResumeCoordinator.java +++ /dev/null @@ -1,111 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.resume; - -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketActorReference; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketEndpointName; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketSessionId; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketSubprotocolName; -import java.time.Instant; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; - -/** - * Decides what a reconnecting client gets. - * - *

The checks run in an order that matters. Authorisation is re-evaluated before availability, - * because a resume is the one moment a long-lived session's permissions are re-examined — the whole - * point of a session that survives a reconnect is that it does not re-authenticate, so if the - * resume path does not check, a revoked permission survives until the client stops reconnecting. - * Checking availability first would spend a replay-store lookup on a caller who is not allowed to - * have the answer, and worse, a "your history has aged out" reply confirms the session exists. - * - *

Availability is then checked per stream, and one aged-out stream forces a snapshot for all of - * them. Replaying the streams that are available and snapshotting the rest hands the client a - * mixture it has no way to reason about: part of its state is continuous and part is a new - * baseline, with nothing in the protocol saying which is which. - */ -public final class ResumeCoordinator { - - private final ReplayAvailability availability; - - /** - * A coordinator over one replay source. - * - * @param availability how far back each stream can be replayed - */ - public ResumeCoordinator(ReplayAvailability availability) { - this.availability = Objects.requireNonNull(availability, "availability"); - } - - /** - * What this client gets. - * - * @param payload what the verified token asserts - * @param caller who is connecting now - * @param endpoint which endpoint they connected to - * @param negotiated what was negotiated on this connection - * @param currentAuthorities what the caller holds now, which may differ from when they left - * @param requiredAuthorities what the endpoint demands - * @param currentPositions the latest position on each stream - * @param now the current instant - */ - public ResumeDecision decide( - ResumeTokenPayload payload, - WebSocketActorReference caller, - WebSocketEndpointName endpoint, - WebSocketSubprotocolName negotiated, - Set currentAuthorities, - Set requiredAuthorities, - Map currentPositions, - Instant now) { - Objects.requireNonNull(payload, "payload"); - Objects.requireNonNull(currentAuthorities, "currentAuthorities"); - Objects.requireNonNull(requiredAuthorities, "requiredAuthorities"); - Objects.requireNonNull(currentPositions, "currentPositions"); - - if (!payload.validAt(now)) { - return ResumeDecision.refused("the resume token has expired"); - } - if (!payload.authorises(payload.sessionId(), caller, endpoint, negotiated)) { - return ResumeDecision.refused("this token does not authorise this connection"); - } - if (!currentAuthorities.containsAll(requiredAuthorities)) { - // The reason the check is here at all. A session that survives a reconnect does not - // re-authenticate, so without this a permission revoked while the client was away comes back - // with it and stays until it stops reconnecting. - return ResumeDecision.refused( - "the caller no longer holds the authorities this endpoint needs"); - } - - Map replayFrom = new LinkedHashMap<>(); - for (Map.Entry entry : payload.streamPositions().entrySet()) { - Optional earliest = availability.earliestAvailable(entry.getKey()); - if (earliest.isEmpty()) { - return ResumeDecision.snapshot( - currentPositions, "stream " + entry.getKey() + " is not replayable"); - } - if (entry.getValue() + 1 < earliest.get()) { - // One aged-out stream forces a snapshot for all of them. Mixing replayed and snapshotted - // streams hands the client state it cannot reason about — part continuous, part a new - // baseline, with nothing saying which. - return ResumeDecision.snapshot( - currentPositions, - "stream " + entry.getKey() + " has aged out past position " + entry.getValue()); - } - replayFrom.put(entry.getKey(), entry.getValue() + 1); - } - return ResumeDecision.replay(replayFrom, "the missed range is available on every stream"); - } - - /** - * Whether a session may be resumed at all. - * - *

Separate from {@link #decide} so a caller can answer "is resume even on" without building a - * decision, and so the flag check is not buried inside the policy. - */ - public static boolean resumable(WebSocketSessionId sessionId, boolean capabilityEnabled) { - return capabilityEnabled && sessionId != null; - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/resume/ResumeDecision.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/resume/ResumeDecision.java deleted file mode 100644 index 5d7bbca8..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/resume/ResumeDecision.java +++ /dev/null @@ -1,87 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.resume; - -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -/** - * What the server will actually do about a resume request. - * - *

Three answers, and the middle one is the reason this is not a boolean. A client whose missed - * range is still available gets replayed; a client whose range has aged out gets a snapshot and a - * new baseline; a client that may not resume at all starts fresh. Collapsing snapshot into either - * neighbour is wrong in a way the client cannot detect: told "replayed" after a snapshot it - * believes it has continuous history it does not have, and told "start fresh" it discards state it - * did not need to. - * - * @param outcome what the server decided - * @param replayFrom the positions to replay from, when replaying - * @param snapshotBaseline the positions the snapshot is current as of, when snapshotting - * @param reason why, in terms safe to publish - */ -public record ResumeDecision( - Outcome outcome, - Optional> replayFrom, - Optional> snapshotBaseline, - String reason) { - - /** What the server decided. */ - public enum Outcome { - - /** The missed range is available. The client keeps its state and receives what it missed. */ - REPLAY, - - /** - * The missed range has aged out. The client receives current state and a new baseline. - * - *

Its own outcome because the client must discard what it had. Told this is a replay, it - * would merge a snapshot into stale history and believe the result is continuous. - */ - SNAPSHOT, - - /** The client may not resume. It starts a new session. */ - REFUSED - } - - public ResumeDecision { - Objects.requireNonNull(outcome, "outcome"); - Objects.requireNonNull(replayFrom, "replayFrom"); - Objects.requireNonNull(snapshotBaseline, "snapshotBaseline"); - Objects.requireNonNull(reason, "reason"); - if ((outcome == Outcome.REPLAY) != replayFrom.isPresent()) { - throw new IllegalArgumentException("a replay decision carries the positions to replay from"); - } - if ((outcome == Outcome.SNAPSHOT) != snapshotBaseline.isPresent()) { - // Without a baseline the client has current state and no idea what sequence follows it, so - // the first message after the snapshot either looks like a gap or is silently misordered. - throw new IllegalArgumentException( - "a snapshot decision must state the baseline it is current as of, or the first message" - + " after it reads as a gap"); - } - if (reason.isBlank()) { - throw new IllegalArgumentException("a resume decision without a reason cannot be diagnosed"); - } - replayFrom = replayFrom.map(Map::copyOf); - snapshotBaseline = snapshotBaseline.map(Map::copyOf); - } - - /** The missed range is available. */ - public static ResumeDecision replay(Map from, String reason) { - return new ResumeDecision(Outcome.REPLAY, Optional.of(from), Optional.empty(), reason); - } - - /** The range has aged out; send current state and a new baseline. */ - public static ResumeDecision snapshot(Map baseline, String reason) { - return new ResumeDecision(Outcome.SNAPSHOT, Optional.empty(), Optional.of(baseline), reason); - } - - /** The client may not resume. */ - public static ResumeDecision refused(String reason) { - return new ResumeDecision(Outcome.REFUSED, Optional.empty(), Optional.empty(), reason); - } - - /** Whether the client keeps the state it already had. */ - public boolean clientKeepsItsState() { - return outcome == Outcome.REPLAY; - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/resume/ResumeTokenCodec.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/resume/ResumeTokenCodec.java deleted file mode 100644 index d777d592..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/resume/ResumeTokenCodec.java +++ /dev/null @@ -1,217 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.resume; - -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketActorReference; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketEndpointName; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketSessionId; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketSubprotocolName; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.time.Instant; -import java.util.Base64; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import javax.crypto.Mac; -import javax.crypto.SecretKey; - -/** - * Encodes and verifies a resume token. - * - *

Signed, not encrypted, and the difference is deliberate. The payload's contents — a session - * id, an actor fingerprint, stream positions — are things the client already knows about itself, so - * hiding them buys nothing; what matters is that the client cannot change them. Encrypting as well - * would add a second key management problem for no property the platform needs. - * - *

The version and key id sit outside the signed payload because verification has to read them - * before it can verify anything — it needs to know which key and which format. That is safe - * precisely because the signature covers the payload: changing the key id makes verification fail - * rather than succeed with a different key's expectations. - */ -public final class ResumeTokenCodec { - - /** The current token format. */ - public static final int VERSION = 1; - - private static final String ALGORITHM = "HmacSHA256"; - private static final char FIELD = '\u001f'; - private static final char SECTION = '\u001e'; - - private final ResumeTokenKeyRing keyRing; - - /** - * A codec over one key ring. - * - * @param keyRing which keys sign and verify - */ - public ResumeTokenCodec(ResumeTokenKeyRing keyRing) { - this.keyRing = Objects.requireNonNull(keyRing, "keyRing"); - } - - /** - * Mints a token for a session. - * - * @param payload what the token asserts - */ - public String encode(ResumeTokenPayload payload) { - Objects.requireNonNull(payload, "payload"); - String body = render(payload); - String signed = VERSION + String.valueOf(SECTION) + keyRing.currentKeyId() + SECTION + body; - return base64(signed) + "." + base64(sign(signed, keyRing.signingKey())); - } - - /** - * Verifies a token and says exactly why when it fails. - * - * @param token the token as presented - * @param now the current instant - */ - public Verification decode(String token, Instant now) { - if (token == null || token.isBlank()) { - return Verification.rejected(ResumeTokenOutcome.TAMPERED); - } - int separator = token.lastIndexOf('.'); - if (separator < 0) { - return Verification.rejected(ResumeTokenOutcome.TAMPERED); - } - String signed; - String signature; - try { - signed = - new String( - Base64.getUrlDecoder().decode(token.substring(0, separator)), StandardCharsets.UTF_8); - signature = token.substring(separator + 1); - } catch (IllegalArgumentException malformed) { - return Verification.rejected(ResumeTokenOutcome.TAMPERED); - } - - String[] sections = signed.split(String.valueOf(SECTION), 3); - if (sections.length != 3) { - return Verification.rejected(ResumeTokenOutcome.TAMPERED); - } - // Version before key, because an unknown version's key field may not even mean what this code - // thinks it does. - int version; - try { - version = Integer.parseInt(sections[0]); - } catch (NumberFormatException malformed) { - return Verification.rejected(ResumeTokenOutcome.TAMPERED); - } - if (version != VERSION) { - return Verification.rejected(ResumeTokenOutcome.UNSUPPORTED_VERSION); - } - - Optional key = keyRing.verificationKey(sections[1]); - if (key.isEmpty()) { - return Verification.rejected(ResumeTokenOutcome.UNKNOWN_KEY); - } - - // Constant-time. A byte-by-byte comparison that returns early leaks the correct signature one - // byte at a time to anyone willing to measure, and a resume token is presented as often as the - // attacker likes. - if (!MessageDigest.isEqual( - base64(sign(signed, key.get())).getBytes(StandardCharsets.UTF_8), - signature.getBytes(StandardCharsets.UTF_8))) { - return Verification.rejected(ResumeTokenOutcome.TAMPERED); - } - - ResumeTokenPayload payload; - try { - payload = parse(sections[2]); - } catch (RuntimeException malformed) { - return Verification.rejected(ResumeTokenOutcome.TAMPERED); - } - // Expiry after the signature, never before: an unverified payload's expiry is a number the - // client chose. - if (!payload.validAt(now)) { - return Verification.rejected(ResumeTokenOutcome.EXPIRED); - } - return Verification.accepted(payload); - } - - /** - * The outcome of verifying a token. - * - * @param outcome why it was or was not accepted - * @param payload what it asserted, when it was accepted - */ - public record Verification(ResumeTokenOutcome outcome, Optional payload) { - - public Verification { - Objects.requireNonNull(outcome, "outcome"); - Objects.requireNonNull(payload, "payload"); - if ((outcome == ResumeTokenOutcome.ACCEPTED) != payload.isPresent()) { - throw new IllegalArgumentException( - "an accepted verification carries a payload and a rejected one does not"); - } - } - - static Verification accepted(ResumeTokenPayload payload) { - return new Verification(ResumeTokenOutcome.ACCEPTED, Optional.of(payload)); - } - - static Verification rejected(ResumeTokenOutcome outcome) { - return new Verification(outcome, Optional.empty()); - } - } - - private static String render(ResumeTokenPayload payload) { - StringBuilder body = new StringBuilder(); - body.append(payload.sessionId().value()).append(FIELD); - body.append(payload.actor().fingerprint()).append(FIELD); - body.append(payload.endpoint().value()).append(FIELD); - body.append(payload.subprotocol().value()).append(FIELD); - body.append(payload.issuedAt().toEpochMilli()).append(FIELD); - body.append(payload.expiresAt().toEpochMilli()).append(FIELD); - // Sorted, so the same payload always renders identically and a signature is reproducible. - new java.util.TreeMap<>(payload.streamPositions()) - .forEach( - (stream, position) -> body.append(stream).append('=').append(position).append(',')); - return body.toString(); - } - - private static ResumeTokenPayload parse(String body) { - String[] fields = body.split(String.valueOf(FIELD), -1); - Map positions = new LinkedHashMap<>(); - if (fields.length > 6 && !fields[6].isEmpty()) { - // -1 limit, so a trailing separator does not silently drop the last entry — the rendered - // form always ends with one, and split's default would discard it along with any empty - // position that ought to have been an error. - for (String entry : fields[6].split(",", -1)) { - if (entry.isEmpty()) { - continue; - } - int equals = entry.lastIndexOf('='); - positions.put(entry.substring(0, equals), Long.parseLong(entry.substring(equals + 1))); - } - } - return new ResumeTokenPayload( - new WebSocketSessionId(fields[0]), - new WebSocketActorReference(fields[1]), - new WebSocketEndpointName(fields[2]), - new WebSocketSubprotocolName(fields[3]), - positions, - Instant.ofEpochMilli(Long.parseLong(fields[4])), - Instant.ofEpochMilli(Long.parseLong(fields[5]))); - } - - private static byte[] sign(String signed, SecretKey key) { - try { - Mac mac = Mac.getInstance(ALGORITHM); - mac.init(key); - return mac.doFinal(signed.getBytes(StandardCharsets.UTF_8)); - } catch (java.security.GeneralSecurityException impossible) { - throw new IllegalStateException("HmacSHA256 is required of every JVM", impossible); - } - } - - private static String base64(String value) { - return Base64.getUrlEncoder() - .withoutPadding() - .encodeToString(value.getBytes(StandardCharsets.UTF_8)); - } - - private static String base64(byte[] value) { - return Base64.getUrlEncoder().withoutPadding().encodeToString(value); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/resume/ResumeTokenKeyRing.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/resume/ResumeTokenKeyRing.java deleted file mode 100644 index 67e8aeec..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/resume/ResumeTokenKeyRing.java +++ /dev/null @@ -1,87 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.resume; - -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import javax.crypto.SecretKey; - -/** - * The signing keys, with exactly one current and any number still accepted. - * - *

A ring rather than a key, because rotation is otherwise an outage. A token is minted with the - * current key and lives for its window; replacing the key with a single new one invalidates every - * token in flight, and every client holding one is told to start a fresh session at the same - * moment. On a platform whose whole purpose is surviving a reconnect, that is the failure the - * feature was added to prevent. - * - *

Retired keys therefore verify and do not sign. The ring is what lets a rotation be a - * deployment rather than an event. - */ -public final class ResumeTokenKeyRing { - - private final String currentKeyId; - private final Map keys; - - private ResumeTokenKeyRing(String currentKeyId, Map keys) { - this.currentKeyId = currentKeyId; - this.keys = keys; - } - - /** - * A ring with one signing key and any number of verify-only keys. - * - * @param currentKeyId which key signs - * @param keys every key that verifies, including the current one - */ - public static ResumeTokenKeyRing of(String currentKeyId, Map keys) { - Objects.requireNonNull(currentKeyId, "currentKeyId"); - Objects.requireNonNull(keys, "keys"); - if (!keys.containsKey(currentKeyId)) { - throw new IllegalArgumentException( - "the current key " + currentKeyId + " is not in the ring, so nothing it signs verifies"); - } - Map copy = new LinkedHashMap<>(keys); - copy.forEach( - (id, key) -> { - Objects.requireNonNull(id, "key id"); - Objects.requireNonNull(key, "key"); - if (key.getEncoded() != null && key.getEncoded().length < 32) { - // 256 bits. A resume token authorises reading a session's history, so a key short - // enough to brute force is a key that hands over other people's messages. - throw new IllegalArgumentException( - "key " - + id - + " is shorter than 256 bits; a resume token authorises reading a" - + " session's history, so a forgeable one hands over somebody else's messages"); - } - }); - return new ResumeTokenKeyRing(currentKeyId, Map.copyOf(copy)); - } - - /** The key that signs new tokens. */ - public SecretKey signingKey() { - return keys.get(currentKeyId); - } - - /** The id of the signing key, carried in the token so verification knows which to use. */ - public String currentKeyId() { - return currentKeyId; - } - - /** - * The key a token names, if this ring still has it. - * - *

Empty means {@link ResumeTokenOutcome#UNKNOWN_KEY} — which is usually a rotation that - * retired a key still in circulation, and occasionally a forgery. The ring cannot tell the - * difference and does not pretend to. - */ - public Optional verificationKey(String keyId) { - return Optional.ofNullable(keys.get(keyId)); - } - - /** How many keys still verify. */ - public int size() { - return keys.size(); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/resume/ResumeTokenOutcome.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/resume/ResumeTokenOutcome.java deleted file mode 100644 index 13fd5819..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/resume/ResumeTokenOutcome.java +++ /dev/null @@ -1,47 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.resume; - -/** - * Why a resume token was or was not accepted. - * - *

The distinctions are not for the client, which is told the same thing for most of them — they - * are for the operator. "Clients cannot resume" has completely different causes and remedies - * depending on which of these is climbing: an expired-token spike is a client that has been offline - * longer than the window and an unknown-key spike is a key rotation that removed a key still in - * use. - * - *

This codec is stateless. A valid token may therefore be presented again until it expires; - * replay detection is not claimed by this outcome model. - */ -public enum ResumeTokenOutcome { - - /** Valid and within its window. */ - ACCEPTED, - - /** - * Signed with a key this deployment does not have. - * - *

Usually a rotation that retired a key still in circulation, occasionally a forgery. The two - * are indistinguishable from the token alone, which is why this is its own outcome rather than - * being folded into a generic rejection. - */ - UNKNOWN_KEY, - - /** A token version this deployment does not understand. */ - UNSUPPORTED_VERSION, - - /** Well-formed, correctly signed, and past its expiry. */ - EXPIRED, - - /** The signature does not verify. */ - TAMPERED; - - /** - * Whether the client should mint a new token and continue. - * - *

The only outcomes worth distinguishing to a client. Everything else is "start a fresh - * session", and telling a client which of the failures it hit would tell an attacker the same. - */ - public boolean clientMayRetryWithNewToken() { - return this == EXPIRED || this == UNKNOWN_KEY || this == UNSUPPORTED_VERSION; - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/resume/ResumeTokenPayload.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/resume/ResumeTokenPayload.java deleted file mode 100644 index 6345e868..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/resume/ResumeTokenPayload.java +++ /dev/null @@ -1,83 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.resume; - -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketActorReference; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketEndpointName; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketSessionId; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketSubprotocolName; -import java.time.Instant; -import java.util.Map; -import java.util.Objects; - -/** - * What a resume token asserts. - * - *

Bound to four things, and each binding closes a specific hole. Without the actor it is a - * bearer credential — whoever holds it resumes as whoever created it. Without the endpoint, a token - * from a low-privilege feed resumes a privileged one. Without the subprotocol, a client resumes - * into a session whose message format it no longer speaks and every subsequent frame fails to - * decode. Without the session id there is nothing to resume. - * - *

The stream positions are the substance: a resume is "I last saw N on each of these streams", - * and the server sends what came after. Carrying them in the signed token prevents the client from - * moving those positions. It does not make the token single-use: without a redemption store the - * same valid token can request the same replay range again until it expires. - * - * @param sessionId the session being resumed - * @param actor who may resume it - * @param endpoint which endpoint it belongs to - * @param subprotocol the format it was negotiated with - * @param streamPositions the last position seen on each stream - * @param issuedAt when the token was minted - * @param expiresAt when it stops working - */ -public record ResumeTokenPayload( - WebSocketSessionId sessionId, - WebSocketActorReference actor, - WebSocketEndpointName endpoint, - WebSocketSubprotocolName subprotocol, - Map streamPositions, - Instant issuedAt, - Instant expiresAt) { - - public ResumeTokenPayload { - Objects.requireNonNull(sessionId, "sessionId"); - Objects.requireNonNull(actor, "actor"); - Objects.requireNonNull(endpoint, "endpoint"); - Objects.requireNonNull(subprotocol, "subprotocol"); - Objects.requireNonNull(streamPositions, "streamPositions"); - Objects.requireNonNull(issuedAt, "issuedAt"); - Objects.requireNonNull(expiresAt, "expiresAt"); - streamPositions = Map.copyOf(streamPositions); - if (!expiresAt.isAfter(issuedAt)) { - throw new IllegalArgumentException("a token that expires when minted resumes nothing"); - } - streamPositions.forEach( - (stream, position) -> { - if (position < 0) { - throw new IllegalArgumentException("a stream position cannot be negative"); - } - }); - } - - /** Whether the token is inside its window. */ - public boolean validAt(Instant now) { - return !now.isBefore(issuedAt) && now.isBefore(expiresAt); - } - - /** - * Whether this token may resume a given session for a given caller on a given endpoint. - * - *

All four checked together, because any one of them alone is a hole and checking three of - * four reads as thorough. - */ - public boolean authorises( - WebSocketSessionId targetSession, - WebSocketActorReference caller, - WebSocketEndpointName targetEndpoint, - WebSocketSubprotocolName negotiated) { - return sessionId.equals(targetSession) - && actor.equals(caller) - && endpoint.equals(targetEndpoint) - && subprotocol.equals(negotiated); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/sockjs/SockJsCompatibilityProfile.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/sockjs/SockJsCompatibilityProfile.java deleted file mode 100644 index f16b4b75..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/sockjs/SockJsCompatibilityProfile.java +++ /dev/null @@ -1,90 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.sockjs; - -import dev.caskeleton.adapter.inbound.websocket.advanced.compression.EndpointContentClass; -import java.time.Duration; -import java.util.List; -import java.util.Objects; -import java.util.Set; - -/** - * SockJS fallback for clients that cannot open a raw WebSocket. - * - *

Off for a new service. It exists for a browser population that a given deployment actually - * has, and enabling it without one costs the whole surface below for nobody. - * - *

What is easy to miss is that the fallback transports are HTTP requests, and HTTP requests - * carry cookies. A raw WebSocket handshake is not subject to the same-origin policy and is - * therefore checked by origin explicitly; the SockJS fallbacks are ordinary cross-origin requests - * that a browser will attach credentials to, which puts CSRF back on a surface that did not have - * it. So this profile does not get to relax origin checking, and the session cookie it needs is - * bounded in lifetime rather than left to the container default. - * - * @param enabled whether the fallback endpoint is exposed - * @param transports which fallbacks are offered - * @param sessionCookieLifetime how long the SockJS session cookie is valid - */ -public record SockJsCompatibilityProfile( - boolean enabled, Set transports, Duration sessionCookieLifetime) { - - public SockJsCompatibilityProfile { - transports = Set.copyOf(Objects.requireNonNull(transports, "transports")); - Objects.requireNonNull(sessionCookieLifetime, "sessionCookieLifetime"); - if (enabled) { - if (transports.isEmpty()) { - throw new IllegalArgumentException( - "SockJS enabled with no transport offers nothing and still exposes the endpoint"); - } - if (sessionCookieLifetime.isNegative() || sessionCookieLifetime.isZero()) { - throw new IllegalArgumentException( - "the SockJS session cookie must expire; a session-lifetime cookie on a fallback " - + "transport outlives the connection it was issued for"); - } - if (sessionCookieLifetime.compareTo(Duration.ofHours(12)) > 0) { - throw new IllegalArgumentException( - "a SockJS session cookie valid for longer than half a day is a bearer credential for " - + "a transport session, kept long after the transport session ended"); - } - } - } - - /** The default. */ - public static SockJsCompatibilityProfile disabled() { - return new SockJsCompatibilityProfile(false, Set.of(), Duration.ofHours(1)); - } - - /** - * Whether this profile may serve an endpoint carrying the given content. - * - *

Refused for a JSONP-polling offer on anything sensitive: JSONP executes server-supplied - * script in the page, so a sensitive payload becomes script the page runs, readable by anything - * else running there. - */ - public boolean mayServe(EndpointContentClass contentClass) { - Objects.requireNonNull(contentClass, "contentClass"); - if (!enabled) { - return false; - } - boolean sensitive = - contentClass == EndpointContentClass.SENSITIVE - || contentClass == EndpointContentClass.SENSITIVE_WITH_ATTACKER_INFLUENCE; - return !sensitive - || transports.stream().noneMatch(SockJsTransport::executesServerSuppliedScript); - } - - /** The checks that stay exactly as strict as they are for a raw WebSocket. */ - public List inheritedFromStable() { - return List.of( - "origin: the same allowlist, checked on every fallback request rather than once at " - + "handshake", - "CSRF: the fallbacks are credentialed cross-origin HTTP requests, so the token requirement " - + "applies where it does not to a raw handshake", - "connection budget: a fallback session counts against the same per-actor and global bounds", - "authentication: the same, and re-established per polling request rather than assumed from " - + "the session cookie"); - } - - /** The transports that a proxy response timeout will cut. */ - public List transportsExposedToProxyTimeouts() { - return transports.stream().filter(SockJsTransport::holdsResponseOpen).sorted().toList(); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/sockjs/SockJsConfiguration.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/sockjs/SockJsConfiguration.java deleted file mode 100644 index 0ff004f7..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/sockjs/SockJsConfiguration.java +++ /dev/null @@ -1,116 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.sockjs; - -import dev.caskeleton.adapter.inbound.websocket.advanced.compression.EndpointContentClass; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketEndpointCatalog; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketEndpointProfile; -import dev.caskeleton.adapter.inbound.websocket.security.WebSocketOriginPolicy; -import java.time.Duration; -import java.util.Objects; -import org.springframework.beans.factory.ObjectProvider; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.socket.WebSocketHandler; -import org.springframework.web.socket.config.annotation.EnableWebSocket; -import org.springframework.web.socket.config.annotation.SockJsServiceRegistration; -import org.springframework.web.socket.config.annotation.WebSocketConfigurer; -import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry; - -/** - * Exposes the SockJS fallback endpoint, when a deployment has a browser population that needs it. - * - *

Off by default and gated on its own flag, because the fallbacks are not a cheaper WebSocket — - * they are HTTP requests. That is the thing that gets missed: an HTTP request carries cookies, so a - * transport a browser will attach credentials to has CSRF exposure a raw WebSocket handshake does - * not, and it is reachable by any origin the CORS configuration allows rather than only the ones - * the handshake's origin check permits. - * - *

So the origin allowlist here is the endpoint's own, not a wildcard, and the session cookie is - * disabled outright. SockJS's cookie exists to help sticky-session load balancers; a deployment - * that needs stickiness should get it from the balancer, because the cookie is a bearer credential - * for a transport session and it outlives the session it was issued for. - */ -@Configuration(proxyBeanMethods = false) -@EnableWebSocket -@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) -@ConditionalOnProperty( - prefix = "app.websocket.advanced.sockjs", - name = "enabled", - havingValue = "true") -public class SockJsConfiguration implements WebSocketConfigurer { - - private final SockJsCompatibilityProfile profile; - private final WebSocketEndpointCatalog endpoints; - private final WebSocketOriginPolicy origins; - private final WebSocketHandler handler; - - public SockJsConfiguration( - SockJsCompatibilityProfile profile, - ObjectProvider endpoints, - ObjectProvider origins, - ObjectProvider handler) { - this.profile = Objects.requireNonNull(profile, "profile"); - this.endpoints = - required( - endpoints, "SockJS requires a WebSocketEndpointCatalog bean from the composition root"); - this.origins = - required(origins, "SockJS requires a WebSocketOriginPolicy bean from the composition root"); - this.handler = - required(handler, "SockJS requires a WebSocketHandler bean from the composition root"); - } - - /** The fallback set, overridable by a deployment that knows its browser population. */ - @Bean - @ConditionalOnMissingBean - static SockJsCompatibilityProfile sockJsCompatibilityProfile() { - return new SockJsCompatibilityProfile( - true, - java.util.Set.of( - SockJsTransport.WEBSOCKET, SockJsTransport.XHR_STREAMING, SockJsTransport.XHR_POLLING), - Duration.ofHours(1)); - } - - @Override - public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { - for (WebSocketEndpointProfile endpoint : endpoints.all()) { - if (!profile.mayServe(contentClassOf(endpoint))) { - // Refused per endpoint rather than globally. A JSONP-capable fallback set may serve the - // public feed and must not serve the one carrying a token, and the decision needs the - // endpoint's content in view. - continue; - } - SockJsServiceRegistration sockJs = - registry - .addHandler(handler, endpoint.path()) - // The endpoint's own allowlist, never a wildcard. A fallback transport is an - // ordinary cross-origin HTTP request, so this is the only thing standing where the - // handshake's origin check stands for a raw WebSocket. - .setAllowedOriginPatterns(origins.allowedOrigins().toArray(String[]::new)) - .withSockJS(); - // Off, not shortened. The cookie is a bearer credential for a transport session, and its - // only purpose is to help a load balancer that should be doing stickiness itself. - sockJs.setSessionCookieNeeded(false); - sockJs.setHeartbeatTime(Duration.ofSeconds(25).toMillis()); - sockJs.setDisconnectDelay(Duration.ofSeconds(5).toMillis()); - } - } - - private static T required(ObjectProvider provider, String message) { - T value = provider.getIfAvailable(); - if (value == null) { - throw new IllegalStateException(message); - } - return value; - } - - private static EndpointContentClass contentClassOf(WebSocketEndpointProfile endpoint) { - // Derived from whether the endpoint authenticates. An endpoint that requires a credential is - // carrying something worth protecting; a public one is not. A deployment with a finer answer - // supplies its own profile. - return endpoint.requiresAuthentication() - ? EndpointContentClass.SENSITIVE - : EndpointContentClass.PUBLIC_DATA; - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/sockjs/SockJsTransport.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/sockjs/SockJsTransport.java deleted file mode 100644 index 2d21031c..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/sockjs/SockJsTransport.java +++ /dev/null @@ -1,61 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.sockjs; - -/** - * The SockJS fallback transports, and what each costs. - * - *

Each is a different shape of HTTP traffic pretending to be a socket, and the differences - * matter to everything in front of the application. A streaming transport holds a response open, - * which a proxy with a response timeout will cut; a polling transport issues a request per message, - * which multiplies request count by message rate. - */ -public enum SockJsTransport { - - /** A real WebSocket. Not a fallback; listed so the set is complete. */ - WEBSOCKET(false, false), - - /** A long-lived streaming response over XHR. Cut by any proxy with a response timeout. */ - XHR_STREAMING(true, true), - - /** One request per message. Request count scales with message rate. */ - XHR_POLLING(true, false), - - /** Streaming via an EventSource. Same proxy timeout exposure as XHR streaming. */ - EVENT_SOURCE(true, true), - - /** - * A script tag per message, for browsers with no cross-origin XHR. - * - *

Executes server-supplied script in the page. Only defensible for a browser population that - * genuinely cannot do anything else. - */ - JSONP_POLLING(true, false), - - /** Streaming through a hidden iframe with an htmlfile ActiveX object. */ - HTML_FILE(true, true), - - /** An iframe hosting a real WebSocket, for pages whose own origin blocks one. */ - IFRAME_WEBSOCKET(true, false); - - private final boolean fallback; - private final boolean holdsResponseOpen; - - SockJsTransport(boolean fallback, boolean holdsResponseOpen) { - this.fallback = fallback; - this.holdsResponseOpen = holdsResponseOpen; - } - - /** Whether this is a fallback rather than a real socket. */ - public boolean fallback() { - return fallback; - } - - /** Whether it keeps an HTTP response open, and so meets proxy response timeouts. */ - public boolean holdsResponseOpen() { - return holdsResponseOpen; - } - - /** Whether it executes server-supplied script in the page. */ - public boolean executesServerSuppliedScript() { - return this == JSONP_POLLING; - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/AdvancedStompSafetyConfiguration.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/AdvancedStompSafetyConfiguration.java deleted file mode 100644 index e1e06b58..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/AdvancedStompSafetyConfiguration.java +++ /dev/null @@ -1,35 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.stomp; - -import org.springframework.beans.factory.InitializingBean; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.Environment; - -/** - * Connects the Advanced STOMP broker exclusivity rule to the actual Spring startup lifecycle. - * - *

This configuration lives inside the Advanced package on purpose. Stable WebSocket modules may - * not depend on Advanced modules, so the Stable startup guard cannot call this policy without - * breaking the leaf's internal DAG. - */ -@Configuration(proxyBeanMethods = false) -public class AdvancedStompSafetyConfiguration { - - @Bean - InitializingBean advancedStompBrokerExclusivity(Environment environment) { - return () -> { - boolean legacyStomp = enabled(environment, "app.websocket.enabled"); - boolean advancedStomp = enabled(environment, "app.websocket.advanced.stomp.enabled"); - boolean relay = enabled(environment, "app.websocket.advanced.stomp.relay.enabled"); - - // There is currently no Advanced simple-broker configuration in this leaf. Passing false is - // intentional: enabling Advanced STOMP without the relay is an incomplete composition and - // must fail rather than start a brokerless message pipeline. - StompBrokerExclusivity.verify(legacyStomp, advancedStomp, false, relay); - }; - } - - private static boolean enabled(Environment environment, String key) { - return environment.getProperty(key, Boolean.class, false); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/SimpleBrokerProfile.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/SimpleBrokerProfile.java deleted file mode 100644 index e91b46fe..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/SimpleBrokerProfile.java +++ /dev/null @@ -1,59 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.stomp; - -import java.util.List; - -/** - * What Spring's in-memory simple broker can and cannot do. - * - *

Written down because the simple broker is the default, works perfectly in a single-node test, - * and fails in production in ways that look like application bugs. It holds subscriptions in one - * JVM's heap: a second node sees none of them, and a restart loses all of them. Nothing about - * either failure is visible from the destination string a developer writes. - * - * @param localOnly whether subscriptions are visible only within this JVM - * @param clusterSupported whether a second node would see the same subscriptions - * @param durableAckSupported whether an acknowledged message survives a restart - */ -public record SimpleBrokerProfile( - boolean localOnly, boolean clusterSupported, boolean durableAckSupported) { - - public SimpleBrokerProfile { - if (!localOnly || clusterSupported || durableAckSupported) { - throw new IllegalArgumentException( - "the simple broker is single-node and non-durable; a profile claiming otherwise " - + "describes a broker that does not exist, and the claim would be believed"); - } - } - - /** The only shape this profile has. */ - public static SimpleBrokerProfile inMemory() { - return new SimpleBrokerProfile(true, false, false); - } - - /** - * Whether this broker may back the named deployment. - * - *

Refused outside local and test. The simple broker in a multi-node deployment does not error - * — it delivers to whichever fraction of users happens to be on the publishing node, which reads - * as intermittent message loss and is diagnosed as anything but the broker. - * - * @param profileNames the active Spring profiles - */ - public static boolean activatableUnder(List profileNames) { - if (profileNames == null || profileNames.isEmpty()) { - // No profile is the default profile, which is a developer's machine. - return true; - } - return profileNames.stream() - .allMatch(name -> name.equals("local") || name.equals("test") || name.equals("default")); - } - - /** The limitations, in the words an operator needs to read them in. */ - public List supportMatrix() { - return List.of( - "cluster: unsupported - subscriptions live in one JVM's heap and a second node sees none", - "durable ack: unsupported - BROKER_ACK is reached and survives no restart", - "receipt: transport-level only - never promoted to APPLICATION_COMMIT", - "redelivery: none - a message written to a closed connection is gone"); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompAckMode.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompAckMode.java deleted file mode 100644 index c4cc1f3e..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompAckMode.java +++ /dev/null @@ -1,76 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.stomp; - -import java.util.Locale; -import java.util.Optional; - -/** - * The three RFC-defined subscription acknowledgement modes. - * - *

Distinguished because they place responsibility for redelivery in different places, and a - * server that treats them alike is wrong for two of the three. Under {@link #AUTO} the server - * forgets the message the moment it writes it; under the other two it must hold it until the client - * says otherwise, and how much it releases on one {@code ACK} differs. - */ -public enum StompAckMode { - - /** - * The server considers a message delivered as soon as it is written. - * - *

No redelivery, ever. A client that disconnects mid-message loses it, which is acceptable for - * a ticker and not for anything a user acts on. - */ - AUTO("auto"), - - /** - * The client acknowledges, and one {@code ACK} covers every message up to and including it. - * - *

Cumulative. The trap is that an {@code ACK} for a message the client actually failed to - * process silently acknowledges everything before it too. - */ - CLIENT("client"), - - /** The client acknowledges each message on its own. No cumulative effect. */ - CLIENT_INDIVIDUAL("client-individual"); - - private final String wireName; - - StompAckMode(String wireName) { - this.wireName = wireName; - } - - /** The name as it appears in the {@code ack} header. */ - public String wireName() { - return wireName; - } - - /** Whether the server must retain the message until the client acknowledges it. */ - public boolean requiresClientAcknowledgement() { - return this != AUTO; - } - - /** Whether one acknowledgement releases every earlier message as well. */ - public boolean cumulative() { - return this == CLIENT; - } - - /** - * Parse an {@code ack} header. - * - *

Empty for anything unrecognised. The caller must refuse rather than default: defaulting an - * unknown mode to {@code auto} turns a client asking for at-least-once into one that silently - * gets at-most-once, and defaulting it to {@code client} makes the server hold messages for a - * client that will never acknowledge them. - */ - public static Optional fromWire(String header) { - if (header == null) { - return Optional.empty(); - } - String normalized = header.trim().toLowerCase(Locale.ROOT); - for (StompAckMode mode : values()) { - if (mode.wireName.equals(normalized)) { - return Optional.of(mode); - } - } - return Optional.empty(); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompAckPolicy.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompAckPolicy.java deleted file mode 100644 index 7b0b5d1a..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompAckPolicy.java +++ /dev/null @@ -1,79 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.stomp; - -import java.time.Duration; -import java.util.Objects; - -/** - * What each acknowledgement signal is allowed to be reported as. - * - *

The whole point is the refusal in {@link #evidenceForReceipt()}: a STOMP {@code RECEIPT} maps - * to {@link StompEvidence#PROTOCOL_RECEIPT} and can never be promoted to {@link - * StompEvidence#APPLICATION_COMMIT}, no matter how convenient that would be for a client that wants - * one signal instead of two. - * - * @param ackMode the subscription's acknowledgement mode - * @param pendingLimit how many unacknowledged messages one subscription may accumulate - * @param acknowledgementTimeout how long to wait before treating a message as unacknowledged - */ -public record StompAckPolicy( - StompAckMode ackMode, int pendingLimit, Duration acknowledgementTimeout) { - - public StompAckPolicy { - Objects.requireNonNull(ackMode, "ackMode"); - Objects.requireNonNull(acknowledgementTimeout, "acknowledgementTimeout"); - if (ackMode.requiresClientAcknowledgement() && pendingLimit < 1) { - throw new IllegalArgumentException( - "a client-acknowledged subscription with no pending allowance can never deliver"); - } - if (!ackMode.requiresClientAcknowledgement() && pendingLimit != 0) { - throw new IllegalArgumentException( - "auto acknowledgement holds nothing, so a pending limit describes a queue that does not " - + "exist"); - } - if (acknowledgementTimeout.isNegative() || acknowledgementTimeout.isZero()) { - throw new IllegalArgumentException( - "an unbounded acknowledgement wait lets one silent client pin the retained messages of " - + "every other one"); - } - } - - /** The conventional auto-mode policy: nothing retained, nothing awaited. */ - public static StompAckPolicy auto() { - return new StompAckPolicy(StompAckMode.AUTO, 0, Duration.ofSeconds(30)); - } - - /** What a {@code RECEIPT} frame proves. Fixed, and deliberately not configurable. */ - public StompEvidence evidenceForReceipt() { - return StompEvidence.PROTOCOL_RECEIPT; - } - - /** What a client {@code ACK} frame proves. */ - public StompEvidence evidenceForClientAck() { - if (!ackMode.requiresClientAcknowledgement()) { - throw new IllegalStateException( - "an auto-mode subscription receives no ACK frames, so asking what one proves means the " - + "caller has the wrong policy in hand"); - } - return StompEvidence.CLIENT_APPLIED; - } - - /** - * Whether reporting a stage is honest given what actually happened. - * - * @param observed the furthest stage genuinely reached - * @param claimed the stage a caller wants to report - */ - public boolean mayReport(StompEvidence observed, StompEvidence claimed) { - Objects.requireNonNull(observed, "observed"); - Objects.requireNonNull(claimed, "claimed"); - return !observed.wouldOverstate(claimed); - } - - /** Whether another unacknowledged message may be delivered on this subscription. */ - public boolean mayDeliver(int pending) { - if (!ackMode.requiresClientAcknowledgement()) { - return true; - } - return pending < pendingLimit; - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompAuthorizationDecision.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompAuthorizationDecision.java deleted file mode 100644 index b31ae4f8..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompAuthorizationDecision.java +++ /dev/null @@ -1,34 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.stomp; - -import java.util.Objects; -import java.util.Optional; - -/** - * Whether one STOMP frame may proceed, and why not when it may not. - * - *

A value rather than an exception so the decision can be tested without a channel, and so the - * reason reaches the metric and the log without the destination going with it. - * - * @param allowed whether the frame proceeds - * @param reason why it was refused, absent when it was allowed - */ -public record StompAuthorizationDecision(boolean allowed, Optional reason) { - - public StompAuthorizationDecision { - Objects.requireNonNull(reason, "reason"); - if (allowed == reason.isPresent()) { - throw new IllegalArgumentException( - "an allowed decision carries no refusal and a refused one must say why"); - } - } - - /** The frame proceeds. */ - public static StompAuthorizationDecision allow() { - return new StompAuthorizationDecision(true, Optional.empty()); - } - - /** The frame is refused. */ - public static StompAuthorizationDecision refuse(StompRefusal reason) { - return new StompAuthorizationDecision(false, Optional.of(Objects.requireNonNull(reason))); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompAuthorizationException.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompAuthorizationException.java deleted file mode 100644 index fdbeba81..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompAuthorizationException.java +++ /dev/null @@ -1,27 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.stomp; - -import java.util.Objects; - -/** - * A STOMP frame that was refused. - * - *

Carries the closed-set reason and nothing else. The destination is deliberately absent from - * the message: this exception's text reaches the client through the STOMP {@code ERROR} frame, and - * echoing the destination back confirms to a prober which destinations exist. - */ -public final class StompAuthorizationException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - private final transient StompRefusal refusal; - - public StompAuthorizationException(StompRefusal refusal) { - super("stomp frame refused"); - this.refusal = Objects.requireNonNull(refusal, "refusal"); - } - - /** Why it was refused, for the metric and the server-side log. */ - public StompRefusal refusal() { - return refusal; - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompAuthorizationPolicy.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompAuthorizationPolicy.java deleted file mode 100644 index 9929d29e..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompAuthorizationPolicy.java +++ /dev/null @@ -1,93 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.stomp; - -import java.util.Objects; -import java.util.Optional; - -/** - * The authorization decision for an inbound STOMP frame. - * - *

Separate from the interceptor so the whole decision table can be exercised without a message - * channel. The interceptor's job is extraction and enforcement; the judgement is here. - * - *

Every path that is not an explicit allow is a refusal. That sounds obvious and is the thing - * that goes wrong: an authorization check written as a series of {@code if (bad) throw} statements - * allows anything the author did not think to test for, and the set of destinations a STOMP client - * can name is unbounded. - */ -public final class StompAuthorizationPolicy { - - private final StompDestinationCatalog catalog; - - public StompAuthorizationPolicy(StompDestinationCatalog catalog) { - this.catalog = Objects.requireNonNull(catalog, "catalog"); - } - - /** Judge one frame. */ - public StompAuthorizationDecision decide(StompFrameRequest request) { - Objects.requireNonNull(request, "request"); - Optional principal = request.principalName().filter(name -> !name.isBlank()); - if (principal.isEmpty()) { - return StompAuthorizationDecision.refuse(StompRefusal.UNAUTHENTICATED); - } - if (request.ackHeader().isPresent() - && StompAckMode.fromWire(request.ackHeader().get()).isEmpty()) { - // Refused rather than defaulted. Defaulting an unrecognised mode to auto turns a client - // asking for at-least-once into one that silently gets at-most-once. - return StompAuthorizationDecision.refuse(StompRefusal.UNSUPPORTED_ACK_MODE); - } - Optional role = catalog.profile().roleOf(request.destination()); - if (role.isEmpty()) { - return StompAuthorizationDecision.refuse(StompRefusal.UNDECLARED_DESTINATION); - } - // A user-prefixed destination is written two ways. "/user/queue/x" is self-addressed: Spring - // resolves it against the session's own principal, so it is declared literally and needs no - // ownership check. "/user/alice/queue/x" names somebody else, and is how one client reaches - // another's private queue. Only the second form needs the check, and it is distinguished by - // the literal not being in the catalog. - String resolved = request.destination(); - if (role.get() == StompDestinationRole.USER - && !catalog.declares(request.operation(), resolved)) { - Optional targeted = stripTargetName(resolved); - if (targeted.isPresent()) { - if (!targeted.get().name().equals(principal.get())) { - return StompAuthorizationDecision.refuse(StompRefusal.FOREIGN_USER_DESTINATION); - } - resolved = targeted.get().destination(); - } - } - Optional required = catalog.permissionFor(request.operation(), resolved); - if (required.isEmpty()) { - // Declared for the other operation, or not declared at all. Distinguished so an operator - // reading the metric can tell a missing declaration from a deliberate read-only feed. - String candidate = resolved; - boolean declaredElsewhere = - java.util.Arrays.stream(StompOperation.values()) - .anyMatch(other -> catalog.declares(other, candidate)); - return StompAuthorizationDecision.refuse( - declaredElsewhere - ? StompRefusal.OPERATION_NOT_PERMITTED - : StompRefusal.UNDECLARED_DESTINATION); - } - if (!request.grantedPermissions().contains(required.get())) { - return StompAuthorizationDecision.refuse(StompRefusal.MISSING_PERMISSION); - } - return StompAuthorizationDecision.allow(); - } - - /** A destination with the target name lifted out of it. */ - private record TargetedDestination(String name, String destination) {} - - private static Optional stripTargetName(String destination) { - int prefixEnd = destination.indexOf('/', 1); - if (prefixEnd < 0) { - return Optional.empty(); - } - int nameEnd = destination.indexOf('/', prefixEnd + 1); - if (nameEnd < 0 || nameEnd == prefixEnd + 1) { - return Optional.empty(); - } - String name = destination.substring(prefixEnd + 1, nameEnd); - String remainder = destination.substring(0, prefixEnd) + destination.substring(nameEnd); - return Optional.of(new TargetedDestination(name, remainder)); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompBrokerExclusivity.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompBrokerExclusivity.java deleted file mode 100644 index d8be278b..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompBrokerExclusivity.java +++ /dev/null @@ -1,74 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.stomp; - -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; - -/** - * Refuses a configuration in which two STOMP runtimes would both try to own the broker. - * - *

This leaf ships an older STOMP-over-SockJS channel with its own - * {@code @EnableWebSocketMessageBroker}, and the Advanced adapter is a second one. Spring will - * start both: each contributes a {@code WebSocketMessageBrokerConfigurer}, both call {@code - * configureMessageBroker}, and the resulting broker is whichever ran last. Nothing fails, nothing - * logs, and the prefixes in effect are not the ones in either configuration file. - * - *

So it is refused at startup instead. The same reasoning, and the same shape, as {@code - * WebSocketStackExclusivity}: a runtime that silently half-applies is worse than one that will not - * start. - */ -public final class StompBrokerExclusivity { - - private StompBrokerExclusivity() {} - - /** - * Fail the context rather than start an ambiguous broker. - * - * @param legacyStompEnabled whether {@code app.websocket.enabled} is set - * @param advancedStompEnabled whether the Advanced STOMP capability is named - * @param simpleBrokerEnabled whether the in-memory broker is configured - * @param relayEnabled whether the RabbitMQ relay is configured - */ - public static void verify( - boolean legacyStompEnabled, - boolean advancedStompEnabled, - boolean simpleBrokerEnabled, - boolean relayEnabled) { - List faults = new ArrayList<>(); - if (legacyStompEnabled && advancedStompEnabled) { - faults.add( - "both the legacy STOMP channel (app.websocket.enabled) and the Advanced STOMP " - + "adapter are enabled; each configures the message broker and the one that wins is " - + "decided by bean ordering"); - } - if (advancedStompEnabled && simpleBrokerEnabled && relayEnabled) { - faults.add( - "the simple broker and the RabbitMQ relay are both enabled; they are alternatives, and " - + "enabling both means subscriptions land in one of them and publishes in the other"); - } - if (advancedStompEnabled && !simpleBrokerEnabled && !relayEnabled) { - faults.add( - "the Advanced STOMP adapter is enabled with no broker behind it; every SUBSCRIBE would " - + "be accepted and nothing would ever be delivered"); - } - if (!faults.isEmpty()) { - throw new IllegalStateException( - "STOMP broker configuration is ambiguous: " + String.join("; ", faults)); - } - } - - /** The same check as a predicate, for a report that wants to show the state without failing. */ - public static boolean valid( - boolean legacyStompEnabled, - boolean advancedStompEnabled, - boolean simpleBrokerEnabled, - boolean relayEnabled) { - try { - verify(legacyStompEnabled, advancedStompEnabled, simpleBrokerEnabled, relayEnabled); - return true; - } catch (IllegalStateException refused) { - Objects.requireNonNull(refused); - return false; - } - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompConfiguration.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompConfiguration.java deleted file mode 100644 index cfb5d3df..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompConfiguration.java +++ /dev/null @@ -1,52 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.stomp; - -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.messaging.simp.config.ChannelRegistration; -import org.springframework.messaging.simp.config.MessageBrokerRegistry; -import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; -import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; - -/** - * Applies the Advanced STOMP profile to Spring's broker registry. - * - *

Only when the capability is named and the legacy channel is not enabled. That second condition - * is not belt-and-braces: two {@code @EnableWebSocketMessageBroker} configurations in one context - * produce a broker whose prefixes are whichever configurer ran last, with no error anywhere. {@link - * StompBrokerExclusivity} still runs and still fails loudly, because a condition that quietly - * declines to start the adapter looks from the outside exactly like an adapter that started and - * does nothing. - */ -@Configuration(proxyBeanMethods = false) -@EnableWebSocketMessageBroker -@Import(StompDefaultsConfiguration.class) -@ConditionalOnProperty( - prefix = "app.websocket.advanced.stomp", - name = "enabled", - havingValue = "true") -public class StompConfiguration implements WebSocketMessageBrokerConfigurer { - - private final StompProfile profile; - private final StompSecurityInterceptor securityInterceptor; - - public StompConfiguration(StompProfile profile, StompSecurityInterceptor securityInterceptor) { - this.profile = profile; - this.securityInterceptor = securityInterceptor; - } - - @Override - public void configureClientInboundChannel(ChannelRegistration registration) { - registration.interceptors(securityInterceptor); - } - - @Override - public void configureMessageBroker(MessageBrokerRegistry registry) { - registry.setApplicationDestinationPrefixes( - profile.applicationPrefixes().toArray(String[]::new)); - registry.setPreservePublishOrder(profile.preserveOrder()); - profile.userPrefixes().stream().findFirst().ifPresent(registry::setUserDestinationPrefix); - // The broker itself is contributed by whichever broker configuration is active. Enabling none - // is refused by StompBrokerExclusivity rather than silently accepted here. - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompDefaultsConfiguration.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompDefaultsConfiguration.java deleted file mode 100644 index 47a528da..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompDefaultsConfiguration.java +++ /dev/null @@ -1,64 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.stomp; - -import java.security.Principal; -import java.util.Set; -import java.util.function.Function; -import org.springframework.beans.factory.ObjectProvider; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -/** - * The Advanced STOMP beans, separate from the configurer that consumes them. - * - *

Separate because a {@code @Configuration} class cannot take its own {@code @Bean} methods as - * constructor arguments — Spring has to build the class before it can call them, and asking for - * both is a cycle the context refuses to start with. - */ -@Configuration(proxyBeanMethods = false) -@ConditionalOnProperty( - prefix = "app.websocket.advanced.stomp", - name = "enabled", - havingValue = "true") -public class StompDefaultsConfiguration { - - /** The prefix layout, overridable by a deployment that declares its own. */ - @Bean - @ConditionalOnMissingBean - public StompProfile stompProfile() { - return StompProfile.conventional(); - } - - /** - * The authorization policy. - * - *

Requires a catalog, and there is deliberately no default one. A default would have to either - * declare nothing, which refuses every frame and reads as a broken adapter, or declare something, - * which publishes destinations nobody chose. - */ - @Bean - @ConditionalOnMissingBean - public StompAuthorizationPolicy stompAuthorizationPolicy( - ObjectProvider catalog) { - StompDestinationCatalog value = catalog.getIfAvailable(); - if (value == null) { - throw new IllegalStateException( - "Advanced STOMP requires a StompDestinationCatalog bean from the composition root"); - } - return new StompAuthorizationPolicy(value); - } - - /** The interceptor, given whatever this deployment uses to read a principal's permissions. */ - @Bean - @ConditionalOnMissingBean - public StompSecurityInterceptor stompSecurityInterceptor( - StompAuthorizationPolicy policy, - ObjectProvider>> permissionReader) { - // No reader configured means no permissions, which means every declared destination is refused - // for want of one. That is the safe direction: the alternative default is "everybody holds - // everything", and it would not be noticed until it was in production. - return new StompSecurityInterceptor( - policy, permissionReader.getIfAvailable(() -> principal -> Set.of())); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompDestinationCatalog.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompDestinationCatalog.java deleted file mode 100644 index 6c3788f5..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompDestinationCatalog.java +++ /dev/null @@ -1,129 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.stomp; - -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; - -/** - * The destinations that exist, and what each one requires. - * - *

Declared rather than discovered. A STOMP destination arrives as a free string from the client, - * so without a catalog the set of reachable destinations is whatever the broker happens to accept — - * which for the simple broker is every string, and for a relay is every string the broker's own - * topology permits. Neither is a decision anybody made. - * - *

Authorization is per operation, not per destination. The same feed is usually readable by many - * and writable by few, and a catalog that carried one permission per destination would have to pick - * the looser of the two. - */ -public final class StompDestinationCatalog { - - private final StompProfile profile; - private final Map permissions; - - private StompDestinationCatalog(StompProfile profile, Map permissions) { - this.profile = profile; - this.permissions = Map.copyOf(permissions); - } - - /** A builder, because a catalog is written once at startup and read on every frame. */ - public static Builder using(StompProfile profile) { - return new Builder(Objects.requireNonNull(profile, "profile")); - } - - /** The prefix profile this catalog was built against. */ - public StompProfile profile() { - return profile; - } - - /** Every declared entry, for the startup report. */ - public List declaredDestinations() { - return permissions.keySet().stream().map(Key::destination).distinct().sorted().toList(); - } - - /** - * The permission required for one operation on one destination. - * - *

Empty means undeclared, and undeclared means refused. Returning a permissive default here - * would make every unlisted destination reachable, which is the failure this class exists to - * prevent. - */ - public Optional permissionFor(StompOperation operation, String destination) { - Objects.requireNonNull(operation, "operation"); - if (destination == null) { - return Optional.empty(); - } - return Optional.ofNullable(permissions.get(new Key(operation, destination))); - } - - /** Whether the destination is declared for the operation at all. */ - public boolean declares(StompOperation operation, String destination) { - return permissionFor(operation, destination).isPresent(); - } - - private record Key(StompOperation operation, String destination) {} - - /** Collects declarations and checks them against the profile as they are made. */ - public static final class Builder { - - private final StompProfile profile; - private final Map permissions = new LinkedHashMap<>(); - - private Builder(StompProfile profile) { - this.profile = profile; - } - - /** - * Declare a destination and the permission each listed operation needs. - * - * @param destination the exact destination string - * @param permission the permission a caller must hold - * @param operations which operations that permission covers - */ - public Builder declare(String destination, String permission, StompOperation... operations) { - Objects.requireNonNull(destination, "destination"); - Objects.requireNonNull(permission, "permission"); - if (permission.isBlank()) { - throw new IllegalArgumentException( - "a blank permission reads as 'declared' while granting everyone access"); - } - if (operations.length == 0) { - throw new IllegalArgumentException( - "a destination declared for no operation is unreachable, which is almost never what " - + "the author meant"); - } - // Checked here rather than at first use: a destination outside every prefix is dead on - // arrival, and startup is when somebody is still reading the output. - if (profile.roleOf(destination).isEmpty()) { - throw new IllegalArgumentException( - "destination matches no declared prefix, so nothing would ever route to it: " - + destination); - } - for (StompOperation operation : Set.of(operations)) { - String previous = permissions.putIfAbsent(new Key(operation, destination), permission); - if (previous != null && !previous.equals(permission)) { - throw new IllegalArgumentException( - "two permissions declared for " - + operation - + " on " - + destination - + "; the looser one would win by accident"); - } - } - return this; - } - - /** Freeze the catalog. */ - public StompDestinationCatalog build() { - if (permissions.isEmpty()) { - throw new IllegalArgumentException( - "an empty catalog refuses every frame, which is a misconfiguration rather than a " - + "lockdown"); - } - return new StompDestinationCatalog(profile, permissions); - } - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompDestinationRole.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompDestinationRole.java deleted file mode 100644 index 7f668c6f..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompDestinationRole.java +++ /dev/null @@ -1,14 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.stomp; - -/** What a matched destination prefix means for routing. */ -public enum StompDestinationRole { - - /** Routed into application code. */ - APPLICATION, - - /** Routed to the broker, with no application code in the path. */ - BROKER, - - /** Resolved to one session's private destination before routing. */ - USER -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompEvidence.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompEvidence.java deleted file mode 100644 index b3630b24..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompEvidence.java +++ /dev/null @@ -1,71 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.stomp; - -/** - * What a STOMP acknowledgement actually proves. - * - *

Six stages because STOMP hands out three different signals that all look like success, and - * conflating any two of them produces a system that reports work as done when it is not. The order - * of the constants is the order the stages occur in; nothing else about it is meaningful, and the - * {@link #rank()} below exists so no caller reaches for the ordinal. - * - *

The specific confusion this exists to prevent: a STOMP {@code RECEIPT} frame means the server - * read the frame. It does not mean a handler ran, a transaction committed, or a broker stored - * anything. A client that treats a receipt as a commit will show a user their order was placed - * while the transaction that would have placed it is still open — or already rolled back. - */ -public enum StompEvidence { - - /** The server read the frame off the socket. Proves transport, nothing else. */ - FRAME_RECEIVED(0), - - /** - * A STOMP {@code RECEIPT} frame was sent. - * - *

A protocol-level acknowledgement of receipt. Explicitly not a commit: the receipt is written - * by the protocol layer, which knows nothing about whether the work succeeded. - */ - PROTOCOL_RECEIPT(1), - - /** The broker accepted the message for delivery. */ - BROKER_DELIVERY(2), - - /** - * The broker acknowledged it. - * - *

Durable only if the broker is durable. Against the simple in-memory broker this stage is - * reached and still survives nothing, which is why the broker profile carries {@code - * durableAckSupported} rather than this enum implying it. - */ - BROKER_ACK(3), - - /** Application code ran and its transaction committed. The first stage that means "done". */ - APPLICATION_COMMIT(4), - - /** The client sent an {@code ACK} frame saying it applied the message. */ - CLIENT_APPLIED(5); - - private final int rank; - - StompEvidence(int rank) { - this.rank = rank; - } - - /** How far along the chain this stage sits. Declared, so no caller depends on the ordinal. */ - public int rank() { - return rank; - } - - /** Whether this stage means the work itself is done rather than merely observed. */ - public boolean provesCompletion() { - return this == APPLICATION_COMMIT || this == CLIENT_APPLIED; - } - - /** - * Whether reporting {@code claimed} on the strength of {@code this} would overstate the case. - * - * @param claimed the stage a caller wants to report - */ - public boolean wouldOverstate(StompEvidence claimed) { - return claimed.rank() > rank; - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompFrameRequest.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompFrameRequest.java deleted file mode 100644 index a8cf7d28..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompFrameRequest.java +++ /dev/null @@ -1,35 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.stomp; - -import java.util.Objects; -import java.util.Optional; -import java.util.Set; - -/** - * One inbound STOMP frame, reduced to what the authorization decision needs. - * - *

Deliberately not the Spring message. The policy is the part worth testing exhaustively, and - * making it depend on a {@code Message} would mean every case needed a channel and an accessor to - * express. The interceptor does the extraction; this carries the result. - * - * @param operation what the frame is trying to do - * @param destination the destination as the client wrote it - * @param principalName the authenticated principal, absent when there is none - * @param grantedPermissions what the principal holds - * @param ackHeader the raw {@code ack} header, absent when unset - */ -public record StompFrameRequest( - StompOperation operation, - String destination, - Optional principalName, - Set grantedPermissions, - Optional ackHeader) { - - public StompFrameRequest { - Objects.requireNonNull(operation, "operation"); - Objects.requireNonNull(destination, "destination"); - Objects.requireNonNull(principalName, "principalName"); - Objects.requireNonNull(ackHeader, "ackHeader"); - grantedPermissions = - Set.copyOf(Objects.requireNonNull(grantedPermissions, "grantedPermissions")); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompOperation.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompOperation.java deleted file mode 100644 index b84c563b..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompOperation.java +++ /dev/null @@ -1,17 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.stomp; - -/** - * The STOMP frame commands the adapter authorizes. - * - *

{@link #SUBSCRIBE} and {@link #SEND} are separate because they are separate permissions. - * Reading a destination and writing to it are different rights, and a catalog that authorized them - * together would let anyone who may watch an order feed also publish into it. - */ -public enum StompOperation { - - /** Establishing a subscription: the right to read a destination. */ - SUBSCRIBE, - - /** Sending a frame: the right to write to a destination. */ - SEND -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompProfile.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompProfile.java deleted file mode 100644 index c0efc6e4..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompProfile.java +++ /dev/null @@ -1,118 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.stomp; - -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Objects; -import java.util.Set; - -/** - * Which destination prefixes mean what. - * - *

Three separate prefix sets rather than one, because the three have different security - * consequences and merging them is how a client subscribes to a destination that was meant to be - * server-only. An application prefix routes a frame into application code; a broker prefix routes - * it to whatever broker is configured, with no application code in the path; a user prefix is - * resolved per session before either happens. A destination that matched two of them would be - * dispatched by whichever check ran first. - * - *

A destination string is not a reliability guarantee. {@code /topic/orders} says where a - * message goes, not that it arrives, is ordered, or survives a broker restart — those come from the - * broker profile, and the simple broker offers none of them. - * - * @param applicationPrefixes prefixes routed into {@code @MessageMapping} handlers - * @param brokerPrefixes prefixes routed straight to the broker - * @param userPrefixes prefixes resolved to a single session before routing - * @param preserveOrder whether to preserve publication order per session - */ -public record StompProfile( - Set applicationPrefixes, - Set brokerPrefixes, - Set userPrefixes, - boolean preserveOrder) { - - public StompProfile { - applicationPrefixes = normalize(applicationPrefixes, "applicationPrefixes"); - brokerPrefixes = normalize(brokerPrefixes, "brokerPrefixes"); - userPrefixes = normalize(userPrefixes, "userPrefixes"); - if (applicationPrefixes.isEmpty() && brokerPrefixes.isEmpty()) { - throw new IllegalArgumentException( - "a STOMP profile with neither an application nor a broker prefix routes nothing"); - } - rejectOverlap(applicationPrefixes, brokerPrefixes, "application", "broker"); - rejectOverlap(applicationPrefixes, userPrefixes, "application", "user"); - rejectOverlap(brokerPrefixes, userPrefixes, "broker", "user"); - } - - /** - * The conventional layout: {@code /app} into handlers, {@code /topic} and {@code /queue} to the - * broker, {@code /user} resolved per session. - */ - public static StompProfile conventional() { - return new StompProfile(Set.of("/app"), Set.of("/topic", "/queue"), Set.of("/user"), true); - } - - /** - * Which of the three roles a destination has, if any. - * - *

Returns empty for anything unmatched, and the caller must treat that as a refusal rather - * than a default. A STOMP client sends the destination as a free string, so "unmatched" is the - * normal shape of both a typo and an attempt to reach somewhere that was never published. - */ - public java.util.Optional roleOf(String destination) { - if (destination == null || destination.isBlank()) { - return java.util.Optional.empty(); - } - if (matchesAny(userPrefixes, destination)) { - return java.util.Optional.of(StompDestinationRole.USER); - } - if (matchesAny(applicationPrefixes, destination)) { - return java.util.Optional.of(StompDestinationRole.APPLICATION); - } - if (matchesAny(brokerPrefixes, destination)) { - return java.util.Optional.of(StompDestinationRole.BROKER); - } - return java.util.Optional.empty(); - } - - private static boolean matchesAny(Set prefixes, String destination) { - // Prefix plus a separator, not bare startsWith: "/topicprivate" is not under "/topic", and - // treating it as though it were hands the caller a destination the operator never published. - return prefixes.stream() - .anyMatch(prefix -> destination.equals(prefix) || destination.startsWith(prefix + "/")); - } - - private static Set normalize(Set prefixes, String field) { - Objects.requireNonNull(prefixes, field); - Set normalized = new LinkedHashSet<>(); - for (String prefix : prefixes) { - Objects.requireNonNull(prefix, field); - if (!prefix.startsWith("/") || prefix.endsWith("/") || prefix.contains("//")) { - throw new IllegalArgumentException( - "a STOMP prefix must be an absolute normalized path without a trailing slash: " - + prefix); - } - normalized.add(prefix); - } - return Set.copyOf(normalized); - } - - private static void rejectOverlap(Set left, Set right, String a, String b) { - List clashes = - left.stream() - .filter(prefix -> right.stream().anyMatch(other -> nested(prefix, other))) - .toList(); - if (!clashes.isEmpty()) { - throw new IllegalArgumentException( - "a destination cannot be both " - + a - + " and " - + b - + "; whichever check ran first would decide where it went: " - + clashes); - } - } - - private static boolean nested(String one, String other) { - return one.equals(other) || one.startsWith(other + "/") || other.startsWith(one + "/"); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompRefusal.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompRefusal.java deleted file mode 100644 index 7b68f2d6..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompRefusal.java +++ /dev/null @@ -1,29 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.stomp; - -/** - * Why a STOMP frame was refused. - * - *

A closed set, because this is what reaches the metric tag. The destination cannot: it is - * client-supplied and unbounded, and a metric tagged with it turns any client into a way to exhaust - * the metrics backend's cardinality budget. - */ -public enum StompRefusal { - - /** The frame arrived before the connection was authenticated. */ - UNAUTHENTICATED, - - /** The destination is not in the catalog. Undeclared is refused, never allowed by default. */ - UNDECLARED_DESTINATION, - - /** The destination is declared, but not for this operation. */ - OPERATION_NOT_PERMITTED, - - /** The caller is authenticated but lacks the declared permission. */ - MISSING_PERMISSION, - - /** The frame's {@code ack} header named a mode the server does not implement. */ - UNSUPPORTED_ACK_MODE, - - /** A user-prefixed destination naming somebody other than the caller. */ - FOREIGN_USER_DESTINATION -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompSecurityInterceptor.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompSecurityInterceptor.java deleted file mode 100644 index 843a0aa7..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompSecurityInterceptor.java +++ /dev/null @@ -1,96 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.stomp; - -import java.security.Principal; -import java.util.Collection; -import java.util.List; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; -import java.util.function.Function; -import org.springframework.messaging.Message; -import org.springframework.messaging.MessageChannel; -import org.springframework.messaging.simp.stomp.StompCommand; -import org.springframework.messaging.simp.stomp.StompHeaderAccessor; -import org.springframework.messaging.support.ChannelInterceptor; -import org.springframework.messaging.support.MessageHeaderAccessor; - -/** - * Applies {@link StompAuthorizationPolicy} to the client inbound channel. - * - *

This class is extraction and enforcement only; every judgement lives in the policy. The split - * is not tidiness — an authorization rule that can only be exercised through a {@code - * MessageChannel} gets tested for the two cases somebody bothered to build a channel for, and the - * ones nobody built are the ones that let a frame through. - * - *

It refuses by throwing, because on this channel that is the only thing a client notices. - * Returning {@code null} from {@code preSend} drops the message silently, and a client whose - * SUBSCRIBE was silently dropped waits forever for messages that will never come, with nothing in - * either log explaining why. - */ -public final class StompSecurityInterceptor implements ChannelInterceptor { - - private final StompAuthorizationPolicy policy; - private final Function> permissionsOf; - - /** - * @param policy the decision table - * @param permissionsOf how to read a principal's permissions; supplied rather than assumed so - * this leaf does not acquire a Spring Security dependency for one call - */ - public StompSecurityInterceptor( - StompAuthorizationPolicy policy, Function> permissionsOf) { - this.policy = Objects.requireNonNull(policy, "policy"); - this.permissionsOf = Objects.requireNonNull(permissionsOf, "permissionsOf"); - } - - @Override - public Message preSend(Message message, MessageChannel channel) { - StompHeaderAccessor accessor = - MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class); - if (accessor == null || accessor.isHeartbeat() || accessor.getCommand() == null) { - return message; - } - Optional operation = operationFor(accessor.getCommand()); - if (operation.isEmpty()) { - // CONNECT, DISCONNECT, ACK, NACK and the transaction frames carry no destination, so there - // is nothing for this policy to authorize. They are not thereby unguarded: the handshake - // authenticates, and ACK/NACK are checked against the subscription that issued them. - return message; - } - String destination = accessor.getDestination(); - if (destination == null) { - throw new StompAuthorizationException(StompRefusal.UNDECLARED_DESTINATION); - } - Principal user = accessor.getUser(); - StompFrameRequest request = - new StompFrameRequest( - operation.get(), - destination, - Optional.ofNullable(user).map(Principal::getName), - user == null ? Set.of() : permissionsOf.apply(user), - firstHeader(accessor, "ack")); - StompAuthorizationDecision decision = policy.decide(request); - if (!decision.allowed()) { - throw new StompAuthorizationException(decision.reason().orElseThrow()); - } - return message; - } - - private static Optional operationFor(StompCommand command) { - if (command == StompCommand.SUBSCRIBE) { - return Optional.of(StompOperation.SUBSCRIBE); - } - if (command == StompCommand.SEND) { - return Optional.of(StompOperation.SEND); - } - return Optional.empty(); - } - - private static Optional firstHeader(StompHeaderAccessor accessor, String name) { - Collection values = accessor.getNativeHeader(name); - if (values == null || values.isEmpty()) { - return Optional.empty(); - } - return Optional.ofNullable(List.copyOf(values).get(0)); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/rabbit/MultiNodeUserDestination.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/rabbit/MultiNodeUserDestination.java deleted file mode 100644 index 1e1f64ba..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/rabbit/MultiNodeUserDestination.java +++ /dev/null @@ -1,98 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.stomp.rabbit; - -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketNodeId; -import java.time.Instant; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.concurrent.ConcurrentHashMap; - -/** - * Resolves a user destination to a node, and decides what to do when it cannot. - * - *

Three outcomes, and the third is the one that exists to stop a loop. A message for a locally - * held user is delivered here. A message for a user held elsewhere, or not found, is broadcast once - * so the holding node can claim it. A message that arrived *because* of such a broadcast and still - * cannot be resolved is sent to the unresolved destination and never broadcast again — otherwise - * every node rebroadcasts it on receipt, and the cluster spends its entire broker budget passing - * one undeliverable message around. - * - *

The registry is a cache. Entries expire, and an expired entry is treated as absent rather than - * as "not connected": the difference is that absent still broadcasts, while "not connected" would - * drop the message for a user who is connected to a node that merely stopped refreshing. - */ -public final class MultiNodeUserDestination { - - private final UserDestinationPolicy policy; - private final WebSocketNodeId localNode; - private final Map registry = new ConcurrentHashMap<>(); - - public MultiNodeUserDestination(UserDestinationPolicy policy, WebSocketNodeId localNode) { - this.policy = Objects.requireNonNull(policy, "policy"); - this.localNode = Objects.requireNonNull(localNode, "localNode"); - } - - /** Record that this node holds a session for the user. */ - public void register(String userFingerprint, Instant at) { - Objects.requireNonNull(userFingerprint, "userFingerprint"); - registry.put(userFingerprint, new UserSessionLocation(localNode, Objects.requireNonNull(at))); - } - - /** Record that some other node reported holding the user. */ - public void observe(String userFingerprint, WebSocketNodeId node, Instant at) { - Objects.requireNonNull(userFingerprint, "userFingerprint"); - registry.put(userFingerprint, new UserSessionLocation(node, Objects.requireNonNull(at))); - } - - /** - * Forget a session. - * - *

Called on disconnect, and this is also where the broker's temporary queue is released. A - * relay creates one per user destination subscription; without this the queues accumulate for - * every session that ever connected, and RabbitMQ's memory alarm fires long before anybody - * connects the two facts. - */ - public boolean deregister(String userFingerprint) { - return registry.remove(userFingerprint) != null; - } - - /** Drop entries no node has refreshed within the policy's TTL. Returns how many went. */ - public int evictExpired(Instant now) { - Objects.requireNonNull(now, "now"); - int before = registry.size(); - registry.values().removeIf(location -> expired(location, now)); - return before - registry.size(); - } - - /** How many mappings are held. */ - public int trackedUsers() { - return registry.size(); - } - - /** - * Decide how to deliver. - * - * @param userFingerprint whose message this is - * @param alreadyBroadcast whether this message arrived via the cluster broadcast - * @param now the current instant - */ - public UserDestinationRouting route( - String userFingerprint, boolean alreadyBroadcast, Instant now) { - Objects.requireNonNull(userFingerprint, "userFingerprint"); - Objects.requireNonNull(now, "now"); - Optional location = - Optional.ofNullable(registry.get(userFingerprint)).filter(entry -> !expired(entry, now)); - if (location.isPresent() && location.get().nodeId().equals(localNode)) { - return UserDestinationRouting.deliverLocally(); - } - if (alreadyBroadcast) { - // The message is already the result of a broadcast. Broadcasting it again is the loop. - return UserDestinationRouting.sendToUnresolved(policy.unresolvedDestination()); - } - return UserDestinationRouting.broadcast(policy.broadcastDestination()); - } - - private boolean expired(UserSessionLocation location, Instant now) { - return !now.isBefore(location.registeredAt().plus(policy.registryTtl())); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/rabbit/RabbitBrokerRelayConfiguration.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/rabbit/RabbitBrokerRelayConfiguration.java deleted file mode 100644 index d03fa771..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/rabbit/RabbitBrokerRelayConfiguration.java +++ /dev/null @@ -1,78 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.stomp.rabbit; - -import dev.caskeleton.adapter.inbound.websocket.advanced.stomp.StompProfile; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketNodeId; -import org.springframework.beans.factory.ObjectProvider; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.messaging.simp.config.MessageBrokerRegistry; -import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; - -/** - * Points the broker at RabbitMQ instead of the in-memory one. - * - *

Contributes only the broker, not the prefixes: those belong to {@link StompProfile} and are - * applied by the STOMP configuration. Two configurers each setting the application prefix is the - * failure this arrangement avoids. - * - *

Enabling this makes delivery depend on a separate machine over a network. The heartbeat is - * configured from the profile rather than defaulted, because the default is the thing that decides - * whether a half-open connection to a dead broker is noticed in seconds or never. - */ -@Configuration(proxyBeanMethods = false) -@ConditionalOnProperty( - prefix = "app.websocket.advanced.stomp.relay", - name = "enabled", - havingValue = "true") -public class RabbitBrokerRelayConfiguration implements WebSocketMessageBrokerConfigurer { - - private final StompProfile profile; - private final RabbitBrokerRelayProfile relay; - - public RabbitBrokerRelayConfiguration(StompProfile profile, RabbitBrokerRelayProfile relay) { - this.profile = profile; - this.relay = relay; - } - - /** The relay target, overridable by a deployment that declares its own. */ - @Bean - @ConditionalOnMissingBean - public static RabbitBrokerRelayProfile rabbitBrokerRelayProfile() { - // static, so the bean is available before this configuration class is constructed - the same - // cycle StompDefaultsConfiguration exists to avoid, here for a single bean. - return RabbitBrokerRelayProfile.localPlaintext(); - } - - /** How a user destination is resolved across nodes. */ - @Bean - @ConditionalOnMissingBean - public UserDestinationPolicy userDestinationPolicy() { - return UserDestinationPolicy.conventional(); - } - - /** The per-node routing table for user destinations. */ - @Bean - @ConditionalOnMissingBean - public MultiNodeUserDestination multiNodeUserDestination( - UserDestinationPolicy policy, ObjectProvider nodeId) { - WebSocketNodeId value = nodeId.getIfAvailable(); - if (value == null) { - throw new IllegalStateException( - "STOMP relay requires a WebSocketNodeId bean from the composition root"); - } - return new MultiNodeUserDestination(policy, value); - } - - @Override - public void configureMessageBroker(MessageBrokerRegistry registry) { - long heartbeat = relay.systemHeartbeat().toMillis(); - registry - .enableStompBrokerRelay(profile.brokerPrefixes().toArray(String[]::new)) - .setRelayHost(relay.host()) - .setRelayPort(relay.port()) - .setSystemHeartbeatSendInterval(heartbeat) - .setSystemHeartbeatReceiveInterval(heartbeat); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/rabbit/RabbitBrokerRelayProfile.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/rabbit/RabbitBrokerRelayProfile.java deleted file mode 100644 index ca2c2fef..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/rabbit/RabbitBrokerRelayProfile.java +++ /dev/null @@ -1,78 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.stomp.rabbit; - -import java.time.Duration; -import java.util.List; -import java.util.Objects; - -/** - * Where the external STOMP broker is and how the relay talks to it. - * - *

The relay changes the failure model rather than adding a feature. With the simple broker, - * delivery fails when this JVM fails; with a relay, delivery fails when a separate machine fails, - * over a network, and the platform's own health check will keep reporting green throughout. That is - * why {@code systemHeartbeat} is part of the profile and not a default: it is the only thing that - * notices a relay connection that is open at the TCP level and dead above it. - * - * @param host the broker's host - * @param port its STOMP port - * @param tls whether the relay connection is encrypted - * @param systemHeartbeat the interval the relay's own connection heartbeats at - */ -public record RabbitBrokerRelayProfile( - String host, int port, boolean tls, Duration systemHeartbeat) { - - public RabbitBrokerRelayProfile { - Objects.requireNonNull(host, "host"); - Objects.requireNonNull(systemHeartbeat, "systemHeartbeat"); - if (host.isBlank()) { - throw new IllegalArgumentException( - "a blank broker host resolves to something, and it is " - + "never the broker that was meant"); - } - if (port < 1 || port > 65535) { - throw new IllegalArgumentException("not a port: " + port); - } - if (systemHeartbeat.isNegative() || systemHeartbeat.isZero()) { - throw new IllegalArgumentException( - "a relay without a heartbeat cannot tell a quiet broker from a dead one, and a " - + "half-open TCP connection to a dead broker accepts every publish silently"); - } - } - - /** The conventional local development relay: plaintext, on the RabbitMQ STOMP port. */ - public static RabbitBrokerRelayProfile localPlaintext() { - return new RabbitBrokerRelayProfile("localhost", 61613, false, Duration.ofSeconds(10)); - } - - /** - * What this profile is missing before it is fit for anything but a developer's machine. - * - *

Reported rather than enforced here, because "is this deployment allowed to be plaintext" is - * a question the startup validator answers with the active profiles in hand. - */ - public List productionConcerns() { - if (tls) { - return List.of(); - } - return List.of( - "the relay carries every message and the broker credentials in clear text; anything on " - + "the path between this node and the broker reads both"); - } - - /** - * How many broker connections a client population costs. - * - *

Worth computing before the first outage rather than after. The relay opens one shared system - * connection plus one per authenticated user session, so a broker with a connection limit turns a - * normal-looking client count into a hard ceiling — and the symptom is new users failing to - * subscribe while existing ones are fine. - * - * @param authenticatedSessions how many user sessions are connected - */ - public int brokerConnectionsFor(int authenticatedSessions) { - if (authenticatedSessions < 0) { - throw new IllegalArgumentException("a session count cannot be negative"); - } - return authenticatedSessions + 1; - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/rabbit/UserDestinationAction.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/rabbit/UserDestinationAction.java deleted file mode 100644 index 59c9a8eb..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/rabbit/UserDestinationAction.java +++ /dev/null @@ -1,21 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.stomp.rabbit; - -/** - * The three dispositions of a user-addressed message. - * - *

A closed set, and the metric is tagged with this rather than with the destination. A user - * destination contains a user identifier by construction, so tagging a metric with it publishes - * every user's name into the metrics backend and gives the cardinality budget an unbounded - * denominator. - */ -public enum UserDestinationAction { - - /** The session is on this node. */ - DELIVER_LOCALLY, - - /** Published to the cluster so the holding node can claim it. */ - BROADCAST, - - /** Already broadcast once and still unclaimed. Terminal, so the loop ends. */ - UNRESOLVED -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/rabbit/UserDestinationPolicy.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/rabbit/UserDestinationPolicy.java deleted file mode 100644 index f092cb56..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/rabbit/UserDestinationPolicy.java +++ /dev/null @@ -1,50 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.stomp.rabbit; - -import java.time.Duration; -import java.util.Objects; - -/** - * How a message for a user who is connected to some other node gets there. - * - *

The mechanism is a broadcast: a node that cannot resolve a user locally publishes to a - * cluster-wide destination, and whichever node holds that session picks it up. Two things about it - * are easy to get wrong, and both are why this is a declared policy rather than three string - * constants. - * - *

First, the broadcast destination and the unresolved destination must differ. If a node - * republished unresolved messages onto the same destination it listens to, every node would - * re-broadcast every unresolvable message forever — a loop that saturates the broker and looks, - * from any single node, like ordinary traffic. - * - *

Second, the registry entry has to expire. It maps a user to a node, the node can vanish - * without unregistering, and an entry that never expires routes that user's messages at a machine - * that is gone. - * - * @param broadcastDestination where a node publishes messages for users it does not hold - * @param unresolvedDestination where messages nobody claimed are sent - * @param registryTtl how long a user-to-node mapping is trusted - */ -public record UserDestinationPolicy( - String broadcastDestination, String unresolvedDestination, Duration registryTtl) { - - public UserDestinationPolicy { - Objects.requireNonNull(broadcastDestination, "broadcastDestination"); - Objects.requireNonNull(unresolvedDestination, "unresolvedDestination"); - Objects.requireNonNull(registryTtl, "registryTtl"); - if (broadcastDestination.equals(unresolvedDestination)) { - throw new IllegalArgumentException( - "the broadcast and unresolved destinations must differ, or every node re-broadcasts " - + "every unresolvable message forever"); - } - if (registryTtl.isNegative() || registryTtl.isZero()) { - throw new IllegalArgumentException( - "a user-to-node mapping that never expires keeps routing at nodes that no longer exist"); - } - } - - /** The conventional layout. */ - public static UserDestinationPolicy conventional() { - return new UserDestinationPolicy( - "/topic/unresolved-user", "/topic/unresolved-user-dlq", Duration.ofMinutes(2)); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/rabbit/UserDestinationRouting.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/rabbit/UserDestinationRouting.java deleted file mode 100644 index 88dd3328..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/rabbit/UserDestinationRouting.java +++ /dev/null @@ -1,42 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.stomp.rabbit; - -import java.util.Objects; -import java.util.Optional; - -/** - * What to do with a message addressed to a user. - * - *

The destination is carried on the routing rather than looked up again by the caller, so the - * decision and the address it implies cannot drift apart. - * - * @param action the disposition - * @param destination where to publish, absent for local delivery - */ -public record UserDestinationRouting(UserDestinationAction action, Optional destination) { - - public UserDestinationRouting { - Objects.requireNonNull(action, "action"); - Objects.requireNonNull(destination, "destination"); - if (action == UserDestinationAction.DELIVER_LOCALLY != destination.isEmpty()) { - throw new IllegalArgumentException( - "local delivery names no destination and a publish must name one"); - } - } - - /** The session is here. */ - public static UserDestinationRouting deliverLocally() { - return new UserDestinationRouting(UserDestinationAction.DELIVER_LOCALLY, Optional.empty()); - } - - /** Ask the cluster who holds it. */ - public static UserDestinationRouting broadcast(String destination) { - return new UserDestinationRouting( - UserDestinationAction.BROADCAST, Optional.of(Objects.requireNonNull(destination))); - } - - /** Nobody claimed it and it has already been round the cluster once. */ - public static UserDestinationRouting sendToUnresolved(String destination) { - return new UserDestinationRouting( - UserDestinationAction.UNRESOLVED, Optional.of(Objects.requireNonNull(destination))); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/rabbit/UserSessionLocation.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/rabbit/UserSessionLocation.java deleted file mode 100644 index 588d5e40..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/rabbit/UserSessionLocation.java +++ /dev/null @@ -1,22 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.stomp.rabbit; - -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketNodeId; -import java.time.Instant; -import java.util.Objects; - -/** - * Where a user was last seen connected. - * - *

A cache of a fact owned by another node, so it carries when it was written and is never read - * without that being checked. - * - * @param nodeId the node that reported holding the session - * @param registeredAt when it reported - */ -public record UserSessionLocation(WebSocketNodeId nodeId, Instant registeredAt) { - - public UserSessionLocation { - Objects.requireNonNull(nodeId, "nodeId"); - Objects.requireNonNull(registeredAt, "registeredAt"); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/authz/MessageAuthorizationPolicy.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/authz/MessageAuthorizationPolicy.java deleted file mode 100644 index 0fc1be11..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/authz/MessageAuthorizationPolicy.java +++ /dev/null @@ -1,93 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.authz; - -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageType; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Set; - -/** - * What a caller must hold to send a particular message type. - * - *

Per message, not per connection, and the difference is the whole point. A connection is - * authorised once at handshake and then lives for hours: authorising there means the caller keeps - * whatever it had when it connected, through every role change and every revocation, until it - * happens to reconnect. On a connection that survives a deploy that is a permission that outlives - * the decision to remove it. - * - *

Per-message authorization also lets one endpoint carry types of different sensitivity, which - * is what an application actually wants — a feed and the commands that act on it are naturally the - * same connection. - * - *

Fail-closed: a type with no declared requirement is refused rather than allowed. A new message - * type is added by someone thinking about the message, not about the permission, and defaulting to - * allow means the omission ships. - */ -public final class MessageAuthorizationPolicy { - - private final Map> requirements; - - private MessageAuthorizationPolicy(Map> requirements) { - this.requirements = requirements; - } - - /** - * A policy over the declared requirements. - * - * @param requirements the authorities each type demands; an empty set means authenticated-only - */ - public static MessageAuthorizationPolicy of(Map> requirements) { - Objects.requireNonNull(requirements, "requirements"); - Map> copy = new LinkedHashMap<>(); - requirements.forEach( - (type, authorities) -> { - Objects.requireNonNull(type, "type"); - Objects.requireNonNull(authorities, "authorities"); - copy.put(type, Set.copyOf(authorities)); - }); - return new MessageAuthorizationPolicy(Map.copyOf(copy)); - } - - /** - * Whether a caller may send a type. - * - * @param type the message type - * @param heldAuthorities what the caller holds right now - */ - public boolean permits(WebSocketMessageType type, Set heldAuthorities) { - Objects.requireNonNull(type, "type"); - Objects.requireNonNull(heldAuthorities, "heldAuthorities"); - Set required = requirements.get(type); - if (required == null) { - // Fail closed. A type nobody declared a requirement for is a type nobody thought about the - // permission for, and defaulting to allow ships the omission. - return false; - } - return heldAuthorities.containsAll(required); - } - - /** Whether a requirement is declared for a type at all. */ - public boolean declares(WebSocketMessageType type) { - return requirements.containsKey(type); - } - - /** - * The types that are published but have no declared requirement. - * - *

Read by the startup validator. Every one of them is currently unsendable, which is safe and - * is not what anybody intended — so the deployment is told rather than left to discover it from a - * client that cannot do anything. - */ - public java.util.List undeclaredAmong( - java.util.Collection publishedTypes) { - return publishedTypes.stream() - .filter(type -> !declares(type)) - .sorted(java.util.Comparator.comparing(WebSocketMessageType::value)) - .toList(); - } - - /** Every declared requirement. */ - public Map> requirements() { - return requirements; - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/budget/WebSocketConnectionBudget.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/budget/WebSocketConnectionBudget.java index 2cbcc45c..c25a52dd 100644 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/budget/WebSocketConnectionBudget.java +++ b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/budget/WebSocketConnectionBudget.java @@ -1,39 +1,25 @@ package dev.caskeleton.adapter.inbound.websocket.budget; -import java.time.Duration; -import java.util.Objects; - /** * What one connection is allowed to consume. * *

Every bound here exists because a WebSocket removes a limit that HTTP provided for free. An - * HTTP request has a finite body, one response, and a lifetime measured in seconds; a connection - * has none of those. Whatever the platform does not bound explicitly is unbounded. + * HTTP request has a finite body and one response; a connection has neither. Whatever the platform + * does not bound explicitly is unbounded. * *

{@code maxBufferedOutboundBytes} is the one that is easiest to omit and worst to lack. A slow * consumer does not fail — it simply reads more slowly than the server writes, and the difference * accumulates in the server's heap. One such client is invisible; a hundred is an OutOfMemoryError * with no failing request anywhere to point at. * - * @param maxFrameBytes the largest single frame accepted - * @param maxMessageBytes the largest reassembled message accepted - * @param maxFragments how many continuation frames one message may span - * @param maxInboundMessagesPerSecond the inbound message rate one connection may sustain + *

Only bounds the handler enforces are here. Idle timeout and frame size belong to the servlet + * container ({@code ServletServerContainerFactoryBean}); the servlet API never shows the + * application a frame. + * + * @param maxMessageBytes the largest inbound text message accepted, in UTF-8 bytes * @param maxBufferedOutboundBytes how much unsent outbound data may accumulate per connection - * @param maxConnectionAge how long any connection may live - * @param idleTimeout how long a silent connection is kept */ -public record WebSocketConnectionBudget( - int maxFrameBytes, - int maxMessageBytes, - int maxFragments, - int maxInboundMessagesPerSecond, - long maxBufferedOutboundBytes, - Duration maxConnectionAge, - Duration idleTimeout) { - - /** The largest frame any profile may accept, whatever an endpoint asks for. */ - public static final int ABSOLUTE_FRAME_MAX = 1024 * 1024; +public record WebSocketConnectionBudget(int maxMessageBytes, long maxBufferedOutboundBytes) { /** The largest reassembled message any profile may accept. */ public static final int ABSOLUTE_MESSAGE_MAX = 8 * 1024 * 1024; @@ -42,19 +28,13 @@ public record WebSocketConnectionBudget( public static final long ABSOLUTE_BUFFERED_OUTBOUND_MAX = 4L * 1024 * 1024; public WebSocketConnectionBudget { - Objects.requireNonNull(maxConnectionAge, "maxConnectionAge"); - Objects.requireNonNull(idleTimeout, "idleTimeout"); - requirePositive(maxFrameBytes, "maxFrameBytes"); - requirePositive(maxMessageBytes, "maxMessageBytes"); - requirePositive(maxFragments, "maxFragments"); - requirePositive(maxInboundMessagesPerSecond, "maxInboundMessagesPerSecond"); + if (maxMessageBytes <= 0) { + throw new IllegalArgumentException( + "maxMessageBytes must be positive, was " + maxMessageBytes); + } if (maxBufferedOutboundBytes <= 0) { throw new IllegalArgumentException("maxBufferedOutboundBytes must be positive"); } - if (maxFrameBytes > ABSOLUTE_FRAME_MAX) { - throw new IllegalArgumentException( - "maxFrameBytes exceeds the platform ceiling of " + ABSOLUTE_FRAME_MAX); - } if (maxMessageBytes > ABSOLUTE_MESSAGE_MAX) { throw new IllegalArgumentException( "maxMessageBytes exceeds the platform ceiling of " + ABSOLUTE_MESSAGE_MAX); @@ -65,39 +45,5 @@ public record WebSocketConnectionBudget( + ABSOLUTE_BUFFERED_OUTBOUND_MAX + "; a per-connection buffer multiplied by the connection count is the heap"); } - if (maxMessageBytes < maxFrameBytes) { - // A message bound below the frame bound admits a frame it must then reject on reassembly, - // which spends the memory the frame bound was supposed to save. - throw new IllegalArgumentException( - "maxMessageBytes below maxFrameBytes accepts a frame it will then refuse"); - } - if ((long) maxFrameBytes * maxFragments < maxMessageBytes) { - // The three bounds have to be able to describe the same message, or the largest message the - // profile claims to accept cannot actually arrive. - throw new IllegalArgumentException( - "maxFrameBytes x maxFragments cannot carry maxMessageBytes, so the largest message this" - + " profile claims to accept can never be delivered"); - } - if (maxConnectionAge.isZero() || maxConnectionAge.isNegative()) { - throw new IllegalArgumentException("a connection with no maximum age is unbounded"); - } - if (idleTimeout.isZero() || idleTimeout.isNegative()) { - throw new IllegalArgumentException("a connection with no idle timeout is never reclaimed"); - } - if (idleTimeout.compareTo(maxConnectionAge) > 0) { - throw new IllegalArgumentException("an idle timeout beyond the maximum age never fires"); - } - } - - /** The platform default: modest frames, a short idle window, a four-hour ceiling. */ - public static WebSocketConnectionBudget standard() { - return new WebSocketConnectionBudget( - 64 * 1024, 512 * 1024, 16, 100, 1024L * 1024, Duration.ofHours(4), Duration.ofSeconds(90)); - } - - private static void requirePositive(int value, String name) { - if (value <= 0) { - throw new IllegalArgumentException(name + " must be positive, was " + value); - } } } diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/codec/StrictWebSocketJsonCodec.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/codec/StrictWebSocketJsonCodec.java deleted file mode 100644 index 67c8e322..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/codec/StrictWebSocketJsonCodec.java +++ /dev/null @@ -1,145 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.codec; - -import dev.caskeleton.adapter.inbound.websocket.budget.WebSocketConnectionBudget; -import dev.caskeleton.adapter.inbound.websocket.error.WebSocketFailureCategory; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageCatalog; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageDescriptor; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageFamily; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageType; -import java.util.Objects; -import tools.jackson.core.StreamReadConstraints; -import tools.jackson.core.StreamReadFeature; -import tools.jackson.core.json.JsonFactory; -import tools.jackson.databind.DeserializationFeature; -import tools.jackson.databind.MapperFeature; -import tools.jackson.databind.json.JsonMapper; - -/** - * Decodes a wire payload into a declared record, and refuses everything else. - * - *

Strict in the specific ways that matter for a socket rather than a request. Two of them are - * not defaults anywhere: - * - *

    - *
  • Duplicate keys are rejected. Every JSON parser accepts them and silently keeps one — - * usually the last. A document carrying {@code "amount"} twice therefore means different - * things to a validating proxy and to this server, which is how a request passes review at - * one layer and executes as something else at the next. - *
  • Depth and length are bounded before parsing. A deeply nested document costs stack - * and heap during parse, so a bound applied after parsing has already paid for the attack. - *
- * - *

Default typing is never enabled and there is no code here that could enable it. Polymorphic - * type resolution from a wire document is the mechanism behind essentially every Java - * deserialization CVE; the manifest is what this codec resolves against instead. - */ -public final class StrictWebSocketJsonCodec { - - private final JsonMapper mapper; - private final WebSocketMessageCatalog catalog; - private final WebSocketWireTypeManifest manifest; - - /** - * A codec over one catalog and manifest. - * - * @param catalog which types are published - * @param manifest which classes they decode to - * @param budget the bounds applied before parsing - */ - public StrictWebSocketJsonCodec( - WebSocketMessageCatalog catalog, - WebSocketWireTypeManifest manifest, - WebSocketConnectionBudget budget) { - this.catalog = Objects.requireNonNull(catalog, "catalog"); - this.manifest = Objects.requireNonNull(manifest, "manifest"); - Objects.requireNonNull(budget, "budget"); - this.mapper = - JsonMapper.builder( - JsonFactory.builder() - .streamReadConstraints( - StreamReadConstraints.builder() - // Depth costs stack during parse, so it is bounded before parsing - // rather than measured after. - .maxNestingDepth(32) - .maxDocumentLength(budget.maxMessageBytes()) - .maxStringLength(budget.maxMessageBytes()) - .maxNumberLength(64) - .build()) - // Not a default in any parser, and the one that matters most here: a duplicate - // key is accepted everywhere and silently resolved to one value, so the same - // document means different things to a proxy and to this server. - .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) - .build()) - .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true) - .configure(DeserializationFeature.FAIL_ON_TRAILING_TOKENS, true) - .configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, true) - .configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, false) - .configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS, false) - .disable(DeserializationFeature.ACCEPT_FLOAT_AS_INT) - .build(); - } - - /** - * Decodes one inbound payload. - * - * @param type the published type the envelope named - * @param family the family the envelope claimed - * @param payload the encoded document - * @throws WebSocketDecodeException when anything about it is not exactly right - */ - public Object decodeFromClient( - WebSocketMessageType type, WebSocketMessageFamily family, String payload) { - Objects.requireNonNull(type, "type"); - Objects.requireNonNull(family, "family"); - Objects.requireNonNull(payload, "payload"); - - // Catalog first, parser second. Deciding whether a type is admissible before handing bytes to - // a parser is what keeps an unpublished type from reaching one at all. - WebSocketMessageDescriptor descriptor = - catalog - .admitFromClient(type, family) - .orElseThrow( - () -> - new WebSocketDecodeException( - WebSocketFailureCategory.UNKNOWN_TYPE, - "this endpoint does not accept " + type + " from a client")); - - Class target = - manifest - .targetFor(descriptor.type()) - .orElseThrow( - () -> - new WebSocketDecodeException( - WebSocketFailureCategory.INTERNAL, - "the catalog publishes " - + type - + " but the manifest binds no class to it")); - - try { - return mapper.readValue(payload, target); - } catch (RuntimeException malformed) { - // The parser's message names the class, the field and often the offending content. None of - // that goes to the peer: the category is what a client can act on, and the detail stays in - // the server's own logs. - throw new WebSocketDecodeException( - WebSocketFailureCategory.MALFORMED, "the payload is not a valid " + type + " document"); - } - } - - /** - * Encodes an outbound payload. - * - * @param type the published type - * @param value the document to send - */ - public String encodeToClient(WebSocketMessageType type, Object value) { - Objects.requireNonNull(type, "type"); - Objects.requireNonNull(value, "value"); - if (!catalog.acceptsFromServer(type)) { - throw new WebSocketDecodeException( - WebSocketFailureCategory.INTERNAL, - "the server may not send " + type + "; it is not published in that direction"); - } - return mapper.writeValueAsString(value); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/codec/WebSocketDecodeException.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/codec/WebSocketDecodeException.java deleted file mode 100644 index 8dc8b0a8..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/codec/WebSocketDecodeException.java +++ /dev/null @@ -1,34 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.codec; - -import dev.caskeleton.adapter.inbound.websocket.error.WebSocketFailureCategory; -import java.util.Objects; - -/** - * A payload that could not be turned into a declared type. - * - *

Carries the category rather than the parser's own message. What a parser says names the class, - * the field and frequently the offending content — useful in a server log and a disclosure on a - * connection the peer holds for hours. - */ -public final class WebSocketDecodeException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - private final transient WebSocketFailureCategory category; - - /** - * A decode failure. - * - * @param category what a client can act on - * @param publishableDetail a message already safe to send - */ - public WebSocketDecodeException(WebSocketFailureCategory category, String publishableDetail) { - super(Objects.requireNonNull(publishableDetail, "publishableDetail")); - this.category = Objects.requireNonNull(category, "category"); - } - - /** What kind of failure this is. */ - public WebSocketFailureCategory category() { - return category; - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/codec/WebSocketWireTypeManifest.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/codec/WebSocketWireTypeManifest.java deleted file mode 100644 index 67d87c27..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/codec/WebSocketWireTypeManifest.java +++ /dev/null @@ -1,61 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.codec; - -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageType; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -/** - * The only Java types this deployment will ever deserialize from a wire message. - * - *

An explicit map from published name to class, and the deciding property is that the class - * never comes from the wire. Every deserialization vulnerability of the last decade has the same - * shape: a document names a type, the receiver resolves it, and the resolution reaches something - * with a side effect in its constructor or its setter. A receiver that can only produce classes - * from this map cannot be steered anywhere its author did not put. - * - *

Fixed at startup for the same reason the catalog is. A manifest that could gain an entry at - * runtime is a manifest that does not answer "what can this deployment be made to instantiate". - */ -public final class WebSocketWireTypeManifest { - - private final Map> byType; - - private WebSocketWireTypeManifest(Map> byType) { - this.byType = byType; - } - - /** A manifest over the declared bindings. */ - public static WebSocketWireTypeManifest of(Map> bindings) { - Objects.requireNonNull(bindings, "bindings"); - Map> copy = new LinkedHashMap<>(); - bindings.forEach( - (type, target) -> { - Objects.requireNonNull(type, "type"); - Objects.requireNonNull(target, "target"); - if (!target.isRecord()) { - // Records only. A record has no setters, no no-arg constructor and no mutable state, - // so the whole class of gadgets that runs code during population does not apply — and - // its components are the schema rather than a subset of it. - throw new IllegalArgumentException( - target.getName() - + " is not a record. Wire types are records because a record cannot run" - + " arbitrary code while being populated, which is the mechanism every" - + " deserialization gadget depends on"); - } - copy.put(type, target); - }); - return new WebSocketWireTypeManifest(Map.copyOf(copy)); - } - - /** The class a published type decodes to, if it is bound. */ - public Optional> targetFor(WebSocketMessageType type) { - return Optional.ofNullable(byType.get(type)); - } - - /** Every binding. */ - public Map> bindings() { - return byType; - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/config/WebSocketPlatformSafetyConfiguration.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/config/WebSocketPlatformSafetyConfiguration.java deleted file mode 100644 index 0d3487f6..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/config/WebSocketPlatformSafetyConfiguration.java +++ /dev/null @@ -1,95 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.config; - -import dev.caskeleton.adapter.inbound.websocket.authz.MessageAuthorizationPolicy; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketEndpointCatalog; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketStackProfile; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageCatalog; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketProtocolProfile; -import dev.caskeleton.adapter.inbound.websocket.security.WebSocketAuthenticationProfile; -import dev.caskeleton.adapter.inbound.websocket.security.WebSocketOriginPolicy; -import java.util.Set; -import org.springframework.beans.factory.InitializingBean; -import org.springframework.beans.factory.ObjectProvider; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.Environment; - -/** - * Connects the WebSocket fail-closed policy objects to the actual Spring startup lifecycle. - * - *

The policy classes are useful only if the composition root cannot bypass them. This - * configuration deliberately performs the checks during context startup: an incoherent transport - * either starts with every required contract in place or does not start at all. - */ -@Configuration(proxyBeanMethods = false) -public class WebSocketPlatformSafetyConfiguration { - - @Bean - InitializingBean webSocketPlatformSafetyGuards( - Environment environment, - ObjectProvider endpoints, - ObjectProvider messages, - ObjectProvider authorization, - ObjectProvider origins, - ObjectProvider authentication, - ObjectProvider protocol) { - return () -> { - if (!enabled(environment, "app.websocket.platform.enabled")) { - return; - } - - WebSocketEndpointCatalog endpointCatalog = - require(endpoints, "WebSocketEndpointCatalog", "app.websocket.platform.enabled"); - WebSocketMessageCatalog messageCatalog = - require(messages, "WebSocketMessageCatalog", "app.websocket.platform.enabled"); - MessageAuthorizationPolicy authorizationPolicy = - require(authorization, "MessageAuthorizationPolicy", "app.websocket.platform.enabled"); - WebSocketOriginPolicy originPolicy = - require(origins, "WebSocketOriginPolicy", "app.websocket.platform.enabled"); - WebSocketAuthenticationProfile authenticationProfile = - require( - authentication, "WebSocketAuthenticationProfile", "app.websocket.platform.enabled"); - WebSocketProtocolProfile protocolProfile = - require(protocol, "WebSocketProtocolProfile", "app.websocket.platform.enabled"); - - Set stacks = - endpointCatalog.all().stream() - .map(profile -> profile.stack()) - .collect(java.util.stream.Collectors.toUnmodifiableSet()); - if (stacks.size() == 1) { - WebSocketStackExclusivity.require(stacks.iterator().next()); - } - - new WebSocketPlatformStartupValidator(production(environment)) - .validate( - endpointCatalog, - messageCatalog, - authorizationPolicy, - originPolicy, - authenticationProfile, - protocolProfile); - }; - } - - private static boolean enabled(Environment environment, String key) { - return environment.getProperty(key, Boolean.class, false); - } - - private static boolean production(Environment environment) { - for (String profile : environment.getActiveProfiles()) { - if ("prod".equals(profile) || "production".equals(profile)) { - return true; - } - } - return false; - } - - private static T require(ObjectProvider provider, String type, String feature) { - T value = provider.getIfAvailable(); - if (value == null) { - throw new IllegalStateException( - feature + " requires a " + type + " bean from the composition root"); - } - return value; - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/config/WebSocketPlatformSettings.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/config/WebSocketPlatformSettings.java deleted file mode 100644 index 890c1ea1..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/config/WebSocketPlatformSettings.java +++ /dev/null @@ -1,60 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.config; - -import java.time.Duration; -import java.util.Set; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.boot.context.properties.bind.DefaultValue; - -/** - * The WebSocket platform's bound configuration. - * - *

Every default here is the safe one, and where there is no safe default there is no default. - * {@code allowedOrigins} is empty and {@code enabled} is false: a deployment that has not said - * which origins may connect has not configured a WebSocket endpoint, and starting one anyway would - * mean the platform chose its own CSRF posture. - * - *

Bounds are here rather than in code so a deployment can lower them, and the validator refuses - * anything that raises them past the platform ceiling. Configuration may make a deployment more - * careful than the default; it may not make it less careful than the platform allows. - * - * @param enabled whether the platform serves any endpoint - * @param nodeId this node's identity, used as a metric tag and in admin listings - * @param allowedOrigins which origins may open a connection - * @param allowMissingOrigin whether a client sending no Origin is admitted - * @param maxFrameBytes the largest frame accepted - * @param maxMessageBytes the largest reassembled message accepted - * @param maxFragments how many frames one message may span - * @param maxBufferedOutboundBytesPerConnection how much unsent data one connection may hold - * @param maxBufferedOutboundBytesPerNode how much this node may hold across all connections - * @param maxConnectionsPerActor how many connections one caller may hold here - * @param pingInterval how often a connection is checked - * @param idleTimeout how long silence is tolerated - * @param maxConnectionAge how long any connection may live - * @param ticketLifetime how long a connection ticket is valid - */ -@ConfigurationProperties(prefix = "app.websocket.platform") -public record WebSocketPlatformSettings( - @DefaultValue("false") boolean enabled, - @DefaultValue("local") String nodeId, - @DefaultValue({}) Set allowedOrigins, - @DefaultValue("false") boolean allowMissingOrigin, - @DefaultValue("65536") int maxFrameBytes, - @DefaultValue("524288") int maxMessageBytes, - @DefaultValue("16") int maxFragments, - @DefaultValue("1048576") long maxBufferedOutboundBytesPerConnection, - @DefaultValue("67108864") long maxBufferedOutboundBytesPerNode, - @DefaultValue("4") int maxConnectionsPerActor, - @DefaultValue("15s") Duration pingInterval, - @DefaultValue("45s") Duration idleTimeout, - @DefaultValue("4h") Duration maxConnectionAge, - @DefaultValue("30s") Duration ticketLifetime) { - - public WebSocketPlatformSettings { - allowedOrigins = Set.copyOf(allowedOrigins); - } - - /** Whether this configuration names any origin at all. */ - public boolean hasOriginAllowlist() { - return !allowedOrigins.isEmpty(); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/config/WebSocketPlatformStartupValidator.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/config/WebSocketPlatformStartupValidator.java deleted file mode 100644 index 1e78a1fc..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/config/WebSocketPlatformStartupValidator.java +++ /dev/null @@ -1,125 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.config; - -import dev.caskeleton.adapter.inbound.websocket.authz.MessageAuthorizationPolicy; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketEndpointCatalog; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketEndpointProfile; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageCatalog; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageDescriptor; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageType; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketProtocolProfile; -import dev.caskeleton.adapter.inbound.websocket.security.WebSocketAuthenticationProfile; -import dev.caskeleton.adapter.inbound.websocket.security.WebSocketOriginPolicy; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; - -/** - * Refuses to start a deployment whose WebSocket configuration is unsafe or incoherent. - * - *

Every check here catches something that works perfectly in development and is wrong in - * production. That is the whole category: a cookie endpoint with no origin allowlist serves every - * same-origin test correctly, an unnegotiated-fallback profile connects fine until the message - * format changes, and an endpoint with no authorization requirement simply refuses everything — - * quietly, and only for the clients that try to use it. - * - *

Fail-closed, because a warning is read by nobody. The deployment starts, the dashboards are - * green, and the line scrolls past in the first thirty seconds of a log nobody keeps. - */ -public final class WebSocketPlatformStartupValidator { - - private final boolean productionProfile; - - /** - * A validator for one deployment. - * - * @param productionProfile whether this deployment is production; the local profile is allowed - * the fallbacks that production is not - */ - public WebSocketPlatformStartupValidator(boolean productionProfile) { - this.productionProfile = productionProfile; - } - - /** - * Refuses an unsafe configuration. - * - * @param endpoints the declared endpoints - * @param messages the published message catalog - * @param authorization what each type requires - * @param originPolicy which origins may connect - * @param authenticationProfile how callers authenticate - * @param protocolProfile which subprotocols are spoken - * @throws IllegalStateException naming every problem at once - */ - public void validate( - WebSocketEndpointCatalog endpoints, - WebSocketMessageCatalog messages, - MessageAuthorizationPolicy authorization, - WebSocketOriginPolicy originPolicy, - WebSocketAuthenticationProfile authenticationProfile, - WebSocketProtocolProfile protocolProfile) { - Objects.requireNonNull(endpoints, "endpoints"); - Objects.requireNonNull(messages, "messages"); - Objects.requireNonNull(authorization, "authorization"); - Objects.requireNonNull(originPolicy, "originPolicy"); - Objects.requireNonNull(authenticationProfile, "authenticationProfile"); - Objects.requireNonNull(protocolProfile, "protocolProfile"); - - List problems = new ArrayList<>(); - - if (!endpoints.singleStack()) { - // Boot deduces one application type from the classpath, so a catalog spanning both runtimes - // means one set of endpoints is never served and nothing says so. - problems.add( - "endpoints are declared on both runtimes; only one can be served, and the other's" - + " endpoints would silently never answer"); - } - - if (!originPolicy.safeFor(authenticationProfile)) { - // The same-origin policy does not protect a WebSocket handshake and there is no preflight. - // The server's own Origin check is the entire CSRF defence. - problems.add( - "the " - + authenticationProfile - + " profile needs an exact origin allowlist and must refuse a missing origin; a" - + " WebSocket handshake is not protected by the same-origin policy and has no" - + " preflight, so this check is the whole defence"); - } - - if (productionProfile && !protocolProfile.productionReady()) { - problems.add( - "the protocol profile accepts a client that negotiates no subprotocol; both ends then" - + " assume their own current format and find out when it changes"); - } - - if (productionProfile) { - List unsafe = endpoints.productionUnsafe(); - if (!unsafe.isEmpty()) { - problems.add( - "these endpoints require no authentication: " - + unsafe.stream().map(profile -> profile.name().value()).toList() - + "; a WebSocket is a long-lived resource, so an unauthenticated one is an" - + " unauthenticated caller holding server memory for hours"); - } - } - - List undeclared = - authorization.undeclaredAmong( - messages.all().stream().map(WebSocketMessageDescriptor::type).toList()); - if (!undeclared.isEmpty()) { - // Refusing them is safe and is not what anybody intended. Without this the deployment learns - // it from a client that cannot do anything. - problems.add( - "these published message types have no authorization requirement and are therefore" - + " unsendable: " - + undeclared.stream().map(WebSocketMessageType::value).toList()); - } - - if (!problems.isEmpty()) { - // Every problem at once. Reporting the first sends an operator through one restart per - // problem, and each restart is a deploy. - throw new IllegalStateException( - "the WebSocket platform configuration is unsafe:\n - " - + String.join("\n - ", problems)); - } - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/config/WebSocketStackExclusivity.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/config/WebSocketStackExclusivity.java deleted file mode 100644 index de4ed6c5..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/config/WebSocketStackExclusivity.java +++ /dev/null @@ -1,78 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.config; - -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketStackProfile; -import java.util.Optional; - -/** - * Which runtime this deployment can actually serve, decided from the classpath rather than asked. - * - *

Spring Boot deduces one application type from what is present, and the deduction is not - * negotiable: with both a servlet container and Reactor Netty available it starts the servlet one. - * A deployment that declared reactive endpoints and shipped both therefore starts, reports itself - * healthy, and serves none of them — no error, no warning, and the endpoints simply never answer. - * - *

Detecting it here means the mismatch is a startup failure with a sentence explaining it, - * rather than a support ticket that says "the WebSocket does not connect". - */ -public final class WebSocketStackExclusivity { - - private static final String SERVLET_MARKER = "jakarta.servlet.Servlet"; - private static final String REACTIVE_MARKER = - "org.springframework.web.reactive.socket.server.WebSocketService"; - - private WebSocketStackExclusivity() {} - - /** Which runtime the classpath will actually produce, or empty when neither is present. */ - public static Optional resolvedStack() { - boolean servlet = present(SERVLET_MARKER); - boolean reactive = present(REACTIVE_MARKER); - if (servlet) { - // Servlet wins whenever both are present, because that is what Boot's own deduction does. - // Reporting the reactive stack here would be a second, disagreeing deduction. - return Optional.of(WebSocketStackProfile.SERVLET); - } - return reactive ? Optional.of(WebSocketStackProfile.REACTIVE) : Optional.empty(); - } - - /** Whether both runtimes are on the classpath. */ - public static boolean bothPresent() { - return present(SERVLET_MARKER) && present(REACTIVE_MARKER); - } - - /** - * Refuses a deployment whose declared stack is not the one it can serve. - * - * @param declared what the endpoints say they need - * @throws IllegalStateException when the classpath cannot serve it - */ - public static void require(WebSocketStackProfile declared) { - Optional resolved = resolvedStack(); - if (resolved.isEmpty()) { - throw new IllegalStateException( - "no WebSocket runtime is on the classpath; the declared " - + declared - + " endpoints would never answer"); - } - if (resolved.get() != declared) { - throw new IllegalStateException( - "the endpoints declare " - + declared - + " but the classpath resolves to " - + resolved.get() - + (bothPresent() - ? ". Both runtimes are present, and Spring Boot deduces one application type" - + " from the classpath — so the declared endpoints would never answer while" - + " the deployment reported itself healthy. Remove the unused starter." - : ". Add the runtime the endpoints need, or change what they declare.")); - } - } - - private static boolean present(String className) { - try { - Class.forName(className, false, WebSocketStackExclusivity.class.getClassLoader()); - return true; - } catch (ClassNotFoundException absent) { - return false; - } - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/core/WebSocketActorReference.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/core/WebSocketActorReference.java deleted file mode 100644 index a8214cf2..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/core/WebSocketActorReference.java +++ /dev/null @@ -1,79 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.core; - -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.HexFormat; -import java.util.Objects; - -/** - * A stable, non-reversible stand-in for who is on the other end. - * - *

The connection context is read by the metrics recorder, the access log, the admin listing and - * anything that debugs a stuck connection. A raw subject or tenant in that record is a subject or - * tenant in all of those, and unlike a request log this one persists for the life of the - * connection. - * - *

A fingerprint keeps what those readers actually need — the ability to tell two connections - * apart and to recognise the same actor twice — and drops what they do not, which is who it is. - * Answering "which user is this" is the admin plane's job, through a lookup that is authorised and - * audited rather than through a field that is simply present. - * - * @param fingerprint a hex digest of the actor's identity under a deployment salt - */ -public record WebSocketActorReference(String fingerprint) { - - private static final int HEX_LENGTH = 64; - - public WebSocketActorReference { - Objects.requireNonNull(fingerprint, "fingerprint"); - if (fingerprint.length() != HEX_LENGTH - || !fingerprint.chars().allMatch(WebSocketActorReference::isHex)) { - throw new IllegalArgumentException("an actor reference is a 64-character hex digest"); - } - } - - /** - * Derives a reference from an identity. - * - * @param subject the authenticated subject - * @param tenantId the tenant, or null when the connection is not tenant scoped - * @param salt a per-deployment secret - */ - public static WebSocketActorReference of(String subject, String tenantId, byte[] salt) { - Objects.requireNonNull(subject, "subject"); - Objects.requireNonNull(salt, "salt"); - if (salt.length < 16) { - // Without a real salt the digest is a rainbow table away from the subject it was meant to - // hide, and subjects are drawn from small predictable sets — email addresses, user ids. - throw new IllegalArgumentException( - "an actor reference needs at least 16 bytes of salt; subjects come from small guessable" - + " sets and an unsalted digest of one is the subject"); - } - try { - MessageDigest digest = MessageDigest.getInstance("SHA-256"); - digest.update(salt); - digest.update((byte) 0x1f); - digest.update(subject.getBytes(StandardCharsets.UTF_8)); - digest.update((byte) 0x1f); - digest.update((tenantId == null ? "" : tenantId).getBytes(StandardCharsets.UTF_8)); - return new WebSocketActorReference(HexFormat.of().formatHex(digest.digest())); - } catch (NoSuchAlgorithmException impossible) { - throw new IllegalStateException("SHA-256 is required of every JVM", impossible); - } - } - - /** - * A short prefix, for a log line where the whole digest is noise. - * - *

Twelve characters: enough to tell connections apart while reading, short enough that it is - * obviously not the identity itself. - */ - public String shortForm() { - return fingerprint.substring(0, 12); - } - - private static boolean isHex(int character) { - return (character >= '0' && character <= '9') || (character >= 'a' && character <= 'f'); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/core/WebSocketConnectionContext.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/core/WebSocketConnectionContext.java deleted file mode 100644 index d77db75b..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/core/WebSocketConnectionContext.java +++ /dev/null @@ -1,97 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.core; - -import java.time.Instant; -import java.util.Objects; -import java.util.Optional; - -/** - * Everything the platform knows about one connection, and nothing the transport owns. - * - *

No {@code WebSocketSession}, no {@code ServerHttpRequest}, no channel. That absence is the - * design's rule and it earns its keep twice: the same context serves the servlet and reactive - * runtimes unchanged, and every decision made from it is testable without starting a server. - * - *

Immutable after OPEN, which the state machine enforces rather than documenting. A connection - * whose actor could change mid-life would make every authorization decision conditional on when it - * was asked — and the audit trail would record the last actor rather than the one who acted. - * - * @param connectionId this connection - * @param sessionId the logical session, which may span a reconnect - * @param nodeId which node holds it - * @param endpoint which endpoint it connected to - * @param subprotocol what was negotiated, or empty on an unnegotiated fallback - * @param actor a non-reversible reference to who is on the other end - * @param state where it is in its life - * @param credentialExpiry when its authorisation stops being valid - * @param openedAt when the handshake completed - */ -public record WebSocketConnectionContext( - WebSocketConnectionId connectionId, - WebSocketSessionId sessionId, - WebSocketNodeId nodeId, - WebSocketEndpointName endpoint, - Optional subprotocol, - WebSocketActorReference actor, - WebSocketConnectionState state, - WebSocketCredentialExpiry credentialExpiry, - Instant openedAt) { - - public WebSocketConnectionContext { - Objects.requireNonNull(connectionId, "connectionId"); - Objects.requireNonNull(sessionId, "sessionId"); - Objects.requireNonNull(nodeId, "nodeId"); - Objects.requireNonNull(endpoint, "endpoint"); - Objects.requireNonNull(subprotocol, "subprotocol"); - Objects.requireNonNull(actor, "actor"); - Objects.requireNonNull(state, "state"); - Objects.requireNonNull(credentialExpiry, "credentialExpiry"); - Objects.requireNonNull(openedAt, "openedAt"); - } - - /** - * The same connection in a new state. - * - * @throws IllegalStateException when the transition is not one the state machine allows - */ - public WebSocketConnectionContext transitionTo(WebSocketConnectionState next) { - if (!state.canTransitionTo(next)) { - throw new IllegalStateException( - "a connection cannot go from " - + state - + " to " - + next - + "; every allowed transition moves forward, and going back would let a node that" - + " announced it was draining quietly resume taking work"); - } - return new WebSocketConnectionContext( - connectionId, - sessionId, - nodeId, - endpoint, - subprotocol, - actor, - next, - credentialExpiry, - openedAt); - } - - /** - * Whether this connection has outlived a bound on its total age. - * - *

Separate from credential expiry, and both are needed. A never-expiring service credential - * still should not hold one connection open across three deploys: a maximum age is what forces a - * client back through the handshake, where the current policy is applied. - * - * @param maximumAge how long any connection may live - * @param now the current instant - */ - public boolean olderThan(java.time.Duration maximumAge, Instant now) { - Objects.requireNonNull(maximumAge, "maximumAge"); - return !now.isBefore(openedAt.plus(maximumAge)); - } - - /** Whether the platform may still write to this connection. */ - public boolean writable() { - return state.writable(); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/core/WebSocketConnectionState.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/core/WebSocketConnectionState.java deleted file mode 100644 index 53ec91d3..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/core/WebSocketConnectionState.java +++ /dev/null @@ -1,75 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.core; - -import java.util.Set; - -/** - * Where a connection is in its life. - * - *

Transitions are one-way and checked, because every state here corresponds to a different - * answer to "may I still write to this?". A platform that treats the question as a boolean writes - * to a draining connection, or refuses to write to one that is merely mid-handshake, and both look - * like flaky delivery from the client's side. - * - *

{@link #DRAINING} is the member that is easy to omit and expensive to lack. Without it a - * rolling restart has only "open" and "closed": either the connection keeps accepting new work - * until it is cut off mid-message, or it is closed abruptly and the client reconnects into the node - * that is also about to go away. - */ -public enum WebSocketConnectionState { - - /** The handshake is being admitted; nothing may be written yet. */ - CONNECTING, - - /** Established and negotiated. Reads and writes are allowed. */ - OPEN, - - /** - * Closing gracefully: no new inbound work is accepted, in-flight writes finish. - * - *

The state a rolling restart needs. Skipping it means choosing between cutting a message in - * half and letting a departing node keep taking work. - */ - DRAINING, - - /** A close frame has been sent or received; the handshake is unwinding. */ - CLOSING, - - /** Terminal. Nothing may be read or written. */ - CLOSED; - - /** Whether the platform may still write application messages. */ - public boolean writable() { - // DRAINING is writable on purpose: the whole point is that in-flight work finishes. - return this == OPEN || this == DRAINING; - } - - /** Whether new inbound application messages may still be accepted. */ - public boolean acceptsInbound() { - return this == OPEN; - } - - /** Whether no further transition is possible. */ - public boolean terminal() { - return this == CLOSED; - } - - /** - * Whether this state may become {@code next}. - * - *

Every allowed edge moves forward. A connection that could go back to OPEN from DRAINING - * would let a node that announced it was leaving quietly resume taking work, which is the one - * thing a drain has to prevent. - */ - public boolean canTransitionTo(WebSocketConnectionState next) { - if (next == null || next == this) { - return false; - } - return switch (this) { - case CONNECTING -> Set.of(OPEN, CLOSING, CLOSED).contains(next); - case OPEN -> Set.of(DRAINING, CLOSING, CLOSED).contains(next); - case DRAINING -> Set.of(CLOSING, CLOSED).contains(next); - case CLOSING -> next == CLOSED; - case CLOSED -> false; - }; - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/core/WebSocketCredentialExpiry.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/core/WebSocketCredentialExpiry.java deleted file mode 100644 index 30cec22a..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/core/WebSocketCredentialExpiry.java +++ /dev/null @@ -1,60 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.core; - -import java.time.Duration; -import java.time.Instant; -import java.util.Objects; -import java.util.Optional; - -/** - * When the credential that authorised this connection stops being valid. - * - *

The problem a long-lived connection has and a request does not. An HTTP request is - * authenticated and finished; a WebSocket is authenticated once and then runs for hours. Without an - * expiry the connection outlives the token, the revoked session, and the role change — and the - * caller keeps receiving data it is no longer entitled to, with nothing in any log to say so. - * - * @param expiresAt when the credential stops being valid, or empty when it does not expire - * @param graceBeforeClose how long after expiry the connection is given to re-authenticate - */ -public record WebSocketCredentialExpiry(Optional expiresAt, Duration graceBeforeClose) { - - public WebSocketCredentialExpiry { - Objects.requireNonNull(expiresAt, "expiresAt"); - Objects.requireNonNull(graceBeforeClose, "graceBeforeClose"); - if (graceBeforeClose.isNegative()) { - throw new IllegalArgumentException("a negative grace period is not a grace period"); - } - if (graceBeforeClose.compareTo(Duration.ofMinutes(5)) > 0) { - // A long grace is an expiry that does not expire. Five minutes is enough for a client to - // notice and re-authenticate; an hour is enough for a revoked session to stay live. - throw new IllegalArgumentException( - "a grace period over five minutes makes the expiry advisory: a revoked credential stays" - + " live for as long as the grace lasts"); - } - } - - /** A credential that never expires, for a service connection with a static credential. */ - public static WebSocketCredentialExpiry never() { - return new WebSocketCredentialExpiry(Optional.empty(), Duration.ZERO); - } - - /** - * A credential valid until an instant, with a grace period to re-authenticate. - * - * @param expiresAt when it stops being valid - * @param graceBeforeClose how long the connection may continue past that - */ - public static WebSocketCredentialExpiry at(Instant expiresAt, Duration graceBeforeClose) { - return new WebSocketCredentialExpiry(Optional.of(expiresAt), graceBeforeClose); - } - - /** Whether the credential has expired. */ - public boolean expiredAt(Instant now) { - return expiresAt.map(expiry -> !now.isBefore(expiry)).orElse(false); - } - - /** Whether the grace period has also elapsed, so the connection must be closed. */ - public boolean mustCloseAt(Instant now) { - return expiresAt.map(expiry -> !now.isBefore(expiry.plus(graceBeforeClose))).orElse(false); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/core/WebSocketEndpointCatalog.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/core/WebSocketEndpointCatalog.java deleted file mode 100644 index af509598..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/core/WebSocketEndpointCatalog.java +++ /dev/null @@ -1,111 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.core; - -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -/** - * Every endpoint this deployment serves, fixed at startup. - * - *

Sealed after construction on purpose. A registry that accepts a new endpoint at runtime means - * the set of things reachable from the internet is not knowable from the code, and the admin - * snapshot, the startup validator and the security review are each describing a moment rather than - * the deployment. - * - *

It also refuses two endpoints on the same path. Two handlers on one path is a coin flip - * decided by registration order, and the loser is silently unreachable — which looks exactly like a - * client bug. - */ -public final class WebSocketEndpointCatalog { - - private final Map byName; - private final Map byPath; - - private WebSocketEndpointCatalog( - Map byName, - Map byPath) { - this.byName = byName; - this.byPath = byPath; - } - - /** - * A catalog over the declared endpoints. - * - * @param profiles every endpoint this deployment serves - * @throws IllegalArgumentException when two endpoints share a name or a path - */ - public static WebSocketEndpointCatalog of(List profiles) { - Objects.requireNonNull(profiles, "profiles"); - Map byName = new LinkedHashMap<>(); - Map byPath = new LinkedHashMap<>(); - for (WebSocketEndpointProfile profile : profiles) { - if (byName.putIfAbsent(profile.name(), profile) != null) { - throw new IllegalArgumentException("two endpoints are named " + profile.name()); - } - WebSocketEndpointName previous = byPath.putIfAbsent(profile.path(), profile.name()); - if (previous != null) { - throw new IllegalArgumentException( - "endpoints " - + previous - + " and " - + profile.name() - + " both listen on " - + profile.path() - + "; which one answers would be decided by registration order and the other would" - + " be silently unreachable"); - } - } - return new WebSocketEndpointCatalog(Map.copyOf(byName), Map.copyOf(byPath)); - } - - /** The endpoint listening on a path, if any. */ - public Optional findByPath(String path) { - return Optional.ofNullable(byPath.get(path)).map(byName::get); - } - - /** The named endpoint, if declared. */ - public Optional find(WebSocketEndpointName name) { - return Optional.ofNullable(byName.get(name)); - } - - /** - * The named endpoint. - * - * @throws IllegalArgumentException when it is not declared - */ - public WebSocketEndpointProfile require(WebSocketEndpointName name) { - return find(name) - .orElseThrow( - () -> - new IllegalArgumentException( - "no endpoint named " + name + "; the declared set is " + byName.keySet())); - } - - /** Every declared endpoint. */ - public List all() { - return List.copyOf(byName.values()); - } - - /** - * The endpoints that are not safe to serve in production. - * - *

Returned rather than thrown, so the startup validator decides. A local profile legitimately - * serves an unauthenticated endpoint, and a catalog that refused to build would make the local - * case impossible rather than deliberate. - */ - public List productionUnsafe() { - return byName.values().stream().filter(profile -> !profile.productionSafe()).toList(); - } - - /** - * Whether every endpoint runs on one stack. - * - *

The two runtimes are mutually exclusive: Boot deduces one application type from the - * classpath, so a catalog spanning both means one set of endpoints is silently never served. - */ - public boolean singleStack() { - return byName.values().stream().map(WebSocketEndpointProfile::stack).distinct().count() <= 1; - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/core/WebSocketEndpointName.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/core/WebSocketEndpointName.java deleted file mode 100644 index 8e743096..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/core/WebSocketEndpointName.java +++ /dev/null @@ -1,31 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.core; - -import java.util.Objects; -import java.util.regex.Pattern; - -/** - * The name of a declared endpoint. - * - *

Bounded and lowercase, because this value reaches a metric tag, a log field and an admin - * listing. An endpoint set that grows with traffic is a cardinality problem; one that differs only - * by case is two entries in every dashboard for one endpoint. - * - * @param value the endpoint name - */ -public record WebSocketEndpointName(String value) { - - private static final Pattern GRAMMAR = Pattern.compile("[a-z][a-z0-9-]{1,63}"); - - public WebSocketEndpointName { - Objects.requireNonNull(value, "value"); - if (!GRAMMAR.matcher(value).matches()) { - throw new IllegalArgumentException( - "an endpoint name must match [a-z][a-z0-9-]{1,63}, was '" + value + "'"); - } - } - - @Override - public String toString() { - return value; - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/core/WebSocketEndpointProfile.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/core/WebSocketEndpointProfile.java deleted file mode 100644 index 2b80b376..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/core/WebSocketEndpointProfile.java +++ /dev/null @@ -1,70 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.core; - -import dev.caskeleton.adapter.inbound.websocket.budget.WebSocketConnectionBudget; -import java.util.Objects; -import java.util.regex.Pattern; - -/** - * One declared endpoint: where it listens, what it speaks, who may reach it, what it may consume. - * - *

A record rather than scattered configuration, so the incoherent combinations are refused at - * construction. The one worth naming is an endpoint that requires no authentication and still - * carries a real connection budget: a WebSocket is a long-lived resource, so an unauthenticated - * endpoint is an unauthenticated caller holding server memory for hours. - * - * @param name the endpoint's identity - * @param path the canonical absolute path it listens on - * @param stack which runtime serves it - * @param requiresAuthentication whether a handshake must be authenticated - * @param budget what one connection may consume - * @param maxConcurrentConnections how many connections this endpoint may hold at once - */ -public record WebSocketEndpointProfile( - WebSocketEndpointName name, - String path, - WebSocketStackProfile stack, - boolean requiresAuthentication, - WebSocketConnectionBudget budget, - int maxConcurrentConnections) { - - private static final Pattern CANONICAL_PATH = Pattern.compile("(/[A-Za-z0-9._~-]+)+"); - - public WebSocketEndpointProfile { - Objects.requireNonNull(name, "name"); - Objects.requireNonNull(path, "path"); - Objects.requireNonNull(stack, "stack"); - Objects.requireNonNull(budget, "budget"); - if (!CANONICAL_PATH.matcher(path).matches()) { - // Canonical, so the path that is matched is the path that was declared. A trailing slash, a - // dot segment or an encoded character makes the route that answers differ from the route - // anyone reviewed. - throw new IllegalArgumentException( - "an endpoint path must be canonical and absolute, was '" - + path - + "'; a trailing slash or a dot segment makes the route that answers differ from the" - + " one that was declared"); - } - if (path.contains("..")) { - throw new IllegalArgumentException("an endpoint path may not contain a dot segment"); - } - if (maxConcurrentConnections <= 0) { - // The design's rule, and it is about memory rather than tidiness: every connection holds - // buffers, and an endpoint with no cap is an endpoint whose memory use is set by whoever - // connects the most. - throw new IllegalArgumentException( - "every endpoint needs a positive connection cap; without one its memory use is decided" - + " by whoever connects the most"); - } - } - - /** - * Whether this endpoint is safe to serve in production. - * - *

Advisory, and read by the startup validator. An unauthenticated endpoint is not always wrong - * — a public status feed is a real thing — but it is never right by default, so it is something a - * deployment has to say out loud. - */ - public boolean productionSafe() { - return requiresAuthentication; - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/core/WebSocketNodeId.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/core/WebSocketNodeId.java deleted file mode 100644 index 4a7e9e81..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/core/WebSocketNodeId.java +++ /dev/null @@ -1,31 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.core; - -import java.util.Objects; -import java.util.regex.Pattern; - -/** - * Which node holds a connection. - * - *

Bounded and low-cardinality, unlike the connection and session identifiers, because a fleet - * has a knowable number of nodes. That is what makes this the one identifier here that is safe as a - * metric tag — and the reason it exists separately rather than being folded into the connection id. - * - * @param value the node identifier - */ -public record WebSocketNodeId(String value) { - - private static final Pattern GRAMMAR = Pattern.compile("[a-z0-9][a-z0-9._-]{0,63}"); - - public WebSocketNodeId { - Objects.requireNonNull(value, "value"); - if (!GRAMMAR.matcher(value).matches()) { - throw new IllegalArgumentException( - "a node id must match [a-z0-9][a-z0-9._-]{0,63}, was '" + value + "'"); - } - } - - @Override - public String toString() { - return value; - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/core/WebSocketSessionId.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/core/WebSocketSessionId.java deleted file mode 100644 index 968ea9d7..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/core/WebSocketSessionId.java +++ /dev/null @@ -1,35 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.core; - -import java.util.Objects; -import java.util.regex.Pattern; - -/** - * A logical session, which may outlive a single connection across a reconnect. - * - *

Opaque by construction. Distinct from the connection id precisely so that a reconnect can be - * recognised without reusing a transport identity. It still encodes nothing: a session id that - * embedded the actor would make every reconnect a disclosure. - * - *

It is also not a metric tag. One value per connection is unbounded by definition, and a tag - * that grows with traffic multiplies every series that carries it. - * - * @param value the identifier - */ -public record WebSocketSessionId(String value) { - - private static final Pattern GRAMMAR = Pattern.compile("[A-Za-z0-9_-]{8,64}"); - - public WebSocketSessionId { - Objects.requireNonNull(value, "value"); - if (!GRAMMAR.matcher(value).matches()) { - throw new IllegalArgumentException( - "a websocketsessionid must match [A-Za-z0-9_-]{8,64}; anything longer is unbounded and anything" - + " shorter is guessable"); - } - } - - @Override - public String toString() { - return value; - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/core/WebSocketStackProfile.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/core/WebSocketStackProfile.java deleted file mode 100644 index a9db035f..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/core/WebSocketStackProfile.java +++ /dev/null @@ -1,18 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.core; - -/** - * Which runtime serves an endpoint. - * - *

Declared per endpoint and validated at startup, because the two runtimes cannot coexist: Boot - * deduces one application type from the classpath, so a deployment carrying both starts one and - * silently serves none of the other's endpoints. Naming the stack is what lets the startup - * validator refuse that instead of discovering it when a client cannot connect. - */ -public enum WebSocketStackProfile { - - /** Servlet containers: Tomcat, Jetty. */ - SERVLET, - - /** Reactor Netty. */ - REACTIVE -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/core/WebSocketSubprotocolName.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/core/WebSocketSubprotocolName.java deleted file mode 100644 index 2b1f3d85..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/core/WebSocketSubprotocolName.java +++ /dev/null @@ -1,59 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.core; - -import java.util.Objects; -import java.util.regex.Pattern; - -/** - * A subprotocol token as it appears in {@code Sec-WebSocket-Protocol}. - * - *

Versioned in the token, which is the only place a WebSocket has to put it. HTTP has content - * negotiation and a URL to version; a WebSocket has one header exchanged once at handshake. A - * subprotocol without a version leaves both ends guessing whose idea of the message format is - * current, and the mismatch shows up as a decode failure on a connection that has been open for - * hours. - * - *

In {@code core} rather than {@code protocol}, which is where the design's module list puts it. - * The connection context has to name the negotiated token, and the context is core — so leaving - * this type in {@code protocol} made {@code core} depend on {@code protocol} while {@code protocol} - * already depended on {@code core}. The module boundary test refused the cycle, which is what it is - * for. - * - *

The split that survives is the useful one: the identifier and its grammar are core, and the - * negotiation policy — {@code WebSocketProtocolProfile} — stays in {@code protocol}. - * - * @param value the token - */ -public record WebSocketSubprotocolName(String value) { - - /** - * The grammar RFC 6455 allows: an HTTP token, and no comma because the header separates on it. - */ - private static final Pattern GRAMMAR = Pattern.compile("[A-Za-z0-9!#$%&'*+.^_`|~-]{1,64}"); - - private static final Pattern VERSIONED = Pattern.compile(".*\\.v[0-9]+(\\..+)?"); - - public WebSocketSubprotocolName { - Objects.requireNonNull(value, "value"); - if (!GRAMMAR.matcher(value).matches()) { - throw new IllegalArgumentException( - "a subprotocol token must be an HTTP token of at most 64 characters, was '" - + value - + "'"); - } - } - - /** The Stable production subprotocol. */ - public static WebSocketSubprotocolName stable() { - return new WebSocketSubprotocolName("ca-skeleton.realtime.v1.json"); - } - - /** Whether the token carries a version segment. */ - public boolean versioned() { - return VERSIONED.matcher(value).matches(); - } - - @Override - public String toString() { - return value; - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/error/WebSocketCloseCode.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/error/WebSocketCloseCode.java deleted file mode 100644 index 6e17d9b5..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/error/WebSocketCloseCode.java +++ /dev/null @@ -1,95 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.error; - -/** - * The close codes this platform sends, and what each one means to a client. - * - *

RFC 6455 reserves 1000–2999 and leaves 4000–4999 to the application. The distinction matters - * more than it looks: a browser surfaces the standard codes with its own wording and treats the - * private range as opaque, so a code chosen from the wrong range either says something the platform - * did not mean or says nothing at all. - * - *

1005 and 1006 are deliberately absent. They are codes a browser *reports* when no close frame - * arrived — sending them is not possible and is refused here rather than discovered at the - * transport layer. - */ -public enum WebSocketCloseCode { - - /** 1000: the purpose is fulfilled. */ - NORMAL(1000), - - /** 1001: the server is going away — a deploy, a drain. */ - GOING_AWAY(1001), - - /** 1008: a policy was violated in a way that cannot be tolerated. */ - POLICY_VIOLATION(1008), - - /** - * 1009: the message is too big to process. - * - *

Standard and specific, which is why the platform uses it rather than a private code. A - * browser tells the developer what happened without the client library knowing anything about - * this API. - */ - MESSAGE_TOO_BIG(1009), - - /** 1011: the server hit a condition it cannot recover from for this connection. */ - INTERNAL_ERROR(1011), - - /** - * 1013: try again later. - * - *

The standard "temporary overload" code, and the right first choice. A client library that - * knows nothing about this API still backs off, where a private code would be opaque to it. - */ - TRY_AGAIN_LATER(1013), - - /** 4401: the credential expired and was not renewed inside the grace period. */ - CREDENTIAL_EXPIRED(4401), - - /** 4403: the caller is no longer authorised for this connection. */ - NOT_AUTHORIZED(4403), - - /** 4408: the connection was idle past its timeout. */ - IDLE_TIMEOUT(4408), - - /** 4423: the connection outlived its maximum age and must re-handshake. */ - MAX_AGE_REACHED(4423), - - /** - * 4503: shed for capacity, with this deployment's own meaning. - * - *

Alongside 1013 rather than instead of it: 1013 is what a generic client understands, and - * 4503 is what this platform's own client uses to distinguish load shedding from a transient - * server condition. A deployment sends whichever the peer can act on. - */ - SHED_FOR_CAPACITY(4503); - - private final int code; - - WebSocketCloseCode(int code) { - this.code = code; - } - - /** The numeric code sent in the close frame. */ - public int code() { - return code; - } - - /** Whether this is a code the application range owns. */ - public boolean applicationRange() { - return code >= 4000 && code <= 4999; - } - - /** - * Whether a close frame may carry this code. - * - *

1005 and 1006 never can: they are what a peer reports when no close frame arrived, so - * sending them is a contradiction. - */ - public static boolean sendable(int code) { - if (code == 1005 || code == 1006 || code == 1015) { - return false; - } - return (code >= 1000 && code <= 1014) || (code >= 3000 && code <= 4999); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/error/WebSocketClosePolicy.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/error/WebSocketClosePolicy.java deleted file mode 100644 index 65d02af4..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/error/WebSocketClosePolicy.java +++ /dev/null @@ -1,73 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.error; - -import java.util.Objects; -import java.util.Optional; - -/** - * Whether a failure ends the connection, and with what code. - * - *

The decision lives here rather than at each throw site so the two stacks cannot answer it - * differently, and so the answer is reviewable as one table instead of scattered across handlers. - * - *

The rule it encodes: a failure caused by one message closes nothing, and a failure that - * invalidates the connection closes it. Getting that backwards in either direction is expensive — - * disconnecting for a malformed command produces a reconnect storm, because the client reconnects - * and sends the same bad message; not disconnecting on an expired credential leaves an unauthorised - * peer receiving data. - */ -public final class WebSocketClosePolicy { - - private WebSocketClosePolicy() {} - - /** - * The close code for a failure, or empty when the connection survives it. - * - * @param category what went wrong - */ - public static Optional closeCodeFor(WebSocketFailureCategory category) { - Objects.requireNonNull(category, "category"); - return switch (category) { - // Answered on the connection, never closed. The client's bug is in one message. - case MALFORMED, - UNKNOWN_TYPE, - VALIDATION_FAILED, - EXPIRED, - NOT_AUTHORIZED, - RATE_LIMITED, - INTERNAL -> - Optional.empty(); - // The connection itself is no longer authorised. Answering and continuing would leave an - // unauthorised peer subscribed. - case CREDENTIAL_EXPIRED -> Optional.of(WebSocketCloseCode.CREDENTIAL_EXPIRED); - // 1009 rather than a private code: a browser surfaces it with its own wording, so the - // developer learns what happened without the client library knowing this API. - case TOO_LARGE -> Optional.of(WebSocketCloseCode.MESSAGE_TOO_BIG); - case OVERLOADED -> Optional.of(WebSocketCloseCode.TRY_AGAIN_LATER); - }; - } - - /** - * Whether a failure is reported before the handshake completes. - * - *

Before 101 there is no WebSocket, so the answer is an HTTP status and a problem document — a - * close frame at that point is a frame on a connection that was never upgraded. After 101 there - * is no status line left to send, so the answer is a typed error message or a close frame. - * - *

This is the split that gets implemented wrong most often, and the symptom is a client that - * sees a connection open and immediately close with no explanation, because the server tried to - * send a 403 to a socket that had already been upgraded. - * - * @param category what went wrong - * @param handshakeCompleted whether the 101 has been sent - */ - public static WebSocketErrorTransport transportFor( - WebSocketFailureCategory category, boolean handshakeCompleted) { - Objects.requireNonNull(category, "category"); - if (!handshakeCompleted) { - return WebSocketErrorTransport.HTTP_PROBLEM; - } - return closeCodeFor(category).isPresent() - ? WebSocketErrorTransport.CLOSE_FRAME - : WebSocketErrorTransport.TYPED_ERROR_MESSAGE; - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/error/WebSocketErrorMessage.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/error/WebSocketErrorMessage.java deleted file mode 100644 index 75187813..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/error/WebSocketErrorMessage.java +++ /dev/null @@ -1,75 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.error; - -import java.util.Objects; -import java.util.Optional; - -/** - * A failure as the peer receives it. - * - *

The correlation is optional and its absence is meaningful: an error answering a command names - * it, and an unsolicited one — a credential expiring, a subscription being revoked — has nothing to - * name. A client with several requests in flight uses that to decide whether to fail one call or - * surface a connection-level problem. - * - *

The detail is written for a client and is not the exception's message. Whatever a decoder or a - * database threw describes the server's internals, and on a connection the peer holds for hours - * that text is retained far longer than a request's error body would be. - * - * @param category what went wrong - * @param detail a message already safe to publish - * @param correlationId the message this answers, when it answers one - * @param retryAfterMillis how long to wait before retrying, when retrying makes sense - */ -public record WebSocketErrorMessage( - WebSocketFailureCategory category, - String detail, - Optional correlationId, - Optional retryAfterMillis) { - - public WebSocketErrorMessage { - Objects.requireNonNull(category, "category"); - Objects.requireNonNull(detail, "detail"); - Objects.requireNonNull(correlationId, "correlationId"); - Objects.requireNonNull(retryAfterMillis, "retryAfterMillis"); - if (detail.isBlank()) { - throw new IllegalArgumentException("an error with no detail tells the client nothing"); - } - if (retryAfterMillis.isPresent() && !category.retryable()) { - // A retry hint on a permanent failure is an invitation to a loop that can only end the same - // way. - throw new IllegalArgumentException( - category + " is not retryable, so a retry hint would invite a loop that cannot succeed"); - } - retryAfterMillis.ifPresent( - millis -> { - if (millis <= 0) { - throw new IllegalArgumentException("a retry delay of " + millis + "ms is not a delay"); - } - }); - } - - /** An error answering a specific message. */ - public static WebSocketErrorMessage answering( - WebSocketFailureCategory category, String detail, String correlationId) { - return new WebSocketErrorMessage( - category, detail, Optional.of(correlationId), Optional.empty()); - } - - /** An error about the connection rather than about a message. */ - public static WebSocketErrorMessage unsolicited( - WebSocketFailureCategory category, String detail) { - return new WebSocketErrorMessage(category, detail, Optional.empty(), Optional.empty()); - } - - /** A retryable error with a delay. */ - public static WebSocketErrorMessage retryable( - WebSocketFailureCategory category, String detail, long retryAfterMillis) { - return new WebSocketErrorMessage( - category, detail, Optional.empty(), Optional.of(retryAfterMillis)); - } - - /** Whether the connection ends after this error. */ - public boolean fatal() { - return WebSocketClosePolicy.closeCodeFor(category).isPresent(); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/error/WebSocketErrorTransport.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/error/WebSocketErrorTransport.java deleted file mode 100644 index a29e6951..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/error/WebSocketErrorTransport.java +++ /dev/null @@ -1,21 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.error; - -/** - * How a failure reaches the peer. - * - *

Three ways, and which one applies is decided by whether the handshake completed rather than by - * how bad the failure is. Before the 101 the connection is still HTTP and there is a status line; - * after it there is neither, and code that tries to send a status anyway produces a client that - * sees a socket open and close immediately with nothing to explain it. - */ -public enum WebSocketErrorTransport { - - /** Before 101: an HTTP status with an RFC 9457 problem document. */ - HTTP_PROBLEM, - - /** After 101, connection survives: a typed error message on the connection. */ - TYPED_ERROR_MESSAGE, - - /** After 101, connection ends: a close frame with a code. */ - CLOSE_FRAME -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/error/WebSocketFailureCategory.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/error/WebSocketFailureCategory.java deleted file mode 100644 index 2fb66550..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/error/WebSocketFailureCategory.java +++ /dev/null @@ -1,59 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.error; - -/** - * What went wrong, in the terms a client can act on. - * - *

Separate from the close code because the two answer different questions. The close code says - * what happens to the connection; the category says what the client should do about the message. - * Most failures do not close anything — a single malformed command on an otherwise healthy - * connection should be answered, not disconnected — and a platform that only had close codes would - * have to tear down a connection to report a typo. - */ -public enum WebSocketFailureCategory { - - /** The frame or document could not be parsed. */ - MALFORMED, - - /** It parsed but names a type this deployment does not publish. */ - UNKNOWN_TYPE, - - /** It parsed and bound but violates a declared constraint. */ - VALIDATION_FAILED, - - /** The caller is not permitted to send this. */ - NOT_AUTHORIZED, - - /** The credential that authorised the connection has expired. */ - CREDENTIAL_EXPIRED, - - /** The message or frame exceeds a declared bound. */ - TOO_LARGE, - - /** The caller is sending faster than its allowance. */ - RATE_LIMITED, - - /** The server has no capacity right now. */ - OVERLOADED, - - /** A command arrived after its deadline. */ - EXPIRED, - - /** Something failed that the platform cannot describe further without leaking. */ - INTERNAL; - - /** - * Whether this failure ends the connection. - * - *

Most do not. A malformed command is the client's bug in one message; disconnecting for it - * turns a typo into a reconnect storm, because the client retries the connection and sends the - * same bad message again. - */ - public boolean fatal() { - return this == CREDENTIAL_EXPIRED || this == TOO_LARGE || this == OVERLOADED; - } - - /** Whether the client should try the same thing again later. */ - public boolean retryable() { - return this == RATE_LIMITED || this == OVERLOADED || this == INTERNAL; - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/evidence/WebSocketConnectionEvidence.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/evidence/WebSocketConnectionEvidence.java deleted file mode 100644 index 2e2eae7d..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/evidence/WebSocketConnectionEvidence.java +++ /dev/null @@ -1,67 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.evidence; - -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketConnectionId; -import dev.caskeleton.adapter.inbound.websocket.error.WebSocketCloseCode; -import java.time.Duration; -import java.time.Instant; -import java.util.Objects; -import java.util.Optional; - -/** - * What happened to one connection over its life. - * - *

The counters are the part that earns its place. A connection that closed normally after two - * hours and a connection that closed normally after two hours having dropped four thousand outbound - * messages look identical without them — and the second is a slow consumer that has been silently - * losing data the whole time. - * - * @param connectionId the connection - * @param openedAt when the handshake completed - * @param closedAt when it closed, if it has - * @param closeCode the code sent or received, if any - * @param inboundMessages how many inbound messages were admitted - * @param outboundMessages how many outbound messages were flushed - * @param droppedOutboundMessages how many were discarded because the peer could not keep up - * @param peakBufferedOutboundBytes the most unsent data held at once - */ -public record WebSocketConnectionEvidence( - WebSocketConnectionId connectionId, - Instant openedAt, - Optional closedAt, - Optional closeCode, - long inboundMessages, - long outboundMessages, - long droppedOutboundMessages, - long peakBufferedOutboundBytes) { - - public WebSocketConnectionEvidence { - Objects.requireNonNull(connectionId, "connectionId"); - Objects.requireNonNull(openedAt, "openedAt"); - Objects.requireNonNull(closedAt, "closedAt"); - Objects.requireNonNull(closeCode, "closeCode"); - if (closeCode.isPresent() && closedAt.isEmpty()) { - throw new IllegalArgumentException("a close code without a close time describes nothing"); - } - if (inboundMessages < 0 - || outboundMessages < 0 - || droppedOutboundMessages < 0 - || peakBufferedOutboundBytes < 0) { - throw new IllegalArgumentException("connection counters cannot be negative"); - } - } - - /** How long the connection was open, so far or in total. */ - public Duration lifetime(Instant now) { - return Duration.between(openedAt, closedAt.orElse(now)); - } - - /** - * Whether this connection lost outbound messages. - * - *

The signal a normal close hides. An operator reading close codes alone sees a clean - * disconnect; this is what says the peer was too slow and data was discarded to protect the node. - */ - public boolean lostMessages() { - return droppedOutboundMessages > 0; - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/evidence/WebSocketEvidenceSource.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/evidence/WebSocketEvidenceSource.java deleted file mode 100644 index 2888df0b..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/evidence/WebSocketEvidenceSource.java +++ /dev/null @@ -1,26 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.evidence; - -/** - * Who observed a stage. - * - *

Recorded because the answer changes what the evidence is worth. A stage the transport saw is a - * fact about bytes; one the application reported is a fact about state. Only the application can - * say its work committed, and evidence that does not name its source lets an inference be read - * later as an observation. - */ -public enum WebSocketEvidenceSource { - - /** The container told us: a frame arrived, a write completed. */ - TRANSPORT, - - /** The platform's own code observed it: decode succeeded, admission passed. */ - PLATFORM, - - /** - * The application reported it. - * - *

The only source permitted to claim {@code APPLICATION_COMMITTED}. Nothing outside the - * application knows whether its transaction committed. - */ - APPLICATION -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/evidence/WebSocketInboundEvidence.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/evidence/WebSocketInboundEvidence.java deleted file mode 100644 index 13db3725..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/evidence/WebSocketInboundEvidence.java +++ /dev/null @@ -1,121 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.evidence; - -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageId; -import java.time.Instant; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; -import java.util.Optional; - -/** - * What is actually known about one inbound message's progress. - * - *

Append-only and monotonic. The point is to be able to answer, after a crash or a lost - * connection, whether the work was durable — and an evidence record that could be rewritten or go - * backwards answers that with whatever was written last rather than with what happened. - * - *

{@code APPLICATION_COMMITTED} may only be recorded by the application. Nothing else knows. A - * handler returning normally means the method returned; it does not mean a transaction committed, - * and inferring one from the other is precisely how a retry re-executes a committed write. - */ -public final class WebSocketInboundEvidence { - - /** - * One observation. - * - * @param stage how far the message got - * @param source who observed it - * @param at when - */ - public record Observation( - WebSocketInboundStage stage, WebSocketEvidenceSource source, Instant at) { - - public Observation { - Objects.requireNonNull(stage, "stage"); - Objects.requireNonNull(source, "source"); - Objects.requireNonNull(at, "at"); - if (stage == WebSocketInboundStage.APPLICATION_COMMITTED - && source != WebSocketEvidenceSource.APPLICATION) { - // The rule the whole record exists for. Only the application knows whether its work is - // durable; anything else claiming it is an inference recorded as an observation. - throw new IllegalArgumentException( - "only the application may record APPLICATION_COMMITTED; " - + source - + " can observe that a handler returned, which is not the same thing"); - } - } - } - - private final WebSocketMessageId messageId; - private final List observations = new ArrayList<>(); - - /** - * Evidence for one message. - * - * @param messageId the message being tracked - */ - public WebSocketInboundEvidence(WebSocketMessageId messageId) { - this.messageId = Objects.requireNonNull(messageId, "messageId"); - } - - /** - * Records that a stage was reached. - * - * @throws IllegalStateException when the stage does not follow what is already recorded - */ - public synchronized WebSocketInboundEvidence record( - WebSocketInboundStage stage, WebSocketEvidenceSource source, Instant at) { - Observation observation = new Observation(stage, source, at); - WebSocketInboundStage latest = furthestStage().orElse(null); - if (!stage.mayFollow(latest)) { - throw new IllegalStateException( - "evidence for " - + messageId - + " already reached " - + latest - + "; recording " - + stage - + " would move it backwards, and evidence that can go backwards answers" - + " 'was this durable' with whatever was written last"); - } - observations.add(observation); - return this; - } - - /** The furthest stage reached. */ - public synchronized Optional furthestStage() { - return observations.stream() - .map(Observation::stage) - .max(java.util.Comparator.comparingInt(WebSocketInboundStage::rank)); - } - - /** - * Whether the message's work is known to be durable. - * - *

Known, not assumed. An unfinished message and a message whose handler returned without - * reporting a commit both answer false, because from the outside they are the same thing. - */ - public synchronized boolean durable() { - return furthestStage().map(WebSocketInboundStage::durable).orElse(false); - } - - /** - * Whether retrying this message is safe. - * - *

The question a reconnect has to answer. Safe exactly when nothing durable happened; anything - * else and the retry is a duplicate. - */ - public synchronized boolean safeToRetry() { - return !durable(); - } - - /** Every observation, in the order recorded. */ - public synchronized List observations() { - return List.copyOf(observations); - } - - /** The message being tracked. */ - public WebSocketMessageId messageId() { - return messageId; - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/evidence/WebSocketInboundStage.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/evidence/WebSocketInboundStage.java deleted file mode 100644 index cc2817e6..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/evidence/WebSocketInboundStage.java +++ /dev/null @@ -1,72 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.evidence; - -/** - * How far one inbound message actually got. - * - *

The distinction this exists for is {@link #APPLICATION_STARTED} versus {@link - * #APPLICATION_COMMITTED}. They are one step apart and mean opposite things when a connection dies - * between them: started-and-not-committed is safe to retry, and committed is not. A platform that - * records only "handled" cannot tell them apart, so after any crash every in-flight command is - * either retried — duplicating whatever committed — or abandoned, and there is no way to know which - * is correct. - * - *

The stages are ordered and progress is one-way, so evidence can be checked for coherence - * rather than trusted. - */ -public enum WebSocketInboundStage { - - /** The frame arrived. */ - FRAME_RECEIVED(1), - - /** Fragments were reassembled into a whole message. */ - MESSAGE_ASSEMBLED(2), - - /** The envelope parsed and its family rules held. */ - ENVELOPE_DECODED(3), - - /** The type is published and the caller may send it. */ - ADMITTED(4), - - /** The application was entered. Nothing durable has necessarily happened. */ - APPLICATION_STARTED(5), - - /** - * The application's work is durable. - * - *

Only ever recorded by the application itself, never inferred from the handler returning. A - * handler can return after a commit or after a rollback, and inferring from the return is how a - * retry re-executes a committed write. - */ - APPLICATION_COMMITTED(6), - - /** A response was handed to the outbound path. */ - RESPONSE_ENQUEUED(7); - - private final int rank; - - WebSocketInboundStage(int rank) { - this.rank = rank; - } - - /** - * Where this stage sits in the sequence. - * - *

Declared rather than taken from {@code ordinal()}. Declaration order is a source-file - * accident: inserting a stage in the middle silently renumbers every stage after it, and - * comparisons that were correct become wrong with no compile error and no test failure unless one - * happens to cover the pair that moved. - */ - public int rank() { - return rank; - } - - /** Whether this stage may follow {@code previous}. */ - public boolean mayFollow(WebSocketInboundStage previous) { - return previous == null || rank > previous.rank(); - } - - /** Whether reaching this stage means something durable happened. */ - public boolean durable() { - return rank >= APPLICATION_COMMITTED.rank(); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/evidence/WebSocketOutboundEvidence.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/evidence/WebSocketOutboundEvidence.java deleted file mode 100644 index f84c9c8d..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/evidence/WebSocketOutboundEvidence.java +++ /dev/null @@ -1,92 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.evidence; - -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageId; -import java.time.Instant; -import java.util.Objects; -import java.util.Optional; - -/** - * How far one outbound message actually got. - * - *

Four states rather than sent/not-sent, because the two useful distinctions both live in the - * middle. {@code WRITTEN_TO_TRANSPORT} means the platform handed the bytes over — it does not mean - * they left the machine, and on a slow consumer they may sit in a buffer for a long time. {@code - * FLUSHED} means the transport says they did. Neither means the peer received them: a WebSocket has - * no application-level acknowledgement, so "delivered" is not knowable here at all and this type - * does not pretend otherwise. - * - *

That is why {@link #acknowledged} exists separately and is only ever set from a message the - * peer sent back. Treating a successful flush as delivery is how an at-least-once guarantee quietly - * becomes at-most-once during a network partition. - * - * @param messageId the message being tracked - * @param stage how far it got - * @param queuedAt when it entered the outbound queue - * @param flushedAt when the transport reported it flushed - * @param acknowledged when the peer confirmed it, if the protocol asked for confirmation - */ -public record WebSocketOutboundEvidence( - WebSocketMessageId messageId, - WebSocketOutboundStage stage, - Instant queuedAt, - Optional flushedAt, - Optional acknowledged) { - - public WebSocketOutboundEvidence { - Objects.requireNonNull(messageId, "messageId"); - Objects.requireNonNull(stage, "stage"); - Objects.requireNonNull(queuedAt, "queuedAt"); - Objects.requireNonNull(flushedAt, "flushedAt"); - Objects.requireNonNull(acknowledged, "acknowledged"); - if (stage == WebSocketOutboundStage.FLUSHED && flushedAt.isEmpty()) { - throw new IllegalArgumentException("a flushed message must say when it was flushed"); - } - if (acknowledged.isPresent() && flushedAt.isEmpty()) { - // An acknowledgement for something never written means the two are being tracked - // independently, and the pair has stopped describing one message. - throw new IllegalArgumentException( - "a message acknowledged but never flushed means the peer confirmed something this node" - + " never sent"); - } - } - - /** A message that has just entered the queue. */ - public static WebSocketOutboundEvidence queued(WebSocketMessageId messageId, Instant at) { - return new WebSocketOutboundEvidence( - messageId, WebSocketOutboundStage.QUEUED, at, Optional.empty(), Optional.empty()); - } - - /** The same message, handed to the transport. */ - public WebSocketOutboundEvidence written() { - return new WebSocketOutboundEvidence( - messageId, WebSocketOutboundStage.WRITTEN_TO_TRANSPORT, queuedAt, flushedAt, acknowledged); - } - - /** The same message, reported flushed by the transport. */ - public WebSocketOutboundEvidence flushed(Instant at) { - return new WebSocketOutboundEvidence( - messageId, WebSocketOutboundStage.FLUSHED, queuedAt, Optional.of(at), acknowledged); - } - - /** The same message, confirmed by the peer. */ - public WebSocketOutboundEvidence acknowledgedAt(Instant at) { - return new WebSocketOutboundEvidence( - messageId, WebSocketOutboundStage.FLUSHED, queuedAt, flushedAt, Optional.of(at)); - } - - /** The same message, dropped because the connection could not take it. */ - public WebSocketOutboundEvidence dropped() { - return new WebSocketOutboundEvidence( - messageId, WebSocketOutboundStage.DROPPED, queuedAt, flushedAt, acknowledged); - } - - /** - * Whether the peer is known to have received this. - * - *

Only true with an acknowledgement. A flush says the bytes left this process, which is a - * different claim and the one that is tempting to substitute. - */ - public boolean knownReceived() { - return acknowledged.isPresent(); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/evidence/WebSocketOutboundStage.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/evidence/WebSocketOutboundStage.java deleted file mode 100644 index f8b1701e..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/evidence/WebSocketOutboundStage.java +++ /dev/null @@ -1,29 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.evidence; - -/** - * How far an outbound message got. - * - *

Note what is absent: there is no {@code DELIVERED}. A WebSocket gives the sender no - * application-level acknowledgement, so delivery is not observable from this side, and a stage - * named for it would be a claim the transport cannot support. - */ -public enum WebSocketOutboundStage { - - /** In the per-connection queue, not yet handed to the transport. */ - QUEUED, - - /** Handed to the transport. Possibly still sitting in a buffer. */ - WRITTEN_TO_TRANSPORT, - - /** The transport reports the bytes left this process. */ - FLUSHED, - - /** - * Discarded without being sent. - * - *

Recorded rather than silent, because a dropped message is the outcome an operator most needs - * to see: it means a consumer was too slow and the platform chose the connection's health over - * that message. - */ - DROPPED -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/handler/LateResponseTombstone.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/handler/LateResponseTombstone.java deleted file mode 100644 index 9fe24d08..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/handler/LateResponseTombstone.java +++ /dev/null @@ -1,108 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.handler; - -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketConnectionId; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketCorrelationId; -import java.time.Duration; -import java.time.Instant; -import java.util.Map; -import java.util.Objects; -import java.util.concurrent.ConcurrentHashMap; - -/** - * Remembers correlation ids that have already timed out, so a late answer is recognised rather than - * re-attached. - * - *

This exists because of what happens without it. A request times out and its entry leaves the - * registry; the work it started is still running and eventually answers. If the client has since - * issued a new request that happened to reuse the correlation id — and clients that number their - * requests reuse ids constantly — the late answer matches the new entry and is delivered as the - * response to a question nobody asked it. Nothing errors, and the client believes it. - * - *

So a timed-out id is not forgotten immediately: it is tombstoned for a window, during which an - * arriving answer is classified as late and dropped, and a new request that tries to claim the same - * id is refused. The window is bounded because the tombstones are otherwise a map that grows with - * every timeout the connection ever had. - */ -public final class LateResponseTombstone { - - private final Duration window; - private final Map tombstones = new ConcurrentHashMap<>(); - - /** - * @param window how long a timed-out correlation id stays recognisable - */ - public LateResponseTombstone(Duration window) { - this.window = Objects.requireNonNull(window, "window"); - if (window.isNegative() || window.isZero()) { - throw new IllegalArgumentException( - "a zero tombstone window forgets a timed-out id immediately, which is exactly when the" - + " late answer for it is still in flight"); - } - } - - /** Record that a request timed out. */ - public void record( - WebSocketConnectionId connectionId, WebSocketCorrelationId correlationId, Instant at) { - Objects.requireNonNull(at, "at"); - tombstones.put(new Key(connectionId, correlationId), at); - } - - /** - * Whether an arriving answer is for a request that already timed out. - * - *

Dropping it is the only safe response. The caller has already been told the request timed - * out, so delivering the answer now would contradict that — and if the id has been reused, it - * would answer the wrong request. - */ - public boolean isLate( - WebSocketConnectionId connectionId, WebSocketCorrelationId correlationId, Instant now) { - Objects.requireNonNull(now, "now"); - Instant recorded = tombstones.get(new Key(connectionId, correlationId)); - return recorded != null && now.isBefore(recorded.plus(window)); - } - - /** - * Whether a new request may claim this correlation id. - * - *

Refused while the tombstone stands. Allowing the reuse is what lets a late answer attach to - * the new request. - */ - public boolean mayReuse( - WebSocketConnectionId connectionId, WebSocketCorrelationId correlationId, Instant now) { - return !isLate(connectionId, correlationId, now); - } - - /** - * Drop tombstones past their window. - * - * @return how many went - */ - public int evictExpired(Instant now) { - Objects.requireNonNull(now, "now"); - int before = tombstones.size(); - tombstones.values().removeIf(recorded -> !now.isBefore(recorded.plus(window))); - return before - tombstones.size(); - } - - /** Forget everything for a connection that has closed. */ - public int releaseConnection(WebSocketConnectionId connectionId) { - Objects.requireNonNull(connectionId, "connectionId"); - int before = tombstones.size(); - tombstones.keySet().removeIf(key -> key.connectionId().equals(connectionId)); - return before - tombstones.size(); - } - - /** How many tombstones are held. */ - public int size() { - return tombstones.size(); - } - - /** A tombstone is per connection: correlation ids are only unique within one. */ - private record Key(WebSocketConnectionId connectionId, WebSocketCorrelationId correlationId) { - - Key { - Objects.requireNonNull(connectionId, "connectionId"); - Objects.requireNonNull(correlationId, "correlationId"); - } - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/handler/WebSocketCorrelationRegistry.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/handler/WebSocketCorrelationRegistry.java deleted file mode 100644 index 041dea15..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/handler/WebSocketCorrelationRegistry.java +++ /dev/null @@ -1,162 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.handler; - -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketConnectionId; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketCorrelationId; -import java.time.Duration; -import java.time.Instant; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.concurrent.ConcurrentHashMap; - -/** - * Which requests are in flight on which connection, so answers reach the right waiter. - * - *

Two properties do the work, and both are about a failure mode HTTP does not have. - * - *

First, entries are scoped to a connection. A correlation id is chosen by the client, so two - * clients will eventually choose the same one — and a registry keyed on the id alone routes one - * caller's answer to the other. That is a disclosure, not a mix-up, and it happens more often than - * it sounds because clients commonly start their counters at 1. - * - *

Second, entries expire. A request whose answer never comes would otherwise occupy the registry - * for the life of the connection, and on a long-lived connection that is a leak measured in hours. - * Expiry also gives the platform something true to tell the waiter instead of leaving it blocked - * for ever. - */ -public final class WebSocketCorrelationRegistry { - - /** - * One in-flight request. - * - * @param connectionId which connection issued it - * @param correlationId what the client called it - * @param issuedAt when it was registered - * @param expiresAt when it stops being answerable - */ - public record InFlight( - WebSocketConnectionId connectionId, - WebSocketCorrelationId correlationId, - Instant issuedAt, - Instant expiresAt) { - - public InFlight { - Objects.requireNonNull(connectionId, "connectionId"); - Objects.requireNonNull(correlationId, "correlationId"); - Objects.requireNonNull(issuedAt, "issuedAt"); - Objects.requireNonNull(expiresAt, "expiresAt"); - } - - /** Whether this entry has aged out. */ - public boolean expiredAt(Instant now) { - return !now.isBefore(expiresAt); - } - } - - private record Key(WebSocketConnectionId connectionId, WebSocketCorrelationId correlationId) {} - - private final Map inFlight = new ConcurrentHashMap<>(); - private final int maxInFlightPerConnection; - - /** - * A registry with a per-connection cap. - * - * @param maxInFlightPerConnection how many requests one connection may have outstanding - */ - public WebSocketCorrelationRegistry(int maxInFlightPerConnection) { - if (maxInFlightPerConnection <= 0) { - throw new IllegalArgumentException("a registry that admits nothing answers nothing"); - } - this.maxInFlightPerConnection = maxInFlightPerConnection; - } - - /** - * Registers a request. - * - * @return false when the correlation is already in use on this connection, or the cap is reached - */ - public boolean register( - WebSocketConnectionId connectionId, - WebSocketCorrelationId correlationId, - Instant now, - Duration timeToLive) { - Objects.requireNonNull(connectionId, "connectionId"); - Objects.requireNonNull(correlationId, "correlationId"); - // Counted before inserting. Without a cap a client can register correlations faster than it - // consumes answers and the map is unbounded — the same slow-consumer shape as the outbound - // buffer, in a different structure. - if (countFor(connectionId, now) >= maxInFlightPerConnection) { - return false; - } - return inFlight.putIfAbsent( - new Key(connectionId, correlationId), - new InFlight(connectionId, correlationId, now, now.plus(timeToLive))) - == null; - } - - /** - * Takes the entry an answer belongs to, if it is still live. - * - *

Scoped to the connection, which is the point: an answer arriving on one connection can never - * resolve a request registered on another. - */ - public Optional complete( - WebSocketConnectionId connectionId, WebSocketCorrelationId correlationId, Instant now) { - Key key = new Key(connectionId, correlationId); - InFlight entry = inFlight.remove(key); - if (entry == null || entry.expiredAt(now)) { - return Optional.empty(); - } - return Optional.of(entry); - } - - /** How many live requests a connection has outstanding. */ - public int countFor(WebSocketConnectionId connectionId, Instant now) { - return (int) - inFlight.values().stream() - .filter(entry -> entry.connectionId().equals(connectionId)) - .filter(entry -> !entry.expiredAt(now)) - .count(); - } - - /** - * Removes and returns the entries that aged out. - * - *

Returned rather than dropped so the platform can tell each waiter something true. A silently - * discarded entry leaves the client waiting for an answer that will never come. - */ - public List reapExpired(Instant now) { - List expired = new ArrayList<>(); - inFlight.forEach( - (key, entry) -> { - if (entry.expiredAt(now) && inFlight.remove(key, entry)) { - expired.add(entry); - } - }); - return List.copyOf(expired); - } - - /** - * Removes everything a connection owns. - * - *

Called when the connection closes. Without it the registry keeps entries for connections - * that no longer exist, and the leak is proportional to churn rather than to load. - */ - public List releaseConnection(WebSocketConnectionId connectionId) { - List released = new ArrayList<>(); - inFlight.forEach( - (key, entry) -> { - if (key.connectionId().equals(connectionId) && inFlight.remove(key, entry)) { - released.add(entry); - } - }); - return List.copyOf(released); - } - - /** How many entries are held in total. */ - public int size() { - return inFlight.size(); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/handler/WebSocketHandlerContext.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/handler/WebSocketHandlerContext.java deleted file mode 100644 index 27644e68..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/handler/WebSocketHandlerContext.java +++ /dev/null @@ -1,63 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.handler; - -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketActorReference; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketConnectionId; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketEndpointName; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageId; -import java.time.Instant; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; - -/** - * What a handler is allowed to know. - * - *

Everything here is a value. There is no session, no channel, no way to write and no way to - * close — deliberately, and it is the reason the platform's ordering and backpressure guarantees - * are guarantees rather than conventions. A handler that could write directly would bypass the - * outbound queue, and every promise about ordering would hold only for handlers that chose to - * cooperate. - * - *

The deadline is here because a handler needs it to make its own decisions — whether to start - * an expensive query at all — and because the platform cannot enforce a deadline on code that does - * not check one. Passing it makes cooperative cancellation possible; withholding it would make - * every timeout a hard abort. - * - * @param connectionId which connection this arrived on - * @param endpoint which endpoint it connected to - * @param actor a non-reversible reference to the caller - * @param authorities what the caller is permitted to do - * @param messageId the message being handled - * @param receivedAt when it arrived - * @param deadline when the platform stops waiting for this handler - */ -public record WebSocketHandlerContext( - WebSocketConnectionId connectionId, - WebSocketEndpointName endpoint, - WebSocketActorReference actor, - Set authorities, - WebSocketMessageId messageId, - Instant receivedAt, - Optional deadline) { - - public WebSocketHandlerContext { - Objects.requireNonNull(connectionId, "connectionId"); - Objects.requireNonNull(endpoint, "endpoint"); - Objects.requireNonNull(actor, "actor"); - Objects.requireNonNull(authorities, "authorities"); - Objects.requireNonNull(messageId, "messageId"); - Objects.requireNonNull(receivedAt, "receivedAt"); - Objects.requireNonNull(deadline, "deadline"); - authorities = Set.copyOf(authorities); - } - - /** Whether the handler has already run out of time. */ - public boolean expired(Instant now) { - return deadline.map(limit -> !now.isBefore(limit)).orElse(false); - } - - /** Whether the caller holds an authority. */ - public boolean holds(String authority) { - return authorities.contains(authority); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/handler/WebSocketHandlerResult.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/handler/WebSocketHandlerResult.java deleted file mode 100644 index 86c52c73..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/handler/WebSocketHandlerResult.java +++ /dev/null @@ -1,95 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.handler; - -import dev.caskeleton.adapter.inbound.websocket.error.WebSocketFailureCategory; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageType; -import java.util.List; -import java.util.Objects; -import java.util.Optional; - -/** - * What a handler wants sent, described rather than sent. - * - *

Returned instead of written, so the platform stays the only thing that touches the socket. - * That is what makes ordering, backpressure and the drain sequence enforceable: a handler cannot - * jump the outbound queue because it has no way to reach past it. - * - *

Failure is a value here too, not an exception. An exception carries a stack trace and a - * message written for a developer, and turning one into a client-facing error is where internals - * leak. A handler that wants to fail says which category and what the peer may be told. - * - * @param emissions what to send, in order - * @param failure the failure to report instead, when the handler failed - */ -public record WebSocketHandlerResult(List emissions, Optional failure) { - - /** - * One message the handler wants sent. - * - * @param type the published type - * @param payload the document, to be encoded by the platform - */ - public record Emission(WebSocketMessageType type, Object payload) { - - public Emission { - Objects.requireNonNull(type, "type"); - Objects.requireNonNull(payload, "payload"); - } - } - - /** - * A failure the handler chose to report. - * - * @param category what a client can act on - * @param publishableDetail a message already safe to send - */ - public record HandlerFailure(WebSocketFailureCategory category, String publishableDetail) { - - public HandlerFailure { - Objects.requireNonNull(category, "category"); - Objects.requireNonNull(publishableDetail, "publishableDetail"); - if (publishableDetail.isBlank()) { - throw new IllegalArgumentException("a failure with no detail tells the client nothing"); - } - } - } - - public WebSocketHandlerResult { - Objects.requireNonNull(emissions, "emissions"); - Objects.requireNonNull(failure, "failure"); - emissions = List.copyOf(emissions); - if (failure.isPresent() && !emissions.isEmpty()) { - // A handler that both failed and produced output leaves the platform to choose which the - // client sees, and either choice is wrong for some caller. - throw new IllegalArgumentException( - "a handler either failed or produced output; both leaves the platform choosing what the" - + " client sees"); - } - } - - /** Nothing to send. */ - public static WebSocketHandlerResult none() { - return new WebSocketHandlerResult(List.of(), Optional.empty()); - } - - /** One message. */ - public static WebSocketHandlerResult of(WebSocketMessageType type, Object payload) { - return new WebSocketHandlerResult(List.of(new Emission(type, payload)), Optional.empty()); - } - - /** Several messages, in order. */ - public static WebSocketHandlerResult ofAll(List emissions) { - return new WebSocketHandlerResult(emissions, Optional.empty()); - } - - /** A failure the peer may be told about. */ - public static WebSocketHandlerResult failed( - WebSocketFailureCategory category, String publishableDetail) { - return new WebSocketHandlerResult( - List.of(), Optional.of(new HandlerFailure(category, publishableDetail))); - } - - /** Whether the handler reported a failure. */ - public boolean succeeded() { - return failure.isEmpty(); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/handler/WebSocketMessageHandler.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/handler/WebSocketMessageHandler.java deleted file mode 100644 index f853be3a..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/handler/WebSocketMessageHandler.java +++ /dev/null @@ -1,39 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.handler; - -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageType; - -/** - * Where an application handles one decoded message. - * - *

The handler receives a decoded record and a context that carries no transport. That is the - * boundary the whole platform is arranged around: an application handler must not be able to write - * to the socket, close the connection, or read another connection's state. If it could, then - * ordering, backpressure and the drain sequence would each be advisory — any handler could bypass - * them by writing directly, and the platform's guarantees would hold only for the handlers that - * happened to cooperate. - * - *

So a handler returns what it wants sent and the platform decides when and whether. A handler - * that needs to emit more than one message returns a stream; one that needs to emit nothing returns - * nothing. - * - * @param the decoded command type this handler accepts - */ -@FunctionalInterface -public interface WebSocketMessageHandler { - - /** - * Handles one message. - * - * @param command the decoded request - * @param context what the handler may know about the connection - * @return what to send back, which the platform schedules - */ - WebSocketHandlerResult handle(C command, WebSocketHandlerContext context); - - /** The type this handler is registered for. */ - default WebSocketMessageType handledType() { - throw new UnsupportedOperationException( - "a handler must declare the type it is registered for; registration by reflection over a" - + " generic parameter is erased at runtime and silently binds the wrong handler"); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/handshake/HandshakeAdmissionPipeline.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/handshake/HandshakeAdmissionPipeline.java deleted file mode 100644 index 4cd5ad37..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/handshake/HandshakeAdmissionPipeline.java +++ /dev/null @@ -1,145 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.handshake; - -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketActorReference; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketEndpointCatalog; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketEndpointProfile; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketProtocolProfile; -import dev.caskeleton.adapter.inbound.websocket.security.WebSocketAuthenticationProfile; -import dev.caskeleton.adapter.inbound.websocket.security.WebSocketConnectionTicket; -import dev.caskeleton.adapter.inbound.websocket.security.WebSocketOriginPolicy; -import dev.caskeleton.adapter.inbound.websocket.security.WebSocketTicketStore; -import java.time.Instant; -import java.util.Objects; -import java.util.Optional; -import java.util.function.IntSupplier; - -/** - * Decides whether a handshake becomes a connection, in an order that is itself the contract. - * - *

The sequence matters more here than in an HTTP filter chain, because everything before the 101 - * is the last chance to refuse cheaply — after it, refusing costs a connection setup and a close - * frame, and the client has already been told it succeeded. - * - *

    - *
  1. Route. An unknown path is refused before anything else runs. Doing origin or - * credential work first spends effort on a request that was never going to be served, which - * is exactly what a scanner sends. - *
  2. Origin. Before authentication, because a cookie-authenticated handshake would - * otherwise authenticate successfully on a cross-origin request — the credential is valid; it - * is the page that is not allowed to use it. Checking after would mean the CSRF defence runs - * only for requests that already passed as legitimate. - *
  3. Capacity. Before the credential, because credential work is the expensive part — a - * ticket lookup or a token verification — and a saturated endpoint should shed before paying - * it. - *
  4. Credential. Last, and only for a request that is routed, permitted and affordable. - *
  5. Subprotocol. After the actor is known, so a refusal is attributable in the log. - *
- */ -public final class HandshakeAdmissionPipeline { - - private final WebSocketEndpointCatalog endpoints; - private final WebSocketOriginPolicy originPolicy; - private final WebSocketAuthenticationProfile authenticationProfile; - private final WebSocketProtocolProfile protocolProfile; - private final WebSocketTicketStore ticketStore; - private final IntSupplier currentConnections; - - /** - * A pipeline for one endpoint set. - * - * @param endpoints which endpoints exist - * @param originPolicy which origins may connect - * @param authenticationProfile how a caller proves identity - * @param protocolProfile which subprotocols are spoken - * @param ticketStore where one-time tickets live - * @param currentConnections how many connections the endpoint currently holds - */ - public HandshakeAdmissionPipeline( - WebSocketEndpointCatalog endpoints, - WebSocketOriginPolicy originPolicy, - WebSocketAuthenticationProfile authenticationProfile, - WebSocketProtocolProfile protocolProfile, - WebSocketTicketStore ticketStore, - IntSupplier currentConnections) { - this.endpoints = Objects.requireNonNull(endpoints, "endpoints"); - this.originPolicy = Objects.requireNonNull(originPolicy, "originPolicy"); - this.authenticationProfile = - Objects.requireNonNull(authenticationProfile, "authenticationProfile"); - this.protocolProfile = Objects.requireNonNull(protocolProfile, "protocolProfile"); - this.ticketStore = Objects.requireNonNull(ticketStore, "ticketStore"); - this.currentConnections = Objects.requireNonNull(currentConnections, "currentConnections"); - } - - /** - * Admits or refuses one handshake. - * - * @param request the handshake, as values - * @param now the current instant - */ - public HandshakeDecision admit(HandshakeRequest request, Instant now) { - Objects.requireNonNull(request, "request"); - - Optional endpoint = endpoints.findByPath(request.path()); - if (endpoint.isEmpty()) { - return HandshakeDecision.refuse(404, "no endpoint is served at that path"); - } - WebSocketEndpointProfile profile = endpoint.get(); - - if (!originPolicy.permits(request.origin().orElse(null))) { - // Before authentication on purpose. A cookie-authenticated handshake from an attacker's page - // authenticates perfectly — the credential is valid and the page is not allowed to use it. - return HandshakeDecision.refuse(403, "this origin may not open a connection"); - } - - if (currentConnections.getAsInt() >= profile.maxConcurrentConnections()) { - // Before the credential, because credential work is the expensive part and a saturated - // endpoint should shed before paying for it. - return HandshakeDecision.refuse(503, "this endpoint is at its connection limit"); - } - - Optional actor = authenticate(request, profile, now); - if (actor.isEmpty()) { - return HandshakeDecision.refuse(401, "this handshake carries no usable credential"); - } - - if (!protocolProfile.acceptsHandshake(request.offeredSubprotocols())) { - // 400 rather than 426. The client did reach a WebSocket endpoint and did attempt an upgrade; - // what it offered is not something this endpoint speaks, and 426 would tell it to upgrade - // something it already upgraded. - return HandshakeDecision.refuse(400, "no offered subprotocol is supported here"); - } - - return HandshakeDecision.admit( - actor.get(), protocolProfile.negotiate(request.offeredSubprotocols())); - } - - private Optional authenticate( - HandshakeRequest request, WebSocketEndpointProfile profile, Instant now) { - if (!profile.requiresAuthentication()) { - return Optional.of(anonymousReference()); - } - return switch (authenticationProfile) { - case ONE_TIME_TICKET -> - request - .ticketValue() - // Redeemed, not read: the store consumes atomically, so two handshakes arriving with - // the same ticket cannot both succeed. - .flatMap(value -> ticketStore.redeem(value, now)) - .filter(ticket -> ticket.validAt(now)) - .filter(ticket -> ticket.endpoint().equals(profile.name())) - .map(WebSocketConnectionTicket::actor); - case SESSION_COOKIE -> - // The cookie's own verification belongs to the security integration; what admission - // decides is that one was attached and the origin was permitted. - request.sessionCookiePresent() ? Optional.of(anonymousReference()) : Optional.empty(); - case BEARER_HEADER -> - request.bearerToken().isPresent() ? Optional.of(anonymousReference()) : Optional.empty(); - }; - } - - private static WebSocketActorReference anonymousReference() { - // A placeholder the runtime replaces with the verified identity. Admission decides - // admissibility; it does not verify tokens, which is the security integration's job. - return new WebSocketActorReference("0".repeat(64)); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/handshake/HandshakeDecision.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/handshake/HandshakeDecision.java deleted file mode 100644 index e211a0cb..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/handshake/HandshakeDecision.java +++ /dev/null @@ -1,61 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.handshake; - -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketActorReference; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketSubprotocolName; -import java.util.Objects; -import java.util.Optional; - -/** - * Whether a handshake is admitted, and what the connection is if so. - * - *

A refusal carries an HTTP status rather than a close code, and that is not a detail. Before - * the 101 there is no WebSocket: the only thing the client can be told is an HTTP response, and a - * server that tries to send a close frame here produces a browser error with no explanation - * attached. - * - * @param admitted whether the upgrade may proceed - * @param actor who is connecting, when admitted - * @param negotiatedSubprotocol what was agreed, when anything was - * @param refusalStatus the HTTP status to answer with, when refused - * @param refusalReason why, in terms safe to publish - */ -public record HandshakeDecision( - boolean admitted, - Optional actor, - Optional negotiatedSubprotocol, - int refusalStatus, - String refusalReason) { - - public HandshakeDecision { - Objects.requireNonNull(actor, "actor"); - Objects.requireNonNull(negotiatedSubprotocol, "negotiatedSubprotocol"); - Objects.requireNonNull(refusalReason, "refusalReason"); - if (admitted != actor.isPresent()) { - throw new IllegalArgumentException( - "an admitted handshake has an actor and a refused one does not; anything else means a" - + " connection is open with nobody attached to it"); - } - if (admitted && refusalStatus != 0) { - throw new IllegalArgumentException("an admitted handshake has no refusal status"); - } - if (!admitted && (refusalStatus < 400 || refusalStatus > 599)) { - throw new IllegalArgumentException("a refusal must carry a 4xx or 5xx status"); - } - } - - /** The handshake may proceed. */ - public static HandshakeDecision admit( - WebSocketActorReference actor, Optional subprotocol) { - return new HandshakeDecision(true, Optional.of(actor), subprotocol, 0, ""); - } - - /** - * The handshake is refused. - * - * @param status the HTTP status - * @param reason why, in terms safe to publish - */ - public static HandshakeDecision refuse(int status, String reason) { - return new HandshakeDecision(false, Optional.empty(), Optional.empty(), status, reason); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/handshake/HandshakeRequest.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/handshake/HandshakeRequest.java deleted file mode 100644 index 31afb38d..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/handshake/HandshakeRequest.java +++ /dev/null @@ -1,41 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.handshake; - -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketSubprotocolName; -import java.util.List; -import java.util.Objects; -import java.util.Optional; - -/** - * The handshake as the admission pipeline sees it: values, no transport. - * - *

A value type so admission is decided by pure code that runs identically under a servlet - * container and under Netty, and can be tested exhaustively without either. The two runtimes hand - * it different objects; they hand admission the same record. - * - * @param path the requested path - * @param origin the {@code Origin} header, absent when the client sent none - * @param offeredSubprotocols what the client offered, in its preference order - * @param ticketValue the ticket from the query string, when the profile uses one - * @param bearerToken the {@code Authorization} bearer, when the profile uses one - * @param sessionCookiePresent whether a session cookie was attached - * @param peerAddress the address the connection came from - */ -public record HandshakeRequest( - String path, - Optional origin, - List offeredSubprotocols, - Optional ticketValue, - Optional bearerToken, - boolean sessionCookiePresent, - String peerAddress) { - - public HandshakeRequest { - Objects.requireNonNull(path, "path"); - Objects.requireNonNull(origin, "origin"); - Objects.requireNonNull(offeredSubprotocols, "offeredSubprotocols"); - Objects.requireNonNull(ticketValue, "ticketValue"); - Objects.requireNonNull(bearerToken, "bearerToken"); - Objects.requireNonNull(peerAddress, "peerAddress"); - offeredSubprotocols = List.copyOf(offeredSubprotocols); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/idempotency/CommandReconciliation.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/idempotency/CommandReconciliation.java deleted file mode 100644 index 2b1b8456..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/idempotency/CommandReconciliation.java +++ /dev/null @@ -1,84 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.idempotency; - -import java.time.Instant; -import java.util.Objects; -import java.util.Optional; - -/** - * Resolves a command whose outcome was never recorded. - * - *

The window is small and unavoidable: the application commits, the process dies, the ledger - * entry is never written. What is left is a claim with no outcome, and neither replaying nor - * re-running is safe — replaying invents a result, re-running duplicates a committed write. - * - *

The only thing that can resolve it is the business data. Did the order exist? Was the payment - * captured? That question is application-specific, so the platform asks rather than guesses, and a - * deployment that cannot answer it says so — leaving the command unresolved is a worse outcome than - * a wrong guess only in the sense that it is visible. - */ -@FunctionalInterface -public interface CommandReconciliation { - - /** - * What the business data says about a command that started and was never resolved. - * - * @param key the command in question - * @param now the current instant - */ - Verdict reconcile(WebSocketCommandKey key, Instant now); - - /** - * The answer, and how confident it is. - * - * @param state what the business data shows - * @param encodedResult the result to replay, when the work is found to have committed - */ - record Verdict(State state, Optional encodedResult) { - - public Verdict { - Objects.requireNonNull(state, "state"); - Objects.requireNonNull(encodedResult, "encodedResult"); - if (state == State.COMMITTED && encodedResult.isEmpty()) { - throw new IllegalArgumentException( - "a command found to have committed must produce the result to replay, or the client" - + " is told it succeeded with nothing to show for it"); - } - if (state != State.COMMITTED && encodedResult.isPresent()) { - throw new IllegalArgumentException("only a committed verdict carries a result"); - } - } - - /** The business data shows the work happened. */ - public static Verdict committed(String encodedResult) { - return new Verdict(State.COMMITTED, Optional.of(encodedResult)); - } - - /** The business data shows the work did not happen. */ - public static Verdict notCommitted() { - return new Verdict(State.NOT_COMMITTED, Optional.empty()); - } - - /** The business data cannot say. */ - public static Verdict indeterminate() { - return new Verdict(State.INDETERMINATE, Optional.empty()); - } - } - - /** What reconciliation concluded. */ - enum State { - - /** The work is in the business data. Replay its result. */ - COMMITTED, - - /** The work is not there. The command may run again. */ - NOT_COMMITTED, - - /** - * The business data does not settle it. - * - *

Left unresolved rather than guessed. An operator can act on a command that says it does - * not know; nobody can act on one that quietly picked an answer. - */ - INDETERMINATE - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/idempotency/CommittedResultLedger.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/idempotency/CommittedResultLedger.java deleted file mode 100644 index 018d19c4..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/idempotency/CommittedResultLedger.java +++ /dev/null @@ -1,61 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.idempotency; - -import java.time.Instant; -import java.util.List; -import java.util.Optional; - -/** - * Where the outcome of a command is durably recorded. - * - *

An SPI, because the only implementation that actually works is one that writes in the same - * transaction as the application's own work. A ledger in memory, in a cache, or in a second - * database has a window between the business commit and the ledger write — and a crash inside that - * window produces exactly the {@link WebSocketCommandOutcome#UNKNOWN} state that no amount of - * retrying can resolve safely. - * - *

The platform therefore does not ship a default. A deployment that has not chosen a - * transactional ledger has not made command idempotency work, and a convenient in-memory default - * would hide that until the first crash. - */ -public interface CommittedResultLedger { - - /** - * Claims a command for execution. - * - *

Atomic. A claim implemented as read-then-write lets two attempts both see nothing and both - * run, which is the duplicate the ledger exists to prevent — and reconnect storms deliver exactly - * the concurrent duplicates that expose it. - * - * @param key what identifies the command - * @param now the current instant - * @param leaseDuration how long the claim holds before another attempt may take it - * @return the outcome, which is {@code NEW} when this caller won the claim - */ - WebSocketCommandOutcome claim( - WebSocketCommandKey key, Instant now, java.time.Duration leaseDuration); - - /** - * Records that the command committed, with the result to replay. - * - *

Must be called inside the application's own transaction. Called after it, the gap between - * the two is the UNKNOWN window. - */ - void recordCommitted(WebSocketCommandKey key, String encodedResult, Instant at); - - /** Records that the command failed without committing, so a retry may run. */ - void recordFailed(WebSocketCommandKey key, Instant at); - - /** The stored result for a committed command. */ - Optional committedResult(WebSocketCommandKey key, Instant now); - - /** The current outcome without claiming anything. */ - WebSocketCommandOutcome outcome(WebSocketCommandKey key, Instant now); - - /** - * Commands whose lease lapsed with no recorded outcome. - * - *

These are the UNKNOWN ones. Returned rather than resolved, because the ledger cannot know - * what happened — only the business data can say, and only a reconciliation that reads it. - */ - List unresolved(Instant now); -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/idempotency/WebSocketCommandKey.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/idempotency/WebSocketCommandKey.java deleted file mode 100644 index 7565b2c3..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/idempotency/WebSocketCommandKey.java +++ /dev/null @@ -1,40 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.idempotency; - -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketActorReference; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketEndpointName; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageId; -import java.util.Objects; - -/** - * What makes two command attempts the same command. - * - *

Deliberately not scoped to the connection, and that is the whole point. A WebSocket client - * that loses its connection reconnects and replays whatever it did not see an answer for — on a new - * connection, with a new connection id. A key that included the connection would treat every replay - * as a new command, which makes the idempotency machinery inert exactly when it is needed. - * - *

Scoped to the actor rather than the session for the same reason one step further out: a client - * that also lost its session identity still must not double-execute. The actor is the coarsest - * scope that is still safe, because two actors' commands can never collide. - * - * @param endpoint which endpoint the command arrived on - * @param actor who sent it - * @param messageId the client's own identifier for the command - */ -public record WebSocketCommandKey( - WebSocketEndpointName endpoint, WebSocketActorReference actor, WebSocketMessageId messageId) { - - public WebSocketCommandKey { - Objects.requireNonNull(endpoint, "endpoint"); - Objects.requireNonNull(actor, "actor"); - Objects.requireNonNull(messageId, "messageId"); - } - - /** A stable storage key, for a store that wants one string. */ - public String storageKey() { - // Separated by a unit separator, which cannot appear in any of the three components' grammars. - // Joining on a printable character would let one component's value forge a boundary and make - // two different commands share a key. - return endpoint.value() + '\u001f' + actor.fingerprint() + '\u001f' + messageId.value(); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/idempotency/WebSocketCommandOutcome.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/idempotency/WebSocketCommandOutcome.java deleted file mode 100644 index ffbb88db..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/idempotency/WebSocketCommandOutcome.java +++ /dev/null @@ -1,33 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.idempotency; - -/** - * What is known about a command that was seen before. - * - *

Four answers rather than seen/not-seen, because each leads somewhere different. Only {@link - * #COMMITTED} may be answered with a stored result; {@link #IN_FLIGHT} must wait or refuse; {@link - * #FAILED} may be retried; and {@link #UNKNOWN} — a command that started and whose outcome was - * never recorded — is the one that must not be guessed. - */ -public enum WebSocketCommandOutcome { - - /** Never seen. Run it. */ - NEW, - - /** Another attempt is running right now. */ - IN_FLIGHT, - - /** It completed and its result is stored. Replay that. */ - COMMITTED, - - /** It ran and failed without committing. Safe to run again. */ - FAILED, - - /** - * It started and nothing recorded what happened. - * - *

The state a crash between the application's commit and the ledger write leaves behind. - * Neither replaying nor re-running is safe, so it is a state of its own rather than being folded - * into either — the platform's only correct move is to say so and let reconciliation decide. - */ - UNKNOWN -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/inbound/FragmentAssembler.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/inbound/FragmentAssembler.java deleted file mode 100644 index 84cccbb6..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/inbound/FragmentAssembler.java +++ /dev/null @@ -1,117 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.inbound; - -import dev.caskeleton.adapter.inbound.websocket.budget.WebSocketConnectionBudget; -import dev.caskeleton.adapter.inbound.websocket.error.WebSocketFailureCategory; -import java.nio.charset.StandardCharsets; -import java.util.Objects; -import java.util.Optional; - -/** - * Reassembles a message from continuation frames, refusing before it costs anything. - * - *

Fragmentation is the inbound attack surface a WebSocket has and HTTP does not. A peer may send - * a first frame and then continuation frames indefinitely, and a naive assembler grows a buffer for - * as long as the peer keeps sending — no single frame is oversized, no error is thrown, and the - * memory is charged to a connection that looks healthy. - * - *

So three separate bounds apply, and each catches a shape the others do not: a frame bound - * refuses one huge frame, a total bound refuses many ordinary frames adding up, and a fragment - * count refuses an endless stream of tiny ones. The third is the one usually missing — a thousand - * one-byte continuations sit well inside both size bounds while costing a thousand array copies. - * - *

One assembler per connection. A shared one would interleave two peers' fragments into one - * message, which is both a corruption and a disclosure. - */ -public final class FragmentAssembler { - - private final WebSocketConnectionBudget budget; - private final StringBuilder buffer = new StringBuilder(); - private int fragments; - private boolean assembling; - - /** - * An assembler for one connection. - * - * @param budget the bounds to enforce - */ - public FragmentAssembler(WebSocketConnectionBudget budget) { - this.budget = Objects.requireNonNull(budget, "budget"); - } - - /** - * Accepts one frame. - * - * @param payload the frame's text - * @param finalFrame whether this frame completes the message - * @return the whole message when this frame completed it, else empty - * @throws FragmentAssemblyException when a bound is crossed or the sequence is invalid - */ - public Optional accept(String payload, boolean finalFrame) { - Objects.requireNonNull(payload, "payload"); - int frameBytes = payload.getBytes(StandardCharsets.UTF_8).length; - if (frameBytes > budget.maxFrameBytes()) { - reset(); - throw new FragmentAssemblyException( - WebSocketFailureCategory.TOO_LARGE, - "a frame exceeds " + budget.maxFrameBytes() + " bytes"); - } - - if (!assembling && finalFrame) { - // The common case: one unfragmented message. Nothing is buffered at all, so the ordinary - // path costs no copy. - return Optional.of(payload); - } - - fragments++; - if (fragments > budget.maxFragments()) { - reset(); - throw new FragmentAssemblyException( - WebSocketFailureCategory.TOO_LARGE, - "a message spans more than " - + budget.maxFragments() - + " frames; an endless stream of small continuations stays inside every size bound" - + " while costing a copy each"); - } - if (buffer.length() + payload.length() > budget.maxMessageBytes()) { - reset(); - throw new FragmentAssemblyException( - WebSocketFailureCategory.TOO_LARGE, - "a reassembled message exceeds " + budget.maxMessageBytes() + " bytes"); - } - - assembling = true; - buffer.append(payload); - if (!finalFrame) { - return Optional.empty(); - } - String message = buffer.toString(); - reset(); - return Optional.of(message); - } - - /** - * Discards any partial message. - * - *

Called when a connection closes or a control frame interrupts. Without it a half-assembled - * message holds its buffer for the life of the connection — which, for a connection that never - * sends again, is hours. - */ - public void reset() { - buffer.setLength(0); - // Trimmed as well as cleared: StringBuilder keeps its grown capacity, so a connection that - // once received a large message would hold that array for ever. - buffer.trimToSize(); - fragments = 0; - assembling = false; - } - - /** Whether a message is partially assembled. */ - public boolean assembling() { - return assembling; - } - - /** How many bytes are currently buffered. */ - public int bufferedLength() { - return buffer.length(); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/inbound/FragmentAssemblyException.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/inbound/FragmentAssemblyException.java deleted file mode 100644 index acb0b08a..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/inbound/FragmentAssemblyException.java +++ /dev/null @@ -1,33 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.inbound; - -import dev.caskeleton.adapter.inbound.websocket.error.WebSocketFailureCategory; -import java.util.Objects; - -/** - * A frame sequence that could not be assembled within its bounds. - * - *

Carries a category, because the answer differs: an oversized message closes the connection - * with 1009, while a malformed sequence does not have to. - */ -public final class FragmentAssemblyException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - private final transient WebSocketFailureCategory category; - - /** - * An assembly failure. - * - * @param category what a client can act on - * @param publishableDetail a message safe to send - */ - public FragmentAssemblyException(WebSocketFailureCategory category, String publishableDetail) { - super(Objects.requireNonNull(publishableDetail, "publishableDetail")); - this.category = Objects.requireNonNull(category, "category"); - } - - /** What kind of failure this is. */ - public WebSocketFailureCategory category() { - return category; - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/lifecycle/CloseOrchestration.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/lifecycle/CloseOrchestration.java deleted file mode 100644 index ef532ea0..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/lifecycle/CloseOrchestration.java +++ /dev/null @@ -1,138 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.lifecycle; - -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketConnectionContext; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketConnectionState; -import dev.caskeleton.adapter.inbound.websocket.error.WebSocketCloseCode; -import java.time.Duration; -import java.time.Instant; -import java.util.Objects; -import java.util.Optional; - -/** - * The order a connection is taken down in, and why each step is where it is. - * - *

Closing a WebSocket is not one action. RFC 6455 has a closing handshake: the server sends a - * close frame, the peer answers, and only then is the TCP connection torn down. Skipping to the - * teardown produces a 1006 on the client — "closed abnormally, no reason given" — which is - * indistinguishable from a network failure and sends every client into its most aggressive - * reconnect path at exactly the moment the fleet is being restarted. - * - *

So the sequence is: stop accepting inbound, finish what is queued, send a close frame with a - * code that says why, wait briefly for the peer's answer, then tear down. Each step has a bound, - * because a peer that is gone will not complete any of them. - */ -public final class CloseOrchestration { - - /** How long the peer is given to answer a close frame before the socket is torn down. */ - public static final Duration CLOSE_HANDSHAKE_TIMEOUT = Duration.ofSeconds(5); - - /** What the platform should do next for one closing connection. */ - public enum Step { - - /** Move to DRAINING: no new inbound work, in-flight writes continue. */ - STOP_ACCEPTING_INBOUND, - - /** Keep writing what is already queued. */ - FLUSH_PENDING, - - /** Send the close frame with its code. */ - SEND_CLOSE_FRAME, - - /** Wait for the peer's close frame. */ - AWAIT_PEER_CLOSE, - - /** Tear down the socket. */ - TEAR_DOWN - } - - private CloseOrchestration() {} - - /** - * The next step for a connection being closed. - * - * @param context the connection - * @param pendingWrites how many messages are still queued - * @param closeFrameSentAt when the close frame went out, if it has - * @param peerClosed whether the peer answered - * @param now the current instant - * @param drainDeadline when the platform stops waiting for pending writes - */ - public static Step nextStep( - WebSocketConnectionContext context, - int pendingWrites, - Optional closeFrameSentAt, - boolean peerClosed, - Instant now, - Instant drainDeadline) { - Objects.requireNonNull(context, "context"); - Objects.requireNonNull(closeFrameSentAt, "closeFrameSentAt"); - - if (context.state() == WebSocketConnectionState.OPEN) { - return Step.STOP_ACCEPTING_INBOUND; - } - if (closeFrameSentAt.isEmpty()) { - // Bounded: a peer that stopped reading would otherwise hold the drain open for as long as it - // wants, and a rolling deploy waits behind it. - return pendingWrites > 0 && now.isBefore(drainDeadline) - ? Step.FLUSH_PENDING - : Step.SEND_CLOSE_FRAME; - } - if (peerClosed) { - return Step.TEAR_DOWN; - } - // Also bounded. A peer that is gone never answers, and waiting for it is how a shutdown hangs - // with no error to point at. - return now.isBefore(closeFrameSentAt.get().plus(CLOSE_HANDSHAKE_TIMEOUT)) - ? Step.AWAIT_PEER_CLOSE - : Step.TEAR_DOWN; - } - - /** - * The code to close with for a given reason. - * - * @param reason why the connection is being closed - */ - public static WebSocketCloseCode codeFor(CloseReason reason) { - Objects.requireNonNull(reason, "reason"); - return switch (reason) { - case CLIENT_REQUESTED -> WebSocketCloseCode.NORMAL; - // 1001, not 1000. A client that is told "going away" reconnects, and one told "normal" - // may reasonably conclude the session is over and not come back. - case NODE_SHUTTING_DOWN -> WebSocketCloseCode.GOING_AWAY; - case CREDENTIAL_EXPIRED -> WebSocketCloseCode.CREDENTIAL_EXPIRED; - case MAX_AGE_REACHED -> WebSocketCloseCode.MAX_AGE_REACHED; - case IDLE_TIMEOUT -> WebSocketCloseCode.IDLE_TIMEOUT; - case POLICY_VIOLATION -> WebSocketCloseCode.POLICY_VIOLATION; - case OUTBOUND_OVERFLOW -> WebSocketCloseCode.SHED_FOR_CAPACITY; - case INTERNAL_ERROR -> WebSocketCloseCode.INTERNAL_ERROR; - }; - } - - /** Why a connection is being closed. */ - public enum CloseReason { - - /** The client asked. */ - CLIENT_REQUESTED, - - /** This node is going away. */ - NODE_SHUTTING_DOWN, - - /** The credential expired past its grace. */ - CREDENTIAL_EXPIRED, - - /** The connection outlived its maximum age. */ - MAX_AGE_REACHED, - - /** The connection was silent past its idle timeout. */ - IDLE_TIMEOUT, - - /** The peer did something the platform will not tolerate. */ - POLICY_VIOLATION, - - /** A guaranteed message could not be queued. */ - OUTBOUND_OVERFLOW, - - /** Something failed that cannot be recovered for this connection. */ - INTERNAL_ERROR - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/lifecycle/HeartbeatPolicy.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/lifecycle/HeartbeatPolicy.java deleted file mode 100644 index 73919a74..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/lifecycle/HeartbeatPolicy.java +++ /dev/null @@ -1,65 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.lifecycle; - -import java.time.Duration; -import java.time.Instant; -import java.util.Objects; - -/** - * How a connection is proven alive, and when it is given up on. - * - *

Heartbeats exist because TCP does not tell you the peer is gone. A laptop that closes its lid, - * a phone that switches to cellular, a NAT that forgets its mapping — none of these produce a FIN. - * The socket stays open and writable from the server's side, and the connection occupies its - * buffers, its registry entry and its subscription for as long as nobody checks. - * - *

Two intervals with a fixed relationship. The ping interval is how often the server asks; the - * idle timeout is how long silence is tolerated. A timeout shorter than two intervals is the - * classic misconfiguration: one dropped ping on a congested network closes a healthy connection, - * and the reconnect storm that follows makes the congestion worse. - * - * @param pingInterval how often the server sends a ping - * @param idleTimeout how long the server tolerates silence before closing - */ -public record HeartbeatPolicy(Duration pingInterval, Duration idleTimeout) { - - public HeartbeatPolicy { - Objects.requireNonNull(pingInterval, "pingInterval"); - Objects.requireNonNull(idleTimeout, "idleTimeout"); - if (pingInterval.isZero() || pingInterval.isNegative()) { - throw new IllegalArgumentException("a connection that is never pinged is never checked"); - } - if (idleTimeout.compareTo(pingInterval.multipliedBy(2)) < 0) { - throw new IllegalArgumentException( - "an idle timeout below two ping intervals closes a healthy connection on one dropped" - + " ping, and the reconnect storm makes the congestion that dropped it worse"); - } - if (pingInterval.compareTo(Duration.ofSeconds(20)) > 0) { - // Intermediaries commonly drop an idle connection at 30-60 seconds and send nothing to say - // so. A ping slower than that lets the platform's own liveness check be the thing that never - // notices. - throw new IllegalArgumentException( - "a ping interval over 20s outlives the idle timeout of common intermediaries, so the" - + " connection is dropped by something in the middle before the server checks"); - } - } - - /** The platform default. */ - public static HeartbeatPolicy standard() { - return new HeartbeatPolicy(Duration.ofSeconds(15), Duration.ofSeconds(45)); - } - - /** Whether a ping is due. */ - public boolean pingDue(Instant lastActivity, Instant now) { - return !now.isBefore(lastActivity.plus(pingInterval)); - } - - /** Whether the connection has been silent too long. */ - public boolean idleExpired(Instant lastActivity, Instant now) { - return !now.isBefore(lastActivity.plus(idleTimeout)); - } - - /** How many pings may go unanswered before the connection is closed. */ - public long toleratedMissedPings() { - return idleTimeout.toMillis() / pingInterval.toMillis(); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/moduleboundary/WebSocketModuleBoundary.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/moduleboundary/WebSocketModuleBoundary.java deleted file mode 100644 index cb408704..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/moduleboundary/WebSocketModuleBoundary.java +++ /dev/null @@ -1,98 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.moduleboundary; - -import java.util.Map; -import java.util.Optional; -import java.util.Set; - -/** - * Resolves a package name to the module that owns it. - * - *

Longest-prefix, so a sub-package belongs to its parent module without needing its own - * declaration. That is what lets {@code servlet.handshake} exist without loosening the boundary: it - * inherits {@code servlet}'s edge set rather than getting one of its own. - */ -public final class WebSocketModuleBoundary { - - /** The platform's root package. */ - public static final String PACKAGE_ROOT = deriveRootPackage(); - - private WebSocketModuleBoundary() {} - - /** Every declared module id. */ - public static Set allModuleIds() { - return WebSocketStableModule.moduleIds(); - } - - /** The declared edge set, by module id. */ - public static Map> dependencyEdges() { - return WebSocketStableModule.dependencyEdges(); - } - - /** The ids of the modules that may not name a framework type. */ - public static Set coreModuleIds() { - return WebSocketStableModule.coreModuleIds(); - } - - /** The package each module lives in, by module id. */ - public static Map packagesById() { - return WebSocketStableModule.packagesById(); - } - - /** - * The module that owns a package, by longest matching prefix. - * - * @param packageName a fully qualified package name - */ - public static Optional moduleIdForPackage(String packageName) { - if (packageName == null || !insidePlatform(packageName)) { - return Optional.empty(); - } - if (packageName.equals(PACKAGE_ROOT)) { - // The root package itself belongs to no module. The leaf's pre-existing STOMP transport - // classes live there, and claiming them for some module would give them an edge set nobody - // chose. - return Optional.empty(); - } - String relative = packageName.substring(PACKAGE_ROOT.length() + 1); - String bestId = null; - String bestPackage = null; - for (Map.Entry entry : packagesById().entrySet()) { - String candidate = entry.getValue(); - if (!matches(relative, candidate)) { - continue; - } - // Longest wins, so a module declared as a sub-package of another takes precedence over its - // parent rather than the iteration order deciding. - if (bestPackage == null || candidate.length() > bestPackage.length()) { - bestPackage = candidate; - bestId = entry.getKey(); - } - } - return Optional.ofNullable(bestId); - } - - /** Whether a package is inside the platform at all. */ - public static boolean insidePlatform(String packageName) { - return packageName != null - && (packageName.equals(PACKAGE_ROOT) || packageName.startsWith(PACKAGE_ROOT + ".")); - } - - /** Whether one module may import another. */ - public static boolean edgeAllowed(String from, String to) { - if (from == null || to == null || from.equals(to)) { - return true; - } - return dependencyEdges().getOrDefault(from, Set.of()).contains(to); - } - - private static boolean matches(String packageName, String candidate) { - return packageName.equals(candidate) || packageName.startsWith(candidate + "."); - } - - private static String deriveRootPackage() { - // Derived from this class rather than written out, so moving the platform cannot leave the - // boundary test scanning a package that no longer exists and reporting success. - String self = WebSocketModuleBoundary.class.getPackageName(); - return self.substring(0, self.lastIndexOf('.')); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/moduleboundary/WebSocketModulePurity.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/moduleboundary/WebSocketModulePurity.java deleted file mode 100644 index e37ec87c..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/moduleboundary/WebSocketModulePurity.java +++ /dev/null @@ -1,27 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.moduleboundary; - -/** - * Whether a module may name a runtime/framework type. - * - *

The distinction is load-bearing for this platform specifically. A WebSocket connection is a - * long-lived object owned by a container, and the temptation to reach for the container's own - * session type from anywhere is constant. A module marked CORE cannot: it has no {@code - * WebSocketSession}, no {@code ServerHttpRequest}, no {@code DataBuffer}, so the decisions it makes - * are testable without a server and portable between the two runtimes. - */ -public enum WebSocketModulePurity { - - /** - * Framework-free decision code. - * - *

Java standard library, this platform's own types, and repository-owned application/domain - * contracts are allowed. Application ports are intentional: they keep a capability testable - * without a server while still letting it delegate durable storage/fan-out to the application - * boundary. Spring, Servlet, Reactor, Netty, Jackson, logging/metrics runtime types are not - * allowed. - */ - CORE, - - /** May name framework types, because its job is to bind to one. */ - FRAMEWORK_BOUND -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/moduleboundary/WebSocketStableModule.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/moduleboundary/WebSocketStableModule.java deleted file mode 100644 index 94600419..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/moduleboundary/WebSocketStableModule.java +++ /dev/null @@ -1,394 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.moduleboundary; - -import java.util.Arrays; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Set; -import java.util.TreeMap; -import java.util.stream.Collectors; - -/** - * The Stable WebSocket platform modules, their purity grade and their allowed internal edges. - * - *

The design models this platform as eighteen Gradle modules under {@code modules/websocket}. - * This repository's fail-closed registry owns the leaf list, so they are sub-packages of one - * registered leaf instead — the same resolution the JPA, GraphQL and web platforms reached. The - * mapping is in {@code docs/websocket/repository-adaptation.md}. - * - *

That choice is only honest if the boundaries are machine checked, so this enum is the declared - * identity and {@code WebSocketModuleBoundaryTest} fails when the source tree and this declaration - * disagree in either direction — an undeclared edge, or a package with no declared identity. - * - *

The edge that matters most is the one that is absent: {@code servlet} and {@code webflux} - * declare no edge to each other. The two runtimes are mutually exclusive, and an edge between them - * would let the reactive runtime compile against a servlet type — which is how a deployment ends up - * shipping both and starting neither. - */ -public enum WebSocketStableModule { - - /** - * Identifiers, endpoint names, connection state and the immutable connection context. - * - *

The design's {@code websocket-core-api}. CORE, and the strictest instance of it in this - * repository: a connection identifier that could hold a {@code WebSocketSession} would make every - * downstream decision untestable without a running container. - */ - CORE("core", "core", WebSocketModulePurity.CORE, "budget"), - - /** Protocol names, versions, message families, envelopes and the wire codec profile. */ - PROTOCOL("protocol", "protocol", WebSocketModulePurity.CORE, "core"), - - /** - * Frame, message and connection resource budgets. - * - *

A leaf: it names no other module. The declared direction was {@code budget -> core} until - * the endpoint profile — which is core — had to name a budget, and the boundary test refused the - * cycle. Numbers depend on nothing, so {@code core -> budget} is the coherent direction and the - * one that was actually true all along. - */ - BUDGET("budget", "budget", WebSocketModulePurity.CORE), - - /** - * The strict wire codec and the manifest of what it will decode. - * - *

FRAMEWORK_BOUND, and separate from {@code protocol} because of it. The design puts the codec - * in {@code websocket-protocol}; here that module is CORE, and a Jackson import in a CORE module - * is refused. Splitting them is better than relaxing the rule: the envelope's field rules stay - * testable with no mapper, and everything that touches a parser sits in one package a reviewer - * can read end to end. - */ - CODEC( - "codec", - "codec", - WebSocketModulePurity.FRAMEWORK_BOUND, - "budget", - "core", - "error", - "protocol"), - - /** Typed errors and the close-code catalog. */ - ERROR("error", "error", WebSocketModulePurity.CORE, "core", "protocol"), - - /** - * The three-axis execution evidence model: inbound, outbound and connection. - * - *

Names {@code error} because connection evidence records the close code the connection ended - * with. That is the field that separates "closed cleanly" from "closed because the peer could not - * keep up", and without it the two are indistinguishable in the record. - */ - EVIDENCE("evidence", "evidence", WebSocketModulePurity.CORE, "core", "error", "protocol"), - - /** The application message handler boundary and correlation registry. */ - HANDLER("handler", "handler", WebSocketModulePurity.CORE, "core", "error", "protocol"), - - /** Command idempotency and the committed-result ledger. */ - IDEMPOTENCY("idempotency", "idempotency", WebSocketModulePurity.CORE, "core", "protocol"), - - /** Authentication profiles, origin policy and one-time connection tickets. */ - SECURITY("security", "security", WebSocketModulePurity.CORE, "core", "error"), - - /** The handshake admission pipeline. */ - /** - * The handshake admission pipeline. - * - *

Names {@code protocol} because subprotocol negotiation is part of admission: it is the last - * decision made before the 101 and the only one a client can still be told about over HTTP. - */ - HANDSHAKE( - "handshake", - "handshake", - WebSocketModulePurity.CORE, - "budget", - "core", - "error", - "protocol", - "security"), - - /** Node-local session registry and per-connection state. */ - SESSION("session", "session", WebSocketModulePurity.CORE, "budget", "core", "evidence"), - - /** Message authorization, applied per message rather than per connection. */ - AUTHZ("authz", "authz", WebSocketModulePurity.CORE, "core", "error", "protocol", "security"), - - /** - * Inbound frame reassembly and its bounds. - * - *

Separate from {@code protocol} because it is about frames rather than about messages: it - * runs before anything has parsed, on bytes chosen entirely by the peer, and its whole job is to - * refuse before the parse is paid for. - */ - INBOUND("inbound", "inbound", WebSocketModulePurity.CORE, "budget", "core", "error"), - - /** Outbound delivery semantics, priority, queueing and backpressure. */ - OUTBOUND( - "outbound", "outbound", WebSocketModulePurity.CORE, "budget", "core", "error", "protocol"), - - /** Ordering profiles, sequencing and gap detection. */ - ORDERING("ordering", "ordering", WebSocketModulePurity.CORE, "core", "protocol"), - - /** Heartbeats, idle policy, credential expiry and connection age. */ - LIFECYCLE( - "lifecycle", "lifecycle", WebSocketModulePurity.CORE, "core", "error", "security", "session"), - - /** Metrics, tracing and safe logging for a long-lived connection. */ - OBSERVABILITY( - "observability", "observability", WebSocketModulePurity.CORE, "core", "error", "evidence"), - - /** The operator's view: snapshot, forced disconnect and drain. */ - ADMIN("admin", "admin", WebSocketModulePurity.CORE, "core", "lifecycle", "session"), - - /** - * The servlet runtime. - * - *

No edge to {@code webflux}: the two runtimes are mutually exclusive and an edge would let - * one compile against the other's session type. - */ - SERVLET( - "servlet", - "servlet", - WebSocketModulePurity.FRAMEWORK_BOUND, - "authz", - "budget", - "core", - "error", - "evidence", - "handler", - "inbound", - "handshake", - "lifecycle", - "observability", - "ordering", - "outbound", - "protocol", - "security", - "session"), - - /** The reactive runtime, with the same allowed edges and no edge to {@code servlet}. */ - WEBFLUX( - "webflux", - "webflux", - WebSocketModulePurity.FRAMEWORK_BOUND, - "authz", - "budget", - "core", - "error", - "evidence", - "handler", - "inbound", - "handshake", - "lifecycle", - "observability", - "ordering", - "outbound", - "protocol", - "security", - "session"), - - /** Bound configuration properties and the startup validator. */ - /** - * Bound configuration and the startup validator. - * - *

Names nearly everything, and that is inherent to what it does: the validator's job is to - * refuse an incoherent combination of the platform's parts, so it has to be able to see them. - */ - CONFIG( - "config", - "config", - WebSocketModulePurity.FRAMEWORK_BOUND, - "authz", - "budget", - "core", - "lifecycle", - "outbound", - "protocol", - "security"), - - /** - * The Advanced capabilities, each behind its own feature flag. - * - *

One module rather than the design's fifteen because they share exactly one property — none - * is on unless named — and nothing else. The flag enum keeps them independent of each other; the - * boundary rule that matters is the one ArchUnit enforces, that no Stable module may name this - * package. A flag decides whether a bean is created and does nothing about a compile-time edge. - */ - ADVANCED( - "advanced", - "advanced", - WebSocketModulePurity.CORE, - "core", - "error", - "evidence", - "protocol", - "security", - "session"), - - /** - * The Advanced STOMP subprotocol adapter. - * - *

Its own module rather than part of {@code advanced} because it is the one Advanced - * capability that cannot be pure: STOMP is Spring Messaging's protocol here, and the adapter is - * the Spring types. Folding it into {@code advanced} would mean relaxing that module's purity for - * every capability in it, so the framework dependency is fenced to the package that needs it. - */ - ADVANCED_STOMP( - "advanced-stomp", - "advanced.stomp", - WebSocketModulePurity.FRAMEWORK_BOUND, - "advanced", - "core", - "error", - "evidence", - "security"), - - /** - * The Advanced binary codecs, CBOR and Protobuf. - * - *

{@code FRAMEWORK_BOUND} because a codec is its format's library — Jackson's CBOR backend and - * protobuf's own runtime. It names the Stable {@code codec} module deliberately: the wire type - * manifest and the decode exception are shared, so a second decode path resolves against the same - * manifest and reports failures in the same vocabulary as the first. Duplicating either would let - * the two codecs publish different type sets, which is exactly what {@code SchemaParity} exists - * to refuse. - */ - ADVANCED_CODEC( - "advanced-codec", - "advanced.codec", - WebSocketModulePurity.FRAMEWORK_BOUND, - "advanced", - "budget", - "codec", - "error", - "protocol"), - - /** - * The SockJS fallback endpoint. - * - *

Its own module because registering a fallback endpoint means holding Spring's WebSocket - * configuration, and folding that into {@code advanced} would relax purity for every capability - * in it. The profile that decides which transports are offered stays pure and lives there; only - * the registration is here. - */ - ADVANCED_SOCKJS( - "advanced-sockjs", - "advanced.sockjs", - WebSocketModulePurity.FRAMEWORK_BOUND, - "advanced", - "core", - "security"), - - /** - * The RabbitMQ broker relay and the multi-node user destination that depends on it. - * - *

Separated from {@code advanced-stomp} because it is a different operational decision with a - * different blast radius. The adapter parses a protocol; the relay opens a TCP connection to - * somebody else's broker and makes every delivery depend on it staying up. - */ - ADVANCED_STOMP_RABBIT( - "advanced-stomp-rabbit", - "advanced.stomp.rabbit", - WebSocketModulePurity.FRAMEWORK_BOUND, - "advanced", - "advanced-stomp", - "core", - "security"), - - /** - * The pre-existing STOMP-over-SockJS live-push channel. - * - *

Not part of the design's platform, and declared here so the boundary is complete rather than - * excused. The design specifies a raw WebSocket platform; this is separate, older machinery that - * predates it and still ships. - * - *

It declares no edge to any platform module, and no platform module declares an edge to it. - * That is the point of listing it: the two are independent, and the enum is where somebody who - * later wires them together has to say so. It is also why the Advanced adapter above does not - * extend it — see {@code StompBrokerExclusivity} for why only one of the two may run. - */ - STOMP("stomp", "stomp", WebSocketModulePurity.FRAMEWORK_BOUND), - - /** - * What the Stable platform must show before it is promoted, and the two scenarios that show it. - * - *

CORE, and a leaf: it names no other module. That is deliberate rather than incidental. A - * gate that imported the parts it gates would be satisfiable by construction — the evidence would - * be whatever the platform happens to produce, checked against a list derived from the same - * source. These are predicates over facts a release engineer supplies, so a missing runtime is a - * missing runtime and not a module that failed to register itself. - */ - RELEASE("release", "release", WebSocketModulePurity.CORE), - - /** The declared module map and its machine-checked identity. */ - MODULE_BOUNDARY("moduleboundary", "moduleboundary", WebSocketModulePurity.CORE); - - private final String id; - private final String packageName; - private final WebSocketModulePurity purity; - - /** - * Populated only from {@link Set#of}, which is genuinely immutable. Error Prone's {@code - * ImmutableEnumChecker} recognises Guava's {@code ImmutableSet} but not the JDK's unmodifiable - * factories, and this leaf has no Guava dependency to add for one field. The same suppression, - * for the same reason, sits on {@code WebStableModule}. - */ - @SuppressWarnings("ImmutableEnumChecker") - private final Set allowedEdges; - - WebSocketStableModule( - String id, String packageName, WebSocketModulePurity purity, String... allowedEdges) { - this.id = id; - this.packageName = packageName; - this.purity = purity; - this.allowedEdges = Set.of(allowedEdges); - } - - /** The module's identity. */ - public String id() { - return id; - } - - /** The package that carries it, relative to the platform root. */ - public String packageName() { - return packageName; - } - - /** Whether it may name a framework type. */ - public WebSocketModulePurity purity() { - return purity; - } - - /** The modules it may import. */ - public Set allowedEdges() { - return allowedEdges; - } - - /** Every declared module id. */ - public static Set moduleIds() { - return Arrays.stream(values()).map(WebSocketStableModule::id).collect(Collectors.toSet()); - } - - /** The ids of the modules that may not name a framework type. */ - public static Set coreModuleIds() { - return Arrays.stream(values()) - .filter(module -> module.purity() == WebSocketModulePurity.CORE) - .map(WebSocketStableModule::id) - .collect(Collectors.toSet()); - } - - /** The declared edge set, by module id. */ - public static Map> dependencyEdges() { - Map> edges = new TreeMap<>(); - for (WebSocketStableModule module : values()) { - edges.put(module.id(), module.allowedEdges()); - } - return Map.copyOf(edges); - } - - /** The package each module lives in, by module id. */ - public static Map packagesById() { - Map packages = new LinkedHashMap<>(); - for (WebSocketStableModule module : values()) { - packages.put(module.id(), module.packageName()); - } - return Map.copyOf(packages); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/observability/SafeWebSocketLogFields.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/observability/SafeWebSocketLogFields.java deleted file mode 100644 index dc2735e9..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/observability/SafeWebSocketLogFields.java +++ /dev/null @@ -1,65 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.observability; - -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketConnectionContext; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Objects; - -/** - * What may be written about a connection, and nothing else. - * - *

Log volume is the part that surprises people. An HTTP request logs once; a connection can log - * on every message for hours, so a field that is merely unwise in a request log is written - * thousands of times here, into a store with a retention policy nobody chose for it. - * - *

So the payload is never logged — not truncated, not redacted, not at debug. A payload log - * behind a debug flag is a payload log the first time somebody debugs a production incident, and - * that is exactly when the data is most sensitive and the flag most likely to be left on. - * - *

The actor appears only as its short fingerprint. That is enough to correlate two connections - * as the same caller while reading, and not enough to name them. - */ -public final class SafeWebSocketLogFields { - - private SafeWebSocketLogFields() {} - - /** - * The fields describing one connection. - * - * @param context the connection - */ - public static Map of(WebSocketConnectionContext context) { - Objects.requireNonNull(context, "context"); - Map fields = new LinkedHashMap<>(); - fields.put("connectionId", context.connectionId().value()); - fields.put("endpoint", context.endpoint().value()); - fields.put("nodeId", context.nodeId().value()); - fields.put("state", context.state().name()); - // Short form, not the whole digest: enough to correlate while reading, and obviously not the - // identity itself. - fields.put("actor", context.actor().shortForm()); - context.subprotocol().ifPresent(name -> fields.put("subprotocol", name.value())); - return Map.copyOf(fields); - } - - /** - * Whether a field name is safe to log for a connection. - * - *

Used by a review check rather than at runtime. The runtime path builds its fields from - * {@link #of}, so there is nothing to filter; this exists so a new log statement elsewhere can be - * checked against the same rule. - */ - public static boolean safeFieldName(String name) { - if (name == null) { - return false; - } - String lower = name.toLowerCase(java.util.Locale.ROOT); - return !(lower.contains("payload") - || lower.contains("body") - || lower.contains("token") - || lower.contains("ticket") - || lower.contains("cookie") - || lower.contains("credential") - || lower.contains("authorization")); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/observability/WebSocketMetricTags.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/observability/WebSocketMetricTags.java deleted file mode 100644 index bb6747db..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/observability/WebSocketMetricTags.java +++ /dev/null @@ -1,76 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.observability; - -import java.util.Locale; -import java.util.Set; - -/** - * Which tags a WebSocket metric may carry. - * - *

An allowlist, and the cardinality risk here is worse than for HTTP. A request produces one - * observation and is gone; a connection produces observations for hours, and a tag carrying the - * connection id turns one time series into one per connection that ever existed — the series - * outlive the connections, so the count only ever grows. - * - *

{@code nodeId} is on the list and the connection and session identifiers are not, for exactly - * that reason: a fleet has a knowable number of nodes and an unbounded number of connections. - */ -public final class WebSocketMetricTags { - - /** The complete set of tags a WebSocket metric may carry. */ - private static final Set ALLOWED = - Set.of( - "endpoint", - "nodeId", - "subprotocol", - "closeCode", - "failureCategory", - "messageType", - "direction", - "outcome"); - - private WebSocketMetricTags() {} - - /** Whether a tag may be recorded. */ - public static boolean allowed(String name) { - return name != null && ALLOWED.contains(name); - } - - /** The complete allowlist. */ - public static Set allowedTags() { - return ALLOWED; - } - - /** - * Refuses a tag that is not on the allowlist. - * - * @throws IllegalArgumentException when it is not allowed - */ - public static void require(String name) { - if (!allowed(name)) { - throw new IllegalArgumentException( - "metric tag '" - + name - + "' is not on the allowlist " - + ALLOWED - + "; a connection produces observations for hours, so an unbounded tag creates" - + " series that outlive the connections and never stop accumulating"); - } - } - - /** Whether a name is one that must never be a tag. */ - public static boolean obviouslyUnbounded(String name) { - if (name == null) { - return false; - } - String lower = name.toLowerCase(Locale.ROOT); - return lower.contains("connection") - || lower.contains("session") - || lower.contains("actor") - || lower.contains("user") - || lower.contains("tenant") - || lower.contains("correlation") - || lower.contains("stream") - || lower.contains("payload") - || lower.contains("ticket"); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/ordering/GapDetector.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/ordering/GapDetector.java deleted file mode 100644 index f8c85677..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/ordering/GapDetector.java +++ /dev/null @@ -1,98 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.ordering; - -import java.util.Map; -import java.util.Objects; -import java.util.concurrent.ConcurrentHashMap; - -/** - * Notices when a stream skipped, reordered or repeated a position. - * - *

Server-side, and that is deliberate. Detecting a gap on the client tells the client something - * went wrong; detecting it here tells the operator, and the operator is the one who can fix it. A - * conflating queue, a dropped droppable message and a genuine bug all look identical from the - * client's side, and only the server knows which happened. - * - *

The three outcomes are distinguished because they mean different things. {@link - * Observation#GAP} under a lossy profile is expected and under a total-order profile is a defect; - * {@link Observation#REORDERED} means something wrote out of order, which no profile permits; - * {@link Observation#DUPLICATE} means a retry was not deduplicated. - */ -public final class GapDetector { - - /** What a sequence number turned out to be. */ - public enum Observation { - - /** Exactly the next position. */ - IN_ORDER, - - /** Ahead of the next position: something in between was not delivered. */ - GAP, - - /** Behind the last position: something arrived out of order. */ - REORDERED, - - /** The same position twice. */ - DUPLICATE - } - - private final Map lastSeen = new ConcurrentHashMap<>(); - - /** - * Records a position and says what it was. - * - * @param streamId which stream - * @param sequence the position observed - */ - public Observation observe(String streamId, long sequence) { - Objects.requireNonNull(streamId, "streamId"); - // Computed atomically. A read-then-write would let two observations on one stream interleave - // and report a gap that is really a race in the detector. - Observation[] result = new Observation[1]; - lastSeen.compute( - streamId, - (id, previous) -> { - if (previous == null) { - result[0] = Observation.IN_ORDER; - return sequence; - } - if (sequence == previous + 1) { - result[0] = Observation.IN_ORDER; - return sequence; - } - if (sequence == previous) { - result[0] = Observation.DUPLICATE; - return previous; - } - if (sequence < previous) { - result[0] = Observation.REORDERED; - // The high-water mark is kept, not lowered. Lowering it would report every subsequent - // in-order message as a duplicate. - return previous; - } - result[0] = Observation.GAP; - return sequence; - }); - return result[0]; - } - - /** - * How many positions were skipped, for a gap. - * - * @param streamId which stream - * @param sequence the position observed - */ - public long gapSize(String streamId, long sequence) { - Long previous = lastSeen.get(streamId); - return previous == null || sequence <= previous ? 0 : sequence - previous - 1; - } - - /** The last position seen on a stream. */ - public long lastSeen(String streamId) { - return lastSeen.getOrDefault(streamId, 0L); - } - - /** Forgets a stream, so the map does not grow with churn. */ - public void forget(String streamId) { - lastSeen.remove(streamId); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/ordering/OrderingProfile.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/ordering/OrderingProfile.java deleted file mode 100644 index 1cdfab35..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/ordering/OrderingProfile.java +++ /dev/null @@ -1,54 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.ordering; - -/** - * What ordering a stream actually promises. - * - *

Declared per stream rather than assumed, because a WebSocket makes the strongest guarantee - * look free and it is not. The transport delivers frames on one connection in order, so a naive - * reading is that everything is ordered — but a reconnect starts a new connection, and anything the - * server produced concurrently was never ordered to begin with. A client that assumed total order - * is wrong at exactly the moment it reconnects, which is the moment it is least able to notice. - * - *

Saying which promise applies also tells the client what to do about a gap, and the answers are - * different: under {@link #PER_STREAM_TOTAL} a gap means resynchronise, under {@link #BEST_EFFORT} - * it means nothing at all. - */ -public enum OrderingProfile { - - /** - * No ordering promise. - * - *

Right for independent notifications. A client must not gap-detect on these, and this profile - * exists so it can tell. - */ - BEST_EFFORT, - - /** - * Every message on one stream arrives once, in order, with no gaps. - * - *

The strongest promise this platform makes, and it is per stream rather than per connection. - * Across a reconnect it holds only if the client resumes from its last sequence, which is what - * the sequence number is for. - */ - PER_STREAM_TOTAL, - - /** - * In order, but messages may be skipped. - * - *

The honest profile for a conflated stream: the client always moves forward and never sees an - * older value after a newer one, but it will not see every value. Without this as a distinct - * profile a conflated stream has to claim either total order — which conflation breaks — or best - * effort, which understates what it does give. - */ - MONOTONIC_LOSSY; - - /** Whether a client should treat a missing sequence as a problem. */ - public boolean gapsAreErrors() { - return this == PER_STREAM_TOTAL; - } - - /** Whether a client may rely on never seeing an older message after a newer one. */ - public boolean monotonic() { - return this != BEST_EFFORT; - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/ordering/StreamSequencer.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/ordering/StreamSequencer.java deleted file mode 100644 index c814f6a2..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/ordering/StreamSequencer.java +++ /dev/null @@ -1,54 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.ordering; - -import java.util.Map; -import java.util.Objects; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.atomic.AtomicLong; - -/** - * Assigns sequence numbers, one counter per stream. - * - *

Per stream rather than per connection, because the number is what a client resumes from after - * a reconnect. A connection-scoped counter restarts at zero on the new connection, and the client's - * "resume from 4210" then either replays from the beginning or is rejected — neither of which is a - * resume. - * - *

Sequences start at 1. Zero is the value an uninitialised field has, so starting there makes - * "never sent anything" and "sent the first message" the same observation on the client's side. - */ -public final class StreamSequencer { - - private final Map counters = new ConcurrentHashMap<>(); - - /** - * The next position on a stream. - * - * @param streamId which stream - */ - public long next(String streamId) { - Objects.requireNonNull(streamId, "streamId"); - return counters.computeIfAbsent(streamId, id -> new AtomicLong()).incrementAndGet(); - } - - /** The last position issued for a stream, or 0 when none has been. */ - public long current(String streamId) { - AtomicLong counter = counters.get(streamId); - return counter == null ? 0 : counter.get(); - } - - /** - * Forgets a stream. - * - *

Called when the last subscriber leaves. Without it the counter map grows with the number of - * streams that ever existed rather than the number in use — the same churn-proportional leak the - * session registry has to avoid. - */ - public void forget(String streamId) { - counters.remove(streamId); - } - - /** How many streams are being tracked. */ - public int trackedStreams() { - return counters.size(); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/outbound/OutboundQueue.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/outbound/OutboundQueue.java index 3c384985..d0b51ebe 100644 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/outbound/OutboundQueue.java +++ b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/outbound/OutboundQueue.java @@ -75,8 +75,7 @@ public final class OutboundQueue { if (superseded != null) { // Replaced in place rather than appended, so the queue holds one entry per key instead of // a history the peer will never catch up with. - replace(superseded, message); - return OutboundEnqueueResult.CONFLATED; + return replace(superseded, message); } } @@ -190,22 +189,24 @@ public final class OutboundQueue { return OutboundEnqueueResult.DROPPED; } - private void replace(OutboundMessage superseded, OutboundMessage replacement) { - Deque lane = lanes.get(superseded.priority()); - lane.remove(superseded); + private OutboundEnqueueResult replace(OutboundMessage superseded, OutboundMessage replacement) { + lanes.get(superseded.priority()).remove(superseded); + conflatable.remove(superseded.conflationKey().orElseThrow()); globalBudget.release(superseded.byteCount()); bufferedBytes -= superseded.byteCount(); retainedBytes -= superseded.byteCount(); - // Reserved for the replacement before it is queued. Assuming the sizes match would let a - // growing conflated value drift past both bounds one byte at a time. - if (globalBudget.reserve(replacement.byteCount())) { - lanes.get(replacement.priority()).addLast(replacement); - bufferedBytes += replacement.byteCount(); - retainedBytes += replacement.byteCount(); - conflatable.put(replacement.conflationKey().orElseThrow(), replacement); - } else { - conflatable.remove(superseded.conflationKey().orElseThrow()); + // Reserved for the replacement against both bounds before it is queued. Assuming the sizes + // match would let a growing conflated value drift past them one byte at a time. When it does + // not fit, both values are gone and the caller is told so rather than hearing CONFLATED. + int bytes = replacement.byteCount(); + if (retainedBytes + bytes > maxBytes || !globalBudget.reserve(bytes)) { droppedMessages++; + return OutboundEnqueueResult.DROPPED; } + lanes.get(replacement.priority()).addLast(replacement); + bufferedBytes += bytes; + retainedBytes += bytes; + conflatable.put(replacement.conflationKey().orElseThrow(), replacement); + return OutboundEnqueueResult.CONFLATED; } } diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/outbound/SerializedOutboundWriter.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/outbound/SerializedOutboundWriter.java index 6d2210d1..962130ba 100644 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/outbound/SerializedOutboundWriter.java +++ b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/outbound/SerializedOutboundWriter.java @@ -103,58 +103,75 @@ public final class SerializedOutboundWriter { /** * Writes whatever is queued, if nobody else is already writing. * - *

Returns immediately when another thread holds the writer. That thread will pick up what was - * just queued before it finishes, so nothing is stranded — and the caller is not parked on a slow - * peer's socket. + *

Returns immediately when another thread holds the writer, and the caller is not parked on a + * slow peer's socket. Nothing is stranded because the holder looks at the queue again after it + * releases the lock: a message queued between its last poll and its unlock would otherwise wait + * for an unrelated future offer, since its producer's {@code tryLock} failed. */ public void drain() { - if (closed.get() || !writeLock.tryLock()) { - return; + while (!closed.get() && writeLock.tryLock()) { + try { + writeQueued(); + } finally { + writeLock.unlock(); + } + if (!hasQueued()) { + return; + } } + } + + private boolean hasQueued() { + queueLock.lock(); try { - while (true) { - Optional next; - // Polled under the queue lock and written outside it, so a slow write never holds the - // queue. + return queue.size() > 0; + } finally { + queueLock.unlock(); + } + } + + /** Called with the write lock held. */ + private void writeQueued() { + while (true) { + Optional next; + // Polled under the queue lock and written outside it, so a slow write never holds the + // queue. + queueLock.lock(); + try { + next = queue.poll(); + } finally { + queueLock.unlock(); + } + if (next.isEmpty()) { + return; + } + OutboundMessage message = next.get(); + try { + sink.write(message.payload()); + written++; + } catch (Exception refused) { + failed++; + // Stop at the first failure. Continuing would write the rest of the queue into a socket + // that has already refused one message, and on a half-closed connection those writes + // succeed silently into nothing. + closed.set(true); queueLock.lock(); try { - next = queue.poll(); + queue.discardAll(); } finally { queueLock.unlock(); } - if (next.isEmpty()) { - return; - } - OutboundMessage message = next.get(); + return; + } finally { + // A polled payload is still retained while sink.write blocks, so both its connection and + // node-wide reservations end only when that write attempt has completed. + queueLock.lock(); try { - sink.write(message.payload()); - written++; - } catch (Exception refused) { - failed++; - // Stop at the first failure. Continuing would write the rest of the queue into a socket - // that has already refused one message, and on a half-closed connection those writes - // succeed silently into nothing. - closed.set(true); - queueLock.lock(); - try { - queue.discardAll(); - } finally { - queueLock.unlock(); - } - return; + queue.releaseInFlight(message); } finally { - // A polled payload is still retained while sink.write blocks, so both its connection and - // node-wide reservations end only when that write attempt has completed. - queueLock.lock(); - try { - queue.releaseInFlight(message); - } finally { - queueLock.unlock(); - } + queueLock.unlock(); } } - } finally { - writeLock.unlock(); } } diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/protocol/WebSocketCatalogFingerprint.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/protocol/WebSocketCatalogFingerprint.java deleted file mode 100644 index e5fbda74..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/protocol/WebSocketCatalogFingerprint.java +++ /dev/null @@ -1,64 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.protocol; - -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.HexFormat; -import java.util.List; -import java.util.Objects; - -/** - * A digest of the published catalog, for detecting drift between two deployments. - * - *

Two nodes serving the same subprotocol version and different catalogs is the failure this - * exists to make visible. It happens during every rolling deploy and is normally harmless — until a - * client connects to the new node, subscribes to a type the old node does not know, reconnects to - * the old node, and receives an error for a type the API says exists. - * - *

The fingerprint is over the published surface only: the type name, its family, its direction - * and its major version. Not the minor, because a minor bump is additive and both nodes can serve - * it — making the fingerprint change on an additive release would report drift on every deploy and - * teach everyone to ignore it. - * - * @param value a hex digest of the catalog's published surface - */ -public record WebSocketCatalogFingerprint(String value) { - - public WebSocketCatalogFingerprint { - Objects.requireNonNull(value, "value"); - if (value.length() != 64) { - throw new IllegalArgumentException("a catalog fingerprint is a 64-character hex digest"); - } - } - - /** - * The fingerprint of a set of descriptors. - * - * @param descriptors every published message type - */ - public static WebSocketCatalogFingerprint of(List descriptors) { - Objects.requireNonNull(descriptors, "descriptors"); - // Sorted, so two nodes that registered the same types in different orders agree. Without this - // the fingerprint reports drift caused by bean ordering. - List lines = - descriptors.stream() - .map( - descriptor -> - descriptor.type().value() - + '\u001f' - + descriptor.family() - + '\u001f' - + descriptor.direction() - + '\u001f' - + descriptor.schemaVersion().major()) - .sorted() - .toList(); - try { - MessageDigest digest = MessageDigest.getInstance("SHA-256"); - lines.forEach(line -> digest.update(line.getBytes(StandardCharsets.UTF_8))); - return new WebSocketCatalogFingerprint(HexFormat.of().formatHex(digest.digest())); - } catch (NoSuchAlgorithmException impossible) { - throw new IllegalStateException("SHA-256 is required of every JVM", impossible); - } - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/protocol/WebSocketCodecProfile.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/protocol/WebSocketCodecProfile.java deleted file mode 100644 index 844d524d..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/protocol/WebSocketCodecProfile.java +++ /dev/null @@ -1,17 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.protocol; - -/** - * How a message is encoded on the wire. - * - *

One member in Stable, and that is the decision rather than an oversight. A second codec - * doubles the decode surface, and the decode path is where a hostile frame is cheapest to exploit — - * every additional format is another parser reachable before authentication has been re-checked. - * - *

The enum exists so that adding one later is a visible change with a reviewed name, instead of - * a content-type string appearing in a handler. - */ -public enum WebSocketCodecProfile { - - /** UTF-8 JSON text frames. */ - JSON -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/protocol/WebSocketCorrelationId.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/protocol/WebSocketCorrelationId.java deleted file mode 100644 index 693a6bce..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/protocol/WebSocketCorrelationId.java +++ /dev/null @@ -1,36 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.protocol; - -import java.util.Objects; -import java.util.regex.Pattern; - -/** - * Which earlier message this one answers. - * - *

A separate type from {@link WebSocketMessageId} even though the grammars match. On a - * connection that multiplexes many in-flight requests, mixing up "my identity" and "what I am - * answering" routes a response to the wrong waiter — and the symptom is one caller receiving - * another's data, which is a disclosure rather than a bug. - * - * @param value the identifier of the message being answered - */ -public record WebSocketCorrelationId(String value) { - - private static final Pattern GRAMMAR = Pattern.compile("[A-Za-z0-9_-]{1,64}"); - - public WebSocketCorrelationId { - Objects.requireNonNull(value, "value"); - if (!GRAMMAR.matcher(value).matches()) { - throw new IllegalArgumentException("a correlation id must match [A-Za-z0-9_-]{1,64}"); - } - } - - /** The correlation that answers a given message. */ - public static WebSocketCorrelationId answering(WebSocketMessageId messageId) { - return new WebSocketCorrelationId(messageId.value()); - } - - @Override - public String toString() { - return value; - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/protocol/WebSocketEnvelope.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/protocol/WebSocketEnvelope.java deleted file mode 100644 index 95de3d7c..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/protocol/WebSocketEnvelope.java +++ /dev/null @@ -1,150 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.protocol; - -import java.time.Instant; -import java.util.Objects; -import java.util.Optional; - -/** - * One message on the wire, with the fields its family is allowed to carry and no others. - * - *

The payload is a {@code String} — the encoded document — rather than a {@code Map} or an - * {@code Object}. That is the design's rule and it is worth stating why, because a map is the - * obvious and wrong choice: it accepts any shape, so nothing is validated until some handler - * reaches for a key that is not there; it makes an entity or a document trivially serializable - * straight onto the wire, which publishes the storage schema; and it is where unbounded nesting - * arrives, because a map has no depth of its own. - * - *

Keeping the payload opaque here forces decoding to happen in one place, against a declared - * type from a closed catalog, with the budget applied. The envelope's job is routing, and routing - * needs the type name and the correlation, not the content. - * - *

The constructor refuses every field a family may not carry. Those are not tidiness rules: a - * {@code sequence} on an unordered family invites gap detection on something nobody ordered, and an - * {@code expiresAt} on a response is a deadline the sender cannot act on. - * - * @param messageId this message's identity - * @param family what kind of message it is - * @param type the published shape name - * @param correlationId which message this answers, for families that answer - * @param streamId which ordered stream it belongs to, for orderable families - * @param sequence its position in that stream - * @param expiresAt when a command stops being worth executing - * @param payload the encoded document, opaque at this layer - */ -public record WebSocketEnvelope( - WebSocketMessageId messageId, - WebSocketMessageFamily family, - WebSocketMessageType type, - Optional correlationId, - Optional streamId, - Optional sequence, - Optional expiresAt, - Optional payload) { - - public WebSocketEnvelope { - Objects.requireNonNull(messageId, "messageId"); - Objects.requireNonNull(family, "family"); - Objects.requireNonNull(type, "type"); - Objects.requireNonNull(correlationId, "correlationId"); - Objects.requireNonNull(streamId, "streamId"); - Objects.requireNonNull(sequence, "sequence"); - Objects.requireNonNull(expiresAt, "expiresAt"); - Objects.requireNonNull(payload, "payload"); - - if (family.requiresCorrelation() && correlationId.isEmpty()) { - throw new IllegalArgumentException( - family + " answers an earlier message and must name it, or the waiter never resolves"); - } - if (!family.orderable() && (streamId.isPresent() || sequence.isPresent())) { - throw new IllegalArgumentException( - family - + " is not an ordered family; a sequence here invites gap detection on something" - + " nobody ordered, and the missing-message alarms are about nothing"); - } - if (family.orderable() && streamId.isPresent() != sequence.isPresent()) { - // Half of an ordering is not an ordering: a stream without positions cannot be gap-checked, - // and a position without a stream cannot be compared to anything. - throw new IllegalArgumentException( - "a stream id and a sequence are meaningless apart; " + family + " has only one"); - } - if (!family.expirable() && expiresAt.isPresent()) { - throw new IllegalArgumentException( - family + " has no deadline the sender could act on; only a command expires"); - } - if (!family.carriesPayload() && payload.isPresent()) { - throw new IllegalArgumentException(family + " carries no payload"); - } - sequence.ifPresent( - value -> { - if (value < 0) { - throw new IllegalArgumentException("a sequence position cannot be negative"); - } - }); - streamId.ifPresent( - value -> { - if (value.isBlank() || value.length() > 64) { - throw new IllegalArgumentException( - "a stream id must be non-blank and at most 64 characters"); - } - }); - } - - /** A command, optionally with a deadline. */ - public static WebSocketEnvelope command( - WebSocketMessageId messageId, WebSocketMessageType type, String payload, Instant expiresAt) { - return new WebSocketEnvelope( - messageId, - WebSocketMessageFamily.COMMAND, - type, - Optional.empty(), - Optional.empty(), - Optional.empty(), - Optional.ofNullable(expiresAt), - Optional.of(payload)); - } - - /** The answer to a command. */ - public static WebSocketEnvelope response( - WebSocketMessageId messageId, - WebSocketMessageType type, - WebSocketCorrelationId correlationId, - String payload) { - return new WebSocketEnvelope( - messageId, - WebSocketMessageFamily.RESPONSE, - type, - Optional.of(correlationId), - Optional.empty(), - Optional.empty(), - Optional.empty(), - Optional.of(payload)); - } - - /** An event, optionally positioned in a stream. */ - public static WebSocketEnvelope event( - WebSocketMessageId messageId, - WebSocketMessageType type, - String streamId, - Long sequence, - String payload) { - return new WebSocketEnvelope( - messageId, - WebSocketMessageFamily.EVENT, - type, - Optional.empty(), - Optional.ofNullable(streamId), - Optional.ofNullable(sequence), - Optional.empty(), - Optional.of(payload)); - } - - /** - * Whether a command has outlived its deadline. - * - *

Checked before the handler runs, never after. A client that gave up waiting has usually - * retried, and executing both is exactly the duplicate the deadline exists to prevent. - */ - public boolean expiredAt(Instant now) { - return expiresAt.map(deadline -> !now.isBefore(deadline)).orElse(false); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/protocol/WebSocketMessageCatalog.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/protocol/WebSocketMessageCatalog.java deleted file mode 100644 index 52af68ea..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/protocol/WebSocketMessageCatalog.java +++ /dev/null @@ -1,100 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.protocol; - -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -/** - * Every message type this deployment publishes, fixed at startup. - * - *

Closed, and that is the security property rather than a style preference. A decoder that - * resolves an arbitrary type name from the wire can be asked to resolve one nobody intended; a - * decoder that looks a name up in this catalog and refuses a miss cannot. Unknown types are - * rejected at the protocol boundary and never reach an application handler. - * - *

Duplicates fail at startup for the same reason two endpoints on one path do: which descriptor - * wins would be decided by registration order, and the loser is silently unreachable. - */ -public final class WebSocketMessageCatalog { - - private final Map byType; - private final WebSocketCatalogFingerprint fingerprint; - - private WebSocketMessageCatalog( - Map byType, - WebSocketCatalogFingerprint fingerprint) { - this.byType = byType; - this.fingerprint = fingerprint; - } - - /** - * A catalog over the published descriptors. - * - * @param descriptors every message type this deployment publishes - * @throws IllegalArgumentException when a type is declared twice - */ - public static WebSocketMessageCatalog of(List descriptors) { - Objects.requireNonNull(descriptors, "descriptors"); - Map byType = new LinkedHashMap<>(); - for (WebSocketMessageDescriptor descriptor : descriptors) { - if (byType.putIfAbsent(descriptor.type(), descriptor) != null) { - throw new IllegalArgumentException( - "message type " - + descriptor.type() - + " is declared twice; which descriptor wins would be decided by registration" - + " order and the other would be silently unreachable"); - } - } - return new WebSocketMessageCatalog( - Map.copyOf(byType), WebSocketCatalogFingerprint.of(List.copyOf(byType.values()))); - } - - /** The descriptor for a type, if it is published. */ - public Optional find(WebSocketMessageType type) { - return Optional.ofNullable(byType.get(type)); - } - - /** - * Whether a client may send this type. - * - *

The check that runs before decoding, on every inbound message. An unpublished type and a - * server-only type get the same answer: a client learns nothing about what exists that it may not - * use. - */ - public boolean acceptsFromClient(WebSocketMessageType type) { - return find(type).map(descriptor -> descriptor.direction().acceptsFromClient()).orElse(false); - } - - /** Whether the server may send this type. */ - public boolean acceptsFromServer(WebSocketMessageType type) { - return find(type).map(descriptor -> descriptor.direction().acceptsFromServer()).orElse(false); - } - - /** - * The descriptor for an inbound type, or empty when the message must be refused. - * - * @param type the wire type name - * @param family the family the envelope claims - */ - public Optional admitFromClient( - WebSocketMessageType type, WebSocketMessageFamily family) { - return find(type) - .filter(descriptor -> descriptor.direction().acceptsFromClient()) - // The claimed family has to match the published one. A client that could label a command - // as an event would route it past whatever the platform does per family — the expiry check - // and the correlation requirement both key on it. - .filter(descriptor -> descriptor.family() == family); - } - - /** Every published descriptor. */ - public List all() { - return List.copyOf(byType.values()); - } - - /** The digest of this catalog's published surface. */ - public WebSocketCatalogFingerprint fingerprint() { - return fingerprint; - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/protocol/WebSocketMessageDescriptor.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/protocol/WebSocketMessageDescriptor.java deleted file mode 100644 index 34a39e0e..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/protocol/WebSocketMessageDescriptor.java +++ /dev/null @@ -1,40 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.protocol; - -import java.util.Objects; - -/** - * One entry in the published message catalog. - * - *

Binds a wire type name to the family it belongs to and the direction it may travel. Direction - * is not decoration: a client that can send an {@code EVENT} can inject something the server will - * relay to other subscribers as though the server had produced it, and a client that can send a - * {@code RESPONSE} can answer a command it never received. - * - * @param type the published shape name - * @param family what kind of message it is - * @param direction who may send it - * @param schemaVersion the payload schema this type currently carries - */ -public record WebSocketMessageDescriptor( - WebSocketMessageType type, - WebSocketMessageFamily family, - WebSocketMessageDirection direction, - WebSocketSchemaVersion schemaVersion) { - - public WebSocketMessageDescriptor { - Objects.requireNonNull(type, "type"); - Objects.requireNonNull(family, "family"); - Objects.requireNonNull(direction, "direction"); - Objects.requireNonNull(schemaVersion, "schemaVersion"); - if (type.version() != schemaVersion.major()) { - // The wire name carries a version and so does the schema. Letting them disagree means the - // name a client matches on says one thing and the document it receives is another. - throw new IllegalArgumentException( - "the type name declares v" - + type.version() - + " and the schema declares v" - + schemaVersion.major() - + "; a client matching on the name would receive a document of a different shape"); - } - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/protocol/WebSocketMessageDirection.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/protocol/WebSocketMessageDirection.java deleted file mode 100644 index e12060f0..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/protocol/WebSocketMessageDirection.java +++ /dev/null @@ -1,36 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.protocol; - -/** - * Who is allowed to send a message type. - * - *

A WebSocket is symmetric at the transport layer — either end may send any frame at any time — - * and that symmetry is not something an application wants. Without a declared direction a client - * can send an event the server relays to other subscribers as if the server had produced it, or a - * response to a command that was never issued. - */ -public enum WebSocketMessageDirection { - - /** Only the client may send it. */ - CLIENT_TO_SERVER, - - /** Only the server may send it. */ - SERVER_TO_CLIENT, - - /** - * Either end may send it. - * - *

Rare and deliberate: a heartbeat is the honest case. Anything else marked bidirectional is - * usually two message types that have not been separated yet. - */ - BIDIRECTIONAL; - - /** Whether a client may send this type. */ - public boolean acceptsFromClient() { - return this == CLIENT_TO_SERVER || this == BIDIRECTIONAL; - } - - /** Whether the server may send this type. */ - public boolean acceptsFromServer() { - return this == SERVER_TO_CLIENT || this == BIDIRECTIONAL; - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/protocol/WebSocketMessageFamily.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/protocol/WebSocketMessageFamily.java deleted file mode 100644 index 91389cd2..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/protocol/WebSocketMessageFamily.java +++ /dev/null @@ -1,64 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.protocol; - -/** - * What kind of thing a message is, and therefore which envelope fields it may carry. - * - *

A closed family set rather than a free-form type string, because the optional fields on an - * envelope are only meaningful per family. A {@code correlationId} on an event means nothing; a - * {@code sequence} on a command means nothing; an {@code expiresAt} on a response means nothing. - * Without families every field is optional on every message and the receiver has to guess which - * ones it can trust. - */ -public enum WebSocketMessageFamily { - - /** Client asks the server to do something. May be correlated, may expire. */ - COMMAND, - - /** The server's answer to one command. Always correlated. */ - RESPONSE, - - /** The server reports something that happened. May be ordered within a stream. */ - EVENT, - - /** The client subscribes to or unsubscribes from a stream. Always correlated. */ - SUBSCRIPTION, - - /** Liveness. Carries nothing but its own identity. */ - HEARTBEAT, - - /** A typed failure, either as an answer to a command or unsolicited. */ - ERROR; - - /** Whether this family answers an earlier message and must name it. */ - public boolean requiresCorrelation() { - return this == RESPONSE || this == SUBSCRIPTION; - } - - /** - * Whether this family may carry a sequence and a stream. - * - *

Only ordered families. A sequence on a command invites a receiver to reorder or gap-detect - * something the sender never ordered, and the resulting "missing message" alarms are about - * nothing. - */ - public boolean orderable() { - return this == EVENT; - } - - /** - * Whether this family may declare an expiry. - * - *

Commands only. An expired command must be refused before the handler runs — a client that - * gave up waiting has usually retried, and executing both is the duplicate the expiry exists to - * prevent. Nothing else has a deadline that means anything: an event that arrives late is still - * news. - */ - public boolean expirable() { - return this == COMMAND; - } - - /** Whether this family carries an application payload at all. */ - public boolean carriesPayload() { - return this != HEARTBEAT; - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/protocol/WebSocketMessageType.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/protocol/WebSocketMessageType.java deleted file mode 100644 index 96d655cb..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/protocol/WebSocketMessageType.java +++ /dev/null @@ -1,62 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.protocol; - -import java.util.Objects; -import java.util.regex.Pattern; - -/** - * The published name of a message's shape. - * - *

Explicitly not a Java class name. A fully qualified class name on the wire is a published - * contract nobody meant to publish: it tells a client the server's package layout, it breaks every - * client the day a class is renamed or moved, and on the inbound side it is the shape that makes - * deserialization gadget attacks possible — a receiver that resolves a type from a wire string can - * be asked to resolve one the author never considered. - * - *

A dotted, versioned, lowercase name instead. It survives refactoring, it says nothing about - * the server's internals, and it is matched against a closed catalog rather than a class loader. - * - * @param value the published name - */ -public record WebSocketMessageType(String value) { - - private static final Pattern GRAMMAR = - Pattern.compile("[a-z][a-z0-9]*(\\.[a-z][a-z0-9]*)*\\.v[0-9]+"); - - /** Shapes that mean a caller put a Java type name on the wire. */ - private static final Pattern LOOKS_LIKE_A_CLASS_NAME = - Pattern.compile(".*(^|\\.)(java|javax|jakarta|com|org|net|io|dev)\\..*[A-Z].*"); - - public WebSocketMessageType { - Objects.requireNonNull(value, "value"); - if (LOOKS_LIKE_A_CLASS_NAME.matcher(value).matches()) { - throw new IllegalArgumentException( - "'" - + value - + "' looks like a Java class name. A class name on the wire publishes the server's" - + " package layout, breaks every client on a rename, and turns the receiver's type" - + " resolution into an attack surface"); - } - if (!GRAMMAR.matcher(value).matches()) { - throw new IllegalArgumentException( - "a message type must be lowercase, dotted and version-suffixed, like" - + " 'order.placed.v1'; was '" - + value - + "'"); - } - } - - /** The major version this type declares. */ - public int version() { - return Integer.parseInt(value.substring(value.lastIndexOf(".v") + 2)); - } - - /** The name without its version suffix. */ - public String unversionedName() { - return value.substring(0, value.lastIndexOf(".v")); - } - - @Override - public String toString() { - return value; - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/protocol/WebSocketProtocolProfile.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/protocol/WebSocketProtocolProfile.java deleted file mode 100644 index 8c1197ae..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/protocol/WebSocketProtocolProfile.java +++ /dev/null @@ -1,101 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.protocol; - -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketSubprotocolName; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Objects; - -/** - * Which subprotocols an endpoint speaks, and what it does when a client offers none. - * - *

The fallback is the interesting field. RFC 6455 lets a client omit {@code - * Sec-WebSocket-Protocol} entirely, and the server may accept the connection anyway — at which - * point both ends have agreed on nothing and each assumes its own current format. That works until - * the format changes, and then it fails on a connection that has been open long enough for nobody - * to associate the failure with a deploy. - * - *

So a production endpoint must name at least one subprotocol and must refuse a client that - * offers none. A local compatibility profile may accept one, because a developer with a browser - * console and no client library is a real case and the blast radius is one machine. - * - * @param supported the subprotocols this endpoint accepts, in server preference order - * @param codec how messages are encoded - * @param allowUnnegotiatedFallback whether a client offering no subprotocol is accepted - */ -public record WebSocketProtocolProfile( - // A List, not a Set. Preference order is the whole point of this field, and an immutable Set - // does not keep it: Set.copyOf reorders by hash, so the profile silently negotiated whichever - // token happened to come first. - List supported, - WebSocketCodecProfile codec, - boolean allowUnnegotiatedFallback) { - - public WebSocketProtocolProfile { - Objects.requireNonNull(supported, "supported"); - Objects.requireNonNull(codec, "codec"); - supported = List.copyOf(new LinkedHashSet<>(supported)); - if (supported.isEmpty() && !allowUnnegotiatedFallback) { - throw new IllegalArgumentException( - "an endpoint that names no subprotocol and refuses the fallback accepts nothing at all"); - } - } - - /** The Stable production profile: one versioned subprotocol, JSON, no fallback. */ - public static WebSocketProtocolProfile stable() { - return new WebSocketProtocolProfile( - List.of(WebSocketSubprotocolName.stable()), WebSocketCodecProfile.JSON, false); - } - - /** - * A local profile that accepts a browser console with no client library. - * - *

Named for where it belongs. A profile that allowed the fallback silently would be - * indistinguishable from the Stable one in review. - */ - public static WebSocketProtocolProfile localCompatibility() { - return new WebSocketProtocolProfile( - List.of(WebSocketSubprotocolName.stable()), WebSocketCodecProfile.JSON, true); - } - - /** - * The subprotocol to answer a handshake with, or empty when the handshake must be refused. - * - * @param offered what the client sent, in its preference order - */ - public java.util.Optional negotiate( - List offered) { - Objects.requireNonNull(offered, "offered"); - if (offered.isEmpty()) { - // The server may only answer with a token the client offered, so an unnegotiated fallback - // is an accepted connection with no agreed protocol rather than a defaulted one. - return java.util.Optional.empty(); - } - // Server preference, not client preference. The client's order is a request; which format this - // deployment would rather speak is the server's decision, and letting the client choose means - // an old client pins every server to an old format. - for (WebSocketSubprotocolName candidate : supported) { - if (offered.contains(candidate)) { - return java.util.Optional.of(candidate); - } - } - return java.util.Optional.empty(); - } - - /** - * Whether a handshake offering these subprotocols may be accepted. - * - * @param offered what the client sent - */ - public boolean acceptsHandshake(List offered) { - Objects.requireNonNull(offered, "offered"); - if (offered.isEmpty()) { - return allowUnnegotiatedFallback; - } - return negotiate(offered).isPresent(); - } - - /** Whether this profile is safe to serve in production. */ - public boolean productionReady() { - return !supported.isEmpty() && !allowUnnegotiatedFallback; - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/protocol/WebSocketSchemaVersion.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/protocol/WebSocketSchemaVersion.java deleted file mode 100644 index e26518c2..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/protocol/WebSocketSchemaVersion.java +++ /dev/null @@ -1,52 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.protocol; - -import java.util.Objects; - -/** - * The version of a message payload's shape. - * - *

Major and minor, with the difference doing real work. A minor bump is additive — a new - * optional field — and an old client can keep reading. A major bump is not, and a connection that - * negotiated the old major must never be handed the new shape. - * - *

The reason this is separate from the version in the type name: the name's version is what a - * client matches on and cannot change without breaking every client, while the minor here moves - * whenever a field is added. Conflating them would make every additive change a breaking one. - * - * @param major the incompatible version, matching the type name's suffix - * @param minor the additive revision within that major - */ -public record WebSocketSchemaVersion(int major, int minor) { - - public WebSocketSchemaVersion { - if (major < 1) { - throw new IllegalArgumentException("a schema major version starts at 1, was " + major); - } - if (minor < 0) { - throw new IllegalArgumentException("a schema minor version cannot be negative"); - } - } - - /** The first version of a shape. */ - public static WebSocketSchemaVersion v(int major) { - return new WebSocketSchemaVersion(major, 0); - } - - /** - * Whether a peer that understands {@code other} can read a document of this version. - * - *

Same major, and this minor no newer than theirs is trivially fine; this minor *newer* than - * theirs is also fine, because a minor bump only adds optional fields and a strict decoder is - * configured to reject unknown ones — which is why the catalog, not the decoder, has to answer - * this question. - */ - public boolean readableBy(WebSocketSchemaVersion other) { - Objects.requireNonNull(other, "other"); - return major == other.major(); - } - - @Override - public String toString() { - return "v" + major + "." + minor; - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/release/WebSocketNginxProxyProfile.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/release/WebSocketNginxProxyProfile.java deleted file mode 100644 index f74df682..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/release/WebSocketNginxProxyProfile.java +++ /dev/null @@ -1,91 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.release; - -import java.time.Duration; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; - -/** - * What a proxy in front of this platform has to do, stated so it can be checked. - * - *

Written down because a WebSocket behind a proxy fails in ways that look like application bugs. - * The three below have each cost somebody a day. - * - *

The read timeout must exceed the heartbeat. A proxy that closes an idle - * upstream connection after sixty seconds will cut a connection whose heartbeat is every ninety, - * and the server sees a client that vanished while the client sees a server that did. Neither log - * says "proxy". - * - *

{@code Upgrade} and {@code Connection} must be passed explicitly. They are - * hop-by-hop headers, so a proxy drops them by default and the upstream sees an ordinary GET — - * which answers 200 with a body, and the client reports a protocol error against a server that did - * nothing wrong. - * - *

Incoming forwarded headers must be replaced, not appended to. A client can - * send its own {@code X-Forwarded-For}, and a proxy that appends leaves the application trusting - * the first entry — which the client chose. That is a client-controlled client IP, reaching the - * rate limiter and the audit log. - * - * @param proxyReadTimeout how long the proxy holds an idle upstream connection - * @param heartbeatInterval how often the platform writes a keepalive - * @param forwardsUpgradeHeaders whether Upgrade and Connection reach the upstream - * @param sanitizesForwardedHeaders whether client-supplied forwarded headers are replaced - * @param masksCredentialsInAccessLog whether tickets and tokens are kept out of the access log - */ -public record WebSocketNginxProxyProfile( - Duration proxyReadTimeout, - Duration heartbeatInterval, - boolean forwardsUpgradeHeaders, - boolean sanitizesForwardedHeaders, - boolean masksCredentialsInAccessLog) { - - public WebSocketNginxProxyProfile { - Objects.requireNonNull(proxyReadTimeout, "proxyReadTimeout"); - Objects.requireNonNull(heartbeatInterval, "heartbeatInterval"); - if (proxyReadTimeout.isNegative() || heartbeatInterval.isNegative()) { - throw new IllegalArgumentException("a timeout is not negative"); - } - } - - /** A profile that satisfies every requirement. */ - public static WebSocketNginxProxyProfile compliant(Duration heartbeatInterval) { - Objects.requireNonNull(heartbeatInterval, "heartbeatInterval"); - return new WebSocketNginxProxyProfile( - heartbeatInterval.multipliedBy(3), heartbeatInterval, true, true, true); - } - - /** What is wrong with this proxy configuration. */ - public List faults() { - List faults = new ArrayList<>(); - if (proxyReadTimeout.compareTo(heartbeatInterval) <= 0) { - faults.add( - "the proxy read timeout (" - + proxyReadTimeout - + ") is not longer than the heartbeat (" - + heartbeatInterval - + "); the proxy will cut connections the platform believes are healthy, and neither" - + " log will say proxy"); - } - if (!forwardsUpgradeHeaders) { - faults.add( - "Upgrade and Connection are hop-by-hop and are dropped unless forwarded explicitly; the" - + " upstream then sees an ordinary GET and answers 200"); - } - if (!sanitizesForwardedHeaders) { - faults.add( - "client-supplied forwarded headers are appended rather than replaced, so the client" - + " chooses the address the rate limiter and the audit log believe"); - } - if (!masksCredentialsInAccessLog) { - faults.add( - "handshake tickets appear in the access log, which is retained longer and read more" - + " widely than anything else that ever holds a credential"); - } - return List.copyOf(faults); - } - - /** Whether the proxy may front this platform. */ - public boolean compliant() { - return faults().isEmpty(); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/release/WebSocketRollingRestartScenario.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/release/WebSocketRollingRestartScenario.java deleted file mode 100644 index e72709b0..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/release/WebSocketRollingRestartScenario.java +++ /dev/null @@ -1,114 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.release; - -import java.time.Duration; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; - -/** - * What a rolling restart has to demonstrate, in order. - * - *

The order is the content. Every step protects the one after it, and skipping any of them - * produces a restart that looks graceful and is not. - * - *

    - *
  • Readiness goes down first. If it stays up while the node drains, the balancer - * keeps sending connections and the drain never finishes. - *
  • New handshakes are refused. A connection accepted during a drain is one that will be cut - * seconds later. - *
  • The queue drains within the deadline. What is still queued at the deadline is lost, so the - * deadline has to be longer than a full queue takes to write. - *
  • Close is 1001 — going away — rather than 1006. The deployed servlet/lifecycle path uses the - * standard going-away signal for a node that is being drained; 1006 means the client never - * saw a close frame at all. - *
  • Clients reconnect with jitter. Without it every client of the restarted node reconnects in - * the same instant and the replacement is met by the entire population at once. - *
  • No duplicate command is produced. A reconnect that resends an in-flight command needs the - * idempotency ledger to recognise it; if it does not, the restart charged somebody twice. - *
- * - * @param drainDeadline how long the node waits before forcing what remains - * @param expectedCloseCode the code clients must observe - * @param reconnectJitter the spread a compliant client applies - */ -public record WebSocketRollingRestartScenario( - Duration drainDeadline, int expectedCloseCode, Duration reconnectJitter) { - - /** The deployed node-drain close code: RFC 6455 "going away". */ - public static final int RESTART_CLOSE_CODE = 1001; - - public WebSocketRollingRestartScenario { - Objects.requireNonNull(drainDeadline, "drainDeadline"); - Objects.requireNonNull(reconnectJitter, "reconnectJitter"); - if (drainDeadline.isNegative() || drainDeadline.isZero()) { - throw new IllegalArgumentException( - "a drain with no deadline never completes; there is always one client that does not" - + " reconnect"); - } - if (reconnectJitter.isNegative() || reconnectJitter.isZero()) { - throw new IllegalArgumentException( - "without jitter every client of the restarted node reconnects in the same instant"); - } - if (expectedCloseCode != RESTART_CLOSE_CODE) { - throw new IllegalArgumentException( - "a rolling restart closes 1001 because this node is going away; 1006 says the client" - + " never saw a close frame at all"); - } - } - - /** The conventional scenario. */ - public static WebSocketRollingRestartScenario conventional() { - return new WebSocketRollingRestartScenario( - Duration.ofSeconds(30), RESTART_CLOSE_CODE, Duration.ofSeconds(5)); - } - - /** - * What the observed run failed to show. - * - * @param readinessDroppedFirst whether readiness went down before draining began - * @param newHandshakesRefused whether the draining node refused new connections - * @param queueDrainedWithinDeadline whether the outbound queue emptied in time - * @param observedCloseCode the code clients actually saw - * @param clientsJittered whether reconnects were spread - * @param duplicateCommands how many commands were executed twice - */ - public List blockers( - boolean readinessDroppedFirst, - boolean newHandshakesRefused, - boolean queueDrainedWithinDeadline, - int observedCloseCode, - boolean clientsJittered, - int duplicateCommands) { - List blockers = new ArrayList<>(); - if (!readinessDroppedFirst) { - blockers.add( - "readiness stayed up during the drain, so the balancer kept sending connections and the" - + " drain cannot finish"); - } - if (!newHandshakesRefused) { - blockers.add("the draining node accepted a handshake it was about to cut"); - } - if (!queueDrainedWithinDeadline) { - blockers.add( - "the outbound queue did not empty within " + drainDeadline + "; what remains is lost"); - } - if (observedCloseCode != expectedCloseCode) { - blockers.add( - "clients observed close code " - + observedCloseCode - + " rather than " - + expectedCloseCode - + "; they cannot tell 'come back' from 'something broke'"); - } - if (!clientsJittered) { - blockers.add("reconnects were not spread, so the replacement node met the whole population"); - } - if (duplicateCommands > 0) { - blockers.add( - duplicateCommands - + " command(s) executed twice across the reconnect; the idempotency ledger did not" - + " recognise the resend"); - } - return List.copyOf(blockers); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/release/WebSocketStableReleaseGate.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/release/WebSocketStableReleaseGate.java deleted file mode 100644 index ffe126cd..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/release/WebSocketStableReleaseGate.java +++ /dev/null @@ -1,106 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.release; - -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; -import java.util.Set; - -/** - * What the Stable platform must show before it is promoted. - * - *

Distinct from the Advanced gate beside it, and stricter in the one dimension that matters: - * Advanced capabilities are off unless a deployment names them, so a broken one affects whoever - * enabled it. Stable is what every deployment gets, so its evidence has to cover every runtime it - * claims to run on rather than the one the author happened to test. - * - *

{@code advancedAbsentFromArtifact} is the condition that keeps the two apart. If an Advanced - * type reached the Stable artifact, then Stable does not build without Advanced and the separation - * is a naming convention — which is exactly what WS-ARCH-6 refuses at compile time and this refuses - * at release time. Both, because the first catches a source edge and this catches a packaging one. - */ -public record WebSocketStableReleaseGate( - Set requiredRuntimes, - Set requiredSuites, - boolean advancedAbsentFromArtifact, - boolean supportMatrixPublished) { - - /** - * The runtimes Stable claims to support. - * - *

Every one is a real container, because upgrade negotiation, close-frame timing and idle - * handling are container code — a mock dispatcher certifies none of it, and the three containers - * disagree about all three. - */ - public static final Set RUNTIMES = Set.of("tomcat", "jetty", "reactor-netty", "nginx"); - - /** - * The suites whose absence has, at some point, hidden a real defect. - * - *

Not a general list. Commit-response-loss and slow-consumer are named because each covers a - * failure that unit tests reported as passing: a control that existed and was reached by nothing. - */ - public static final Set SUITES = - Set.of( - "websocket:test", - "websocketJettyTest", - "websocketNginxTest", - "commit-response-loss", - "slow-consumer"); - - public WebSocketStableReleaseGate { - requiredRuntimes = Set.copyOf(Objects.requireNonNull(requiredRuntimes, "requiredRuntimes")); - requiredSuites = Set.copyOf(Objects.requireNonNull(requiredSuites, "requiredSuites")); - if (requiredRuntimes.isEmpty() || requiredSuites.isEmpty()) { - throw new IllegalArgumentException( - "a gate requiring no runtime or no suite passes everything, which is worse than no gate" - + " because it reads as one"); - } - } - - /** The standard gate: every claimed runtime, every named suite. */ - public static WebSocketStableReleaseGate standard() { - return new WebSocketStableReleaseGate(RUNTIMES, SUITES, false, false); - } - - /** - * Why the platform may not be promoted yet. - * - * @param verifiedRuntimes the runtimes evidence actually covers - * @param passedSuites the suites that actually passed - */ - public List blockers(Set verifiedRuntimes, Set passedSuites) { - Objects.requireNonNull(verifiedRuntimes, "verifiedRuntimes"); - Objects.requireNonNull(passedSuites, "passedSuites"); - List blockers = new ArrayList<>(); - List missingRuntimes = - requiredRuntimes.stream().filter(r -> !verifiedRuntimes.contains(r)).sorted().toList(); - if (!missingRuntimes.isEmpty()) { - blockers.add( - "no evidence on: " - + missingRuntimes - + "; upgrade negotiation and close-frame timing are container code and the" - + " containers disagree"); - } - List missingSuites = - requiredSuites.stream().filter(s -> !passedSuites.contains(s)).sorted().toList(); - if (!missingSuites.isEmpty()) { - blockers.add("suites not passed: " + missingSuites); - } - if (!advancedAbsentFromArtifact) { - blockers.add( - "an Advanced type is present in the Stable artifact, so Stable does not build without" - + " Advanced and the separation is a naming convention"); - } - if (!supportMatrixPublished) { - blockers.add( - "the support matrix is unpublished; a platform that does not say what it does not" - + " support is read as supporting it"); - } - return List.copyOf(blockers); - } - - /** Whether promotion may proceed. */ - public boolean promotable(Set verifiedRuntimes, Set passedSuites) { - return blockers(verifiedRuntimes, passedSuites).isEmpty(); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/security/WebSocketAuthenticationProfile.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/security/WebSocketAuthenticationProfile.java deleted file mode 100644 index 56aec31c..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/security/WebSocketAuthenticationProfile.java +++ /dev/null @@ -1,57 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.security; - -/** - * How a handshake proves who is connecting. - * - *

The constraint that shapes all of this: a browser's {@code WebSocket} constructor cannot set - * headers. There is no way to send {@code Authorization} from a browser, which is why so many - * WebSocket deployments end up putting a token in the query string — where it lands in access logs, - * in {@code Referer} headers, and in browser history. - * - *

So the profiles here are the three that actually work, and the query-string token is not one - * of them. - */ -public enum WebSocketAuthenticationProfile { - - /** - * A one-time ticket, minted over an authenticated HTTP call and spent at the handshake. - * - *

The right answer for a browser. The ticket is short-lived, single-use and bound to the - * actor, so its appearance in a log is worth nothing by the time anyone reads it — unlike the - * bearer token it stands in for. - */ - ONE_TIME_TICKET, - - /** - * A cookie the browser attaches on its own. - * - *

Works, and brings CSRF with it. A WebSocket handshake is a cross-origin-capable GET that the - * same-origin policy does not protect, so a cookie-authenticated endpoint must check {@code - * Origin} — that check is the entire defence, and there is no preflight to fall back on. - */ - SESSION_COOKIE, - - /** - * An {@code Authorization} header, for a non-browser client. - * - *

Available to server-to-server callers and native apps, which can set headers. Not available - * to a browser, so an endpoint that requires it has decided it is not for browsers. - */ - BEARER_HEADER; - - /** - * Whether this profile is subject to CSRF. - * - *

True exactly when the browser attaches the credential without the page asking. A ticket is - * fetched by the page and a header is set by the client, so neither travels on a cross-origin - * handshake the attacker initiated. - */ - public boolean ambientlyAttached() { - return this == SESSION_COOKIE; - } - - /** Whether a browser can use this profile at all. */ - public boolean browserCapable() { - return this != BEARER_HEADER; - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/security/WebSocketConnectionTicket.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/security/WebSocketConnectionTicket.java deleted file mode 100644 index 884bd320..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/security/WebSocketConnectionTicket.java +++ /dev/null @@ -1,77 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.security; - -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketActorReference; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketEndpointName; -import java.time.Duration; -import java.time.Instant; -import java.util.Objects; -import java.util.regex.Pattern; - -/** - * A single-use credential minted over authenticated HTTP and spent at the handshake. - * - *

It exists because a browser cannot set headers on a {@code WebSocket} constructor. The usual - * workaround is a bearer token in the query string, which then appears in the access log, in the - * {@code Referer} of anything the page loads next, and in browser history — a long-lived credential - * written to three places nobody audits. - * - *

A ticket goes in the same query string and is worth nothing by the time anyone reads it: it - * expires in seconds, it works once, and it is bound to one endpoint and one actor. All three - * bounds are needed. Without single use, a ticket in a log is replayable. Without an endpoint - * binding, a ticket minted for a low-privilege feed opens a privileged one. Without an actor - * binding, it is a bearer token again. - * - * @param value the opaque ticket - * @param actor who it was minted for - * @param endpoint which endpoint it opens - * @param issuedAt when it was minted - * @param expiresAt when it stops working - */ -public record WebSocketConnectionTicket( - String value, - WebSocketActorReference actor, - WebSocketEndpointName endpoint, - Instant issuedAt, - Instant expiresAt) { - - /** How long a ticket may live at most. */ - public static final Duration MAX_LIFETIME = Duration.ofSeconds(30); - - private static final Pattern GRAMMAR = Pattern.compile("[A-Za-z0-9_-]{32,128}"); - - public WebSocketConnectionTicket { - Objects.requireNonNull(value, "value"); - Objects.requireNonNull(actor, "actor"); - Objects.requireNonNull(endpoint, "endpoint"); - Objects.requireNonNull(issuedAt, "issuedAt"); - Objects.requireNonNull(expiresAt, "expiresAt"); - if (!GRAMMAR.matcher(value).matches()) { - // At least 32 characters of URL-safe entropy. A ticket short enough to guess is a ticket an - // attacker mints by trying, and it travels in a query string where rate limiting is coarse. - throw new IllegalArgumentException( - "a connection ticket must be 32-128 URL-safe characters; shorter is guessable and it" - + " travels somewhere that is logged"); - } - if (!expiresAt.isAfter(issuedAt)) { - throw new IllegalArgumentException("a ticket that expires when minted opens nothing"); - } - if (Duration.between(issuedAt, expiresAt).compareTo(MAX_LIFETIME) > 0) { - // The lifetime is what makes a logged ticket harmless. Extend it and the query-string - // exposure the ticket was introduced to fix comes back. - throw new IllegalArgumentException( - "a ticket may live at most " - + MAX_LIFETIME.toSeconds() - + "s; a longer one is a bearer token in a query string again"); - } - } - - /** Whether the ticket is still within its window. */ - public boolean validAt(Instant now) { - return !now.isBefore(issuedAt) && now.isBefore(expiresAt); - } - - /** Whether this ticket opens the given endpoint for the given actor. */ - public boolean opens(WebSocketEndpointName target, WebSocketActorReference caller) { - return endpoint.equals(target) && actor.equals(caller); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/security/WebSocketOriginPolicy.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/security/WebSocketOriginPolicy.java deleted file mode 100644 index c3a8bac4..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/security/WebSocketOriginPolicy.java +++ /dev/null @@ -1,116 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.security; - -import java.util.Locale; -import java.util.Objects; -import java.util.Set; - -/** - * Which origins may open a connection. - * - *

The single most load-bearing check in a cookie-authenticated WebSocket, and the one most often - * left out — because it looks like CORS and is not. The same-origin policy does not apply to a - * WebSocket handshake: a page on any origin can open one to any host, the browser will attach the - * cookies, and there is no preflight and no {@code Access-Control-Allow-Origin} negotiation to - * refuse it. The server checking {@code Origin} itself is the whole defence. - * - *

A missing {@code Origin} header is therefore not the same as an empty one. Browsers always - * send it on a WebSocket handshake; a non-browser client usually sends none. Refusing the absent - * case would lock out every server-to-server caller, and accepting it blindly would let an - * attacker's script omit the header — except a script cannot, which is exactly why the two cases - * are decided separately here. - */ -public final class WebSocketOriginPolicy { - - private final Set allowedOrigins; - private final boolean allowMissingOrigin; - - private WebSocketOriginPolicy(Set allowedOrigins, boolean allowMissingOrigin) { - this.allowedOrigins = allowedOrigins; - this.allowMissingOrigin = allowMissingOrigin; - } - - /** - * A policy for browser clients on known origins. - * - *

A missing origin is refused: every browser sends one, so its absence means the caller is not - * the browser this endpoint is for. - */ - public static WebSocketOriginPolicy browsersOnly(Set origins) { - return new WebSocketOriginPolicy(normalize(origins), false); - } - - /** - * A policy that also admits non-browser clients. - * - *

Only sound where the credential is not ambiently attached. A cookie-authenticated endpoint - * that allowed a missing origin would accept exactly the request a CSRF attack cannot make — and - * would gain nothing, because the attacker's page cannot omit the header anyway. - */ - public static WebSocketOriginPolicy browsersAndServices(Set origins) { - return new WebSocketOriginPolicy(normalize(origins), true); - } - - /** - * Whether a handshake carrying this {@code Origin} may proceed. - * - * @param origin the header value, or null when the client sent none - */ - public boolean permits(String origin) { - if (origin == null || origin.isBlank()) { - return allowMissingOrigin; - } - // Exact match, never a suffix test. `endsWith(".example.com")` admits both - // "evil-example.com" and "example.com.attacker.net". - return allowedOrigins.contains(origin.toLowerCase(Locale.ROOT)); - } - - /** - * Whether this policy is safe for a given authentication profile. - * - *

Read by the startup validator. A cookie profile with an empty allowlist is an endpoint with - * no CSRF defence at all, and it will work perfectly in every test that connects from the same - * origin. - */ - public boolean safeFor(WebSocketAuthenticationProfile profile) { - if (!profile.ambientlyAttached()) { - return true; - } - return !allowedOrigins.isEmpty() && !allowMissingOrigin; - } - - /** The permitted origins. */ - public Set allowedOrigins() { - return allowedOrigins; - } - - private static Set normalize(Set origins) { - Objects.requireNonNull(origins, "origins"); - Set normalized = new java.util.TreeSet<>(); - for (String origin : origins) { - Objects.requireNonNull(origin, "origin"); - String lower = origin.toLowerCase(Locale.ROOT); - if (lower.isBlank()) { - throw new IllegalArgumentException("a blank origin is not an origin"); - } - if (lower.contains("*")) { - // A wildcard reads as "any subdomain" and matches nothing, because origins are compared - // exactly. The entry looks like a policy and is a no-op. - throw new IllegalArgumentException( - "origin '" - + origin - + "' contains a wildcard; origins are compared exactly, so this" - + " matches nothing while reading as though it matches a family"); - } - if (!lower.startsWith("http://") && !lower.startsWith("https://")) { - throw new IllegalArgumentException( - "origin '" + origin + "' must be scheme://host[:port]; a bare host never matches"); - } - if (lower.chars().filter(character -> character == '/').count() != 2) { - throw new IllegalArgumentException( - "origin '" + origin + "' must carry no path or trailing slash"); - } - normalized.add(lower); - } - return Set.copyOf(normalized); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/security/WebSocketTicketStore.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/security/WebSocketTicketStore.java deleted file mode 100644 index 68737e66..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/security/WebSocketTicketStore.java +++ /dev/null @@ -1,32 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.security; - -import java.time.Instant; -import java.util.Optional; - -/** - * Where tickets are held between minting and spending. - * - *

{@link #redeem} both reads and consumes, atomically, and that is the entire contract. A store - * offering a separate lookup would be used as read-then-delete, and two handshakes arriving with - * the same ticket would both find it — which is single-use in name only. Reconnect storms deliver - * exactly those concurrent duplicates. - */ -public interface WebSocketTicketStore { - - /** Records a freshly minted ticket. */ - void issue(WebSocketConnectionTicket ticket); - - /** - * Consumes a ticket, if it exists and has not expired. - * - *

Atomic: a second call with the same value returns empty even if it arrives in the same - * millisecond. - * - * @param value the opaque ticket presented at the handshake - * @param now the current instant - */ - Optional redeem(String value, Instant now); - - /** Drops expired tickets. */ - int purgeExpired(Instant now); -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/servlet/PlatformWebSocketHandler.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/servlet/PlatformWebSocketHandler.java index f0ac0682..366ff318 100644 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/servlet/PlatformWebSocketHandler.java +++ b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/servlet/PlatformWebSocketHandler.java @@ -2,20 +2,21 @@ package dev.caskeleton.adapter.inbound.websocket.servlet; import dev.caskeleton.adapter.inbound.websocket.budget.WebSocketConnectionBudget; import dev.caskeleton.adapter.inbound.websocket.core.WebSocketConnectionId; -import dev.caskeleton.adapter.inbound.websocket.error.WebSocketCloseCode; -import dev.caskeleton.adapter.inbound.websocket.error.WebSocketClosePolicy; -import dev.caskeleton.adapter.inbound.websocket.error.WebSocketFailureCategory; -import dev.caskeleton.adapter.inbound.websocket.inbound.FragmentAssembler; -import dev.caskeleton.adapter.inbound.websocket.inbound.FragmentAssemblyException; import dev.caskeleton.adapter.inbound.websocket.outbound.GlobalBufferBudget; +import dev.caskeleton.adapter.inbound.websocket.outbound.OutboundDelivery; import dev.caskeleton.adapter.inbound.websocket.outbound.OutboundEnqueueResult; +import dev.caskeleton.adapter.inbound.websocket.outbound.OutboundMessage; +import dev.caskeleton.adapter.inbound.websocket.outbound.OutboundPriority; import dev.caskeleton.adapter.inbound.websocket.outbound.OutboundQueue; import dev.caskeleton.adapter.inbound.websocket.outbound.SerializedOutboundWriter; +import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageId; +import java.nio.charset.StandardCharsets; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.function.BiFunction; +import org.springframework.context.SmartLifecycle; import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; @@ -24,23 +25,20 @@ import org.springframework.web.socket.handler.TextWebSocketHandler; /** * The servlet runtime's entry point: container callbacks in, platform values out. * - *

Everything here is translation. The container hands it a session and a message; it hands the - * platform a string and gets back a decision. The platform types that do the deciding — the - * assembler, the queue, the writer — have no idea a servlet exists, which is what lets the same - * decisions serve the reactive runtime and be tested without a container. + *

Everything here is translation. The container hands it a session and a whole text message + * (partial delivery is off, so the container reassembles frames into its own bounded buffer); the + * handler checks the size, hands the application a string and queues its reply. The queue and the + * writer have no idea a servlet exists, which is what lets them be tested without a container. * *

Per-connection state lives in maps keyed by session id rather than in the session's own * attributes. Attributes are a {@code Map} the container also writes to, and - * anything stored there is reachable by every other handler in the application — including a - * fragment assembler holding a partially received message. + * anything stored there is reachable by every other handler in the application. */ -public class PlatformWebSocketHandler extends TextWebSocketHandler - implements org.springframework.context.SmartLifecycle { +public class PlatformWebSocketHandler extends TextWebSocketHandler implements SmartLifecycle { private final WebSocketConnectionBudget budget; private final GlobalBufferBudget globalBudget; private final BiFunction> application; - private final Map assemblers = new ConcurrentHashMap<>(); private final Map writers = new ConcurrentHashMap<>(); private final Map sessions = new ConcurrentHashMap<>(); private volatile boolean running; @@ -64,7 +62,6 @@ public class PlatformWebSocketHandler extends TextWebSocketHandler @Override public void afterConnectionEstablished(WebSocketSession session) { sessions.put(session.getId(), session); - assemblers.put(session.getId(), new FragmentAssembler(budget)); writers.put( session.getId(), new SerializedOutboundWriter( @@ -75,22 +72,20 @@ public class PlatformWebSocketHandler extends TextWebSocketHandler @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { - FragmentAssembler assembler = assemblers.get(session.getId()); - if (assembler == null) { + if (!writers.containsKey(session.getId())) { return; } - Optional whole; - try { - whole = assembler.accept(message.getPayload(), message.isLast()); - } catch (FragmentAssemblyException tooLarge) { - closeFor(session, tooLarge.category(), tooLarge.getMessage()); - return; - } - if (whole.isEmpty()) { + String payload = message.getPayload(); + if (payload.getBytes(StandardCharsets.UTF_8).length > budget.maxMessageBytes()) { + // 1009 rather than a private code: a browser surfaces it with its own wording. + close( + session, + CloseStatus.TOO_BIG_TO_PROCESS, + "a message exceeds " + budget.maxMessageBytes() + " bytes"); return; } application - .apply(connectionId(session), whole.get()) + .apply(connectionId(session), payload) .ifPresent(reply -> writeReply(session, reply)); } @@ -100,7 +95,6 @@ public class PlatformWebSocketHandler extends TextWebSocketHandler // otherwise keep counting bytes for a connection that no longer exists, and the leak is // proportional to churn. sessions.remove(session.getId()); - assemblers.remove(session.getId()); SerializedOutboundWriter writer = writers.remove(session.getId()); if (writer != null) { writer.close(); @@ -151,7 +145,6 @@ public class PlatformWebSocketHandler extends TextWebSocketHandler writers.values().forEach(SerializedOutboundWriter::close); sessions.clear(); writers.clear(); - assemblers.clear(); } @Override @@ -161,9 +154,10 @@ public class PlatformWebSocketHandler extends TextWebSocketHandler @Override public int getPhase() { - // Stopped before the web server, which is the ordering that matters: after the server stops - // there is no connection left to send a close frame on. - return Integer.MIN_VALUE + 1; + // Spring stops the highest phase first. Boot's graceful web-server shutdown runs at + // DEFAULT_PHASE - 1024 and the server stop at DEFAULT_PHASE - 2048, so DEFAULT_PHASE closes + // these connections while the server can still send the close frame. + return SmartLifecycle.DEFAULT_PHASE; } private void writeReply(WebSocketSession session, String reply) { @@ -173,28 +167,25 @@ public class PlatformWebSocketHandler extends TextWebSocketHandler } OutboundEnqueueResult result = writer.offer( - new dev.caskeleton.adapter.inbound.websocket.outbound.OutboundMessage( - new dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageId( - Integer.toHexString(reply.hashCode()) + "-r"), + new OutboundMessage( + new WebSocketMessageId(Integer.toHexString(reply.hashCode()) + "-r"), reply, - dev.caskeleton.adapter.inbound.websocket.outbound.OutboundDelivery.GUARANTEED, - dev.caskeleton.adapter.inbound.websocket.outbound.OutboundPriority.RESPONSE, + OutboundDelivery.GUARANTEED, + OutboundPriority.RESPONSE, Optional.empty())); if (result == OutboundEnqueueResult.CONNECTION_MUST_CLOSE) { - closeFor(session, WebSocketFailureCategory.OVERLOADED, "outbound buffer exhausted"); + // 1013 try again later: a generic client backs off and reconnects instead of waiting for a + // reply that was never queued. + close(session, CloseStatus.SERVICE_OVERLOAD, "outbound buffer exhausted"); } } - private void closeFor( - WebSocketSession session, WebSocketFailureCategory category, String reason) { - WebSocketCloseCode code = - WebSocketClosePolicy.closeCodeFor(category).orElse(WebSocketCloseCode.POLICY_VIOLATION); + private static void close(WebSocketSession session, CloseStatus status, String reason) { try { - // The reason is truncated to 123 bytes because RFC 6455 caps the close frame's reason at - // that, and a container handed a longer one throws while closing — turning a clean refusal - // into an abnormal 1006 the client cannot interpret. - session.close( - new CloseStatus(code.code(), reason.length() > 100 ? reason.substring(0, 100) : reason)); + // The reason is truncated because RFC 6455 caps the close frame's reason at 123 bytes, and a + // container handed a longer one throws while closing — turning a clean refusal into an + // abnormal 1006 the client cannot interpret. + session.close(status.withReason(reason.length() > 100 ? reason.substring(0, 100) : reason)); } catch (Exception alreadyGone) { // The peer closed first. Nothing left to tell it. } diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/session/WebSocketSessionRegistry.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/session/WebSocketSessionRegistry.java deleted file mode 100644 index e0658652..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/session/WebSocketSessionRegistry.java +++ /dev/null @@ -1,163 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.session; - -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketActorReference; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketConnectionContext; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketConnectionId; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketConnectionState; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketEndpointName; -import java.time.Instant; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.atomic.AtomicInteger; - -/** - * The connections this node holds, and only this node. - * - *

Node-local by design, and the name says so because the alternative is the mistake. A registry - * that looked cluster-wide would be asked to deliver a message to a connection on another node, and - * it cannot — the socket is a file descriptor on one machine. Pretending otherwise produces a - * "send" that silently does nothing, which is far worse than an API that never offered it. - * - *

Cross-node delivery is a different problem with a different answer: publish to a bus and let - * each node deliver to its own connections. This registry is the local half of that, and it is - * complete for what it claims. - * - *

The per-actor index exists because the operations that matter are per-actor: disconnect - * everything this user has open, count what they are holding, refuse a new connection when they - * already hold too many. Scanning every connection for those is fine at a hundred and not at a - * hundred thousand. - */ -public final class WebSocketSessionRegistry { - - private final Map byId = - new ConcurrentHashMap<>(); - private final Map> byActor = - new ConcurrentHashMap<>(); - private final Map countByEndpoint = - new ConcurrentHashMap<>(); - private final int maxConnectionsPerActor; - - /** - * A registry with a per-actor cap. - * - * @param maxConnectionsPerActor how many connections one actor may hold on this node - */ - public WebSocketSessionRegistry(int maxConnectionsPerActor) { - if (maxConnectionsPerActor <= 0) { - throw new IllegalArgumentException("a registry that admits nothing holds nothing"); - } - this.maxConnectionsPerActor = maxConnectionsPerActor; - } - - /** - * Registers a newly opened connection. - * - * @return false when this actor already holds its maximum on this node - */ - public boolean register(WebSocketConnectionContext context) { - Objects.requireNonNull(context, "context"); - Map held = - byActor.computeIfAbsent(context.actor(), actor -> new ConcurrentHashMap<>()); - synchronized (held) { - // Synchronized on the per-actor map rather than the whole registry: the check and the insert - // have to be one step or two concurrent handshakes both see room, and a per-actor lock keeps - // one busy actor from serialising every other actor's connects. - if (held.size() >= maxConnectionsPerActor) { - return false; - } - held.put(context.connectionId(), Boolean.TRUE); - } - byId.put(context.connectionId(), context); - countByEndpoint - .computeIfAbsent(context.endpoint(), endpoint -> new AtomicInteger()) - .incrementAndGet(); - return true; - } - - /** Replaces a connection's context, for a state transition. */ - public void update(WebSocketConnectionContext context) { - Objects.requireNonNull(context, "context"); - byId.computeIfPresent(context.connectionId(), (id, existing) -> context); - } - - /** Removes a connection and everything indexed for it. */ - public Optional deregister(WebSocketConnectionId connectionId) { - WebSocketConnectionContext removed = byId.remove(connectionId); - if (removed == null) { - return Optional.empty(); - } - Map held = byActor.get(removed.actor()); - if (held != null) { - synchronized (held) { - held.remove(connectionId); - if (held.isEmpty()) { - // Removed when empty, or the actor index grows without bound across churn — a leak - // proportional to how many distinct users ever connected rather than to how many are - // connected now. - byActor.remove(removed.actor(), held); - } - } - } - countByEndpoint.computeIfPresent( - removed.endpoint(), (endpoint, count) -> count.decrementAndGet() <= 0 ? null : count); - return Optional.of(removed); - } - - /** The connection, if this node holds it. */ - public Optional find(WebSocketConnectionId connectionId) { - return Optional.ofNullable(byId.get(connectionId)); - } - - /** Every connection this actor holds on this node. */ - public List connectionsOf(WebSocketActorReference actor) { - Map held = byActor.get(actor); - if (held == null) { - return List.of(); - } - return held.keySet().stream().map(byId::get).filter(Objects::nonNull).toList(); - } - - /** How many connections an endpoint holds on this node. */ - public int countFor(WebSocketEndpointName endpoint) { - AtomicInteger count = countByEndpoint.get(endpoint); - return count == null ? 0 : Math.max(0, count.get()); - } - - /** How many connections this node holds in total. */ - public int size() { - return byId.size(); - } - - /** - * Moves every connection to DRAINING and returns them. - * - *

The first half of a graceful shutdown: stop accepting new inbound work while in-flight - * writes finish. Returned so the caller can close them in its own order and on its own schedule — - * a registry that closed them itself would decide the drain's pacing, which belongs to whoever - * knows how long the deploy is willing to wait. - */ - public List drainAll() { - return byId.values().stream() - .filter(context -> context.state() == WebSocketConnectionState.OPEN) - .map( - context -> { - WebSocketConnectionContext draining = - context.transitionTo(WebSocketConnectionState.DRAINING); - byId.put(draining.connectionId(), draining); - return draining; - }) - .toList(); - } - - /** The connections whose credential has expired past its grace, or which are too old. */ - public List expiredAt(Instant now, java.time.Duration maximumAge) { - return byId.values().stream() - .filter( - context -> - context.credentialExpiry().mustCloseAt(now) || context.olderThan(maximumAge, now)) - .toList(); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/LiveEventStompBroadcaster.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/LiveEventStompBroadcaster.java index 4aa9db2b..b120c0dc 100644 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/LiveEventStompBroadcaster.java +++ b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/LiveEventStompBroadcaster.java @@ -37,12 +37,12 @@ public class LiveEventStompBroadcaster { private static final Logger log = LoggerFactory.getLogger(LiveEventStompBroadcaster.class); private final SimpMessagingTemplate messaging; - private final WebSocketProperties properties; + private final WebSocketSettings properties; private final List> projectors; public LiveEventStompBroadcaster( SimpMessagingTemplate messaging, - WebSocketProperties properties, + WebSocketSettings properties, List> projectors) { this.messaging = messaging; this.properties = properties; diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketConfig.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketConfig.java index cd740386..42be62f7 100644 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketConfig.java +++ b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketConfig.java @@ -1,10 +1,11 @@ package dev.caskeleton.adapter.inbound.websocket.stomp; import java.util.List; +import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.messaging.simp.config.ChannelRegistration; import org.springframework.messaging.simp.config.MessageBrokerRegistry; @@ -25,21 +26,29 @@ import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerCo * *

Feature-agnostic transport machinery only — see {@link LiveEventStompBroadcaster} for the * generic domain-event push. Design rationale in the module README. + * + *

Registered through this module's own {@code AutoConfiguration.imports}: on when the module is + * present in a servlet application, off with {@code app.websocket.enabled=false}. */ -@Configuration +@AutoConfiguration +@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) @EnableWebSocketMessageBroker -@EnableConfigurationProperties(WebSocketProperties.class) -@ConditionalOnProperty(prefix = "app.websocket", name = "enabled", havingValue = "true") +@EnableConfigurationProperties(WebSocketSettings.class) +@ConditionalOnProperty( + prefix = "app.websocket", + name = "enabled", + havingValue = "true", + matchIfMissing = true) public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { - private final WebSocketProperties properties; + private final WebSocketSettings properties; private final AuthenticatedHandshakeInterceptor handshakeInterceptor = new AuthenticatedHandshakeInterceptor(); private final SafeStompSubProtocolErrorHandler errorHandler = new SafeStompSubProtocolErrorHandler(); private final WebSocketInboundAuthorizationInterceptor inboundAuthorization; - public WebSocketConfig(WebSocketProperties properties) { + public WebSocketConfig(WebSocketSettings properties) { this.properties = properties; this.inboundAuthorization = new WebSocketInboundAuthorizationInterceptor(properties); } diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketInboundAuthorizationInterceptor.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketInboundAuthorizationInterceptor.java index f1f161b1..186b1226 100644 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketInboundAuthorizationInterceptor.java +++ b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketInboundAuthorizationInterceptor.java @@ -13,9 +13,9 @@ final class WebSocketInboundAuthorizationInterceptor implements ChannelIntercept private static final String APPLICATION_PREFIX = "/app/"; - private final WebSocketProperties properties; + private final WebSocketSettings properties; - WebSocketInboundAuthorizationInterceptor(WebSocketProperties properties) { + WebSocketInboundAuthorizationInterceptor(WebSocketSettings properties) { this.properties = properties; } diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketProperties.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketSettings.java similarity index 93% rename from src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketProperties.java rename to src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketSettings.java index dec79d5a..29457908 100644 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketProperties.java +++ b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketSettings.java @@ -10,10 +10,13 @@ import org.springframework.validation.annotation.Validated; /** WebSocket (STOMP) settings bound from {@code app.websocket.*}. */ @ConfigurationProperties(prefix = "app.websocket") @Validated -public class WebSocketProperties { +public class WebSocketSettings { - /** Whether to expose the WebSocket/STOMP runtime. Activation must be explicit. */ - private boolean enabled; + /** + * Whether to expose the WebSocket/STOMP runtime. On when the module is present; {@code false} + * turns it off. + */ + private boolean enabled = true; /** STOMP handshake endpoint path (SockJS enabled). */ private String endpoint = "/ws"; @@ -78,7 +81,7 @@ public class WebSocketProperties { return true; } String[] origins = allowedOriginPatterns(); - return origins.length > 0 && Arrays.stream(origins).allMatch(WebSocketProperties::validOrigin); + return origins.length > 0 && Arrays.stream(origins).allMatch(WebSocketSettings::validOrigin); } private static boolean validPath(String value, String requiredPrefix) { diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/webflux/ReactiveFrameSink.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/webflux/ReactiveFrameSink.java deleted file mode 100644 index e006fd57..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/webflux/ReactiveFrameSink.java +++ /dev/null @@ -1,82 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.webflux; - -import dev.caskeleton.adapter.inbound.websocket.outbound.SerializedOutboundWriter; -import java.util.Objects; -import java.util.concurrent.atomic.AtomicReference; -import org.springframework.web.reactive.socket.WebSocketSession; -import reactor.core.publisher.Mono; -import reactor.core.publisher.Sinks; - -/** - * The reactive runtime's write path. - * - *

A {@code Sinks.Many} rather than a direct {@code session.send} per message, and the reason is - * structural: {@code WebSocketSession.send} returns a {@code Mono} that must be subscribed exactly - * once for the whole session. Calling it per message means many concurrent sends on one session, - * which the reactive API leaves as undefined as the servlet one — frames interleave and the peer - * sees a corrupt stream. - * - *

So the session is subscribed once to a sink, and every write pushes into it. The sink's - * back-pressure buffer is bounded by the platform's own queue above it, which is why this class - * uses {@code tryEmitNext} and treats a failure as a transport refusal rather than buffering again - * — a second unbounded buffer here would silently undo the queue's whole purpose. - */ -public final class ReactiveFrameSink implements SerializedOutboundWriter.FrameSink { - - private final Sinks.Many outbound; - private final AtomicReference failure = new AtomicReference<>(); - - private ReactiveFrameSink(Sinks.Many outbound) { - this.outbound = outbound; - } - - /** - * Attaches a sink to a session and returns the publisher the runtime must subscribe. - * - * @param session the reactive session - * @return the sink, and the {@code Mono} that drives it - */ - public static Attached attach(WebSocketSession session) { - Objects.requireNonNull(session, "session"); - // Bounded and single-subscriber. `onBackpressureBuffer()` with no bound is the default reach - // and it is exactly the unbounded buffer the outbound queue exists to replace. - Sinks.Many sink = Sinks.many().unicast().onBackpressureBuffer(); - ReactiveFrameSink frameSink = new ReactiveFrameSink(sink); - Mono pump = - session.send(sink.asFlux().map(session::textMessage)).doOnError(frameSink.failure::set); - return new Attached(frameSink, pump); - } - - @Override - public void write(String payload) throws Exception { - Throwable observed = failure.get(); - if (observed != null) { - throw new IllegalStateException("the session has already failed", observed); - } - Sinks.EmitResult result = outbound.tryEmitNext(payload); - if (result.isFailure()) { - // Not retried and not buffered. A retry here would spin on a peer that is not reading, and - // buffering would re-create the unbounded growth the queue above already refuses. - throw new IllegalStateException("the reactive sink refused the frame: " + result); - } - } - - /** Signals that no further messages will be written. */ - public void complete() { - outbound.tryEmitComplete(); - } - - /** - * A sink and the publisher that drives it. - * - * @param sink where the writer pushes - * @param pump the {@code Mono} the runtime must return so the session is subscribed exactly once - */ - public record Attached(ReactiveFrameSink sink, Mono pump) { - - public Attached { - Objects.requireNonNull(sink, "sink"); - Objects.requireNonNull(pump, "pump"); - } - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/webflux/WebSocketDataBufferLifecycle.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/webflux/WebSocketDataBufferLifecycle.java deleted file mode 100644 index cfdac02c..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/webflux/WebSocketDataBufferLifecycle.java +++ /dev/null @@ -1,106 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.webflux; - -import java.util.Objects; -import java.util.concurrent.atomic.AtomicLong; -import java.util.function.LongConsumer; - -/** - * Tracks what is retained, so a leak is a number rather than a slow heap. - * - *

Reference counting is the kind of bug that does not fail where it happens. A buffer that is - * retained and never released costs nothing at the call site, produces a Netty warning on a logger - * most deployments have turned down, and shows up weeks later as a heap that grows with traffic - * nobody can attribute. The only way to notice it early is to count. - * - *

Every path releases, including the two that are easy to forget. Cancellation is the common one - * — for a long-lived socket it is the normal way a subscription ends — and an error path that - * returns before its release is the other. - */ -public final class WebSocketDataBufferLifecycle { - - private final WebSocketDataBufferPolicy policy; - private final AtomicLong retainedBytes = new AtomicLong(); - private final AtomicLong retainCount = new AtomicLong(); - private final AtomicLong releaseCount = new AtomicLong(); - private final LongConsumer onLimitExceeded; - - /** - * @param policy what this runtime is allowed to retain - * @param onLimitExceeded called with the attempted size when the ceiling would be crossed - */ - public WebSocketDataBufferLifecycle( - WebSocketDataBufferPolicy policy, LongConsumer onLimitExceeded) { - this.policy = Objects.requireNonNull(policy, "policy"); - this.onLimitExceeded = Objects.requireNonNull(onLimitExceeded, "onLimitExceeded"); - } - - /** The policy in force. */ - public WebSocketDataBufferPolicy policy() { - return policy; - } - - /** - * Record a retain. - * - * @param bytes how large the retained buffer is - * @return whether the retain is permitted; false means the caller must copy or drop instead - */ - public boolean retain(int bytes) { - if (bytes < 0) { - throw new IllegalArgumentException("a buffer has a non-negative size"); - } - if (!policy.mayRetain(retainedBytes.get(), bytes)) { - onLimitExceeded.accept(bytes); - return false; - } - retainedBytes.addAndGet(bytes); - retainCount.incrementAndGet(); - return true; - } - - /** - * Record a release. - * - *

Refuses to go negative rather than silently wrapping. A release without a matching retain is - * a double-release, which in Netty is a buffer returned to the pool twice and handed to two - * owners — the same use-after-free as the leak's opposite, and far harder to trace from a - * corrupted message than from a counter that complained. - */ - public void release(int bytes) { - if (bytes < 0) { - throw new IllegalArgumentException("a buffer has a non-negative size"); - } - long remaining = retainedBytes.addAndGet(-bytes); - releaseCount.incrementAndGet(); - if (remaining < 0) { - retainedBytes.set(0); - throw new IllegalStateException( - "more bytes were released than retained; a double release returns one pooled buffer to" - + " two owners"); - } - } - - /** How much is currently retained. */ - public long retainedBytes() { - return retainedBytes.get(); - } - - /** - * Whether every retain has been matched. - * - *

The assertion a leak test makes after a stream ends, including one that was cancelled. - */ - public boolean balanced() { - return retainCount.get() == releaseCount.get() && retainedBytes.get() == 0; - } - - /** How many retains happened. */ - public long retains() { - return retainCount.get(); - } - - /** How many releases happened. */ - public long releases() { - return releaseCount.get(); - } -} diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/webflux/WebSocketDataBufferPolicy.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/webflux/WebSocketDataBufferPolicy.java deleted file mode 100644 index 3abe2c27..00000000 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/webflux/WebSocketDataBufferPolicy.java +++ /dev/null @@ -1,62 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.webflux; - -/** - * How pooled buffers are handled on the reactive stack. - * - *

The reason this is a declared policy rather than a convention: Reactor Netty hands the handler - * a {@code DataBuffer} backed by a pooled, reference-counted Netty buffer, and that buffer is - * released the moment the handler's callback returns. Anything the handler kept — a reference - * stashed for an async continuation, a payload queued for later — is then a use-after-free that - * reads whatever the pool has since put there. The failure is not a crash; it is a message whose - * contents are somebody else's. - * - *

Retaining fixes that and creates the opposite failure: a retained buffer that is not released - * on every exit path leaks pool memory, and Netty reports it as a warning nobody reads while the - * heap grows with the number of cancelled subscriptions. - * - *

So the policy states both halves, and {@code maxRetainedBytes} bounds the second. A deployment - * that does not cross an async boundary sets {@code retainAcrossAsyncBoundary} false and pays for - * neither. - * - * @param pooled whether the runtime hands out pooled buffers at all - * @param retainAcrossAsyncBoundary whether a buffer may outlive the callback that received it - * @param maxRetainedBytes the ceiling on what one connection may hold retained - */ -public record WebSocketDataBufferPolicy( - boolean pooled, boolean retainAcrossAsyncBoundary, long maxRetainedBytes) { - - public WebSocketDataBufferPolicy { - if (retainAcrossAsyncBoundary && !pooled) { - throw new IllegalArgumentException( - "retaining is only meaningful for pooled buffers; an unpooled one is ordinary heap and" - + " needs no reference counting"); - } - if (retainAcrossAsyncBoundary && maxRetainedBytes < 1) { - throw new IllegalArgumentException( - "retaining without a ceiling leaks the pool one cancelled subscription at a time, and" - + " Netty reports it as a warning nobody reads"); - } - if (!retainAcrossAsyncBoundary && maxRetainedBytes != 0) { - throw new IllegalArgumentException( - "a policy that retains nothing describes a ceiling that cannot be reached"); - } - } - - /** The safe default: copy out of the pooled buffer before the callback returns. */ - public static WebSocketDataBufferPolicy copyOnReceive() { - return new WebSocketDataBufferPolicy(true, false, 0); - } - - /** Retain across an async boundary, bounded. */ - public static WebSocketDataBufferPolicy retaining(long maxRetainedBytes) { - return new WebSocketDataBufferPolicy(true, true, maxRetainedBytes); - } - - /** Whether another retained buffer of this size may be held. */ - public boolean mayRetain(long currentlyRetained, int additionalBytes) { - if (!retainAcrossAsyncBoundary) { - return false; - } - return currentlyRetained + additionalBytes <= maxRetainedBytes; - } -} diff --git a/src/adapter/inbound/websocket/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/src/adapter/inbound/websocket/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports new file mode 100644 index 00000000..8fd18244 --- /dev/null +++ b/src/adapter/inbound/websocket/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports @@ -0,0 +1 @@ +dev.caskeleton.adapter.inbound.websocket.stomp.WebSocketConfig diff --git a/src/adapter/inbound/websocket/src/systemTest/java/dev/caskeleton/adapter/inbound/websocket/runtime/TomcatWebSocketShutdownIT.java b/src/adapter/inbound/websocket/src/systemTest/java/dev/caskeleton/adapter/inbound/websocket/runtime/TomcatWebSocketShutdownIT.java new file mode 100644 index 00000000..6925cf2f --- /dev/null +++ b/src/adapter/inbound/websocket/src/systemTest/java/dev/caskeleton/adapter/inbound/websocket/runtime/TomcatWebSocketShutdownIT.java @@ -0,0 +1,59 @@ +package dev.caskeleton.adapter.inbound.websocket.runtime; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.adapter.inbound.websocket.testkit.runtime.WebSocketFixtureApplication; +import java.net.URI; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import org.junit.jupiter.api.Test; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.web.server.context.WebServerApplicationContext; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.web.socket.CloseStatus; +import org.springframework.web.socket.WebSocketHttpHeaders; +import org.springframework.web.socket.WebSocketSession; +import org.springframework.web.socket.client.standard.StandardWebSocketClient; +import org.springframework.web.socket.handler.TextWebSocketHandler; + +/** + * Closing the application context tells live clients 1001, through Spring's own lifecycle order. + * + *

Its own context, because closing it is the behaviour under test. The abuse contract calls + * {@code stop()} directly, which proves what stop does but not that Spring runs it while the server + * can still send a close frame. + */ +class TomcatWebSocketShutdownIT { + + @Test + void closingTheContextClosesLiveConnectionsWith1001() throws Exception { + // given + ConfigurableApplicationContext context = + new SpringApplicationBuilder(WebSocketFixtureApplication.class) + .properties("server.port=0", "server.shutdown=graceful") + .run(); + int port = ((WebServerApplicationContext) context).getWebServer().getPort(); + AtomicInteger observedCode = new AtomicInteger(); + CountDownLatch closed = new CountDownLatch(1); + new StandardWebSocketClient() + .execute( + new TextWebSocketHandler() { + @Override + public void afterConnectionClosed(WebSocketSession peer, CloseStatus status) { + observedCode.set(status.getCode()); + closed.countDown(); + } + }, + new WebSocketHttpHeaders(), + URI.create("ws://localhost:" + port + WebSocketFixtureApplication.PATH)) + .get(10, TimeUnit.SECONDS); + + // when + context.close(); + + // then + // A 1006 here means the server stopped before the handler could send its close frame. + assertThat(closed.await(20, TimeUnit.SECONDS) ? observedCode.get() : -1).isEqualTo(1001); + } +} diff --git a/src/adapter/inbound/websocket/src/systemTest/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketBoundaryQualificationTest.java b/src/adapter/inbound/websocket/src/systemTest/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketBoundaryQualificationTest.java index 1866aaba..64ad5671 100644 --- a/src/adapter/inbound/websocket/src/systemTest/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketBoundaryQualificationTest.java +++ b/src/adapter/inbound/websocket/src/systemTest/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketBoundaryQualificationTest.java @@ -28,9 +28,10 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringBootConfiguration; +import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.boot.test.context.runner.WebApplicationContextRunner; import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.annotation.Bean; @@ -64,8 +65,9 @@ class WebSocketBoundaryQualificationTest { private static final String AUTHORIZATION = "Bearer qualification-token"; - private final ApplicationContextRunner contextRunner = - new ApplicationContextRunner().withUserConfiguration(WebSocketConfig.class); + private final WebApplicationContextRunner contextRunner = + new WebApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(WebSocketConfig.class)); private final AtomicReference openSession = new AtomicReference<>(); private final List openClients = new CopyOnWriteArrayList<>(); @@ -96,14 +98,16 @@ class WebSocketBoundaryQualificationTest { } @Test - void defaultsKeepTransportDisabledAndCreateNoRuntimeBeans() { - contextRunner.run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context).doesNotHaveBean(WebSocketConfig.class); - assertThat(context).doesNotHaveBean(WebSocketProperties.class); - assertThat(context).doesNotHaveBean(LiveEventStompBroadcaster.class); - }); + void switchedOffCreatesNoRuntimeBeans() { + contextRunner + .withPropertyValues("app.websocket.enabled=false") + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context).doesNotHaveBean(WebSocketConfig.class); + assertThat(context).doesNotHaveBean(WebSocketSettings.class); + assertThat(context).doesNotHaveBean(LiveEventStompBroadcaster.class); + }); } @Test diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/client/OutboundClientTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/client/OutboundClientTest.java deleted file mode 100644 index bc1d151c..00000000 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/client/OutboundClientTest.java +++ /dev/null @@ -1,149 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.client; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.net.URI; -import java.time.Duration; -import java.util.List; -import java.util.Optional; -import java.util.OptionalLong; -import java.util.random.RandomGenerator; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -/** Connecting out to somebody else, without becoming their outage. */ -@Tag("websocket-advanced") -class OutboundClientTest { - - private static NamedClientProfile profile(String name, String uri) { - return new NamedClientProfile( - name, - URI.create(uri), - Optional.of("ca-skeleton.v1"), - Duration.ofSeconds(5), - Duration.ofSeconds(60)); - } - - @Test - @DisplayName("reconnect waits grow, stay under the ceiling and are jittered") - void reconnectBackoffIsBoundedAndJittered() { - // The ceiling has to be a ceiling: adding jitter on top of maxBackoff means the configured - // maximum is not the maximum, which only shows up when the peer stays down for an hour. - ReconnectPolicy policy = ReconnectPolicy.conventional(); - RandomGenerator zero = new FixedRandom(0); - RandomGenerator max = new FixedRandom(Long.MAX_VALUE); - - assertThat(policy.backoffFor(1, zero)).isEqualTo(Duration.ofSeconds(1)); - assertThat(policy.backoffFor(4, zero)).isEqualTo(Duration.ofSeconds(8)); - assertThat(policy.backoffFor(50, zero)).isEqualTo(Duration.ofSeconds(60)); - assertThat(policy.backoffFor(50, max)).isLessThanOrEqualTo(Duration.ofSeconds(60)); - assertThat(policy.backoffFor(50, max).isNegative()).isFalse(); - } - - @Test - @DisplayName("a policy without jitter is refused") - void jitterlessPolicyIsRefused() { - // Without it every client of a restarted peer reconnects in lockstep and keeps it down. - assertThatThrownBy( - () -> - new ReconnectPolicy( - Duration.ofSeconds(1), Duration.ofSeconds(60), 2.0, OptionalLong.of(20), 0.0)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("lockstep"); - } - - @Test - @DisplayName("attempts are bounded") - void attemptsAreBounded() { - // A client retrying forever against a decommissioned peer is a permanent load source that - // nobody notices, because each individual attempt looks reasonable. - ReconnectPolicy policy = ReconnectPolicy.conventional(); - - assertThat(policy.mayRetry(19)).isTrue(); - assertThat(policy.mayRetry(20)).isFalse(); - } - - @Test - @DisplayName("a zero first backoff is refused") - void zeroFirstBackoffIsRefused() { - assertThatThrownBy( - () -> - new ReconnectPolicy( - Duration.ZERO, Duration.ofSeconds(60), 2.0, OptionalLong.empty(), 1.0)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("tight loop"); - } - - @Test - @DisplayName("outbound connections are named, and two of one name are refused") - void connectionsAreNamedAndUnique() { - // Whichever was registered last would silently win, and the other peer would never be reached. - assertThatThrownBy( - () -> - NamedClientRegistry.of( - List.of(profile("upstream", "wss://a"), profile("upstream", "wss://b")))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("silently win"); - } - - @Test - @DisplayName("an undeclared name is not resolvable") - void undeclaredNameIsRefused() { - NamedClientRegistry registry = NamedClientRegistry.of(List.of(profile("upstream", "wss://a"))); - - assertThat(registry.find("upstream")).isPresent(); - assertThat(registry.find("somewhere-else")).isEmpty(); - assertThat(registry.names()).containsExactly("upstream"); - } - - @Test - @DisplayName("a plaintext outbound connection says what it exposes") - void plaintextConnectionIsReported() { - NamedClientRegistry registry = - NamedClientRegistry.of( - List.of(profile("insecure", "ws://a"), profile("secure", "wss://b"))); - - assertThat(registry.plaintextConcerns()).singleElement().asString().contains("insecure"); - assertThat(profile("secure", "wss://b").secure()).isTrue(); - } - - @Test - @DisplayName("a non-WebSocket URI and unbounded timeouts are refused") - void malformedProfileIsRefused() { - assertThatThrownBy( - () -> - new NamedClientProfile( - "x", - URI.create("https://peer"), - Optional.empty(), - Duration.ofSeconds(1), - Duration.ofSeconds(1))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("not a WebSocket URI"); - assertThatThrownBy( - () -> - new NamedClientProfile( - "x", - URI.create("wss://peer"), - Optional.empty(), - Duration.ofSeconds(1), - Duration.ZERO)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("half-open connection to a vanished peer"); - } - - /** A generator with one answer, so the backoff arithmetic is checked rather than sampled. */ - private record FixedRandom(long value) implements RandomGenerator { - @Override - public long nextLong() { - return value; - } - - @Override - public long nextLong(long bound) { - return Math.min(value, bound - 1); - } - } -} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/cluster/ClusterFanoutTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/cluster/ClusterFanoutTest.java deleted file mode 100644 index 52894bce..00000000 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/cluster/ClusterFanoutTest.java +++ /dev/null @@ -1,163 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.cluster; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketActorReference; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketEndpointName; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketNodeId; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageType; -import java.nio.charset.StandardCharsets; -import java.time.Duration; -import java.time.Instant; -import java.util.Optional; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -/** - * Delivering across nodes, where the sender does not hold the connection. - * - *

Two facts shape everything here. The index is a cache of state owned by another machine, so - * every entry is about the past; and durable fan-out is at-least-once by construction, so - * redelivery is normal operation rather than an error. - */ -@Tag("websocket-advanced") -class ClusterFanoutTest { - - private static final Instant NOW = Instant.parse("2026-08-25T10:00:00Z"); - private static final byte[] SALT = - "a-deployment-salt-of-adequate-length".getBytes(StandardCharsets.UTF_8); - private static final WebSocketActorReference ALICE = - WebSocketActorReference.of("alice", "acme", SALT); - private static final WebSocketEndpointName ENDPOINT = new WebSocketEndpointName("live-updates"); - private static final WebSocketMessageType TYPE = new WebSocketMessageType("order.placed.v1"); - - private static FanoutEnvelope ordered(long sequence) { - return new FanoutEnvelope( - ALICE, - ENDPOINT, - TYPE, - "{}", - Optional.of("orders"), - Optional.of(sequence), - NOW, - NOW.plusSeconds(30)); - } - - @Test - @DisplayName("an index key carries a fingerprint, never a subject") - void indexKeyCarriesNoIdentity() { - // Redis keys reach MONITOR, the slow log, KEYS output during an incident, and every backup — - // none of which have the access controls the application has. - String key = ExternalSessionSummary.indexKey(ALICE, ENDPOINT); - - assertThat(key).doesNotContain("alice"); - assertThat(key).doesNotContain("acme"); - assertThat(key).contains(ALICE.fingerprint()); - } - - @Test - @DisplayName("an index entry knows when it was observed and when it stops meaning anything") - void indexEntriesAgeOut() { - // The index caches a fact owned by another machine. Treating an entry as current is how a - // message is routed to a node that stopped existing three minutes ago. - ExternalSessionSummary summary = - new ExternalSessionSummary(ALICE, new WebSocketNodeId("edge-1"), ENDPOINT, 2, NOW); - - assertThat(summary.staleAt(Duration.ofSeconds(30), NOW.plusSeconds(10))).isFalse(); - assertThat(summary.staleAt(Duration.ofSeconds(30), NOW.plusSeconds(31))).isTrue(); - } - - @Test - @DisplayName("a redelivered position is not delivered twice") - void redeliveryIsDeduplicated() { - // At-least-once is the contract, so this is normal operation: a redeploy, a slow node or a - // broker rebalance all produce it. Without deduplication a rolling restart shows every client - // a burst of repeats. - FanoutDeduplicator deduplicator = new FanoutDeduplicator(Duration.ofMinutes(5)); - - assertThat(deduplicator.shouldDeliver(ordered(41), NOW)).isTrue(); - assertThat(deduplicator.shouldDeliver(ordered(42), NOW)).isTrue(); - assertThat(deduplicator.shouldDeliver(ordered(42), NOW)).isFalse(); - assertThat(deduplicator.shouldDeliver(ordered(41), NOW)).isFalse(); - assertThat(deduplicator.shouldDeliver(ordered(43), NOW)).isTrue(); - } - - @Test - @DisplayName("an unordered fan-out is not deduplicated") - void unorderedFanoutIsNotDeduplicated() { - // There is no key to deduplicate against, and inventing one would silently drop legitimately - // repeated values. - FanoutDeduplicator deduplicator = new FanoutDeduplicator(Duration.ofMinutes(5)); - FanoutEnvelope unordered = - new FanoutEnvelope( - ALICE, - ENDPOINT, - TYPE, - "{}", - Optional.empty(), - Optional.empty(), - NOW, - NOW.plusSeconds(30)); - - assertThat(deduplicator.shouldDeliver(unordered, NOW)).isTrue(); - assertThat(deduplicator.shouldDeliver(unordered, NOW)).isTrue(); - } - - @Test - @DisplayName("an expired fan-out is dropped by the receiving node") - void expiredFanoutIsDropped() { - // Checked on receipt as well as at publication. A message that sat through an outage arrives - // late, and for the ephemeral traffic fan-out carries, late is indistinguishable from wrong. - FanoutDeduplicator deduplicator = new FanoutDeduplicator(Duration.ofMinutes(5)); - - assertThat(deduplicator.shouldDeliver(ordered(41), NOW.plusSeconds(60))).isFalse(); - } - - @Test - @DisplayName("the deduplicator forgets streams that go quiet") - void deduplicatorForgetsIdleStreams() { - // Otherwise it grows with the number of streams that ever existed rather than the number in - // use. - FanoutDeduplicator deduplicator = new FanoutDeduplicator(Duration.ofMinutes(5)); - deduplicator.shouldDeliver(ordered(41), NOW); - - assertThat(deduplicator.trackedStreams()).isOne(); - assertThat(deduplicator.evictIdle(NOW.plus(Duration.ofMinutes(6)))).isOne(); - assertThat(deduplicator.trackedStreams()).isZero(); - } - - @Test - @DisplayName("a fan-out envelope carries an encoded document, not a business object") - void envelopeCarriesAnEncodedDocument() { - // The payload is serialized by one node and read by another, which during a rolling deploy are - // different versions of the code. Keeping it the catalog-encoded document makes it the same - // contract the client sees rather than a second private one. - assertThat( - java.util.Arrays.stream(FanoutEnvelope.class.getRecordComponents()) - .filter(component -> component.getName().equals("payload")) - .findFirst() - .orElseThrow() - .getType()) - .isEqualTo(String.class); - } - - @Test - @DisplayName("half an ordering is refused") - void halfAnOrderingIsRefused() { - assertThatThrownBy( - () -> - new FanoutEnvelope( - ALICE, - ENDPOINT, - TYPE, - "{}", - Optional.of("orders"), - Optional.empty(), - NOW, - NOW.plusSeconds(30))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("meaningless apart"); - } -} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/cluster/PortBackedBridgeTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/cluster/PortBackedBridgeTest.java deleted file mode 100644 index 9247ec46..00000000 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/cluster/PortBackedBridgeTest.java +++ /dev/null @@ -1,328 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.cluster; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.websocket.advanced.presence.PortBackedPresenceStore; -import dev.caskeleton.adapter.inbound.websocket.advanced.presence.PresenceState; -import dev.caskeleton.adapter.inbound.websocket.advanced.resume.PortBackedReplayAvailability; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketActorReference; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketEndpointName; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketNodeId; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageType; -import dev.caskeleton.application.realtime.ActorFingerprint; -import dev.caskeleton.application.realtime.ConnectionRegistration; -import dev.caskeleton.application.realtime.ConnectionRegistryPort; -import dev.caskeleton.application.realtime.DurableFanoutPort; -import dev.caskeleton.application.realtime.DurableFanoutRecord; -import dev.caskeleton.application.realtime.DurableFanoutUnavailableException; -import dev.caskeleton.application.realtime.LiveEventReplayPort; -import dev.caskeleton.application.realtime.RealtimeChannel; -import dev.caskeleton.application.realtime.RealtimeNodeId; -import dev.caskeleton.application.realtime.ReplayWindow; -import dev.caskeleton.application.realtime.ReplayedEvent; -import java.nio.charset.StandardCharsets; -import java.time.Duration; -import java.time.Instant; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.ConcurrentHashMap; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -/** - * The bridges between this leaf's vocabulary and the application's realtime ports. - * - *

These classes are translators, so what is worth asserting is the translation and the failure - * behaviour — not the storage, which the outbound adapters own and test against their own - * datastore. - */ -@Tag("websocket-advanced") -class PortBackedBridgeTest { - - private static final Instant NOW = Instant.parse("2026-08-25T10:00:00Z"); - private static final byte[] SALT = - "a-deployment-salt-of-adequate-length".getBytes(StandardCharsets.UTF_8); - private static final WebSocketActorReference ALICE = - WebSocketActorReference.of("alice", "acme", SALT); - private static final WebSocketEndpointName FEED = new WebSocketEndpointName("live-updates"); - private static final WebSocketNodeId EDGE_ONE = new WebSocketNodeId("edge-1"); - private static final WebSocketNodeId EDGE_TWO = new WebSocketNodeId("edge-2"); - - @Test - @DisplayName("an announcement reaches the registry as a fingerprint, never a subject") - void announcementCarriesOnlyAFingerprint() { - // The port's own type refuses anything that is not a fingerprint, which is what stops a later - // change here from passing a raw subject into a datastore key. - RecordingRegistry registry = new RecordingRegistry(); - new PortBackedExternalSessionIndex(registry) - .announce( - new ExternalSessionSummary(ALICE, EDGE_ONE, FEED, 2, NOW), Duration.ofSeconds(30)); - - ConnectionRegistration announced = registry.announced.get(0); - assertThat(announced.actor().value()).isEqualTo(ALICE.fingerprint()).doesNotContain("alice"); - assertThat(announced.channel().value()).isEqualTo("live-updates"); - assertThat(announced.connectionCount()).isEqualTo(2); - } - - @Test - @DisplayName("a located actor comes back in this leaf's types") - void locatedActorIsTranslatedBack() { - RecordingRegistry registry = new RecordingRegistry(); - registry.announce( - new ConnectionRegistration( - new ActorFingerprint(ALICE.fingerprint()), - new RealtimeNodeId("edge-2"), - new RealtimeChannel("live-updates"), - 3, - NOW), - Duration.ofSeconds(30)); - - assertThat(new PortBackedExternalSessionIndex(registry).locate(ALICE, FEED, NOW)) - .singleElement() - .satisfies( - summary -> { - assertThat(summary.nodeId()).isEqualTo(EDGE_TWO); - assertThat(summary.connectionCount()).isEqualTo(3); - }); - } - - @Test - @DisplayName("a registry that reports nothing produces no locations rather than an error") - void emptyRegistryProducesNoLocations() { - assertThat(new PortBackedExternalSessionIndex(new RecordingRegistry()).locate(ALICE, FEED, NOW)) - .isEmpty(); - } - - @Test - @DisplayName("presence sums connections across nodes") - void presenceSumsAcrossNodes() { - // Two tabs on two nodes is one person with two connections, not two presences. - RecordingRegistry registry = new RecordingRegistry(); - announce(registry, "edge-1", 1, NOW); - announce(registry, "edge-2", 2, NOW); - - assertThat(store(registry).presenceOf(ALICE, NOW).activeConnectionCount()).isEqualTo(3); - } - - @Test - @DisplayName("presence ages on the oldest contributing report, not the newest") - void presenceAgesOnTheOldestReport() { - // Taking the newest would let one freshly-refreshed node make an otherwise stale picture look - // current, which is exactly the case presence must not get wrong. - RecordingRegistry registry = new RecordingRegistry(); - announce(registry, "edge-1", 1, NOW.minusSeconds(120)); - announce(registry, "edge-2", 1, NOW); - - assertThat(store(registry).presenceOf(ALICE, NOW).state()).isEqualTo(PresenceState.STALE); - } - - @Test - @DisplayName("nothing reported is offline") - void nothingReportedIsOffline() { - assertThat(store(new RecordingRegistry()).presenceOf(ALICE, NOW).state()) - .isEqualTo(PresenceState.OFFLINE); - } - - @Test - @DisplayName("replay availability distinguishes an unknown stream from an aged-out one") - void availabilityDistinguishesUnknownFromAgedOut() { - // Answering 0 for both would let a resume for a stream that never existed look like a complete - // replay of nothing. - PortBackedReplayAvailability availability = - new PortBackedReplayAvailability( - new StubReplay( - Map.of("orders", new ReplayWindow("orders", Optional.of(41L), Optional.of(90L))))); - - assertThat(availability.earliestAvailable("orders")).contains(41L); - assertThat(availability.earliestAvailable("never-existed")).isEmpty(); - } - - @Test - @DisplayName("a replay store that cannot be read reports nothing available") - void unreadableReplayStoreReportsNothing() { - // Degraded to "cannot resume", which becomes a resynchronise. Honouring a token we cannot - // verify would deliver a stream with a hole the client cannot see. - assertThat(new PortBackedReplayAvailability(new FailingReplay()).earliestAvailable("orders")) - .isEmpty(); - } - - @Test - @DisplayName("a fan-out is partitioned by recipient, not by feed") - void fanoutIsPartitionedByRecipient() { - // Keying on the endpoint would put a whole feed in one partition and serialise every recipient - // behind the slowest. - RecordingFanout fanout = new RecordingFanout(); - new MessagingFanoutAdapter(fanout).publish(envelope()); - - assertThat(fanout.published.get(0).partitionKey()).isEqualTo(ALICE.fingerprint()); - assertThat(fanout.published.get(0).channel().value()).isEqualTo("live-updates"); - } - - @Test - @DisplayName("a transport that refuses reaches the caller") - void refusedPublishReachesTheCaller() { - // Fail-closed, unlike the ephemeral fan-out: the caller is the only party that can choose - // between retrying, dropping and falling back. - assertThatThrownBy(() -> new MessagingFanoutAdapter(new RefusingFanout()).publish(envelope())) - .isInstanceOf(DurableFanoutUnavailableException.class); - } - - @Test - @DisplayName("an expired record is not delivered by the receiving node") - void expiredRecordIsNotDelivered() { - // Checked on receipt because a durable transport is exactly the one that can hold a message - // through an outage, and the receiver is the only place that knows what time it is then. - RecordingFanout fanout = new RecordingFanout(); - new MessagingFanoutAdapter(fanout).publish(envelope()); - DurableFanoutRecord record = fanout.published.get(0); - - assertThat(MessagingFanoutAdapter.deliverable(record, NOW.plusSeconds(10))).isTrue(); - assertThat(MessagingFanoutAdapter.deliverable(record, NOW.plusSeconds(60))).isFalse(); - } - - @Test - @DisplayName("a record naming a feed this build does not know is dropped, not fatal") - void unknownFeedIsDropped() { - // During a rolling deploy the other half of the cluster may publish for a feed this node has - // not learned yet, and failing the consumer would stop it processing the records it does - // understand. - RecordingFanout fanout = new RecordingFanout(); - MessagingFanoutAdapter adapter = new MessagingFanoutAdapter(fanout); - DurableFanoutRecord unknown = - new DurableFanoutRecord( - // A dotted channel: legal for the application's channel vocabulary and not for this - // leaf's endpoint names, which is exactly the shape a newer node would publish. - new RealtimeChannel("orders.v2"), - ALICE.fingerprint(), - "{}", - Optional.empty(), - Optional.empty(), - NOW, - NOW.plusSeconds(30)); - - assertThat(adapter.receive(unknown, ALICE, new WebSocketMessageType("order.placed.v1"))) - .isEmpty(); - } - - private static FanoutEnvelope envelope() { - return new FanoutEnvelope( - ALICE, - FEED, - new WebSocketMessageType("order.placed.v1"), - "{}", - Optional.of("orders"), - Optional.of(41L), - NOW, - NOW.plusSeconds(30)); - } - - private static PortBackedPresenceStore store(ConnectionRegistryPort registry) { - return new PortBackedPresenceStore( - registry, FEED, Duration.ofSeconds(30), Duration.ofSeconds(90)); - } - - private static void announce( - RecordingRegistry registry, String node, int connections, Instant observedAt) { - registry.announce( - new ConnectionRegistration( - new ActorFingerprint(ALICE.fingerprint()), - new RealtimeNodeId(node), - new RealtimeChannel("live-updates"), - connections, - observedAt), - Duration.ofSeconds(30)); - } - - /** An in-memory registry that records what it was told. */ - private static final class RecordingRegistry implements ConnectionRegistryPort { - - private final List announced = new ArrayList<>(); - private final Map held = new ConcurrentHashMap<>(); - - @Override - public void announce(ConnectionRegistration registration, Duration timeToLive) { - announced.add(registration); - held.put( - key(registration.actor(), registration.channel(), registration.nodeId()), registration); - } - - @Override - public void withdraw(ActorFingerprint actor, RealtimeChannel channel, RealtimeNodeId nodeId) { - held.remove(key(actor, channel, nodeId)); - } - - @Override - public List locate( - ActorFingerprint actor, RealtimeChannel channel, Instant now) { - return held.values().stream() - .filter(entry -> entry.actor().equals(actor) && entry.channel().equals(channel)) - .toList(); - } - - @Override - public void heartbeat(RealtimeNodeId nodeId, Instant now) {} - - @Override - public List evictSilentNodes(Duration heartbeatTimeout, Instant now) { - return List.of(); - } - - private static String key( - ActorFingerprint actor, RealtimeChannel channel, RealtimeNodeId node) { - return actor.value() + "|" + channel.value() + "|" + node.value(); - } - } - - /** A replay port over a fixed set of windows. */ - private record StubReplay(Map windows) implements LiveEventReplayPort { - - @Override - public ReplayWindow window(String streamId) { - return windows.getOrDefault(streamId, ReplayWindow.empty(streamId)); - } - - @Override - public List replayAfter(String streamId, long afterPosition, int limit) { - return List.of(); - } - } - - /** A replay port that is down. */ - private static final class FailingReplay implements LiveEventReplayPort { - - @Override - public ReplayWindow window(String streamId) { - throw new IllegalStateException("the store is unreachable"); - } - - @Override - public List replayAfter(String streamId, long afterPosition, int limit) { - throw new IllegalStateException("the store is unreachable"); - } - } - - /** A durable fan-out that records what it was given. */ - private static final class RecordingFanout implements DurableFanoutPort { - - private final List published = new ArrayList<>(); - - @Override - public void publish(DurableFanoutRecord record) { - published.add(record); - } - } - - /** A durable fan-out that will not accept anything. */ - private static final class RefusingFanout implements DurableFanoutPort { - - @Override - public void publish(DurableFanoutRecord record) { - throw new DurableFanoutUnavailableException( - record.channel(), new IllegalStateException("broker down")); - } - } -} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/cluster/ReplayCursorTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/cluster/ReplayCursorTest.java deleted file mode 100644 index 933ceed4..00000000 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/cluster/ReplayCursorTest.java +++ /dev/null @@ -1,180 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.cluster; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageCatalog; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageDescriptor; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageDirection; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageFamily; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageType; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketSchemaVersion; -import java.util.List; -import java.util.Map; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -/** - * Replaying retained messages, where the producer and the consumer are not the same deployment. - * - *

That is what makes this different from live delivery. Retention outlives deploys by - * definition, so a retained message can name a type that has since been removed, changed major - * version, or was never meant to reach a client at all. "The producer and consumer agree" is - * exactly the assumption that does not hold on a replay path. - */ -@Tag("websocket-advanced") -class ReplayCursorTest { - - private static final WebSocketMessageType PLACED = new WebSocketMessageType("order.placed.v1"); - private static final WebSocketMessageType COMMAND = new WebSocketMessageType("order.place.v1"); - - private final WebSocketMessageCatalog catalog = - WebSocketMessageCatalog.of( - List.of( - new WebSocketMessageDescriptor( - PLACED, - WebSocketMessageFamily.EVENT, - WebSocketMessageDirection.SERVER_TO_CLIENT, - WebSocketSchemaVersion.v(1)), - new WebSocketMessageDescriptor( - COMMAND, - WebSocketMessageFamily.COMMAND, - WebSocketMessageDirection.CLIENT_TO_SERVER, - WebSocketSchemaVersion.v(1)))); - - private final ReplayEventMapper mapper = new ReplayEventMapper(catalog); - - private static Map headers(String type, String sequence) { - return Map.of( - "ws-stream-id", - "orders", - "ws-message-type", - type, - "ws-sequence", - sequence, - "ws-occurred-at", - "1756116000000"); - } - - @Test - @DisplayName("a cursor starts having delivered nothing") - void cursorStartsEmpty() { - ReplayCursor cursor = ReplayCursor.startingAt("orders", 43); - - assertThat(cursor.delivered()).isZero(); - assertThat(cursor.caughtUpTo(43)).isFalse(); - } - - @Test - @DisplayName("a cursor advances one position at a time") - void cursorAdvancesOneAtATime() { - ReplayCursor cursor = ReplayCursor.startingAt("orders", 43).advancedTo(43).advancedTo(44); - - assertThat(cursor.delivered()).isEqualTo(2); - assertThat(cursor.caughtUpTo(44)).isTrue(); - } - - @Test - @DisplayName("a cursor cannot skip a position") - void cursorCannotSkip() { - // A skip is a hole in somebody's history with nothing recording that it happened. - assertThatThrownBy(() -> ReplayCursor.startingAt("orders", 43).advancedTo(45)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("nothing recording that it did"); - } - - @Test - @DisplayName("a cursor cannot start before the first position") - void cursorCannotStartAtZero() { - // The source would answer with the first real message, silently shifting every position after. - assertThatThrownBy(() -> ReplayCursor.startingAt("orders", 0)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("starts at position 1"); - } - - @Test - @DisplayName("a well-formed retained message maps") - void wellFormedMessageMaps() { - ReplayEventMapper.Mapped mapped = mapper.map(headers("order.placed.v1", "42"), "{}"); - - assertThat(mapped.record()).isPresent(); - assertThat(mapped.record().orElseThrow().sequence()).isEqualTo(42); - assertThat(mapped.record().orElseThrow().streamId()).isEqualTo("orders"); - } - - @Test - @DisplayName("a retained message naming a removed type is refused") - void removedTypeIsRefused() { - // The replay-path failure that live traffic never sees: the message was valid when it was - // written and the deployment that would receive it no longer publishes the type. - assertThat(mapper.map(headers("order.cancelled.v1", "42"), "{}").rejection()) - .contains(ReplayEventMapper.Rejection.UNKNOWN_TYPE); - } - - @Test - @DisplayName("a client-to-server type is never replayed to a client") - void clientOnlyTypeIsRefused() { - // Otherwise a retained command is delivered to subscribers as though the server had produced - // it. - assertThat(mapper.map(headers("order.place.v1", "42"), "{}").rejection()) - .contains(ReplayEventMapper.Rejection.WRONG_DIRECTION); - } - - @Test - @DisplayName("a message from before a breaking change is refused") - void schemaMismatchIsRefused() { - // A retained v2 message where the deployment publishes v1: forwarding it hands the client a - // document of a shape its current code cannot read. - WebSocketMessageCatalog v2 = - WebSocketMessageCatalog.of( - List.of( - new WebSocketMessageDescriptor( - new WebSocketMessageType("order.placed.v2"), - WebSocketMessageFamily.EVENT, - WebSocketMessageDirection.SERVER_TO_CLIENT, - WebSocketSchemaVersion.v(2)))); - - assertThat(new ReplayEventMapper(v2).map(headers("order.placed.v1", "42"), "{}").rejection()) - .contains(ReplayEventMapper.Rejection.UNKNOWN_TYPE); - } - - @Test - @DisplayName("a message missing what the platform needs is refused, not guessed") - void malformedMessageIsRefused() { - assertThat(mapper.map(Map.of("ws-stream-id", "orders"), "{}").rejection()) - .contains(ReplayEventMapper.Rejection.MALFORMED); - assertThat(mapper.map(headers("order.placed.v1", "not-a-number"), "{}").rejection()) - .contains(ReplayEventMapper.Rejection.MALFORMED); - assertThat(mapper.map(headers("order.placed.v1", "0"), "{}").rejection()) - .contains(ReplayEventMapper.Rejection.MALFORMED); - } - - @Test - @DisplayName("the broker's own headers do not reach the client") - void brokerHeadersDoNotReachTheClient() { - // A broker record carries queue names, delivery counts and routing keys. Forwarding it - // publishes the internal topology and makes the client's contract whatever the broker - // serializes. - Map withBrokerNoise = - Map.of( - "ws-stream-id", "orders", - "ws-message-type", "order.placed.v1", - "ws-sequence", "42", - "ws-occurred-at", "1756116000000", - "x-death-count", "11", - "amqp-routing-key", "internal.orders.retry.q"); - - ReplayRecord record = mapper.map(withBrokerNoise, "{}").record().orElseThrow(); - - // The record's components are the whole contract: there is nowhere for the broker's headers to - // travel. - assertThat(record.streamId()).isEqualTo("orders"); - assertThat(record.payload()).isEqualTo("{}"); - assertThat( - java.util.Arrays.stream(ReplayRecord.class.getRecordComponents()) - .map(java.lang.reflect.RecordComponent::getName) - .toList()) - .containsExactly("streamId", "sequence", "type", "payload", "occurredAt"); - } -} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/codec/BinaryCodecBackendScopeTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/codec/BinaryCodecBackendScopeTest.java deleted file mode 100644 index 03365882..00000000 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/codec/BinaryCodecBackendScopeTest.java +++ /dev/null @@ -1,162 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.codec; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.adapter.inbound.websocket.moduleboundary.WebSocketBuildModel; -import java.io.IOException; -import java.io.UncheckedIOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * The two binary backends stay off every adopter's runtime classpath. - * - *

This reads the build file because that is where the mistake is made. Both jars were {@code - * implementation} first, on the reasoning that an enabled codec should fail at startup rather than - * at the first frame. The reasoning missed what the jars do by merely being present: Spring Boot - * registers a {@code cborMapper} bean when Jackson's CBOR backend is on the runtime classpath, and - * Spring registers a Protobuf message converter when protobuf-java is. The sibling web leaf shipped - * the same mistake and the consequence was concrete — three {@code ObjectMapper} beans in the - * composition root, every {@code @Autowired ObjectMapper} ambiguous, and the application refusing - * to start. - * - *

Nothing else catches it. The codec's own tests pass either way, because the test source set - * has the jars. The failure appears only in whatever composes this leaf, which is a different - * build. - */ -class BinaryCodecBackendScopeTest { - - private static String buildFile() { - Path build = WebSocketBuildModel.mainSourceRoot().getParent().getParent().getParent(); - Path file = build.resolve("build.gradle"); - if (!Files.isRegularFile(file)) { - throw new IllegalStateException( - "cannot locate this leaf's build.gradle at " + file + "; the scope rule checks nothing"); - } - try { - return Files.readString(file); - } catch (IOException failure) { - throw new UncheckedIOException(failure); - } - } - - /** - * Reports whether the build file declares the coordinate in the given scope. - * - *

Two notations mean the same declaration. The literal {@code 'group:artifact:version'} form - * is matched directly; the version-catalog form is matched by resolving the leaf's {@code libs.*} - * accessors back to their modules. Matching only the literal string would have read {@code - * compileOnly libs.protobuf.java} as "not declared" — a scope contract reported as broken because - * versions moved into a catalog, which is a false positive expensive enough to be worth the - * parser. - */ - private static boolean declares(String scope, String coordinate) { - if (declaresLiterally(scope, coordinate)) { - return true; - } - for (Map.Entry alias : catalogModules().entrySet()) { - if (alias.getValue().equals(coordinate) - && Pattern.compile( - "^\\s*" + scope + "\\s+" + Pattern.quote(alias.getKey()) + "\\s*$", - Pattern.MULTILINE) - .matcher(buildFile()) - .find()) { - return true; - } - } - return false; - } - - /** Version-catalog accessor to {@code group:artifact}, parsed from the catalog itself. */ - private static Map catalogModules() { - Path catalog = - WebSocketBuildModel.mainSourceRoot() - .getParent() - .getParent() - .getParent() - .getParent() - .getParent() - .getParent() - .resolve("gradle/libs.versions.toml"); - Map modules = new LinkedHashMap<>(); - if (!Files.isRegularFile(catalog)) { - return modules; - } - try { - Matcher entry = - Pattern.compile("(?m)^([A-Za-z0-9_-]+)\\s*=\\s*\\{[^}]*module\\s*=\\s*\"([^\"]+)\"") - .matcher(Files.readString(catalog)); - while (entry.find()) { - modules.put("libs." + entry.group(1).replace('-', '.').replace('_', '.'), entry.group(2)); - } - } catch (IOException failure) { - throw new UncheckedIOException(failure); - } - return modules; - } - - private static boolean declaresLiterally(String scope, String coordinate) { - return Pattern.compile( - "^\\s*" + scope + "\\s+'" + Pattern.quote(coordinate) + "(:|')", Pattern.MULTILINE) - .matcher(buildFile()) - .find(); - } - - @Test - @DisplayName("neither backend is an implementation dependency") - void backendsAreNotOnTheRuntimeClasspath() { - for (WebSocketBinaryCodecBackend backend : WebSocketBinaryCodecBackend.values()) { - assertThat(declares("implementation", backend.coordinate())) - .as( - "%s must not be an implementation dependency: on an adopter's runtime classpath it" - + " registers a bean nobody asked for", - backend.coordinate()) - .isFalse(); - } - } - - @Test - @DisplayName("both backends are compile-only, so the codecs still compile") - void backendsAreCompileOnly() { - for (WebSocketBinaryCodecBackend backend : WebSocketBinaryCodecBackend.values()) { - assertThat(declares("compileOnly", backend.coordinate())) - .as("%s must be compileOnly", backend.coordinate()) - .isTrue(); - } - } - - @Test - @DisplayName("both backends are on the test classpath, so the codecs are actually exercised") - void backendsAreOnTheTestClasspath() { - // The other half. compileOnly alone would leave the codec tests unable to run, and a codec - // whose tests cannot run is worse than one that is absent. - for (WebSocketBinaryCodecBackend backend : WebSocketBinaryCodecBackend.values()) { - assertThat(declares("testImplementation", backend.coordinate())) - .as("%s must be on the test classpath", backend.coordinate()) - .isTrue(); - assertThat(backend.available()) - .as("%s must actually resolve in this lane", backend.coordinate()) - .isTrue(); - } - } - - @Test - @DisplayName("an absent backend would be refused by name rather than by NoClassDefFoundError") - void absentBackendIsNamed() { - // The message a deployment reads when it enables a capability and forgets the jar. Asserted on - // the text because the text is the entire value of the check. - for (WebSocketBinaryCodecBackend backend : WebSocketBinaryCodecBackend.values()) { - assertThat(backend.coordinate()).contains(":"); - } - assertThat(WebSocketBinaryCodecBackend.CBOR.coordinate()) - .isEqualTo("tools.jackson.dataformat:jackson-dataformat-cbor"); - assertThat(WebSocketBinaryCodecBackend.PROTOBUF.coordinate()) - .isEqualTo("com.google.protobuf:protobuf-java"); - } -} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/codec/BinaryCodecRoundTripTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/codec/BinaryCodecRoundTripTest.java deleted file mode 100644 index 9419ed36..00000000 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/codec/BinaryCodecRoundTripTest.java +++ /dev/null @@ -1,316 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.codec; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import com.google.protobuf.DescriptorProtos.DescriptorProto; -import com.google.protobuf.DescriptorProtos.FieldDescriptorProto; -import com.google.protobuf.DescriptorProtos.FileDescriptorProto; -import com.google.protobuf.Descriptors; -import com.google.protobuf.DynamicMessage; -import dev.caskeleton.adapter.inbound.websocket.advanced.codec.cbor.CborCodecProfile; -import dev.caskeleton.adapter.inbound.websocket.advanced.codec.cbor.DuplicateKeyPolicy; -import dev.caskeleton.adapter.inbound.websocket.advanced.codec.cbor.WebSocketCborCodec; -import dev.caskeleton.adapter.inbound.websocket.advanced.codec.protobuf.ProtobufCodecProfile; -import dev.caskeleton.adapter.inbound.websocket.advanced.codec.protobuf.WebSocketProtobufCodec; -import dev.caskeleton.adapter.inbound.websocket.codec.WebSocketDecodeException; -import dev.caskeleton.adapter.inbound.websocket.codec.WebSocketWireTypeManifest; -import dev.caskeleton.adapter.inbound.websocket.error.WebSocketFailureCategory; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageCatalog; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageDescriptor; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageDirection; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageFamily; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageType; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketSchemaVersion; -import java.util.List; -import java.util.Map; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -/** - * The two binary codecs, exercised end to end rather than asserted about. - * - *

The Protobuf side builds its descriptor at runtime from a {@code FileDescriptorProto}, which - * is how protobuf works when the schema is not known at build time. That is not a shortcut for the - * test — it is the same mechanism the codec uses in production, because a template ships no {@code - * .proto} of its own. - */ -@Tag("websocket-advanced") -class BinaryCodecRoundTripTest { - - private static final WebSocketMessageType PLACED = new WebSocketMessageType("order.placed.v1"); - private static final WebSocketMessageType UNPUBLISHED = - new WebSocketMessageType("order.secret.v1"); - - /** A wire record the CBOR codec decodes into. */ - public record OrderPlaced(String orderId, int quantity) {} - - private static WebSocketMessageCatalog catalog() { - return WebSocketMessageCatalog.of( - List.of( - new WebSocketMessageDescriptor( - PLACED, - WebSocketMessageFamily.COMMAND, - WebSocketMessageDirection.BIDIRECTIONAL, - WebSocketSchemaVersion.v(1)))); - } - - private static BinaryCodecProfile binary(int maxBytes) { - return new BinaryCodecProfile(true, WebSocketSchemaVersion.v(1), maxBytes, false); - } - - private static WebSocketCborCodec cborCodec(int maxBytes) { - return new WebSocketCborCodec( - catalog(), - WebSocketWireTypeManifest.of(Map.of(PLACED, OrderPlaced.class)), - CborCodecProfile.strict(binary(maxBytes))); - } - - // ---- CBOR ---- - - @Test - @DisplayName("a CBOR round trip returns the same record") - void cborRoundTrips() { - WebSocketCborCodec codec = cborCodec(65_536); - OrderPlaced sent = new OrderPlaced("ord-1", 3); - - byte[] encoded = codec.encodeToClient(PLACED, sent); - - assertThat(codec.decodeFromClient(PLACED, WebSocketMessageFamily.COMMAND, encoded)) - .isEqualTo(sent); - } - - @Test - @DisplayName("an unpublished type never reaches the CBOR parser") - void cborRefusesUnpublishedTypes() { - // The catalog is consulted first, so a second decode path does not widen the set of reachable - // types. - assertThatThrownBy( - () -> - cborCodec(65_536) - .decodeFromClient(UNPUBLISHED, WebSocketMessageFamily.COMMAND, new byte[] {0})) - .isInstanceOf(WebSocketDecodeException.class) - .extracting(failure -> ((WebSocketDecodeException) failure).category()) - .isEqualTo(WebSocketFailureCategory.UNKNOWN_TYPE); - } - - @Test - @DisplayName("a CBOR frame beyond the ceiling is refused before parsing") - void cborRefusesOversizedFrames() { - // Checked before the parser sees it. CBOR declares a collection's length ahead of its contents, - // so a limit applied afterwards has already paid for the allocation. - WebSocketCborCodec codec = cborCodec(8); - - assertThatThrownBy( - () -> codec.decodeFromClient(PLACED, WebSocketMessageFamily.COMMAND, new byte[64])) - .isInstanceOf(WebSocketDecodeException.class) - .extracting(failure -> ((WebSocketDecodeException) failure).category()) - .isEqualTo(WebSocketFailureCategory.TOO_LARGE); - } - - @Test - @DisplayName("a codec that would resolve duplicate keys is refused at construction") - void cborRefusesAnAmbiguousProfile() { - // Bytes with two readings, and which one a component sees depends on which decoder it uses. - assertThatThrownBy( - () -> - new WebSocketCborCodec( - catalog(), - WebSocketWireTypeManifest.of(Map.of(PLACED, OrderPlaced.class)), - new CborCodecProfile(binary(1024), true, DuplicateKeyPolicy.LAST_WINS))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("two different things to two readers"); - } - - @Test - @DisplayName("a CBOR frame with an unknown field is refused") - void cborRefusesUnknownFields() { - WebSocketCborCodec codec = cborCodec(65_536); - byte[] extra = - cborCodec(65_536) - .encodeToClient(PLACED, Map.of("orderId", "ord-1", "quantity", 3, "surprise", "x")); - - assertThatThrownBy(() -> codec.decodeFromClient(PLACED, WebSocketMessageFamily.COMMAND, extra)) - .isInstanceOf(WebSocketDecodeException.class) - .extracting(failure -> ((WebSocketDecodeException) failure).category()) - .isEqualTo(WebSocketFailureCategory.MALFORMED); - } - - // ---- Protobuf ---- - - /** - * The one descriptor instance this test uses. - * - *

Shared rather than rebuilt per call, because protobuf compares descriptors by identity and - * so does the codec. That is the right contract: a deployment compiles its schema once and builds - * every message from it, and two independently compiled copies of the same {@code .proto} are two - * different schemas as far as protobuf is concerned. - */ - private static final Descriptors.Descriptor ORDER_DESCRIPTOR = buildOrderDescriptor(); - - /** Compiles a two-field message descriptor at runtime, as a deployment's schema would. */ - private static Descriptors.Descriptor buildOrderDescriptor() { - FileDescriptorProto file = - FileDescriptorProto.newBuilder() - .setName("order.proto") - .setSyntax("proto3") - .addMessageType( - DescriptorProto.newBuilder() - .setName("OrderPlaced") - .addField( - FieldDescriptorProto.newBuilder() - .setName("order_id") - .setNumber(1) - .setType(FieldDescriptorProto.Type.TYPE_STRING) - .setLabel(FieldDescriptorProto.Label.LABEL_OPTIONAL)) - .addField( - FieldDescriptorProto.newBuilder() - .setName("quantity") - .setNumber(2) - .setType(FieldDescriptorProto.Type.TYPE_INT32) - .setLabel(FieldDescriptorProto.Label.LABEL_OPTIONAL))) - .build(); - try { - return Descriptors.FileDescriptor.buildFrom(file, new Descriptors.FileDescriptor[0]) - .findMessageTypeByName("OrderPlaced"); - } catch (Descriptors.DescriptorValidationException invalid) { - throw new IllegalStateException(invalid); - } - } - - private static WebSocketProtobufCodec protobufCodec(int maxBytes) { - return new WebSocketProtobufCodec( - catalog(), - Map.of(PLACED, ORDER_DESCRIPTOR), - new ProtobufCodecProfile("orders-descriptors:1", binary(maxBytes))); - } - - @Test - @DisplayName("a Protobuf round trip returns the same field values") - void protobufRoundTrips() { - Descriptors.Descriptor descriptor = ORDER_DESCRIPTOR; - WebSocketProtobufCodec codec = protobufCodec(65_536); - DynamicMessage sent = - DynamicMessage.newBuilder(descriptor) - .setField(descriptor.findFieldByName("order_id"), "ord-1") - .setField(descriptor.findFieldByName("quantity"), 3) - .build(); - - byte[] encoded = codec.encodeToClient(PLACED, sent); - var decoded = codec.decodeFromClient(PLACED, WebSocketMessageFamily.COMMAND, encoded); - - assertThat(decoded.getField(decoded.getDescriptorForType().findFieldByName("order_id"))) - .isEqualTo("ord-1"); - assertThat(decoded.getField(decoded.getDescriptorForType().findFieldByName("quantity"))) - .isEqualTo(3); - } - - @Test - @DisplayName("a Protobuf frame carrying an unpublished field is refused, not silently dropped") - void protobufRefusesUnknownFields() { - // Protobuf's default is to retain unknown fields so an intermediary can round-trip them, which - // at a trust boundary means re-emitting bytes this server never validated — and a field the - // server cannot see is one its authorization checks cannot consider. - Descriptors.Descriptor wider = widerDescriptor(); - DynamicMessage fromNewerPeer = - DynamicMessage.newBuilder(wider) - .setField(wider.findFieldByName("order_id"), "ord-1") - .setField(wider.findFieldByName("quantity"), 3) - .setField(wider.findFieldByName("discount_code"), "SECRET") - .build(); - - assertThatThrownBy( - () -> - protobufCodec(65_536) - .decodeFromClient( - PLACED, WebSocketMessageFamily.COMMAND, fromNewerPeer.toByteArray())) - .isInstanceOf(WebSocketDecodeException.class) - .hasMessageContaining("fields this build does not publish"); - } - - @Test - @DisplayName("a message built against another descriptor is refused on encode") - void protobufRefusesAForeignDescriptor() { - // Field numbers collide across schemas, so the peer would decode a well-formed message with - // the wrong values rather than failing to parse. - Descriptors.Descriptor wider = widerDescriptor(); - DynamicMessage foreign = - DynamicMessage.newBuilder(wider).setField(wider.findFieldByName("order_id"), "x").build(); - - assertThatThrownBy(() -> protobufCodec(65_536).encodeToClient(PLACED, foreign)) - .isInstanceOf(WebSocketDecodeException.class) - .hasMessageContaining("built against a different descriptor"); - } - - @Test - @DisplayName("an unpublished type never reaches the Protobuf parser") - void protobufRefusesUnpublishedTypes() { - assertThatThrownBy( - () -> - protobufCodec(65_536) - .decodeFromClient(UNPUBLISHED, WebSocketMessageFamily.COMMAND, new byte[] {})) - .isInstanceOf(WebSocketDecodeException.class) - .extracting(failure -> ((WebSocketDecodeException) failure).category()) - .isEqualTo(WebSocketFailureCategory.UNKNOWN_TYPE); - } - - @Test - @DisplayName("a codec with no descriptor is refused at construction") - void protobufRefusesAnEmptyDescriptorSet() { - assertThatThrownBy( - () -> - new WebSocketProtobufCodec( - catalog(), Map.of(), new ProtobufCodecProfile("none:0", binary(1024)))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("should not enable the capability"); - } - - @Test - @DisplayName("a Protobuf frame beyond the ceiling is refused before parsing") - void protobufRefusesOversizedFrames() { - assertThatThrownBy( - () -> - protobufCodec(8) - .decodeFromClient(PLACED, WebSocketMessageFamily.COMMAND, new byte[64])) - .isInstanceOf(WebSocketDecodeException.class) - .extracting(failure -> ((WebSocketDecodeException) failure).category()) - .isEqualTo(WebSocketFailureCategory.TOO_LARGE); - } - - /** The same message with one extra field, standing in for a newer peer's schema. */ - private static Descriptors.Descriptor widerDescriptor() { - FileDescriptorProto file = - FileDescriptorProto.newBuilder() - .setName("order-wider.proto") - .setSyntax("proto3") - .addMessageType( - DescriptorProto.newBuilder() - .setName("OrderPlaced") - .addField( - FieldDescriptorProto.newBuilder() - .setName("order_id") - .setNumber(1) - .setType(FieldDescriptorProto.Type.TYPE_STRING) - .setLabel(FieldDescriptorProto.Label.LABEL_OPTIONAL)) - .addField( - FieldDescriptorProto.newBuilder() - .setName("quantity") - .setNumber(2) - .setType(FieldDescriptorProto.Type.TYPE_INT32) - .setLabel(FieldDescriptorProto.Label.LABEL_OPTIONAL)) - .addField( - FieldDescriptorProto.newBuilder() - .setName("discount_code") - .setNumber(3) - .setType(FieldDescriptorProto.Type.TYPE_STRING) - .setLabel(FieldDescriptorProto.Label.LABEL_OPTIONAL))) - .build(); - try { - return Descriptors.FileDescriptor.buildFrom(file, new Descriptors.FileDescriptor[0]) - .findMessageTypeByName("OrderPlaced"); - } catch (Descriptors.DescriptorValidationException invalid) { - throw new IllegalStateException(invalid); - } - } -} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/codec/BinaryCodecTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/codec/BinaryCodecTest.java deleted file mode 100644 index 9937fc3e..00000000 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/codec/BinaryCodecTest.java +++ /dev/null @@ -1,178 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.codec; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.websocket.advanced.codec.cbor.CborCodecProfile; -import dev.caskeleton.adapter.inbound.websocket.advanced.codec.cbor.DuplicateKeyPolicy; -import dev.caskeleton.adapter.inbound.websocket.advanced.codec.protobuf.DescriptorCompatibility; -import dev.caskeleton.adapter.inbound.websocket.advanced.codec.protobuf.DescriptorCompatibilityGate; -import dev.caskeleton.adapter.inbound.websocket.advanced.codec.protobuf.ProtobufCodecProfile; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageType; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketSchemaVersion; -import java.util.Map; -import java.util.Set; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -/** - * A second codec is only safe if it means the same thing as the first. - * - *

Every case here is a way two codecs can both be individually correct and still disagree about - * what a frame said. - */ -@Tag("websocket-advanced") -class BinaryCodecTest { - - private static final WebSocketSchemaVersion V1 = WebSocketSchemaVersion.v(1); - - private static BinaryCodecProfile binary(int maxBytes) { - return new BinaryCodecProfile(true, V1, maxBytes, false); - } - - @Test - @DisplayName("a binary frame names its message type as the JSON one does") - void binaryFramesNameTheirType() { - // Without it the reader guesses from context, and a client that switched format has silently - // switched contract. - assertThatThrownBy(() -> new BinaryCodecProfile(false, V1, 1024, false)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("switched contract"); - } - - @Test - @DisplayName("a length-prefixed codec is bounded") - void lengthPrefixedCodecIsBounded() { - // The frame carries a length and the decoder allocates it, so a frame within the transport - // limit can still declare a length far beyond it. - assertThatThrownBy(() -> new BinaryCodecProfile(true, V1, 0, false)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("allocate the length it was told"); - assertThat(binary(1024).withinBounds(1024)).isTrue(); - assertThat(binary(1024).withinBounds(1025)).isFalse(); - } - - @Test - @DisplayName("a reused or retyped protobuf field number is breaking") - void retypedFieldNumberIsBreaking() { - // Nothing errors. The receiver reads a value of the right type in the wrong place, which - // surfaces as a data bug far from the change. - assertThat( - DescriptorCompatibilityGate.compare( - Map.of(1, "string", 2, "int64"), Map.of(1, "string", 2, "bytes"))) - .isEqualTo(DescriptorCompatibility.BREAKING); - - assertThatThrownBy( - () -> - DescriptorCompatibilityGate.verify( - Map.of(1, "string", 2, "int64"), Map.of(1, "string", 2, "bytes"))) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("reads the wrong field without erroring"); - } - - @Test - @DisplayName("adding and removing fields are classified apart") - void addAndRemoveAreClassifiedApart() { - // They need opposite rollout orders: added fields want writers upgraded first, removed fields - // want readers upgraded first, and doing both at once has no safe order at all. - assertThat( - DescriptorCompatibilityGate.compare( - Map.of(1, "string"), Map.of(1, "string", 2, "int64"))) - .isEqualTo(DescriptorCompatibility.BACKWARD_COMPATIBLE); - assertThat( - DescriptorCompatibilityGate.compare( - Map.of(1, "string", 2, "int64"), Map.of(1, "string"))) - .isEqualTo(DescriptorCompatibility.FORWARD_COMPATIBLE); - assertThat( - DescriptorCompatibilityGate.compare( - Map.of(1, "string", 2, "int64"), Map.of(1, "string", 3, "int64"))) - .isEqualTo(DescriptorCompatibility.BREAKING); - assertThat(DescriptorCompatibilityGate.compare(Map.of(1, "string"), Map.of(1, "string"))) - .isEqualTo(DescriptorCompatibility.FULLY_COMPATIBLE); - } - - @Test - @DisplayName("a renamed field is invisible, which is why the gate reads numbers") - void renamesAreInvisibleToTheWire() { - // Field names are absent from the encoding entirely. A gate comparing names would pass exactly - // the changes that matter and fail the ones that do not. - assertThat(DescriptorCompatibilityGate.compare(Map.of(7, "string"), Map.of(7, "string"))) - .isEqualTo(DescriptorCompatibility.FULLY_COMPATIBLE); - } - - @Test - @DisplayName("the protobuf codec is not an attachment transport") - void protobufIsNotAnAttachmentTransport() { - // The broker, the replay store and every in-memory queue would each hold the payload whole. - assertThatThrownBy(() -> new ProtobufCodecProfile("orders-descriptors:3", binary(1_000_000))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("attachment transport"); - assertThat(new ProtobufCodecProfile("orders-descriptors:3", binary(65_536)).withinBounds(4096)) - .isTrue(); - } - - @Test - @DisplayName("an unnamed descriptor artifact is refused") - void unnamedDescriptorArtifactIsRefused() { - assertThatThrownBy(() -> new ProtobufCodecProfile(" ", binary(1024))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("not a version that can be compared"); - } - - @Test - @DisplayName("a CBOR map with a duplicate key is refused, not resolved") - void duplicateCborKeysAreRefused() { - // RFC 8949 leaves the resolution to the decoder. A validator reading the first value and an - // executor reading the last disagree about what the message said, and the attacker picks both. - assertThat(CborCodecProfile.strict(binary(1024)).unambiguous()).isTrue(); - assertThat(new CborCodecProfile(binary(1024), true, DuplicateKeyPolicy.LAST_WINS).unambiguous()) - .isFalse(); - } - - @Test - @DisplayName("canonical encoding is part of the profile, not a decoder default") - void canonicalEncodingIsDeclared() { - assertThat(CborCodecProfile.strict(binary(1024)).canonicalEncodingRequired()).isTrue(); - } - - @Test - @DisplayName("a codec that publishes a different catalog than JSON is refused") - void catalogParityIsEnforced() { - // Neither direction shows up in a codec's own round-trip test, which is why this compares - // catalogs rather than encodings. - WebSocketMessageType placed = new WebSocketMessageType("order.placed.v1"); - WebSocketMessageType cancelled = new WebSocketMessageType("order.cancelled.v1"); - - assertThat(SchemaParity.differences(Set.of(placed), Set.of(placed))).isEmpty(); - assertThat(SchemaParity.differences(Set.of(placed, cancelled), Set.of(placed))) - .singleElement() - .asString() - .contains("a client that switches format loses them"); - assertThat(SchemaParity.differences(Set.of(placed), Set.of(placed, cancelled))) - .singleElement() - .asString() - .contains("was not reviewed as accepting"); - assertThatThrownBy(() -> SchemaParity.verify(Set.of(placed), Set.of(cancelled))) - .isInstanceOf(IllegalStateException.class); - } - - @Test - @DisplayName("agreeing on the type but not on what it decodes to is caught") - void bindingParityIsEnforced() { - // Same types is not enough: a handler receiving a well-formed object of the wrong shape is - // the result. - WebSocketMessageType placed = new WebSocketMessageType("order.placed.v1"); - - assertThat( - SchemaParity.bindingDifferences( - Map.of(placed, String.class), Map.of(placed, Integer.class))) - .singleElement() - .asString() - .contains("decodes to java.lang.String as JSON and java.lang.Integer in binary"); - assertThat( - SchemaParity.bindingDifferences( - Map.of(placed, String.class), Map.of(placed, String.class))) - .isEmpty(); - } -} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/compression/CompressionPolicyTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/compression/CompressionPolicyTest.java deleted file mode 100644 index 79506fc9..00000000 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/compression/CompressionPolicyTest.java +++ /dev/null @@ -1,104 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.compression; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketEndpointName; -import java.util.Map; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -/** The two ways permessage-deflate goes wrong: the length side channel, and the memory. */ -@Tag("websocket-advanced") -class CompressionPolicyTest { - - private static final WebSocketEndpointName FEED = new WebSocketEndpointName("public-feed"); - private static final WebSocketEndpointName SESSION = new WebSocketEndpointName("user-session"); - private static final WebSocketEndpointName UNKNOWN = new WebSocketEndpointName("not-declared"); - - private static CompressionPolicy policy() { - return new CompressionPolicy( - CompressionProfile.boundedMemory(15, 1024), - 1_048_576, - Map.of( - FEED, - EndpointContentClass.PUBLIC_DATA, - SESSION, - EndpointContentClass.SENSITIVE_WITH_ATTACKER_INFLUENCE)); - } - - @Test - @DisplayName("compression is off unless the profile says otherwise") - void compressionIsOffByDefault() { - assertThat(CompressionProfile.disabled().enabled()).isFalse(); - assertThat(CompressionProfile.disabled().shouldCompress(100_000)).isFalse(); - } - - @Test - @DisplayName("an endpoint mixing a secret with attacker input never compresses") - void crimeShapedEndpointNeverCompresses() { - // No parameter combination makes it safe: the leak is in the compressed length, which every - // setting produces. An attacker who injects a guess into each message recovers the secret a - // byte at a time. - assertThat(policy().mayCompress(SESSION)).isFalse(); - assertThat(policy().mayCompress(FEED)).isTrue(); - } - - @Test - @DisplayName("an endpoint nobody classified does not compress") - void unclassifiedEndpointDoesNotCompress() { - // Defaulting the other way makes every endpoint somebody forgot to classify a candidate for - // the failure above. - assertThat(policy().mayCompress(UNKNOWN)).isFalse(); - assertThat(policy().contentClassOf(UNKNOWN)).isEmpty(); - } - - @Test - @DisplayName("compression without a decompressed-size ceiling is refused") - void unboundedInflationIsRefused() { - // A 64KB frame inside every inbound bound can inflate to 64MB. The check has to be during - // inflation, not after, or the allocation has already happened. - assertThatThrownBy( - () -> new CompressionPolicy(CompressionProfile.boundedMemory(15, 0), 0, Map.of())) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("hundreds of times larger"); - } - - @Test - @DisplayName("inflation stops at the ceiling") - void inflationStopsAtTheCeiling() { - CompressionPolicy policy = policy(); - - assertThat(policy.mayInflateFurther(1_048_576)).isTrue(); - assertThat(policy.mayInflateFurther(1_048_577)).isFalse(); - assertThat(policy.permittedRatioFor(1024)).isEqualTo(1024); - } - - @Test - @DisplayName("context takeover is what makes memory scale with connection lifetime") - void contextTakeoverCostsMemoryPerConnection() { - // With both windows kept alive, ten thousand connections is 640MB of sliding window before a - // single message is buffered. - assertThat(new CompressionProfile(true, false, false, 15, 0).windowBytesPerConnection()) - .isEqualTo(65_536); - assertThat(CompressionProfile.boundedMemory(15, 0).windowBytesPerConnection()).isZero(); - } - - @Test - @DisplayName("a window size outside RFC 7692 is refused") - void invalidWindowBitsAreRefused() { - assertThatThrownBy(() -> CompressionProfile.boundedMemory(16, 0)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("RFC 7692"); - assertThatThrownBy(() -> CompressionProfile.boundedMemory(7, 0)) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("small messages are sent uncompressed") - void smallMessagesAreNotCompressed() { - assertThat(CompressionProfile.boundedMemory(15, 1024).shouldCompress(1023)).isFalse(); - assertThat(CompressionProfile.boundedMemory(15, 1024).shouldCompress(1024)).isTrue(); - } -} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/graphql/GraphQlTransportBridgePolicyTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/graphql/GraphQlTransportBridgePolicyTest.java deleted file mode 100644 index 0cd7e7ab..00000000 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/graphql/GraphQlTransportBridgePolicyTest.java +++ /dev/null @@ -1,66 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.graphql; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -/** A transport bridge, and the two things it is not allowed to become. */ -@Tag("websocket-advanced") -class GraphQlTransportBridgePolicyTest { - - @Test - @DisplayName("the bridge does not own GraphQL semantics") - void bridgeDoesNotOwnGraphQlSemantics() { - // graphql-transport-ws has a lifecycle that looks enough like a message protocol to - // reimplement by accident, and a second definition of what an error is disagrees with the - // first the moment a resolver throws something it did not anticipate. - assertThat(GraphQlTransportBridgePolicy.standard().ownsGraphQlSemantics()).isFalse(); - assertThatThrownBy( - () -> - new GraphQlTransportBridgePolicy( - GraphQlTransportBridgePolicy.SUBPROTOCOL, true, true)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("a resolver throws something it did not anticipate"); - } - - @Test - @DisplayName("the bridge reuses the Stable connection runtime") - void bridgeReusesTheStableRuntime() { - // Its own would have its own heartbeat, queue bound, backpressure and security checks, none of - // them the ones the platform was reviewed with. - assertThat(GraphQlTransportBridgePolicy.standard().usesStableConnectionRuntime()).isTrue(); - assertThatThrownBy( - () -> - new GraphQlTransportBridgePolicy( - GraphQlTransportBridgePolicy.SUBPROTOCOL, false, false)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("reviewed with"); - } - - @Test - @DisplayName("the subprotocol token is the one the specification defines") - void subprotocolIsTheSpecifiedToken() { - assertThat(GraphQlTransportBridgePolicy.standard().subprotocol()) - .isEqualTo("graphql-transport-ws"); - } - - @Test - @DisplayName("the GraphQL lifecycle frames are forwarded rather than interpreted") - void lifecycleFramesAreForwarded() { - assertThat(GraphQlTransportBridgePolicy.standard().forwardedWithoutInterpretation()) - .anyMatch(line -> line.contains("connection_init")) - .anyMatch(line -> line.contains("subscribe, next, complete and error")); - } - - @Test - @DisplayName("the Stable budgets are reused rather than restated") - void stableBudgetsAreReused() { - assertThat(GraphQlTransportBridgePolicy.standard().reusedFromStable()) - .anyMatch(line -> line.contains("connection budget")) - .anyMatch(line -> line.contains("shedding bound")) - .anyMatch(line -> line.contains("heartbeat")); - } -} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/graphql/GraphQlTransportBridgeTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/graphql/GraphQlTransportBridgeTest.java deleted file mode 100644 index 925f400f..00000000 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/graphql/GraphQlTransportBridgeTest.java +++ /dev/null @@ -1,177 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.graphql; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketActorReference; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketConnectionContext; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketConnectionId; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketConnectionState; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketCredentialExpiry; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketEndpointName; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketNodeId; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketSessionId; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketSubprotocolName; -import java.nio.charset.StandardCharsets; -import java.time.Duration; -import java.time.Instant; -import java.util.Optional; -import java.util.concurrent.atomic.AtomicInteger; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -/** - * The three rules the transport enforces, and the everything-else it does not. - * - *

Each of the three is about the connection rather than about a query, which is why a GraphQL - * engine cannot enforce them and this bridge must. - */ -@Tag("websocket-advanced") -class GraphQlTransportBridgeTest { - - private static final Instant OPENED = Instant.parse("2026-08-25T10:00:00Z"); - private static final Duration DEADLINE = Duration.ofSeconds(10); - - private static final byte[] SALT = - "a-deployment-salt-of-adequate-length".getBytes(StandardCharsets.UTF_8); - - private static WebSocketConnectionContext context() { - return new WebSocketConnectionContext( - new WebSocketConnectionId("c-01H8XQ2N4K"), - new WebSocketSessionId("s-01H8XQ2N4K"), - new WebSocketNodeId("edge-1"), - new WebSocketEndpointName("live-updates"), - Optional.of(WebSocketSubprotocolName.stable()), - WebSocketActorReference.of("alice", "acme", SALT), - WebSocketConnectionState.OPEN, - WebSocketCredentialExpiry.never(), - OPENED); - } - - private static GraphQlTransportBridge bridge() { - return new GraphQlTransportBridge(GraphQlTransportBridgePolicy.standard(), DEADLINE); - } - - @Test - @DisplayName("an unacknowledged connection is closed at the deadline") - void unacknowledgedConnectionTimesOut() { - // Without it an unauthenticated socket is held for as long as the peer cares to hold it, which - // is a connection slot spent by anyone who can open a TCP connection. - GraphQlTransportBridge bridge = bridge(); - - assertThat(bridge.initTimeoutAt(OPENED, OPENED.plusSeconds(9))).isEmpty(); - assertThat(bridge.initTimeoutAt(OPENED, OPENED.plusSeconds(10))) - .contains(GraphQlCloseCode.INITIALISATION_TIMEOUT); - } - - @Test - @DisplayName("an acknowledged connection never times out for initialisation") - void acknowledgedConnectionDoesNotTimeOut() { - GraphQlTransportBridge bridge = bridge(); - assertThat(bridge.onConnectionInit(OPENED)).isEmpty(); - - assertThat(bridge.initTimeoutAt(OPENED, OPENED.plusSeconds(600))).isEmpty(); - assertThat(bridge.acknowledged()).isTrue(); - } - - @Test - @DisplayName("a second connection_init is refused") - void secondInitIsRefused() { - // Not a retry: the first established the connection's parameters, and honouring a second would - // let a client change them mid-connection. - GraphQlTransportBridge bridge = bridge(); - bridge.onConnectionInit(OPENED); - - assertThat(bridge.onConnectionInit(OPENED.plusSeconds(1))) - .contains(GraphQlCloseCode.TOO_MANY_INITIALISATION_REQUESTS); - } - - @Test - @DisplayName("a subscribe before acknowledgement is unauthorized") - void subscribeBeforeInitIsUnauthorized() { - // Nothing has authenticated the connection yet, so serving it would run an operation for a peer - // nobody identified. - assertThat(bridge().onSubscribe("op-1")).contains(GraphQlCloseCode.UNAUTHORIZED); - } - - @Test - @DisplayName("two live subscriptions cannot share an operation id") - void duplicateSubscriptionIdIsRefused() { - // The id routes next and complete frames back, so sharing one interleaves two result streams - // into one with nothing to separate them. - GraphQlTransportBridge bridge = bridge(); - bridge.onConnectionInit(OPENED); - - assertThat(bridge.onSubscribe("op-1")).isEmpty(); - assertThat(bridge.onSubscribe("op-1")).contains(GraphQlCloseCode.SUBSCRIBER_ALREADY_EXISTS); - assertThat(bridge.onSubscribe("op-2")).isEmpty(); - assertThat(bridge.liveSubscriptions()).isEqualTo(2); - } - - @Test - @DisplayName("a completed id may be used again") - void completedIdIsReusable() { - // The specification permits it, and holding the id would make a client that numbers its - // operations sequentially fail on its second one. - GraphQlTransportBridge bridge = bridge(); - bridge.onConnectionInit(OPENED); - bridge.onSubscribe("op-1"); - bridge.onComplete("op-1"); - - assertThat(bridge.onSubscribe("op-1")).isEmpty(); - assertThat(bridge.liveSubscriptions()).isOne(); - } - - @Test - @DisplayName("a frame is forwarded byte for byte") - void framesAreForwardedUntouched() { - // Parsing here to "validate" would be the start of a second GraphQL implementation, and it - // would disagree with the engine's the first time a resolver throws something unanticipated. - AtomicInteger forwarded = new AtomicInteger(); - StringBuilder seen = new StringBuilder(); - bridge() - .forward( - context(), - "{\"type\":\"subscribe\",\"payload\":{\"query\":\"{ x }\"}}", - (context, payload) -> { - forwarded.incrementAndGet(); - seen.append(payload); - }); - - assertThat(forwarded.get()).isOne(); - assertThat(seen).hasToString("{\"type\":\"subscribe\",\"payload\":{\"query\":\"{ x }\"}}"); - } - - @Test - @DisplayName("a bridge without an init deadline is refused") - void deadlelessBridgeIsRefused() { - assertThatThrownBy( - () -> - new GraphQlTransportBridge(GraphQlTransportBridgePolicy.standard(), Duration.ZERO)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("anyone who can connect"); - } - - @Test - @DisplayName("the close reasons are fixed text, never the client's own input") - void closeReasonsAreFixed() { - // A close reason is echoed straight back over the wire, so reflecting client input makes a - // close frame an injection point into whatever reads the peer's logs. - for (GraphQlCloseCode code : GraphQlCloseCode.values()) { - assertThat(code.reason()).isNotBlank(); - assertThat(code.code()).isBetween(4000, 4999); - } - assertThat(GraphQlCloseCode.SUBSCRIBER_ALREADY_EXISTS.reason()) - .doesNotContain("op-") - .isEqualTo("subscriber already exists"); - } - - @Test - @DisplayName("the bridge states what it enforces and what it forwards") - void responsibilitiesAreStated() { - assertThat(bridge().enforcedByTheTransport()).hasSize(3); - assertThat(bridge().policy().ownsGraphQlSemantics()).isFalse(); - assertThat(bridge().policy().usesStableConnectionRuntime()).isTrue(); - } -} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/http2/HttpCompatibilityTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/http2/HttpCompatibilityTest.java deleted file mode 100644 index 36415ed7..00000000 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/http2/HttpCompatibilityTest.java +++ /dev/null @@ -1,91 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.http2; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.websocket.advanced.http3.Http3ExperimentalProfile; -import java.util.Set; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -/** - * The gap between a standard existing and a path supporting it. - * - *

RFC 8441 has been published since 2018 and a request still dies if any single hop does not - * implement extended CONNECT — and it dies, rather than negotiating a fallback. - */ -@Tag("websocket-advanced") -class HttpCompatibilityTest { - - @Test - @DisplayName("extended CONNECT cannot be enabled without a validated client and proxy") - void enablingWithoutEvidenceIsRefused() { - assertThatThrownBy(() -> new Http2CompatibilityProfile(true, Set.of("chrome"), Set.of())) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("rather than negotiating a fallback"); - assertThat(Http2CompatibilityProfile.disabled().enabled()).isFalse(); - } - - @Test - @DisplayName("an untested hop is refused, not assumed") - void untestedHopIsRefused() { - // The assumption is the whole failure: an untested intermediary is exactly the one that will - // not implement it. - Http2CompatibilityProfile profile = - new Http2CompatibilityProfile(true, Set.of("chrome"), Set.of("nginx-1.27")); - - assertThat(profile.supports("chrome", "nginx-1.27")).isTrue(); - assertThat(profile.supports("chrome", "corporate-proxy")).isFalse(); - assertThat(profile.supports("curl", "nginx-1.27")).isFalse(); - } - - @Test - @DisplayName("the classic upgrade path stays tested while extended CONNECT is on") - void classicUpgradeStaysTested() { - // It is what every unlisted client uses, and what the listed ones fall back to when a proxy is - // swapped. - assertThat(Http2CompatibilityProfile.disabled().fallbackPath()) - .anyMatch(line -> line.contains("Upgrade: websocket")) - .anyMatch(line -> line.contains("must keep passing its own contract test")); - } - - @Test - @DisplayName("HTTP/3 is never advertised as stable support") - void http3IsNeverStable() { - assertThat(new Http3ExperimentalProfile(true, "netty-quic", Set.of("chrome")).stableSupport()) - .isFalse(); - } - - @Test - @DisplayName("HTTP/3 promotion requires a rollback that does not need a deploy") - void http3PromotionRequiresRollback() { - // The population that cannot connect over QUIC is also the population that cannot be surveyed, - // so the way back has to work without shipping a build. - Http3ExperimentalProfile profile = - new Http3ExperimentalProfile(true, "netty-quic", Set.of("chrome")); - - assertThat(profile.promotable(true, true)).isTrue(); - assertThat(profile.promotable(false, true)).isFalse(); - assertThat(profile.promotable(true, false)).isFalse(); - assertThat(new Http3ExperimentalProfile(true, "netty-quic", Set.of()).promotable(true, true)) - .isFalse(); - } - - @Test - @DisplayName("the QUIC implementation is named because they differ") - void quicImplementationIsNamed() { - assertThatThrownBy(() -> new Http3ExperimentalProfile(true, " ", Set.of("chrome"))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("does not say which behaviour"); - } - - @Test - @DisplayName("the matrix records the dimensions a single pass/fail would hide") - void matrixDimensionsAreRecorded() { - assertThat(Http3ExperimentalProfile.disabled().requiredMatrixDimensions()) - .anyMatch(line -> line.contains("UDP")) - .anyMatch(line -> line.contains("packet loss")) - .anyMatch(line -> line.contains("proxy")); - } -} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/presence/PresenceSummaryTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/presence/PresenceSummaryTest.java deleted file mode 100644 index 4dd98e2c..00000000 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/presence/PresenceSummaryTest.java +++ /dev/null @@ -1,113 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.presence; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketActorReference; -import java.nio.charset.StandardCharsets; -import java.time.Duration; -import java.time.Instant; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -/** - * Presence, and the reason nothing important may depend on it. - * - *

It is derived from a cluster index that caches facts owned by other machines, so it is always - * a statement about the past. An attacker who can make a node stop reporting can therefore move the - * platform's belief about who is present — which is fine for a green dot and not for anything else. - */ -@Tag("websocket-advanced") -class PresenceSummaryTest { - - private static final Instant NOW = Instant.parse("2026-08-25T10:00:00Z"); - private static final Duration IDLE_AFTER = Duration.ofSeconds(30); - private static final Duration STALE_AFTER = Duration.ofSeconds(90); - private static final byte[] SALT = - "a-deployment-salt-of-adequate-length".getBytes(StandardCharsets.UTF_8); - private static final WebSocketActorReference ALICE = - WebSocketActorReference.of("alice", "acme", SALT); - - private static PresenceSummary at(int connections, long secondsLate) { - return PresenceSummary.classify( - ALICE, connections, NOW, IDLE_AFTER, STALE_AFTER, NOW.plusSeconds(secondsLate)); - } - - @Test - @DisplayName("recent connections are online, quiet ones are idle") - void recentConnectionsAreOnline() { - assertThat(at(2, 5).state()).isEqualTo(PresenceState.ONLINE); - assertThat(at(2, 45).state()).isEqualTo(PresenceState.IDLE); - assertThat(at(2, 45).appearsOnline()).isTrue(); - } - - @Test - @DisplayName("an observation nobody refreshed is stale, not offline") - void unrefreshedObservationIsStale() { - // The distinction that matters during an incident: a Redis partition makes every entry stop - // being refreshed. Reporting that as OFFLINE tells the operator every user disconnected, when - // what actually happened is that the index went dark and the connections are fine. - PresenceSummary summary = at(3, 120); - - assertThat(summary.state()).isEqualTo(PresenceState.STALE); - assertThat(summary.fresh()).isFalse(); - assertThat(summary.appearsOnline()).isFalse(); - } - - @Test - @DisplayName("staleness is judged before the connection count is believed") - void stalenessOutranksTheCount() { - // Reading the count first is precisely how a dead node keeps a green dot lit. - assertThat(at(9, 120).state()).isEqualTo(PresenceState.STALE); - } - - @Test - @DisplayName("a fresh observation of nothing is offline") - void freshEmptyObservationIsOffline() { - PresenceSummary summary = at(0, 5); - - assertThat(summary.state()).isEqualTo(PresenceState.OFFLINE); - assertThat(summary.fresh()).isTrue(); - assertThat(summary.appearsOnline()).isFalse(); - assertThat(PresenceSummary.absent(ALICE, NOW).state()).isEqualTo(PresenceState.OFFLINE); - } - - @Test - @DisplayName("presence keeps the count and the observation time together") - void countAndObservationTimeTravelTogether() { - // Either alone is misleading: a count without a time reads as current, and a time without a - // count cannot answer the question that was asked. - PresenceSummary summary = at(2, 5); - - assertThat(summary.activeConnectionCount()).isEqualTo(2); - assertThat(summary.lastObservedAt()).isEqualTo(NOW); - } - - @Test - @DisplayName("presence names an actor by fingerprint") - void presenceCarriesNoRawIdentity() { - assertThat(at(1, 1).actor().fingerprint()).doesNotContain("alice"); - } - - @Test - @DisplayName("offline with live connections is refused") - void offlineWithConnectionsIsRefused() { - assertThatThrownBy(() -> new PresenceSummary(ALICE, 2, PresenceState.OFFLINE, NOW)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("contradiction"); - } - - @Test - @DisplayName("an idle window at or past the stale window is refused") - void unreachableIdleWindowIsRefused() { - // Otherwise IDLE is unreachable and the caller believes it has a four-state model when it has - // three. - assertThatThrownBy( - () -> - PresenceSummary.classify( - ALICE, 1, NOW, Duration.ofSeconds(90), Duration.ofSeconds(90), NOW)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("silently unreachable"); - } -} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/release/AdvancedPromotionGateTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/release/AdvancedPromotionGateTest.java deleted file mode 100644 index a67abf02..00000000 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/release/AdvancedPromotionGateTest.java +++ /dev/null @@ -1,118 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.release; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.websocket.advanced.WebSocketAdvancedCapability; -import java.time.Duration; -import java.util.Set; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -/** What a capability has to show before it is allowed near production. */ -@Tag("websocket-advanced") -class AdvancedPromotionGateTest { - - private static AdvancedPromotionGate satisfied() { - return new AdvancedPromotionGate(Set.of("websocket:test"), Duration.ofHours(8), true, true); - } - - @Test - @DisplayName("capabilities are gated one at a time, with the suites their own failures need") - void capabilitiesAreGatedIndividually() { - // They share a feature-flag mechanism and nothing else. Promoting them together means the - // evidence for the cheapest is treated as evidence for the most dangerous. - assertThat( - AdvancedPromotionGate.forCapability(WebSocketAdvancedCapability.CLUSTER_REDIS) - .requiredSuites()) - .contains("multi-node-fanout", "node-loss"); - assertThat( - AdvancedPromotionGate.forCapability(WebSocketAdvancedCapability.BROKER_RELAY_RABBIT) - .requiredSuites()) - .contains("broker-outage", "broker-reconnect"); - assertThat( - AdvancedPromotionGate.forCapability(WebSocketAdvancedCapability.COMPRESSION) - .requiredSuites()) - .contains("decompression-bound", "memory-under-load"); - } - - @Test - @DisplayName("soak length scales with how long the failure takes to appear") - void soakScalesWithTheFailureMode() { - assertThat( - AdvancedPromotionGate.forCapability(WebSocketAdvancedCapability.HTTP3_EXPERIMENTAL) - .minimumSoak()) - .isEqualTo(Duration.ofDays(7)); - assertThat( - AdvancedPromotionGate.forCapability(WebSocketAdvancedCapability.CLUSTER_MESSAGING) - .minimumSoak()) - .isEqualTo(Duration.ofHours(24)); - assertThat( - AdvancedPromotionGate.forCapability(WebSocketAdvancedCapability.RESUME).minimumSoak()) - .isEqualTo(Duration.ofHours(8)); - } - - @Test - @DisplayName("a changed Stable contract blocks promotion") - void changedStableContractBlocksPromotion() { - // If enabling the capability changed Stable's wire contract or dependency graph, Stable was - // never independent of it, and deployments that did not enable it are affected anyway. - AdvancedPromotionGate gate = - new AdvancedPromotionGate(Set.of("websocket:test"), Duration.ofHours(8), true, false); - - assertThat(gate.blockers(Set.of("websocket:test"), Duration.ofHours(9))) - .singleElement() - .asString() - .contains("not independent of this capability"); - } - - @Test - @DisplayName("an unexercised rollback blocks promotion") - void unexercisedRollbackBlocksPromotion() { - // A flag nobody has turned off is not known to turn off, and the moment it is needed is the - // worst time to find out. - AdvancedPromotionGate gate = - new AdvancedPromotionGate(Set.of("websocket:test"), Duration.ofHours(8), false, true); - - assertThat(gate.blockers(Set.of("websocket:test"), Duration.ofHours(9))) - .singleElement() - .asString() - .contains("worst time to find out"); - } - - @Test - @DisplayName("blockers are listed rather than collapsed to a boolean") - void blockersAreEnumerated() { - // "Not yet" without a list is a gate somebody works around instead of satisfying. - AdvancedPromotionGate gate = - new AdvancedPromotionGate( - Set.of("websocket:test", "broker-outage"), Duration.ofHours(8), false, false); - - assertThat(gate.blockers(Set.of("websocket:test"), Duration.ofHours(1))) - .hasSize(4) - .anyMatch(line -> line.contains("broker-outage")) - .anyMatch(line -> line.contains("short of the required")) - .anyMatch(line -> line.contains("rollback not exercised")) - .anyMatch(line -> line.contains("dependency graph changed")); - } - - @Test - @DisplayName("a fully satisfied gate promotes") - void satisfiedGatePromotes() { - assertThat(satisfied().promotable(Set.of("websocket:test"), Duration.ofHours(8))).isTrue(); - assertThat(satisfied().promotable(Set.of("websocket:test"), Duration.ofHours(7))).isFalse(); - } - - @Test - @DisplayName("a gate requiring nothing is refused") - void emptyGateIsRefused() { - // It passes everything, which is worse than no gate because it reads as one. - assertThatThrownBy(() -> new AdvancedPromotionGate(Set.of(), Duration.ofHours(1), true, true)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("reads as one"); - assertThatThrownBy(() -> new AdvancedPromotionGate(Set.of("a"), Duration.ZERO, true, true)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("hours of real traffic"); - } -} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/resume/ResumeDecisionTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/resume/ResumeDecisionTest.java deleted file mode 100644 index 9fc5d363..00000000 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/resume/ResumeDecisionTest.java +++ /dev/null @@ -1,189 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.resume; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketActorReference; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketEndpointName; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketSessionId; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketSubprotocolName; -import java.nio.charset.StandardCharsets; -import java.time.Instant; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -/** - * What a reconnecting client is given, and the ways that decision goes quietly wrong. - * - *

Resume is the one moment a long-lived session's permissions are re-examined. The point of a - * session surviving a reconnect is that it does not re-authenticate — so a resume path that does - * not check authority is a path on which a revoked permission comes back with the client and stays - * until it stops reconnecting. - */ -@Tag("websocket-advanced") -class ResumeDecisionTest { - - private static final Instant NOW = Instant.parse("2026-08-25T10:00:00Z"); - private static final byte[] SALT = - "a-deployment-salt-of-adequate-length".getBytes(StandardCharsets.UTF_8); - private static final WebSocketSessionId SESSION = new WebSocketSessionId("s-01H8XQ2N4K"); - private static final WebSocketEndpointName ENDPOINT = new WebSocketEndpointName("live-updates"); - private static final WebSocketSubprotocolName PROTOCOL = WebSocketSubprotocolName.stable(); - private static final WebSocketActorReference ALICE = - WebSocketActorReference.of("alice", "acme", SALT); - - private static ResumeTokenPayload token(Map positions) { - return new ResumeTokenPayload( - SESSION, ALICE, ENDPOINT, PROTOCOL, positions, NOW, NOW.plusSeconds(60)); - } - - private ResumeDecision decide( - ResumeCoordinator coordinator, Set held, Map positions) { - return coordinator.decide( - token(positions), - ALICE, - ENDPOINT, - PROTOCOL, - held, - Set.of("feed:read"), - Map.of("orders", 100L), - NOW.plusSeconds(1)); - } - - @Test - @DisplayName("an available range is replayed from the next position") - void availableRangeIsReplayed() { - ResumeCoordinator coordinator = - new ResumeCoordinator(ReplayAvailability.of(Map.of("orders", 1L))); - - ResumeDecision decision = decide(coordinator, Set.of("feed:read"), Map.of("orders", 42L)); - - assertThat(decision.outcome()).isEqualTo(ResumeDecision.Outcome.REPLAY); - // From 43, not 42: the client said it saw 42, so replaying 42 would deliver it twice. - assertThat(decision.replayFrom().orElseThrow()).containsEntry("orders", 43L); - assertThat(decision.clientKeepsItsState()).isTrue(); - } - - @Test - @DisplayName("an aged-out range gets a snapshot with a new baseline") - void agedOutRangeGetsASnapshot() { - // Its own outcome because the client must discard what it had. Told this is a replay, it would - // merge current state into stale history and believe the result is continuous. - ResumeCoordinator coordinator = - new ResumeCoordinator(ReplayAvailability.of(Map.of("orders", 90L))); - - ResumeDecision decision = decide(coordinator, Set.of("feed:read"), Map.of("orders", 42L)); - - assertThat(decision.outcome()).isEqualTo(ResumeDecision.Outcome.SNAPSHOT); - assertThat(decision.snapshotBaseline().orElseThrow()).containsEntry("orders", 100L); - assertThat(decision.clientKeepsItsState()).isFalse(); - } - - @Test - @DisplayName("a revoked authority refuses the resume") - void revokedAuthorityRefusesResume() { - // The check that exists because a resume does not re-authenticate. Without it the permission - // comes back with the client every time it reconnects. - ResumeCoordinator coordinator = - new ResumeCoordinator(ReplayAvailability.of(Map.of("orders", 1L))); - - ResumeDecision decision = decide(coordinator, Set.of(), Map.of("orders", 42L)); - - assertThat(decision.outcome()).isEqualTo(ResumeDecision.Outcome.REFUSED); - assertThat(decision.reason()).contains("no longer holds"); - } - - @Test - @DisplayName("authorisation is checked before availability") - void authorisationPrecedesAvailability() { - // Two reasons. A replay-store lookup should not be spent on a caller who may not have the - // answer, and "your history has aged out" confirms the session exists. - ResumeCoordinator coordinator = - new ResumeCoordinator( - streamId -> { - throw new AssertionError("availability was consulted before authorisation"); - }); - - assertThat(decide(coordinator, Set.of(), Map.of("orders", 42L)).outcome()) - .isEqualTo(ResumeDecision.Outcome.REFUSED); - } - - @Test - @DisplayName("a token for another actor is refused") - void tokenForAnotherActorIsRefused() { - ResumeCoordinator coordinator = - new ResumeCoordinator(ReplayAvailability.of(Map.of("orders", 1L))); - - ResumeDecision decision = - coordinator.decide( - token(Map.of("orders", 42L)), - WebSocketActorReference.of("mallory", "acme", SALT), - ENDPOINT, - PROTOCOL, - Set.of("feed:read"), - Set.of("feed:read"), - Map.of("orders", 100L), - NOW.plusSeconds(1)); - - assertThat(decision.outcome()).isEqualTo(ResumeDecision.Outcome.REFUSED); - } - - @Test - @DisplayName("one aged-out stream snapshots all of them") - void oneAgedOutStreamSnapshotsEverything() { - // Replaying the available streams and snapshotting the rest hands the client a mixture it has - // no way to reason about — part continuous, part a new baseline, nothing saying which. - ResumeCoordinator coordinator = - new ResumeCoordinator(ReplayAvailability.of(Map.of("orders", 1L, "prices", 900L))); - - ResumeDecision decision = - coordinator.decide( - token(Map.of("orders", 42L, "prices", 10L)), - ALICE, - ENDPOINT, - PROTOCOL, - Set.of("feed:read"), - Set.of("feed:read"), - Map.of("orders", 100L, "prices", 950L), - NOW.plusSeconds(1)); - - assertThat(decision.outcome()).isEqualTo(ResumeDecision.Outcome.SNAPSHOT); - } - - @Test - @DisplayName("an unknown stream is not the same as an aged-out one") - void unknownStreamIsDistinctFromAgedOut() { - // Answering 0 for both would make a resume for a stream that no longer exists look like a - // complete replay of nothing. - ResumeCoordinator coordinator = new ResumeCoordinator(ReplayAvailability.none()); - - ResumeDecision decision = decide(coordinator, Set.of("feed:read"), Map.of("orders", 42L)); - - assertThat(decision.outcome()).isEqualTo(ResumeDecision.Outcome.SNAPSHOT); - assertThat(decision.reason()).contains("not replayable"); - } - - @Test - @DisplayName("a snapshot without a baseline is refused at construction") - void snapshotNeedsABaseline() { - // Without one the client has current state and no idea what sequence follows it, so the next - // message reads as a gap. - assertThatThrownBy( - () -> - new ResumeDecision( - ResumeDecision.Outcome.SNAPSHOT, Optional.empty(), Optional.empty(), "why")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("reads as a gap"); - } - - @Test - @DisplayName("resume is off unless the capability is enabled") - void resumeRequiresItsCapability() { - assertThat(ResumeCoordinator.resumable(SESSION, false)).isFalse(); - assertThat(ResumeCoordinator.resumable(SESSION, true)).isTrue(); - } -} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/resume/ResumeTokenTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/resume/ResumeTokenTest.java deleted file mode 100644 index f299777e..00000000 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/resume/ResumeTokenTest.java +++ /dev/null @@ -1,188 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.resume; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.websocket.advanced.WebSocketAdvancedCapability; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketActorReference; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketEndpointName; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketSessionId; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketSubprotocolName; -import java.nio.charset.StandardCharsets; -import java.time.Duration; -import java.time.Instant; -import java.util.Map; -import javax.crypto.SecretKey; -import javax.crypto.spec.SecretKeySpec; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -/** - * A credential that authorises reading somebody's session history. - * - *

That is what a resume token is, and it explains the shape of every rule here. It is not a - * convenience identifier: presented successfully it produces the messages a session missed, so a - * forgeable, unbound or replayable one hands over another caller's data. - */ -@Tag("websocket-advanced") -class ResumeTokenTest { - - private static final Instant NOW = Instant.parse("2026-08-25T10:00:00Z"); - private static final byte[] SALT = - "a-deployment-salt-of-adequate-length".getBytes(StandardCharsets.UTF_8); - private static final WebSocketSessionId SESSION = new WebSocketSessionId("s-01H8XQ2N4K"); - private static final WebSocketEndpointName ENDPOINT = new WebSocketEndpointName("live-updates"); - private static final WebSocketSubprotocolName PROTOCOL = WebSocketSubprotocolName.stable(); - private static final WebSocketActorReference ALICE = - WebSocketActorReference.of("alice", "acme", SALT); - - private static SecretKey key(String seed) { - return new SecretKeySpec( - (seed + "0".repeat(40)).substring(0, 40).getBytes(StandardCharsets.UTF_8), "HmacSHA256"); - } - - private final ResumeTokenKeyRing ring = - ResumeTokenKeyRing.of("k1", Map.of("k1", key("current"), "k0", key("retired"))); - private final ResumeTokenCodec codec = new ResumeTokenCodec(ring); - - private static ResumeTokenPayload payload() { - return new ResumeTokenPayload( - SESSION, ALICE, ENDPOINT, PROTOCOL, Map.of("orders", 42L), NOW, NOW.plusSeconds(60)); - } - - @Test - @DisplayName("a freshly minted token verifies and round-trips its positions") - void freshTokenVerifies() { - ResumeTokenCodec.Verification verification = - codec.decode(codec.encode(payload()), NOW.plusSeconds(1)); - - assertThat(verification.outcome()).isEqualTo(ResumeTokenOutcome.ACCEPTED); - assertThat(verification.payload().orElseThrow().streamPositions()).containsEntry("orders", 42L); - } - - @Test - @DisplayName("a tampered payload is refused") - void tamperedTokenIsRefused() { - String token = codec.encode(payload()); - String tampered = "A" + token.substring(1); - - assertThat(codec.decode(tampered, NOW.plusSeconds(1)).outcome()) - .isIn(ResumeTokenOutcome.TAMPERED, ResumeTokenOutcome.UNSUPPORTED_VERSION); - } - - @Test - @DisplayName("a token signed by a key this deployment does not have is UNKNOWN_KEY") - void unknownKeyIsDistinguished() { - // Usually a rotation that retired a key still in circulation, occasionally a forgery. The two - // are indistinguishable from the token, and an operator needs to know which spike this is. - ResumeTokenCodec foreign = - new ResumeTokenCodec(ResumeTokenKeyRing.of("k9", Map.of("k9", key("elsewhere")))); - - assertThat(codec.decode(foreign.encode(payload()), NOW.plusSeconds(1)).outcome()) - .isEqualTo(ResumeTokenOutcome.UNKNOWN_KEY); - } - - @Test - @DisplayName("a retired key still verifies, so rotation is not an outage") - void retiredKeyStillVerifies() { - // Replacing the key with a single new one invalidates every token in flight and tells every - // client to start fresh at the same moment — the exact failure resume exists to prevent. - ResumeTokenCodec oldCodec = - new ResumeTokenCodec(ResumeTokenKeyRing.of("k0", Map.of("k0", key("retired")))); - String mintedBeforeRotation = oldCodec.encode(payload()); - - assertThat(codec.decode(mintedBeforeRotation, NOW.plusSeconds(1)).outcome()) - .isEqualTo(ResumeTokenOutcome.ACCEPTED); - } - - @Test - @DisplayName("an expired token is EXPIRED, not TAMPERED") - void expiredTokenIsDistinguished() { - assertThat(codec.decode(codec.encode(payload()), NOW.plusSeconds(120)).outcome()) - .isEqualTo(ResumeTokenOutcome.EXPIRED); - } - - @Test - @DisplayName("expiry is checked after the signature, never before") - void expiryIsCheckedAfterTheSignature() { - // An unverified payload's expiry is a number the client chose. Reading it first would let a - // forged token with a distant expiry get further than one with a near one. - ResumeTokenCodec foreign = - new ResumeTokenCodec(ResumeTokenKeyRing.of("k9", Map.of("k9", key("elsewhere")))); - ResumeTokenPayload longLived = - new ResumeTokenPayload( - SESSION, ALICE, ENDPOINT, PROTOCOL, Map.of(), NOW, NOW.plus(Duration.ofDays(1))); - - // Signed by an unknown key: rejected for that, not accepted because it had not expired. - assertThat(codec.decode(foreign.encode(longLived), NOW.plusSeconds(1)).outcome()) - .isEqualTo(ResumeTokenOutcome.UNKNOWN_KEY); - } - - @Test - @DisplayName("a token authorises only its own actor, endpoint, session and protocol") - void tokenIsBoundToAllFour() { - // Each binding closes a specific hole, and checking three of four reads as thorough. - ResumeTokenPayload token = payload(); - - assertThat(token.authorises(SESSION, ALICE, ENDPOINT, PROTOCOL)).isTrue(); - // Another actor: without this the token is a bearer credential. - assertThat( - token.authorises( - SESSION, WebSocketActorReference.of("mallory", "acme", SALT), ENDPOINT, PROTOCOL)) - .isFalse(); - // Another endpoint: without this a low-privilege token resumes a privileged feed. - assertThat(token.authorises(SESSION, ALICE, new WebSocketEndpointName("admin-feed"), PROTOCOL)) - .isFalse(); - // Another session: without this there is nothing being resumed. - assertThat(token.authorises(new WebSocketSessionId("s-other0001"), ALICE, ENDPOINT, PROTOCOL)) - .isFalse(); - // Another subprotocol: without this the client resumes into a format it no longer speaks and - // every subsequent frame fails to decode. - assertThat( - token.authorises( - SESSION, ALICE, ENDPOINT, new WebSocketSubprotocolName("vendor.other.v1.json"))) - .isFalse(); - } - - @Test - @DisplayName("a key shorter than 256 bits is refused") - void shortKeyIsRefused() { - assertThatThrownBy( - () -> - ResumeTokenKeyRing.of( - "k1", - Map.of( - "k1", - new SecretKeySpec("short".getBytes(StandardCharsets.UTF_8), "HmacSHA256")))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("somebody else's messages"); - } - - @Test - @DisplayName("a ring whose current key is not in it is refused") - void currentKeyMustBeInTheRing() { - assertThatThrownBy(() -> ResumeTokenKeyRing.of("k9", Map.of("k1", key("current")))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("nothing it signs verifies"); - } - - @Test - @DisplayName("only the recoverable outcomes tell the client to retry") - void onlyRecoverableOutcomesInviteARetry() { - // Telling a client which of the failures it hit would tell an attacker the same. - assertThat(ResumeTokenOutcome.EXPIRED.clientMayRetryWithNewToken()).isTrue(); - assertThat(ResumeTokenOutcome.UNKNOWN_KEY.clientMayRetryWithNewToken()).isTrue(); - assertThat(ResumeTokenOutcome.TAMPERED.clientMayRetryWithNewToken()).isFalse(); - } - - @Test - @DisplayName("capabilities that change failure modes are marked as such") - void failureModeChangingCapabilitiesAreMarked() { - // Turning on a network dependency in the delivery path is not the same kind of decision as - // turning on a codec. - assertThat(WebSocketAdvancedCapability.CLUSTER_REDIS.altersFailureModes()).isTrue(); - assertThat(WebSocketAdvancedCapability.RESUME.altersFailureModes()).isTrue(); - assertThat(WebSocketAdvancedCapability.CODEC_CBOR.altersFailureModes()).isFalse(); - } -} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/sockjs/SockJsCompatibilityProfileTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/sockjs/SockJsCompatibilityProfileTest.java deleted file mode 100644 index d240d28a..00000000 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/sockjs/SockJsCompatibilityProfileTest.java +++ /dev/null @@ -1,109 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.sockjs; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.websocket.advanced.compression.EndpointContentClass; -import java.time.Duration; -import java.util.Set; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -/** - * The fallback transports, and what they put back that a raw WebSocket had removed. - * - *

They are HTTP requests, and HTTP requests carry cookies — which puts CSRF back on a surface - * that did not have it. - */ -@Tag("websocket-advanced") -class SockJsCompatibilityProfileTest { - - @Test - @DisplayName("SockJS is off for a new service") - void sockJsIsOffByDefault() { - assertThat(SockJsCompatibilityProfile.disabled().enabled()).isFalse(); - assertThat(SockJsCompatibilityProfile.disabled().mayServe(EndpointContentClass.PUBLIC_DATA)) - .isFalse(); - } - - @Test - @DisplayName("JSONP polling may not carry sensitive content") - void jsonpMayNotCarrySensitiveContent() { - // JSONP executes server-supplied script in the page, so a sensitive payload becomes script the - // page runs, readable by anything else running there. - SockJsCompatibilityProfile withJsonp = - new SockJsCompatibilityProfile( - true, - Set.of(SockJsTransport.XHR_POLLING, SockJsTransport.JSONP_POLLING), - Duration.ofHours(1)); - - assertThat(withJsonp.mayServe(EndpointContentClass.PUBLIC_DATA)).isTrue(); - assertThat(withJsonp.mayServe(EndpointContentClass.SENSITIVE)).isFalse(); - } - - @Test - @DisplayName("without JSONP a sensitive endpoint may still use the fallbacks") - void nonScriptFallbacksMayCarrySensitiveContent() { - SockJsCompatibilityProfile safe = - new SockJsCompatibilityProfile( - true, - Set.of(SockJsTransport.XHR_POLLING, SockJsTransport.XHR_STREAMING), - Duration.ofHours(1)); - - assertThat(safe.mayServe(EndpointContentClass.SENSITIVE)).isTrue(); - } - - @Test - @DisplayName("the security checks are not relaxed relative to a raw WebSocket") - void securityChecksAreNotRelaxed() { - assertThat(SockJsCompatibilityProfile.disabled().inheritedFromStable()) - .anyMatch(line -> line.startsWith("origin:")) - .anyMatch(line -> line.startsWith("CSRF:")) - .anyMatch(line -> line.startsWith("connection budget:")) - .anyMatch(line -> line.startsWith("authentication:")); - } - - @Test - @DisplayName("the session cookie expires, and not in a week") - void sessionCookieIsBounded() { - // A session-lifetime cookie on a fallback transport outlives the connection it was issued for, - // and is a bearer credential the whole time. - assertThatThrownBy( - () -> - new SockJsCompatibilityProfile( - true, Set.of(SockJsTransport.XHR_POLLING), Duration.ZERO)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("must expire"); - assertThatThrownBy( - () -> - new SockJsCompatibilityProfile( - true, Set.of(SockJsTransport.XHR_POLLING), Duration.ofDays(7))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("bearer credential"); - } - - @Test - @DisplayName("enabling SockJS with no transport is refused") - void emptyTransportSetIsRefused() { - assertThatThrownBy(() -> new SockJsCompatibilityProfile(true, Set.of(), Duration.ofHours(1))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("still exposes the endpoint"); - } - - @Test - @DisplayName("the transports a proxy response timeout will cut are identified") - void proxyTimeoutExposureIsIdentified() { - SockJsCompatibilityProfile profile = - new SockJsCompatibilityProfile( - true, - Set.of( - SockJsTransport.XHR_POLLING, - SockJsTransport.XHR_STREAMING, - SockJsTransport.EVENT_SOURCE), - Duration.ofHours(1)); - - assertThat(profile.transportsExposedToProxyTimeouts()) - .containsExactly(SockJsTransport.XHR_STREAMING, SockJsTransport.EVENT_SOURCE); - } -} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/SimpleBrokerProfileTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/SimpleBrokerProfileTest.java deleted file mode 100644 index ff4c323a..00000000 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/SimpleBrokerProfileTest.java +++ /dev/null @@ -1,62 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.stomp; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.util.List; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -/** - * What the in-memory broker cannot do. - * - *

It is the default, works perfectly in a single-node test, and fails in production in ways that - * look like application bugs. - */ -@Tag("websocket-advanced") -class SimpleBrokerProfileTest { - - @Test - @DisplayName("neither clustering nor durable acknowledgement is claimed") - void neitherClusteringNorDurabilityIsClaimed() { - SimpleBrokerProfile profile = SimpleBrokerProfile.inMemory(); - - assertThat(profile.localOnly()).isTrue(); - assertThat(profile.clusterSupported()).isFalse(); - assertThat(profile.durableAckSupported()).isFalse(); - } - - @Test - @DisplayName("a profile claiming a capability this broker lacks is refused") - void overclaimingIsRefused() { - // The claim would be believed, and the belief is what turns intermittent message loss into a - // fortnight of looking at application code. - assertThatThrownBy(() -> new SimpleBrokerProfile(true, true, false)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("does not exist"); - assertThatThrownBy(() -> new SimpleBrokerProfile(false, false, false)) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("activation outside local and test is refused") - void activationOutsideLocalAndTestIsRefused() { - // In a multi-node deployment it does not error: it delivers to whichever fraction of users - // happens to be on the publishing node. - assertThat(SimpleBrokerProfile.activatableUnder(List.of("local"))).isTrue(); - assertThat(SimpleBrokerProfile.activatableUnder(List.of("test"))).isTrue(); - assertThat(SimpleBrokerProfile.activatableUnder(List.of())).isTrue(); - assertThat(SimpleBrokerProfile.activatableUnder(List.of("prod"))).isFalse(); - assertThat(SimpleBrokerProfile.activatableUnder(List.of("local", "prod"))).isFalse(); - } - - @Test - @DisplayName("the limitations are written down where an operator reads them") - void limitationsAreRecorded() { - assertThat(SimpleBrokerProfile.inMemory().supportMatrix()) - .anyMatch(line -> line.startsWith("cluster: unsupported")) - .anyMatch(line -> line.startsWith("durable ack: unsupported")) - .anyMatch(line -> line.contains("never promoted to APPLICATION_COMMIT")); - } -} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompAuthorizationPolicyTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompAuthorizationPolicyTest.java deleted file mode 100644 index ce91de7c..00000000 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompAuthorizationPolicyTest.java +++ /dev/null @@ -1,143 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.stomp; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.Optional; -import java.util.Set; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -/** - * The whole decision table for an inbound STOMP frame. - * - *

Exercised as a value, without a channel, because an authorization rule reachable only through - * a {@code MessageChannel} gets tested for the two cases somebody bothered to build a channel for — - * and the ones nobody built are the ones that let a frame through. - */ -@Tag("websocket-advanced") -class StompAuthorizationPolicyTest { - - private static final StompDestinationCatalog CATALOG = - StompDestinationCatalog.using(StompProfile.conventional()) - .declare("/topic/orders", "orders:read", StompOperation.SUBSCRIBE) - .declare("/app/orders", "orders:write", StompOperation.SEND) - .declare("/user/queue/replies", "replies:read", StompOperation.SUBSCRIBE) - .declare("/user/queue/nudge", "nudge:send", StompOperation.SEND) - .build(); - - private static final StompAuthorizationPolicy POLICY = new StompAuthorizationPolicy(CATALOG); - - private static StompFrameRequest frame( - StompOperation operation, String destination, String principal, String... permissions) { - return new StompFrameRequest( - operation, - destination, - Optional.ofNullable(principal), - Set.of(permissions), - Optional.empty()); - } - - @Test - @DisplayName("a declared destination with the permission is allowed") - void declaredAndPermittedIsAllowed() { - assertThat( - POLICY - .decide(frame(StompOperation.SUBSCRIBE, "/topic/orders", "alice", "orders:read")) - .allowed()) - .isTrue(); - } - - @Test - @DisplayName("an unauthenticated frame is refused before anything else is considered") - void unauthenticatedIsRefusedFirst() { - assertThat( - POLICY - .decide(frame(StompOperation.SUBSCRIBE, "/topic/orders", null, "orders:read")) - .reason()) - .contains(StompRefusal.UNAUTHENTICATED); - assertThat(POLICY.decide(frame(StompOperation.SUBSCRIBE, "/topic/orders", " ")).reason()) - .contains(StompRefusal.UNAUTHENTICATED); - } - - @Test - @DisplayName("an undeclared destination is refused") - void undeclaredDestinationIsRefused() { - assertThat( - POLICY - .decide(frame(StompOperation.SUBSCRIBE, "/topic/secrets", "alice", "orders:read")) - .reason()) - .contains(StompRefusal.UNDECLARED_DESTINATION); - } - - @Test - @DisplayName("reading a destination does not grant writing to it") - void readDoesNotGrantWrite() { - // The distinct reason matters: an operator reading the metric can tell a missing declaration - // from a deliberately read-only feed. - assertThat( - POLICY - .decide(frame(StompOperation.SEND, "/topic/orders", "alice", "orders:read")) - .reason()) - .contains(StompRefusal.OPERATION_NOT_PERMITTED); - } - - @Test - @DisplayName("an authenticated caller without the permission is refused") - void missingPermissionIsRefused() { - assertThat(POLICY.decide(frame(StompOperation.SUBSCRIBE, "/topic/orders", "alice")).reason()) - .contains(StompRefusal.MISSING_PERMISSION); - } - - @Test - @DisplayName("a self-addressed user destination resolves to the caller") - void selfAddressedUserDestinationIsAllowed() { - // "/user/queue/replies" is Spring's own form: the broker resolves it against the session's - // principal, so there is nobody else it could reach. - assertThat( - POLICY - .decide( - frame(StompOperation.SUBSCRIBE, "/user/queue/replies", "alice", "replies:read")) - .allowed()) - .isTrue(); - } - - @Test - @DisplayName("a user destination naming somebody else is refused") - void foreignUserDestinationIsRefused() { - // "/user/bob/queue/nudge" is how one client reaches another's private queue. - assertThat( - POLICY - .decide(frame(StompOperation.SEND, "/user/bob/queue/nudge", "alice", "nudge:send")) - .reason()) - .contains(StompRefusal.FOREIGN_USER_DESTINATION); - assertThat( - POLICY - .decide( - frame(StompOperation.SEND, "/user/alice/queue/nudge", "alice", "nudge:send")) - .allowed()) - .isTrue(); - } - - @Test - @DisplayName("an unrecognised ack header is refused rather than defaulted") - void unrecognisedAckModeIsRefused() { - StompFrameRequest request = - new StompFrameRequest( - StompOperation.SUBSCRIBE, - "/topic/orders", - Optional.of("alice"), - Set.of("orders:read"), - Optional.of("eventually")); - - assertThat(POLICY.decide(request).reason()).contains(StompRefusal.UNSUPPORTED_ACK_MODE); - } - - @Test - @DisplayName("a decision is either an allow or a stated reason, never both or neither") - void decisionsAreWellFormed() { - assertThat(StompAuthorizationDecision.allow().reason()).isEmpty(); - assertThat(StompAuthorizationDecision.refuse(StompRefusal.MISSING_PERMISSION).allowed()) - .isFalse(); - } -} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompBrokerExclusivityTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompBrokerExclusivityTest.java deleted file mode 100644 index 03e79c48..00000000 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompBrokerExclusivityTest.java +++ /dev/null @@ -1,62 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.stomp; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -/** - * Configurations in which the broker that ends up running is not the one anybody configured. - * - *

All four cases start cleanly and log nothing. That is the reason for a startup check rather - * than a comment. - */ -@Tag("websocket-advanced") -class StompBrokerExclusivityTest { - - @Test - @DisplayName("the advanced adapter with exactly one broker is accepted") - void oneAdapterAndOneBrokerIsAccepted() { - StompBrokerExclusivity.verify(false, true, true, false); - StompBrokerExclusivity.verify(false, true, false, true); - assertThat(StompBrokerExclusivity.valid(false, true, true, false)).isTrue(); - } - - @Test - @DisplayName("the legacy channel alone is accepted") - void legacyChannelAloneIsAccepted() { - StompBrokerExclusivity.verify(true, false, false, false); - assertThat(StompBrokerExclusivity.valid(true, false, false, false)).isTrue(); - } - - @Test - @DisplayName("two STOMP runtimes are refused") - void twoRuntimesAreRefused() { - // Each configures the broker; the one that wins is decided by bean ordering, and the prefixes - // in effect are not the ones in either configuration file. - assertThatThrownBy(() -> StompBrokerExclusivity.verify(true, true, true, false)) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("decided by bean ordering"); - } - - @Test - @DisplayName("two brokers are refused") - void twoBrokersAreRefused() { - // Subscriptions land in one and publishes in the other. - assertThatThrownBy(() -> StompBrokerExclusivity.verify(false, true, true, true)) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("alternatives"); - } - - @Test - @DisplayName("an adapter with no broker is refused") - void adapterWithoutABrokerIsRefused() { - // Every SUBSCRIBE would be accepted and nothing would ever be delivered, which from the - // client's side is indistinguishable from a quiet system. - assertThatThrownBy(() -> StompBrokerExclusivity.verify(false, true, false, false)) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("no broker behind it"); - } -} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompDestinationCatalogTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompDestinationCatalogTest.java deleted file mode 100644 index 198587b0..00000000 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompDestinationCatalogTest.java +++ /dev/null @@ -1,92 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.stomp; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -/** The set of destinations that exist, declared rather than discovered. */ -@Tag("websocket-advanced") -class StompDestinationCatalogTest { - - private static StompDestinationCatalog.Builder builder() { - return StompDestinationCatalog.using(StompProfile.conventional()); - } - - @Test - @DisplayName("reading and writing a destination are separate declarations") - void readAndWriteAreSeparate() { - // The same feed is usually readable by many and writable by few. A catalog carrying one - // permission per destination would have to pick the looser of the two. - StompDestinationCatalog catalog = - builder() - .declare("/topic/orders", "orders:read", StompOperation.SUBSCRIBE) - .declare("/app/orders", "orders:write", StompOperation.SEND) - .build(); - - assertThat(catalog.permissionFor(StompOperation.SUBSCRIBE, "/topic/orders")) - .contains("orders:read"); - assertThat(catalog.permissionFor(StompOperation.SEND, "/topic/orders")).isEmpty(); - } - - @Test - @DisplayName("an undeclared destination has no permission at all") - void undeclaredDestinationHasNoPermission() { - // Empty, not a permissive default. A default here makes every unlisted destination reachable. - StompDestinationCatalog catalog = - builder().declare("/topic/orders", "orders:read", StompOperation.SUBSCRIBE).build(); - - assertThat(catalog.permissionFor(StompOperation.SUBSCRIBE, "/topic/secrets")).isEmpty(); - assertThat(catalog.declares(StompOperation.SUBSCRIBE, "/topic/secrets")).isFalse(); - } - - @Test - @DisplayName("a destination outside every prefix is refused at startup") - void unroutableDestinationIsRefusedAtStartup() { - // Dead on arrival, and startup is when somebody is still reading the output. - assertThatThrownBy( - () -> builder().declare("/admin/shutdown", "admin", StompOperation.SEND).build()) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("matches no declared prefix"); - } - - @Test - @DisplayName("a blank permission is refused") - void blankPermissionIsRefused() { - // It reads as "declared" while granting everyone access. - assertThatThrownBy(() -> builder().declare("/topic/orders", " ", StompOperation.SUBSCRIBE)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("blank permission"); - } - - @Test - @DisplayName("two permissions for one operation on one destination are refused") - void conflictingPermissionsAreRefused() { - assertThatThrownBy( - () -> - builder() - .declare("/topic/orders", "orders:read", StompOperation.SUBSCRIBE) - .declare("/topic/orders", "orders:admin", StompOperation.SUBSCRIBE)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("looser one would win"); - } - - @Test - @DisplayName("an empty catalog is refused") - void emptyCatalogIsRefused() { - // It refuses every frame, which is a misconfiguration rather than a lockdown. - assertThatThrownBy(() -> builder().build()) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("misconfiguration"); - } - - @Test - @DisplayName("a destination declared for no operation is refused") - void destinationWithNoOperationIsRefused() { - assertThatThrownBy(() -> builder().declare("/topic/orders", "orders:read")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("unreachable"); - } -} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompEvidenceTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompEvidenceTest.java deleted file mode 100644 index 91e296fa..00000000 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompEvidenceTest.java +++ /dev/null @@ -1,105 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.stomp; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.time.Duration; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -/** - * The three STOMP signals that all look like success. - * - *

Each of these tests is one way somebody could report work as done when it is not. - */ -@Tag("websocket-advanced") -class StompEvidenceTest { - - @Test - @DisplayName("a RECEIPT is never a commit") - void receiptIsNeverACommit() { - // The single most consequential confusion in STOMP. A receipt is written by the protocol - // layer, which knows nothing about whether the work succeeded — so a client treating it as a - // commit shows a user their order was placed while the transaction is still open. - StompAckPolicy policy = StompAckPolicy.auto(); - - assertThat(policy.evidenceForReceipt()).isEqualTo(StompEvidence.PROTOCOL_RECEIPT); - assertThat(policy.evidenceForReceipt().provesCompletion()).isFalse(); - assertThat(policy.mayReport(StompEvidence.PROTOCOL_RECEIPT, StompEvidence.APPLICATION_COMMIT)) - .isFalse(); - } - - @Test - @DisplayName("only a commit or a client apply proves completion") - void onlyCommitAndClientApplyProveCompletion() { - assertThat(StompEvidence.FRAME_RECEIVED.provesCompletion()).isFalse(); - assertThat(StompEvidence.BROKER_DELIVERY.provesCompletion()).isFalse(); - assertThat(StompEvidence.BROKER_ACK.provesCompletion()).isFalse(); - assertThat(StompEvidence.APPLICATION_COMMIT.provesCompletion()).isTrue(); - assertThat(StompEvidence.CLIENT_APPLIED.provesCompletion()).isTrue(); - } - - @Test - @DisplayName("reporting a stage further along than what happened is refused") - void overstatingIsRefused() { - assertThat(StompEvidence.BROKER_ACK.wouldOverstate(StompEvidence.APPLICATION_COMMIT)).isTrue(); - assertThat(StompEvidence.APPLICATION_COMMIT.wouldOverstate(StompEvidence.BROKER_ACK)).isFalse(); - assertThat(StompEvidence.BROKER_ACK.wouldOverstate(StompEvidence.BROKER_ACK)).isFalse(); - } - - @Test - @DisplayName("the three ack modes are distinguished, not conflated") - void ackModesAreDistinguished() { - // They place responsibility for redelivery in different places, and a server that treats them - // alike is wrong for two of the three. - assertThat(StompAckMode.AUTO.requiresClientAcknowledgement()).isFalse(); - assertThat(StompAckMode.CLIENT.requiresClientAcknowledgement()).isTrue(); - assertThat(StompAckMode.CLIENT_INDIVIDUAL.requiresClientAcknowledgement()).isTrue(); - assertThat(StompAckMode.CLIENT.cumulative()).isTrue(); - assertThat(StompAckMode.CLIENT_INDIVIDUAL.cumulative()).isFalse(); - } - - @Test - @DisplayName("an unrecognised ack header is not defaulted") - void unrecognisedAckHeaderIsNotDefaulted() { - // Defaulting to auto turns a client asking for at-least-once into one that silently gets - // at-most-once. - assertThat(StompAckMode.fromWire("client-individual")).contains(StompAckMode.CLIENT_INDIVIDUAL); - assertThat(StompAckMode.fromWire("CLIENT")).contains(StompAckMode.CLIENT); - assertThat(StompAckMode.fromWire("eventually")).isEmpty(); - assertThat(StompAckMode.fromWire(null)).isEmpty(); - } - - @Test - @DisplayName("a client-acknowledged subscription is bounded") - void clientAcknowledgedSubscriptionIsBounded() { - StompAckPolicy policy = new StompAckPolicy(StompAckMode.CLIENT, 2, Duration.ofSeconds(30)); - - assertThat(policy.mayDeliver(1)).isTrue(); - assertThat(policy.mayDeliver(2)).isFalse(); - assertThat(StompAckPolicy.auto().mayDeliver(9999)).isTrue(); - } - - @Test - @DisplayName("a policy that could never deliver, or never bound, is refused") - void contradictoryPoliciesAreRefused() { - assertThatThrownBy(() -> new StompAckPolicy(StompAckMode.CLIENT, 0, Duration.ofSeconds(1))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("can never deliver"); - assertThatThrownBy(() -> new StompAckPolicy(StompAckMode.AUTO, 5, Duration.ofSeconds(1))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("does not exist"); - assertThatThrownBy(() -> new StompAckPolicy(StompAckMode.CLIENT, 1, Duration.ZERO)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("pin the retained messages"); - } - - @Test - @DisplayName("asking what an ACK proves on an auto subscription is a caller error") - void ackOnAutoSubscriptionIsACallerError() { - assertThatThrownBy(() -> StompAckPolicy.auto().evidenceForClientAck()) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("wrong policy in hand"); - } -} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompProfileTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompProfileTest.java deleted file mode 100644 index da12cf21..00000000 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/StompProfileTest.java +++ /dev/null @@ -1,74 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.stomp; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.util.Set; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -/** What a destination prefix decides, and what it does not. */ -@Tag("websocket-advanced") -class StompProfileTest { - - @Test - @DisplayName("each prefix routes to its own role") - void prefixesRouteToTheirRole() { - StompProfile profile = StompProfile.conventional(); - - assertThat(profile.roleOf("/app/orders")).contains(StompDestinationRole.APPLICATION); - assertThat(profile.roleOf("/topic/orders")).contains(StompDestinationRole.BROKER); - assertThat(profile.roleOf("/user/queue/replies")).contains(StompDestinationRole.USER); - } - - @Test - @DisplayName("an unmatched destination is refused, not defaulted") - void unmatchedDestinationIsRefused() { - // The destination is a free string from the client, so unmatched is the normal shape of both a - // typo and an attempt to reach somewhere that was never published. - assertThat(StompProfile.conventional().roleOf("/admin/shutdown")).isEmpty(); - assertThat(StompProfile.conventional().roleOf("")).isEmpty(); - } - - @Test - @DisplayName("a prefix match stops at a segment boundary") - void prefixMatchStopsAtASegmentBoundary() { - // "/topicprivate" is not under "/topic", and treating it as though it were hands the caller a - // destination the operator never published. - assertThat(StompProfile.conventional().roleOf("/topicprivate/secrets")).isEmpty(); - assertThat(StompProfile.conventional().roleOf("/topic")).contains(StompDestinationRole.BROKER); - } - - @Test - @DisplayName("overlapping prefixes are refused") - void overlappingPrefixesAreRefused() { - // A destination matching two roles would be dispatched by whichever check ran first, which is - // an ordering detail deciding an authorization outcome. - assertThatThrownBy( - () -> new StompProfile(Set.of("/app"), Set.of("/app/broker"), Set.of("/user"), true)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("whichever check ran first"); - } - - @Test - @DisplayName("a profile that routes nothing is refused") - void emptyProfileIsRefused() { - assertThatThrownBy(() -> new StompProfile(Set.of(), Set.of(), Set.of("/user"), true)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("routes nothing"); - } - - @Test - @DisplayName("a malformed prefix is refused at construction") - void malformedPrefixIsRefused() { - assertThatThrownBy( - () -> new StompProfile(Set.of("app"), Set.of("/topic"), Set.of("/user"), true)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("absolute normalized path"); - assertThatThrownBy( - () -> new StompProfile(Set.of("/app/"), Set.of("/topic"), Set.of("/user"), true)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("absolute normalized path"); - } -} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/rabbit/MultiNodeUserDestinationTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/rabbit/MultiNodeUserDestinationTest.java deleted file mode 100644 index 09702be1..00000000 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/rabbit/MultiNodeUserDestinationTest.java +++ /dev/null @@ -1,126 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.stomp.rabbit; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketNodeId; -import java.time.Duration; -import java.time.Instant; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -/** Reaching a user who is connected somewhere else, without the cluster eating itself. */ -@Tag("websocket-advanced") -class MultiNodeUserDestinationTest { - - private static final Instant NOW = Instant.parse("2026-08-25T10:00:00Z"); - private static final WebSocketNodeId LOCAL = new WebSocketNodeId("edge-1"); - private static final WebSocketNodeId REMOTE = new WebSocketNodeId("edge-2"); - private static final String ALICE = "fp-alice"; - - private static MultiNodeUserDestination routing() { - return new MultiNodeUserDestination(UserDestinationPolicy.conventional(), LOCAL); - } - - @Test - @DisplayName("a locally held session is delivered to directly") - void localSessionIsDeliveredDirectly() { - MultiNodeUserDestination routing = routing(); - routing.register(ALICE, NOW); - - assertThat(routing.route(ALICE, false, NOW).action()) - .isEqualTo(UserDestinationAction.DELIVER_LOCALLY); - assertThat(routing.route(ALICE, false, NOW).destination()).isEmpty(); - } - - @Test - @DisplayName("a session held elsewhere is broadcast once") - void remoteSessionIsBroadcast() { - MultiNodeUserDestination routing = routing(); - routing.observe(ALICE, REMOTE, NOW); - - assertThat(routing.route(ALICE, false, NOW).action()) - .isEqualTo(UserDestinationAction.BROADCAST); - assertThat(routing.route(ALICE, false, NOW).destination()).contains("/topic/unresolved-user"); - } - - @Test - @DisplayName("an already-broadcast message is never broadcast again") - void broadcastMessagesDoNotLoop() { - // Without this, every node rebroadcasts every unresolvable message on receipt and the cluster - // spends its whole broker budget passing one undeliverable message around — which from any - // single node looks like ordinary traffic. - MultiNodeUserDestination routing = routing(); - - assertThat(routing.route("fp-nobody", true, NOW).action()) - .isEqualTo(UserDestinationAction.UNRESOLVED); - assertThat(routing.route("fp-nobody", true, NOW).destination()) - .contains("/topic/unresolved-user-dlq"); - } - - @Test - @DisplayName("an unknown user is broadcast, not dropped") - void unknownUserIsBroadcast() { - assertThat(routing().route("fp-nobody", false, NOW).action()) - .isEqualTo(UserDestinationAction.BROADCAST); - } - - @Test - @DisplayName("an expired mapping is treated as absent, not as disconnected") - void expiredMappingIsAbsentNotDisconnected() { - // The difference is that absent still broadcasts. Treating it as "not connected" drops the - // message for a user who is connected to a node that merely stopped refreshing. - MultiNodeUserDestination routing = routing(); - routing.register(ALICE, NOW); - Instant late = NOW.plus(Duration.ofMinutes(3)); - - assertThat(routing.route(ALICE, false, late).action()) - .isEqualTo(UserDestinationAction.BROADCAST); - } - - @Test - @DisplayName("a stale mapping is evicted so it stops routing at a machine that is gone") - void staleMappingsAreEvicted() { - MultiNodeUserDestination routing = routing(); - routing.observe(ALICE, REMOTE, NOW); - routing.register("fp-bob", NOW.plus(Duration.ofMinutes(3))); - - assertThat(routing.evictExpired(NOW.plus(Duration.ofMinutes(3)))).isOne(); - assertThat(routing.trackedUsers()).isOne(); - } - - @Test - @DisplayName("disconnecting releases the mapping and its broker queue") - void disconnectReleasesTheMapping() { - // A relay creates one temporary queue per user-destination subscription. Without this they - // accumulate for every session that ever connected, and RabbitMQ's memory alarm fires long - // before anybody connects the two facts. - MultiNodeUserDestination routing = routing(); - routing.register(ALICE, NOW); - - assertThat(routing.deregister(ALICE)).isTrue(); - assertThat(routing.deregister(ALICE)).isFalse(); - assertThat(routing.trackedUsers()).isZero(); - } - - @Test - @DisplayName("the routing action is the metric tag, never the destination") - void routingCarriesABoundedTag() { - // A user destination contains a user identifier by construction, so tagging a metric with it - // publishes every user's name and gives the cardinality budget an unbounded denominator. - assertThat(UserDestinationAction.values()).hasSize(3); - } - - @Test - @DisplayName("a policy that would loop or never expire is refused") - void loopingOrImmortalPolicyIsRefused() { - assertThatThrownBy( - () -> new UserDestinationPolicy("/topic/a", "/topic/a", Duration.ofMinutes(1))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("forever"); - assertThatThrownBy(() -> new UserDestinationPolicy("/topic/a", "/topic/b", Duration.ZERO)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("no longer exist"); - } -} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/rabbit/RabbitBrokerRelayProfileTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/rabbit/RabbitBrokerRelayProfileTest.java deleted file mode 100644 index 6ead249d..00000000 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/advanced/stomp/rabbit/RabbitBrokerRelayProfileTest.java +++ /dev/null @@ -1,65 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.advanced.stomp.rabbit; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.time.Duration; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -/** - * The relay's cost and its failure model. - * - *

Enabling it moves delivery's dependency from this JVM to a separate machine over a network, - * and the platform's own health check keeps reporting green throughout an outage. - */ -@Tag("websocket-advanced") -class RabbitBrokerRelayProfileTest { - - @Test - @DisplayName("a relay without a heartbeat is refused") - void heartbeatlessRelayIsRefused() { - // A half-open TCP connection to a dead broker accepts every publish silently. The heartbeat is - // the only thing that notices. - assertThatThrownBy(() -> new RabbitBrokerRelayProfile("broker", 61613, true, Duration.ZERO)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("quiet broker from a dead one"); - } - - @Test - @DisplayName("broker connection cost is one per session plus the shared system connection") - void connectionCostIsComputable() { - // Worth computing before the first outage. A broker connection limit turns a normal-looking - // client count into a hard ceiling, and the symptom is new users failing to subscribe while - // existing ones are fine. - RabbitBrokerRelayProfile profile = RabbitBrokerRelayProfile.localPlaintext(); - - assertThat(profile.brokerConnectionsFor(0)).isOne(); - assertThat(profile.brokerConnectionsFor(500)).isEqualTo(501); - } - - @Test - @DisplayName("a plaintext relay says what it exposes") - void plaintextRelayReportsItsExposure() { - assertThat(RabbitBrokerRelayProfile.localPlaintext().productionConcerns()) - .singleElement() - .asString() - .contains("clear text"); - assertThat( - new RabbitBrokerRelayProfile("broker", 61614, true, Duration.ofSeconds(10)) - .productionConcerns()) - .isEmpty(); - } - - @Test - @DisplayName("a blank host and an impossible port are refused") - void malformedTargetIsRefused() { - assertThatThrownBy(() -> new RabbitBrokerRelayProfile(" ", 61613, true, Duration.ofSeconds(1))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("never the broker that was meant"); - assertThatThrownBy(() -> new RabbitBrokerRelayProfile("broker", 0, true, Duration.ofSeconds(1))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("not a port"); - } -} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/arch/WebSocketArchitectureRulesTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/arch/WebSocketArchitectureRulesTest.java deleted file mode 100644 index 78b5b088..00000000 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/arch/WebSocketArchitectureRulesTest.java +++ /dev/null @@ -1,91 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.arch; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import com.tngtech.archunit.core.domain.JavaClasses; -import com.tngtech.archunit.core.importer.ClassFileImporter; -import com.tngtech.archunit.core.importer.ImportOption; -import com.tngtech.archunit.lang.ArchRule; -import dev.caskeleton.adapter.inbound.websocket.testkit.arch.WebSocketArchitectureRules; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * The rule pack, applied to this leaf and proven to be capable of failing. - * - *

Both halves are needed. A rule that passes against a clean tree looks identical to a rule that - * matches nothing — a typo in a package name produces a permanently green check, which is worse - * than no check because it is believed. - */ -class WebSocketArchitectureRulesTest { - - private static JavaClasses production; - - @BeforeAll - static void importProduction() { - production = - new ClassFileImporter() - .withImportOption(ImportOption.Predefined.DO_NOT_INCLUDE_TESTS) - .importPackages("dev.caskeleton.adapter.inbound.websocket"); - } - - @Test - @DisplayName("the import actually found the platform") - void importFoundThePlatform() { - // Without this, every rule below passes against an empty class set. - assertThat(production.size()).isGreaterThan(30); - } - - @Test - @DisplayName("every rule holds against this leaf") - void everyRuleHolds() { - for (ArchRule rule : WebSocketArchitectureRules.all()) { - assertThatCode(() -> rule.check(production)) - .as("%s", rule.getDescription()) - .doesNotThrowAnyException(); - } - } - - @Test - @DisplayName("the handler rule can actually fail") - void theHandlerRuleCanFail() { - // Applied to a package that does hold transport types, the rule must object. A rule that - // cannot fail is a rule that is checking a package name nobody spelled correctly. - JavaClasses stompTransport = - new ClassFileImporter() - .withImportOption(ImportOption.Predefined.DO_NOT_INCLUDE_TESTS) - .importPackages("dev.caskeleton.adapter.inbound.websocket.stomp"); - - assertThat(stompTransport.size()).isPositive(); - assertThatThrownBy( - () -> - com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses() - .that() - .resideInAPackage("dev.caskeleton.adapter.inbound.websocket.stomp..") - .should() - .dependOnClassesThat() - .resideInAnyPackage("org.springframework.web.socket..") - .check(stompTransport)) - .isInstanceOf(AssertionError.class); - } - - @Test - @DisplayName("the handler package is genuinely free of transport types") - void handlerPackageIsFreeOfTransport() { - // Stated separately from the pack so the failure names this specific boundary. It is the one - // the entire outbound design rests on. - WebSocketArchitectureRules.handlersDoNotTouchTheTransport().check(production); - - assertThat( - production.stream() - .filter( - type -> - type.getPackageName() - .startsWith("dev.caskeleton.adapter.inbound.websocket.handler")) - .count()) - .isPositive(); - } -} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/authz/MessageAuthorizationPolicyTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/authz/MessageAuthorizationPolicyTest.java deleted file mode 100644 index 7d06f22e..00000000 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/authz/MessageAuthorizationPolicyTest.java +++ /dev/null @@ -1,70 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.authz; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageType; -import java.util.List; -import java.util.Map; -import java.util.Set; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * Authorization per message rather than per connection. - * - *

A connection is authorised once and lives for hours. Authorising there means the caller keeps - * whatever it had when it connected — through every role change and every revocation — until it - * happens to reconnect. - */ -class MessageAuthorizationPolicyTest { - - private static final WebSocketMessageType READ = new WebSocketMessageType("order.read.v1"); - private static final WebSocketMessageType CANCEL = new WebSocketMessageType("order.cancel.v1"); - private static final WebSocketMessageType UNDECLARED = - new WebSocketMessageType("order.refund.v1"); - - private final MessageAuthorizationPolicy policy = - MessageAuthorizationPolicy.of(Map.of(READ, Set.of(), CANCEL, Set.of("order:cancel"))); - - @Test - @DisplayName("a declared type with no authorities needs only authentication") - void authenticatedOnlyTypeIsPermitted() { - assertThat(policy.permits(READ, Set.of())).isTrue(); - } - - @Test - @DisplayName("a type requiring an authority refuses a caller without it") - void missingAuthorityIsRefused() { - assertThat(policy.permits(CANCEL, Set.of())).isFalse(); - assertThat(policy.permits(CANCEL, Set.of("order:read"))).isFalse(); - assertThat(policy.permits(CANCEL, Set.of("order:cancel"))).isTrue(); - } - - @Test - @DisplayName("authorities are evaluated per message, so a revocation takes effect immediately") - void authoritiesAreEvaluatedPerMessage() { - // The same connection, two different moments. Per-connection authorization would give the same - // answer both times. - assertThat(policy.permits(CANCEL, Set.of("order:cancel"))).isTrue(); - assertThat(policy.permits(CANCEL, Set.of())).isFalse(); - } - - @Test - @DisplayName("an undeclared type is refused, not allowed") - void undeclaredTypeIsRefused() { - // A new message type is added by someone thinking about the message, not the permission. - // Defaulting to allow ships the omission. - assertThat(policy.permits(UNDECLARED, Set.of("order:cancel", "admin"))).isFalse(); - } - - @Test - @DisplayName("undeclared published types are reported so the omission is visible") - void undeclaredTypesAreReported() { - // Refusing them is safe and is not what anybody intended, so the deployment is told rather - // than left to hear it from a client that cannot do anything. - List undeclared = - policy.undeclaredAmong(List.of(READ, CANCEL, UNDECLARED)); - - assertThat(undeclared).containsExactly(UNDECLARED); - } -} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/budget/WebSocketConnectionBudgetTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/budget/WebSocketConnectionBudgetTest.java index 7a0dc115..1c50900c 100644 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/budget/WebSocketConnectionBudgetTest.java +++ b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/budget/WebSocketConnectionBudgetTest.java @@ -1,141 +1,50 @@ package dev.caskeleton.adapter.inbound.websocket.budget; -import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import java.time.Duration; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; /** * The limits HTTP gave for free and a connection does not. * - *

A request has a finite body, one response and a lifetime in seconds. A connection has none of - * those, so whatever is not bounded here is unbounded in production — and the symptom is never a - * failing request. It is heap. + *

A request has a finite body and one response. A connection has neither, so whatever is not + * bounded here is unbounded in production — and the symptom is never a failing request. It is heap. */ class WebSocketConnectionBudgetTest { - @Test - @DisplayName("the standard budget bounds every dimension") - void standardBudgetBoundsEverything() { - WebSocketConnectionBudget budget = WebSocketConnectionBudget.standard(); - - assertThat(budget.maxFrameBytes()).isPositive(); - assertThat(budget.maxMessageBytes()).isPositive(); - assertThat(budget.maxFragments()).isPositive(); - assertThat(budget.maxInboundMessagesPerSecond()).isPositive(); - assertThat(budget.maxBufferedOutboundBytes()).isPositive(); - assertThat(budget.maxConnectionAge()).isPositive(); - assertThat(budget.idleTimeout()).isPositive(); - } - @Test @DisplayName("the outbound buffer is bounded, because a slow consumer never fails") - void outboundBufferIsBounded() { + void outboundBufferAboveTheCeilingIsRefused() { // A slow consumer reads more slowly than the server writes and the difference accumulates in // the server's heap. One is invisible; a hundred is an OutOfMemoryError with no failing // request to point at. - assertThatThrownBy( - () -> - new WebSocketConnectionBudget( - 64 * 1024, - 512 * 1024, - 16, - 100, - 64L * 1024 * 1024, - Duration.ofHours(4), - Duration.ofSeconds(90))) + assertThatThrownBy(() -> new WebSocketConnectionBudget(64 * 1024, 64L * 1024 * 1024)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("multiplied by the connection count is the heap"); } @Test - @DisplayName("a message bound below the frame bound is refused") - void messageBoundBelowFrameBoundIsRefused() { - // It would accept a frame and then refuse it on reassembly, spending exactly the memory the - // frame bound was there to save. + void messageBoundAboveTheCeilingIsRefused() { assertThatThrownBy( () -> new WebSocketConnectionBudget( - 64 * 1024, - 32 * 1024, - 16, - 100, - 1024L * 1024, - Duration.ofHours(4), - Duration.ofSeconds(90))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("will then refuse"); - } - - @Test - @DisplayName("the three size bounds must be able to describe the same message") - void sizeBoundsMustBeCoherent() { - // frame x fragments below the message bound means the largest message the profile claims to - // accept can never actually arrive. - assertThatThrownBy( - () -> - new WebSocketConnectionBudget( - 64 * 1024, - 512 * 1024, - 2, - 100, - 1024L * 1024, - Duration.ofHours(4), - Duration.ofSeconds(90))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("can never be delivered"); - } - - @Test - @DisplayName("a connection with no maximum age is refused") - void unboundedAgeIsRefused() { - assertThatThrownBy( - () -> - new WebSocketConnectionBudget( - 64 * 1024, - 512 * 1024, - 16, - 100, - 1024L * 1024, - Duration.ZERO, - Duration.ofSeconds(90))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("unbounded"); - } - - @Test - @DisplayName("an idle timeout beyond the maximum age never fires") - void idleTimeoutBeyondMaxAgeIsRefused() { - assertThatThrownBy( - () -> - new WebSocketConnectionBudget( - 64 * 1024, - 512 * 1024, - 16, - 100, - 1024L * 1024, - Duration.ofMinutes(1), - Duration.ofHours(1))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("never fires"); - } - - @Test - @DisplayName("no profile may exceed the platform ceilings") - void platformCeilingsHold() { - assertThatThrownBy( - () -> - new WebSocketConnectionBudget( - WebSocketConnectionBudget.ABSOLUTE_FRAME_MAX + 1, - WebSocketConnectionBudget.ABSOLUTE_MESSAGE_MAX, - 64, - 100, - 1024L * 1024, - Duration.ofHours(4), - Duration.ofSeconds(90))) + WebSocketConnectionBudget.ABSOLUTE_MESSAGE_MAX + 1, 1024L * 1024)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("ceiling"); } + + @Test + void nonPositiveMessageBoundIsRefused() { + assertThatThrownBy(() -> new WebSocketConnectionBudget(0, 1024L * 1024)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("maxMessageBytes must be positive"); + } + + @Test + void nonPositiveOutboundBoundIsRefused() { + assertThatThrownBy(() -> new WebSocketConnectionBudget(1024, 0)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("maxBufferedOutboundBytes must be positive"); + } } diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/codec/WebSocketJsonWireManifestTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/codec/WebSocketJsonWireManifestTest.java deleted file mode 100644 index 1a624d41..00000000 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/codec/WebSocketJsonWireManifestTest.java +++ /dev/null @@ -1,197 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.codec; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.websocket.budget.WebSocketConnectionBudget; -import dev.caskeleton.adapter.inbound.websocket.error.WebSocketFailureCategory; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageCatalog; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageDescriptor; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageDirection; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageFamily; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageType; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketSchemaVersion; -import java.util.List; -import java.util.Map; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * The decode path, which is the cheapest place to attack a socket. - * - *

It runs on every inbound frame, before most policy, on bytes chosen entirely by the peer. Each - * case here is a document a permissive parser accepts and this one must not. - */ -class WebSocketJsonWireManifestTest { - - /** A wire type: a record, so nothing runs while it is populated. */ - public record PlaceOrder(String sku, int quantity) {} - - private static final WebSocketMessageType PLACE = new WebSocketMessageType("order.place.v1"); - private static final WebSocketMessageType PLACED = new WebSocketMessageType("order.placed.v1"); - - private final WebSocketMessageCatalog catalog = - WebSocketMessageCatalog.of( - List.of( - new WebSocketMessageDescriptor( - PLACE, - WebSocketMessageFamily.COMMAND, - WebSocketMessageDirection.CLIENT_TO_SERVER, - WebSocketSchemaVersion.v(1)), - new WebSocketMessageDescriptor( - PLACED, - WebSocketMessageFamily.EVENT, - WebSocketMessageDirection.SERVER_TO_CLIENT, - WebSocketSchemaVersion.v(1)))); - - private final StrictWebSocketJsonCodec codec = - new StrictWebSocketJsonCodec( - catalog, - WebSocketWireTypeManifest.of(Map.of(PLACE, PlaceOrder.class)), - WebSocketConnectionBudget.standard()); - - @Test - @DisplayName("a well-formed document decodes") - void wellFormedDocumentDecodes() { - Object decoded = - codec.decodeFromClient( - PLACE, WebSocketMessageFamily.COMMAND, "{\"sku\":\"A-1\",\"quantity\":2}"); - - assertThat(decoded).isEqualTo(new PlaceOrder("A-1", 2)); - } - - @Test - @DisplayName("a duplicate key is refused") - void duplicateKeyIsRefused() { - // Every parser accepts this and silently keeps one value, so the same document means different - // things to a validating proxy and to this server — a request that passes review at one layer - // and executes as something else at the next. - assertThatThrownBy( - () -> - codec.decodeFromClient( - PLACE, - WebSocketMessageFamily.COMMAND, - "{\"sku\":\"A-1\",\"quantity\":2,\"quantity\":99999}")) - .isInstanceOf(WebSocketDecodeException.class); - } - - @Test - @DisplayName("an unknown field is refused") - void unknownFieldIsRefused() { - // Accepting it means a client can send anything alongside the real fields and get no signal - // that a typo'd field name was ignored. - assertThatThrownBy( - () -> - codec.decodeFromClient( - PLACE, - WebSocketMessageFamily.COMMAND, - "{\"sku\":\"A-1\",\"quantity\":2,\"admin\":true}")) - .isInstanceOf(WebSocketDecodeException.class); - } - - @Test - @DisplayName("trailing content after the document is refused") - void trailingContentIsRefused() { - // Two documents in one frame: a proxy that reads the first and a server that reads both is the - // same smuggling shape as a duplicate key. - assertThatThrownBy( - () -> - codec.decodeFromClient( - PLACE, - WebSocketMessageFamily.COMMAND, - "{\"sku\":\"A-1\",\"quantity\":2}{\"sku\":\"B-2\",\"quantity\":9}")) - .isInstanceOf(WebSocketDecodeException.class); - } - - @Test - @DisplayName("deeply nested content is refused before it is parsed") - void deepNestingIsRefused() { - // Depth costs stack during parse, so a bound applied afterwards has already paid for the - // attack. - String deep = "[".repeat(200) + "]".repeat(200); - - assertThatThrownBy(() -> codec.decodeFromClient(PLACE, WebSocketMessageFamily.COMMAND, deep)) - .isInstanceOf(WebSocketDecodeException.class); - } - - @Test - @DisplayName("a case-different field name is refused") - void caseInsensitiveBindingIsOff() { - assertThatThrownBy( - () -> - codec.decodeFromClient( - PLACE, WebSocketMessageFamily.COMMAND, "{\"SKU\":\"A-1\",\"quantity\":2}")) - .isInstanceOf(WebSocketDecodeException.class); - } - - @Test - @DisplayName("a float where an int belongs is refused") - void floatForIntIsRefused() { - assertThatThrownBy( - () -> - codec.decodeFromClient( - PLACE, WebSocketMessageFamily.COMMAND, "{\"sku\":\"A-1\",\"quantity\":2.7}")) - .isInstanceOf(WebSocketDecodeException.class); - } - - @Test - @DisplayName("an unpublished type never reaches the parser") - void unpublishedTypeNeverReachesTheParser() { - // Catalog first, parser second. The bytes are not handed to a parser at all. - assertThatThrownBy( - () -> - codec.decodeFromClient( - new WebSocketMessageType("secret.internal.v1"), - WebSocketMessageFamily.COMMAND, - "{}")) - .isInstanceOf(WebSocketDecodeException.class) - .extracting(failure -> ((WebSocketDecodeException) failure).category()) - .isEqualTo(WebSocketFailureCategory.UNKNOWN_TYPE); - } - - @Test - @DisplayName("a server-only type sent by a client is refused") - void serverOnlyTypeFromClientIsRefused() { - assertThatThrownBy(() -> codec.decodeFromClient(PLACED, WebSocketMessageFamily.EVENT, "{}")) - .isInstanceOf(WebSocketDecodeException.class); - } - - @Test - @DisplayName("the decode failure tells the peer nothing about the server") - void decodeFailureDoesNotLeak() { - // A parser's message names the class, the field and often the offending content. Useful in a - // server log, a disclosure on a connection held for hours. - WebSocketDecodeException failure = - org.junit.jupiter.api.Assertions.assertThrows( - WebSocketDecodeException.class, - () -> - codec.decodeFromClient( - PLACE, WebSocketMessageFamily.COMMAND, "{\"sku\":\"A-1\",\"admin\":true}")); - - assertThat(failure.getMessage()).doesNotContain("PlaceOrder"); - assertThat(failure.getMessage()).doesNotContain("admin"); - assertThat(failure.getMessage()).doesNotContain("dev.caskeleton"); - } - - @Test - @DisplayName("only records may be wire types") - void onlyRecordsMayBeWireTypes() { - // A record cannot run arbitrary code while being populated, which is the mechanism every - // deserialization gadget depends on. - assertThatThrownBy(() -> WebSocketWireTypeManifest.of(Map.of(PLACE, java.util.HashMap.class))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("deserialization gadget"); - assertThatCode(() -> WebSocketWireTypeManifest.of(Map.of(PLACE, PlaceOrder.class))) - .doesNotThrowAnyException(); - } - - @Test - @DisplayName("the server may not encode a type it is not published to send") - void serverCannotEncodeAClientOnlyType() { - assertThatThrownBy(() -> codec.encodeToClient(PLACE, new PlaceOrder("A-1", 1))) - .isInstanceOf(WebSocketDecodeException.class); - assertThat(codec.encodeToClient(PLACED, new PlaceOrder("A-1", 1))) - .isEqualTo("{\"sku\":\"A-1\",\"quantity\":1}"); - } -} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/config/WebSocketEnvironmentBindingTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/config/WebSocketEnvironmentBindingTest.java deleted file mode 100644 index fa820176..00000000 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/config/WebSocketEnvironmentBindingTest.java +++ /dev/null @@ -1,54 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.config; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.adapter.inbound.websocket.stomp.WebSocketProperties; -import java.util.Map; -import org.junit.jupiter.api.Test; -import org.springframework.boot.context.properties.bind.Bindable; -import org.springframework.boot.context.properties.bind.Binder; -import org.springframework.core.env.StandardEnvironment; -import org.springframework.core.env.SystemEnvironmentPropertySource; - -class WebSocketEnvironmentBindingTest { - - @Test - void officialAppWebsocketEnvironmentNamesBindTheCanonicalPropertyTree() { - StandardEnvironment environment = new StandardEnvironment(); - environment - .getPropertySources() - .addFirst( - new SystemEnvironmentPropertySource( - "websocket-contract", - Map.of( - "APP_WEBSOCKET_ENABLED", "true", - "APP_WEBSOCKET_ENDPOINT", "/live/ws", - "APP_WEBSOCKET_ALLOWED_ORIGINS", "https://client.example", - "APP_WEBSOCKET_BROADCAST_DESTINATION", "/topic/live", - "APP_WEBSOCKET_PLATFORM_ENABLED", "true", - "APP_WEBSOCKET_PLATFORM_NODE_ID", "node-a", - "APP_WEBSOCKET_PLATFORM_MAX_FRAME_BYTES", "32768", - "APP_WEBSOCKET_ADVANCED_STOMP_ENABLED", "true"))); - - WebSocketProperties stomp = - Binder.get(environment) - .bind("app.websocket", Bindable.of(WebSocketProperties.class)) - .orElseThrow(() -> new AssertionError("websocket env did not bind")); - WebSocketPlatformSettings platform = - Binder.get(environment) - .bind("app.websocket.platform", Bindable.of(WebSocketPlatformSettings.class)) - .orElseThrow(() -> new AssertionError("websocket env did not bind")); - - assertThat(stomp.isEnabled()).isTrue(); - assertThat(stomp.getEndpoint()).isEqualTo("/live/ws"); - assertThat(stomp.getAllowedOrigins()).isEqualTo("https://client.example"); - assertThat(stomp.getBroadcastDestination()).isEqualTo("/topic/live"); - - assertThat(platform.enabled()).isTrue(); - assertThat(platform.nodeId()).isEqualTo("node-a"); - assertThat(platform.maxFrameBytes()).isEqualTo(32768); - - assertThat(environment.getProperty("app.websocket.advanced.stomp.enabled", Boolean.class)) - .isTrue(); - } -} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/config/WebSocketPlatformSafetyConfigurationTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/config/WebSocketPlatformSafetyConfigurationTest.java deleted file mode 100644 index 0418fa0f..00000000 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/config/WebSocketPlatformSafetyConfigurationTest.java +++ /dev/null @@ -1,167 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.config; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.adapter.inbound.websocket.advanced.sockjs.SockJsConfiguration; -import dev.caskeleton.adapter.inbound.websocket.advanced.stomp.AdvancedStompSafetyConfiguration; -import dev.caskeleton.adapter.inbound.websocket.advanced.stomp.StompDefaultsConfiguration; -import dev.caskeleton.adapter.inbound.websocket.advanced.stomp.StompProfile; -import dev.caskeleton.adapter.inbound.websocket.advanced.stomp.rabbit.RabbitBrokerRelayConfiguration; -import dev.caskeleton.adapter.inbound.websocket.authz.MessageAuthorizationPolicy; -import dev.caskeleton.adapter.inbound.websocket.budget.WebSocketConnectionBudget; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketEndpointCatalog; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketEndpointName; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketEndpointProfile; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketStackProfile; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageCatalog; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageDescriptor; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageDirection; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageFamily; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageType; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketProtocolProfile; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketSchemaVersion; -import dev.caskeleton.adapter.inbound.websocket.security.WebSocketAuthenticationProfile; -import dev.caskeleton.adapter.inbound.websocket.security.WebSocketOriginPolicy; -import java.util.List; -import java.util.Map; -import java.util.Set; -import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.runner.ApplicationContextRunner; -import org.springframework.boot.test.context.runner.WebApplicationContextRunner; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -class WebSocketPlatformSafetyConfigurationTest { - - private static final WebSocketMessageType PLACE = new WebSocketMessageType("order.place.v1"); - - @Test - void advancedStompAndLegacyStompAreRejectedByTheActualStartupPath() { - new ApplicationContextRunner() - .withUserConfiguration(AdvancedStompSafetyConfiguration.class) - .withPropertyValues( - "app.websocket.enabled=true", - "app.websocket.advanced.stomp.enabled=true", - "app.websocket.advanced.stomp.relay.enabled=true") - .run( - context -> { - assertThat(context).hasFailed(); - assertThat(context.getStartupFailure()) - .hasMessageContaining("legacy STOMP") - .hasMessageContaining("Advanced STOMP"); - }); - } - - @Test - void platformStartupValidatorIsPartOfTheActualStartupPath() { - new ApplicationContextRunner() - .withUserConfiguration( - WebSocketPlatformSafetyConfiguration.class, UnsafePlatformComposition.class) - .withPropertyValues("app.websocket.platform.enabled=true") - .run( - context -> { - assertThat(context).hasFailed(); - assertThat(context.getStartupFailure()).hasMessageContaining("the whole defence"); - }); - } - - @Test - void enablingSockJsNamesTheMissingCompositionPrerequisite() { - new WebApplicationContextRunner() - .withUserConfiguration(SockJsConfiguration.class) - .withPropertyValues("app.websocket.advanced.sockjs.enabled=true") - .run( - context -> { - assertThat(context).hasFailed(); - assertThat(context.getStartupFailure()) - .hasRootCauseMessage( - "SockJS requires a WebSocketEndpointCatalog bean from the composition root"); - }); - } - - @Test - void enablingRabbitRelayNamesTheMissingNodeIdentity() { - new ApplicationContextRunner() - .withUserConfiguration( - RabbitBrokerRelayConfiguration.class, RelayCompositionPrerequisites.class) - .withPropertyValues("app.websocket.advanced.stomp.relay.enabled=true") - .run( - context -> { - assertThat(context).hasFailed(); - assertThat(context.getStartupFailure()) - .hasRootCauseMessage( - "STOMP relay requires a WebSocketNodeId bean from the composition root"); - }); - } - - @Test - void enablingAdvancedStompNamesTheMissingDestinationCatalog() { - new ApplicationContextRunner() - .withUserConfiguration(StompDefaultsConfiguration.class) - .withPropertyValues("app.websocket.advanced.stomp.enabled=true") - .run( - context -> { - assertThat(context).hasFailed(); - assertThat(context.getStartupFailure()) - .hasMessageContaining( - "Advanced STOMP requires a StompDestinationCatalog bean from the composition root"); - }); - } - - @Configuration(proxyBeanMethods = false) - static class RelayCompositionPrerequisites { - - @Bean - StompProfile stompProfile() { - return StompProfile.conventional(); - } - } - - @Configuration(proxyBeanMethods = false) - static class UnsafePlatformComposition { - - @Bean - WebSocketEndpointCatalog endpoints() { - return WebSocketEndpointCatalog.of( - List.of( - new WebSocketEndpointProfile( - new WebSocketEndpointName("orders"), - "/ws/orders", - WebSocketStackProfile.SERVLET, - true, - WebSocketConnectionBudget.standard(), - 100))); - } - - @Bean - WebSocketMessageCatalog messages() { - return WebSocketMessageCatalog.of( - List.of( - new WebSocketMessageDescriptor( - PLACE, - WebSocketMessageFamily.COMMAND, - WebSocketMessageDirection.CLIENT_TO_SERVER, - WebSocketSchemaVersion.v(1)))); - } - - @Bean - MessageAuthorizationPolicy authorization() { - return MessageAuthorizationPolicy.of(Map.of(PLACE, Set.of())); - } - - @Bean - WebSocketOriginPolicy origins() { - return WebSocketOriginPolicy.browsersOnly(Set.of()); - } - - @Bean - WebSocketAuthenticationProfile authentication() { - return WebSocketAuthenticationProfile.SESSION_COOKIE; - } - - @Bean - WebSocketProtocolProfile protocol() { - return WebSocketProtocolProfile.stable(); - } - } -} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/config/WebSocketPlatformStartupValidatorTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/config/WebSocketPlatformStartupValidatorTest.java deleted file mode 100644 index a8cad351..00000000 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/config/WebSocketPlatformStartupValidatorTest.java +++ /dev/null @@ -1,216 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.config; - -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.websocket.authz.MessageAuthorizationPolicy; -import dev.caskeleton.adapter.inbound.websocket.budget.WebSocketConnectionBudget; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketEndpointCatalog; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketEndpointName; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketEndpointProfile; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketStackProfile; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageCatalog; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageDescriptor; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageDirection; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageFamily; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageType; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketProtocolProfile; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketSchemaVersion; -import dev.caskeleton.adapter.inbound.websocket.security.WebSocketAuthenticationProfile; -import dev.caskeleton.adapter.inbound.websocket.security.WebSocketOriginPolicy; -import java.util.List; -import java.util.Map; -import java.util.Set; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * Configurations that work perfectly in development and are wrong in production. - * - *

That is the entire category this validator covers. A cookie endpoint with no origin allowlist - * serves every same-origin test correctly; an unnegotiated-fallback profile connects fine until the - * message format changes; a type with no authorization requirement refuses everything, quietly, and - * only for the clients that try to use it. - */ -class WebSocketPlatformStartupValidatorTest { - - private static final WebSocketMessageType PLACE = new WebSocketMessageType("order.place.v1"); - - private final WebSocketPlatformStartupValidator production = - new WebSocketPlatformStartupValidator(true); - private final WebSocketPlatformStartupValidator local = - new WebSocketPlatformStartupValidator(false); - - private static WebSocketEndpointCatalog endpoints(boolean authenticated) { - return WebSocketEndpointCatalog.of( - List.of( - new WebSocketEndpointProfile( - new WebSocketEndpointName("live-updates"), - "/ws/v1/live", - WebSocketStackProfile.SERVLET, - authenticated, - WebSocketConnectionBudget.standard(), - 1000))); - } - - private static WebSocketMessageCatalog messages() { - return WebSocketMessageCatalog.of( - List.of( - new WebSocketMessageDescriptor( - PLACE, - WebSocketMessageFamily.COMMAND, - WebSocketMessageDirection.CLIENT_TO_SERVER, - WebSocketSchemaVersion.v(1)))); - } - - private static WebSocketOriginPolicy origins() { - return WebSocketOriginPolicy.browsersOnly(Set.of("https://app.example.com")); - } - - @Test - @DisplayName("a coherent production configuration starts") - void coherentConfigurationStarts() { - assertThatCode( - () -> - production.validate( - endpoints(true), - messages(), - MessageAuthorizationPolicy.of(Map.of(PLACE, Set.of())), - origins(), - WebSocketAuthenticationProfile.ONE_TIME_TICKET, - WebSocketProtocolProfile.stable())) - .doesNotThrowAnyException(); - } - - @Test - @DisplayName("a cookie profile with no origin allowlist fails startup") - void cookieProfileNeedsOrigins() { - assertThatThrownBy( - () -> - production.validate( - endpoints(true), - messages(), - MessageAuthorizationPolicy.of(Map.of(PLACE, Set.of())), - WebSocketOriginPolicy.browsersOnly(Set.of()), - WebSocketAuthenticationProfile.SESSION_COOKIE, - WebSocketProtocolProfile.stable())) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("the whole defence"); - } - - @Test - @DisplayName("the unnegotiated fallback fails production and passes local") - void fallbackIsProductionOnlyProblem() { - assertThatThrownBy( - () -> - production.validate( - endpoints(true), - messages(), - MessageAuthorizationPolicy.of(Map.of(PLACE, Set.of())), - origins(), - WebSocketAuthenticationProfile.ONE_TIME_TICKET, - WebSocketProtocolProfile.localCompatibility())) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("assume their own current format"); - - assertThatCode( - () -> - local.validate( - endpoints(true), - messages(), - MessageAuthorizationPolicy.of(Map.of(PLACE, Set.of())), - origins(), - WebSocketAuthenticationProfile.ONE_TIME_TICKET, - WebSocketProtocolProfile.localCompatibility())) - .doesNotThrowAnyException(); - } - - @Test - @DisplayName("an unauthenticated endpoint fails production startup") - void unauthenticatedEndpointFailsProduction() { - assertThatThrownBy( - () -> - production.validate( - endpoints(false), - messages(), - MessageAuthorizationPolicy.of(Map.of(PLACE, Set.of())), - origins(), - WebSocketAuthenticationProfile.ONE_TIME_TICKET, - WebSocketProtocolProfile.stable())) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("holding server memory for hours"); - } - - @Test - @DisplayName("a published type with no authorization requirement fails startup") - void undeclaredAuthorizationFailsStartup() { - // It is currently unsendable, which is safe and is not what anybody intended. Without this the - // deployment hears about it from a client that cannot do anything. - assertThatThrownBy( - () -> - production.validate( - endpoints(true), - messages(), - MessageAuthorizationPolicy.of(Map.of()), - origins(), - WebSocketAuthenticationProfile.ONE_TIME_TICKET, - WebSocketProtocolProfile.stable())) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("unsendable"); - } - - @Test - @DisplayName("endpoints spanning both runtimes fail startup") - void mixedRuntimesFailStartup() { - WebSocketEndpointCatalog mixed = - WebSocketEndpointCatalog.of( - List.of( - new WebSocketEndpointProfile( - new WebSocketEndpointName("live-updates"), - "/ws/v1/live", - WebSocketStackProfile.SERVLET, - true, - WebSocketConnectionBudget.standard(), - 1000), - new WebSocketEndpointProfile( - new WebSocketEndpointName("reactive-feed"), - "/ws/v1/reactive", - WebSocketStackProfile.REACTIVE, - true, - WebSocketConnectionBudget.standard(), - 1000))); - - assertThatThrownBy( - () -> - production.validate( - mixed, - messages(), - MessageAuthorizationPolicy.of(Map.of(PLACE, Set.of())), - origins(), - WebSocketAuthenticationProfile.ONE_TIME_TICKET, - WebSocketProtocolProfile.stable())) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("silently never answer"); - } - - @Test - @DisplayName("every problem is named at once") - void everyProblemIsNamedAtOnce() { - // Reporting the first sends an operator through one restart per problem, and each restart is a - // deploy. - assertThatThrownBy( - () -> - production.validate( - endpoints(false), - messages(), - MessageAuthorizationPolicy.of(Map.of()), - WebSocketOriginPolicy.browsersOnly(Set.of()), - WebSocketAuthenticationProfile.SESSION_COOKIE, - WebSocketProtocolProfile.localCompatibility())) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("the whole defence") - .hasMessageContaining("assume their own current format") - .hasMessageContaining("holding server memory for hours") - .hasMessageContaining("unsendable"); - } -} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/config/WebSocketStackExclusivityTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/config/WebSocketStackExclusivityTest.java deleted file mode 100644 index b6ecf9b5..00000000 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/config/WebSocketStackExclusivityTest.java +++ /dev/null @@ -1,73 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.config; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketStackProfile; -import java.time.Duration; -import java.util.Set; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * The mismatch that produces a healthy-looking deployment serving nothing. - * - *

Boot deduces one application type from the classpath, and with both present it picks the - * servlet one. A deployment that declared reactive endpoints and shipped both therefore starts, - * reports itself healthy, and never answers — no error and no warning anywhere. - */ -class WebSocketStackExclusivityTest { - - @Test - @DisplayName("the resolved stack is what the classpath will actually produce") - void resolvedStackMatchesTheClasspath() { - // This leaf compiles against both runtimes, and the test classpath carries the servlet one. - // The assertion is about agreeing with Boot's own deduction rather than about a preference. - assertThat(WebSocketStackExclusivity.resolvedStack()).contains(WebSocketStackProfile.SERVLET); - } - - @Test - @DisplayName("declaring the stack the classpath produces is accepted") - void matchingDeclarationIsAccepted() { - assertThatCode(() -> WebSocketStackExclusivity.require(WebSocketStackProfile.SERVLET)) - .doesNotThrowAnyException(); - } - - @Test - @DisplayName("declaring the other stack fails with an explanation") - void mismatchedDeclarationFails() { - // The whole value is in the message: "the WebSocket does not connect" is otherwise a support - // ticket with nothing to go on. - assertThatThrownBy(() -> WebSocketStackExclusivity.require(WebSocketStackProfile.REACTIVE)) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("would never answer while"); - } - - @Test - @DisplayName("the platform defaults to serving nothing") - void platformDefaultsToDisabled() { - // A deployment that has not said which origins may connect has not configured a WebSocket - // endpoint, and starting one anyway would mean the platform chose its own CSRF posture. - WebSocketPlatformSettings defaults = - new WebSocketPlatformSettings( - false, - "local", - Set.of(), - false, - 65536, - 524288, - 16, - 1048576, - 67108864, - 4, - Duration.ofSeconds(15), - Duration.ofSeconds(45), - Duration.ofHours(4), - Duration.ofSeconds(30)); - - assertThat(defaults.enabled()).isFalse(); - assertThat(defaults.hasOriginAllowlist()).isFalse(); - assertThat(defaults.allowMissingOrigin()).isFalse(); - } -} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/core/WebSocketConnectionStateTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/core/WebSocketConnectionStateTest.java deleted file mode 100644 index 90ea769c..00000000 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/core/WebSocketConnectionStateTest.java +++ /dev/null @@ -1,178 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.core; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.time.Duration; -import java.time.Instant; -import java.util.Optional; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * The state machine, and the two things a long-lived connection gets wrong that a request cannot. - * - *

A request is authenticated and finished. A connection is authenticated once and then runs for - * hours: it outlives the token, the revoked session and the role change, and it is still open - * during the deploy that was supposed to replace it. Both of those have their own case here. - */ -class WebSocketConnectionStateTest { - - private static final Instant NOW = Instant.parse("2026-08-25T10:00:00Z"); - private static final byte[] SALT = - "a-deployment-salt-of-adequate-length".getBytes(java.nio.charset.StandardCharsets.UTF_8); - - @Test - @DisplayName("a connection walks forward through its states") - void statesMoveForward() { - assertThat(WebSocketConnectionState.CONNECTING.canTransitionTo(WebSocketConnectionState.OPEN)) - .isTrue(); - assertThat(WebSocketConnectionState.OPEN.canTransitionTo(WebSocketConnectionState.DRAINING)) - .isTrue(); - assertThat(WebSocketConnectionState.DRAINING.canTransitionTo(WebSocketConnectionState.CLOSING)) - .isTrue(); - assertThat(WebSocketConnectionState.CLOSING.canTransitionTo(WebSocketConnectionState.CLOSED)) - .isTrue(); - } - - @Test - @DisplayName("a draining connection cannot go back to open") - void drainingIsOneWay() { - // The one edge a rolling restart depends on being absent. A node that announced it was leaving - // must not resume taking work. - assertThat(WebSocketConnectionState.DRAINING.canTransitionTo(WebSocketConnectionState.OPEN)) - .isFalse(); - assertThat(WebSocketConnectionState.CLOSED.canTransitionTo(WebSocketConnectionState.OPEN)) - .isFalse(); - } - - @Test - @DisplayName("a draining connection still finishes its in-flight writes") - void drainingIsWritableButRefusesNewInbound() { - // Both halves matter. Refusing writes cuts a message in half; accepting inbound keeps a - // departing node taking work it will not finish. - assertThat(WebSocketConnectionState.DRAINING.writable()).isTrue(); - assertThat(WebSocketConnectionState.DRAINING.acceptsInbound()).isFalse(); - } - - @Test - @DisplayName("a connecting connection is not yet writable") - void connectingIsNotWritable() { - assertThat(WebSocketConnectionState.CONNECTING.writable()).isFalse(); - assertThat(WebSocketConnectionState.CLOSING.writable()).isFalse(); - assertThat(WebSocketConnectionState.CLOSED.writable()).isFalse(); - } - - @Test - @DisplayName("a context refuses a transition the machine does not allow") - void contextRefusesAnIllegalTransition() { - WebSocketConnectionContext open = context(WebSocketConnectionState.OPEN); - - assertThatCode(() -> open.transitionTo(WebSocketConnectionState.DRAINING)) - .doesNotThrowAnyException(); - assertThatThrownBy( - () -> - open.transitionTo(WebSocketConnectionState.DRAINING) - .transitionTo(WebSocketConnectionState.OPEN)) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("moves forward"); - } - - @Test - @DisplayName("identity does not change with state") - void identityIsStableAcrossTransitions() { - // An actor that could change mid-life would make every authorization decision conditional on - // when it was asked, and the audit record would name the last actor rather than the one who - // acted. - WebSocketConnectionContext open = context(WebSocketConnectionState.OPEN); - - WebSocketConnectionContext draining = open.transitionTo(WebSocketConnectionState.DRAINING); - - assertThat(draining.actor()).isEqualTo(open.actor()); - assertThat(draining.endpoint()).isEqualTo(open.endpoint()); - assertThat(draining.subprotocol()).isEqualTo(open.subprotocol()); - assertThat(draining.connectionId()).isEqualTo(open.connectionId()); - } - - @Test - @DisplayName("the context holds a fingerprint, never the subject") - void contextHoldsNoRawIdentity() { - WebSocketActorReference actor = WebSocketActorReference.of("alice@example.com", "acme", SALT); - - assertThat(actor.fingerprint()).doesNotContain("alice"); - assertThat(actor.fingerprint()).doesNotContain("acme"); - assertThat(actor.fingerprint()).hasSize(64); - assertThat(actor.shortForm()).hasSize(12); - } - - @Test - @DisplayName("the same identity produces the same reference, a different one does not") - void referenceIsStableAndDiscriminating() { - // Both properties are needed: stable so a reconnect is recognisable, discriminating so two - // actors are never conflated in an admin listing. - assertThat(WebSocketActorReference.of("alice", "acme", SALT)) - .isEqualTo(WebSocketActorReference.of("alice", "acme", SALT)); - assertThat(WebSocketActorReference.of("alice", "acme", SALT)) - .isNotEqualTo(WebSocketActorReference.of("alice", "other", SALT)); - assertThat(WebSocketActorReference.of("alice", "acme", SALT)) - .isNotEqualTo(WebSocketActorReference.of("bob", "acme", SALT)); - } - - @Test - @DisplayName("an unsalted reference is refused") - void referenceRequiresRealSalt() { - // Subjects come from small guessable sets. An unsalted digest of one is a rainbow table away - // from the subject it was meant to hide. - assertThatThrownBy(() -> WebSocketActorReference.of("alice", "acme", new byte[4])) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("guessable sets"); - } - - @Test - @DisplayName("a credential expiry closes the connection after its grace period") - void credentialExpiryClosesTheConnection() { - WebSocketCredentialExpiry expiry = - WebSocketCredentialExpiry.at(NOW.plusSeconds(60), Duration.ofSeconds(30)); - - assertThat(expiry.expiredAt(NOW)).isFalse(); - assertThat(expiry.expiredAt(NOW.plusSeconds(61))).isTrue(); - // Expired but still inside the grace: the client has a window to re-authenticate. - assertThat(expiry.mustCloseAt(NOW.plusSeconds(61))).isFalse(); - assertThat(expiry.mustCloseAt(NOW.plusSeconds(91))).isTrue(); - } - - @Test - @DisplayName("a grace period long enough to make expiry advisory is refused") - void longGraceIsRefused() { - assertThatThrownBy(() -> WebSocketCredentialExpiry.at(NOW, Duration.ofHours(1))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("advisory"); - } - - @Test - @DisplayName("maximum connection age is separate from credential expiry") - void maximumAgeIsSeparateFromExpiry() { - // A never-expiring service credential still should not hold one connection open across three - // deploys. Age is what forces a client back through the handshake, where current policy is - // applied. - WebSocketConnectionContext open = context(WebSocketConnectionState.OPEN); - - assertThat(open.credentialExpiry().mustCloseAt(NOW.plusSeconds(100_000))).isFalse(); - assertThat(open.olderThan(Duration.ofHours(4), NOW.plusSeconds(100_000))).isTrue(); - assertThat(open.olderThan(Duration.ofHours(4), NOW.plusSeconds(60))).isFalse(); - } - - private static WebSocketConnectionContext context(WebSocketConnectionState state) { - return new WebSocketConnectionContext( - new WebSocketConnectionId("c-01H8XQ2N4K"), - new WebSocketSessionId("s-01H8XQ2N4K"), - new WebSocketNodeId("edge-1"), - new WebSocketEndpointName("live-updates"), - Optional.of(WebSocketSubprotocolName.stable()), - WebSocketActorReference.of("alice", "acme", SALT), - state, - WebSocketCredentialExpiry.never(), - NOW); - } -} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/core/WebSocketEndpointProfileTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/core/WebSocketEndpointProfileTest.java deleted file mode 100644 index 7dc99509..00000000 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/core/WebSocketEndpointProfileTest.java +++ /dev/null @@ -1,152 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.core; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.websocket.budget.WebSocketConnectionBudget; -import java.util.List; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * What a declared endpoint must say before it can be served. - * - *

An endpoint is the only thing here reachable from the internet, and a WebSocket endpoint is - * reachable for hours at a time. Each case is something a deployment could leave unsaid and only - * discover under load or under attack. - */ -class WebSocketEndpointProfileTest { - - @Test - @DisplayName("an endpoint path must be canonical and absolute") - void pathMustBeCanonical() { - assertThatCode(() -> profile("live-updates", "/ws/v1/live")).doesNotThrowAnyException(); - // A trailing slash, a dot segment or a relative path each make the route that answers differ - // from the route that was reviewed. - assertThatThrownBy(() -> profile("live-updates", "/ws/v1/live/")) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> profile("live-updates", "ws/v1/live")) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> profile("live-updates", "/ws/../admin")) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("every endpoint declares a positive connection cap") - void connectionCapIsMandatory() { - assertThatThrownBy( - () -> - new WebSocketEndpointProfile( - new WebSocketEndpointName("live-updates"), - "/ws/v1/live", - WebSocketStackProfile.SERVLET, - true, - WebSocketConnectionBudget.standard(), - 0)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("connects the most"); - } - - @Test - @DisplayName("an unauthenticated endpoint is buildable but not production safe") - void unauthenticatedEndpointIsFlagged() { - // Not refused: a public status feed is a real thing. Flagged, so serving one in production is - // a decision somebody made rather than a default nobody noticed. - WebSocketEndpointProfile open = - new WebSocketEndpointProfile( - new WebSocketEndpointName("public-status"), - "/ws/v1/status", - WebSocketStackProfile.SERVLET, - false, - WebSocketConnectionBudget.standard(), - 100); - - assertThat(open.productionSafe()).isFalse(); - assertThat(WebSocketEndpointCatalog.of(List.of(open)).productionUnsafe()).containsExactly(open); - } - - @Test - @DisplayName("two endpoints on one path are refused") - void duplicatePathIsRefused() { - // Which one answers would be decided by registration order, and the loser is silently - // unreachable — indistinguishable from a client bug. - assertThatThrownBy( - () -> - WebSocketEndpointCatalog.of( - List.of( - profile("live-updates", "/ws/v1/live"), - profile("other-feed", "/ws/v1/live")))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("silently unreachable"); - } - - @Test - @DisplayName("two endpoints with one name are refused") - void duplicateNameIsRefused() { - assertThatThrownBy( - () -> - WebSocketEndpointCatalog.of( - List.of( - profile("live-updates", "/ws/v1/live"), - profile("live-updates", "/ws/v1/other")))) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("the catalog resolves by path and by name") - void catalogResolvesBothWays() { - WebSocketEndpointCatalog catalog = - WebSocketEndpointCatalog.of(List.of(profile("live-updates", "/ws/v1/live"))); - - assertThat(catalog.findByPath("/ws/v1/live")).isPresent(); - assertThat(catalog.findByPath("/ws/v1/live/")).isEmpty(); - assertThat(catalog.require(new WebSocketEndpointName("live-updates")).path()) - .isEqualTo("/ws/v1/live"); - } - - @Test - @DisplayName("an undeclared endpoint is refused rather than defaulted") - void undeclaredEndpointIsRefused() { - WebSocketEndpointCatalog catalog = - WebSocketEndpointCatalog.of(List.of(profile("live-updates", "/ws/v1/live"))); - - assertThatThrownBy(() -> catalog.require(new WebSocketEndpointName("nope"))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("declared set"); - } - - @Test - @DisplayName("a catalog spanning both runtimes is detectable") - void mixedStackCatalogIsDetectable() { - // Boot deduces one application type from the classpath, so a catalog spanning both means one - // set of endpoints is never served and nothing says so. - WebSocketEndpointCatalog mixed = - WebSocketEndpointCatalog.of( - List.of( - profile("live-updates", "/ws/v1/live"), - new WebSocketEndpointProfile( - new WebSocketEndpointName("reactive-feed"), - "/ws/v1/reactive", - WebSocketStackProfile.REACTIVE, - true, - WebSocketConnectionBudget.standard(), - 100))); - - assertThat(mixed.singleStack()).isFalse(); - assertThat( - WebSocketEndpointCatalog.of(List.of(profile("live-updates", "/ws/v1/live"))) - .singleStack()) - .isTrue(); - } - - private static WebSocketEndpointProfile profile(String name, String path) { - return new WebSocketEndpointProfile( - new WebSocketEndpointName(name), - path, - WebSocketStackProfile.SERVLET, - true, - WebSocketConnectionBudget.standard(), - 1000); - } -} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/core/WebSocketIdentifierTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/core/WebSocketIdentifierTest.java index 7be8bd53..0e43816b 100644 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/core/WebSocketIdentifierTest.java +++ b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/core/WebSocketIdentifierTest.java @@ -1,6 +1,5 @@ package dev.caskeleton.adapter.inbound.websocket.core; -import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -10,34 +9,12 @@ import org.junit.jupiter.api.Test; /** * Identifiers that travel further than anyone intends. * - *

A connection identifier reaches logs, admin listings and whatever a client is handed for - * support. Every case here is a value that would be accepted by a plain {@code String} and cause - * trouble later: unbounded length, a control character in a log line, or a guessable value. + *

A connection identifier reaches logs and whatever a client is handed for support. Every case + * here is a value that would be accepted by a plain {@code String} and cause trouble later: + * unbounded length, a control character in a log line, or a guessable value. */ class WebSocketIdentifierTest { - @Test - @DisplayName("an endpoint name is lowercase, bounded and dash-separated") - void endpointNameIsBounded() { - assertThatCode(() -> new WebSocketEndpointName("live-updates")).doesNotThrowAnyException(); - assertThatThrownBy(() -> new WebSocketEndpointName("Live-Updates")) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> new WebSocketEndpointName("a")) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> new WebSocketEndpointName("x".repeat(65))) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("an endpoint name cannot carry whitespace or control characters") - void endpointNameRejectsControlCharacters() { - // A newline here is a forged log line everywhere the name is logged. - assertThatThrownBy(() -> new WebSocketEndpointName("live updates")) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> new WebSocketEndpointName("live\nupdates")) - .isInstanceOf(IllegalArgumentException.class); - } - @Test @DisplayName("a connection id is long enough not to be guessed and short enough to be bounded") void connectionIdIsBounded() { @@ -49,34 +26,15 @@ class WebSocketIdentifierTest { } @Test - @DisplayName("an identifier that looks like a credential or a key is still refused by shape") - void identifiersRejectStructuredValues() { + @DisplayName("an identifier that looks like a credential is still refused by shape") + void connectionIdRejectsStructuredValues() { // Not proof that a caller did not encode meaning, but it does refuse the shapes that carry it: // a JWT has dots, a URL has slashes, an email has an at sign. assertThatThrownBy(() -> new WebSocketConnectionId("eyJhbGciOi.eyJzdWIi.sig")) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> new WebSocketSessionId("tenant/acme/user/42")) + assertThatThrownBy(() -> new WebSocketConnectionId("tenant/acme/user/42")) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> new WebSocketSessionId("alice@example.com")) + assertThatThrownBy(() -> new WebSocketConnectionId("alice@example.com")) .isInstanceOf(IllegalArgumentException.class); } - - @Test - @DisplayName("a node id is low cardinality, which is what makes it the one safe tag") - void nodeIdIsLowCardinality() { - assertThatCode(() -> new WebSocketNodeId("edge-3.eu-west-1")).doesNotThrowAnyException(); - assertThatThrownBy(() -> new WebSocketNodeId("Edge-3")) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("connection and session identity are separate types") - void connectionAndSessionAreDistinctTypes() { - // Distinct so a reconnect can be recognised without reusing a transport identity, and so no - // method can take one where it meant the other. - WebSocketConnectionId connection = new WebSocketConnectionId("c-01H8XQ2N4K"); - WebSocketSessionId session = new WebSocketSessionId("c-01H8XQ2N4K"); - - assertThat((Object) connection).isNotEqualTo(session); - } } diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/error/WebSocketCloseCodeTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/error/WebSocketCloseCodeTest.java deleted file mode 100644 index 65d88c96..00000000 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/error/WebSocketCloseCodeTest.java +++ /dev/null @@ -1,152 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.error; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * How a failure reaches a peer, which is where WebSocket diverges from HTTP most sharply. - * - *

HTTP has one answer for everything: a status and a body. A WebSocket has three, chosen by - * whether the handshake completed and whether the connection survives — and picking the wrong one - * produces a client that sees a socket open and immediately close with nothing to explain it. - */ -class WebSocketCloseCodeTest { - - @Test - @DisplayName("before the handshake a failure is an HTTP problem") - void beforeHandshakeIsHttp() { - // There is no WebSocket yet. A close frame here is a frame on a connection that was never - // upgraded. - assertThat(WebSocketClosePolicy.transportFor(WebSocketFailureCategory.NOT_AUTHORIZED, false)) - .isEqualTo(WebSocketErrorTransport.HTTP_PROBLEM); - assertThat(WebSocketClosePolicy.transportFor(WebSocketFailureCategory.OVERLOADED, false)) - .isEqualTo(WebSocketErrorTransport.HTTP_PROBLEM); - } - - @Test - @DisplayName("after the handshake a survivable failure is a typed message") - void afterHandshakeSurvivableIsATypedMessage() { - // No status line left to send, and no reason to end a healthy connection over one bad message. - assertThat(WebSocketClosePolicy.transportFor(WebSocketFailureCategory.MALFORMED, true)) - .isEqualTo(WebSocketErrorTransport.TYPED_ERROR_MESSAGE); - assertThat(WebSocketClosePolicy.transportFor(WebSocketFailureCategory.VALIDATION_FAILED, true)) - .isEqualTo(WebSocketErrorTransport.TYPED_ERROR_MESSAGE); - } - - @Test - @DisplayName("a malformed message does not close the connection") - void malformedDoesNotDisconnect() { - // Disconnecting turns a client-side typo into a reconnect storm: the client reconnects and - // sends the same bad message. - assertThat(WebSocketClosePolicy.closeCodeFor(WebSocketFailureCategory.MALFORMED)).isEmpty(); - assertThat(WebSocketClosePolicy.closeCodeFor(WebSocketFailureCategory.UNKNOWN_TYPE)).isEmpty(); - assertThat(WebSocketClosePolicy.closeCodeFor(WebSocketFailureCategory.EXPIRED)).isEmpty(); - } - - @Test - @DisplayName("an expired credential does close the connection") - void expiredCredentialDisconnects() { - // Answering and continuing would leave an unauthorised peer subscribed and receiving data. - assertThat(WebSocketClosePolicy.closeCodeFor(WebSocketFailureCategory.CREDENTIAL_EXPIRED)) - .contains(WebSocketCloseCode.CREDENTIAL_EXPIRED); - assertThat(WebSocketClosePolicy.transportFor(WebSocketFailureCategory.CREDENTIAL_EXPIRED, true)) - .isEqualTo(WebSocketErrorTransport.CLOSE_FRAME); - } - - @Test - @DisplayName("message too big is 1009, the standard code") - void messageTooBigUsesTheStandardCode() { - // A browser surfaces 1009 with its own wording, so a developer learns what happened without - // the client library knowing anything about this API. - assertThat(WebSocketClosePolicy.closeCodeFor(WebSocketFailureCategory.TOO_LARGE)) - .contains(WebSocketCloseCode.MESSAGE_TOO_BIG); - assertThat(WebSocketCloseCode.MESSAGE_TOO_BIG.code()).isEqualTo(1009); - assertThat(WebSocketCloseCode.MESSAGE_TOO_BIG.applicationRange()).isFalse(); - } - - @Test - @DisplayName("temporary overload is 1013, with 4503 available alongside it") - void overloadUsesTheStandardCodeFirst() { - // 1013 is what a generic client backs off on. 4503 exists for this platform's own client to - // distinguish shedding from a transient server condition. - assertThat(WebSocketClosePolicy.closeCodeFor(WebSocketFailureCategory.OVERLOADED)) - .contains(WebSocketCloseCode.TRY_AGAIN_LATER); - assertThat(WebSocketCloseCode.TRY_AGAIN_LATER.code()).isEqualTo(1013); - assertThat(WebSocketCloseCode.SHED_FOR_CAPACITY.code()).isEqualTo(4503); - assertThat(WebSocketCloseCode.SHED_FOR_CAPACITY.applicationRange()).isTrue(); - } - - @Test - @DisplayName("codes a peer only reports can never be sent") - void reportOnlyCodesAreNotSendable() { - // 1005 and 1006 are what a browser reports when no close frame arrived. Sending them is a - // contradiction, and it is refused here rather than at the transport layer. - assertThat(WebSocketCloseCode.sendable(1005)).isFalse(); - assertThat(WebSocketCloseCode.sendable(1006)).isFalse(); - assertThat(WebSocketCloseCode.sendable(1015)).isFalse(); - assertThat(WebSocketCloseCode.sendable(1000)).isTrue(); - assertThat(WebSocketCloseCode.sendable(4503)).isTrue(); - } - - @Test - @DisplayName("every code this platform sends is sendable") - void everyDeclaredCodeIsSendable() { - for (WebSocketCloseCode code : WebSocketCloseCode.values()) { - assertThat(WebSocketCloseCode.sendable(code.code())) - .as("%s (%d) cannot appear in a close frame", code, code.code()) - .isTrue(); - } - } - - @Test - @DisplayName("an unsolicited error carries no correlation") - void unsolicitedErrorHasNoCorrelation() { - // The absence is the signal: a client with several requests in flight uses it to decide - // between failing one call and surfacing a connection-level problem. - assertThat( - WebSocketErrorMessage.unsolicited( - WebSocketFailureCategory.CREDENTIAL_EXPIRED, "the credential expired") - .correlationId()) - .isEmpty(); - assertThat( - WebSocketErrorMessage.answering( - WebSocketFailureCategory.VALIDATION_FAILED, "amount must be positive", "m-1") - .correlationId()) - .contains("m-1"); - } - - @Test - @DisplayName("a retry hint on a permanent failure is refused") - void retryHintOnPermanentFailureIsRefused() { - // It would invite a loop that can only end the same way. - assertThatThrownBy( - () -> - WebSocketErrorMessage.retryable( - WebSocketFailureCategory.VALIDATION_FAILED, "amount must be positive", 1000)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("cannot succeed"); - } - - @Test - @DisplayName("an error with no detail is refused") - void errorNeedsDetail() { - assertThatThrownBy( - () -> WebSocketErrorMessage.unsolicited(WebSocketFailureCategory.INTERNAL, " ")) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("every failure category has a decided transport") - void everyCategoryIsDecided() { - // A category added without a decision here would fall through to whatever the switch's default - // happened to be; there is no default, so it cannot compile. - for (WebSocketFailureCategory category : WebSocketFailureCategory.values()) { - assertThat(WebSocketClosePolicy.transportFor(category, true)).isNotNull(); - assertThat(WebSocketClosePolicy.transportFor(category, false)) - .isEqualTo(WebSocketErrorTransport.HTTP_PROBLEM); - } - } -} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/evidence/WebSocketInboundEvidenceTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/evidence/WebSocketInboundEvidenceTest.java deleted file mode 100644 index 0d76b1d3..00000000 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/evidence/WebSocketInboundEvidenceTest.java +++ /dev/null @@ -1,201 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.evidence; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketConnectionId; -import dev.caskeleton.adapter.inbound.websocket.error.WebSocketCloseCode; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageId; -import java.time.Instant; -import java.util.Optional; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * The question evidence exists to answer: after this connection died, was the work durable? - * - *

Nothing else can answer it. The connection is gone, the client is reconnecting, and the - * platform has to decide whether replaying the command is recovery or duplication. Every rule here - * exists so the answer is what happened rather than what was last written. - */ -class WebSocketInboundEvidenceTest { - - private static final Instant NOW = Instant.parse("2026-08-25T10:00:00Z"); - private static final WebSocketMessageId MESSAGE = new WebSocketMessageId("m-1"); - - @Test - @DisplayName("evidence starts empty and is not durable") - void startsUnknownAndNotDurable() { - WebSocketInboundEvidence evidence = new WebSocketInboundEvidence(MESSAGE); - - assertThat(evidence.furthestStage()).isEmpty(); - assertThat(evidence.durable()).isFalse(); - assertThat(evidence.safeToRetry()).isTrue(); - } - - @Test - @DisplayName("only the application may claim its work committed") - void onlyTheApplicationClaimsCommit() { - // The rule the whole record exists for. A handler returning means the method returned; it does - // not mean a transaction committed, and inferring one from the other is how a retry - // re-executes a committed write. - assertThatThrownBy( - () -> - new WebSocketInboundEvidence(MESSAGE) - .record( - WebSocketInboundStage.APPLICATION_COMMITTED, - WebSocketEvidenceSource.PLATFORM, - NOW)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("not the same thing"); - - assertThatCode( - () -> - new WebSocketInboundEvidence(MESSAGE) - .record( - WebSocketInboundStage.APPLICATION_COMMITTED, - WebSocketEvidenceSource.APPLICATION, - NOW)) - .doesNotThrowAnyException(); - } - - @Test - @DisplayName("started is not committed") - void startedIsNotCommitted() { - // One step apart, opposite meanings when the connection dies between them. - WebSocketInboundEvidence started = - new WebSocketInboundEvidence(MESSAGE) - .record( - WebSocketInboundStage.APPLICATION_STARTED, WebSocketEvidenceSource.PLATFORM, NOW); - - assertThat(started.durable()).isFalse(); - assertThat(started.safeToRetry()).isTrue(); - - WebSocketInboundEvidence committed = - started.record( - WebSocketInboundStage.APPLICATION_COMMITTED, - WebSocketEvidenceSource.APPLICATION, - NOW.plusMillis(5)); - - assertThat(committed.durable()).isTrue(); - assertThat(committed.safeToRetry()).isFalse(); - } - - @Test - @DisplayName("evidence cannot move backwards") - void evidenceIsMonotonic() { - // Evidence that can go backwards answers "was this durable" with whatever was written last. - WebSocketInboundEvidence evidence = - new WebSocketInboundEvidence(MESSAGE) - .record( - WebSocketInboundStage.APPLICATION_COMMITTED, - WebSocketEvidenceSource.APPLICATION, - NOW); - - assertThatThrownBy( - () -> - evidence.record( - WebSocketInboundStage.ADMITTED, WebSocketEvidenceSource.PLATFORM, NOW)) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("backwards"); - } - - @Test - @DisplayName("the same stage cannot be recorded twice") - void sameStageCannotRepeat() { - WebSocketInboundEvidence evidence = - new WebSocketInboundEvidence(MESSAGE) - .record(WebSocketInboundStage.ADMITTED, WebSocketEvidenceSource.PLATFORM, NOW); - - assertThatThrownBy( - () -> - evidence.record( - WebSocketInboundStage.ADMITTED, WebSocketEvidenceSource.PLATFORM, NOW)) - .isInstanceOf(IllegalStateException.class); - } - - @Test - @DisplayName("stage order is declared, not taken from declaration position") - void stageOrderIsDeclared() { - // ordinal() would renumber every stage after an insertion, and comparisons that were correct - // become wrong with no compile error. - assertThat(WebSocketInboundStage.FRAME_RECEIVED.rank()) - .isLessThan(WebSocketInboundStage.APPLICATION_COMMITTED.rank()); - assertThat(WebSocketInboundStage.APPLICATION_STARTED.durable()).isFalse(); - assertThat(WebSocketInboundStage.APPLICATION_COMMITTED.durable()).isTrue(); - assertThat(WebSocketInboundStage.RESPONSE_ENQUEUED.durable()).isTrue(); - } - - @Test - @DisplayName("a flush is not a delivery") - void flushIsNotDelivery() { - // A WebSocket gives the sender no application acknowledgement, so delivery is not observable - // here. Treating a flush as one turns at-least-once into at-most-once during a partition. - WebSocketOutboundEvidence flushed = - WebSocketOutboundEvidence.queued(MESSAGE, NOW).written().flushed(NOW.plusMillis(2)); - - assertThat(flushed.stage()).isEqualTo(WebSocketOutboundStage.FLUSHED); - assertThat(flushed.knownReceived()).isFalse(); - assertThat(flushed.acknowledgedAt(NOW.plusMillis(9)).knownReceived()).isTrue(); - } - - @Test - @DisplayName("there is no DELIVERED stage to reach for") - void thereIsNoDeliveredStage() { - assertThat(WebSocketOutboundStage.values()) - .noneMatch(stage -> stage.name().contains("DELIVERED")); - } - - @Test - @DisplayName("an acknowledgement for something never sent is refused") - void acknowledgementWithoutASendIsRefused() { - assertThatThrownBy( - () -> - new WebSocketOutboundEvidence( - MESSAGE, - WebSocketOutboundStage.QUEUED, - NOW, - Optional.empty(), - Optional.of(NOW))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("never sent"); - } - - @Test - @DisplayName("a dropped outbound message is recorded, not silent") - void droppedMessagesAreVisible() { - // A clean close hides this entirely. Two hours and a normal close code looks identical whether - // four thousand messages were discarded or none were. - WebSocketConnectionEvidence lossy = - new WebSocketConnectionEvidence( - new WebSocketConnectionId("c-01H8XQ2N4K"), - NOW, - Optional.of(NOW.plusSeconds(7200)), - Optional.of(WebSocketCloseCode.NORMAL), - 120, - 4000, - 4000, - 900_000); - - assertThat(lossy.lostMessages()).isTrue(); - assertThat(lossy.lifetime(NOW)).isEqualTo(java.time.Duration.ofHours(2)); - } - - @Test - @DisplayName("a close code without a close time is refused") - void closeCodeNeedsACloseTime() { - assertThatThrownBy( - () -> - new WebSocketConnectionEvidence( - new WebSocketConnectionId("c-01H8XQ2N4K"), - NOW, - Optional.empty(), - Optional.of(WebSocketCloseCode.NORMAL), - 0, - 0, - 0, - 0)) - .isInstanceOf(IllegalArgumentException.class); - } -} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/fault/CommandLossRecoveryTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/fault/CommandLossRecoveryTest.java deleted file mode 100644 index 877c440e..00000000 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/fault/CommandLossRecoveryTest.java +++ /dev/null @@ -1,236 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.fault; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketActorReference; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketEndpointName; -import dev.caskeleton.adapter.inbound.websocket.idempotency.CommandReconciliation; -import dev.caskeleton.adapter.inbound.websocket.idempotency.CommittedResultLedger; -import dev.caskeleton.adapter.inbound.websocket.idempotency.WebSocketCommandKey; -import dev.caskeleton.adapter.inbound.websocket.idempotency.WebSocketCommandOutcome; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageId; -import dev.caskeleton.adapter.inbound.websocket.testkit.fault.WebSocketFaultInjector; -import dev.caskeleton.adapter.inbound.websocket.testkit.fault.WebSocketFaultPoint; -import java.nio.charset.StandardCharsets; -import java.time.Duration; -import java.time.Instant; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.atomic.AtomicInteger; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * A crash at each point in a command's life, and what a reconnecting client must then be told. - * - *

The reconnect is what makes this a WebSocket problem rather than a general one. An HTTP client - * that loses a response has one request to reason about; a WebSocket client reconnects and replays - * everything it never saw an answer for, all at once — so the recovery path is exercised at - * concurrency, on every deploy, whether or not anybody planned for it. - */ -class CommandLossRecoveryTest { - - private static final Instant NOW = Instant.parse("2026-08-25T10:00:00Z"); - private static final Duration LEASE = Duration.ofSeconds(30); - private static final byte[] SALT = - "a-deployment-salt-of-adequate-length".getBytes(StandardCharsets.UTF_8); - - private final Ledger ledger = new Ledger(); - private final WebSocketFaultInjector faults = new WebSocketFaultInjector(); - private final AtomicInteger sideEffects = new AtomicInteger(); - - private static WebSocketCommandKey key(String messageId) { - return new WebSocketCommandKey( - new WebSocketEndpointName("live-updates"), - WebSocketActorReference.of("alice", "acme", SALT), - new WebSocketMessageId(messageId)); - } - - /** - * One attempt at handling a command, with faults where the platform's own steps are. - * - * @return the result to send, or empty when the attempt did not get that far - */ - private Optional attempt(WebSocketCommandKey commandKey, Instant now) { - faults.trigger(WebSocketFaultPoint.BEFORE_DECODE); - WebSocketCommandOutcome outcome = ledger.claim(commandKey, now, LEASE); - if (outcome == WebSocketCommandOutcome.COMMITTED) { - return ledger.committedResult(commandKey, now); - } - if (outcome != WebSocketCommandOutcome.NEW) { - return Optional.empty(); - } - faults.trigger(WebSocketFaultPoint.AFTER_ADMISSION_BEFORE_APPLICATION); - faults.trigger(WebSocketFaultPoint.AFTER_APPLICATION_START_BEFORE_COMMIT); - // The business work. - int order = sideEffects.incrementAndGet(); - faults.trigger(WebSocketFaultPoint.AFTER_APPLICATION_COMMIT_BEFORE_LEDGER); - ledger.recordCommitted(commandKey, "{\"order\":" + order + "}", now); - faults.trigger(WebSocketFaultPoint.AFTER_LEDGER_BEFORE_RESPONSE); - return ledger.committedResult(commandKey, now); - } - - @Test - @DisplayName("a crash before the application leaves nothing behind") - void crashBeforeApplicationLeavesNothing() { - faults.arm(WebSocketFaultPoint.AFTER_ADMISSION_BEFORE_APPLICATION); - expectFault(() -> attempt(key("m-1"), NOW)); - - // The claim stands, so the immediate retry is told to wait rather than running twice. After - // the lease lapses it is genuinely retryable, because nothing durable happened. - assertThat(sideEffects).hasValue(0); - assertThat(ledger.claim(key("m-1"), NOW.plus(LEASE).plusSeconds(1), LEASE)) - .isEqualTo(WebSocketCommandOutcome.UNKNOWN); - } - - @Test - @DisplayName("a crash between commit and ledger is UNKNOWN, and reconciliation settles it") - void crashInTheWindowIsUnknownAndReconcilable() { - // The only window that cannot be resolved by replaying or re-running. - faults.arm(WebSocketFaultPoint.AFTER_APPLICATION_COMMIT_BEFORE_LEDGER); - expectFault(() -> attempt(key("m-1"), NOW)); - - assertThat(sideEffects).hasValue(1); - Instant later = NOW.plus(LEASE).plusSeconds(1); - assertThat(ledger.outcome(key("m-1"), later)).isEqualTo(WebSocketCommandOutcome.UNKNOWN); - - // Only the business data can say. Here it can: the side effect is visible. - CommandReconciliation reconciliation = - (commandKey, now) -> - sideEffects.get() > 0 - ? CommandReconciliation.Verdict.committed("{\"order\":1}") - : CommandReconciliation.Verdict.notCommitted(); - - assertThat(reconciliation.reconcile(key("m-1"), later).state()) - .isEqualTo(CommandReconciliation.State.COMMITTED); - // And the work was not done twice on the way to finding out. - assertThat(sideEffects).hasValue(1); - } - - @Test - @DisplayName("a crash after the ledger replays the stored result rather than re-running") - void crashAfterLedgerReplays() { - faults.arm(WebSocketFaultPoint.AFTER_LEDGER_BEFORE_RESPONSE); - expectFault(() -> attempt(key("m-1"), NOW)); - - Optional replayed = attempt(key("m-1"), NOW.plusSeconds(1)); - - assertThat(replayed).contains("{\"order\":1}"); - assertThat(sideEffects).hasValue(1); - } - - @Test - @DisplayName("a reconnect storm replaying one command executes it once") - void reconnectStormExecutesOnce() { - // The shape a WebSocket produces and HTTP does not: the same command arriving many times at - // once, because every client on a dropped node reconnects together. - List> results = new ArrayList<>(); - for (int index = 0; index < 20; index++) { - results.add(attempt(key("m-1"), NOW.plusMillis(index))); - } - - assertThat(sideEffects).hasValue(1); - assertThat(results).filteredOn(Optional::isPresent).isNotEmpty(); - assertThat(results.stream().filter(Optional::isPresent).map(Optional::orElseThrow).distinct()) - .containsExactly("{\"order\":1}"); - } - - @Test - @DisplayName("two different commands from one client are both executed") - void distinctCommandsBothRun() { - // The mirror of the above: deduplicating too aggressively is the other way to be wrong, and it - // is silent. - attempt(key("m-1"), NOW); - attempt(key("m-2"), NOW); - - assertThat(sideEffects).hasValue(2); - } - - private static void expectFault(Runnable attempt) { - try { - attempt.run(); - throw new AssertionError("the armed fault did not fire"); - } catch (WebSocketFaultInjector.InjectedWebSocketFault expected) { - // The point of arming it. - } - } - - /** A ledger with the semantics a real one must have. */ - private static final class Ledger implements CommittedResultLedger { - - private record Entry( - WebSocketCommandOutcome outcome, Optional result, Instant leaseExpiresAt) {} - - private final Map entries = new ConcurrentHashMap<>(); - - @Override - public WebSocketCommandOutcome claim( - WebSocketCommandKey key, Instant now, Duration leaseDuration) { - Objects.requireNonNull(key, "key"); - Entry claim = - new Entry(WebSocketCommandOutcome.IN_FLIGHT, Optional.empty(), now.plus(leaseDuration)); - Entry existing = entries.putIfAbsent(key.storageKey(), claim); - if (existing == null) { - return WebSocketCommandOutcome.NEW; - } - return switch (existing.outcome()) { - case COMMITTED -> WebSocketCommandOutcome.COMMITTED; - case FAILED -> - entries.replace(key.storageKey(), existing, claim) - ? WebSocketCommandOutcome.NEW - : WebSocketCommandOutcome.IN_FLIGHT; - case IN_FLIGHT -> - now.isBefore(existing.leaseExpiresAt()) - ? WebSocketCommandOutcome.IN_FLIGHT - : WebSocketCommandOutcome.UNKNOWN; - case NEW, UNKNOWN -> WebSocketCommandOutcome.UNKNOWN; - }; - } - - @Override - public void recordCommitted(WebSocketCommandKey key, String encodedResult, Instant at) { - entries.put( - key.storageKey(), - new Entry(WebSocketCommandOutcome.COMMITTED, Optional.of(encodedResult), at)); - } - - @Override - public void recordFailed(WebSocketCommandKey key, Instant at) { - entries.computeIfPresent( - key.storageKey(), - (storageKey, existing) -> - existing.outcome() == WebSocketCommandOutcome.COMMITTED - ? existing - : new Entry(WebSocketCommandOutcome.FAILED, Optional.empty(), at)); - } - - @Override - public Optional committedResult(WebSocketCommandKey key, Instant now) { - Entry entry = entries.get(key.storageKey()); - return entry != null && entry.outcome() == WebSocketCommandOutcome.COMMITTED - ? entry.result() - : Optional.empty(); - } - - @Override - public WebSocketCommandOutcome outcome(WebSocketCommandKey key, Instant now) { - Entry entry = entries.get(key.storageKey()); - if (entry == null) { - return WebSocketCommandOutcome.NEW; - } - return entry.outcome() == WebSocketCommandOutcome.IN_FLIGHT - && !now.isBefore(entry.leaseExpiresAt()) - ? WebSocketCommandOutcome.UNKNOWN - : entry.outcome(); - } - - @Override - public List unresolved(Instant now) { - return List.of(); - } - } -} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/handler/LateResponseTombstoneTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/handler/LateResponseTombstoneTest.java deleted file mode 100644 index 6a3f393a..00000000 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/handler/LateResponseTombstoneTest.java +++ /dev/null @@ -1,115 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.handler; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketConnectionId; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketCorrelationId; -import java.time.Duration; -import java.time.Instant; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * What happens to the answer that arrives after the caller gave up. - * - *

The bug this prevents produces no error at any layer. A request times out, the work behind it - * finishes anyway, and the answer arrives at a registry where the correlation id has since been - * claimed by a different request — because clients that number their requests reuse ids as a matter - * of course. The answer is delivered, the shape matches, and the client applies somebody else's - * result. - */ -class LateResponseTombstoneTest { - - private static final Instant NOW = Instant.parse("2026-08-25T10:00:00Z"); - private static final WebSocketConnectionId CONNECTION = new WebSocketConnectionId("conn-0001"); - private static final WebSocketCorrelationId CORRELATION = new WebSocketCorrelationId("req-7"); - - private final LateResponseTombstone tombstones = - new LateResponseTombstone(Duration.ofSeconds(30)); - - @Test - @DisplayName("an id nobody timed out is not late") - void unknownIdIsNotLate() { - assertThat(tombstones.isLate(CONNECTION, CORRELATION, NOW)).isFalse(); - assertThat(tombstones.mayReuse(CONNECTION, CORRELATION, NOW)).isTrue(); - } - - @Test - @DisplayName("an answer inside the window is recognised as late") - void answerInsideTheWindowIsLate() { - tombstones.record(CONNECTION, CORRELATION, NOW); - - assertThat(tombstones.isLate(CONNECTION, CORRELATION, NOW.plusSeconds(29))).isTrue(); - } - - @Test - @DisplayName("the id cannot be reused while the tombstone stands") - void reuseIsRefusedWhileTombstoned() { - // The other half of the same defect. Recognising the late answer is useless if a new request - // has already taken the id it would have matched. - tombstones.record(CONNECTION, CORRELATION, NOW); - - assertThat(tombstones.mayReuse(CONNECTION, CORRELATION, NOW.plusSeconds(1))).isFalse(); - assertThat(tombstones.mayReuse(CONNECTION, CORRELATION, NOW.plusSeconds(30))).isTrue(); - } - - @Test - @DisplayName("the window ends, so the id becomes ordinary again") - void windowEnds() { - // Bounded on purpose: the alternative is a map that grows with every timeout the connection - // ever had, which turns a transient fault into a memory leak. - tombstones.record(CONNECTION, CORRELATION, NOW); - - assertThat(tombstones.isLate(CONNECTION, CORRELATION, NOW.plusSeconds(30))).isFalse(); - assertThat(tombstones.isLate(CONNECTION, CORRELATION, NOW.plusSeconds(31))).isFalse(); - } - - @Test - @DisplayName("a correlation id is scoped to its connection") - void correlationIsScopedToConnection() { - // Clients number from one. Without the connection in the key, the first client to time out - // request 1 would tombstone request 1 for every other client on the node. - tombstones.record(CONNECTION, CORRELATION, NOW); - - assertThat(tombstones.isLate(new WebSocketConnectionId("conn-0002"), CORRELATION, NOW)) - .isFalse(); - } - - @Test - @DisplayName("expired tombstones are evicted rather than accumulating") - void expiredTombstonesAreEvicted() { - tombstones.record(CONNECTION, CORRELATION, NOW); - tombstones.record(CONNECTION, new WebSocketCorrelationId("req-8"), NOW.plusSeconds(20)); - - assertThat(tombstones.evictExpired(NOW.plusSeconds(31))).isEqualTo(1); - assertThat(tombstones.size()).isEqualTo(1); - assertThat(tombstones.evictExpired(NOW.plusSeconds(51))).isEqualTo(1); - assertThat(tombstones.size()).isZero(); - } - - @Test - @DisplayName("a closed connection takes its tombstones with it") - void closedConnectionReleasesItsTombstones() { - // Nothing can arrive for a connection that is gone, and the ids cannot collide with a new - // connection's because the connection id is part of the key. - tombstones.record(CONNECTION, CORRELATION, NOW); - tombstones.record(CONNECTION, new WebSocketCorrelationId("req-8"), NOW); - tombstones.record(new WebSocketConnectionId("conn-0002"), CORRELATION, NOW); - - assertThat(tombstones.releaseConnection(CONNECTION)).isEqualTo(2); - assertThat(tombstones.size()).isEqualTo(1); - } - - @Test - @DisplayName("a zero window is refused at construction") - void zeroWindowIsRefused() { - // It would forget the id at the instant the late answer for it is most likely still in flight, - // which is a tombstone that exists and protects nothing. - assertThatThrownBy(() -> new LateResponseTombstone(Duration.ZERO)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("still in flight"); - assertThatThrownBy(() -> new LateResponseTombstone(Duration.ofSeconds(-1))) - .isInstanceOf(IllegalArgumentException.class); - } -} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/handler/WebSocketCorrelationRegistryTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/handler/WebSocketCorrelationRegistryTest.java deleted file mode 100644 index ba7f88a9..00000000 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/handler/WebSocketCorrelationRegistryTest.java +++ /dev/null @@ -1,163 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.handler; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketConnectionId; -import dev.caskeleton.adapter.inbound.websocket.error.WebSocketFailureCategory; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketCorrelationId; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageType; -import java.time.Duration; -import java.time.Instant; -import java.util.List; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * Routing answers to waiters on a connection that multiplexes many at once. - * - *

The correlation id is chosen by the client, so two clients will eventually pick the same one. - * Most start their counters at 1, so "eventually" is the second connection. - */ -class WebSocketCorrelationRegistryTest { - - private static final Instant NOW = Instant.parse("2026-08-25T10:00:00Z"); - private static final Duration TTL = Duration.ofSeconds(30); - private static final WebSocketConnectionId ALICE = new WebSocketConnectionId("c-alice-0001"); - private static final WebSocketConnectionId BOB = new WebSocketConnectionId("c-bob-00001"); - private static final WebSocketCorrelationId ONE = new WebSocketCorrelationId("1"); - - private final WebSocketCorrelationRegistry registry = new WebSocketCorrelationRegistry(4); - - @Test - @DisplayName("an answer resolves the request that issued it") - void answerResolvesItsRequest() { - assertThat(registry.register(ALICE, ONE, NOW, TTL)).isTrue(); - - assertThat(registry.complete(ALICE, ONE, NOW.plusSeconds(1))).isPresent(); - // Taken, not copied: a second answer for the same correlation resolves nothing. - assertThat(registry.complete(ALICE, ONE, NOW.plusSeconds(1))).isEmpty(); - } - - @Test - @DisplayName("two connections may use the same correlation id without colliding") - void correlationIsScopedToTheConnection() { - // Clients pick these, and most start at 1. Keyed on the id alone, one caller's answer goes to - // the other — a disclosure rather than a mix-up. - assertThat(registry.register(ALICE, ONE, NOW, TTL)).isTrue(); - assertThat(registry.register(BOB, ONE, NOW, TTL)).isTrue(); - - assertThat(registry.complete(ALICE, ONE, NOW)).isPresent(); - // Bob's is untouched by Alice's answer. - assertThat(registry.complete(BOB, ONE, NOW)).isPresent(); - } - - @Test - @DisplayName("an answer on the wrong connection resolves nothing") - void answerOnAnotherConnectionResolvesNothing() { - registry.register(ALICE, ONE, NOW, TTL); - - assertThat(registry.complete(BOB, ONE, NOW)).isEmpty(); - assertThat(registry.complete(ALICE, ONE, NOW)).isPresent(); - } - - @Test - @DisplayName("a duplicate correlation on one connection is refused") - void duplicateCorrelationIsRefused() { - assertThat(registry.register(ALICE, ONE, NOW, TTL)).isTrue(); - assertThat(registry.register(ALICE, ONE, NOW, TTL)).isFalse(); - } - - @Test - @DisplayName("a connection cannot register more than its cap") - void inFlightIsCapped() { - // Without a cap a client registers faster than it consumes answers and the map is unbounded — - // the slow-consumer shape again, in a different structure. - for (int index = 0; index < 4; index++) { - assertThat(registry.register(ALICE, new WebSocketCorrelationId("c" + index), NOW, TTL)) - .isTrue(); - } - - assertThat(registry.register(ALICE, new WebSocketCorrelationId("c9"), NOW, TTL)).isFalse(); - } - - @Test - @DisplayName("an expired entry no longer resolves") - void expiredEntryDoesNotResolve() { - registry.register(ALICE, ONE, NOW, TTL); - - assertThat(registry.complete(ALICE, ONE, NOW.plus(TTL))).isEmpty(); - } - - @Test - @DisplayName("expired entries are returned so the waiter can be told") - void expiredEntriesAreReturned() { - // Silently discarding one leaves the client waiting for an answer that will never come. - registry.register(ALICE, ONE, NOW, TTL); - - List expired = registry.reapExpired(NOW.plus(TTL)); - - assertThat(expired).hasSize(1); - assertThat(expired.get(0).correlationId()).isEqualTo(ONE); - assertThat(registry.size()).isZero(); - } - - @Test - @DisplayName("expiry frees the connection's allowance") - void expiryFreesTheCap() { - for (int index = 0; index < 4; index++) { - registry.register(ALICE, new WebSocketCorrelationId("c" + index), NOW, TTL); - } - - assertThat(registry.countFor(ALICE, NOW.plus(TTL))).isZero(); - assertThat(registry.register(ALICE, new WebSocketCorrelationId("c9"), NOW.plus(TTL), TTL)) - .isTrue(); - } - - @Test - @DisplayName("closing a connection releases everything it owned") - void closingReleasesEverything() { - // Otherwise the leak is proportional to churn rather than to load. - registry.register(ALICE, ONE, NOW, TTL); - registry.register(BOB, ONE, NOW, TTL); - - assertThat(registry.releaseConnection(ALICE)).hasSize(1); - assertThat(registry.size()).isEqualTo(1); - assertThat(registry.complete(BOB, ONE, NOW)).isPresent(); - } - - @Test - @DisplayName("a handler cannot both fail and emit") - void handlerResultIsOneOrTheOther() { - // Both leaves the platform choosing what the client sees, and either choice is wrong for - // somebody. - assertThatThrownBy( - () -> - new WebSocketHandlerResult( - List.of( - new WebSocketHandlerResult.Emission( - new WebSocketMessageType("order.placed.v1"), "{}")), - java.util.Optional.of( - new WebSocketHandlerResult.HandlerFailure( - WebSocketFailureCategory.INTERNAL, "boom")))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("choosing what the"); - } - - @Test - @DisplayName("a handler describes what to send rather than sending it") - void handlerResultIsDescriptive() { - // The reason ordering and backpressure are guarantees rather than conventions: a handler has - // no way to reach past the outbound queue. - WebSocketHandlerResult result = - WebSocketHandlerResult.of(new WebSocketMessageType("order.placed.v1"), "{}"); - - assertThat(result.succeeded()).isTrue(); - assertThat(result.emissions()).hasSize(1); - assertThat(WebSocketHandlerResult.none().emissions()).isEmpty(); - assertThat( - WebSocketHandlerResult.failed(WebSocketFailureCategory.VALIDATION_FAILED, "bad") - .succeeded()) - .isFalse(); - } -} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/handshake/HandshakeAdmissionPipelineTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/handshake/HandshakeAdmissionPipelineTest.java deleted file mode 100644 index 3bb7ade1..00000000 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/handshake/HandshakeAdmissionPipelineTest.java +++ /dev/null @@ -1,352 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.handshake; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.websocket.budget.WebSocketConnectionBudget; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketActorReference; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketEndpointCatalog; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketEndpointName; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketEndpointProfile; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketStackProfile; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketSubprotocolName; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketProtocolProfile; -import dev.caskeleton.adapter.inbound.websocket.security.WebSocketAuthenticationProfile; -import dev.caskeleton.adapter.inbound.websocket.security.WebSocketConnectionTicket; -import dev.caskeleton.adapter.inbound.websocket.security.WebSocketOriginPolicy; -import dev.caskeleton.adapter.inbound.websocket.security.WebSocketTicketStore; -import java.nio.charset.StandardCharsets; -import java.time.Duration; -import java.time.Instant; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.atomic.AtomicInteger; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * Handshake admission, where the order of the checks is itself the contract. - * - *

Everything here happens before the 101, which is the last point at which refusing is cheap and - * the only point at which the client can be told why in a way a browser surfaces. - */ -class HandshakeAdmissionPipelineTest { - - private static final Instant NOW = Instant.parse("2026-08-25T10:00:00Z"); - private static final byte[] SALT = - "a-deployment-salt-of-adequate-length".getBytes(StandardCharsets.UTF_8); - private static final WebSocketEndpointName ENDPOINT = new WebSocketEndpointName("live-updates"); - private static final String PATH = "/ws/v1/live"; - private static final WebSocketActorReference ALICE = - WebSocketActorReference.of("alice", "acme", SALT); - - private final AtomicInteger connections = new AtomicInteger(); - private final RecordingTicketStore tickets = new RecordingTicketStore(); - - private HandshakeAdmissionPipeline pipeline( - WebSocketAuthenticationProfile authentication, WebSocketOriginPolicy origins, int cap) { - return new HandshakeAdmissionPipeline( - WebSocketEndpointCatalog.of( - List.of( - new WebSocketEndpointProfile( - ENDPOINT, - PATH, - WebSocketStackProfile.SERVLET, - true, - WebSocketConnectionBudget.standard(), - cap))), - origins, - authentication, - WebSocketProtocolProfile.stable(), - tickets, - connections::get); - } - - private static HandshakeRequest request(String origin, String ticket) { - return new HandshakeRequest( - PATH, - Optional.ofNullable(origin), - List.of(WebSocketSubprotocolName.stable()), - Optional.ofNullable(ticket), - Optional.empty(), - false, - "203.0.113.4"); - } - - private String mintTicket() { - WebSocketConnectionTicket ticket = - new WebSocketConnectionTicket("t".repeat(40), ALICE, ENDPOINT, NOW, NOW.plusSeconds(10)); - tickets.issue(ticket); - return ticket.value(); - } - - @Test - @DisplayName("a valid handshake is admitted with the negotiated subprotocol") - void validHandshakeIsAdmitted() { - HandshakeDecision decision = - pipeline( - WebSocketAuthenticationProfile.ONE_TIME_TICKET, - WebSocketOriginPolicy.browsersOnly(Set.of("https://app.example.com")), - 100) - .admit(request("https://app.example.com", mintTicket()), NOW); - - assertThat(decision.admitted()).isTrue(); - assertThat(decision.actor()).contains(ALICE); - assertThat(decision.negotiatedSubprotocol()).contains(WebSocketSubprotocolName.stable()); - } - - @Test - @DisplayName("an unknown path is refused before anything else runs") - void unknownPathIsRefusedFirst() { - // A scanner sends exactly these. Doing origin or credential work first spends effort on a - // request that was never going to be served. - HandshakeDecision decision = - pipeline( - WebSocketAuthenticationProfile.ONE_TIME_TICKET, - WebSocketOriginPolicy.browsersOnly(Set.of("https://app.example.com")), - 100) - .admit( - new HandshakeRequest( - "/ws/v1/nope", - Optional.of("https://evil.example"), - List.of(WebSocketSubprotocolName.stable()), - Optional.of("t".repeat(40)), - Optional.empty(), - false, - "203.0.113.4"), - NOW); - - assertThat(decision.refusalStatus()).isEqualTo(404); - // The ticket was never looked at, which is the point of checking the route first. - assertThat(tickets.redemptions()).isZero(); - } - - @Test - @DisplayName("a foreign origin is refused before the credential is examined") - void foreignOriginIsRefusedBeforeAuthentication() { - // The order that makes the CSRF defence real. A cookie handshake from an attacker's page - // authenticates perfectly — the credential is valid; the page is not allowed to use it. - String ticket = mintTicket(); - - HandshakeDecision decision = - pipeline( - WebSocketAuthenticationProfile.ONE_TIME_TICKET, - WebSocketOriginPolicy.browsersOnly(Set.of("https://app.example.com")), - 100) - .admit(request("https://evil.example", ticket), NOW); - - assertThat(decision.refusalStatus()).isEqualTo(403); - assertThat(tickets.redemptions()).isZero(); - } - - @Test - @DisplayName("a saturated endpoint sheds before paying for the credential") - void saturationShedsBeforeAuthentication() { - connections.set(1); - String ticket = mintTicket(); - - HandshakeDecision decision = - pipeline( - WebSocketAuthenticationProfile.ONE_TIME_TICKET, - WebSocketOriginPolicy.browsersOnly(Set.of("https://app.example.com")), - 1) - .admit(request("https://app.example.com", ticket), NOW); - - assertThat(decision.refusalStatus()).isEqualTo(503); - // The expensive part was never reached, and the ticket is still spendable. - assertThat(tickets.redemptions()).isZero(); - } - - @Test - @DisplayName("a ticket works exactly once") - void ticketIsSingleUse() { - // Reconnect storms deliver concurrent duplicates, so a read-then-delete store would let two - // handshakes both find the same ticket. - String ticket = mintTicket(); - HandshakeAdmissionPipeline pipeline = - pipeline( - WebSocketAuthenticationProfile.ONE_TIME_TICKET, - WebSocketOriginPolicy.browsersOnly(Set.of("https://app.example.com")), - 100); - - assertThat(pipeline.admit(request("https://app.example.com", ticket), NOW).admitted()).isTrue(); - assertThat(pipeline.admit(request("https://app.example.com", ticket), NOW).refusalStatus()) - .isEqualTo(401); - } - - @Test - @DisplayName("a ticket minted for another endpoint does not open this one") - void ticketIsBoundToItsEndpoint() { - // Without the binding, a ticket for a low-privilege feed opens a privileged one. - WebSocketConnectionTicket elsewhere = - new WebSocketConnectionTicket( - "u".repeat(40), - ALICE, - new WebSocketEndpointName("other-feed"), - NOW, - NOW.plusSeconds(10)); - tickets.issue(elsewhere); - - HandshakeDecision decision = - pipeline( - WebSocketAuthenticationProfile.ONE_TIME_TICKET, - WebSocketOriginPolicy.browsersOnly(Set.of("https://app.example.com")), - 100) - .admit(request("https://app.example.com", elsewhere.value()), NOW); - - assertThat(decision.refusalStatus()).isEqualTo(401); - } - - @Test - @DisplayName("an expired ticket is refused") - void expiredTicketIsRefused() { - String ticket = mintTicket(); - - HandshakeDecision decision = - pipeline( - WebSocketAuthenticationProfile.ONE_TIME_TICKET, - WebSocketOriginPolicy.browsersOnly(Set.of("https://app.example.com")), - 100) - .admit(request("https://app.example.com", ticket), NOW.plusSeconds(60)); - - assertThat(decision.refusalStatus()).isEqualTo(401); - } - - @Test - @DisplayName("a ticket may not outlive its window") - void ticketLifetimeIsCapped() { - // The short lifetime is what makes a ticket in an access log harmless. Extend it and the - // query-string exposure it was introduced to fix comes back. - assertThatThrownBy( - () -> - new WebSocketConnectionTicket( - "t".repeat(40), ALICE, ENDPOINT, NOW, NOW.plus(Duration.ofHours(1)))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("bearer token in a query string"); - } - - @Test - @DisplayName("a short ticket is refused as guessable") - void shortTicketIsRefused() { - assertThatThrownBy( - () -> new WebSocketConnectionTicket("abc", ALICE, ENDPOINT, NOW, NOW.plusSeconds(10))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("guessable"); - } - - @Test - @DisplayName("a missing origin is refused for browsers and allowed for services") - void missingOriginDependsOnThePolicy() { - // Browsers always send one, so its absence means the caller is not the browser this endpoint - // is for. A service caller usually sends none, and refusing it would lock out every one. - assertThat(WebSocketOriginPolicy.browsersOnly(Set.of("https://app.example.com")).permits(null)) - .isFalse(); - assertThat( - WebSocketOriginPolicy.browsersAndServices(Set.of("https://app.example.com")) - .permits(null)) - .isTrue(); - } - - @Test - @DisplayName("a cookie profile with no origin allowlist is flagged unsafe") - void cookieProfileNeedsAnOriginAllowlist() { - // The same-origin policy does not protect a WebSocket handshake, and there is no preflight. - // The server's own Origin check is the entire defence. - assertThat( - WebSocketOriginPolicy.browsersOnly(Set.of()) - .safeFor(WebSocketAuthenticationProfile.SESSION_COOKIE)) - .isFalse(); - assertThat( - WebSocketOriginPolicy.browsersAndServices(Set.of("https://app.example.com")) - .safeFor(WebSocketAuthenticationProfile.SESSION_COOKIE)) - .isFalse(); - assertThat( - WebSocketOriginPolicy.browsersOnly(Set.of("https://app.example.com")) - .safeFor(WebSocketAuthenticationProfile.SESSION_COOKIE)) - .isTrue(); - } - - @Test - @DisplayName("origin matching is exact") - void originMatchingIsExact() { - WebSocketOriginPolicy policy = - WebSocketOriginPolicy.browsersOnly(Set.of("https://app.example.com")); - - assertThat(policy.permits("https://evil-app.example.com")).isFalse(); - assertThat(policy.permits("https://app.example.com.attacker.net")).isFalse(); - assertThat(policy.permits("http://app.example.com")).isFalse(); - assertThat(policy.permits("HTTPS://APP.EXAMPLE.COM")).isTrue(); - } - - @Test - @DisplayName("a wildcard origin is refused at construction") - void wildcardOriginIsRefused() { - assertThatThrownBy(() -> WebSocketOriginPolicy.browsersOnly(Set.of("https://*.example.com"))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("matches nothing"); - } - - @Test - @DisplayName("an unsupported subprotocol is refused after the actor is known") - void unsupportedSubprotocolIsRefusedLast() { - HandshakeDecision decision = - pipeline( - WebSocketAuthenticationProfile.ONE_TIME_TICKET, - WebSocketOriginPolicy.browsersOnly(Set.of("https://app.example.com")), - 100) - .admit( - new HandshakeRequest( - PATH, - Optional.of("https://app.example.com"), - List.of(new WebSocketSubprotocolName("vendor.other.v1.json")), - Optional.of(mintTicket()), - Optional.empty(), - false, - "203.0.113.4"), - NOW); - - // 400, not 426: the client did upgrade; what it offered is not spoken here. - assertThat(decision.refusalStatus()).isEqualTo(400); - } - - @Test - @DisplayName("an admitted decision always has an actor") - void admittedDecisionAlwaysHasAnActor() { - assertThatThrownBy(() -> new HandshakeDecision(true, Optional.empty(), Optional.empty(), 0, "")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("nobody attached to it"); - } - - /** A store whose redeem is atomic and which counts how often it was reached. */ - private static final class RecordingTicketStore implements WebSocketTicketStore { - - private final Map held = new ConcurrentHashMap<>(); - private final AtomicInteger redemptions = new AtomicInteger(); - - @Override - public void issue(WebSocketConnectionTicket ticket) { - held.put(ticket.value(), ticket); - } - - @Override - public Optional redeem(String value, Instant now) { - redemptions.incrementAndGet(); - // remove(), not get()-then-remove(). Two concurrent handshakes must not both find it. - return Optional.ofNullable(held.remove(value)); - } - - @Override - public int purgeExpired(Instant now) { - int before = held.size(); - held.values().removeIf(ticket -> !ticket.validAt(now)); - return before - held.size(); - } - - private int redemptions() { - return redemptions.get(); - } - } -} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/idempotency/InMemoryCommittedResultLedger.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/idempotency/InMemoryCommittedResultLedger.java deleted file mode 100644 index eaf4b5ab..00000000 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/idempotency/InMemoryCommittedResultLedger.java +++ /dev/null @@ -1,121 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.idempotency; - -import java.time.Duration; -import java.time.Instant; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.concurrent.ConcurrentHashMap; - -/** - * A ledger for tests, written to the same rules the real one must follow. - * - *

In memory, and therefore not a ledger anyone should deploy — the SPI's whole point is that a - * usable implementation writes in the application's own transaction, which this cannot. It exists - * to exercise the state machine, and it is deliberately no laxer than a correct implementation: the - * claim is atomic, an expired lease with no outcome reports UNKNOWN rather than NEW, and a - * committed entry is never overwritten. - */ -final class InMemoryCommittedResultLedger implements CommittedResultLedger { - - private record Entry( - WebSocketCommandOutcome outcome, Optional result, Instant leaseExpiresAt) {} - - private final Map entries = new ConcurrentHashMap<>(); - - @Override - public WebSocketCommandOutcome claim( - WebSocketCommandKey key, Instant now, Duration leaseDuration) { - Objects.requireNonNull(key, "key"); - Entry claim = - new Entry(WebSocketCommandOutcome.IN_FLIGHT, Optional.empty(), now.plus(leaseDuration)); - Entry existing = entries.putIfAbsent(key.storageKey(), claim); - if (existing == null) { - return WebSocketCommandOutcome.NEW; - } - return switch (existing.outcome()) { - case COMMITTED -> WebSocketCommandOutcome.COMMITTED; - // A failure is a completed attempt that changed nothing, so the next attempt may take it. - case FAILED -> - entries.replace(key.storageKey(), existing, claim) - ? WebSocketCommandOutcome.NEW - : WebSocketCommandOutcome.IN_FLIGHT; - case IN_FLIGHT -> - // A lapsed lease with no outcome is the crash window. Reporting NEW here would let a - // retry re-run work that may already be durable, which is precisely the bug UNKNOWN - // exists to keep visible. - now.isBefore(existing.leaseExpiresAt()) - ? WebSocketCommandOutcome.IN_FLIGHT - : WebSocketCommandOutcome.UNKNOWN; - case NEW, UNKNOWN -> WebSocketCommandOutcome.UNKNOWN; - }; - } - - @Override - public void recordCommitted(WebSocketCommandKey key, String encodedResult, Instant at) { - entries.put( - key.storageKey(), - new Entry(WebSocketCommandOutcome.COMMITTED, Optional.of(encodedResult), at)); - } - - @Override - public void recordFailed(WebSocketCommandKey key, Instant at) { - entries.computeIfPresent( - key.storageKey(), - (storageKey, existing) -> - existing.outcome() == WebSocketCommandOutcome.COMMITTED - // Never downgrade a committed entry. A late failure report for work that already - // committed would make the next attempt run it again. - ? existing - : new Entry(WebSocketCommandOutcome.FAILED, Optional.empty(), at)); - } - - @Override - public Optional committedResult(WebSocketCommandKey key, Instant now) { - Entry entry = entries.get(key.storageKey()); - return entry != null && entry.outcome() == WebSocketCommandOutcome.COMMITTED - ? entry.result() - : Optional.empty(); - } - - @Override - public WebSocketCommandOutcome outcome(WebSocketCommandKey key, Instant now) { - Entry entry = entries.get(key.storageKey()); - if (entry == null) { - return WebSocketCommandOutcome.NEW; - } - if (entry.outcome() == WebSocketCommandOutcome.IN_FLIGHT - && !now.isBefore(entry.leaseExpiresAt())) { - return WebSocketCommandOutcome.UNKNOWN; - } - return entry.outcome(); - } - - @Override - public List unresolved(Instant now) { - List stranded = new ArrayList<>(); - entries.forEach( - (storageKey, entry) -> { - if (entry.outcome() == WebSocketCommandOutcome.IN_FLIGHT - && !now.isBefore(entry.leaseExpiresAt())) { - stranded.add(parse(storageKey)); - } - }); - return List.copyOf(stranded); - } - - /** Simulates a crash: the claim stands and no outcome is ever recorded. */ - void abandonClaim(WebSocketCommandKey key) { - // Nothing to do beyond leaving the entry in place; that is exactly what a dead process leaves. - } - - private static WebSocketCommandKey parse(String storageKey) { - String[] parts = storageKey.split("\u001f", -1); - return new WebSocketCommandKey( - new dev.caskeleton.adapter.inbound.websocket.core.WebSocketEndpointName(parts[0]), - new dev.caskeleton.adapter.inbound.websocket.core.WebSocketActorReference(parts[1]), - new dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageId(parts[2])); - } -} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/idempotency/WebSocketCommandIdempotencyTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/idempotency/WebSocketCommandIdempotencyTest.java deleted file mode 100644 index 4d278a71..00000000 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/idempotency/WebSocketCommandIdempotencyTest.java +++ /dev/null @@ -1,172 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.idempotency; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketActorReference; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketEndpointName; -import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageId; -import java.nio.charset.StandardCharsets; -import java.time.Duration; -import java.time.Instant; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * Command idempotency across a reconnect, which is the case a WebSocket has and HTTP does not. - * - *

A client that loses its connection reconnects and replays whatever it never saw an answer for. - * That happens on a new connection with a new id, so anything scoped to the connection is inert - * exactly when it is needed — and the replay lands as concurrent duplicates, because reconnect - * storms deliver them all at once. - */ -class WebSocketCommandIdempotencyTest { - - private static final Instant NOW = Instant.parse("2026-08-25T10:00:00Z"); - private static final Duration LEASE = Duration.ofSeconds(30); - private static final byte[] SALT = - "a-deployment-salt-of-adequate-length".getBytes(StandardCharsets.UTF_8); - - private final InMemoryCommittedResultLedger ledger = new InMemoryCommittedResultLedger(); - - private static WebSocketCommandKey key(String messageId) { - return new WebSocketCommandKey( - new WebSocketEndpointName("live-updates"), - WebSocketActorReference.of("alice", "acme", SALT), - new WebSocketMessageId(messageId)); - } - - @Test - @DisplayName("a first attempt wins the claim") - void firstAttemptWins() { - assertThat(ledger.claim(key("m-1"), NOW, LEASE)).isEqualTo(WebSocketCommandOutcome.NEW); - } - - @Test - @DisplayName("the key survives a reconnect") - void keySurvivesAReconnect() { - // Scoped to the actor and the client's own message id, never to the connection. A key that - // included the connection would treat every replay as a new command. - assertThat(key("m-1")).isEqualTo(key("m-1")); - assertThat(key("m-1").storageKey()).doesNotContain("c-"); - } - - @Test - @DisplayName("a concurrent duplicate is told the command is in flight") - void concurrentDuplicateIsInFlight() { - ledger.claim(key("m-1"), NOW, LEASE); - - assertThat(ledger.claim(key("m-1"), NOW.plusSeconds(1), LEASE)) - .isEqualTo(WebSocketCommandOutcome.IN_FLIGHT); - } - - @Test - @DisplayName("a replay after commit gets the stored result, not a second execution") - void replayAfterCommitReturnsTheStoredResult() { - ledger.claim(key("m-1"), NOW, LEASE); - ledger.recordCommitted(key("m-1"), "{\"orderId\":\"o-1\"}", NOW.plusSeconds(1)); - - assertThat(ledger.claim(key("m-1"), NOW.plusSeconds(2), LEASE)) - .isEqualTo(WebSocketCommandOutcome.COMMITTED); - assertThat(ledger.committedResult(key("m-1"), NOW.plusSeconds(2))) - .contains("{\"orderId\":\"o-1\"}"); - } - - @Test - @DisplayName("a failed attempt may be retried") - void failedAttemptMayBeRetried() { - ledger.claim(key("m-1"), NOW, LEASE); - ledger.recordFailed(key("m-1"), NOW.plusSeconds(1)); - - assertThat(ledger.claim(key("m-1"), NOW.plusSeconds(2), LEASE)) - .isEqualTo(WebSocketCommandOutcome.NEW); - } - - @Test - @DisplayName("a crash between commit and ledger write reports UNKNOWN, never NEW") - void crashWindowReportsUnknown() { - // The state that must not be guessed. Reporting NEW would let the retry re-run work that may - // already be durable; reporting COMMITTED would invent a result. - ledger.claim(key("m-1"), NOW, LEASE); - ledger.abandonClaim(key("m-1")); - - assertThat(ledger.claim(key("m-1"), NOW.plus(LEASE).plusSeconds(1), LEASE)) - .isEqualTo(WebSocketCommandOutcome.UNKNOWN); - assertThat(ledger.unresolved(NOW.plus(LEASE).plusSeconds(1))).containsExactly(key("m-1")); - } - - @Test - @DisplayName("a late failure report never downgrades a committed entry") - void lateFailureDoesNotDowngradeACommit() { - // Otherwise the next attempt runs work that already committed. - ledger.claim(key("m-1"), NOW, LEASE); - ledger.recordCommitted(key("m-1"), "{}", NOW.plusSeconds(1)); - ledger.recordFailed(key("m-1"), NOW.plusSeconds(2)); - - assertThat(ledger.outcome(key("m-1"), NOW.plusSeconds(3))) - .isEqualTo(WebSocketCommandOutcome.COMMITTED); - } - - @Test - @DisplayName("two actors' commands never collide") - void actorsAreIsolated() { - WebSocketCommandKey mallory = - new WebSocketCommandKey( - new WebSocketEndpointName("live-updates"), - WebSocketActorReference.of("mallory", "acme", SALT), - new WebSocketMessageId("m-1")); - - ledger.claim(key("m-1"), NOW, LEASE); - - assertThat(ledger.claim(mallory, NOW, LEASE)).isEqualTo(WebSocketCommandOutcome.NEW); - } - - @Test - @DisplayName("the storage key cannot be forged by a component's own content") - void storageKeyCannotBeForged() { - // Joined on a unit separator, which no component's grammar admits. A printable separator would - // let one component's value forge a boundary and make two different commands share a key. - assertThat(key("m-1").storageKey()).contains("\u001f"); - assertThat(key("m-1").storageKey()).isNotEqualTo(key("m-2").storageKey()); - } - - @Test - @DisplayName("a committed verdict must carry the result to replay") - void committedVerdictNeedsAResult() { - // Otherwise the client is told it succeeded with nothing to show for it. - assertThatThrownBy( - () -> - new CommandReconciliation.Verdict( - CommandReconciliation.State.COMMITTED, java.util.Optional.empty())) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("nothing to show for it"); - } - - @Test - @DisplayName("an indeterminate verdict is a real answer, not a fallback to one of the others") - void indeterminateIsItsOwnAnswer() { - // An operator can act on a command that says it does not know. Nobody can act on one that - // quietly picked. - CommandReconciliation.Verdict verdict = CommandReconciliation.Verdict.indeterminate(); - - assertThat(verdict.state()).isEqualTo(CommandReconciliation.State.INDETERMINATE); - assertThat(verdict.encodedResult()).isEmpty(); - } - - @Test - @DisplayName("reconciliation resolves what the ledger cannot") - void reconciliationResolvesTheCrashWindow() { - ledger.claim(key("m-1"), NOW, LEASE); - ledger.abandonClaim(key("m-1")); - Instant later = NOW.plus(LEASE).plusSeconds(1); - assertThat(ledger.outcome(key("m-1"), later)).isEqualTo(WebSocketCommandOutcome.UNKNOWN); - - // Only the business data can settle it, so the platform asks rather than guesses. - CommandReconciliation reconciliation = - (commandKey, now) -> CommandReconciliation.Verdict.committed("{\"orderId\":\"o-1\"}"); - CommandReconciliation.Verdict verdict = reconciliation.reconcile(key("m-1"), later); - - assertThat(verdict.state()).isEqualTo(CommandReconciliation.State.COMMITTED); - assertThat(verdict.encodedResult()).contains("{\"orderId\":\"o-1\"}"); - } -} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/inbound/FragmentAssemblerTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/inbound/FragmentAssemblerTest.java deleted file mode 100644 index ac7e0b80..00000000 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/inbound/FragmentAssemblerTest.java +++ /dev/null @@ -1,122 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.inbound; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.websocket.budget.WebSocketConnectionBudget; -import java.time.Duration; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * Reassembly, which is the inbound attack surface a WebSocket has and HTTP does not. - * - *

A peer may send a first frame and then continuation frames indefinitely. A naive assembler - * grows a buffer for as long as they keep coming: no frame is oversized, nothing throws, and the - * memory is charged to a connection that looks healthy. - */ -class FragmentAssemblerTest { - - private static final WebSocketConnectionBudget BUDGET = - new WebSocketConnectionBudget( - 64, 256, 8, 100, 1024, Duration.ofHours(4), Duration.ofSeconds(90)); - - private final FragmentAssembler assembler = new FragmentAssembler(BUDGET); - - @Test - @DisplayName("an unfragmented message passes through without buffering") - void unfragmentedMessagePassesThrough() { - assertThat(assembler.accept("hello", true)).contains("hello"); - assertThat(assembler.bufferedLength()).isZero(); - } - - @Test - @DisplayName("fragments are joined in order") - void fragmentsAreJoined() { - assertThat(assembler.accept("he", false)).isEmpty(); - assertThat(assembler.accept("ll", false)).isEmpty(); - assertThat(assembler.accept("o", true)).contains("hello"); - } - - @Test - @DisplayName("an oversized frame is refused") - void oversizedFrameIsRefused() { - assertThatThrownBy(() -> assembler.accept("x".repeat(65), true)) - .isInstanceOf(FragmentAssemblyException.class) - .hasMessageContaining("exceeds 64 bytes"); - } - - @Test - @DisplayName("many ordinary frames adding up are refused") - void accumulatedSizeIsRefused() { - // No individual frame is oversized. This is the shape a frame bound alone does not catch. - assertThatThrownBy( - () -> { - for (int index = 0; index < 8; index++) { - assembler.accept("x".repeat(60), false); - } - }) - .isInstanceOf(FragmentAssemblyException.class) - .hasMessageContaining("reassembled message exceeds"); - } - - @Test - @DisplayName("an endless stream of tiny fragments is refused") - void endlessTinyFragmentsAreRefused() { - // Well inside both size bounds and costing a copy each. This is the bound that is usually - // missing. - assertThatThrownBy( - () -> { - for (int index = 0; index < 20; index++) { - assembler.accept("x", false); - } - }) - .isInstanceOf(FragmentAssemblyException.class) - .hasMessageContaining("costing a copy each"); - } - - @Test - @DisplayName("a refused sequence leaves nothing buffered") - void refusalResetsTheBuffer() { - // Otherwise a peer that repeatedly fails assembly still occupies memory between attempts. - try { - for (int index = 0; index < 20; index++) { - assembler.accept("x", false); - } - } catch (FragmentAssemblyException expected) { - // the bound fired, which is the point - } - - assertThat(assembler.assembling()).isFalse(); - assertThat(assembler.bufferedLength()).isZero(); - } - - @Test - @DisplayName("a reset releases the grown buffer, not just its contents") - void resetReleasesCapacity() { - // StringBuilder keeps its capacity. A connection that once received a large message would hold - // that array for the rest of its life — hours, for a connection that never sends again. - assembler.accept("x".repeat(60), false); - assembler.accept("x".repeat(60), true); - - assembler.reset(); - - assertThat(assembler.bufferedLength()).isZero(); - assertThat(assembler.assembling()).isFalse(); - } - - @Test - @DisplayName("the assembler is per connection") - void assemblerIsPerConnection() { - // A shared one interleaves two peers' fragments into one message, which is both a corruption - // and a disclosure. - FragmentAssembler alice = new FragmentAssembler(BUDGET); - FragmentAssembler bob = new FragmentAssembler(BUDGET); - - alice.accept("alice", false); - bob.accept("bob", false); - - assertThat(alice.accept("-done", true)).contains("alice-done"); - assertThat(bob.accept("-done", true)).contains("bob-done"); - } -} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/lifecycle/ConnectionLifecycleTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/lifecycle/ConnectionLifecycleTest.java deleted file mode 100644 index 01b95ffe..00000000 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/lifecycle/ConnectionLifecycleTest.java +++ /dev/null @@ -1,168 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.lifecycle; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketActorReference; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketConnectionContext; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketConnectionId; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketConnectionState; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketCredentialExpiry; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketEndpointName; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketNodeId; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketSessionId; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketSubprotocolName; -import dev.caskeleton.adapter.inbound.websocket.error.WebSocketCloseCode; -import java.nio.charset.StandardCharsets; -import java.time.Duration; -import java.time.Instant; -import java.util.Optional; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * Liveness and shutdown, the two places a long-lived connection costs more than a request. - * - *

TCP does not report a departed peer. A closed laptop lid, a phone switching to cellular, a NAT - * forgetting its mapping — none produce a FIN, and the connection keeps its buffers, its registry - * entry and its subscriptions until something checks. - */ -class ConnectionLifecycleTest { - - private static final Instant NOW = Instant.parse("2026-08-25T10:00:00Z"); - private static final byte[] SALT = - "a-deployment-salt-of-adequate-length".getBytes(StandardCharsets.UTF_8); - - @Test - @DisplayName("the standard heartbeat tolerates a dropped ping") - void standardHeartbeatToleratesADroppedPing() { - // A timeout below two intervals closes a healthy connection on one dropped ping, and the - // reconnect storm makes the congestion that dropped it worse. - HeartbeatPolicy policy = HeartbeatPolicy.standard(); - - assertThat(policy.toleratedMissedPings()).isGreaterThanOrEqualTo(2); - } - - @Test - @DisplayName("a timeout under two ping intervals is refused") - void tooTightTimeoutIsRefused() { - assertThatThrownBy(() -> new HeartbeatPolicy(Duration.ofSeconds(15), Duration.ofSeconds(20))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("one dropped ping"); - } - - @Test - @DisplayName("a ping slower than common intermediaries is refused") - void tooSlowPingIsRefused() { - // Intermediaries commonly drop an idle connection at 30-60s and say nothing. A slower ping - // lets the liveness check be the thing that never notices. - assertThatThrownBy(() -> new HeartbeatPolicy(Duration.ofSeconds(60), Duration.ofSeconds(180))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("before the server checks"); - } - - @Test - @DisplayName("a ping falls due and silence eventually expires") - void pingAndIdleFire() { - HeartbeatPolicy policy = HeartbeatPolicy.standard(); - - assertThat(policy.pingDue(NOW, NOW.plusSeconds(5))).isFalse(); - assertThat(policy.pingDue(NOW, NOW.plusSeconds(15))).isTrue(); - assertThat(policy.idleExpired(NOW, NOW.plusSeconds(30))).isFalse(); - assertThat(policy.idleExpired(NOW, NOW.plusSeconds(45))).isTrue(); - } - - @Test - @DisplayName("a shutdown closes with going-away, not normal") - void shutdownUsesGoingAway() { - // A client told "going away" reconnects. One told "normal" may reasonably conclude the session - // is over and never come back. - assertThat(CloseOrchestration.codeFor(CloseOrchestration.CloseReason.NODE_SHUTTING_DOWN)) - .isEqualTo(WebSocketCloseCode.GOING_AWAY); - assertThat(CloseOrchestration.codeFor(CloseOrchestration.CloseReason.CLIENT_REQUESTED)) - .isEqualTo(WebSocketCloseCode.NORMAL); - } - - @Test - @DisplayName("closing stops inbound before anything else") - void closingStopsInboundFirst() { - WebSocketConnectionContext open = context(WebSocketConnectionState.OPEN); - - assertThat( - CloseOrchestration.nextStep(open, 0, Optional.empty(), false, NOW, NOW.plusSeconds(10))) - .isEqualTo(CloseOrchestration.Step.STOP_ACCEPTING_INBOUND); - } - - @Test - @DisplayName("a draining connection finishes what is queued before the close frame") - void drainingFlushesFirst() { - WebSocketConnectionContext draining = context(WebSocketConnectionState.DRAINING); - - assertThat( - CloseOrchestration.nextStep( - draining, 3, Optional.empty(), false, NOW, NOW.plusSeconds(10))) - .isEqualTo(CloseOrchestration.Step.FLUSH_PENDING); - } - - @Test - @DisplayName("the drain is bounded, so a stopped reader cannot hold the deploy") - void drainIsBounded() { - WebSocketConnectionContext draining = context(WebSocketConnectionState.DRAINING); - - assertThat( - CloseOrchestration.nextStep( - draining, 3, Optional.empty(), false, NOW.plusSeconds(11), NOW.plusSeconds(10))) - .isEqualTo(CloseOrchestration.Step.SEND_CLOSE_FRAME); - } - - @Test - @DisplayName("the close handshake is awaited briefly and then abandoned") - void closeHandshakeIsBounded() { - // Skipping straight to teardown gives the client a 1006 — "closed abnormally, no reason" — - // which is indistinguishable from a network failure and triggers its most aggressive reconnect - // path during a fleet restart. Waiting for ever is how a shutdown hangs. - WebSocketConnectionContext draining = context(WebSocketConnectionState.DRAINING); - Instant sentAt = NOW; - - assertThat( - CloseOrchestration.nextStep( - draining, 0, Optional.of(sentAt), false, NOW.plusSeconds(1), NOW.plusSeconds(10))) - .isEqualTo(CloseOrchestration.Step.AWAIT_PEER_CLOSE); - assertThat( - CloseOrchestration.nextStep( - draining, 0, Optional.of(sentAt), false, NOW.plusSeconds(30), NOW.plusSeconds(10))) - .isEqualTo(CloseOrchestration.Step.TEAR_DOWN); - } - - @Test - @DisplayName("the peer answering ends the handshake immediately") - void peerCloseEndsTheHandshake() { - WebSocketConnectionContext draining = context(WebSocketConnectionState.DRAINING); - - assertThat( - CloseOrchestration.nextStep( - draining, 0, Optional.of(NOW), true, NOW.plusSeconds(1), NOW.plusSeconds(10))) - .isEqualTo(CloseOrchestration.Step.TEAR_DOWN); - } - - @Test - @DisplayName("every close reason maps to a code") - void everyReasonHasACode() { - for (CloseOrchestration.CloseReason reason : CloseOrchestration.CloseReason.values()) { - assertThat(CloseOrchestration.codeFor(reason)).isNotNull(); - } - } - - private static WebSocketConnectionContext context(WebSocketConnectionState state) { - return new WebSocketConnectionContext( - new WebSocketConnectionId("c-01H8XQ2N4K"), - new WebSocketSessionId("s-01H8XQ2N4K"), - new WebSocketNodeId("edge-1"), - new WebSocketEndpointName("live-updates"), - Optional.of(WebSocketSubprotocolName.stable()), - WebSocketActorReference.of("alice", "acme", SALT), - state, - WebSocketCredentialExpiry.never(), - NOW); - } -} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/moduleboundary/WebSocketBuildModel.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/moduleboundary/WebSocketBuildModel.java deleted file mode 100644 index 41feab0d..00000000 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/moduleboundary/WebSocketBuildModel.java +++ /dev/null @@ -1,264 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.moduleboundary; - -import java.io.IOException; -import java.io.UncheckedIOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.TreeMap; -import java.util.TreeSet; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.stream.Stream; - -/** - * Reads a web platform source tree and reports where it disagrees with the declared module map. - * - *

This deliberately works on source text rather than on compiled classes. An import that a - * boundary forbids has usually been erased by the compiler — a constant is inlined, a type is only - * named in a signature that is not retained — so a bytecode scan would report a boundary as clean - * while the source a reviewer reads still crosses it. - * - *

It lives in the test source set on purpose. Scanning a checkout is build-time work: a running - * application has no source tree to scan, and a runtime scan would fail exactly in the packaged - * environments where nothing is wrong. - * - *

Every entry point refuses to report success on an empty scan. A boundary rule that passes - * because it found no files is the failure mode this whole model exists to prevent. - */ -public final class WebSocketBuildModel { - - /** - * Import prefixes that make a module framework bound. - * - *

The design's constraint names Servlet, Spring MVC, Spring WebFlux and Reactor. The set here - * is wider on purpose: {@code jakarta} covers servlet and validation, {@code com.fasterxml} - * covers Jackson, {@code io.micrometer} covers observation. Each binds a module to a runtime just - * as firmly as Spring does. Repository-owned {@code dev.caskeleton.application} and {@code - * dev.caskeleton.domain} contracts are intentionally absent: CORE means framework-free, not - * "forbidden from depending on application ports". - */ - public static final Pattern FRAMEWORK_IMPORT = - Pattern.compile( - // `tools.jackson` is Jackson 3 and `com.fasterxml` is Jackson 2. Both are listed because - // this repository runs on Spring 7, whose message converters take Jackson 3 — so a CORE - // module could have imported a mapper without this detector noticing, which is a hole in - // exactly the check that is supposed to have none. - "^(org\\.springframework|jakarta|reactor|io\\.micrometer|com\\.fasterxml" - + "|tools\\.jackson|org\\.slf4j|io\\.swagger)\\."); - - private static final Pattern IMPORT_STATEMENT = - Pattern.compile("^\\s*import\\s+(?:static\\s+)?([\\w.]+)\\s*;", Pattern.MULTILINE); - - private static final Pattern PACKAGE_STATEMENT = - Pattern.compile("^\\s*package\\s+([\\w.]+)\\s*;", Pattern.MULTILINE); - - private WebSocketBuildModel() {} - - /** Scans every source root the platform's module map governs. */ - public static WebSocketSourceGraph scanPlatformSources() { - return scan(platformSourceRoots()); - } - - /** - * Scans a Java source root — the directory that directly contains the {@code dev} package folder. - * - * @throws IllegalStateException when the root holds no platform source at all - */ - public static WebSocketSourceGraph scan(Path sourceRoot) { - return scan(List.of(sourceRoot)); - } - - /** - * Scans several Java source roots as one platform. - * - * @throws IllegalStateException when the roots hold no platform source at all - */ - public static WebSocketSourceGraph scan(List sourceRoots) { - Map> edges = new TreeMap<>(); - Map> frameworkImports = new TreeMap<>(); - Set packages = new TreeSet<>(); - int fileCount = 0; - - List files = new ArrayList<>(); - for (Path sourceRoot : sourceRoots) { - files.addAll(javaFilesUnder(sourceRoot)); - } - for (Path file : files) { - String source = read(file); - String packageName = declaredPackage(source).orElse(null); - if (packageName == null || !WebSocketModuleBoundary.insidePlatform(packageName)) { - continue; - } - fileCount++; - packages.add(packageName); - String moduleId = WebSocketModuleBoundary.moduleIdForPackage(packageName).orElse(null); - if (moduleId == null) { - // An unregistered package still has to appear in `packages` so the rule can name it, but it - // owns no module identity and therefore contributes no edges. - continue; - } - edges.computeIfAbsent(moduleId, key -> new TreeSet<>()); - frameworkImports.computeIfAbsent(moduleId, key -> new TreeSet<>()); - - Matcher matcher = IMPORT_STATEMENT.matcher(source); - while (matcher.find()) { - String imported = matcher.group(1); - if (WebSocketModuleBoundary.insidePlatform(imported)) { - importedModule(imported) - .filter(target -> !target.equals(moduleId)) - .ifPresent(target -> edges.get(moduleId).add(target)); - } else if (FRAMEWORK_IMPORT.matcher(imported).find()) { - frameworkImports.get(moduleId).add(imported); - } - } - } - - if (fileCount == 0) { - throw new IllegalStateException( - "no web platform source was found under " - + sourceRoots.stream().map(root -> root.toAbsolutePath().toString()).toList() - + "; a boundary rule must never pass by scanning nothing"); - } - return new WebSocketSourceGraph(edges, frameworkImports, packages, fileCount); - } - - /** Packages that hold source but were never given a module identity. */ - public static List undeclaredPackages(WebSocketSourceGraph graph) { - return graph.packages().stream() - .filter(packageName -> WebSocketModuleBoundary.moduleIdForPackage(packageName).isEmpty()) - .sorted() - .toList(); - } - - /** Declared modules whose package holds no source, so the declaration describes nothing. */ - public static List declaredButAbsentModules(WebSocketSourceGraph graph) { - List absent = new ArrayList<>(); - WebSocketModuleBoundary.packagesById() - .forEach( - (moduleId, packageName) -> { - boolean present = - graph.packages().stream() - .anyMatch( - scanned -> - scanned.equals(packageName) || scanned.startsWith(packageName + ".")); - if (!present) { - absent.add(moduleId + " (" + packageName + ")"); - } - }); - absent.sort(String::compareTo); - return List.copyOf(absent); - } - - /** Imports that cross a module boundary the declaration does not allow. */ - public static List undeclaredEdges(WebSocketSourceGraph graph) { - List violations = new ArrayList<>(); - graph - .moduleEdges() - .forEach( - (from, targets) -> - targets.stream() - .filter(to -> !WebSocketModuleBoundary.edgeAllowed(from, to)) - .forEach(to -> violations.add(from + " -> " + to))); - violations.sort(String::compareTo); - return List.copyOf(violations); - } - - /** Framework imports found in modules declared {@link WebSocketModulePurity#CORE}. */ - public static List frameworkImportsInCoreModules(WebSocketSourceGraph graph) { - Set core = WebSocketModuleBoundary.coreModuleIds(); - List violations = new ArrayList<>(); - graph - .frameworkImports() - .forEach( - (moduleId, imports) -> { - if (!core.contains(moduleId)) { - return; - } - imports.forEach(imported -> violations.add(moduleId + " imports " + imported)); - }); - violations.sort(String::compareTo); - return List.copyOf(violations); - } - - /** Every source root the module map governs. */ - public static List platformSourceRoots() { - return List.of(mainSourceRoot()); - } - - /** - * Locates this leaf's production source root. - * - * @throws IllegalStateException when it cannot be found, rather than returning a path that would - * scan to zero files - */ - public static Path mainSourceRoot() { - String packagePath = WebSocketModuleBoundary.PACKAGE_ROOT.replace('.', '/'); - for (Path directory = Path.of("").toAbsolutePath(); - directory != null; - directory = directory.getParent()) { - Path candidate = directory.resolve("src").resolve("main").resolve("java"); - if (Files.isDirectory(candidate.resolve(packagePath))) { - return candidate; - } - } - throw new IllegalStateException( - "cannot locate src/main/java/" - + packagePath - + " from " - + Path.of("").toAbsolutePath() - + "; the module boundary rules have nothing to check"); - } - - private static Optional importedModule(String importedType) { - int lastDot = importedType.lastIndexOf('.'); - if (lastDot < 0) { - return Optional.empty(); - } - // A static import names a member, so peel qualifiers until one resolves to a declared module. - for (String candidate = importedType.substring(0, lastDot); - candidate.length() >= WebSocketModuleBoundary.PACKAGE_ROOT.length(); - candidate = candidate.substring(0, Math.max(candidate.lastIndexOf('.'), 0))) { - Optional moduleId = WebSocketModuleBoundary.moduleIdForPackage(candidate); - if (moduleId.isPresent()) { - return moduleId; - } - if (candidate.lastIndexOf('.') < 0) { - break; - } - } - return Optional.empty(); - } - - private static Optional declaredPackage(String source) { - Matcher matcher = PACKAGE_STATEMENT.matcher(source); - return matcher.find() ? Optional.of(matcher.group(1)) : Optional.empty(); - } - - private static List javaFilesUnder(Path root) { - if (!Files.isDirectory(root)) { - throw new IllegalStateException("source root does not exist: " + root.toAbsolutePath()); - } - try (Stream files = Files.walk(root)) { - return files - .filter(Files::isRegularFile) - .filter(path -> path.getFileName().toString().endsWith(".java")) - .sorted() - .toList(); - } catch (IOException ex) { - throw new UncheckedIOException(ex); - } - } - - private static String read(Path file) { - try { - return Files.readString(file); - } catch (IOException ex) { - throw new UncheckedIOException(ex); - } - } -} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/moduleboundary/WebSocketModuleBoundaryTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/moduleboundary/WebSocketModuleBoundaryTest.java deleted file mode 100644 index fb9be7a0..00000000 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/moduleboundary/WebSocketModuleBoundaryTest.java +++ /dev/null @@ -1,147 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.moduleboundary; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.io.IOException; -import java.io.UncheckedIOException; -import java.nio.file.Files; -import java.nio.file.Path; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -/** - * The declared module map has to match the source tree, in both directions. - * - *

This is what makes the eighteen-modules-as-packages adaptation honest rather than a claim. A - * design module boundary that only exists in a document is a boundary the first refactor walks - * through; scanned and enforced, promoting a package to its own Gradle leaf later is a registry - * edit rather than an archaeology exercise. - * - *

The negative cases run against a temporary tree. Asserting only that the real tree is clean - * would leave the detector itself untested, and a detector that finds nothing looks identical to a - * codebase with nothing to find. - */ -class WebSocketModuleBoundaryTest { - - private static final String ROOT = WebSocketModuleBoundary.PACKAGE_ROOT; - - private static WebSocketSourceGraph production; - - @BeforeAll - static void scanProductionTree() { - production = WebSocketBuildModel.scanPlatformSources(); - } - - @Test - @DisplayName("the scan actually reads the production tree") - void theScanActuallyReadsTheProductionTree() { - // A scan pointed at the wrong directory finds nothing and reports every boundary as clean. - assertThat(production.fileCount()).isGreaterThan(5); - assertThat(production.packages()).contains(ROOT + ".moduleboundary"); - } - - @Test - @DisplayName("every production package has a declared module identity") - void everyProductionPackageHasADeclaredModuleIdentity() { - assertThat(WebSocketBuildModel.undeclaredPackages(production)) - .as("add the package to WebSocketStableModule before shipping it") - .isEmpty(); - } - - @Test - @DisplayName("every cross-module import is a declared edge") - void everyCrossModuleImportIsADeclaredEdge() { - assertThat(WebSocketBuildModel.undeclaredEdges(production)).isEmpty(); - } - - @Test - @DisplayName("core modules stay framework free") - void coreModulesStayFrameworkFree() { - // The strictest rule in this platform. A CORE module that could name a WebSocketSession would - // make the same decision untestable without a running container and unportable between the - // two runtimes. - assertThat(WebSocketBuildModel.frameworkImportsInCoreModules(production)).isEmpty(); - } - - @Test - @DisplayName("the servlet and reactive runtimes declare no edge to each other") - void theTwoRuntimesAreMutuallyExclusive() { - // The absent edge is the load-bearing one. With it, the reactive runtime compiles against a - // servlet session type, and a deployment ends up shipping both stacks and starting neither. - assertThat(WebSocketStableModule.SERVLET.allowedEdges()).doesNotContain("webflux"); - assertThat(WebSocketStableModule.WEBFLUX.allowedEdges()).doesNotContain("servlet"); - } - - @Test - @DisplayName("an undeclared cross-module import is rejected") - void anUndeclaredCrossModuleImportIsRejected(@TempDir Path tree) { - writeType(tree, ROOT + ".ordering", "LeakySequence", ROOT + ".security.ConnectionTicket"); - - assertThat(WebSocketBuildModel.undeclaredEdges(WebSocketBuildModel.scan(tree))) - .containsExactly("ordering -> security"); - } - - @Test - @DisplayName("a framework import in a core module is rejected") - void aFrameworkImportInACoreModuleIsRejected(@TempDir Path tree) { - writeType( - tree, ROOT + ".protocol", "LeakyEnvelope", "org.springframework.stereotype.Component"); - - assertThat(WebSocketBuildModel.frameworkImportsInCoreModules(WebSocketBuildModel.scan(tree))) - .containsExactly("protocol imports org.springframework.stereotype.Component"); - } - - @Test - @DisplayName("a transport session type in a core module is rejected") - void aTransportSessionInACoreModuleIsRejected(@TempDir Path tree) { - // The specific leak this platform is most exposed to: a long-lived connection makes reaching - // for the container's own session type tempting from everywhere. - writeType( - tree, - ROOT + ".session", - "LeakyRegistry", - "org.springframework.web.socket.WebSocketSession"); - - assertThat(WebSocketBuildModel.frameworkImportsInCoreModules(WebSocketBuildModel.scan(tree))) - .containsExactly("session imports org.springframework.web.socket.WebSocketSession"); - } - - @Test - @DisplayName("no two modules claim the same package") - void packagesAreClaimedOnce() { - // Two ids on one package makes ownership depend on iteration order, so an edge check silently - // consults whichever declaration won — and the other module's rules apply to nothing. It - // happened once while adding a module and nothing else noticed. - assertThat(WebSocketStableModule.packagesById().values()).doesNotHaveDuplicates(); - } - - @Test - @DisplayName("a package with no declared identity is rejected") - void aPackageWithNoDeclaredIdentityIsRejected(@TempDir Path tree) { - writeType(tree, ROOT + ".undeclared", "Stowaway", null); - - assertThat(WebSocketBuildModel.undeclaredPackages(WebSocketBuildModel.scan(tree))) - .containsExactly(ROOT + ".undeclared"); - } - - private static void writeType( - Path sourceRoot, String packageName, String typeName, String importedType) { - Path directory = sourceRoot.resolve(packageName.replace('.', '/')); - try { - Files.createDirectories(directory); - Files.writeString( - directory.resolve(typeName + ".java"), - "package " - + packageName - + ";\n\n" - + (importedType == null ? "" : "import " + importedType + ";\n\n") - + "final class " - + typeName - + " {}\n"); - } catch (IOException e) { - throw new UncheckedIOException(e); - } - } -} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/moduleboundary/WebSocketSourceGraph.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/moduleboundary/WebSocketSourceGraph.java deleted file mode 100644 index 7ddc9088..00000000 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/moduleboundary/WebSocketSourceGraph.java +++ /dev/null @@ -1,30 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.moduleboundary; - -import java.util.Map; -import java.util.Set; - -/** - * What a scan of a web platform source tree actually found. - * - *

Everything here is observed, never declared: {@link WebSocketStableModule} says what the - * module map is supposed to be, and this record says what the checkout is. The boundary rules are - * the comparison between the two. - * - * @param moduleEdges module identifier to the module identifiers it imports, self-edges excluded - * @param frameworkImports module identifier to the framework imports it uses, empty when pure - * @param packages every package that contained at least one Java file - * @param fileCount how many Java files were read, so a rule can refuse to pass on an empty scan - */ -public record WebSocketSourceGraph( - Map> moduleEdges, - Map> frameworkImports, - Set packages, - int fileCount) { - - /** Canonicalises the collections so callers cannot mutate a scan result. */ - public WebSocketSourceGraph { - moduleEdges = Map.copyOf(moduleEdges); - frameworkImports = Map.copyOf(frameworkImports); - packages = Set.copyOf(packages); - } -} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/observability/WebSocketObservabilityTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/observability/WebSocketObservabilityTest.java deleted file mode 100644 index 7f6040c2..00000000 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/observability/WebSocketObservabilityTest.java +++ /dev/null @@ -1,97 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.observability; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketActorReference; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketConnectionContext; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketConnectionId; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketConnectionState; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketCredentialExpiry; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketEndpointName; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketNodeId; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketSessionId; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketSubprotocolName; -import java.nio.charset.StandardCharsets; -import java.time.Instant; -import java.util.Map; -import java.util.Optional; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * Telemetry for something that lives for hours rather than milliseconds. - * - *

Both failure modes are worse here than for a request. A high-cardinality tag creates series - * that outlive the connections and never stop accumulating; a sensitive log field is written on - * every message for hours rather than once. - */ -class WebSocketObservabilityTest { - - private static final byte[] SALT = - "a-deployment-salt-of-adequate-length".getBytes(StandardCharsets.UTF_8); - - @Test - @DisplayName("the connection identifier is not a metric tag") - void connectionIdIsNotATag() { - // One series per connection that ever existed, and the series outlive the connections. - assertThat(WebSocketMetricTags.allowed("connectionId")).isFalse(); - assertThat(WebSocketMetricTags.allowed("sessionId")).isFalse(); - assertThat(WebSocketMetricTags.allowed("actor")).isFalse(); - } - - @Test - @DisplayName("the node identifier is a tag, because a fleet has a knowable number of nodes") - void nodeIdIsATag() { - assertThat(WebSocketMetricTags.allowed("nodeId")).isTrue(); - assertThat(WebSocketMetricTags.allowed("endpoint")).isTrue(); - assertThat(WebSocketMetricTags.allowed("closeCode")).isTrue(); - } - - @Test - @DisplayName("a forbidden tag is refused where it is recorded") - void forbiddenTagIsRefused() { - assertThatThrownBy(() -> WebSocketMetricTags.require("correlationId")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("never stop accumulating"); - } - - @Test - @DisplayName("connection log fields carry no payload and no raw identity") - void logFieldsCarryNoPayloadOrIdentity() { - Map fields = SafeWebSocketLogFields.of(context()); - - assertThat(fields).containsKeys("connectionId", "endpoint", "nodeId", "state", "actor"); - assertThat(fields).doesNotContainKey("payload"); - // The actor is the short fingerprint: enough to correlate while reading, not enough to name. - assertThat(fields.get("actor")).hasSize(12); - assertThat(fields.values()).noneMatch(value -> value.contains("alice")); - } - - @Test - @DisplayName("a payload field is never safe to log, at any level") - void payloadIsNeverSafeToLog() { - // A payload log behind a debug flag is a payload log the first time somebody debugs a - // production incident — exactly when the data is most sensitive and the flag most likely to - // be left on. - assertThat(SafeWebSocketLogFields.safeFieldName("payload")).isFalse(); - assertThat(SafeWebSocketLogFields.safeFieldName("messageBody")).isFalse(); - assertThat(SafeWebSocketLogFields.safeFieldName("ticket")).isFalse(); - assertThat(SafeWebSocketLogFields.safeFieldName("authorization")).isFalse(); - assertThat(SafeWebSocketLogFields.safeFieldName("endpoint")).isTrue(); - } - - private static WebSocketConnectionContext context() { - Instant now = Instant.parse("2026-08-25T10:00:00Z"); - return new WebSocketConnectionContext( - new WebSocketConnectionId("c-01H8XQ2N4K"), - new WebSocketSessionId("s-01H8XQ2N4K"), - new WebSocketNodeId("edge-1"), - new WebSocketEndpointName("live-updates"), - Optional.of(WebSocketSubprotocolName.stable()), - WebSocketActorReference.of("alice", "acme", SALT), - WebSocketConnectionState.OPEN, - WebSocketCredentialExpiry.never(), - now); - } -} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/ordering/StreamOrderingTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/ordering/StreamOrderingTest.java deleted file mode 100644 index f0b0705a..00000000 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/ordering/StreamOrderingTest.java +++ /dev/null @@ -1,108 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.ordering; - -import static org.assertj.core.api.Assertions.assertThat; - -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * Ordering, which a WebSocket makes look free and is not. - * - *

Frames on one connection arrive in order, so total order looks like a property of the - * transport. It is not: a reconnect starts a new connection, and anything produced concurrently was - * never ordered. A client that assumed otherwise is wrong exactly when it reconnects. - */ -class StreamOrderingTest { - - private final StreamSequencer sequencer = new StreamSequencer(); - private final GapDetector detector = new GapDetector(); - - @Test - @DisplayName("sequences start at 1, not 0") - void sequencesStartAtOne() { - // Zero is what an uninitialised field holds, so starting there makes "never sent anything" and - // "sent the first message" the same observation on the client. - assertThat(sequencer.current("orders")).isZero(); - assertThat(sequencer.next("orders")).isOne(); - } - - @Test - @DisplayName("each stream has its own counter") - void countersArePerStream() { - // Per stream because the number is what a client resumes from. A connection-scoped counter - // restarts at zero on the new connection, and "resume from 4210" then means nothing. - sequencer.next("orders"); - sequencer.next("orders"); - - assertThat(sequencer.next("prices")).isOne(); - assertThat(sequencer.next("orders")).isEqualTo(3); - } - - @Test - @DisplayName("a forgotten stream does not keep its counter") - void forgettingReleasesTheCounter() { - // Otherwise the map grows with the number of streams that ever existed rather than with the - // number in use. - sequencer.next("orders"); - sequencer.forget("orders"); - - assertThat(sequencer.trackedStreams()).isZero(); - } - - @Test - @DisplayName("consecutive positions are in order") - void consecutivePositionsAreInOrder() { - assertThat(detector.observe("orders", 1)).isEqualTo(GapDetector.Observation.IN_ORDER); - assertThat(detector.observe("orders", 2)).isEqualTo(GapDetector.Observation.IN_ORDER); - } - - @Test - @DisplayName("a skipped position is a gap, with a size") - void skippedPositionIsAGap() { - detector.observe("orders", 1); - - assertThat(detector.gapSize("orders", 5)).isEqualTo(3); - assertThat(detector.observe("orders", 5)).isEqualTo(GapDetector.Observation.GAP); - } - - @Test - @DisplayName("a repeat and a reorder are distinguished") - void repeatAndReorderAreDistinct() { - // They mean different things: a duplicate is a retry that was not deduplicated, a reorder is - // something writing out of order, which no profile permits. - detector.observe("orders", 5); - - assertThat(detector.observe("orders", 5)).isEqualTo(GapDetector.Observation.DUPLICATE); - assertThat(detector.observe("orders", 3)).isEqualTo(GapDetector.Observation.REORDERED); - } - - @Test - @DisplayName("a reorder does not lower the high-water mark") - void reorderKeepsTheHighWaterMark() { - // Lowering it would report every subsequent in-order message as a duplicate. - detector.observe("orders", 5); - detector.observe("orders", 3); - - assertThat(detector.lastSeen("orders")).isEqualTo(5); - assertThat(detector.observe("orders", 6)).isEqualTo(GapDetector.Observation.IN_ORDER); - } - - @Test - @DisplayName("gaps are errors only where total order was promised") - void gapsMeanDifferentThingsPerProfile() { - // The reason the profile is declared: under a lossy profile a gap is expected, and a client - // that resynchronised on every one would never stop. - assertThat(OrderingProfile.PER_STREAM_TOTAL.gapsAreErrors()).isTrue(); - assertThat(OrderingProfile.MONOTONIC_LOSSY.gapsAreErrors()).isFalse(); - assertThat(OrderingProfile.BEST_EFFORT.gapsAreErrors()).isFalse(); - } - - @Test - @DisplayName("a conflated stream is monotonic without being complete") - void conflatedStreamIsMonotonicLossy() { - // Without this profile a conflated stream must claim total order — which conflation breaks — - // or best effort, which understates what it gives. - assertThat(OrderingProfile.MONOTONIC_LOSSY.monotonic()).isTrue(); - assertThat(OrderingProfile.BEST_EFFORT.monotonic()).isFalse(); - } -} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/outbound/OutboundQueueSnapshotTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/outbound/OutboundQueueSnapshotTest.java index d5e466ba..cee5263e 100644 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/outbound/OutboundQueueSnapshotTest.java +++ b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/outbound/OutboundQueueSnapshotTest.java @@ -5,7 +5,6 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import dev.caskeleton.adapter.inbound.websocket.budget.WebSocketConnectionBudget; import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageId; -import java.time.Duration; import java.util.Optional; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -21,8 +20,7 @@ import org.junit.jupiter.api.Test; class OutboundQueueSnapshotTest { private static final WebSocketConnectionBudget BUDGET = - new WebSocketConnectionBudget( - 64 * 1024, 512 * 1024, 16, 100, 1024, Duration.ofHours(4), Duration.ofSeconds(90)); + new WebSocketConnectionBudget(512 * 1024, 1024); private final OutboundQueue queue = new OutboundQueue(BUDGET, 2, new GlobalBufferBudget(1_000_000)); diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/outbound/OutboundQueueTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/outbound/OutboundQueueTest.java index 11cd7c3a..e88640ff 100644 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/outbound/OutboundQueueTest.java +++ b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/outbound/OutboundQueueTest.java @@ -2,10 +2,10 @@ package dev.caskeleton.adapter.inbound.websocket.outbound; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.tuple; import dev.caskeleton.adapter.inbound.websocket.budget.WebSocketConnectionBudget; import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageId; -import java.time.Duration; import java.util.Optional; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -20,8 +20,7 @@ import org.junit.jupiter.api.Test; class OutboundQueueTest { private static final WebSocketConnectionBudget BUDGET = - new WebSocketConnectionBudget( - 64 * 1024, 512 * 1024, 16, 100, 1024, Duration.ofHours(4), Duration.ofSeconds(90)); + new WebSocketConnectionBudget(512 * 1024, 1024); private final GlobalBufferBudget global = new GlobalBufferBudget(4096); private final OutboundQueue queue = new OutboundQueue(BUDGET, 4, global); @@ -127,6 +126,19 @@ class OutboundQueueTest { assertThat(queue.bufferedBytes()).isEqualTo(50); } + @Test + void conflationThatDoesNotFitTheConnectionBoundIsReportedAsDropped() { + // given + queue.offer(conflatable("m-1", "x", "AAPL")); + + // when + OutboundEnqueueResult result = queue.offer(conflatable("m-2", "x".repeat(2000), "AAPL")); + + // then + assertThat(tuple(result, queue.snapshot())) + .isEqualTo(tuple(OutboundEnqueueResult.DROPPED, new OutboundQueueSnapshot(0, 0, 1, false))); + } + @Test @DisplayName("a byte bound refuses what a count bound admits") void byteBoundIsSeparateFromCountBound() { diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/outbound/SerializedOutboundWriterTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/outbound/SerializedOutboundWriterTest.java index 5bd0c9f6..f4f53379 100644 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/outbound/SerializedOutboundWriterTest.java +++ b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/outbound/SerializedOutboundWriterTest.java @@ -5,7 +5,6 @@ import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.adapter.inbound.websocket.budget.WebSocketConnectionBudget; import dev.caskeleton.adapter.inbound.websocket.core.WebSocketConnectionId; import dev.caskeleton.adapter.inbound.websocket.protocol.WebSocketMessageId; -import java.time.Duration; import java.util.List; import java.util.Optional; import java.util.concurrent.CopyOnWriteArrayList; @@ -29,8 +28,7 @@ import org.junit.jupiter.api.Test; class SerializedOutboundWriterTest { private static final WebSocketConnectionBudget BUDGET = - new WebSocketConnectionBudget( - 64 * 1024, 512 * 1024, 16, 100, 64 * 1024, Duration.ofHours(4), Duration.ofSeconds(90)); + new WebSocketConnectionBudget(512 * 1024, 64 * 1024); private final GlobalBufferBudget global = new GlobalBufferBudget(1024 * 1024); @@ -80,7 +78,6 @@ class SerializedOutboundWriterTest { future.get(60, TimeUnit.SECONDS); } } - writer.drain(); assertThat(maxConcurrent).hasValue(1); assertThat(writer.written()).isEqualTo(64); @@ -90,7 +87,8 @@ class SerializedOutboundWriterTest { @DisplayName("nothing is stranded when a caller finds the writer busy") void nothingIsStrandedWhenBusy() throws Exception { // tryLock returns immediately rather than blocking, so the queued message has to be picked up - // by whoever is already writing. If it were not, a message would sit in the queue for ever. + // by whoever is already writing. No manual drain() afterwards: that would hide a message + // queued between the holder's last poll and its unlock. List written = new CopyOnWriteArrayList<>(); OutboundQueue queue = new OutboundQueue(BUDGET, 1000, global); SerializedOutboundWriter writer = @@ -107,7 +105,6 @@ class SerializedOutboundWriterTest { future.get(30, TimeUnit.SECONDS); } } - writer.drain(); assertThat(written).hasSize(40); assertThat(queue.size()).isZero(); diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/protocol/WebSocketEnvelopeTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/protocol/WebSocketEnvelopeTest.java deleted file mode 100644 index 6beca1ae..00000000 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/protocol/WebSocketEnvelopeTest.java +++ /dev/null @@ -1,186 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.protocol; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.time.Instant; -import java.util.Optional; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * The envelope's rules, each of which prevents one specific wrong behaviour downstream. - * - *

A connection multiplexes many in-flight messages of different kinds. Without per-family field - * rules, every optional field is optional on every message and the receiver has to guess which ones - * mean anything — which is how a response gets routed to the wrong waiter and a gap alarm fires for - * a stream nobody ordered. - */ -class WebSocketEnvelopeTest { - - private static final Instant NOW = Instant.parse("2026-08-25T10:00:00Z"); - private static final WebSocketMessageId ID = new WebSocketMessageId("m-1"); - private static final WebSocketMessageType TYPE = new WebSocketMessageType("order.place.v1"); - - @Test - @DisplayName("a message type is a published name, never a Java class name") - void messageTypeIsNotAClassName() { - // A class name on the wire publishes the package layout, breaks every client on a rename, and - // makes the receiver's type resolution an attack surface. - assertThatThrownBy( - () -> new WebSocketMessageType("dev.caskeleton.domain.order.PlaceOrderCommand")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("attack surface"); - assertThatThrownBy(() -> new WebSocketMessageType("java.util.HashMap")) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("a message type carries its version") - void messageTypeIsVersioned() { - assertThat(TYPE.version()).isOne(); - assertThat(TYPE.unversionedName()).isEqualTo("order.place"); - assertThatThrownBy(() -> new WebSocketMessageType("order.place")) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("a response must name what it answers") - void responseRequiresCorrelation() { - // Without it the waiter never resolves, and on a multiplexed connection there is no other way - // to tell whose answer this is. - assertThatThrownBy( - () -> - new WebSocketEnvelope( - ID, - WebSocketMessageFamily.RESPONSE, - TYPE, - Optional.empty(), - Optional.empty(), - Optional.empty(), - Optional.empty(), - Optional.of("{}"))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("never resolves"); - } - - @Test - @DisplayName("an unordered family may not carry a sequence") - void unorderedFamilyRejectsSequence() { - // A sequence on a command invites gap detection on something the sender never ordered, and - // every resulting missing-message alarm is about nothing. - assertThatThrownBy( - () -> - new WebSocketEnvelope( - ID, - WebSocketMessageFamily.COMMAND, - TYPE, - Optional.empty(), - Optional.of("stream-1"), - Optional.of(1L), - Optional.empty(), - Optional.of("{}"))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("about nothing"); - } - - @Test - @DisplayName("a stream id and a sequence are meaningless apart") - void orderingFieldsComeTogether() { - // A stream without positions cannot be gap-checked; a position without a stream cannot be - // compared to anything. - assertThatThrownBy(() -> WebSocketEnvelope.event(ID, TYPE, "stream-1", null, "{}")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("meaningless apart"); - assertThatThrownBy(() -> WebSocketEnvelope.event(ID, TYPE, null, 1L, "{}")) - .isInstanceOf(IllegalArgumentException.class); - assertThatCode(() -> WebSocketEnvelope.event(ID, TYPE, "stream-1", 1L, "{}")) - .doesNotThrowAnyException(); - } - - @Test - @DisplayName("an unordered event is allowed to carry neither") - void eventMayBeUnordered() { - assertThatCode(() -> WebSocketEnvelope.event(ID, TYPE, null, null, "{}")) - .doesNotThrowAnyException(); - } - - @Test - @DisplayName("only a command may declare an expiry") - void onlyCommandsExpire() { - // An event that arrives late is still news; a response's deadline is one the sender cannot act - // on. - assertThatCode(() -> WebSocketEnvelope.command(ID, TYPE, "{}", NOW.plusSeconds(5))) - .doesNotThrowAnyException(); - assertThatThrownBy( - () -> - new WebSocketEnvelope( - ID, - WebSocketMessageFamily.EVENT, - TYPE, - Optional.empty(), - Optional.empty(), - Optional.empty(), - Optional.of(NOW), - Optional.of("{}"))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("only a command expires"); - } - - @Test - @DisplayName("an expired command is detectable before the handler runs") - void expiredCommandIsDetectable() { - // The client that gave up waiting has usually retried. Running both is the duplicate the - // deadline exists to prevent. - WebSocketEnvelope command = WebSocketEnvelope.command(ID, TYPE, "{}", NOW.plusSeconds(5)); - - assertThat(command.expiredAt(NOW)).isFalse(); - assertThat(command.expiredAt(NOW.plusSeconds(5))).isTrue(); - assertThat(WebSocketEnvelope.command(ID, TYPE, "{}", null).expiredAt(NOW)).isFalse(); - } - - @Test - @DisplayName("a heartbeat carries no payload") - void heartbeatCarriesNothing() { - assertThatThrownBy( - () -> - new WebSocketEnvelope( - ID, - WebSocketMessageFamily.HEARTBEAT, - TYPE, - Optional.empty(), - Optional.empty(), - Optional.empty(), - Optional.empty(), - Optional.of("{}"))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("carries no payload"); - } - - @Test - @DisplayName("the payload stays an encoded document, not a map") - void payloadIsOpaque() { - // The record component's type is the assertion. A Map here would accept any shape, defer every - // validation to whichever handler reaches for a missing key, make an entity trivially - // serializable onto the wire, and bring unbounded nesting with it. - java.lang.reflect.RecordComponent payload = - java.util.Arrays.stream(WebSocketEnvelope.class.getRecordComponents()) - .filter(component -> component.getName().equals("payload")) - .findFirst() - .orElseThrow(); - - assertThat(payload.getGenericType().getTypeName()) - .isEqualTo("java.util.Optional"); - } - - @Test - @DisplayName("a correlation id is a different type from a message id") - void correlationIsADistinctType() { - // Mixing "my identity" with "what I am answering" routes a response to the wrong waiter, and - // one caller receiving another's data is a disclosure rather than a bug. - assertThat((Object) new WebSocketMessageId("m-1")) - .isNotEqualTo(new WebSocketCorrelationId("m-1")); - assertThat(WebSocketCorrelationId.answering(ID).value()).isEqualTo("m-1"); - } -} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/protocol/WebSocketMessageDescriptorTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/protocol/WebSocketMessageDescriptorTest.java deleted file mode 100644 index d43d9217..00000000 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/protocol/WebSocketMessageDescriptorTest.java +++ /dev/null @@ -1,165 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.protocol; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.util.List; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * The catalog, and the asymmetry a WebSocket does not provide on its own. - * - *

At the transport layer either end may send any frame at any time. That symmetry is not - * something an application wants, and nothing enforces the difference unless the catalog does. - */ -class WebSocketMessageDescriptorTest { - - private static final WebSocketMessageType PLACE = new WebSocketMessageType("order.place.v1"); - private static final WebSocketMessageType PLACED = new WebSocketMessageType("order.placed.v1"); - - private static final WebSocketMessageCatalog CATALOG = - WebSocketMessageCatalog.of( - List.of( - new WebSocketMessageDescriptor( - PLACE, - WebSocketMessageFamily.COMMAND, - WebSocketMessageDirection.CLIENT_TO_SERVER, - WebSocketSchemaVersion.v(1)), - new WebSocketMessageDescriptor( - PLACED, - WebSocketMessageFamily.EVENT, - WebSocketMessageDirection.SERVER_TO_CLIENT, - WebSocketSchemaVersion.v(1)))); - - @Test - @DisplayName("an unknown type is refused before any handler") - void unknownTypeIsRefused() { - // The security property of a closed catalog: a decoder that resolves an arbitrary name from - // the wire can be asked to resolve one nobody intended. - assertThat(CATALOG.find(new WebSocketMessageType("nope.v1"))).isEmpty(); - assertThat(CATALOG.acceptsFromClient(new WebSocketMessageType("nope.v1"))).isFalse(); - } - - @Test - @DisplayName("a client cannot send a server-only type") - void clientCannotSendAServerOnlyType() { - // Otherwise a client injects an event the server relays to other subscribers as though the - // server had produced it. - assertThat(CATALOG.acceptsFromClient(PLACED)).isFalse(); - assertThat(CATALOG.acceptsFromClient(PLACE)).isTrue(); - } - - @Test - @DisplayName("an unpublished type and a forbidden one are answered identically") - void unpublishedAndForbiddenAreIndistinguishable() { - // A client learns nothing about what exists that it may not use. - assertThat(CATALOG.admitFromClient(PLACED, WebSocketMessageFamily.EVENT)).isEmpty(); - assertThat( - CATALOG.admitFromClient( - new WebSocketMessageType("nope.v1"), WebSocketMessageFamily.EVENT)) - .isEmpty(); - } - - @Test - @DisplayName("a claimed family that disagrees with the catalog is refused") - void mislabelledFamilyIsRefused() { - // A client labelling a command as an event routes it past everything the platform does per - // family — the expiry check and the correlation requirement both key on it. - assertThat(CATALOG.admitFromClient(PLACE, WebSocketMessageFamily.EVENT)).isEmpty(); - assertThat(CATALOG.admitFromClient(PLACE, WebSocketMessageFamily.COMMAND)).isPresent(); - } - - @Test - @DisplayName("a duplicate type fails at startup") - void duplicateTypeFailsAtStartup() { - assertThatThrownBy( - () -> - WebSocketMessageCatalog.of( - List.of( - new WebSocketMessageDescriptor( - PLACE, - WebSocketMessageFamily.COMMAND, - WebSocketMessageDirection.CLIENT_TO_SERVER, - WebSocketSchemaVersion.v(1)), - new WebSocketMessageDescriptor( - PLACE, - WebSocketMessageFamily.EVENT, - WebSocketMessageDirection.SERVER_TO_CLIENT, - WebSocketSchemaVersion.v(1))))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("silently unreachable"); - } - - @Test - @DisplayName("the type name's version and the schema's major must agree") - void typeNameAndSchemaVersionMustAgree() { - assertThatThrownBy( - () -> - new WebSocketMessageDescriptor( - PLACE, - WebSocketMessageFamily.COMMAND, - WebSocketMessageDirection.CLIENT_TO_SERVER, - WebSocketSchemaVersion.v(2))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("different shape"); - } - - @Test - @DisplayName("a minor bump stays readable, a major bump does not") - void majorBreaksAndMinorDoesNot() { - // Conflating the two would make every additive change a breaking one. - assertThat(new WebSocketSchemaVersion(1, 3).readableBy(new WebSocketSchemaVersion(1, 0))) - .isTrue(); - assertThat(new WebSocketSchemaVersion(2, 0).readableBy(new WebSocketSchemaVersion(1, 9))) - .isFalse(); - } - - @Test - @DisplayName("the catalog fingerprint ignores registration order") - void fingerprintIgnoresRegistrationOrder() { - // Otherwise it reports drift caused by bean ordering, and everyone learns to ignore it. - List forward = CATALOG.all(); - List reversed = new java.util.ArrayList<>(forward); - java.util.Collections.reverse(reversed); - - assertThat(WebSocketMessageCatalog.of(reversed).fingerprint()).isEqualTo(CATALOG.fingerprint()); - } - - @Test - @DisplayName("the fingerprint changes when the published surface changes") - void fingerprintTracksThePublishedSurface() { - List extra = new java.util.ArrayList<>(CATALOG.all()); - extra.add( - new WebSocketMessageDescriptor( - new WebSocketMessageType("order.cancel.v1"), - WebSocketMessageFamily.COMMAND, - WebSocketMessageDirection.CLIENT_TO_SERVER, - WebSocketSchemaVersion.v(1))); - WebSocketMessageCatalog extended = WebSocketMessageCatalog.of(extra); - - assertThat(extended.fingerprint()).isNotEqualTo(CATALOG.fingerprint()); - } - - @Test - @DisplayName("an additive minor release does not report drift") - void additiveReleaseDoesNotReportDrift() { - // Both nodes can serve a minor bump, so reporting drift on every additive release would train - // people to ignore the signal that matters. - WebSocketMessageCatalog bumped = - WebSocketMessageCatalog.of( - List.of( - new WebSocketMessageDescriptor( - PLACE, - WebSocketMessageFamily.COMMAND, - WebSocketMessageDirection.CLIENT_TO_SERVER, - new WebSocketSchemaVersion(1, 4)), - new WebSocketMessageDescriptor( - PLACED, - WebSocketMessageFamily.EVENT, - WebSocketMessageDirection.SERVER_TO_CLIENT, - new WebSocketSchemaVersion(1, 2)))); - - assertThat(bumped.fingerprint()).isEqualTo(CATALOG.fingerprint()); - } -} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/protocol/WebSocketProtocolProfileTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/protocol/WebSocketProtocolProfileTest.java deleted file mode 100644 index d8068687..00000000 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/protocol/WebSocketProtocolProfileTest.java +++ /dev/null @@ -1,92 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.protocol; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketSubprotocolName; -import java.util.List; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * Subprotocol negotiation, which happens once and then cannot be revisited. - * - *

An HTTP request negotiates per call; a WebSocket negotiates at handshake and lives for hours - * on whatever was agreed. Getting it wrong is not a failed request — it is a connection that works - * until the message format changes, then fails in a way nobody associates with a deploy. - */ -class WebSocketProtocolProfileTest { - - private static final WebSocketSubprotocolName STABLE = WebSocketSubprotocolName.stable(); - private static final WebSocketSubprotocolName OTHER = - new WebSocketSubprotocolName("vendor.other.v1.json"); - - @Test - @DisplayName("the Stable subprotocol carries its version in the token") - void stableSubprotocolIsVersioned() { - // The only place a WebSocket can put a version. Without it both ends assume their own current - // format and find out later. - assertThat(STABLE.value()).isEqualTo("ca-skeleton.realtime.v1.json"); - assertThat(STABLE.versioned()).isTrue(); - assertThat(new WebSocketSubprotocolName("ca-skeleton.realtime.json").versioned()).isFalse(); - } - - @Test - @DisplayName("a production endpoint refuses a client that offers no subprotocol") - void productionRefusesTheUnnegotiatedFallback() { - assertThat(WebSocketProtocolProfile.stable().acceptsHandshake(List.of())).isFalse(); - assertThat(WebSocketProtocolProfile.stable().productionReady()).isTrue(); - } - - @Test - @DisplayName("the local compatibility profile accepts one, and says so in its name") - void localCompatibilityAcceptsTheFallback() { - assertThat(WebSocketProtocolProfile.localCompatibility().acceptsHandshake(List.of())).isTrue(); - // Not production ready, and the flag is what a startup validator can refuse on. - assertThat(WebSocketProtocolProfile.localCompatibility().productionReady()).isFalse(); - } - - @Test - @DisplayName("a client offering only an unknown subprotocol is refused") - void unknownSubprotocolIsRefused() { - assertThat(WebSocketProtocolProfile.stable().acceptsHandshake(List.of(OTHER))).isFalse(); - assertThat(WebSocketProtocolProfile.stable().negotiate(List.of(OTHER))).isEmpty(); - } - - @Test - @DisplayName("negotiation follows server preference, not client preference") - void negotiationFollowsServerPreference() { - // A client's order is a request. Honouring it lets one old client pin the server to an old - // format for as long as it keeps connecting. - WebSocketProtocolProfile profile = - new WebSocketProtocolProfile(List.of(STABLE, OTHER), WebSocketCodecProfile.JSON, false); - - assertThat(profile.negotiate(List.of(OTHER, STABLE))).contains(STABLE); - } - - @Test - @DisplayName("the Stable codec is JSON and there is exactly one") - void stableCodecIsJsonOnly() { - // Every additional codec is another parser reachable from an unauthenticated frame. - assertThat(WebSocketCodecProfile.values()).containsExactly(WebSocketCodecProfile.JSON); - assertThat(WebSocketProtocolProfile.stable().codec()).isEqualTo(WebSocketCodecProfile.JSON); - } - - @Test - @DisplayName("a profile that accepts nothing at all is refused") - void profileThatAcceptsNothingIsRefused() { - assertThatThrownBy( - () -> new WebSocketProtocolProfile(List.of(), WebSocketCodecProfile.JSON, false)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("accepts nothing at all"); - } - - @Test - @DisplayName("a subprotocol token with a comma is refused") - void subprotocolTokenRejectsAComma() { - // The header separates on commas, so a token containing one is two tokens to the client and - // one to the server. - assertThatThrownBy(() -> new WebSocketSubprotocolName("a.v1.json,b.v1.json")) - .isInstanceOf(IllegalArgumentException.class); - } -} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/release/WebSocketNginxProxyProfileTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/release/WebSocketNginxProxyProfileTest.java deleted file mode 100644 index 76de9a40..00000000 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/release/WebSocketNginxProxyProfileTest.java +++ /dev/null @@ -1,95 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.release; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.time.Duration; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * The three proxy mistakes that present as application bugs. - * - *

Each is checked here because each is invisible from the application's side: a cut connection - * with no cause in any server log, a 200 where a 101 was expected, and a client-chosen client IP - * reaching the rate limiter. - */ -class WebSocketNginxProxyProfileTest { - - private static final Duration HEARTBEAT = Duration.ofSeconds(30); - - @Test - @DisplayName("a compliant profile has no faults") - void compliantProfileHasNoFaults() { - WebSocketNginxProxyProfile profile = WebSocketNginxProxyProfile.compliant(HEARTBEAT); - - assertThat(profile.compliant()).isTrue(); - assertThat(profile.faults()).isEmpty(); - assertThat(profile.proxyReadTimeout()).isGreaterThan(profile.heartbeatInterval()); - } - - @Test - @DisplayName("a read timeout at or below the heartbeat is a fault") - void tooShortReadTimeoutIsAFault() { - // Equal is not enough: a beat that arrives at the timeout instant races it, and the loser is - // decided by scheduling. The connection dies with no cause in any server log. - assertThat(new WebSocketNginxProxyProfile(HEARTBEAT, HEARTBEAT, true, true, true).faults()) - .anyMatch(fault -> fault.contains("neither log will say proxy")); - assertThat( - new WebSocketNginxProxyProfile(Duration.ofSeconds(10), HEARTBEAT, true, true, true) - .faults()) - .hasSize(1); - } - - @Test - @DisplayName("dropped upgrade headers are a fault") - void droppedUpgradeHeadersAreAFault() { - // Upgrade and Connection are hop-by-hop, so a proxy drops them unless told otherwise, and the - // upstream then answers an ordinary GET with 200 and a body. - assertThat( - new WebSocketNginxProxyProfile(Duration.ofSeconds(90), HEARTBEAT, false, true, true) - .faults()) - .anyMatch(fault -> fault.contains("hop-by-hop")); - } - - @Test - @DisplayName("appending to client-supplied forwarded headers is a fault") - void unsanitizedForwardedHeadersAreAFault() { - // The client sends its own X-Forwarded-For, the proxy appends, and the application trusts the - // first entry — which the client chose. That address reaches the rate limiter and the audit - // log. - assertThat( - new WebSocketNginxProxyProfile(Duration.ofSeconds(90), HEARTBEAT, true, false, true) - .faults()) - .anyMatch(fault -> fault.contains("the client chooses the address")); - } - - @Test - @DisplayName("a ticket in the access log is a fault") - void loggedCredentialIsAFault() { - // A handshake ticket is a credential, and the access log is retained longer and read more - // widely than anything else that ever holds one. - assertThat( - new WebSocketNginxProxyProfile(Duration.ofSeconds(90), HEARTBEAT, true, true, false) - .faults()) - .anyMatch(fault -> fault.contains("retained longer and read more widely")); - } - - @Test - @DisplayName("every fault is reported at once") - void faultsAreReportedTogether() { - assertThat( - new WebSocketNginxProxyProfile(Duration.ofSeconds(10), HEARTBEAT, false, false, false) - .faults()) - .hasSize(4); - } - - @Test - @DisplayName("a negative timeout is refused at construction") - void negativeTimeoutIsRefused() { - assertThatThrownBy( - () -> - new WebSocketNginxProxyProfile(Duration.ofSeconds(-1), HEARTBEAT, true, true, true)) - .isInstanceOf(IllegalArgumentException.class); - } -} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/release/WebSocketRollingRestartScenarioTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/release/WebSocketRollingRestartScenarioTest.java deleted file mode 100644 index a7ab3acd..00000000 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/release/WebSocketRollingRestartScenarioTest.java +++ /dev/null @@ -1,118 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.release; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.time.Duration; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * A restart that looks graceful and is not. - * - *

Every step below has a failure mode that produces no error: readiness left up drains forever, - * a 1006 tells the client nothing, an un-jittered reconnect arrives as a thundering herd, and a - * resent command charges somebody twice. The scenario names them so a restart can be judged rather - * than described. - */ -class WebSocketRollingRestartScenarioTest { - - private final WebSocketRollingRestartScenario scenario = - WebSocketRollingRestartScenario.conventional(); - - private java.util.List blockers( - boolean readinessFirst, - boolean refusedHandshakes, - boolean drained, - int closeCode, - boolean jittered, - int duplicates) { - return scenario.blockers( - readinessFirst, refusedHandshakes, drained, closeCode, jittered, duplicates); - } - - @Test - @DisplayName("a clean restart reports nothing") - void cleanRestartReportsNothing() { - assertThat(blockers(true, true, true, 1001, true, 0)).isEmpty(); - } - - @Test - @DisplayName("readiness left up means the drain cannot finish") - void readinessLeftUpBlocks() { - // The balancer keeps sending connections to a node that is trying to empty itself, so the - // queue never reaches zero and the deadline forces a cut that looked avoidable. - assertThat(blockers(false, true, true, 1001, true, 0)) - .anyMatch(blocker -> blocker.contains("balancer kept sending")); - } - - @Test - @DisplayName("accepting a handshake while draining is a blocker") - void acceptingWhileDrainingBlocks() { - assertThat(blockers(true, false, true, 1001, true, 0)) - .anyMatch(blocker -> blocker.contains("about to cut")); - } - - @Test - @DisplayName("an unfinished drain names what is lost") - void unfinishedDrainBlocks() { - assertThat(blockers(true, true, false, 1001, true, 0)) - .anyMatch(blocker -> blocker.contains("what remains is lost")); - } - - @Test - @DisplayName("an abnormal close is a blocker") - void abnormalCloseBlocks() { - // 1006 is not a close code at all — it means no frame arrived, which is what an abrupt kill - // looks like. - assertThat(blockers(true, true, true, 1006, true, 0)) - .anyMatch(blocker -> blocker.contains("observed close code 1006")); - } - - @Test - @DisplayName("an un-jittered reconnect is a blocker") - void unjitteredReconnectBlocks() { - assertThat(blockers(true, true, true, 1001, false, 0)) - .anyMatch(blocker -> blocker.contains("whole population")); - } - - @Test - @DisplayName("a command executed twice is a blocker, and it is counted") - void duplicateCommandBlocks() { - // The one failure with a financial shape. A reconnect that resends an in-flight command needs - // the idempotency ledger to recognise it; if it does not, the restart charged somebody twice. - assertThat(blockers(true, true, true, 1001, true, 3)) - .anyMatch(blocker -> blocker.contains("3 command(s) executed twice")); - } - - @Test - @DisplayName("every failure is reported at once") - void failuresAreReportedTogether() { - assertThat(blockers(false, false, false, 1006, false, 1)).hasSize(6); - } - - @Test - @DisplayName("a scenario with no deadline or no jitter is refused at construction") - void degenerateScenarioIsRefused() { - assertThatThrownBy( - () -> new WebSocketRollingRestartScenario(Duration.ZERO, 1001, Duration.ofSeconds(5))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("never completes"); - assertThatThrownBy( - () -> new WebSocketRollingRestartScenario(Duration.ofSeconds(30), 1001, Duration.ZERO)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("same instant"); - } - - @Test - @DisplayName("a scenario that expects a different close code is refused at construction") - void wrongExpectationIsRefused() { - // Otherwise the release gate could drift away from the close code the runtime actually sends. - assertThatThrownBy( - () -> - new WebSocketRollingRestartScenario( - Duration.ofSeconds(30), 1012, Duration.ofSeconds(5))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("closes 1001"); - } -} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/release/WebSocketStableReleaseGateTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/release/WebSocketStableReleaseGateTest.java deleted file mode 100644 index cbe9e488..00000000 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/release/WebSocketStableReleaseGateTest.java +++ /dev/null @@ -1,125 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.release; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.util.HashSet; -import java.util.Set; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * The conditions Stable may not be promoted without. - * - *

Each case falsifies one condition and asserts the gate refuses. A gate whose refusals are - * never exercised is the failure this repository keeps finding: a control that exists, passes its - * tests, and is reached by nothing. - */ -class WebSocketStableReleaseGateTest { - - private static final Set ALL_RUNTIMES = WebSocketStableReleaseGate.RUNTIMES; - private static final Set ALL_SUITES = WebSocketStableReleaseGate.SUITES; - - private static WebSocketStableReleaseGate satisfied() { - return new WebSocketStableReleaseGate(ALL_RUNTIMES, ALL_SUITES, true, true); - } - - private static Set without(Set values, String removed) { - Set remaining = new HashSet<>(values); - remaining.remove(removed); - return Set.copyOf(remaining); - } - - @Test - @DisplayName("a fully evidenced release is promotable") - void fullEvidencePromotes() { - assertThat(satisfied().promotable(ALL_RUNTIMES, ALL_SUITES)).isTrue(); - assertThat(satisfied().blockers(ALL_RUNTIMES, ALL_SUITES)).isEmpty(); - } - - @Test - @DisplayName("the standard gate starts un-promotable") - void standardGateStartsClosed() { - // Nothing is proven at the moment a release begins, so the default has to be refusal. A gate - // that defaults to open is satisfied by forgetting to run it. - WebSocketStableReleaseGate standard = WebSocketStableReleaseGate.standard(); - - assertThat(standard.promotable(Set.of(), Set.of())).isFalse(); - assertThat(standard.blockers(ALL_RUNTIMES, ALL_SUITES)) - .anyMatch(blocker -> blocker.contains("Advanced type is present")) - .anyMatch(blocker -> blocker.contains("support matrix is unpublished")); - } - - @Test - @DisplayName("a missing container is a blocker, and it is named") - void missingRuntimeBlocks() { - // Upgrade negotiation, close-frame timing and idle handling are container code, and the three - // containers disagree about all three — so evidence on one certifies exactly one. - assertThat(satisfied().blockers(without(ALL_RUNTIMES, "jetty"), ALL_SUITES)) - .hasSize(1) - .allMatch(blocker -> blocker.contains("jetty")); - } - - @Test - @DisplayName("the proxy counts as a runtime") - void proxyIsARuntime() { - // The one most often left out, and the one that fails in production rather than in a test: a - // proxy read timeout below the heartbeat cuts healthy connections and no server log says so. - assertThat(satisfied().blockers(without(ALL_RUNTIMES, "nginx"), ALL_SUITES)) - .anyMatch(blocker -> blocker.contains("nginx")); - } - - @Test - @DisplayName("the two named failure suites are mandatory") - void namedSuitesAreMandatory() { - // Named individually because each covers a failure that unit tests reported as passing. - assertThat(satisfied().blockers(ALL_RUNTIMES, without(ALL_SUITES, "commit-response-loss"))) - .anyMatch(blocker -> blocker.contains("commit-response-loss")); - assertThat(satisfied().blockers(ALL_RUNTIMES, without(ALL_SUITES, "slow-consumer"))) - .anyMatch(blocker -> blocker.contains("slow-consumer")); - } - - @Test - @DisplayName("an Advanced type in the Stable artifact blocks the release") - void advancedInArtifactBlocks() { - // The packaging half of WS-ARCH-6. The compile-time rule refuses a source edge; nothing in it - // notices a type that arrived through packaging, and the effect is the same — Stable does not - // build without Advanced. - WebSocketStableReleaseGate leaked = - new WebSocketStableReleaseGate(ALL_RUNTIMES, ALL_SUITES, false, true); - - assertThat(leaked.promotable(ALL_RUNTIMES, ALL_SUITES)).isFalse(); - assertThat(leaked.blockers(ALL_RUNTIMES, ALL_SUITES)) - .anyMatch(blocker -> blocker.contains("naming convention")); - } - - @Test - @DisplayName("an unpublished support matrix blocks the release") - void unpublishedMatrixBlocks() { - // What is not stated as unsupported is read as supported, and the reading happens after - // somebody has already built on it. - WebSocketStableReleaseGate silent = - new WebSocketStableReleaseGate(ALL_RUNTIMES, ALL_SUITES, true, false); - - assertThat(silent.blockers(ALL_RUNTIMES, ALL_SUITES)) - .anyMatch(blocker -> blocker.contains("read as supporting it")); - } - - @Test - @DisplayName("every blocker is reported at once") - void blockersAreReportedTogether() { - // Reporting one at a time turns a release into a queue of rediscoveries. - assertThat(WebSocketStableReleaseGate.standard().blockers(Set.of(), Set.of())).hasSize(4); - } - - @Test - @DisplayName("a gate that requires nothing is refused at construction") - void emptyGateIsRefused() { - // It would pass everything while reading, in a release checklist, as a gate. - assertThatThrownBy(() -> new WebSocketStableReleaseGate(Set.of(), ALL_SUITES, true, true)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("passes everything"); - assertThatThrownBy(() -> new WebSocketStableReleaseGate(ALL_RUNTIMES, Set.of(), true, true)) - .isInstanceOf(IllegalArgumentException.class); - } -} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/servlet/PlatformWebSocketHandlerBackpressureTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/servlet/PlatformWebSocketHandlerTest.java similarity index 67% rename from src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/servlet/PlatformWebSocketHandlerBackpressureTest.java rename to src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/servlet/PlatformWebSocketHandlerTest.java index 8ed9bfcd..16e888db 100644 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/servlet/PlatformWebSocketHandlerBackpressureTest.java +++ b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/servlet/PlatformWebSocketHandlerTest.java @@ -4,11 +4,11 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import dev.caskeleton.adapter.inbound.websocket.budget.WebSocketConnectionBudget; import dev.caskeleton.adapter.inbound.websocket.outbound.GlobalBufferBudget; -import java.time.Duration; import java.util.Optional; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; @@ -16,18 +16,53 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.boot.web.server.context.WebServerApplicationContext; import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; -class PlatformWebSocketHandlerBackpressureTest { +class PlatformWebSocketHandlerTest { + + @Test + void stopRunsBeforeTheWebServerGracefulShutdown() { + // Spring stops the highest phase first; below this the server is gone before 1001 is sent. + PlatformWebSocketHandler handler = + new PlatformWebSocketHandler( + new WebSocketConnectionBudget(64, 10), + new GlobalBufferBudget(1_024), + (connection, request) -> Optional.empty()); + + assertThat(handler.getPhase()) + .isGreaterThan(WebServerApplicationContext.GRACEFUL_SHUTDOWN_PHASE); + } + + @Test + void messageOverTheBoundInUtf8BytesClosesWith1009() throws Exception { + // given + // 30 characters are 90 UTF-8 bytes, over the 64-byte bound although under it in chars. + PlatformWebSocketHandler handler = + new PlatformWebSocketHandler( + new WebSocketConnectionBudget(64, 1_024), + new GlobalBufferBudget(1_024), + (connection, request) -> Optional.of("unexpected")); + WebSocketSession session = mock(WebSocketSession.class); + when(session.getId()).thenReturn("session-02"); + handler.afterConnectionEstablished(session); + + // when + handler.handleTextMessage(session, new TextMessage("한".repeat(30))); + + // then + ArgumentCaptor closed = ArgumentCaptor.forClass(CloseStatus.class); + verify(session).close(closed.capture()); + assertThat(closed.getValue().getCode()).isEqualTo(1009); + } @Test void guaranteedReplyOverflowClosesTheConnectionInsteadOfSilentlyLosingTheReply() throws Exception { - WebSocketConnectionBudget budget = - new WebSocketConnectionBudget( - 16, 64, 4, 100, 10, Duration.ofHours(1), Duration.ofMinutes(1)); + WebSocketConnectionBudget budget = new WebSocketConnectionBudget(64, 10); PlatformWebSocketHandler handler = new PlatformWebSocketHandler( budget, diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/session/WebSocketSessionRegistryTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/session/WebSocketSessionRegistryTest.java deleted file mode 100644 index cd7152d6..00000000 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/session/WebSocketSessionRegistryTest.java +++ /dev/null @@ -1,211 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.session; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketActorReference; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketConnectionContext; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketConnectionId; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketConnectionState; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketCredentialExpiry; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketEndpointName; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketNodeId; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketSessionId; -import dev.caskeleton.adapter.inbound.websocket.core.WebSocketSubprotocolName; -import java.nio.charset.StandardCharsets; -import java.time.Duration; -import java.time.Instant; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * The connections one node holds, and the bookkeeping that has to survive churn. - * - *

A registry is easy to get right for a hundred connections and wrong for a hundred thousand. - * The cases that matter are the ones about what happens over time — indexes that grow with the - * number of users who ever connected rather than with the number connected now. - */ -class WebSocketSessionRegistryTest { - - private static final Instant NOW = Instant.parse("2026-08-25T10:00:00Z"); - private static final byte[] SALT = - "a-deployment-salt-of-adequate-length".getBytes(StandardCharsets.UTF_8); - private static final WebSocketEndpointName ENDPOINT = new WebSocketEndpointName("live-updates"); - - private final WebSocketSessionRegistry registry = new WebSocketSessionRegistry(3); - - @Test - @DisplayName("a registered connection is findable") - void registeredConnectionIsFindable() { - WebSocketConnectionContext context = context("c-00000001", "alice"); - - assertThat(registry.register(context)).isTrue(); - assertThat(registry.find(context.connectionId())).contains(context); - assertThat(registry.countFor(ENDPOINT)).isOne(); - } - - @Test - @DisplayName("an actor cannot exceed its per-node cap") - void perActorCapHolds() { - for (int index = 0; index < 3; index++) { - assertThat(registry.register(context("c-0000000" + index, "alice"))).isTrue(); - } - - assertThat(registry.register(context("c-00000009", "alice"))).isFalse(); - // Another actor is unaffected: the cap is per actor, not global. - assertThat(registry.register(context("c-00000010", "bob"))).isTrue(); - } - - @Test - @DisplayName("concurrent registrations cannot exceed the cap") - void concurrentRegistrationsRespectTheCap() throws Exception { - // The check and the insert have to be one step. Two handshakes arriving together would both - // see room otherwise, which is how a cap becomes a suggestion under exactly the load it is for. - AtomicInteger accepted = new AtomicInteger(); - CountDownLatch start = new CountDownLatch(1); - try (ExecutorService pool = Executors.newFixedThreadPool(8)) { - Future[] futures = new Future[16]; - for (int index = 0; index < futures.length; index++) { - int id = index; - futures[index] = - pool.submit( - () -> { - start.await(); - if (registry.register(context(String.format("c-%08d", id), "alice"))) { - accepted.incrementAndGet(); - } - return null; - }); - } - start.countDown(); - for (Future future : futures) { - future.get(30, TimeUnit.SECONDS); - } - } - - assertThat(accepted).hasValue(3); - assertThat(registry.connectionsOf(actor("alice"))).hasSize(3); - } - - @Test - @DisplayName("deregistering frees the actor's allowance") - void deregisteringFreesTheAllowance() { - registry.register(context("c-00000001", "alice")); - registry.register(context("c-00000002", "alice")); - registry.register(context("c-00000003", "alice")); - - registry.deregister(new WebSocketConnectionId("c-00000002")); - - assertThat(registry.register(context("c-00000004", "alice"))).isTrue(); - } - - @Test - @DisplayName("the actor index does not grow with churn") - void actorIndexDoesNotLeakAcrossChurn() { - // A leak here is proportional to how many distinct users ever connected, not to how many are - // connected — so it looks fine for a day and unbounded over a month. - for (int index = 0; index < 50; index++) { - WebSocketConnectionContext context = - context("c-000000" + String.format("%02d", index), "user" + index); - registry.register(context); - registry.deregister(context.connectionId()); - } - - assertThat(registry.size()).isZero(); - assertThat(registry.connectionsOf(actor("user7"))).isEmpty(); - } - - @Test - @DisplayName("the endpoint count returns to zero") - void endpointCountReturnsToZero() { - WebSocketConnectionContext context = context("c-00000001", "alice"); - registry.register(context); - registry.deregister(context.connectionId()); - - assertThat(registry.countFor(ENDPOINT)).isZero(); - } - - @Test - @DisplayName("everything an actor holds is listable") - void actorConnectionsAreListable() { - // The operation the index exists for: disconnect everything this user has open. - registry.register(context("c-00000001", "alice")); - registry.register(context("c-00000002", "alice")); - registry.register(context("c-00000003", "bob")); - - assertThat(registry.connectionsOf(actor("alice"))).hasSize(2); - assertThat(registry.connectionsOf(actor("bob"))).hasSize(1); - } - - @Test - @DisplayName("draining moves open connections and returns them") - void drainMovesAndReturns() { - // Returned rather than closed, so the caller decides the pacing — that belongs to whoever - // knows how long the deploy is willing to wait. - registry.register(context("c-00000001", "alice")); - registry.register(context("c-00000002", "bob")); - - List draining = registry.drainAll(); - - assertThat(draining).hasSize(2); - assertThat(draining).allMatch(context -> context.state() == WebSocketConnectionState.DRAINING); - assertThat(registry.find(new WebSocketConnectionId("c-00000001")).orElseThrow().state()) - .isEqualTo(WebSocketConnectionState.DRAINING); - } - - @Test - @DisplayName("draining twice does not fail on already-draining connections") - void drainIsIdempotent() { - registry.register(context("c-00000001", "alice")); - registry.drainAll(); - - assertThat(registry.drainAll()).isEmpty(); - } - - @Test - @DisplayName("connections past their credential grace or their age are listed") - void expiredConnectionsAreListed() { - WebSocketConnectionContext aging = - new WebSocketConnectionContext( - new WebSocketConnectionId("c-00000001"), - new WebSocketSessionId("s-00000001"), - new WebSocketNodeId("edge-1"), - ENDPOINT, - Optional.of(WebSocketSubprotocolName.stable()), - actor("alice"), - WebSocketConnectionState.OPEN, - WebSocketCredentialExpiry.at(NOW.plusSeconds(10), Duration.ofSeconds(5)), - NOW); - registry.register(aging); - - assertThat(registry.expiredAt(NOW.plusSeconds(1), Duration.ofHours(4))).isEmpty(); - // Past the credential's grace. - assertThat(registry.expiredAt(NOW.plusSeconds(20), Duration.ofHours(4))).hasSize(1); - // Or past the maximum age, even with a live credential. - assertThat(registry.expiredAt(NOW.plusSeconds(1), Duration.ofMillis(1))).hasSize(1); - } - - private static WebSocketActorReference actor(String subject) { - return WebSocketActorReference.of(subject, "acme", SALT); - } - - private static WebSocketConnectionContext context(String connectionId, String subject) { - return new WebSocketConnectionContext( - new WebSocketConnectionId(connectionId), - new WebSocketSessionId("s-" + connectionId.substring(2)), - new WebSocketNodeId("edge-1"), - ENDPOINT, - Optional.of(WebSocketSubprotocolName.stable()), - actor(subject), - WebSocketConnectionState.OPEN, - WebSocketCredentialExpiry.never(), - NOW); - } -} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/LiveEventStompBroadcasterTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/LiveEventStompBroadcasterTest.java index e2c2704a..e76f8e6f 100644 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/LiveEventStompBroadcasterTest.java +++ b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/LiveEventStompBroadcasterTest.java @@ -21,7 +21,7 @@ import org.springframework.messaging.simp.SimpMessagingTemplate; class LiveEventStompBroadcasterTest { private final SimpMessagingTemplate messaging = mock(SimpMessagingTemplate.class); - private final WebSocketProperties properties = new WebSocketProperties(); + private final WebSocketSettings properties = new WebSocketSettings(); @Test void dropsDomainEventWhenNoProjectorIsAllowlisted() { diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketAutoConfigurationTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketAutoConfigurationTest.java new file mode 100644 index 00000000..00a7c811 --- /dev/null +++ b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketAutoConfigurationTest.java @@ -0,0 +1,51 @@ +package dev.caskeleton.adapter.inbound.websocket.stomp; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import org.junit.jupiter.api.Test; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.test.context.runner.WebApplicationContextRunner; + +/** The STOMP channel reaches an application through this module's own auto-configuration entry. */ +class WebSocketAutoConfigurationTest { + + private final WebApplicationContextRunner runner = + new WebApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(WebSocketConfig.class)); + + @Test + void theChannelIsRegisteredInTheModulesOwnImportsFile() throws IOException { + try (InputStream imports = + getClass() + .getClassLoader() + .getResourceAsStream( + "META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports")) { + assertThat(imports).isNotNull(); + assertThat(new String(imports.readAllBytes(), StandardCharsets.UTF_8)) + .contains(WebSocketConfig.class.getName()); + } + } + + @Test + void presentWithoutTheSwitchIsOn() { + runner.run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context).hasSingleBean(LiveEventStompBroadcaster.class); + }); + } + + @Test + void switchedOffHoldsNothing() { + runner + .withPropertyValues("app.websocket.enabled=false") + .run( + context -> { + assertThat(context).doesNotHaveBean(WebSocketSettings.class); + assertThat(context).doesNotHaveBean(LiveEventStompBroadcaster.class); + }); + } +} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketEnvironmentBindingTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketEnvironmentBindingTest.java new file mode 100644 index 00000000..0e1fcd23 --- /dev/null +++ b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketEnvironmentBindingTest.java @@ -0,0 +1,44 @@ +package dev.caskeleton.adapter.inbound.websocket.stomp; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.springframework.boot.context.properties.bind.Bindable; +import org.springframework.boot.context.properties.bind.Binder; +import org.springframework.core.env.StandardEnvironment; +import org.springframework.core.env.SystemEnvironmentPropertySource; + +class WebSocketEnvironmentBindingTest { + + @Test + void officialAppWebsocketEnvironmentNamesBindTheCanonicalPropertyTree() { + // given + StandardEnvironment environment = new StandardEnvironment(); + environment + .getPropertySources() + .addFirst( + new SystemEnvironmentPropertySource( + "websocket-contract", + Map.of( + "APP_WEBSOCKET_ENABLED", "true", + "APP_WEBSOCKET_ENDPOINT", "/live/ws", + "APP_WEBSOCKET_ALLOWED_ORIGINS", "https://client.example", + "APP_WEBSOCKET_BROADCAST_DESTINATION", "/topic/live"))); + + // when + WebSocketSettings stomp = + Binder.get(environment) + .bind("app.websocket", Bindable.of(WebSocketSettings.class)) + .orElseThrow(() -> new AssertionError("websocket env did not bind")); + + // then + assertThat(stomp) + .extracting( + WebSocketSettings::isEnabled, + WebSocketSettings::getEndpoint, + WebSocketSettings::getAllowedOrigins, + WebSocketSettings::getBroadcastDestination) + .containsExactly(true, "/live/ws", "https://client.example", "/topic/live"); + } +} diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketInboundAuthorizationInterceptorTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketInboundAuthorizationInterceptorTest.java index 20766e29..a725311d 100644 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketInboundAuthorizationInterceptorTest.java +++ b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketInboundAuthorizationInterceptorTest.java @@ -16,7 +16,7 @@ class WebSocketInboundAuthorizationInterceptorTest { private static final Principal AUTHENTICATED = () -> "qualified-user"; - private final WebSocketProperties properties = new WebSocketProperties(); + private final WebSocketSettings properties = new WebSocketSettings(); private final WebSocketInboundAuthorizationInterceptor interceptor = new WebSocketInboundAuthorizationInterceptor(properties); private final MessageChannel channel = mock(MessageChannel.class); diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketPropertiesTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketSettingsTest.java similarity index 85% rename from src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketPropertiesTest.java rename to src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketSettingsTest.java index d8022082..c4d996bf 100644 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketPropertiesTest.java +++ b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketSettingsTest.java @@ -12,7 +12,7 @@ import org.springframework.boot.validation.autoconfigure.ValidationAutoConfigura import org.springframework.context.annotation.Configuration; import org.springframework.validation.annotation.Validated; -class WebSocketPropertiesTest { +class WebSocketSettingsTest { private final ApplicationContextRunner runner = new ApplicationContextRunner() @@ -20,12 +20,12 @@ class WebSocketPropertiesTest { .withUserConfiguration(EnableProperties.class); @Test - void defaultsKeepTransportDisabledAndUseASafeLocalOrigin() { - WebSocketProperties properties = new WebSocketProperties(); + void defaultsTurnTheTransportOnWithASafeLocalOrigin() { + WebSocketSettings properties = new WebSocketSettings(); - assertThat(properties.isEnabled()).isFalse(); + assertThat(properties.isEnabled()).isTrue(); assertThat(properties.getAllowedOrigins()).isEqualTo("http://localhost:3000"); - assertThat(WebSocketProperties.class).hasAnnotation(Validated.class); + assertThat(WebSocketSettings.class).hasAnnotation(Validated.class); } @Test @@ -39,7 +39,7 @@ class WebSocketPropertiesTest { .run( context -> { assertThat(context).hasNotFailed(); - WebSocketProperties properties = context.getBean(WebSocketProperties.class); + WebSocketSettings properties = context.getBean(WebSocketSettings.class); assertThat(properties.allowedOriginPatterns()) .containsExactly("https://client.example:8443"); }); @@ -70,6 +70,6 @@ class WebSocketPropertiesTest { } @Configuration(proxyBeanMethods = false) - @EnableConfigurationProperties(WebSocketProperties.class) + @EnableConfigurationProperties(WebSocketSettings.class) static class EnableProperties {} } diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/webflux/WebSocketDataBufferLifecycleTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/webflux/WebSocketDataBufferLifecycleTest.java deleted file mode 100644 index e0df1531..00000000 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/webflux/WebSocketDataBufferLifecycleTest.java +++ /dev/null @@ -1,127 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.webflux; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.util.concurrent.atomic.AtomicLong; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * Reference counting on the reactive stack, made countable. - * - *

Both directions are wrong in a way that does not fail where it happens. Under-releasing leaks - * pooled memory and surfaces weeks later as unattributable heap growth; over-releasing returns one - * pooled buffer to two owners and surfaces as a message whose contents belong to another - * connection. Neither throws at the call site, so the only early warning is a counter. - */ -class WebSocketDataBufferLifecycleTest { - - private final AtomicLong refusals = new AtomicLong(); - - private WebSocketDataBufferLifecycle lifecycle(WebSocketDataBufferPolicy policy) { - return new WebSocketDataBufferLifecycle(policy, bytes -> refusals.incrementAndGet()); - } - - @Test - @DisplayName("the safe default retains nothing") - void copyOnReceiveRetainsNothing() { - // A handler that copies out of the pooled buffer before returning cannot use-after-free, and - // this is the policy that says so rather than leaving it to convention. - WebSocketDataBufferLifecycle lifecycle = lifecycle(WebSocketDataBufferPolicy.copyOnReceive()); - - assertThat(lifecycle.retain(128)).isFalse(); - assertThat(lifecycle.retainedBytes()).isZero(); - assertThat(refusals.get()).isEqualTo(1); - } - - @Test - @DisplayName("a retaining policy holds up to its ceiling and refuses past it") - void retainingIsBounded() { - WebSocketDataBufferLifecycle lifecycle = lifecycle(WebSocketDataBufferPolicy.retaining(1_000)); - - assertThat(lifecycle.retain(600)).isTrue(); - assertThat(lifecycle.retain(400)).isTrue(); - assertThat(lifecycle.retain(1)).isFalse(); - assertThat(lifecycle.retainedBytes()).isEqualTo(1_000); - assertThat(refusals.get()).isEqualTo(1); - } - - @Test - @DisplayName("releasing frees the ceiling again") - void releasingFreesTheCeiling() { - WebSocketDataBufferLifecycle lifecycle = lifecycle(WebSocketDataBufferPolicy.retaining(1_000)); - lifecycle.retain(1_000); - - lifecycle.release(600); - - assertThat(lifecycle.retain(600)).isTrue(); - } - - @Test - @DisplayName("a balanced stream ends with nothing retained") - void balancedStreamEndsClean() { - // What a leak test asserts after the stream ends — including a cancelled one, which for a - // long-lived socket is the ordinary way it ends. - WebSocketDataBufferLifecycle lifecycle = lifecycle(WebSocketDataBufferPolicy.retaining(1_000)); - lifecycle.retain(100); - lifecycle.retain(200); - - assertThat(lifecycle.balanced()).isFalse(); - - lifecycle.release(100); - lifecycle.release(200); - - assertThat(lifecycle.balanced()).isTrue(); - assertThat(lifecycle.retains()).isEqualTo(lifecycle.releases()); - } - - @Test - @DisplayName("a double release is refused rather than wrapping past zero") - void doubleReleaseIsRefused() { - // The counter is the only place this is visible. Letting it go negative would hide the second - // release and leave the corrupted message as the first symptom. - WebSocketDataBufferLifecycle lifecycle = lifecycle(WebSocketDataBufferPolicy.retaining(1_000)); - lifecycle.retain(100); - lifecycle.release(100); - - assertThatThrownBy(() -> lifecycle.release(100)) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("two owners"); - assertThat(lifecycle.retainedBytes()).isZero(); - } - - @Test - @DisplayName("retaining an unpooled buffer is refused at construction") - void unpooledRetentionIsRefused() { - assertThatThrownBy(() -> new WebSocketDataBufferPolicy(false, true, 100)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("needs no reference counting"); - } - - @Test - @DisplayName("retaining without a ceiling is refused at construction") - void unboundedRetentionIsRefused() { - assertThatThrownBy(() -> new WebSocketDataBufferPolicy(true, true, 0)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("one cancelled subscription at a time"); - } - - @Test - @DisplayName("a ceiling that cannot be reached is refused at construction") - void unreachableCeilingIsRefused() { - // A policy stating a limit it never applies reads to an operator as a limit that is in force. - assertThatThrownBy(() -> new WebSocketDataBufferPolicy(true, false, 100)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("cannot be reached"); - } - - @Test - @DisplayName("a negative size is refused in both directions") - void negativeSizesAreRefused() { - WebSocketDataBufferLifecycle lifecycle = lifecycle(WebSocketDataBufferPolicy.retaining(1_000)); - - assertThatThrownBy(() -> lifecycle.retain(-1)).isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> lifecycle.release(-1)).isInstanceOf(IllegalArgumentException.class); - } -} diff --git a/src/adapter/inbound/websocket/src/testFixtures/java/dev/caskeleton/adapter/inbound/websocket/testkit/arch/WebSocketArchitectureRules.java b/src/adapter/inbound/websocket/src/testFixtures/java/dev/caskeleton/adapter/inbound/websocket/testkit/arch/WebSocketArchitectureRules.java deleted file mode 100644 index e79c653a..00000000 --- a/src/adapter/inbound/websocket/src/testFixtures/java/dev/caskeleton/adapter/inbound/websocket/testkit/arch/WebSocketArchitectureRules.java +++ /dev/null @@ -1,160 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.testkit.arch; - -import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses; -import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noMethods; - -import com.tngtech.archunit.lang.ArchRule; - -/** - * The boundaries this platform depends on that no dependency gate can see. - * - *

A Gradle gate checks which artifacts a module may use. Every rule here is about how a legal - * artifact is used: {@code spring-websocket} is a legitimate dependency of this leaf, so nothing in - * the build can tell that a handler reached for a {@code WebSocketSession} — only a rule that reads - * the handler can. - * - *

In the testkit rather than {@code main} because ArchUnit is a test library, and shipping it in - * production would put it on every deployment's classpath to serve code that only runs in a test. - */ -public final class WebSocketArchitectureRules { - - private static final String PLATFORM = "dev.caskeleton.adapter.inbound.websocket"; - - private WebSocketArchitectureRules() {} - - /** - * A message handler cannot touch the transport. - * - *

The rule the entire outbound design rests on. A handler that can reach a session can write - * to the socket directly, and once one can, ordering, backpressure and the drain sequence are - * advisory — they hold for the handlers that cooperate and silently do not for the one that did - * not. Nothing at the type level prevents it; the handler receives a context by design, but - * nothing stops it from being handed a session by whoever wires it. - */ - public static ArchRule handlersDoNotTouchTheTransport() { - return noClasses() - .that() - .resideInAPackage(PLATFORM + ".handler..") - .should() - .dependOnClassesThat() - .resideInAnyPackage( - "org.springframework.web.socket..", - "jakarta.websocket..", - "io.netty..", - "reactor.netty..") - .as( - "WS-ARCH-1: a message handler may not name a transport session. A handler that can" - + " write directly bypasses the outbound queue, and every ordering and" - + " backpressure guarantee becomes advisory") - .allowEmptyShould(true); - } - - /** - * The two runtimes never see each other. - * - *

They are mutually exclusive at deployment: Boot deduces one application type from the - * classpath. A compile-time edge between them makes it possible to ship both, at which point one - * set of endpoints is silently never served. - */ - public static ArchRule runtimesAreMutuallyExclusive() { - return noClasses() - .that() - .resideInAPackage(PLATFORM + ".servlet..") - .should() - .dependOnClassesThat() - .resideInAPackage(PLATFORM + ".webflux..") - .as("WS-ARCH-2: the servlet runtime may not name the reactive one") - .allowEmptyShould(true); - } - - /** The reverse of {@link #runtimesAreMutuallyExclusive}. */ - public static ArchRule reactiveRuntimeDoesNotNameServlet() { - return noClasses() - .that() - .resideInAPackage(PLATFORM + ".webflux..") - .should() - .dependOnClassesThat() - .resideInAnyPackage(PLATFORM + ".servlet..", "jakarta.servlet..") - .as("WS-ARCH-3: the reactive runtime may not name the servlet one") - .allowEmptyShould(true); - } - - /** - * The platform does not reach persistence or the domain directly. - * - *

A transport that reads a repository has skipped the application: there is no use case to - * test, no transaction anybody declared, and no port a second transport could reuse. It is the - * same rule the HTTP platform carries, and it matters more here because a long-lived connection - * makes "just read it directly in the handler" look cheap. - */ - public static ArchRule platformDoesNotReachPersistence() { - return noClasses() - .that() - .resideInAPackage(PLATFORM + "..") - .should() - .dependOnClassesThat() - .resideInAnyPackage( - "dev.caskeleton.adapter.outbound..", - "jakarta.persistence..", - "org.springframework.data..") - .as("WS-ARCH-4: the websocket platform reaches the application, never persistence") - .allowEmptyShould(true); - } - - /** - * Nothing writes a raw close code. - * - *

A literal {@code close(1008, ...)} scattered through handlers is how the close-code catalog - * stops being the catalog. The codes are a published contract, and a client branches on them. - */ - public static ArchRule closeCodesComeFromTheCatalog() { - return noMethods() - .that() - .areDeclaredInClassesThat() - .resideInAPackage(PLATFORM + "..") - .and() - .areDeclaredInClassesThat() - .resideOutsideOfPackage(PLATFORM + ".error..") - .should() - .haveNameMatching("closeWithCode|sendCloseCode") - .as( - "WS-ARCH-5: close codes come from WebSocketCloseCode, not from a literal at the call" - + " site") - .allowEmptyShould(true); - } - - /** - * No Stable module may name an Advanced one. - * - *

The rule the design states and the one a feature flag cannot enforce. A flag decides whether - * an Advanced bean is created; it does nothing about a Stable class that imports an Advanced - * type, and such a class makes the Stable platform fail to compile without the Advanced code — at - * which point the separation exists only in the documentation. - */ - public static ArchRule stableDoesNotDependOnAdvanced() { - return noClasses() - .that() - .resideInAPackage(PLATFORM + "..") - .and() - .resideOutsideOfPackage(PLATFORM + ".advanced..") - .should() - .dependOnClassesThat() - .resideInAPackage(PLATFORM + ".advanced..") - .as( - "WS-ARCH-6: a Stable module may not name an Advanced one. A feature flag decides" - + " whether a bean is created; it does nothing about a compile-time edge, and one" - + " such edge makes Stable unbuildable without Advanced") - .allowEmptyShould(true); - } - - /** Every rule, for a consumer that wants the whole pack. */ - public static java.util.List all() { - return java.util.List.of( - handlersDoNotTouchTheTransport(), - runtimesAreMutuallyExclusive(), - reactiveRuntimeDoesNotNameServlet(), - platformDoesNotReachPersistence(), - closeCodesComeFromTheCatalog(), - stableDoesNotDependOnAdvanced()); - } -} diff --git a/src/adapter/inbound/websocket/src/testFixtures/java/dev/caskeleton/adapter/inbound/websocket/testkit/fault/WebSocketFaultInjector.java b/src/adapter/inbound/websocket/src/testFixtures/java/dev/caskeleton/adapter/inbound/websocket/testkit/fault/WebSocketFaultInjector.java deleted file mode 100644 index 06d975c0..00000000 --- a/src/adapter/inbound/websocket/src/testFixtures/java/dev/caskeleton/adapter/inbound/websocket/testkit/fault/WebSocketFaultInjector.java +++ /dev/null @@ -1,62 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.testkit.fault; - -import java.util.Objects; -import java.util.concurrent.atomic.AtomicReference; - -/** - * Arms one fault point for one command. - * - *

Called at every point a command passes through, whether or not a fault is armed. A handler - * that only consulted the injector where it expected a fault would be testing the injector. - */ -public final class WebSocketFaultInjector { - - private final AtomicReference armed = new AtomicReference<>(); - - /** Arms a point, replacing whatever was armed. */ - public void arm(WebSocketFaultPoint point) { - armed.set(Objects.requireNonNull(point, "point")); - } - - /** Disarms. */ - public void disarm() { - armed.set(null); - } - - /** - * Fails when this point is armed. - * - *

Single-shot: the point is disarmed as it fires, so a retry of the same command proceeds. A - * fault that stayed armed would make every attempt fail, which tests nothing about recovery. - * - * @throws InjectedWebSocketFault when this point was armed - */ - public void trigger(WebSocketFaultPoint point) { - if (armed.compareAndSet(point, null)) { - throw new InjectedWebSocketFault(point); - } - } - - /** Whether anything is armed. */ - public boolean armed() { - return armed.get() != null; - } - - /** The injected failure. */ - public static final class InjectedWebSocketFault extends RuntimeException { - - private static final long serialVersionUID = 1L; - - private final transient WebSocketFaultPoint point; - - InjectedWebSocketFault(WebSocketFaultPoint point) { - super("injected fault at " + point); - this.point = point; - } - - /** Where it fired. */ - public WebSocketFaultPoint point() { - return point; - } - } -} diff --git a/src/adapter/inbound/websocket/src/testFixtures/java/dev/caskeleton/adapter/inbound/websocket/testkit/fault/WebSocketFaultPoint.java b/src/adapter/inbound/websocket/src/testFixtures/java/dev/caskeleton/adapter/inbound/websocket/testkit/fault/WebSocketFaultPoint.java deleted file mode 100644 index 83d7a2fd..00000000 --- a/src/adapter/inbound/websocket/src/testFixtures/java/dev/caskeleton/adapter/inbound/websocket/testkit/fault/WebSocketFaultPoint.java +++ /dev/null @@ -1,39 +0,0 @@ -package dev.caskeleton.adapter.inbound.websocket.testkit.fault; - -/** - * Where a command's handling can be interrupted. - * - *

The ordering is the point. Between {@link #AFTER_APPLICATION_COMMIT_BEFORE_LEDGER} and {@link - * #AFTER_LEDGER_BEFORE_RESPONSE} lies the only window in which a crash produces an outcome nothing - * can reconstruct: the business work is durable and the ledger does not know it. Every other point - * is recoverable by replaying or by discarding, and this one is neither. - * - *

A WebSocket makes that window matter more than HTTP does. An HTTP client that loses its - * connection has one request to reason about; a WebSocket client reconnects and replays everything - * it never saw an answer for, all at once. - */ -public enum WebSocketFaultPoint { - - /** Before the message is decoded. Nothing has happened. */ - BEFORE_DECODE, - - /** Decoded and admitted, not yet handed to the application. */ - AFTER_ADMISSION_BEFORE_APPLICATION, - - /** Inside the application, before its transaction commits. */ - AFTER_APPLICATION_START_BEFORE_COMMIT, - - /** - * The application committed and the ledger has not recorded it. - * - *

The window. Replaying invents a result; re-running duplicates a committed write. Only the - * business data can settle it. - */ - AFTER_APPLICATION_COMMIT_BEFORE_LEDGER, - - /** The ledger recorded the outcome and the response has not been sent. */ - AFTER_LEDGER_BEFORE_RESPONSE, - - /** The response was queued and the socket died before it was written. */ - AFTER_RESPONSE_QUEUED_BEFORE_FLUSH -} diff --git a/src/adapter/inbound/websocket/src/testFixtures/java/dev/caskeleton/adapter/inbound/websocket/testkit/runtime/SlowConsumerContract.java b/src/adapter/inbound/websocket/src/testFixtures/java/dev/caskeleton/adapter/inbound/websocket/testkit/runtime/SlowConsumerContract.java index 6bc07f8d..e2d08ad3 100644 --- a/src/adapter/inbound/websocket/src/testFixtures/java/dev/caskeleton/adapter/inbound/websocket/testkit/runtime/SlowConsumerContract.java +++ b/src/adapter/inbound/websocket/src/testFixtures/java/dev/caskeleton/adapter/inbound/websocket/testkit/runtime/SlowConsumerContract.java @@ -39,8 +39,7 @@ import org.junit.jupiter.api.Timeout; public abstract class SlowConsumerContract { private static final WebSocketConnectionBudget BUDGET = - new WebSocketConnectionBudget( - 64 * 1024, 512 * 1024, 16, 100, 8 * 1024, Duration.ofHours(1), Duration.ofSeconds(90)); + new WebSocketConnectionBudget(512 * 1024, 8 * 1024); /** * A writer whose peer has stopped reading. diff --git a/src/adapter/inbound/websocket/src/testFixtures/java/dev/caskeleton/adapter/inbound/websocket/testkit/runtime/WebSocketFixtureApplication.java b/src/adapter/inbound/websocket/src/testFixtures/java/dev/caskeleton/adapter/inbound/websocket/testkit/runtime/WebSocketFixtureApplication.java index ebd3f6b4..50167983 100644 --- a/src/adapter/inbound/websocket/src/testFixtures/java/dev/caskeleton/adapter/inbound/websocket/testkit/runtime/WebSocketFixtureApplication.java +++ b/src/adapter/inbound/websocket/src/testFixtures/java/dev/caskeleton/adapter/inbound/websocket/testkit/runtime/WebSocketFixtureApplication.java @@ -3,7 +3,6 @@ package dev.caskeleton.adapter.inbound.websocket.testkit.runtime; import dev.caskeleton.adapter.inbound.websocket.budget.WebSocketConnectionBudget; import dev.caskeleton.adapter.inbound.websocket.outbound.GlobalBufferBudget; import dev.caskeleton.adapter.inbound.websocket.servlet.PlatformWebSocketHandler; -import java.time.Duration; import java.util.Optional; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.Bean; @@ -23,32 +22,25 @@ import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry * a lane sized realistically would spend its time pushing bytes rather than crossing one. */ @Configuration(proxyBeanMethods = false) -@EnableAutoConfiguration +// The lanes that boot this fixture test the handler library, not the STOMP channel, which the +// module otherwise auto-configures whenever it is on a servlet classpath. +@EnableAutoConfiguration( + excludeName = "dev.caskeleton.adapter.inbound.websocket.stomp.WebSocketConfig") @EnableWebSocket public class WebSocketFixtureApplication implements WebSocketConfigurer { /** Where the fixture endpoint listens. */ public static final String PATH = "/ws/v1/fixture"; - /** The frame bound this lane tests against. */ - public static final int MAX_FRAME_BYTES = 512; - - /** The reassembled-message bound this lane tests against. */ + /** The message bound this lane tests against. */ public static final int MAX_MESSAGE_BYTES = 1024; private final PlatformWebSocketHandler handler = new PlatformWebSocketHandler( - new WebSocketConnectionBudget( - MAX_FRAME_BYTES, - MAX_MESSAGE_BYTES, - 8, - 100, - 8 * 1024, - Duration.ofHours(1), - Duration.ofSeconds(90)), + new WebSocketConnectionBudget(MAX_MESSAGE_BYTES, 8 * 1024), new GlobalBufferBudget(1024 * 1024), // Echoes with a prefix, so a test can tell an answer from its own request and can prove - // the whole reassembled message arrived rather than the last fragment. + // the whole message arrived. (connectionId, message) -> Optional.of("echo:" + message)); /** The handler under test, for assertions about connection accounting. */ diff --git a/src/adapter/inbound/websocket/src/testFixtures/java/dev/caskeleton/adapter/inbound/websocket/testkit/runtime/WebSocketRuntimeContract.java b/src/adapter/inbound/websocket/src/testFixtures/java/dev/caskeleton/adapter/inbound/websocket/testkit/runtime/WebSocketRuntimeContract.java index 6b77ef17..8ddc3e61 100644 --- a/src/adapter/inbound/websocket/src/testFixtures/java/dev/caskeleton/adapter/inbound/websocket/testkit/runtime/WebSocketRuntimeContract.java +++ b/src/adapter/inbound/websocket/src/testFixtures/java/dev/caskeleton/adapter/inbound/websocket/testkit/runtime/WebSocketRuntimeContract.java @@ -50,7 +50,7 @@ public abstract class WebSocketRuntimeContract { @Test @DisplayName("a message inside the bound round-trips whole") void messageWithinBoundRoundTrips() throws Exception { - String payload = "x".repeat(WebSocketFixtureApplication.MAX_FRAME_BYTES - 10); + String payload = "x".repeat(WebSocketFixtureApplication.MAX_MESSAGE_BYTES - 10); try (Peer peer = Peer.connect(endpoint())) { peer.send(payload); diff --git a/src/adapter/outbound/cache-redis/CLAUDE.md b/src/adapter/outbound/cache-redis/CLAUDE.md index 56ad12d3..22e57845 100644 --- a/src/adapter/outbound/cache-redis/CLAUDE.md +++ b/src/adapter/outbound/cache-redis/CLAUDE.md @@ -16,16 +16,16 @@ Package root: `dev.caskeleton.adapter.outbound.cache`. - Own canonical physical keys, digesting, codec/envelope, program catalog, typed Redis atomic facades, runtime client adaptation, and capability-specific failure semantics. - Implement absolute soft/hard expiry and deterministic bounded jitter behind the semantic cache - port; cache-aside/source protection policy remains framework-free in `application-core`, but `CacheAsideExecutor` itself is currently deprecated because shipped bootstrap does not compose it. + port (`CacheRegionPort`). - Implement the provider-neutral `EdgeRateLimitPort` with dedicated coordination Redis settings, connection/admission, private keys and versioned atomic programs. - Keep the legacy cache router isolated while consumers migrate to semantic ports. - Reuse `adapter:outbound:support` for shared outbound concerns. - Depend on `:adapter:outbound:redis-runtime` for the shared topology client, connection lifecycle, low-level gateway and conditional Redis runtime composition used by the semantic adapters. -- Keep the general-purpose typed SDK in the separate optional `:adapter:outbound:redis-sdk` leaf. - This semantic adapter has no production dependency on that SDK; it is test-only here while the - existing SDK contract suite is migrated to its owning leaf. +- Keep the general-purpose typed SDK in the separate library leaf `:adapter:outbound:redis-sdk` + (see its `README.md`). This leaf does not depend on it in any configuration, tests included; the + SDK's tests and lanes live in that leaf. ## Redis runtime and optional typed SDK (`…cache.redis.sdk`) @@ -37,7 +37,7 @@ different. `cache-redis` depends on this leaf. - `:adapter:outbound:redis-sdk` owns the optional general-purpose typed API, command catalog/policy, operation budgets, command guard, raw/admin surfaces, programmability and extensions. - `cache-redis` does **not** depend on it in production. + `cache-redis` does **not** depend on it, in production or in tests. - The semantic cache/idempotency/rate-limit/lease/realtime adapters in this leaf intentionally call the runtime gateway through their own closed semantic programs/contracts. They do not pass through `CommandPolicyGuard`, and `redis-command-policy.yml` does not control those semantic adapters. @@ -86,8 +86,8 @@ in `docs/superpowers/plans/2026-08-07-redis-wrapper-typed-api-status.md`. only a pre-filter — and all of them build commands through `ExtensionCommandRunner` so the guard sees their keys. Search is the exception that proves it: an index is not a key, so its name is namespaced by `LettuceRedisSearchOperations` itself. -- `RedisSdkModuleBoundaryTest` scans both `redis-runtime` and `redis-sdk` source roots and - enforces the internal package graph, driver containment, the absence of an arbitrary string +- `RedisSdkModuleBoundaryTest` (in `redis-sdk`) scans both `redis-runtime` and `redis-sdk` source + roots and enforces the internal package graph, driver containment, the absence of an arbitrary string command surface, and the designed module list. - Decisions that must not be changed without revisiting the design: no unbounded `entries`, `members`, `rangeAll`, or `keys`; no optional R2 permit or budget; no arbitrary command string @@ -113,17 +113,21 @@ in `docs/superpowers/plans/2026-08-07-redis-wrapper-typed-api-status.md`. ## Tests -Focused tests use fakes for contract, key, catalog, and typed-facade behavior. R1/R2 promotion -requires a separate real Redis service lane; it may never be silently skipped when selected. +Focused tests drive the semantic adapters against the in-memory gateway from +`testFixtures(project(':adapter:outbound:redis-runtime'))` (`InMemoryGatewayAccess`), the one fake +of `RedisCommandGateway`. R1/R2 promotion requires a separate real Redis service lane; it may never +be silently skipped when selected. -`redisTopologyTest` is the only real-server lane, declared through `ca.strict-test-lane`. It is -opt-in and fail-closed in five ways: the lane must be one of `standalone`, `sentinel`, `cluster`, -`tls`; the endpoint properties must be present (`sentinel` additionally needs -`redis.topology.master`, `tls` needs `redis.topology.trust-material`); a run that discovers or -executes zero tests fails (the convention, not this leaf, owns that); the classes the lane exists to -run must actually have run; and a skipped test fails the run rather than counting as executed. -`tls` is a lane, not a deployment mode — its shape is standalone and the task maps it so, because -what it qualifies is the transport. +`redisTopologyTest` is the only real-server lane, declared through `ca.redis-topology-lane`. This +leaf declares `standalone` and `cluster` (`LiveRedisSemanticPortsTest`); `redis-runtime` and +`redis-sdk` declare their own lanes for their own classes. It is opt-in and fail-closed: the mode +must be one of `standalone`, `sentinel`, `cluster`, `tls` and one this leaf declares; the endpoint +properties must be present (`sentinel` additionally needs `redis.topology.master`, `tls` needs +`redis.topology.trust-material`); a run that discovers or executes zero tests fails (the +convention, not this leaf, owns that); the classes the leaf names in `redisTopologyLane` must +actually have run; and a skipped test fails the run rather than counting as executed. `tls` is a +lane, not a deployment mode — its shape is standalone and the task maps it so, because what it +qualifies is the transport. Two former checks are gone. A scan of the test sources for the literal text `@Tag("redis-topology")` only improved the message for a failure `failOnNoDiscoveredTests` already produced, and a comment @@ -135,9 +139,9 @@ containing the same text satisfied it. A hand-maintained per-mode floor on the e `RedisSdkAutoConfiguration` now belongs to `:adapter:outbound:redis-runtime`. It is the only place Redis settings and the shared runtime substrate come into existence, and it exists only while -`app.redis.enabled` (env `APP_REDIS_ENABLED`) is true. It builds the topology client, connection -owner and health contributors; `RedisCapabilityConfig` in `app-bootstrap` composes the semantic -ports in this leaf on top of that runtime. +`app.redis.enabled` (env `APP_REDIS_ENABLED`, default `true` — the module is on when present) is +true. It builds the topology client, connection owner and health contributors; `RedisCapabilityConfig` +in this leaf (its own `AutoConfiguration.imports`) composes the semantic ports on top of that runtime. The optional `:adapter:outbound:redis-sdk` is not auto-composed by the shipped application. Its `RedisStartupProbe` is a library API, not an implicit production guard. In particular there is no @@ -161,9 +165,9 @@ that slot. Routed leases are never pooled: a pooled connection is pinned to the node. `RedisSdkSettings` -must never carry a class-level `@ConfigurationProperties`: the bootstrap's application-wide -`@ConfigurationPropertiesScan` would then register it in every deployment, so a service that runs -no Redis would bind Redis configuration. `RedisOptionalityContractTest` in `app-bootstrap` enforces -that. Role selectors (cache binding, session auth-mode, idempotency/lease/rate-limit provider) -choose which capabilities compose; none of them activates Redis, and selecting one while the global -switch is off is refused by `RedisActivationValidator`. +must never carry a class-level `@ConfigurationProperties`: `RedisSdkAutoConfiguration` binds it, so +`APP_REDIS_ENABLED=false` binds no Redis configuration at all. A properties scan that reached this +package would bind it regardless (bootstrap's `@ConfigurationPropertiesScan` lists only +`dev.caskeleton.bootstrap.*` packages). Role selectors (cache binding, session auth-mode, idempotency/lease/rate-limit provider) +choose which capabilities compose; none of them activates Redis, and with the global switch off +this module contributes no bean at all. diff --git a/src/adapter/outbound/cache-redis/README.md b/src/adapter/outbound/cache-redis/README.md index b61dddb9..2f72e69c 100644 --- a/src/adapter/outbound/cache-redis/README.md +++ b/src/adapter/outbound/cache-redis/README.md @@ -14,14 +14,54 @@ The default application therefore does not acquire the optional SDK's command po selecting a semantic Redis capability. Semantic adapters call the runtime gateway directly and own their own correctness rules. +## Using it as a capability module — what it provides, the one line, the env keys + +The web-only default composition does not ship this module: `app-bootstrap/build.gradle` lists it +as a commented `runtimeOnly` line. A service selects it by uncommenting that one line, and deleting +the line removes everything below: + +```groovy +runtimeOnly project(':adapter:outbound:cache-redis') // brings :adapter:outbound:redis-runtime +``` + +**Provides**, all registered by this module itself: + +- the port implementations the role selectors ask for — `CacheRegionPort` (cache), + `EdgeRateLimitPort` (rate limit), `DistributedLeasePort` (lease), `IdempotencyStorePort` + (idempotency; the application builds the executor over it); +- `RedisCapabilityConfig` (`AutoConfiguration.imports`, after `RedisSdkAutoConfiguration`). With + `APP_REDIS_ENABLED=false` neither it nor redis-runtime's `RedisSdkAutoConfiguration` contributes a + bean — no settings, client, connection, thread or health contributor. The module pulls no Spring + Data Redis, so there is no Boot Redis auto-configuration to exclude; +- the readiness contribution `RedisReadinessGroupPostProcessor` (this module's `spring.factories`): + `redisRequired` joins the readiness group only when a correctness role selects Redis; +- the shipped settings `config/module-defaults/cache-redis.yml` — `app.redis.enabled`, + `app.rate-limit.*`, and the Redis parts of `ca-skeleton.capabilities.*` (cache, lease, rate-limit, + the Redis idempotency store's tuning). The support leaf's `ModuleDefaultsEnvironmentPostProcessor` + loads it below every application setting. + +The application provides `SecretSourcePort` and `Clock`. + +**Env keys** (`src/.env.example`, registry `docs/registries/env-keys.yaml`): + +| Purpose | Keys | +|---|---| +| Switch | `APP_REDIS_ENABLED` (default true; `false` turns the present module off) | +| Connection | `APP_REDIS_MODE`, `APP_REDIS_NODES`, `APP_REDIS_DATABASE`, `APP_REDIS_SENTINEL_*`, `APP_REDIS_TLS_*`, `APP_REDIS_AUTHENTICATION_*` (credential references) | +| Namespace | `APP_REDIS_NAMESPACE_ENVIRONMENT`, `APP_REDIS_NAMESPACE_SERVICE`, `APP_REDIS_NAMESPACE_DOMAIN` | +| Roles | `APP_CACHE_CANONICAL_DEFAULT_PROVIDER`, `APP_RATE_LIMIT_PROVIDER`, `APP_LEASE_PROVIDER`, `APP_IDEMPOTENCY_PROVIDER=redis` | +| Role tuning | `APP_CACHE_REDIS_*`, `APP_RATE_LIMIT_*`, `APP_LEASE_REDIS_*`, `APP_IDEMPOTENCY_REDIS_COMMAND_TIMEOUT` | +| Prod secrets (per selected role) | `APP_CACHE_REDIS_PASSWORD`, `APP_CACHE_REDIS_KEY_HMAC_SECRET`, `APP_RATE_LIMIT_REDIS_PASSWORD`, `APP_RATE_LIMIT_REDIS_KEY_HMAC_SECRET`, `APP_IDEMPOTENCY_REDIS_KEY_HMAC_SECRET`, `APP_LEASE_REDIS_KEY_HMAC_SECRET` | + ## Activation and composition -Redis has one global activation switch: +Redis is on when this module is present. It has one off switch: -`app.redis.enabled=true` / `APP_REDIS_ENABLED=true`. +`app.redis.enabled=false` / `APP_REDIS_ENABLED=false` (default `true`). -A semantic role does **not** activate Redis by itself. The composition root rejects a deployment -that selects Redis for a role while the global switch is off. +A semantic role does **not** activate Redis by itself: with the switch off this module +contributes no bean at all, whatever a role selector says. Redis idempotency refuses +`ca-skeleton.capabilities.idempotency.key-version` other than 1 at startup (no dual-read yet). Current role selectors are: @@ -54,9 +94,15 @@ Connection lane limits and command queue limits are different contracts. In part - `app.redis.capacity.maximum-in-flight-commands` bounds the per-connection command queue. - `app.redis.capacity.maximum-script-connections` bounds physical SCRIPT lane connections (default 8). +- `app.redis.lifecycle.acquire-timeout` (default 2s) is how long a borrow waits for a returned + connection when its lane is full. The second limit exists so a burst of semantic Lua calls cannot turn a command-capacity number such -as 64 into 64 physical Redis sockets. +as 64 into 64 physical Redis sockets. It bounds connections, not callers: a lease holds a connection +for one script round trip, so the ninth concurrent caller waits for one to come back instead of +being refused. Only a borrow still waiting when the acquire timeout runs out is refused, and that +refusal is a `RedisCommandRejectedException` whose metadata is not ambiguous — no command was ever +sent. ## Script ACL startup probe @@ -121,7 +167,10 @@ Rate-limit failures remain fail-closed according to the application contract. ## Idempotency semantics The Redis idempotency adapter stores owner-safe claim state and executes claim/transition/release -programs atomically. +programs atomically. `RedisIdempotencyConfig` contributes only the `IdempotencyStorePort`; the +`IdempotencyExecutor` and its lifecycle policy (lease, replay TTL, retention, codec id, policy +revision) come from app-bootstrap `IdempotencySettings`. This leaf reads only `key-version` and +`command-timeout` under `ca-skeleton.capabilities.idempotency`. Redis `TIME` determines lease deadlines. A failure after a command may have executed is returned as an indeterminate outcome; the adapter does not convert an ambiguous write into a clean @@ -153,7 +202,9 @@ turning a Redis outage into a log-flood outage. ## Optional typed SDK `:adapter:outbound:redis-sdk` contains the broader typed command surface, command policy, raw/admin -and extension machinery. It is a separate optional production leaf. +and extension machinery. It is a separate library leaf that service code takes with +`implementation`; see `src/adapter/outbound/redis-sdk/README.md`. This leaf does not depend on it, +in production or in tests. Its policy file and optional startup/library probes apply only when that SDK is deliberately added to a composition. Do not infer SDK command-policy enforcement from the presence of a semantic cache @@ -168,7 +219,7 @@ Useful focused checks: ./gradlew :adapter:outbound:redis-runtime:check ./gradlew :app-bootstrap:test --tests '*RedisSemanticScriptAclProbeTest' ./gradlew :app-bootstrap:verifyEnvKeys -./gradlew verifyRuntimeModuleRegistry verifyRuntimeModuleMembership +./gradlew architectureCheck ``` Live Redis/topology qualification remains separate from fast unit tests. A release claim for a diff --git a/src/adapter/outbound/cache-redis/build.gradle b/src/adapter/outbound/cache-redis/build.gradle index 1d0d31fb..41dd7cde 100644 --- a/src/adapter/outbound/cache-redis/build.gradle +++ b/src/adapter/outbound/cache-redis/build.gradle @@ -7,8 +7,8 @@ plugins { // Semantic Redis capability adapter. // // Shared connection/topology/gateway machinery is owned by :adapter:outbound:redis-runtime. -// The general-purpose typed SDK is a separate optional production leaf -// (:adapter:outbound:redis-sdk) and is intentionally absent from this module's production graph. +// The general-purpose typed SDK (:adapter:outbound:redis-sdk) is a separate library leaf and is +// absent from every configuration of this module, tests included. dependencies { // Registered edges used by the semantic adapters and their composition contracts. implementation project(':application-core') @@ -16,10 +16,11 @@ dependencies { implementation project(':adapter:outbound:support') implementation project(':adapter:outbound:redis-runtime') - // The general-purpose typed SDK is intentionally not a production dependency. Its tests remain - // here temporarily so the split preserves the existing contract and topology qualification - // suite without making the shipped semantic Redis adapter depend on the optional SDK. - testImplementation project(':adapter:outbound:redis-sdk') + // The in-memory gateway and the topology endpoint the semantic adapter tests run against. + testImplementation testFixtures(project(':adapter:outbound:redis-runtime')) + // RedisReadinessGroupPostProcessorTest boots a real actuator health context: the readiness group + // and its membership validation are what the post-processor exists to keep bootable. + testImplementation 'org.springframework.boot:spring-boot-starter-actuator' implementation 'org.springframework.boot:spring-boot-autoconfigure' // The role-aware health contributors are HealthIndicators; the readiness probe is the only @@ -30,10 +31,9 @@ dependencies { // does not need it from here — the app already has Jackson — so compileOnly is the honest scope. compileOnly 'com.fasterxml.jackson.core:jackson-annotations' implementation 'io.lettuce:lettuce-core' - // Reactor is in the public signature of sdk.api.reactive, and it was reaching this module only - // transitively through lettuce-core. A driver upgrade that stopped exposing it would have - // broken compilation of the SDK's own published API, so it is declared directly. - implementation 'io.projectreactor:reactor-core' + // The activation guard raises typed startup failures (support.startup), which log with + // StructuredArguments. + implementation libs.logstash.logback.encoder implementation 'org.slf4j:slf4j-api' // Deliberately absent: @@ -45,6 +45,10 @@ dependencies { // Zero imports. } -// Redis topology qualification is opt-in and owned by `ca.redis-topology-lane`. The Java -// convention owns mode/property validation, tag selection, TLS deployment mapping, required-class -// coverage and no-skip enforcement; this leaf keeps only its dependency declaration surface. +// Redis topology qualification is opt-in and owned by `ca.redis-topology-lane`: mode/property +// validation, tag selection, TLS mapping and no-skip enforcement. The leaf names the classes each +// of its lanes exists to run. Sentinel and TLS are qualified by redis-runtime and redis-sdk. +redisTopologyLane { + requiredClasses 'standalone', 'LiveRedisSemanticPortsTest' + requiredClasses 'cluster', 'LiveRedisSemanticPortsTest' +} diff --git a/src/adapter/outbound/cache-redis/gradle.lockfile b/src/adapter/outbound/cache-redis/gradle.lockfile index 062d16a3..7e0de2cd 100644 --- a/src/adapter/outbound/cache-redis/gradle.lockfile +++ b/src/adapter/outbound/cache-redis/gradle.lockfile @@ -4,7 +4,10 @@ biz.aQute.bnd:biz.aQute.bnd.annotation:7.1.0=testCompileClasspath ch.qos.logback:logback-classic:1.5.38=testCompileClasspath,testRuntimeClasspath ch.qos.logback:logback-core:1.5.38=testCompileClasspath,testRuntimeClasspath -com.fasterxml.jackson.core:jackson-annotations:2.21=compileClasspath,testCompileClasspath,testRuntimeClasspath +com.fasterxml.jackson.core:jackson-annotations:2.21=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +com.fasterxml.jackson.core:jackson-core:2.21.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +com.fasterxml.jackson.core:jackson-databind:2.21.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +com.fasterxml.jackson:jackson-bom:2.21.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,testAnnotationProcessor com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,testAnnotationProcessor com.github.spotbugs:spotbugs-annotations:4.10.2=spotbugs @@ -42,6 +45,8 @@ io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,testAnnota io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,testAnnotationProcessor io.lettuce:lettuce-core:6.8.2.RELEASE=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath io.micrometer:micrometer-commons:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +io.micrometer:micrometer-core:1.16.7=testCompileClasspath,testRuntimeClasspath +io.micrometer:micrometer-jakarta9:1.16.7=testCompileClasspath,testRuntimeClasspath io.micrometer:micrometer-observation:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath io.netty:netty-buffer:4.2.17.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath io.netty:netty-codec-base:4.2.17.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath @@ -60,6 +65,7 @@ javax.inject:javax.inject:1=annotationProcessor,testAnnotationProcessor jaxen:jaxen:2.0.6=spotbugs net.bytebuddy:byte-buddy-agent:1.17.8=testCompileClasspath,testRuntimeClasspath net.bytebuddy:byte-buddy:1.17.8=testCompileClasspath,testRuntimeClasspath +net.logstash.logback:logstash-logback-encoder:8.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath net.minidev:accessors-smart:2.6.0=testCompileClasspath,testRuntimeClasspath net.minidev:json-smart:2.6.0=testCompileClasspath,testRuntimeClasspath net.sf.saxon:Saxon-HE:12.9=checkstyle,spotbugs @@ -90,6 +96,7 @@ org.codehaus.plexus:plexus-container-default:2.1.0=checkstyle org.codehaus.plexus:plexus-utils:3.3.0=checkstyle org.dom4j:dom4j:2.2.0=spotbugs org.hamcrest:hamcrest:3.0=testCompileClasspath,testRuntimeClasspath +org.hdrhistogram:HdrHistogram:2.2.2=testRuntimeClasspath org.javassist:javassist:3.28.0-GA=checkstyle org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,compileClasspath,runtimeClasspath,testAnnotationProcessor,testCompileClasspath,testRuntimeClasspath org.junit.jupiter:junit-jupiter-api:6.0.3=testCompileClasspath,testRuntimeClasspath @@ -101,6 +108,7 @@ 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.1.0=spotbugs +org.latencyutils:LatencyUtils:2.0.3=testRuntimeClasspath org.mockito:mockito-core:5.20.0=mockitoAgent,testCompileClasspath,testRuntimeClasspath org.mockito:mockito-junit-jupiter:5.20.0=testCompileClasspath,testRuntimeClasspath org.objenesis:objenesis:3.3=testRuntimeClasspath @@ -123,16 +131,22 @@ org.slf4j:jul-to-slf4j:2.0.18=testCompileClasspath,testRuntimeClasspath org.slf4j:slf4j-api:2.0.18=compileClasspath,runtimeClasspath,spotbugs,spotbugsSlf4j,testCompileClasspath,testRuntimeClasspath org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j org.slf4j:slf4j-simple:2.0.18=checkstyle +org.springframework.boot:spring-boot-actuator-autoconfigure:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-actuator:4.0.8=testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-autoconfigure:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-configuration-processor:4.0.8=annotationProcessor org.springframework.boot:spring-boot-health:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-http-converter:4.0.8=testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-jackson:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-micrometer-metrics:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-micrometer-observation:4.0.8=testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-resttestclient:4.0.8=testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-servlet:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-actuator:4.0.8=testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-starter-jackson-test:4.0.8=testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-starter-jackson:4.0.8=testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-starter-logging:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-micrometer-metrics:4.0.8=testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-starter-test:4.0.8=testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-starter-tomcat-runtime:4.0.8=testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-starter-tomcat:4.0.8=testCompileClasspath,testRuntimeClasspath diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisCacheConfig.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisCacheConfig.java index 8bd179fe..92f04fd5 100644 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisCacheConfig.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisCacheConfig.java @@ -14,8 +14,8 @@ import org.springframework.context.annotation.Configuration; * The Redis-backed semantic cache region. * *

One capability, one configuration class (BOOT-007). It contributes nothing unless the cache - * binding names Redis, and it is only reachable at all while the Redis master switch is on, because - * {@link RedisCapabilityConfig} imports it and carries that switch. + * binding names Redis, and it is only reachable at all while the Redis switch is on, because {@link + * RedisCapabilityConfig} imports it and carries that switch. */ @Configuration(proxyBeanMethods = false) class RedisCacheConfig { diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisCapabilityConfig.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisCapabilityConfig.java index ee53a2f9..b268d693 100644 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisCapabilityConfig.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisCapabilityConfig.java @@ -23,10 +23,9 @@ import org.springframework.context.annotation.Import; *

Each port is conditional on its own selector, so selecting Redis for leases does not build an * idempotency store nobody asked for. All of them are conditional on {@link RedisRuntimeOwner}, * which exists only while the global switch is on — a role selector never activates Redis by - * itself, and {@code RedisActivationValidator} refuses the contradiction of a role that selects - * Redis while the switch is off. + * itself. With the switch off this module contributes no bean at all. * - *

This class is the composition point only: it holds the master switch, binds the settings once, + *

This class is the composition point only: it holds the switch, binds the settings once, * bridges the secret backend into the SDK, and imports one configuration per capability. It used to * hold all four capabilities plus rate-limit policy compilation and the key digest — 376 lines, in * a leaf whose Notification platform had already been split into nine focused configurations. The @@ -39,10 +38,9 @@ import org.springframework.context.annotation.Import; @AutoConfiguration(after = RedisSdkAutoConfiguration.class) @EnableConfigurationProperties(RedisCapabilitySettings.class) // The global switch, not a role selector. A role selector says which capability composes; it -// never says Redis exists, and RedisActivationValidator refuses the contradiction of one -// without the other. +// never says Redis exists. @ConditionalOnProperty(prefix = "app.redis", name = "enabled", havingValue = "true") -// Imported rather than scanned: the master switch above gates this class, and an @Import only +// Imported rather than scanned: the switch above gates this class, and an @Import only // registers what a registered configuration asked for. Component scanning would have made each // capability configuration independently discoverable and the switch advisory. @Import({ diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisCapabilitySettings.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisCapabilitySettings.java index c0899a50..aa498a17 100644 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisCapabilitySettings.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisCapabilitySettings.java @@ -378,22 +378,16 @@ public class RedisCapabilitySettings { } } - /** Owner-safe request replay (V2) provider composition. */ + /** + * The Redis idempotency store's own knobs. The provider-neutral lifecycle settings (lease, replay + * TTL, retention, codec, policy revision) under the same prefix are bound by the composition + * root, which builds the executor. + */ public static class Idempotency { private String provider = "disabled"; private int keyVersion = 1; private Duration commandTimeout = Duration.ofMillis(200); - private Duration processingLease = Duration.ofSeconds(30); - private Duration replayTtl = Duration.ofHours(24); - private Duration failureRetention = Duration.ofHours(24); - private String responseCodecId = "json-v2"; - - // The owner-safe claim carries this as a number, not a name: the store writes it into the - // record and compares it there, and `IdempotencyClaimRequest` rejects anything below 1. It - // used to be the string "request-replay-v2", which nothing read, because the only executor - // that could have read it was written against a contract nothing implements. - private int policyRevision = 2; public boolean redisSelected() { return "redis".equalsIgnoreCase(provider); @@ -422,45 +416,5 @@ public class RedisCapabilitySettings { public void setCommandTimeout(Duration commandTimeout) { this.commandTimeout = commandTimeout; } - - public Duration getProcessingLease() { - return processingLease; - } - - public void setProcessingLease(Duration processingLease) { - this.processingLease = processingLease; - } - - public Duration getReplayTtl() { - return replayTtl; - } - - public void setReplayTtl(Duration replayTtl) { - this.replayTtl = replayTtl; - } - - public Duration getFailureRetention() { - return failureRetention; - } - - public void setFailureRetention(Duration failureRetention) { - this.failureRetention = failureRetention; - } - - public String getResponseCodecId() { - return responseCodecId; - } - - public void setResponseCodecId(String responseCodecId) { - this.responseCodecId = responseCodecId; - } - - public int getPolicyRevision() { - return policyRevision; - } - - public void setPolicyRevision(int policyRevision) { - this.policyRevision = policyRevision; - } } } diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisIdempotencyConfig.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisIdempotencyConfig.java index 81296082..ff0b413c 100644 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisIdempotencyConfig.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisIdempotencyConfig.java @@ -4,19 +4,17 @@ import dev.caskeleton.adapter.outbound.cache.redis.idempotency.IdempotencyScript import dev.caskeleton.adapter.outbound.cache.redis.idempotency.RedisIdempotencyStoreAdapter; import dev.caskeleton.adapter.outbound.cache.redis.sdk.config.RedisSdkSettings; import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeOwner; -import dev.caskeleton.application.idempotency.v2.IdempotencyExecutorV2; -import dev.caskeleton.application.idempotency.v2.IdempotencyStorePortV2; +import dev.caskeleton.adapter.outbound.support.startup.StartupPhase; +import dev.caskeleton.adapter.outbound.support.startup.StartupValidationContext; +import dev.caskeleton.application.idempotency.IdempotencyStorePort; import java.time.Clock; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** - * The Redis-backed owner-safe idempotency store and the executor that drives it. - * - *

Both beans stay together because the selection guard in {@code - * IdempotencyProviderSelectionConfig} refuses a store with no executor: they are one selection, not - * two (BOOT-007). + * The Redis-backed owner-safe idempotency store. Redis contributes the store only; the executor + * that drives it is assembled once by the composition root from the provider-neutral settings. */ @Configuration(proxyBeanMethods = false) class RedisIdempotencyConfig { @@ -28,18 +26,28 @@ class RedisIdempotencyConfig { * @param sdk the Redis SDK settings, which own the namespace * @param capabilities the capability settings * @param clock the clock lease deadlines are measured against - * @return the V2 store port + * @return the store port */ @Bean @ConditionalOnProperty( name = "ca-skeleton.capabilities.idempotency.provider", havingValue = "redis") - IdempotencyStorePortV2 redisIdempotencyStore( + IdempotencyStorePort redisIdempotencyStore( RedisRuntimeOwner owner, RedisSdkSettings sdk, RedisCapabilitySettings capabilities, Clock clock) { RedisCapabilitySettings.Idempotency idempotency = capabilities.getIdempotency(); + if (idempotency.getKeyVersion() != 1) { + // A new key version would orphan every replay record written under the old one; refused + // until a migration can read the previous keyspace during the replay-retention window. + StartupValidationContext.forPhase(StartupPhase.ADAPTER_ENABLEMENT) + .reject("ca-skeleton.capabilities.idempotency.key-version=" + idempotency.getKeyVersion()) + .failIfViolated( + "Redis idempotency key-version rotation is unsupported without dual-read", + "keep ca-skeleton.capabilities.idempotency.key-version=1 until a migration can read " + + "the previous keyspace during the replay-retention window."); + } return new RedisIdempotencyStoreAdapter( owner, new RedisIdempotencyStoreAdapter.IdempotencyKeys( @@ -48,32 +56,4 @@ class RedisIdempotencyConfig { clock, idempotency.getCommandTimeout()); } - - /** - * The request-replay lifecycle driven over the selected owner-safe store. - * - *

Provider-neutral by type — it depends on {@link IdempotencyStorePortV2}, not on Redis — and - * composed here because this is where the settings behind it are bound. A selection that produced - * the store and no executor produced a store nothing could drive, which is what {@code - * IdempotencyProviderSelectionConfig} refuses. - * - * @param store the selected owner-safe store - * @param capabilities the capability settings - * @return the owner-safe request-replay executor - */ - @Bean - @ConditionalOnProperty( - name = "ca-skeleton.capabilities.idempotency.provider", - havingValue = "redis") - IdempotencyExecutorV2 idempotencyExecutorV2( - IdempotencyStorePortV2 store, RedisCapabilitySettings capabilities) { - RedisCapabilitySettings.Idempotency idempotency = capabilities.getIdempotency(); - return new IdempotencyExecutorV2( - store, - idempotency.getProcessingLease(), - idempotency.getReplayTtl(), - idempotency.getFailureRetention(), - idempotency.getResponseCodecId(), - idempotency.getPolicyRevision()); - } } diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/redis/RedisReadinessGroupPostProcessor.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisReadinessGroupPostProcessor.java similarity index 80% rename from src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/redis/RedisReadinessGroupPostProcessor.java rename to src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisReadinessGroupPostProcessor.java index 373b5adf..b9bb2d81 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/redis/RedisReadinessGroupPostProcessor.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisReadinessGroupPostProcessor.java @@ -1,9 +1,8 @@ -package dev.caskeleton.bootstrap.autoconfigure.redis; +package dev.caskeleton.adapter.outbound.cache.redis.capability; import dev.caskeleton.adapter.outbound.cache.redis.sdk.config.RedisCorrectnessRoles; -import dev.caskeleton.bootstrap.runtime.ReadinessGroup; -import dev.caskeleton.bootstrap.runtime.SecretSourceValidator; -import dev.caskeleton.bootstrap.runtime.startup.StartupOrder; +import dev.caskeleton.adapter.outbound.support.startup.ReadinessGroup; +import dev.caskeleton.adapter.outbound.support.startup.StartupOrder; import org.springframework.boot.EnvironmentPostProcessor; import org.springframework.boot.SpringApplication; import org.springframework.core.Ordered; @@ -45,15 +44,14 @@ public class RedisReadinessGroupPostProcessor implements EnvironmentPostProcesso } private static boolean redisEnabled(ConfigurableEnvironment environment) { - return Boolean.parseBoolean( - environment.getProperty(SecretSourceValidator.REDIS_ENABLED_PROPERTY, "false")); + return Boolean.parseBoolean(environment.getProperty("app.redis.enabled", "false")); } @Override public int getOrder() { - // After config data: the readiness group this appends to is defined in application.yml, and - // reading it before that file is loaded would append to an empty string and silently drop - // readinessState and db from the group. + // After config data and the module defaults: the readiness group this appends to is defined in + // the application's configuration and the role selectors in this module's defaults; reading + // either earlier would append to an empty string or miss a selected role. return StartupOrder.READINESS_REDIS; } } diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/RedisIdempotencyStoreAdapter.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/RedisIdempotencyStoreAdapter.java index 408433c0..0ada2911 100644 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/RedisIdempotencyStoreAdapter.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/RedisIdempotencyStoreAdapter.java @@ -6,23 +6,23 @@ import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisNamespace; import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisConnectionKind; import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisLease; import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeOwner; +import dev.caskeleton.application.idempotency.IdempotencyClaimAttempt; +import dev.caskeleton.application.idempotency.IdempotencyClaimOutcome; +import dev.caskeleton.application.idempotency.IdempotencyClaimRequest; +import dev.caskeleton.application.idempotency.IdempotencyCompleteOutcome; +import dev.caskeleton.application.idempotency.IdempotencyFailOutcome; +import dev.caskeleton.application.idempotency.IdempotencyFailureDisposition; +import dev.caskeleton.application.idempotency.IdempotencyInspection; +import dev.caskeleton.application.idempotency.IdempotencyInspectionOutcome; +import dev.caskeleton.application.idempotency.IdempotencyInspectionRequest; +import dev.caskeleton.application.idempotency.IdempotencyMutationResult; +import dev.caskeleton.application.idempotency.IdempotencyOwner; +import dev.caskeleton.application.idempotency.IdempotencyReleaseOutcome; +import dev.caskeleton.application.idempotency.IdempotencyRenewOutcome; +import dev.caskeleton.application.idempotency.IdempotencyScopeDigest; +import dev.caskeleton.application.idempotency.IdempotencyStartOutcome; +import dev.caskeleton.application.idempotency.IdempotencyStorePort; import dev.caskeleton.application.idempotency.StoredResponse; -import dev.caskeleton.application.idempotency.v2.IdempotencyClaimAttempt; -import dev.caskeleton.application.idempotency.v2.IdempotencyClaimOutcome; -import dev.caskeleton.application.idempotency.v2.IdempotencyClaimRequest; -import dev.caskeleton.application.idempotency.v2.IdempotencyCompleteOutcome; -import dev.caskeleton.application.idempotency.v2.IdempotencyFailOutcome; -import dev.caskeleton.application.idempotency.v2.IdempotencyFailureDisposition; -import dev.caskeleton.application.idempotency.v2.IdempotencyInspection; -import dev.caskeleton.application.idempotency.v2.IdempotencyInspectionOutcome; -import dev.caskeleton.application.idempotency.v2.IdempotencyInspectionRequest; -import dev.caskeleton.application.idempotency.v2.IdempotencyMutationResult; -import dev.caskeleton.application.idempotency.v2.IdempotencyOwner; -import dev.caskeleton.application.idempotency.v2.IdempotencyReleaseOutcome; -import dev.caskeleton.application.idempotency.v2.IdempotencyRenewOutcome; -import dev.caskeleton.application.idempotency.v2.IdempotencyScopeDigest; -import dev.caskeleton.application.idempotency.v2.IdempotencyStartOutcome; -import dev.caskeleton.application.idempotency.v2.IdempotencyStorePortV2; import dev.caskeleton.application.transaction.OperationId; import java.security.SecureRandom; import java.time.Clock; @@ -47,10 +47,10 @@ import java.util.concurrent.TimeUnit; * effect, while a caller told "indeterminate" inspects with the same attempt and discovers what * actually happened. This adapter never converts an ambiguous write into a clean answer. * - *

{@code application-core} sees {@link IdempotencyStorePortV2}. No Redis type, key, or script + *

{@code application-core} sees {@link IdempotencyStorePort}. No Redis type, key, or script * digest crosses this boundary. */ -public final class RedisIdempotencyStoreAdapter implements IdempotencyStorePortV2 { +public final class RedisIdempotencyStoreAdapter implements IdempotencyStorePort { private static final SecureRandom RANDOM = new SecureRandom(); diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/realtime/RealtimeKeys.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/realtime/RealtimeKeys.java deleted file mode 100644 index a0975e74..00000000 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/realtime/RealtimeKeys.java +++ /dev/null @@ -1,81 +0,0 @@ -package dev.caskeleton.adapter.outbound.cache.redis.realtime; - -import dev.caskeleton.adapter.outbound.cache.redis.keyspace.CapabilityKeyspace; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisNamespace; -import dev.caskeleton.application.realtime.ActorFingerprint; -import dev.caskeleton.application.realtime.RealtimeChannel; -import java.nio.charset.StandardCharsets; -import java.util.Objects; - -/** - * The physical keys the realtime registry owns, and nothing else does. - * - *

The actor appears only as the fingerprint the caller already produced. This adapter never sees - * a user id or a tenant name, and that is deliberate rather than incidental: a Redis key reaches - * MONITOR output, the slow log, {@code KEYS} during an incident and every backup — none of which - * has the access controls the application has, and all of which outlive the request. - * - *

There are three key shapes and they are separate on purpose. The per-actor hash answers "where - * is this actor", the per-node set answers "what was this node holding", and the heartbeat sorted - * set answers "which nodes are still alive". Deriving any of them from another would mean scanning: - * finding a dead node's entries by walking every actor is O(actors) on a path that runs whenever a - * node dies, which is exactly when the cluster has least to spare. - */ -public final class RealtimeKeys { - - private final CapabilityKeyspace keyspace; - - /** - * Creates the key renderer. - * - * @param namespace the deployment namespace every capability shares - * @param keyVersion the physical key layout version - */ - public RealtimeKeys(RedisNamespace namespace, int keyVersion) { - this.keyspace = new CapabilityKeyspace(namespace, "realtime", keyVersion); - } - - /** Where one actor is connected: a hash of node id to encoded registration. */ - public byte[] actorKey(RealtimeChannel channel, ActorFingerprint actor) { - Objects.requireNonNull(channel, "channel must be non-null"); - Objects.requireNonNull(actor, "actor must be non-null"); - return keyspace.key("actor", channel.value(), actor.value()); - } - - /** - * What one node is holding: a set of {@code channel/fingerprint} members. - * - *

Maintained alongside the actor hash so that evicting a dead node is a read of one set rather - * than a scan of every actor. - */ - public byte[] nodeKey(String nodeId) { - Objects.requireNonNull(nodeId, "node id must be non-null"); - return keyspace.key("node", nodeId); - } - - /** Which nodes are alive: a sorted set scored by last heartbeat, in epoch millis. */ - public byte[] heartbeatKey() { - return keyspace.key("heartbeat"); - } - - /** The fan-out channel a publisher writes to. */ - public byte[] fanoutChannel(RealtimeChannel channel) { - Objects.requireNonNull(channel, "channel must be non-null"); - return keyspace.key("fanout", channel.value()); - } - - /** The member that identifies one actor entry inside a node's set. */ - public static byte[] nodeMember(RealtimeChannel channel, ActorFingerprint actor) { - return (channel.value() + "/" + actor.value()).getBytes(StandardCharsets.UTF_8); - } - - /** Splits a node-set member back into its channel and fingerprint. */ - public static String[] splitNodeMember(byte[] member) { - String rendered = new String(member, StandardCharsets.UTF_8); - int separator = rendered.indexOf('/'); - if (separator < 0) { - throw new IllegalArgumentException("not a node-set member"); - } - return new String[] {rendered.substring(0, separator), rendered.substring(separator + 1)}; - } -} diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/realtime/RedisConnectionRegistryAdapter.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/realtime/RedisConnectionRegistryAdapter.java deleted file mode 100644 index dfac7701..00000000 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/realtime/RedisConnectionRegistryAdapter.java +++ /dev/null @@ -1,301 +0,0 @@ -package dev.caskeleton.adapter.outbound.cache.redis.realtime; - -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.ExpirationCondition; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.PageRequest; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.ScoreRange; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.SortedSetAddOptions; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisConnectionKind; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisLease; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeOwner; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations.HashScanPage; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations.MemberScanPage; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations.ScoredMemberPage; -import dev.caskeleton.application.realtime.ActorFingerprint; -import dev.caskeleton.application.realtime.ConnectionRegistration; -import dev.caskeleton.application.realtime.ConnectionRegistryPort; -import dev.caskeleton.application.realtime.RealtimeChannel; -import dev.caskeleton.application.realtime.RealtimeNodeId; -import java.nio.charset.StandardCharsets; -import java.time.Duration; -import java.time.Instant; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.List; -import java.util.Objects; -import java.util.Optional; -import java.util.concurrent.CompletionStage; -import java.util.concurrent.TimeUnit; - -/** - * The cluster session registry, on Redis. - * - *

Three structures, written together and read separately, because the three questions they - * answer have different shapes. - * - *

    - *
  • A hash per actor, so "where is this actor" is one read. It is read whole, which is bounded - * here in a way a general hash read is not: its fields are cluster nodes, so its size is the - * node count and not the traffic. - *
  • A set per node, so "what was this node holding" does not require walking every actor. - * Evicting a dead node by scanning actors would be O(actors) on the path that runs exactly - * when a node has just died — when the cluster has least to spare. This one is - * unbounded in the number of actors, so it is read by cursor rather than whole. - *
  • A sorted set of nodes scored by last heartbeat, so "which nodes are gone" is a range query. - *
- * - *

Every failure degrades to "nothing found". That is not laziness about error - * handling — it is the correct answer for this port. The caller's fallback for an unknown location - * is to broadcast to the cluster and let the holder claim the message, which works. Throwing would - * turn a Redis blip into a failed user-visible operation, and a registry that is only a routing - * hint has no business doing that. - * - *

The TTL lives on the actor hash rather than on individual fields. Hash-field TTLs need Redis - * 7.4; depending on them would make this adapter refuse to run on anything older for a property the - * node heartbeat already provides more reliably — a node that dies stops refreshing, and its - * entries go when its heartbeat expires rather than one at a time. - */ -public final class RedisConnectionRegistryAdapter implements ConnectionRegistryPort { - - /** How many node-set members one eviction step reads. */ - private static final int EVICTION_PAGE = 256; - - /** How many silent nodes one eviction pass handles. */ - private static final int EVICTION_NODE_LIMIT = 64; - - private final RedisRuntimeOwner owner; - private final RealtimeKeys keys; - private final Duration commandTimeout; - - /** - * Creates the adapter. - * - * @param owner the Redis runtime owner leases come from - * @param keys renders the private physical keys this adapter owns - * @param commandTimeout the ceiling on one registry operation - */ - public RedisConnectionRegistryAdapter( - RedisRuntimeOwner owner, RealtimeKeys keys, Duration commandTimeout) { - this.owner = Objects.requireNonNull(owner, "runtime owner must be non-null"); - this.keys = Objects.requireNonNull(keys, "keys must be non-null"); - this.commandTimeout = - Objects.requireNonNull(commandTimeout, "command timeout must be non-null"); - if (commandTimeout.isNegative() || commandTimeout.isZero()) { - throw new IllegalArgumentException( - "an unbounded registry command blocks the caller on a datastore that is only a routing" - + " hint"); - } - } - - @Override - public void announce(ConnectionRegistration registration, Duration timeToLive) { - Objects.requireNonNull(registration, "registration must be non-null"); - Objects.requireNonNull(timeToLive, "time to live must be non-null"); - byte[] actorKey = keys.actorKey(registration.channel(), registration.actor()); - byte[] nodeKey = keys.nodeKey(registration.nodeId().value()); - try (RedisLease lease = owner.borrow(RedisConnectionKind.REGULAR)) { - await( - lease - .gateway() - .hashPut( - actorKey, - utf8(registration.nodeId().value()), - RegistrationCodec.encode(registration))); - // Refreshed on every announce. A node that keeps reporting keeps its entry alive; one that - // stops loses it without anybody having to notice. - await(lease.gateway().expire(actorKey, timeToLive, ExpirationCondition.ALWAYS)); - await( - lease - .gateway() - .setAdd( - nodeKey, - List.of(RealtimeKeys.nodeMember(registration.channel(), registration.actor())))); - // The node set outlives the entries it points at, deliberately. It is what an eviction reads, - // and a set that expired first would leave those entries with nothing able to find them. - await( - lease.gateway().expire(nodeKey, timeToLive.multipliedBy(4), ExpirationCondition.ALWAYS)); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - } catch (Exception degraded) { - // The actor is simply not findable, and the caller broadcasts. - Objects.requireNonNull(degraded); - } - } - - @Override - public void withdraw(ActorFingerprint actor, RealtimeChannel channel, RealtimeNodeId nodeId) { - Objects.requireNonNull(actor, "actor must be non-null"); - Objects.requireNonNull(channel, "channel must be non-null"); - Objects.requireNonNull(nodeId, "node id must be non-null"); - try (RedisLease lease = owner.borrow(RedisConnectionKind.REGULAR)) { - await( - lease.gateway().hashDelete(keys.actorKey(channel, actor), List.of(utf8(nodeId.value())))); - await( - lease - .gateway() - .setRemove( - keys.nodeKey(nodeId.value()), List.of(RealtimeKeys.nodeMember(channel, actor)))); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - } catch (Exception degraded) { - // A withdrawal that did not happen leaves an entry the TTL and the node heartbeat both - // remove. Failing loudly here would turn an ordinary disconnect into an error. - Objects.requireNonNull(degraded); - } - } - - @Override - public List locate( - ActorFingerprint actor, RealtimeChannel channel, Instant now) { - Objects.requireNonNull(actor, "actor must be non-null"); - Objects.requireNonNull(channel, "channel must be non-null"); - Objects.requireNonNull(now, "now must be non-null"); - try (RedisLease lease = owner.borrow(RedisConnectionKind.REGULAR)) { - HashScanPage page = await(lease.gateway().hashEntries(keys.actorKey(channel, actor))); - List found = new ArrayList<>(page.size()); - for (int index = 0; index < page.size(); index++) { - RealtimeNodeId nodeId = nodeIdOrNull(page.fields().get(index)); - if (nodeId == null) { - continue; - } - ConnectionRegistration decoded = - RegistrationCodec.decode(actor, channel, nodeId, page.values().get(index)); - if (decoded != null) { - found.add(decoded); - } - } - // Newest first, so a caller that takes the first entry takes the freshest report rather than - // whichever node Redis happened to return first. - found.sort(Comparator.comparing(ConnectionRegistration::observedAt).reversed()); - return List.copyOf(found); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - return List.of(); - } catch (Exception degraded) { - Objects.requireNonNull(degraded); - return List.of(); - } - } - - @Override - public void heartbeat(RealtimeNodeId nodeId, Instant now) { - Objects.requireNonNull(nodeId, "node id must be non-null"); - Objects.requireNonNull(now, "now must be non-null"); - try (RedisLease lease = owner.borrow(RedisConnectionKind.REGULAR)) { - await( - lease - .gateway() - .sortedSetAdd( - keys.heartbeatKey(), - List.of(utf8(nodeId.value())), - List.of((double) now.toEpochMilli()), - SortedSetAddOptions.upsert())); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - } catch (Exception degraded) { - // A missed heartbeat makes this node look dead to an evictor, which removes entries the node - // re-announces on its next report. Costly, not wrong. - Objects.requireNonNull(degraded); - } - } - - @Override - public List evictSilentNodes(Duration heartbeatTimeout, Instant now) { - Objects.requireNonNull(heartbeatTimeout, "heartbeat timeout must be non-null"); - Objects.requireNonNull(now, "now must be non-null"); - if (heartbeatTimeout.isNegative() || heartbeatTimeout.isZero()) { - throw new IllegalArgumentException( - "a zero heartbeat timeout evicts every node on every pass, including the live ones"); - } - double cutoff = (double) now.minus(heartbeatTimeout).toEpochMilli(); - List evicted = new ArrayList<>(); - List handled = new ArrayList<>(); - try (RedisLease lease = owner.borrow(RedisConnectionKind.REGULAR)) { - ScoredMemberPage silent = - await( - lease - .gateway() - .sortedSetRangeByScore( - keys.heartbeatKey(), - new ScoreRange(Double.NEGATIVE_INFINITY, true, cutoff, true), - new PageRequest(0, EVICTION_NODE_LIMIT), - false)); - for (byte[] member : silent.members()) { - RealtimeNodeId nodeId = nodeIdOrNull(member); - handled.add(member); - if (nodeId == null) { - continue; - } - forgetNode(lease, nodeId); - evicted.add(nodeId); - } - if (!handled.isEmpty()) { - // Removed last. A node whose entries were not fully cleared keeps its heartbeat member, so - // the next pass tries again rather than leaving the entries behind for ever. - await(lease.gateway().sortedSetRemove(keys.heartbeatKey(), handled)); - } - return List.copyOf(evicted); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - return List.copyOf(evicted); - } catch (Exception degraded) { - Objects.requireNonNull(degraded); - return List.copyOf(evicted); - } - } - - private void forgetNode(RedisLease lease, RealtimeNodeId nodeId) throws Exception { - byte[] nodeKey = keys.nodeKey(nodeId.value()); - String cursor = "0"; - do { - MemberScanPage page = - await(lease.gateway().setScan(nodeKey, cursor, EVICTION_PAGE, Optional.empty())); - for (byte[] member : page.members()) { - removeActorEntry(lease, nodeId, member); - } - cursor = page.nextCursor(); - // By cursor rather than whole: this set is one member per actor the node was holding, so a - // single read of it on a busy node is exactly the unbounded reply the SDK forbids. - } while (!"0".equals(cursor)); - await(lease.gateway().delete(List.of(nodeKey))); - } - - private void removeActorEntry(RedisLease lease, RealtimeNodeId nodeId, byte[] member) - throws Exception { - String[] parts; - try { - parts = RealtimeKeys.splitNodeMember(member); - } catch (IllegalArgumentException malformed) { - Objects.requireNonNull(malformed); - return; - } - RealtimeChannel channel; - ActorFingerprint actor; - try { - channel = new RealtimeChannel(parts[0]); - actor = new ActorFingerprint(parts[1]); - } catch (IllegalArgumentException malformed) { - // Written by something that is not this adapter. Deleting the node set below takes it with - // it, and guessing at a key from a value we cannot parse would delete somebody else's. - Objects.requireNonNull(malformed); - return; - } - await(lease.gateway().hashDelete(keys.actorKey(channel, actor), List.of(utf8(nodeId.value())))); - } - - private RealtimeNodeId nodeIdOrNull(byte[] raw) { - try { - return new RealtimeNodeId(new String(raw, StandardCharsets.UTF_8)); - } catch (IllegalArgumentException malformed) { - Objects.requireNonNull(malformed); - return null; - } - } - - private T await(CompletionStage stage) throws Exception { - return stage.toCompletableFuture().get(commandTimeout.toNanos(), TimeUnit.NANOSECONDS); - } - - private static byte[] utf8(String value) { - return value.getBytes(StandardCharsets.UTF_8); - } -} diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/realtime/RedisEphemeralFanoutAdapter.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/realtime/RedisEphemeralFanoutAdapter.java deleted file mode 100644 index ba584a26..00000000 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/realtime/RedisEphemeralFanoutAdapter.java +++ /dev/null @@ -1,133 +0,0 @@ -package dev.caskeleton.adapter.outbound.cache.redis.realtime; - -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations.RedisPubSubGateway; -import dev.caskeleton.application.realtime.EphemeralFanoutPort; -import dev.caskeleton.application.realtime.FanoutSubscription; -import dev.caskeleton.application.realtime.RealtimeChannel; -import java.nio.charset.StandardCharsets; -import java.time.Duration; -import java.util.List; -import java.util.Objects; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.function.BiConsumer; - -/** - * Best-effort cluster fan-out, on Redis pub/sub. - * - *

Redis pub/sub is fire-and-forget in the strongest sense: the server delivers to whoever is - * subscribed at that instant and then forgets the message entirely. There is no queue, no - * acknowledgement and no replay, so a subscriber that is reconnecting misses everything published - * while it was away and has no way to discover that it did. - * - *

That is a correct transport for presence updates and cache invalidations, whose next message - * supersedes the one that was lost, and a wrong one for anything a user is told happened. Which one - * a call site gets is decided by which port it injects, not by a flag here. - * - *

Two failure modes this adapter handles that a thin wrapper would not. - * - *

A listener's exception must not escape. Listeners run on the driver's shared - * delivery thread, so an exception leaving one stops delivery for every other subscription on that - * connection — and the failure surfaces against whichever channel happened to be next rather than - * the one that caused it. - * - *

A publish that fails is not an error. The message was ephemeral by - * construction, so "the broker did not accept it" and "it reached nobody" are the same outcome to - * the caller, and the returned count already means the latter. - */ -public final class RedisEphemeralFanoutAdapter implements EphemeralFanoutPort { - - private final RedisPubSubGateway gateway; - private final RealtimeKeys keys; - private final Duration commandTimeout; - - /** - * Creates the adapter. - * - * @param gateway the pub/sub gateway, which owns its own connections - * @param keys renders the channel names this adapter owns - * @param commandTimeout the ceiling on one publish - */ - public RedisEphemeralFanoutAdapter( - RedisPubSubGateway gateway, RealtimeKeys keys, Duration commandTimeout) { - this.gateway = Objects.requireNonNull(gateway, "pub/sub gateway must be non-null"); - this.keys = Objects.requireNonNull(keys, "keys must be non-null"); - this.commandTimeout = - Objects.requireNonNull(commandTimeout, "command timeout must be non-null"); - if (commandTimeout.isNegative() || commandTimeout.isZero()) { - throw new IllegalArgumentException( - "an unbounded publish blocks the caller on a best-effort transport"); - } - } - - @Override - public long publish(RealtimeChannel channel, byte[] payload) { - Objects.requireNonNull(channel, "channel must be non-null"); - Objects.requireNonNull(payload, "payload must be non-null"); - try { - Long delivered = - gateway - .publish(keys.fanoutChannel(channel), payload.clone()) - .toCompletableFuture() - .get(commandTimeout.toNanos(), TimeUnit.NANOSECONDS); - return delivered == null ? 0L : delivered; - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - return 0L; - } catch (Exception degraded) { - Objects.requireNonNull(degraded); - return 0L; - } - } - - @Override - public FanoutSubscription subscribe( - RealtimeChannel channel, BiConsumer listener) { - Objects.requireNonNull(channel, "channel must be non-null"); - Objects.requireNonNull(listener, "listener must be non-null"); - String target = new String(keys.fanoutChannel(channel), StandardCharsets.UTF_8); - RedisPubSubGateway.RedisSubscriptionHandle handle = - gateway.subscribe( - List.of(target), - RedisPubSubGateway.SubscriptionKind.CHANNEL, - (delivered, payload) -> deliver(channel, listener, payload)); - return new HandleSubscription(handle); - } - - private static void deliver( - RealtimeChannel channel, BiConsumer listener, byte[] payload) { - try { - listener.accept(channel, payload); - } catch (RuntimeException failure) { - // Swallowed on purpose. See the class comment: this runs on the driver's shared delivery - // thread, and letting it out stops every other subscription on the connection. - Objects.requireNonNull(failure); - } - } - - /** A subscription that closes its handle exactly once. */ - private static final class HandleSubscription implements FanoutSubscription { - - private final RedisPubSubGateway.RedisSubscriptionHandle handle; - private final AtomicBoolean open = new AtomicBoolean(true); - - HandleSubscription(RedisPubSubGateway.RedisSubscriptionHandle handle) { - this.handle = handle; - } - - @Override - public boolean active() { - return open.get(); - } - - @Override - public void close() { - // Guarded rather than idempotent-by-hope: this is called from a stream teardown that can run - // twice when a cancel races a completion, and unsubscribing a channel a second time would - // remove a subscription a later caller had just established. - if (open.compareAndSet(true, false)) { - handle.close(); - } - } - } -} diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/realtime/RegistrationCodec.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/realtime/RegistrationCodec.java deleted file mode 100644 index 81e64fe8..00000000 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/realtime/RegistrationCodec.java +++ /dev/null @@ -1,76 +0,0 @@ -package dev.caskeleton.adapter.outbound.cache.redis.realtime; - -import dev.caskeleton.application.realtime.ActorFingerprint; -import dev.caskeleton.application.realtime.ConnectionRegistration; -import dev.caskeleton.application.realtime.RealtimeChannel; -import dev.caskeleton.application.realtime.RealtimeNodeId; -import java.nio.charset.StandardCharsets; -import java.time.Instant; -import java.util.Objects; - -/** - * How a registration is written into a Redis hash field. - * - *

A fixed three-field text encoding rather than JSON, and the reason is what happens when it - * changes. This value is written by one node and read by another, which during a rolling deploy are - * different versions of the code; a JSON reader that gained a required field would fail on every - * entry the old nodes are still writing, for the whole rollout. A leading version token makes an - * incompatible change something the reader can detect and skip rather than throw on. - * - *

Skipping is the right response for this data specifically. An entry that cannot be decoded is - * a routing hint, so discarding it costs one broadcast; throwing would fail the whole lookup and - * take the entries that decoded fine with it. - */ -final class RegistrationCodec { - - private static final String VERSION = "v1"; - - /** ASCII unit separator: it cannot occur in a count or an epoch, so no escaping is needed. */ - private static final String SEPARATOR = ""; - - private RegistrationCodec() {} - - /** Encodes a registration for storage. */ - static byte[] encode(ConnectionRegistration registration) { - Objects.requireNonNull(registration, "registration must be non-null"); - String rendered = - VERSION - + SEPARATOR - + registration.connectionCount() - + SEPARATOR - + registration.observedAt().toEpochMilli(); - return rendered.getBytes(StandardCharsets.UTF_8); - } - - /** - * Decodes a stored registration. - * - * @param actor whose entry this is, from the key rather than the value - * @param channel which feed, likewise from the key - * @param nodeId which node, from the hash field name - * @param stored the encoded value - * @return the registration, or {@code null} when the value is from an incompatible writer - */ - static ConnectionRegistration decode( - ActorFingerprint actor, RealtimeChannel channel, RealtimeNodeId nodeId, byte[] stored) { - if (stored == null) { - return null; - } - String[] parts = new String(stored, StandardCharsets.UTF_8).split(SEPARATOR, -1); - if (parts.length != 3 || !VERSION.equals(parts[0])) { - return null; - } - try { - return new ConnectionRegistration( - actor, - nodeId, - channel, - Integer.parseInt(parts[1]), - Instant.ofEpochMilli(Long.parseLong(parts[2]))); - } catch (IllegalArgumentException malformed) { - // Same reasoning as an unknown version: a routing hint that cannot be read is dropped, not - // raised. Raising would lose the entries beside it that were perfectly readable. - return null; - } - } -} diff --git a/src/adapter/outbound/cache-redis/src/main/resources/META-INF/spring.factories b/src/adapter/outbound/cache-redis/src/main/resources/META-INF/spring.factories new file mode 100644 index 00000000..b17e600c --- /dev/null +++ b/src/adapter/outbound/cache-redis/src/main/resources/META-INF/spring.factories @@ -0,0 +1,2 @@ +org.springframework.boot.EnvironmentPostProcessor=\ +dev.caskeleton.adapter.outbound.cache.redis.capability.RedisReadinessGroupPostProcessor diff --git a/src/adapter/outbound/cache-redis/src/main/resources/config/module-defaults/cache-redis.yml b/src/adapter/outbound/cache-redis/src/main/resources/config/module-defaults/cache-redis.yml new file mode 100644 index 00000000..786d6ad2 --- /dev/null +++ b/src/adapter/outbound/cache-redis/src/main/resources/config/module-defaults/cache-redis.yml @@ -0,0 +1,79 @@ +# cache-redis 모듈이 가져오는 기본 설정. 이 모듈을 runtimeOnly 로 고르면 함께 들어오고, 그 줄을 +# 지우면 함께 사라진다. +# +# ModuleDefaultsEnvironmentPostProcessor(adapter:outbound:support)가 가장 낮은 우선순위로 읽는다. +# application*.yml, 환경변수, 명령행 인자가 언제나 이긴다. +app: + # The one global Redis switch. On while this module is present, like every capability: selecting + # the module is the decision to run it. False means no Redis settings are bound, no Redis + # credential is required, no client, connection, thread or health contributor is created, and no + # Redis-specific resource is read. There is deliberately no second capability switch: a role such as + # cache or session selects *which* Redis capabilities compose, never *whether* Redis exists. + redis: + enabled: ${APP_REDIS_ENABLED:true} + rate-limit: + # Inbound HTTP enforcement is a separate axis from outbound provider activation. + # enabled=true with no exact EdgeRateLimitPort fails fast; it never installs a local fallback. + enabled: ${APP_RATE_LIMIT_ENABLED:false} + default-policy-id: ${APP_RATE_LIMIT_DEFAULT_POLICY_ID:api-default} + hash-key-version: ${APP_RATE_LIMIT_HASH_KEY_VERSION:1} + caller-deadline-budget: 2s + # remote-addr-only | forwarded-headers-trusted (trusted ingress only) + client-ip-mode: ${APP_RATE_LIMIT_CLIENT_IP_MODE:remote-addr-only} + +ca-skeleton: + capabilities: + # Every capability below renders its keys under one namespace — app.redis.namespace, which is + # {environment}:{service}:{domain}. The per-capability namespace-application / + # namespace-environment pairs that used to live here are gone: four capabilities each joining + # two free-form tokens in their own order produced four different key prefixes, and the ACL + # pattern meant to fence the deployment in matched none of them. + cache: + # Canonical semantic cache activation. Disabled by default; "redis" composes + # RedisCacheRegionAdapter for the region named below and resolves HMAC material by reference. + bindings: + default: ${APP_CACHE_CANONICAL_DEFAULT_PROVIDER:disabled} + semantic-region: ${APP_CACHE_REDIS_SEMANTIC_REGION:default} + key-version: 1 + key-hmac-secret-reference: secret://environment/APP_CACHE_REDIS_KEY_HMAC_SECRET + command-timeout: ${APP_CACHE_REDIS_COMMAND_TIMEOUT:200ms} + positive-soft-ttl: ${APP_CACHE_REDIS_POSITIVE_SOFT_TTL:30s} + positive-hard-ttl: ${APP_CACHE_REDIS_POSITIVE_HARD_TTL:5m} + negative-ttl: ${APP_CACHE_REDIS_NEGATIVE_TTL:10s} + # Floor on the hard TTL. Below it, entries expire faster than the round trip that wrote them: + # every read misses and every miss writes. + minimum-hard-ttl: ${APP_CACHE_REDIS_MINIMUM_HARD_TTL:1s} + idempotency: + # Redis store tuning only; the provider selector and lifecycle policy stay with the + # application's idempotency executor. + key-version: 1 + command-timeout: ${APP_IDEMPOTENCY_REDIS_COMMAND_TIMEOUT:200ms} + lease: + # disabled | redis. This is EFFICIENCY_ONLY and never supplies fencing. + provider: ${APP_LEASE_PROVIDER:disabled} + key-version: 1 + command-timeout: ${APP_LEASE_REDIS_COMMAND_TIMEOUT:200ms} + contention-retry-after: ${APP_LEASE_REDIS_CONTENTION_RETRY_AFTER:50ms} + # How much shorter than the server's TTL this holder considers its lease valid. The two + # clocks are not the same clock, and a holder that measured the full TTL locally would still + # believe it held a lease the server had already handed to somebody else. + drift-budget: ${APP_LEASE_REDIS_DRIFT_BUDGET:10ms} + rate-limit: + # disabled | redis. This is the sole outbound provider activation selector. + provider: ${APP_RATE_LIMIT_PROVIDER:disabled} + failure-policy: ${APP_RATE_LIMIT_FAILURE_POLICY:fail-closed} + default-policy-id: ${APP_RATE_LIMIT_DEFAULT_POLICY_ID:api-default} + failure-retry-after: ${APP_RATE_LIMIT_FAILURE_RETRY_AFTER:100ms} + key-version: ${APP_RATE_LIMIT_KEY_VERSION:1} + command-timeout: ${APP_RATE_LIMIT_REDIS_COMMAND_TIMEOUT:200ms} + policies: + api-default: + revision: ${APP_RATE_LIMIT_POLICY_REVISION:v1} + algorithm: ${APP_RATE_LIMIT_ALGORITHM:sliding-counter} + limit: ${APP_RATE_LIMIT_LIMIT:100} + window: ${APP_RATE_LIMIT_WINDOW:1s} + capacity: ${APP_RATE_LIMIT_CAPACITY:100} + refill-tokens: ${APP_RATE_LIMIT_REFILL_TOKENS:100} + refill-period: ${APP_RATE_LIMIT_REFILL_PERIOD:1s} + maximum-cost: ${APP_RATE_LIMIT_MAXIMUM_COST:10} + cleanup-grace: ${APP_RATE_LIMIT_CLEANUP_GRACE:5s} diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/LiveRedisSemanticPortsTest.java b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/LiveRedisSemanticPortsTest.java index da52ecb9..8b6937e3 100644 --- a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/LiveRedisSemanticPortsTest.java +++ b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/LiveRedisSemanticPortsTest.java @@ -24,11 +24,11 @@ import dev.caskeleton.application.cache.CacheRecordIntent; import dev.caskeleton.application.cache.CacheRecordMetadata; import dev.caskeleton.application.cache.CacheRecordOutcome; import dev.caskeleton.application.cache.CacheRegionPort; +import dev.caskeleton.application.idempotency.IdempotencyClaimAttempt; +import dev.caskeleton.application.idempotency.IdempotencyClaimOutcome; +import dev.caskeleton.application.idempotency.IdempotencyClaimRequest; +import dev.caskeleton.application.idempotency.IdempotencyScopeDigest; import dev.caskeleton.application.idempotency.RequestFingerprint; -import dev.caskeleton.application.idempotency.v2.IdempotencyClaimAttempt; -import dev.caskeleton.application.idempotency.v2.IdempotencyClaimOutcome; -import dev.caskeleton.application.idempotency.v2.IdempotencyClaimRequest; -import dev.caskeleton.application.idempotency.v2.IdempotencyScopeDigest; import dev.caskeleton.application.lease.LeaseAcquireOutcome; import dev.caskeleton.application.lease.LeaseAttempt; import dev.caskeleton.application.lease.LeaseRequest; @@ -123,6 +123,7 @@ class LiveRedisSemanticPortsTest { }) .create(), limits, + Duration.ofSeconds(2), Duration.ofSeconds(2)); return owner; } diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/cache/RedisCacheRegionAdapterTest.java b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/cache/RedisCacheRegionAdapterTest.java index 6263386c..1dcc18cd 100644 --- a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/cache/RedisCacheRegionAdapterTest.java +++ b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/cache/RedisCacheRegionAdapterTest.java @@ -58,7 +58,7 @@ class RedisCacheRegionAdapterTest { limits.put(kind, 4); } return new RedisCacheRegionAdapter<>( - new RedisRuntimeOwner(client, limits, Duration.ofSeconds(1)), + new RedisRuntimeOwner(client, limits, Duration.ofSeconds(1), Duration.ofSeconds(1)), cacheKeys, key -> "digest-" + key, value -> value.getBytes(StandardCharsets.UTF_8), diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisCapabilityActivationTest.java b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisCapabilityActivationTest.java new file mode 100644 index 00000000..8228719f --- /dev/null +++ b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisCapabilityActivationTest.java @@ -0,0 +1,79 @@ +package dev.caskeleton.adapter.outbound.cache.redis.capability; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeOwner; +import dev.caskeleton.application.outbound.SecretSourcePort; +import java.time.Clock; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import org.junit.jupiter.api.Test; +import org.springframework.boot.SpringBootConfiguration; +import org.springframework.boot.WebApplicationType; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.annotation.Bean; + +/** + * The capability as an application receives it: this module's own registrations and shipped + * defaults (loaded by the support module's post-processor), nothing hand-picked. + * + *

No Redis runs here. Turning it on builds the client and the connection owner without + * connecting; a role that would probe the server is deliberately not selected. + */ +class RedisCapabilityActivationTest { + + @Test + void presentModuleComposesTheRedisRuntime() { + // when — no switch: the module's shipped default is on + try (ConfigurableApplicationContext context = + start( + "--app.redis.nodes=redis.invalid:6379", + "--app.redis.authentication.credential-reference=" + + "secret://ca-skeleton-application@environment/APP_REDIS_PASSWORD")) { + + // then + assertThat(context.getBeansOfType(RedisRuntimeOwner.class)).hasSize(1); + } + } + + @Test + void theSwitchOffLeavesNoRedisBeanAndNeedsNoRedis() { + // when + try (ConfigurableApplicationContext context = start("--app.redis.enabled=false")) { + + // then + assertThat(RedisCapabilityCompositionTest.redisBeans(context)).isEmpty(); + } + } + + private static ConfigurableApplicationContext start(String... overrides) { + List arguments = + new ArrayList<>( + List.of( + "--spring.main.banner-mode=off", + "--spring.config.name=redis-capability-activation-test-has-no-config-file")); + arguments.addAll(List.of(overrides)); + return new SpringApplicationBuilder(Application.class) + .web(WebApplicationType.NONE) + .run(arguments.toArray(String[]::new)); + } + + /** An application that provides the two collaborators this module takes, and nothing else. */ + @SpringBootConfiguration + @EnableAutoConfiguration + static class Application { + + @Bean + SecretSourcePort secretSource() { + return name -> Optional.of("fixture-secret-" + name); + } + + @Bean + Clock clock() { + return Clock.systemUTC(); + } + } +} diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisCapabilityCompositionTest.java b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisCapabilityCompositionTest.java index d8832968..7b62afc1 100644 --- a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisCapabilityCompositionTest.java +++ b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisCapabilityCompositionTest.java @@ -5,18 +5,22 @@ import static org.mockito.Mockito.mock; import dev.caskeleton.adapter.outbound.cache.redis.sdk.config.RedisSdkAutoConfiguration; import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeOwner; +import dev.caskeleton.adapter.outbound.support.startup.RequiredAdapterDisabledException; import dev.caskeleton.application.cache.CacheRegionPort; -import dev.caskeleton.application.idempotency.v2.IdempotencyStorePortV2; +import dev.caskeleton.application.idempotency.IdempotencyStorePort; import dev.caskeleton.application.lease.DistributedLeasePort; import dev.caskeleton.application.outbound.SecretSourcePort; import dev.caskeleton.shared.ratelimit.EdgeRateLimitPort; import java.time.Clock; import java.time.Duration; +import java.util.Arrays; +import java.util.List; import java.util.Optional; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -70,7 +74,7 @@ class RedisCapabilityCompositionTest { assertThat(context).hasSingleBean(RedisRuntimeOwner.class); assertThat(context.getBeansOfType(CacheRegionPort.class)).isEmpty(); assertThat(context.getBeansOfType(EdgeRateLimitPort.class)).isEmpty(); - assertThat(context.getBeansOfType(IdempotencyStorePortV2.class)).isEmpty(); + assertThat(context.getBeansOfType(IdempotencyStorePort.class)).isEmpty(); assertThat(context.getBeansOfType(DistributedLeasePort.class)).isEmpty(); }); } @@ -85,7 +89,7 @@ class RedisCapabilityCompositionTest { assertThat(context).hasNotFailed(); assertThat(context).hasSingleBean(CacheRegionPort.class); assertThat(context.getBeansOfType(EdgeRateLimitPort.class)).isEmpty(); - assertThat(context.getBeansOfType(IdempotencyStorePortV2.class)).isEmpty(); + assertThat(context.getBeansOfType(IdempotencyStorePort.class)).isEmpty(); assertThat(context.getBeansOfType(DistributedLeasePort.class)).isEmpty(); }); } @@ -126,29 +130,50 @@ class RedisCapabilityCompositionTest { assertThat(context).hasSingleBean(CacheRegionPort.class); assertThat(context).hasSingleBean(EdgeRateLimitPort.class); assertThat(context).hasSingleBean(DistributedLeasePort.class); - assertThat(context).hasSingleBean(IdempotencyStorePortV2.class); + assertThat(context).hasSingleBean(IdempotencyStorePort.class); }); } @Test - @DisplayName("the switch off composes nothing, whatever the roles say") - void theSwitchOffComposesNothing() { - // The contradiction itself is refused by RedisActivationValidator; what is asserted here is - // that this configuration contributes no bean to argue about in the first place. + void redisIdempotencyRefusesAKeyVersionRotationUntilDualReadExists() { + runner + .withPropertyValues( + "ca-skeleton.capabilities.idempotency.provider=redis", + "ca-skeleton.capabilities.idempotency.key-version=2") + .run( + context -> + assertThat(context.getStartupFailure()) + .hasRootCauseInstanceOf(RequiredAdapterDisabledException.class) + .hasStackTraceContaining("ca-skeleton.capabilities.idempotency.key-version=2") + .hasStackTraceContaining("unsupported without dual-read")); + } + + @Test + void theSwitchOffLeavesNoRedisBeanWhateverTheRolesSay() { new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(RedisSdkAutoConfiguration.class)) - .withUserConfiguration(RedisCapabilityConfig.class, Support.class) + .withConfiguration( + AutoConfigurations.of(RedisSdkAutoConfiguration.class, RedisCapabilityConfig.class)) + .withUserConfiguration(Support.class) .withPropertyValues( "app.redis.enabled=false", "ca-skeleton.capabilities.cache.bindings.default=redis", "ca-skeleton.capabilities.lease.provider=redis") - .run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context.getBeansOfType(RedisCapabilityConfig.class)).isEmpty(); - assertThat(context.getBeansOfType(CacheRegionPort.class)).isEmpty(); - assertThat(context.getBeansOfType(DistributedLeasePort.class)).isEmpty(); - }); + .run(context -> assertThat(redisBeans(context)).isEmpty()); + } + + /** Every bean a Redis leaf or the Lettuce client contributed; the test's own beans are not. */ + static List redisBeans(ApplicationContext context) { + return Arrays.stream(context.getBeanDefinitionNames()) + .filter( + name -> { + Class type = context.getType(name); + if (type == null || type.getName().contains("Test$")) { + return false; + } + return type.getName().startsWith("dev.caskeleton.adapter.outbound.cache.redis.") + || type.getName().startsWith("io.lettuce."); + }) + .toList(); } /** The two collaborators the composition takes from the rest of the application. */ diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/redis/RedisReadinessGroupPostProcessorTest.java b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisReadinessGroupPostProcessorTest.java similarity index 87% rename from src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/redis/RedisReadinessGroupPostProcessorTest.java rename to src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisReadinessGroupPostProcessorTest.java index 706b4b22..8557e188 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/redis/RedisReadinessGroupPostProcessorTest.java +++ b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisReadinessGroupPostProcessorTest.java @@ -1,13 +1,13 @@ -package dev.caskeleton.bootstrap.autoconfigure.redis; +package dev.caskeleton.adapter.outbound.cache.redis.capability; import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.adapter.outbound.cache.redis.sdk.config.RedisCorrectnessRoles; -import dev.caskeleton.bootstrap.contract.support.ShippedConfiguration; -import dev.caskeleton.bootstrap.runtime.ReadinessGroup; -import dev.caskeleton.bootstrap.runtime.SecretSourceValidator; +import dev.caskeleton.adapter.outbound.support.startup.ReadinessGroup; import java.io.IOException; +import java.util.ArrayList; import java.util.LinkedHashMap; +import java.util.List; import java.util.Map; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -27,8 +27,6 @@ import org.springframework.boot.health.contributor.HealthIndicator; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.MutablePropertySources; -import org.springframework.core.env.PropertySourcesPropertyResolver; import org.springframework.core.env.StandardEnvironment; /** @@ -41,23 +39,19 @@ import org.springframework.core.env.StandardEnvironment; * was not a wrong string: it was Boot refusing to start. * *

So each case boots a {@link org.springframework.boot.SpringApplication} with membership - * validation on and the readiness include read out of the shipped {@code application.yml}. If the - * shipped group ever names a conditional contributor again, the Redis-off case here fails exactly - * the way production did. + * validation on and the readiness include the template ships. If the group ever names a conditional + * contributor again, the Redis-off case here fails exactly the way production did. */ class RedisReadinessGroupPostProcessorTest { /** - * The readiness include as shipped. + * The readiness include the template ships ({@code config/observability.yml} in app-bootstrap). * - *

Read from the real file rather than restated, so a change to the group is a change to this - * test's inputs and cannot pass by editing one of the two. + *

Restated rather than read: this module cannot see the application's files, and the claim + * under test is only that the appender keeps whatever base group it is given. */ - private static String shippedReadinessInclude() throws IOException { - MutablePropertySources sources = new MutablePropertySources(); - ShippedConfiguration.propertySources().forEach(sources::addLast); - return new PropertySourcesPropertyResolver(sources) - .getProperty(ReadinessGroup.INCLUDE_PROPERTY); + private static String shippedReadinessInclude() { + return "readinessState"; } private static ConfigurableApplicationContext boot(Map properties) @@ -75,10 +69,13 @@ class RedisReadinessGroupPostProcessorTest { defaults.put("management.endpoint.health.validate-group-membership", "true"); defaults.put(ReadinessGroup.INCLUDE_PROPERTY, shippedReadinessInclude()); defaults.putAll(properties); + // Command-line arguments, not builder properties: those are default properties, the one source + // below this module's own shipped defaults, so app.redis.enabled would read the shipped false. + List arguments = new ArrayList<>(); + defaults.forEach((key, value) -> arguments.add("--" + key + "=" + value)); return new SpringApplicationBuilder(HealthContext.class) .web(WebApplicationType.NONE) - .properties(defaults) - .run(); + .run(arguments.toArray(String[]::new)); } private static Map redisOn() { @@ -161,7 +158,7 @@ class RedisReadinessGroupPostProcessorTest { Map.of( ReadinessGroup.INCLUDE_PROPERTY, shippedReadinessInclude(), - SecretSourceValidator.REDIS_ENABLED_PROPERTY, + "app.redis.enabled", "true", selector.getKey(), selector.getValue()))); diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisSemanticScriptAclProbeTest.java b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisSemanticScriptAclProbeTest.java index 7c7c03a9..b455e804 100644 --- a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisSemanticScriptAclProbeTest.java +++ b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisSemanticScriptAclProbeTest.java @@ -111,7 +111,7 @@ class RedisSemanticScriptAclProbeTest { for (RedisConnectionKind kind : RedisConnectionKind.values()) { limits.put(kind, 1); } - return new RedisRuntimeOwner(client, limits, Duration.ofSeconds(1)); + return new RedisRuntimeOwner(client, limits, Duration.ofSeconds(1), Duration.ofSeconds(1)); } private static RedisCommandGateway gateway(boolean denyScripts) { diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/RedisIdempotencyStoreAdapterTest.java b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/RedisIdempotencyStoreAdapterTest.java index e5ce81fd..a43df3be 100644 --- a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/RedisIdempotencyStoreAdapterTest.java +++ b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/RedisIdempotencyStoreAdapterTest.java @@ -9,20 +9,20 @@ import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisR import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeOwner; import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations.InMemoryGatewayAccess; import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations.RedisCommandGateway; +import dev.caskeleton.application.idempotency.IdempotencyClaimAttempt; +import dev.caskeleton.application.idempotency.IdempotencyClaimOutcome; +import dev.caskeleton.application.idempotency.IdempotencyClaimRequest; +import dev.caskeleton.application.idempotency.IdempotencyCompleteOutcome; +import dev.caskeleton.application.idempotency.IdempotencyFailOutcome; +import dev.caskeleton.application.idempotency.IdempotencyFailureDisposition; +import dev.caskeleton.application.idempotency.IdempotencyInspectionOutcome; +import dev.caskeleton.application.idempotency.IdempotencyInspectionRequest; +import dev.caskeleton.application.idempotency.IdempotencyOwner; +import dev.caskeleton.application.idempotency.IdempotencyReleaseOutcome; +import dev.caskeleton.application.idempotency.IdempotencyScopeDigest; +import dev.caskeleton.application.idempotency.IdempotencyStartOutcome; import dev.caskeleton.application.idempotency.RequestFingerprint; import dev.caskeleton.application.idempotency.StoredResponse; -import dev.caskeleton.application.idempotency.v2.IdempotencyClaimAttempt; -import dev.caskeleton.application.idempotency.v2.IdempotencyClaimOutcome; -import dev.caskeleton.application.idempotency.v2.IdempotencyClaimRequest; -import dev.caskeleton.application.idempotency.v2.IdempotencyCompleteOutcome; -import dev.caskeleton.application.idempotency.v2.IdempotencyFailOutcome; -import dev.caskeleton.application.idempotency.v2.IdempotencyFailureDisposition; -import dev.caskeleton.application.idempotency.v2.IdempotencyInspectionOutcome; -import dev.caskeleton.application.idempotency.v2.IdempotencyInspectionRequest; -import dev.caskeleton.application.idempotency.v2.IdempotencyOwner; -import dev.caskeleton.application.idempotency.v2.IdempotencyReleaseOutcome; -import dev.caskeleton.application.idempotency.v2.IdempotencyScopeDigest; -import dev.caskeleton.application.idempotency.v2.IdempotencyStartOutcome; import dev.caskeleton.application.transaction.OperationId; import java.time.Clock; import java.time.Duration; @@ -66,7 +66,7 @@ class RedisIdempotencyStoreAdapterTest { limits.put(kind, 4); } return new RedisIdempotencyStoreAdapter( - new RedisRuntimeOwner(client, limits, Duration.ofSeconds(1)), + new RedisRuntimeOwner(client, limits, Duration.ofSeconds(1), Duration.ofSeconds(1)), new RedisIdempotencyStoreAdapter.IdempotencyKeys( new RedisNamespace("prod", "ca-skeleton", "shared"), 1), new IdempotencyScripts(), diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/lease/RedisDistributedLeaseAdapterTest.java b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/lease/RedisDistributedLeaseAdapterTest.java index cab61ad2..8dfafee7 100644 --- a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/lease/RedisDistributedLeaseAdapterTest.java +++ b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/lease/RedisDistributedLeaseAdapterTest.java @@ -69,7 +69,7 @@ class RedisDistributedLeaseAdapterTest { limits.put(kind, 4); } return new RedisDistributedLeaseAdapter( - new RedisRuntimeOwner(client, limits, Duration.ofSeconds(1)), + new RedisRuntimeOwner(client, limits, Duration.ofSeconds(1), Duration.ofSeconds(1)), new RedisDistributedLeaseAdapter.LeaseKeys( new RedisNamespace("prod", "ca-skeleton", "shared"), 1), new LeaseScripts(), diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RedisEdgeRateLimitAdapterTest.java b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RedisEdgeRateLimitAdapterTest.java index 779c65ab..b81d9791 100644 --- a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RedisEdgeRateLimitAdapterTest.java +++ b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/ratelimit/RedisEdgeRateLimitAdapterTest.java @@ -63,7 +63,7 @@ class RedisEdgeRateLimitAdapterTest { limits.put(kind, 4); } return new RedisEdgeRateLimitAdapter( - new RedisRuntimeOwner(client, limits, Duration.ofSeconds(1)), + new RedisRuntimeOwner(client, limits, Duration.ofSeconds(1), Duration.ofSeconds(1)), keys, Map.of(policy.policyId(), policy), new RateLimitScripts(), diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/realtime/RedisConnectionRegistryAdapterTest.java b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/realtime/RedisConnectionRegistryAdapterTest.java deleted file mode 100644 index 41e39a59..00000000 --- a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/realtime/RedisConnectionRegistryAdapterTest.java +++ /dev/null @@ -1,262 +0,0 @@ -package dev.caskeleton.adapter.outbound.cache.redis.realtime; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisDeploymentMode; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisNamespace; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisConnectionKind; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeClient; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeOwner; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations.InMemoryGatewayAccess; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations.RedisCommandGateway; -import dev.caskeleton.application.realtime.ActorFingerprint; -import dev.caskeleton.application.realtime.ConnectionRegistration; -import dev.caskeleton.application.realtime.RealtimeChannel; -import dev.caskeleton.application.realtime.RealtimeNodeId; -import java.nio.charset.StandardCharsets; -import java.time.Duration; -import java.time.Instant; -import java.util.EnumMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * The cluster registry's behaviour, including the parts that only matter when something is wrong. - * - *

Two properties get the most attention here because they are the ones a naive implementation - * gets wrong in a way nothing notices: a dead node's entries must go without scanning every actor, - * and every failure must degrade to "nothing found" rather than throwing — the caller's fallback is - * a cluster broadcast, and an exception would turn a Redis blip into a failed delivery. - */ -class RedisConnectionRegistryAdapterTest { - - private static final Instant NOW = Instant.parse("2026-08-25T10:00:00Z"); - private static final Duration TTL = Duration.ofSeconds(30); - private static final RealtimeChannel FEED = new RealtimeChannel("live-updates"); - private static final ActorFingerprint ALICE = new ActorFingerprint("fp-alice-0000001"); - private static final ActorFingerprint BOB = new ActorFingerprint("fp-bob-000000001"); - private static final RealtimeNodeId EDGE_ONE = new RealtimeNodeId("edge-1"); - private static final RealtimeNodeId EDGE_TWO = new RealtimeNodeId("edge-2"); - - private final InMemoryGatewayAccess gateway = InMemoryGatewayAccess.create(); - private final RedisConnectionRegistryAdapter adapter = adapter(gateway.gateway()); - - private static RedisConnectionRegistryAdapter adapter(RedisCommandGateway gateway) { - return adapter(new StubClient(gateway)); - } - - private static RedisConnectionRegistryAdapter adapter(RedisRuntimeClient client) { - Map limits = new EnumMap<>(RedisConnectionKind.class); - for (RedisConnectionKind kind : RedisConnectionKind.values()) { - limits.put(kind, 4); - } - return new RedisConnectionRegistryAdapter( - new RedisRuntimeOwner(client, limits, Duration.ofSeconds(1)), - new RealtimeKeys(new RedisNamespace("prod", "ca-skeleton", "shared"), 1), - Duration.ofSeconds(2)); - } - - private static ConnectionRegistration registration( - ActorFingerprint actor, RealtimeNodeId node, int connections, Instant observedAt) { - return new ConnectionRegistration(actor, node, FEED, connections, observedAt); - } - - @Test - @DisplayName("an announced actor is found on the node that announced it") - void announcedActorIsFound() { - adapter.announce(registration(ALICE, EDGE_ONE, 2, NOW), TTL); - - List found = adapter.locate(ALICE, FEED, NOW); - - assertThat(found).hasSize(1); - assertThat(found.get(0).nodeId()).isEqualTo(EDGE_ONE); - assertThat(found.get(0).connectionCount()).isEqualTo(2); - assertThat(found.get(0).observedAt()).isEqualTo(NOW); - } - - @Test - @DisplayName("an actor on two nodes is reported from both, newest first") - void multipleNodesAreReportedNewestFirst() { - // Newest first so a caller taking the first entry takes the freshest report rather than - // whichever node Redis happened to return first. - adapter.announce(registration(ALICE, EDGE_ONE, 1, NOW), TTL); - adapter.announce(registration(ALICE, EDGE_TWO, 3, NOW.plusSeconds(5)), TTL); - - assertThat(adapter.locate(ALICE, FEED, NOW.plusSeconds(5))) - .extracting(ConnectionRegistration::nodeId) - .containsExactly(EDGE_TWO, EDGE_ONE); - } - - @Test - @DisplayName("a re-announce from the same node replaces rather than duplicates") - void reAnnounceReplaces() { - adapter.announce(registration(ALICE, EDGE_ONE, 1, NOW), TTL); - adapter.announce(registration(ALICE, EDGE_ONE, 4, NOW.plusSeconds(1)), TTL); - - assertThat(adapter.locate(ALICE, FEED, NOW.plusSeconds(1))) - .singleElement() - .extracting(ConnectionRegistration::connectionCount) - .isEqualTo(4); - } - - @Test - @DisplayName("a withdrawal removes only the withdrawing node's entry") - void withdrawalIsScopedToItsNode() { - adapter.announce(registration(ALICE, EDGE_ONE, 1, NOW), TTL); - adapter.announce(registration(ALICE, EDGE_TWO, 1, NOW), TTL); - - adapter.withdraw(ALICE, FEED, EDGE_ONE); - - assertThat(adapter.locate(ALICE, FEED, NOW)) - .extracting(ConnectionRegistration::nodeId) - .containsExactly(EDGE_TWO); - } - - @Test - @DisplayName("evicting a silent node removes every actor it was holding") - void evictingANodeRemovesItsActors() { - // Via the node's own set, not by scanning actors. Scanning would be O(actors) on the path that - // runs exactly when a node has just died. - adapter.announce(registration(ALICE, EDGE_ONE, 1, NOW), TTL); - adapter.announce(registration(BOB, EDGE_ONE, 1, NOW), TTL); - adapter.announce(registration(ALICE, EDGE_TWO, 1, NOW), TTL); - adapter.heartbeat(EDGE_ONE, NOW); - adapter.heartbeat(EDGE_TWO, NOW.plusSeconds(60)); - - List evicted = - adapter.evictSilentNodes(Duration.ofSeconds(30), NOW.plusSeconds(60)); - - assertThat(evicted).containsExactly(EDGE_ONE); - assertThat(adapter.locate(BOB, FEED, NOW.plusSeconds(60))).isEmpty(); - assertThat(adapter.locate(ALICE, FEED, NOW.plusSeconds(60))) - .extracting(ConnectionRegistration::nodeId) - .containsExactly(EDGE_TWO); - } - - @Test - @DisplayName("a node that is still reporting is not evicted") - void reportingNodeSurvives() { - adapter.announce(registration(ALICE, EDGE_ONE, 1, NOW), TTL); - adapter.heartbeat(EDGE_ONE, NOW.plusSeconds(50)); - - assertThat(adapter.evictSilentNodes(Duration.ofSeconds(30), NOW.plusSeconds(60))).isEmpty(); - assertThat(adapter.locate(ALICE, FEED, NOW.plusSeconds(60))).hasSize(1); - } - - @Test - @DisplayName("an unknown actor is empty rather than an error") - void unknownActorIsEmpty() { - assertThat(adapter.locate(ALICE, FEED, NOW)).isEmpty(); - } - - @Test - @DisplayName("a registry that cannot be reached reports nothing found") - void unreachableRegistryDegrades() { - // The property that decides whether a Redis blip is a routing miss or a failed delivery. The - // caller broadcasts on empty, which is correct; an exception here would propagate. - RedisConnectionRegistryAdapter broken = adapter((RedisRuntimeClient) new FailingGateway()); - - assertThat(broken.locate(ALICE, FEED, NOW)).isEmpty(); - assertThat(broken.evictSilentNodes(Duration.ofSeconds(30), NOW)).isEmpty(); - } - - @Test - @DisplayName("an announce against an unreachable registry does not throw") - void unreachableAnnounceDoesNotThrow() { - RedisConnectionRegistryAdapter broken = adapter((RedisRuntimeClient) new FailingGateway()); - - broken.announce(registration(ALICE, EDGE_ONE, 1, NOW), TTL); - broken.withdraw(ALICE, FEED, EDGE_ONE); - broken.heartbeat(EDGE_ONE, NOW); - } - - @Test - @DisplayName("a key carries the fingerprint and never a subject") - void keysCarryNoIdentity() { - // Redis keys reach MONITOR, the slow log and every backup — none of which has the access - // controls the application has. - RealtimeKeys keys = new RealtimeKeys(new RedisNamespace("prod", "ca-skeleton", "shared"), 1); - String rendered = new String(keys.actorKey(FEED, ALICE), StandardCharsets.UTF_8); - - assertThat(rendered).contains(ALICE.value()).contains("realtime").contains("live-updates"); - } - - @Test - @DisplayName("a stored entry from an incompatible writer is skipped, not fatal") - void incompatibleEntriesAreSkipped() { - // During a rolling deploy both versions write. An entry that cannot be decoded is a routing - // hint, so dropping it costs one broadcast; throwing would lose the entries beside it that - // decoded perfectly well. - assertThat( - RegistrationCodec.decode( - ALICE, FEED, EDGE_ONE, "v912".getBytes(StandardCharsets.UTF_8))) - .isNull(); - assertThat( - RegistrationCodec.decode( - ALICE, FEED, EDGE_ONE, "garbage".getBytes(StandardCharsets.UTF_8))) - .isNull(); - assertThat(RegistrationCodec.decode(ALICE, FEED, EDGE_ONE, null)).isNull(); - } - - @Test - @DisplayName("a zero heartbeat timeout is refused rather than evicting everything") - void zeroHeartbeatTimeoutIsRefused() { - assertThat( - org.assertj.core.api.Assertions.catchThrowable( - () -> adapter.evictSilentNodes(Duration.ZERO, NOW))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("including the live ones"); - } - - /** A gateway whose every command fails, standing in for an unreachable server. */ - private record FailingGateway() implements RedisRuntimeClient { - - @Override - public RedisDeploymentMode mode() { - return RedisDeploymentMode.STANDALONE; - } - - @Override - public RedisRuntimeClient.RedisLaneConnection openLane( - RedisConnectionKind kind, Optional routingKey) { - throw new IllegalStateException("redis is unreachable"); - } - - @Override - public void close() {} - } - - /** The in-memory gateway behind a runtime client. */ - private record StubClient(RedisCommandGateway gateway) implements RedisRuntimeClient { - - @Override - public RedisDeploymentMode mode() { - return RedisDeploymentMode.STANDALONE; - } - - @Override - public RedisRuntimeClient.RedisLaneConnection openLane( - RedisConnectionKind kind, Optional routingKey) { - return new RedisRuntimeClient.RedisLaneConnection() { - @Override - public RedisCommandGateway gateway() { - return gateway; - } - - @Override - public boolean open() { - return true; - } - - @Override - public void close() {} - }; - } - - @Override - public void close() {} - } -} diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/RedisCommandMetadataDiffTest.java b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/RedisCommandMetadataDiffTest.java deleted file mode 100644 index cfb95d32..00000000 --- a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/RedisCommandMetadataDiffTest.java +++ /dev/null @@ -1,119 +0,0 @@ -package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.command; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.CommandId; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.KeySpec; -import java.util.List; -import java.util.Map; -import java.util.Set; -import org.junit.jupiter.api.Test; - -class RedisCommandMetadataDiffTest { - - private final RedisCommandCatalog catalog = - RedisCommandCatalog.of(new RedisCommandPolicyLoader().load(policyDocument())); - - @Test - void reportsNoDriftWhenPolicyMatchesTheServer() { - RedisCommandMetadataDiff diff = - RedisCommandMetadataDiff.compare( - catalog, - List.of( - server("GET", KeySpec.SINGLE_KEY, Set.of("read", "string", "fast"), false), - server("MGET", new KeySpec(1, -1, 1, false), Set.of("read", "string"), false)), - Map.of( - CommandId.of("GET"), Set.of("read", "string", "fast"), - CommandId.of("MGET"), Set.of("read", "string"))); - - assertThat(diff.requiresReview()).isFalse(); - assertThat(diff.toMarkdown()).isEqualTo("### Redis command metadata drift\n"); - } - - @Test - void reportsACommandTheServerGrewAndThePolicyNeverClassified() { - RedisCommandMetadataDiff diff = - RedisCommandMetadataDiff.compare( - catalog, - List.of( - server("GET", KeySpec.SINGLE_KEY, Set.of("read"), false), - server("MGET", new KeySpec(1, -1, 1, false), Set.of("read"), false), - server("VADD", KeySpec.SINGLE_KEY, Set.of("write"), false)), - Map.of()); - - assertThat(diff.added()).containsExactly(CommandId.of("VADD")); - assertThat(diff.requiresReview()).isTrue(); - assertThat(diff.toMarkdown()).contains("absent from policy: VADD"); - } - - @Test - void reportsAKeySpecificationThatMoved() { - RedisCommandMetadataDiff diff = - RedisCommandMetadataDiff.compare( - catalog, - List.of( - server("GET", KeySpec.SINGLE_KEY, Set.of("read"), false), - server("MGET", new KeySpec(2, -1, 1, false), Set.of("read"), false)), - Map.of()); - - assertThat(diff.changedKeySpecs()).containsExactly(CommandId.of("MGET")); - assertThat(diff.requiresReview()).isTrue(); - } - - @Test - void reportsAnAclCategoryChangeAgainstTheReviewedBaseline() { - RedisCommandMetadataDiff diff = - RedisCommandMetadataDiff.compare( - catalog, - List.of( - server("GET", KeySpec.SINGLE_KEY, Set.of("read", "string", "admin"), false), - server("MGET", new KeySpec(1, -1, 1, false), Set.of("read"), false)), - Map.of(CommandId.of("GET"), Set.of("read", "string", "fast"))); - - assertThat(diff.changedAclCategories()).containsExactly(CommandId.of("GET")); - } - - @Test - void reportsADeprecationThatIsStillApplicationReachable() { - RedisCommandMetadataDiff diff = - RedisCommandMetadataDiff.compare( - catalog, - List.of( - server("GET", KeySpec.SINGLE_KEY, Set.of("read"), true), - server("MGET", new KeySpec(1, -1, 1, false), Set.of("read"), false)), - Map.of()); - - assertThat(diff.deprecatedChanges()).containsExactly(CommandId.of("GET")); - } - - @Test - void reportsACommandThatDisappearedFromTheServer() { - RedisCommandMetadataDiff diff = - RedisCommandMetadataDiff.compare( - catalog, List.of(server("GET", KeySpec.SINGLE_KEY, Set.of("read"), false)), Map.of()); - - assertThat(diff.removed()).containsExactly(CommandId.of("MGET")); - } - - private static RedisServerCommandMetadata server( - String command, KeySpec keySpec, Set aclCategories, boolean deprecated) { - return new RedisServerCommandMetadata( - CommandId.parse(command), keySpec, aclCategories, deprecated); - } - - private static String policyDocument() { - return """ - commands: - GET: - risk: R1 - support: TYPED - read-only: true - MGET: - risk: R2 - support: ADVANCED_TYPED - read-only: true - key-spec: "1 -1 1" - required-policy: multi-key-read - """; - } -} diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/RedisConnectionRegistryTest.java b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/RedisConnectionRegistryTest.java deleted file mode 100644 index 8e41ef7b..00000000 --- a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/RedisConnectionRegistryTest.java +++ /dev/null @@ -1,100 +0,0 @@ -package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisDeploymentMode; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.CommandId; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.error.RedisCommandRejectedException; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.command.RedisCommandCatalog; -import java.util.EnumMap; -import java.util.Map; -import org.junit.jupiter.api.Test; - -class RedisConnectionRegistryTest { - - private final RedisCommandCatalog catalog = RedisCommandCatalog.loadDefault(); - - @Test - void routesEachCommandFamilyToItsOwnLane() { - assertThat(laneFor("GET")).isEqualTo(RedisConnectionKind.REGULAR); - assertThat(laneFor("HGETALL")).isEqualTo(RedisConnectionKind.REGULAR); - assertThat(laneFor("BLPOP")).isEqualTo(RedisConnectionKind.BLOCKING); - assertThat(laneFor("XREAD")).isEqualTo(RedisConnectionKind.BLOCKING); - assertThat(laneFor("INFO")).isEqualTo(RedisConnectionKind.ADMIN); - } - - @Test - void aBlockedCommandHasNoLane() { - assertThatThrownBy(() -> laneFor("FLUSHALL")).isInstanceOf(IllegalArgumentException.class); - } - - @Test - void exhaustingALaneRejectsImmediatelyInsteadOfQueueing() { - RedisConnectionRegistry registry = registry(1); - - try (RedisConnectionLease first = registry.borrow(RedisConnectionKind.BLOCKING)) { - assertThat(first.kind()).isEqualTo(RedisConnectionKind.BLOCKING); - assertThat(registry.borrowedCount(RedisConnectionKind.BLOCKING)).isEqualTo(1); - assertThatThrownBy(() -> registry.borrow(RedisConnectionKind.BLOCKING)) - .isInstanceOf(RedisCommandRejectedException.class) - .hasMessageContaining("reached its limit of 1"); - } - - assertThat(registry.borrowedCount(RedisConnectionKind.BLOCKING)).isZero(); - } - - @Test - void aSaturatedBlockingLaneNeverConsumesTheRegularLane() { - RedisConnectionRegistry registry = registry(2); - - try (RedisConnectionLease blockingOne = registry.borrow(RedisConnectionKind.BLOCKING); - RedisConnectionLease blockingTwo = registry.borrow(RedisConnectionKind.BLOCKING)) { - assertThat(blockingOne.connection()).isNotNull(); - assertThat(blockingTwo.connection()).isNotNull(); - assertThat(registry.borrowedCount(RedisConnectionKind.BLOCKING)).isEqualTo(2); - assertThat(registry.borrowedCount(RedisConnectionKind.REGULAR)).isZero(); - - try (RedisConnectionLease regular = registry.borrow(RedisConnectionKind.REGULAR)) { - assertThat(regular.kind()).isEqualTo(RedisConnectionKind.REGULAR); - } - } - } - - @Test - void closingALeaseTwiceReleasesItOnlyOnce() { - RedisConnectionRegistry registry = registry(1); - RedisConnectionLease lease = registry.borrow(RedisConnectionKind.TRANSACTION); - - lease.close(); - lease.close(); - - assertThat(registry.borrowedCount(RedisConnectionKind.TRANSACTION)).isZero(); - } - - @Test - void everyLaneNeedsAPositiveCeiling() { - Map incomplete = new EnumMap<>(RedisConnectionKind.class); - incomplete.put(RedisConnectionKind.REGULAR, 4); - - assertThatThrownBy( - () -> - new RedisConnectionRegistry( - incomplete, kind -> new Object(), RedisDeploymentMode.STANDALONE)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("positive limit"); - } - - private RedisConnectionKind laneFor(String command) { - return RedisConnectionKind.forCommand(catalog.require(CommandId.parse(command)).descriptor()); - } - - private static RedisConnectionRegistry registry(int limit) { - Map limits = new EnumMap<>(RedisConnectionKind.class); - for (RedisConnectionKind kind : RedisConnectionKind.values()) { - limits.put(kind, limit); - } - return new RedisConnectionRegistry( - limits, kind -> new Object(), RedisDeploymentMode.STANDALONE); - } -} diff --git a/src/adapter/outbound/fileserver/CLAUDE.md b/src/adapter/outbound/fileserver/CLAUDE.md index 9c9f3028..996be8b8 100644 --- a/src/adapter/outbound/fileserver/CLAUDE.md +++ b/src/adapter/outbound/fileserver/CLAUDE.md @@ -8,70 +8,36 @@ - Runtime baseline: Java 21; repository framework baseline: Spring Boot 4.0.0. - Registry SSOT: `src/config/architecture/modules.json`. -Package root: `dev.caskeleton.adapter.outbound.fileserver`. Driven (outbound) adapter implementing -`dev.caskeleton.application.filepublication.FilePublicationPort` (application-core). The legacy -`FileExportPort` remains temporarily as `@Deprecated(forRemoval = true)` compatibility. Design rationale lives in [README.md](README.md). +Package root: `dev.caskeleton.adapter.outbound.fileserver.platform`. Driven (outbound) adapter for +the HTTP Fileserver platform: it implements the `application-fileserver` ports (content storage, +verification, identifiers, audit, metrics). Design rationale lives in [README.md](README.md). ## Responsibility -This leaf contains two related but distinct capability families: - -1. **Publication/export** — R2 `app.fileserver.*` plus the deprecated R1 `app.file-export.*` seam. -2. **HTTP Fileserver platform** — `platform/**`, activated through `app.fileserver-platform.*`, - covering upload/download transport, verification, storage, quota, lifecycle, readiness, metrics, - tracing and audit. Its detailed contracts live under `docs/fileserver/`. - -The publication-specific prohibitions below do not erase platform capabilities that are explicitly -implemented and certified in `docs/fileserver/support-matrix.md`. - -- Publish typed tabular data through a bounded producer/sink contract behind - `FilePublicationPort`. -- Own exact destination routing, provider-neutral operation/manifest/reference records, CSV - encoding, schema validation, formula policy, staging, checksum/counts, recovery, and provider - publication semantics. -- Implement the first qualified R2 provider, `local-persistent`, behind strict pre-provisioned-root - attestation and no-downgrade force/hard-link semantics. -- Return opaque references and explicit publication/durability guarantees; do not expose paths. -- Opt-in, in three separate namespaces that cannot be confused for one another: - `FileserverR2Config` gates R2 publication with `app.fileserver.enabled=true`; `FileExportConfig` - gates R1 CSV export with `app.file-export.enabled=true`, and its overwrite-capable legacy bean - additionally requires `app.file-export.legacy-enabled=true` and a separate root. The HTTP - Fileserver platform is a different capability again and lives under `app.fileserver-platform.*`, - owned by `app-bootstrap`. All selectors default off, and R1/R2 simultaneous activation fails - before filesystem initialization. +- Local filesystem content storage, verification, identifiers, audit and metrics behind + `application-fileserver` ports. +- Activated only through `app.fileserver-platform.*` (default off), from + `platform.autoconfigure.FileserverCapabilityAutoConfiguration` registered in this leaf's + `AutoConfiguration.imports`. +- Detailed transport/security/operations contracts live under `docs/fileserver/`; certified + behavior is listed in `docs/fileserver/support-matrix.md`. ## Allowed -- Project deps: `:application-core`, `:shared-contract` — SSOT is the - `adapter-outbound-fileserver` entry in `src/config/architecture/modules.json`; `src/build.gradle` - enforces it. No - `:domain-core`, no sibling adapters. -- External runtime: JDK filesystem, `spring-boot-autoconfigure`, and `slf4j-api`. - `spring-boot-configuration-processor` is annotation-processor-only; no broad Boot starter or - external file-client SDK is allowed. +- Project deps: SSOT is the `adapter-outbound-fileserver` entry in + `src/config/architecture/modules.json`; `src/build.gradle` enforces it. No `:domain-core`. +- External runtime: JDK filesystem, `spring-boot-autoconfigure`, `micrometer-core` and `slf4j-api`. ## Forbidden -- Inbound adapters, sibling outbound adapters, persistence, `app-bootstrap`, `sample-portfolio` - (ArchUnit `OUTBOUND_ADAPTERS_*` family rules). -- Leaking filesystem, stream, framework, or provider types across `FilePublicationPort`. -- Advertising `FILE_AND_DIRECTORY_SYNC` as physical device/controller/replica/site power-loss - protection. It is the attested local file/directory force boundary only. -- For the **publication/export** capability, advertising `shared-mounted`/NFS, SFTP, cross-node - fencing, reaper, retention, quota, readiness/health, metrics, tracing, or audit as implemented. - This restriction does not apply to HTTP-platform features explicitly implemented under - `platform/**` and listed in `docs/fileserver/support-matrix.md`. -- Auto-promoting canonical R1 artifacts: schema v1 is strict read-only compatibility and retains - `PROCESS_LOCAL_SYNC`; R2 writes schema v2 only. -- Adding a second production provider without an explicit selector and startup ambiguity tests. +- Inbound adapters, persistence, `app-bootstrap`, `sample-portfolio` (ArchUnit + `OUTBOUND_ADAPTERS_*` family rules). +- Leaking filesystem, stream, framework, or provider types across the application ports. +- Advertising a platform feature as implemented unless `docs/fileserver/support-matrix.md` lists it. - Fully-qualified inline type references; more than one public top-level type per file. ## Tests -The focused suite includes contract/R1 compatibility, R2 binding/routing, strict root attestation, -canonical control records, secure control/payload operations, deterministic recovery, -forked-process crash/OS-lock qualification, Spring composition, and the legacy adapter. - ```bash cd src ./gradlew :adapter:outbound:fileserver:check diff --git a/src/adapter/outbound/fileserver/README.md b/src/adapter/outbound/fileserver/README.md index 72e17126..c3b00f9b 100644 --- a/src/adapter/outbound/fileserver/README.md +++ b/src/adapter/outbound/fileserver/README.md @@ -1,145 +1,28 @@ # adapter:outbound:fileserver — design-decision reference -File-server publication outbound (driven) adapter. Package root: -`dev.caskeleton.adapter.outbound.fileserver`. It implements the framework-free -`application-core` `FilePublicationPort` and temporarily retains the legacy `FileExportPort`. -Publication and the legacy compatibility port have separate opt-in selectors. +Outbound (driven) adapter for the HTTP Fileserver platform. Package root: +`dev.caskeleton.adapter.outbound.fileserver.platform`. It implements the `application-fileserver` +ports: local filesystem content storage, upload verification, identifiers, audit and metrics. The allowed/forbidden production dependency policy is owned by the `adapter-outbound-fileserver` entry in `src/config/architecture/modules.json`; root Gradle -verification reads that registry. Module rules live in [CLAUDE.md](CLAUDE.md); this document -records the **design rationale** lifted out of the code comments. +verification reads that registry. Module rules live in [CLAUDE.md](CLAUDE.md). -This leaf also contains the HTTP Fileserver platform under `platform/**`; its transport/security/ -operations contracts live in `docs/fileserver/`. The publication/export capability documented below -and the HTTP platform share a leaf but have separate activation namespaces and evidence. - -For the repository-level choice between this Fileserver platform and Object Storage, see +Transport, security, configuration and operations contracts live in `docs/fileserver/`. For the +repository-level choice between this Fileserver platform and Object Storage, see [`docs/storage-capability-boundary.md`](../../../docs/storage-capability-boundary.md). -## Implemented capability +## Activation -The application-facing contract remains provider-neutral: callers select a logical -`FileDestinationId` through `FilePublicationPort` and never receive a path, host, mount, Spring, or -NIO type. Inside this leaf, `RoutingFilePublicationAdapter` performs an exact destination lookup -before producer invocation. The canonical operation/manifest/reference records and the provider -boundary are shared control-plane concepts; the only implemented R2 persistence/publication -provider is currently `local-persistent`. - -`local-persistent` is an explicit, fail-closed provider for a pre-provisioned absolute filesystem -root. Startup compiles destination policy, rejects implicit/default providers and shared-root -double ownership, attests owner/mode/FileStore/mount-sentinel/path identity, requires -`SecureDirectoryStream`, and probes exclusive create, hard-link publication, and file/directory -force. One provider/control/payload runtime is shared by every destination that names the same -provider ID. - -An accepted publication streams typed rows once, applies CSV/schema/formula/size policy, writes and -forces a private stage, and advances the forced control plane through: - -```text -WRITING -> SEALED -> DATA_PUBLISHED -> MANIFEST_PUBLISHED - -> REFERENCE_PUBLISHED -> PUBLISHED -``` - -Data is published with an exclusive no-overwrite hard link. A private manifest and direct opaque -reference index are forced before the terminal operation record. Recovery uses the operation ID, -validates data/manifest/reference/receipt equality, and either restores the exact receipt, resumes -from verified sealed bytes without replaying the producer, or fails closed as -indeterminate/quarantined. Terminal mismatches preserve all evidence. Operation-scoped JVM and OS -file locks serialize cooperating processes that use the same attested root. - -The R2 selector is `app.fileserver.enabled=true` and defaults to `false` in -`app-bootstrap/application.yml`. The leaf is included by `app-bootstrap`, but disabled composition -performs no root attestation or filesystem initialization. Enabling R2 requires an exact -destination/provider graph and all local attestation inputs. - -## Publication contract - -The current contract is: - -- `FilePublishReceipt publish(FilePublishRequest, TabularRowProducer)`. - -The request uses `FileDestinationId`, `FilePublishOperationId`, `LogicalFileName`, -`SourceRevision`, and `ExportSchema`; it has no `Path`, `File`, Spring, stream, or provider type. -`TabularCell` preserves value types until encoding. The producer writes rows to a bounded sink and -can call `checkpoint()` for cooperative interruption checks. - -`FileExportPort.exportCsv(...)` remains as `@Deprecated(forRemoval = true)` compatibility only. It materializes all rows, writes -directly to a separate final-path root, permits overwrite, accepts only a bare file name, and -returns an absolute path. It must not be used as -R2 durability or cluster-safety evidence. - -## Settings - -- `app.fileserver.enabled=false` -- `app.fileserver.destinations..provider-ref=` -- `app.fileserver.destinations..required-publication=unique-atomic-create` -- `app.fileserver.destinations..required-durability=file-and-directory-sync` -- `app.fileserver.destinations..maximum-rows` -- `app.fileserver.destinations..maximum-encoded-bytes` -- `app.fileserver.providers..type=local-persistent` -- `app.fileserver.providers..root-directory` -- `app.fileserver.providers..auto-create=false` -- `app.fileserver.providers..strict-path-security=true` -- `app.fileserver.providers..expected-file-store-name` -- `app.fileserver.providers..expected-file-store-type` -- `app.fileserver.providers..mount-sentinel-name` -- `app.fileserver.providers..mount-sentinel-sha256` -- `app.fileserver.providers..expected-owner` -- `app.fileserver.providers..maximum-root-mode` - -The shipped composition maps the five topology-specific values to -`APP_FILESERVER_LOCAL_ROOT`, `APP_FILESERVER_LOCAL_EXPECTED_FILE_STORE_NAME`, -`APP_FILESERVER_LOCAL_EXPECTED_FILE_STORE_TYPE`, -`APP_FILESERVER_LOCAL_MOUNT_SENTINEL_SHA256`, and `APP_FILESERVER_LOCAL_EXPECTED_OWNER`. They are -restart-only and required when `app.fileserver.enabled=true`; blank disabled defaults are not a -local-filesystem fallback. - -Unknown R2 properties fail binding. The provider always fails closed if the filesystem cannot -supply the required secure relative operations, exclusive hard-link creation, and force -boundaries. There is no copy-to-final, overwrite-capable rename, or guarantee downgrade fallback. - -## Guarantee boundary - -`local-persistent` is the only R2 provider implemented and qualified by this module. Its -`FILE_AND_DIRECTORY_SYNC` receipt means the implementation successfully forced the file and -relevant directories inside the attested local filesystem protocol. It does **not** claim physical -device, storage-controller cache, volume-replica, backup, or site-level power-loss protection; -those require deployment/storage evidence. - -`shared-mounted`/NFS and SFTP providers are not implemented. Cross-node producer fencing, -background reconciliation/reaping, retention, quota/backpressure, readiness/health, metrics, -tracing, and audit are also not implemented. No setting or bean for those capabilities is exposed. - -The prior `LocalFilePublicationAdapter` remains a separately selected R1 compatibility runtime -under `app.file-export.enabled=true`; the deprecated legacy port additionally -requires `app.file-export.legacy-enabled=true` and a separate root. R1 and R2 selectors -cannot be enabled together. When an attested R2 root contains a canonical terminal R1 journal and -matching root-level artifact, R2 may restore its original `PROCESS_LOCAL_SYNC` receipt read-only. -It never writes schema v1, creates an R2 manifest/reference for that artifact, or promotes its -durability guarantee. +`app.fileserver-platform.enabled=true` (default `false`). While it is off, the auto-configuration +that binds the block is not processed, so nothing is created. See +`docs/fileserver/configuration.md` for the keys. ## Tests -- `FilePublicationContractTest`: framework-free values and invalid contract inputs. -- `LocalFilePublicationAdapterTest`: streaming, limits, type checks, formula mitigation, receipt, - publication, and staging cleanup. -- `LocalPublicationJournalTest`: canonical request fingerprint and strict journal integrity. -- `LocalFilePublicationRecoveryTest`: restart receipt restoration, sealed resume, conflict, and - artifact-integrity handling. -- `FileserverBindingCompilerTest`: exact destination/provider compilation and guarantee policy. -- `LocalPersistentRootAttestorTest`: root, owner, mode, FileStore, sentinel, path, and capability - attestation. -- `FileserverControlRecordCodecTest`: canonical v2 operation/manifest/reference records and strict - R1 read-only dispatch. -- `LocalPersistentControlPlaneTest`: secure record replacement, locking, and failure boundaries. -- `LocalPersistentPayloadOperationsTest`: secure bounded stage/data operations and force behavior. -- `LocalPersistentPublicationProviderTest` and `LocalPersistentPublicationRecoveryTest`: ordered - publication and deterministic state recovery. -- `FileserverR2ConfigTest` and `FilePublicationConfigTest`: disabled side-effect freedom, exact - routing, selector ambiguity, and R1/R2 bean composition. -- `LocalPersistentCrashRecoveryTest`: forked-process force-boundary and OS-lock qualification. -- `FilesystemCsvExportAdapterTest`: legacy compatibility path. +- `platform/**`: auto-configuration, local storage, security and verification tests. +- `testkit/`: content-store contract, crash-recovery matrix, large-file memory bound and the NFS/PVC + certification helpers. ```bash cd src diff --git a/src/adapter/outbound/fileserver/build.gradle b/src/adapter/outbound/fileserver/build.gradle index 174c5354..7e29d813 100644 --- a/src/adapter/outbound/fileserver/build.gradle +++ b/src/adapter/outbound/fileserver/build.gradle @@ -3,12 +3,7 @@ plugins { id 'ca.spring-config' } -// Driven adapter for provider-neutral file publication and legacy CSV export. The only qualified -// R2 provider is local-persistent; shared-mounted/NFS and SFTP are not stand-ins or implemented -// capabilities. Its IO path uses only the JDK. Spring Boot autoconfigure supplies explicit, -// disabled-default R1/R2 composition and SLF4J remains the diagnostics API. -description = 'Outbound adapter: file publication (R1 CSV export, R2 local-persistent) plus the ' + \ - 'local filesystem content platform behind the HTTP Fileserver' +description = 'Outbound adapter: local filesystem content platform behind the HTTP Fileserver' dependencies { implementation project(':application-core') diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/CompiledFileDestination.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/CompiledFileDestination.java deleted file mode 100644 index b121a709..00000000 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/CompiledFileDestination.java +++ /dev/null @@ -1,198 +0,0 @@ -package dev.caskeleton.adapter.outbound.fileserver; - -import dev.caskeleton.application.filepublication.FileDestinationId; -import dev.caskeleton.application.filepublication.FilePublishReceipt.DurabilityGuarantee; -import dev.caskeleton.application.filepublication.FilePublishReceipt.PublicationGuarantee; -import java.nio.file.Path; -import java.nio.file.attribute.PosixFilePermission; -import java.util.Objects; -import java.util.Set; - -/** Framework-free, validated effective descriptor for one adapter-internal destination binding. */ -record CompiledFileDestination( - FileDestinationId destinationId, - String providerId, - Path rootDirectory, - long maximumRows, - long maximumEncodedBytes, - String expectedFileStoreName, - String expectedFileStoreType, - String mountSentinelName, - String mountSentinelSha256, - String expectedOwner, - String maximumRootMode, - Set maximumRootPermissions, - String effectivePolicyRevision, - String effectivePolicyDigest, - String routeToken, - String formatPolicyDigest, - PublicationGuarantee requiredPublicationGuarantee, - DurabilityGuarantee requiredDurabilityGuarantee) { - - CompiledFileDestination { - Objects.requireNonNull(destinationId, "destinationId must be non-null"); - providerId = FileserverR2Validation.requireNormalizedId("providerId", providerId); - rootDirectory = - FileserverR2Validation.requireAbsoluteNormalizedPath("rootDirectory", rootDirectory); - if (maximumRows < 1) { - throw new IllegalArgumentException("maximumRows must be positive"); - } - if (maximumEncodedBytes < 1) { - throw new IllegalArgumentException("maximumEncodedBytes must be positive"); - } - FileserverR2Validation.requireNonBlank("expectedFileStoreName", expectedFileStoreName); - FileserverR2Validation.requireNonBlank("expectedFileStoreType", expectedFileStoreType); - mountSentinelName = FileserverR2Validation.requireSentinelName(mountSentinelName); - mountSentinelSha256 = - FileserverR2Validation.requireSha256("mountSentinelSha256", mountSentinelSha256); - FileserverR2Validation.requireNonBlank("expectedOwner", expectedOwner); - maximumRootPermissions = - FileserverR2Validation.requireMatchingMaximumRootPermissions( - maximumRootMode, maximumRootPermissions); - if (requiredPublicationGuarantee != PublicationGuarantee.UNIQUE_ATOMIC_CREATE) { - throw new IllegalArgumentException( - "requiredPublicationGuarantee must be UNIQUE_ATOMIC_CREATE"); - } - if (requiredDurabilityGuarantee != DurabilityGuarantee.FILE_AND_DIRECTORY_SYNC) { - throw new IllegalArgumentException( - "requiredDurabilityGuarantee must be FILE_AND_DIRECTORY_SYNC"); - } - if (!FilePublicationCanonicalDigests.EFFECTIVE_POLICY_REVISION.equals( - effectivePolicyRevision)) { - throw new IllegalArgumentException( - "effectivePolicyRevision must be exactly " - + FilePublicationCanonicalDigests.EFFECTIVE_POLICY_REVISION); - } - FileserverR2Validation.requireSha256("effectivePolicyDigest", effectivePolicyDigest); - String canonicalEffectivePolicyDigest = - FilePublicationCanonicalDigests.effectivePolicyDigest( - FilePublicationCanonicalDigests.effectivePolicyDescriptor( - destinationId, - providerId, - maximumRows, - maximumEncodedBytes, - requiredPublicationGuarantee, - requiredDurabilityGuarantee)); - if (!canonicalEffectivePolicyDigest.equals(effectivePolicyDigest)) { - throw new IllegalArgumentException( - "effectivePolicyDigest must match the canonical destination policy"); - } - if (!FilePublicationCanonicalDigests.routeToken(effectivePolicyDigest).equals(routeToken)) { - throw new IllegalArgumentException("routeToken must be derived from effectivePolicyDigest"); - } - if (!FilePublicationCanonicalDigests.formatPolicyDigest().equals(formatPolicyDigest)) { - throw new IllegalArgumentException( - "formatPolicyDigest must match the canonical format policy"); - } - } - - CompiledFileDestination( - FileDestinationId destinationId, - String providerId, - Path rootDirectory, - long maximumRows, - long maximumEncodedBytes, - String expectedFileStoreName, - String expectedFileStoreType, - String mountSentinelName, - String mountSentinelSha256, - String expectedOwner, - String maximumRootMode, - Set maximumRootPermissions, - PublicationGuarantee requiredPublicationGuarantee, - DurabilityGuarantee requiredDurabilityGuarantee) { - this( - destinationId, - providerId, - rootDirectory, - maximumRows, - maximumEncodedBytes, - expectedFileStoreName, - expectedFileStoreType, - mountSentinelName, - mountSentinelSha256, - expectedOwner, - maximumRootMode, - maximumRootPermissions, - FilePublicationCanonicalDigests.effectivePolicyDescriptor( - destinationId, - providerId, - maximumRows, - maximumEncodedBytes, - requiredPublicationGuarantee, - requiredDurabilityGuarantee), - requiredPublicationGuarantee, - requiredDurabilityGuarantee); - } - - private CompiledFileDestination( - FileDestinationId destinationId, - String providerId, - Path rootDirectory, - long maximumRows, - long maximumEncodedBytes, - String expectedFileStoreName, - String expectedFileStoreType, - String mountSentinelName, - String mountSentinelSha256, - String expectedOwner, - String maximumRootMode, - Set maximumRootPermissions, - FilePublicationCanonicalDigests.EffectivePolicyDescriptor descriptor, - PublicationGuarantee requiredPublicationGuarantee, - DurabilityGuarantee requiredDurabilityGuarantee) { - this( - destinationId, - providerId, - rootDirectory, - maximumRows, - maximumEncodedBytes, - expectedFileStoreName, - expectedFileStoreType, - mountSentinelName, - mountSentinelSha256, - expectedOwner, - maximumRootMode, - maximumRootPermissions, - FilePublicationCanonicalDigests.compiledIdentity(descriptor), - requiredPublicationGuarantee, - requiredDurabilityGuarantee); - } - - private CompiledFileDestination( - FileDestinationId destinationId, - String providerId, - Path rootDirectory, - long maximumRows, - long maximumEncodedBytes, - String expectedFileStoreName, - String expectedFileStoreType, - String mountSentinelName, - String mountSentinelSha256, - String expectedOwner, - String maximumRootMode, - Set maximumRootPermissions, - FilePublicationCanonicalDigests.CompiledIdentity identity, - PublicationGuarantee requiredPublicationGuarantee, - DurabilityGuarantee requiredDurabilityGuarantee) { - this( - destinationId, - providerId, - rootDirectory, - maximumRows, - maximumEncodedBytes, - expectedFileStoreName, - expectedFileStoreType, - mountSentinelName, - mountSentinelSha256, - expectedOwner, - maximumRootMode, - maximumRootPermissions, - identity.effectivePolicyRevision(), - identity.effectivePolicyDigest(), - identity.routeToken(), - identity.formatPolicyDigest(), - requiredPublicationGuarantee, - requiredDurabilityGuarantee); - } -} diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/DurablePublicationRecord.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/DurablePublicationRecord.java deleted file mode 100644 index 4289cbad..00000000 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/DurablePublicationRecord.java +++ /dev/null @@ -1,255 +0,0 @@ -package dev.caskeleton.adapter.outbound.fileserver; - -import java.time.Instant; -import java.util.Objects; - -/** Immutable schema-v2 durable operation journal record. */ -record DurablePublicationRecord( - int schemaVersion, - long stateRevision, - State state, - String operationId, - String requestFingerprint, - String effectivePolicyRevision, - String effectivePolicyDigest, - String destinationId, - String providerId, - String fileId, - String routeToken, - String publishedFileName, - String stageFileName, - long byteSize, - long rowCount, - int columnCount, - String sha256, - long formulaMitigatedCount, - String manifestDigest, - String referenceDigest, - Instant createdAt, - Instant sealedAt, - Instant publishedAt, - String lastFailureCode, - String receiptSnapshot) { - - static final int CURRENT_SCHEMA_VERSION = 2; - - DurablePublicationRecord { - if (schemaVersion != CURRENT_SCHEMA_VERSION) { - throw new IllegalArgumentException("unsupported durable publication record schema"); - } - Objects.requireNonNull(state, "state must be non-null"); - if (stateRevision < state.minimumRevision()) { - throw new IllegalArgumentException("stateRevision is behind the durable publication state"); - } - FileserverControlRecordCodec.requireText(operationId, "operationId", 128); - FileserverControlRecordCodec.requireDigest(requestFingerprint, "requestFingerprint"); - FileserverControlRecordCodec.requireText( - effectivePolicyRevision, "effectivePolicyRevision", 128); - FileserverControlRecordCodec.requireDigest(effectivePolicyDigest, "effectivePolicyDigest"); - FileserverControlRecordCodec.requireLogicalId(destinationId, "destinationId"); - FileserverControlRecordCodec.requireLogicalId(providerId, "providerId"); - FileserverControlRecordCodec.requireFileId(fileId); - FileserverControlRecordCodec.requireRouteToken(routeToken); - FileserverControlRecordCodec.requireSegment(publishedFileName, "publishedFileName"); - FileserverControlRecordCodec.requireSegment(stageFileName, "stageFileName"); - FileserverControlRecordCodec.requireInstant(createdAt, "createdAt"); - FileserverControlRecordCodec.requireOptionalFailureCode(lastFailureCode); - FileserverControlRecordCodec.requireOptionalDigest(sha256, "sha256"); - FileserverControlRecordCodec.requireOptionalDigest(manifestDigest, "manifestDigest"); - FileserverControlRecordCodec.requireOptionalDigest(referenceDigest, "referenceDigest"); - FileserverControlRecordCodec.requireNoControl(receiptSnapshot, "receiptSnapshot", 12_288); - - if (byteSize < 0 || rowCount < 0 || columnCount < 0 || formulaMitigatedCount < 0) { - throw new IllegalArgumentException("operation sizes and counts must be non-negative"); - } - FileserverControlRecordCodec.requireFormulaCountWithinCells( - rowCount, columnCount, formulaMitigatedCount, "operation"); - - if (state == State.WRITING) { - requireWritingPresence( - byteSize, - rowCount, - columnCount, - sha256, - formulaMitigatedCount, - manifestDigest, - referenceDigest, - sealedAt, - publishedAt, - lastFailureCode, - receiptSnapshot); - } else if (state == State.QUARANTINED) { - requireQuarantinedPresence( - byteSize, - rowCount, - columnCount, - sha256, - formulaMitigatedCount, - manifestDigest, - referenceDigest, - sealedAt, - publishedAt, - lastFailureCode, - receiptSnapshot, - createdAt); - } else { - requireProgressedPresence( - state, - byteSize, - columnCount, - sha256, - manifestDigest, - referenceDigest, - createdAt, - sealedAt, - publishedAt, - lastFailureCode, - receiptSnapshot); - if (state == State.PUBLISHED) { - FileserverControlRecordCodec.validateReceiptSnapshot( - receiptSnapshot, - operationId, - destinationId, - publishedFileName, - byteSize, - rowCount, - columnCount, - sha256, - formulaMitigatedCount, - publishedAt, - routeToken, - fileId); - } - } - } - - private static void requireWritingPresence( - long byteSize, - long rowCount, - int columnCount, - String sha256, - long formulaMitigatedCount, - String manifestDigest, - String referenceDigest, - Instant sealedAt, - Instant publishedAt, - String lastFailureCode, - String receiptSnapshot) { - if (byteSize != 0 - || rowCount != 0 - || columnCount != 0 - || formulaMitigatedCount != 0 - || !FileserverControlRecordCodec.allBlank( - sha256, manifestDigest, referenceDigest, lastFailureCode, receiptSnapshot) - || sealedAt != null - || publishedAt != null) { - throw new IllegalArgumentException("WRITING record contains progressed fields"); - } - } - - private static void requireProgressedPresence( - State state, - long byteSize, - int columnCount, - String sha256, - String manifestDigest, - String referenceDigest, - Instant createdAt, - Instant sealedAt, - Instant publishedAt, - String lastFailureCode, - String receiptSnapshot) { - if (byteSize < 0 || columnCount < 1) { - throw new IllegalArgumentException("sealed record sizes are incomplete"); - } - FileserverControlRecordCodec.requireDigest(sha256, "sha256"); - FileserverControlRecordCodec.requireOrderedInstant(createdAt, sealedAt, "sealedAt"); - if (!lastFailureCode.isEmpty()) { - throw new IllegalArgumentException("non-quarantined record contains lastFailureCode"); - } - - requireDigestPresence( - state.minimumRevision() >= State.MANIFEST_PUBLISHED.minimumRevision(), - manifestDigest, - "manifestDigest"); - requireDigestPresence( - state.minimumRevision() >= State.REFERENCE_PUBLISHED.minimumRevision(), - referenceDigest, - "referenceDigest"); - - if (state == State.PUBLISHED) { - FileserverControlRecordCodec.requireOrderedInstant(sealedAt, publishedAt, "publishedAt"); - } else if (publishedAt != null || !receiptSnapshot.isEmpty()) { - throw new IllegalArgumentException("non-terminal record contains terminal receipt fields"); - } - } - - private static void requireQuarantinedPresence( - long byteSize, - long rowCount, - int columnCount, - String sha256, - long formulaMitigatedCount, - String manifestDigest, - String referenceDigest, - Instant sealedAt, - Instant publishedAt, - String lastFailureCode, - String receiptSnapshot, - Instant createdAt) { - if (lastFailureCode.isEmpty()) { - throw new IllegalArgumentException("QUARANTINED record requires lastFailureCode"); - } - if (publishedAt != null || !receiptSnapshot.isEmpty()) { - throw new IllegalArgumentException("QUARANTINED record cannot contain a receipt"); - } - if (sha256.isEmpty()) { - if (byteSize != 0 - || rowCount != 0 - || columnCount != 0 - || formulaMitigatedCount != 0 - || sealedAt != null - || !manifestDigest.isEmpty() - || !referenceDigest.isEmpty()) { - throw new IllegalArgumentException("unsealed QUARANTINED record is inconsistent"); - } - return; - } - FileserverControlRecordCodec.requireDigest(sha256, "sha256"); - if (columnCount < 1) { - throw new IllegalArgumentException("sealed QUARANTINED record requires columnCount"); - } - FileserverControlRecordCodec.requireOrderedInstant(createdAt, sealedAt, "sealedAt"); - if (!referenceDigest.isEmpty() && manifestDigest.isEmpty()) { - throw new IllegalArgumentException("referenceDigest requires manifestDigest"); - } - } - - private static void requireDigestPresence(boolean required, String digest, String field) { - if (required) { - FileserverControlRecordCodec.requireDigest(digest, field); - } else if (!digest.isEmpty()) { - throw new IllegalArgumentException(field + " appears before its publication state"); - } - } - - enum State { - WRITING(1), - SEALED(2), - DATA_PUBLISHED(3), - MANIFEST_PUBLISHED(4), - REFERENCE_PUBLISHED(5), - PUBLISHED(6), - QUARANTINED(2); - - private final long minimumRevision; - - State(long minimumRevision) { - this.minimumRevision = minimumRevision; - } - - long minimumRevision() { - return minimumRevision; - } - } -} diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/FileExportConfig.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/FileExportConfig.java deleted file mode 100644 index d4688758..00000000 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/FileExportConfig.java +++ /dev/null @@ -1,75 +0,0 @@ -package dev.caskeleton.adapter.outbound.fileserver; - -import dev.caskeleton.application.fileexport.FileExportPort; -import dev.caskeleton.application.filepublication.FileDestinationId; -import dev.caskeleton.application.filepublication.FilePublicationPort; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.Environment; - -/** - * Opt-in wiring for the file-server export adapter. The single {@link FileExportPort} bean is - * contributed only when {@code app.file-export.enabled=true}, so the module never activates - * unexpectedly when merely present on the classpath (there is a single implementation, so no - * backend selector is needed). The adapter is a plain class; this config assembles it as a bean, - * mirroring the object-storage module. - */ -@Configuration(proxyBeanMethods = false) -@ConditionalOnProperty(prefix = "app.file-export", name = "enabled", havingValue = "true") -@EnableConfigurationProperties(FileExportSettings.class) -@SuppressWarnings("removal") -public class FileExportConfig { - - @Bean - @ConditionalOnProperty( - prefix = "app.file-export", - name = {"enabled", "legacy-enabled"}, - havingValue = "true") - public FileExportPort filesystemCsvExportPort( - FileExportSettings properties, Environment environment) { - FileserverActivationValidator.rejectAmbiguous(environment); - Path publicationRoot = configuredRoot(properties.getBaseDirectory(), "base-directory"); - Path legacyRoot = configuredRoot(properties.getLegacyBaseDirectory(), "legacy-base-directory"); - Path canonicalPublicationRoot = canonicalDirectory(publicationRoot); - Path canonicalLegacyRoot = canonicalDirectory(legacyRoot); - if (canonicalPublicationRoot.startsWith(canonicalLegacyRoot) - || canonicalLegacyRoot.startsWith(canonicalPublicationRoot)) { - throw new IllegalStateException("fileserver publication and legacy roots must not overlap"); - } - return new FilesystemCsvExportAdapter(legacyRoot.toString()); - } - - @Bean - @ConditionalOnProperty(prefix = "app.file-export", name = "enabled", havingValue = "true") - public FilePublicationPort localFilePublicationPort( - FileExportSettings properties, Environment environment) { - FileserverActivationValidator.rejectAmbiguous(environment); - return new LocalFilePublicationAdapter( - new LocalFilePublicationPolicy( - new FileDestinationId(properties.getDestinationId()), - configuredRoot(properties.getBaseDirectory(), "base-directory"), - properties.getMaximumRows(), - properties.getMaximumEncodedBytes())); - } - - private static Path configuredRoot(String value, String property) { - if (value == null || value.isBlank()) { - throw new IllegalArgumentException("app.file-export." + property + " must be non-blank"); - } - return Path.of(value).toAbsolutePath().normalize(); - } - - private static Path canonicalDirectory(Path root) { - try { - Files.createDirectories(root); - return root.toRealPath(); - } catch (IOException exception) { - throw new IllegalStateException("fileserver root cannot be canonicalized", exception); - } - } -} diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/FileExportSettings.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/FileExportSettings.java deleted file mode 100644 index dc9a6cd8..00000000 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/FileExportSettings.java +++ /dev/null @@ -1,92 +0,0 @@ -package dev.caskeleton.adapter.outbound.fileserver; - -import org.springframework.boot.context.properties.ConfigurationProperties; - -/** - * Typed settings for the file-server export adapter, bound from {@code app.file-export.*}. Bound as - * a mutable JavaBean (not a record) so a fork can leave any subset of fields unset and inherit the - * defaults below. - */ -@ConfigurationProperties(prefix = "app.file-export") -public class FileExportSettings { - - /** - * Whether to contribute the export adapter. Defaults to {@code false} so the module never - * activates unexpectedly when merely present on the classpath; a fork opts in explicitly. - */ - private boolean enabled = false; - - /** Whether to expose the overwrite-capable legacy port. Always requires {@link #enabled}. */ - private boolean legacyEnabled = false; - - /** Base directory that export files are written under (stand-in for an NFS/SFTP drop). */ - private String baseDirectory = "./.data/fileserver"; - - /** Separate root for the legacy overwrite-capable port; never shares publication control data. */ - private String legacyBaseDirectory = "./.data/fileserver-legacy"; - - /** Logical destination identifier exposed to application-core; never a path or host. */ - private String destinationId = "local-export"; - - /** Hard upper bound for data rows accepted by one streaming publication. */ - private long maximumRows = 1_000_000; - - /** Hard upper bound for encoded bytes, including the CSV header. */ - private long maximumEncodedBytes = 1_073_741_824; - - public boolean isEnabled() { - return enabled; - } - - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } - - public boolean isLegacyEnabled() { - return legacyEnabled; - } - - public void setLegacyEnabled(boolean legacyEnabled) { - this.legacyEnabled = legacyEnabled; - } - - public String getBaseDirectory() { - return baseDirectory; - } - - public void setBaseDirectory(String baseDirectory) { - this.baseDirectory = baseDirectory; - } - - public String getLegacyBaseDirectory() { - return legacyBaseDirectory; - } - - public void setLegacyBaseDirectory(String legacyBaseDirectory) { - this.legacyBaseDirectory = legacyBaseDirectory; - } - - public String getDestinationId() { - return destinationId; - } - - public void setDestinationId(String destinationId) { - this.destinationId = destinationId; - } - - public long getMaximumRows() { - return maximumRows; - } - - public void setMaximumRows(long maximumRows) { - this.maximumRows = maximumRows; - } - - public long getMaximumEncodedBytes() { - return maximumEncodedBytes; - } - - public void setMaximumEncodedBytes(long maximumEncodedBytes) { - this.maximumEncodedBytes = maximumEncodedBytes; - } -} diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/FilePublicationCanonicalDigests.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/FilePublicationCanonicalDigests.java deleted file mode 100644 index b3f87f2c..00000000 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/FilePublicationCanonicalDigests.java +++ /dev/null @@ -1,201 +0,0 @@ -package dev.caskeleton.adapter.outbound.fileserver; - -import dev.caskeleton.application.filepublication.ExportSchema; -import dev.caskeleton.application.filepublication.ExportSchema.Column; -import dev.caskeleton.application.filepublication.FileDestinationId; -import dev.caskeleton.application.filepublication.FilePublishReceipt.DurabilityGuarantee; -import dev.caskeleton.application.filepublication.FilePublishReceipt.PublicationGuarantee; -import java.nio.ByteBuffer; -import java.nio.CharBuffer; -import java.nio.charset.CharacterCodingException; -import java.nio.charset.CodingErrorAction; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.ArrayList; -import java.util.HexFormat; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Objects; - -/** Restart-stable canonical identities for the R2 destination, schema, and format policies. */ -final class FilePublicationCanonicalDigests { - - static final String EFFECTIVE_POLICY_REVISION = "fileserver-effective-policy-v1"; - static final String FORMAT_ENCODER_REVISION = "csv-rfc4180-encoder-v1"; - - private static final HexFormat HEX = HexFormat.of(); - - private FilePublicationCanonicalDigests() {} - - static EffectivePolicyDescriptor effectivePolicyDescriptor( - FileDestinationId destinationId, - String providerId, - long maximumRows, - long maximumEncodedBytes, - PublicationGuarantee requiredPublicationGuarantee, - DurabilityGuarantee requiredDurabilityGuarantee) { - return new EffectivePolicyDescriptor( - destinationId, - providerId, - maximumRows, - maximumEncodedBytes, - requiredPublicationGuarantee, - requiredDurabilityGuarantee, - FORMAT_ENCODER_REVISION); - } - - static String effectivePolicyDigest(EffectivePolicyDescriptor descriptor) { - Objects.requireNonNull(descriptor, "descriptor must be non-null"); - Map fields = new LinkedHashMap<>(); - fields.put("destinationId", descriptor.destinationId().value()); - fields.put("providerId", descriptor.providerId()); - fields.put("maximumRows", Long.toString(descriptor.maximumRows())); - fields.put("maximumEncodedBytes", Long.toString(descriptor.maximumEncodedBytes())); - fields.put("requiredPublicationGuarantee", descriptor.requiredPublicationGuarantee().name()); - fields.put("requiredDurabilityGuarantee", descriptor.requiredDurabilityGuarantee().name()); - fields.put("formatEncoderRevision", descriptor.formatEncoderRevision()); - return digestNamedFields(fields); - } - - static CompiledIdentity compiledIdentity(EffectivePolicyDescriptor descriptor) { - String effectivePolicyDigest = effectivePolicyDigest(descriptor); - return compiledIdentity(effectivePolicyDigest); - } - - static CompiledIdentity compiledIdentity(String effectivePolicyDigest) { - FileserverR2Validation.requireSha256("effectivePolicyDigest", effectivePolicyDigest); - return new CompiledIdentity( - EFFECTIVE_POLICY_REVISION, - effectivePolicyDigest, - routeToken(effectivePolicyDigest), - formatPolicyDigest()); - } - - static String schemaDigest(ExportSchema schema) { - Objects.requireNonNull(schema, "schema must be non-null"); - Map fields = new LinkedHashMap<>(); - fields.put("schemaId", schema.schemaId()); - fields.put("schemaVersion", Integer.toString(schema.version())); - fields.put("columnCount", Integer.toString(schema.columns().size())); - for (int index = 0; index < schema.columns().size(); index++) { - Column column = schema.columns().get(index); - String prefix = "column." + String.format(Locale.ROOT, "%08d", index) + "."; - fields.put(prefix + "name", column.name()); - fields.put(prefix + "cellType", column.cellType().name()); - fields.put(prefix + "nullable", Boolean.toString(column.nullable())); - fields.put(prefix + "maximumUtf8Bytes", Integer.toString(column.maximumUtf8Bytes())); - fields.put(prefix + "formulaPolicy", column.formulaPolicy().name()); - } - return digestNamedFields(fields); - } - - static String formatPolicyDigest() { - Map fields = new LinkedHashMap<>(); - fields.put("formatEncoderRevision", FORMAT_ENCODER_REVISION); - fields.put("formatProfileId", "csv-rfc4180-v1"); - fields.put("charset", StandardCharsets.UTF_8.name()); - fields.put("delimiter", ","); - fields.put("quote", "\""); - fields.put("recordSeparator", "LF"); - fields.put("nullCell", "empty"); - fields.put("formulaMitigationPrefix", "'"); - return digestNamedFields(fields); - } - - static String routeToken(String effectivePolicyDigest) { - String validated = - FileserverR2Validation.requireSha256("effectivePolicyDigest", effectivePolicyDigest); - return "r" + validated.substring(0, 31); - } - - static String digestNamedFields(Map fields) { - Objects.requireNonNull(fields, "fields must be non-null"); - List orderedValues = new ArrayList<>(fields.size() * 2); - fields.entrySet().stream() - .sorted(Map.Entry.comparingByKey()) - .forEach( - entry -> { - orderedValues.add( - Objects.requireNonNull(entry.getKey(), "field name must be non-null")); - orderedValues.add( - Objects.requireNonNull(entry.getValue(), "field value must be non-null")); - }); - return digestOrderedValues(orderedValues); - } - - static String digestOrderedValues(List values) { - Objects.requireNonNull(values, "values must be non-null"); - MessageDigest digest = sha256(); - digest.update(intBytes(values.size())); - for (String value : values) { - byte[] encoded = - strictUtf8(Objects.requireNonNull(value, "canonical value must be non-null")); - digest.update(intBytes(encoded.length)); - digest.update(encoded); - } - return HEX.formatHex(digest.digest()); - } - - private static byte[] strictUtf8(String value) { - try { - ByteBuffer encoded = - StandardCharsets.UTF_8 - .newEncoder() - .onMalformedInput(CodingErrorAction.REPORT) - .onUnmappableCharacter(CodingErrorAction.REPORT) - .encode(CharBuffer.wrap(value)); - byte[] bytes = new byte[encoded.remaining()]; - encoded.get(bytes); - return bytes; - } catch (CharacterCodingException exception) { - throw new IllegalArgumentException("canonical value must be valid UTF-8", exception); - } - } - - private static byte[] intBytes(int value) { - return ByteBuffer.allocate(Integer.BYTES).putInt(value).array(); - } - - private static MessageDigest sha256() { - try { - return MessageDigest.getInstance("SHA-256"); - } catch (NoSuchAlgorithmException exception) { - throw new IllegalStateException("SHA-256 unavailable", exception); - } - } - - record EffectivePolicyDescriptor( - FileDestinationId destinationId, - String providerId, - long maximumRows, - long maximumEncodedBytes, - PublicationGuarantee requiredPublicationGuarantee, - DurabilityGuarantee requiredDurabilityGuarantee, - String formatEncoderRevision) { - - EffectivePolicyDescriptor { - Objects.requireNonNull(destinationId, "destinationId must be non-null"); - providerId = FileserverR2Validation.requireNormalizedId("providerId", providerId); - if (maximumRows < 1) { - throw new IllegalArgumentException("maximumRows must be positive"); - } - if (maximumEncodedBytes < 1) { - throw new IllegalArgumentException("maximumEncodedBytes must be positive"); - } - Objects.requireNonNull( - requiredPublicationGuarantee, "requiredPublicationGuarantee must be non-null"); - Objects.requireNonNull( - requiredDurabilityGuarantee, "requiredDurabilityGuarantee must be non-null"); - FileserverR2Validation.requireNonBlank("formatEncoderRevision", formatEncoderRevision); - } - } - - record CompiledIdentity( - String effectivePolicyRevision, - String effectivePolicyDigest, - String routeToken, - String formatPolicyDigest) {} -} diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/FilePublicationProvider.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/FilePublicationProvider.java deleted file mode 100644 index 54233811..00000000 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/FilePublicationProvider.java +++ /dev/null @@ -1,15 +0,0 @@ -package dev.caskeleton.adapter.outbound.fileserver; - -import dev.caskeleton.application.filepublication.FilePublishReceipt; -import dev.caskeleton.application.filepublication.FilePublishRequest; -import dev.caskeleton.application.filepublication.TabularRowProducer; - -/** - * Adapter-internal provider selected only after exact destination routing. - * - *

Provider types remain private to this outbound adapter and never cross the application port. - */ -interface FilePublicationProvider { - - FilePublishReceipt publish(FilePublishRequest request, TabularRowProducer producer); -} diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/FilePublishRequestFingerprint.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/FilePublishRequestFingerprint.java deleted file mode 100644 index 129025a5..00000000 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/FilePublishRequestFingerprint.java +++ /dev/null @@ -1,77 +0,0 @@ -package dev.caskeleton.adapter.outbound.fileserver; - -import dev.caskeleton.application.filepublication.ExportSchema.Column; -import dev.caskeleton.application.filepublication.FilePublishRequest; -import java.nio.ByteBuffer; -import java.nio.CharBuffer; -import java.nio.charset.CharacterCodingException; -import java.nio.charset.CodingErrorAction; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.HexFormat; -import java.util.Objects; - -/** Canonical fingerprint for retry/recovery intent comparison. */ -final class FilePublishRequestFingerprint { - - private static final HexFormat HEX = HexFormat.of(); - - private FilePublishRequestFingerprint() {} - - static String calculate(FilePublishRequest request) { - Objects.requireNonNull(request, "request must be non-null"); - MessageDigest digest = sha256(); - update(digest, request.operationId().value()); - update(digest, request.destinationId().value()); - update(digest, request.logicalFileName().value()); - update(digest, request.sourceRevision().value()); - update(digest, request.formatProfileId()); - update(digest, request.schema().schemaId()); - update(digest, request.schema().version()); - update(digest, request.schema().columns().size()); - for (Column column : request.schema().columns()) { - update(digest, column.name()); - update(digest, column.cellType().name()); - update(digest, column.nullable() ? 1 : 0); - update(digest, column.formulaPolicy().name()); - update(digest, column.maximumUtf8Bytes()); - } - return HEX.formatHex(digest.digest()); - } - - private static void update(MessageDigest digest, String value) { - byte[] bytes = strictUtf8(value); - digest.update(ByteBuffer.allocate(Integer.BYTES).putInt(bytes.length).array()); - digest.update(bytes); - } - - private static byte[] strictUtf8(String value) { - try { - ByteBuffer encoded = - StandardCharsets.UTF_8 - .newEncoder() - .onMalformedInput(CodingErrorAction.REPORT) - .onUnmappableCharacter(CodingErrorAction.REPORT) - .encode(CharBuffer.wrap(value)); - byte[] bytes = new byte[encoded.remaining()]; - encoded.get(bytes); - return bytes; - } catch (CharacterCodingException exception) { - throw new IllegalArgumentException( - "file publication request contains malformed Unicode", exception); - } - } - - private static void update(MessageDigest digest, int value) { - digest.update(ByteBuffer.allocate(Integer.BYTES).putInt(value).array()); - } - - private static MessageDigest sha256() { - try { - return MessageDigest.getInstance("SHA-256"); - } catch (NoSuchAlgorithmException exception) { - throw new IllegalStateException("SHA-256 unavailable", exception); - } - } -} diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/FileserverActivationValidator.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/FileserverActivationValidator.java deleted file mode 100644 index d8ebf9ff..00000000 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/FileserverActivationValidator.java +++ /dev/null @@ -1,22 +0,0 @@ -package dev.caskeleton.adapter.outbound.fileserver; - -import org.springframework.boot.context.properties.bind.Bindable; -import org.springframework.boot.context.properties.bind.Binder; -import org.springframework.core.env.Environment; - -/** Order-independent fail-fast validation for mutually exclusive R1 and R2 selectors. */ -final class FileserverActivationValidator { - - private FileserverActivationValidator() {} - - static void rejectAmbiguous(Environment environment) { - Binder binder = Binder.get(environment); - boolean legacy = - binder.bind("app.file-export.enabled", Bindable.of(Boolean.class)).orElse(false); - boolean r2 = binder.bind("app.fileserver.enabled", Bindable.of(Boolean.class)).orElse(false); - if (legacy && r2) { - throw new IllegalStateException( - "app.file-export.enabled and app.fileserver.enabled cannot both be true"); - } - } -} diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/FileserverBindingCompiler.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/FileserverBindingCompiler.java deleted file mode 100644 index d6a89051..00000000 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/FileserverBindingCompiler.java +++ /dev/null @@ -1,227 +0,0 @@ -package dev.caskeleton.adapter.outbound.fileserver; - -import dev.caskeleton.adapter.outbound.fileserver.FileserverR2Settings.DestinationSettings; -import dev.caskeleton.adapter.outbound.fileserver.FileserverR2Settings.ProviderSettings; -import dev.caskeleton.application.filepublication.FileDestinationId; -import dev.caskeleton.application.filepublication.FilePublishReceipt.DurabilityGuarantee; -import dev.caskeleton.application.filepublication.FilePublishReceipt.PublicationGuarantee; -import java.nio.file.Path; -import java.nio.file.attribute.PosixFilePermission; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Set; - -/** Fail-closed compiler for exact R2 destination/provider bindings. */ -final class FileserverBindingCompiler { - - private static final String LOCAL_PERSISTENT = "local-persistent"; - private static final String UNIQUE_ATOMIC_CREATE = "unique-atomic-create"; - private static final String FILE_AND_DIRECTORY_SYNC = "file-and-directory-sync"; - - private FileserverBindingCompiler() {} - - static Map compile(FileserverR2Settings settings) { - Objects.requireNonNull(settings, "settings must be non-null"); - if (!settings.enabled()) { - return Map.of(); - } - if (settings.destinations().isEmpty()) { - throw new IllegalArgumentException( - "app.fileserver destinations must be explicitly configured when enabled"); - } - if (settings.providers().isEmpty()) { - throw new IllegalArgumentException( - "app.fileserver providers must be explicitly configured when enabled"); - } - - Map providers = validateProviders(settings.providers()); - rejectSharedRootAcrossProviderIds(providers); - Map destinations = normalizeDestinations(settings.destinations()); - Map compiled = new LinkedHashMap<>(); - Map policyDigests = new LinkedHashMap<>(); - destinations.forEach( - (destinationId, destination) -> { - String providerId = - FileserverR2Validation.normalizeId("provider-ref", destination.providerRef()); - ValidatedProvider provider = providers.get(providerId); - if (provider == null) { - throw new IllegalArgumentException( - "destination " + destinationId + " references unknown provider-ref " + providerId); - } - validateDestination(destinationId, destination); - FileDestinationId applicationDestinationId = new FileDestinationId(destinationId); - FilePublicationCanonicalDigests.EffectivePolicyDescriptor policyDescriptor = - FilePublicationCanonicalDigests.effectivePolicyDescriptor( - applicationDestinationId, - providerId, - destination.maximumRows(), - destination.maximumEncodedBytes(), - PublicationGuarantee.UNIQUE_ATOMIC_CREATE, - DurabilityGuarantee.FILE_AND_DIRECTORY_SYNC); - String effectivePolicyDigest = - FilePublicationCanonicalDigests.effectivePolicyDigest(policyDescriptor); - policyDigests.put(applicationDestinationId, effectivePolicyDigest); - FilePublicationCanonicalDigests.CompiledIdentity identity = - FilePublicationCanonicalDigests.compiledIdentity(effectivePolicyDigest); - compiled.put( - applicationDestinationId, - new CompiledFileDestination( - applicationDestinationId, - providerId, - provider.rootDirectory(), - destination.maximumRows(), - destination.maximumEncodedBytes(), - provider.settings().expectedFileStoreName(), - provider.settings().expectedFileStoreType(), - provider.settings().mountSentinelName(), - provider.settings().mountSentinelSha256(), - provider.settings().expectedOwner(), - provider.settings().maximumRootMode(), - provider.maximumRootPermissions(), - identity.effectivePolicyRevision(), - identity.effectivePolicyDigest(), - identity.routeToken(), - identity.formatPolicyDigest(), - PublicationGuarantee.UNIQUE_ATOMIC_CREATE, - DurabilityGuarantee.FILE_AND_DIRECTORY_SYNC)); - }); - Map routeTokens = deriveUniqueRouteTokens(policyDigests); - compiled.forEach( - (destinationId, destination) -> { - if (!destination.routeToken().equals(routeTokens.get(destinationId))) { - throw new IllegalStateException("compiled route token differs from route registry"); - } - }); - return Map.copyOf(compiled); - } - - static Map deriveUniqueRouteTokens( - Map policyDigests) { - Objects.requireNonNull(policyDigests, "policyDigests must be non-null"); - Map routeOwners = new LinkedHashMap<>(); - Map routeTokens = new LinkedHashMap<>(); - policyDigests.forEach( - (destinationId, policyDigest) -> { - Objects.requireNonNull(destinationId, "destinationId must be non-null"); - String routeToken = FilePublicationCanonicalDigests.routeToken(policyDigest); - FileDestinationId existingRouteOwner = routeOwners.putIfAbsent(routeToken, destinationId); - if (existingRouteOwner != null) { - throw new IllegalArgumentException( - "compiled route token collision for " - + routeToken - + " between " - + existingRouteOwner.value() - + " and " - + destinationId.value()); - } - routeTokens.put(destinationId, routeToken); - }); - return Map.copyOf(routeTokens); - } - - private static Map validateProviders( - Map configuredProviders) { - Map providers = new LinkedHashMap<>(); - configuredProviders.forEach( - (configuredId, provider) -> { - String providerId = FileserverR2Validation.normalizeId("provider", configuredId); - if (providers.containsKey(providerId)) { - throw new IllegalArgumentException("duplicate normalized provider id: " + providerId); - } - providers.put(providerId, validateProvider(providerId, provider)); - }); - return providers; - } - - private static void rejectSharedRootAcrossProviderIds(Map providers) { - Map rootOwners = new LinkedHashMap<>(); - providers.forEach( - (providerId, provider) -> { - String existing = rootOwners.putIfAbsent(provider.rootDirectory(), providerId); - if (existing != null && !existing.equals(providerId)) { - throw new IllegalArgumentException( - "different fileserver provider IDs cannot share one root directory"); - } - }); - } - - private static Map normalizeDestinations( - Map configuredDestinations) { - Map destinations = new LinkedHashMap<>(); - configuredDestinations.forEach( - (configuredId, destination) -> { - String destinationId = FileserverR2Validation.normalizeId("destination", configuredId); - if (destinations.putIfAbsent(destinationId, destination) != null) { - throw new IllegalArgumentException( - "duplicate normalized destination id: " + destinationId); - } - }); - return destinations; - } - - private static ValidatedProvider validateProvider(String providerId, ProviderSettings provider) { - if (provider == null) { - throw new IllegalArgumentException("provider " + providerId + " settings must be non-null"); - } - if (!LOCAL_PERSISTENT.equals(provider.type())) { - throw new IllegalArgumentException( - "provider " + providerId + " type must be exactly local-persistent"); - } - if (provider.autoCreate()) { - throw new IllegalArgumentException("provider " + providerId + " auto-create must be false"); - } - if (!provider.strictPathSecurity()) { - throw new IllegalArgumentException( - "provider " + providerId + " strict-path-security must be true"); - } - - Path root = - FileserverR2Validation.requireAbsoluteNormalizedPath( - "provider " + providerId + " root-directory", provider.rootDirectory()); - FileserverR2Validation.requireNonBlank( - "expected-file-store-name attestation input", provider.expectedFileStoreName()); - FileserverR2Validation.requireNonBlank( - "expected-file-store-type attestation input", provider.expectedFileStoreType()); - FileserverR2Validation.requireNonBlank( - "expected-owner attestation input", provider.expectedOwner()); - FileserverR2Validation.requireSentinelName(provider.mountSentinelName()); - FileserverR2Validation.requireSha256( - "provider " + providerId + " mount-sentinel-sha256", provider.mountSentinelSha256()); - Set maximumPermissions = - FileserverR2Validation.parseMaximumRootMode(provider.maximumRootMode()); - return new ValidatedProvider(provider, root, maximumPermissions); - } - - private static void validateDestination(String destinationId, DestinationSettings destination) { - if (destination == null) { - throw new IllegalArgumentException( - "destination " + destinationId + " settings must be non-null"); - } - if (!UNIQUE_ATOMIC_CREATE.equals(destination.requiredPublication())) { - throw new IllegalArgumentException( - "destination " - + destinationId - + " required-publication must be exactly unique-atomic-create"); - } - if (!FILE_AND_DIRECTORY_SYNC.equals(destination.requiredDurability())) { - throw new IllegalArgumentException( - "destination " - + destinationId - + " required-durability must be exactly file-and-directory-sync"); - } - if (destination.maximumRows() < 1) { - throw new IllegalArgumentException( - "destination " + destinationId + " maximum-rows must be positive"); - } - if (destination.maximumEncodedBytes() < 1) { - throw new IllegalArgumentException( - "destination " + destinationId + " maximum-encoded-bytes must be positive"); - } - } - - private record ValidatedProvider( - ProviderSettings settings, - Path rootDirectory, - Set maximumRootPermissions) {} -} diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/FileserverControlRecordCodec.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/FileserverControlRecordCodec.java deleted file mode 100644 index b94e783a..00000000 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/FileserverControlRecordCodec.java +++ /dev/null @@ -1,855 +0,0 @@ -package dev.caskeleton.adapter.outbound.fileserver; - -import dev.caskeleton.application.filepublication.FileDestinationId; -import dev.caskeleton.application.filepublication.FilePublishOperationId; -import dev.caskeleton.application.filepublication.FilePublishReceipt; -import dev.caskeleton.application.filepublication.FilePublishReceipt.DurabilityGuarantee; -import dev.caskeleton.application.filepublication.FilePublishReceipt.PublicationGuarantee; -import dev.caskeleton.application.filepublication.FileVersion; -import dev.caskeleton.application.filepublication.PublishedFileReference; -import java.nio.ByteBuffer; -import java.nio.charset.CharacterCodingException; -import java.nio.charset.CodingErrorAction; -import java.nio.charset.StandardCharsets; -import java.time.Instant; -import java.util.Arrays; -import java.util.Base64; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** Strict bounded canonical JSON codec for the three private Fileserver R2 control records. */ -final class FileserverControlRecordCodec { - - private static final int MAXIMUM_RECORD_BYTES = 16_384; - private static final int MAXIMUM_RECEIPT_PAYLOAD_BYTES = 8_192; - private static final String RECEIPT_PREFIX = "rsv1."; - private static final String DIGEST_PATTERN = "[0-9a-f]{64}"; - private static final String FILE_ID_PATTERN = "[0-9a-f]{32}"; - private static final String ROUTE_PATTERN = "[a-z][a-z0-9]{5,31}"; - private static final String LOGICAL_ID_PATTERN = "[a-z][a-z0-9-]{0,62}"; - private static final String SEGMENT_PATTERN = "[A-Za-z0-9][A-Za-z0-9._-]{0,255}"; - private static final String FAILURE_CODE_PATTERN = "[A-Z][A-Z0-9_]{0,63}"; - - private static final List OPERATION_FIELDS = - List.of( - "schemaVersion", - "stateRevision", - "state", - "operationId", - "requestFingerprint", - "effectivePolicyRevision", - "effectivePolicyDigest", - "destinationId", - "providerId", - "fileId", - "routeToken", - "publishedFileName", - "stageFileName", - "byteSize", - "rowCount", - "columnCount", - "sha256", - "formulaMitigatedCount", - "manifestDigest", - "referenceDigest", - "createdAt", - "sealedAt", - "publishedAt", - "lastFailureCode", - "receiptSnapshot"); - - private static final List MANIFEST_FIELDS = - List.of( - "schemaVersion", - "operationId", - "fileId", - "providerId", - "fileReference", - "requestFingerprint", - "destinationId", - "schemaId", - "exportSchemaVersion", - "schemaDigest", - "formatProfileId", - "formatPolicyDigest", - "effectivePolicyRevision", - "effectivePolicyDigest", - "publishedFileName", - "fileVersion", - "mediaType", - "charset", - "byteSize", - "rowCount", - "columnCount", - "sha256", - "formulaMitigatedCount", - "publicationGuarantee", - "durabilityGuarantee", - "internalLocator", - "createdAt", - "publishedAt"); - - private static final List REFERENCE_FIELDS = - List.of( - "schemaVersion", - "fileId", - "routeToken", - "fileReference", - "operationId", - "fileVersion", - "manifestDigest", - "internalLocator", - "destinationId", - "providerId", - "publishedFileName", - "mediaType", - "charset", - "byteSize", - "sha256", - "publishedAt"); - - private static final List RECEIPT_FIELDS = - List.of( - "operationId", - "reference", - "destinationId", - "publishedFileName", - "fileVersion", - "formatProfileId", - "mediaType", - "charset", - "byteSize", - "dataRowCount", - "columnCount", - "sha256", - "publishedAt", - "publicationGuarantee", - "durabilityGuarantee", - "formulaMitigatedCount"); - - byte[] encodeOperation(DurablePublicationRecord record) { - if (record == null) { - throw new IllegalArgumentException("operation record must be non-null"); - } - JsonWriter json = new JsonWriter(); - json.number("schemaVersion", record.schemaVersion()); - json.number("stateRevision", record.stateRevision()); - json.string("state", record.state().name()); - json.string("operationId", record.operationId()); - json.string("requestFingerprint", record.requestFingerprint()); - json.string("effectivePolicyRevision", record.effectivePolicyRevision()); - json.string("effectivePolicyDigest", record.effectivePolicyDigest()); - json.string("destinationId", record.destinationId()); - json.string("providerId", record.providerId()); - json.string("fileId", record.fileId()); - json.string("routeToken", record.routeToken()); - json.string("publishedFileName", record.publishedFileName()); - json.string("stageFileName", record.stageFileName()); - json.number("byteSize", record.byteSize()); - json.number("rowCount", record.rowCount()); - json.number("columnCount", record.columnCount()); - json.string("sha256", record.sha256()); - json.number("formulaMitigatedCount", record.formulaMitigatedCount()); - json.string("manifestDigest", record.manifestDigest()); - json.string("referenceDigest", record.referenceDigest()); - json.string("createdAt", instant(record.createdAt())); - json.string("sealedAt", optionalInstant(record.sealedAt())); - json.string("publishedAt", optionalInstant(record.publishedAt())); - json.string("lastFailureCode", record.lastFailureCode()); - json.string("receiptSnapshot", record.receiptSnapshot()); - return json.bytes(); - } - - DurablePublicationRecord decodeOperation(byte[] bytes) { - Map values = parse(bytes, OPERATION_FIELDS); - DurablePublicationRecord record = - new DurablePublicationRecord( - integer(values, "schemaVersion"), - longValue(values, "stateRevision"), - DurablePublicationRecord.State.valueOf(string(values, "state")), - string(values, "operationId"), - string(values, "requestFingerprint"), - string(values, "effectivePolicyRevision"), - string(values, "effectivePolicyDigest"), - string(values, "destinationId"), - string(values, "providerId"), - string(values, "fileId"), - string(values, "routeToken"), - string(values, "publishedFileName"), - string(values, "stageFileName"), - longValue(values, "byteSize"), - longValue(values, "rowCount"), - integer(values, "columnCount"), - string(values, "sha256"), - longValue(values, "formulaMitigatedCount"), - string(values, "manifestDigest"), - string(values, "referenceDigest"), - requiredInstant(values, "createdAt"), - optionalInstant(values, "sealedAt"), - optionalInstant(values, "publishedAt"), - string(values, "lastFailureCode"), - string(values, "receiptSnapshot")); - requireCanonical(bytes, encodeOperation(record)); - return record; - } - - byte[] encodeManifest(PrivateFileManifest manifest) { - if (manifest == null) { - throw new IllegalArgumentException("manifest must be non-null"); - } - JsonWriter json = new JsonWriter(); - json.number("schemaVersion", manifest.schemaVersion()); - json.string("operationId", manifest.operationId()); - json.string("fileId", manifest.fileId()); - json.string("providerId", manifest.providerId()); - json.string("fileReference", manifest.fileReference()); - json.string("requestFingerprint", manifest.requestFingerprint()); - json.string("destinationId", manifest.destinationId()); - json.string("schemaId", manifest.schemaId()); - json.number("exportSchemaVersion", manifest.exportSchemaVersion()); - json.string("schemaDigest", manifest.schemaDigest()); - json.string("formatProfileId", manifest.formatProfileId()); - json.string("formatPolicyDigest", manifest.formatPolicyDigest()); - json.string("effectivePolicyRevision", manifest.effectivePolicyRevision()); - json.string("effectivePolicyDigest", manifest.effectivePolicyDigest()); - json.string("publishedFileName", manifest.publishedFileName()); - json.string("fileVersion", manifest.fileVersion()); - json.string("mediaType", manifest.mediaType()); - json.string("charset", manifest.charset()); - json.number("byteSize", manifest.byteSize()); - json.number("rowCount", manifest.rowCount()); - json.number("columnCount", manifest.columnCount()); - json.string("sha256", manifest.sha256()); - json.number("formulaMitigatedCount", manifest.formulaMitigatedCount()); - json.string("publicationGuarantee", manifest.publicationGuarantee().name()); - json.string("durabilityGuarantee", manifest.durabilityGuarantee().name()); - json.string("internalLocator", manifest.internalLocator()); - json.string("createdAt", instant(manifest.createdAt())); - json.string("publishedAt", instant(manifest.publishedAt())); - return json.bytes(); - } - - PrivateFileManifest decodeManifest(byte[] bytes) { - Map values = parse(bytes, MANIFEST_FIELDS); - PrivateFileManifest manifest = - new PrivateFileManifest( - integer(values, "schemaVersion"), - string(values, "operationId"), - string(values, "fileId"), - string(values, "providerId"), - string(values, "fileReference"), - string(values, "requestFingerprint"), - string(values, "destinationId"), - string(values, "schemaId"), - integer(values, "exportSchemaVersion"), - string(values, "schemaDigest"), - string(values, "formatProfileId"), - string(values, "formatPolicyDigest"), - string(values, "effectivePolicyRevision"), - string(values, "effectivePolicyDigest"), - string(values, "publishedFileName"), - string(values, "fileVersion"), - string(values, "mediaType"), - string(values, "charset"), - longValue(values, "byteSize"), - longValue(values, "rowCount"), - integer(values, "columnCount"), - string(values, "sha256"), - longValue(values, "formulaMitigatedCount"), - PublicationGuarantee.valueOf(string(values, "publicationGuarantee")), - DurabilityGuarantee.valueOf(string(values, "durabilityGuarantee")), - string(values, "internalLocator"), - requiredInstant(values, "createdAt"), - requiredInstant(values, "publishedAt")); - requireCanonical(bytes, encodeManifest(manifest)); - return manifest; - } - - byte[] encodeReference(PublishedReferenceRecord reference) { - if (reference == null) { - throw new IllegalArgumentException("reference record must be non-null"); - } - JsonWriter json = new JsonWriter(); - json.number("schemaVersion", reference.schemaVersion()); - json.string("fileId", reference.fileId()); - json.string("routeToken", reference.routeToken()); - json.string("fileReference", reference.fileReference()); - json.string("operationId", reference.operationId()); - json.string("fileVersion", reference.fileVersion()); - json.string("manifestDigest", reference.manifestDigest()); - json.string("internalLocator", reference.internalLocator()); - json.string("destinationId", reference.destinationId()); - json.string("providerId", reference.providerId()); - json.string("publishedFileName", reference.publishedFileName()); - json.string("mediaType", reference.mediaType()); - json.string("charset", reference.charset()); - json.number("byteSize", reference.byteSize()); - json.string("sha256", reference.sha256()); - json.string("publishedAt", instant(reference.publishedAt())); - return json.bytes(); - } - - PublishedReferenceRecord decodeReference(byte[] bytes) { - Map values = parse(bytes, REFERENCE_FIELDS); - PublishedReferenceRecord reference = - new PublishedReferenceRecord( - integer(values, "schemaVersion"), - string(values, "fileId"), - string(values, "routeToken"), - string(values, "fileReference"), - string(values, "operationId"), - string(values, "fileVersion"), - string(values, "manifestDigest"), - string(values, "internalLocator"), - string(values, "destinationId"), - string(values, "providerId"), - string(values, "publishedFileName"), - string(values, "mediaType"), - string(values, "charset"), - longValue(values, "byteSize"), - string(values, "sha256"), - requiredInstant(values, "publishedAt")); - requireCanonical(bytes, encodeReference(reference)); - return reference; - } - - String encodeReceiptSnapshot(FilePublishReceipt receipt) { - byte[] payload = encodeReceiptPayload(receipt); - if (payload.length > MAXIMUM_RECEIPT_PAYLOAD_BYTES) { - throw new IllegalArgumentException("receipt snapshot payload exceeds maximum size"); - } - return RECEIPT_PREFIX + Base64.getUrlEncoder().withoutPadding().encodeToString(payload); - } - - FilePublishReceipt decodeReceiptSnapshot(String snapshot) { - requireNoControl(snapshot, "receiptSnapshot", 12_288); - if (!snapshot.startsWith(RECEIPT_PREFIX) || snapshot.length() == RECEIPT_PREFIX.length()) { - throw new IllegalArgumentException("receipt snapshot has an unsupported format"); - } - String encoded = snapshot.substring(RECEIPT_PREFIX.length()); - if (!encoded.matches("[A-Za-z0-9_-]+")) { - throw new IllegalArgumentException("receipt snapshot is not unpadded base64url"); - } - byte[] payload; - try { - payload = Base64.getUrlDecoder().decode(encoded); - } catch (IllegalArgumentException exception) { - throw new IllegalArgumentException("receipt snapshot payload is malformed", exception); - } - if (payload.length > MAXIMUM_RECEIPT_PAYLOAD_BYTES - || !Base64.getUrlEncoder().withoutPadding().encodeToString(payload).equals(encoded)) { - throw new IllegalArgumentException("receipt snapshot payload is not canonical"); - } - - Map values = parse(payload, RECEIPT_FIELDS); - FilePublishReceipt receipt = - new FilePublishReceipt( - new FilePublishOperationId(string(values, "operationId")), - new PublishedFileReference(string(values, "reference")), - new FileDestinationId(string(values, "destinationId")), - string(values, "publishedFileName"), - new FileVersion(string(values, "fileVersion")), - string(values, "formatProfileId"), - string(values, "mediaType"), - string(values, "charset"), - longValue(values, "byteSize"), - longValue(values, "dataRowCount"), - integer(values, "columnCount"), - string(values, "sha256"), - requiredInstant(values, "publishedAt"), - PublicationGuarantee.valueOf(string(values, "publicationGuarantee")), - DurabilityGuarantee.valueOf(string(values, "durabilityGuarantee")), - longValue(values, "formulaMitigatedCount")); - requireCanonical(payload, encodeReceiptPayload(receipt)); - return receipt; - } - - private byte[] encodeReceiptPayload(FilePublishReceipt receipt) { - validateReceipt(receipt); - JsonWriter json = new JsonWriter(); - json.string("operationId", receipt.operationId().value()); - json.string("reference", receipt.reference().value()); - json.string("destinationId", receipt.destinationId().value()); - json.string("publishedFileName", receipt.publishedFileName()); - json.string("fileVersion", receipt.version().value()); - json.string("formatProfileId", receipt.formatProfileId()); - json.string("mediaType", receipt.mediaType()); - json.string("charset", receipt.charset()); - json.number("byteSize", receipt.byteSize()); - json.number("dataRowCount", receipt.dataRowCount()); - json.number("columnCount", receipt.columnCount()); - json.string("sha256", receipt.sha256()); - json.string("publishedAt", instant(receipt.publishedAt())); - json.string("publicationGuarantee", receipt.publicationGuarantee().name()); - json.string("durabilityGuarantee", receipt.durabilityGuarantee().name()); - json.number("formulaMitigatedCount", receipt.formulaMitigatedCount()); - return json.bytes(); - } - - private static void validateReceipt(FilePublishReceipt receipt) { - if (receipt == null) { - throw new IllegalArgumentException("receipt must be non-null"); - } - requireText(receipt.operationId().value(), "receipt.operationId", 128); - requireReferenceMatches(receipt.reference().value(), null, null); - requireLogicalId(receipt.destinationId().value(), "receipt.destinationId"); - requireSegment(receipt.publishedFileName(), "receipt.publishedFileName"); - requireText(receipt.version().value(), "receipt.fileVersion", 128); - requireText(receipt.formatProfileId(), "receipt.formatProfileId", 128); - requireText(receipt.mediaType(), "receipt.mediaType", 128); - requireText(receipt.charset(), "receipt.charset", 64); - if (receipt.byteSize() < 0 - || receipt.dataRowCount() < 0 - || receipt.columnCount() < 1 - || receipt.formulaMitigatedCount() < 0) { - throw new IllegalArgumentException("receipt sizes and counts are out of range"); - } - requireFormulaCountWithinCells( - receipt.dataRowCount(), receipt.columnCount(), receipt.formulaMitigatedCount(), "receipt"); - requireDigest(receipt.sha256(), "receipt.sha256"); - requireInstant(receipt.publishedAt(), "receipt.publishedAt"); - } - - static void validateReceiptSnapshot( - String snapshot, - String operationId, - String destinationId, - String publishedFileName, - long byteSize, - long rowCount, - int columnCount, - String sha256, - long formulaMitigatedCount, - Instant publishedAt, - String routeToken, - String fileId) { - FilePublishReceipt receipt = new FileserverControlRecordCodec().decodeReceiptSnapshot(snapshot); - if (!receipt.operationId().value().equals(operationId) - || !receipt.destinationId().value().equals(destinationId) - || !receipt.publishedFileName().equals(publishedFileName) - || receipt.byteSize() != byteSize - || receipt.dataRowCount() != rowCount - || receipt.columnCount() != columnCount - || !receipt.sha256().equals(sha256) - || receipt.formulaMitigatedCount() != formulaMitigatedCount - || !receipt.publishedAt().equals(publishedAt)) { - throw new IllegalArgumentException("receipt snapshot does not match operation record"); - } - requireReferenceMatches(receipt.reference().value(), fileId, routeToken); - } - - static void requireReferenceMatches( - String reference, String expectedFileId, String expectedRouteToken) { - requireNoControl(reference, "fileReference", 256); - String[] segments = reference.split("\\.", -1); - if (segments.length != 4) { - throw new IllegalArgumentException("fileReference is malformed"); - } - String routeToken = expectedRouteToken == null ? segments[1] : expectedRouteToken; - R2PublishedReferenceCodec.DecodedReference decoded = - new R2PublishedReferenceCodec() - .decode(new PublishedFileReference(reference), Set.of(routeToken)); - if (expectedFileId != null && !expectedFileId.equals(decoded.fileId())) { - throw new IllegalArgumentException("fileReference does not match fileId"); - } - if (expectedRouteToken != null && !expectedRouteToken.equals(decoded.routeToken())) { - throw new IllegalArgumentException("fileReference does not match routeToken"); - } - } - - static void requireDigest(String value, String field) { - if (value == null || !value.matches(DIGEST_PATTERN)) { - throw new IllegalArgumentException(field + " must be a lowercase SHA-256 digest"); - } - } - - static void requireOptionalDigest(String value, String field) { - if (value == null || (!value.isEmpty() && !value.matches(DIGEST_PATTERN))) { - throw new IllegalArgumentException(field + " must be blank or a lowercase SHA-256 digest"); - } - } - - static void requireFileId(String value) { - if (value == null || !value.matches(FILE_ID_PATTERN)) { - throw new IllegalArgumentException( - "fileId must be exactly 32 lowercase hexadecimal characters"); - } - } - - static void requireRouteToken(String value) { - if (value == null || !value.matches(ROUTE_PATTERN)) { - throw new IllegalArgumentException("routeToken must match " + ROUTE_PATTERN); - } - } - - static void requireLogicalId(String value, String field) { - if (value == null || !value.matches(LOGICAL_ID_PATTERN)) { - throw new IllegalArgumentException(field + " must match " + LOGICAL_ID_PATTERN); - } - } - - static void requireSegment(String value, String field) { - if (value == null - || !value.matches(SEGMENT_PATTERN) - || value.equals(".") - || value.equals("..") - || value.contains("/") - || value.contains("\\") - || value.contains(":")) { - throw new IllegalArgumentException(field + " must be a safe single segment"); - } - } - - static void requireText(String value, String field, int maximumLength) { - if (value == null || value.isBlank() || value.length() > maximumLength) { - throw new IllegalArgumentException(field + " is invalid"); - } - requireNoControl(value, field, maximumLength); - } - - static void requireNoControl(String value, String field, int maximumLength) { - if (value == null || value.length() > maximumLength) { - throw new IllegalArgumentException(field + " is invalid"); - } - requireWellFormedUnicode(value, field); - if (value.codePoints().anyMatch(Character::isISOControl)) { - throw new IllegalArgumentException(field + " contains a control character"); - } - } - - static void requireOptionalFailureCode(String value) { - if (value == null || (!value.isEmpty() && !value.matches(FAILURE_CODE_PATTERN))) { - throw new IllegalArgumentException("lastFailureCode is invalid"); - } - } - - static void requireFormulaCountWithinCells( - long rowCount, int columnCount, long formulaMitigatedCount, String recordType) { - if (formulaMitigatedCount == 0) { - return; - } - if (rowCount == 0 || columnCount == 0) { - throw new IllegalArgumentException( - recordType + " formulaMitigatedCount requires at least one cell"); - } - if (rowCount <= Long.MAX_VALUE / columnCount - && formulaMitigatedCount > rowCount * columnCount) { - throw new IllegalArgumentException( - recordType + " formulaMitigatedCount exceeds the number of cells"); - } - } - - static void requireInstant(Instant value, String field) { - if (value == null) { - throw new IllegalArgumentException(field + " must be a UTC Instant"); - } - } - - static void requireOrderedInstant(Instant earlier, Instant later, String field) { - requireInstant(later, field); - if (later.isBefore(earlier)) { - throw new IllegalArgumentException(field + " precedes the prior timestamp"); - } - } - - static boolean allBlank(String... values) { - for (String value : values) { - if (value == null || !value.isEmpty()) { - return false; - } - } - return true; - } - - private static Map parse(byte[] bytes, List fields) { - return new FlatJsonParser(bytes, fields).parse(); - } - - private static String string(Map values, String field) { - JsonValue value = values.get(field); - if (value == null || !value.string()) { - throw new IllegalArgumentException(field + " must be a JSON string"); - } - return value.value(); - } - - private static long longValue(Map values, String field) { - JsonValue value = values.get(field); - if (value == null || value.string()) { - throw new IllegalArgumentException(field + " must be a JSON integer"); - } - try { - return Long.parseLong(value.value()); - } catch (NumberFormatException exception) { - throw new IllegalArgumentException(field + " is outside the integer range", exception); - } - } - - private static int integer(Map values, String field) { - long value = longValue(values, field); - if (value < Integer.MIN_VALUE || value > Integer.MAX_VALUE) { - throw new IllegalArgumentException(field + " is outside the integer range"); - } - return (int) value; - } - - private static Instant requiredInstant(Map values, String field) { - String value = string(values, field); - if (value.isEmpty()) { - throw new IllegalArgumentException(field + " must be present"); - } - return parseInstant(value, field); - } - - private static Instant optionalInstant(Map values, String field) { - String value = string(values, field); - return value.isEmpty() ? null : parseInstant(value, field); - } - - private static Instant parseInstant(String value, String field) { - try { - Instant result = Instant.parse(value); - if (!result.toString().equals(value)) { - throw new IllegalArgumentException(field + " is not a canonical UTC Instant"); - } - return result; - } catch (RuntimeException exception) { - throw new IllegalArgumentException(field + " is not a canonical UTC Instant", exception); - } - } - - private static String instant(Instant value) { - requireInstant(value, "instant"); - return value.toString(); - } - - private static String optionalInstant(Instant value) { - return value == null ? "" : value.toString(); - } - - private static void requireCanonical(byte[] supplied, byte[] canonical) { - if (!Arrays.equals(supplied, canonical)) { - throw new IllegalArgumentException("control record is not canonical JSON"); - } - } - - private static void requireWellFormedUnicode(String value, String field) { - for (int index = 0; index < value.length(); index++) { - char character = value.charAt(index); - if (Character.isHighSurrogate(character)) { - if (index + 1 >= value.length() || !Character.isLowSurrogate(value.charAt(index + 1))) { - throw new IllegalArgumentException(field + " contains an unpaired surrogate"); - } - index++; - } else if (Character.isLowSurrogate(character)) { - throw new IllegalArgumentException(field + " contains an unpaired surrogate"); - } - } - } - - private record JsonValue(String value, boolean string) {} - - private static final class JsonWriter { - - private final StringBuilder target = new StringBuilder(1024); - private boolean first = true; - - private JsonWriter() { - target.append('{'); - } - - private void string(String key, String value) { - prefix(key); - appendQuoted(target, value); - } - - private void number(String key, long value) { - prefix(key); - target.append(value); - } - - private void prefix(String key) { - if (!first) { - target.append(','); - } - first = false; - appendQuoted(target, key); - target.append(':'); - } - - private byte[] bytes() { - byte[] result = target.append('}').toString().getBytes(StandardCharsets.UTF_8); - if (result.length > MAXIMUM_RECORD_BYTES) { - throw new IllegalArgumentException("control record exceeds maximum size"); - } - return result; - } - } - - private static void appendQuoted(StringBuilder target, String value) { - requireNoControl(value, "JSON string", MAXIMUM_RECORD_BYTES); - target.append('"'); - for (int index = 0; index < value.length(); index++) { - char character = value.charAt(index); - if (character == '"') { - target.append("\\\""); - } else if (character == '\\') { - target.append("\\\\"); - } else { - target.append(character); - } - } - target.append('"'); - } - - private static final class FlatJsonParser { - - private final String input; - private final Set allowedFields; - private int cursor; - - private FlatJsonParser(byte[] bytes, List fields) { - if (bytes == null || bytes.length < 2 || bytes.length > MAXIMUM_RECORD_BYTES) { - throw new IllegalArgumentException("control record size is out of bounds"); - } - input = decodeUtf8(bytes); - allowedFields = new LinkedHashSet<>(fields); - } - - private Map parse() { - Map values = new LinkedHashMap<>(); - whitespace(); - expect('{'); - whitespace(); - if (!peek('}')) { - while (true) { - String key = quoted(); - if (!allowedFields.contains(key)) { - throw new IllegalArgumentException("unknown control record field"); - } - whitespace(); - expect(':'); - whitespace(); - JsonValue value = - peek('"') ? new JsonValue(quoted(), true) : new JsonValue(number(), false); - if (values.putIfAbsent(key, value) != null) { - throw new IllegalArgumentException("duplicate control record field"); - } - whitespace(); - if (!peek(',')) { - break; - } - cursor++; - whitespace(); - } - } - expect('}'); - whitespace(); - if (cursor != input.length()) { - throw new IllegalArgumentException("trailing control record content"); - } - if (!values.keySet().equals(allowedFields)) { - throw new IllegalArgumentException("control record fields do not match schema"); - } - return values; - } - - private String quoted() { - expect('"'); - StringBuilder value = new StringBuilder(); - while (cursor < input.length()) { - char character = input.charAt(cursor++); - if (character == '"') { - String result = value.toString(); - requireNoControl(result, "JSON string", MAXIMUM_RECORD_BYTES); - return result; - } - if (character < 0x20) { - throw new IllegalArgumentException("unescaped JSON control character"); - } - if (character != '\\') { - value.append(character); - continue; - } - if (cursor >= input.length()) { - throw new IllegalArgumentException("truncated JSON escape"); - } - char escape = input.charAt(cursor++); - switch (escape) { - case '"' -> value.append('"'); - case '\\' -> value.append('\\'); - case '/' -> value.append('/'); - case 'u' -> value.append(unicode()); - case 'b', 'f', 'n', 'r', 't' -> - throw new IllegalArgumentException("control characters are forbidden"); - default -> throw new IllegalArgumentException("invalid JSON escape"); - } - } - throw new IllegalArgumentException("unterminated JSON string"); - } - - private char unicode() { - if (cursor + 4 > input.length()) { - throw new IllegalArgumentException("truncated JSON unicode escape"); - } - String digits = input.substring(cursor, cursor + 4); - if (!digits.matches("[0-9A-Fa-f]{4}")) { - throw new IllegalArgumentException("invalid JSON unicode escape"); - } - cursor += 4; - return (char) Integer.parseInt(digits, 16); - } - - private String number() { - int start = cursor; - if (peek('-')) { - cursor++; - } - int digits = cursor; - while (cursor < input.length()) { - char character = input.charAt(cursor); - if (character < '0' || character > '9') { - break; - } - cursor++; - } - if (cursor == digits) { - throw new IllegalArgumentException("invalid JSON integer"); - } - return input.substring(start, cursor); - } - - private void whitespace() { - while (cursor < input.length() && Character.isWhitespace(input.charAt(cursor))) { - cursor++; - } - } - - private boolean peek(char expected) { - return cursor < input.length() && input.charAt(cursor) == expected; - } - - private void expect(char expected) { - if (!peek(expected)) { - throw new IllegalArgumentException("unexpected control record token"); - } - cursor++; - } - - private static String decodeUtf8(byte[] bytes) { - try { - return StandardCharsets.UTF_8 - .newDecoder() - .onMalformedInput(CodingErrorAction.REPORT) - .onUnmappableCharacter(CodingErrorAction.REPORT) - .decode(ByteBuffer.wrap(bytes)) - .toString(); - } catch (CharacterCodingException exception) { - throw new IllegalArgumentException("control record is not valid UTF-8", exception); - } - } - } -} diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/FileserverR2Config.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/FileserverR2Config.java deleted file mode 100644 index d6e94b16..00000000 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/FileserverR2Config.java +++ /dev/null @@ -1,93 +0,0 @@ -package dev.caskeleton.adapter.outbound.fileserver; - -import dev.caskeleton.application.filepublication.FileDestinationId; -import dev.caskeleton.application.filepublication.FilePublicationPort; -import java.nio.file.Path; -import java.security.SecureRandom; -import java.time.Clock; -import java.util.ArrayList; -import java.util.HexFormat; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.Environment; - -/** Fail-closed Spring composition for the explicit Fileserver R2 destination registry. */ -@Configuration(proxyBeanMethods = false) -@ConditionalOnProperty(prefix = "app.fileserver", name = "enabled", havingValue = "true") -@EnableConfigurationProperties(FileserverR2Settings.class) -public class FileserverR2Config { - - private static final SecureRandom SECURE_RANDOM = new SecureRandom(); - private static final HexFormat HEX = HexFormat.of(); - - @Bean - @ConditionalOnProperty(prefix = "app.fileserver", name = "enabled", havingValue = "true") - public FilePublicationPort routingFilePublicationPort( - FileserverR2Settings settings, Environment environment) { - FileserverActivationValidator.rejectAmbiguous(environment); - Map destinations = - FileserverBindingCompiler.compile(settings); - rejectSharedRootAcrossProviderIds(destinations); - - Map> byProvider = new LinkedHashMap<>(); - destinations.values().stream() - .sorted(java.util.Comparator.comparing(destination -> destination.destinationId().value())) - .forEach( - destination -> - byProvider - .computeIfAbsent(destination.providerId(), ignored -> new ArrayList<>()) - .add(destination)); - - Map routes = new LinkedHashMap<>(); - for (List providerDestinations : byProvider.values()) { - CompiledFileDestination first = providerDestinations.getFirst(); - LocalPersistentRootAttestor attestor = new LocalPersistentRootAttestor(); - LocalPersistentRootEvidence evidence = attestor.attest(first); - LocalPersistentControlPlane controlPlane = - new LocalPersistentControlPlane(attestor, evidence); - LocalPersistentPayloadOperations payload = - new LocalPersistentPayloadOperations(attestor, evidence); - Map runtimes = - new LinkedHashMap<>(); - providerDestinations.forEach( - destination -> - runtimes.put( - destination.destinationId(), - new LocalPersistentPublicationProvider.DestinationRuntime( - destination, controlPlane, payload))); - LocalPersistentPublicationProvider provider = - new LocalPersistentPublicationProvider( - runtimes, Clock.systemUTC(), FileserverR2Config::randomFileId); - providerDestinations.forEach( - destination -> routes.put(destination.destinationId(), provider)); - } - return new RoutingFilePublicationAdapter(routes); - } - - private static void rejectSharedRootAcrossProviderIds( - Map destinations) { - Map rootOwners = new LinkedHashMap<>(); - destinations - .values() - .forEach( - destination -> { - String existing = - rootOwners.putIfAbsent(destination.rootDirectory(), destination.providerId()); - if (existing != null && !existing.equals(destination.providerId())) { - throw new IllegalArgumentException( - "different fileserver provider IDs cannot share one root directory"); - } - }); - } - - private static String randomFileId() { - byte[] bytes = new byte[16]; - SECURE_RANDOM.nextBytes(bytes); - return HEX.formatHex(bytes); - } -} diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/FileserverR2Settings.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/FileserverR2Settings.java deleted file mode 100644 index 5ed171f8..00000000 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/FileserverR2Settings.java +++ /dev/null @@ -1,41 +0,0 @@ -package dev.caskeleton.adapter.outbound.fileserver; - -import java.util.Map; -import org.springframework.boot.context.properties.ConfigurationProperties; - -/** Typed, opt-in settings for exact R2 destination-to-provider bindings. */ -@ConfigurationProperties(prefix = "app.fileserver", ignoreUnknownFields = false) -public record FileserverR2Settings( - boolean enabled, - Map destinations, - Map providers) { - - public FileserverR2Settings { - destinations = destinations == null ? Map.of() : Map.copyOf(destinations); - providers = providers == null ? Map.of() : Map.copyOf(providers); - } - - /** Required publication contract and bounds for one logical application destination. */ - public record DestinationSettings( - String providerRef, - String requiredPublication, - String requiredDurability, - long maximumRows, - long maximumEncodedBytes) {} - - /** - * Provider-specific root and startup-attestation inputs. The sentinel name is one control-free - * path segment whose UTF-8 encoding is at most 255 bytes. - */ - public record ProviderSettings( - String type, - String rootDirectory, - boolean autoCreate, - boolean strictPathSecurity, - String expectedFileStoreName, - String expectedFileStoreType, - String mountSentinelName, - String mountSentinelSha256, - String expectedOwner, - String maximumRootMode) {} -} diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/FileserverR2Validation.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/FileserverR2Validation.java deleted file mode 100644 index 42d188e2..00000000 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/FileserverR2Validation.java +++ /dev/null @@ -1,189 +0,0 @@ -package dev.caskeleton.adapter.outbound.fileserver; - -import java.nio.CharBuffer; -import java.nio.charset.CharacterCodingException; -import java.nio.charset.CodingErrorAction; -import java.nio.charset.StandardCharsets; -import java.nio.file.InvalidPathException; -import java.nio.file.Path; -import java.nio.file.attribute.PosixFilePermission; -import java.util.EnumSet; -import java.util.Objects; -import java.util.Set; - -/** Shared fail-closed value validation for R2 settings and compiled descriptors. */ -final class FileserverR2Validation { - - private static final String ID_PATTERN = "[a-z][a-z0-9-]{0,62}"; - private static final String SHA256_PATTERN = "[0-9a-f]{64}"; - private static final String POSIX_MODE_PATTERN = "0[0-7]{3}"; - private static final int MAXIMUM_FILE_NAME_UTF8_BYTES = 255; - - private FileserverR2Validation() {} - - static String normalizeId(String label, String value) { - if (value == null || value.trim().isEmpty()) { - throw new IllegalArgumentException(label + " id must be non-blank"); - } - String normalized = value.trim(); - if (!normalized.matches(ID_PATTERN)) { - throw new IllegalArgumentException( - label + " id must match [a-z][a-z0-9-]{0,62} after trimming"); - } - return normalized; - } - - static String requireNormalizedId(String label, String value) { - String normalized = normalizeId(label, value); - if (!normalized.equals(value)) { - throw new IllegalArgumentException(label + " must already be normalized"); - } - return normalized; - } - - static String requireNonBlank(String label, String value) { - if (value == null || value.isBlank()) { - throw new IllegalArgumentException(label + " must be non-blank"); - } - return value; - } - - static Path requireAbsoluteNormalizedPath(String label, String configuredPath) { - String value = requireNonBlank(label, configuredPath); - try { - return requireAbsoluteNormalizedPath(label, Path.of(value)); - } catch (InvalidPathException exception) { - throw new IllegalArgumentException(label + " must be a valid path", exception); - } - } - - static Path requireAbsoluteNormalizedPath(String label, Path path) { - Objects.requireNonNull(path, label + " must be non-null"); - if (!path.isAbsolute()) { - throw new IllegalArgumentException(label + " must be absolute"); - } - Path normalized = path.normalize(); - if (!path.equals(normalized)) { - throw new IllegalArgumentException(label + " must already be normalized"); - } - return normalized; - } - - static String requireSentinelName(String value) { - requireNonBlank("mount-sentinel-name", value); - if (".".equals(value) - || "..".equals(value) - || value.contains("/") - || value.contains("\\") - || value.chars().anyMatch(Character::isISOControl)) { - throw invalidSentinelName(); - } - - try { - int encodedLength = - StandardCharsets.UTF_8 - .newEncoder() - .onMalformedInput(CodingErrorAction.REPORT) - .onUnmappableCharacter(CodingErrorAction.REPORT) - .encode(CharBuffer.wrap(value)) - .remaining(); - if (encodedLength > MAXIMUM_FILE_NAME_UTF8_BYTES) { - throw invalidSentinelName(); - } - } catch (CharacterCodingException exception) { - throw invalidSentinelName(exception); - } - - try { - Path sentinel = Path.of(value); - if (sentinel.getNameCount() != 1 - || sentinel.getFileName() == null - || !value.equals(sentinel.getFileName().toString())) { - throw invalidSentinelName(); - } - } catch (InvalidPathException exception) { - throw invalidSentinelName(exception); - } - return value; - } - - static String requireSha256(String label, String value) { - if (value == null || !value.matches(SHA256_PATTERN)) { - throw new IllegalArgumentException(label + " must be a lowercase SHA-256 digest"); - } - return value; - } - - static Set parseMaximumRootMode(String mode) { - if (mode == null || !mode.matches(POSIX_MODE_PATTERN)) { - throw new IllegalArgumentException( - "maximum-root-mode must be exactly four octal digits such as 0750"); - } - int owner = mode.charAt(1) - '0'; - int group = mode.charAt(2) - '0'; - int others = mode.charAt(3) - '0'; - if ((group & 2) != 0 || (others & 2) != 0) { - throw new IllegalArgumentException("maximum-root-mode must not allow group or world write"); - } - - EnumSet permissions = EnumSet.noneOf(PosixFilePermission.class); - addPermissions( - permissions, - owner, - PosixFilePermission.OWNER_READ, - PosixFilePermission.OWNER_WRITE, - PosixFilePermission.OWNER_EXECUTE); - addPermissions( - permissions, - group, - PosixFilePermission.GROUP_READ, - PosixFilePermission.GROUP_WRITE, - PosixFilePermission.GROUP_EXECUTE); - addPermissions( - permissions, - others, - PosixFilePermission.OTHERS_READ, - PosixFilePermission.OTHERS_WRITE, - PosixFilePermission.OTHERS_EXECUTE); - return Set.copyOf(permissions); - } - - static Set requireMatchingMaximumRootPermissions( - String mode, Set permissions) { - Set immutablePermissions = - Set.copyOf(Objects.requireNonNull(permissions, "maximumRootPermissions must be non-null")); - if (!immutablePermissions.equals(parseMaximumRootMode(mode))) { - throw new IllegalArgumentException( - "maximumRootPermissions must exactly match maximumRootMode"); - } - return immutablePermissions; - } - - private static IllegalArgumentException invalidSentinelName() { - return new IllegalArgumentException( - "mount-sentinel-name must be a valid control-free single path name of at most 255 UTF-8 bytes"); - } - - private static IllegalArgumentException invalidSentinelName(Exception cause) { - return new IllegalArgumentException( - "mount-sentinel-name must be a valid control-free single path name of at most 255 UTF-8 bytes", - cause); - } - - private static void addPermissions( - Set permissions, - int mode, - PosixFilePermission read, - PosixFilePermission write, - PosixFilePermission execute) { - if ((mode & 4) != 0) { - permissions.add(read); - } - if ((mode & 2) != 0) { - permissions.add(write); - } - if ((mode & 1) != 0) { - permissions.add(execute); - } - } -} diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/FilesystemCsvExportAdapter.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/FilesystemCsvExportAdapter.java deleted file mode 100644 index 3cb705fd..00000000 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/FilesystemCsvExportAdapter.java +++ /dev/null @@ -1,210 +0,0 @@ -package dev.caskeleton.adapter.outbound.fileserver; - -import dev.caskeleton.application.fileexport.ExportedFile; -import dev.caskeleton.application.fileexport.FileExportPort; -import dev.caskeleton.application.filepublication.PublishedFileReference; -import dev.caskeleton.shared.error.DependencyFailureException; -import dev.caskeleton.shared.error.OperationalError; -import java.io.BufferedWriter; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.nio.file.FileAlreadyExistsException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.StandardOpenOption; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.HexFormat; -import java.util.List; -import java.util.Objects; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Filesystem-backed {@link FileExportPort} — writes a CSV export under a configured base directory - * (the "file server" boundary, a stand-in for NFS/SFTP). Fields are escaped per RFC-4180 and the - * file is UTF-8 encoded. This adapter is legacy compatibility code; its receipt exposes only an - * opaque reference, never the physical filesystem path. - */ -@SuppressWarnings("removal") -public class FilesystemCsvExportAdapter implements FileExportPort { - - private static final String DEPENDENCY_NAME = "fileserver"; - - private static final Logger log = LoggerFactory.getLogger(FilesystemCsvExportAdapter.class); - - private final Path baseDir; - - public FilesystemCsvExportAdapter(String baseDirectory) { - this.baseDir = Path.of(baseDirectory).toAbsolutePath().normalize(); - try { - Files.createDirectories(baseDir); - log.info("filesystem file-export storage initialized"); - } catch (IOException e) { - throw new DependencyFailureException( - OperationalError.INTERNAL_ERROR, - DEPENDENCY_NAME, - "cannot create file-export base dir", - e); - } - } - - /** - * Writes the export a record at a time, into a file that must not already exist. - * - *

Two things changed here and both were failure modes rather than style. The whole export used - * to be assembled in one {@code StringBuilder} and then converted to a byte array, so peak memory - * was roughly twice the export — a million-row report is an out-of-memory error, not a slow one. - * And {@code Files.write} truncates, so exporting a name that already existed silently replaced - * whatever was there; {@code CREATE_NEW} makes a name collision an error the caller can see. - * - *

Encoding streams through a bounded writer instead, so resident memory tracks the widest row - * rather than the report. - */ - @Override - public ExportedFile exportCsv(String fileName, List header, List> rows) { - Objects.requireNonNull(header, "header must be non-null"); - Objects.requireNonNull(rows, "rows must be non-null"); - Path target = resolve(fileName); - - long bytesWritten; - try (BufferedWriter writer = - Files.newBufferedWriter( - target, - StandardCharsets.UTF_8, - StandardOpenOption.CREATE_NEW, - StandardOpenOption.WRITE)) { - CountingAppendable counter = new CountingAppendable(writer); - if (!header.isEmpty()) { - appendRow(counter, header); - } - for (List row : rows) { - Objects.requireNonNull(row, "row must be non-null"); - appendRow(counter, row); - } - writer.flush(); - bytesWritten = counter.bytes(); - } catch (FileAlreadyExistsException collision) { - throw new DependencyFailureException( - OperationalError.INTERNAL_ERROR, - DEPENDENCY_NAME, - "csv export name already exists; exports never overwrite", - collision); - } catch (IOException e) { - throw new DependencyFailureException( - OperationalError.INTERNAL_ERROR, DEPENDENCY_NAME, "failed to write CSV export", e); - } - log.info("exported {} rows ({} bytes)", rows.size(), bytesWritten); - return new ExportedFile(fileName, opaqueReference(target), bytesWritten, rows.size()); - } - - /** - * Derives a stable opaque compatibility reference without exposing the server path. - * - *

The legacy API has no lookup operation, so the reference is a receipt identity only. The - * physical target remains adapter-private. - */ - private static PublishedFileReference opaqueReference(Path target) { - try { - byte[] digest = - MessageDigest.getInstance("SHA-256") - .digest(target.toString().getBytes(StandardCharsets.UTF_8)); - return new PublishedFileReference("legacy-file-export:" + HexFormat.of().formatHex(digest)); - } catch (NoSuchAlgorithmException impossible) { - throw new IllegalStateException("SHA-256 is required by the Java runtime", impossible); - } - } - - /** Appends one CSV record (comma-separated, escaped fields, trailing line feed). */ - private static void appendRow(CountingAppendable out, List fields) throws IOException { - for (int i = 0; i < fields.size(); i++) { - if (i > 0) { - out.append(","); - } - out.append(escape(fields.get(i))); - } - out.append("\n"); - } - - /** - * Counts encoded bytes while writing, so the reported size is not a second encoding pass. - * - *

{@link ExportedFile} promises a byte count. Re-encoding the whole export to measure it would - * reintroduce exactly the memory cost this streaming write exists to avoid. - */ - private static final class CountingAppendable { - - private final BufferedWriter writer; - private long bytes; - - private CountingAppendable(BufferedWriter writer) { - this.writer = writer; - } - - private void append(String text) throws IOException { - writer.write(text); - bytes += text.getBytes(StandardCharsets.UTF_8).length; - } - - private long bytes() { - return bytes; - } - } - - /** - * Minimal RFC-4180 escaping plus a formula-injection guard. - * - *

RFC-4180 quoting makes a field survive a CSV parser; it does nothing about the spreadsheet - * that opens the result. A field starting with {@code =}, {@code +}, {@code -}, {@code @}, a tab - * or a carriage return is evaluated as a formula by Excel, LibreOffice and Sheets, and {@code - * =cmd|'/c calc'!A1} is remote code execution against whoever opens the export. - * - *

This legacy port has no schema and therefore no per-column policy, and its callers predate - * the R2 contract, so the value is neutralised with a leading apostrophe rather than rejected — - * the cell still reads correctly and no existing caller starts failing. - */ - private static String escape(String value) { - if (value == null) { - return ""; - } - if (isFormulaShaped(value)) { - value = "'" + value; - } - if (value.contains(",") - || value.contains("\"") - || value.contains("\n") - || value.contains("\r")) { - return '"' + value.replace("\"", "\"\"") + '"'; - } - return value; - } - - private static boolean isFormulaShaped(String value) { - if (value.isEmpty()) { - return false; - } - return switch (value.charAt(0)) { - case '=', '+', '-', '@', '\t', '\r' -> true; - default -> false; - }; - } - - /** Resolves a bare file name under {@code baseDir}, rejecting blank names and path traversal. */ - private Path resolve(String fileName) { - if (fileName == null || fileName.isBlank()) { - throw new IllegalArgumentException("fileName must be non-null and non-blank"); - } - Path relative = Path.of(fileName); - if (relative.isAbsolute() - || relative.getNameCount() != 1 - || ".".equals(fileName) - || "..".equals(fileName)) { - throw new IllegalArgumentException("fileName must be a bare file name"); - } - Path resolved = baseDir.resolve(relative).normalize(); - if (!resolved.startsWith(baseDir) || resolved.equals(baseDir)) { - throw new IllegalArgumentException("illegal export file name (path traversal): " + fileName); - } - return resolved; - } -} diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/LocalFilePublicationAdapter.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/LocalFilePublicationAdapter.java deleted file mode 100644 index 471fe5a3..00000000 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/LocalFilePublicationAdapter.java +++ /dev/null @@ -1,437 +0,0 @@ -package dev.caskeleton.adapter.outbound.fileserver; - -import dev.caskeleton.application.filepublication.FilePublicationException; -import dev.caskeleton.application.filepublication.FilePublicationPort; -import dev.caskeleton.application.filepublication.FilePublishReceipt; -import dev.caskeleton.application.filepublication.FilePublishReceipt.DurabilityGuarantee; -import dev.caskeleton.application.filepublication.FilePublishReceipt.PublicationGuarantee; -import dev.caskeleton.application.filepublication.FilePublishRequest; -import dev.caskeleton.application.filepublication.FileVersion; -import dev.caskeleton.application.filepublication.PublishedFileReference; -import dev.caskeleton.application.filepublication.TabularRowProducer; -import dev.caskeleton.application.filepublication.TabularRowSink; -import java.io.IOException; -import java.io.OutputStream; -import java.nio.channels.Channels; -import java.nio.channels.FileChannel; -import java.nio.charset.StandardCharsets; -import java.nio.file.FileAlreadyExistsException; -import java.nio.file.Files; -import java.nio.file.LinkOption; -import java.nio.file.Path; -import java.nio.file.StandardOpenOption; -import java.nio.file.attribute.PosixFilePermission; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.time.Instant; -import java.util.HexFormat; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; - -/** - * Local staged CSV provider with single-node operation recovery. It does not claim cross-node - * fencing, background reconciliation, or R2 qualification. - */ -public final class LocalFilePublicationAdapter implements FilePublicationPort { - - private static final String FORMAT_PROFILE = "csv-rfc4180-v1"; - private static final HexFormat HEX = HexFormat.of(); - - private final LocalFilePublicationPolicy policy; - private final Path baseDirectory; - private final Path stagingDirectory; - private final LocalPublicationJournal journal; - private final AtomicLinkPublisher atomicLinkPublisher; - - public LocalFilePublicationAdapter(LocalFilePublicationPolicy policy) { - this(policy, (target, staging) -> Files.createLink(target, staging)); - } - - LocalFilePublicationAdapter( - LocalFilePublicationPolicy policy, AtomicLinkPublisher atomicLinkPublisher) { - this.policy = Objects.requireNonNull(policy, "policy must be non-null"); - this.atomicLinkPublisher = - Objects.requireNonNull(atomicLinkPublisher, "atomicLinkPublisher must be non-null"); - this.baseDirectory = policy.baseDirectory(); - this.stagingDirectory = baseDirectory.resolve(".staging"); - initializeDirectories(); - try { - this.journal = new LocalPublicationJournal(baseDirectory); - } catch (LocalPublicationJournalException exception) { - throw new FilePublicationException( - FilePublicationException.Reason.UNAVAILABLE, - "file publication control journal is unavailable", - exception); - } - } - - @Override - public FilePublishReceipt publish(FilePublishRequest request, TabularRowProducer producer) { - validateRequest(request); - Objects.requireNonNull(producer, "producer must be non-null"); - LocalPublicationJournal.OperationLock operationLock; - try { - operationLock = journal.acquire(request.operationId().value()); - } catch (LocalPublicationJournalException exception) { - throw new FilePublicationException( - FilePublicationException.Reason.UNAVAILABLE, - "file publication operation lock is unavailable", - exception); - } - try (operationLock) { - return publishLocked(request, producer); - } catch (LocalPublicationJournalException exception) { - throw indeterminate(exception); - } - } - - private FilePublishReceipt publishLocked( - FilePublishRequest request, TabularRowProducer producer) { - String operationToken = operationToken(request.operationId().value()); - String publishedFileName = request.logicalFileName().value() + "--" + operationToken + ".csv"; - Path staging = stagingDirectory.resolve("." + operationToken + ".part"); - Path target = baseDirectory.resolve(publishedFileName); - String requestFingerprint = FilePublishRequestFingerprint.calculate(request); - Optional prior; - try { - prior = journal.find(request.operationId().value()); - } catch (LocalPublicationJournalException exception) { - throw indeterminate(exception); - } - if (prior.isPresent()) { - return recover(prior.get(), request, requestFingerprint, staging, target); - } - if (Files.exists(target, LinkOption.NOFOLLOW_LINKS)) { - throw new FilePublicationException( - FilePublicationException.Reason.CONFLICT, - "file publication target already exists for operation"); - } - - LocalPublicationJournalRecord writing = - LocalPublicationJournalRecord.writing( - request.operationId().value(), - requestFingerprint, - publishedFileName, - staging.getFileName().toString()); - storeBeforeCommit(writing); - StreamingCsvEncoder.Stats stats; - try (FileChannel channel = - FileChannel.open( - staging, - StandardOpenOption.CREATE_NEW, - StandardOpenOption.WRITE, - LinkOption.NOFOLLOW_LINKS); - OutputStream output = Channels.newOutputStream(channel)) { - restrictPermissions(staging); - StreamingCsvEncoder encoder = - new StreamingCsvEncoder( - request.schema(), - output, - sha256(), - policy.maximumRows(), - policy.maximumEncodedBytes()); - encoder.writeHeader(); - TabularRowSink sink = - new TabularRowSink() { - @Override - public void write(dev.caskeleton.application.filepublication.TabularRow row) { - encoder.write(row); - } - - @Override - public void checkpoint() { - encoder.checkpoint(); - } - }; - producer.produce(sink); - encoder.checkpoint(); - output.flush(); - channel.force(true); - stats = encoder.finish(); - } catch (RuntimeException exception) { - deleteStaging(staging, exception); - journal.delete(request.operationId().value(), exception); - throw exception; - } catch (FileAlreadyExistsException exception) { - throw new FilePublicationException( - FilePublicationException.Reason.CONFLICT, - "file publication operation is already staging", - exception); - } catch (IOException exception) { - deleteStaging(staging, exception); - journal.delete(request.operationId().value(), exception); - throw new FilePublicationException( - FilePublicationException.Reason.UNAVAILABLE, - "file publication staging failed", - exception); - } - - LocalPublicationJournalRecord sealed = - LocalPublicationJournalRecord.sealed( - request.operationId().value(), - requestFingerprint, - publishedFileName, - staging.getFileName().toString(), - stats.byteSize(), - stats.rowCount(), - request.schema().columns().size(), - stats.sha256(), - stats.formulaMitigatedCount()); - storeBeforeCommit(sealed); - PublicationGuarantee guarantee = publishStaging(staging, target); - verifyArtifact(target, sealed); - Instant publishedAt = Instant.now(); - storeTerminal(sealed.published(publishedAt, guarantee.name())); - return receipt(request, sealed, guarantee, publishedAt); - } - - private FilePublishReceipt recover( - LocalPublicationJournalRecord record, - FilePublishRequest request, - String requestFingerprint, - Path staging, - Path target) { - if (!record.requestFingerprint().equals(requestFingerprint)) { - throw new FilePublicationException( - FilePublicationException.Reason.CONFLICT, - "file publication operation was already used for a different request"); - } - if (!record.stageFileName().equals(staging.getFileName().toString()) - || !record.publishedFileName().equals(target.getFileName().toString())) { - throw indeterminate(new IOException("journal locator mismatch")); - } - if (record.state() == LocalPublicationJournalRecord.State.WRITING) { - throw indeterminate(new IOException("publication interrupted before sealing")); - } - PublicationGuarantee guarantee; - if (record.state() == LocalPublicationJournalRecord.State.PUBLISHED) { - verifyArtifact(target, record); - guarantee = publicationGuarantee(record.publicationGuarantee()); - return receipt(request, record, guarantee, Instant.parse(record.publishedAt())); - } - - if (Files.exists(target, LinkOption.NOFOLLOW_LINKS)) { - verifyArtifact(target, record); - try { - forceDirectory(baseDirectory); - } catch (IOException exception) { - throw indeterminate(exception); - } - guarantee = PublicationGuarantee.UNIQUE_ATOMIC_CREATE; - } else if (Files.exists(staging, LinkOption.NOFOLLOW_LINKS)) { - verifyArtifact(staging, record); - guarantee = publishStaging(staging, target); - verifyArtifact(target, record); - } else { - throw indeterminate(new IOException("sealed publication artifact is unavailable")); - } - Instant publishedAt = Instant.now(); - storeTerminal(record.published(publishedAt, guarantee.name())); - return receipt(request, record, guarantee, publishedAt); - } - - private FilePublishReceipt receipt( - FilePublishRequest request, - LocalPublicationJournalRecord record, - PublicationGuarantee guarantee, - Instant publishedAt) { - String operationToken = operationToken(request.operationId().value()); - return new FilePublishReceipt( - request.operationId(), - new PublishedFileReference( - "filepub:" + policy.destinationId().value() + ":" + operationToken), - request.destinationId(), - record.publishedFileName(), - new FileVersion(record.sha256()), - request.formatProfileId(), - "text/csv", - "UTF-8", - record.byteSize(), - record.rowCount(), - record.columnCount(), - record.sha256(), - publishedAt, - guarantee, - DurabilityGuarantee.PROCESS_LOCAL_SYNC, - record.formulaMitigatedCount()); - } - - private static PublicationGuarantee publicationGuarantee(String name) { - try { - return PublicationGuarantee.valueOf(name); - } catch (IllegalArgumentException exception) { - throw new FilePublicationException( - FilePublicationException.Reason.PUBLISH_INDETERMINATE, - "file publication journal contains an unknown guarantee", - exception); - } - } - - private static void verifyArtifact(Path artifact, LocalPublicationJournalRecord record) { - try { - if (!Files.isRegularFile(artifact, LinkOption.NOFOLLOW_LINKS) - || Files.size(artifact) != record.byteSize() - || !digest(artifact).equals(record.sha256())) { - throw indeterminate(new IOException("publication artifact integrity mismatch")); - } - } catch (IOException exception) { - throw indeterminate(exception); - } - } - - private static String digest(Path artifact) throws IOException { - MessageDigest digest = sha256(); - try (var input = Files.newInputStream(artifact, LinkOption.NOFOLLOW_LINKS)) { - byte[] buffer = new byte[8192]; - int read; - while ((read = input.read(buffer)) != -1) { - digest.update(buffer, 0, read); - } - } - return HEX.formatHex(digest.digest()); - } - - private void validateRequest(FilePublishRequest request) { - Objects.requireNonNull(request, "request must be non-null"); - if (!policy.destinationId().equals(request.destinationId())) { - throw new FilePublicationException( - FilePublicationException.Reason.INVALID_REQUEST, - "file publication destination is not bound to this provider"); - } - if (!FORMAT_PROFILE.equals(request.formatProfileId())) { - throw new FilePublicationException( - FilePublicationException.Reason.INVALID_REQUEST, - "unsupported file publication format profile"); - } - } - - private PublicationGuarantee publishStaging(Path staging, Path target) { - try { - atomicLinkPublisher.publish(target, staging); - forceDirectory(baseDirectory); - Files.delete(staging); - forceDirectory(stagingDirectory); - return PublicationGuarantee.UNIQUE_ATOMIC_CREATE; - } catch (FileAlreadyExistsException exception) { - throw new FilePublicationException( - FilePublicationException.Reason.CONFLICT, - "file publication target already exists", - exception); - } catch (IOException exception) { - if (Files.exists(target, LinkOption.NOFOLLOW_LINKS)) { - throw indeterminate(exception); - } - throw unavailableAtomicPublication(exception); - } catch (UnsupportedOperationException exception) { - throw unavailableAtomicPublication(exception); - } - } - - private static FilePublicationException unavailableAtomicPublication(Exception exception) { - return new FilePublicationException( - FilePublicationException.Reason.UNAVAILABLE, - "exclusive atomic file publication is unavailable", - exception); - } - - private static void forceDirectory(Path directory) throws IOException { - try (FileChannel channel = FileChannel.open(directory, StandardOpenOption.READ)) { - channel.force(true); - } - } - - private void initializeDirectories() { - try { - Files.createDirectories(baseDirectory); - if (Files.isSymbolicLink(baseDirectory) - || !Files.isDirectory(baseDirectory, LinkOption.NOFOLLOW_LINKS)) { - throw new FilePublicationException( - FilePublicationException.Reason.INVALID_REQUEST, - "file publication base directory must be a real directory"); - } - Files.createDirectories(stagingDirectory); - if (Files.isSymbolicLink(stagingDirectory) - || !Files.isDirectory(stagingDirectory, LinkOption.NOFOLLOW_LINKS)) { - throw new FilePublicationException( - FilePublicationException.Reason.INVALID_REQUEST, - "file publication staging directory must be a real directory"); - } - restrictPermissions(stagingDirectory); - } catch (IOException exception) { - throw new FilePublicationException( - FilePublicationException.Reason.UNAVAILABLE, - "file publication directories are unavailable", - exception); - } - } - - private static void restrictPermissions(Path path) throws IOException { - try { - Files.setPosixFilePermissions( - path, - Files.isDirectory(path, LinkOption.NOFOLLOW_LINKS) - ? Set.of( - PosixFilePermission.OWNER_READ, - PosixFilePermission.OWNER_WRITE, - PosixFilePermission.OWNER_EXECUTE) - : Set.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE)); - } catch (UnsupportedOperationException ignored) { - // Non-POSIX filesystems are allowed only as R1; deployment evidence owns permission claims. - } - } - - private static MessageDigest sha256() { - try { - return MessageDigest.getInstance("SHA-256"); - } catch (NoSuchAlgorithmException exception) { - throw new IllegalStateException("SHA-256 unavailable", exception); - } - } - - private static String operationToken(String operationId) { - MessageDigest digest = sha256(); - return HEX.formatHex(digest.digest(operationId.getBytes(StandardCharsets.UTF_8))) - .substring(0, 24); - } - - private void storeBeforeCommit(LocalPublicationJournalRecord record) { - try { - journal.store(record); - } catch (LocalPublicationJournalException exception) { - throw new FilePublicationException( - FilePublicationException.Reason.UNAVAILABLE, - "file publication control journal update failed before commit", - exception); - } - } - - private void storeTerminal(LocalPublicationJournalRecord record) { - try { - journal.store(record); - } catch (LocalPublicationJournalException exception) { - throw indeterminate(exception); - } - } - - private static FilePublicationException indeterminate(Throwable exception) { - return new FilePublicationException( - FilePublicationException.Reason.PUBLISH_INDETERMINATE, - "file publication commit outcome is indeterminate", - exception); - } - - private static void deleteStaging(Path staging, Throwable original) { - try { - Files.deleteIfExists(staging); - } catch (IOException cleanupFailure) { - original.addSuppressed(cleanupFailure); - } - } - - @FunctionalInterface - interface AtomicLinkPublisher { - - void publish(Path target, Path staging) throws IOException; - } -} diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/LocalFilePublicationPolicy.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/LocalFilePublicationPolicy.java deleted file mode 100644 index 8b5f3774..00000000 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/LocalFilePublicationPolicy.java +++ /dev/null @@ -1,25 +0,0 @@ -package dev.caskeleton.adapter.outbound.fileserver; - -import dev.caskeleton.application.filepublication.FileDestinationId; -import java.nio.file.Path; -import java.util.Objects; - -/** Immutable operational bounds for the local R1 provider. */ -public record LocalFilePublicationPolicy( - FileDestinationId destinationId, - Path baseDirectory, - long maximumRows, - long maximumEncodedBytes) { - - public LocalFilePublicationPolicy { - Objects.requireNonNull(destinationId, "destinationId must be non-null"); - Objects.requireNonNull(baseDirectory, "baseDirectory must be non-null"); - baseDirectory = baseDirectory.toAbsolutePath().normalize(); - if (maximumRows < 1) { - throw new IllegalArgumentException("maximumRows must be >= 1"); - } - if (maximumEncodedBytes < 1) { - throw new IllegalArgumentException("maximumEncodedBytes must be >= 1"); - } - } -} diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/LocalPersistentControlPlane.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/LocalPersistentControlPlane.java deleted file mode 100644 index 3b5849d1..00000000 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/LocalPersistentControlPlane.java +++ /dev/null @@ -1,1470 +0,0 @@ -package dev.caskeleton.adapter.outbound.fileserver; - -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.channels.FileChannel; -import java.nio.channels.FileLock; -import java.nio.channels.SeekableByteChannel; -import java.nio.charset.StandardCharsets; -import java.nio.file.DirectoryStream; -import java.nio.file.FileAlreadyExistsException; -import java.nio.file.Files; -import java.nio.file.LinkOption; -import java.nio.file.NoSuchFileException; -import java.nio.file.OpenOption; -import java.nio.file.Path; -import java.nio.file.SecureDirectoryStream; -import java.nio.file.StandardCopyOption; -import java.nio.file.StandardOpenOption; -import java.nio.file.attribute.BasicFileAttributeView; -import java.nio.file.attribute.BasicFileAttributes; -import java.nio.file.attribute.PosixFileAttributeView; -import java.nio.file.attribute.PosixFileAttributes; -import java.nio.file.attribute.PosixFilePermission; -import java.nio.file.attribute.PosixFilePermissions; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.SecureRandom; -import java.util.HexFormat; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.locks.ReentrantLock; - -/** Forced local storage for canonical Fileserver R2 control records. */ -final class LocalPersistentControlPlane { - - private static final int MAXIMUM_RECORD_BYTES = 16_384; - private static final int OPERATION_LOCK_STRIPE_COUNT = 256; - private static final SecureRandom SECURE_RANDOM = new SecureRandom(); - private static final HexFormat HEX = HexFormat.of(); - private static final ReentrantLock[] OPERATION_LOCK_STRIPES = createOperationLockStripes(); - private static final ReentrantLock[] IMMUTABLE_LOCK_STRIPES = createOperationLockStripes(); - private static final ThreadLocal> HELD_OPERATION_TOKENS = new ThreadLocal<>(); - private static final Set POISONED_OPERATION_LOCK_ROOTS = ConcurrentHashMap.newKeySet(); - private static final Set TEMPORARY_WRITE_OPTIONS = - Set.of(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE, LinkOption.NOFOLLOW_LINKS); - - private final LocalPersistentRootAttestor attestor; - private final LocalPersistentRootEvidence evidence; - private final FileserverControlRecordCodec codec; - private final ContextualFaultCallback faultCallback; - private final SecureRecordOperations secureRecordOperations; - private final IdentityVerifier identityVerifier; - private final LockLifecycle lockLifecycle; - private final String operationLockRootKey; - private final Path operationsDirectory; - private final Path manifestsDirectory; - private final Path referencesDirectory; - - LocalPersistentControlPlane( - LocalPersistentRootAttestor attestor, LocalPersistentRootEvidence evidence) { - this( - attestor, - evidence, - new FileserverControlRecordCodec(), - context -> {}, - systemSecureRecordOperations(), - null, - systemLockLifecycle()); - } - - LocalPersistentControlPlane( - LocalPersistentRootAttestor attestor, - LocalPersistentRootEvidence evidence, - FaultCallback faultCallback) { - this( - attestor, - evidence, - new FileserverControlRecordCodec(), - contextual(faultCallback), - systemSecureRecordOperations(), - null, - systemLockLifecycle()); - } - - LocalPersistentControlPlane( - LocalPersistentRootAttestor attestor, - LocalPersistentRootEvidence evidence, - FileserverControlRecordCodec codec) { - this( - attestor, - evidence, - codec, - context -> {}, - systemSecureRecordOperations(), - null, - systemLockLifecycle()); - } - - LocalPersistentControlPlane( - LocalPersistentRootAttestor attestor, - LocalPersistentRootEvidence evidence, - FaultCallback faultCallback, - SecureRecordOperations secureRecordOperations, - IdentityVerifier identityVerifier) { - this( - attestor, - evidence, - new FileserverControlRecordCodec(), - contextual(faultCallback), - secureRecordOperations, - identityVerifier, - systemLockLifecycle()); - } - - LocalPersistentControlPlane( - LocalPersistentRootAttestor attestor, - LocalPersistentRootEvidence evidence, - FaultCallback faultCallback, - SecureRecordOperations secureRecordOperations, - IdentityVerifier identityVerifier, - LockLifecycle lockLifecycle) { - this( - attestor, - evidence, - new FileserverControlRecordCodec(), - contextual(faultCallback), - secureRecordOperations, - identityVerifier, - lockLifecycle); - } - - static LocalPersistentControlPlane withContextualFaultCallback( - LocalPersistentRootAttestor attestor, - LocalPersistentRootEvidence evidence, - ContextualFaultCallback faultCallback) { - return new LocalPersistentControlPlane( - attestor, - evidence, - new FileserverControlRecordCodec(), - faultCallback, - systemSecureRecordOperations(), - null, - systemLockLifecycle()); - } - - private LocalPersistentControlPlane( - LocalPersistentRootAttestor attestor, - LocalPersistentRootEvidence evidence, - FileserverControlRecordCodec codec, - ContextualFaultCallback faultCallback, - SecureRecordOperations secureRecordOperations, - IdentityVerifier identityVerifier, - LockLifecycle lockLifecycle) { - this.attestor = Objects.requireNonNull(attestor, "attestor must be non-null"); - this.evidence = Objects.requireNonNull(evidence, "evidence must be non-null"); - this.codec = Objects.requireNonNull(codec, "codec must be non-null"); - this.faultCallback = Objects.requireNonNull(faultCallback, "faultCallback must be non-null"); - this.secureRecordOperations = - Objects.requireNonNull(secureRecordOperations, "secureRecordOperations must be non-null"); - this.identityVerifier = - identityVerifier == null - ? () -> this.attestor.verifyIdentity(this.evidence) - : identityVerifier; - this.lockLifecycle = Objects.requireNonNull(lockLifecycle, "lockLifecycle must be non-null"); - operationLockRootKey = operationLockRootKey(evidence); - Path controlDirectory = evidence.root().resolve(".ca-fileserver"); - operationsDirectory = controlDirectory.resolve("operations"); - manifestsDirectory = controlDirectory.resolve("manifests"); - referencesDirectory = controlDirectory.resolve("references"); - verifyAttestedIdentity(); - } - - Path root() { - return evidence.root(); - } - - void storeOperation(DurablePublicationRecord record) { - Objects.requireNonNull(record, "record must be non-null"); - storeOperation(record.operationId(), record); - } - - void storeOperation(String operationId, DurablePublicationRecord record) { - FileserverControlRecordCodec.requireText(operationId, "operationId", 128); - Objects.requireNonNull(record, "record must be non-null"); - requireOperationLockRootHealthy(); - if (!operationId.equals(record.operationId())) { - throw conflict("operationId cannot change"); - } - Path target = operationPath(operationId); - String token = sha256(operationId); - String scopedLockKey = scopedOperationLockKey(token); - Set heldTokens = HELD_OPERATION_TOKENS.get(); - if (heldTokens != null && heldTokens.contains(scopedLockKey)) { - storeOperationUpdate(target, record); - return; - } - try (OperationLock ignored = acquireOperationLock(operationId)) { - storeOperationUpdate(target, record); - } - } - - OperationLock acquireOperationLock(String operationId) { - FileserverControlRecordCodec.requireText(operationId, "operationId", 128); - String token = sha256(operationId); - String scopedLockKey = scopedOperationLockKey(token); - Path lockPath = operationsDirectory.resolve(token.substring(0, 2)).resolve(token + ".lock"); - ReentrantLock jvmLock = - OPERATION_LOCK_STRIPES[ - Math.floorMod(scopedLockKey.hashCode(), OPERATION_LOCK_STRIPE_COUNT)]; - requireOperationLockRootHealthy(); - jvmLock.lock(); - FileChannel channel = null; - FileLock fileLock = null; - try { - requireOperationLockRootHealthy(); - verifyAttestedIdentity(); - preparePrivateShard(lockPath.getParent(), true); - verifyAttestedIdentity(); - channel = - FileChannel.open( - lockPath, - Set.of( - StandardOpenOption.CREATE, StandardOpenOption.WRITE, LinkOption.NOFOLLOW_LINKS), - PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-------"))); - validateOperationLockFile(lockPath); - fileLock = channel.lock(); - verifyAttestedIdentity(); - requireOperationLockRootHealthy(); - Set heldTokens = HELD_OPERATION_TOKENS.get(); - if (heldTokens == null) { - heldTokens = new java.util.HashSet<>(); - HELD_OPERATION_TOKENS.set(heldTokens); - } - heldTokens.add(scopedLockKey); - return new OperationLock( - operationLockRootKey, - scopedLockKey, - Thread.currentThread(), - jvmLock, - channel, - fileLock, - lockLifecycle); - } catch (IOException | RuntimeException exception) { - closeLockAfterAcquireFailure(fileLock, channel, exception); - jvmLock.unlock(); - if (exception instanceof LocalPersistentControlPlaneException controlPlaneException) { - throw controlPlaneException; - } - throw storage("operation lock cannot be acquired", exception); - } - } - - boolean operationLockHeldByCurrentThread(String operationId) { - FileserverControlRecordCodec.requireText(operationId, "operationId", 128); - Set heldTokens = HELD_OPERATION_TOKENS.get(); - return heldTokens != null && heldTokens.contains(scopedOperationLockKey(sha256(operationId))); - } - - boolean operationLockStripeHeldByCurrentThread(String operationId) { - FileserverControlRecordCodec.requireText(operationId, "operationId", 128); - String scopedLockKey = scopedOperationLockKey(sha256(operationId)); - return OPERATION_LOCK_STRIPES[ - Math.floorMod(scopedLockKey.hashCode(), OPERATION_LOCK_STRIPE_COUNT)] - .isHeldByCurrentThread(); - } - - Optional findOperation(String operationId) { - FileserverControlRecordCodec.requireText(operationId, "operationId", 128); - Optional result = - find(operationPath(operationId), codec::decodeOperation); - result.ifPresent( - record -> { - if (!record.operationId().equals(operationId)) { - throw integrity("operation control record identity mismatch"); - } - }); - return result; - } - - Optional findStoredOperation(String operationId) { - FileserverControlRecordCodec.requireText(operationId, "operationId", 128); - Optional result = - find(operationPath(operationId), this::decodeStoredOperation); - result.ifPresent( - record -> { - if (!record.operationId().equals(operationId)) { - throw integrity("operation control record identity mismatch"); - } - }); - return result; - } - - void storeManifest(PrivateFileManifest manifest) { - Objects.requireNonNull(manifest, "manifest must be non-null"); - requireOperationLockRootHealthy(); - Path target = fileRecordPath(manifestsDirectory, manifest.fileId()); - withImmutableLock( - "manifest:" + manifest.fileId(), - () -> - storeImmutable( - target, - codec.encodeManifest(manifest), - codec::decodeManifest, - manifest, - existing -> existing.fileId().equals(manifest.fileId()))); - } - - Optional findManifest(String fileId) { - FileserverControlRecordCodec.requireFileId(fileId); - Optional result = - find(fileRecordPath(manifestsDirectory, fileId), codec::decodeManifest); - result.ifPresent( - manifest -> { - if (!manifest.fileId().equals(fileId)) { - throw integrity("manifest control record identity mismatch"); - } - }); - return result; - } - - void storeReference(PublishedReferenceRecord reference) { - Objects.requireNonNull(reference, "reference must be non-null"); - requireOperationLockRootHealthy(); - Path target = fileRecordPath(referencesDirectory, reference.fileId()); - withImmutableLock( - "reference:" + reference.fileId(), - () -> - storeImmutable( - target, - codec.encodeReference(reference), - codec::decodeReference, - reference, - existing -> existing.fileId().equals(reference.fileId()))); - } - - Optional findReference(String fileId) { - FileserverControlRecordCodec.requireFileId(fileId); - Optional result = - find(fileRecordPath(referencesDirectory, fileId), codec::decodeReference); - result.ifPresent( - reference -> { - if (!reference.fileId().equals(fileId)) { - throw integrity("reference control record identity mismatch"); - } - }); - return result; - } - - private void storeOperationUpdate(Path target, DurablePublicationRecord candidate) { - verifyAttestedIdentity(); - try { - preparePrivateShard(target.getParent(), true); - Optional existing = readExisting(target, codec::decodeOperation); - if (existing.isPresent()) { - DurablePublicationRecord current = existing.orElseThrow(); - if (!current.operationId().equals(candidate.operationId())) { - throw integrity("stored operation identity does not match its lookup key"); - } - validateOperationTransition(current, candidate); - if (current.equals(candidate)) { - repairAndReadBack( - target, codec::decodeOperation, candidate, FaultSubject.operation(candidate)); - return; - } - } else { - validateInitialOperation(candidate); - } - durableWrite( - target, - codec.encodeOperation(candidate), - codec::decodeOperation, - candidate, - true, - null, - FaultSubject.operation(candidate)); - } catch (IOException exception) { - throw storage("operation control record cannot be durably stored", exception); - } - } - - private void storeImmutable( - Path target, - byte[] encoded, - Decoder decoder, - T candidate, - IdentityMatch identityMatch) { - verifyAttestedIdentity(); - try { - preparePrivateShard(target.getParent(), true); - Optional existing = readExisting(target, decoder); - if (existing.isPresent()) { - T current = existing.orElseThrow(); - if (!identityMatch.matches(current)) { - throw integrity("stored immutable identity does not match its lookup key"); - } - if (!current.equals(candidate)) { - throw conflict("immutable control record already exists with different content"); - } - repairAndReadBack(target, decoder, candidate, immutableFaultSubject(candidate)); - return; - } - durableWrite( - target, - encoded, - decoder, - candidate, - false, - identityMatch, - immutableFaultSubject(candidate)); - } catch (IOException exception) { - throw storage("immutable control record cannot be durably stored", exception); - } - } - - private void durableWrite( - Path target, - byte[] encoded, - Decoder decoder, - T expected, - boolean replaceExisting, - IdentityMatch identityMatch, - FaultSubject faultSubject) { - RecordLocation targetLocation = recordLocation(target); - String temporaryName = "." + target.getFileName() + "." + uniqueToken() + ".tmp"; - Path temporary = target.getParent().resolve(temporaryName); - CreatedTemporary created = null; - try { - created = - secureRecordOperations.createNewAndForce( - targetLocation.topDirectory(), targetLocation.shard(), temporaryName, encoded); - reached(faultSubject, FaultPoint.TEMP_FORCED); - requireCreatedTemporaryIdentity(targetLocation, temporaryName, created); - verifyAttestedIdentity(); - if (replaceExisting) { - Files.move( - temporary, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); - } else { - try { - Files.createLink(target, temporary); - } catch (FileAlreadyExistsException collision) { - verifyAttestedIdentity(); - requireDeleteCreatedTemporary(targetLocation, temporaryName, created); - created = null; - T existing = - readExisting(target, decoder) - .orElseThrow(() -> integrity("immutable collision target disappeared")); - if (identityMatch != null && !identityMatch.matches(existing)) { - throw integrity("immutable collision identity does not match its lookup key"); - } - if (!expected.equals(existing)) { - throw conflict("immutable control record already exists with different content"); - } - repairAndReadBack(target, decoder, expected, faultSubject); - return; - } - } - verifyAttestedIdentity(); - if (replaceExisting) { - created = null; - } else { - requireDeleteCreatedTemporary(targetLocation, temporaryName, created); - created = null; - } - reached(faultSubject, FaultPoint.RECORD_REPLACED); - forceDirectory(target.getParent()); - reached(faultSubject, FaultPoint.PARENT_FORCED); - requireExactReadBack(target, decoder, expected); - verifyAttestedIdentity(); - } catch (IOException exception) { - cleanupCreatedTemporary(targetLocation, temporaryName, created, exception); - throw storage("control record cannot be durably stored", exception); - } catch (RuntimeException exception) { - cleanupCreatedTemporary(targetLocation, temporaryName, created, exception); - throw exception; - } - } - - private void repairAndReadBack( - Path target, Decoder decoder, T expected, FaultSubject faultSubject) throws IOException { - forceDirectory(target.getParent()); - reached(faultSubject, FaultPoint.PARENT_FORCED); - requireExactReadBack(target, decoder, expected); - verifyAttestedIdentity(); - } - - private void requireExactReadBack(Path target, Decoder decoder, T expected) - throws IOException { - T readBack = - readExisting(target, decoder) - .orElseThrow(() -> integrity("stored control record disappeared during read-back")); - if (!expected.equals(readBack)) { - throw integrity("stored control record failed canonical read-back"); - } - } - - private static void validateOperationTransition( - DurablePublicationRecord current, DurablePublicationRecord candidate) { - if (current.equals(candidate)) { - return; - } - if (!current.requestFingerprint().equals(candidate.requestFingerprint())) { - throw conflict("operation requestFingerprint cannot change"); - } - if (!sameOperationIdentity(current, candidate)) { - throw conflict("operation immutable identity cannot change"); - } - if (candidate.stateRevision() < current.stateRevision()) { - throw conflict("operation stateRevision cannot decrease"); - } - if (candidate.stateRevision() == current.stateRevision()) { - throw conflict("operation revision already exists with different content"); - } - if (current.stateRevision() == Long.MAX_VALUE - || candidate.stateRevision() != current.stateRevision() + 1) { - throw conflict("operation stateRevision must advance exactly once"); - } - if (!isAllowedAdjacentTransition(current.state(), candidate.state())) { - throw conflict("operation state must follow the adjacent transition matrix"); - } - if (current.state() != DurablePublicationRecord.State.WRITING) { - requireSealedFactsUnchanged(current, candidate); - } - if (current.state() == DurablePublicationRecord.State.MANIFEST_PUBLISHED - || current.state() == DurablePublicationRecord.State.REFERENCE_PUBLISHED) { - if (!current.manifestDigest().equals(candidate.manifestDigest())) { - throw conflict("operation manifestDigest cannot change after publication"); - } - } - if (current.state() == DurablePublicationRecord.State.REFERENCE_PUBLISHED - && !current.referenceDigest().equals(candidate.referenceDigest())) { - throw conflict("operation referenceDigest cannot change after publication"); - } - } - - private static void validateInitialOperation(DurablePublicationRecord candidate) { - if (candidate.state() != DurablePublicationRecord.State.WRITING - || candidate.stateRevision() != DurablePublicationRecord.State.WRITING.minimumRevision()) { - throw conflict("initial operation must be WRITING at its minimum revision"); - } - } - - private static boolean sameOperationIdentity( - DurablePublicationRecord current, DurablePublicationRecord candidate) { - return current.operationId().equals(candidate.operationId()) - && current.effectivePolicyRevision().equals(candidate.effectivePolicyRevision()) - && current.effectivePolicyDigest().equals(candidate.effectivePolicyDigest()) - && current.destinationId().equals(candidate.destinationId()) - && current.providerId().equals(candidate.providerId()) - && current.fileId().equals(candidate.fileId()) - && current.routeToken().equals(candidate.routeToken()) - && current.publishedFileName().equals(candidate.publishedFileName()) - && current.stageFileName().equals(candidate.stageFileName()) - && current.createdAt().equals(candidate.createdAt()); - } - - private static boolean isAllowedAdjacentTransition( - DurablePublicationRecord.State current, DurablePublicationRecord.State candidate) { - return switch (current) { - case WRITING -> - candidate == DurablePublicationRecord.State.SEALED - || candidate == DurablePublicationRecord.State.QUARANTINED; - case SEALED -> - candidate == DurablePublicationRecord.State.DATA_PUBLISHED - || candidate == DurablePublicationRecord.State.QUARANTINED; - case DATA_PUBLISHED -> - candidate == DurablePublicationRecord.State.MANIFEST_PUBLISHED - || candidate == DurablePublicationRecord.State.QUARANTINED; - case MANIFEST_PUBLISHED -> - candidate == DurablePublicationRecord.State.REFERENCE_PUBLISHED - || candidate == DurablePublicationRecord.State.QUARANTINED; - case REFERENCE_PUBLISHED -> - candidate == DurablePublicationRecord.State.PUBLISHED - || candidate == DurablePublicationRecord.State.QUARANTINED; - case PUBLISHED, QUARANTINED -> false; - }; - } - - private static void requireSealedFactsUnchanged( - DurablePublicationRecord current, DurablePublicationRecord candidate) { - if (current.byteSize() != candidate.byteSize() - || current.rowCount() != candidate.rowCount() - || current.columnCount() != candidate.columnCount() - || !current.sha256().equals(candidate.sha256()) - || current.formulaMitigatedCount() != candidate.formulaMitigatedCount() - || !Objects.equals(current.sealedAt(), candidate.sealedAt())) { - throw conflict("operation sealed facts cannot change after sealing"); - } - } - - private Optional find(Path target, Decoder decoder) { - verifyAttestedIdentity(); - try { - if (!preparePrivateShard(target.getParent(), false)) { - verifyAttestedIdentity(); - return Optional.empty(); - } - Optional result = readExisting(target, decoder); - verifyAttestedIdentity(); - return result; - } catch (IOException exception) { - throw storage("control record cannot be read", exception); - } - } - - private Optional readExisting(Path target, Decoder decoder) throws IOException { - RecordLocation location = recordLocation(target); - Optional secureRecord = - secureRecordOperations.read( - location.topDirectory(), - location.shard(), - location.relativeFileName(), - MAXIMUM_RECORD_BYTES); - if (secureRecord.isEmpty()) { - return Optional.empty(); - } - byte[] encoded = secureRecord.orElseThrow().bytes(); - try { - return Optional.of(decoder.decode(encoded)); - } catch (LocalPersistentControlPlaneException exception) { - throw exception; - } catch (RuntimeException exception) { - throw integrity("control record is not canonical or supported", exception); - } - } - - private StoredOperationRecord decodeStoredOperation(byte[] encoded) { - try { - return new R2StoredOperationRecord(codec.decodeOperation(encoded)); - } catch (RuntimeException versionTwoFailure) { - try { - LocalPublicationJournalRecord r1 = LocalPublicationJournalCodec.decodeCanonical(encoded); - if (r1.state() != LocalPublicationJournalRecord.State.PUBLISHED) { - throw new IllegalArgumentException( - "R1 compatibility operation must be terminal PUBLISHED"); - } - return new R1StoredOperationRecord(r1); - } catch (RuntimeException versionOneFailure) { - versionOneFailure.addSuppressed(versionTwoFailure); - throw new IllegalArgumentException( - "operation control record schema is corrupt or unsupported", versionOneFailure); - } - } - } - - private static FaultSubject immutableFaultSubject(Object candidate) { - if (candidate instanceof PrivateFileManifest manifest) { - return FaultSubject.immutable(ControlRecordKind.MANIFEST, manifest.fileId()); - } - if (candidate instanceof PublishedReferenceRecord reference) { - return FaultSubject.immutable(ControlRecordKind.REFERENCE, reference.fileId()); - } - throw new IllegalArgumentException("unsupported immutable control record type"); - } - - private void reached(FaultSubject subject, FaultPoint boundary) { - faultCallback.reached( - new FaultContext(subject.recordKind(), subject.identity(), subject.operation(), boundary)); - } - - private static ContextualFaultCallback contextual(FaultCallback callback) { - Objects.requireNonNull(callback, "faultCallback must be non-null"); - return context -> callback.reached(context.boundary()); - } - - private boolean preparePrivateShard(Path shard, boolean createIfMissing) throws IOException { - validateShardCoordinates(shard); - verifyAttestedIdentity(); - boolean created = false; - Path topDirectory = shard.getParent(); - String shardName = shard.getFileName().toString(); - Optional inspected = secureRecordOperations.statShard(topDirectory, shardName); - if (inspected.isEmpty()) { - if (!createIfMissing) { - verifyAttestedIdentity(); - return false; - } - try { - Files.createDirectory( - shard, - PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwx------"))); - created = true; - } catch (FileAlreadyExistsException ignored) { - // A concurrent creator must still pass the complete no-follow validation below. - } - } - inspected = secureRecordOperations.statShard(topDirectory, shardName); - validatePrivateShard(shard, inspected.orElseThrow(() -> integrity("control shard vanished"))); - if (created) { - forceDirectory(shard.getParent()); - } - verifyAttestedIdentity(); - return true; - } - - private void validatePrivateShard(Path shard, SecureShard attributes) throws IOException { - if (!attributes.directory() || attributes.symbolicLink()) { - throw integrity("control record shard is not a real directory"); - } - if (!attributes.owner().equals(evidence.expectedOwner())) { - throw integrity("control record shard owner does not match the attested owner"); - } - if (!attributes.permissions().equals(PosixFilePermissions.fromString("rwx------"))) { - throw integrity("control record shard permissions must be 0700"); - } - var store = Files.getFileStore(shard); - var topStore = Files.getFileStore(shard.getParent()); - if (!store.equals(topStore) - || !store.name().equals(evidence.fileStoreName()) - || !store.type().equals(evidence.fileStoreType())) { - throw integrity("control record shard FileStore does not match the attested root"); - } - } - - private void validateShardCoordinates(Path shard) { - Path top = shard.getParent(); - String name = shard.getFileName().toString(); - if ((!top.equals(operationsDirectory) - && !top.equals(manifestsDirectory) - && !top.equals(referencesDirectory)) - || !name.matches("[0-9a-f]{2}")) { - throw integrity("control record shard coordinates are unsafe"); - } - } - - private Path operationPath(String operationId) { - FileserverControlRecordCodec.requireText(operationId, "operationId", 128); - String token = sha256(operationId); - return operationsDirectory.resolve(token.substring(0, 2)).resolve(token + ".json"); - } - - private static Path fileRecordPath(Path directory, String fileId) { - FileserverControlRecordCodec.requireFileId(fileId); - return directory.resolve(fileId.substring(0, 2)).resolve(fileId + ".json"); - } - - private static String sha256(String value) { - try { - return HEX.formatHex( - MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8))); - } catch (NoSuchAlgorithmException exception) { - throw new IllegalStateException("SHA-256 must be available", exception); - } - } - - private static String uniqueToken() { - byte[] bytes = new byte[16]; - SECURE_RANDOM.nextBytes(bytes); - return HEX.formatHex(bytes); - } - - private String scopedOperationLockKey(String operationToken) { - return operationLockRootKey + "\u0000" + operationToken; - } - - private static String operationLockRootKey(LocalPersistentRootEvidence evidence) { - return evidence.root().toAbsolutePath().normalize() - + "\u0000" - + evidence.rootFileKey() - + "\u0000" - + evidence.fileStoreName() - + "\u0000" - + evidence.fileStoreType(); - } - - private void requireOperationLockRootHealthy() { - if (POISONED_OPERATION_LOCK_ROOTS.contains(operationLockRootKey)) { - throw storage("operation lock scope is poisoned because OS unlock was not proven"); - } - } - - private RecordLocation recordLocation(Path target) { - Path shardPath = target.getParent(); - validateShardCoordinates(shardPath); - String relativeFileName = target.getFileName().toString(); - Path relative = Path.of(relativeFileName); - if (relative.isAbsolute() - || relative.getNameCount() != 1 - || relativeFileName.equals(".") - || relativeFileName.equals("..")) { - throw integrity("control record filename is unsafe"); - } - return new RecordLocation( - shardPath.getParent(), shardPath.getFileName().toString(), relativeFileName); - } - - private void validateOperationLockFile(Path lockPath) throws IOException { - PosixFileAttributes attributes = - Files.readAttributes(lockPath, PosixFileAttributes.class, LinkOption.NOFOLLOW_LINKS); - if (!attributes.isRegularFile() || attributes.isSymbolicLink()) { - throw integrity("operation lock is not a regular file"); - } - if (!attributes.owner().getName().equals(evidence.expectedOwner())) { - throw integrity("operation lock owner does not match the attested owner"); - } - if (!attributes.permissions().equals(PosixFilePermissions.fromString("rw-------"))) { - throw integrity("operation lock permissions must be 0600"); - } - var store = Files.getFileStore(lockPath); - if (!store.name().equals(evidence.fileStoreName()) - || !store.type().equals(evidence.fileStoreType())) { - throw integrity("operation lock FileStore does not match the attested root"); - } - } - - private static void forceDirectory(Path directory) throws IOException { - try (FileChannel channel = FileChannel.open(directory, StandardOpenOption.READ)) { - channel.force(true); - } - } - - private void verifyAttestedIdentity() { - try { - identityVerifier.verify(); - } catch (LocalPersistentControlPlaneException exception) { - throw exception; - } catch (RuntimeException exception) { - throw storage("attested persistent root identity verification failed", exception); - } - } - - private void requireDeleteCreatedTemporary( - RecordLocation target, String temporaryName, CreatedTemporary created) throws IOException { - requireCreatedTemporaryIdentity(target, temporaryName, created); - secureRecordOperations.deleteExact(target.topDirectory(), target.shard(), temporaryName); - } - - private void requireCreatedTemporaryIdentity( - RecordLocation target, String temporaryName, CreatedTemporary created) throws IOException { - Optional current = - secureRecordOperations.fileKeyNoFollow( - target.topDirectory(), target.shard(), temporaryName); - if (current.isEmpty() || !current.orElseThrow().equals(created.fileKey())) { - throw integrity("created temporary identity changed before commit or exact deletion"); - } - } - - private void cleanupCreatedTemporary( - RecordLocation target, String temporaryName, CreatedTemporary created, Throwable original) { - if (created == null) { - return; - } - try { - Optional current = - secureRecordOperations.fileKeyNoFollow( - target.topDirectory(), target.shard(), temporaryName); - if (current.isPresent() && current.orElseThrow().equals(created.fileKey())) { - secureRecordOperations.deleteExact(target.topDirectory(), target.shard(), temporaryName); - } - } catch (IOException cleanupFailure) { - original.addSuppressed(cleanupFailure); - } catch (RuntimeException cleanupFailure) { - original.addSuppressed(cleanupFailure); - } - } - - private static void withImmutableLock(String key, Runnable action) { - ReentrantLock lock = - IMMUTABLE_LOCK_STRIPES[Math.floorMod(key.hashCode(), OPERATION_LOCK_STRIPE_COUNT)]; - lock.lock(); - try { - action.run(); - } finally { - lock.unlock(); - } - } - - private static ReentrantLock[] createOperationLockStripes() { - ReentrantLock[] stripes = new ReentrantLock[OPERATION_LOCK_STRIPE_COUNT]; - for (int index = 0; index < stripes.length; index++) { - stripes[index] = new ReentrantLock(); - } - return stripes; - } - - private void closeLockAfterAcquireFailure( - FileLock fileLock, FileChannel channel, Throwable original) { - boolean releaseProvedUnlock = false; - boolean closeProvedUnlock = false; - if (fileLock != null) { - try { - lockLifecycle.release(fileLock); - releaseProvedUnlock = true; - } catch (IOException | RuntimeException closeFailure) { - original.addSuppressed(closeFailure); - } - } - if (channel != null) { - try { - lockLifecycle.close(channel); - closeProvedUnlock = true; - } catch (IOException | RuntimeException closeFailure) { - original.addSuppressed(closeFailure); - } - } - if (fileLock != null && !releaseProvedUnlock && !closeProvedUnlock) { - POISONED_OPERATION_LOCK_ROOTS.add(operationLockRootKey); - } - } - - private static LocalPersistentControlPlaneException conflict(String message) { - return new LocalPersistentControlPlaneException(FailureKind.CONFLICT, message); - } - - private static LocalPersistentControlPlaneException integrity(String message) { - return new LocalPersistentControlPlaneException(FailureKind.INTEGRITY, message); - } - - private static LocalPersistentControlPlaneException integrity(String message, Throwable cause) { - return new LocalPersistentControlPlaneException(FailureKind.INTEGRITY, message, cause); - } - - private static LocalPersistentControlPlaneException storage(String message) { - return new LocalPersistentControlPlaneException(FailureKind.STORAGE, message); - } - - private static LocalPersistentControlPlaneException storage(String message, Throwable cause) { - return new LocalPersistentControlPlaneException(FailureKind.STORAGE, message, cause); - } - - @FunctionalInterface - private interface Decoder { - T decode(byte[] bytes); - } - - @FunctionalInterface - private interface IdentityMatch { - boolean matches(T value); - } - - static SecureRecordOperations systemSecureRecordOperations() { - return SystemSecureRecordOperations.INSTANCE; - } - - static LockLifecycle systemLockLifecycle() { - return SystemLockLifecycle.INSTANCE; - } - - interface LockLifecycle { - - void release(FileLock lock) throws IOException; - - void close(FileChannel channel) throws IOException; - } - - interface SecureRecordOperations { - - Optional statShard(Path topDirectory, String shard) throws IOException; - - Optional read( - Path topDirectory, String shard, String relativeFileName, int maximumBytes) - throws IOException; - - CreatedTemporary createNewAndForce( - Path topDirectory, String shard, String relativeFileName, byte[] bytes) throws IOException; - - Optional fileKeyNoFollow(Path topDirectory, String shard, String relativeFileName) - throws IOException; - - void deleteExact(Path topDirectory, String shard, String relativeFileName) throws IOException; - } - - @FunctionalInterface - interface IdentityVerifier { - void verify(); - } - - enum SecureRecordAction { - STAT_SHARD_NOFOLLOW, - READ, - CREATE_NEW_AND_FORCE, - STAT_NOFOLLOW, - DELETE_EXACT - } - - record SecureRecordCall(Path topDirectory, String shard, String relativeFileName) {} - - record SecureShard( - boolean directory, - boolean symbolicLink, - String owner, - Set permissions, - String fileKey) { - - SecureShard { - Objects.requireNonNull(owner, "owner must be non-null"); - permissions = Set.copyOf(permissions); - Objects.requireNonNull(fileKey, "fileKey must be non-null"); - } - } - - static final class SecureRecord { - - private final byte[] bytes; - private final String fileKey; - - private SecureRecord(byte[] bytes, String fileKey) { - this.bytes = bytes.clone(); - this.fileKey = Objects.requireNonNull(fileKey, "fileKey must be non-null"); - } - - byte[] bytes() { - return bytes.clone(); - } - - String fileKey() { - return fileKey; - } - } - - record CreatedTemporary(String fileKey) { - - CreatedTemporary { - Objects.requireNonNull(fileKey, "fileKey must be non-null"); - } - } - - private record RecordLocation(Path topDirectory, String shard, String relativeFileName) {} - - private enum SystemLockLifecycle implements LockLifecycle { - INSTANCE; - - @Override - public void release(FileLock lock) throws IOException { - lock.release(); - } - - @Override - public void close(FileChannel channel) throws IOException { - channel.close(); - } - } - - private enum SystemSecureRecordOperations implements SecureRecordOperations { - INSTANCE; - - @Override - public Optional statShard(Path topDirectory, String shard) throws IOException { - validateShardCoordinates(topDirectory, shard); - try (SecureDirectoryStream top = openSecure(topDirectory)) { - PosixFileAttributeView view = - top.getFileAttributeView( - Path.of(shard), PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS); - if (view == null) { - throw new IOException("secure shard POSIX attribute view is unavailable"); - } - try { - PosixFileAttributes attributes = view.readAttributes(); - if (attributes.fileKey() == null) { - throw integrity("control record shard has no stable file identity"); - } - return Optional.of( - new SecureShard( - attributes.isDirectory(), - attributes.isSymbolicLink(), - attributes.owner().getName(), - attributes.permissions(), - attributes.fileKey().toString())); - } catch (NoSuchFileException missing) { - return Optional.empty(); - } - } - } - - @Override - public Optional read( - Path topDirectory, String shard, String relativeFileName, int maximumBytes) - throws IOException { - validateCoordinates(topDirectory, shard, relativeFileName); - try (SecureDirectoryStream top = openSecure(topDirectory); - SecureDirectoryStream directory = - top.newDirectoryStream(Path.of(shard), LinkOption.NOFOLLOW_LINKS)) { - Path relative = Path.of(relativeFileName); - BasicFileAttributes before; - try { - before = attributes(directory, relative); - } catch (NoSuchFileException missing) { - return Optional.empty(); - } - validateRegularRecord(before, maximumBytes); - byte[] bytes = readBounded(directory, relative, before, maximumBytes); - BasicFileAttributes after = attributes(directory, relative); - validateRegularRecord(after, maximumBytes); - String beforeKey = requireFileKey(before); - if (!beforeKey.equals(requireFileKey(after)) - || before.size() != after.size() - || bytes.length != after.size()) { - throw integrity("control record identity changed while being read"); - } - return Optional.of(new SecureRecord(bytes, beforeKey)); - } - } - - @Override - public CreatedTemporary createNewAndForce( - Path topDirectory, String shard, String relativeFileName, byte[] bytes) throws IOException { - validateCoordinates(topDirectory, shard, relativeFileName); - try (SecureDirectoryStream top = openSecure(topDirectory); - SecureDirectoryStream directory = - top.newDirectoryStream(Path.of(shard), LinkOption.NOFOLLOW_LINKS)) { - Path relative = Path.of(relativeFileName); - String createdKey = null; - try { - try (SeekableByteChannel channel = - directory.newByteChannel( - relative, - TEMPORARY_WRITE_OPTIONS, - PosixFilePermissions.asFileAttribute( - PosixFilePermissions.fromString("rw-------")))) { - BasicFileAttributes createdAttributes = attributes(directory, relative); - validateRegularRecord(createdAttributes, MAXIMUM_RECORD_BYTES); - createdKey = requireFileKey(createdAttributes); - if (!(channel instanceof FileChannel fileChannel)) { - throw new IOException("secure relative temporary channel cannot be forced"); - } - ByteBuffer buffer = ByteBuffer.wrap(bytes); - while (buffer.hasRemaining()) { - fileChannel.write(buffer); - } - fileChannel.force(true); - } - BasicFileAttributes attributes = attributes(directory, relative); - validateRegularRecord(attributes, MAXIMUM_RECORD_BYTES); - if (attributes.size() != bytes.length || !createdKey.equals(requireFileKey(attributes))) { - throw integrity("forced temporary identity or size does not match its creation"); - } - return new CreatedTemporary(createdKey); - } catch (IOException | RuntimeException failure) { - cleanupCreatedRelative(directory, relative, createdKey, failure); - throw failure; - } - } - } - - @Override - public Optional fileKeyNoFollow( - Path topDirectory, String shard, String relativeFileName) throws IOException { - validateCoordinates(topDirectory, shard, relativeFileName); - try (SecureDirectoryStream top = openSecure(topDirectory); - SecureDirectoryStream directory = - top.newDirectoryStream(Path.of(shard), LinkOption.NOFOLLOW_LINKS)) { - try { - BasicFileAttributes attributes = attributes(directory, Path.of(relativeFileName)); - validateRegularRecord(attributes, MAXIMUM_RECORD_BYTES); - return Optional.of(requireFileKey(attributes)); - } catch (NoSuchFileException missing) { - return Optional.empty(); - } - } - } - - @Override - public void deleteExact(Path topDirectory, String shard, String relativeFileName) - throws IOException { - validateCoordinates(topDirectory, shard, relativeFileName); - try (SecureDirectoryStream top = openSecure(topDirectory); - SecureDirectoryStream directory = - top.newDirectoryStream(Path.of(shard), LinkOption.NOFOLLOW_LINKS)) { - directory.deleteFile(Path.of(relativeFileName)); - } - } - - private static byte[] readBounded( - SecureDirectoryStream directory, - Path relative, - BasicFileAttributes attributes, - int maximumBytes) - throws IOException { - if (attributes.size() > maximumBytes) { - throw integrity("control record exceeds the maximum size"); - } - ByteBuffer buffer = ByteBuffer.allocate(maximumBytes + 1); - try (SeekableByteChannel channel = - directory.newByteChannel( - relative, Set.of(StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS))) { - while (buffer.hasRemaining() && channel.read(buffer) >= 0) { - // Continue until EOF or one byte beyond the accepted bound. - } - } - if (buffer.position() > maximumBytes) { - throw integrity("control record exceeds the maximum size"); - } - return java.util.Arrays.copyOf(buffer.array(), buffer.position()); - } - - private static BasicFileAttributes attributes( - SecureDirectoryStream directory, Path relative) throws IOException { - BasicFileAttributeView view = - directory.getFileAttributeView( - relative, BasicFileAttributeView.class, LinkOption.NOFOLLOW_LINKS); - if (view == null) { - throw new IOException("secure no-follow attribute view is unavailable"); - } - return view.readAttributes(); - } - - private static void cleanupCreatedRelative( - SecureDirectoryStream directory, - Path relative, - String createdKey, - Throwable original) { - if (createdKey == null) { - return; - } - try { - BasicFileAttributes current = attributes(directory, relative); - if (current.isRegularFile() - && !current.isSymbolicLink() - && createdKey.equals(requireFileKey(current))) { - directory.deleteFile(relative); - } - } catch (NoSuchFileException ignored) { - // The exact created entry is already absent. - } catch (IOException | RuntimeException cleanupFailure) { - original.addSuppressed(cleanupFailure); - } - } - - private static void validateRegularRecord(BasicFileAttributes attributes, int maximumBytes) { - if (!attributes.isRegularFile() || attributes.isSymbolicLink()) { - throw integrity("control record is not a no-follow regular file"); - } - if (attributes.size() > maximumBytes) { - throw integrity("control record exceeds the maximum size"); - } - requireFileKey(attributes); - } - - private static String requireFileKey(BasicFileAttributes attributes) { - if (attributes.fileKey() == null) { - throw integrity("control record has no stable file identity"); - } - return attributes.fileKey().toString(); - } - - private static void validateCoordinates( - Path topDirectory, String shard, String relativeFileName) { - Path relative = Path.of(relativeFileName); - if (!topDirectory.isAbsolute() - || !topDirectory.normalize().equals(topDirectory) - || !shard.matches("[0-9a-f]{2}") - || relative.isAbsolute() - || relative.getNameCount() != 1 - || relativeFileName.equals(".") - || relativeFileName.equals("..")) { - throw integrity("secure record coordinates are unsafe"); - } - } - - private static void validateShardCoordinates(Path topDirectory, String shard) { - if (!topDirectory.isAbsolute() - || !topDirectory.normalize().equals(topDirectory) - || !shard.matches("[0-9a-f]{2}")) { - throw integrity("secure shard coordinates are unsafe"); - } - } - - // The stream is the return value; the caller owns and closes it. "resource" says that to the - // Eclipse compiler, "StreamResourceLeak" to ErrorProne. - @SuppressWarnings({"StreamResourceLeak", "unchecked", "resource"}) - private static SecureDirectoryStream openSecure(Path directory) throws IOException { - DirectoryStream stream = Files.newDirectoryStream(directory); - if (stream instanceof SecureDirectoryStream secure) { - return (SecureDirectoryStream) secure; - } - stream.close(); - throw new IOException("SecureDirectoryStream unavailable for " + directory); - } - } - - enum FaultPoint { - TEMP_FORCED, - RECORD_REPLACED, - PARENT_FORCED - } - - enum ControlRecordKind { - OPERATION, - MANIFEST, - REFERENCE - } - - record OperationFaultState(DurablePublicationRecord.State state, long stateRevision) { - - OperationFaultState { - Objects.requireNonNull(state, "state must be non-null"); - if (stateRevision < 1) { - throw new IllegalArgumentException("stateRevision must be positive"); - } - } - } - - record FaultContext( - ControlRecordKind recordKind, - String identity, - Optional operation, - FaultPoint boundary) { - - FaultContext { - Objects.requireNonNull(recordKind, "recordKind must be non-null"); - FileserverControlRecordCodec.requireText(identity, "identity", 128); - Objects.requireNonNull(operation, "operation must be non-null"); - Objects.requireNonNull(boundary, "boundary must be non-null"); - if ((recordKind == ControlRecordKind.OPERATION) != operation.isPresent()) { - throw new IllegalArgumentException( - "operation fault state presence must match the control record kind"); - } - } - } - - sealed interface StoredOperationRecord permits R1StoredOperationRecord, R2StoredOperationRecord { - - String operationId(); - } - - record R1StoredOperationRecord(LocalPublicationJournalRecord record) - implements StoredOperationRecord { - - R1StoredOperationRecord { - Objects.requireNonNull(record, "record must be non-null"); - if (record.state() != LocalPublicationJournalRecord.State.PUBLISHED) { - throw new IllegalArgumentException("R1 compatibility record must be terminal PUBLISHED"); - } - } - - @Override - public String operationId() { - return record.operationId(); - } - } - - record R2StoredOperationRecord(DurablePublicationRecord record) implements StoredOperationRecord { - - R2StoredOperationRecord { - Objects.requireNonNull(record, "record must be non-null"); - } - - @Override - public String operationId() { - return record.operationId(); - } - } - - private record FaultSubject( - ControlRecordKind recordKind, String identity, Optional operation) { - - private static FaultSubject operation(DurablePublicationRecord record) { - return new FaultSubject( - ControlRecordKind.OPERATION, - record.operationId(), - Optional.of(new OperationFaultState(record.state(), record.stateRevision()))); - } - - private static FaultSubject immutable(ControlRecordKind kind, String identity) { - return new FaultSubject(kind, identity, Optional.empty()); - } - } - - enum FailureKind { - CONFLICT, - INTEGRITY, - STORAGE - } - - @FunctionalInterface - interface FaultCallback { - void reached(FaultPoint point); - } - - @FunctionalInterface - interface ContextualFaultCallback { - void reached(FaultContext context); - } - - static final class OperationLock implements AutoCloseable { - - private final String rootKey; - private final String scopedLockKey; - private final Thread owner; - private final ReentrantLock jvmLock; - private final FileChannel channel; - private final FileLock fileLock; - private final LockLifecycle lifecycle; - private final AtomicBoolean closed = new AtomicBoolean(); - - private OperationLock( - String rootKey, - String scopedLockKey, - Thread owner, - ReentrantLock jvmLock, - FileChannel channel, - FileLock fileLock, - LockLifecycle lifecycle) { - this.rootKey = rootKey; - this.scopedLockKey = scopedLockKey; - this.owner = owner; - this.jvmLock = jvmLock; - this.channel = channel; - this.fileLock = fileLock; - this.lifecycle = lifecycle; - } - - @Override - public void close() { - if (Thread.currentThread() != owner) { - throw new IllegalStateException("operation lock must be closed by its owning thread"); - } - if (!closed.compareAndSet(false, true)) { - return; - } - LocalPersistentControlPlaneException failure = null; - boolean releaseProvedUnlock = false; - boolean closeProvedUnlock = false; - try { - lifecycle.release(fileLock); - releaseProvedUnlock = true; - } catch (IOException | RuntimeException exception) { - failure = storage("operation OS lock cannot be released", exception); - } - try { - lifecycle.close(channel); - closeProvedUnlock = true; - } catch (IOException | RuntimeException exception) { - if (failure == null) { - failure = storage("operation lock channel cannot be closed", exception); - } else { - failure.addSuppressed(exception); - } - } finally { - if (!releaseProvedUnlock && !closeProvedUnlock) { - POISONED_OPERATION_LOCK_ROOTS.add(rootKey); - } - Set heldTokens = HELD_OPERATION_TOKENS.get(); - if (heldTokens != null) { - heldTokens.remove(scopedLockKey); - } - if (heldTokens == null || heldTokens.isEmpty()) { - HELD_OPERATION_TOKENS.remove(); - } - jvmLock.unlock(); - } - if (failure != null) { - throw failure; - } - } - } - - static final class LocalPersistentControlPlaneException extends RuntimeException { - private static final long serialVersionUID = 1L; - - private final FailureKind kind; - - private LocalPersistentControlPlaneException(FailureKind kind, String message) { - super(message); - this.kind = kind; - } - - private LocalPersistentControlPlaneException( - FailureKind kind, String message, Throwable cause) { - super(message, cause); - this.kind = kind; - } - - FailureKind kind() { - return kind; - } - } -} diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/LocalPersistentPayloadOperations.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/LocalPersistentPayloadOperations.java deleted file mode 100644 index d0566494..00000000 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/LocalPersistentPayloadOperations.java +++ /dev/null @@ -1,1101 +0,0 @@ -package dev.caskeleton.adapter.outbound.fileserver; - -import java.io.FilterOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.nio.ByteBuffer; -import java.nio.CharBuffer; -import java.nio.channels.Channels; -import java.nio.channels.FileChannel; -import java.nio.channels.SeekableByteChannel; -import java.nio.charset.CharacterCodingException; -import java.nio.charset.CodingErrorAction; -import java.nio.charset.StandardCharsets; -import java.nio.file.DirectoryStream; -import java.nio.file.FileAlreadyExistsException; -import java.nio.file.Files; -import java.nio.file.LinkOption; -import java.nio.file.NoSuchFileException; -import java.nio.file.OpenOption; -import java.nio.file.Path; -import java.nio.file.SecureDirectoryStream; -import java.nio.file.StandardOpenOption; -import java.nio.file.attribute.PosixFileAttributeView; -import java.nio.file.attribute.PosixFileAttributes; -import java.nio.file.attribute.PosixFilePermission; -import java.nio.file.attribute.PosixFilePermissions; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.HexFormat; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; - -/** - * Secure payload boundary for the qualified local-persistent Fileserver R2 provider. - * - *

Caller values are converted to bounded generated segments before filesystem access. Reads, - * writes, and exact deletes use {@link SecureDirectoryStream}; the JDK's missing relative - * hard-link, directory-create, and directory-force primitives are bracketed by attested identity - * checks in this class. - */ -final class LocalPersistentPayloadOperations { - - private static final Set PRIVATE_DIRECTORY_PERMISSIONS = - PosixFilePermissions.fromString("rwx------"); - private static final Set PRIVATE_FILE_PERMISSIONS = - PosixFilePermissions.fromString("rw-------"); - private static final Set CREATE_STAGE_OPTIONS = - Set.of(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE, LinkOption.NOFOLLOW_LINKS); - private static final Set READ_OPTIONS = - Set.of(StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS); - private static final HexFormat HEX = HexFormat.of(); - - private final LocalPersistentRootEvidence evidence; - private final PayloadAccess access; - private final IdentityVerifier identityVerifier; - private final FaultCallback faultCallback; - private final Path stagingDirectory; - private final Path dataDirectory; - - LocalPersistentPayloadOperations( - LocalPersistentRootAttestor attestor, LocalPersistentRootEvidence evidence) { - this(attestor, evidence, systemPayloadAccess(), null, ignored -> {}); - } - - LocalPersistentPayloadOperations( - LocalPersistentRootAttestor attestor, - LocalPersistentRootEvidence evidence, - FaultCallback faultCallback) { - this(attestor, evidence, systemPayloadAccess(), null, faultCallback); - } - - LocalPersistentPayloadOperations( - LocalPersistentRootAttestor attestor, - LocalPersistentRootEvidence evidence, - PayloadAccess access, - IdentityVerifier identityVerifier, - FaultCallback faultCallback) { - LocalPersistentRootAttestor requiredAttestor = - Objects.requireNonNull(attestor, "attestor must be non-null"); - this.evidence = Objects.requireNonNull(evidence, "evidence must be non-null"); - this.access = Objects.requireNonNull(access, "access must be non-null"); - this.identityVerifier = - identityVerifier == null - ? () -> requiredAttestor.verifyIdentity(this.evidence) - : identityVerifier; - this.faultCallback = Objects.requireNonNull(faultCallback, "faultCallback must be non-null"); - stagingDirectory = evidence.root().resolve(".ca-fileserver").resolve("staging"); - dataDirectory = evidence.root().resolve("data"); - requireTopDirectory(stagingDirectory, ".ca-fileserver/staging"); - requireTopDirectory(dataDirectory, "data"); - } - - static String stageFileName(String operationId) { - requireOperationId(operationId); - return "op-" + sha256(operationId) + ".part"; - } - - Path root() { - return evidence.root(); - } - - VerifiedArtifact stage( - String operationId, String stageFileName, long maximumBytes, PayloadWriter writer) { - requireOperationId(operationId); - requireExactStageFileName(operationId, stageFileName); - requirePositiveMaximum(maximumBytes); - Objects.requireNonNull(writer, "writer must be non-null"); - String shard = operationShard(operationId); - verifyIdentity(); - requireTopDirectory(stagingDirectory, ".ca-fileserver/staging"); - preparePrivateShard(stagingDirectory, shard); - VerifiedArtifact staged; - try { - staged = - access.createStageAndForce( - stagingDirectory, shard, stageFileName, operationId, maximumBytes, writer); - } catch (StageWriteFailureException failure) { - Throwable original = failure.original(); - cleanupFailedStage(shard, stageFileName, failure.createdFileKey(), original); - throwOriginal(original); - throw new AssertionError("unreachable"); - } catch (FileAlreadyExistsException exception) { - throw failure(FailureKind.CONFLICT, "payload stage already exists", exception); - } catch (LocalPersistentPayloadException exception) { - throw exception; - } catch (IOException exception) { - throw failure(FailureKind.STORAGE, "payload stage cannot be durably written", exception); - } - try { - requireArtifact( - staged, ArtifactKind.STAGE, operationId, shard, stageFileName, maximumBytes, null); - } catch (LocalPersistentPayloadException exception) { - cleanupFailedStage(shard, stageFileName, staged.fileKey(), exception); - throw exception; - } - verifyIdentity(); - reached(new FaultContext(FaultPoint.STAGE_FORCED, operationId, null, staged)); - return staged; - } - - Optional inspectStage( - String operationId, String stageFileName, long maximumBytes) { - requireOperationId(operationId); - requireExactStageFileName(operationId, stageFileName); - requirePositiveMaximum(maximumBytes); - String shard = operationShard(operationId); - verifyIdentity(); - requireTopDirectory(stagingDirectory, ".ca-fileserver/staging"); - return inspectExisting( - ArtifactKind.STAGE, stagingDirectory, shard, stageFileName, operationId, maximumBytes); - } - - Optional inspectData( - String fileId, String publishedFileName, long maximumBytes) { - requireFileId(fileId); - requireGeneratedSegment(publishedFileName, "publishedFileName"); - requirePositiveMaximum(maximumBytes); - verifyIdentity(); - requireTopDirectory(dataDirectory, "data"); - return inspectExisting( - ArtifactKind.DATA, - dataDirectory, - dataShard(fileId), - publishedFileName, - fileId, - maximumBytes); - } - - Optional inspectLegacyRootArtifact( - String publishedFileName, long maximumBytes) { - requireLegacySegment(publishedFileName); - requirePositiveMaximum(maximumBytes); - verifyIdentity(); - try { - VerifiedArtifact artifact = - access.inspect( - ArtifactKind.LEGACY_ROOT, - evidence.root(), - null, - publishedFileName, - publishedFileName, - maximumBytes); - if (artifact == null) { - return Optional.empty(); - } - requireArtifact( - artifact, - ArtifactKind.LEGACY_ROOT, - publishedFileName, - null, - publishedFileName, - maximumBytes, - null); - verifyIdentity(); - return Optional.of(artifact); - } catch (LocalPersistentPayloadException exception) { - throw exception; - } catch (IOException exception) { - throw failure(FailureKind.STORAGE, "legacy payload cannot be inspected", exception); - } - } - - VerifiedArtifact publishData( - VerifiedArtifact staged, String fileId, String publishedFileName, long maximumBytes) { - Objects.requireNonNull(staged, "staged artifact must be non-null"); - requireFileId(fileId); - requireGeneratedSegment(publishedFileName, "publishedFileName"); - requirePositiveMaximum(maximumBytes); - if (staged.kind() != ArtifactKind.STAGE) { - throw new IllegalArgumentException("staged artifact must have STAGE kind"); - } - verifyIdentity(); - requireTopDirectory(stagingDirectory, ".ca-fileserver/staging"); - requireTopDirectory(dataDirectory, "data"); - String dataShard = dataShard(fileId); - preparePrivateShard(dataDirectory, dataShard); - VerifiedArtifact currentStage = - inspectExisting( - ArtifactKind.STAGE, - stagingDirectory, - staged.shard(), - staged.fileName(), - staged.identity(), - maximumBytes) - .orElseThrow( - () -> failure(FailureKind.INTEGRITY, "sealed payload stage is missing", null)); - requireSameArtifact(staged, currentStage, "sealed payload stage identity changed"); - Path target = dataDirectory.resolve(dataShard).resolve(publishedFileName); - Path existing = stagingDirectory.resolve(staged.shard()).resolve(staged.fileName()); - boolean linked = false; - try { - verifyIdentity(); - requireShard(dataDirectory, dataShard); - requireShard(stagingDirectory, staged.shard()); - VerifiedArtifact immediatelyBeforeLink = - inspectExisting( - ArtifactKind.STAGE, - stagingDirectory, - staged.shard(), - staged.fileName(), - staged.identity(), - maximumBytes) - .orElseThrow( - () -> failure(FailureKind.INTEGRITY, "sealed payload stage is missing", null)); - requireSameArtifact(staged, immediatelyBeforeLink, "sealed payload stage identity changed"); - access.createHardLink(target, existing); - linked = true; - reached(new FaultContext(FaultPoint.DATA_LINKED, fileId, dataShard, null)); - verifyIdentity(); - requireShard(dataDirectory, dataShard); - VerifiedArtifact data = - inspectExisting( - ArtifactKind.DATA, - dataDirectory, - dataShard, - publishedFileName, - fileId, - maximumBytes) - .orElseThrow( - () -> - failure( - FailureKind.INDETERMINATE, - "linked payload data cannot be read back", - null)); - requireSameContentAndFileKey(staged, data, "published data differs from sealed stage"); - access.forceDirectory(dataDirectory.resolve(dataShard)); - verifyIdentity(); - requireShard(dataDirectory, dataShard); - reached(new FaultContext(FaultPoint.DATA_DIRECTORY_FORCED, fileId, dataShard, data)); - return data; - } catch (FileAlreadyExistsException exception) { - throw failure(FailureKind.CONFLICT, "payload target already exists", exception); - } catch (LocalPersistentPayloadException exception) { - throw exception; - } catch (IOException exception) { - throw failure( - linked ? FailureKind.INDETERMINATE : FailureKind.STORAGE, - "payload data publication failed", - exception); - } - } - - void forceDataDirectory(String fileId) { - requireFileId(fileId); - String shard = dataShard(fileId); - verifyIdentity(); - requireTopDirectory(dataDirectory, "data"); - requireShard(dataDirectory, shard); - try { - access.forceDirectory(dataDirectory.resolve(shard)); - verifyIdentity(); - requireShard(dataDirectory, shard); - reached(new FaultContext(FaultPoint.DATA_DIRECTORY_FORCED, fileId, shard, null)); - } catch (LocalPersistentPayloadException exception) { - throw exception; - } catch (IOException exception) { - throw failure(FailureKind.INDETERMINATE, "payload data directory force failed", exception); - } - } - - void deleteStageExact(VerifiedArtifact staged) { - Objects.requireNonNull(staged, "staged artifact must be non-null"); - if (staged.kind() != ArtifactKind.STAGE) { - throw new IllegalArgumentException("staged artifact must have STAGE kind"); - } - verifyIdentity(); - requireTopDirectory(stagingDirectory, ".ca-fileserver/staging"); - requireShard(stagingDirectory, staged.shard()); - try { - boolean deleted = - access.deleteExact(stagingDirectory, staged.shard(), staged.fileName(), staged); - if (!deleted) { - return; - } - access.forceDirectory(stagingDirectory.resolve(staged.shard())); - verifyIdentity(); - requireShard(stagingDirectory, staged.shard()); - reached( - new FaultContext(FaultPoint.STAGE_DELETED, staged.identity(), staged.shard(), staged)); - } catch (LocalPersistentPayloadException exception) { - throw exception; - } catch (IOException exception) { - throw failure(FailureKind.INDETERMINATE, "payload stage exact delete failed", exception); - } - } - - private Optional inspectExisting( - ArtifactKind kind, - Path topDirectory, - String shard, - String fileName, - String identity, - long maximumBytes) { - ShardAttributes shardAttributes = statShard(topDirectory, shard); - if (shardAttributes == null) { - return Optional.empty(); - } - requireShardAttributes(shardAttributes); - try { - VerifiedArtifact artifact = - access.inspect(kind, topDirectory, shard, fileName, identity, maximumBytes); - if (artifact == null) { - return Optional.empty(); - } - requireArtifact(artifact, kind, identity, shard, fileName, maximumBytes, shardAttributes); - verifyIdentity(); - return Optional.of(artifact); - } catch (LocalPersistentPayloadException exception) { - throw exception; - } catch (IOException exception) { - throw failure(FailureKind.STORAGE, "payload artifact cannot be inspected", exception); - } - } - - private void preparePrivateShard(Path topDirectory, String shard) { - ShardAttributes attributes = statShard(topDirectory, shard); - if (attributes == null) { - try { - attributes = access.createPrivateShard(topDirectory, shard); - access.forceDirectory(topDirectory); - } catch (FileAlreadyExistsException ignored) { - attributes = statShard(topDirectory, shard); - } catch (LocalPersistentPayloadException exception) { - throw exception; - } catch (IOException exception) { - throw failure(FailureKind.STORAGE, "private payload shard cannot be prepared", exception); - } - } - if (attributes == null) { - throw failure(FailureKind.INTEGRITY, "private payload shard disappeared", null); - } - requireShardAttributes(attributes); - requireTopDirectory( - topDirectory, topDirectory.equals(dataDirectory) ? "data" : ".ca-fileserver/staging"); - } - - private ShardAttributes statShard(Path topDirectory, String shard) { - try { - return access.statShard(topDirectory, shard); - } catch (LocalPersistentPayloadException exception) { - throw exception; - } catch (IOException exception) { - throw failure(FailureKind.STORAGE, "private payload shard cannot be inspected", exception); - } - } - - private void requireShard(Path topDirectory, String shard) { - ShardAttributes attributes = statShard(topDirectory, shard); - if (attributes == null) { - throw failure(FailureKind.INTEGRITY, "private payload shard is missing", null); - } - requireShardAttributes(attributes); - } - - private void requireShardAttributes(ShardAttributes attributes) { - if (!evidence.expectedOwner().equals(attributes.owner()) - || !PRIVATE_DIRECTORY_PERMISSIONS.equals(attributes.permissions()) - || !evidence.fileStoreName().equals(attributes.fileStoreName()) - || !evidence.fileStoreType().equals(attributes.fileStoreType()) - || attributes.fileKey() == null - || attributes.fileKey().isBlank()) { - throw failure(FailureKind.INTEGRITY, "private payload shard attestation failed", null); - } - } - - private void requireTopDirectory(Path directory, String evidenceKey) { - String expectedFileKey = evidence.criticalDirectoryFileKeys().get(evidenceKey); - if (expectedFileKey == null) { - throw failure(FailureKind.INTEGRITY, "payload top directory is not attested", null); - } - try { - PosixFileAttributes attributes = - Files.readAttributes(directory, PosixFileAttributes.class, LinkOption.NOFOLLOW_LINKS); - if (!attributes.isDirectory() - || attributes.isSymbolicLink() - || !expectedFileKey.equals(fileKey(attributes.fileKey())) - || !evidence.expectedOwner().equals(attributes.owner().getName()) - || !PRIVATE_DIRECTORY_PERMISSIONS.equals(attributes.permissions()) - || !evidence.fileStoreName().equals(access.fileStoreName(directory)) - || !evidence.fileStoreType().equals(access.fileStoreType(directory))) { - throw failure(FailureKind.INTEGRITY, "payload top directory attestation failed", null); - } - } catch (LocalPersistentPayloadException exception) { - throw exception; - } catch (IOException exception) { - throw failure( - FailureKind.INDETERMINATE, "payload top directory cannot be attested", exception); - } - } - - private void requireArtifact( - VerifiedArtifact artifact, - ArtifactKind kind, - String identity, - String shard, - String fileName, - long maximumBytes, - ShardAttributes shardAttributes) { - if (artifact.kind() != kind - || !identity.equals(artifact.identity()) - || !Objects.equals(shard, artifact.shard()) - || !fileName.equals(artifact.fileName()) - || artifact.byteSize() < 0 - || artifact.byteSize() > maximumBytes - || !artifact.sha256().matches("[0-9a-f]{64}") - || artifact.fileKey().isBlank() - || !evidence.expectedOwner().equals(artifact.owner()) - || !PRIVATE_FILE_PERMISSIONS.equals(artifact.permissions()) - || !evidence.fileStoreName().equals(artifact.fileStoreName()) - || !evidence.fileStoreType().equals(artifact.fileStoreType())) { - throw failure(FailureKind.INTEGRITY, "payload artifact attestation failed", null); - } - if (shardAttributes != null - && (!shardAttributes.fileStoreName().equals(artifact.fileStoreName()) - || !shardAttributes.fileStoreType().equals(artifact.fileStoreType()))) { - throw failure(FailureKind.INTEGRITY, "payload artifact FileStore mismatch", null); - } - } - - private static void requireSameArtifact( - VerifiedArtifact expected, VerifiedArtifact actual, String message) { - if (!expected.equals(actual)) { - throw failure(FailureKind.INTEGRITY, message, null); - } - } - - private static void requireSameContentAndFileKey( - VerifiedArtifact expected, VerifiedArtifact actual, String message) { - if (!expected.fileKey().equals(actual.fileKey()) - || expected.byteSize() != actual.byteSize() - || !expected.sha256().equals(actual.sha256())) { - throw failure(FailureKind.INTEGRITY, message, null); - } - } - - private void cleanupFailedStage( - String shard, String stageFileName, String createdFileKey, Throwable original) { - if (createdFileKey == null) { - return; - } - try { - access.cleanupCreatedStage(stagingDirectory, shard, stageFileName, createdFileKey, original); - } catch (Throwable cleanupFailure) { - if (cleanupFailure != original) { - original.addSuppressed(cleanupFailure); - } - } - } - - private void verifyIdentity() { - try { - identityVerifier.verify(); - } catch (LocalPersistentPayloadException exception) { - throw exception; - } catch (RuntimeException exception) { - throw failure( - FailureKind.INDETERMINATE, "persistent payload root identity changed", exception); - } - } - - private void reached(FaultContext context) { - faultCallback.reached(context); - } - - static PayloadAccess systemPayloadAccess() { - return SystemPayloadAccess.INSTANCE; - } - - private static String operationShard(String operationId) { - return sha256(operationId).substring(0, 2); - } - - private static String dataShard(String fileId) { - return fileId.substring(0, 2); - } - - private static void requireOperationId(String operationId) { - FileserverControlRecordCodec.requireText(operationId, "operationId", 128); - } - - private static void requireFileId(String fileId) { - if (fileId == null || !fileId.matches("[0-9a-f]{32}")) { - throw new IllegalArgumentException("fileId must be 32 lowercase hexadecimal characters"); - } - } - - private static void requireExactStageFileName(String operationId, String stageFileName) { - if (!stageFileName(operationId).equals(stageFileName)) { - throw new IllegalArgumentException("stageFileName must be derived from operationId"); - } - } - - private static void requireGeneratedSegment(String value, String field) { - FileserverControlRecordCodec.requireSegment(value, field); - } - - private static void requireLegacySegment(String value) { - if (value == null - || value.isBlank() - || ".".equals(value) - || "..".equals(value) - || value.indexOf('/') >= 0 - || value.indexOf('\\') >= 0 - || value.codePoints().anyMatch(codePoint -> Character.isISOControl(codePoint))) { - throw new IllegalArgumentException("legacy publishedFileName must be one safe segment"); - } - try { - int bytes = - StandardCharsets.UTF_8 - .newEncoder() - .onMalformedInput(CodingErrorAction.REPORT) - .onUnmappableCharacter(CodingErrorAction.REPORT) - .encode(CharBuffer.wrap(value)) - .remaining(); - if (bytes > 255) { - throw new IllegalArgumentException( - "legacy publishedFileName UTF-8 encoding exceeds 255 bytes"); - } - } catch (CharacterCodingException exception) { - throw new IllegalArgumentException("legacy publishedFileName must be valid UTF-8", exception); - } - } - - private static void requirePositiveMaximum(long maximumBytes) { - if (maximumBytes < 1) { - throw new IllegalArgumentException("maximumBytes must be positive"); - } - } - - private static String sha256(String value) { - return HEX.formatHex(sha256().digest(value.getBytes(StandardCharsets.UTF_8))); - } - - private static MessageDigest sha256() { - try { - return MessageDigest.getInstance("SHA-256"); - } catch (NoSuchAlgorithmException exception) { - throw new IllegalStateException("SHA-256 unavailable", exception); - } - } - - private static String fileKey(Object value) { - if (value == null || value.toString().isBlank()) { - throw failure(FailureKind.INTEGRITY, "payload filesystem has no stable file key", null); - } - return value.toString(); - } - - private static LocalPersistentPayloadException failure( - FailureKind kind, String message, Throwable cause) { - return cause == null - ? new LocalPersistentPayloadException(kind, message) - : new LocalPersistentPayloadException(kind, message, cause); - } - - private static void throwOriginal(Throwable original) { - if (original instanceof RuntimeException runtimeException) { - throw runtimeException; - } - if (original instanceof Error error) { - throw error; - } - throw failure(FailureKind.STORAGE, "payload writer failed", original); - } - - enum ArtifactKind { - STAGE, - DATA, - LEGACY_ROOT - } - - enum FailureKind { - CAPACITY, - CONFLICT, - INTEGRITY, - STORAGE, - INDETERMINATE - } - - enum FaultPoint { - STAGE_FORCED, - DATA_LINKED, - DATA_DIRECTORY_FORCED, - STAGE_DELETED - } - - record VerifiedArtifact( - ArtifactKind kind, - String identity, - String shard, - String fileName, - long byteSize, - String sha256, - String fileKey, - String owner, - Set permissions, - String fileStoreName, - String fileStoreType) { - - VerifiedArtifact { - Objects.requireNonNull(kind, "kind must be non-null"); - Objects.requireNonNull(identity, "identity must be non-null"); - Objects.requireNonNull(fileName, "fileName must be non-null"); - Objects.requireNonNull(sha256, "sha256 must be non-null"); - Objects.requireNonNull(fileKey, "fileKey must be non-null"); - Objects.requireNonNull(owner, "owner must be non-null"); - permissions = Set.copyOf(Objects.requireNonNull(permissions, "permissions must be non-null")); - Objects.requireNonNull(fileStoreName, "fileStoreName must be non-null"); - Objects.requireNonNull(fileStoreType, "fileStoreType must be non-null"); - } - } - - record ShardAttributes( - String fileKey, - String owner, - Set permissions, - String fileStoreName, - String fileStoreType) { - - ShardAttributes { - Objects.requireNonNull(fileKey, "fileKey must be non-null"); - Objects.requireNonNull(owner, "owner must be non-null"); - permissions = Set.copyOf(Objects.requireNonNull(permissions, "permissions must be non-null")); - Objects.requireNonNull(fileStoreName, "fileStoreName must be non-null"); - Objects.requireNonNull(fileStoreType, "fileStoreType must be non-null"); - } - } - - record FaultContext(FaultPoint point, String identity, String shard, VerifiedArtifact artifact) { - - FaultContext { - Objects.requireNonNull(point, "point must be non-null"); - Objects.requireNonNull(identity, "identity must be non-null"); - } - } - - @FunctionalInterface - interface PayloadWriter { - void write(OutputStream output) throws IOException; - } - - @FunctionalInterface - interface IdentityVerifier { - void verify(); - } - - @FunctionalInterface - interface FaultCallback { - void reached(FaultContext context); - } - - interface PayloadAccess { - - ShardAttributes statShard(Path topDirectory, String shard) throws IOException; - - ShardAttributes createPrivateShard(Path topDirectory, String shard) throws IOException; - - String fileStoreName(Path path) throws IOException; - - String fileStoreType(Path path) throws IOException; - - VerifiedArtifact createStageAndForce( - Path topDirectory, - String shard, - String fileName, - String operationId, - long maximumBytes, - PayloadWriter writer) - throws IOException; - - VerifiedArtifact inspect( - ArtifactKind kind, - Path topDirectory, - String shard, - String fileName, - String identity, - long maximumBytes) - throws IOException; - - void createHardLink(Path link, Path existing) throws IOException; - - void forceDirectory(Path directory) throws IOException; - - void cleanupCreatedStage( - Path topDirectory, - String shard, - String fileName, - String expectedFileKey, - Throwable originalFailure) - throws IOException; - - boolean deleteExact(Path topDirectory, String shard, String fileName, VerifiedArtifact expected) - throws IOException; - } - - static final class LocalPersistentPayloadException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - private final FailureKind kind; - - LocalPersistentPayloadException(FailureKind kind, String message) { - super(message); - this.kind = Objects.requireNonNull(kind, "kind must be non-null"); - } - - LocalPersistentPayloadException(FailureKind kind, String message, Throwable cause) { - super(message, cause); - this.kind = Objects.requireNonNull(kind, "kind must be non-null"); - } - - FailureKind kind() { - return kind; - } - } - - private static final class StageWriteFailureException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - private final Throwable original; - private final String createdFileKey; - - private StageWriteFailureException(Throwable original, String createdFileKey) { - super(null, null, false, false); - this.original = Objects.requireNonNull(original, "original must be non-null"); - this.createdFileKey = createdFileKey; - } - - private Throwable original() { - return original; - } - - private String createdFileKey() { - return createdFileKey; - } - } - - private enum SystemPayloadAccess implements PayloadAccess { - INSTANCE; - - @Override - public ShardAttributes statShard(Path topDirectory, String shard) throws IOException { - Path shardPath = topDirectory.resolve(shard); - PosixFileAttributes attributes; - try { - attributes = - Files.readAttributes(shardPath, PosixFileAttributes.class, LinkOption.NOFOLLOW_LINKS); - } catch (NoSuchFileException ignored) { - return null; - } - if (!attributes.isDirectory() || attributes.isSymbolicLink()) { - throw failure(FailureKind.INTEGRITY, "payload shard is not a no-follow directory", null); - } - return shardAttributes(shardPath, attributes); - } - - @Override - public ShardAttributes createPrivateShard(Path topDirectory, String shard) throws IOException { - Path shardPath = - Files.createDirectory( - topDirectory.resolve(shard), - PosixFilePermissions.asFileAttribute(PRIVATE_DIRECTORY_PERMISSIONS)); - Files.setPosixFilePermissions(shardPath, PRIVATE_DIRECTORY_PERMISSIONS); - PosixFileAttributes attributes = - Files.readAttributes(shardPath, PosixFileAttributes.class, LinkOption.NOFOLLOW_LINKS); - return shardAttributes(shardPath, attributes); - } - - @Override - public String fileStoreName(Path path) throws IOException { - return Files.getFileStore(path).name(); - } - - @Override - public String fileStoreType(Path path) throws IOException { - return Files.getFileStore(path).type(); - } - - @Override - public VerifiedArtifact createStageAndForce( - Path topDirectory, - String shard, - String fileName, - String operationId, - long maximumBytes, - PayloadWriter writer) - throws IOException { - String createdFileKey = null; - try (SecureDirectoryStream shardStream = openSecureDirectory(topDirectory, shard); - SeekableByteChannel channel = - shardStream.newByteChannel( - Path.of(fileName), - CREATE_STAGE_OPTIONS, - PosixFilePermissions.asFileAttribute(PRIVATE_FILE_PERMISSIONS))) { - PosixFileAttributes created = readPosix(shardStream, fileName); - requireRegular(created); - createdFileKey = fileKey(created.fileKey()); - if (!(channel instanceof FileChannel fileChannel)) { - throw new IOException("payload filesystem does not expose a force-capable file channel"); - } - OutputStream output = - new NonClosingBoundedOutputStream(Channels.newOutputStream(fileChannel), maximumBytes); - writer.write(output); - output.flush(); - fileChannel.force(true); - } catch (FileAlreadyExistsException exception) { - throw exception; - } catch (Throwable original) { - throw new StageWriteFailureException(original, createdFileKey); - } - try { - VerifiedArtifact artifact = - inspect(ArtifactKind.STAGE, topDirectory, shard, fileName, operationId, maximumBytes); - if (artifact == null) { - throw new IOException("forced payload stage disappeared"); - } - if (!artifact.fileKey().equals(createdFileKey)) { - throw failure(FailureKind.INTEGRITY, "forced payload stage identity changed", null); - } - return artifact; - } catch (Throwable original) { - throw new StageWriteFailureException(original, createdFileKey); - } - } - - @Override - public VerifiedArtifact inspect( - ArtifactKind kind, - Path topDirectory, - String shard, - String fileName, - String identity, - long maximumBytes) - throws IOException { - try (SecureDirectoryStream directory = openSecureDirectory(topDirectory, shard)) { - PosixFileAttributes before; - try { - before = readPosix(directory, fileName); - } catch (NoSuchFileException ignored) { - return null; - } - requireRegular(before); - if (before.size() > maximumBytes) { - throw failure(FailureKind.CAPACITY, "payload artifact exceeds configured bound", null); - } - MessageDigest digest = sha256(); - long bytesRead = 0; - try (SeekableByteChannel channel = - directory.newByteChannel(Path.of(fileName), READ_OPTIONS)) { - ByteBuffer buffer = ByteBuffer.allocate(8192); - while (true) { - int read = channel.read(buffer); - if (read < 0) { - break; - } - if (read == 0) { - continue; - } - if (bytesRead > maximumBytes - read) { - throw failure( - FailureKind.CAPACITY, "payload artifact exceeds configured bound", null); - } - bytesRead += read; - buffer.flip(); - digest.update(buffer); - buffer.clear(); - } - } - PosixFileAttributes after = readPosix(directory, fileName); - requireRegular(after); - String beforeFileKey = fileKey(before.fileKey()); - if (!beforeFileKey.equals(fileKey(after.fileKey())) - || before.size() != after.size() - || before.size() != bytesRead - || !before.lastModifiedTime().equals(after.lastModifiedTime())) { - throw failure(FailureKind.INTEGRITY, "payload artifact changed during inspection", null); - } - Path artifactPath = - shard == null - ? topDirectory.resolve(fileName) - : topDirectory.resolve(shard).resolve(fileName); - return new VerifiedArtifact( - kind, - identity, - shard, - fileName, - bytesRead, - HEX.formatHex(digest.digest()), - beforeFileKey, - after.owner().getName(), - after.permissions(), - Files.getFileStore(artifactPath).name(), - Files.getFileStore(artifactPath).type()); - } - } - - @Override - public void createHardLink(Path link, Path existing) throws IOException { - Files.createLink(link, existing); - } - - @Override - public void forceDirectory(Path directory) throws IOException { - try (FileChannel channel = FileChannel.open(directory, StandardOpenOption.READ)) { - channel.force(true); - } - } - - @Override - public void cleanupCreatedStage( - Path topDirectory, - String shard, - String fileName, - String expectedFileKey, - Throwable originalFailure) - throws IOException { - try (SecureDirectoryStream directory = openSecureDirectory(topDirectory, shard)) { - PosixFileAttributes attributes; - try { - attributes = readPosix(directory, fileName); - } catch (NoSuchFileException ignored) { - return; - } - requireRegular(attributes); - if (!expectedFileKey.equals(fileKey(attributes.fileKey()))) { - throw failure( - FailureKind.INTEGRITY, "refusing cleanup of a replaced payload stage", null); - } - directory.deleteFile(Path.of(fileName)); - } - forceDirectory(topDirectory.resolve(shard)); - } - - @Override - public boolean deleteExact( - Path topDirectory, String shard, String fileName, VerifiedArtifact expected) - throws IOException { - try (SecureDirectoryStream directory = openSecureDirectory(topDirectory, shard)) { - PosixFileAttributes attributes; - try { - attributes = readPosix(directory, fileName); - } catch (NoSuchFileException ignored) { - return false; - } - requireRegular(attributes); - if (!expected.fileKey().equals(fileKey(attributes.fileKey())) - || expected.byteSize() != attributes.size()) { - throw failure(FailureKind.INTEGRITY, "refusing delete of a replaced payload stage", null); - } - directory.deleteFile(Path.of(fileName)); - return true; - } - } - - private static ShardAttributes shardAttributes(Path path, PosixFileAttributes attributes) - throws IOException { - return new ShardAttributes( - fileKey(attributes.fileKey()), - attributes.owner().getName(), - attributes.permissions(), - Files.getFileStore(path).name(), - Files.getFileStore(path).type()); - } - - // "resource" is for the Eclipse compiler, "StreamResourceLeak" for ErrorProne: both see an - // open stream leaving the method and neither can see that ownership goes to the caller, which - // closes it. Every failure path below closes what it opened before rethrowing. - @SuppressWarnings({"StreamResourceLeak", "resource"}) - private static SecureDirectoryStream openSecureDirectory(Path topDirectory, String shard) - throws IOException { - DirectoryStream top = Files.newDirectoryStream(topDirectory); - if (!(top instanceof SecureDirectoryStream secureTop)) { - top.close(); - throw failure( - FailureKind.INTEGRITY, "SecureDirectoryStream is unavailable for payload root", null); - } - if (shard == null) { - return secureTop; - } - SecureDirectoryStream child; - try { - child = secureTop.newDirectoryStream(Path.of(shard), LinkOption.NOFOLLOW_LINKS); - } catch (IOException | RuntimeException | Error openFailure) { - try { - secureTop.close(); - } catch (IOException | RuntimeException | Error closeFailure) { - openFailure.addSuppressed(closeFailure); - } - throw openFailure; - } - try { - secureTop.close(); - return child; - } catch (IOException | RuntimeException | Error closeFailure) { - try { - child.close(); - } catch (IOException | RuntimeException | Error childCloseFailure) { - closeFailure.addSuppressed(childCloseFailure); - } - throw closeFailure; - } - } - - private static PosixFileAttributes readPosix( - SecureDirectoryStream directory, String fileName) throws IOException { - PosixFileAttributeView view = - directory.getFileAttributeView( - Path.of(fileName), PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS); - if (view == null) { - throw failure(FailureKind.INTEGRITY, "POSIX payload attributes are unavailable", null); - } - return view.readAttributes(); - } - - private static void requireRegular(PosixFileAttributes attributes) { - if (!attributes.isRegularFile() || attributes.isSymbolicLink()) { - throw failure( - FailureKind.INTEGRITY, "payload artifact is not a no-follow regular file", null); - } - } - } - - private static final class NonClosingBoundedOutputStream extends FilterOutputStream { - - private final long maximumBytes; - private long written; - - private NonClosingBoundedOutputStream(OutputStream delegate, long maximumBytes) { - super(delegate); - this.maximumBytes = maximumBytes; - } - - @Override - public void write(int value) throws IOException { - requireCapacity(1); - out.write(value); - written++; - } - - @Override - public void write(byte[] bytes, int offset, int length) throws IOException { - Objects.checkFromIndexSize(offset, length, bytes.length); - requireCapacity(length); - out.write(bytes, offset, length); - written += length; - } - - @Override - public void close() throws IOException { - flush(); - } - - private void requireCapacity(int nextBytes) { - if (written > maximumBytes - nextBytes) { - throw failure(FailureKind.CAPACITY, "payload byte limit exceeded", null); - } - } - } -} diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/LocalPersistentPublicationProvider.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/LocalPersistentPublicationProvider.java deleted file mode 100644 index c0ab0883..00000000 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/LocalPersistentPublicationProvider.java +++ /dev/null @@ -1,896 +0,0 @@ -package dev.caskeleton.adapter.outbound.fileserver; - -import dev.caskeleton.application.filepublication.FileDestinationId; -import dev.caskeleton.application.filepublication.FilePublicationException; -import dev.caskeleton.application.filepublication.FilePublishOperationId; -import dev.caskeleton.application.filepublication.FilePublishReceipt; -import dev.caskeleton.application.filepublication.FilePublishReceipt.DurabilityGuarantee; -import dev.caskeleton.application.filepublication.FilePublishReceipt.PublicationGuarantee; -import dev.caskeleton.application.filepublication.FilePublishRequest; -import dev.caskeleton.application.filepublication.FileVersion; -import dev.caskeleton.application.filepublication.PublishedFileReference; -import dev.caskeleton.application.filepublication.TabularRowProducer; -import dev.caskeleton.application.filepublication.TabularRowSink; -import java.io.OutputStream; -import java.nio.charset.StandardCharsets; -import java.nio.file.Path; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.time.Clock; -import java.time.Instant; -import java.util.HexFormat; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -/** Qualified local-persistent R2 provider with direct operation recovery. */ -final class LocalPersistentPublicationProvider implements FilePublicationProvider { - - private static final String FORMAT_PROFILE = "csv-rfc4180-v1"; - private static final String MEDIA_TYPE = "text/csv"; - private static final String CHARSET = StandardCharsets.UTF_8.name(); - private static final HexFormat HEX = HexFormat.of(); - - private final Map runtimes; - private final Clock clock; - private final FileIdGenerator fileIds; - private final FileserverControlRecordCodec codec; - private final LocalPersistentRecoveryVerifier verifier; - - LocalPersistentPublicationProvider( - Map runtimes, Clock clock, FileIdGenerator fileIds) { - this( - runtimes, - clock, - fileIds, - new FileserverControlRecordCodec(), - new LocalPersistentRecoveryVerifier()); - } - - LocalPersistentPublicationProvider( - Map runtimes, - Clock clock, - FileIdGenerator fileIds, - FileserverControlRecordCodec codec, - LocalPersistentRecoveryVerifier verifier) { - this.runtimes = Map.copyOf(Objects.requireNonNull(runtimes, "runtimes must be non-null")); - if (this.runtimes.isEmpty()) { - throw new IllegalArgumentException("local-persistent provider requires a destination"); - } - String providerId = null; - Path providerRoot = null; - LocalPersistentControlPlane sharedControlPlane = null; - LocalPersistentPayloadOperations sharedPayload = null; - for (Map.Entry entry : this.runtimes.entrySet()) { - FileDestinationId destinationId = - Objects.requireNonNull(entry.getKey(), "destinationId must be non-null"); - DestinationRuntime runtime = - Objects.requireNonNull(entry.getValue(), "destination runtime must be non-null"); - if (!destinationId.equals(runtime.destination().destinationId())) { - throw new IllegalArgumentException("destination runtime key does not match descriptor"); - } - if (!runtime.destination().rootDirectory().equals(runtime.controlPlane().root()) - || !runtime.destination().rootDirectory().equals(runtime.payload().root())) { - throw new IllegalArgumentException( - "destination descriptor and runtime root must be identical"); - } - if (providerId == null) { - providerId = runtime.destination().providerId(); - providerRoot = runtime.destination().rootDirectory(); - sharedControlPlane = runtime.controlPlane(); - sharedPayload = runtime.payload(); - } else if (!providerId.equals(runtime.destination().providerId()) - || !providerRoot.equals(runtime.destination().rootDirectory()) - || sharedControlPlane != runtime.controlPlane() - || sharedPayload != runtime.payload()) { - throw new IllegalArgumentException( - "one provider instance requires one provider ID, root, and shared runtime"); - } - } - this.clock = Objects.requireNonNull(clock, "clock must be non-null"); - this.fileIds = Objects.requireNonNull(fileIds, "fileIds must be non-null"); - this.codec = Objects.requireNonNull(codec, "codec must be non-null"); - this.verifier = Objects.requireNonNull(verifier, "verifier must be non-null"); - } - - @Override - public FilePublishReceipt publish(FilePublishRequest request, TabularRowProducer producer) { - DestinationRuntime runtime = validateAndSelect(request, producer); - String requestFingerprint; - try { - requestFingerprint = FilePublishRequestFingerprint.calculate(request); - } catch (IllegalArgumentException exception) { - throw invalidRequest("file publication request is not canonical UTF-8", exception); - } - LocalPersistentControlPlane controlPlane = runtime.controlPlane(); - try (LocalPersistentControlPlane.OperationLock ignored = - controlPlane.acquireOperationLock(request.operationId().value())) { - Optional existing = - controlPlane.findStoredOperation(request.operationId().value()); - if (existing.isPresent()) { - return recoverStored(runtime, request, requestFingerprint, existing.orElseThrow()); - } - return publishNew(runtime, request, requestFingerprint, producer); - } catch (FilePublicationException exception) { - throw exception; - } catch (LocalPersistentControlPlane.LocalPersistentControlPlaneException exception) { - throw mapControlFailure(exception); - } catch (LocalPersistentPayloadOperations.LocalPersistentPayloadException exception) { - throw mapPayloadFailure(exception); - } - } - - private DestinationRuntime validateAndSelect( - FilePublishRequest request, TabularRowProducer producer) { - if (request == null) { - throw invalidRequest("file publication request must be non-null", null); - } - if (producer == null) { - throw invalidRequest("file publication producer must be non-null", null); - } - DestinationRuntime runtime = runtimes.get(request.destinationId()); - if (runtime == null) { - throw invalidRequest("file publication destination is not configured", null); - } - if (!FORMAT_PROFILE.equals(request.formatProfileId())) { - throw invalidRequest("file publication format profile is not supported", null); - } - try { - FilePublicationCanonicalDigests.schemaDigest(request.schema()); - } catch (IllegalArgumentException exception) { - throw invalidRequest("file publication schema is not canonical UTF-8", exception); - } - return runtime; - } - - private FilePublishReceipt publishNew( - DestinationRuntime runtime, - FilePublishRequest request, - String requestFingerprint, - TabularRowProducer producer) { - String fileId = fileIds.nextFileId(); - FileserverControlRecordCodec.requireFileId(fileId); - String publishedFileName = LocalPersistentRecoveryVerifier.generatedFileName(fileId); - String stageFileName = - LocalPersistentPayloadOperations.stageFileName(request.operationId().value()); - CompiledFileDestination destination = runtime.destination(); - DurablePublicationRecord writing = - new DurablePublicationRecord( - DurablePublicationRecord.CURRENT_SCHEMA_VERSION, - 1, - DurablePublicationRecord.State.WRITING, - request.operationId().value(), - requestFingerprint, - destination.effectivePolicyRevision(), - destination.effectivePolicyDigest(), - destination.destinationId().value(), - destination.providerId(), - fileId, - destination.routeToken(), - publishedFileName, - stageFileName, - 0, - 0, - 0, - "", - 0, - "", - "", - clock.instant(), - null, - null, - "", - ""); - runtime.controlPlane().storeOperation(writing); - - StreamingCsvEncoder.Stats[] stats = new StreamingCsvEncoder.Stats[1]; - LocalPersistentPayloadOperations.VerifiedArtifact staged = null; - try { - staged = - runtime - .payload() - .stage( - writing.operationId(), - writing.stageFileName(), - destination.maximumEncodedBytes(), - output -> - stats[0] = - streamRequest( - request, - producer, - output, - destination.maximumRows(), - destination.maximumEncodedBytes())); - if (stats[0] == null - || stats[0].byteSize() != staged.byteSize() - || !stats[0].sha256().equals(staged.sha256())) { - throw new IllegalStateException("streaming encoder statistics do not match staged bytes"); - } - } catch (Throwable original) { - if (staged != null) { - try { - runtime.payload().deleteStageExact(staged); - } catch (Throwable cleanupFailure) { - if (cleanupFailure != original) { - original.addSuppressed(cleanupFailure); - } - } - } - quarantinePreservingOriginal(runtime.controlPlane(), writing, "STAGE_FAILED", original); - throwOriginal(original); - throw new AssertionError("unreachable"); - } - - DurablePublicationRecord sealed = - transition( - writing, - DurablePublicationRecord.State.SEALED, - staged.byteSize(), - stats[0].rowCount(), - request.schema().columns().size(), - staged.sha256(), - stats[0].formulaMitigatedCount(), - "", - "", - clock.instant(), - null, - "", - ""); - runtime.controlPlane().storeOperation(sealed); - return recoverR2(runtime, request, requestFingerprint, sealed); - } - - private static StreamingCsvEncoder.Stats streamRequest( - FilePublishRequest request, - TabularRowProducer producer, - OutputStream output, - long maximumRows, - long maximumEncodedBytes) { - StreamingCsvEncoder encoder = - new StreamingCsvEncoder( - request.schema(), output, sha256(), maximumRows, maximumEncodedBytes); - encoder.writeHeader(); - TabularRowSink sink = - new TabularRowSink() { - @Override - public void write(dev.caskeleton.application.filepublication.TabularRow row) { - encoder.write(row); - } - - @Override - public void checkpoint() { - encoder.checkpoint(); - } - }; - producer.produce(sink); - encoder.checkpoint(); - return encoder.finish(); - } - - private FilePublishReceipt recoverStored( - DestinationRuntime runtime, - FilePublishRequest request, - String requestFingerprint, - LocalPersistentControlPlane.StoredOperationRecord stored) { - if (stored instanceof LocalPersistentControlPlane.R1StoredOperationRecord r1) { - return restoreR1(runtime, request, requestFingerprint, r1.record()); - } - if (stored instanceof LocalPersistentControlPlane.R2StoredOperationRecord r2) { - return recoverR2(runtime, request, requestFingerprint, r2.record()); - } - throw new IllegalStateException("unsupported stored operation record"); - } - - private FilePublishReceipt restoreR1( - DestinationRuntime runtime, - FilePublishRequest request, - String requestFingerprint, - LocalPublicationJournalRecord record) { - if (!record.requestFingerprint().equals(requestFingerprint)) { - throw conflict("operation ID was already used for a different request", null); - } - LocalPersistentPayloadOperations.VerifiedArtifact artifact = - runtime - .payload() - .inspectLegacyRootArtifact(record.publishedFileName(), exactBound(record.byteSize())) - .orElseThrow(() -> indeterminate("legacy publication artifact is unavailable", null)); - if (artifact.byteSize() != record.byteSize() || !artifact.sha256().equals(record.sha256())) { - throw indeterminate("legacy publication artifact does not match its journal", null); - } - PublicationGuarantee publicationGuarantee; - try { - publicationGuarantee = PublicationGuarantee.valueOf(record.publicationGuarantee()); - } catch (IllegalArgumentException exception) { - throw indeterminate("legacy publication guarantee is unsupported", exception); - } - String operationToken = sha256Hex(record.operationId()).substring(0, 24); - return new FilePublishReceipt( - new FilePublishOperationId(record.operationId()), - new PublishedFileReference( - "filepub:" + request.destinationId().value() + ":" + operationToken), - request.destinationId(), - record.publishedFileName(), - new FileVersion(record.sha256()), - request.formatProfileId(), - MEDIA_TYPE, - CHARSET, - record.byteSize(), - record.rowCount(), - record.columnCount(), - record.sha256(), - Instant.parse(record.publishedAt()), - publicationGuarantee, - DurabilityGuarantee.PROCESS_LOCAL_SYNC, - record.formulaMitigatedCount()); - } - - private FilePublishReceipt recoverR2( - DestinationRuntime runtime, - FilePublishRequest request, - String requestFingerprint, - DurablePublicationRecord startingOperation) { - DurablePublicationRecord operation = startingOperation; - if (!operation.requestFingerprint().equals(requestFingerprint)) { - throw conflict("operation ID was already used for a different request", null); - } - try { - verifier.requireOperationMatches( - operation, request, runtime.destination(), requestFingerprint); - } catch (IllegalArgumentException exception) { - throw indeterminate("durable operation policy or identity does not match", exception); - } - - while (true) { - try { - switch (operation.state()) { - case WRITING -> { - throw quarantineAndIndeterminate( - runtime.controlPlane(), - operation, - "UNSEALED_WRITING", - "publication was interrupted before payload sealing", - null); - } - case QUARANTINED -> throw indeterminate("publication is quarantined", null); - case SEALED -> operation = resumeData(runtime, operation); - case DATA_PUBLISHED -> operation = resumeManifest(runtime, request, operation); - case MANIFEST_PUBLISHED -> operation = resumeReference(runtime, request, operation); - case REFERENCE_PUBLISHED -> operation = completeTerminal(runtime, request, operation); - case PUBLISHED -> { - return restoreTerminal(runtime, request, operation); - } - default -> throw new IllegalStateException("unsupported durable publication state"); - } - } catch (RecoveryIntegrityException exception) { - throw quarantineAndIndeterminate( - runtime.controlPlane(), - operation, - "RECOVERY_INTEGRITY", - "publication recovery evidence is inconsistent", - exception); - } catch (LocalPersistentPayloadOperations.LocalPersistentPayloadException exception) { - if (exception.kind() == LocalPersistentPayloadOperations.FailureKind.INTEGRITY - || exception.kind() == LocalPersistentPayloadOperations.FailureKind.CAPACITY) { - throw quarantineAndIndeterminate( - runtime.controlPlane(), - operation, - "PAYLOAD_INTEGRITY", - "publication payload evidence is inconsistent", - exception); - } - throw indeterminate("publication payload recovery is indeterminate", exception); - } - } - } - - private DurablePublicationRecord resumeData( - DestinationRuntime runtime, DurablePublicationRecord operation) { - long bound = exactBound(operation.byteSize()); - Optional stage = - runtime.payload().inspectStage(operation.operationId(), operation.stageFileName(), bound); - Optional data = - runtime.payload().inspectData(operation.fileId(), operation.publishedFileName(), bound); - stage.ifPresent(artifact -> requireArtifact(operation, artifact)); - data.ifPresent(artifact -> requireArtifact(operation, artifact)); - if (stage.isEmpty() && data.isEmpty()) { - throw new RecoveryIntegrityException("sealed payload has no recoverable artifact"); - } - - LocalPersistentPayloadOperations.VerifiedArtifact published; - if (data.isPresent()) { - published = data.orElseThrow(); - if (stage.isPresent() && !stage.orElseThrow().fileKey().equals(published.fileKey())) { - throw new RecoveryIntegrityException("stage and data are not the same exclusive hard-link"); - } - runtime.payload().forceDataDirectory(operation.fileId()); - } else { - published = - runtime - .payload() - .publishData( - stage.orElseThrow(), operation.fileId(), operation.publishedFileName(), bound); - requireArtifact(operation, published); - } - DurablePublicationRecord advanced = - transition( - operation, - DurablePublicationRecord.State.DATA_PUBLISHED, - operation.byteSize(), - operation.rowCount(), - operation.columnCount(), - operation.sha256(), - operation.formulaMitigatedCount(), - "", - "", - operation.sealedAt(), - null, - "", - ""); - runtime.controlPlane().storeOperation(advanced); - if (stage.isPresent()) { - runtime.payload().deleteStageExact(stage.orElseThrow()); - } - return advanced; - } - - private DurablePublicationRecord resumeManifest( - DestinationRuntime runtime, FilePublishRequest request, DurablePublicationRecord operation) { - LocalPersistentPayloadOperations.VerifiedArtifact data = - requireMatchingData(runtime, operation); - cleanupResidualStage(runtime, operation, data); - PublishedFileReference opaqueReference = verifier.reference(operation); - Optional existing = - runtime.controlPlane().findManifest(operation.fileId()); - PrivateFileManifest manifest; - if (existing.isPresent()) { - manifest = existing.orElseThrow(); - requireManifest(runtime, request, operation, manifest, opaqueReference); - } else { - manifest = - new PrivateFileManifest( - PrivateFileManifest.CURRENT_SCHEMA_VERSION, - operation.operationId(), - operation.fileId(), - operation.providerId(), - opaqueReference.value(), - operation.requestFingerprint(), - operation.destinationId(), - request.schema().schemaId(), - request.schema().version(), - FilePublicationCanonicalDigests.schemaDigest(request.schema()), - request.formatProfileId(), - runtime.destination().formatPolicyDigest(), - operation.effectivePolicyRevision(), - operation.effectivePolicyDigest(), - operation.publishedFileName(), - operation.sha256(), - MEDIA_TYPE, - CHARSET, - operation.byteSize(), - operation.rowCount(), - operation.columnCount(), - operation.sha256(), - operation.formulaMitigatedCount(), - PublicationGuarantee.UNIQUE_ATOMIC_CREATE, - DurabilityGuarantee.FILE_AND_DIRECTORY_SYNC, - operation.publishedFileName(), - operation.createdAt(), - clock.instant()); - } - runtime.controlPlane().storeManifest(manifest); - String manifestDigest = verifier.canonicalManifestDigest(manifest); - DurablePublicationRecord advanced = - transition( - operation, - DurablePublicationRecord.State.MANIFEST_PUBLISHED, - operation.byteSize(), - operation.rowCount(), - operation.columnCount(), - operation.sha256(), - operation.formulaMitigatedCount(), - manifestDigest, - "", - operation.sealedAt(), - null, - "", - ""); - runtime.controlPlane().storeOperation(advanced); - return advanced; - } - - private DurablePublicationRecord resumeReference( - DestinationRuntime runtime, FilePublishRequest request, DurablePublicationRecord operation) { - LocalPersistentPayloadOperations.VerifiedArtifact data = - requireMatchingData(runtime, operation); - cleanupResidualStage(runtime, operation, data); - PrivateFileManifest manifest = - runtime - .controlPlane() - .findManifest(operation.fileId()) - .orElseThrow(() -> new RecoveryIntegrityException("published manifest is missing")); - PublishedFileReference opaqueReference = verifier.reference(operation); - requireManifest(runtime, request, operation, manifest, opaqueReference); - String manifestDigest = verifier.canonicalManifestDigest(manifest); - if (!manifestDigest.equals(operation.manifestDigest())) { - throw new RecoveryIntegrityException("operation manifest digest does not match"); - } - Optional existing = - runtime.controlPlane().findReference(operation.fileId()); - PublishedReferenceRecord reference; - if (existing.isPresent()) { - reference = existing.orElseThrow(); - requireReference(operation, manifest, reference, opaqueReference, manifestDigest); - } else { - reference = - new PublishedReferenceRecord( - PublishedReferenceRecord.CURRENT_SCHEMA_VERSION, - operation.fileId(), - operation.routeToken(), - opaqueReference.value(), - operation.operationId(), - operation.sha256(), - manifestDigest, - operation.publishedFileName(), - operation.destinationId(), - operation.providerId(), - operation.publishedFileName(), - MEDIA_TYPE, - CHARSET, - operation.byteSize(), - operation.sha256(), - manifest.publishedAt()); - } - runtime.controlPlane().storeReference(reference); - String referenceDigest = verifier.canonicalReferenceDigest(reference); - DurablePublicationRecord advanced = - transition( - operation, - DurablePublicationRecord.State.REFERENCE_PUBLISHED, - operation.byteSize(), - operation.rowCount(), - operation.columnCount(), - operation.sha256(), - operation.formulaMitigatedCount(), - manifestDigest, - referenceDigest, - operation.sealedAt(), - null, - "", - ""); - runtime.controlPlane().storeOperation(advanced); - return advanced; - } - - private DurablePublicationRecord completeTerminal( - DestinationRuntime runtime, FilePublishRequest request, DurablePublicationRecord operation) { - LocalPersistentPayloadOperations.VerifiedArtifact data = - requireMatchingData(runtime, operation); - cleanupResidualStage(runtime, operation, data); - PrivateFileManifest manifest = - runtime - .controlPlane() - .findManifest(operation.fileId()) - .orElseThrow(() -> new RecoveryIntegrityException("published manifest is missing")); - PublishedReferenceRecord reference = - runtime - .controlPlane() - .findReference(operation.fileId()) - .orElseThrow(() -> new RecoveryIntegrityException("published reference is missing")); - PublishedFileReference opaqueReference = verifier.reference(operation); - requireManifest(runtime, request, operation, manifest, opaqueReference); - String manifestDigest = verifier.canonicalManifestDigest(manifest); - requireReference(operation, manifest, reference, opaqueReference, manifestDigest); - String referenceDigest = verifier.canonicalReferenceDigest(reference); - if (!operation.manifestDigest().equals(manifestDigest) - || !operation.referenceDigest().equals(referenceDigest)) { - throw new RecoveryIntegrityException("operation metadata digest does not match"); - } - FilePublishReceipt receipt = - verifier.expectedReceipt(operation, request, manifest, opaqueReference); - DurablePublicationRecord terminal = - transition( - operation, - DurablePublicationRecord.State.PUBLISHED, - operation.byteSize(), - operation.rowCount(), - operation.columnCount(), - operation.sha256(), - operation.formulaMitigatedCount(), - manifestDigest, - referenceDigest, - operation.sealedAt(), - manifest.publishedAt(), - "", - codec.encodeReceiptSnapshot(receipt)); - runtime.controlPlane().storeOperation(terminal); - return terminal; - } - - private FilePublishReceipt restoreTerminal( - DestinationRuntime runtime, FilePublishRequest request, DurablePublicationRecord operation) { - try { - requireMatchingData(runtime, operation); - PrivateFileManifest manifest = - runtime - .controlPlane() - .findManifest(operation.fileId()) - .orElseThrow(() -> new RecoveryIntegrityException("terminal manifest is missing")); - PublishedReferenceRecord reference = - runtime - .controlPlane() - .findReference(operation.fileId()) - .orElseThrow(() -> new RecoveryIntegrityException("terminal reference is missing")); - PublishedFileReference opaqueReference = verifier.reference(operation); - requireManifest(runtime, request, operation, manifest, opaqueReference); - String manifestDigest = verifier.canonicalManifestDigest(manifest); - requireReference(operation, manifest, reference, opaqueReference, manifestDigest); - return verifier.requireTerminalReceipt(operation, request, manifest, reference); - } catch (IllegalArgumentException | RecoveryIntegrityException exception) { - throw indeterminate("terminal publication evidence does not match", exception); - } - } - - private LocalPersistentPayloadOperations.VerifiedArtifact requireMatchingData( - DestinationRuntime runtime, DurablePublicationRecord operation) { - LocalPersistentPayloadOperations.VerifiedArtifact data = - runtime - .payload() - .inspectData( - operation.fileId(), operation.publishedFileName(), exactBound(operation.byteSize())) - .orElseThrow(() -> new RecoveryIntegrityException("published data is missing")); - requireArtifact(operation, data); - return data; - } - - private void cleanupResidualStage( - DestinationRuntime runtime, - DurablePublicationRecord operation, - LocalPersistentPayloadOperations.VerifiedArtifact data) { - Optional residual = - runtime - .payload() - .inspectStage( - operation.operationId(), - operation.stageFileName(), - exactBound(operation.byteSize())); - if (residual.isEmpty()) { - return; - } - LocalPersistentPayloadOperations.VerifiedArtifact staged = residual.orElseThrow(); - requireArtifact(operation, staged); - if (!staged.fileKey().equals(data.fileKey())) { - throw new RecoveryIntegrityException("residual stage is not the published data hard-link"); - } - runtime.payload().deleteStageExact(staged); - } - - private void requireArtifact( - DurablePublicationRecord operation, - LocalPersistentPayloadOperations.VerifiedArtifact artifact) { - try { - verifier.requireArtifact(operation, artifact); - } catch (IllegalArgumentException exception) { - throw new RecoveryIntegrityException("payload artifact does not match", exception); - } - } - - private void requireManifest( - DestinationRuntime runtime, - FilePublishRequest request, - DurablePublicationRecord operation, - PrivateFileManifest manifest, - PublishedFileReference reference) { - try { - verifier.requireManifest(operation, request, runtime.destination(), manifest, reference); - } catch (IllegalArgumentException exception) { - throw new RecoveryIntegrityException("private manifest does not match", exception); - } - } - - private void requireReference( - DurablePublicationRecord operation, - PrivateFileManifest manifest, - PublishedReferenceRecord reference, - PublishedFileReference opaqueReference, - String manifestDigest) { - try { - verifier.requireReference(operation, manifest, reference, opaqueReference, manifestDigest); - } catch (IllegalArgumentException exception) { - throw new RecoveryIntegrityException("reference index does not match", exception); - } - } - - private static DurablePublicationRecord transition( - DurablePublicationRecord current, - DurablePublicationRecord.State state, - long byteSize, - long rowCount, - int columnCount, - String sha256, - long formulaMitigatedCount, - String manifestDigest, - String referenceDigest, - Instant sealedAt, - Instant publishedAt, - String lastFailureCode, - String receiptSnapshot) { - return new DurablePublicationRecord( - current.schemaVersion(), - current.stateRevision() + 1, - state, - current.operationId(), - current.requestFingerprint(), - current.effectivePolicyRevision(), - current.effectivePolicyDigest(), - current.destinationId(), - current.providerId(), - current.fileId(), - current.routeToken(), - current.publishedFileName(), - current.stageFileName(), - byteSize, - rowCount, - columnCount, - sha256, - formulaMitigatedCount, - manifestDigest, - referenceDigest, - current.createdAt(), - sealedAt, - publishedAt, - lastFailureCode, - receiptSnapshot); - } - - private static DurablePublicationRecord quarantined( - DurablePublicationRecord current, String failureCode) { - return transition( - current, - DurablePublicationRecord.State.QUARANTINED, - current.byteSize(), - current.rowCount(), - current.columnCount(), - current.sha256(), - current.formulaMitigatedCount(), - current.manifestDigest(), - current.referenceDigest(), - current.sealedAt(), - null, - failureCode, - ""); - } - - private static void quarantinePreservingOriginal( - LocalPersistentControlPlane controlPlane, - DurablePublicationRecord operation, - String failureCode, - Throwable original) { - try { - controlPlane.storeOperation(quarantined(operation, failureCode)); - } catch (Throwable controlFailure) { - if (controlFailure != original) { - original.addSuppressed(controlFailure); - } - } - } - - private static FilePublicationException quarantineAndIndeterminate( - LocalPersistentControlPlane controlPlane, - DurablePublicationRecord operation, - String failureCode, - String message, - Throwable cause) { - FilePublicationException failure = indeterminate(message, cause); - if (operation.state() != DurablePublicationRecord.State.PUBLISHED - && operation.state() != DurablePublicationRecord.State.QUARANTINED) { - try { - controlPlane.storeOperation(quarantined(operation, failureCode)); - } catch (Throwable quarantineFailure) { - failure.addSuppressed(quarantineFailure); - } - } - return failure; - } - - private static long exactBound(long byteSize) { - if (byteSize < 1) { - throw new RecoveryIntegrityException("sealed artifact byte size must be positive"); - } - return byteSize; - } - - private static FilePublicationException mapControlFailure( - LocalPersistentControlPlane.LocalPersistentControlPlaneException exception) { - if (exception.kind() == LocalPersistentControlPlane.FailureKind.CONFLICT) { - return conflict("file publication control conflict", exception); - } - return indeterminate("file publication control state is indeterminate", exception); - } - - private static FilePublicationException mapPayloadFailure( - LocalPersistentPayloadOperations.LocalPersistentPayloadException exception) { - return switch (exception.kind()) { - case CAPACITY -> - new FilePublicationException( - FilePublicationException.Reason.CAPACITY_EXCEEDED, - "file publication capacity was exceeded", - exception); - case CONFLICT -> conflict("file publication target conflict", exception); - case INTEGRITY, STORAGE, INDETERMINATE -> - indeterminate("file publication payload state is indeterminate", exception); - }; - } - - private static FilePublicationException invalidRequest(String message, Throwable cause) { - return cause == null - ? new FilePublicationException(FilePublicationException.Reason.INVALID_REQUEST, message) - : new FilePublicationException( - FilePublicationException.Reason.INVALID_REQUEST, message, cause); - } - - private static FilePublicationException conflict(String message, Throwable cause) { - return cause == null - ? new FilePublicationException(FilePublicationException.Reason.CONFLICT, message) - : new FilePublicationException(FilePublicationException.Reason.CONFLICT, message, cause); - } - - private static FilePublicationException indeterminate(String message, Throwable cause) { - return cause == null - ? new FilePublicationException( - FilePublicationException.Reason.PUBLISH_INDETERMINATE, message) - : new FilePublicationException( - FilePublicationException.Reason.PUBLISH_INDETERMINATE, message, cause); - } - - private static void throwOriginal(Throwable original) { - if (original instanceof RuntimeException runtimeException) { - throw runtimeException; - } - if (original instanceof Error error) { - throw error; - } - throw indeterminate("file publication producer failed", original); - } - - private static MessageDigest sha256() { - try { - return MessageDigest.getInstance("SHA-256"); - } catch (NoSuchAlgorithmException exception) { - throw new IllegalStateException("SHA-256 unavailable", exception); - } - } - - private static String sha256Hex(String value) { - return HEX.formatHex(sha256().digest(value.getBytes(StandardCharsets.UTF_8))); - } - - record DestinationRuntime( - CompiledFileDestination destination, - LocalPersistentControlPlane controlPlane, - LocalPersistentPayloadOperations payload) { - - DestinationRuntime { - Objects.requireNonNull(destination, "destination must be non-null"); - Objects.requireNonNull(controlPlane, "controlPlane must be non-null"); - Objects.requireNonNull(payload, "payload must be non-null"); - } - } - - @FunctionalInterface - interface FileIdGenerator { - String nextFileId(); - } - - private static final class RecoveryIntegrityException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - private RecoveryIntegrityException(String message) { - super(message); - } - - private RecoveryIntegrityException(String message, Throwable cause) { - super(message, cause); - } - } -} diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/LocalPersistentRecoveryVerifier.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/LocalPersistentRecoveryVerifier.java deleted file mode 100644 index 4a43965b..00000000 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/LocalPersistentRecoveryVerifier.java +++ /dev/null @@ -1,210 +0,0 @@ -package dev.caskeleton.adapter.outbound.fileserver; - -import dev.caskeleton.application.filepublication.FilePublishOperationId; -import dev.caskeleton.application.filepublication.FilePublishReceipt; -import dev.caskeleton.application.filepublication.FilePublishReceipt.DurabilityGuarantee; -import dev.caskeleton.application.filepublication.FilePublishReceipt.PublicationGuarantee; -import dev.caskeleton.application.filepublication.FilePublishRequest; -import dev.caskeleton.application.filepublication.FileVersion; -import dev.caskeleton.application.filepublication.PublishedFileReference; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.HexFormat; -import java.util.Objects; - -/** Full-field verifier used before any R2 recovery transition or terminal receipt restoration. */ -final class LocalPersistentRecoveryVerifier { - - private static final String MEDIA_TYPE = "text/csv"; - private static final String CHARSET = StandardCharsets.UTF_8.name(); - private static final HexFormat HEX = HexFormat.of(); - - private final FileserverControlRecordCodec codec; - private final R2PublishedReferenceCodec referenceCodec; - - LocalPersistentRecoveryVerifier() { - this(new FileserverControlRecordCodec(), new R2PublishedReferenceCodec()); - } - - LocalPersistentRecoveryVerifier( - FileserverControlRecordCodec codec, R2PublishedReferenceCodec referenceCodec) { - this.codec = Objects.requireNonNull(codec, "codec must be non-null"); - this.referenceCodec = Objects.requireNonNull(referenceCodec, "referenceCodec must be non-null"); - } - - void requireOperationMatches( - DurablePublicationRecord operation, - FilePublishRequest request, - CompiledFileDestination destination, - String requestFingerprint) { - Objects.requireNonNull(operation, "operation must be non-null"); - Objects.requireNonNull(request, "request must be non-null"); - Objects.requireNonNull(destination, "destination must be non-null"); - if (!operation.operationId().equals(request.operationId().value()) - || !operation.requestFingerprint().equals(requestFingerprint) - || !operation.destinationId().equals(destination.destinationId().value()) - || !operation.providerId().equals(destination.providerId()) - || !operation.effectivePolicyRevision().equals(destination.effectivePolicyRevision()) - || !operation.effectivePolicyDigest().equals(destination.effectivePolicyDigest()) - || !operation.routeToken().equals(destination.routeToken()) - || !operation - .routeToken() - .equals(FilePublicationCanonicalDigests.routeToken(operation.effectivePolicyDigest())) - || !operation.publishedFileName().equals(generatedFileName(operation.fileId())) - || !operation - .stageFileName() - .equals(LocalPersistentPayloadOperations.stageFileName(operation.operationId()))) { - throw new IllegalArgumentException("durable operation does not match the current request"); - } - } - - void requireArtifact( - DurablePublicationRecord operation, - LocalPersistentPayloadOperations.VerifiedArtifact artifact) { - Objects.requireNonNull(operation, "operation must be non-null"); - Objects.requireNonNull(artifact, "artifact must be non-null"); - if (artifact.byteSize() != operation.byteSize() - || !artifact.sha256().equals(operation.sha256())) { - throw new IllegalArgumentException("payload artifact does not match the durable operation"); - } - } - - void requireManifest( - DurablePublicationRecord operation, - FilePublishRequest request, - CompiledFileDestination destination, - PrivateFileManifest manifest, - PublishedFileReference reference) { - Objects.requireNonNull(manifest, "manifest must be non-null"); - if (!manifest.operationId().equals(operation.operationId()) - || !manifest.fileId().equals(operation.fileId()) - || !manifest.providerId().equals(operation.providerId()) - || !manifest.fileReference().equals(reference.value()) - || !manifest.requestFingerprint().equals(operation.requestFingerprint()) - || !manifest.destinationId().equals(operation.destinationId()) - || !manifest.schemaId().equals(request.schema().schemaId()) - || manifest.exportSchemaVersion() != request.schema().version() - || !manifest - .schemaDigest() - .equals(FilePublicationCanonicalDigests.schemaDigest(request.schema())) - || !manifest.formatProfileId().equals(request.formatProfileId()) - || !manifest.formatPolicyDigest().equals(destination.formatPolicyDigest()) - || !manifest.effectivePolicyRevision().equals(operation.effectivePolicyRevision()) - || !manifest.effectivePolicyDigest().equals(operation.effectivePolicyDigest()) - || !manifest.publishedFileName().equals(operation.publishedFileName()) - || !manifest.fileVersion().equals(operation.sha256()) - || !manifest.mediaType().equals(MEDIA_TYPE) - || !manifest.charset().equals(CHARSET) - || manifest.byteSize() != operation.byteSize() - || manifest.rowCount() != operation.rowCount() - || manifest.columnCount() != operation.columnCount() - || !manifest.sha256().equals(operation.sha256()) - || manifest.formulaMitigatedCount() != operation.formulaMitigatedCount() - || manifest.publicationGuarantee() != PublicationGuarantee.UNIQUE_ATOMIC_CREATE - || manifest.durabilityGuarantee() != DurabilityGuarantee.FILE_AND_DIRECTORY_SYNC - || !manifest.internalLocator().equals(operation.publishedFileName()) - || !manifest.createdAt().equals(operation.createdAt()) - || manifest.publishedAt().isBefore(operation.sealedAt())) { - throw new IllegalArgumentException("private manifest does not match the durable operation"); - } - } - - void requireReference( - DurablePublicationRecord operation, - PrivateFileManifest manifest, - PublishedReferenceRecord reference, - PublishedFileReference opaqueReference, - String manifestDigest) { - Objects.requireNonNull(reference, "reference must be non-null"); - if (!reference.fileId().equals(operation.fileId()) - || !reference.routeToken().equals(operation.routeToken()) - || !reference.fileReference().equals(opaqueReference.value()) - || !reference.operationId().equals(operation.operationId()) - || !reference.fileVersion().equals(operation.sha256()) - || !reference.manifestDigest().equals(manifestDigest) - || !reference.internalLocator().equals(operation.publishedFileName()) - || !reference.destinationId().equals(operation.destinationId()) - || !reference.providerId().equals(operation.providerId()) - || !reference.publishedFileName().equals(operation.publishedFileName()) - || !reference.mediaType().equals(MEDIA_TYPE) - || !reference.charset().equals(CHARSET) - || reference.byteSize() != operation.byteSize() - || !reference.sha256().equals(operation.sha256()) - || !reference.publishedAt().equals(manifest.publishedAt()) - || !operation.destinationId().equals(reference.destinationId())) { - throw new IllegalArgumentException("reference index does not match the private manifest"); - } - } - - FilePublishReceipt expectedReceipt( - DurablePublicationRecord operation, - FilePublishRequest request, - PrivateFileManifest manifest, - PublishedFileReference reference) { - return new FilePublishReceipt( - new FilePublishOperationId(operation.operationId()), - reference, - request.destinationId(), - operation.publishedFileName(), - new FileVersion(operation.sha256()), - request.formatProfileId(), - MEDIA_TYPE, - CHARSET, - operation.byteSize(), - operation.rowCount(), - operation.columnCount(), - operation.sha256(), - manifest.publishedAt(), - PublicationGuarantee.UNIQUE_ATOMIC_CREATE, - DurabilityGuarantee.FILE_AND_DIRECTORY_SYNC, - operation.formulaMitigatedCount()); - } - - FilePublishReceipt requireTerminalReceipt( - DurablePublicationRecord operation, - FilePublishRequest request, - PrivateFileManifest manifest, - PublishedReferenceRecord reference) { - PublishedFileReference opaqueReference = - referenceCodec.encode(operation.routeToken(), operation.fileId()); - String manifestDigest = canonicalDigest(codec.encodeManifest(manifest)); - requireReference(operation, manifest, reference, opaqueReference, manifestDigest); - String referenceDigest = canonicalDigest(codec.encodeReference(reference)); - if (!operation.manifestDigest().equals(manifestDigest) - || !operation.referenceDigest().equals(referenceDigest)) { - throw new IllegalArgumentException("terminal operation metadata digests do not match"); - } - FilePublishReceipt expected = expectedReceipt(operation, request, manifest, opaqueReference); - FilePublishReceipt stored = codec.decodeReceiptSnapshot(operation.receiptSnapshot()); - if (!expected.equals(stored) || !operation.publishedAt().equals(expected.publishedAt())) { - throw new IllegalArgumentException("terminal receipt snapshot does not match verified truth"); - } - return stored; - } - - String canonicalManifestDigest(PrivateFileManifest manifest) { - return canonicalDigest(codec.encodeManifest(manifest)); - } - - String canonicalReferenceDigest(PublishedReferenceRecord reference) { - return canonicalDigest(codec.encodeReference(reference)); - } - - PublishedFileReference reference(DurablePublicationRecord operation) { - return referenceCodec.encode(operation.routeToken(), operation.fileId()); - } - - static String generatedFileName(String fileId) { - FileserverControlRecordCodec.requireFileId(fileId); - return "file-" + fileId + ".csv"; - } - - private static String canonicalDigest(byte[] bytes) { - try { - return HEX.formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); - } catch (NoSuchAlgorithmException exception) { - throw new IllegalStateException("SHA-256 unavailable", exception); - } - } -} diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/LocalPersistentRootAttestor.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/LocalPersistentRootAttestor.java deleted file mode 100644 index ddeda2bb..00000000 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/LocalPersistentRootAttestor.java +++ /dev/null @@ -1,773 +0,0 @@ -package dev.caskeleton.adapter.outbound.fileserver; - -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.channels.FileChannel; -import java.nio.file.DirectoryStream; -import java.nio.file.FileStore; -import java.nio.file.Files; -import java.nio.file.LinkOption; -import java.nio.file.NoSuchFileException; -import java.nio.file.OpenOption; -import java.nio.file.Path; -import java.nio.file.SecureDirectoryStream; -import java.nio.file.StandardOpenOption; -import java.nio.file.attribute.BasicFileAttributes; -import java.nio.file.attribute.FileAttribute; -import java.nio.file.attribute.PosixFileAttributes; -import java.nio.file.attribute.PosixFilePermission; -import java.nio.file.attribute.PosixFilePermissions; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.SecureRandom; -import java.util.ArrayList; -import java.util.HexFormat; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; - -/** Fail-closed POSIX capability attestation for a pre-provisioned persistent root. */ -final class LocalPersistentRootAttestor { - - private static final String CONTROL_DIRECTORY = ".ca-fileserver"; - private static final String DATA_DIRECTORY = "data"; - private static final String[] CONTROL_CHILDREN = { - "staging", "operations", "manifests", "references", "quarantine", "probe" - }; - private static final Set PRIVATE_DIRECTORY_PERMISSIONS = - PosixFilePermissions.fromString("rwx------"); - private static final Set PRIVATE_FILE_PERMISSIONS = - PosixFilePermissions.fromString("rw-------"); - private static final FileAttribute> PRIVATE_DIRECTORY_ATTRIBUTE = - PosixFilePermissions.asFileAttribute(PRIVATE_DIRECTORY_PERMISSIONS); - private static final FileAttribute> PRIVATE_FILE_ATTRIBUTE = - PosixFilePermissions.asFileAttribute(PRIVATE_FILE_PERMISSIONS); - private static final SecureRandom SECURE_RANDOM = new SecureRandom(); - - private final CapabilityOperations capabilityOperations; - private final FileStoreProbe fileStoreProbe; - private final ParentIdentityProbe parentIdentityProbe; - - LocalPersistentRootAttestor() { - this(systemCapabilityOperations(), systemFileStoreProbe(), systemParentIdentityProbe()); - } - - LocalPersistentRootAttestor( - CapabilityOperations capabilityOperations, FileStoreProbe fileStoreProbe) { - this(capabilityOperations, fileStoreProbe, systemParentIdentityProbe()); - } - - LocalPersistentRootAttestor( - CapabilityOperations capabilityOperations, - FileStoreProbe fileStoreProbe, - ParentIdentityProbe parentIdentityProbe) { - this.capabilityOperations = - Objects.requireNonNull(capabilityOperations, "capabilityOperations must be non-null"); - this.fileStoreProbe = Objects.requireNonNull(fileStoreProbe, "fileStoreProbe must be non-null"); - this.parentIdentityProbe = - Objects.requireNonNull(parentIdentityProbe, "parentIdentityProbe must be non-null"); - } - - LocalPersistentRootEvidence attest(CompiledFileDestination destination) { - Objects.requireNonNull(destination, "destination must be non-null"); - try { - return attestChecked(destination); - } catch (LocalPersistentRootAttestationException exception) { - throw exception; - } catch (IOException | RuntimeException exception) { - throw failure( - "persistent root attestation failed: " + exceptionMessage(exception), exception); - } - } - - void verifyIdentity(LocalPersistentRootEvidence evidence) { - Objects.requireNonNull(evidence, "evidence must be non-null"); - try { - Path root = evidence.root(); - requireAbsoluteNormalized(root); - rejectSymbolicRootOrAncestor(root); - PosixFileAttributes rootAttributes = readPosixRoot(root); - Path realRoot = root.toRealPath(); - if (!realRoot.equals(root)) { - throw failure("root real path no longer matches attested root"); - } - requireIdentity("root", rootAttributes.fileKey(), evidence.rootFileKey()); - PosixFileAttributes confirmedRootAttributes = readPosixRoot(realRoot); - requireIdentity("root", confirmedRootAttributes.fileKey(), evidence.rootFileKey()); - requireEqual( - "root owner", evidence.expectedOwner(), confirmedRootAttributes.owner().getName()); - validateRootPermissions( - confirmedRootAttributes.permissions(), evidence.maximumRootPermissions()); - - FileStoreIdentity rootStore = fileStoreProbe.inspect(root); - requireEqual("root FileStore name", evidence.fileStoreName(), rootStore.name()); - requireEqual("root FileStore type", evidence.fileStoreType(), rootStore.type()); - validateSentinel(root, evidence.mountSentinelName(), evidence.mountSentinelSha256()); - - for (Map.Entry entry : evidence.criticalDirectoryFileKeys().entrySet()) { - Path directory = root.resolve(entry.getKey()); - PosixFileAttributes attributes = readPrivateDirectory(directory, evidence.expectedOwner()); - requireIdentity(entry.getKey(), attributes.fileKey(), entry.getValue()); - FileStoreIdentity directoryStore = fileStoreProbe.inspect(directory); - if (!rootStore.equals(directoryStore)) { - throw failure( - entry.getKey() + " FileStore no longer matches the attested root FileStore"); - } - } - } catch (LocalPersistentRootAttestationException exception) { - throw exception; - } catch (IOException | RuntimeException exception) { - throw failure( - "persistent root identity verification failed: " + exceptionMessage(exception), - exception); - } - } - - private LocalPersistentRootEvidence attestChecked(CompiledFileDestination destination) - throws IOException { - Path configuredRoot = destination.rootDirectory(); - requireAbsoluteNormalized(configuredRoot); - rejectSymbolicRootOrAncestor(configuredRoot); - PosixFileAttributes rootAttributes = readPosixRoot(configuredRoot); - Path realRoot = configuredRoot.toRealPath(); - if (!realRoot.equals(configuredRoot)) { - throw failure("root real path must exactly match the configured absolute path"); - } - PosixFileAttributes confirmedRootAttributes = readPosixRoot(realRoot); - requireIdentity( - "root", - confirmedRootAttributes.fileKey(), - requireFileKey("root", rootAttributes.fileKey())); - rootAttributes = confirmedRootAttributes; - String rootFileKey = requireFileKey("root", rootAttributes.fileKey()); - requireEqual("root owner", destination.expectedOwner(), rootAttributes.owner().getName()); - validateRootPermissions(rootAttributes.permissions(), destination.maximumRootPermissions()); - - FileStoreIdentity rootStore = fileStoreProbe.inspect(realRoot); - requireEqual("root FileStore name", destination.expectedFileStoreName(), rootStore.name()); - requireEqual("root FileStore type", destination.expectedFileStoreType(), rootStore.type()); - String sentinelDigest = - validateSentinel( - realRoot, destination.mountSentinelName(), destination.mountSentinelSha256()); - - Map directoryFileKeys = - prepareInternalDirectories(realRoot, destination.expectedOwner(), rootStore, rootFileKey); - requireSecureDirectoryStream(realRoot); - runCapabilityProbe(realRoot.resolve(CONTROL_DIRECTORY).resolve("probe")); - - LocalPersistentRootEvidence evidence = - new LocalPersistentRootEvidence( - realRoot, - rootFileKey, - rootStore.name(), - rootStore.type(), - destination.expectedOwner(), - destination.maximumRootPermissions(), - destination.mountSentinelName(), - sentinelDigest, - true, - true, - true, - directoryFileKeys); - verifyIdentity(evidence); - return evidence; - } - - private Map prepareInternalDirectories( - Path root, String expectedOwner, FileStoreIdentity rootStore, String rootFileKey) - throws IOException { - Map identities = new LinkedHashMap<>(); - List createdDirectories = new ArrayList<>(); - try { - prevalidateExistingHierarchy(root, expectedOwner, rootStore); - - Path data = root.resolve(DATA_DIRECTORY); - PosixFileAttributes dataAttributes = - createOrValidatePrivateDirectory( - DATA_DIRECTORY, - data, - root, - expectedOwner, - rootFileKey, - rootStore, - createdDirectories); - identities.put(DATA_DIRECTORY, requireFileKey(DATA_DIRECTORY, dataAttributes.fileKey())); - - Path control = root.resolve(CONTROL_DIRECTORY); - PosixFileAttributes controlAttributes = - createOrValidatePrivateDirectory( - CONTROL_DIRECTORY, - control, - root, - expectedOwner, - rootFileKey, - rootStore, - createdDirectories); - String controlFileKey = requireFileKey(CONTROL_DIRECTORY, controlAttributes.fileKey()); - identities.put(CONTROL_DIRECTORY, controlFileKey); - - for (String child : CONTROL_CHILDREN) { - Path directory = control.resolve(child); - String relativeName = CONTROL_DIRECTORY + "/" + child; - PosixFileAttributes attributes = - createOrValidatePrivateDirectory( - relativeName, - directory, - control, - expectedOwner, - controlFileKey, - rootStore, - createdDirectories); - identities.put(relativeName, requireFileKey(relativeName, attributes.fileKey())); - } - } catch (IOException | RuntimeException exception) { - rollbackCreatedDirectories(createdDirectories, exception); - throw exception; - } - return Map.copyOf(identities); - } - - private void prevalidateExistingHierarchy( - Path root, String expectedOwner, FileStoreIdentity rootStore) throws IOException { - requireSameFileStore("root parent", root, rootStore); - prevalidatePrivateDirectoryIfPresent( - DATA_DIRECTORY, root.resolve(DATA_DIRECTORY), expectedOwner, rootStore); - - Path control = root.resolve(CONTROL_DIRECTORY); - PosixFileAttributes controlAttributes = - prevalidatePrivateDirectoryIfPresent(CONTROL_DIRECTORY, control, expectedOwner, rootStore); - if (controlAttributes == null) { - return; - } - requireSameFileStore("control parent", control, rootStore); - for (String child : CONTROL_CHILDREN) { - String relativeName = CONTROL_DIRECTORY + "/" + child; - prevalidatePrivateDirectoryIfPresent( - relativeName, control.resolve(child), expectedOwner, rootStore); - } - } - - private PosixFileAttributes prevalidatePrivateDirectoryIfPresent( - String relativeName, Path directory, String expectedOwner, FileStoreIdentity rootStore) - throws IOException { - if (!existsNoFollow(directory)) { - return null; - } - PosixFileAttributes attributes = readPrivateDirectory(directory, expectedOwner); - requireSameFileStore(relativeName, directory, rootStore); - return attributes; - } - - private PosixFileAttributes createOrValidatePrivateDirectory( - String relativeName, - Path directory, - Path parent, - String expectedOwner, - String expectedParentFileKey, - FileStoreIdentity rootStore, - List createdDirectories) - throws IOException { - requireSameFileStore(relativeName + " parent", parent, rootStore); - requireParentIdentity(parent, expectedParentFileKey, "before " + relativeName); - boolean created = false; - try { - Files.createDirectory(directory, PRIVATE_DIRECTORY_ATTRIBUTE); - created = true; - String createdFileKey = - readNoFollowDirectoryFileKey(directory, "new internal directory " + relativeName); - createdDirectories.add( - new CreatedDirectory(directory, parent, createdFileKey, expectedParentFileKey)); - Files.setPosixFilePermissions(directory, PRIVATE_DIRECTORY_PERMISSIONS); - } catch (java.nio.file.FileAlreadyExistsException ignored) { - // Existing state is accepted only after the same strict no-follow validation below. - } - - PosixFileAttributes attributes = readPrivateDirectory(directory, expectedOwner); - requireSameFileStore(relativeName, directory, rootStore); - requireParentIdentity(parent, expectedParentFileKey, "after " + relativeName + " validation"); - if (created) { - capabilityOperations.forceDirectory(parent); - requireParentIdentity( - parent, expectedParentFileKey, "after " + relativeName + " parent force"); - } - return attributes; - } - - private void rollbackCreatedDirectories( - List createdDirectories, Exception primaryFailure) { - Exception rollbackFailure = null; - for (int index = createdDirectories.size() - 1; index >= 0; index--) { - CreatedDirectory created = createdDirectories.get(index); - try { - rollbackCreatedDirectory(created); - } catch (IOException | RuntimeException exception) { - if (rollbackFailure == null) { - rollbackFailure = exception; - } else { - rollbackFailure.addSuppressed(exception); - } - } - } - if (rollbackFailure != null) { - primaryFailure.addSuppressed(rollbackFailure); - } - } - - private void rollbackCreatedDirectory(CreatedDirectory created) throws IOException { - String parentFileKey = parentIdentityProbe.inspect(created.parent()); - if (!created.parentFileKey().equals(parentFileKey)) { - throw failure("refusing rollback because parent identity changed: " + created.parent()); - } - - BasicFileAttributes attributes; - try { - attributes = - Files.readAttributes( - created.directory(), BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); - } catch (NoSuchFileException ignored) { - return; - } - if (attributes.isSymbolicLink() || !attributes.isDirectory()) { - throw failure("refusing rollback of replaced internal directory: " + created.directory()); - } - String actualFileKey = - requireFileKey("rollback directory " + created.directory(), attributes.fileKey()); - if (!created.directoryFileKey().equals(actualFileKey)) { - throw failure( - "refusing rollback because internal directory identity changed: " + created.directory()); - } - Files.delete(created.directory()); - capabilityOperations.forceDirectory(created.parent()); - } - - private static String readNoFollowDirectoryFileKey(Path directory, String description) - throws IOException { - BasicFileAttributes attributes = - Files.readAttributes(directory, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); - if (attributes.isSymbolicLink() || !attributes.isDirectory()) { - throw failure(description + " must be a no-follow directory"); - } - return requireFileKey(description, attributes.fileKey()); - } - - private void requireParentIdentity(Path parent, String expectedFileKey, String phase) - throws IOException { - String actualFileKey = parentIdentityProbe.inspect(parent); - if (!expectedFileKey.equals(actualFileKey)) { - throw failure("parent identity mismatch " + phase + ": " + parent); - } - } - - private static boolean existsNoFollow(Path path) throws IOException { - try { - Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); - return true; - } catch (NoSuchFileException exception) { - return false; - } - } - - private static PosixFileAttributes readPrivateDirectory(Path directory, String expectedOwner) - throws IOException { - PosixFileAttributes attributes; - try { - attributes = - Files.readAttributes(directory, PosixFileAttributes.class, LinkOption.NOFOLLOW_LINKS); - } catch (NoSuchFileException exception) { - throw failure("internal directory does not exist: " + directory, exception); - } - if (attributes.isSymbolicLink()) { - throw failure("internal directory is a symbolic link: " + directory); - } - if (!attributes.isDirectory()) { - throw failure("internal path is not a directory: " + directory); - } - Path realDirectory = directory.toRealPath(); - if (!realDirectory.equals(directory)) { - throw failure("internal directory real path mismatch: " + directory); - } - PosixFileAttributes confirmedAttributes = - Files.readAttributes(directory, PosixFileAttributes.class, LinkOption.NOFOLLOW_LINKS); - requireIdentity( - "internal directory " + directory, - confirmedAttributes.fileKey(), - requireFileKey("internal directory " + directory, attributes.fileKey())); - if (confirmedAttributes.isSymbolicLink() || !confirmedAttributes.isDirectory()) { - throw failure("internal directory identity changed during validation: " + directory); - } - attributes = confirmedAttributes; - if (expectedOwner != null && !expectedOwner.equals(attributes.owner().getName())) { - throw failure("internal directory owner mismatch: " + directory); - } - if (!PRIVATE_DIRECTORY_PERMISSIONS.equals(attributes.permissions())) { - throw failure("internal directory must have exact private mode 0700: " + directory); - } - return attributes; - } - - private void requireSameFileStore( - String relativeName, Path directory, FileStoreIdentity rootStore) throws IOException { - FileStoreIdentity directoryStore = fileStoreProbe.inspect(directory); - if (!rootStore.equals(directoryStore)) { - throw failure(relativeName + " FileStore does not match root FileStore"); - } - } - - private void requireSecureDirectoryStream(Path root) throws IOException { - try (SecureDirectoryStream ignored = capabilityOperations.openSecureDirectory(root)) { - // Opening and closing without exposing the stream is the capability evidence. - } - } - - private void runCapabilityProbe(Path probeDirectory) throws IOException { - String token = randomToken(); - Path file = probeDirectory.resolve("probe-" + token + ".tmp"); - Path link = probeDirectory.resolve("probe-" + token + ".link"); - try { - Set options = - Set.of( - StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE, LinkOption.NOFOLLOW_LINKS); - try (FileChannel channel = FileChannel.open(file, options, PRIVATE_FILE_ATTRIBUTE)) { - Files.setPosixFilePermissions(file, PRIVATE_FILE_PERMISSIONS); - writeFully( - channel, ByteBuffer.wrap(token.getBytes(java.nio.charset.StandardCharsets.UTF_8))); - capabilityOperations.forceFile(channel); - } - capabilityOperations.createHardLink(link, file); - capabilityOperations.forceDirectory(probeDirectory); - requireRegularProbeArtifact(file, "probe file"); - requireRegularProbeArtifact(link, "probe hard-link"); - requireSameFileKey(file, link); - } catch (IOException | RuntimeException exception) { - cleanupProbe(probeDirectory, link, file, exception); - throw exception; - } - cleanupProbe(probeDirectory, link, file, null); - } - - private void cleanupProbe(Path probeDirectory, Path link, Path file, Exception primaryFailure) - throws IOException { - Exception cleanupFailure = null; - try { - Files.deleteIfExists(link); - } catch (IOException | RuntimeException exception) { - cleanupFailure = exception; - } - try { - Files.deleteIfExists(file); - } catch (IOException | RuntimeException exception) { - cleanupFailure = combineCleanupFailures(cleanupFailure, exception); - } - try { - capabilityOperations.forceDirectory(probeDirectory); - } catch (IOException | RuntimeException exception) { - cleanupFailure = combineCleanupFailures(cleanupFailure, exception); - } - if (cleanupFailure == null) { - return; - } - if (primaryFailure != null) { - primaryFailure.addSuppressed(cleanupFailure); - return; - } - if (cleanupFailure instanceof IOException ioException) { - throw ioException; - } - throw (RuntimeException) cleanupFailure; - } - - private static Exception combineCleanupFailures(Exception existing, Exception additional) { - if (existing == null) { - return additional; - } - existing.addSuppressed(additional); - return existing; - } - - private static void requireRegularProbeArtifact(Path artifact, String description) - throws IOException { - BasicFileAttributes attributes = - Files.readAttributes(artifact, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); - if (attributes.isSymbolicLink() || !attributes.isRegularFile()) { - throw failure(description + " is not a regular no-follow file"); - } - } - - private static void requireSameFileKey(Path file, Path link) throws IOException { - BasicFileAttributes fileAttributes = - Files.readAttributes(file, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); - BasicFileAttributes linkAttributes = - Files.readAttributes(link, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); - String fileKey = requireFileKey("probe file", fileAttributes.fileKey()); - String linkKey = requireFileKey("probe hard-link", linkAttributes.fileKey()); - if (!fileKey.equals(linkKey)) { - throw failure("exclusive hard-link probe did not preserve file identity"); - } - } - - private static void writeFully(FileChannel channel, ByteBuffer content) throws IOException { - while (content.hasRemaining()) { - channel.write(content); - } - } - - private static String validateSentinel(Path root, String sentinelName, String expectedDigest) - throws IOException { - Path sentinel = root.resolve(sentinelName); - BasicFileAttributes before; - try { - before = Files.readAttributes(sentinel, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); - } catch (NoSuchFileException exception) { - throw failure("mount sentinel does not exist: " + sentinel, exception); - } - if (before.isSymbolicLink()) { - throw failure("mount sentinel must not be a symbolic link: " + sentinel); - } - if (!before.isRegularFile()) { - throw failure("mount sentinel must be a regular no-follow file: " + sentinel); - } - - String digest = digestNoFollow(sentinel); - BasicFileAttributes after = - Files.readAttributes(sentinel, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); - String beforeFileKey = requireFileKey("mount sentinel", before.fileKey()); - requireIdentity("mount sentinel", after.fileKey(), beforeFileKey); - if (!expectedDigest.equals(digest)) { - throw failure("mount sentinel SHA-256 mismatch"); - } - return digest; - } - - private static String digestNoFollow(Path file) throws IOException { - MessageDigest digest; - try { - digest = MessageDigest.getInstance("SHA-256"); - } catch (NoSuchAlgorithmException exception) { - throw new AssertionError("SHA-256 must be available", exception); - } - Set options = Set.of(StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS); - try (FileChannel channel = FileChannel.open(file, options)) { - ByteBuffer buffer = ByteBuffer.allocate(8192); - while (channel.read(buffer) >= 0) { - buffer.flip(); - digest.update(buffer); - buffer.clear(); - } - } - return HexFormat.of().formatHex(digest.digest()); - } - - private static void rejectSymbolicRootOrAncestor(Path root) throws IOException { - Path current = root.getRoot(); - if (current == null) { - throw failure("root path must be absolute"); - } - for (Path element : root) { - current = current.resolve(element); - BasicFileAttributes attributes; - try { - attributes = - Files.readAttributes(current, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); - } catch (NoSuchFileException exception) { - throw failure("root or an existing ancestor does not exist: " + current, exception); - } - if (attributes.isSymbolicLink()) { - String kind = current.equals(root) ? "root" : "root ancestor"; - throw failure(kind + " is a symbolic link: " + current); - } - } - } - - private static PosixFileAttributes readPosixRoot(Path root) throws IOException { - PosixFileAttributes attributes; - try { - attributes = Files.readAttributes(root, PosixFileAttributes.class, LinkOption.NOFOLLOW_LINKS); - } catch (NoSuchFileException exception) { - throw failure("root does not exist: " + root, exception); - } catch (UnsupportedOperationException exception) { - throw failure("strict POSIX root attributes are required", exception); - } - if (attributes.isSymbolicLink()) { - throw failure("root is a symbolic link: " + root); - } - if (!attributes.isDirectory()) { - throw failure("root must be a directory: " + root); - } - return attributes; - } - - private static void validateRootPermissions( - Set actual, Set maximum) { - if (actual.contains(PosixFilePermission.GROUP_WRITE) - || actual.contains(PosixFilePermission.OTHERS_WRITE)) { - throw failure("root must never be group/world writable"); - } - if (!maximum.containsAll(actual)) { - throw failure("root permissions are broader than configured maximum-root-mode"); - } - } - - private static void requireAbsoluteNormalized(Path root) { - if (!root.isAbsolute()) { - throw failure("root path must be absolute"); - } - if (!root.equals(root.normalize())) { - throw failure("root path must already be normalized"); - } - } - - private static void requireEqual(String description, String expected, String actual) { - if (!expected.equals(actual)) { - throw failure(description + " mismatch: expected " + expected + " but was " + actual); - } - } - - private static void requireIdentity( - String description, Object actualFileKey, String expectedFileKey) { - String actual = requireFileKey(description, actualFileKey); - if (!expectedFileKey.equals(actual)) { - throw failure(description + " identity mismatch"); - } - } - - private static String requireFileKey(String description, Object fileKey) { - if (fileKey == null) { - throw failure(description + " file identity is unavailable"); - } - return fileKey.toString(); - } - - private static String randomToken() { - byte[] bytes = new byte[16]; - SECURE_RANDOM.nextBytes(bytes); - return HexFormat.of().formatHex(bytes); - } - - private static String exceptionMessage(Exception exception) { - return exception.getMessage() == null - ? exception.getClass().getSimpleName() - : exception.getMessage(); - } - - private static LocalPersistentRootAttestationException failure(String message) { - return new LocalPersistentRootAttestationException(message); - } - - private static LocalPersistentRootAttestationException failure(String message, Throwable cause) { - return new LocalPersistentRootAttestationException(message, cause); - } - - static CapabilityOperations systemCapabilityOperations() { - return SystemCapabilityOperations.INSTANCE; - } - - static FileStoreProbe systemFileStoreProbe() { - return path -> { - FileStore store = Files.getFileStore(path); - return new FileStoreIdentity(store.name(), store.type(), store.toString()); - }; - } - - static ParentIdentityProbe systemParentIdentityProbe() { - return parent -> { - PosixFileAttributes attributes = - Files.readAttributes(parent, PosixFileAttributes.class, LinkOption.NOFOLLOW_LINKS); - if (attributes.isSymbolicLink() || !attributes.isDirectory()) { - throw failure("parent must be a no-follow directory: " + parent); - } - Path realParent = parent.toRealPath(); - if (!realParent.equals(parent)) { - throw failure("parent real path mismatch: " + parent); - } - String fileKey = requireFileKey("parent " + parent, attributes.fileKey()); - PosixFileAttributes confirmedAttributes = - Files.readAttributes(parent, PosixFileAttributes.class, LinkOption.NOFOLLOW_LINKS); - requireIdentity("parent " + parent, confirmedAttributes.fileKey(), fileKey); - if (confirmedAttributes.isSymbolicLink() || !confirmedAttributes.isDirectory()) { - throw failure("parent identity changed during validation: " + parent); - } - return fileKey; - }; - } - - interface CapabilityOperations { - - SecureDirectoryStream openSecureDirectory(Path directory) throws IOException; - - void forceFile(FileChannel channel) throws IOException; - - void createHardLink(Path link, Path existing) throws IOException; - - void forceDirectory(Path directory) throws IOException; - } - - interface FileStoreProbe { - - FileStoreIdentity inspect(Path path) throws IOException; - } - - interface ParentIdentityProbe { - - String inspect(Path parent) throws IOException; - } - - record FileStoreIdentity(String name, String type, String identity) { - - FileStoreIdentity { - Objects.requireNonNull(name, "name must be non-null"); - Objects.requireNonNull(type, "type must be non-null"); - Objects.requireNonNull(identity, "identity must be non-null"); - } - } - - static final class LocalPersistentRootAttestationException extends IllegalStateException { - private static final long serialVersionUID = 1L; - - private LocalPersistentRootAttestationException(String message) { - super(message); - } - - private LocalPersistentRootAttestationException(String message, Throwable cause) { - super(message, cause); - } - } - - private record CreatedDirectory( - Path directory, Path parent, String directoryFileKey, String parentFileKey) {} - - private enum SystemCapabilityOperations implements CapabilityOperations { - INSTANCE; - - @Override - // The stream is the return value and the caller closes it; "resource" says that to the Eclipse - // compiler, "StreamResourceLeak" to ErrorProne. - @SuppressWarnings({"StreamResourceLeak", "unchecked", "resource"}) - public SecureDirectoryStream openSecureDirectory(Path directory) throws IOException { - DirectoryStream stream = Files.newDirectoryStream(directory); - if (stream instanceof SecureDirectoryStream secureStream) { - return (SecureDirectoryStream) secureStream; - } - stream.close(); - throw new IOException("SecureDirectoryStream unavailable for " + directory); - } - - @Override - public void forceFile(FileChannel channel) throws IOException { - channel.force(true); - } - - @Override - public void createHardLink(Path link, Path existing) throws IOException { - Files.createLink(link, existing); - } - - @Override - public void forceDirectory(Path directory) throws IOException { - try (FileChannel channel = FileChannel.open(directory, StandardOpenOption.READ)) { - channel.force(true); - } - } - } -} diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/LocalPersistentRootEvidence.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/LocalPersistentRootEvidence.java deleted file mode 100644 index 45347a62..00000000 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/LocalPersistentRootEvidence.java +++ /dev/null @@ -1,41 +0,0 @@ -package dev.caskeleton.adapter.outbound.fileserver; - -import java.nio.file.Path; -import java.nio.file.attribute.PosixFilePermission; -import java.util.Map; -import java.util.Objects; -import java.util.Set; - -/** Immutable startup evidence for one pre-provisioned local persistent root. */ -record LocalPersistentRootEvidence( - Path root, - String rootFileKey, - String fileStoreName, - String fileStoreType, - String expectedOwner, - Set maximumRootPermissions, - String mountSentinelName, - String mountSentinelSha256, - boolean secureDirectoryStream, - boolean directorySync, - boolean exclusiveHardLink, - Map criticalDirectoryFileKeys) { - - LocalPersistentRootEvidence { - root = Path.of(Objects.requireNonNull(root, "root must be non-null").toString()); - Objects.requireNonNull(rootFileKey, "rootFileKey must be non-null"); - Objects.requireNonNull(fileStoreName, "fileStoreName must be non-null"); - Objects.requireNonNull(fileStoreType, "fileStoreType must be non-null"); - Objects.requireNonNull(expectedOwner, "expectedOwner must be non-null"); - maximumRootPermissions = - Set.copyOf( - Objects.requireNonNull( - maximumRootPermissions, "maximumRootPermissions must be non-null")); - Objects.requireNonNull(mountSentinelName, "mountSentinelName must be non-null"); - Objects.requireNonNull(mountSentinelSha256, "mountSentinelSha256 must be non-null"); - criticalDirectoryFileKeys = - Map.copyOf( - Objects.requireNonNull( - criticalDirectoryFileKeys, "criticalDirectoryFileKeys must be non-null")); - } -} diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/LocalPublicationJournal.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/LocalPublicationJournal.java deleted file mode 100644 index 3e8ddfe2..00000000 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/LocalPublicationJournal.java +++ /dev/null @@ -1,294 +0,0 @@ -package dev.caskeleton.adapter.outbound.fileserver; - -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.channels.FileChannel; -import java.nio.channels.FileLock; -import java.nio.file.AtomicMoveNotSupportedException; -import java.nio.file.FileAlreadyExistsException; -import java.nio.file.Files; -import java.nio.file.LinkOption; -import java.nio.file.Path; -import java.nio.file.StandardCopyOption; -import java.nio.file.StandardOpenOption; -import java.nio.file.attribute.PosixFilePermission; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.HexFormat; -import java.util.Optional; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.Semaphore; - -/** Forced, atomically replaced operation journal for the local provider. */ -final class LocalPublicationJournal { - - private static final int MAXIMUM_RECORD_BYTES = 16_384; - private static final int JVM_LOCK_STRIPE_COUNT = 256; - private static final HexFormat HEX = HexFormat.of(); - private static final Semaphore[] JVM_LOCK_STRIPES = createLockStripes(); - - private final Path controlDirectory; - private final Path operationsDirectory; - - LocalPublicationJournal(Path baseDirectory) { - controlDirectory = baseDirectory.resolve(".ca-fileserver"); - operationsDirectory = controlDirectory.resolve("operations"); - initialize(); - } - - Optional find(String operationId) { - Path record = recordPath(operationId); - validateShardIfPresent(record.getParent()); - if (!Files.exists(record, LinkOption.NOFOLLOW_LINKS)) { - return Optional.empty(); - } - try { - if (!Files.isRegularFile(record, LinkOption.NOFOLLOW_LINKS) - || Files.size(record) > MAXIMUM_RECORD_BYTES) { - throw new LocalPublicationJournalException("local publication journal is corrupt"); - } - LocalPublicationJournalRecord decoded = - LocalPublicationJournalCodec.decode(Files.readAllBytes(record)); - if (!decoded.operationId().equals(operationId)) { - throw new LocalPublicationJournalException("local publication journal identity mismatch"); - } - return Optional.of(decoded); - } catch (IOException exception) { - throw new LocalPublicationJournalException( - "local publication journal cannot be read", exception); - } - } - - OperationLock acquire(String operationId) { - Path lockPath = lockPath(operationId); - Semaphore jvmLock = - JVM_LOCK_STRIPES[ - Math.floorMod(lockPath.toAbsolutePath().normalize().hashCode(), JVM_LOCK_STRIPE_COUNT)]; - jvmLock.acquireUninterruptibly(); - FileChannel channel = null; - try { - createRealDirectory(lockPath.getParent()); - restrictDirectory(lockPath.getParent()); - if (Files.exists(lockPath, LinkOption.NOFOLLOW_LINKS) - && !Files.isRegularFile(lockPath, LinkOption.NOFOLLOW_LINKS)) { - throw new LocalPublicationJournalException("local publication operation lock is invalid"); - } - channel = - FileChannel.open( - lockPath, - StandardOpenOption.CREATE, - StandardOpenOption.WRITE, - LinkOption.NOFOLLOW_LINKS); - restrictFile(lockPath); - return new OperationLock(channel.lock(), channel, jvmLock); - } catch (IOException | RuntimeException exception) { - closeAfterAcquireFailure(channel, exception); - jvmLock.release(); - if (exception instanceof LocalPublicationJournalException journalException) { - throw journalException; - } - throw new LocalPublicationJournalException( - "local publication operation lock is unavailable", exception); - } - } - - void store(LocalPublicationJournalRecord record) { - byte[] encoded = LocalPublicationJournalCodec.encode(record); - Path target = recordPath(record.operationId()); - Path parent = target.getParent(); - Path temporary = parent.resolve("." + target.getFileName() + "." + UUID.randomUUID() + ".tmp"); - try { - createRealDirectory(parent); - restrictDirectory(parent); - try (FileChannel channel = - FileChannel.open( - temporary, - StandardOpenOption.CREATE_NEW, - StandardOpenOption.WRITE, - LinkOption.NOFOLLOW_LINKS)) { - restrictFile(temporary); - ByteBuffer buffer = ByteBuffer.wrap(encoded); - while (buffer.hasRemaining()) { - channel.write(buffer); - } - channel.force(true); - } - Files.move( - temporary, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); - forceDirectory(parent); - } catch (AtomicMoveNotSupportedException exception) { - deleteTemporary(temporary, exception); - throw new LocalPublicationJournalException( - "atomic local publication journal update is unavailable", exception); - } catch (IOException exception) { - deleteTemporary(temporary, exception); - throw new LocalPublicationJournalException( - "local publication journal cannot be stored", exception); - } - } - - void delete(String operationId, Throwable original) { - Path target = recordPath(operationId); - try { - validateShardIfPresent(target.getParent()); - if (Files.deleteIfExists(target)) { - forceDirectory(target.getParent()); - } - } catch (IOException cleanupFailure) { - original.addSuppressed(cleanupFailure); - } - } - - Path recordPath(String operationId) { - String token = token(operationId); - return operationsDirectory.resolve(token.substring(0, 2)).resolve(token + ".json"); - } - - private Path lockPath(String operationId) { - String token = token(operationId); - return operationsDirectory.resolve(token.substring(0, 2)).resolve(token + ".lock"); - } - - private void initialize() { - try { - createRealDirectory(controlDirectory); - restrictDirectory(controlDirectory); - createRealDirectory(operationsDirectory); - restrictDirectory(operationsDirectory); - } catch (IOException exception) { - throw new LocalPublicationJournalException( - "local publication control directory is unavailable", exception); - } - } - - private static void createRealDirectory(Path directory) throws IOException { - try { - Files.createDirectory(directory); - } catch (FileAlreadyExistsException ignored) { - // Validate the existing entry without following a symbolic link. - } - validateRealDirectory(directory); - } - - private static void validateShardIfPresent(Path directory) { - if (Files.exists(directory, LinkOption.NOFOLLOW_LINKS)) { - validateRealDirectory(directory); - } - } - - private static void validateRealDirectory(Path directory) { - if (Files.isSymbolicLink(directory) - || !Files.isDirectory(directory, LinkOption.NOFOLLOW_LINKS)) { - throw new LocalPublicationJournalException("local publication control directory is invalid"); - } - } - - private static void restrictDirectory(Path path) throws IOException { - try { - Files.setPosixFilePermissions( - path, - Set.of( - PosixFilePermission.OWNER_READ, - PosixFilePermission.OWNER_WRITE, - PosixFilePermission.OWNER_EXECUTE)); - } catch (UnsupportedOperationException ignored) { - // Deployment qualification owns non-POSIX permission evidence. - } - } - - private static void restrictFile(Path path) throws IOException { - try { - Files.setPosixFilePermissions( - path, Set.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE)); - } catch (UnsupportedOperationException ignored) { - // Deployment qualification owns non-POSIX permission evidence. - } - } - - private static void forceDirectory(Path directory) throws IOException { - try (FileChannel channel = FileChannel.open(directory, StandardOpenOption.READ)) { - channel.force(true); - } - } - - private static String token(String operationId) { - try { - return HEX.formatHex( - MessageDigest.getInstance("SHA-256") - .digest(operationId.getBytes(java.nio.charset.StandardCharsets.UTF_8))); - } catch (NoSuchAlgorithmException exception) { - throw new IllegalStateException("SHA-256 unavailable", exception); - } - } - - private static void deleteTemporary(Path temporary, Throwable original) { - try { - Files.deleteIfExists(temporary); - } catch (IOException cleanupFailure) { - original.addSuppressed(cleanupFailure); - } - } - - private static Semaphore[] createLockStripes() { - Semaphore[] locks = new Semaphore[JVM_LOCK_STRIPE_COUNT]; - for (int index = 0; index < locks.length; index++) { - locks[index] = new Semaphore(1); - } - return locks; - } - - private static void closeAfterAcquireFailure(FileChannel channel, Throwable original) { - if (channel == null) { - return; - } - try { - channel.close(); - } catch (IOException closeFailure) { - original.addSuppressed(closeFailure); - } - } - - static final class OperationLock implements AutoCloseable { - - private final FileLock fileLock; - private final FileChannel channel; - private final Semaphore jvmLock; - private boolean closed; - - private OperationLock(FileLock fileLock, FileChannel channel, Semaphore jvmLock) { - this.fileLock = fileLock; - this.channel = channel; - this.jvmLock = jvmLock; - } - - @Override - public void close() { - if (closed) { - return; - } - closed = true; - IOException failure = null; - try { - fileLock.release(); - } catch (IOException exception) { - failure = exception; - } - try { - channel.close(); - } catch (IOException exception) { - if (failure == null) { - failure = exception; - } else { - failure.addSuppressed(exception); - } - } finally { - jvmLock.release(); - } - if (failure != null) { - throw new LocalPublicationJournalException( - "local publication operation lock cannot be released", failure); - } - } - } -} diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/LocalPublicationJournalCodec.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/LocalPublicationJournalCodec.java deleted file mode 100644 index a88c8957..00000000 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/LocalPublicationJournalCodec.java +++ /dev/null @@ -1,266 +0,0 @@ -package dev.caskeleton.adapter.outbound.fileserver; - -import java.nio.ByteBuffer; -import java.nio.charset.CharacterCodingException; -import java.nio.charset.CodingErrorAction; -import java.nio.charset.StandardCharsets; -import java.util.Arrays; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Set; - -/** Strict bounded codec for the flat local operation-journal JSON document. */ -final class LocalPublicationJournalCodec { - - private static final Set KEYS = - Set.of( - "schemaVersion", - "state", - "operationId", - "requestFingerprint", - "publishedFileName", - "stageFileName", - "byteSize", - "rowCount", - "columnCount", - "sha256", - "formulaMitigatedCount", - "publishedAt", - "publicationGuarantee"); - - private LocalPublicationJournalCodec() {} - - static byte[] encode(LocalPublicationJournalRecord record) { - StringBuilder json = new StringBuilder(768); - json.append('{'); - number(json, "schemaVersion", record.schemaVersion()); - string(json, "state", record.state().name()); - string(json, "operationId", record.operationId()); - string(json, "requestFingerprint", record.requestFingerprint()); - string(json, "publishedFileName", record.publishedFileName()); - string(json, "stageFileName", record.stageFileName()); - number(json, "byteSize", record.byteSize()); - number(json, "rowCount", record.rowCount()); - number(json, "columnCount", record.columnCount()); - string(json, "sha256", record.sha256()); - number(json, "formulaMitigatedCount", record.formulaMitigatedCount()); - string(json, "publishedAt", record.publishedAt()); - string(json, "publicationGuarantee", record.publicationGuarantee()); - json.append("}\n"); - return json.toString().getBytes(StandardCharsets.UTF_8); - } - - static LocalPublicationJournalRecord decode(byte[] bytes) { - try { - Map values = new FlatJsonParser(bytes).parse(); - if (!values.keySet().equals(KEYS)) { - throw new IllegalArgumentException("journal fields do not match schema"); - } - return new LocalPublicationJournalRecord( - integer(values, "schemaVersion"), - LocalPublicationJournalRecord.State.valueOf(values.get("state")), - values.get("operationId"), - values.get("requestFingerprint"), - values.get("publishedFileName"), - values.get("stageFileName"), - longValue(values, "byteSize"), - longValue(values, "rowCount"), - integer(values, "columnCount"), - values.get("sha256"), - longValue(values, "formulaMitigatedCount"), - values.get("publishedAt"), - values.get("publicationGuarantee")); - } catch (RuntimeException exception) { - throw new LocalPublicationJournalException("local publication journal is corrupt", exception); - } - } - - static LocalPublicationJournalRecord decodeCanonical(byte[] bytes) { - try { - StandardCharsets.UTF_8 - .newDecoder() - .onMalformedInput(CodingErrorAction.REPORT) - .onUnmappableCharacter(CodingErrorAction.REPORT) - .decode(ByteBuffer.wrap(bytes)); - LocalPublicationJournalRecord record = decode(bytes); - if (!Arrays.equals(bytes, encode(record))) { - throw new IllegalArgumentException("journal is not canonical"); - } - return record; - } catch (CharacterCodingException | IllegalArgumentException exception) { - throw new LocalPublicationJournalException("local publication journal is corrupt", exception); - } - } - - private static int integer(Map values, String key) { - return Integer.parseInt(values.get(key)); - } - - private static long longValue(Map values, String key) { - return Long.parseLong(values.get(key)); - } - - private static void number(StringBuilder json, String key, long value) { - fieldPrefix(json, key); - json.append(value); - } - - private static void string(StringBuilder json, String key, String value) { - fieldPrefix(json, key); - appendQuoted(json, value); - } - - private static void fieldPrefix(StringBuilder json, String key) { - if (json.length() > 1) { - json.append(','); - } - appendQuoted(json, key); - json.append(':'); - } - - private static void appendQuoted(StringBuilder target, String value) { - target.append('"'); - for (int index = 0; index < value.length(); index++) { - char character = value.charAt(index); - switch (character) { - case '"' -> target.append("\\\""); - case '\\' -> target.append("\\\\"); - case '\b' -> target.append("\\b"); - case '\f' -> target.append("\\f"); - case '\n' -> target.append("\\n"); - case '\r' -> target.append("\\r"); - case '\t' -> target.append("\\t"); - default -> { - if (character < 0x20) { - target.append("\\u%04x".formatted((int) character)); - } else { - target.append(character); - } - } - } - } - target.append('"'); - } - - private static final class FlatJsonParser { - - private static final int MAXIMUM_JOURNAL_BYTES = 16_384; - - private final String input; - private int cursor; - - private FlatJsonParser(byte[] bytes) { - if (bytes.length < 2 || bytes.length > MAXIMUM_JOURNAL_BYTES) { - throw new IllegalArgumentException("journal size is out of bounds"); - } - input = new String(bytes, StandardCharsets.UTF_8); - } - - private Map parse() { - Map values = new LinkedHashMap<>(); - whitespace(); - expect('{'); - whitespace(); - while (!peek('}')) { - String key = quoted(); - if (!KEYS.contains(key)) { - throw new IllegalArgumentException("unknown journal field"); - } - whitespace(); - expect(':'); - whitespace(); - String value = peek('"') ? quoted() : number(); - if (values.putIfAbsent(key, value) != null) { - throw new IllegalArgumentException("duplicate journal field"); - } - whitespace(); - if (peek(',')) { - cursor++; - whitespace(); - } else { - break; - } - } - expect('}'); - whitespace(); - if (cursor != input.length()) { - throw new IllegalArgumentException("trailing journal content"); - } - return values; - } - - private String quoted() { - expect('"'); - StringBuilder value = new StringBuilder(); - while (cursor < input.length()) { - char character = input.charAt(cursor++); - if (character == '"') { - return value.toString(); - } - if (character != '\\') { - if (character < 0x20) { - throw new IllegalArgumentException("unescaped control character"); - } - value.append(character); - continue; - } - if (cursor >= input.length()) { - throw new IllegalArgumentException("truncated escape"); - } - char escape = input.charAt(cursor++); - switch (escape) { - case '"' -> value.append('"'); - case '\\' -> value.append('\\'); - case 'b' -> value.append('\b'); - case 'f' -> value.append('\f'); - case 'n' -> value.append('\n'); - case 'r' -> value.append('\r'); - case 't' -> value.append('\t'); - case 'u' -> value.append(unicode()); - default -> throw new IllegalArgumentException("invalid escape"); - } - } - throw new IllegalArgumentException("unterminated string"); - } - - private char unicode() { - if (cursor + 4 > input.length()) { - throw new IllegalArgumentException("truncated unicode escape"); - } - int value = Integer.parseInt(input.substring(cursor, cursor + 4), 16); - cursor += 4; - return (char) value; - } - - private String number() { - int start = cursor; - if (peek('-')) { - cursor++; - } - while (cursor < input.length() && Character.isDigit(input.charAt(cursor))) { - cursor++; - } - if (cursor == start || (cursor == start + 1 && input.charAt(start) == '-')) { - throw new IllegalArgumentException("invalid number"); - } - return input.substring(start, cursor); - } - - private void whitespace() { - while (cursor < input.length() && Character.isWhitespace(input.charAt(cursor))) { - cursor++; - } - } - - private boolean peek(char expected) { - return cursor < input.length() && input.charAt(cursor) == expected; - } - - private void expect(char expected) { - if (!peek(expected)) { - throw new IllegalArgumentException("unexpected journal token"); - } - cursor++; - } - } -} diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/LocalPublicationJournalException.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/LocalPublicationJournalException.java deleted file mode 100644 index fcc75af5..00000000 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/LocalPublicationJournalException.java +++ /dev/null @@ -1,15 +0,0 @@ -package dev.caskeleton.adapter.outbound.fileserver; - -/** Internal control-plane failure that never includes a filesystem path. */ -final class LocalPublicationJournalException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - LocalPublicationJournalException(String message) { - super(message); - } - - LocalPublicationJournalException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/LocalPublicationJournalRecord.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/LocalPublicationJournalRecord.java deleted file mode 100644 index 91795acb..00000000 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/LocalPublicationJournalRecord.java +++ /dev/null @@ -1,145 +0,0 @@ -package dev.caskeleton.adapter.outbound.fileserver; - -import java.time.Instant; -import java.util.Objects; - -/** Immutable local control record; internal locators are relative file names only. */ -record LocalPublicationJournalRecord( - int schemaVersion, - State state, - String operationId, - String requestFingerprint, - String publishedFileName, - String stageFileName, - long byteSize, - long rowCount, - int columnCount, - String sha256, - long formulaMitigatedCount, - String publishedAt, - String publicationGuarantee) { - - static final int CURRENT_SCHEMA_VERSION = 1; - - LocalPublicationJournalRecord { - if (schemaVersion != CURRENT_SCHEMA_VERSION) { - throw new IllegalArgumentException("unsupported local publication journal schema"); - } - Objects.requireNonNull(state, "state must be non-null"); - requireText(operationId, "operationId", 128); - requireDigest(requestFingerprint, "requestFingerprint"); - requireFileName(publishedFileName, "publishedFileName"); - requireFileName(stageFileName, "stageFileName"); - if (byteSize < 0 || rowCount < 0 || columnCount < 0 || formulaMitigatedCount < 0) { - throw new IllegalArgumentException("journal counts must be non-negative"); - } - if (state != State.WRITING) { - requireDigest(sha256, "sha256"); - if (columnCount < 1) { - throw new IllegalArgumentException("sealed journal columnCount must be positive"); - } - } else if (!sha256.isEmpty()) { - throw new IllegalArgumentException("writing journal must not contain a digest"); - } - if (state == State.PUBLISHED) { - Instant.parse(publishedAt); - if (publicationGuarantee.isBlank()) { - throw new IllegalArgumentException("published journal must contain publicationGuarantee"); - } - } else if (!publishedAt.isEmpty() || !publicationGuarantee.isEmpty()) { - throw new IllegalArgumentException("non-terminal journal must not contain receipt fields"); - } - } - - static LocalPublicationJournalRecord writing( - String operationId, - String requestFingerprint, - String publishedFileName, - String stageFileName) { - return new LocalPublicationJournalRecord( - CURRENT_SCHEMA_VERSION, - State.WRITING, - operationId, - requestFingerprint, - publishedFileName, - stageFileName, - 0, - 0, - 0, - "", - 0, - "", - ""); - } - - static LocalPublicationJournalRecord sealed( - String operationId, - String requestFingerprint, - String publishedFileName, - String stageFileName, - long byteSize, - long rowCount, - int columnCount, - String sha256, - long formulaMitigatedCount) { - return new LocalPublicationJournalRecord( - CURRENT_SCHEMA_VERSION, - State.SEALED, - operationId, - requestFingerprint, - publishedFileName, - stageFileName, - byteSize, - rowCount, - columnCount, - sha256, - formulaMitigatedCount, - "", - ""); - } - - LocalPublicationJournalRecord published(Instant time, String guarantee) { - return new LocalPublicationJournalRecord( - schemaVersion, - State.PUBLISHED, - operationId, - requestFingerprint, - publishedFileName, - stageFileName, - byteSize, - rowCount, - columnCount, - sha256, - formulaMitigatedCount, - Objects.requireNonNull(time, "time must be non-null").toString(), - guarantee); - } - - private static void requireDigest(String value, String field) { - if (value == null || !value.matches("[0-9a-f]{64}")) { - throw new IllegalArgumentException(field + " must be a lowercase SHA-256 digest"); - } - } - - private static void requireFileName(String value, String field) { - requireText(value, field, 256); - if (value.contains("/") || value.contains("\\") || value.equals(".") || value.equals("..")) { - throw new IllegalArgumentException(field + " must be a relative file name"); - } - } - - private static void requireText(String value, String field, int maximumLength) { - if (value == null - || value.isBlank() - || value.length() > maximumLength - || value.chars().anyMatch(Character::isISOControl)) { - throw new IllegalArgumentException(field + " is invalid"); - } - } - - enum State { - WRITING, - SEALED, - PUBLISHED - } -} diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/PrivateFileManifest.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/PrivateFileManifest.java deleted file mode 100644 index 25527a72..00000000 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/PrivateFileManifest.java +++ /dev/null @@ -1,77 +0,0 @@ -package dev.caskeleton.adapter.outbound.fileserver; - -import dev.caskeleton.application.filepublication.FilePublishReceipt.DurabilityGuarantee; -import dev.caskeleton.application.filepublication.FilePublishReceipt.PublicationGuarantee; -import java.time.Instant; -import java.util.Objects; - -/** Provider-private schema-v1 manifest for exact artifact verification and restoration. */ -record PrivateFileManifest( - int schemaVersion, - String operationId, - String fileId, - String providerId, - String fileReference, - String requestFingerprint, - String destinationId, - String schemaId, - int exportSchemaVersion, - String schemaDigest, - String formatProfileId, - String formatPolicyDigest, - String effectivePolicyRevision, - String effectivePolicyDigest, - String publishedFileName, - String fileVersion, - String mediaType, - String charset, - long byteSize, - long rowCount, - int columnCount, - String sha256, - long formulaMitigatedCount, - PublicationGuarantee publicationGuarantee, - DurabilityGuarantee durabilityGuarantee, - String internalLocator, - Instant createdAt, - Instant publishedAt) { - - static final int CURRENT_SCHEMA_VERSION = 1; - - PrivateFileManifest { - if (schemaVersion != CURRENT_SCHEMA_VERSION) { - throw new IllegalArgumentException("unsupported private manifest schema"); - } - FileserverControlRecordCodec.requireText(operationId, "operationId", 128); - FileserverControlRecordCodec.requireFileId(fileId); - FileserverControlRecordCodec.requireLogicalId(providerId, "providerId"); - FileserverControlRecordCodec.requireReferenceMatches(fileReference, fileId, null); - FileserverControlRecordCodec.requireDigest(requestFingerprint, "requestFingerprint"); - FileserverControlRecordCodec.requireLogicalId(destinationId, "destinationId"); - FileserverControlRecordCodec.requireText(schemaId, "schemaId", 128); - if (exportSchemaVersion < 1) { - throw new IllegalArgumentException("exportSchemaVersion must be positive"); - } - FileserverControlRecordCodec.requireDigest(schemaDigest, "schemaDigest"); - FileserverControlRecordCodec.requireText(formatProfileId, "formatProfileId", 128); - FileserverControlRecordCodec.requireDigest(formatPolicyDigest, "formatPolicyDigest"); - FileserverControlRecordCodec.requireText( - effectivePolicyRevision, "effectivePolicyRevision", 128); - FileserverControlRecordCodec.requireDigest(effectivePolicyDigest, "effectivePolicyDigest"); - FileserverControlRecordCodec.requireSegment(publishedFileName, "publishedFileName"); - FileserverControlRecordCodec.requireText(fileVersion, "fileVersion", 128); - FileserverControlRecordCodec.requireText(mediaType, "mediaType", 128); - FileserverControlRecordCodec.requireText(charset, "charset", 64); - if (byteSize < 0 || rowCount < 0 || columnCount < 1 || formulaMitigatedCount < 0) { - throw new IllegalArgumentException("manifest sizes and counts are out of range"); - } - FileserverControlRecordCodec.requireFormulaCountWithinCells( - rowCount, columnCount, formulaMitigatedCount, "manifest"); - FileserverControlRecordCodec.requireDigest(sha256, "sha256"); - Objects.requireNonNull(publicationGuarantee, "publicationGuarantee must be non-null"); - Objects.requireNonNull(durabilityGuarantee, "durabilityGuarantee must be non-null"); - FileserverControlRecordCodec.requireSegment(internalLocator, "internalLocator"); - FileserverControlRecordCodec.requireInstant(createdAt, "createdAt"); - FileserverControlRecordCodec.requireOrderedInstant(createdAt, publishedAt, "publishedAt"); - } -} diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/PublishedReferenceRecord.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/PublishedReferenceRecord.java deleted file mode 100644 index 6061c918..00000000 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/PublishedReferenceRecord.java +++ /dev/null @@ -1,48 +0,0 @@ -package dev.caskeleton.adapter.outbound.fileserver; - -import java.time.Instant; - -/** Schema-v1 direct reference index from an opaque file ID to provider-private metadata. */ -record PublishedReferenceRecord( - int schemaVersion, - String fileId, - String routeToken, - String fileReference, - String operationId, - String fileVersion, - String manifestDigest, - String internalLocator, - String destinationId, - String providerId, - String publishedFileName, - String mediaType, - String charset, - long byteSize, - String sha256, - Instant publishedAt) { - - static final int CURRENT_SCHEMA_VERSION = 1; - - PublishedReferenceRecord { - if (schemaVersion != CURRENT_SCHEMA_VERSION) { - throw new IllegalArgumentException("unsupported published reference record schema"); - } - FileserverControlRecordCodec.requireFileId(fileId); - FileserverControlRecordCodec.requireRouteToken(routeToken); - FileserverControlRecordCodec.requireReferenceMatches(fileReference, fileId, routeToken); - FileserverControlRecordCodec.requireText(operationId, "operationId", 128); - FileserverControlRecordCodec.requireText(fileVersion, "fileVersion", 128); - FileserverControlRecordCodec.requireDigest(manifestDigest, "manifestDigest"); - FileserverControlRecordCodec.requireSegment(internalLocator, "internalLocator"); - FileserverControlRecordCodec.requireLogicalId(destinationId, "destinationId"); - FileserverControlRecordCodec.requireLogicalId(providerId, "providerId"); - FileserverControlRecordCodec.requireSegment(publishedFileName, "publishedFileName"); - FileserverControlRecordCodec.requireText(mediaType, "mediaType", 128); - FileserverControlRecordCodec.requireText(charset, "charset", 64); - if (byteSize < 0) { - throw new IllegalArgumentException("reference byteSize must be non-negative"); - } - FileserverControlRecordCodec.requireDigest(sha256, "sha256"); - FileserverControlRecordCodec.requireInstant(publishedAt, "publishedAt"); - } -} diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/R2PublishedReferenceCodec.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/R2PublishedReferenceCodec.java deleted file mode 100644 index a722a598..00000000 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/R2PublishedReferenceCodec.java +++ /dev/null @@ -1,79 +0,0 @@ -package dev.caskeleton.adapter.outbound.fileserver; - -import dev.caskeleton.application.filepublication.PublishedFileReference; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.HexFormat; -import java.util.Objects; -import java.util.Set; - -/** Strict codec for the provider-neutral R2 opaque published-file reference. */ -final class R2PublishedReferenceCodec { - - private static final String VERSION = "fsr1"; - private static final String ROUTE_PATTERN = "[a-z][a-z0-9]{5,31}"; - private static final String FILE_ID_PATTERN = "[0-9a-f]{32}"; - private static final String CHECK_PATTERN = "[0-9a-f]{12}"; - - PublishedFileReference encode(String routeToken, String fileId) { - requireRouteToken(routeToken); - requireFileId(fileId); - String prefix = VERSION + "." + routeToken + "." + fileId; - return new PublishedFileReference(prefix + "." + checkDigits(prefix)); - } - - DecodedReference decode(PublishedFileReference reference, Set allowedRouteTokens) { - Objects.requireNonNull(reference, "reference must be non-null"); - Objects.requireNonNull(allowedRouteTokens, "allowedRouteTokens must be non-null"); - if (allowedRouteTokens.isEmpty()) { - throw new IllegalArgumentException("route allowlist must not be empty"); - } - allowedRouteTokens.forEach(R2PublishedReferenceCodec::requireRouteToken); - - String[] segments = reference.value().split("\\.", -1); - if (segments.length != 4 - || !VERSION.equals(segments[0]) - || !segments[1].matches(ROUTE_PATTERN) - || !segments[2].matches(FILE_ID_PATTERN) - || !segments[3].matches(CHECK_PATTERN)) { - throw new IllegalArgumentException("published file reference is malformed"); - } - if (!allowedRouteTokens.contains(segments[1])) { - throw new IllegalArgumentException("published file reference route is not allowed"); - } - - String prefix = segments[0] + "." + segments[1] + "." + segments[2]; - byte[] expected = checkDigits(prefix).getBytes(StandardCharsets.US_ASCII); - byte[] supplied = segments[3].getBytes(StandardCharsets.US_ASCII); - if (!MessageDigest.isEqual(expected, supplied)) { - throw new IllegalArgumentException("published file reference check digits do not match"); - } - return new DecodedReference(segments[1], segments[2]); - } - - private static void requireRouteToken(String routeToken) { - if (routeToken == null || !routeToken.matches(ROUTE_PATTERN)) { - throw new IllegalArgumentException("routeToken must match " + ROUTE_PATTERN); - } - } - - private static void requireFileId(String fileId) { - if (fileId == null || !fileId.matches(FILE_ID_PATTERN)) { - throw new IllegalArgumentException( - "fileId must be exactly 32 lowercase hexadecimal characters"); - } - } - - private static String checkDigits(String prefix) { - try { - byte[] digest = - MessageDigest.getInstance("SHA-256").digest(prefix.getBytes(StandardCharsets.UTF_8)); - return HexFormat.of().formatHex(digest, 0, 6); - } catch (NoSuchAlgorithmException exception) { - throw new IllegalStateException("SHA-256 is unavailable", exception); - } - } - - record DecodedReference(String routeToken, String fileId) {} -} diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/RoutingFilePublicationAdapter.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/RoutingFilePublicationAdapter.java deleted file mode 100644 index 4cb36960..00000000 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/RoutingFilePublicationAdapter.java +++ /dev/null @@ -1,42 +0,0 @@ -package dev.caskeleton.adapter.outbound.fileserver; - -import dev.caskeleton.application.filepublication.FileDestinationId; -import dev.caskeleton.application.filepublication.FilePublicationException; -import dev.caskeleton.application.filepublication.FilePublicationPort; -import dev.caskeleton.application.filepublication.FilePublishReceipt; -import dev.caskeleton.application.filepublication.FilePublishRequest; -import dev.caskeleton.application.filepublication.TabularRowProducer; -import java.util.Map; -import java.util.Objects; - -/** Exact destination router with no default or fallback provider. */ -final class RoutingFilePublicationAdapter implements FilePublicationPort { - - private final Map routes; - - RoutingFilePublicationAdapter(Map routes) { - this.routes = Map.copyOf(Objects.requireNonNull(routes, "routes must be non-null")); - if (this.routes.isEmpty()) { - throw new IllegalArgumentException("fileserver routing requires at least one destination"); - } - } - - @Override - public FilePublishReceipt publish(FilePublishRequest request, TabularRowProducer producer) { - if (request == null) { - throw invalidRequest("file publication request must be non-null"); - } - if (producer == null) { - throw invalidRequest("file publication producer must be non-null"); - } - FilePublicationProvider provider = routes.get(request.destinationId()); - if (provider == null) { - throw invalidRequest("file publication destination is not configured"); - } - return provider.publish(request, producer); - } - - private static FilePublicationException invalidRequest(String message) { - return new FilePublicationException(FilePublicationException.Reason.INVALID_REQUEST, message); - } -} diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/StreamingCsvEncoder.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/StreamingCsvEncoder.java deleted file mode 100644 index 140dca95..00000000 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/StreamingCsvEncoder.java +++ /dev/null @@ -1,190 +0,0 @@ -package dev.caskeleton.adapter.outbound.fileserver; - -import dev.caskeleton.application.filepublication.ExportSchema; -import dev.caskeleton.application.filepublication.FilePublicationException; -import dev.caskeleton.application.filepublication.TabularCell; -import dev.caskeleton.application.filepublication.TabularCell.BooleanCell; -import dev.caskeleton.application.filepublication.TabularCell.DateCell; -import dev.caskeleton.application.filepublication.TabularCell.DecimalCell; -import dev.caskeleton.application.filepublication.TabularCell.InstantCell; -import dev.caskeleton.application.filepublication.TabularCell.IntegerCell; -import dev.caskeleton.application.filepublication.TabularCell.NullCell; -import dev.caskeleton.application.filepublication.TabularCell.TextCell; -import dev.caskeleton.application.filepublication.TabularRow; -import java.io.IOException; -import java.io.OutputStream; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.util.HexFormat; -import java.util.List; - -/** Attempt-scoped row-at-a-time RFC-4180 encoder with schema and byte bounds. */ -final class StreamingCsvEncoder { - - private static final HexFormat HEX = HexFormat.of(); - - private final ExportSchema schema; - private final OutputStream output; - private final MessageDigest digest; - private final long maximumRows; - private final long maximumBytes; - - private long bytesWritten; - private long rowsWritten; - private long formulaMitigated; - - StreamingCsvEncoder( - ExportSchema schema, - OutputStream output, - MessageDigest digest, - long maximumRows, - long maximumBytes) { - this.schema = schema; - this.output = output; - this.digest = digest; - this.maximumRows = maximumRows; - this.maximumBytes = maximumBytes; - } - - void writeHeader() { - writeRecord(schema.columns().stream().map(ExportSchema.Column::name).toList()); - } - - void write(TabularRow row) { - checkpoint(); - if (rowsWritten >= maximumRows) { - throw failure( - FilePublicationException.Reason.CAPACITY_EXCEEDED, "file publication row limit exceeded"); - } - List cells = row.cells(); - if (cells.size() != schema.columns().size()) { - throw failure( - FilePublicationException.Reason.INVALID_REQUEST, - "row column count does not match schema"); - } - String[] values = new String[cells.size()]; - for (int index = 0; index < cells.size(); index++) { - values[index] = encodeCell(cells.get(index), schema.columns().get(index)); - } - writeRecord(List.of(values)); - rowsWritten++; - checkpoint(); - } - - void checkpoint() { - if (Thread.currentThread().isInterrupted()) { - throw failure(FilePublicationException.Reason.CANCELLED, "file publication cancelled"); - } - } - - Stats finish() { - return new Stats(bytesWritten, rowsWritten, formulaMitigated, HEX.formatHex(digest.digest())); - } - - private String encodeCell(TabularCell cell, ExportSchema.Column column) { - if (cell instanceof NullCell) { - if (!column.nullable()) { - throw failure( - FilePublicationException.Reason.INVALID_REQUEST, - "null cell is not allowed for column " + column.name()); - } - return ""; - } - if (cell.cellType() != column.cellType()) { - throw failure( - FilePublicationException.Reason.INVALID_REQUEST, - "cell type does not match schema column " + column.name()); - } - - String rendered = - switch (cell) { - case TextCell text -> encodeText(text.value(), column); - case IntegerCell integer -> Long.toString(integer.value()); - case DecimalCell decimal -> decimal.value().toPlainString(); - case BooleanCell bool -> Boolean.toString(bool.value()); - case DateCell date -> date.value().toString(); - case InstantCell instant -> instant.value().toString(); - case NullCell ignored -> throw new IllegalStateException("handled above"); - }; - - int bytes = rendered.getBytes(StandardCharsets.UTF_8).length; - if (bytes > column.maximumUtf8Bytes()) { - throw failure( - FilePublicationException.Reason.CAPACITY_EXCEEDED, - "cell byte limit exceeded for column " + column.name()); - } - return rendered; - } - - private String encodeText(String value, ExportSchema.Column column) { - if (!isFormulaCandidate(value)) { - return value; - } - return switch (column.formulaPolicy()) { - case ALLOW -> value; - case MITIGATE -> { - formulaMitigated++; - yield "'" + value; - } - case REJECT -> - throw failure( - FilePublicationException.Reason.INVALID_REQUEST, - "spreadsheet formula text rejected for column " + column.name()); - }; - } - - private void writeRecord(List fields) { - StringBuilder row = new StringBuilder(); - for (int index = 0; index < fields.size(); index++) { - if (index > 0) { - row.append(','); - } - row.append(escape(fields.get(index))); - } - row.append('\n'); - writeBytes(row.toString().getBytes(StandardCharsets.UTF_8)); - } - - private void writeBytes(byte[] bytes) { - if (bytesWritten > maximumBytes - bytes.length) { - throw failure( - FilePublicationException.Reason.CAPACITY_EXCEEDED, - "file publication byte limit exceeded"); - } - try { - output.write(bytes); - digest.update(bytes); - bytesWritten += bytes.length; - } catch (IOException exception) { - throw new FilePublicationException( - FilePublicationException.Reason.UNAVAILABLE, "file publication write failed", exception); - } - } - - private static String escape(String value) { - if (value.contains(",") - || value.contains("\"") - || value.contains("\n") - || value.contains("\r")) { - return '"' + value.replace("\"", "\"\"") + '"'; - } - return value; - } - - private static boolean isFormulaCandidate(String value) { - if (value.isEmpty()) { - return false; - } - return switch (value.charAt(0)) { - case '=', '+', '-', '@', '\t', '\r' -> true; - default -> false; - }; - } - - private static FilePublicationException failure( - FilePublicationException.Reason reason, String message) { - return new FilePublicationException(reason, message); - } - - record Stats(long byteSize, long rowCount, long formulaMitigatedCount, String sha256) {} -} diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/autoconfigure/FileserverCapabilityAutoConfiguration.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/autoconfigure/FileserverCapabilityAutoConfiguration.java index 7ed0425b..0e2ac37b 100644 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/autoconfigure/FileserverCapabilityAutoConfiguration.java +++ b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/autoconfigure/FileserverCapabilityAutoConfiguration.java @@ -21,17 +21,18 @@ import org.springframework.core.env.Environment; * below, not by naming the configurations, so adding or splitting one of them here is no longer a * change to app-bootstrap's compile. * - *

Registered through this leaf's {@code AutoConfiguration.imports}. The master switch is carried - * here rather than assumed, so a deployment that never turned the platform on assembles nothing - * from this leaf — and, because the settings are bound here rather than by the application-wide - * properties scan, it does not even bind, let alone reject, a Fileserver configuration block it - * never enabled. + *

Registered through this leaf's {@code AutoConfiguration.imports}. The capability switch is + * carried here rather than assumed, so a deployment that never turned the platform on assembles + * nothing from this leaf — and, because the settings are bound here rather than by the + * application-wide properties scan, it does not even bind, let alone reject, a Fileserver + * configuration block it never enabled. */ @AutoConfiguration @ConditionalOnProperty( prefix = FileserverPlatformSettings.PREFIX, name = "enabled", - havingValue = "true") + havingValue = "true", + matchIfMissing = true) // Listed concretely rather than through the two aggregators that used to hold them. Those // aggregators each mixed a leaf-internal concern with one that needs a sibling adapter — the JPA // metadata store, the identifier generator — so they could not move as a unit, and a grouping that @@ -48,7 +49,7 @@ import org.springframework.core.env.Environment; public class FileserverCapabilityAutoConfiguration { /** - * Binds the platform settings once the master switch has already been proven true. + * Binds the platform settings once the capability switch has already been proven true. * *

Binding is deliberately not delegated to {@code @ConfigurationPropertiesScan}: that would * bind — and reject — Fileserver detail settings in deployments that never switched the diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/autoconfigure/FileserverPlatformSettings.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/autoconfigure/FileserverPlatformSettings.java index 55d03a7d..869e9d85 100644 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/autoconfigure/FileserverPlatformSettings.java +++ b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/autoconfigure/FileserverPlatformSettings.java @@ -25,11 +25,12 @@ import org.springframework.util.unit.DataSize; * the cross-field rules (a core pool larger than its maximum, a soft water mark above the hard one) * that per-field constraints cannot. * - * @param enabled master switch for the whole capability + * @param enabled capability switch for the whole capability; on unless set to {@code false}, + * because an application that selected this capability wants it * @param instanceId writer-lease owner for this node; must be unique per instance */ public record FileserverPlatformSettings( - @DefaultValue("false") boolean enabled, + @DefaultValue("true") boolean enabled, @DefaultValue("local-node") String instanceId, @DefaultValue("default") String defaultNamespace, @DefaultValue Storage storage, diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalAppendEngine.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalAppendEngine.java index ad9f55ba..0954d126 100644 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalAppendEngine.java +++ b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalAppendEngine.java @@ -6,6 +6,7 @@ import dev.caskeleton.application.fileserver.api.error.AmbiguousCompletionExcept import dev.caskeleton.application.fileserver.api.error.FileTooLargeException; import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode; import dev.caskeleton.application.fileserver.api.error.FileserverFailureContext; +import dev.caskeleton.application.fileserver.api.error.IntegrityMismatchException; import dev.caskeleton.application.fileserver.api.error.PartialWriteException; import dev.caskeleton.application.fileserver.api.error.UploadOffsetMismatchException; import java.io.IOException; @@ -13,6 +14,7 @@ import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.ReadableByteChannel; import java.nio.file.Path; +import java.util.Optional; /** * Sequential, bounded-memory append with a running SHA-256. @@ -23,12 +25,13 @@ import java.nio.file.Path; * write cannot inflate a resumable position. * *

An append is all-or-nothing against the physical object. A request that turns out to be - * overlong, short, or that fails mid-transfer is rolled back to the offset it started from, because - * the caller only commits the new offset on success: leaving the surplus bytes on disk would make - * the metadata offset and the physical length disagree permanently, and every subsequent retry - * would be refused for a mismatch the client cannot repair. When the rollback itself cannot be - * proven the failure is escalated to an ambiguous outcome rather than reported as a plain - * rejection, since only reconciliation can settle what is actually on the volume. + * overlong, short, fails its client chunk checksum, or fails mid-transfer is rolled back to the + * offset it started from, because the caller only commits the new offset on success: leaving the + * surplus bytes on disk would make the metadata offset and the physical length disagree + * permanently, and every subsequent retry would be refused for a mismatch the client cannot repair. + * When the rollback itself cannot be proven the failure is escalated to an ambiguous outcome rather + * than reported as a plain rejection, since only reconciliation can settle what is actually on the + * volume. */ final class LocalAppendEngine { @@ -48,6 +51,7 @@ final class LocalAppendEngine { long expectedOffset, ReadableByteChannel source, long contentLength, + Optional expectedChunkSha256, WriteFence fence) { Path staging = handle.stagingPath(); fence.requireStillOwned(); @@ -56,6 +60,10 @@ final class LocalAppendEngine { handle .digestAt(expectedOffset) .orElseGet(() -> rehashPrefix(root, staging, expectedOffset)); + // Separate from the running digest: a client checksum describes this request's bytes, never + // the object from byte 0. Only computed when there is something to compare it with. + Optional chunkDigest = + expectedChunkSha256.map(ignored -> StreamingDigest.empty()); try (FileChannel target = channels.openForWrite(root, staging)) { requireOffset(handle, expectedOffset, target.size()); @@ -63,7 +71,11 @@ final class LocalAppendEngine { long appended; try { appended = - copyAndDigest(target, source, digest, contentLength, handle.maximumLength(), fence); + copyAndDigest( + target, source, digest, chunkDigest, contentLength, handle.maximumLength(), fence); + // Inside the rollback boundary: a chunk that fails its checksum is truncated away like a + // short or overlong body, so the caller never commits an offset past it. + requireChunkChecksum(handle, chunkDigest, expectedChunkSha256); } catch (IOException | RuntimeException failure) { throw rollback(handle, target, expectedOffset, failure); } @@ -113,6 +125,19 @@ final class LocalAppendEngine { FileserverErrorCode.AMBIGUOUS_COMPLETION, handle.uploadId(), false, true, true)); } + private static void requireChunkChecksum( + LocalUploadHandle handle, + Optional chunkDigest, + Optional expectedChunkSha256) { + if (expectedChunkSha256.isPresent() + && !chunkDigest.orElseThrow().hex().equalsIgnoreCase(expectedChunkSha256.get())) { + throw new IntegrityMismatchException( + "client chunk checksum does not match the server-computed digest of the chunk", + FileserverFailureContext.forUpload( + FileserverErrorCode.CHECKSUM_MISMATCH, handle.uploadId(), false, false, false)); + } + } + private static void requireOffset( LocalUploadHandle handle, long expectedOffset, long actualOffset) { if (actualOffset != expectedOffset) { @@ -181,6 +206,7 @@ final class LocalAppendEngine { FileChannel target, ReadableByteChannel source, StreamingDigest digest, + Optional chunkDigest, long contentLength, long maximumFileSize, WriteFence fence) @@ -217,6 +243,10 @@ final class LocalAppendEngine { buffer.rewind(); buffer.limit(written); digest.update(buffer); + if (chunkDigest.isPresent()) { + buffer.rewind(); + chunkDigest.get().update(buffer); + } appended += written; } if (contentLength >= 0 && appended != contentLength) { diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalBlockingContentStore.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalBlockingContentStore.java index 6d8f1859..db90db8d 100644 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalBlockingContentStore.java +++ b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalBlockingContentStore.java @@ -31,6 +31,7 @@ import java.nio.file.attribute.BasicFileAttributes; import java.time.Instant; import java.util.Arrays; import java.util.Locale; +import java.util.Optional; /** * Local filesystem implementation of the blocking storage SPI. @@ -126,9 +127,29 @@ public final class LocalBlockingContentStore implements BlockingContentStore { ReadableByteChannel source, long contentLength, WriteFence fence) { + return append(handle, expectedOffset, source, contentLength, Optional.empty(), fence); + } + + /** + * Appends and rejects, with the bytes rolled back, a request whose own digest differs from {@code + * expectedChunkSha256}. + */ + public AppendResult append( + UploadHandle handle, + long expectedOffset, + ReadableByteChannel source, + long contentLength, + Optional expectedChunkSha256, + WriteFence fence) { LocalUploadHandle local = UploadHandle.requireOwn(handle, LocalUploadHandle.class); return appendEngine.append( - properties.root(), local, expectedOffset, source, contentLength, fence); + properties.root(), + local, + expectedOffset, + source, + contentLength, + expectedChunkSha256, + fence); } @Override diff --git a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalUploadStorageGateway.java b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalUploadStorageGateway.java index 16b82d16..91c6779b 100644 --- a/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalUploadStorageGateway.java +++ b/src/adapter/outbound/fileserver/src/main/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalUploadStorageGateway.java @@ -8,6 +8,7 @@ import dev.caskeleton.application.fileserver.api.content.UploadHandle; import dev.caskeleton.application.fileserver.api.content.WriteFence; import dev.caskeleton.application.fileserver.upload.UploadStorageGateway; import java.nio.channels.ReadableByteChannel; +import java.util.Optional; import java.util.OptionalLong; /** @@ -46,8 +47,9 @@ public final class LocalUploadStorageGateway implements UploadStorageGateway { long expectedOffset, ReadableByteChannel source, long contentLength, + Optional expectedChunkSha256, WriteFence fence) { - return store.append(handle, expectedOffset, source, contentLength, fence); + return store.append(handle, expectedOffset, source, contentLength, expectedChunkSha256, fence); } @Override diff --git a/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/FilePublicationConfigTest.java b/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/FilePublicationConfigTest.java deleted file mode 100644 index 882b767c..00000000 --- a/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/FilePublicationConfigTest.java +++ /dev/null @@ -1,110 +0,0 @@ -package dev.caskeleton.adapter.outbound.fileserver; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.application.fileexport.FileExportPort; -import dev.caskeleton.application.filepublication.FilePublicationPort; -import java.nio.file.Files; -import java.nio.file.Path; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; -import org.springframework.boot.test.context.runner.ApplicationContextRunner; - -@SuppressWarnings("removal") -class FilePublicationConfigTest { - - @TempDir Path tempDir; - - private final ApplicationContextRunner runner = - new ApplicationContextRunner().withUserConfiguration(FileExportConfig.class); - - @Test - void remainsDisabledUnlessExplicitlyEnabled() { - runner.run( - context -> { - assertThat(context).doesNotHaveBean(FileExportSettings.class); - assertThat(context).doesNotHaveBean(FileExportPort.class); - assertThat(context).doesNotHaveBean(FilePublicationPort.class); - }); - } - - @Test - void bindsPublicationLimitsAndContributesOnlyTheStreamingPortByDefault() { - runner - .withPropertyValues( - "app.file-export.enabled=true", - "app.file-export.base-directory=build/test-files", - "app.file-export.destination-id=nightly-export", - "app.file-export.maximum-rows=125", - "app.file-export.maximum-encoded-bytes=4096") - .run( - context -> { - assertThat(context).doesNotHaveBean(FileExportPort.class); - assertThat(context).hasSingleBean(FilePublicationPort.class); - - FileExportSettings properties = context.getBean(FileExportSettings.class); - assertThat(properties.getDestinationId()).isEqualTo("nightly-export"); - assertThat(properties.getMaximumRows()).isEqualTo(125); - assertThat(properties.getMaximumEncodedBytes()).isEqualTo(4096); - }); - } - - @Test - void legacyPortRequiresItsOwnOptInAndSeparateRoot() { - runner - .withPropertyValues( - "app.file-export.enabled=true", - "app.file-export.base-directory=build/test-files", - "app.file-export.legacy-enabled=true", - "app.file-export.legacy-base-directory=build/test-files-legacy") - .run( - context -> { - assertThat(context).hasSingleBean(FileExportPort.class); - assertThat(context).hasSingleBean(FilePublicationPort.class); - FileExportSettings properties = context.getBean(FileExportSettings.class); - assertThat(properties.getLegacyBaseDirectory()).isEqualTo("build/test-files-legacy"); - }); - } - - @Test - void rejectsBlankPublicationRootAndOverlappingLegacyRoot() { - runner - .withPropertyValues("app.file-export.enabled=true", "app.file-export.base-directory= ") - .run(context -> assertThat(context).hasFailed()); - - runner - .withPropertyValues( - "app.file-export.enabled=true", - "app.file-export.legacy-enabled=true", - "app.file-export.base-directory=build/shared-files", - "app.file-export.legacy-base-directory=build/shared-files/legacy") - .run( - context -> - assertThat(context) - .hasFailed() - .getFailure() - .hasRootCauseMessage( - "fileserver publication and legacy roots must not overlap")); - } - - @Test - void rejectsLegacyRootThatAliasesThePublicationRootThroughASymbolicLink() throws Exception { - Path publicationRoot = Files.createDirectory(tempDir.resolve("publication")); - Path legacyAlias = tempDir.resolve("legacy-alias"); - Files.createSymbolicLink(legacyAlias, publicationRoot); - - runner - .withPropertyValues( - "app.file-export.enabled=true", - "app.file-export.legacy-enabled=true", - "app.file-export.base-directory=" + publicationRoot, - "app.file-export.legacy-base-directory=" + legacyAlias) - .run( - context -> - assertThat(context) - .hasFailed() - .getFailure() - .hasRootCauseMessage( - "fileserver publication and legacy roots must not overlap")); - } -} diff --git a/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/FileserverBindingCompilerTest.java b/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/FileserverBindingCompilerTest.java deleted file mode 100644 index c5ad0512..00000000 --- a/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/FileserverBindingCompilerTest.java +++ /dev/null @@ -1,969 +0,0 @@ -package dev.caskeleton.adapter.outbound.fileserver; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.application.filepublication.ExportSchema; -import dev.caskeleton.application.filepublication.ExportSchema.CellType; -import dev.caskeleton.application.filepublication.ExportSchema.Column; -import dev.caskeleton.application.filepublication.ExportSchema.FormulaPolicy; -import dev.caskeleton.application.filepublication.FileDestinationId; -import dev.caskeleton.application.filepublication.FilePublishReceipt.DurabilityGuarantee; -import dev.caskeleton.application.filepublication.FilePublishReceipt.PublicationGuarantee; -import java.nio.file.Path; -import java.nio.file.attribute.PosixFilePermission; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; -import org.junit.jupiter.api.parallel.ResourceLock; -import org.springframework.boot.context.properties.bind.Bindable; -import org.springframework.boot.context.properties.bind.Binder; -import org.springframework.boot.context.properties.source.MapConfigurationPropertySource; - -class FileserverBindingCompilerTest { - - private static final String SENTINEL_SHA256 = - "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; - - @TempDir Path tempDirectory; - - @Test - void disabledEmptySettingsCompileToAnImmutableEmptyMapWithoutCreatingDirectories() { - Path undeclaredRoot = tempDirectory.resolve("must-not-be-created"); - - Map result = - FileserverBindingCompiler.compile(new FileserverR2Settings(false, null, null)); - - assertThat(result).isEmpty(); - assertThatThrownBy( - () -> - result.put( - new FileDestinationId("unexpected"), - compiledDestinationFor(undeclaredRoot.toAbsolutePath()))) - .isInstanceOf(UnsupportedOperationException.class); - assertThat(undeclaredRoot).doesNotExist(); - } - - @Test - void settingsDefensivelyCopyMapsAndConvertNullMapsToEmptyMaps() { - Map destinations = new LinkedHashMap<>(); - Map providers = new LinkedHashMap<>(); - destinations.put("local-export", destination("local-primary")); - providers.put("local-primary", provider(tempDirectory.resolve("root").toAbsolutePath())); - - FileserverR2Settings settings = new FileserverR2Settings(true, destinations, providers); - destinations.clear(); - providers.clear(); - - assertThat(settings.destinations()).containsOnlyKeys("local-export"); - assertThat(settings.providers()).containsOnlyKeys("local-primary"); - assertThat(new FileserverR2Settings(false, null, null).destinations()).isEmpty(); - assertThat(new FileserverR2Settings(false, null, null).providers()).isEmpty(); - assertThatThrownBy(() -> settings.destinations().clear()) - .isInstanceOf(UnsupportedOperationException.class); - } - - @Test - void springBootBinderBindsNestedDestinationAndProviderMapsBeforeCompilation() { - Path root = tempDirectory.resolve("bound-root").toAbsolutePath(); - Map properties = new LinkedHashMap<>(); - properties.put("app.fileserver.enabled", "true"); - properties.put("app.fileserver.destinations.local-export.provider-ref", "local-primary"); - properties.put( - "app.fileserver.destinations.local-export.required-publication", "unique-atomic-create"); - properties.put( - "app.fileserver.destinations.local-export.required-durability", "file-and-directory-sync"); - properties.put("app.fileserver.destinations.local-export.maximum-rows", "125"); - properties.put("app.fileserver.destinations.local-export.maximum-encoded-bytes", "4096"); - properties.put("app.fileserver.providers.local-primary.type", "local-persistent"); - properties.put("app.fileserver.providers.local-primary.root-directory", root.toString()); - properties.put("app.fileserver.providers.local-primary.auto-create", "false"); - properties.put("app.fileserver.providers.local-primary.strict-path-security", "true"); - properties.put( - "app.fileserver.providers.local-primary.expected-file-store-name", "expected-store"); - properties.put( - "app.fileserver.providers.local-primary.expected-file-store-type", "expected-type"); - properties.put( - "app.fileserver.providers.local-primary.mount-sentinel-name", ".ca-fileserver-volume"); - properties.put("app.fileserver.providers.local-primary.mount-sentinel-sha256", SENTINEL_SHA256); - properties.put("app.fileserver.providers.local-primary.expected-owner", "fileserver"); - properties.put("app.fileserver.providers.local-primary.maximum-root-mode", "0750"); - - FileserverR2Settings settings = - new Binder(new MapConfigurationPropertySource(properties)) - .bind("app.fileserver", Bindable.of(FileserverR2Settings.class)) - .orElseThrow(() -> new AssertionError("app.fileserver settings were not bound")); - Map compiled = - FileserverBindingCompiler.compile(settings); - - assertThat(compiled).containsOnlyKeys(new FileDestinationId("local-export")); - assertThat(compiled.get(new FileDestinationId("local-export"))) - .satisfies( - destination -> { - assertThat(destination.providerId()).isEqualTo("local-primary"); - assertThat(destination.rootDirectory()).isEqualTo(root); - assertThat(destination.maximumRows()).isEqualTo(125); - assertThat(destination.maximumEncodedBytes()).isEqualTo(4096); - }); - } - - @Test - void enabledSettingsRequireAnExplicitDestination() { - FileserverR2Settings settings = - new FileserverR2Settings( - true, - Map.of(), - Map.of("local-primary", provider(tempDirectory.resolve("root").toAbsolutePath()))); - - assertThatThrownBy(() -> FileserverBindingCompiler.compile(settings)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("destination"); - } - - @Test - void enabledSettingsRequireAnExplicitProvider() { - FileserverR2Settings settings = - new FileserverR2Settings( - true, Map.of("local-export", destination("local-primary")), Map.of()); - - assertThatThrownBy(() -> FileserverBindingCompiler.compile(settings)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("provider"); - } - - @Test - void rejectsUnknownProviderReference() { - FileserverR2Settings settings = - enabled( - Map.of("local-export", destination("missing")), - Map.of("local-primary", provider(tempDirectory.resolve("root").toAbsolutePath()))); - - assertThatThrownBy(() -> FileserverBindingCompiler.compile(settings)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("missing"); - } - - @Test - void rejectsEveryProviderTypeExceptExactLocalPersistent() { - for (String type : - new String[] {"shared-mounted", "sftp", "LOCAL-PERSISTENT", "local-persistent "}) { - FileserverR2Settings settings = - enabled( - Map.of("local-export", destination("local-primary")), - Map.of( - "local-primary", provider(tempDirectory.resolve("root").toAbsolutePath(), type))); - - assertThatThrownBy(() -> FileserverBindingCompiler.compile(settings)) - .as("provider type %s", type) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("local-persistent"); - } - } - - @Test - void compilesOnlyTheDeclaredExactBinding() { - Path root = tempDirectory.resolve("root").toAbsolutePath().normalize(); - - Map result = - FileserverBindingCompiler.compile(validSettings(root)); - - FileDestinationId destinationId = new FileDestinationId("local-export"); - assertThat(result).containsOnlyKeys(destinationId); - assertThat(result.get(destinationId)) - .satisfies( - destination -> { - assertThat(destination.destinationId()).isEqualTo(destinationId); - assertThat(destination.providerId()).isEqualTo("local-primary"); - assertThat(destination.rootDirectory()).isEqualTo(root); - assertThat(destination.maximumRows()).isEqualTo(1_000_000); - assertThat(destination.maximumEncodedBytes()).isEqualTo(1_073_741_824); - assertThat(destination.expectedFileStoreName()).isEqualTo("expected-store"); - assertThat(destination.expectedFileStoreType()).isEqualTo("expected-type"); - assertThat(destination.mountSentinelName()).isEqualTo(".ca-fileserver-volume"); - assertThat(destination.mountSentinelSha256()).isEqualTo(SENTINEL_SHA256); - assertThat(destination.expectedOwner()).isEqualTo("fileserver"); - assertThat(destination.maximumRootMode()).isEqualTo("0750"); - assertThat(destination.maximumRootPermissions()) - .containsExactlyInAnyOrder( - PosixFilePermission.OWNER_READ, - PosixFilePermission.OWNER_WRITE, - PosixFilePermission.OWNER_EXECUTE, - PosixFilePermission.GROUP_READ, - PosixFilePermission.GROUP_EXECUTE); - assertThat(destination.requiredPublicationGuarantee()) - .isEqualTo(PublicationGuarantee.UNIQUE_ATOMIC_CREATE); - assertThat(destination.requiredDurabilityGuarantee()) - .isEqualTo(DurabilityGuarantee.FILE_AND_DIRECTORY_SYNC); - }); - } - - @Test - void trimsIdentifiersButRejectsBlankDestinationProviderAndProviderReferenceIds() { - assertThat( - FileserverBindingCompiler.compile( - validSettingsWithIds(" local-export ", " local-primary "))) - .containsOnlyKeys(new FileDestinationId("local-export")); - - assertThatThrownBy( - () -> - FileserverBindingCompiler.compile( - enabled( - Map.of(" ", destination("local-primary")), - Map.of( - "local-primary", - provider(tempDirectory.resolve("root").toAbsolutePath()))))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("destination"); - - assertThatThrownBy( - () -> - FileserverBindingCompiler.compile( - enabled( - Map.of("local-export", destination("local-primary")), - Map.of(" ", provider(tempDirectory.resolve("root").toAbsolutePath()))))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("provider"); - - assertThatThrownBy( - () -> - FileserverBindingCompiler.compile( - enabled( - Map.of("local-export", destination(" ")), - Map.of( - "local-primary", - provider(tempDirectory.resolve("root").toAbsolutePath()))))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("provider-ref"); - } - - @Test - void rejectsDuplicateDestinationAndProviderIdsAfterTrimming() { - Map destinations = new LinkedHashMap<>(); - destinations.put("local-export", destination("local-primary")); - destinations.put(" local-export ", destination("local-primary")); - - assertThatThrownBy( - () -> - FileserverBindingCompiler.compile( - enabled( - destinations, - Map.of( - "local-primary", - provider(tempDirectory.resolve("root").toAbsolutePath()))))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("duplicate") - .hasMessageContaining("local-export"); - - Map providers = new LinkedHashMap<>(); - providers.put("local-primary", provider(tempDirectory.resolve("root-one").toAbsolutePath())); - providers.put(" local-primary ", provider(tempDirectory.resolve("root-two").toAbsolutePath())); - - assertThatThrownBy( - () -> - FileserverBindingCompiler.compile( - enabled(Map.of("local-export", destination("local-primary")), providers))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("duplicate") - .hasMessageContaining("local-primary"); - } - - @Test - void rejectsRelativeRootDirectory() { - FileserverR2Settings settings = - enabled( - Map.of("local-export", destination("local-primary")), - Map.of("local-primary", provider(Path.of("relative/root")))); - - assertThatThrownBy(() -> FileserverBindingCompiler.compile(settings)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("absolute"); - } - - @Test - void rejectsAbsoluteRootDirectoryThatIsNotAlreadyNormalized() { - Path nonNormalizedRoot = - tempDirectory.resolve("configured-parent").resolve("..").resolve("actual-root"); - assertThat(nonNormalizedRoot).isAbsolute(); - assertThat(nonNormalizedRoot).isNotEqualTo(nonNormalizedRoot.normalize()); - - FileserverR2Settings settings = - enabled( - Map.of("local-export", destination("local-primary")), - Map.of("local-primary", provider(nonNormalizedRoot))); - - assertThatThrownBy(() -> FileserverBindingCompiler.compile(settings)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("normalized"); - assertThatThrownBy(() -> compiledDestinationFor(nonNormalizedRoot)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("normalized"); - } - - @Test - void rejectsAutoCreateAndDisabledStrictPathSecurity() { - Path root = tempDirectory.resolve("root").toAbsolutePath(); - - assertThatThrownBy( - () -> - FileserverBindingCompiler.compile( - settingsWithProvider(providerBuilder(root).autoCreate(true).build()))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("auto-create"); - - assertThatThrownBy( - () -> - FileserverBindingCompiler.compile( - settingsWithProvider(providerBuilder(root).strictPathSecurity(false).build()))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("strict-path-security"); - } - - @Test - void rejectsUnsupportedPublicationAndDurabilityRequirements() { - FileserverR2Settings.DestinationSettings normal = destination("local-primary"); - - assertThatThrownBy( - () -> - FileserverBindingCompiler.compile( - settingsWithDestination( - new FileserverR2Settings.DestinationSettings( - normal.providerRef(), - "atomic-create", - normal.requiredDurability(), - normal.maximumRows(), - normal.maximumEncodedBytes())))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("unique-atomic-create"); - - assertThatThrownBy( - () -> - FileserverBindingCompiler.compile( - settingsWithDestination( - new FileserverR2Settings.DestinationSettings( - normal.providerRef(), - normal.requiredPublication(), - "process-local-sync", - normal.maximumRows(), - normal.maximumEncodedBytes())))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("file-and-directory-sync"); - } - - @Test - void rejectsBlankRootAttestationInputs() { - Path root = tempDirectory.resolve("root").toAbsolutePath(); - - for (int blankField = 0; blankField < 4; blankField++) { - FileserverR2Settings.ProviderSettings provider = - switch (blankField) { - case 0 -> providerBuilder(root).rootDirectory(" ").build(); - case 1 -> providerBuilder(root).expectedFileStoreName(" ").build(); - case 2 -> providerBuilder(root).expectedFileStoreType(" ").build(); - case 3 -> providerBuilder(root).expectedOwner(" ").build(); - default -> throw new AssertionError("unexpected attestation field index"); - }; - - assertThatThrownBy(() -> FileserverBindingCompiler.compile(settingsWithProvider(provider))) - .as("blank attestation field %s", blankField) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("blank"); - } - } - - @Test - void rejectsInvalidMountSentinelNameAndDigest() { - Path root = tempDirectory.resolve("root").toAbsolutePath(); - - for (String invalidName : - new String[] { - "", - " ", - ".", - "..", - "../sentinel", - "dir/sentinel", - "sentinel\nname", - "sentinel\u0000name", - "sentinel\uD800", - "a".repeat(256), - "가".repeat(86) - }) { - FileserverR2Settings.ProviderSettings provider = - providerBuilder(root).mountSentinelName(invalidName).build(); - - assertThatThrownBy(() -> FileserverBindingCompiler.compile(settingsWithProvider(provider))) - .as("sentinel name %s", invalidName) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("sentinel"); - } - - FileserverR2Settings.ProviderSettings maximumLengthSentinel = - providerBuilder(root).mountSentinelName("a".repeat(255)).build(); - assertThat(FileserverBindingCompiler.compile(settingsWithProvider(maximumLengthSentinel))) - .containsOnlyKeys(new FileDestinationId("local-export")); - - for (String invalidDigest : - new String[] { - "", - " ", - "abc", - SENTINEL_SHA256.substring(1), - SENTINEL_SHA256.toUpperCase(Locale.ROOT), - SENTINEL_SHA256 + "0" - }) { - FileserverR2Settings.ProviderSettings provider = - providerBuilder(root).mountSentinelSha256(invalidDigest).build(); - - assertThatThrownBy(() -> FileserverBindingCompiler.compile(settingsWithProvider(provider))) - .as("sentinel digest %s", invalidDigest) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("SHA-256"); - } - } - - @Test - void rejectsInvalidOrWritableByOthersMaximumRootMode() { - Path root = tempDirectory.resolve("root").toAbsolutePath(); - - for (String invalidMode : - new String[] {"", " ", "750", "0088", "0780", "07500", "0752", "0770"}) { - FileserverR2Settings.ProviderSettings provider = - providerBuilder(root).maximumRootMode(invalidMode).build(); - - assertThatThrownBy(() -> FileserverBindingCompiler.compile(settingsWithProvider(provider))) - .as("maximum root mode %s", invalidMode) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("maximum-root-mode"); - } - } - - @Test - void rejectsNonpositiveRowAndByteBounds() { - FileserverR2Settings.DestinationSettings normal = destination("local-primary"); - - for (long maximumRows : new long[] {0, -1}) { - FileserverR2Settings.DestinationSettings destination = - new FileserverR2Settings.DestinationSettings( - normal.providerRef(), - normal.requiredPublication(), - normal.requiredDurability(), - maximumRows, - normal.maximumEncodedBytes()); - - assertThatThrownBy( - () -> FileserverBindingCompiler.compile(settingsWithDestination(destination))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("maximum-rows"); - } - - for (long maximumEncodedBytes : new long[] {0, -1}) { - FileserverR2Settings.DestinationSettings destination = - new FileserverR2Settings.DestinationSettings( - normal.providerRef(), - normal.requiredPublication(), - normal.requiredDurability(), - normal.maximumRows(), - maximumEncodedBytes); - - assertThatThrownBy( - () -> FileserverBindingCompiler.compile(settingsWithDestination(destination))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("maximum-encoded-bytes"); - } - } - - @Test - void canonicalDigestsLengthPrefixValuesAndDoNotDependOnMapIterationOrder() { - assertThat(FilePublicationCanonicalDigests.digestOrderedValues(List.of("ab", "c"))) - .isNotEqualTo(FilePublicationCanonicalDigests.digestOrderedValues(List.of("a", "bc"))); - - Map firstOrder = new LinkedHashMap<>(); - firstOrder.put("destinationId", "local-export"); - firstOrder.put("providerId", "local-primary"); - Map reverseOrder = new LinkedHashMap<>(); - reverseOrder.put("providerId", "local-primary"); - reverseOrder.put("destinationId", "local-export"); - - assertThat(FilePublicationCanonicalDigests.digestNamedFields(firstOrder)) - .isEqualTo(FilePublicationCanonicalDigests.digestNamedFields(reverseOrder)); - } - - @Test - void freezesRestartStableEffectiveAndFormatPolicyIdentity() { - Path root = tempDirectory.resolve("root").toAbsolutePath(); - - CompiledFileDestination first = - FileserverBindingCompiler.compile(validSettings(root)) - .get(new FileDestinationId("local-export")); - CompiledFileDestination restarted = - FileserverBindingCompiler.compile(validSettings(root)) - .get(new FileDestinationId("local-export")); - - assertThat(first.effectivePolicyRevision()).isEqualTo("fileserver-effective-policy-v1"); - assertThat(first.effectivePolicyDigest()) - .isEqualTo("ea26b7bda7d1c83c34da62f14f920964d9d87193be0604e8415102d77e210fac"); - assertThat(first.routeToken()).isEqualTo("rea26b7bda7d1c83c34da62f14f92096"); - assertThat(first.routeToken()).hasSize(32).matches("r[0-9a-f]{31}"); - assertThat(first.formatPolicyDigest()) - .isEqualTo("cb59c3249946e7366d2e52529cc42eb8b3283b5d52fbf841edefc4701602afc7"); - assertThat(restarted.effectivePolicyRevision()).isEqualTo(first.effectivePolicyRevision()); - assertThat(restarted.effectivePolicyDigest()).isEqualTo(first.effectivePolicyDigest()); - assertThat(restarted.routeToken()).isEqualTo(first.routeToken()); - assertThat(restarted.formatPolicyDigest()).isEqualTo(first.formatPolicyDigest()); - } - - @Test - void effectiveIdentityDoesNotDependOnDestinationOrProviderMapIterationOrder() { - Path firstRoot = tempDirectory.resolve("root-one").toAbsolutePath(); - Path secondRoot = tempDirectory.resolve("root-two").toAbsolutePath(); - Map destinations = new LinkedHashMap<>(); - destinations.put("second-export", destination("second-provider")); - destinations.put("first-export", destination("first-provider")); - Map providers = new LinkedHashMap<>(); - providers.put("first-provider", provider(firstRoot)); - providers.put("second-provider", provider(secondRoot)); - - Map first = - FileserverBindingCompiler.compile(enabled(destinations, providers)); - - Map reversedDestinations = - new LinkedHashMap<>(); - reversedDestinations.put("first-export", destination("first-provider")); - reversedDestinations.put("second-export", destination("second-provider")); - Map reversedProviders = new LinkedHashMap<>(); - reversedProviders.put("second-provider", provider(secondRoot)); - reversedProviders.put("first-provider", provider(firstRoot)); - Map restarted = - FileserverBindingCompiler.compile(enabled(reversedDestinations, reversedProviders)); - - assertThat(restarted).containsOnlyKeys(first.keySet().toArray(FileDestinationId[]::new)); - first.forEach( - (id, destination) -> { - assertThat(restarted.get(id).effectivePolicyDigest()) - .isEqualTo(destination.effectivePolicyDigest()); - assertThat(restarted.get(id).routeToken()).isEqualTo(destination.routeToken()); - }); - } - - @Test - void rejectsCompiledAllowlistRouteTokenCollisionInsteadOfExtendingTheToken() { - String sharedRoutePrefix = "a".repeat(31); - String firstDigest = sharedRoutePrefix + "0".repeat(33); - String secondDigest = sharedRoutePrefix + "f".repeat(33); - assertThat(firstDigest).isNotEqualTo(secondDigest); - assertThat(FilePublicationCanonicalDigests.routeToken(firstDigest)) - .isEqualTo(FilePublicationCanonicalDigests.routeToken(secondDigest)); - Map policyDigests = new LinkedHashMap<>(); - policyDigests.put(new FileDestinationId("first-export"), firstDigest); - policyDigests.put(new FileDestinationId("second-export"), secondDigest); - - assertThatThrownBy(() -> FileserverBindingCompiler.deriveUniqueRouteTokens(policyDigests)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("route token") - .hasMessageContaining("collision") - .hasMessageContaining("raaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); - } - - @Test - void schemaDigestCoversSchemaIdentityVersionAndEveryOrderedColumnField() { - ExportSchema baseline = - schema( - "work-log", - 3, - List.of( - new Column("id", CellType.INTEGER, false, FormulaPolicy.REJECT, 32), - new Column("summary", CellType.TEXT, true, FormulaPolicy.MITIGATE, 512))); - String digest = FilePublicationCanonicalDigests.schemaDigest(baseline); - - assertThat(digest) - .isEqualTo("2d64afed0358055c34785db1610ee74586f1973f3948b88b6fc8b53181b83c16"); - assertThat(FilePublicationCanonicalDigests.schemaDigest(baseline)).isEqualTo(digest); - assertThat( - FilePublicationCanonicalDigests.schemaDigest( - schema("work-log-v2", 3, baseline.columns()))) - .isNotEqualTo(digest); - assertThat( - FilePublicationCanonicalDigests.schemaDigest(schema("work-log", 4, baseline.columns()))) - .isNotEqualTo(digest); - assertThat( - FilePublicationCanonicalDigests.schemaDigest( - schema( - "work-log", 3, List.of(baseline.columns().get(1), baseline.columns().get(0))))) - .isNotEqualTo(digest); - assertThat( - FilePublicationCanonicalDigests.schemaDigest( - schema( - "work-log", - 3, - List.of( - new Column("identifier", CellType.INTEGER, false, FormulaPolicy.REJECT, 32), - baseline.columns().get(1))))) - .isNotEqualTo(digest); - assertThat( - FilePublicationCanonicalDigests.schemaDigest( - schema( - "work-log", - 3, - List.of( - new Column("id", CellType.TEXT, false, FormulaPolicy.REJECT, 32), - baseline.columns().get(1))))) - .isNotEqualTo(digest); - assertThat( - FilePublicationCanonicalDigests.schemaDigest( - schema( - "work-log", - 3, - List.of( - new Column("id", CellType.INTEGER, true, FormulaPolicy.REJECT, 32), - baseline.columns().get(1))))) - .isNotEqualTo(digest); - assertThat( - FilePublicationCanonicalDigests.schemaDigest( - schema( - "work-log", - 3, - List.of( - new Column("id", CellType.INTEGER, false, FormulaPolicy.REJECT, 64), - baseline.columns().get(1))))) - .isNotEqualTo(digest); - assertThat( - FilePublicationCanonicalDigests.schemaDigest( - schema( - "work-log", - 3, - List.of( - new Column("id", CellType.INTEGER, false, FormulaPolicy.ALLOW, 32), - baseline.columns().get(1))))) - .isNotEqualTo(digest); - } - - @Test - void formatPolicyRevisionAndCanonicalOptionsAreStable() { - assertThat(FilePublicationCanonicalDigests.FORMAT_ENCODER_REVISION) - .isEqualTo("csv-rfc4180-encoder-v1"); - assertThat(FilePublicationCanonicalDigests.formatPolicyDigest()) - .isEqualTo("cb59c3249946e7366d2e52529cc42eb8b3283b5d52fbf841edefc4701602afc7") - .isEqualTo(FilePublicationCanonicalDigests.formatPolicyDigest()); - } - - @Test - void compiledIdentityRejectsDirectRevisionAndFormatDigestSubstitution() { - Path root = tempDirectory.resolve("root").toAbsolutePath(); - CompiledFileDestination canonical = compiledDestinationFor(root); - - assertThatThrownBy( - () -> - compiledDestinationWithIdentity( - root, - "fileserver-effective-policy-v2", - canonical.effectivePolicyDigest(), - canonical.routeToken(), - canonical.formatPolicyDigest())) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("effectivePolicyRevision"); - assertThatThrownBy( - () -> - compiledDestinationWithIdentity( - root, - canonical.effectivePolicyRevision(), - canonical.effectivePolicyDigest(), - canonical.routeToken(), - "f".repeat(64))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("formatPolicyDigest"); - } - - @Test - void compiledIdentityRejectsDigestThatDoesNotDescribeItsActualPolicyFields() { - Path root = tempDirectory.resolve("root").toAbsolutePath(); - CompiledFileDestination canonical = compiledDestinationFor(root); - String unrelatedDigest = "1".repeat(64); - - assertThat(unrelatedDigest).isNotEqualTo(canonical.effectivePolicyDigest()); - assertThatThrownBy( - () -> - compiledDestinationWithIdentity( - root, - canonical.effectivePolicyRevision(), - unrelatedDigest, - FilePublicationCanonicalDigests.routeToken(unrelatedDigest), - canonical.formatPolicyDigest())) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("effectivePolicyDigest") - .hasMessageContaining("canonical"); - } - - @Test - void schemaDigestRejectsMalformedUtf16WithoutReplacementCharacterAliases() { - for (String malformed : List.of("\uD800", "\uDC00")) { - ExportSchema malformedSchemaId = - schema( - "work-log-" + malformed, - 1, - List.of(new Column("id", CellType.INTEGER, false, FormulaPolicy.REJECT, 32))); - ExportSchema malformedColumnName = - schema( - "work-log", - 1, - List.of( - new Column( - "column-" + malformed, CellType.INTEGER, false, FormulaPolicy.REJECT, 32))); - String replacementSchemaDigest = - FilePublicationCanonicalDigests.schemaDigest( - schema( - "work-log-?", - 1, - List.of(new Column("id", CellType.INTEGER, false, FormulaPolicy.REJECT, 32)))); - String replacementColumnDigest = - FilePublicationCanonicalDigests.schemaDigest( - schema( - "work-log", - 1, - List.of( - new Column("column-?", CellType.INTEGER, false, FormulaPolicy.REJECT, 32)))); - - assertThat(replacementSchemaDigest).matches("[0-9a-f]{64}"); - assertThat(replacementColumnDigest).matches("[0-9a-f]{64}"); - assertStrictUtf8Rejection(malformedSchemaId, malformed); - assertStrictUtf8Rejection(malformedColumnName, malformed); - } - } - - @Test - void schemaDigestAcceptsSupplementaryUnicodeWithoutLosingRestartStability() { - ExportSchema unicodeSchema = - schema( - "작업-\uD83D\uDE80", - 7, - List.of( - new Column("메모-\uD83E\uDDEA", CellType.TEXT, true, FormulaPolicy.MITIGATE, 1_024))); - - assertThat(FilePublicationCanonicalDigests.schemaDigest(unicodeSchema)) - .isEqualTo("6c6568f87eadcd12aaf5efcff7dfd081115a82233b73903f8f0a029287b76eac") - .isEqualTo(FilePublicationCanonicalDigests.schemaDigest(unicodeSchema)); - } - - @Test - @ResourceLock("java.util.Locale.default") - void schemaDigestDoesNotDependOnTheJvmDefaultLocale() { - ExportSchema schema = - schema( - "work-log", - 3, - List.of( - new Column("id", CellType.INTEGER, false, FormulaPolicy.REJECT, 32), - new Column("summary", CellType.TEXT, true, FormulaPolicy.MITIGATE, 512))); - Locale original = Locale.getDefault(); - String baseline = FilePublicationCanonicalDigests.schemaDigest(schema); - try { - Locale.setDefault(Locale.forLanguageTag("ar-EG")); - assertThat(FilePublicationCanonicalDigests.schemaDigest(schema)).isEqualTo(baseline); - } finally { - Locale.setDefault(original); - } - } - - private static ExportSchema schema(String schemaId, int version, List columns) { - return new ExportSchema(schemaId, version, columns); - } - - private static void assertStrictUtf8Rejection(ExportSchema schema, String malformed) { - assertThatThrownBy(() -> FilePublicationCanonicalDigests.schemaDigest(schema)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("canonical value must be valid UTF-8") - .satisfies( - failure -> - assertThat(failure.getCause()) - .isInstanceOf(java.nio.charset.CharacterCodingException.class) - .hasMessageNotContaining(malformed)); - } - - private FileserverR2Settings validSettings(Path root) { - return enabled( - Map.of("local-export", destination("local-primary")), - Map.of("local-primary", provider(root))); - } - - private FileserverR2Settings validSettingsWithIds(String destinationId, String providerId) { - return enabled( - Map.of(destinationId, destination(providerId)), - Map.of(providerId, provider(tempDirectory.resolve("root").toAbsolutePath()))); - } - - private FileserverR2Settings settingsWithDestination( - FileserverR2Settings.DestinationSettings destination) { - return enabled( - Map.of("local-export", destination), - Map.of("local-primary", provider(tempDirectory.resolve("root").toAbsolutePath()))); - } - - private FileserverR2Settings settingsWithProvider( - FileserverR2Settings.ProviderSettings provider) { - return enabled( - Map.of("local-export", destination("local-primary")), Map.of("local-primary", provider)); - } - - private static FileserverR2Settings enabled( - Map destinations, - Map providers) { - return new FileserverR2Settings(true, destinations, providers); - } - - private static FileserverR2Settings.DestinationSettings destination(String providerRef) { - return new FileserverR2Settings.DestinationSettings( - providerRef, "unique-atomic-create", "file-and-directory-sync", 1_000_000, 1_073_741_824); - } - - private static FileserverR2Settings.ProviderSettings provider(Path root) { - return providerBuilder(root).build(); - } - - private static FileserverR2Settings.ProviderSettings provider(Path root, String type) { - return providerBuilder(root).type(type).build(); - } - - private static ProviderSettingsBuilder providerBuilder(Path root) { - return new ProviderSettingsBuilder(root); - } - - private static CompiledFileDestination compiledDestinationFor(Path root) { - return new CompiledFileDestination( - new FileDestinationId("unexpected"), - "local-primary", - root, - 1, - 1, - "expected-store", - "expected-type", - ".ca-fileserver-volume", - SENTINEL_SHA256, - "fileserver", - "0750", - Set.of( - PosixFilePermission.OWNER_READ, - PosixFilePermission.OWNER_WRITE, - PosixFilePermission.OWNER_EXECUTE, - PosixFilePermission.GROUP_READ, - PosixFilePermission.GROUP_EXECUTE), - PublicationGuarantee.UNIQUE_ATOMIC_CREATE, - DurabilityGuarantee.FILE_AND_DIRECTORY_SYNC); - } - - private static CompiledFileDestination compiledDestinationWithIdentity( - Path root, - String effectivePolicyRevision, - String effectivePolicyDigest, - String routeToken, - String formatPolicyDigest) { - return new CompiledFileDestination( - new FileDestinationId("unexpected"), - "local-primary", - root, - 1, - 1, - "expected-store", - "expected-type", - ".ca-fileserver-volume", - SENTINEL_SHA256, - "fileserver", - "0750", - Set.of( - PosixFilePermission.OWNER_READ, - PosixFilePermission.OWNER_WRITE, - PosixFilePermission.OWNER_EXECUTE, - PosixFilePermission.GROUP_READ, - PosixFilePermission.GROUP_EXECUTE), - effectivePolicyRevision, - effectivePolicyDigest, - routeToken, - formatPolicyDigest, - PublicationGuarantee.UNIQUE_ATOMIC_CREATE, - DurabilityGuarantee.FILE_AND_DIRECTORY_SYNC); - } - - private static final class ProviderSettingsBuilder { - - private String type = "local-persistent"; - private String rootDirectory; - private boolean autoCreate; - private boolean strictPathSecurity = true; - private String expectedFileStoreName = "expected-store"; - private String expectedFileStoreType = "expected-type"; - private String mountSentinelName = ".ca-fileserver-volume"; - private String mountSentinelSha256 = SENTINEL_SHA256; - private String expectedOwner = "fileserver"; - private String maximumRootMode = "0750"; - - private ProviderSettingsBuilder(Path root) { - rootDirectory = root.toString(); - } - - private ProviderSettingsBuilder type(String value) { - type = value; - return this; - } - - private ProviderSettingsBuilder rootDirectory(String value) { - rootDirectory = value; - return this; - } - - private ProviderSettingsBuilder autoCreate(boolean value) { - autoCreate = value; - return this; - } - - private ProviderSettingsBuilder strictPathSecurity(boolean value) { - strictPathSecurity = value; - return this; - } - - private ProviderSettingsBuilder expectedFileStoreName(String value) { - expectedFileStoreName = value; - return this; - } - - private ProviderSettingsBuilder expectedFileStoreType(String value) { - expectedFileStoreType = value; - return this; - } - - private ProviderSettingsBuilder mountSentinelName(String value) { - mountSentinelName = value; - return this; - } - - private ProviderSettingsBuilder mountSentinelSha256(String value) { - mountSentinelSha256 = value; - return this; - } - - private ProviderSettingsBuilder expectedOwner(String value) { - expectedOwner = value; - return this; - } - - private ProviderSettingsBuilder maximumRootMode(String value) { - maximumRootMode = value; - return this; - } - - private FileserverR2Settings.ProviderSettings build() { - return new FileserverR2Settings.ProviderSettings( - type, - rootDirectory, - autoCreate, - strictPathSecurity, - expectedFileStoreName, - expectedFileStoreType, - mountSentinelName, - mountSentinelSha256, - expectedOwner, - maximumRootMode); - } - } -} diff --git a/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/FileserverControlRecordCodecTest.java b/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/FileserverControlRecordCodecTest.java deleted file mode 100644 index 8ad022d5..00000000 --- a/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/FileserverControlRecordCodecTest.java +++ /dev/null @@ -1,924 +0,0 @@ -package dev.caskeleton.adapter.outbound.fileserver; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.application.filepublication.FileDestinationId; -import dev.caskeleton.application.filepublication.FilePublishOperationId; -import dev.caskeleton.application.filepublication.FilePublishReceipt; -import dev.caskeleton.application.filepublication.FilePublishReceipt.DurabilityGuarantee; -import dev.caskeleton.application.filepublication.FilePublishReceipt.PublicationGuarantee; -import dev.caskeleton.application.filepublication.FileVersion; -import dev.caskeleton.application.filepublication.PublishedFileReference; -import java.nio.charset.StandardCharsets; -import java.time.Instant; -import java.util.Arrays; -import java.util.Base64; -import java.util.Locale; -import java.util.Set; -import org.junit.jupiter.api.Test; - -class FileserverControlRecordCodecTest { - - private static final String FILE_ID = "00112233445566778899aabbccddeeff"; - private static final String DIGEST_A = "a".repeat(64); - private static final String DIGEST_B = "b".repeat(64); - private static final String DIGEST_C = "c".repeat(64); - private static final Instant CREATED_AT = Instant.parse("2026-07-28T01:02:03Z"); - private static final Instant SEALED_AT = Instant.parse("2026-07-28T01:02:04Z"); - private static final Instant PUBLISHED_AT = Instant.parse("2026-07-28T01:02:05Z"); - - private final R2PublishedReferenceCodec referenceCodec = new R2PublishedReferenceCodec(); - private final FileserverControlRecordCodec codec = new FileserverControlRecordCodec(); - - @Test - void referenceRoundTripRejectsCorruptionUnknownRouteAndTruncation() { - PublishedFileReference reference = referenceCodec.encode("routea1", FILE_ID); - - assertThat(reference.value()) - .isEqualTo("fsr1.routea1.00112233445566778899aabbccddeeff.201c97ae3a2c") - .matches("fsr1\\.routea1\\.[0-9a-f]{32}\\.[0-9a-f]{12}"); - assertThat(referenceCodec.decode(reference, Set.of("routea1")).fileId()).isEqualTo(FILE_ID); - assertThat(referenceCodec.decode(reference, Set.of("routea1")).routeToken()) - .isEqualTo("routea1"); - - assertThatThrownBy( - () -> - referenceCodec.decode( - new PublishedFileReference( - reference.value().substring(0, reference.value().length() - 1) + "0"), - Set.of("routea1"))) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> referenceCodec.decode(reference, Set.of("routeb2"))) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - referenceCodec.decode( - new PublishedFileReference( - reference.value().substring(0, reference.value().length() - 1)), - Set.of("routea1"))) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void referenceRejectsUppercaseWrongSegmentsAndNonCanonicalTokens() { - String canonical = referenceCodec.encode("routea1", FILE_ID).value(); - - for (String invalid : - new String[] { - canonical.toUpperCase(Locale.ROOT), - canonical + ".extra", - canonical.replace("routea1", "route-a"), - canonical.replace(FILE_ID, FILE_ID.substring(1)), - "fsr2" + canonical.substring(4), - canonical.replace("routea1", "Routea1") - }) { - assertThatThrownBy( - () -> referenceCodec.decode(new PublishedFileReference(invalid), Set.of("routea1"))) - .isInstanceOf(IllegalArgumentException.class); - } - - assertThatThrownBy(() -> referenceCodec.encode("route-a", FILE_ID)) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> referenceCodec.encode("routea1", FILE_ID.toUpperCase(Locale.ROOT))) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> referenceCodec.decode(referenceCodec.encode("routea1", FILE_ID), Set.of())) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void operationRecordAndTerminalReceiptHaveCanonicalExactRoundTrips() { - FilePublishReceipt receipt = receipt(); - String snapshot = codec.encodeReceiptSnapshot(receipt); - DurablePublicationRecord record = publishedRecord(snapshot); - - byte[] encoded = codec.encodeOperation(record); - - assertThat(encoded).hasSizeLessThanOrEqualTo(16_384); - assertThat(codec.decodeOperation(encoded)).isEqualTo(record); - assertThat(codec.decodeReceiptSnapshot(snapshot)).isEqualTo(receipt); - assertThat(snapshot).startsWith("rsv1.").doesNotContain("="); - assertThat(new String(encoded, StandardCharsets.UTF_8)) - .startsWith( - "{\"schemaVersion\":2,\"stateRevision\":6,\"state\":\"PUBLISHED\"," - + "\"operationId\":\"operation-01\"") - .endsWith("\"receiptSnapshot\":\"" + snapshot + "\"}"); - assertThat(fieldCount(encoded)).isEqualTo(25); - } - - @Test - void manifestAndReferenceIndexHaveCanonicalExactRoundTrips() { - PrivateFileManifest manifest = manifest(); - PublishedReferenceRecord reference = referenceRecord(); - - byte[] encodedManifest = codec.encodeManifest(manifest); - byte[] encodedReference = codec.encodeReference(reference); - - assertThat(encodedManifest).hasSizeLessThanOrEqualTo(16_384); - assertThat(encodedReference).hasSizeLessThanOrEqualTo(16_384); - assertThat(codec.decodeManifest(encodedManifest)).isEqualTo(manifest); - assertThat(codec.decodeReference(encodedReference)).isEqualTo(reference); - assertThat(new String(encodedManifest, StandardCharsets.UTF_8)) - .startsWith("{\"schemaVersion\":1,\"operationId\":\"operation-01\""); - assertThat(new String(encodedReference, StandardCharsets.UTF_8)) - .startsWith("{\"schemaVersion\":1,\"fileId\":\"" + FILE_ID + "\""); - } - - @Test - void allRecordDecodersRejectNewerMissingUnknownAndDuplicateFields() { - assertClosedSchema( - codec.encodeOperation(publishedRecord(codec.encodeReceiptSnapshot(receipt()))), - codec::decodeOperation, - "\"schemaVersion\":2", - "\"schemaVersion\":3", - "\"stateRevision\":6"); - assertClosedSchema( - codec.encodeManifest(manifest()), - codec::decodeManifest, - "\"schemaVersion\":1", - "\"schemaVersion\":2", - "\"operationId\":\"operation-01\""); - assertClosedSchema( - codec.encodeReference(referenceRecord()), - codec::decodeReference, - "\"schemaVersion\":1", - "\"schemaVersion\":2", - "\"fileId\":\"" + FILE_ID + "\""); - } - - @Test - void canonicalDecoderRejectsWhitespaceReorderingEscapesNumbersUtf8AndTrailingContent() { - byte[] canonical = - codec.encodeOperation(publishedRecord(codec.encodeReceiptSnapshot(receipt()))); - String json = new String(canonical, StandardCharsets.UTF_8); - - for (String invalid : - new String[] { - " " + json, - json.replace( - "\"schemaVersion\":2,\"stateRevision\":6", "\"stateRevision\":6,\"schemaVersion\":2"), - json.replace("\"operation-01\"", "\"operation\\u002d01\""), - json.replace("\"stateRevision\":6", "\"stateRevision\":06"), - json.replace("\"stateRevision\":6", "\"stateRevision\":+6"), - json.replace("\"stateRevision\":6", "\"stateRevision\":-0"), - json.replace("\"stateRevision\":6", "\"stateRevision\":9223372036854775808"), - json + "null", - json.replace("\"operation-01\"", "\"operation-\\ud800\"") - }) { - assertThatThrownBy(() -> codec.decodeOperation(invalid.getBytes(StandardCharsets.UTF_8))) - .isInstanceOf(IllegalArgumentException.class); - } - assertThatThrownBy( - () -> codec.decodeOperation(new byte[] {'{', '"', (byte) 0xc3, (byte) 0x28, '"', '}'})) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void operationStateRevisionAndPresenceInvariantsFailClosed() { - assertThatThrownBy( - () -> - operation( - 1, - DurablePublicationRecord.State.SEALED, - 42, - 1, - 2, - DIGEST_C, - SEALED_AT, - "", - "", - null, - "", - "")) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - operation( - 1, - DurablePublicationRecord.State.WRITING, - 42, - 0, - 0, - "", - null, - "", - "", - null, - "", - "")) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - operation( - 6, - DurablePublicationRecord.State.PUBLISHED, - 42, - 1, - 2, - DIGEST_C, - SEALED_AT, - DIGEST_A, - DIGEST_B, - PUBLISHED_AT, - "", - "")) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - operation( - 7, - DurablePublicationRecord.State.QUARANTINED, - 0, - 0, - 0, - "", - null, - "", - "", - null, - "", - "")) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void quarantinedNullShaFailsClosedWithIllegalArgumentException() { - assertThatThrownBy( - () -> - operationWithFormulaCount( - 2, - DurablePublicationRecord.State.QUARANTINED, - 0, - 0, - 0, - null, - 0, - null, - "", - "", - null, - "INTEGRITY_FAILURE", - "")) - .isExactlyInstanceOf(IllegalArgumentException.class); - } - - @Test - void formulaMitigationCountCannotExceedCellsAndUsesOverflowSafeBounds() { - assertThatThrownBy( - () -> - operationWithFormulaCount( - 2, - DurablePublicationRecord.State.SEALED, - 42, - 1, - 2, - DIGEST_C, - 3, - SEALED_AT, - "", - "", - null, - "", - "")) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> manifestWithCounts(1, 2, 3)) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> codec.encodeReceiptSnapshot(receiptWithCounts(1, 2, 3))) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - operationWithFormulaCount( - 2, - DurablePublicationRecord.State.SEALED, - 42, - 0, - 2, - DIGEST_C, - 1, - SEALED_AT, - "", - "", - null, - "", - "")) - .isInstanceOf(IllegalArgumentException.class); - - long overflowRows = Long.MAX_VALUE / 2 + 1; - DurablePublicationRecord overflowSafeOperation = - operationWithFormulaCount( - 2, - DurablePublicationRecord.State.SEALED, - 42, - overflowRows, - 2, - DIGEST_C, - Long.MAX_VALUE, - SEALED_AT, - "", - "", - null, - "", - ""); - PrivateFileManifest overflowSafeManifest = manifestWithCounts(overflowRows, 2, Long.MAX_VALUE); - FilePublishReceipt overflowSafeReceipt = receiptWithCounts(overflowRows, 2, Long.MAX_VALUE); - - assertThat(codec.decodeOperation(codec.encodeOperation(overflowSafeOperation))) - .isEqualTo(overflowSafeOperation); - assertThat(codec.decodeManifest(codec.encodeManifest(overflowSafeManifest))) - .isEqualTo(overflowSafeManifest); - assertThat(codec.decodeReceiptSnapshot(codec.encodeReceiptSnapshot(overflowSafeReceipt))) - .isEqualTo(overflowSafeReceipt); - } - - @Test - void allSevenStatesRoundTripOnlyWithTheirRequiredProgressionFields() { - DurablePublicationRecord writing = - operation( - 1, DurablePublicationRecord.State.WRITING, 0, 0, 0, "", null, "", "", null, "", ""); - DurablePublicationRecord sealed = - operation( - 2, - DurablePublicationRecord.State.SEALED, - 42, - 1, - 2, - DIGEST_C, - SEALED_AT, - "", - "", - null, - "", - ""); - DurablePublicationRecord dataPublished = - operation( - 3, - DurablePublicationRecord.State.DATA_PUBLISHED, - 42, - 1, - 2, - DIGEST_C, - SEALED_AT, - "", - "", - null, - "", - ""); - DurablePublicationRecord manifestPublished = - operation( - 4, - DurablePublicationRecord.State.MANIFEST_PUBLISHED, - 42, - 1, - 2, - DIGEST_C, - SEALED_AT, - DIGEST_A, - "", - null, - "", - ""); - DurablePublicationRecord referencePublished = - operation( - 5, - DurablePublicationRecord.State.REFERENCE_PUBLISHED, - 42, - 1, - 2, - DIGEST_C, - SEALED_AT, - DIGEST_A, - DIGEST_B, - null, - "", - ""); - DurablePublicationRecord published = publishedRecord(codec.encodeReceiptSnapshot(receipt())); - DurablePublicationRecord quarantined = - operation( - 2, - DurablePublicationRecord.State.QUARANTINED, - 0, - 0, - 0, - "", - null, - "", - "", - null, - "INTEGRITY_FAILURE", - ""); - - assertThat( - Set.of( - writing.state(), - sealed.state(), - dataPublished.state(), - manifestPublished.state(), - referencePublished.state(), - published.state(), - quarantined.state())) - .containsExactlyInAnyOrder(DurablePublicationRecord.State.values()); - for (DurablePublicationRecord record : - new DurablePublicationRecord[] { - writing, - sealed, - dataPublished, - manifestPublished, - referencePublished, - published, - quarantined - }) { - assertThat(codec.decodeOperation(codec.encodeOperation(record))).isEqualTo(record); - if (record.state() != DurablePublicationRecord.State.PUBLISHED) { - assertThat(record.receiptSnapshot()).isEmpty(); - } - } - } - - @Test - void recordsRejectUnsafeLocatorsDigestsEnumsAndSensitiveOrRawContentFields() { - for (String locator : - new String[] { - "/srv/report.csv", - "C:\\data\\report.csv", - "https:report.csv", - ".", - "..", - "report\u0001.csv" - }) { - assertThatThrownBy(() -> withManifestLocator(locator)) - .isInstanceOf(IllegalArgumentException.class); - } - assertThatThrownBy(() -> withManifestSchemaDigest(DIGEST_A.toUpperCase(Locale.ROOT))) - .isInstanceOf(IllegalArgumentException.class); - - String manifestJson = new String(codec.encodeManifest(manifest()), StandardCharsets.UTF_8); - for (String field : new String[] {"credential", "rawRows", "rawCell", "absolutePath"}) { - assertThatThrownBy( - () -> - codec.decodeManifest( - manifestJson - .substring(0, manifestJson.length() - 1) - .concat(",\"" + field + "\":\"secret\"}") - .getBytes(StandardCharsets.UTF_8))) - .isInstanceOf(IllegalArgumentException.class); - } - assertThatThrownBy( - () -> - codec.decodeManifest( - manifestJson - .replace( - "\"durabilityGuarantee\":\"FILE_AND_DIRECTORY_SYNC\"", - "\"durabilityGuarantee\":\"LOCAL_DISK\"") - .getBytes(StandardCharsets.UTF_8))) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void receiptSnapshotRejectsPaddingWrongVersionNonCanonicalPayloadAndUnsafeData() { - String snapshot = codec.encodeReceiptSnapshot(receipt()); - - assertThatThrownBy(() -> codec.decodeReceiptSnapshot(snapshot + "=")) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> codec.decodeReceiptSnapshot("rsv2." + snapshot.substring(5))) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> codec.encodeReceiptSnapshot(receiptWithPublishedFileName("../report.csv"))) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void canonicalCodecRoundTripsSupplementaryUnicodeInOpaqueText() { - FilePublishReceipt unicodeReceipt = - new FilePublishReceipt( - new FilePublishOperationId("operation-\uD83D\uDE00"), - referenceCodec.encode("routea1", FILE_ID), - new FileDestinationId("local-export"), - "report.csv", - new FileVersion("version-\uD83D\uDE80"), - "csv-\uD83D\uDCC4", - "text/csv", - "UTF-8", - 42, - 1, - 2, - DIGEST_C, - PUBLISHED_AT, - PublicationGuarantee.UNIQUE_ATOMIC_CREATE, - DurabilityGuarantee.FILE_AND_DIRECTORY_SYNC, - 0); - - String snapshot = codec.encodeReceiptSnapshot(unicodeReceipt); - - assertThat(codec.decodeReceiptSnapshot(snapshot)).isEqualTo(unicodeReceipt); - } - - @Test - void receiptSnapshotRejectsBase64urlAliasWithNonZeroTrailingBits() { - String canonical = receiptSnapshotWithUnusedTrailingBits(); - String canonicalPayload = canonical.substring("rsv1.".length()); - String alias = nonCanonicalTrailingBitAlias(canonical); - String aliasPayload = alias.substring("rsv1.".length()); - - assertThat(canonicalPayload.length() % 4).isIn(2, 3); - assertThat(Base64.getUrlDecoder().decode(aliasPayload)) - .isEqualTo(Base64.getUrlDecoder().decode(canonicalPayload)); - assertThat(alias).isNotEqualTo(canonical); - assertThatThrownBy(() -> codec.decodeReceiptSnapshot(alias)) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void terminalReceiptSnapshotMustMatchEveryRecoverableJournalField() { - for (String mismatchedField : - new String[] { - "operationId", - "destinationId", - "publishedFileName", - "byteSize", - "rowCount", - "columnCount", - "sha256", - "formulaMitigatedCount", - "publishedAt", - "routeToken", - "fileId" - }) { - String snapshot = codec.encodeReceiptSnapshot(receiptVariant(mismatchedField)); - assertThatThrownBy(() -> publishedRecord(snapshot)) - .as("mismatched %s", mismatchedField) - .isInstanceOf(IllegalArgumentException.class); - } - } - - @Test - void opaqueOperationAndVersionValuesAreNotMistakenForInternalLocators() { - FilePublishReceipt opaqueReceipt = - new FilePublishReceipt( - new FilePublishOperationId("customer/order:01"), - referenceCodec.encode("routea1", FILE_ID), - new FileDestinationId("local-export"), - "report.csv", - new FileVersion("etag/2026:07"), - "csv-rfc4180", - "text/csv", - "UTF-8", - 42, - 1, - 2, - DIGEST_C, - PUBLISHED_AT, - PublicationGuarantee.UNIQUE_ATOMIC_CREATE, - DurabilityGuarantee.FILE_AND_DIRECTORY_SYNC, - 0); - - String snapshot = codec.encodeReceiptSnapshot(opaqueReceipt); - - assertThat(codec.decodeReceiptSnapshot(snapshot)).isEqualTo(opaqueReceipt); - assertThatThrownBy(() -> withManifestLocator("customer/order:01")) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void encodedRecordSizeIsBoundedAndOversizedInputFailsClosed() { - assertThat(codec.encodeOperation(publishedRecord(codec.encodeReceiptSnapshot(receipt())))) - .hasSizeLessThanOrEqualTo(16_384); - assertThat(codec.encodeManifest(manifest())).hasSizeLessThanOrEqualTo(16_384); - assertThat(codec.encodeReference(referenceRecord())).hasSizeLessThanOrEqualTo(16_384); - - byte[] oversized = new byte[16_385]; - Arrays.fill(oversized, (byte) ' '); - assertThatThrownBy(() -> codec.decodeOperation(oversized)) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> codec.decodeManifest(oversized)) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> codec.decodeReference(oversized)) - .isInstanceOf(IllegalArgumentException.class); - } - - private DurablePublicationRecord publishedRecord(String snapshot) { - return operation( - 6, - DurablePublicationRecord.State.PUBLISHED, - 42, - 1, - 2, - DIGEST_C, - SEALED_AT, - DIGEST_A, - DIGEST_B, - PUBLISHED_AT, - "", - snapshot); - } - - private DurablePublicationRecord operation( - long revision, - DurablePublicationRecord.State state, - long byteSize, - long rowCount, - int columnCount, - String sha256, - Instant sealedAt, - String manifestDigest, - String referenceDigest, - Instant publishedAt, - String failureCode, - String receiptSnapshot) { - return operationWithFormulaCount( - revision, - state, - byteSize, - rowCount, - columnCount, - sha256, - 0, - sealedAt, - manifestDigest, - referenceDigest, - publishedAt, - failureCode, - receiptSnapshot); - } - - private DurablePublicationRecord operationWithFormulaCount( - long revision, - DurablePublicationRecord.State state, - long byteSize, - long rowCount, - int columnCount, - String sha256, - long formulaMitigatedCount, - Instant sealedAt, - String manifestDigest, - String referenceDigest, - Instant publishedAt, - String failureCode, - String receiptSnapshot) { - return new DurablePublicationRecord( - 2, - revision, - state, - "operation-01", - DIGEST_A, - "policy-v1", - DIGEST_B, - "local-export", - "local-primary", - FILE_ID, - "routea1", - "report.csv", - "operation-01.part", - byteSize, - rowCount, - columnCount, - sha256, - formulaMitigatedCount, - manifestDigest, - referenceDigest, - CREATED_AT, - sealedAt, - publishedAt, - failureCode, - receiptSnapshot); - } - - private FilePublishReceipt receipt() { - return receiptWithPublishedFileName("report.csv"); - } - - private FilePublishReceipt receiptWithPublishedFileName(String publishedFileName) { - return new FilePublishReceipt( - new FilePublishOperationId("operation-01"), - referenceCodec.encode("routea1", FILE_ID), - new FileDestinationId("local-export"), - publishedFileName, - new FileVersion("version-01"), - "csv-rfc4180", - "text/csv", - "UTF-8", - 42, - 1, - 2, - DIGEST_C, - PUBLISHED_AT, - PublicationGuarantee.UNIQUE_ATOMIC_CREATE, - DurabilityGuarantee.FILE_AND_DIRECTORY_SYNC, - 0); - } - - private FilePublishReceipt receiptWithCounts( - long rowCount, int columnCount, long formulaMitigatedCount) { - return new FilePublishReceipt( - new FilePublishOperationId("operation-01"), - referenceCodec.encode("routea1", FILE_ID), - new FileDestinationId("local-export"), - "report.csv", - new FileVersion("version-01"), - "csv-rfc4180", - "text/csv", - "UTF-8", - 42, - rowCount, - columnCount, - DIGEST_C, - PUBLISHED_AT, - PublicationGuarantee.UNIQUE_ATOMIC_CREATE, - DurabilityGuarantee.FILE_AND_DIRECTORY_SYNC, - formulaMitigatedCount); - } - - private FilePublishReceipt receiptVariant(String mismatchedField) { - PublishedFileReference reference = - switch (mismatchedField) { - case "routeToken" -> referenceCodec.encode("routeb2", FILE_ID); - case "fileId" -> referenceCodec.encode("routea1", "f".repeat(32)); - default -> referenceCodec.encode("routea1", FILE_ID); - }; - return new FilePublishReceipt( - new FilePublishOperationId( - mismatchedField.equals("operationId") ? "operation-02" : "operation-01"), - reference, - new FileDestinationId( - mismatchedField.equals("destinationId") ? "other-export" : "local-export"), - mismatchedField.equals("publishedFileName") ? "other.csv" : "report.csv", - new FileVersion("version-01"), - "csv-rfc4180", - "text/csv", - "UTF-8", - mismatchedField.equals("byteSize") ? 43 : 42, - mismatchedField.equals("rowCount") ? 2 : 1, - mismatchedField.equals("columnCount") ? 3 : 2, - mismatchedField.equals("sha256") ? DIGEST_B : DIGEST_C, - mismatchedField.equals("publishedAt") ? PUBLISHED_AT.plusSeconds(1) : PUBLISHED_AT, - PublicationGuarantee.UNIQUE_ATOMIC_CREATE, - DurabilityGuarantee.FILE_AND_DIRECTORY_SYNC, - mismatchedField.equals("formulaMitigatedCount") ? 1 : 0); - } - - private PrivateFileManifest manifest() { - return manifestWith(DIGEST_B, "00112233445566778899aabbccddeeff.csv"); - } - - private PrivateFileManifest withManifestLocator(String locator) { - return manifestWith(DIGEST_B, locator); - } - - private PrivateFileManifest withManifestSchemaDigest(String digest) { - return manifestWith(digest, "00112233445566778899aabbccddeeff.csv"); - } - - private PrivateFileManifest manifestWith(String schemaDigest, String locator) { - return manifestWith(schemaDigest, locator, 1, 2, 0); - } - - private PrivateFileManifest manifestWithCounts( - long rowCount, int columnCount, long formulaMitigatedCount) { - return manifestWith( - DIGEST_B, - "00112233445566778899aabbccddeeff.csv", - rowCount, - columnCount, - formulaMitigatedCount); - } - - private PrivateFileManifest manifestWith( - String schemaDigest, - String locator, - long rowCount, - int columnCount, - long formulaMitigatedCount) { - return new PrivateFileManifest( - 1, - "operation-01", - FILE_ID, - "local-primary", - referenceCodec.encode("routea1", FILE_ID).value(), - DIGEST_A, - "local-export", - "worklog-v1", - 1, - schemaDigest, - "csv-rfc4180", - DIGEST_A, - "policy-v1", - DIGEST_B, - "report.csv", - "version-01", - "text/csv", - "UTF-8", - 42, - rowCount, - columnCount, - DIGEST_C, - formulaMitigatedCount, - PublicationGuarantee.UNIQUE_ATOMIC_CREATE, - DurabilityGuarantee.FILE_AND_DIRECTORY_SYNC, - locator, - CREATED_AT, - PUBLISHED_AT); - } - - private String receiptSnapshotWithUnusedTrailingBits() { - for (int suffixLength = 0; suffixLength < 8; suffixLength++) { - FilePublishReceipt candidate = - new FilePublishReceipt( - new FilePublishOperationId("operation-01"), - referenceCodec.encode("routea1", FILE_ID), - new FileDestinationId("local-export"), - "report.csv", - new FileVersion("version-01"), - "csv-rfc4180" + "x".repeat(suffixLength), - "text/csv", - "UTF-8", - 42, - 1, - 2, - DIGEST_C, - PUBLISHED_AT, - PublicationGuarantee.UNIQUE_ATOMIC_CREATE, - DurabilityGuarantee.FILE_AND_DIRECTORY_SYNC, - 0); - String snapshot = codec.encodeReceiptSnapshot(candidate); - int remainder = (snapshot.length() - "rsv1.".length()) % 4; - if (remainder == 2 || remainder == 3) { - return snapshot; - } - } - throw new AssertionError("could not construct a receipt snapshot with unused trailing bits"); - } - - private static String nonCanonicalTrailingBitAlias(String snapshot) { - String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; - int finalIndex = snapshot.length() - 1; - int value = alphabet.indexOf(snapshot.charAt(finalIndex)); - if (value < 0 || value == alphabet.length() - 1) { - throw new AssertionError("unexpected canonical base64url tail"); - } - return snapshot.substring(0, finalIndex) + alphabet.charAt(value + 1); - } - - private PublishedReferenceRecord referenceRecord() { - return new PublishedReferenceRecord( - 1, - FILE_ID, - "routea1", - referenceCodec.encode("routea1", FILE_ID).value(), - "operation-01", - "version-01", - DIGEST_A, - "00112233445566778899aabbccddeeff.csv", - "local-export", - "local-primary", - "report.csv", - "text/csv", - "UTF-8", - 42, - DIGEST_C, - PUBLISHED_AT); - } - - private static int fieldCount(byte[] encoded) { - String json = new String(encoded, StandardCharsets.UTF_8); - return json.split("\":", -1).length - 1; - } - - private static void assertClosedSchema( - byte[] canonical, - Decoder decoder, - String currentSchema, - String newerSchema, - String requiredField) { - String json = new String(canonical, StandardCharsets.UTF_8); - assertThatThrownBy( - () -> - decoder.decode( - json.replace(currentSchema, newerSchema).getBytes(StandardCharsets.UTF_8))) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - decoder.decode( - json.substring(0, json.length() - 1) - .concat(",\"unknown\":\"value\"}") - .getBytes(StandardCharsets.UTF_8))) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - decoder.decode( - json.substring(0, json.length() - 1) - .concat("," + requiredField + "}") - .getBytes(StandardCharsets.UTF_8))) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - decoder.decode( - json.replaceFirst(",?" + java.util.regex.Pattern.quote(requiredField), "") - .getBytes(StandardCharsets.UTF_8))) - .isInstanceOf(IllegalArgumentException.class); - } - - @FunctionalInterface - private interface Decoder { - Object decode(byte[] bytes); - } -} diff --git a/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/FileserverCrashScenarioMain.java b/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/FileserverCrashScenarioMain.java deleted file mode 100644 index b8e0e713..00000000 --- a/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/FileserverCrashScenarioMain.java +++ /dev/null @@ -1,473 +0,0 @@ -package dev.caskeleton.adapter.outbound.fileserver; - -import static java.nio.charset.StandardCharsets.UTF_8; - -import dev.caskeleton.application.filepublication.ExportSchema; -import dev.caskeleton.application.filepublication.ExportSchema.CellType; -import dev.caskeleton.application.filepublication.ExportSchema.Column; -import dev.caskeleton.application.filepublication.ExportSchema.FormulaPolicy; -import dev.caskeleton.application.filepublication.FileDestinationId; -import dev.caskeleton.application.filepublication.FilePublicationException; -import dev.caskeleton.application.filepublication.FilePublishOperationId; -import dev.caskeleton.application.filepublication.FilePublishReceipt; -import dev.caskeleton.application.filepublication.FilePublishReceipt.DurabilityGuarantee; -import dev.caskeleton.application.filepublication.FilePublishReceipt.PublicationGuarantee; -import dev.caskeleton.application.filepublication.FilePublishRequest; -import dev.caskeleton.application.filepublication.LogicalFileName; -import dev.caskeleton.application.filepublication.SourceRevision; -import dev.caskeleton.application.filepublication.TabularCell.IntegerCell; -import dev.caskeleton.application.filepublication.TabularCell.TextCell; -import dev.caskeleton.application.filepublication.TabularRow; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.nio.channels.FileChannel; -import java.nio.channels.FileLock; -import java.nio.file.FileStore; -import java.nio.file.Files; -import java.nio.file.LinkOption; -import java.nio.file.OpenOption; -import java.nio.file.Path; -import java.nio.file.StandardOpenOption; -import java.nio.file.attribute.PosixFilePermission; -import java.nio.file.attribute.PosixFilePermissions; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.Arrays; -import java.util.HexFormat; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.concurrent.atomic.AtomicInteger; - -/** - * Forked-process helper for Fileserver R2 crash and OS-lock qualification. - * - *

Its output is deliberately restricted to fixed protocol markers. In particular, it never - * writes the supplied root path or exception messages to a child-process log. - */ -final class FileserverCrashScenarioMain { - - static final int CRASH_EXIT_CODE = 91; - static final String RECOVERY_SUCCESS = "RECOVERY_SUCCESS"; - static final String RECOVERY_INDETERMINATE_QUARANTINED = "RECOVERY_INDETERMINATE_QUARANTINED"; - static final String LOCK_ACQUIRED = "LOCK_ACQUIRED"; - static final String LOCK_BUSY = "LOCK_BUSY"; - static final String LOCK_RELEASED = "LOCK_RELEASED"; - - private static final int SCENARIO_FAILURE_EXIT_CODE = 70; - private static final int ARGUMENT_FAILURE_EXIT_CODE = 64; - private static final String OPERATION_ID = "operation-r2-01"; - private static final String SOURCE_REVISION = "source-42"; - private static final byte[] EXPECTED_PAYLOAD = "id,note\n1,'=cmd\n".getBytes(UTF_8); - - private FileserverCrashScenarioMain() {} - - public static void main(String[] arguments) { - try { - run(arguments); - } catch (Throwable failure) { - System.out.println("SCENARIO_FAILED"); - System.out.flush(); - Runtime.getRuntime().halt(SCENARIO_FAILURE_EXIT_CODE); - } - } - - private static void run(String[] arguments) throws IOException { - if (arguments.length < 2) { - Runtime.getRuntime().halt(ARGUMENT_FAILURE_EXIT_CODE); - } - ScenarioMode mode = ScenarioMode.valueOf(arguments[0]); - Path root = Path.of(arguments[1]).toAbsolutePath().normalize(); - switch (mode) { - case CRASH -> { - if (arguments.length != 3) { - Runtime.getRuntime().halt(ARGUMENT_FAILURE_EXIT_CODE); - } - crash(root, CrashBoundary.valueOf(arguments[2])); - } - case RECOVER -> { - if (arguments.length != 2) { - Runtime.getRuntime().halt(ARGUMENT_FAILURE_EXIT_CODE); - } - recover(root); - } - case LOCK_HOLD -> { - if (arguments.length != 2) { - Runtime.getRuntime().halt(ARGUMENT_FAILURE_EXIT_CODE); - } - holdOperationLock(root); - } - case LOCK_TRY -> { - if (arguments.length != 2) { - Runtime.getRuntime().halt(ARGUMENT_FAILURE_EXIT_CODE); - } - tryOperationLock(root); - } - default -> Runtime.getRuntime().halt(ARGUMENT_FAILURE_EXIT_CODE); - } - } - - private static void crash(Path root, CrashBoundary boundary) throws IOException { - LocalPersistentPublicationTestFixture fixture = - LocalPersistentPublicationTestFixture.create(root); - LocalPersistentControlPlane controlPlane = - fixture.controlPlane(context -> boundary.haltAt(context)); - LocalPersistentPayloadOperations payload = fixture.payload(context -> boundary.haltAt(context)); - fixture - .provider(controlPlane, payload, fixture::fileId) - .publish( - fixture.request(SOURCE_REVISION), - sink -> sink.write(new TabularRow(List.of(new IntegerCell(1), new TextCell("=cmd"))))); - System.out.println("CRASH_BOUNDARY_NOT_REACHED"); - System.out.flush(); - Runtime.getRuntime().halt(SCENARIO_FAILURE_EXIT_CODE); - } - - private static void recover(Path root) throws IOException { - ScenarioRuntime runtime = ScenarioRuntime.open(root); - AtomicInteger producerCalls = new AtomicInteger(); - AtomicInteger fileIdCalls = new AtomicInteger(); - try { - FilePublishReceipt receipt = - runtime - .provider( - () -> { - fileIdCalls.incrementAndGet(); - throw new AssertionError("recovery allocated a new file ID"); - }) - .publish( - runtime.request(), - sink -> { - producerCalls.incrementAndGet(); - throw new AssertionError("recovery replayed the producer"); - }); - require(producerCalls.get() == 0, "producer was replayed"); - require(fileIdCalls.get() == 0, "file ID was reallocated"); - requireExactReceiptAndArtifacts(runtime, receipt); - emit(RECOVERY_SUCCESS); - } catch (FilePublicationException failure) { - require( - failure.reason() == FilePublicationException.Reason.PUBLISH_INDETERMINATE, - "recovery failed with a non-indeterminate reason"); - require(producerCalls.get() == 0, "producer was replayed"); - require(fileIdCalls.get() == 0, "file ID was reallocated"); - DurablePublicationRecord retained = - runtime.controlPlane().findOperation(OPERATION_ID).orElseThrow(); - require( - retained.state() == DurablePublicationRecord.State.QUARANTINED, - "indeterminate recovery did not retain quarantine evidence"); - require(countRegularFiles(runtime.root().resolve("data")) == 0, "partial final data exists"); - emit(RECOVERY_INDETERMINATE_QUARANTINED); - } - } - - private static void holdOperationLock(Path root) throws IOException { - ScenarioRuntime runtime = ScenarioRuntime.open(root); - try (LocalPersistentControlPlane.OperationLock ignored = - runtime.controlPlane().acquireOperationLock(OPERATION_ID)) { - emit(LOCK_ACQUIRED); - try (BufferedReader input = new BufferedReader(new InputStreamReader(System.in, UTF_8))) { - String command = input.readLine(); - require("RELEASE".equals(command), "lock holder received an invalid command"); - } - } - emit(LOCK_RELEASED); - } - - private static void tryOperationLock(Path root) throws IOException { - Path lockFile = operationLockPath(root, OPERATION_ID); - require( - Files.isRegularFile(lockFile, LinkOption.NOFOLLOW_LINKS) && !Files.isSymbolicLink(lockFile), - "operation lock file is unavailable"); - try (FileChannel channel = - FileChannel.open( - lockFile, Set.of(StandardOpenOption.WRITE, LinkOption.NOFOLLOW_LINKS)); - FileLock lock = channel.tryLock()) { - emit(lock == null ? LOCK_BUSY : LOCK_ACQUIRED); - } - } - - private static void requireExactReceiptAndArtifacts( - ScenarioRuntime runtime, FilePublishReceipt receipt) throws IOException { - String expectedFileName = - LocalPersistentRecoveryVerifier.generatedFileName( - LocalPersistentPublicationTestFixture.FILE_ID); - String expectedDigest = LocalPersistentPublicationTestFixture.sha256(EXPECTED_PAYLOAD); - require(receipt.operationId().value().equals(OPERATION_ID), "operation ID changed"); - require( - receipt.destinationId().equals(LocalPersistentPublicationTestFixture.DESTINATION), - "destination changed"); - require(receipt.publishedFileName().equals(expectedFileName), "file name changed"); - require(receipt.version().value().equals(expectedDigest), "version changed"); - require(receipt.formatProfileId().equals("csv-rfc4180-v1"), "format changed"); - require(receipt.mediaType().equals("text/csv"), "media type changed"); - require(receipt.charset().equals(UTF_8.name()), "charset changed"); - require(receipt.byteSize() == EXPECTED_PAYLOAD.length, "byte size changed"); - require(receipt.dataRowCount() == 1, "row count changed"); - require(receipt.columnCount() == 2, "column count changed"); - require(receipt.sha256().equals(expectedDigest), "payload digest changed"); - require( - receipt.publishedAt().equals(LocalPersistentPublicationTestFixture.PUBLISHED_AT), - "publication time changed"); - require( - receipt.publicationGuarantee() == PublicationGuarantee.UNIQUE_ATOMIC_CREATE, - "publication guarantee changed"); - require( - receipt.durabilityGuarantee() == DurabilityGuarantee.FILE_AND_DIRECTORY_SYNC, - "durability guarantee changed"); - require(receipt.formulaMitigatedCount() == 1, "formula count changed"); - - R2PublishedReferenceCodec.DecodedReference reference = - new R2PublishedReferenceCodec() - .decode(receipt.reference(), Set.of(runtime.destination().routeToken())); - require( - reference.fileId().equals(LocalPersistentPublicationTestFixture.FILE_ID), - "reference file ID changed"); - Path data = - runtime - .root() - .resolve("data") - .resolve(LocalPersistentPublicationTestFixture.FILE_ID.substring(0, 2)) - .resolve(expectedFileName); - require( - Arrays.equals(Files.readAllBytes(data), EXPECTED_PAYLOAD), - "published data is partial or different"); - require(countRegularFiles(runtime.root().resolve("data")) == 1, "unexpected final data exists"); - - DurablePublicationRecord operation = - runtime.controlPlane().findOperation(OPERATION_ID).orElseThrow(); - require( - operation.state() == DurablePublicationRecord.State.PUBLISHED, - "terminal operation was not restored"); - require( - runtime - .controlPlane() - .findManifest(LocalPersistentPublicationTestFixture.FILE_ID) - .isPresent(), - "manifest is absent"); - require( - runtime - .controlPlane() - .findReference(LocalPersistentPublicationTestFixture.FILE_ID) - .isPresent(), - "reference is absent"); - } - - private static long countRegularFiles(Path directory) throws IOException { - if (!Files.exists(directory, LinkOption.NOFOLLOW_LINKS)) { - return 0; - } - try (var files = Files.walk(directory)) { - return files.filter(path -> Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS)).count(); - } - } - - private static Path operationLockPath(Path root, String operationId) { - String token = sha256(operationId); - return root.resolve(".ca-fileserver") - .resolve("operations") - .resolve(token.substring(0, 2)) - .resolve(token + ".lock"); - } - - private static String sha256(String value) { - try { - return HexFormat.of() - .formatHex(MessageDigest.getInstance("SHA-256").digest(value.getBytes(UTF_8))); - } catch (NoSuchAlgorithmException failure) { - throw new AssertionError("SHA-256 must be available", failure); - } - } - - private static void emit(String marker) { - System.out.println(marker); - System.out.flush(); - } - - private static void require(boolean condition, String message) { - if (!condition) { - throw new IllegalStateException(message); - } - } - - enum CrashBoundary { - J_WRITING, - STAGE_FORCED, - J_SEALED, - DATA_LINKED, - DATA_DIRECTORY_FORCED, - MANIFEST_FORCED, - MANIFEST_DIRECTORY_FORCED, - REFERENCE_FORCED, - REFERENCE_DIRECTORY_FORCED, - TERMINAL_JOURNAL_FORCED, - TERMINAL_JOURNAL_DIRECTORY_FORCED; - - void haltAt(LocalPersistentControlPlane.FaultContext context) { - if (matches(context)) { - Runtime.getRuntime().halt(CRASH_EXIT_CODE); - } - } - - void haltAt(LocalPersistentPayloadOperations.FaultContext context) { - if (matches(context)) { - Runtime.getRuntime().halt(CRASH_EXIT_CODE); - } - } - - boolean permitsIndeterminateQuarantine() { - return this == J_WRITING || this == STAGE_FORCED; - } - - private boolean matches(LocalPersistentControlPlane.FaultContext context) { - return switch (this) { - case J_WRITING -> - operationAt( - context, - DurablePublicationRecord.State.WRITING, - LocalPersistentControlPlane.FaultPoint.PARENT_FORCED); - case J_SEALED -> - operationAt( - context, - DurablePublicationRecord.State.SEALED, - LocalPersistentControlPlane.FaultPoint.PARENT_FORCED); - case MANIFEST_FORCED -> - immutableAt( - context, - LocalPersistentControlPlane.ControlRecordKind.MANIFEST, - LocalPersistentControlPlane.FaultPoint.TEMP_FORCED); - case MANIFEST_DIRECTORY_FORCED -> - immutableAt( - context, - LocalPersistentControlPlane.ControlRecordKind.MANIFEST, - LocalPersistentControlPlane.FaultPoint.PARENT_FORCED); - case REFERENCE_FORCED -> - immutableAt( - context, - LocalPersistentControlPlane.ControlRecordKind.REFERENCE, - LocalPersistentControlPlane.FaultPoint.TEMP_FORCED); - case REFERENCE_DIRECTORY_FORCED -> - immutableAt( - context, - LocalPersistentControlPlane.ControlRecordKind.REFERENCE, - LocalPersistentControlPlane.FaultPoint.PARENT_FORCED); - case TERMINAL_JOURNAL_FORCED -> - operationAt( - context, - DurablePublicationRecord.State.PUBLISHED, - LocalPersistentControlPlane.FaultPoint.TEMP_FORCED); - case TERMINAL_JOURNAL_DIRECTORY_FORCED -> - operationAt( - context, - DurablePublicationRecord.State.PUBLISHED, - LocalPersistentControlPlane.FaultPoint.PARENT_FORCED); - default -> false; - }; - } - - private boolean matches(LocalPersistentPayloadOperations.FaultContext context) { - return switch (this) { - case STAGE_FORCED -> - context.point() == LocalPersistentPayloadOperations.FaultPoint.STAGE_FORCED; - case DATA_LINKED -> - context.point() == LocalPersistentPayloadOperations.FaultPoint.DATA_LINKED; - case DATA_DIRECTORY_FORCED -> - context.point() == LocalPersistentPayloadOperations.FaultPoint.DATA_DIRECTORY_FORCED; - default -> false; - }; - } - - private static boolean operationAt( - LocalPersistentControlPlane.FaultContext context, - DurablePublicationRecord.State state, - LocalPersistentControlPlane.FaultPoint point) { - Optional operation = context.operation(); - return context.recordKind() == LocalPersistentControlPlane.ControlRecordKind.OPERATION - && context.boundary() == point - && operation.isPresent() - && operation.orElseThrow().state() == state; - } - - private static boolean immutableAt( - LocalPersistentControlPlane.FaultContext context, - LocalPersistentControlPlane.ControlRecordKind kind, - LocalPersistentControlPlane.FaultPoint point) { - return context.recordKind() == kind - && context.operation().isEmpty() - && context.boundary() == point; - } - } - - private enum ScenarioMode { - CRASH, - RECOVER, - LOCK_HOLD, - LOCK_TRY - } - - private record ScenarioRuntime( - Path root, - CompiledFileDestination destination, - LocalPersistentControlPlane controlPlane, - LocalPersistentPayloadOperations payload) { - - private static ScenarioRuntime open(Path root) throws IOException { - Path normalizedRoot = root.toAbsolutePath().normalize(); - FileStore store = Files.getFileStore(normalizedRoot); - Set rootMode = PosixFilePermissions.fromString("rwx------"); - FileDestinationId destinationId = LocalPersistentPublicationTestFixture.DESTINATION; - CompiledFileDestination destination = - new CompiledFileDestination( - destinationId, - "local-primary", - normalizedRoot, - 10_000, - 16 * 1024 * 1024, - store.name(), - store.type(), - LocalPersistentPublicationTestFixture.SENTINEL_NAME, - LocalPersistentPublicationTestFixture.sha256( - LocalPersistentPublicationTestFixture.SENTINEL_CONTENT), - Files.getOwner(normalizedRoot).getName(), - "0700", - rootMode, - PublicationGuarantee.UNIQUE_ATOMIC_CREATE, - DurabilityGuarantee.FILE_AND_DIRECTORY_SYNC); - LocalPersistentRootAttestor attestor = new LocalPersistentRootAttestor(); - LocalPersistentRootEvidence evidence = attestor.attest(destination); - return new ScenarioRuntime( - normalizedRoot, - destination, - new LocalPersistentControlPlane(attestor, evidence), - new LocalPersistentPayloadOperations(attestor, evidence)); - } - - private FilePublishRequest request() { - return new FilePublishRequest( - new FilePublishOperationId(OPERATION_ID), - LocalPersistentPublicationTestFixture.DESTINATION, - new LogicalFileName("report"), - new SourceRevision(SOURCE_REVISION), - new ExportSchema( - "worklog-v1", - 1, - List.of( - new Column("id", CellType.INTEGER, false, FormulaPolicy.REJECT, 64), - new Column("note", CellType.TEXT, false, FormulaPolicy.MITIGATE, 256))), - "csv-rfc4180-v1"); - } - - private LocalPersistentPublicationProvider provider( - LocalPersistentPublicationProvider.FileIdGenerator fileIds) { - LocalPersistentPublicationProvider.DestinationRuntime runtime = - new LocalPersistentPublicationProvider.DestinationRuntime( - destination, controlPlane, payload); - return new LocalPersistentPublicationProvider( - Map.of(LocalPersistentPublicationTestFixture.DESTINATION, runtime), - LocalPersistentPublicationTestFixture.FIXED_CLOCK, - fileIds); - } - } -} diff --git a/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/FileserverR2ConfigTest.java b/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/FileserverR2ConfigTest.java deleted file mode 100644 index f780c119..00000000 --- a/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/FileserverR2ConfigTest.java +++ /dev/null @@ -1,534 +0,0 @@ -package dev.caskeleton.adapter.outbound.fileserver; - -import static java.nio.charset.StandardCharsets.UTF_8; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.application.fileexport.FileExportPort; -import dev.caskeleton.application.filepublication.ExportSchema; -import dev.caskeleton.application.filepublication.ExportSchema.CellType; -import dev.caskeleton.application.filepublication.ExportSchema.Column; -import dev.caskeleton.application.filepublication.ExportSchema.FormulaPolicy; -import dev.caskeleton.application.filepublication.FileDestinationId; -import dev.caskeleton.application.filepublication.FilePublicationException; -import dev.caskeleton.application.filepublication.FilePublicationPort; -import dev.caskeleton.application.filepublication.FilePublishOperationId; -import dev.caskeleton.application.filepublication.FilePublishRequest; -import dev.caskeleton.application.filepublication.LogicalFileName; -import dev.caskeleton.application.filepublication.SourceRevision; -import java.io.IOException; -import java.lang.reflect.Field; -import java.nio.file.FileStore; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.attribute.PosixFilePermissions; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.HexFormat; -import java.util.List; -import java.util.Map; -import java.util.concurrent.atomic.AtomicInteger; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; -import org.springframework.boot.test.context.runner.ApplicationContextRunner; - -@SuppressWarnings("removal") -class FileserverR2ConfigTest { - - private static final String SENTINEL_NAME = ".ca-fileserver-volume"; - private static final byte[] SENTINEL_CONTENT = "fileserver-r2-config-test\n".getBytes(UTF_8); - - @TempDir Path temporaryDirectory; - - private final ApplicationContextRunner r2Runner = - new ApplicationContextRunner().withUserConfiguration(FileserverR2Config.class); - - @Test - void disabledR2CreatesNoPortOrFilesystemSideEffect() { - Path absentRoot = temporaryDirectory.resolve("disabled-root").toAbsolutePath().normalize(); - - r2Runner - .withPropertyValues( - "app.fileserver.enabled=false", - destinationProperty("local-export", "provider-ref", "local-primary"), - providerProperty("local-primary", "type", "local-persistent"), - providerProperty("local-primary", "root-directory", absentRoot.toString())) - .run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context).doesNotHaveBean(FileserverR2Settings.class); - assertThat(context).doesNotHaveBean(FilePublicationPort.class); - assertThat(absentRoot).doesNotExist(); - }); - } - - @Test - void enabledR2CreatesExactlyOneRoutingPortAndAttestsTheRealPosixRoot() throws IOException { - RootFixture root = preProvisionedRoot("enabled"); - - r2Runner - .withPropertyValues(validProperties(root, "local-export")) - .run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context).hasSingleBean(FilePublicationPort.class); - assertThat(context.getBean(FilePublicationPort.class)) - .isInstanceOf(RoutingFilePublicationAdapter.class); - assertThat(root.path().resolve(".ca-fileserver")).isDirectory(); - assertThat(root.path().resolve("data")).isDirectory(); - }); - } - - @Test - void requestForUnknownDestinationFailsBeforeProducerInvocation() throws IOException { - RootFixture root = preProvisionedRoot("unknown-destination"); - - r2Runner - .withPropertyValues(validProperties(root, "configured-export")) - .run( - context -> { - assertThat(context).hasNotFailed(); - AtomicInteger producerCalls = new AtomicInteger(); - FilePublicationPort port = context.getBean(FilePublicationPort.class); - - assertThatThrownBy( - () -> - port.publish( - request("unknown-export"), - sink -> { - producerCalls.incrementAndGet(); - throw new AssertionError( - "an unknown destination must not invoke the producer"); - })) - .isInstanceOfSatisfying( - FilePublicationException.class, - exception -> - assertThat(exception.reason()) - .isEqualTo(FilePublicationException.Reason.INVALID_REQUEST)); - assertThat(producerCalls).hasValue(0); - }); - } - - @Test - void destinationsBoundToOneProviderReuseOneProviderRuntime() throws Exception { - RootFixture root = preProvisionedRoot("shared-provider"); - String[] properties = - concatenate( - validProperties(root, "daily-export"), - destinationProperties("monthly-export", "local-primary")); - - r2Runner - .withPropertyValues(properties) - .run( - context -> { - assertThat(context).hasNotFailed(); - RoutingFilePublicationAdapter router = - context.getBean(RoutingFilePublicationAdapter.class); - Map routes = routes(router); - - assertThat(routes).hasSize(2); - assertThat(routes.keySet()) - .containsExactlyInAnyOrder( - new FileDestinationId("daily-export"), - new FileDestinationId("monthly-export")); - FilePublicationProvider daily = routes.get(new FileDestinationId("daily-export")); - assertThat(routes.get(new FileDestinationId("monthly-export"))).isSameAs(daily); - }); - } - - @Test - void destinationsBoundToDifferentProvidersUseDifferentProviderRuntimes() throws Exception { - RootFixture primaryRoot = preProvisionedRoot("multi-provider-primary"); - RootFixture secondaryRoot = preProvisionedRoot("multi-provider-secondary"); - String[] properties = - concatenate( - validProperties(primaryRoot, "daily-export"), - destinationProperties("monthly-export", "secondary"), - providerProperties(secondaryRoot, "secondary", "local-persistent")); - - r2Runner - .withPropertyValues(properties) - .run( - context -> { - assertThat(context).hasNotFailed(); - RoutingFilePublicationAdapter router = - context.getBean(RoutingFilePublicationAdapter.class); - Map routes = routes(router); - - assertThat(routes).hasSize(2); - assertThat(routes.get(new FileDestinationId("daily-export"))) - .isNotSameAs(routes.get(new FileDestinationId("monthly-export"))); - assertThat(primaryRoot.path().resolve(".ca-fileserver")).isDirectory(); - assertThat(secondaryRoot.path().resolve(".ca-fileserver")).isDirectory(); - }); - } - - @Test - void enablingLegacyR1AndR2TogetherFailsBeforeEitherFilesystemIsMutated() throws IOException { - assertAmbiguousActivationHasNoSideEffects( - preProvisionedRoot("ambiguous-r2-r1-first"), - temporaryDirectory.resolve("ambiguous-r1-r1-first").toAbsolutePath().normalize(), - temporaryDirectory.resolve("ambiguous-legacy-r1-first").toAbsolutePath().normalize(), - FileExportConfig.class, - FileserverR2Config.class); - assertAmbiguousActivationHasNoSideEffects( - preProvisionedRoot("ambiguous-r2-r2-first"), - temporaryDirectory.resolve("ambiguous-r1-r2-first").toAbsolutePath().normalize(), - temporaryDirectory.resolve("ambiguous-legacy-r2-first").toAbsolutePath().normalize(), - FileserverR2Config.class, - FileExportConfig.class); - } - - private static void assertAmbiguousActivationHasNoSideEffects( - RootFixture r2Root, - Path r1Root, - Path legacyRoot, - Class firstConfiguration, - Class secondConfiguration) { - new ApplicationContextRunner() - .withUserConfiguration(firstConfiguration, secondConfiguration) - .withPropertyValues(validProperties(r2Root, "local-export")) - .withPropertyValues( - "app.file-export.enabled=true", - "app.file-export.legacy-enabled=true", - "app.file-export.base-directory=" + r1Root, - "app.file-export.legacy-base-directory=" + legacyRoot) - .run( - context -> { - assertThat(context) - .hasFailed() - .getFailure() - .hasRootCauseMessage( - "app.file-export.enabled and app.fileserver.enabled cannot both be true"); - assertThat(r2Root.path().resolve(".ca-fileserver")).doesNotExist(); - assertThat(r2Root.path().resolve("data")).doesNotExist(); - assertThat(r1Root).doesNotExist(); - assertThat(legacyRoot).doesNotExist(); - }); - } - - @Test - void legacyR1AloneRemainsAvailableWhenR2IsDisabled() { - Path r1Root = temporaryDirectory.resolve("r1-only").toAbsolutePath().normalize(); - - new ApplicationContextRunner() - .withUserConfiguration(FileserverR2Config.class, FileExportConfig.class) - .withPropertyValues( - "app.fileserver.enabled=false", - "app.file-export.enabled=true", - "app.file-export.base-directory=" + r1Root) - .run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context).hasSingleBean(FilePublicationPort.class); - assertThat(context.getBean(FilePublicationPort.class)) - .isInstanceOf(LocalFilePublicationAdapter.class); - assertThat(context).doesNotHaveBean(RoutingFilePublicationAdapter.class); - assertThat(context).doesNotHaveBean(FileExportPort.class); - }); - } - - @ParameterizedTest - @ValueSource(strings = {"shared-mounted", "sftp"}) - void configuredButUnimplementedProviderTypeFailsWithoutCreatingItsRoot(String providerType) { - Path absentRoot = - temporaryDirectory.resolve("unsupported-" + providerType).toAbsolutePath().normalize(); - String[] properties = - validProperties(absentRoot, "local-export", "local-primary", providerType); - - r2Runner - .withPropertyValues(properties) - .run( - context -> { - assertThat(context) - .hasFailed() - .getFailure() - .hasRootCauseMessage( - "provider local-primary type must be exactly local-persistent"); - assertThat(absentRoot).doesNotExist(); - }); - } - - @Test - void providerTypeHasNoDefault() { - Path absentRoot = temporaryDirectory.resolve("missing-type").toAbsolutePath().normalize(); - String[] properties = - without( - validProperties(absentRoot, "local-export", "local-primary", "local-persistent"), - providerProperty("local-primary", "type", "local-persistent")); - - r2Runner - .withPropertyValues(properties) - .run( - context -> { - assertThat(context) - .hasFailed() - .getFailure() - .hasRootCauseMessage( - "provider local-primary type must be exactly local-persistent"); - assertThat(absentRoot).doesNotExist(); - }); - } - - @Test - void missingAndUnknownProviderReferencesFailBeforeAttestation() throws IOException { - RootFixture missingReferenceRoot = preProvisionedRoot("missing-provider-ref"); - String[] missingReference = - without( - validProperties(missingReferenceRoot, "local-export"), - destinationProperty("local-export", "provider-ref", "local-primary")); - - r2Runner - .withPropertyValues(missingReference) - .run( - context -> { - assertThat(context).hasFailed(); - assertThat(missingReferenceRoot.path().resolve(".ca-fileserver")).doesNotExist(); - assertThat(missingReferenceRoot.path().resolve("data")).doesNotExist(); - }); - - RootFixture unknownReferenceRoot = preProvisionedRoot("unknown-provider-ref"); - String[] unknownReference = - replace( - validProperties(unknownReferenceRoot, "local-export"), - destinationProperty("local-export", "provider-ref", "local-primary"), - destinationProperty("local-export", "provider-ref", "missing-provider")); - - r2Runner - .withPropertyValues(unknownReference) - .run( - context -> { - assertThat(context) - .hasFailed() - .getFailure() - .hasRootCauseMessage( - "destination local-export references unknown provider-ref missing-provider"); - assertThat(unknownReferenceRoot.path().resolve(".ca-fileserver")).doesNotExist(); - assertThat(unknownReferenceRoot.path().resolve("data")).doesNotExist(); - }); - } - - @Test - void unknownConfigurationFieldIsRejectedInsteadOfSilentlyIgnored() throws IOException { - RootFixture root = preProvisionedRoot("unknown-field"); - - r2Runner - .withPropertyValues(validProperties(root, "local-export")) - .withPropertyValues(providerProperty("local-primary", "strict-path-securty", "true")) - .run( - context -> { - assertThat(context).hasFailed(); - assertThat(root.path().resolve(".ca-fileserver")).doesNotExist(); - assertThat(root.path().resolve("data")).doesNotExist(); - }); - } - - @ParameterizedTest - @ValueSource(strings = {"app.fileserver.enabld=true", "app.fileserver.enabled=not-a-boolean"}) - void aSelectorThatDoesNotEnableTheCapabilityDoesNotBindItsSettings(String selector) - throws IOException { - RootFixture root = preProvisionedRoot("invalid-selector"); - String[] configured = - replace(validProperties(root, "local-export"), "app.fileserver.enabled=true", selector); - - r2Runner - .withPropertyValues(configured) - .run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context).doesNotHaveBean(FileserverR2Settings.class); - assertThat(context).doesNotHaveBean(FilePublicationPort.class); - assertThat(root.path().resolve(".ca-fileserver")).doesNotExist(); - assertThat(root.path().resolve("data")).doesNotExist(); - }); - } - - @Test - void differentProviderIdsCannotOwnTheSameNormalizedRoot() throws IOException { - RootFixture root = preProvisionedRoot("duplicate-root"); - String[] firstProvider = validProperties(root, "first-export"); - String[] secondProvider = - concatenate( - destinationProperties("second-export", "secondary"), - providerProperties(root, "secondary", "local-persistent")); - - r2Runner - .withPropertyValues(concatenate(firstProvider, secondProvider)) - .run( - context -> { - assertThat(context).hasFailed(); - assertThat(root.path().resolve(".ca-fileserver")).doesNotExist(); - assertThat(root.path().resolve("data")).doesNotExist(); - }); - } - - @Test - void unreferencedProviderStillCannotClaimAnotherProviderRoot() throws IOException { - RootFixture root = preProvisionedRoot("unreferenced-duplicate-root"); - String[] configured = - concatenate( - validProperties(root, "first-export"), - providerProperties(root, "unreferenced-secondary", "local-persistent")); - - r2Runner - .withPropertyValues(configured) - .run( - context -> { - assertThat(context) - .hasFailed() - .getFailure() - .hasRootCauseMessage( - "different fileserver provider IDs cannot share one root directory"); - assertThat(root.path().resolve(".ca-fileserver")).doesNotExist(); - assertThat(root.path().resolve("data")).doesNotExist(); - }); - } - - @SuppressWarnings("unchecked") - private static Map routes( - RoutingFilePublicationAdapter router) { - try { - Field routes = RoutingFilePublicationAdapter.class.getDeclaredField("routes"); - routes.setAccessible(true); - return (Map) routes.get(router); - } catch (ReflectiveOperationException exception) { - throw new LinkageError("routing adapter route inspection failed", exception); - } - } - - private RootFixture preProvisionedRoot(String name) throws IOException { - Path root = temporaryDirectory.resolve(name).toAbsolutePath().normalize(); - Files.createDirectory( - root, PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwx------"))); - Path sentinel = - Files.createFile( - root.resolve(SENTINEL_NAME), - PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-------"))); - Files.write(sentinel, SENTINEL_CONTENT); - FileStore fileStore = Files.getFileStore(root); - return new RootFixture( - root, - fileStore.name(), - fileStore.type(), - Files.getOwner(root).getName(), - sha256(SENTINEL_CONTENT)); - } - - private static String[] validProperties(RootFixture root, String destinationId) { - return validProperties(root.path(), destinationId, "local-primary", "local-persistent"); - } - - private static String[] validProperties( - Path root, String destinationId, String providerId, String providerType) { - try { - FileStore fileStore = Files.getFileStore(root.getParent()); - return concatenate( - new String[] {"app.fileserver.enabled=true"}, - destinationProperties(destinationId, providerId), - providerProperties( - root, - providerId, - providerType, - fileStore.name(), - fileStore.type(), - Files.getOwner(root.getParent()).getName(), - sha256(SENTINEL_CONTENT))); - } catch (IOException exception) { - throw new AssertionError("test filesystem evidence must be readable", exception); - } - } - - private static String[] providerProperties( - RootFixture root, String providerId, String providerType) { - return providerProperties( - root.path(), - providerId, - providerType, - root.fileStoreName(), - root.fileStoreType(), - root.owner(), - root.sentinelSha256()); - } - - private static String[] providerProperties( - Path root, - String providerId, - String providerType, - String fileStoreName, - String fileStoreType, - String owner, - String sentinelSha256) { - return new String[] { - providerProperty(providerId, "type", providerType), - providerProperty(providerId, "root-directory", root.toString()), - providerProperty(providerId, "auto-create", "false"), - providerProperty(providerId, "strict-path-security", "true"), - providerProperty(providerId, "expected-file-store-name", fileStoreName), - providerProperty(providerId, "expected-file-store-type", fileStoreType), - providerProperty(providerId, "mount-sentinel-name", SENTINEL_NAME), - providerProperty(providerId, "mount-sentinel-sha256", sentinelSha256), - providerProperty(providerId, "expected-owner", owner), - providerProperty(providerId, "maximum-root-mode", "0700") - }; - } - - private static String[] destinationProperties(String destinationId, String providerId) { - return new String[] { - destinationProperty(destinationId, "provider-ref", providerId), - destinationProperty(destinationId, "required-publication", "unique-atomic-create"), - destinationProperty(destinationId, "required-durability", "file-and-directory-sync"), - destinationProperty(destinationId, "maximum-rows", "1000"), - destinationProperty(destinationId, "maximum-encoded-bytes", "1048576") - }; - } - - private static String destinationProperty(String destinationId, String property, String value) { - return "app.fileserver.destinations." + destinationId + "." + property + "=" + value; - } - - private static String providerProperty(String providerId, String property, String value) { - return "app.fileserver.providers." + providerId + "." + property + "=" + value; - } - - private static FilePublishRequest request(String destinationId) { - return new FilePublishRequest( - new FilePublishOperationId("routing-test-operation"), - new FileDestinationId(destinationId), - new LogicalFileName("routing-test"), - new SourceRevision("source-1"), - new ExportSchema( - "routing-schema", - 1, - List.of(new Column("id", CellType.INTEGER, false, FormulaPolicy.REJECT, 32))), - "csv-rfc4180-v1"); - } - - private static String sha256(byte[] bytes) { - try { - return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); - } catch (NoSuchAlgorithmException exception) { - throw new AssertionError("SHA-256 must be available", exception); - } - } - - private static String[] concatenate(String[]... groups) { - return java.util.Arrays.stream(groups).flatMap(java.util.Arrays::stream).toArray(String[]::new); - } - - private static String[] without(String[] values, String excluded) { - return java.util.Arrays.stream(values) - .filter(value -> !value.equals(excluded)) - .toArray(String[]::new); - } - - private static String[] replace(String[] values, String original, String replacement) { - return java.util.Arrays.stream(values) - .map(value -> value.equals(original) ? replacement : value) - .toArray(String[]::new); - } - - private record RootFixture( - Path path, String fileStoreName, String fileStoreType, String owner, String sentinelSha256) {} -} diff --git a/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/FilesystemCsvExportAdapterTest.java b/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/FilesystemCsvExportAdapterTest.java deleted file mode 100644 index 2a405b3b..00000000 --- a/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/FilesystemCsvExportAdapterTest.java +++ /dev/null @@ -1,138 +0,0 @@ -package dev.caskeleton.adapter.outbound.fileserver; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.application.fileexport.ExportedFile; -import dev.caskeleton.shared.error.DependencyFailureException; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.Arrays; -import java.util.List; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -/** Temp-dir CSV write/verify contract for {@link FilesystemCsvExportAdapter}. */ -@SuppressWarnings("removal") -class FilesystemCsvExportAdapterTest { - - private Path baseDir; - private FilesystemCsvExportAdapter adapter; - - @BeforeEach - void setUp(@TempDir Path tempDir) { - baseDir = tempDir; - adapter = new FilesystemCsvExportAdapter(tempDir.toString()); - } - - @Test - void exportsHeaderAndRowsWithCsvEscaping() throws IOException { - List header = List.of("id", "name", "note"); - List> rows = - List.of( - List.of("1", "plain", "ok"), - List.of("2", "has,comma", "quote\"inside"), - List.of("3", "line\nbreak", "trailing")); - - ExportedFile result = adapter.exportCsv("export.csv", header, rows); - - Path written = baseDir.resolve("export.csv"); - assertThat(written).exists(); - assertThat(result.fileName()).isEqualTo("export.csv"); - assertThat(result.reference().value()) - .startsWith("legacy-file-export:") - .doesNotContain(written.toAbsolutePath().normalize().toString()) - .doesNotContain(baseDir.toAbsolutePath().normalize().toString()); - assertThat(result.rowCount()).isEqualTo(3); - assertThat(result.byteSize()).isEqualTo(Files.size(written)); - - String content = Files.readString(written, StandardCharsets.UTF_8); - assertThat(content) - .isEqualTo( - """ - id,name,note - 1,plain,ok - 2,"has,comma","quote""inside" - 3,"line - break",trailing - """); - } - - @Test - void writesHeaderOnlyWhenRowsEmpty() throws IOException { - ExportedFile result = adapter.exportCsv("empty.csv", List.of("a", "b"), List.of()); - - assertThat(result.rowCount()).isZero(); - assertThat(Files.readString(baseDir.resolve("empty.csv"), StandardCharsets.UTF_8)) - .isEqualTo("a,b\n"); - } - - @Test - void writesNoHeaderLineWhenHeaderEmpty() throws IOException { - adapter.exportCsv("headerless.csv", List.of(), List.of(List.of("only", "data"))); - - assertThat(Files.readString(baseDir.resolve("headerless.csv"), StandardCharsets.UTF_8)) - .isEqualTo("only,data\n"); - } - - @Test - void nullFieldIsWrittenAsEmpty() throws IOException { - List rowWithNull = Arrays.asList("x", null, "z"); - adapter.exportCsv("nulls.csv", List.of("a", "b", "c"), List.of(rowWithNull)); - - assertThat(Files.readString(baseDir.resolve("nulls.csv"), StandardCharsets.UTF_8)) - .isEqualTo("a,b,c\nx,,z\n"); - } - - @Test - void refusesToOverwriteAnExistingExport() throws IOException { - adapter.exportCsv("dup.csv", List.of("a"), List.of(List.of("first"))); - - assertThatThrownBy(() -> adapter.exportCsv("dup.csv", List.of("a"), List.of(List.of("second")))) - .isInstanceOf(DependencyFailureException.class); - - assertThat(Files.readString(baseDir.resolve("dup.csv"), StandardCharsets.UTF_8)) - .as("a name collision must not destroy the export already at that name") - .isEqualTo("a\nfirst\n"); - } - - /** - * A CSV is data to this adapter and a program to the spreadsheet that opens it. - * - *

A leading {@code =} makes the cell an executable formula; {@code =cmd|'/c calc'!A1} runs a - * command on the reviewer's machine. RFC-4180 quoting does nothing about it — that is a parser - * concern, not an evaluation one. - */ - @Test - void neutralisesSpreadsheetFormulaText() throws IOException { - adapter.exportCsv( - "formula.csv", List.of("a"), List.of(List.of("=cmd|'/c calc'!A1"), List.of("-2+3"))); - - String written = Files.readString(baseDir.resolve("formula.csv"), StandardCharsets.UTF_8); - assertThat(written).doesNotContain("\n=cmd").doesNotContain("\n-2+3"); - assertThat(written).contains("'=cmd").contains("'-2+3"); - } - - @Test - void pathTraversalFileNameIsRejected() { - assertThatThrownBy(() -> adapter.exportCsv("../escape.csv", List.of("a"), List.of())) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void nestedControlLikePathIsRejected() { - assertThatThrownBy( - () -> - adapter.exportCsv(".ca-fileserver/operations/record.json", List.of("a"), List.of())) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void blankFileNameIsRejected() { - assertThatThrownBy(() -> adapter.exportCsv(" ", List.of("a"), List.of())) - .isInstanceOf(IllegalArgumentException.class); - } -} diff --git a/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/LocalFilePublicationAdapterTest.java b/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/LocalFilePublicationAdapterTest.java deleted file mode 100644 index f5895b81..00000000 --- a/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/LocalFilePublicationAdapterTest.java +++ /dev/null @@ -1,235 +0,0 @@ -package dev.caskeleton.adapter.outbound.fileserver; - -import static java.nio.charset.StandardCharsets.UTF_8; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.application.filepublication.ExportSchema; -import dev.caskeleton.application.filepublication.FileDestinationId; -import dev.caskeleton.application.filepublication.FilePublicationException; -import dev.caskeleton.application.filepublication.FilePublishOperationId; -import dev.caskeleton.application.filepublication.FilePublishReceipt; -import dev.caskeleton.application.filepublication.FilePublishRequest; -import dev.caskeleton.application.filepublication.LogicalFileName; -import dev.caskeleton.application.filepublication.SourceRevision; -import dev.caskeleton.application.filepublication.TabularCell.IntegerCell; -import dev.caskeleton.application.filepublication.TabularCell.TextCell; -import dev.caskeleton.application.filepublication.TabularRow; -import java.io.IOException; -import java.io.UncheckedIOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.security.MessageDigest; -import java.util.HexFormat; -import java.util.List; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.stream.Stream; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -class LocalFilePublicationAdapterTest { - - private static final FileDestinationId DESTINATION = new FileDestinationId("local-export"); - - @TempDir Path tempDir; - - private LocalFilePublicationAdapter adapter; - - @BeforeEach - void setUp() { - adapter = - new LocalFilePublicationAdapter( - new LocalFilePublicationPolicy(DESTINATION, tempDir, 10, 1024)); - } - - @Test - void publishesRowsThroughTheSinkAndReturnsAnOpaqueReceipt() throws IOException { - AtomicInteger producerCalls = new AtomicInteger(); - - FilePublishReceipt receipt = - adapter.publish( - request(), - sink -> { - producerCalls.incrementAndGet(); - sink.write(new TabularRow(List.of(new IntegerCell(1), new TextCell("=cmd")))); - }); - - assertThat(producerCalls).hasValue(1); - assertThat(receipt.reference().value()).doesNotContain(tempDir.toString()); - assertThat(receipt.sha256()).hasSize(64); - assertThat(receipt.dataRowCount()).isEqualTo(1); - assertThat(receipt.formulaMitigatedCount()).isEqualTo(1); - - Path published = onlyPublishedCsv(); - assertThat(Files.readString(published, UTF_8)).isEqualTo("id,note\n1,'=cmd\n"); - } - - @Test - void removesStagingAndLeavesNoFinalArtifactWhenByteLimitIsExceeded() throws IOException { - LocalFilePublicationAdapter tinyAdapter = - new LocalFilePublicationAdapter( - new LocalFilePublicationPolicy(DESTINATION, tempDir, 10, 16)); - - assertThatThrownBy( - () -> - tinyAdapter.publish( - request(), - sink -> - sink.write( - new TabularRow( - List.of(new IntegerCell(1), new TextCell("x".repeat(100))))))) - .isInstanceOf(FilePublicationException.class) - .hasMessageContaining("byte"); - - assertThat(publishedCsvFiles()).isEmpty(); - try (Stream staging = Files.list(tempDir.resolve(".staging"))) { - assertThat(staging).isEmpty(); - } - } - - @Test - void rejectsWrongCellTypeAndDeletesTheStagingFile() throws IOException { - assertThatThrownBy( - () -> - adapter.publish( - request(), - sink -> - sink.write( - new TabularRow( - List.of(new TextCell("not-an-id"), new TextCell("ok")))))) - .isInstanceOf(FilePublicationException.class) - .hasMessageContaining("cell type"); - - assertThat(publishedCsvFiles()).isEmpty(); - try (Stream staging = Files.list(tempDir.resolve(".staging"))) { - assertThat(staging).isEmpty(); - } - } - - @Test - void propagatesProducerFailureAndDeletesStaging() throws IOException { - IllegalStateException sourceFailure = new IllegalStateException("source unavailable"); - - assertThatThrownBy( - () -> - adapter.publish( - request(), - sink -> { - throw sourceFailure; - })) - .isSameAs(sourceFailure); - - assertThat(publishedCsvFiles()).isEmpty(); - try (Stream staging = Files.list(tempDir.resolve(".staging"))) { - assertThat(staging).isEmpty(); - } - } - - @Test - void targetConflictAfterSealingPreservesTheOnlyRecoveryArtifact() throws Exception { - FilePublishRequest request = request(); - String token = - HexFormat.of() - .formatHex( - MessageDigest.getInstance("SHA-256") - .digest(request.operationId().value().getBytes(UTF_8))) - .substring(0, 24); - Path target = tempDir.resolve(request.logicalFileName().value() + "--" + token + ".csv"); - - assertThatThrownBy( - () -> - adapter.publish( - request, - sink -> { - sink.write(new TabularRow(List.of(new IntegerCell(1), new TextCell("ok")))); - try { - Files.writeString(target, "collision", UTF_8); - } catch (IOException exception) { - throw new UncheckedIOException(exception); - } - })) - .isInstanceOfSatisfying( - FilePublicationException.class, - exception -> - assertThat(exception.reason()).isEqualTo(FilePublicationException.Reason.CONFLICT)); - - assertThat(Files.readString(target, UTF_8)).isEqualTo("collision"); - try (Stream staging = Files.list(tempDir.resolve(".staging"))) { - assertThat(staging.filter(Files::isRegularFile)).hasSize(1); - } - } - - @Test - void unavailableAtomicPrimitiveFailsClosedAndPreservesTheSealedStage() throws Exception { - LocalFilePublicationPolicy failClosedPolicy = - new LocalFilePublicationPolicy(DESTINATION, tempDir, 10, 1024); - LocalFilePublicationAdapter failingAdapter = - new LocalFilePublicationAdapter( - failClosedPolicy, - (target, staging) -> { - throw new IOException("hard links unavailable"); - }); - FilePublishRequest request = request(); - String token = - HexFormat.of() - .formatHex( - MessageDigest.getInstance("SHA-256") - .digest(request.operationId().value().getBytes(UTF_8))) - .substring(0, 24); - Path target = tempDir.resolve(request.logicalFileName().value() + "--" + token + ".csv"); - - assertThatThrownBy( - () -> - failingAdapter.publish( - request, - sink -> - sink.write( - new TabularRow(List.of(new IntegerCell(1), new TextCell("ok")))))) - .isInstanceOfSatisfying( - FilePublicationException.class, - exception -> - assertThat(exception.reason()) - .isEqualTo(FilePublicationException.Reason.UNAVAILABLE)); - assertThat(target).doesNotExist(); - try (Stream staging = Files.list(tempDir.resolve(".staging"))) { - assertThat(staging.filter(Files::isRegularFile)).hasSize(1); - } - } - - private FilePublishRequest request() { - return new FilePublishRequest( - new FilePublishOperationId("01J1234567890ABCDEFGHJKMNP"), - DESTINATION, - new LogicalFileName("worklogs"), - new SourceRevision("snapshot-42"), - new ExportSchema( - "worklog-v1", - 1, - List.of( - new ExportSchema.Column( - "id", - ExportSchema.CellType.INTEGER, - false, - ExportSchema.FormulaPolicy.REJECT, - 64), - new ExportSchema.Column( - "note", - ExportSchema.CellType.TEXT, - false, - ExportSchema.FormulaPolicy.MITIGATE, - 128))), - "csv-rfc4180-v1"); - } - - private Path onlyPublishedCsv() throws IOException { - assertThat(publishedCsvFiles()).hasSize(1); - return publishedCsvFiles().getFirst(); - } - - private List publishedCsvFiles() throws IOException { - try (Stream files = Files.list(tempDir)) { - return files.filter(path -> path.getFileName().toString().endsWith(".csv")).toList(); - } - } -} diff --git a/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/LocalFilePublicationRecoveryTest.java b/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/LocalFilePublicationRecoveryTest.java deleted file mode 100644 index 2d2ed602..00000000 --- a/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/LocalFilePublicationRecoveryTest.java +++ /dev/null @@ -1,280 +0,0 @@ -package dev.caskeleton.adapter.outbound.fileserver; - -import static java.nio.charset.StandardCharsets.UTF_8; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.application.filepublication.ExportSchema; -import dev.caskeleton.application.filepublication.ExportSchema.CellType; -import dev.caskeleton.application.filepublication.ExportSchema.Column; -import dev.caskeleton.application.filepublication.ExportSchema.FormulaPolicy; -import dev.caskeleton.application.filepublication.FileDestinationId; -import dev.caskeleton.application.filepublication.FilePublicationException; -import dev.caskeleton.application.filepublication.FilePublishOperationId; -import dev.caskeleton.application.filepublication.FilePublishReceipt; -import dev.caskeleton.application.filepublication.FilePublishRequest; -import dev.caskeleton.application.filepublication.LogicalFileName; -import dev.caskeleton.application.filepublication.SourceRevision; -import dev.caskeleton.application.filepublication.TabularCell.IntegerCell; -import dev.caskeleton.application.filepublication.TabularCell.TextCell; -import dev.caskeleton.application.filepublication.TabularRow; -import java.nio.file.Files; -import java.nio.file.Path; -import java.security.MessageDigest; -import java.util.HexFormat; -import java.util.List; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicReference; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -class LocalFilePublicationRecoveryTest { - - private static final FileDestinationId DESTINATION = new FileDestinationId("local-export"); - - @TempDir Path tempDir; - - private LocalFilePublicationPolicy policy; - - @BeforeEach - void setUp() { - policy = new LocalFilePublicationPolicy(DESTINATION, tempDir, 10, 1024); - } - - @Test - void completedOperationIsRestoredAfterRestartWithoutCallingProducer() { - LocalFilePublicationAdapter first = new LocalFilePublicationAdapter(policy); - FilePublishReceipt original = first.publish(request("source-1"), this::produceOneRow); - AtomicInteger producerCalls = new AtomicInteger(); - - FilePublishReceipt restored = - new LocalFilePublicationAdapter(policy) - .publish( - request("source-1"), - sink -> { - producerCalls.incrementAndGet(); - throw new AssertionError("terminal retry must not invoke producer"); - }); - - assertThat(producerCalls).hasValue(0); - assertThat(restored).isEqualTo(original); - } - - @Test - void reusedOperationIdWithDifferentIntentIsAConflict() { - new LocalFilePublicationAdapter(policy).publish(request("source-1"), this::produceOneRow); - AtomicInteger producerCalls = new AtomicInteger(); - - assertThatThrownBy( - () -> - new LocalFilePublicationAdapter(policy) - .publish(request("source-2"), sink -> producerCalls.incrementAndGet())) - .isInstanceOfSatisfying( - FilePublicationException.class, - exception -> - assertThat(exception.reason()).isEqualTo(FilePublicationException.Reason.CONFLICT)); - assertThat(producerCalls).hasValue(0); - } - - @Test - void terminalRecordWithMutatedArtifactIsIndeterminate() throws Exception { - FilePublishReceipt receipt = - new LocalFilePublicationAdapter(policy).publish(request("source-1"), this::produceOneRow); - Files.writeString(tempDir.resolve(receipt.publishedFileName()), "mutated", UTF_8); - AtomicInteger producerCalls = new AtomicInteger(); - - assertThatThrownBy( - () -> - new LocalFilePublicationAdapter(policy) - .publish(request("source-1"), sink -> producerCalls.incrementAndGet())) - .isInstanceOfSatisfying( - FilePublicationException.class, - exception -> - assertThat(exception.reason()) - .isEqualTo(FilePublicationException.Reason.PUBLISH_INDETERMINATE)); - assertThat(producerCalls).hasValue(0); - } - - @Test - void corruptOperationJournalIsMappedToTheProviderNeutralIndeterminateFailure() throws Exception { - FilePublishRequest request = request("source-1"); - new LocalFilePublicationAdapter(policy).publish(request, this::produceOneRow); - LocalPublicationJournal journal = new LocalPublicationJournal(tempDir); - Files.writeString( - journal.recordPath(request.operationId().value()), "{\"corrupt\":true}", UTF_8); - - assertThatThrownBy( - () -> new LocalFilePublicationAdapter(policy).publish(request, this::produceOneRow)) - .isInstanceOfSatisfying( - FilePublicationException.class, - exception -> - assertThat(exception.reason()) - .isEqualTo(FilePublicationException.Reason.PUBLISH_INDETERMINATE)); - } - - @Test - void sealedStagingIsPublishedAfterRestartWithoutCallingProducer() throws Exception { - FilePublishRequest request = request("source-1"); - String operationToken = token(request.operationId().value()); - String stageName = "." + operationToken + ".part"; - String publishedName = request.logicalFileName().value() + "--" + operationToken + ".csv"; - byte[] payload = "id,note\n1,ok\n".getBytes(UTF_8); - String digest = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(payload)); - Path stagingDirectory = tempDir.resolve(".staging"); - Files.createDirectories(stagingDirectory); - Files.write(stagingDirectory.resolve(stageName), payload); - LocalPublicationJournal journal = new LocalPublicationJournal(tempDir); - journal.store( - LocalPublicationJournalRecord.sealed( - request.operationId().value(), - FilePublishRequestFingerprint.calculate(request), - publishedName, - stageName, - payload.length, - 1, - 2, - digest, - 0)); - AtomicInteger producerCalls = new AtomicInteger(); - - FilePublishReceipt receipt = - new LocalFilePublicationAdapter(policy) - .publish(request, sink -> producerCalls.incrementAndGet()); - - assertThat(producerCalls).hasValue(0); - assertThat(Files.readAllBytes(tempDir.resolve(publishedName))).isEqualTo(payload); - assertThat(receipt.sha256()).isEqualTo(digest); - } - - @Test - void sealedTargetRecoveryReconstructsTheHardLinkCommitWithoutCallingProducer() throws Exception { - FilePublishRequest request = request("source-1"); - String operationToken = token(request.operationId().value()); - String stageName = "." + operationToken + ".part"; - String publishedName = request.logicalFileName().value() + "--" + operationToken + ".csv"; - byte[] payload = "id,note\n1,ok\n".getBytes(UTF_8); - String digest = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(payload)); - Files.write(tempDir.resolve(publishedName), payload); - new LocalPublicationJournal(tempDir) - .store( - LocalPublicationJournalRecord.sealed( - request.operationId().value(), - FilePublishRequestFingerprint.calculate(request), - publishedName, - stageName, - payload.length, - 1, - 2, - digest, - 0)); - - FilePublishReceipt receipt = - new LocalFilePublicationAdapter(policy) - .publish( - request, - sink -> { - throw new AssertionError("sealed target recovery must not invoke producer"); - }); - - assertThat(receipt.publicationGuarantee()) - .isEqualTo(FilePublishReceipt.PublicationGuarantee.UNIQUE_ATOMIC_CREATE); - } - - @Test - void concurrentAdaptersSerializeOneOperationAndInvokeTheProducerOnce() throws Exception { - LocalFilePublicationAdapter firstAdapter = new LocalFilePublicationAdapter(policy); - LocalFilePublicationAdapter secondAdapter = new LocalFilePublicationAdapter(policy); - CountDownLatch firstProducerStarted = new CountDownLatch(1); - CountDownLatch releaseFirstProducer = new CountDownLatch(1); - CountDownLatch secondCallStarted = new CountDownLatch(1); - CountDownLatch secondCallFinished = new CountDownLatch(1); - AtomicInteger producerCalls = new AtomicInteger(); - AtomicReference firstReceipt = new AtomicReference<>(); - AtomicReference secondReceipt = new AtomicReference<>(); - AtomicReference failure = new AtomicReference<>(); - Thread first = - Thread.ofPlatform() - .start( - () -> { - try { - firstReceipt.set( - firstAdapter.publish( - request("source-1"), - sink -> { - producerCalls.incrementAndGet(); - firstProducerStarted.countDown(); - try { - releaseFirstProducer.await(); - } catch (InterruptedException exception) { - Thread.currentThread().interrupt(); - throw new IllegalStateException(exception); - } - produceOneRow(sink); - })); - } catch (Throwable throwable) { - failure.compareAndSet(null, throwable); - } - }); - - assertThat(firstProducerStarted.await(1, TimeUnit.SECONDS)).isTrue(); - Thread second = - Thread.ofPlatform() - .start( - () -> { - secondCallStarted.countDown(); - try { - secondReceipt.set( - secondAdapter.publish( - request("source-1"), - sink -> { - producerCalls.incrementAndGet(); - produceOneRow(sink); - })); - } catch (Throwable throwable) { - failure.compareAndSet(null, throwable); - } finally { - secondCallFinished.countDown(); - } - }); - assertThat(secondCallStarted.await(1, TimeUnit.SECONDS)).isTrue(); - assertThat(secondCallFinished.await(100, TimeUnit.MILLISECONDS)).isFalse(); - - releaseFirstProducer.countDown(); - first.join(2_000); - second.join(2_000); - - assertThat(first.isAlive()).isFalse(); - assertThat(second.isAlive()).isFalse(); - assertThat(failure.get()).isNull(); - assertThat(producerCalls).hasValue(1); - assertThat(secondReceipt.get()).isEqualTo(firstReceipt.get()); - } - - private void produceOneRow(dev.caskeleton.application.filepublication.TabularRowSink sink) { - sink.write(new TabularRow(List.of(new IntegerCell(1), new TextCell("ok")))); - } - - private static FilePublishRequest request(String sourceRevision) { - return new FilePublishRequest( - new FilePublishOperationId("operation-1"), - DESTINATION, - new LogicalFileName("report"), - new SourceRevision(sourceRevision), - new ExportSchema( - "work-log", - 1, - List.of( - new Column("id", CellType.INTEGER, false, FormulaPolicy.REJECT, 32), - new Column("note", CellType.TEXT, false, FormulaPolicy.MITIGATE, 256))), - "csv-rfc4180-v1"); - } - - private static String token(String operationId) throws Exception { - return HexFormat.of() - .formatHex(MessageDigest.getInstance("SHA-256").digest(operationId.getBytes(UTF_8))) - .substring(0, 24); - } -} diff --git a/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/LocalPersistentControlPlaneTest.java b/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/LocalPersistentControlPlaneTest.java deleted file mode 100644 index a948982e..00000000 --- a/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/LocalPersistentControlPlaneTest.java +++ /dev/null @@ -1,2087 +0,0 @@ -package dev.caskeleton.adapter.outbound.fileserver; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.application.filepublication.FileDestinationId; -import dev.caskeleton.application.filepublication.FilePublishOperationId; -import dev.caskeleton.application.filepublication.FilePublishReceipt; -import dev.caskeleton.application.filepublication.FilePublishReceipt.DurabilityGuarantee; -import dev.caskeleton.application.filepublication.FilePublishReceipt.PublicationGuarantee; -import dev.caskeleton.application.filepublication.FileVersion; -import java.io.IOException; -import java.nio.channels.FileChannel; -import java.nio.channels.FileLock; -import java.nio.channels.OverlappingFileLockException; -import java.nio.charset.StandardCharsets; -import java.nio.file.FileStore; -import java.nio.file.Files; -import java.nio.file.LinkOption; -import java.nio.file.Path; -import java.nio.file.StandardOpenOption; -import java.nio.file.attribute.PosixFileAttributes; -import java.nio.file.attribute.PosixFilePermission; -import java.nio.file.attribute.PosixFilePermissions; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.time.Instant; -import java.util.ArrayList; -import java.util.HexFormat; -import java.util.List; -import java.util.Optional; -import java.util.Set; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.condition.EnabledOnOs; -import org.junit.jupiter.api.condition.OS; -import org.junit.jupiter.api.io.TempDir; - -@EnabledOnOs(OS.LINUX) -class LocalPersistentControlPlaneTest { - - private static final String OPERATION_ID = "customer/order:01"; - private static final String FILE_ID = "00112233445566778899aabbccddeeff"; - private static final String DIGEST_A = "a".repeat(64); - private static final String DIGEST_B = "b".repeat(64); - private static final String DIGEST_C = "c".repeat(64); - private static final String SENTINEL_NAME = ".ca-fileserver-volume"; - private static final byte[] SENTINEL_CONTENT = - "fileserver-r2-control-plane".getBytes(StandardCharsets.UTF_8); - private static final Instant CREATED_AT = Instant.parse("2026-07-28T01:02:03Z"); - private static final Instant SEALED_AT = Instant.parse("2026-07-28T01:02:04Z"); - private static final Instant PUBLISHED_AT = Instant.parse("2026-07-28T01:02:05Z"); - - @TempDir Path tempDirectory; - private final AtomicInteger rootSequence = new AtomicInteger(); - - @Test - void storesAndDirectlyLoadsOperationManifestAndReferenceRecords() throws IOException { - ControlFixture fixture = controlFixture(); - Path root = fixture.root(); - LocalPersistentControlPlane controlPlane = fixture.controlPlane(); - DurablePublicationRecord operation = writingRecord(); - PrivateFileManifest manifest = manifest(); - PublishedReferenceRecord reference = referenceRecord(); - - controlPlane.storeOperation(operation); - controlPlane.storeManifest(manifest); - controlPlane.storeReference(reference); - - LocalPersistentControlPlane reopened = fixture.controlPlane(); - assertThat(reopened.findOperation(OPERATION_ID)).contains(operation); - assertThat(reopened.findManifest(FILE_ID)).contains(manifest); - assertThat(reopened.findReference(FILE_ID)).contains(reference); - String operationToken = sha256(OPERATION_ID.getBytes(StandardCharsets.UTF_8)); - assertThat( - root.resolve(".ca-fileserver/operations") - .resolve(operationToken.substring(0, 2)) - .resolve(operationToken + ".json")) - .isRegularFile(); - assertThat(root.resolve(".ca-fileserver/operations/customer")).doesNotExist(); - } - - @Test - void typedOperationLookupDispatchesCanonicalR2AndTerminalR1FromTheSameHashedPath() - throws IOException { - ControlFixture r2Fixture = controlFixture(); - r2Fixture.controlPlane().storeOperation(writingRecord()); - - assertThat(r2Fixture.controlPlane().findStoredOperation(OPERATION_ID)) - .contains(new LocalPersistentControlPlane.R2StoredOperationRecord(writingRecord())); - - ControlFixture r1Fixture = controlFixture(); - LocalPublicationJournalRecord published = publishedR1Record(OPERATION_ID); - writeR1Operation( - r1Fixture.root(), OPERATION_ID, LocalPublicationJournalCodec.encode(published)); - byte[] before = Files.readAllBytes(operationPath(r1Fixture.root(), OPERATION_ID)); - - assertThat(r1Fixture.controlPlane().findStoredOperation(OPERATION_ID)) - .contains(new LocalPersistentControlPlane.R1StoredOperationRecord(published)); - assertThat(Files.readAllBytes(operationPath(r1Fixture.root(), OPERATION_ID))).isEqualTo(before); - assertThat(r1Fixture.root().resolve(".ca-fileserver/manifests")).isEmptyDirectory(); - assertThat(r1Fixture.root().resolve(".ca-fileserver/references")).isEmptyDirectory(); - assertFailureKind( - LocalPersistentControlPlane.FailureKind.INTEGRITY, - () -> r1Fixture.controlPlane().findOperation(OPERATION_ID)); - assertFailureKind( - LocalPersistentControlPlane.FailureKind.INTEGRITY, - () -> r1Fixture.controlPlane().storeOperation(writingRecord())); - assertThat(Files.readAllBytes(operationPath(r1Fixture.root(), OPERATION_ID))).isEqualTo(before); - } - - @Test - void typedOperationLookupRejectsMalformedNonCanonicalNonTerminalAndWrongIdentityR1() - throws IOException { - byte[] canonical = LocalPublicationJournalCodec.encode(publishedR1Record(OPERATION_ID)); - byte[] whitespace = - new String(canonical, StandardCharsets.UTF_8) - .replace("{", "{ ") - .getBytes(StandardCharsets.UTF_8); - byte[] reordered = - new String(canonical, StandardCharsets.UTF_8) - .replace( - "{\"schemaVersion\":1,\"state\":\"PUBLISHED\"", - "{\"state\":\"PUBLISHED\",\"schemaVersion\":1") - .getBytes(StandardCharsets.UTF_8); - byte[] escaped = - new String(canonical, StandardCharsets.UTF_8) - .replace( - "\"operationId\":\"customer/order:01\"", "\"operationId\":\"customer\\/order:01\"") - .getBytes(StandardCharsets.UTF_8); - LocalPublicationJournalRecord sealed = - LocalPublicationJournalRecord.sealed( - OPERATION_ID, DIGEST_A, "report.csv", "customer-order-01.part", 42, 1, 2, DIGEST_C, 0); - List invalid = - List.of( - new byte[] {(byte) 0xc3, (byte) 0x28}, - whitespace, - reordered, - escaped, - LocalPublicationJournalCodec.encode(sealed), - LocalPublicationJournalCodec.encode( - LocalPublicationJournalRecord.writing( - OPERATION_ID, DIGEST_A, "report.csv", "customer-order-01.part")), - LocalPublicationJournalCodec.encode(publishedR1Record("other/order:02")), - "{}".getBytes(StandardCharsets.UTF_8), - new String(canonical, StandardCharsets.UTF_8) - .replace("\"schemaVersion\":1", "\"schemaVersion\":3") - .getBytes(StandardCharsets.UTF_8)); - - for (byte[] encoded : invalid) { - ControlFixture fixture = controlFixture(); - writeR1Operation(fixture.root(), OPERATION_ID, encoded); - - assertFailureKind( - LocalPersistentControlPlane.FailureKind.INTEGRITY, - () -> fixture.controlPlane().findStoredOperation(OPERATION_ID)); - } - } - - @Test - void contextualFaultsIdentifyRecordBoundaryIdentityAndApplicableOperationRevision() - throws IOException { - ControlFixture fixture = controlFixture(); - List contexts = new ArrayList<>(); - LocalPersistentControlPlane controlPlane = fixture.contextualControlPlane(contexts::add); - - controlPlane.storeOperation(writingRecord()); - controlPlane.storeManifest(manifest()); - controlPlane.storeReference(referenceRecord()); - - assertThat(contexts) - .containsExactly( - operationFault(LocalPersistentControlPlane.FaultPoint.TEMP_FORCED), - operationFault(LocalPersistentControlPlane.FaultPoint.RECORD_REPLACED), - operationFault(LocalPersistentControlPlane.FaultPoint.PARENT_FORCED), - immutableFault( - LocalPersistentControlPlane.ControlRecordKind.MANIFEST, - LocalPersistentControlPlane.FaultPoint.TEMP_FORCED), - immutableFault( - LocalPersistentControlPlane.ControlRecordKind.MANIFEST, - LocalPersistentControlPlane.FaultPoint.RECORD_REPLACED), - immutableFault( - LocalPersistentControlPlane.ControlRecordKind.MANIFEST, - LocalPersistentControlPlane.FaultPoint.PARENT_FORCED), - immutableFault( - LocalPersistentControlPlane.ControlRecordKind.REFERENCE, - LocalPersistentControlPlane.FaultPoint.TEMP_FORCED), - immutableFault( - LocalPersistentControlPlane.ControlRecordKind.REFERENCE, - LocalPersistentControlPlane.FaultPoint.RECORD_REPLACED), - immutableFault( - LocalPersistentControlPlane.ControlRecordKind.REFERENCE, - LocalPersistentControlPlane.FaultPoint.PARENT_FORCED)); - } - - @Test - void contextualParentFaultRetryReportsTheSameRepairSubjectAndPreservesCleanupOrder() - throws IOException { - ControlFixture fixture = controlFixture(); - List contexts = new ArrayList<>(); - AtomicBoolean failOnce = new AtomicBoolean(true); - InjectedFault original = new InjectedFault(); - LocalPersistentControlPlane controlPlane = - fixture.contextualControlPlane( - context -> { - contexts.add(context); - if (context.boundary() == LocalPersistentControlPlane.FaultPoint.PARENT_FORCED - && failOnce.getAndSet(false)) { - throw original; - } - }); - - assertThatThrownBy(() -> controlPlane.storeOperation(writingRecord())).isSameAs(original); - controlPlane.storeOperation(writingRecord()); - - assertThat(contexts) - .containsExactly( - operationFault(LocalPersistentControlPlane.FaultPoint.TEMP_FORCED), - operationFault(LocalPersistentControlPlane.FaultPoint.RECORD_REPLACED), - operationFault(LocalPersistentControlPlane.FaultPoint.PARENT_FORCED), - operationFault(LocalPersistentControlPlane.FaultPoint.PARENT_FORCED)); - assertThat(controlPlane.findOperation(OPERATION_ID)).contains(writingRecord()); - } - - @Test - void initialOperationMustBeWritingAtItsMinimumRevision() throws IOException { - for (DurablePublicationRecord invalidInitial : - List.of( - sealedRecord(2), - progressedRecord(DurablePublicationRecord.State.PUBLISHED, 6), - quarantinedFrom(writingRecord(), 2), - writingRecord(2))) { - LocalPersistentControlPlane controlPlane = controlFixture().controlPlane(); - - assertFailureKind( - LocalPersistentControlPlane.FailureKind.CONFLICT, - () -> controlPlane.storeOperation(invalidInitial)); - assertThat(controlPlane.findOperation(OPERATION_ID)).isEmpty(); - } - } - - @Test - void operationRevisionFingerprintIdentityAndStateAreMonotonic() throws IOException { - List points = new ArrayList<>(); - LocalPersistentControlPlane controlPlane = controlFixture().controlPlane(points::add); - DurablePublicationRecord original = storeSealedOperation(controlPlane); - - points.clear(); - controlPlane.storeOperation(original); - - assertThat(points).containsExactly(LocalPersistentControlPlane.FaultPoint.PARENT_FORCED); - assertThat(controlPlane.findOperation(OPERATION_ID)).contains(original); - assertFailureKind( - LocalPersistentControlPlane.FailureKind.CONFLICT, - () -> controlPlane.storeOperation(writingRecord(1))); - - assertFailureKind( - LocalPersistentControlPlane.FailureKind.CONFLICT, - () -> - controlPlane.storeOperation( - operationRecord( - 2, - DurablePublicationRecord.State.SEALED, - OPERATION_ID, - DIGEST_A, - "policy-v1", - DIGEST_B, - "local-export", - "local-primary", - FILE_ID, - "routea1", - "report.csv", - "customer-order-01.part", - CREATED_AT.minusSeconds(1)))); - assertFailureKind( - LocalPersistentControlPlane.FailureKind.CONFLICT, - () -> - controlPlane.storeOperation( - operationRecord( - 3, - DurablePublicationRecord.State.SEALED, - OPERATION_ID, - DIGEST_C, - "policy-v1", - DIGEST_B, - "local-export", - "local-primary", - FILE_ID, - "routea1", - "report.csv", - "customer-order-01.part", - CREATED_AT))); - - for (DurablePublicationRecord incompatible : - List.of( - operationRecord( - 3, - DurablePublicationRecord.State.SEALED, - "other/order:02", - DIGEST_A, - "policy-v1", - DIGEST_B, - "local-export", - "local-primary", - FILE_ID, - "routea1", - "report.csv", - "customer-order-01.part", - CREATED_AT), - operationRecord( - 3, - DurablePublicationRecord.State.SEALED, - OPERATION_ID, - DIGEST_A, - "policy-v1", - DIGEST_B, - "other-export", - "local-primary", - FILE_ID, - "routea1", - "report.csv", - "customer-order-01.part", - CREATED_AT), - operationRecord( - 3, - DurablePublicationRecord.State.SEALED, - OPERATION_ID, - DIGEST_A, - "policy-v1", - DIGEST_B, - "local-export", - "other-primary", - FILE_ID, - "routea1", - "report.csv", - "customer-order-01.part", - CREATED_AT), - operationRecord( - 3, - DurablePublicationRecord.State.SEALED, - OPERATION_ID, - DIGEST_A, - "policy-v1", - DIGEST_B, - "local-export", - "local-primary", - "f".repeat(32), - "routea1", - "report.csv", - "customer-order-01.part", - CREATED_AT), - operationRecord( - 3, - DurablePublicationRecord.State.SEALED, - OPERATION_ID, - DIGEST_A, - "policy-v1", - DIGEST_B, - "local-export", - "local-primary", - FILE_ID, - "routeb2", - "report.csv", - "customer-order-01.part", - CREATED_AT), - operationRecord( - 3, - DurablePublicationRecord.State.SEALED, - OPERATION_ID, - DIGEST_A, - "policy-v1", - DIGEST_B, - "local-export", - "local-primary", - FILE_ID, - "routea1", - "other.csv", - "customer-order-01.part", - CREATED_AT), - operationRecord( - 3, - DurablePublicationRecord.State.SEALED, - OPERATION_ID, - DIGEST_A, - "policy-v1", - DIGEST_B, - "local-export", - "local-primary", - FILE_ID, - "routea1", - "report.csv", - "other.part", - CREATED_AT), - operationRecord( - 3, - DurablePublicationRecord.State.SEALED, - OPERATION_ID, - DIGEST_A, - "policy-v2", - DIGEST_C, - "local-export", - "local-primary", - FILE_ID, - "routea1", - "report.csv", - "customer-order-01.part", - CREATED_AT))) { - assertFailureKind( - LocalPersistentControlPlane.FailureKind.CONFLICT, - () -> controlPlane.storeOperation(OPERATION_ID, incompatible)); - } - assertFailureKind( - LocalPersistentControlPlane.FailureKind.CONFLICT, - () -> controlPlane.storeOperation(writingRecord(3))); - assertThat(controlPlane.findOperation(OPERATION_ID)).contains(original); - } - - @Test - void operationTransitionsAreAdjacentAndPublishedIsTerminal() throws IOException { - LocalPersistentControlPlane jump = controlFixture().controlPlane(); - jump.storeOperation(writingRecord()); - assertFailureKind( - LocalPersistentControlPlane.FailureKind.CONFLICT, - () -> jump.storeOperation(progressedRecord(DurablePublicationRecord.State.PUBLISHED, 6))); - - LocalPersistentControlPlane sameState = controlFixture().controlPlane(); - storeSealedOperation(sameState); - assertFailureKind( - LocalPersistentControlPlane.FailureKind.CONFLICT, - () -> sameState.storeOperation(sealedRecord(3))); - - LocalPersistentControlPlane chain = controlFixture().controlPlane(); - chain.storeOperation(writingRecord()); - chain.storeOperation(sealedRecord(2)); - chain.storeOperation(progressedRecord(DurablePublicationRecord.State.DATA_PUBLISHED, 3)); - chain.storeOperation(progressedRecord(DurablePublicationRecord.State.MANIFEST_PUBLISHED, 4)); - chain.storeOperation(progressedRecord(DurablePublicationRecord.State.REFERENCE_PUBLISHED, 5)); - DurablePublicationRecord published = - progressedRecord(DurablePublicationRecord.State.PUBLISHED, 6); - chain.storeOperation(published); - - assertFailureKind( - LocalPersistentControlPlane.FailureKind.CONFLICT, - () -> chain.storeOperation(progressedRecord(DurablePublicationRecord.State.PUBLISHED, 7))); - assertFailureKind( - LocalPersistentControlPlane.FailureKind.CONFLICT, - () -> chain.storeOperation(quarantinedRecord(7))); - assertThat(chain.findOperation(OPERATION_ID)).contains(published); - } - - @Test - void everyNonTerminalStateCanOnlyEnterQuarantineOnceAndQuarantineIsTerminal() throws IOException { - List normalPath = - List.of( - writingRecord(), - sealedRecord(2), - progressedRecord(DurablePublicationRecord.State.DATA_PUBLISHED, 3), - progressedRecord(DurablePublicationRecord.State.MANIFEST_PUBLISHED, 4), - progressedRecord(DurablePublicationRecord.State.REFERENCE_PUBLISHED, 5)); - - for (int currentIndex = 0; currentIndex < normalPath.size(); currentIndex++) { - LocalPersistentControlPlane controlPlane = controlFixture().controlPlane(); - for (int prefixIndex = 0; prefixIndex <= currentIndex; prefixIndex++) { - controlPlane.storeOperation(normalPath.get(prefixIndex)); - } - DurablePublicationRecord current = normalPath.get(currentIndex); - DurablePublicationRecord quarantined = quarantinedFrom(current, current.stateRevision() + 1); - - controlPlane.storeOperation(quarantined); - controlPlane.storeOperation(quarantined); - assertFailureKind( - LocalPersistentControlPlane.FailureKind.CONFLICT, - () -> - controlPlane.storeOperation( - quarantinedFrom(quarantined, quarantined.stateRevision() + 1))); - assertThat(controlPlane.findOperation(OPERATION_ID)).contains(quarantined); - } - } - - @Test - void sealedFactsAndPublishedDigestsFreezeAcrossLaterRevisions() throws IOException { - LocalPersistentControlPlane controlPlane = controlFixture().controlPlane(); - storeSealedOperation(controlPlane); - - for (DurablePublicationRecord changedSealedFact : - List.of( - progressedRecord( - DurablePublicationRecord.State.DATA_PUBLISHED, - 3, - 43, - 1, - 2, - DIGEST_C, - 0, - SEALED_AT, - "", - ""), - progressedRecord( - DurablePublicationRecord.State.DATA_PUBLISHED, - 3, - 42, - 2, - 2, - DIGEST_C, - 0, - SEALED_AT, - "", - ""), - progressedRecord( - DurablePublicationRecord.State.DATA_PUBLISHED, - 3, - 42, - 1, - 3, - DIGEST_C, - 0, - SEALED_AT, - "", - ""), - progressedRecord( - DurablePublicationRecord.State.DATA_PUBLISHED, - 3, - 42, - 1, - 2, - DIGEST_A, - 0, - SEALED_AT, - "", - ""), - progressedRecord( - DurablePublicationRecord.State.DATA_PUBLISHED, - 3, - 42, - 1, - 2, - DIGEST_C, - 1, - SEALED_AT, - "", - ""), - progressedRecord( - DurablePublicationRecord.State.DATA_PUBLISHED, - 3, - 42, - 1, - 2, - DIGEST_C, - 0, - SEALED_AT.plusSeconds(1), - "", - ""))) { - assertFailureKind( - LocalPersistentControlPlane.FailureKind.CONFLICT, - () -> controlPlane.storeOperation(changedSealedFact)); - } - - controlPlane.storeOperation(progressedRecord(DurablePublicationRecord.State.DATA_PUBLISHED, 3)); - controlPlane.storeOperation( - progressedRecord(DurablePublicationRecord.State.MANIFEST_PUBLISHED, 4)); - assertFailureKind( - LocalPersistentControlPlane.FailureKind.CONFLICT, - () -> - controlPlane.storeOperation( - progressedRecord( - DurablePublicationRecord.State.REFERENCE_PUBLISHED, - 5, - 42, - 1, - 2, - DIGEST_C, - 0, - SEALED_AT, - DIGEST_C, - DIGEST_B))); - controlPlane.storeOperation( - progressedRecord(DurablePublicationRecord.State.REFERENCE_PUBLISHED, 5)); - assertFailureKind( - LocalPersistentControlPlane.FailureKind.CONFLICT, - () -> - controlPlane.storeOperation( - progressedRecord( - DurablePublicationRecord.State.PUBLISHED, - 6, - 42, - 1, - 2, - DIGEST_C, - 0, - SEALED_AT, - DIGEST_A, - DIGEST_C))); - assertThat(controlPlane.findOperation(OPERATION_ID)) - .contains(progressedRecord(DurablePublicationRecord.State.REFERENCE_PUBLISHED, 5)); - } - - @Test - void manifestAndReferenceAreImmutableIdempotentRecords() throws IOException { - LocalPersistentControlPlane controlPlane = controlFixture().controlPlane(); - PrivateFileManifest manifest = manifest(); - PublishedReferenceRecord reference = referenceRecord(); - - controlPlane.storeManifest(manifest); - controlPlane.storeManifest(manifest); - controlPlane.storeReference(reference); - controlPlane.storeReference(reference); - - assertFailureKind( - LocalPersistentControlPlane.FailureKind.CONFLICT, - () -> controlPlane.storeManifest(manifestWithSchemaId("worklog-v2"))); - assertFailureKind( - LocalPersistentControlPlane.FailureKind.CONFLICT, - () -> controlPlane.storeReference(referenceWithVersion("version-02"))); - assertThat(controlPlane.findManifest(FILE_ID)).contains(manifest); - assertThat(controlPlane.findReference(FILE_ID)).contains(reference); - } - - @Test - void forcedWriteFaultPointsAreStrictAndShardExistsBeforeTempForce() throws IOException { - ControlFixture fixture = controlFixture(); - List points = new ArrayList<>(); - Path shard = operationPath(fixture.root(), OPERATION_ID).getParent(); - LocalPersistentControlPlane controlPlane = - fixture.controlPlane( - point -> { - if (point == LocalPersistentControlPlane.FaultPoint.TEMP_FORCED) { - assertThat(shard).isDirectory(); - } - points.add(point); - }); - - controlPlane.storeOperation(writingRecord()); - - assertThat(points) - .containsExactly( - LocalPersistentControlPlane.FaultPoint.TEMP_FORCED, - LocalPersistentControlPlane.FaultPoint.RECORD_REPLACED, - LocalPersistentControlPlane.FaultPoint.PARENT_FORCED); - assertThat(controlPlane.findOperation(OPERATION_ID)).contains(writingRecord()); - } - - @Test - void corruptNewerAndMismatchedRecordsAreIntegrityFailuresNeverAbsent() throws IOException { - ControlFixture fixture = controlFixture(); - LocalPersistentControlPlane controlPlane = fixture.controlPlane(); - controlPlane.storeOperation(writingRecord()); - Path operationPath = operationPath(fixture.root(), OPERATION_ID); - - Files.writeString(operationPath, "{}", StandardCharsets.UTF_8); - assertFailureKind( - LocalPersistentControlPlane.FailureKind.INTEGRITY, - () -> controlPlane.findOperation(OPERATION_ID)); - - byte[] newer = - new String( - new FileserverControlRecordCodec().encodeOperation(writingRecord()), - StandardCharsets.UTF_8) - .replace("\"schemaVersion\":2", "\"schemaVersion\":3") - .getBytes(StandardCharsets.UTF_8); - Files.write(operationPath, newer); - assertFailureKind( - LocalPersistentControlPlane.FailureKind.INTEGRITY, - () -> controlPlane.findOperation(OPERATION_ID)); - - Files.write( - operationPath, - new FileserverControlRecordCodec() - .encodeOperation( - operationRecord( - 1, - DurablePublicationRecord.State.WRITING, - "other/order:02", - DIGEST_A, - "policy-v1", - DIGEST_B, - "local-export", - "local-primary", - FILE_ID, - "routea1", - "report.csv", - "other-order-02.part", - CREATED_AT))); - assertFailureKind( - LocalPersistentControlPlane.FailureKind.INTEGRITY, - () -> controlPlane.storeOperation(writingRecord())); - - controlPlane.storeManifest(manifest()); - Files.write( - manifestPath(fixture.root(), FILE_ID), - new FileserverControlRecordCodec() - .encodeManifest(manifestFor("f".repeat(32), "worklog-v1"))); - assertFailureKind( - LocalPersistentControlPlane.FailureKind.INTEGRITY, - () -> controlPlane.storeManifest(manifest())); - - controlPlane.storeReference(referenceRecord()); - Files.write( - referencePath(fixture.root(), FILE_ID), - new FileserverControlRecordCodec() - .encodeReference(referenceRecordFor("f".repeat(32), "version-01"))); - assertFailureKind( - LocalPersistentControlPlane.FailureKind.INTEGRITY, - () -> controlPlane.findReference(FILE_ID)); - } - - @Test - void retryAfterReplacementFaultRepairsParentForceWithoutIncompatibleOverwrite() - throws IOException { - ControlFixture fixture = controlFixture(); - List points = new ArrayList<>(); - AtomicBoolean failOnce = new AtomicBoolean(true); - LocalPersistentControlPlane controlPlane = - fixture.controlPlane( - point -> { - points.add(point); - if (point == LocalPersistentControlPlane.FaultPoint.RECORD_REPLACED - && failOnce.getAndSet(false)) { - throw new InjectedFault(); - } - }); - - assertThatThrownBy(() -> controlPlane.storeOperation(writingRecord())) - .isExactlyInstanceOf(InjectedFault.class); - assertFailureKind( - LocalPersistentControlPlane.FailureKind.CONFLICT, - () -> controlPlane.storeOperation(writingRecord(1, CREATED_AT.minusSeconds(1)))); - controlPlane.storeOperation(writingRecord()); - - assertThat(points) - .containsExactly( - LocalPersistentControlPlane.FaultPoint.TEMP_FORCED, - LocalPersistentControlPlane.FaultPoint.RECORD_REPLACED, - LocalPersistentControlPlane.FaultPoint.PARENT_FORCED); - assertThat(controlPlane.findOperation(OPERATION_ID)).contains(writingRecord()); - } - - @Test - void parentForcedCallbackFailureIsRepairedByIdenticalOperationRetry() throws IOException { - ControlFixture fixture = controlFixture(); - List points = new ArrayList<>(); - AtomicBoolean failOnce = new AtomicBoolean(true); - InjectedFault original = new InjectedFault(); - LocalPersistentControlPlane controlPlane = - fixture.controlPlane( - point -> { - points.add(point); - if (point == LocalPersistentControlPlane.FaultPoint.PARENT_FORCED - && failOnce.getAndSet(false)) { - throw original; - } - }); - - assertThatThrownBy(() -> controlPlane.storeOperation(writingRecord())).isSameAs(original); - controlPlane.storeOperation(writingRecord()); - - assertThat(points) - .containsExactly( - LocalPersistentControlPlane.FaultPoint.TEMP_FORCED, - LocalPersistentControlPlane.FaultPoint.RECORD_REPLACED, - LocalPersistentControlPlane.FaultPoint.PARENT_FORCED, - LocalPersistentControlPlane.FaultPoint.PARENT_FORCED); - assertThat(controlPlane.findOperation(OPERATION_ID)).contains(writingRecord()); - } - - @Test - void immutableHardLinkHasFullFaultOrderAndRepairsRecordAndParentFailures() throws IOException { - ControlFixture successfulFixture = controlFixture(); - List successfulPoints = new ArrayList<>(); - LocalPersistentControlPlane successful = successfulFixture.controlPlane(successfulPoints::add); - successful.storeManifest(manifest()); - assertThat(successfulPoints) - .containsExactly( - LocalPersistentControlPlane.FaultPoint.TEMP_FORCED, - LocalPersistentControlPlane.FaultPoint.RECORD_REPLACED, - LocalPersistentControlPlane.FaultPoint.PARENT_FORCED); - assertThat(successful.findManifest(FILE_ID)).contains(manifest()); - - ControlFixture recordFixture = controlFixture(); - List recordPoints = new ArrayList<>(); - AtomicBoolean failRecordOnce = new AtomicBoolean(true); - LocalPersistentControlPlane recordFailure = - recordFixture.controlPlane( - point -> { - recordPoints.add(point); - if (point == LocalPersistentControlPlane.FaultPoint.RECORD_REPLACED - && failRecordOnce.getAndSet(false)) { - throw new InjectedFault(); - } - }); - assertThatThrownBy(() -> recordFailure.storeManifest(manifest())) - .isExactlyInstanceOf(InjectedFault.class); - recordFailure.storeManifest(manifest()); - assertThat(recordPoints) - .containsExactly( - LocalPersistentControlPlane.FaultPoint.TEMP_FORCED, - LocalPersistentControlPlane.FaultPoint.RECORD_REPLACED, - LocalPersistentControlPlane.FaultPoint.PARENT_FORCED); - assertThat(recordFailure.findManifest(FILE_ID)).contains(manifest()); - - ControlFixture parentFixture = controlFixture(); - List parentPoints = new ArrayList<>(); - AtomicBoolean failParentOnce = new AtomicBoolean(true); - LocalPersistentControlPlane parentFailure = - parentFixture.controlPlane( - point -> { - parentPoints.add(point); - if (point == LocalPersistentControlPlane.FaultPoint.PARENT_FORCED - && failParentOnce.getAndSet(false)) { - throw new InjectedFault(); - } - }); - assertThatThrownBy(() -> parentFailure.storeManifest(manifest())) - .isExactlyInstanceOf(InjectedFault.class); - parentFailure.storeManifest(manifest()); - assertThat(parentPoints) - .containsExactly( - LocalPersistentControlPlane.FaultPoint.TEMP_FORCED, - LocalPersistentControlPlane.FaultPoint.RECORD_REPLACED, - LocalPersistentControlPlane.FaultPoint.PARENT_FORCED, - LocalPersistentControlPlane.FaultPoint.PARENT_FORCED); - assertThat(parentFailure.findManifest(FILE_ID)).contains(manifest()); - } - - @Test - void tempForceFailureCleansOnlyItsUniqueTemporaryFile() throws IOException { - ControlFixture fixture = controlFixture(); - Path shard = operationPath(fixture.root(), OPERATION_ID).getParent(); - Files.createDirectory( - shard, PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwx------"))); - Path bystander = Files.writeString(shard.resolve(".bystander.tmp"), "keep"); - LocalPersistentControlPlane controlPlane = - fixture.controlPlane( - point -> { - if (point == LocalPersistentControlPlane.FaultPoint.TEMP_FORCED) { - throw new InjectedFault(); - } - }); - - assertThatThrownBy(() -> controlPlane.storeOperation(writingRecord())) - .isExactlyInstanceOf(InjectedFault.class); - - assertThat(operationPath(fixture.root(), OPERATION_ID)).doesNotExist(); - assertThat(bystander).hasContent("keep"); - try (var entries = Files.list(shard)) { - assertThat(entries.map(path -> path.getFileName().toString())) - .containsExactlyInAnyOrder( - ".bystander.tmp", - operationLockPath(fixture.root(), OPERATION_ID).getFileName().toString()); - } - } - - @Test - void sameOperationLockSerializesAcrossInstancesAndHasExplicitClosePolicy() throws Exception { - ControlFixture fixture = controlFixture(); - LocalPersistentControlPlane first = fixture.controlPlane(); - LocalPersistentControlPlane second = fixture.controlPlane(); - ExecutorService executor = Executors.newSingleThreadExecutor(); - CountDownLatch attempted = new CountDownLatch(1); - CountDownLatch entered = new CountDownLatch(1); - LocalPersistentControlPlane.OperationLock firstLock = first.acquireOperationLock(OPERATION_ID); - try { - Future contender = - executor.submit( - () -> { - attempted.countDown(); - try (LocalPersistentControlPlane.OperationLock ignored = - second.acquireOperationLock(OPERATION_ID)) { - entered.countDown(); - } - }); - - assertThat(attempted.await(5, TimeUnit.SECONDS)).isTrue(); - assertThat(entered.await(200, TimeUnit.MILLISECONDS)).isFalse(); - firstLock.close(); - firstLock.close(); - assertThat(entered.await(5, TimeUnit.SECONDS)).isTrue(); - contender.get(5, TimeUnit.SECONDS); - - Path lockFile = operationLockPath(fixture.root(), OPERATION_ID); - assertThat(Files.isRegularFile(lockFile, LinkOption.NOFOLLOW_LINKS)).isTrue(); - assertThat(Files.getPosixFilePermissions(lockFile)) - .containsExactlyInAnyOrderElementsOf(PosixFilePermissions.fromString("rw-------")); - - LocalPersistentControlPlane.OperationLock ownerLock = - first.acquireOperationLock("customer/order:02"); - try { - Future wrongThreadClose = executor.submit(ownerLock::close); - assertThatThrownBy(() -> wrongThreadClose.get(5, TimeUnit.SECONDS)) - .isInstanceOf(ExecutionException.class) - .hasRootCauseInstanceOf(IllegalStateException.class); - } finally { - ownerLock.close(); - } - } finally { - firstLock.close(); - executor.shutdownNow(); - assertThat(executor.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); - } - } - - @Test - void storeOperationAcquiresTheFullOperationLockInternallyAcrossInstances() throws Exception { - ControlFixture fixture = controlFixture(); - LocalPersistentControlPlane first = fixture.controlPlane(); - LocalPersistentControlPlane second = fixture.controlPlane(); - ExecutorService executor = Executors.newSingleThreadExecutor(); - CountDownLatch attempted = new CountDownLatch(1); - CountDownLatch stored = new CountDownLatch(1); - LocalPersistentControlPlane.OperationLock firstLock = first.acquireOperationLock(OPERATION_ID); - try { - Future store = - executor.submit( - () -> { - attempted.countDown(); - second.storeOperation(writingRecord()); - stored.countDown(); - }); - - assertThat(attempted.await(5, TimeUnit.SECONDS)).isTrue(); - assertThat(stored.await(200, TimeUnit.MILLISECONDS)).isFalse(); - firstLock.close(); - assertThat(stored.await(5, TimeUnit.SECONDS)).isTrue(); - store.get(5, TimeUnit.SECONDS); - assertThat(first.findOperation(OPERATION_ID)).contains(writingRecord()); - } finally { - firstLock.close(); - executor.shutdownNow(); - assertThat(executor.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); - } - } - - @Test - void heldOperationReentrancyIsScopedToTheAttestedRoot() throws Exception { - ControlFixture rootA = controlFixture(); - ControlFixture rootB = controlFixture(); - LocalPersistentControlPlane firstRoot = rootA.controlPlane(); - LocalPersistentControlPlane secondRoot = rootB.controlPlane(); - ExecutorService executor = Executors.newFixedThreadPool(2); - CountDownLatch rootAHeld = new CountDownLatch(1); - CountDownLatch rootBHeld = new CountDownLatch(1); - CountDownLatch beginCrossRootStore = new CountDownLatch(1); - CountDownLatch releaseRootB = new CountDownLatch(1); - CountDownLatch stored = new CountDownLatch(1); - try { - Future crossRootStore = - executor.submit( - () -> { - try (LocalPersistentControlPlane.OperationLock ignored = - firstRoot.acquireOperationLock(OPERATION_ID)) { - rootAHeld.countDown(); - await(beginCrossRootStore); - secondRoot.storeOperation(writingRecord()); - stored.countDown(); - } - }); - assertThat(rootAHeld.await(5, TimeUnit.SECONDS)).isTrue(); - Future rootBHolder = - executor.submit( - () -> { - try (LocalPersistentControlPlane.OperationLock ignored = - secondRoot.acquireOperationLock(OPERATION_ID)) { - rootBHeld.countDown(); - await(releaseRootB); - } - }); - - assertThat(rootBHeld.await(5, TimeUnit.SECONDS)).isTrue(); - beginCrossRootStore.countDown(); - assertThat(stored.await(200, TimeUnit.MILLISECONDS)).isFalse(); - releaseRootB.countDown(); - assertThat(stored.await(5, TimeUnit.SECONDS)).isTrue(); - rootBHolder.get(5, TimeUnit.SECONDS); - crossRootStore.get(5, TimeUnit.SECONDS); - assertThat(secondRoot.findOperation(OPERATION_ID)).contains(writingRecord()); - } finally { - beginCrossRootStore.countDown(); - releaseRootB.countDown(); - executor.shutdownNow(); - assertThat(executor.awaitTermination(10, TimeUnit.SECONDS)).isTrue(); - } - } - - @Test - void operationLockAlsoHoldsTheStableOsFileLock() throws Exception { - ControlFixture fixture = controlFixture(); - LocalPersistentControlPlane controlPlane = fixture.controlPlane(); - LocalPersistentControlPlane.OperationLock operationLock = - controlPlane.acquireOperationLock(OPERATION_ID); - Path lockPath = operationLockPath(fixture.root(), OPERATION_ID); - try (FileChannel probe = - FileChannel.open(lockPath, StandardOpenOption.WRITE, LinkOption.NOFOLLOW_LINKS)) { - FileLock overlapping = null; - try { - overlapping = probe.tryLock(); - } catch (OverlappingFileLockException expected) { - // The held lock is independently visible to the JVM's OS-lock table. - } - assertThat(overlapping).isNull(); - - operationLock.close(); - try (FileLock acquiredAfterClose = probe.tryLock()) { - assertThat(acquiredAfterClose).isNotNull(); - } - } finally { - operationLock.close(); - } - } - - @Test - void operationLockClosePoisonsOnlyTheAttestedRootWhenUnlockCannotBeProven() throws Exception { - ControlFixture poisonedRoot = controlFixture(); - RecordingLockLifecycle lifecycle = new RecordingLockLifecycle(true, true); - LocalPersistentControlPlane poisoned = poisonedRoot.controlPlane(lifecycle); - LocalPersistentControlPlane.OperationLock lock = poisoned.acquireOperationLock(OPERATION_ID); - try { - assertFailureKind(LocalPersistentControlPlane.FailureKind.STORAGE, lock::close); - assertThat(poisoned.operationLockHeldByCurrentThread(OPERATION_ID)).isFalse(); - assertThat(poisoned.operationLockStripeHeldByCurrentThread(OPERATION_ID)).isFalse(); - - lifecycle.allowReleaseAndClose(); - ExecutorService executor = Executors.newSingleThreadExecutor(); - try { - assertFutureFailureKind( - LocalPersistentControlPlane.FailureKind.STORAGE, - executor.submit( - () -> { - try (LocalPersistentControlPlane.OperationLock ignored = - poisoned.acquireOperationLock(OPERATION_ID)) { - throw new AssertionError("poisoned root unexpectedly acquired a lock"); - } - })); - assertFutureFailureKind( - LocalPersistentControlPlane.FailureKind.STORAGE, - executor.submit(() -> poisoned.storeOperation(writingRecord()))); - assertFutureFailureKind( - LocalPersistentControlPlane.FailureKind.STORAGE, - executor.submit( - () -> { - try (LocalPersistentControlPlane.OperationLock ignored = - poisonedRoot.controlPlane().acquireOperationLock(OPERATION_ID)) { - throw new AssertionError("same-root instance ignored the poison latch"); - } - })); - } finally { - executor.shutdownNow(); - assertThat(executor.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); - } - - ControlFixture otherRoot = controlFixture(); - LocalPersistentControlPlane unaffected = otherRoot.controlPlane(); - unaffected.storeOperation(writingRecord()); - assertThat(unaffected.findOperation(OPERATION_ID)).contains(writingRecord()); - } finally { - lifecycle.forceCleanup(); - } - } - - @Test - void poisonedRootBlocksEveryWriteIncludingHeldLockFastPathButAllowsReads() throws Exception { - ControlFixture fixture = controlFixture(); - LocalPersistentControlPlane healthy = fixture.controlPlane(); - healthy.storeOperation(writingRecord()); - healthy.storeManifest(manifest()); - healthy.storeReference(referenceRecord()); - - LocalPersistentControlPlane.OperationLock held = healthy.acquireOperationLock(OPERATION_ID); - RecordingLockLifecycle lifecycle = new RecordingLockLifecycle(true, true); - LocalPersistentControlPlane poisoner = fixture.controlPlane(lifecycle); - ExecutorService executor = Executors.newSingleThreadExecutor(); - try { - assertFutureFailureKind( - LocalPersistentControlPlane.FailureKind.STORAGE, - executor.submit( - () -> { - try (LocalPersistentControlPlane.OperationLock ignored = - poisoner.acquireOperationLock("customer/order:poison")) { - // The injected close failure poisons this attested root. - } - })); - - assertFailureKind( - LocalPersistentControlPlane.FailureKind.STORAGE, - () -> healthy.storeOperation(writingRecord())); - assertFailureKind( - LocalPersistentControlPlane.FailureKind.STORAGE, () -> healthy.storeManifest(manifest())); - assertFailureKind( - LocalPersistentControlPlane.FailureKind.STORAGE, - () -> healthy.storeReference(referenceRecord())); - - assertThat(healthy.findOperation(OPERATION_ID)).contains(writingRecord()); - assertThat(healthy.findManifest(FILE_ID)).contains(manifest()); - assertThat(healthy.findReference(FILE_ID)).contains(referenceRecord()); - } finally { - held.close(); - lifecycle.forceCleanup(); - executor.shutdownNow(); - assertThat(executor.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); - } - } - - @Test - void releaseFailureWithSuccessfulChannelCloseReportsStorageWithoutPoisoning() throws Exception { - ControlFixture fixture = controlFixture(); - RecordingLockLifecycle lifecycle = new RecordingLockLifecycle(true, false); - LocalPersistentControlPlane controlPlane = fixture.controlPlane(lifecycle); - LocalPersistentControlPlane.OperationLock lock = - controlPlane.acquireOperationLock(OPERATION_ID); - - assertFailureKind(LocalPersistentControlPlane.FailureKind.STORAGE, lock::close); - assertThat(controlPlane.operationLockHeldByCurrentThread(OPERATION_ID)).isFalse(); - assertThat(controlPlane.operationLockStripeHeldByCurrentThread(OPERATION_ID)).isFalse(); - - lifecycle.allowReleaseAndClose(); - assertOperationLockCanBeAcquiredByAnotherThread(controlPlane); - controlPlane.storeOperation(writingRecord()); - assertThat(controlPlane.findOperation(OPERATION_ID)).contains(writingRecord()); - lifecycle.forceCleanup(); - } - - @Test - void successfulReleaseWithChannelCloseFailureReportsStorageWithoutPoisoning() throws Exception { - ControlFixture fixture = controlFixture(); - RecordingLockLifecycle lifecycle = new RecordingLockLifecycle(false, true); - LocalPersistentControlPlane controlPlane = fixture.controlPlane(lifecycle); - LocalPersistentControlPlane.OperationLock lock = - controlPlane.acquireOperationLock(OPERATION_ID); - try { - assertFailureKind(LocalPersistentControlPlane.FailureKind.STORAGE, lock::close); - assertThat(controlPlane.operationLockHeldByCurrentThread(OPERATION_ID)).isFalse(); - assertThat(controlPlane.operationLockStripeHeldByCurrentThread(OPERATION_ID)).isFalse(); - - lifecycle.allowReleaseAndClose(); - assertOperationLockCanBeAcquiredByAnotherThread(controlPlane); - controlPlane.storeOperation(writingRecord()); - assertThat(controlPlane.findOperation(OPERATION_ID)).contains(writingRecord()); - } finally { - lifecycle.forceCleanup(); - } - } - - @Test - void symlinkWrongTypeWrongModeAndOversizedRecordsFailAsIntegrityNeverAbsent() throws IOException { - ControlFixture fixture = controlFixture(); - LocalPersistentControlPlane controlPlane = fixture.controlPlane(); - Path operation = operationPath(fixture.root(), OPERATION_ID); - Path shard = operation.getParent(); - Path outside = Files.createDirectory(tempDirectory.resolve("outside")); - - Files.createSymbolicLink(shard, outside); - assertFailureKind( - LocalPersistentControlPlane.FailureKind.INTEGRITY, - () -> controlPlane.findOperation(OPERATION_ID)); - assertThat(outside).isEmptyDirectory(); - Files.delete(shard); - - Files.writeString(shard, "not-a-directory"); - assertFailureKind( - LocalPersistentControlPlane.FailureKind.INTEGRITY, - () -> controlPlane.findOperation(OPERATION_ID)); - Files.delete(shard); - - Files.createDirectory( - shard, PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwxr-x---"))); - assertFailureKind( - LocalPersistentControlPlane.FailureKind.INTEGRITY, - () -> controlPlane.findOperation(OPERATION_ID)); - Files.setPosixFilePermissions(shard, PosixFilePermissions.fromString("rwx------")); - - Path externalRecord = Files.writeString(outside.resolve("external.json"), "external-secret"); - Files.createSymbolicLink(operation, externalRecord); - assertFailureKind( - LocalPersistentControlPlane.FailureKind.INTEGRITY, - () -> controlPlane.findOperation(OPERATION_ID)); - assertThat(externalRecord).hasContent("external-secret"); - Files.delete(operation); - - Files.write(operation, new byte[16_385]); - assertFailureKind( - LocalPersistentControlPlane.FailureKind.INTEGRITY, - () -> controlPlane.findOperation(OPERATION_ID)); - } - - @Test - void recordIoUsesInjectedSecureShardRelativeOperationsForReadCreateStatAndDelete() - throws IOException { - ControlFixture fixture = controlFixture(); - RecordingSecureRecordOperations operations = new RecordingSecureRecordOperations(); - LocalPersistentControlPlane successful = - fixture.controlPlane(point -> {}, operations, fixture::verifyIdentity); - - successful.storeOperation(writingRecord()); - assertThat(successful.findOperation(OPERATION_ID)).contains(writingRecord()); - - LocalPersistentControlPlane failing = - fixture.controlPlane( - point -> { - if (point == LocalPersistentControlPlane.FaultPoint.TEMP_FORCED) { - throw new InjectedFault(); - } - }, - operations, - fixture::verifyIdentity); - assertThatThrownBy(() -> failing.storeOperation(sealedRecord(2))) - .isExactlyInstanceOf(InjectedFault.class); - - assertThat(operations.actions) - .contains( - LocalPersistentControlPlane.SecureRecordAction.STAT_SHARD_NOFOLLOW, - LocalPersistentControlPlane.SecureRecordAction.READ, - LocalPersistentControlPlane.SecureRecordAction.CREATE_NEW_AND_FORCE, - LocalPersistentControlPlane.SecureRecordAction.STAT_NOFOLLOW, - LocalPersistentControlPlane.SecureRecordAction.DELETE_EXACT); - assertThat(operations.calls) - .allSatisfy( - call -> { - assertThat(call.topDirectory()) - .isEqualTo(fixture.root().resolve(".ca-fileserver/operations")); - assertThat(call.shard()).matches("[0-9a-f]{2}"); - assertThat(Path.of(call.relativeFileName())).isRelative(); - assertThat(Path.of(call.relativeFileName()).getNameCount()).isEqualTo(1); - }); - assertThat(operations.shardCalls) - .allSatisfy( - call -> { - assertThat(call.topDirectory()) - .isEqualTo(fixture.root().resolve(".ca-fileserver/operations")); - assertThat(call.shard()).matches("[0-9a-f]{2}"); - }); - } - - @Test - void cleanupPreservesAReplacementWhoseNoFollowFileKeyDiffersFromCreatedTemp() throws IOException { - ControlFixture fixture = controlFixture(); - AtomicBoolean replaced = new AtomicBoolean(); - InjectedFault original = new InjectedFault(); - Path replacementSource = - Files.writeString(tempDirectory.resolve("replacement-source.tmp"), "replacement"); - LocalPersistentControlPlane controlPlane = - fixture.controlPlane( - point -> { - if (point == LocalPersistentControlPlane.FaultPoint.TEMP_FORCED) { - Path shard = operationPath(fixture.root(), OPERATION_ID).getParent(); - try (var paths = Files.list(shard)) { - Path temporary = - paths - .filter(path -> path.getFileName().toString().endsWith(".tmp")) - .findFirst() - .orElseThrow(); - Files.delete(temporary); - Files.move(replacementSource, temporary); - replaced.set(true); - } catch (IOException exception) { - throw new AssertionError(exception); - } - throw original; - } - }); - - assertThatThrownBy(() -> controlPlane.storeOperation(writingRecord())).isSameAs(original); - - assertThat(replaced).isTrue(); - Path shard = operationPath(fixture.root(), OPERATION_ID).getParent(); - try (var paths = Files.list(shard)) { - Path replacement = - paths - .filter(path -> path.getFileName().toString().endsWith(".tmp")) - .findFirst() - .orElseThrow(); - assertThat(replacement).hasContent("replacement"); - } - } - - @Test - void operationRejectsAndPreservesTempReplacementBeforeAtomicMove() throws IOException { - ControlFixture fixture = controlFixture(); - Path replacementSource = - Files.writeString(tempDirectory.resolve("operation-replacement.tmp"), "replacement"); - LocalPersistentControlPlane controlPlane = - fixture.controlPlane( - point -> { - if (point == LocalPersistentControlPlane.FaultPoint.TEMP_FORCED) { - replaceForcedTemporary( - operationPath(fixture.root(), OPERATION_ID).getParent(), replacementSource); - } - }); - - assertFailureKind( - LocalPersistentControlPlane.FailureKind.INTEGRITY, - () -> controlPlane.storeOperation(writingRecord())); - - assertThat(operationPath(fixture.root(), OPERATION_ID)).doesNotExist(); - assertThat(forcedTemporary(operationPath(fixture.root(), OPERATION_ID).getParent())) - .hasContent("replacement"); - } - - @Test - void immutableRejectsAndPreservesTempReplacementBeforeHardLink() throws IOException { - ControlFixture fixture = controlFixture(); - Path replacementSource = - Files.writeString(tempDirectory.resolve("manifest-replacement.tmp"), "replacement"); - LocalPersistentControlPlane controlPlane = - fixture.controlPlane( - point -> { - if (point == LocalPersistentControlPlane.FaultPoint.TEMP_FORCED) { - replaceForcedTemporary( - manifestPath(fixture.root(), FILE_ID).getParent(), replacementSource); - } - }); - - assertFailureKind( - LocalPersistentControlPlane.FailureKind.INTEGRITY, - () -> controlPlane.storeManifest(manifest())); - - assertThat(manifestPath(fixture.root(), FILE_ID)).doesNotExist(); - assertThat(forcedTemporary(manifestPath(fixture.root(), FILE_ID).getParent())) - .hasContent("replacement"); - } - - @Test - void shardCreationAndAbsoluteCommitAreBracketedByIdentityVerification() throws IOException { - ControlFixture fixture = controlFixture(); - AtomicInteger identityChecks = new AtomicInteger(); - LocalPersistentControlPlane controlPlane = - fixture.controlPlane( - point -> {}, - LocalPersistentControlPlane.systemSecureRecordOperations(), - () -> { - fixture.verifyIdentity(); - identityChecks.incrementAndGet(); - }); - - identityChecks.set(0); - controlPlane.storeManifest(manifest()); - - assertThat(identityChecks).hasValueGreaterThanOrEqualTo(5); - Path shard = manifestPath(fixture.root(), FILE_ID).getParent(); - assertThat(Files.getPosixFilePermissions(shard)) - .containsExactlyInAnyOrderElementsOf(PosixFilePermissions.fromString("rwx------")); - assertThat(Files.getOwner(shard).getName()).isEqualTo(fixture.evidence().expectedOwner()); - assertThat(Files.getFileStore(shard).name()).isEqualTo(fixture.evidence().fileStoreName()); - - ControlFixture changedFixture = controlFixture(); - Path target = manifestPath(changedFixture.root(), FILE_ID); - LocalPersistentControlPlane changed = - changedFixture.controlPlane( - point -> {}, - LocalPersistentControlPlane.systemSecureRecordOperations(), - () -> { - changedFixture.verifyIdentity(); - if (Files.exists(target, LinkOption.NOFOLLOW_LINKS)) { - throw new InjectedIdentityChange(); - } - }); - assertFailureKind( - LocalPersistentControlPlane.FailureKind.STORAGE, () -> changed.storeManifest(manifest())); - } - - @Test - void concurrentCrossInstanceImmutableCollisionIsNeverClassifiedAsStorage() throws Exception { - ControlFixture fixture = controlFixture(); - LocalPersistentControlPlane first = fixture.controlPlane(); - LocalPersistentControlPlane second = fixture.controlPlane(); - ExecutorService executor = Executors.newFixedThreadPool(2); - CountDownLatch ready = new CountDownLatch(2); - CountDownLatch start = new CountDownLatch(1); - try { - Future one = - executor.submit( - () -> { - ready.countDown(); - await(start); - first.storeManifest(manifest()); - }); - Future two = - executor.submit( - () -> { - ready.countDown(); - await(start); - second.storeManifest(manifest()); - }); - assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue(); - start.countDown(); - - one.get(5, TimeUnit.SECONDS); - two.get(5, TimeUnit.SECONDS); - assertThat(first.findManifest(FILE_ID)).contains(manifest()); - } finally { - executor.shutdownNow(); - assertThat(executor.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); - } - } - - private ControlFixture controlFixture() throws IOException { - Path root = createPersistentRoot(); - LocalPersistentRootAttestor attestor = new LocalPersistentRootAttestor(); - return new ControlFixture(root, attestor, attestor.attest(destinationFor(root))); - } - - private static LocalPublicationJournalRecord publishedR1Record(String operationId) { - return LocalPublicationJournalRecord.sealed( - operationId, DIGEST_A, "report.csv", "customer-order-01.part", 42, 1, 2, DIGEST_C, 0) - .published(PUBLISHED_AT, PublicationGuarantee.UNIQUE_ATOMIC_CREATE.name()); - } - - private static void writeR1Operation(Path root, String operationId, byte[] encoded) - throws IOException { - Path target = operationPath(root, operationId); - Files.createDirectory( - target.getParent(), - PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwx------"))); - Files.write(target, encoded); - } - - private static LocalPersistentControlPlane.FaultContext operationFault( - LocalPersistentControlPlane.FaultPoint boundary) { - return new LocalPersistentControlPlane.FaultContext( - LocalPersistentControlPlane.ControlRecordKind.OPERATION, - OPERATION_ID, - Optional.of( - new LocalPersistentControlPlane.OperationFaultState( - DurablePublicationRecord.State.WRITING, 1)), - boundary); - } - - private static LocalPersistentControlPlane.FaultContext immutableFault( - LocalPersistentControlPlane.ControlRecordKind kind, - LocalPersistentControlPlane.FaultPoint boundary) { - return new LocalPersistentControlPlane.FaultContext(kind, FILE_ID, Optional.empty(), boundary); - } - - private Path createPersistentRoot() throws IOException { - Path root = - tempDirectory - .resolve("persistent-root-" + rootSequence.incrementAndGet()) - .toAbsolutePath() - .normalize(); - Files.createDirectory( - root, PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwx------"))); - Files.createFile( - root.resolve(SENTINEL_NAME), - PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-------"))); - Files.write(root.resolve(SENTINEL_NAME), SENTINEL_CONTENT); - return root; - } - - private static CompiledFileDestination destinationFor(Path root) throws IOException { - PosixFileAttributes attributes = Files.readAttributes(root, PosixFileAttributes.class); - FileStore store = Files.getFileStore(root); - Set permissions = Set.copyOf(attributes.permissions()); - return new CompiledFileDestination( - new FileDestinationId("local-export"), - "local-primary", - root, - 1_000, - 1_048_576, - store.name(), - store.type(), - SENTINEL_NAME, - sha256(root.resolve(SENTINEL_NAME)), - attributes.owner().getName(), - mode(permissions), - permissions, - PublicationGuarantee.UNIQUE_ATOMIC_CREATE, - DurabilityGuarantee.FILE_AND_DIRECTORY_SYNC); - } - - private static DurablePublicationRecord writingRecord() { - return writingRecord(1); - } - - private static DurablePublicationRecord writingRecord(long revision) { - return writingRecord(revision, CREATED_AT); - } - - private static DurablePublicationRecord writingRecord(long revision, Instant createdAt) { - return operationRecord( - revision, - DurablePublicationRecord.State.WRITING, - OPERATION_ID, - DIGEST_A, - "policy-v1", - DIGEST_B, - "local-export", - "local-primary", - FILE_ID, - "routea1", - "report.csv", - "customer-order-01.part", - createdAt); - } - - private static DurablePublicationRecord storeSealedOperation( - LocalPersistentControlPlane controlPlane) { - DurablePublicationRecord sealed = sealedRecord(2); - controlPlane.storeOperation(writingRecord()); - controlPlane.storeOperation(sealed); - return sealed; - } - - private static DurablePublicationRecord sealedRecord(long revision) { - return operationRecord( - revision, - DurablePublicationRecord.State.SEALED, - OPERATION_ID, - DIGEST_A, - "policy-v1", - DIGEST_B, - "local-export", - "local-primary", - FILE_ID, - "routea1", - "report.csv", - "customer-order-01.part", - CREATED_AT); - } - - private static DurablePublicationRecord progressedRecord( - DurablePublicationRecord.State state, long revision) { - String manifestDigest = - switch (state) { - case MANIFEST_PUBLISHED, REFERENCE_PUBLISHED, PUBLISHED -> DIGEST_A; - default -> ""; - }; - String referenceDigest = - switch (state) { - case REFERENCE_PUBLISHED, PUBLISHED -> DIGEST_B; - default -> ""; - }; - return progressedRecord( - state, revision, 42, 1, 2, DIGEST_C, 0, SEALED_AT, manifestDigest, referenceDigest); - } - - private static DurablePublicationRecord progressedRecord( - DurablePublicationRecord.State state, - long revision, - long byteSize, - long rowCount, - int columnCount, - String sha256, - long formulaMitigatedCount, - Instant sealedAt, - String manifestDigest, - String referenceDigest) { - Instant publishedAt = state == DurablePublicationRecord.State.PUBLISHED ? PUBLISHED_AT : null; - String receiptSnapshot = - state == DurablePublicationRecord.State.PUBLISHED - ? new FileserverControlRecordCodec() - .encodeReceiptSnapshot( - receipt(byteSize, rowCount, columnCount, sha256, formulaMitigatedCount)) - : ""; - return new DurablePublicationRecord( - 2, - revision, - state, - OPERATION_ID, - DIGEST_A, - "policy-v1", - DIGEST_B, - "local-export", - "local-primary", - FILE_ID, - "routea1", - "report.csv", - "customer-order-01.part", - byteSize, - rowCount, - columnCount, - sha256, - formulaMitigatedCount, - manifestDigest, - referenceDigest, - CREATED_AT, - sealedAt, - publishedAt, - "", - receiptSnapshot); - } - - private static DurablePublicationRecord quarantinedRecord(long revision) { - return new DurablePublicationRecord( - 2, - revision, - DurablePublicationRecord.State.QUARANTINED, - OPERATION_ID, - DIGEST_A, - "policy-v1", - DIGEST_B, - "local-export", - "local-primary", - FILE_ID, - "routea1", - "report.csv", - "customer-order-01.part", - 42, - 1, - 2, - DIGEST_C, - 0, - DIGEST_A, - DIGEST_B, - CREATED_AT, - SEALED_AT, - null, - "INTEGRITY_FAILURE", - ""); - } - - private static DurablePublicationRecord quarantinedFrom( - DurablePublicationRecord current, long revision) { - return new DurablePublicationRecord( - 2, - revision, - DurablePublicationRecord.State.QUARANTINED, - current.operationId(), - current.requestFingerprint(), - current.effectivePolicyRevision(), - current.effectivePolicyDigest(), - current.destinationId(), - current.providerId(), - current.fileId(), - current.routeToken(), - current.publishedFileName(), - current.stageFileName(), - current.byteSize(), - current.rowCount(), - current.columnCount(), - current.sha256(), - current.formulaMitigatedCount(), - current.manifestDigest(), - current.referenceDigest(), - current.createdAt(), - current.sealedAt(), - null, - "INTEGRITY_FAILURE", - ""); - } - - private static FilePublishReceipt receipt( - long byteSize, long rowCount, int columnCount, String sha256, long formulaMitigatedCount) { - return new FilePublishReceipt( - new FilePublishOperationId(OPERATION_ID), - new R2PublishedReferenceCodec().encode("routea1", FILE_ID), - new FileDestinationId("local-export"), - "report.csv", - new FileVersion("version-01"), - "csv-rfc4180", - "text/csv", - "UTF-8", - byteSize, - rowCount, - columnCount, - sha256, - PUBLISHED_AT, - PublicationGuarantee.UNIQUE_ATOMIC_CREATE, - DurabilityGuarantee.FILE_AND_DIRECTORY_SYNC, - formulaMitigatedCount); - } - - private static DurablePublicationRecord operationRecord( - long revision, - DurablePublicationRecord.State state, - String operationId, - String requestFingerprint, - String policyRevision, - String policyDigest, - String destinationId, - String providerId, - String fileId, - String routeToken, - String publishedFileName, - String stageFileName, - Instant createdAt) { - boolean writing = state == DurablePublicationRecord.State.WRITING; - return new DurablePublicationRecord( - 2, - revision, - state, - operationId, - requestFingerprint, - policyRevision, - policyDigest, - destinationId, - providerId, - fileId, - routeToken, - publishedFileName, - stageFileName, - writing ? 0 : 42, - writing ? 0 : 1, - writing ? 0 : 2, - writing ? "" : DIGEST_C, - 0, - "", - "", - createdAt, - writing ? null : SEALED_AT, - null, - "", - ""); - } - - private static PrivateFileManifest manifest() { - return manifestWithSchemaId("worklog-v1"); - } - - private static PrivateFileManifest manifestWithSchemaId(String schemaId) { - return manifestFor(FILE_ID, schemaId); - } - - private static PrivateFileManifest manifestFor(String fileId, String schemaId) { - return new PrivateFileManifest( - 1, - OPERATION_ID, - fileId, - "local-primary", - new R2PublishedReferenceCodec().encode("routea1", fileId).value(), - DIGEST_A, - "local-export", - schemaId, - 1, - DIGEST_B, - "csv-rfc4180", - DIGEST_A, - "policy-v1", - DIGEST_B, - "report.csv", - "version-01", - "text/csv", - "UTF-8", - 42, - 1, - 2, - DIGEST_C, - 0, - PublicationGuarantee.UNIQUE_ATOMIC_CREATE, - DurabilityGuarantee.FILE_AND_DIRECTORY_SYNC, - fileId + ".csv", - CREATED_AT, - PUBLISHED_AT); - } - - private static PublishedReferenceRecord referenceRecord() { - return referenceRecordFor(FILE_ID, "version-01"); - } - - private static PublishedReferenceRecord referenceWithVersion(String version) { - return referenceRecordFor(FILE_ID, version); - } - - private static PublishedReferenceRecord referenceRecordFor(String fileId, String version) { - return new PublishedReferenceRecord( - 1, - fileId, - "routea1", - new R2PublishedReferenceCodec().encode("routea1", fileId).value(), - OPERATION_ID, - version, - DIGEST_A, - fileId + ".csv", - "local-export", - "local-primary", - "report.csv", - "text/csv", - "UTF-8", - 42, - DIGEST_C, - PUBLISHED_AT); - } - - private static Path operationPath(Path root, String operationId) { - String token = sha256(operationId.getBytes(StandardCharsets.UTF_8)); - return root.resolve(".ca-fileserver/operations") - .resolve(token.substring(0, 2)) - .resolve(token + ".json"); - } - - private static Path operationLockPath(Path root, String operationId) { - String token = sha256(operationId.getBytes(StandardCharsets.UTF_8)); - return root.resolve(".ca-fileserver/operations") - .resolve(token.substring(0, 2)) - .resolve(token + ".lock"); - } - - private static Path manifestPath(Path root, String fileId) { - return root.resolve(".ca-fileserver/manifests") - .resolve(fileId.substring(0, 2)) - .resolve(fileId + ".json"); - } - - private static Path referencePath(Path root, String fileId) { - return root.resolve(".ca-fileserver/references") - .resolve(fileId.substring(0, 2)) - .resolve(fileId + ".json"); - } - - private static void assertFailureKind( - LocalPersistentControlPlane.FailureKind expected, Runnable invocation) { - assertThatThrownBy(invocation::run) - .isInstanceOf(LocalPersistentControlPlane.LocalPersistentControlPlaneException.class) - .satisfies( - failure -> - assertThat( - ((LocalPersistentControlPlane.LocalPersistentControlPlaneException) failure) - .kind()) - .isEqualTo(expected)); - } - - private static void assertFutureFailureKind( - LocalPersistentControlPlane.FailureKind expected, Future future) { - assertThatThrownBy(() -> future.get(1, TimeUnit.SECONDS)) - .isInstanceOf(ExecutionException.class) - .satisfies( - failure -> - assertThat( - ((LocalPersistentControlPlane.LocalPersistentControlPlaneException) - failure.getCause()) - .kind()) - .isEqualTo(expected)); - } - - private static void assertOperationLockCanBeAcquiredByAnotherThread( - LocalPersistentControlPlane controlPlane) throws Exception { - ExecutorService executor = Executors.newSingleThreadExecutor(); - try { - Future acquired = - executor.submit( - () -> { - try (LocalPersistentControlPlane.OperationLock ignored = - controlPlane.acquireOperationLock(OPERATION_ID)) { - // Acquisition itself proves both the JVM stripe and OS lock were released. - } - }); - acquired.get(5, TimeUnit.SECONDS); - } finally { - executor.shutdownNow(); - assertThat(executor.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); - } - } - - private static String sha256(Path file) throws IOException { - return sha256(Files.readAllBytes(file)); - } - - private static String sha256(byte[] bytes) { - try { - return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); - } catch (NoSuchAlgorithmException exception) { - throw new AssertionError("SHA-256 must be available", exception); - } - } - - private static String mode(Set permissions) { - int value = 0; - value |= permissions.contains(PosixFilePermission.OWNER_READ) ? 0400 : 0; - value |= permissions.contains(PosixFilePermission.OWNER_WRITE) ? 0200 : 0; - value |= permissions.contains(PosixFilePermission.OWNER_EXECUTE) ? 0100 : 0; - value |= permissions.contains(PosixFilePermission.GROUP_READ) ? 0040 : 0; - value |= permissions.contains(PosixFilePermission.GROUP_WRITE) ? 0020 : 0; - value |= permissions.contains(PosixFilePermission.GROUP_EXECUTE) ? 0010 : 0; - value |= permissions.contains(PosixFilePermission.OTHERS_READ) ? 0004 : 0; - value |= permissions.contains(PosixFilePermission.OTHERS_WRITE) ? 0002 : 0; - value |= permissions.contains(PosixFilePermission.OTHERS_EXECUTE) ? 0001 : 0; - return String.format("%04o", value); - } - - private static void await(CountDownLatch latch) { - try { - if (!latch.await(5, TimeUnit.SECONDS)) { - throw new AssertionError("timed out waiting for concurrent test start"); - } - } catch (InterruptedException exception) { - Thread.currentThread().interrupt(); - throw new AssertionError(exception); - } - } - - private static void replaceForcedTemporary(Path shard, Path replacementSource) { - Path temporary = forcedTemporary(shard); - try { - Files.delete(temporary); - Files.move(replacementSource, temporary); - } catch (IOException exception) { - throw new AssertionError(exception); - } - } - - private static Path forcedTemporary(Path shard) { - try (var paths = Files.list(shard)) { - return paths - .filter(path -> path.getFileName().toString().endsWith(".tmp")) - .findFirst() - .orElseThrow(); - } catch (IOException exception) { - throw new AssertionError(exception); - } - } - - private record ControlFixture( - Path root, LocalPersistentRootAttestor attestor, LocalPersistentRootEvidence evidence) { - - private LocalPersistentControlPlane controlPlane() { - return new LocalPersistentControlPlane(attestor, evidence); - } - - private LocalPersistentControlPlane controlPlane( - LocalPersistentControlPlane.FaultCallback faultCallback) { - return new LocalPersistentControlPlane(attestor, evidence, faultCallback); - } - - private LocalPersistentControlPlane contextualControlPlane( - LocalPersistentControlPlane.ContextualFaultCallback faultCallback) { - return LocalPersistentControlPlane.withContextualFaultCallback( - attestor, evidence, faultCallback); - } - - private LocalPersistentControlPlane controlPlane( - LocalPersistentControlPlane.FaultCallback faultCallback, - LocalPersistentControlPlane.SecureRecordOperations operations, - LocalPersistentControlPlane.IdentityVerifier identityVerifier) { - return new LocalPersistentControlPlane( - attestor, evidence, faultCallback, operations, identityVerifier); - } - - private LocalPersistentControlPlane controlPlane( - LocalPersistentControlPlane.LockLifecycle lifecycle) { - return new LocalPersistentControlPlane( - attestor, - evidence, - point -> {}, - LocalPersistentControlPlane.systemSecureRecordOperations(), - null, - lifecycle); - } - - private void verifyIdentity() { - attestor.verifyIdentity(evidence); - } - } - - private static final class RecordingLockLifecycle - implements LocalPersistentControlPlane.LockLifecycle { - - private final List locks = new ArrayList<>(); - private final List channels = new ArrayList<>(); - private volatile boolean failRelease; - private volatile boolean failClose; - - private RecordingLockLifecycle(boolean failRelease, boolean failClose) { - this.failRelease = failRelease; - this.failClose = failClose; - } - - @Override - public synchronized void release(FileLock lock) throws IOException { - locks.add(lock); - if (failRelease) { - throw new IOException("injected operation lock release failure"); - } - lock.release(); - } - - @Override - public synchronized void close(FileChannel channel) throws IOException { - channels.add(channel); - if (failClose) { - throw new IOException("injected operation lock channel close failure"); - } - channel.close(); - } - - private void allowReleaseAndClose() { - failRelease = false; - failClose = false; - } - - private synchronized void forceCleanup() { - for (FileLock lock : locks) { - try { - if (lock.isValid()) { - lock.release(); - } - } catch (IOException ignored) { - // Best-effort cleanup of the deliberately leaked test resource. - } - } - for (FileChannel channel : channels) { - try { - if (channel.isOpen()) { - channel.close(); - } - } catch (IOException ignored) { - // Best-effort cleanup of the deliberately leaked test resource. - } - } - } - } - - private static final class RecordingSecureRecordOperations - implements LocalPersistentControlPlane.SecureRecordOperations { - - private final LocalPersistentControlPlane.SecureRecordOperations delegate = - LocalPersistentControlPlane.systemSecureRecordOperations(); - private final List actions = new ArrayList<>(); - private final List calls = new ArrayList<>(); - private final List shardCalls = new ArrayList<>(); - - @Override - public Optional statShard( - Path topDirectory, String shard) throws IOException { - actions.add(LocalPersistentControlPlane.SecureRecordAction.STAT_SHARD_NOFOLLOW); - shardCalls.add(new ShardCall(topDirectory, shard)); - return delegate.statShard(topDirectory, shard); - } - - @Override - public Optional read( - Path topDirectory, String shard, String relativeFileName, int maximumBytes) - throws IOException { - record( - LocalPersistentControlPlane.SecureRecordAction.READ, - topDirectory, - shard, - relativeFileName); - return delegate.read(topDirectory, shard, relativeFileName, maximumBytes); - } - - @Override - public LocalPersistentControlPlane.CreatedTemporary createNewAndForce( - Path topDirectory, String shard, String relativeFileName, byte[] bytes) throws IOException { - record( - LocalPersistentControlPlane.SecureRecordAction.CREATE_NEW_AND_FORCE, - topDirectory, - shard, - relativeFileName); - return delegate.createNewAndForce(topDirectory, shard, relativeFileName, bytes); - } - - @Override - public Optional fileKeyNoFollow( - Path topDirectory, String shard, String relativeFileName) throws IOException { - record( - LocalPersistentControlPlane.SecureRecordAction.STAT_NOFOLLOW, - topDirectory, - shard, - relativeFileName); - return delegate.fileKeyNoFollow(topDirectory, shard, relativeFileName); - } - - @Override - public void deleteExact(Path topDirectory, String shard, String relativeFileName) - throws IOException { - record( - LocalPersistentControlPlane.SecureRecordAction.DELETE_EXACT, - topDirectory, - shard, - relativeFileName); - delegate.deleteExact(topDirectory, shard, relativeFileName); - } - - private void record( - LocalPersistentControlPlane.SecureRecordAction action, - Path topDirectory, - String shard, - String relativeFileName) { - actions.add(action); - calls.add( - new LocalPersistentControlPlane.SecureRecordCall(topDirectory, shard, relativeFileName)); - } - } - - private record ShardCall(Path topDirectory, String shard) {} - - private static final class InjectedFault extends RuntimeException { - private static final long serialVersionUID = 1L; - } - - private static final class InjectedIdentityChange extends RuntimeException { - private static final long serialVersionUID = 1L; - } -} diff --git a/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/LocalPersistentCrashRecoveryTest.java b/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/LocalPersistentCrashRecoveryTest.java deleted file mode 100644 index 1b22d273..00000000 --- a/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/LocalPersistentCrashRecoveryTest.java +++ /dev/null @@ -1,229 +0,0 @@ -package dev.caskeleton.adapter.outbound.fileserver; - -import static java.nio.charset.StandardCharsets.UTF_8; -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.application.filepublication.FilePublishRequest; -import java.io.IOException; -import java.io.InputStream; -import java.net.URISyntaxException; -import java.net.URL; -import java.net.URLClassLoader; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Locale; -import java.util.Set; -import java.util.StringTokenizer; -import java.util.concurrent.TimeUnit; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.EnumSource; - -class LocalPersistentCrashRecoveryTest { - - private static final long PROCESS_TIMEOUT_SECONDS = 20; - private static final long PROTOCOL_TIMEOUT_SECONDS = 10; - private static final long OUTPUT_POLL_MILLIS = 20; - private static final int MAXIMUM_CHILD_OUTPUT_BYTES = 4_096; - private static final String CHILD_MAIN = FileserverCrashScenarioMain.class.getName(); - - @TempDir Path temporaryDirectory; - - @ParameterizedTest(name = "{0}") - @EnumSource(FileserverCrashScenarioMain.CrashBoundary.class) - void everyForceBoundaryRecoversWithoutProducerReplayOrPartialFinalBytes( - FileserverCrashScenarioMain.CrashBoundary boundary) throws Exception { - Path root = temporaryDirectory.resolve("crash-" + boundary.name().toLowerCase(Locale.ROOT)); - - ChildResult crashed = runChild("CRASH", root, boundary.name()); - - assertThat(crashed.exitCode()).isEqualTo(FileserverCrashScenarioMain.CRASH_EXIT_CODE); - assertThat(crashed.output()).isEmpty(); - - ChildResult recovered = runChild("RECOVER", root); - String expected = - boundary.permitsIndeterminateQuarantine() - ? FileserverCrashScenarioMain.RECOVERY_INDETERMINATE_QUARANTINED - : FileserverCrashScenarioMain.RECOVERY_SUCCESS; - - assertThat(recovered.exitCode()).isZero(); - assertThat(recovered.output()).isEqualTo(expected); - } - - @Test - void osOperationLockExcludesAnotherProcessAndReleasesAfterCloseAndForcedTermination() - throws Exception { - verifyLockRelease(false); - verifyLockRelease(true); - } - - private void verifyLockRelease(boolean terminateForcibly) throws Exception { - Path root = - temporaryDirectory.resolve(terminateForcibly ? "lock-forced-termination" : "lock-release"); - LocalPersistentPublicationTestFixture.create(root); - StartedChild holder = startChild("LOCK_HOLD", root); - try { - awaitMarker(holder, FileserverCrashScenarioMain.LOCK_ACQUIRED); - assertThat(holder.process().isAlive()).isTrue(); - - ChildResult excluded = runChild("LOCK_TRY", root); - assertThat(excluded.exitCode()).isZero(); - assertThat(excluded.output()).isEqualTo(FileserverCrashScenarioMain.LOCK_BUSY); - - if (terminateForcibly) { - holder.process().destroyForcibly(); - assertThat(holder.process().waitFor(PROCESS_TIMEOUT_SECONDS, TimeUnit.SECONDS)).isTrue(); - } else { - holder.process().getOutputStream().write("RELEASE\n".getBytes(UTF_8)); - holder.process().getOutputStream().flush(); - awaitMarker(holder, FileserverCrashScenarioMain.LOCK_RELEASED); - assertThat(holder.process().waitFor(PROCESS_TIMEOUT_SECONDS, TimeUnit.SECONDS)).isTrue(); - assertThat(holder.process().exitValue()).isZero(); - } - - ChildResult acquiredAfterOwnerExit = runChild("LOCK_TRY", root); - assertThat(acquiredAfterOwnerExit.exitCode()).isZero(); - assertThat(acquiredAfterOwnerExit.output()) - .isEqualTo(FileserverCrashScenarioMain.LOCK_ACQUIRED); - } finally { - if (holder.process().isAlive()) { - holder.process().destroyForcibly(); - holder.process().waitFor(PROCESS_TIMEOUT_SECONDS, TimeUnit.SECONDS); - } - Files.deleteIfExists(holder.capture()); - } - } - - private static ChildResult runChild(String mode, Path root, String... trailingArguments) - throws IOException, InterruptedException { - StartedChild child = startChild(mode, root, trailingArguments); - try { - boolean finished = child.process().waitFor(PROCESS_TIMEOUT_SECONDS, TimeUnit.SECONDS); - if (!finished) { - child.process().destroyForcibly(); - child.process().waitFor(PROCESS_TIMEOUT_SECONDS, TimeUnit.SECONDS); - throw new AssertionError("forked Fileserver scenario exceeded its bounded timeout"); - } - return new ChildResult(child.process().exitValue(), readProtocolOutput(child.capture())); - } finally { - if (child.process().isAlive()) { - child.process().destroyForcibly(); - } - Files.deleteIfExists(child.capture()); - } - } - - private static StartedChild startChild(String mode, Path root, String... trailingArguments) - throws IOException { - List command = new java.util.ArrayList<>(); - command.add(javaExecutable()); - command.add("-cp"); - command.add(testRuntimeClasspath()); - command.add(CHILD_MAIN); - command.add(mode); - command.add(root.toAbsolutePath().normalize().toString()); - command.addAll(List.of(trailingArguments)); - Path capture = Files.createTempFile(root.getParent(), ".fileserver-child-output-", ".log"); - try { - Process process = - new ProcessBuilder(command) - .redirectErrorStream(true) - .redirectOutput(capture.toFile()) - .start(); - return new StartedChild(process, capture); - } catch (IOException failure) { - try { - Files.deleteIfExists(capture); - } catch (IOException cleanupFailure) { - failure.addSuppressed(cleanupFailure); - } - throw failure; - } - } - - private static void awaitMarker(StartedChild child, String marker) - throws IOException, InterruptedException { - long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(PROTOCOL_TIMEOUT_SECONDS); - while (System.nanoTime() < deadline) { - String output = readProtocolOutput(child.capture()); - if (output.lines().anyMatch(marker::equals)) { - return; - } - if (!child.process().isAlive()) { - throw new AssertionError("forked lock holder exited before its protocol marker"); - } - Thread.sleep(OUTPUT_POLL_MILLIS); - } - throw new AssertionError("forked lock holder exceeded its bounded marker timeout"); - } - - private static String readProtocolOutput(Path capture) throws IOException { - byte[] bytes; - try (InputStream input = Files.newInputStream(capture)) { - bytes = input.readNBytes(MAXIMUM_CHILD_OUTPUT_BYTES + 1); - } - if (bytes.length > MAXIMUM_CHILD_OUTPUT_BYTES) { - return "CHILD_OUTPUT_LIMIT_EXCEEDED"; - } - String output = new String(bytes, UTF_8).trim(); - if (output.isEmpty() || output.lines().allMatch(line -> line.matches("[A-Z][A-Z0-9_]*"))) { - return output; - } - return "NON_PROTOCOL_CHILD_OUTPUT"; - } - - private static String javaExecutable() { - return Path.of( - System.getProperty("java.home"), - "bin", - System.getProperty("os.name").startsWith("Windows") ? "java.exe" : "java") - .toString(); - } - - private static String testRuntimeClasspath() { - Set entries = new LinkedHashSet<>(); - addCodeSource(entries, FileserverCrashScenarioMain.class); - addCodeSource(entries, LocalPersistentPublicationProvider.class); - addCodeSource(entries, FilePublishRequest.class); - StringTokenizer classPath = - new StringTokenizer(System.getProperty("java.class.path", ""), java.io.File.pathSeparator); - while (classPath.hasMoreTokens()) { - entries.add(classPath.nextToken()); - } - for (ClassLoader loader = Thread.currentThread().getContextClassLoader(); - loader != null; - loader = loader.getParent()) { - if (loader instanceof URLClassLoader urlClassLoader) { - for (URL url : urlClassLoader.getURLs()) { - if ("file".equals(url.getProtocol())) { - try { - entries.add(Path.of(url.toURI()).toString()); - } catch (URISyntaxException failure) { - throw new IllegalStateException("test runtime classpath URL is invalid", failure); - } - } - } - } - } - if (entries.isEmpty()) { - throw new IllegalStateException("test runtime classpath cannot be resolved"); - } - return String.join(java.io.File.pathSeparator, entries); - } - - private static void addCodeSource(Set entries, Class type) { - try { - entries.add( - Path.of(type.getProtectionDomain().getCodeSource().getLocation().toURI()).toString()); - } catch (URISyntaxException failure) { - throw new IllegalStateException("class code source is invalid", failure); - } - } - - private record ChildResult(int exitCode, String output) {} - - private record StartedChild(Process process, Path capture) {} -} diff --git a/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/LocalPersistentPayloadOperationsTest.java b/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/LocalPersistentPayloadOperationsTest.java deleted file mode 100644 index 699b6db9..00000000 --- a/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/LocalPersistentPayloadOperationsTest.java +++ /dev/null @@ -1,757 +0,0 @@ -package dev.caskeleton.adapter.outbound.fileserver; - -import static java.nio.charset.StandardCharsets.UTF_8; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.assertj.core.api.Assertions.catchThrowable; - -import dev.caskeleton.application.filepublication.FileDestinationId; -import dev.caskeleton.application.filepublication.FilePublishReceipt.DurabilityGuarantee; -import dev.caskeleton.application.filepublication.FilePublishReceipt.PublicationGuarantee; -import java.io.IOException; -import java.nio.file.FileStore; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.attribute.BasicFileAttributes; -import java.nio.file.attribute.PosixFilePermission; -import java.nio.file.attribute.PosixFilePermissions; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.ArrayList; -import java.util.HexFormat; -import java.util.List; -import java.util.Set; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -class LocalPersistentPayloadOperationsTest { - - private static final String OPERATION_ID = "customer/order:01"; - private static final String FILE_ID = "00112233445566778899aabbccddeeff"; - private static final String SENTINEL_NAME = ".ca-fileserver-volume"; - private static final byte[] SENTINEL_CONTENT = "fileserver-r2-payload-root\n".getBytes(UTF_8); - - @TempDir Path temporaryDirectory; - private final AtomicInteger rootSequence = new AtomicInteger(); - - @Test - void stagesThroughOneStreamingWriterThenForcesAndReportsStableDigest() throws IOException { - PayloadFixture fixture = payloadFixture(); - AtomicInteger writerCalls = new AtomicInteger(); - List events = new ArrayList<>(); - LocalPersistentPayloadOperations payload = fixture.payload(events::add); - String stageFileName = LocalPersistentPayloadOperations.stageFileName(OPERATION_ID); - byte[] chunk = "0123456789abcdef".repeat(64).getBytes(UTF_8); - - LocalPersistentPayloadOperations.VerifiedArtifact staged = - payload.stage( - OPERATION_ID, - stageFileName, - chunk.length * 128L, - output -> { - writerCalls.incrementAndGet(); - assertThat(output).isNotInstanceOf(java.io.ByteArrayOutputStream.class); - for (int index = 0; index < 128; index++) { - output.write(chunk); - } - }); - - byte[] expected = new byte[chunk.length * 128]; - for (int index = 0; index < 128; index++) { - System.arraycopy(chunk, 0, expected, index * chunk.length, chunk.length); - } - Path stagedPath = stagePath(fixture.root(), OPERATION_ID, stageFileName); - assertThat(writerCalls).hasValue(1); - assertThat(staged.byteSize()).isEqualTo(expected.length); - assertThat(staged.sha256()).isEqualTo(sha256(expected)); - assertThat(Files.readAllBytes(stagedPath)).isEqualTo(expected); - assertThat(Files.getPosixFilePermissions(stagedPath)) - .containsExactlyInAnyOrderElementsOf(PosixFilePermissions.fromString("rw-------")); - assertThat(events) - .containsExactly( - new LocalPersistentPayloadOperations.FaultContext( - LocalPersistentPayloadOperations.FaultPoint.STAGE_FORCED, - OPERATION_ID, - null, - staged)); - } - - @Test - void enforcesTheByteLimitWhileWritingAndAgainFromStableAttributes() throws IOException { - PayloadFixture fixture = payloadFixture(); - AtomicInteger writerCalls = new AtomicInteger(); - LocalPersistentPayloadOperations payload = fixture.payload(); - String stageFileName = LocalPersistentPayloadOperations.stageFileName(OPERATION_ID); - - Throwable failure = - catchThrowable( - () -> - payload.stage( - OPERATION_ID, - stageFileName, - 4, - output -> { - writerCalls.incrementAndGet(); - output.write(new byte[] {1, 2, 3, 4, 5}); - })); - - assertFailureKind(LocalPersistentPayloadOperations.FailureKind.CAPACITY, failure); - assertThat(writerCalls).hasValue(1); - assertThat(stagePath(fixture.root(), OPERATION_ID, stageFileName)).doesNotExist(); - } - - @Test - void writerFailureDeletesOnlyTheCreatedStageAndPreservesTheOriginalFailure() throws IOException { - PayloadFixture fixture = payloadFixture(); - LocalPersistentPayloadOperations payload = fixture.payload(); - String stageFileName = LocalPersistentPayloadOperations.stageFileName(OPERATION_ID); - InjectedFault original = new InjectedFault("writer"); - - Throwable failure = - catchThrowable( - () -> - payload.stage( - OPERATION_ID, - stageFileName, - 1024, - output -> { - output.write("partial".getBytes(UTF_8)); - throw original; - })); - - assertThat(failure).isSameAs(original); - assertThat(stagePath(fixture.root(), OPERATION_ID, stageFileName)).doesNotExist(); - } - - @Test - void cleanupFailureIsSuppressedOnTheOriginalWriterFailureAndTheResourceIsClosed() - throws IOException { - PayloadFixture fixture = payloadFixture(); - InjectedFault original = new InjectedFault("writer"); - InjectedFault cleanup = new InjectedFault("cleanup"); - AtomicBoolean closeObserved = new AtomicBoolean(); - LocalPersistentPayloadOperations.PayloadAccess access = - new DelegatingPayloadAccess() { - @Override - public void cleanupCreatedStage( - Path topDirectory, - String shard, - String fileName, - String expectedFileKey, - Throwable originalFailure) { - closeObserved.set( - canExclusivelyOpen(stagePath(fixture.root(), OPERATION_ID, fileName))); - throw cleanup; - } - }; - LocalPersistentPayloadOperations payload = - fixture.payload( - access, () -> fixture.attestor().verifyIdentity(fixture.evidence()), ignored -> {}); - - Throwable failure = - catchThrowable( - () -> - payload.stage( - OPERATION_ID, - LocalPersistentPayloadOperations.stageFileName(OPERATION_ID), - 1024, - output -> { - output.write("partial".getBytes(UTF_8)); - throw original; - })); - - assertThat(failure).isSameAs(original); - assertThat(failure.getSuppressed()).containsExactly(cleanup); - assertThat(closeObserved).isTrue(); - } - - @Test - void outerPostForceAttestationFailureExactDeletesTheCreatedStage() throws IOException { - PayloadFixture fixture = payloadFixture(); - LocalPersistentPayloadOperations.PayloadAccess access = - new DelegatingPayloadAccess() { - @Override - public LocalPersistentPayloadOperations.VerifiedArtifact createStageAndForce( - Path topDirectory, - String shard, - String fileName, - String operationId, - long maximumBytes, - LocalPersistentPayloadOperations.PayloadWriter writer) - throws IOException { - LocalPersistentPayloadOperations.VerifiedArtifact actual = - super.createStageAndForce( - topDirectory, shard, fileName, operationId, maximumBytes, writer); - return new LocalPersistentPayloadOperations.VerifiedArtifact( - actual.kind(), - actual.identity(), - actual.shard(), - actual.fileName(), - actual.byteSize(), - actual.sha256(), - actual.fileKey(), - "unexpected-owner", - actual.permissions(), - actual.fileStoreName(), - actual.fileStoreType()); - } - }; - LocalPersistentPayloadOperations payload = - fixture.payload( - access, () -> fixture.attestor().verifyIdentity(fixture.evidence()), ignored -> {}); - String stageName = LocalPersistentPayloadOperations.stageFileName(OPERATION_ID); - - assertFailureKind( - LocalPersistentPayloadOperations.FailureKind.INTEGRITY, - catchThrowable( - () -> - payload.stage( - OPERATION_ID, - stageName, - 1024, - output -> output.write("payload".getBytes(UTF_8))))); - assertThat(stagePath(fixture.root(), OPERATION_ID, stageName)).doesNotExist(); - } - - @Test - void inspectionStreamsAndRejectsDigestSizeSymlinkAndOversizedArtifacts() throws IOException { - PayloadFixture fixture = payloadFixture(); - LocalPersistentPayloadOperations payload = fixture.payload(); - String stageName = LocalPersistentPayloadOperations.stageFileName(OPERATION_ID); - LocalPersistentPayloadOperations.VerifiedArtifact staged = - payload.stage(OPERATION_ID, stageName, 1024, out -> out.write("payload".getBytes(UTF_8))); - - assertThat(payload.inspectStage(OPERATION_ID, stageName, 1024)).contains(staged); - assertThat( - payload.inspectStage( - "missing-operation", - LocalPersistentPayloadOperations.stageFileName("missing-operation"), - 1024)) - .isEmpty(); - - String symlinkOperation = "symlink-operation"; - String symlinkName = LocalPersistentPayloadOperations.stageFileName(symlinkOperation); - Path symlinkShard = - fixture - .root() - .resolve(".ca-fileserver/staging") - .resolve(operationToken(symlinkOperation).substring(0, 2)); - Files.createDirectory( - symlinkShard, PosixFilePermissions.asFileAttribute(ownerDirectoryPermissions())); - Files.createSymbolicLink( - symlinkShard.resolve(symlinkName), stagePath(fixture.root(), OPERATION_ID, stageName)); - - assertFailureKind( - LocalPersistentPayloadOperations.FailureKind.INTEGRITY, - catchThrowable(() -> payload.inspectStage(symlinkOperation, symlinkName, 1024))); - assertFailureKind( - LocalPersistentPayloadOperations.FailureKind.CAPACITY, - catchThrowable(() -> payload.inspectStage(OPERATION_ID, stageName, 3))); - } - - @Test - void rejectsSymlinkShardInsteadOfFollowingIt() throws IOException { - PayloadFixture fixture = payloadFixture(); - LocalPersistentPayloadOperations payload = fixture.payload(); - String operationId = "symlink-shard-operation"; - String shard = operationToken(operationId).substring(0, 2); - Path staging = fixture.root().resolve(".ca-fileserver/staging"); - Path external = temporaryDirectory.resolve("external-" + rootSequence.incrementAndGet()); - Files.createDirectory(external); - Files.createSymbolicLink(staging.resolve(shard), external); - - assertFailureKind( - LocalPersistentPayloadOperations.FailureKind.INTEGRITY, - catchThrowable( - () -> - payload.stage( - operationId, - LocalPersistentPayloadOperations.stageFileName(operationId), - 1024, - out -> out.write(1)))); - assertThat(external).isEmptyDirectory(); - } - - @Test - void publishesByExclusiveHardLinkAndForcesTheDataDirectoryInOrder() throws IOException { - PayloadFixture fixture = payloadFixture(); - List events = new ArrayList<>(); - LocalPersistentPayloadOperations payload = fixture.payload(events::add); - String stageName = LocalPersistentPayloadOperations.stageFileName(OPERATION_ID); - LocalPersistentPayloadOperations.VerifiedArtifact staged = - payload.stage(OPERATION_ID, stageName, 1024, out -> out.write("payload".getBytes(UTF_8))); - - LocalPersistentPayloadOperations.VerifiedArtifact data = - payload.publishData(staged, FILE_ID, "report.csv", 1024); - - Path stagePath = stagePath(fixture.root(), OPERATION_ID, stageName); - Path dataPath = dataPath(fixture.root(), FILE_ID, "report.csv"); - assertThat(data.kind()).isEqualTo(LocalPersistentPayloadOperations.ArtifactKind.DATA); - assertThat(data.fileKey()).isEqualTo(staged.fileKey()); - assertThat(Files.readAttributes(stagePath, BasicFileAttributes.class).fileKey()) - .isEqualTo(Files.readAttributes(dataPath, BasicFileAttributes.class).fileKey()); - assertThat(payload.inspectData(FILE_ID, "report.csv", 1024)).contains(data); - assertThat(events) - .extracting(LocalPersistentPayloadOperations.FaultContext::point) - .containsExactly( - LocalPersistentPayloadOperations.FaultPoint.STAGE_FORCED, - LocalPersistentPayloadOperations.FaultPoint.DATA_LINKED, - LocalPersistentPayloadOperations.FaultPoint.DATA_DIRECTORY_FORCED); - } - - @Test - void recoveryForcesAnExistingMatchingDataShardWithoutRepublishing() throws IOException { - PayloadFixture fixture = payloadFixture(); - List recoveryEvents = new ArrayList<>(); - LocalPersistentPayloadOperations initial = fixture.payload(); - LocalPersistentPayloadOperations.VerifiedArtifact staged = - initial.stage( - OPERATION_ID, - LocalPersistentPayloadOperations.stageFileName(OPERATION_ID), - 1024, - out -> out.write("payload".getBytes(UTF_8))); - initial.publishData(staged, FILE_ID, "report.csv", 1024); - byte[] before = Files.readAllBytes(dataPath(fixture.root(), FILE_ID, "report.csv")); - - fixture.payload(recoveryEvents::add).forceDataDirectory(FILE_ID); - - assertThat(Files.readAllBytes(dataPath(fixture.root(), FILE_ID, "report.csv"))) - .isEqualTo(before); - assertThat(recoveryEvents) - .extracting(LocalPersistentPayloadOperations.FaultContext::point) - .containsExactly(LocalPersistentPayloadOperations.FaultPoint.DATA_DIRECTORY_FORCED); - } - - @Test - void inspectsLegacyRootArtifactByBoundedNoFollowStreamingWithoutRewritingIt() throws IOException { - PayloadFixture fixture = payloadFixture(); - String legacyName = "월간 export -- legacy 01.csv"; - Path legacyPath = fixture.root().resolve(legacyName); - byte[] bytes = "legacy-payload".getBytes(UTF_8); - Files.write(legacyPath, bytes); - Files.setPosixFilePermissions(legacyPath, PosixFilePermissions.fromString("rw-------")); - var before = Files.readAttributes(legacyPath, BasicFileAttributes.class); - - LocalPersistentPayloadOperations.VerifiedArtifact artifact = - fixture.payload().inspectLegacyRootArtifact(legacyName, bytes.length).orElseThrow(); - - var after = Files.readAttributes(legacyPath, BasicFileAttributes.class); - assertThat(artifact.kind()) - .isEqualTo(LocalPersistentPayloadOperations.ArtifactKind.LEGACY_ROOT); - assertThat(artifact.fileName()).isEqualTo(legacyName); - assertThat(artifact.byteSize()).isEqualTo(bytes.length); - assertThat(artifact.sha256()).isEqualTo(sha256(bytes)); - assertThat(after.fileKey()).isEqualTo(before.fileKey()); - assertThat(after.lastModifiedTime()).isEqualTo(before.lastModifiedTime()); - } - - @Test - void legacyRootInspectionRejectsSymlinkAndCapacityOverflow() throws IOException { - PayloadFixture fixture = payloadFixture(); - Path target = fixture.root().resolve("legacy-target.csv"); - Files.write(target, "payload".getBytes(UTF_8)); - Files.setPosixFilePermissions(target, PosixFilePermissions.fromString("rw-------")); - Files.createSymbolicLink(fixture.root().resolve("legacy-link.csv"), target); - - assertFailureKind( - LocalPersistentPayloadOperations.FailureKind.INTEGRITY, - catchThrowable(() -> fixture.payload().inspectLegacyRootArtifact("legacy-link.csv", 1024))); - assertFailureKind( - LocalPersistentPayloadOperations.FailureKind.CAPACITY, - catchThrowable(() -> fixture.payload().inspectLegacyRootArtifact("legacy-target.csv", 3))); - } - - @Test - void collisionNeverOverwritesExistingTargetAndReturnsTypedConflict() throws IOException { - PayloadFixture fixture = payloadFixture(); - LocalPersistentPayloadOperations payload = fixture.payload(); - LocalPersistentPayloadOperations.VerifiedArtifact first = - payload.stage( - OPERATION_ID, - LocalPersistentPayloadOperations.stageFileName(OPERATION_ID), - 1024, - out -> out.write("first".getBytes(UTF_8))); - payload.publishData(first, FILE_ID, "report.csv", 1024); - byte[] before = Files.readAllBytes(dataPath(fixture.root(), FILE_ID, "report.csv")); - String secondOperation = "customer/order:02"; - LocalPersistentPayloadOperations.VerifiedArtifact second = - payload.stage( - secondOperation, - LocalPersistentPayloadOperations.stageFileName(secondOperation), - 1024, - out -> out.write("second".getBytes(UTF_8))); - - assertFailureKind( - LocalPersistentPayloadOperations.FailureKind.CONFLICT, - catchThrowable(() -> payload.publishData(second, FILE_ID, "report.csv", 1024))); - assertThat(Files.readAllBytes(dataPath(fixture.root(), FILE_ID, "report.csv"))) - .isEqualTo(before); - } - - @Test - void rechecksStageIdentityImmediatelyBeforeHardLinkAndPreservesReplacement() throws IOException { - PayloadFixture fixture = payloadFixture(); - LocalPersistentPayloadOperations.VerifiedArtifact staged = - fixture - .payload() - .stage( - OPERATION_ID, - LocalPersistentPayloadOperations.stageFileName(OPERATION_ID), - 1024, - out -> out.write("original".getBytes(UTF_8))); - Path stagePath = stagePath(fixture.root(), OPERATION_ID, staged.fileName()); - Files.move(stagePath, stagePath.resolveSibling("saved.part")); - Files.write(stagePath, "replacement".getBytes(UTF_8)); - Files.setPosixFilePermissions(stagePath, PosixFilePermissions.fromString("rw-------")); - - assertFailureKind( - LocalPersistentPayloadOperations.FailureKind.INTEGRITY, - catchThrowable(() -> fixture.payload().publishData(staged, FILE_ID, "report.csv", 1024))); - assertThat(Files.readString(stagePath)).isEqualTo("replacement"); - assertThat(dataPath(fixture.root(), FILE_ID, "report.csv")).doesNotExist(); - } - - @Test - void exactStageDeleteRejectsReplacementAndForcesOnlyAfterMatchingDelete() throws IOException { - PayloadFixture fixture = payloadFixture(); - List events = new ArrayList<>(); - LocalPersistentPayloadOperations payload = fixture.payload(events::add); - LocalPersistentPayloadOperations.VerifiedArtifact staged = - payload.stage( - OPERATION_ID, - LocalPersistentPayloadOperations.stageFileName(OPERATION_ID), - 1024, - out -> out.write("original".getBytes(UTF_8))); - Path stagePath = stagePath(fixture.root(), OPERATION_ID, staged.fileName()); - Path original = stagePath.resolveSibling("saved.part"); - Files.move(stagePath, original); - Files.write(stagePath, "replacement".getBytes(UTF_8)); - Files.setPosixFilePermissions(stagePath, PosixFilePermissions.fromString("rw-------")); - - assertFailureKind( - LocalPersistentPayloadOperations.FailureKind.INTEGRITY, - catchThrowable(() -> payload.deleteStageExact(staged))); - assertThat(Files.readString(stagePath)).isEqualTo("replacement"); - - Files.delete(stagePath); - Files.move(original, stagePath); - payload.deleteStageExact(staged); - - assertThat(stagePath).doesNotExist(); - assertThat(events) - .extracting(LocalPersistentPayloadOperations.FaultContext::point) - .containsExactly( - LocalPersistentPayloadOperations.FaultPoint.STAGE_FORCED, - LocalPersistentPayloadOperations.FaultPoint.STAGE_DELETED); - } - - @Test - void rootIdentityFailureBeforeMutationCreatesNothingAndAfterCommitIsIndeterminate() - throws IOException { - PayloadFixture fixture = payloadFixture(); - String stageName = LocalPersistentPayloadOperations.stageFileName(OPERATION_ID); - AtomicInteger calls = new AtomicInteger(); - LocalPersistentPayloadOperations beforeFailure = - fixture.payload( - LocalPersistentPayloadOperations.systemPayloadAccess(), - () -> { - if (calls.incrementAndGet() == 1) { - throw new InjectedFault("identity-before"); - } - }, - ignored -> {}); - - assertFailureKind( - LocalPersistentPayloadOperations.FailureKind.INDETERMINATE, - catchThrowable( - () -> - beforeFailure.stage( - OPERATION_ID, stageName, 1024, out -> out.write("bytes".getBytes(UTF_8))))); - assertThat(stagePath(fixture.root(), OPERATION_ID, stageName)).doesNotExist(); - - calls.set(0); - LocalPersistentPayloadOperations afterFailure = - fixture.payload( - LocalPersistentPayloadOperations.systemPayloadAccess(), - () -> { - if (calls.incrementAndGet() == 2) { - throw new InjectedFault("identity-after"); - } - }, - ignored -> {}); - assertFailureKind( - LocalPersistentPayloadOperations.FailureKind.INDETERMINATE, - catchThrowable( - () -> - afterFailure.stage( - OPERATION_ID, stageName, 1024, out -> out.write("bytes".getBytes(UTF_8))))); - assertThat(stagePath(fixture.root(), OPERATION_ID, stageName)).isRegularFile(); - } - - @Test - void faultCallbacksAfterDurableBoundariesNeverRemoveCommittedArtifacts() throws IOException { - for (LocalPersistentPayloadOperations.FaultPoint point : - List.of( - LocalPersistentPayloadOperations.FaultPoint.STAGE_FORCED, - LocalPersistentPayloadOperations.FaultPoint.DATA_LINKED, - LocalPersistentPayloadOperations.FaultPoint.DATA_DIRECTORY_FORCED)) { - PayloadFixture fixture = payloadFixture(); - InjectedFault fault = new InjectedFault(point.name()); - AtomicBoolean enabled = new AtomicBoolean(true); - LocalPersistentPayloadOperations payload = - fixture.payload( - context -> { - if (enabled.get() && context.point() == point) { - throw fault; - } - }); - String stageName = LocalPersistentPayloadOperations.stageFileName(OPERATION_ID); - - if (point == LocalPersistentPayloadOperations.FaultPoint.STAGE_FORCED) { - assertThatThrownBy( - () -> - payload.stage( - OPERATION_ID, stageName, 1024, out -> out.write("payload".getBytes(UTF_8)))) - .isSameAs(fault); - assertThat(stagePath(fixture.root(), OPERATION_ID, stageName)).isRegularFile(); - } else { - enabled.set(false); - LocalPersistentPayloadOperations.VerifiedArtifact staged = - payload.stage( - OPERATION_ID, stageName, 1024, out -> out.write("payload".getBytes(UTF_8))); - enabled.set(true); - assertThatThrownBy(() -> payload.publishData(staged, FILE_ID, "report.csv", 1024)) - .isSameAs(fault); - assertThat(dataPath(fixture.root(), FILE_ID, "report.csv")).isRegularFile(); - } - } - } - - @Test - void stageDeletedCallbackRunsAfterDeletionAndItsFailureDoesNotRestoreTheStage() - throws IOException { - PayloadFixture fixture = payloadFixture(); - LocalPersistentPayloadOperations payload = fixture.payload(); - LocalPersistentPayloadOperations.VerifiedArtifact staged = - payload.stage( - OPERATION_ID, - LocalPersistentPayloadOperations.stageFileName(OPERATION_ID), - 1024, - out -> out.write("payload".getBytes(UTF_8))); - InjectedFault fault = new InjectedFault("after-delete"); - LocalPersistentPayloadOperations failing = - fixture.payload( - context -> { - if (context.point() == LocalPersistentPayloadOperations.FaultPoint.STAGE_DELETED) { - throw fault; - } - }); - - assertThatThrownBy(() -> failing.deleteStageExact(staged)).isSameAs(fault); - assertThat(stagePath(fixture.root(), OPERATION_ID, staged.fileName())).doesNotExist(); - } - - private PayloadFixture payloadFixture() throws IOException { - Path root = - temporaryDirectory - .resolve("payload-root-" + rootSequence.incrementAndGet()) - .toAbsolutePath() - .normalize(); - Files.createDirectory(root, PosixFilePermissions.asFileAttribute(ownerDirectoryPermissions())); - Files.write(root.resolve(SENTINEL_NAME), SENTINEL_CONTENT); - FileStore store = Files.getFileStore(root); - String owner = Files.getOwner(root).getName(); - CompiledFileDestination destination = - new CompiledFileDestination( - new FileDestinationId("local-export"), - "local-primary", - root, - 10_000, - 16 * 1024 * 1024, - store.name(), - store.type(), - SENTINEL_NAME, - sha256(SENTINEL_CONTENT), - owner, - mode(ownerDirectoryPermissions()), - ownerDirectoryPermissions(), - PublicationGuarantee.UNIQUE_ATOMIC_CREATE, - DurabilityGuarantee.FILE_AND_DIRECTORY_SYNC); - LocalPersistentRootAttestor attestor = new LocalPersistentRootAttestor(); - LocalPersistentRootEvidence evidence = attestor.attest(destination); - return new PayloadFixture(root, attestor, evidence); - } - - private static Path stagePath(Path root, String operationId, String stageFileName) { - return root.resolve(".ca-fileserver/staging") - .resolve(operationToken(operationId).substring(0, 2)) - .resolve(stageFileName); - } - - private static Path dataPath(Path root, String fileId, String publishedFileName) { - return root.resolve("data").resolve(fileId.substring(0, 2)).resolve(publishedFileName); - } - - private static String operationToken(String operationId) { - return sha256(operationId.getBytes(UTF_8)); - } - - private static String sha256(byte[] bytes) { - try { - return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); - } catch (NoSuchAlgorithmException exception) { - throw new AssertionError("SHA-256 must be available", exception); - } - } - - private static Set ownerDirectoryPermissions() { - return PosixFilePermissions.fromString("rwx------"); - } - - private static String mode(Set permissions) { - int value = 0; - value |= permissions.contains(PosixFilePermission.OWNER_READ) ? 0400 : 0; - value |= permissions.contains(PosixFilePermission.OWNER_WRITE) ? 0200 : 0; - value |= permissions.contains(PosixFilePermission.OWNER_EXECUTE) ? 0100 : 0; - value |= permissions.contains(PosixFilePermission.GROUP_READ) ? 0040 : 0; - value |= permissions.contains(PosixFilePermission.GROUP_WRITE) ? 0020 : 0; - value |= permissions.contains(PosixFilePermission.GROUP_EXECUTE) ? 0010 : 0; - value |= permissions.contains(PosixFilePermission.OTHERS_READ) ? 0004 : 0; - value |= permissions.contains(PosixFilePermission.OTHERS_WRITE) ? 0002 : 0; - value |= permissions.contains(PosixFilePermission.OTHERS_EXECUTE) ? 0001 : 0; - return String.format("%04o", value); - } - - private static boolean canExclusivelyOpen(Path path) { - try (var ignored = - java.nio.channels.FileChannel.open(path, java.nio.file.StandardOpenOption.WRITE)) { - return true; - } catch (IOException exception) { - return false; - } - } - - private static void assertFailureKind( - LocalPersistentPayloadOperations.FailureKind expected, Throwable failure) { - assertThat(failure) - .isInstanceOf(LocalPersistentPayloadOperations.LocalPersistentPayloadException.class); - assertThat(((LocalPersistentPayloadOperations.LocalPersistentPayloadException) failure).kind()) - .isEqualTo(expected); - } - - private record PayloadFixture( - Path root, LocalPersistentRootAttestor attestor, LocalPersistentRootEvidence evidence) { - - LocalPersistentPayloadOperations payload() { - return new LocalPersistentPayloadOperations(attestor, evidence); - } - - LocalPersistentPayloadOperations payload( - LocalPersistentPayloadOperations.FaultCallback callback) { - return new LocalPersistentPayloadOperations(attestor, evidence, callback); - } - - LocalPersistentPayloadOperations payload( - LocalPersistentPayloadOperations.PayloadAccess access, - LocalPersistentPayloadOperations.IdentityVerifier verifier, - LocalPersistentPayloadOperations.FaultCallback callback) { - return new LocalPersistentPayloadOperations(attestor, evidence, access, verifier, callback); - } - } - - private abstract static class DelegatingPayloadAccess - implements LocalPersistentPayloadOperations.PayloadAccess { - - private final LocalPersistentPayloadOperations.PayloadAccess delegate = - LocalPersistentPayloadOperations.systemPayloadAccess(); - - @Override - public LocalPersistentPayloadOperations.ShardAttributes statShard( - Path topDirectory, String shard) throws IOException { - return delegate.statShard(topDirectory, shard); - } - - @Override - public LocalPersistentPayloadOperations.ShardAttributes createPrivateShard( - Path topDirectory, String shard) throws IOException { - return delegate.createPrivateShard(topDirectory, shard); - } - - @Override - public String fileStoreName(Path path) throws IOException { - return delegate.fileStoreName(path); - } - - @Override - public String fileStoreType(Path path) throws IOException { - return delegate.fileStoreType(path); - } - - @Override - public LocalPersistentPayloadOperations.VerifiedArtifact createStageAndForce( - Path topDirectory, - String shard, - String fileName, - String operationId, - long maximumBytes, - LocalPersistentPayloadOperations.PayloadWriter writer) - throws IOException { - return delegate.createStageAndForce( - topDirectory, shard, fileName, operationId, maximumBytes, writer); - } - - @Override - public LocalPersistentPayloadOperations.VerifiedArtifact inspect( - LocalPersistentPayloadOperations.ArtifactKind kind, - Path topDirectory, - String shard, - String fileName, - String identity, - long maximumBytes) - throws IOException { - return delegate.inspect(kind, topDirectory, shard, fileName, identity, maximumBytes); - } - - @Override - public void createHardLink(Path link, Path existing) throws IOException { - delegate.createHardLink(link, existing); - } - - @Override - public void forceDirectory(Path directory) throws IOException { - delegate.forceDirectory(directory); - } - - @Override - public void cleanupCreatedStage( - Path topDirectory, - String shard, - String fileName, - String expectedFileKey, - Throwable originalFailure) - throws IOException { - delegate.cleanupCreatedStage(topDirectory, shard, fileName, expectedFileKey, originalFailure); - } - - @Override - public boolean deleteExact( - Path topDirectory, - String shard, - String fileName, - LocalPersistentPayloadOperations.VerifiedArtifact expected) - throws IOException { - return delegate.deleteExact(topDirectory, shard, fileName, expected); - } - } - - private static final class InjectedFault extends RuntimeException { - - private static final long serialVersionUID = 1L; - - private InjectedFault(String message) { - super(message); - } - } -} diff --git a/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/LocalPersistentPublicationProviderTest.java b/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/LocalPersistentPublicationProviderTest.java deleted file mode 100644 index 0b94b858..00000000 --- a/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/LocalPersistentPublicationProviderTest.java +++ /dev/null @@ -1,511 +0,0 @@ -package dev.caskeleton.adapter.outbound.fileserver; - -import static java.nio.charset.StandardCharsets.UTF_8; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.application.filepublication.ExportSchema; -import dev.caskeleton.application.filepublication.ExportSchema.CellType; -import dev.caskeleton.application.filepublication.ExportSchema.Column; -import dev.caskeleton.application.filepublication.ExportSchema.FormulaPolicy; -import dev.caskeleton.application.filepublication.FileDestinationId; -import dev.caskeleton.application.filepublication.FilePublicationException; -import dev.caskeleton.application.filepublication.FilePublishOperationId; -import dev.caskeleton.application.filepublication.FilePublishReceipt; -import dev.caskeleton.application.filepublication.FilePublishReceipt.DurabilityGuarantee; -import dev.caskeleton.application.filepublication.FilePublishReceipt.PublicationGuarantee; -import dev.caskeleton.application.filepublication.FilePublishRequest; -import dev.caskeleton.application.filepublication.LogicalFileName; -import dev.caskeleton.application.filepublication.SourceRevision; -import dev.caskeleton.application.filepublication.TabularCell.IntegerCell; -import dev.caskeleton.application.filepublication.TabularCell.TextCell; -import dev.caskeleton.application.filepublication.TabularRow; -import java.io.IOException; -import java.nio.file.FileStore; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.attribute.PosixFilePermission; -import java.nio.file.attribute.PosixFilePermissions; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.time.Clock; -import java.time.Instant; -import java.time.ZoneOffset; -import java.util.ArrayList; -import java.util.HexFormat; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import java.util.concurrent.atomic.AtomicInteger; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; - -class LocalPersistentPublicationProviderTest { - - @TempDir Path temporaryDirectory; - - @ParameterizedTest - @ValueSource(strings = {"sourceRevision", "logicalFileName"}) - void malformedUnicodeIsRejectedBeforeProducerFileIdAndControlMutation(String malformedField) - throws IOException { - LocalPersistentPublicationTestFixture fixture = - LocalPersistentPublicationTestFixture.create( - temporaryDirectory.resolve("malformed-" + malformedField)); - LocalPersistentControlPlane controlPlane = fixture.controlPlane(); - AtomicInteger producerCalls = new AtomicInteger(); - AtomicInteger fileIdCalls = new AtomicInteger(); - LocalPersistentPublicationProvider provider = - fixture.provider( - controlPlane, - fixture.payload(), - () -> { - fileIdCalls.incrementAndGet(); - return fixture.fileId(); - }); - FilePublishRequest valid = fixture.request("source-42"); - FilePublishRequest malformed = - new FilePublishRequest( - valid.operationId(), - valid.destinationId(), - malformedField.equals("logicalFileName") - ? new LogicalFileName("report-\ud800") - : valid.logicalFileName(), - malformedField.equals("sourceRevision") - ? new SourceRevision("source-\ud800") - : valid.sourceRevision(), - valid.schema(), - valid.formatProfileId()); - - assertThatThrownBy( - () -> - provider.publish( - malformed, - sink -> { - producerCalls.incrementAndGet(); - throw new AssertionError("invalid request must not invoke producer"); - })) - .isInstanceOfSatisfying( - FilePublicationException.class, - exception -> - assertThat(exception.reason()) - .isEqualTo(FilePublicationException.Reason.INVALID_REQUEST)); - assertThat(producerCalls).hasValue(0); - assertThat(fileIdCalls).hasValue(0); - assertThat(controlPlane.findStoredOperation(valid.operationId().value())).isEmpty(); - } - - @Test - void concurrentCallsForOneOperationInvokeProducerExactlyOnceAndRestoreOneReceipt() - throws Exception { - LocalPersistentPublicationTestFixture fixture = - LocalPersistentPublicationTestFixture.create(temporaryDirectory.resolve("concurrent")); - AtomicInteger producerCalls = new AtomicInteger(); - AtomicInteger fileIdCalls = new AtomicInteger(); - CountDownLatch firstProducerEntered = new CountDownLatch(1); - CountDownLatch releaseFirstProducer = new CountDownLatch(1); - CountDownLatch secondCallStarted = new CountDownLatch(1); - LocalPersistentPublicationProvider provider = - fixture.provider( - fixture.controlPlane(), - fixture.payload(), - () -> { - fileIdCalls.incrementAndGet(); - return fixture.fileId(); - }); - ExecutorService executor = Executors.newFixedThreadPool(2); - Future first = null; - Future second = null; - try { - first = - executor.submit( - () -> - provider.publish( - fixture.request("source-42"), - sink -> { - producerCalls.incrementAndGet(); - firstProducerEntered.countDown(); - await(releaseFirstProducer); - sink.write( - new TabularRow(List.of(new IntegerCell(1), new TextCell("=cmd")))); - })); - assertThat(firstProducerEntered.await(2, TimeUnit.SECONDS)).isTrue(); - second = - executor.submit( - () -> { - secondCallStarted.countDown(); - return provider.publish( - fixture.request("source-42"), - sink -> { - producerCalls.incrementAndGet(); - throw new AssertionError("serialized retry must not invoke producer"); - }); - }); - assertThat(secondCallStarted.await(2, TimeUnit.SECONDS)).isTrue(); - Future blockedSecond = second; - assertThatThrownBy(() -> blockedSecond.get(150, TimeUnit.MILLISECONDS)) - .isInstanceOf(TimeoutException.class); - - releaseFirstProducer.countDown(); - assertThat(second.get(5, TimeUnit.SECONDS)).isEqualTo(first.get(5, TimeUnit.SECONDS)); - assertThat(producerCalls).hasValue(1); - assertThat(fileIdCalls).hasValue(1); - } finally { - releaseFirstProducer.countDown(); - cancel(first); - cancel(second); - executor.shutdownNow(); - assertThat(executor.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); - } - } - - @Test - void rejectsCrossWiredRootsProviderIdsAndSeparateRuntimeInstances() throws IOException { - LocalPersistentPublicationTestFixture first = - LocalPersistentPublicationTestFixture.create(temporaryDirectory.resolve("wiring-first")); - LocalPersistentPublicationTestFixture second = - LocalPersistentPublicationTestFixture.create(temporaryDirectory.resolve("wiring-second")); - FileDestinationId secondaryId = new FileDestinationId("secondary-export"); - CompiledFileDestination secondary = - first.destinationFor(secondaryId, first.destination().providerId()); - CompiledFileDestination otherProvider = first.destinationFor(secondaryId, "other-primary"); - LocalPersistentControlPlane sharedControl = first.controlPlane(); - LocalPersistentPayloadOperations sharedPayload = first.payload(); - LocalPersistentPublicationProvider.DestinationRuntime primaryRuntime = - new LocalPersistentPublicationProvider.DestinationRuntime( - first.destination(), sharedControl, sharedPayload); - - assertThatThrownBy( - () -> - new LocalPersistentPublicationProvider( - Map.of( - LocalPersistentPublicationTestFixture.DESTINATION, - new LocalPersistentPublicationProvider.DestinationRuntime( - first.destination(), second.controlPlane(), second.payload())), - LocalPersistentPublicationTestFixture.FIXED_CLOCK, - first::fileId)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("root"); - assertThatThrownBy( - () -> - new LocalPersistentPublicationProvider( - Map.of( - LocalPersistentPublicationTestFixture.DESTINATION, - primaryRuntime, - secondaryId, - new LocalPersistentPublicationProvider.DestinationRuntime( - otherProvider, sharedControl, sharedPayload)), - LocalPersistentPublicationTestFixture.FIXED_CLOCK, - first::fileId)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("provider ID"); - assertThatThrownBy( - () -> - new LocalPersistentPublicationProvider( - Map.of( - LocalPersistentPublicationTestFixture.DESTINATION, - primaryRuntime, - secondaryId, - new LocalPersistentPublicationProvider.DestinationRuntime( - secondary, first.controlPlane(), first.payload())), - LocalPersistentPublicationTestFixture.FIXED_CLOCK, - first::fileId)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("shared runtime"); - } - - @Test - void publishesOnceInTheExactDurableOrderAndReturnsOnlyAnOpaqueR2Receipt() throws IOException { - LocalPersistentPublicationTestFixture fixture = - LocalPersistentPublicationTestFixture.create(temporaryDirectory.resolve("publish")); - DurableOrderRecorder order = new DurableOrderRecorder(); - AtomicInteger producerCalls = new AtomicInteger(); - LocalPersistentControlPlane controlPlane = fixture.controlPlane(order::record); - LocalPersistentPublicationProvider provider = - fixture.provider(controlPlane, fixture.payload(order::record), () -> fixture.fileId()); - - FilePublishReceipt receipt = - provider.publish( - fixture.request("source-42"), - sink -> { - producerCalls.incrementAndGet(); - sink.write(new TabularRow(List.of(new IntegerCell(1), new TextCell("=cmd")))); - }); - - assertThat(producerCalls).hasValue(1); - assertThat(order.events()) - .containsExactly( - "J_WRITING", - "STAGE_FORCED", - "J_SEALED", - "DATA_LINKED", - "DATA_DIRECTORY_FORCED", - "J_DATA_PUBLISHED", - "MANIFEST_FORCED", - "J_MANIFEST_PUBLISHED", - "REFERENCE_FORCED", - "J_REFERENCE_PUBLISHED", - "J_PUBLISHED"); - assertThat(receipt.operationId()).isEqualTo(fixture.request("source-42").operationId()); - assertThat(receipt.destinationId()) - .isEqualTo(LocalPersistentPublicationTestFixture.DESTINATION); - assertThat(receipt.reference().value()) - .startsWith("fsr1.") - .doesNotContain(fixture.root().toString()); - assertThat(receipt.publishedFileName()).endsWith(".csv").doesNotContain("/", "\\"); - assertThat(receipt.publishedAt()).isEqualTo(LocalPersistentPublicationTestFixture.PUBLISHED_AT); - assertThat(receipt.publicationGuarantee()).isEqualTo(PublicationGuarantee.UNIQUE_ATOMIC_CREATE); - assertThat(receipt.durabilityGuarantee()) - .isEqualTo(DurabilityGuarantee.FILE_AND_DIRECTORY_SYNC); - assertThat(receipt.dataRowCount()).isEqualTo(1); - assertThat(receipt.columnCount()).isEqualTo(2); - assertThat(receipt.formulaMitigatedCount()).isEqualTo(1); - assertThat(receipt.sha256()) - .isEqualTo( - LocalPersistentPublicationTestFixture.sha256("id,note\n1,'=cmd\n".getBytes(UTF_8))); - - R2PublishedReferenceCodec.DecodedReference decoded = - new R2PublishedReferenceCodec() - .decode(receipt.reference(), Set.of(fixture.destination().routeToken())); - assertThat(decoded.fileId()).isEqualTo(fixture.fileId()); - DurablePublicationRecord operation = - controlPlane.findOperation(fixture.operationId()).orElseThrow(); - PrivateFileManifest manifest = controlPlane.findManifest(decoded.fileId()).orElseThrow(); - PublishedReferenceRecord reference = controlPlane.findReference(decoded.fileId()).orElseThrow(); - assertThat(operation.state()).isEqualTo(DurablePublicationRecord.State.PUBLISHED); - assertThat( - new FileserverControlRecordCodec().decodeReceiptSnapshot(operation.receiptSnapshot())) - .isEqualTo(receipt); - assertThat(manifest.internalLocator()) - .isEqualTo(receipt.publishedFileName()) - .doesNotContain("/", "\\", fixture.root().toString()); - assertThat(reference.internalLocator()).isEqualTo(manifest.internalLocator()); - assertThat(reference.manifestDigest()).isEqualTo(operation.manifestDigest()); - assertThat( - fixture - .root() - .resolve("data") - .resolve(fixture.fileId().substring(0, 2)) - .resolve(manifest.internalLocator())) - .hasBinaryContent("id,note\n1,'=cmd\n".getBytes(UTF_8)); - } - - private static final class DurableOrderRecorder { - - private final List events = new ArrayList<>(); - - void record(LocalPersistentControlPlane.FaultContext context) { - if (context.boundary() != LocalPersistentControlPlane.FaultPoint.PARENT_FORCED) { - return; - } - switch (context.recordKind()) { - case OPERATION -> events.add("J_" + context.operation().orElseThrow().state().name()); - case MANIFEST -> events.add("MANIFEST_FORCED"); - case REFERENCE -> events.add("REFERENCE_FORCED"); - default -> throw new IllegalStateException("unsupported control record kind"); - } - } - - void record(LocalPersistentPayloadOperations.FaultContext context) { - if (context.point() != LocalPersistentPayloadOperations.FaultPoint.STAGE_DELETED) { - events.add(context.point().name()); - } - } - - List events() { - return List.copyOf(events); - } - } - - private static void await(CountDownLatch latch) { - try { - if (!latch.await(5, TimeUnit.SECONDS)) { - throw new AssertionError("timed out waiting for concurrent publication release"); - } - } catch (InterruptedException exception) { - Thread.currentThread().interrupt(); - throw new IllegalStateException("concurrent publication interrupted", exception); - } - } - - private static void cancel(Future future) { - if (future != null && !future.isDone()) { - future.cancel(true); - } - } -} - -final class LocalPersistentPublicationTestFixture { - - static final FileDestinationId DESTINATION = new FileDestinationId("local-export"); - static final Instant PUBLISHED_AT = Instant.parse("2026-07-28T01:02:17Z"); - static final Clock FIXED_CLOCK = Clock.fixed(PUBLISHED_AT, ZoneOffset.UTC); - static final String FILE_ID = "00112233445566778899aabbccddeeff"; - static final String SENTINEL_NAME = ".ca-fileserver-volume"; - static final byte[] SENTINEL_CONTENT = "fileserver-r2-provider-root\n".getBytes(UTF_8); - - private final Path root; - private final CompiledFileDestination destination; - private final LocalPersistentRootAttestor attestor; - private final LocalPersistentRootEvidence evidence; - - private LocalPersistentPublicationTestFixture( - Path root, - CompiledFileDestination destination, - LocalPersistentRootAttestor attestor, - LocalPersistentRootEvidence evidence) { - this.root = root; - this.destination = destination; - this.attestor = attestor; - this.evidence = evidence; - } - - static LocalPersistentPublicationTestFixture create(Path root) throws IOException { - Path normalizedRoot = root.toAbsolutePath().normalize(); - Files.createDirectory( - normalizedRoot, - PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwx------"))); - Files.write(normalizedRoot.resolve(SENTINEL_NAME), SENTINEL_CONTENT); - FileStore store = Files.getFileStore(normalizedRoot); - Set rootMode = PosixFilePermissions.fromString("rwx------"); - CompiledFileDestination destination = - new CompiledFileDestination( - DESTINATION, - "local-primary", - normalizedRoot, - 10_000, - 16 * 1024 * 1024, - store.name(), - store.type(), - SENTINEL_NAME, - sha256(SENTINEL_CONTENT), - Files.getOwner(normalizedRoot).getName(), - "0700", - rootMode, - PublicationGuarantee.UNIQUE_ATOMIC_CREATE, - DurabilityGuarantee.FILE_AND_DIRECTORY_SYNC); - LocalPersistentRootAttestor attestor = new LocalPersistentRootAttestor(); - LocalPersistentRootEvidence evidence = attestor.attest(destination); - return new LocalPersistentPublicationTestFixture( - normalizedRoot, destination, attestor, evidence); - } - - LocalPersistentControlPlane controlPlane() { - return new LocalPersistentControlPlane(attestor, evidence); - } - - LocalPersistentControlPlane controlPlane( - LocalPersistentControlPlane.ContextualFaultCallback callback) { - return LocalPersistentControlPlane.withContextualFaultCallback(attestor, evidence, callback); - } - - LocalPersistentPayloadOperations payload() { - return new LocalPersistentPayloadOperations(attestor, evidence); - } - - LocalPersistentPayloadOperations payload( - LocalPersistentPayloadOperations.FaultCallback callback) { - return new LocalPersistentPayloadOperations(attestor, evidence, callback); - } - - LocalPersistentPublicationProvider provider() { - return provider(controlPlane(), payload(), () -> FILE_ID); - } - - LocalPersistentPublicationProvider provider( - LocalPersistentControlPlane controlPlane, - LocalPersistentPayloadOperations payload, - LocalPersistentPublicationProvider.FileIdGenerator fileIds) { - return provider(destination, controlPlane, payload, fileIds); - } - - LocalPersistentPublicationProvider provider( - CompiledFileDestination effectiveDestination, - LocalPersistentControlPlane controlPlane, - LocalPersistentPayloadOperations payload, - LocalPersistentPublicationProvider.FileIdGenerator fileIds) { - LocalPersistentPublicationProvider.DestinationRuntime runtime = - new LocalPersistentPublicationProvider.DestinationRuntime( - effectiveDestination, controlPlane, payload); - return new LocalPersistentPublicationProvider( - Map.of(DESTINATION, runtime), FIXED_CLOCK, fileIds); - } - - CompiledFileDestination destinationWithLimits(long maximumRows, long maximumEncodedBytes) { - return destinationFor( - destination.destinationId(), destination.providerId(), maximumRows, maximumEncodedBytes); - } - - CompiledFileDestination destinationFor(FileDestinationId destinationId, String providerId) { - return destinationFor( - destinationId, providerId, destination.maximumRows(), destination.maximumEncodedBytes()); - } - - private CompiledFileDestination destinationFor( - FileDestinationId destinationId, - String providerId, - long maximumRows, - long maximumEncodedBytes) { - return new CompiledFileDestination( - destinationId, - providerId, - destination.rootDirectory(), - maximumRows, - maximumEncodedBytes, - destination.expectedFileStoreName(), - destination.expectedFileStoreType(), - destination.mountSentinelName(), - destination.mountSentinelSha256(), - destination.expectedOwner(), - destination.maximumRootMode(), - destination.maximumRootPermissions(), - destination.requiredPublicationGuarantee(), - destination.requiredDurabilityGuarantee()); - } - - FilePublishRequest request(String sourceRevision) { - return new FilePublishRequest( - new FilePublishOperationId(operationId()), - DESTINATION, - new LogicalFileName("report"), - new SourceRevision(sourceRevision), - new ExportSchema( - "worklog-v1", - 1, - List.of( - new Column("id", CellType.INTEGER, false, FormulaPolicy.REJECT, 64), - new Column("note", CellType.TEXT, false, FormulaPolicy.MITIGATE, 256))), - "csv-rfc4180-v1"); - } - - Path root() { - return root; - } - - CompiledFileDestination destination() { - return destination; - } - - String operationId() { - return "operation-r2-01"; - } - - String fileId() { - return FILE_ID; - } - - static String sha256(byte[] bytes) { - try { - return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); - } catch (NoSuchAlgorithmException exception) { - throw new AssertionError("SHA-256 must be available", exception); - } - } -} diff --git a/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/LocalPersistentPublicationRecoveryTest.java b/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/LocalPersistentPublicationRecoveryTest.java deleted file mode 100644 index 9400ea3d..00000000 --- a/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/LocalPersistentPublicationRecoveryTest.java +++ /dev/null @@ -1,1121 +0,0 @@ -package dev.caskeleton.adapter.outbound.fileserver; - -import static java.nio.charset.StandardCharsets.UTF_8; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.assertj.core.api.Assertions.catchThrowable; - -import dev.caskeleton.application.filepublication.FilePublicationException; -import dev.caskeleton.application.filepublication.FilePublishReceipt; -import dev.caskeleton.application.filepublication.FilePublishReceipt.DurabilityGuarantee; -import dev.caskeleton.application.filepublication.FilePublishReceipt.PublicationGuarantee; -import dev.caskeleton.application.filepublication.PublishedFileReference; -import dev.caskeleton.application.filepublication.TabularCell.IntegerCell; -import dev.caskeleton.application.filepublication.TabularCell.TextCell; -import dev.caskeleton.application.filepublication.TabularRow; -import java.io.IOException; -import java.nio.channels.FileChannel; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.StandardCopyOption; -import java.nio.file.StandardOpenOption; -import java.nio.file.attribute.PosixFilePermissions; -import java.util.List; -import java.util.Locale; -import java.util.concurrent.atomic.AtomicInteger; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.EnumSource; -import org.junit.jupiter.params.provider.ValueSource; - -class LocalPersistentPublicationRecoveryTest { - - @TempDir Path temporaryDirectory; - private final AtomicInteger fixtureSequence = new AtomicInteger(); - - @Test - void sealedStageResumesFromDurableBytesWithoutReplayingTheProducer() throws IOException { - LocalPersistentPublicationTestFixture fixture = fixture("sealed-stage"); - PublishedBaseline baseline = publishBaseline(fixture); - LocalPersistentPayloadOperations payload = fixture.payload(); - Path data = baseline.dataPath(); - Path preservedData = fixture.root().resolve("preserved-data"); - Files.move(data, preservedData, StandardCopyOption.ATOMIC_MOVE); - forceDirectory(data.getParent()); - payload.stage( - fixture.operationId(), - baseline.operation().stageFileName(), - baseline.operation().byteSize(), - output -> Files.copy(preservedData, output)); - Files.delete(preservedData); - forceDirectory(fixture.root()); - removeControlRecord(baseline.referencePath()); - removeControlRecord(baseline.manifestPath()); - rewriteOperation( - baseline.operationPath(), - atState(baseline.operation(), DurablePublicationRecord.State.SEALED)); - - FilePublishReceipt restored = recoverWithoutProducer(fixture); - - assertThat(restored).isEqualTo(baseline.receipt()); - assertThat(data).hasBinaryContent(baseline.payload()); - assertThat(fixture.controlPlane().findOperation(fixture.operationId()).orElseThrow().state()) - .isEqualTo(DurablePublicationRecord.State.PUBLISHED); - } - - @Test - void sealedMatchingDataIsReverifiedAndResumesAtManifestWithoutProducerReplay() - throws IOException { - LocalPersistentPublicationTestFixture fixture = fixture("sealed-data"); - PublishedBaseline baseline = publishBaseline(fixture); - removeControlRecord(baseline.referencePath()); - removeControlRecord(baseline.manifestPath()); - rewriteOperation( - baseline.operationPath(), - atState(baseline.operation(), DurablePublicationRecord.State.SEALED)); - - FilePublishReceipt restored = recoverWithoutProducer(fixture); - - assertThat(restored).isEqualTo(baseline.receipt()); - assertThat(baseline.dataPath()).hasBinaryContent(baseline.payload()); - } - - @ParameterizedTest - @EnumSource( - value = DurablePublicationRecord.State.class, - names = {"DATA_PUBLISHED", "MANIFEST_PUBLISHED", "REFERENCE_PUBLISHED"}) - void resumesEveryDurableMetadataStateWithoutProducerReplay(DurablePublicationRecord.State state) - throws IOException { - LocalPersistentPublicationTestFixture fixture = fixture(state.name().toLowerCase(Locale.ROOT)); - PublishedBaseline baseline = publishBaseline(fixture); - if (state == DurablePublicationRecord.State.DATA_PUBLISHED) { - removeControlRecord(baseline.referencePath()); - removeControlRecord(baseline.manifestPath()); - } else if (state == DurablePublicationRecord.State.MANIFEST_PUBLISHED) { - removeControlRecord(baseline.referencePath()); - } - rewriteOperation(baseline.operationPath(), atState(baseline.operation(), state)); - - FilePublishReceipt restored = recoverWithoutProducer(fixture); - - assertThat(restored).isEqualTo(baseline.receipt()); - assertThat(fixture.controlPlane().findOperation(fixture.operationId()).orElseThrow().state()) - .isEqualTo(DurablePublicationRecord.State.PUBLISHED); - } - - @Test - void publishedOperationRestoresTheExactReceiptWithoutProducerOrFileIdAllocation() - throws IOException { - LocalPersistentPublicationTestFixture fixture = fixture("published-restore"); - PublishedBaseline baseline = publishBaseline(fixture); - - FilePublishReceipt restored = recoverWithoutProducer(fixture); - - assertThat(restored).isEqualTo(baseline.receipt()); - } - - @ParameterizedTest - @ValueSource(booleans = {false, true}) - void existingWritingOrUnsealedQuarantineNeverReplaysProducer(boolean alreadyQuarantined) - throws IOException { - LocalPersistentPublicationTestFixture fixture = - fixture(alreadyQuarantined ? "existing-quarantine" : "existing-writing"); - LocalPersistentControlPlane controlPlane = fixture.controlPlane(); - DurablePublicationRecord writing = writingRecord(fixture); - controlPlane.storeOperation(writing); - if (alreadyQuarantined) { - controlPlane.storeOperation(unsealedQuarantined(writing, "STAGE_FAILED")); - } - AtomicInteger producerCalls = new AtomicInteger(); - AtomicInteger fileIdCalls = new AtomicInteger(); - - assertThatThrownBy( - () -> - fixture - .provider( - controlPlane, - fixture.payload(), - () -> { - fileIdCalls.incrementAndGet(); - return "f".repeat(32); - }) - .publish(fixture.request("source-42"), sink -> producerCalls.incrementAndGet())) - .isInstanceOfSatisfying( - FilePublicationException.class, - exception -> - assertThat(exception.reason()) - .isEqualTo(FilePublicationException.Reason.PUBLISH_INDETERMINATE)); - - assertThat(producerCalls).hasValue(0); - assertThat(fileIdCalls).hasValue(0); - DurablePublicationRecord retained = - controlPlane.findOperation(fixture.operationId()).orElseThrow(); - assertThat(retained.state()).isEqualTo(DurablePublicationRecord.State.QUARANTINED); - assertThat(retained.sha256()).isEmpty(); - assertThat(stagePath(fixture, retained)).doesNotExist(); - } - - @Test - void reusedOperationWithDifferentFingerprintIsConflictWithoutMutationOrReplay() - throws IOException { - LocalPersistentPublicationTestFixture fixture = fixture("fingerprint-conflict"); - PublishedBaseline baseline = publishBaseline(fixture); - byte[] operationEvidence = Files.readAllBytes(baseline.operationPath()); - AtomicInteger producerCalls = new AtomicInteger(); - AtomicInteger fileIdCalls = new AtomicInteger(); - - assertThatThrownBy( - () -> - fixture - .provider( - fixture.controlPlane(), - fixture.payload(), - () -> { - fileIdCalls.incrementAndGet(); - return "f".repeat(32); - }) - .publish( - fixture.request("different-source"), - sink -> producerCalls.incrementAndGet())) - .isInstanceOfSatisfying( - FilePublicationException.class, - exception -> - assertThat(exception.reason()).isEqualTo(FilePublicationException.Reason.CONFLICT)); - - assertThat(producerCalls).hasValue(0); - assertThat(fileIdCalls).hasValue(0); - assertThat(baseline.operationPath()).hasBinaryContent(operationEvidence); - } - - @Test - void currentEffectivePolicyMismatchFailsClosedWithoutReinterpretingStoredEvidence() - throws IOException { - LocalPersistentPublicationTestFixture fixture = fixture("policy-mismatch"); - PublishedBaseline baseline = publishBaseline(fixture); - byte[] operationEvidence = Files.readAllBytes(baseline.operationPath()); - CompiledFileDestination changedPolicy = - fixture.destinationWithLimits( - fixture.destination().maximumRows() + 1, fixture.destination().maximumEncodedBytes()); - AtomicInteger producerCalls = new AtomicInteger(); - AtomicInteger fileIdCalls = new AtomicInteger(); - - assertThatThrownBy( - () -> - fixture - .provider( - changedPolicy, - fixture.controlPlane(), - fixture.payload(), - () -> { - fileIdCalls.incrementAndGet(); - return "f".repeat(32); - }) - .publish(fixture.request("source-42"), sink -> producerCalls.incrementAndGet())) - .isInstanceOfSatisfying( - FilePublicationException.class, - exception -> - assertThat(exception.reason()) - .isEqualTo(FilePublicationException.Reason.PUBLISH_INDETERMINATE)); - - assertThat(producerCalls).hasValue(0); - assertThat(fileIdCalls).hasValue(0); - assertThat(baseline.operationPath()).hasBinaryContent(operationEvidence); - } - - @ParameterizedTest - @ValueSource(strings = {"sentinel", "root"}) - void attestedRootIdentityChangeFailsBeforeProducerAndFileIdAllocation(String change) - throws IOException { - LocalPersistentPublicationTestFixture fixture = fixture("identity-" + change); - LocalPersistentControlPlane controlPlane = fixture.controlPlane(); - LocalPersistentPublicationProvider provider = - fixture.provider( - controlPlane, - fixture.payload(), - () -> { - throw new AssertionError("identity failure must precede file ID allocation"); - }); - if (change.equals("sentinel")) { - Path sentinel = fixture.root().resolve(LocalPersistentPublicationTestFixture.SENTINEL_NAME); - Files.write( - sentinel, - "changed-sentinel\n".getBytes(UTF_8), - StandardOpenOption.WRITE, - StandardOpenOption.TRUNCATE_EXISTING); - forceFile(sentinel); - forceDirectory(fixture.root()); - } else { - Path attestedRoot = fixture.root().resolveSibling(fixture.root().getFileName() + "-attested"); - Files.move(fixture.root(), attestedRoot, StandardCopyOption.ATOMIC_MOVE); - Files.createDirectory( - fixture.root(), - PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwx------"))); - Files.write( - fixture.root().resolve(LocalPersistentPublicationTestFixture.SENTINEL_NAME), - LocalPersistentPublicationTestFixture.SENTINEL_CONTENT); - forceDirectory(fixture.root().getParent()); - } - AtomicInteger producerCalls = new AtomicInteger(); - - assertThatThrownBy( - () -> - provider.publish( - fixture.request("source-42"), sink -> producerCalls.incrementAndGet())) - .isInstanceOfSatisfying( - FilePublicationException.class, - exception -> - assertThat(exception.reason()) - .isEqualTo(FilePublicationException.Reason.PUBLISH_INDETERMINATE)); - assertThat(producerCalls).hasValue(0); - } - - @Test - void sealedStageAndDataWithEqualBytesButDifferentFileKeysAreQuarantined() throws IOException { - LocalPersistentPublicationTestFixture fixture = fixture("split-hard-link"); - PublishedBaseline baseline = publishBaseline(fixture); - LocalPersistentPayloadOperations payload = fixture.payload(); - LocalPersistentPayloadOperations.VerifiedArtifact staged = - payload.stage( - fixture.operationId(), - baseline.operation().stageFileName(), - baseline.operation().byteSize(), - output -> Files.copy(baseline.dataPath(), output)); - LocalPersistentPayloadOperations.VerifiedArtifact data = - payload - .inspectData( - fixture.fileId(), - baseline.operation().publishedFileName(), - baseline.operation().byteSize()) - .orElseThrow(); - assertThat(staged.sha256()).isEqualTo(data.sha256()); - assertThat(staged.fileKey()).isNotEqualTo(data.fileKey()); - prepareAtState(baseline, DurablePublicationRecord.State.SEALED); - - DurablePublicationRecord quarantined = recoverAndRequireQuarantine(fixture); - - assertThat(quarantined.lastFailureCode()).isEqualTo("RECOVERY_INTEGRITY"); - assertThat(stagePath(fixture, quarantined)).hasBinaryContent(baseline.payload()); - assertThat(baseline.dataPath()).hasBinaryContent(baseline.payload()); - } - - @Test - void sealedWithoutStageOrDataIsQuarantinedWithoutProducerReplay() throws IOException { - LocalPersistentPublicationTestFixture fixture = fixture("sealed-missing-all"); - PublishedBaseline baseline = publishBaseline(fixture); - Files.delete(baseline.dataPath()); - forceDirectory(baseline.dataPath().getParent()); - prepareAtState(baseline, DurablePublicationRecord.State.SEALED); - - DurablePublicationRecord quarantined = recoverAndRequireQuarantine(fixture); - - assertThat(quarantined.lastFailureCode()).isEqualTo("RECOVERY_INTEGRITY"); - assertThat(stagePath(fixture, quarantined)).doesNotExist(); - assertThat(baseline.dataPath()).doesNotExist(); - } - - @Test - void dataPublishedRetryDeletesResidualMatchingStageAndConverges() throws IOException { - LocalPersistentPublicationTestFixture fixture = fixture("residual-stage"); - PublishedBaseline baseline = publishBaseline(fixture); - Path residualStage = stagePath(fixture, baseline.operation()); - Files.createLink(residualStage, baseline.dataPath()); - forceDirectory(residualStage.getParent()); - assertThat(Files.isSameFile(residualStage, baseline.dataPath())).isTrue(); - prepareAtState(baseline, DurablePublicationRecord.State.DATA_PUBLISHED); - - FilePublishReceipt restored = recoverWithoutProducer(fixture); - - assertThat(restored).isEqualTo(baseline.receipt()); - assertThat(residualStage).doesNotExist(); - assertThat(baseline.dataPath()).hasBinaryContent(baseline.payload()); - } - - @ParameterizedTest - @EnumSource( - value = DurablePublicationRecord.State.class, - names = {"DATA_PUBLISHED", "MANIFEST_PUBLISHED", "REFERENCE_PUBLISHED"}) - void missingRequiredArtifactAtEveryNonTerminalStateIsQuarantined( - DurablePublicationRecord.State state) throws IOException { - LocalPersistentPublicationTestFixture fixture = - fixture("missing-" + state.name().toLowerCase(Locale.ROOT)); - PublishedBaseline baseline = publishBaseline(fixture); - prepareAtState(baseline, state); - switch (state) { - case DATA_PUBLISHED -> { - Files.delete(baseline.dataPath()); - forceDirectory(baseline.dataPath().getParent()); - } - case MANIFEST_PUBLISHED -> removeControlRecord(baseline.manifestPath()); - case REFERENCE_PUBLISHED -> removeControlRecord(baseline.referencePath()); - default -> throw new AssertionError("unexpected recovery fixture state " + state); - } - - DurablePublicationRecord quarantined = recoverAndRequireQuarantine(fixture); - - assertThat(quarantined.lastFailureCode()).isEqualTo("RECOVERY_INTEGRITY"); - } - - @ParameterizedTest - @EnumSource( - value = DurablePublicationRecord.State.class, - names = {"DATA_PUBLISHED", "MANIFEST_PUBLISHED", "REFERENCE_PUBLISHED"}) - void mismatchedEvidenceAtEveryNonTerminalStateIsPreservedAndQuarantined( - DurablePublicationRecord.State state) throws IOException { - LocalPersistentPublicationTestFixture fixture = - fixture("mismatch-" + state.name().toLowerCase(Locale.ROOT)); - PublishedBaseline baseline = publishBaseline(fixture); - prepareAtState(baseline, state); - Path mismatchedEvidence; - switch (state) { - case DATA_PUBLISHED -> { - Files.write( - baseline.dataPath(), - "same-state-wrong-data".getBytes(UTF_8), - StandardOpenOption.WRITE, - StandardOpenOption.TRUNCATE_EXISTING); - forceFile(baseline.dataPath()); - forceDirectory(baseline.dataPath().getParent()); - mismatchedEvidence = baseline.dataPath(); - } - case MANIFEST_PUBLISHED -> { - PrivateFileManifest manifest = - fixture.controlPlane().findManifest(fixture.fileId()).orElseThrow(); - rewriteRecord( - baseline.manifestPath(), - new FileserverControlRecordCodec() - .encodeManifest(manifestWithSchemaId(manifest, "different-schema"))); - mismatchedEvidence = baseline.manifestPath(); - } - case REFERENCE_PUBLISHED -> { - PublishedReferenceRecord reference = - fixture.controlPlane().findReference(fixture.fileId()).orElseThrow(); - rewriteRecord( - baseline.referencePath(), - new FileserverControlRecordCodec() - .encodeReference(referenceWithMediaType(reference, "application/csv"))); - mismatchedEvidence = baseline.referencePath(); - } - default -> throw new AssertionError("unexpected recovery fixture state " + state); - } - byte[] mismatch = Files.readAllBytes(mismatchedEvidence); - - DurablePublicationRecord quarantined = recoverAndRequireQuarantine(fixture); - - assertThat(quarantined.lastFailureCode()).isIn("RECOVERY_INTEGRITY", "PAYLOAD_INTEGRITY"); - assertThat(mismatchedEvidence).hasBinaryContent(mismatch); - } - - @Test - void producerFailureAfterWritingJournalLeavesUnsealedQuarantineAndSuppressesControlFailure() - throws IOException { - LocalPersistentPublicationTestFixture fixture = fixture("writing-failure"); - RuntimeException sourceFailure = new IllegalStateException("source failed"); - RuntimeException quarantineCallbackFailure = - new IllegalStateException("quarantine callback failed"); - LocalPersistentControlPlane controlPlane = - fixture.controlPlane( - context -> { - if (context.recordKind() == LocalPersistentControlPlane.ControlRecordKind.OPERATION - && context.boundary() == LocalPersistentControlPlane.FaultPoint.PARENT_FORCED - && context.operation().orElseThrow().state() - == DurablePublicationRecord.State.QUARANTINED) { - throw quarantineCallbackFailure; - } - }); - LocalPersistentPublicationProvider provider = - fixture.provider(controlPlane, fixture.payload(), () -> fixture.fileId()); - - Throwable failure = - catchThrowable( - () -> - provider.publish( - fixture.request("source-42"), - sink -> { - sink.write( - new TabularRow(List.of(new IntegerCell(1), new TextCell("partial")))); - throw sourceFailure; - })); - - assertThat(failure).isSameAs(sourceFailure); - assertThat(failure.getSuppressed()).contains(quarantineCallbackFailure); - DurablePublicationRecord quarantined = - controlPlane.findOperation(fixture.operationId()).orElseThrow(); - assertThat(quarantined.state()).isEqualTo(DurablePublicationRecord.State.QUARANTINED); - assertThat(quarantined.sha256()).isEmpty(); - assertThat(stagePath(fixture, quarantined)).doesNotExist(); - - AtomicInteger retryProducerCalls = new AtomicInteger(); - assertThatThrownBy( - () -> - fixture - .provider() - .publish( - fixture.request("source-42"), sink -> retryProducerCalls.incrementAndGet())) - .isInstanceOfSatisfying( - FilePublicationException.class, - exception -> - assertThat(exception.reason()) - .isEqualTo(FilePublicationException.Reason.PUBLISH_INDETERMINATE)); - assertThat(retryProducerCalls).hasValue(0); - } - - @Test - void publishedMismatchPreservesTerminalJournalManifestReferenceAndMismatchedData() - throws IOException { - LocalPersistentPublicationTestFixture fixture = fixture("terminal-mismatch"); - PublishedBaseline baseline = publishBaseline(fixture); - byte[] operationEvidence = Files.readAllBytes(baseline.operationPath()); - byte[] manifestEvidence = Files.readAllBytes(baseline.manifestPath()); - byte[] referenceEvidence = Files.readAllBytes(baseline.referencePath()); - byte[] mismatch = "tampered-terminal-data".getBytes(UTF_8); - Files.write( - baseline.dataPath(), - mismatch, - StandardOpenOption.WRITE, - StandardOpenOption.TRUNCATE_EXISTING); - forceFile(baseline.dataPath()); - forceDirectory(baseline.dataPath().getParent()); - AtomicInteger producerCalls = new AtomicInteger(); - AtomicInteger fileIdCalls = new AtomicInteger(); - LocalPersistentPublicationProvider provider = - fixture.provider( - fixture.controlPlane(), - fixture.payload(), - () -> { - fileIdCalls.incrementAndGet(); - return "f".repeat(32); - }); - - assertThatThrownBy( - () -> - provider.publish( - fixture.request("source-42"), sink -> producerCalls.incrementAndGet())) - .isInstanceOfSatisfying( - FilePublicationException.class, - exception -> - assertThat(exception.reason()) - .isEqualTo(FilePublicationException.Reason.PUBLISH_INDETERMINATE)); - - assertThat(producerCalls).hasValue(0); - assertThat(fileIdCalls).hasValue(0); - assertThat(baseline.operationPath()).hasBinaryContent(operationEvidence); - assertThat(baseline.manifestPath()).hasBinaryContent(manifestEvidence); - assertThat(baseline.referencePath()).hasBinaryContent(referenceEvidence); - assertThat(baseline.dataPath()).hasBinaryContent(mismatch); - assertThat(fixture.controlPlane().findOperation(fixture.operationId()).orElseThrow().state()) - .isEqualTo(DurablePublicationRecord.State.PUBLISHED); - } - - @ParameterizedTest - @ValueSource(strings = {"receipt", "manifest", "reference"}) - void alteredTerminalMetadataRemainsByteForByteImmutableAndNeverBecomesQuarantine( - String alteredKind) throws IOException { - LocalPersistentPublicationTestFixture fixture = fixture("terminal-" + alteredKind); - PublishedBaseline baseline = publishBaseline(fixture); - FileserverControlRecordCodec codec = new FileserverControlRecordCodec(); - if (alteredKind.equals("receipt")) { - FilePublishReceipt alteredReceipt = - receiptWithFormat(baseline.receipt(), "csv-rfc4180-altered"); - rewriteOperation( - baseline.operationPath(), - publishedWithReceipt(baseline.operation(), codec.encodeReceiptSnapshot(alteredReceipt))); - } else if (alteredKind.equals("manifest")) { - PrivateFileManifest manifest = - fixture.controlPlane().findManifest(fixture.fileId()).orElseThrow(); - rewriteRecord( - baseline.manifestPath(), - codec.encodeManifest(manifestWithSchemaId(manifest, "different-schema"))); - } else { - PublishedReferenceRecord reference = - fixture.controlPlane().findReference(fixture.fileId()).orElseThrow(); - rewriteRecord( - baseline.referencePath(), - codec.encodeReference(referenceWithMediaType(reference, "application/csv"))); - } - byte[] operationEvidence = Files.readAllBytes(baseline.operationPath()); - byte[] manifestEvidence = Files.readAllBytes(baseline.manifestPath()); - byte[] referenceEvidence = Files.readAllBytes(baseline.referencePath()); - byte[] dataEvidence = Files.readAllBytes(baseline.dataPath()); - - expectIndeterminateWithoutProducerOrFileId(fixture); - - assertThat(baseline.operationPath()).hasBinaryContent(operationEvidence); - assertThat(baseline.manifestPath()).hasBinaryContent(manifestEvidence); - assertThat(baseline.referencePath()).hasBinaryContent(referenceEvidence); - assertThat(baseline.dataPath()).hasBinaryContent(dataEvidence); - assertThat(fixture.controlPlane().findOperation(fixture.operationId()).orElseThrow().state()) - .isEqualTo(DurablePublicationRecord.State.PUBLISHED); - } - - @Test - void restoresCanonicalR1ArtifactInPlaceWithoutPromotingOrRewritingIt() throws IOException { - LocalPersistentPublicationTestFixture fixture = fixture("r1-restore"); - byte[] payload = "id,note\n1,legacy\n".getBytes(UTF_8); - String digest = LocalPersistentPublicationTestFixture.sha256(payload); - String operationToken = operationToken(fixture.operationId()); - String publishedFileName = "report--" + operationToken + ".csv"; - String stageFileName = "." + operationToken + ".part"; - Path artifact = fixture.root().resolve(publishedFileName); - Files.write(artifact, payload, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE); - Files.setPosixFilePermissions(artifact, PosixFilePermissions.fromString("rw-------")); - forceFile(artifact); - forceDirectory(fixture.root()); - LocalPublicationJournalRecord r1 = - LocalPublicationJournalRecord.sealed( - fixture.operationId(), - FilePublishRequestFingerprint.calculate(fixture.request("source-42")), - publishedFileName, - stageFileName, - payload.length, - 1, - 2, - digest, - 0) - .published( - LocalPersistentPublicationTestFixture.PUBLISHED_AT, - PublicationGuarantee.UNIQUE_ATOMIC_CREATE.name()); - LocalPublicationJournal journal = new LocalPublicationJournal(fixture.root()); - journal.store(r1); - Path operationPath = journal.recordPath(fixture.operationId()); - byte[] operationEvidence = Files.readAllBytes(operationPath); - AtomicInteger producerCalls = new AtomicInteger(); - AtomicInteger fileIdCalls = new AtomicInteger(); - - FilePublishReceipt restored = - fixture - .provider( - fixture.controlPlane(), - fixture.payload(), - () -> { - fileIdCalls.incrementAndGet(); - return fixture.fileId(); - }) - .publish(fixture.request("source-42"), sink -> producerCalls.incrementAndGet()); - - assertThat(producerCalls).hasValue(0); - assertThat(fileIdCalls).hasValue(0); - assertThat(restored.reference()) - .isEqualTo( - new PublishedFileReference( - "filepub:" + fixture.destination().destinationId().value() + ":" + operationToken)); - assertThat(restored.publishedFileName()).isEqualTo(publishedFileName); - assertThat(restored.version().value()).isEqualTo(digest); - assertThat(restored.publishedAt()) - .isEqualTo(LocalPersistentPublicationTestFixture.PUBLISHED_AT); - assertThat(restored.publicationGuarantee()) - .isEqualTo(PublicationGuarantee.UNIQUE_ATOMIC_CREATE); - assertThat(restored.durabilityGuarantee()).isEqualTo(DurabilityGuarantee.PROCESS_LOCAL_SYNC); - assertThat(operationPath).hasBinaryContent(operationEvidence); - assertThat(artifact).hasBinaryContent(payload); - assertThat(countRegularFiles(fixture.root().resolve(".ca-fileserver/manifests"))).isZero(); - assertThat(countRegularFiles(fixture.root().resolve(".ca-fileserver/references"))).isZero(); - } - - @ParameterizedTest - @ValueSource(strings = {"corrupt", "noncanonical"}) - void corruptOrNoncanonicalR1IsIndeterminateAndNeverPromoted(String invalidKind) - throws IOException { - LocalPersistentPublicationTestFixture fixture = fixture("r1-" + invalidKind); - R1Baseline baseline = prepareR1Baseline(fixture); - byte[] canonical = Files.readAllBytes(baseline.operationPath()); - byte[] invalid = - invalidKind.equals("corrupt") - ? "{\"corrupt\":true}".getBytes(UTF_8) - : new String(canonical, UTF_8).replaceFirst("\\{", "{ ").getBytes(UTF_8); - rewriteRecord(baseline.operationPath(), invalid); - - expectIndeterminateWithoutProducerOrFileId(fixture); - - assertThat(baseline.operationPath()).hasBinaryContent(invalid); - assertThat(baseline.artifact()).hasBinaryContent(baseline.payload()); - assertThat(countRegularFiles(fixture.root().resolve(".ca-fileserver/manifests"))).isZero(); - assertThat(countRegularFiles(fixture.root().resolve(".ca-fileserver/references"))).isZero(); - } - - private LocalPersistentPublicationTestFixture fixture(String name) throws IOException { - return LocalPersistentPublicationTestFixture.create( - temporaryDirectory.resolve(name + "-" + fixtureSequence.incrementAndGet())); - } - - private static PublishedBaseline publishBaseline(LocalPersistentPublicationTestFixture fixture) - throws IOException { - byte[] payload = "id,note\n1,'=cmd\n".getBytes(UTF_8); - LocalPersistentControlPlane controlPlane = fixture.controlPlane(); - FilePublishReceipt receipt = - fixture - .provider(controlPlane, fixture.payload(), () -> fixture.fileId()) - .publish( - fixture.request("source-42"), - sink -> - sink.write(new TabularRow(List.of(new IntegerCell(1), new TextCell("=cmd"))))); - DurablePublicationRecord operation = - controlPlane.findOperation(fixture.operationId()).orElseThrow(); - Path operationPath = operationPath(fixture.root(), fixture.operationId()); - Path manifestPath = fileRecordPath(fixture.root(), "manifests", fixture.fileId()); - Path referencePath = fileRecordPath(fixture.root(), "references", fixture.fileId()); - Path dataPath = - fixture - .root() - .resolve("data") - .resolve(fixture.fileId().substring(0, 2)) - .resolve(operation.publishedFileName()); - assertThat(dataPath).hasBinaryContent(payload); - return new PublishedBaseline( - receipt, operation, payload, operationPath, manifestPath, referencePath, dataPath); - } - - private static FilePublishReceipt recoverWithoutProducer( - LocalPersistentPublicationTestFixture fixture) { - AtomicInteger producerCalls = new AtomicInteger(); - AtomicInteger fileIdCalls = new AtomicInteger(); - FilePublishReceipt receipt = - fixture - .provider( - fixture.controlPlane(), - fixture.payload(), - () -> { - fileIdCalls.incrementAndGet(); - return "f".repeat(32); - }) - .publish( - fixture.request("source-42"), - sink -> { - producerCalls.incrementAndGet(); - throw new AssertionError("recovery must not invoke the producer"); - }); - assertThat(producerCalls).hasValue(0); - assertThat(fileIdCalls).hasValue(0); - return receipt; - } - - private static R1Baseline prepareR1Baseline(LocalPersistentPublicationTestFixture fixture) - throws IOException { - byte[] payload = "id,note\n1,legacy\n".getBytes(UTF_8); - String digest = LocalPersistentPublicationTestFixture.sha256(payload); - String operationToken = operationToken(fixture.operationId()); - String publishedFileName = "report--" + operationToken + ".csv"; - String stageFileName = "." + operationToken + ".part"; - Path artifact = fixture.root().resolve(publishedFileName); - Files.write(artifact, payload, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE); - Files.setPosixFilePermissions(artifact, PosixFilePermissions.fromString("rw-------")); - forceFile(artifact); - forceDirectory(fixture.root()); - LocalPublicationJournalRecord record = - LocalPublicationJournalRecord.sealed( - fixture.operationId(), - FilePublishRequestFingerprint.calculate(fixture.request("source-42")), - publishedFileName, - stageFileName, - payload.length, - 1, - 2, - digest, - 0) - .published( - LocalPersistentPublicationTestFixture.PUBLISHED_AT, - PublicationGuarantee.UNIQUE_ATOMIC_CREATE.name()); - LocalPublicationJournal journal = new LocalPublicationJournal(fixture.root()); - journal.store(record); - return new R1Baseline(artifact, payload, journal.recordPath(fixture.operationId())); - } - - private static DurablePublicationRecord recoverAndRequireQuarantine( - LocalPersistentPublicationTestFixture fixture) { - expectIndeterminateWithoutProducerOrFileId(fixture); - DurablePublicationRecord operation = - fixture.controlPlane().findOperation(fixture.operationId()).orElseThrow(); - assertThat(operation.state()).isEqualTo(DurablePublicationRecord.State.QUARANTINED); - return operation; - } - - private static void expectIndeterminateWithoutProducerOrFileId( - LocalPersistentPublicationTestFixture fixture) { - AtomicInteger producerCalls = new AtomicInteger(); - AtomicInteger fileIdCalls = new AtomicInteger(); - assertThatThrownBy( - () -> - fixture - .provider( - fixture.controlPlane(), - fixture.payload(), - () -> { - fileIdCalls.incrementAndGet(); - return "f".repeat(32); - }) - .publish(fixture.request("source-42"), sink -> producerCalls.incrementAndGet())) - .isInstanceOfSatisfying( - FilePublicationException.class, - exception -> - assertThat(exception.reason()) - .isEqualTo(FilePublicationException.Reason.PUBLISH_INDETERMINATE)); - assertThat(producerCalls).hasValue(0); - assertThat(fileIdCalls).hasValue(0); - } - - private static void prepareAtState( - PublishedBaseline baseline, DurablePublicationRecord.State state) throws IOException { - switch (state) { - case SEALED, DATA_PUBLISHED -> { - removeControlRecord(baseline.referencePath()); - removeControlRecord(baseline.manifestPath()); - } - case MANIFEST_PUBLISHED -> removeControlRecord(baseline.referencePath()); - case REFERENCE_PUBLISHED -> { - // Both immutable metadata records remain authority for this state. - } - default -> throw new IllegalArgumentException("unsupported non-terminal fixture state"); - } - rewriteOperation(baseline.operationPath(), atState(baseline.operation(), state)); - } - - private static DurablePublicationRecord atState( - DurablePublicationRecord terminal, DurablePublicationRecord.State state) { - if (state == DurablePublicationRecord.State.WRITING - || state == DurablePublicationRecord.State.PUBLISHED - || state == DurablePublicationRecord.State.QUARANTINED) { - throw new IllegalArgumentException("fixture supports only sealed non-terminal states"); - } - boolean hasManifest = - state == DurablePublicationRecord.State.MANIFEST_PUBLISHED - || state == DurablePublicationRecord.State.REFERENCE_PUBLISHED; - boolean hasReference = state == DurablePublicationRecord.State.REFERENCE_PUBLISHED; - return new DurablePublicationRecord( - DurablePublicationRecord.CURRENT_SCHEMA_VERSION, - state.minimumRevision(), - state, - terminal.operationId(), - terminal.requestFingerprint(), - terminal.effectivePolicyRevision(), - terminal.effectivePolicyDigest(), - terminal.destinationId(), - terminal.providerId(), - terminal.fileId(), - terminal.routeToken(), - terminal.publishedFileName(), - terminal.stageFileName(), - terminal.byteSize(), - terminal.rowCount(), - terminal.columnCount(), - terminal.sha256(), - terminal.formulaMitigatedCount(), - hasManifest ? terminal.manifestDigest() : "", - hasReference ? terminal.referenceDigest() : "", - terminal.createdAt(), - terminal.sealedAt(), - null, - "", - ""); - } - - private static DurablePublicationRecord writingRecord( - LocalPersistentPublicationTestFixture fixture) { - return new DurablePublicationRecord( - DurablePublicationRecord.CURRENT_SCHEMA_VERSION, - DurablePublicationRecord.State.WRITING.minimumRevision(), - DurablePublicationRecord.State.WRITING, - fixture.operationId(), - FilePublishRequestFingerprint.calculate(fixture.request("source-42")), - fixture.destination().effectivePolicyRevision(), - fixture.destination().effectivePolicyDigest(), - fixture.destination().destinationId().value(), - fixture.destination().providerId(), - fixture.fileId(), - fixture.destination().routeToken(), - LocalPersistentRecoveryVerifier.generatedFileName(fixture.fileId()), - LocalPersistentPayloadOperations.stageFileName(fixture.operationId()), - 0, - 0, - 0, - "", - 0, - "", - "", - LocalPersistentPublicationTestFixture.PUBLISHED_AT, - null, - null, - "", - ""); - } - - private static DurablePublicationRecord unsealedQuarantined( - DurablePublicationRecord writing, String failureCode) { - return new DurablePublicationRecord( - writing.schemaVersion(), - writing.stateRevision() + 1, - DurablePublicationRecord.State.QUARANTINED, - writing.operationId(), - writing.requestFingerprint(), - writing.effectivePolicyRevision(), - writing.effectivePolicyDigest(), - writing.destinationId(), - writing.providerId(), - writing.fileId(), - writing.routeToken(), - writing.publishedFileName(), - writing.stageFileName(), - 0, - 0, - 0, - "", - 0, - "", - "", - writing.createdAt(), - null, - null, - failureCode, - ""); - } - - private static DurablePublicationRecord publishedWithReceipt( - DurablePublicationRecord published, String receiptSnapshot) { - return new DurablePublicationRecord( - published.schemaVersion(), - published.stateRevision(), - published.state(), - published.operationId(), - published.requestFingerprint(), - published.effectivePolicyRevision(), - published.effectivePolicyDigest(), - published.destinationId(), - published.providerId(), - published.fileId(), - published.routeToken(), - published.publishedFileName(), - published.stageFileName(), - published.byteSize(), - published.rowCount(), - published.columnCount(), - published.sha256(), - published.formulaMitigatedCount(), - published.manifestDigest(), - published.referenceDigest(), - published.createdAt(), - published.sealedAt(), - published.publishedAt(), - published.lastFailureCode(), - receiptSnapshot); - } - - private static FilePublishReceipt receiptWithFormat( - FilePublishReceipt receipt, String formatProfileId) { - return new FilePublishReceipt( - receipt.operationId(), - receipt.reference(), - receipt.destinationId(), - receipt.publishedFileName(), - receipt.version(), - formatProfileId, - receipt.mediaType(), - receipt.charset(), - receipt.byteSize(), - receipt.dataRowCount(), - receipt.columnCount(), - receipt.sha256(), - receipt.publishedAt(), - receipt.publicationGuarantee(), - receipt.durabilityGuarantee(), - receipt.formulaMitigatedCount()); - } - - private static PrivateFileManifest manifestWithSchemaId( - PrivateFileManifest manifest, String schemaId) { - return new PrivateFileManifest( - manifest.schemaVersion(), - manifest.operationId(), - manifest.fileId(), - manifest.providerId(), - manifest.fileReference(), - manifest.requestFingerprint(), - manifest.destinationId(), - schemaId, - manifest.exportSchemaVersion(), - manifest.schemaDigest(), - manifest.formatProfileId(), - manifest.formatPolicyDigest(), - manifest.effectivePolicyRevision(), - manifest.effectivePolicyDigest(), - manifest.publishedFileName(), - manifest.fileVersion(), - manifest.mediaType(), - manifest.charset(), - manifest.byteSize(), - manifest.rowCount(), - manifest.columnCount(), - manifest.sha256(), - manifest.formulaMitigatedCount(), - manifest.publicationGuarantee(), - manifest.durabilityGuarantee(), - manifest.internalLocator(), - manifest.createdAt(), - manifest.publishedAt()); - } - - private static PublishedReferenceRecord referenceWithMediaType( - PublishedReferenceRecord reference, String mediaType) { - return new PublishedReferenceRecord( - reference.schemaVersion(), - reference.fileId(), - reference.routeToken(), - reference.fileReference(), - reference.operationId(), - reference.fileVersion(), - reference.manifestDigest(), - reference.internalLocator(), - reference.destinationId(), - reference.providerId(), - reference.publishedFileName(), - mediaType, - reference.charset(), - reference.byteSize(), - reference.sha256(), - reference.publishedAt()); - } - - private static Path stagePath( - LocalPersistentPublicationTestFixture fixture, DurablePublicationRecord operation) { - String operationDigest = - LocalPersistentPublicationTestFixture.sha256(fixture.operationId().getBytes(UTF_8)); - return fixture - .root() - .resolve(".ca-fileserver/staging") - .resolve(operationDigest.substring(0, 2)) - .resolve(operation.stageFileName()); - } - - private static Path operationPath(Path root, String operationId) { - String digest = LocalPersistentPublicationTestFixture.sha256(operationId.getBytes(UTF_8)); - return root.resolve(".ca-fileserver/operations") - .resolve(digest.substring(0, 2)) - .resolve(digest + ".json"); - } - - private static Path fileRecordPath(Path root, String kind, String fileId) { - return root.resolve(".ca-fileserver") - .resolve(kind) - .resolve(fileId.substring(0, 2)) - .resolve(fileId + ".json"); - } - - private static void rewriteOperation(Path target, DurablePublicationRecord record) - throws IOException { - rewriteRecord(target, new FileserverControlRecordCodec().encodeOperation(record)); - } - - private static void rewriteRecord(Path target, byte[] canonicalRecord) throws IOException { - Files.write( - target, canonicalRecord, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING); - forceFile(target); - forceDirectory(target.getParent()); - } - - private static void removeControlRecord(Path target) throws IOException { - Files.delete(target); - forceDirectory(target.getParent()); - } - - private static void forceFile(Path file) throws IOException { - try (FileChannel channel = FileChannel.open(file, StandardOpenOption.WRITE)) { - channel.force(true); - } - } - - private static void forceDirectory(Path directory) throws IOException { - try (FileChannel channel = FileChannel.open(directory, StandardOpenOption.READ)) { - channel.force(true); - } - } - - private static long countRegularFiles(Path directory) throws IOException { - try (var paths = Files.walk(directory)) { - return paths.filter(Files::isRegularFile).count(); - } - } - - private static String operationToken(String operationId) { - return LocalPersistentPublicationTestFixture.sha256(operationId.getBytes(UTF_8)) - .substring(0, 24); - } - - private static final class PublishedBaseline { - - private final FilePublishReceipt receipt; - private final DurablePublicationRecord operation; - private final byte[] payload; - private final Path operationPath; - private final Path manifestPath; - private final Path referencePath; - private final Path dataPath; - - private PublishedBaseline( - FilePublishReceipt receipt, - DurablePublicationRecord operation, - byte[] payload, - Path operationPath, - Path manifestPath, - Path referencePath, - Path dataPath) { - this.receipt = receipt; - this.operation = operation; - this.payload = payload.clone(); - this.operationPath = operationPath; - this.manifestPath = manifestPath; - this.referencePath = referencePath; - this.dataPath = dataPath; - } - - private FilePublishReceipt receipt() { - return receipt; - } - - private DurablePublicationRecord operation() { - return operation; - } - - private byte[] payload() { - return payload.clone(); - } - - private Path operationPath() { - return operationPath; - } - - private Path manifestPath() { - return manifestPath; - } - - private Path referencePath() { - return referencePath; - } - - private Path dataPath() { - return dataPath; - } - } - - private static final class R1Baseline { - - private final Path artifact; - private final byte[] payload; - private final Path operationPath; - - private R1Baseline(Path artifact, byte[] payload, Path operationPath) { - this.artifact = artifact; - this.payload = payload.clone(); - this.operationPath = operationPath; - } - - private Path artifact() { - return artifact; - } - - private byte[] payload() { - return payload.clone(); - } - - private Path operationPath() { - return operationPath; - } - } -} diff --git a/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/LocalPersistentRootAttestorTest.java b/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/LocalPersistentRootAttestorTest.java deleted file mode 100644 index a2c215e2..00000000 --- a/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/LocalPersistentRootAttestorTest.java +++ /dev/null @@ -1,769 +0,0 @@ -package dev.caskeleton.adapter.outbound.fileserver; - -import static java.nio.charset.StandardCharsets.UTF_8; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.assertj.core.api.Assertions.catchThrowable; - -import dev.caskeleton.application.filepublication.FileDestinationId; -import dev.caskeleton.application.filepublication.FilePublishReceipt.DurabilityGuarantee; -import dev.caskeleton.application.filepublication.FilePublishReceipt.PublicationGuarantee; -import java.io.IOException; -import java.nio.channels.FileChannel; -import java.nio.file.FileStore; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.SecureDirectoryStream; -import java.nio.file.attribute.PosixFileAttributes; -import java.nio.file.attribute.PosixFilePermission; -import java.nio.file.attribute.PosixFilePermissions; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.HashSet; -import java.util.Set; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.condition.EnabledOnOs; -import org.junit.jupiter.api.condition.OS; -import org.junit.jupiter.api.io.TempDir; - -@EnabledOnOs(OS.LINUX) -class LocalPersistentRootAttestorTest { - - private static final String SENTINEL_NAME = ".ca-fileserver-volume"; - private static final byte[] SENTINEL_CONTENT = "fileserver-r2-test-volume\n".getBytes(UTF_8); - private static final Set INTERNAL_DIRECTORIES = - Set.of( - ".ca-fileserver", - "data", - ".ca-fileserver/staging", - ".ca-fileserver/operations", - ".ca-fileserver/manifests", - ".ca-fileserver/references", - ".ca-fileserver/quarantine", - ".ca-fileserver/probe"); - - @TempDir Path tempDirectory; - - @Test - void attestsOwnerModeStoreSentinelSecureDirectoryAndSyncPrimitives() throws IOException { - RootFixture fixture = attestedRoot("successful-root"); - PosixFileAttributes rootAttributes = - Files.readAttributes(fixture.root(), PosixFileAttributes.class); - - LocalPersistentRootEvidence evidence = - new LocalPersistentRootAttestor().attest(destinationFor(fixture)); - - assertThat(evidence.root()).isEqualTo(fixture.root().toRealPath()); - assertThat(evidence.rootFileKey()).isEqualTo(rootAttributes.fileKey().toString()); - assertThat(evidence.fileStoreName()).isEqualTo(fixture.fileStoreName()); - assertThat(evidence.fileStoreType()).isEqualTo(fixture.fileStoreType()); - assertThat(evidence.mountSentinelSha256()).isEqualTo(fixture.sentinelSha256()); - assertThat(evidence.secureDirectoryStream()).isTrue(); - assertThat(evidence.directorySync()).isTrue(); - assertThat(evidence.exclusiveHardLink()).isTrue(); - assertThat(evidence.criticalDirectoryFileKeys()).containsOnlyKeys(INTERNAL_DIRECTORIES); - assertThat(fixture.root().resolve(".ca-fileserver").resolve("data")).doesNotExist(); - - for (String relativeDirectory : INTERNAL_DIRECTORIES) { - Path directory = fixture.root().resolve(relativeDirectory); - assertThat(directory).isDirectory(); - assertThat(Files.getPosixFilePermissions(directory)) - .containsExactlyInAnyOrderElementsOf(PosixFilePermissions.fromString("rwx------")); - } - try (var probeArtifacts = - Files.list(fixture.root().resolve(".ca-fileserver").resolve("probe"))) { - assertThat(probeArtifacts).isEmpty(); - } - assertThatCode(() -> new LocalPersistentRootAttestor().verifyIdentity(evidence)) - .doesNotThrowAnyException(); - } - - @Test - void evidenceDefensivelyCopiesIdentitiesAndMaximumRootPermissions() throws IOException { - RootFixture fixture = attestedRoot("immutable-evidence"); - LocalPersistentRootEvidence evidence = - new LocalPersistentRootAttestor().attest(destinationFor(fixture)); - - assertThat(evidence.expectedOwner()).isEqualTo(fixture.owner()); - assertThat(evidence.maximumRootPermissions()) - .containsExactlyInAnyOrderElementsOf(fixture.maximumPermissions()); - assertThatThrownBy(() -> evidence.criticalDirectoryFileKeys().put("mutable", "identity")) - .isInstanceOf(UnsupportedOperationException.class); - assertThatThrownBy(() -> evidence.maximumRootPermissions().add(PosixFilePermission.GROUP_WRITE)) - .isInstanceOf(UnsupportedOperationException.class); - } - - @Test - void rejectsMissingRoot() throws IOException { - RootFixture fixture = attestedRoot("missing-root-reference"); - Path missingRoot = tempDirectory.resolve("missing-root").toAbsolutePath().normalize(); - - assertAttestationFailure(destinationFor(fixture, missingRoot)) - .hasMessageContaining("root") - .hasMessageContaining("exist"); - assertThat(missingRoot.resolve(".ca-fileserver")).doesNotExist(); - } - - @Test - void rejectsRelativeRootBeforeAttestation() throws IOException { - RootFixture fixture = attestedRoot("relative-root-reference"); - - assertThatThrownBy(() -> destinationFor(fixture, Path.of("relative/root"))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("absolute"); - } - - @Test - void rejectsNonNormalizedRootBeforeAttestation() throws IOException { - RootFixture fixture = attestedRoot("non-normalized-root-reference"); - Path nonNormalized = - tempDirectory.resolve("unused").resolve("..").resolve("non-normalized-root"); - - assertThat(nonNormalized).isNotEqualTo(nonNormalized.normalize()); - assertThatThrownBy(() -> destinationFor(fixture, nonNormalized)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("normalized"); - } - - @Test - void rejectsSymbolicLinkRoot() throws IOException { - RootFixture fixture = attestedRoot("real-root"); - Path symbolicRoot = tempDirectory.resolve("symbolic-root").toAbsolutePath().normalize(); - Files.createSymbolicLink(symbolicRoot, fixture.root()); - - assertAttestationFailure(destinationFor(fixture, symbolicRoot)) - .hasMessageContaining("symbolic link"); - assertThat(fixture.root().resolve(".ca-fileserver")).doesNotExist(); - } - - @Test - void rejectsSymbolicLinkInAnyExistingRootAncestor() throws IOException { - Path realParent = tempDirectory.resolve("real-parent"); - Files.createDirectory(realParent); - Path root = realParent.resolve("root"); - Files.createDirectory(root, PosixFilePermissions.asFileAttribute(ownerOnlyDirectoryMode())); - createSentinel(root); - RootFixture fixture = fixtureFor(root); - Path symbolicParent = tempDirectory.resolve("symbolic-parent"); - Files.createSymbolicLink(symbolicParent, realParent); - Path configuredRoot = symbolicParent.resolve("root").toAbsolutePath().normalize(); - - assertAttestationFailure(destinationFor(fixture, configuredRoot)) - .hasMessageContaining("symbolic link") - .hasMessageContaining("ancestor"); - assertThat(root.resolve(".ca-fileserver")).doesNotExist(); - } - - @Test - void rejectsOwnerMismatchBeforeCreatingInternalArtifacts() throws IOException { - RootFixture fixture = attestedRoot("owner-mismatch"); - CompiledFileDestination destination = - destinationFor( - fixture.root(), - "definitely-not-" + fixture.owner(), - fixture.maximumPermissions(), - fixture.fileStoreName(), - fixture.fileStoreType(), - fixture.sentinelSha256()); - - assertAttestationFailure(destination).hasMessageContaining("owner"); - assertThat(fixture.root().resolve(".ca-fileserver")).doesNotExist(); - } - - @Test - void rejectsGroupOrWorldWritableRootEvenWhenConfiguredModeWasPreviouslyValid() - throws IOException { - RootFixture fixture = attestedRoot("group-writable"); - CompiledFileDestination destination = destinationFor(fixture); - Set writable = new HashSet<>(fixture.maximumPermissions()); - writable.add(PosixFilePermission.GROUP_WRITE); - Files.setPosixFilePermissions(fixture.root(), writable); - - assertAttestationFailure(destination).hasMessageContaining("group/world writable"); - assertThat(fixture.root().resolve(".ca-fileserver")).doesNotExist(); - } - - @Test - void rejectsRootPermissionsBroaderThanConfiguredMaximum() throws IOException { - RootFixture fixture = attestedRoot("broader-mode"); - Set actualPermissions = PosixFilePermissions.fromString("rwxr-x---"); - Files.setPosixFilePermissions(fixture.root(), actualPermissions); - CompiledFileDestination destination = - destinationFor( - fixture.root(), - fixture.owner(), - ownerOnlyDirectoryMode(), - fixture.fileStoreName(), - fixture.fileStoreType(), - fixture.sentinelSha256()); - - assertAttestationFailure(destination).hasMessageContaining("maximum"); - assertThat(fixture.root().resolve(".ca-fileserver")).doesNotExist(); - } - - @Test - void rejectsFileStoreNameMismatchBeforeCreatingInternalArtifacts() throws IOException { - RootFixture fixture = attestedRoot("store-name-mismatch"); - CompiledFileDestination destination = - destinationFor( - fixture.root(), - fixture.owner(), - fixture.maximumPermissions(), - fixture.fileStoreName() + "-different", - fixture.fileStoreType(), - fixture.sentinelSha256()); - - assertAttestationFailure(destination).hasMessageContaining("FileStore name"); - assertThat(fixture.root().resolve(".ca-fileserver")).doesNotExist(); - } - - @Test - void rejectsFileStoreTypeMismatchBeforeCreatingInternalArtifacts() throws IOException { - RootFixture fixture = attestedRoot("store-type-mismatch"); - CompiledFileDestination destination = - destinationFor( - fixture.root(), - fixture.owner(), - fixture.maximumPermissions(), - fixture.fileStoreName(), - fixture.fileStoreType() + "-different", - fixture.sentinelSha256()); - - assertAttestationFailure(destination).hasMessageContaining("FileStore type"); - assertThat(fixture.root().resolve(".ca-fileserver")).doesNotExist(); - } - - @Test - void rejectsMissingMountSentinelBeforeCreatingInternalArtifacts() throws IOException { - RootFixture fixture = attestedRoot("missing-sentinel"); - Files.delete(fixture.root().resolve(SENTINEL_NAME)); - - assertAttestationFailure(destinationFor(fixture)).hasMessageContaining("sentinel"); - assertThat(fixture.root().resolve(".ca-fileserver")).doesNotExist(); - } - - @Test - void rejectsSymbolicLinkMountSentinelBeforeCreatingInternalArtifacts() throws IOException { - RootFixture fixture = attestedRoot("symbolic-sentinel"); - Path sentinel = fixture.root().resolve(SENTINEL_NAME); - Files.delete(sentinel); - Path target = tempDirectory.resolve("sentinel-target"); - Files.write(target, SENTINEL_CONTENT); - Files.createSymbolicLink(sentinel, target); - - assertAttestationFailure(destinationFor(fixture)) - .hasMessageContaining("sentinel") - .hasMessageContaining("symbolic link"); - assertThat(fixture.root().resolve(".ca-fileserver")).doesNotExist(); - } - - @Test - void rejectsNonRegularMountSentinelBeforeCreatingInternalArtifacts() throws IOException { - RootFixture fixture = attestedRoot("non-regular-sentinel"); - Path sentinel = fixture.root().resolve(SENTINEL_NAME); - Files.delete(sentinel); - Files.createDirectory(sentinel); - - assertAttestationFailure(destinationFor(fixture)) - .hasMessageContaining("sentinel") - .hasMessageContaining("regular"); - assertThat(fixture.root().resolve(".ca-fileserver")).doesNotExist(); - } - - @Test - void rejectsMountSentinelDigestMismatchBeforeCreatingInternalArtifacts() throws IOException { - RootFixture fixture = attestedRoot("digest-mismatch"); - Files.writeString(fixture.root().resolve(SENTINEL_NAME), "different-volume\n"); - - assertAttestationFailure(destinationFor(fixture)).hasMessageContaining("SHA-256"); - assertThat(fixture.root().resolve(".ca-fileserver")).doesNotExist(); - } - - @Test - void rejectsExistingRootLevelDataDirectorySymbolicLink() throws IOException { - RootFixture fixture = attestedRoot("internal-symbolic-link"); - Path control = fixture.root().resolve(".ca-fileserver"); - Files.createDirectory(control, PosixFilePermissions.asFileAttribute(ownerOnlyDirectoryMode())); - for (String name : - new String[] {"staging", "operations", "manifests", "references", "quarantine", "probe"}) { - Files.createDirectory( - control.resolve(name), PosixFilePermissions.asFileAttribute(ownerOnlyDirectoryMode())); - } - Path externalData = tempDirectory.resolve("external-data"); - Files.createDirectory(externalData); - Files.createSymbolicLink(fixture.root().resolve("data"), externalData); - - assertAttestationFailure(destinationFor(fixture)) - .hasMessageContaining("data") - .hasMessageContaining("symbolic link"); - } - - @Test - void rejectsExistingControlChildBeforeCreatingRootLevelData() throws IOException { - RootFixture fixture = attestedRoot("existing-control-child-symbolic-link"); - Path control = fixture.root().resolve(".ca-fileserver"); - Files.createDirectory(control, PosixFilePermissions.asFileAttribute(ownerOnlyDirectoryMode())); - Path externalStaging = tempDirectory.resolve("external-staging"); - Files.createDirectory(externalStaging); - Files.createSymbolicLink(control.resolve("staging"), externalStaging); - - assertAttestationFailure(destinationFor(fixture)) - .hasMessageContaining("staging") - .hasMessageContaining("symbolic link"); - assertThat(fixture.root().resolve("data")).doesNotExist(); - assertThat(control).isDirectory(); - assertThat(control.resolve("staging")).isSymbolicLink(); - } - - @Test - void removesNewHierarchyAfterInternalDirectoryFileStoreMismatch() throws IOException { - RootFixture fixture = attestedRoot("internal-store-mismatch"); - LocalPersistentRootAttestor.FileStoreProbe systemProbe = - LocalPersistentRootAttestor.systemFileStoreProbe(); - LocalPersistentRootAttestor.FileStoreProbe mismatchingProbe = - path -> { - LocalPersistentRootAttestor.FileStoreIdentity actual = systemProbe.inspect(path); - if (path.endsWith("staging")) { - return new LocalPersistentRootAttestor.FileStoreIdentity( - actual.name() + "-different", actual.type(), actual.identity() + "-different"); - } - return actual; - }; - - LocalPersistentRootAttestor attestor = - new LocalPersistentRootAttestor( - LocalPersistentRootAttestor.systemCapabilityOperations(), mismatchingProbe); - - assertAttestationFailure(attestor, destinationFor(fixture)) - .hasMessageContaining("staging") - .hasMessageContaining("FileStore"); - assertThat(fixture.root().resolve("data")).doesNotExist(); - assertThat(fixture.root().resolve(".ca-fileserver")).doesNotExist(); - } - - @Test - void preservesPreexistingRootLevelDataAfterFileStoreMismatch() throws IOException { - RootFixture fixture = attestedRoot("preexisting-data-store-mismatch"); - Path data = fixture.root().resolve("data"); - Files.createDirectory(data, PosixFilePermissions.asFileAttribute(ownerOnlyDirectoryMode())); - LocalPersistentRootAttestor.FileStoreProbe systemProbe = - LocalPersistentRootAttestor.systemFileStoreProbe(); - LocalPersistentRootAttestor.FileStoreProbe mismatchingProbe = - path -> { - LocalPersistentRootAttestor.FileStoreIdentity actual = systemProbe.inspect(path); - if (path.equals(data)) { - return new LocalPersistentRootAttestor.FileStoreIdentity( - actual.name() + "-different", actual.type(), actual.identity() + "-different"); - } - return actual; - }; - LocalPersistentRootAttestor attestor = - new LocalPersistentRootAttestor( - LocalPersistentRootAttestor.systemCapabilityOperations(), mismatchingProbe); - - assertAttestationFailure(attestor, destinationFor(fixture)) - .hasMessageContaining("data") - .hasMessageContaining("FileStore"); - assertThat(data).isDirectory(); - assertThat(fixture.root().resolve(".ca-fileserver")).doesNotExist(); - } - - @Test - void rollbackNeverDeletesAReplacementAtACreatedDirectoryPath() throws IOException { - RootFixture fixture = attestedRoot("rollback-replacement"); - Path control = fixture.root().resolve(".ca-fileserver"); - Path staging = control.resolve("staging"); - Path movedCreatedStaging = control.resolve("attestor-created-staging"); - AtomicBoolean replaced = new AtomicBoolean(); - LocalPersistentRootAttestor.FileStoreProbe systemProbe = - LocalPersistentRootAttestor.systemFileStoreProbe(); - LocalPersistentRootAttestor.FileStoreProbe replacingMismatchingProbe = - path -> { - LocalPersistentRootAttestor.FileStoreIdentity actual = systemProbe.inspect(path); - if (path.equals(staging) && replaced.compareAndSet(false, true)) { - Files.move(staging, movedCreatedStaging); - Files.createDirectory( - staging, PosixFilePermissions.asFileAttribute(ownerOnlyDirectoryMode())); - actual = systemProbe.inspect(staging); - return new LocalPersistentRootAttestor.FileStoreIdentity( - actual.name() + "-different", actual.type(), actual.identity() + "-different"); - } - return actual; - }; - LocalPersistentRootAttestor attestor = - new LocalPersistentRootAttestor( - LocalPersistentRootAttestor.systemCapabilityOperations(), replacingMismatchingProbe); - - assertAttestationFailure(attestor, destinationFor(fixture)) - .hasMessageContaining("staging") - .hasMessageContaining("FileStore"); - assertThat(replaced).isTrue(); - assertThat(staging).isDirectory(); - assertThat(movedCreatedStaging).isDirectory(); - } - - @Test - void rejectsParentIdentityChangeAcrossRootLevelDataCreationAndRollsBack() throws IOException { - RootFixture fixture = attestedRoot("parent-identity-race"); - LocalPersistentRootAttestor.ParentIdentityProbe systemProbe = - LocalPersistentRootAttestor.systemParentIdentityProbe(); - AtomicInteger rootInspections = new AtomicInteger(); - LocalPersistentRootAttestor.ParentIdentityProbe changingProbe = - parent -> { - String identity = systemProbe.inspect(parent); - if (parent.equals(fixture.root()) && rootInspections.incrementAndGet() == 3) { - return identity + "-replaced"; - } - return identity; - }; - LocalPersistentRootAttestor attestor = - new LocalPersistentRootAttestor( - LocalPersistentRootAttestor.systemCapabilityOperations(), - LocalPersistentRootAttestor.systemFileStoreProbe(), - changingProbe); - - assertAttestationFailure(attestor, destinationFor(fixture)) - .hasMessageContaining("parent") - .hasMessageContaining("identity"); - assertThat(fixture.root().resolve("data")).doesNotExist(); - assertThat(fixture.root().resolve(".ca-fileserver")).doesNotExist(); - } - - @Test - void rejectsUnavailableSecureDirectoryStreamWithoutDowngrade() throws IOException { - RootFixture fixture = attestedRoot("secure-directory-unavailable"); - LocalPersistentRootAttestor.CapabilityOperations capabilities = - new DelegatingCapabilities() { - @Override - public SecureDirectoryStream openSecureDirectory(Path directory) - throws IOException { - throw new IOException("SecureDirectoryStream unavailable"); - } - }; - - assertAttestationFailure( - new LocalPersistentRootAttestor( - capabilities, LocalPersistentRootAttestor.systemFileStoreProbe()), - destinationFor(fixture)) - .hasMessageContaining("SecureDirectoryStream"); - } - - @Test - void rejectsUnavailableExclusiveHardLinkWithoutDowngrade() throws IOException { - RootFixture fixture = attestedRoot("hard-link-unavailable"); - LocalPersistentRootAttestor.CapabilityOperations capabilities = - new DelegatingCapabilities() { - @Override - public void createHardLink(Path link, Path existing) throws IOException { - throw new IOException("exclusive hard-link unavailable"); - } - }; - - assertAttestationFailure( - new LocalPersistentRootAttestor( - capabilities, LocalPersistentRootAttestor.systemFileStoreProbe()), - destinationFor(fixture)) - .hasMessageContaining("hard-link"); - } - - @Test - void preservesPrimaryHardLinkFailureWhenCleanupForceThrowsRuntimeException() throws IOException { - RootFixture fixture = attestedRoot("hard-link-cleanup-runtime"); - AtomicBoolean cleanupForceAttempted = new AtomicBoolean(); - LocalPersistentRootAttestor.CapabilityOperations capabilities = - new DelegatingCapabilities() { - @Override - public void createHardLink(Path link, Path existing) throws IOException { - throw new IOException("primary hard-link failure"); - } - - @Override - public void forceDirectory(Path directory) throws IOException { - if (directory.endsWith("probe")) { - cleanupForceAttempted.set(true); - throw new IllegalStateException("cleanup force runtime failure"); - } - super.forceDirectory(directory); - } - }; - LocalPersistentRootAttestor attestor = - new LocalPersistentRootAttestor( - capabilities, LocalPersistentRootAttestor.systemFileStoreProbe()); - - Throwable failure = catchThrowable(() -> attestor.attest(destinationFor(fixture))); - - assertThat(failure) - .isInstanceOf(LocalPersistentRootAttestor.LocalPersistentRootAttestationException.class) - .hasMessageContaining("primary hard-link failure"); - assertThat(failure.getCause()) - .isInstanceOf(IOException.class) - .hasMessageContaining("primary hard-link failure"); - assertThat(failure.getCause().getSuppressed()) - .singleElement() - .satisfies( - cleanupFailure -> - assertThat(cleanupFailure) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("cleanup force runtime failure")); - assertThat(cleanupForceAttempted).isTrue(); - } - - @Test - void rejectsUnavailableDirectoryForceWithoutDowngrade() throws IOException { - RootFixture fixture = attestedRoot("directory-force-unavailable"); - AtomicBoolean probeDirectoryForceAttempted = new AtomicBoolean(); - LocalPersistentRootAttestor.CapabilityOperations capabilities = - new DelegatingCapabilities() { - @Override - public void forceDirectory(Path directory) throws IOException { - if (directory.endsWith("probe")) { - probeDirectoryForceAttempted.set(true); - throw new IOException("probe directory force unavailable"); - } - super.forceDirectory(directory); - } - }; - - assertAttestationFailure( - new LocalPersistentRootAttestor( - capabilities, LocalPersistentRootAttestor.systemFileStoreProbe()), - destinationFor(fixture)) - .hasMessageContaining("directory force"); - assertThat(probeDirectoryForceAttempted).isTrue(); - try (var probeArtifacts = - Files.list(fixture.root().resolve(".ca-fileserver").resolve("probe"))) { - assertThat(probeArtifacts).isEmpty(); - } - } - - @Test - void rejectsUnavailableFileForceWithoutDowngrade() throws IOException { - RootFixture fixture = attestedRoot("file-force-unavailable"); - AtomicBoolean fileForceAttempted = new AtomicBoolean(); - LocalPersistentRootAttestor.CapabilityOperations capabilities = - new DelegatingCapabilities() { - @Override - public void forceFile(FileChannel channel) throws IOException { - fileForceAttempted.set(true); - throw new IOException("file force unavailable"); - } - }; - - assertAttestationFailure( - new LocalPersistentRootAttestor( - capabilities, LocalPersistentRootAttestor.systemFileStoreProbe()), - destinationFor(fixture)) - .hasMessageContaining("file force"); - assertThat(fileForceAttempted).isTrue(); - try (var probeArtifacts = - Files.list(fixture.root().resolve(".ca-fileserver").resolve("probe"))) { - assertThat(probeArtifacts).isEmpty(); - } - } - - @Test - void verifyIdentityRejectsChangedMountSentinel() throws IOException { - RootFixture fixture = attestedRoot("verify-sentinel"); - LocalPersistentRootAttestor attestor = new LocalPersistentRootAttestor(); - LocalPersistentRootEvidence evidence = attestor.attest(destinationFor(fixture)); - Files.writeString(fixture.root().resolve(SENTINEL_NAME), "changed-volume\n"); - - assertThatThrownBy(() -> attestor.verifyIdentity(evidence)) - .isInstanceOf(LocalPersistentRootAttestor.LocalPersistentRootAttestationException.class) - .hasMessageContaining("sentinel"); - } - - @Test - void verifyIdentityRejectsRootModeDriftOnTheSameInode() throws IOException { - RootFixture fixture = attestedRoot("verify-root-mode"); - LocalPersistentRootAttestor attestor = new LocalPersistentRootAttestor(); - LocalPersistentRootEvidence evidence = attestor.attest(destinationFor(fixture)); - String originalFileKey = - Files.readAttributes(fixture.root(), PosixFileAttributes.class).fileKey().toString(); - Set driftedPermissions = - new HashSet<>(Files.getPosixFilePermissions(fixture.root())); - driftedPermissions.add(PosixFilePermission.GROUP_WRITE); - Files.setPosixFilePermissions(fixture.root(), driftedPermissions); - - assertThat(Files.readAttributes(fixture.root(), PosixFileAttributes.class).fileKey().toString()) - .isEqualTo(originalFileKey); - assertThatThrownBy(() -> attestor.verifyIdentity(evidence)) - .isInstanceOf(LocalPersistentRootAttestor.LocalPersistentRootAttestationException.class) - .hasMessageContaining("group/world writable"); - } - - @Test - void verifyIdentityRejectsReplacedCriticalInternalDirectory() throws IOException { - RootFixture fixture = attestedRoot("verify-internal-directory"); - LocalPersistentRootAttestor attestor = new LocalPersistentRootAttestor(); - LocalPersistentRootEvidence evidence = attestor.attest(destinationFor(fixture)); - Path data = fixture.root().resolve("data"); - assertThat(data).isDirectory(); - Files.move(data, data.resolveSibling("original-data")); - Files.createDirectory(data, PosixFilePermissions.asFileAttribute(ownerOnlyDirectoryMode())); - - assertThatThrownBy(() -> attestor.verifyIdentity(evidence)) - .isInstanceOf(LocalPersistentRootAttestor.LocalPersistentRootAttestationException.class) - .hasMessageContaining("data") - .hasMessageContaining("identity"); - } - - @Test - void verifyIdentityRejectsReplacedRoot() throws IOException { - RootFixture fixture = attestedRoot("verify-root"); - LocalPersistentRootAttestor attestor = new LocalPersistentRootAttestor(); - LocalPersistentRootEvidence evidence = attestor.attest(destinationFor(fixture)); - Path movedRoot = fixture.root().resolveSibling("original-root"); - Files.move(fixture.root(), movedRoot); - Files.createDirectory( - fixture.root(), PosixFilePermissions.asFileAttribute(ownerOnlyDirectoryMode())); - createSentinel(fixture.root()); - - assertThatThrownBy(() -> attestor.verifyIdentity(evidence)) - .isInstanceOf(LocalPersistentRootAttestor.LocalPersistentRootAttestationException.class) - .hasMessageContaining("root") - .hasMessageContaining("identity"); - } - - private RootFixture attestedRoot(String name) throws IOException { - Path root = tempDirectory.resolve(name).toAbsolutePath().normalize(); - Files.createDirectory(root, PosixFilePermissions.asFileAttribute(ownerOnlyDirectoryMode())); - createSentinel(root); - return fixtureFor(root); - } - - private static void createSentinel(Path root) throws IOException { - Path sentinel = root.resolve(SENTINEL_NAME); - Files.createFile( - sentinel, - PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-------"))); - Files.write(sentinel, SENTINEL_CONTENT); - } - - private static RootFixture fixtureFor(Path root) throws IOException { - PosixFileAttributes attributes = Files.readAttributes(root, PosixFileAttributes.class); - FileStore store = Files.getFileStore(root); - return new RootFixture( - root, - attributes.owner().getName(), - Set.copyOf(attributes.permissions()), - store.name(), - store.type(), - sha256(root.resolve(SENTINEL_NAME))); - } - - private static CompiledFileDestination destinationFor(RootFixture fixture) { - return destinationFor(fixture, fixture.root()); - } - - private static CompiledFileDestination destinationFor(RootFixture fixture, Path root) { - return destinationFor( - root, - fixture.owner(), - fixture.maximumPermissions(), - fixture.fileStoreName(), - fixture.fileStoreType(), - fixture.sentinelSha256()); - } - - private static CompiledFileDestination destinationFor( - Path root, - String expectedOwner, - Set maximumPermissions, - String expectedFileStoreName, - String expectedFileStoreType, - String expectedSentinelSha256) { - return new CompiledFileDestination( - new FileDestinationId("local-export"), - "local-primary", - root, - 1_000, - 1_048_576, - expectedFileStoreName, - expectedFileStoreType, - SENTINEL_NAME, - expectedSentinelSha256, - expectedOwner, - mode(maximumPermissions), - maximumPermissions, - PublicationGuarantee.UNIQUE_ATOMIC_CREATE, - DurabilityGuarantee.FILE_AND_DIRECTORY_SYNC); - } - - private static org.assertj.core.api.AbstractThrowableAssert - assertAttestationFailure(CompiledFileDestination destination) { - return assertAttestationFailure(new LocalPersistentRootAttestor(), destination); - } - - private static org.assertj.core.api.AbstractThrowableAssert - assertAttestationFailure( - LocalPersistentRootAttestor attestor, CompiledFileDestination destination) { - return assertThatThrownBy(() -> attestor.attest(destination)) - .isInstanceOf(LocalPersistentRootAttestor.LocalPersistentRootAttestationException.class); - } - - private static String sha256(Path file) throws IOException { - try { - return java.util.HexFormat.of() - .formatHex(MessageDigest.getInstance("SHA-256").digest(Files.readAllBytes(file))); - } catch (NoSuchAlgorithmException exception) { - throw new AssertionError("SHA-256 must be available", exception); - } - } - - private static Set ownerOnlyDirectoryMode() { - return PosixFilePermissions.fromString("rwx------"); - } - - private static String mode(Set permissions) { - int value = 0; - value |= permissions.contains(PosixFilePermission.OWNER_READ) ? 0400 : 0; - value |= permissions.contains(PosixFilePermission.OWNER_WRITE) ? 0200 : 0; - value |= permissions.contains(PosixFilePermission.OWNER_EXECUTE) ? 0100 : 0; - value |= permissions.contains(PosixFilePermission.GROUP_READ) ? 0040 : 0; - value |= permissions.contains(PosixFilePermission.GROUP_WRITE) ? 0020 : 0; - value |= permissions.contains(PosixFilePermission.GROUP_EXECUTE) ? 0010 : 0; - value |= permissions.contains(PosixFilePermission.OTHERS_READ) ? 0004 : 0; - value |= permissions.contains(PosixFilePermission.OTHERS_WRITE) ? 0002 : 0; - value |= permissions.contains(PosixFilePermission.OTHERS_EXECUTE) ? 0001 : 0; - return String.format("%04o", value); - } - - private record RootFixture( - Path root, - String owner, - Set maximumPermissions, - String fileStoreName, - String fileStoreType, - String sentinelSha256) {} - - private abstract static class DelegatingCapabilities - implements LocalPersistentRootAttestor.CapabilityOperations { - - private final LocalPersistentRootAttestor.CapabilityOperations delegate = - LocalPersistentRootAttestor.systemCapabilityOperations(); - - @Override - public SecureDirectoryStream openSecureDirectory(Path directory) throws IOException { - return delegate.openSecureDirectory(directory); - } - - @Override - public void forceFile(FileChannel channel) throws IOException { - delegate.forceFile(channel); - } - - @Override - public void createHardLink(Path link, Path existing) throws IOException { - delegate.createHardLink(link, existing); - } - - @Override - public void forceDirectory(Path directory) throws IOException { - delegate.forceDirectory(directory); - } - } -} diff --git a/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/LocalPublicationJournalTest.java b/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/LocalPublicationJournalTest.java deleted file mode 100644 index a13d7868..00000000 --- a/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/LocalPublicationJournalTest.java +++ /dev/null @@ -1,147 +0,0 @@ -package dev.caskeleton.adapter.outbound.fileserver; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.application.filepublication.ExportSchema; -import dev.caskeleton.application.filepublication.ExportSchema.CellType; -import dev.caskeleton.application.filepublication.ExportSchema.Column; -import dev.caskeleton.application.filepublication.ExportSchema.FormulaPolicy; -import dev.caskeleton.application.filepublication.FileDestinationId; -import dev.caskeleton.application.filepublication.FilePublishOperationId; -import dev.caskeleton.application.filepublication.FilePublishRequest; -import dev.caskeleton.application.filepublication.LogicalFileName; -import dev.caskeleton.application.filepublication.SourceRevision; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.time.Instant; -import java.util.List; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -class LocalPublicationJournalTest { - - @TempDir Path tempDir; - - @Test - void requestFingerprintIsStableAndCoversSourceAndSchema() { - String first = FilePublishRequestFingerprint.calculate(request("source-1", 1)); - String same = FilePublishRequestFingerprint.calculate(request("source-1", 1)); - String differentSource = FilePublishRequestFingerprint.calculate(request("source-2", 1)); - String differentSchema = FilePublishRequestFingerprint.calculate(request("source-1", 2)); - - assertThat(first).matches("[0-9a-f]{64}").isEqualTo(same); - assertThat(differentSource).isNotEqualTo(first); - assertThat(differentSchema).isNotEqualTo(first); - } - - @Test - void journalRoundTripsASealedRecordAndRejectsCorruption() throws Exception { - LocalPublicationJournal journal = new LocalPublicationJournal(tempDir); - LocalPublicationJournalRecord sealed = - LocalPublicationJournalRecord.sealed( - "operation-1", - "1".repeat(64), - "report--token.csv", - ".token.part", - 42, - 3, - 2, - "a".repeat(64), - 1); - - journal.store(sealed); - - assertThat(journal.find("operation-1")).contains(sealed); - - Path record = journal.recordPath("operation-1"); - Files.writeString( - record, Files.readString(record).replace("\"byteSize\":42", "\"byteSize\":x")); - - assertThatThrownBy(() -> journal.find("operation-1")) - .isInstanceOf(LocalPublicationJournalException.class) - .hasMessageContaining("corrupt"); - } - - @Test - void strictCompatibilityDecodeRequiresUtf8AndByteForByteCanonicalEncoding() { - LocalPublicationJournalRecord published = - LocalPublicationJournalRecord.sealed( - "operation-1", - "1".repeat(64), - "report--token.csv", - ".token.part", - 42, - 3, - 2, - "a".repeat(64), - 1) - .published(Instant.parse("2026-07-28T01:02:03Z"), "UNIQUE_ATOMIC_CREATE"); - byte[] canonical = LocalPublicationJournalCodec.encode(published); - - assertThat(LocalPublicationJournalCodec.decodeCanonical(canonical)).isEqualTo(published); - assertThatThrownBy( - () -> - LocalPublicationJournalCodec.decodeCanonical( - new String(canonical, StandardCharsets.UTF_8) - .replace("{", "{ ") - .getBytes(StandardCharsets.UTF_8))) - .isInstanceOf(LocalPublicationJournalException.class) - .hasMessageContaining("corrupt"); - assertThatThrownBy( - () -> - LocalPublicationJournalCodec.decodeCanonical(new byte[] {(byte) 0xc3, (byte) 0x28})) - .isInstanceOf(LocalPublicationJournalException.class) - .hasMessageContaining("corrupt"); - } - - @Test - void rejectsSymlinkedControlDirectoryWithoutWritingOutsideTheBase() throws Exception { - Path base = Files.createDirectory(tempDir.resolve("base")); - Path outside = Files.createDirectory(tempDir.resolve("outside")); - Files.createSymbolicLink(base.resolve(".ca-fileserver"), outside); - - assertThatThrownBy(() -> new LocalPublicationJournal(base)) - .isInstanceOf(LocalPublicationJournalException.class); - assertThat(outside.resolve("operations")).doesNotExist(); - } - - @Test - void rejectsSymlinkedJournalShardWithoutWritingOutsideTheControlDirectory() throws Exception { - LocalPublicationJournal journal = new LocalPublicationJournal(tempDir); - Path outside = Files.createDirectory(tempDir.resolve("outside")); - Path shard = journal.recordPath("operation-1").getParent(); - Files.createSymbolicLink(shard, outside); - LocalPublicationJournalRecord sealed = - LocalPublicationJournalRecord.sealed( - "operation-1", - "1".repeat(64), - "report--token.csv", - ".token.part", - 42, - 3, - 2, - "a".repeat(64), - 1); - - assertThatThrownBy(() -> journal.store(sealed)) - .isInstanceOf(LocalPublicationJournalException.class); - assertThat(outside).isEmptyDirectory(); - } - - private static FilePublishRequest request(String sourceRevision, int schemaVersion) { - return new FilePublishRequest( - new FilePublishOperationId("operation-1"), - new FileDestinationId("local-export"), - new LogicalFileName("report"), - new SourceRevision(sourceRevision), - new ExportSchema( - "work-log", - schemaVersion, - List.of( - new Column("id", CellType.INTEGER, false, FormulaPolicy.REJECT, 32), - new Column("note", CellType.TEXT, false, FormulaPolicy.MITIGATE, 256))), - "csv-rfc4180-v1"); - } -} diff --git a/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalAppendMemoryTest.java b/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalAppendMemoryTest.java index 72c3b992..a222f969 100644 --- a/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalAppendMemoryTest.java +++ b/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalAppendMemoryTest.java @@ -11,6 +11,7 @@ import java.nio.ByteBuffer; import java.nio.channels.ReadableByteChannel; import java.nio.file.Files; import java.nio.file.Path; +import java.util.Optional; import java.util.UUID; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -48,6 +49,7 @@ class LocalAppendMemoryTest { 0, new GeneratedByteChannel(PAYLOAD_BYTES), PAYLOAD_BYTES, + Optional.empty(), WriteFence.unfenced()); assertThat(result.committedOffset()).isEqualTo(PAYLOAD_BYTES); diff --git a/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalStorageGatewayContractTest.java b/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalStorageGatewayContractTest.java index 7e1fbf71..08d2995f 100644 --- a/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalStorageGatewayContractTest.java +++ b/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/platform/local/LocalStorageGatewayContractTest.java @@ -1,15 +1,20 @@ package dev.caskeleton.adapter.outbound.fileserver.platform.local; +import static dev.caskeleton.adapter.outbound.fileserver.platform.local.LocalContentStoreFixture.sha256Hex; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; import dev.caskeleton.application.fileserver.api.ByteRange; import dev.caskeleton.application.fileserver.api.ContentKey; import dev.caskeleton.application.fileserver.api.UploadId; +import dev.caskeleton.application.fileserver.api.content.AppendResult; import dev.caskeleton.application.fileserver.api.content.DeletePrecondition; import dev.caskeleton.application.fileserver.api.content.PublishMode; import dev.caskeleton.application.fileserver.api.content.StoredContent; import dev.caskeleton.application.fileserver.api.content.UploadHandle; +import dev.caskeleton.application.fileserver.api.content.WriteFence; +import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode; import dev.caskeleton.application.fileserver.api.error.IntegrityMismatchException; import dev.caskeleton.application.fileserver.download.ZeroCopyTransferResult; import java.io.ByteArrayOutputStream; @@ -19,6 +24,7 @@ import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.nio.charset.StandardCharsets; import java.nio.file.Path; +import java.util.Optional; import java.util.UUID; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -83,6 +89,50 @@ class LocalStorageGatewayContractTest { .isInstanceOf(IntegrityMismatchException.class); } + @Test + void aSecondChunkIsCheckedAgainstItsOwnDigestRatherThanTheWholeObject() { + // given + UploadHandle handle = + uploads.createStaging(newUploadId(), LocalContentStoreFixture.NAMESPACE, 1024); + uploads.append(handle, 0, channel("abc"), 3); + + // when + AppendResult second = + uploads.append( + handle, 3, channel("def"), 3, Optional.of(sha256Hex("def")), WriteFence.unfenced()); + + // then + assertThat(second.committedOffset()).isEqualTo(6); + } + + @Test + void aChunkWhoseChecksumDoesNotMatchIsRejectedAndRolledBackToItsPreAppendLength() { + // given + UploadHandle handle = + uploads.createStaging(newUploadId(), LocalContentStoreFixture.NAMESPACE, 1024); + uploads.append(handle, 0, channel("abc"), 3); + + // when + Throwable failure = + catchThrowable( + () -> + uploads.append( + handle, + 3, + channel("def"), + 3, + Optional.of(sha256Hex("xyz")), + WriteFence.unfenced())); + + // then + assertThat(failure) + .isInstanceOfSatisfying( + IntegrityMismatchException.class, + mismatch -> + assertThat(mismatch.code()).isEqualTo(FileserverErrorCode.CHECKSUM_MISMATCH)); + assertThat(uploads.stagingLength(handle)).isEqualTo(3); + } + @Test void aPublishedObjectIsReadableThroughTheDownloadGateway() throws IOException { StoredContent published = publish("the quick brown fox"); diff --git a/src/adapter/outbound/httpclient/CLAUDE.md b/src/adapter/outbound/httpclient/CLAUDE.md index 6f414e4b..330d5f96 100644 --- a/src/adapter/outbound/httpclient/CLAUDE.md +++ b/src/adapter/outbound/httpclient/CLAUDE.md @@ -43,8 +43,7 @@ moving a type between packages. so production still cannot reach it. `PlatformClasses` is the single definition of "production classes" the boundary rules import. - Stable code never references `http3`. -- `org.springframework.web.service.registry` appears only in `spring7`. -- `RestTemplate` appears only in `migration`. +- no class uses `org.springframework.web.service.registry` or `RestTemplate`. ## Boundaries diff --git a/src/adapter/outbound/httpclient/README.md b/src/adapter/outbound/httpclient/README.md index 21139d2e..900203ab 100644 --- a/src/adapter/outbound/httpclient/README.md +++ b/src/adapter/outbound/httpclient/README.md @@ -48,11 +48,32 @@ a single execution model. - **Secrets.** No URL, query value, path variable, token, cookie, or idempotency key reaches a log, a metric label, or an exception message. +## 제공하는 것 · 추가할 한 줄 · env 키 + +- 제공: 위 H1–H3 surface(`HttpServiceRegistry`, `GenericHttpGateway`, `DynamicTargetGateway` 등), + transport·TLS·credential·resilience·관측, actuator endpoint. OAuth2 client credential 지원 + (`spring-security-oauth2-client`)도 이 모듈이 가진다. 설정 기본값 `config/module-defaults/httpclient.yml`은 + support의 `ModuleDefaultsEnvironmentPostProcessor`가 읽는다(우선순위 가장 낮음). +- 추가할 한 줄(기본 조립에는 없다): + + ```groovy + // app-bootstrap/build.gradle + runtimeOnly project(':adapter:outbound:httpclient') // 외부 HTTP 호출 + ``` + + 이 줄을 지우면 platform bean, 설정 기본값, OAuth2 client 의존성이 모두 함께 빠진다. +- 켜기와 끄기: 모듈이 있으면 켜진다. `APP_HTTPCLIENT_ENABLED=false`로만 끈다. +- 필요한 env 키(`docs/registries/env-keys.yaml` SSOT): client 하나 이상 — + `APP_HTTPCLIENT_CLIENTS_0_NAME`, `APP_HTTPCLIENT_CLIENTS_0_BASE_URL`, + `APP_HTTPCLIENT_CLIENTS_0_ALLOWED_HOSTS_0`, `APP_HTTPCLIENT_CLIENTS_0_ALLOWED_PORTS_0`, + `APP_HTTPCLIENT_CLIENTS_0_REQUEST_MAX_BODY_BYTES`, `APP_HTTPCLIENT_CLIENTS_0_TLS_PROFILE_ID` + (필드 전체는 `docs/httpclient/env-fields.yaml`). client가 없으면 `HTTPCLIENT_ACTIVE_WITHOUT_CLIENTS`로 + 기동이 실패한다. + ## Configuration -Profiles live under `http-clients.`; Dynamic Target policies under -`http-dynamic-targets.`. With neither present the capability holds no runtime resources at -all. Every startup guard, property, and violation code is listed in +Profiles live under `app.httpclient.clients[N]`; Dynamic Target policies under +`app.httpclient.dynamic-targets[N]`. Every startup guard, property, and violation code is listed in `docs/httpclient/configuration-reference.md`. ## Verification @@ -73,5 +94,5 @@ not assert. ## Further reading `docs/httpclient/` holds the support matrix, configuration reference, retry and ambiguity guide, -security guide, streaming guide, operations runbook, migration guide, performance baseline, and +security guide, streaming guide, operations runbook, performance baseline, and release checklist. diff --git a/src/adapter/outbound/httpclient/build.gradle b/src/adapter/outbound/httpclient/build.gradle index e4b0de7c..e2150e17 100644 --- a/src/adapter/outbound/httpclient/build.gradle +++ b/src/adapter/outbound/httpclient/build.gradle @@ -2,7 +2,8 @@ plugins { id 'ca.spring-library' id 'java-test-fixtures' id 'ca.auxiliary-source-set' - id 'ca.jmh-benchmarks' + id 'ca.platform-module' + id 'me.champeau.jmh' } // Shared test code as a Gradle test-fixtures variant — ADR-BUILD-001. @@ -121,11 +122,14 @@ dependencies { // UTF-8 is pinned for every JavaCompile task in the root build; this leaf no longer repeats it. -// JMH is owned by ca.jmh-benchmarks. This leaf's benchmarks deliberately see test fixtures, -// not the ordinary test output, so benchmark support remains a reusable main-like surface. -jmhBenchmarks { - compilesAgainst 'main', 'testFixtures' - jsonReport 'reports/jmh/result.json' +// The benchmarks see test fixtures, not the ordinary test output (`./gradlew :adapter:outbound:httpclient:jmh`). +jmh { + jmhVersion = libs.versions.jmh.get() + resultFormat = 'JSON' + resultsFile = layout.buildDirectory.file('reports/jmh/result.json') +} +dependencies { + jmhImplementation testFixtures(project) } tasks.named('test', Test) { diff --git a/src/adapter/outbound/httpclient/gradle.lockfile b/src/adapter/outbound/httpclient/gradle.lockfile index 1f7fdc18..62ad3ba6 100644 --- a/src/adapter/outbound/httpclient/gradle.lockfile +++ b/src/adapter/outbound/httpclient/gradle.lockfile @@ -1,9 +1,9 @@ # 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. -biz.aQute.bnd:biz.aQute.bnd.annotation:7.1.0=httpClientPerformanceTestCompileClasspath,integrationTestCompileClasspath,jmhCompileClasspath,testCompileClasspath,testkitCompileClasspath -ch.qos.logback:logback-classic:1.5.38=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -ch.qos.logback:logback-core:1.5.38=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +biz.aQute.bnd:biz.aQute.bnd.annotation:7.1.0=httpClientPerformanceTestCompileClasspath,integrationTestCompileClasspath,testCompileClasspath,testkitCompileClasspath +ch.qos.logback:logback-classic:1.5.38=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +ch.qos.logback:logback-core:1.5.38=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath com.fasterxml.jackson.core:jackson-annotations:2.21=compileClasspath,httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath com.fasterxml.jackson.core:jackson-core:2.21.5=compileClasspath,httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath com.fasterxml.jackson.core:jackson-databind:2.21.5=compileClasspath,httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath @@ -22,7 +22,7 @@ com.google.auto:auto-common:1.2.2=annotationProcessor,httpClientPerformanceTestA com.google.code.findbugs:jsr305:3.0.2=checkstyle,spotbugs com.google.code.gson:gson:2.13.2=integrationTestCompileClasspath,integrationTestRuntimeClasspath,spotbugs,testkitCompileClasspath,testkitRuntimeClasspath com.google.errorprone:error_prone_annotation:2.49.0=annotationProcessor,httpClientPerformanceTestAnnotationProcessor,integrationTestAnnotationProcessor,jmhAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor,testkitAnnotationProcessor -com.google.errorprone:error_prone_annotations:2.38.0=httpClientPerformanceTestCompileClasspath,jmhCompileClasspath,testCompileClasspath +com.google.errorprone:error_prone_annotations:2.38.0=httpClientPerformanceTestCompileClasspath,testCompileClasspath com.google.errorprone:error_prone_annotations:2.41.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,spotbugs,testkitCompileClasspath,testkitRuntimeClasspath com.google.errorprone:error_prone_annotations:2.47.0=checkstyle com.google.errorprone:error_prone_annotations:2.49.0=annotationProcessor,httpClientPerformanceTestAnnotationProcessor,integrationTestAnnotationProcessor,jmhAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor,testkitAnnotationProcessor @@ -36,23 +36,23 @@ com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=anno com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,httpClientPerformanceTestAnnotationProcessor,integrationTestAnnotationProcessor,jmhAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor,testkitAnnotationProcessor com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,httpClientPerformanceTestAnnotationProcessor,integrationTestAnnotationProcessor,jmhAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor,testkitAnnotationProcessor com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins -com.jayway.jsonpath:json-path:2.10.0=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +com.jayway.jsonpath:json-path:2.10.0=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath com.nimbusds:content-type:2.3=compileClasspath,httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath com.nimbusds:lang-tag:1.7=compileClasspath,httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath com.nimbusds:nimbus-jose-jwt:10.4=compileClasspath,httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath com.nimbusds:oauth2-oidc-sdk:11.26.1=compileClasspath,httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath com.puppycrawl.tools:checkstyle:13.5.0=checkstyle -com.squareup.okhttp3:mockwebserver:4.12.0=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -com.squareup.okhttp3:okhttp-tls:4.12.0=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -com.squareup.okhttp3:okhttp:4.12.0=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -com.squareup.okio:okio-jvm:3.6.0=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -com.squareup.okio:okio:3.6.0=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -com.tngtech.archunit:archunit-junit5-api:1.3.0=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +com.squareup.okhttp3:mockwebserver:4.12.0=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +com.squareup.okhttp3:okhttp-tls:4.12.0=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +com.squareup.okhttp3:okhttp:4.12.0=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +com.squareup.okio:okio-jvm:3.6.0=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +com.squareup.okio:okio:3.6.0=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +com.tngtech.archunit:archunit-junit5-api:1.3.0=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath com.tngtech.archunit:archunit-junit5-engine-api:1.3.0=httpClientPerformanceTestRuntimeClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitRuntimeClasspath com.tngtech.archunit:archunit-junit5-engine:1.3.0=httpClientPerformanceTestRuntimeClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitRuntimeClasspath -com.tngtech.archunit:archunit-junit5:1.3.0=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -com.tngtech.archunit:archunit:1.3.0=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -com.vaadin.external.google:android-json:0.0.20131108.vaadin1=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +com.tngtech.archunit:archunit-junit5:1.3.0=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +com.tngtech.archunit:archunit:1.3.0=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +com.vaadin.external.google:android-json:0.0.20131108.vaadin1=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath commons-beanutils:commons-beanutils:1.11.0=checkstyle commons-codec:commons-codec:1.19.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath commons-collections:commons-collections:3.2.2=checkstyle @@ -97,27 +97,27 @@ io.netty:netty-transport-native-unix-common:4.2.17.Final=compileClasspath,httpCl io.netty:netty-transport:4.2.17.Final=compileClasspath,httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath io.projectreactor.netty:reactor-netty-core:1.3.7=compileClasspath,httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath io.projectreactor.netty:reactor-netty-http:1.3.7=compileClasspath,httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -io.projectreactor.tools:blockhound:1.0.17.RELEASE=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +io.projectreactor.tools:blockhound:1.0.17.RELEASE=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath io.projectreactor:reactor-core:3.8.7=compileClasspath,httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -io.projectreactor:reactor-test:3.8.7=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -jakarta.activation:jakarta.activation-api:2.1.4=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -jakarta.annotation:jakarta.annotation-api:3.0.0=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -jakarta.xml.bind:jakarta.xml.bind-api:4.0.5=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +io.projectreactor:reactor-test:3.8.7=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +jakarta.activation:jakarta.activation-api:2.1.4=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +jakarta.annotation:jakarta.annotation-api:3.0.0=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +jakarta.xml.bind:jakarta.xml.bind-api:4.0.5=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath javax.inject:javax.inject:1=annotationProcessor,httpClientPerformanceTestAnnotationProcessor,integrationTestAnnotationProcessor,jmhAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor,testkitAnnotationProcessor jaxen:jaxen:2.0.6=spotbugs -junit:junit:4.13.2=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -net.bytebuddy:byte-buddy-agent:1.17.8=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -net.bytebuddy:byte-buddy:1.17.8=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +junit:junit:4.13.2=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +net.bytebuddy:byte-buddy-agent:1.17.8=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +net.bytebuddy:byte-buddy:1.17.8=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath net.java.dev.jna:jna:5.18.1=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath net.minidev:accessors-smart:2.6.0=compileClasspath,httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath net.minidev:json-smart:2.6.0=compileClasspath,httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -net.sf.jopt-simple:jopt-simple:5.0.4=jmhAnnotationProcessor,jmhCompileClasspath,jmhRuntimeClasspath +net.sf.jopt-simple:jopt-simple:5.0.4=jmh,jmhCompileClasspath,jmhRuntimeClasspath net.sf.saxon:Saxon-HE:12.9=checkstyle,spotbugs org.antlr:antlr4-runtime:4.13.2=checkstyle org.apache.bcel:bcel:6.12.0=spotbugs org.apache.commons:commons-compress:1.28.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath org.apache.commons:commons-lang3:3.20.0=checkstyle,integrationTestCompileClasspath,integrationTestRuntimeClasspath,spotbugs,testkitCompileClasspath,testkitRuntimeClasspath -org.apache.commons:commons-math3:3.6.1=jmhAnnotationProcessor,jmhCompileClasspath,jmhRuntimeClasspath +org.apache.commons:commons-math3:3.6.1=jmh,jmhCompileClasspath,jmhRuntimeClasspath org.apache.commons:commons-text:1.15.0=spotbugs org.apache.commons:commons-text:1.3=checkstyle org.apache.httpcomponents.client5:httpclient5:5.5.2=compileClasspath,httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath @@ -125,20 +125,20 @@ org.apache.httpcomponents.core5:httpcore5-h2:5.3.6=compileClasspath,httpClientPe org.apache.httpcomponents.core5:httpcore5:5.3.6=compileClasspath,httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath org.apache.httpcomponents:httpclient:4.5.13=checkstyle org.apache.httpcomponents:httpcore:4.4.16=checkstyle -org.apache.logging.log4j:log4j-api:2.25.5=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,spotbugs,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +org.apache.logging.log4j:log4j-api:2.25.5=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,spotbugs,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath org.apache.logging.log4j:log4j-core:2.25.5=spotbugs -org.apache.logging.log4j:log4j-to-slf4j:2.25.5=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +org.apache.logging.log4j:log4j-to-slf4j:2.25.5=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath org.apache.maven.doxia:doxia-core:1.12.0=checkstyle 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.tomcat.embed:tomcat-embed-core:11.0.24=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.apache.tomcat.embed:tomcat-embed-el:11.0.24=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.apache.tomcat.embed:tomcat-embed-websocket:11.0.24=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +org.apache.tomcat.embed:tomcat-embed-core:11.0.24=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +org.apache.tomcat.embed:tomcat-embed-el:11.0.24=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +org.apache.tomcat.embed:tomcat-embed-websocket:11.0.24=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath org.apache.xbean:xbean-reflect:3.7=checkstyle -org.apiguardian:apiguardian-api:1.1.2=httpClientPerformanceTestCompileClasspath,integrationTestCompileClasspath,jmhCompileClasspath,testCompileClasspath,testFixturesCompileClasspath,testkitCompileClasspath -org.assertj:assertj-core:3.27.7=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.awaitility:awaitility:4.3.0=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +org.apiguardian:apiguardian-api:1.1.2=httpClientPerformanceTestCompileClasspath,integrationTestCompileClasspath,testCompileClasspath,testFixturesCompileClasspath,testkitCompileClasspath +org.assertj:assertj-core:3.27.7=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +org.awaitility:awaitility:4.3.0=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath 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 @@ -159,74 +159,77 @@ org.eclipse.jetty:jetty-client:12.1.12=compileClasspath,httpClientPerformanceTes org.eclipse.jetty:jetty-http:12.1.12=compileClasspath,httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath org.eclipse.jetty:jetty-io:12.1.12=compileClasspath,httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath org.eclipse.jetty:jetty-util:12.1.12=compileClasspath,httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.hamcrest:hamcrest-core:3.0=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.hamcrest:hamcrest:3.0=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +org.hamcrest:hamcrest-core:3.0=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +org.hamcrest:hamcrest:3.0=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath org.hdrhistogram:HdrHistogram:2.2.2=httpClientPerformanceTestRuntimeClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,runtimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitRuntimeClasspath org.javassist:javassist:3.28.0-GA=checkstyle -org.jetbrains.kotlin:kotlin-stdlib-common:2.2.21=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.jetbrains.kotlin:kotlin-stdlib-jdk7:2.2.21=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.jetbrains.kotlin:kotlin-stdlib-jdk8:2.2.21=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.jetbrains.kotlin:kotlin-stdlib:2.2.21=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.jetbrains:annotations:13.0=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.jetbrains.kotlin:kotlin-stdlib-common:2.2.21=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +org.jetbrains.kotlin:kotlin-stdlib-jdk7:2.2.21=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +org.jetbrains.kotlin:kotlin-stdlib-jdk8:2.2.21=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +org.jetbrains.kotlin:kotlin-stdlib:2.2.21=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +org.jetbrains:annotations:13.0=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.jetbrains:annotations:17.0.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,compileClasspath,httpClientPerformanceTestAnnotationProcessor,httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestAnnotationProcessor,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhAnnotationProcessor,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testAnnotationProcessor,testCompileClasspath,testFixturesAnnotationProcessor,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitAnnotationProcessor,testkitCompileClasspath,testkitRuntimeClasspath -org.junit.jupiter:junit-jupiter-api:6.0.3=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +org.junit.jupiter:junit-jupiter-api:6.0.3=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath org.junit.jupiter:junit-jupiter-engine:6.0.3=httpClientPerformanceTestRuntimeClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testRuntimeClasspath,testkitRuntimeClasspath -org.junit.jupiter:junit-jupiter-params:6.0.3=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.junit.jupiter:junit-jupiter:6.0.3=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.junit.platform:junit-platform-commons:6.0.3=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +org.junit.jupiter:junit-jupiter-params:6.0.3=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +org.junit.jupiter:junit-jupiter:6.0.3=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +org.junit.platform:junit-platform-commons:6.0.3=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath org.junit.platform:junit-platform-engine:6.0.3=httpClientPerformanceTestRuntimeClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitRuntimeClasspath org.junit.platform:junit-platform-launcher:6.0.3=httpClientPerformanceTestRuntimeClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testRuntimeClasspath,testkitRuntimeClasspath -org.junit:junit-bom:6.0.3=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +org.junit:junit-bom:6.0.3=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath org.junit:junit-bom:6.1.0=spotbugs org.latencyutils:LatencyUtils:2.0.3=httpClientPerformanceTestRuntimeClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,runtimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitRuntimeClasspath -org.mockito:mockito-core:5.20.0=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,mockitoAgent,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.mockito:mockito-junit-jupiter:5.20.0=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +org.mockito:mockito-core:5.20.0=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,mockitoAgent,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +org.mockito:mockito-junit-jupiter:5.20.0=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath org.objenesis:objenesis:3.3=httpClientPerformanceTestRuntimeClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testRuntimeClasspath,testkitRuntimeClasspath -org.openjdk.jmh:jmh-core:1.37=jmhAnnotationProcessor,jmhCompileClasspath,jmhRuntimeClasspath -org.openjdk.jmh:jmh-generator-annprocess:1.37=jmhAnnotationProcessor -org.opentest4j:opentest4j:1.3.0=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.osgi:org.osgi.annotation.bundle:2.0.0=httpClientPerformanceTestCompileClasspath,integrationTestCompileClasspath,jmhCompileClasspath,testCompileClasspath,testkitCompileClasspath -org.osgi:org.osgi.annotation.versioning:1.1.2=httpClientPerformanceTestCompileClasspath,integrationTestCompileClasspath,jmhCompileClasspath,testCompileClasspath,testkitCompileClasspath -org.osgi:org.osgi.resource:1.0.0=httpClientPerformanceTestCompileClasspath,integrationTestCompileClasspath,jmhCompileClasspath,testCompileClasspath,testkitCompileClasspath -org.osgi:org.osgi.service.serviceloader:1.0.0=httpClientPerformanceTestCompileClasspath,integrationTestCompileClasspath,jmhCompileClasspath,testCompileClasspath,testkitCompileClasspath +org.openjdk.jmh:jmh-core:1.37=jmh,jmhCompileClasspath,jmhRuntimeClasspath +org.openjdk.jmh:jmh-generator-asm:1.37=jmh,jmhCompileClasspath,jmhRuntimeClasspath +org.openjdk.jmh:jmh-generator-bytecode:1.37=jmh,jmhCompileClasspath,jmhRuntimeClasspath +org.openjdk.jmh:jmh-generator-reflection:1.37=jmh,jmhCompileClasspath,jmhRuntimeClasspath +org.opentest4j:opentest4j:1.3.0=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +org.osgi:org.osgi.annotation.bundle:2.0.0=httpClientPerformanceTestCompileClasspath,integrationTestCompileClasspath,testCompileClasspath,testkitCompileClasspath +org.osgi:org.osgi.annotation.versioning:1.1.2=httpClientPerformanceTestCompileClasspath,integrationTestCompileClasspath,testCompileClasspath,testkitCompileClasspath +org.osgi:org.osgi.resource:1.0.0=httpClientPerformanceTestCompileClasspath,integrationTestCompileClasspath,testCompileClasspath,testkitCompileClasspath +org.osgi:org.osgi.service.serviceloader:1.0.0=httpClientPerformanceTestCompileClasspath,integrationTestCompileClasspath,testCompileClasspath,testkitCompileClasspath 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.0=jmh org.ow2.asm:asm:9.10.1=spotbugs org.ow2.asm:asm:9.7.1=compileClasspath,httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath org.pcollections:pcollections:4.0.1=annotationProcessor,httpClientPerformanceTestAnnotationProcessor,integrationTestAnnotationProcessor,jmhAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor,testkitAnnotationProcessor org.reactivestreams:reactive-streams:1.0.4=compileClasspath,httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath org.reflections:reflections:0.10.2=checkstyle org.rnorth.duct-tape:duct-tape:1.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.skyscreamer:jsonassert:1.5.3=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.slf4j:jul-to-slf4j:2.0.18=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +org.skyscreamer:jsonassert:1.5.3=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +org.slf4j:jul-to-slf4j:2.0.18=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath org.slf4j:slf4j-api:2.0.18=compileClasspath,httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,spotbugs,spotbugsSlf4j,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j org.slf4j:slf4j-simple:2.0.18=checkstyle org.springframework.boot:spring-boot-actuator-autoconfigure:4.0.8=compileClasspath,httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-actuator:4.0.8=compileClasspath,httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-autoconfigure:4.0.8=compileClasspath,httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.springframework.boot:spring-boot-http-converter:4.0.8=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.springframework.boot:spring-boot-jackson:4.0.8=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.springframework.boot:spring-boot-resttestclient:4.0.8=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.springframework.boot:spring-boot-servlet:4.0.8=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.springframework.boot:spring-boot-starter-jackson-test:4.0.8=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.springframework.boot:spring-boot-starter-jackson:4.0.8=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.springframework.boot:spring-boot-starter-logging:4.0.8=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.springframework.boot:spring-boot-starter-test:4.0.8=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.springframework.boot:spring-boot-starter-tomcat-runtime:4.0.8=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.springframework.boot:spring-boot-starter-tomcat:4.0.8=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.springframework.boot:spring-boot-starter-webmvc-test:4.0.8=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.springframework.boot:spring-boot-starter-webmvc:4.0.8=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.springframework.boot:spring-boot-starter:4.0.8=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.springframework.boot:spring-boot-test-autoconfigure:4.0.8=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.springframework.boot:spring-boot-test:4.0.8=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.springframework.boot:spring-boot-tomcat:4.0.8=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.springframework.boot:spring-boot-web-server:4.0.8=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.springframework.boot:spring-boot-webmvc-test:4.0.8=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.springframework.boot:spring-boot-webmvc:4.0.8=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +org.springframework.boot:spring-boot-http-converter:4.0.8=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +org.springframework.boot:spring-boot-jackson:4.0.8=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +org.springframework.boot:spring-boot-resttestclient:4.0.8=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +org.springframework.boot:spring-boot-servlet:4.0.8=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +org.springframework.boot:spring-boot-starter-jackson-test:4.0.8=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +org.springframework.boot:spring-boot-starter-jackson:4.0.8=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +org.springframework.boot:spring-boot-starter-logging:4.0.8=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +org.springframework.boot:spring-boot-starter-test:4.0.8=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +org.springframework.boot:spring-boot-starter-tomcat-runtime:4.0.8=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +org.springframework.boot:spring-boot-starter-tomcat:4.0.8=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +org.springframework.boot:spring-boot-starter-webmvc-test:4.0.8=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +org.springframework.boot:spring-boot-starter-webmvc:4.0.8=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +org.springframework.boot:spring-boot-starter:4.0.8=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +org.springframework.boot:spring-boot-test-autoconfigure:4.0.8=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +org.springframework.boot:spring-boot-test:4.0.8=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +org.springframework.boot:spring-boot-tomcat:4.0.8=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +org.springframework.boot:spring-boot-web-server:4.0.8=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +org.springframework.boot:spring-boot-webmvc-test:4.0.8=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +org.springframework.boot:spring-boot-webmvc:4.0.8=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath org.springframework.boot:spring-boot:4.0.8=compileClasspath,httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath org.springframework.security:spring-security-core:7.0.7=compileClasspath,httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath org.springframework.security:spring-security-crypto:7.0.7=compileClasspath,httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath @@ -238,16 +241,16 @@ org.springframework:spring-beans:7.0.9=compileClasspath,httpClientPerformanceTes org.springframework:spring-context:7.0.9=compileClasspath,httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath org.springframework:spring-core:7.0.9=compileClasspath,httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath org.springframework:spring-expression:7.0.9=compileClasspath,httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.springframework:spring-test:7.0.9=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +org.springframework:spring-test:7.0.9=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath org.springframework:spring-web:7.0.9=compileClasspath,httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath org.springframework:spring-webflux:7.0.9=compileClasspath,httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.springframework:spring-webmvc:7.0.9=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +org.springframework:spring-webmvc:7.0.9=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath org.testcontainers:testcontainers-junit-jupiter:2.0.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath org.testcontainers:testcontainers-toxiproxy:2.0.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath org.testcontainers:testcontainers:2.0.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath org.xmlresolver:xmlresolver:5.3.3=checkstyle,spotbugs -org.xmlunit:xmlunit-core:2.10.4=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.yaml:snakeyaml:2.5=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +org.xmlunit:xmlunit-core:2.10.4=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +org.yaml:snakeyaml:2.5=httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath tools.jackson.core:jackson-core:3.1.5=compileClasspath,httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath tools.jackson.core:jackson-databind:3.1.5=compileClasspath,httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath tools.jackson:jackson-bom:3.1.5=compileClasspath,httpClientPerformanceTestCompileClasspath,httpClientPerformanceTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientPlatformAutoConfiguration.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientPlatformAutoConfiguration.java index 203cda54..360033bb 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientPlatformAutoConfiguration.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientPlatformAutoConfiguration.java @@ -10,12 +10,13 @@ import org.springframework.core.env.Environment; /** * The one entry point through which the HTTP Client platform exists at all. * - *

This is an auto-configuration rather than a component-scanned {@code @Configuration}, and it - * lives in a package the composition root's scan explicitly excludes. That is the whole point: when - * the master switch is absent or false the class is never processed, so none of the configurations - * it imports are discovered either. No property is bound, no transport provider is constructed, no - * connection pool, TLS context, credential, thread or gateway exists, and a malformed HTTP setting - * in a deployment that never wanted outbound HTTP cannot fail its startup. + *

On when present: an application that selected this module wants outbound HTTP, so a missing + * {@code app.httpclient.enabled} means on. This is an auto-configuration rather than a + * component-scanned {@code @Configuration}: when the capability switch is {@code false} the class + * is never processed, so none of the configurations it imports are discovered either. No property + * is bound, no transport provider is constructed, no connection pool, TLS context, credential, + * thread or gateway exists, and a malformed HTTP setting in a deployment that switched outbound + * HTTP off cannot fail its startup. * *

The previous shape had nine independently annotated {@code @Configuration} classes inside the * scanned package. Wrapping them in a conditional parent would have changed nothing — the component @@ -29,7 +30,8 @@ import org.springframework.core.env.Environment; @ConditionalOnProperty( prefix = HttpClientPlatformSettings.PREFIX, name = "enabled", - havingValue = "true") + havingValue = "true", + matchIfMissing = true) @Import({ HttpClientResilienceAutoConfiguration.class, HttpClientSecurityAutoConfiguration.class, @@ -44,7 +46,7 @@ import org.springframework.core.env.Environment; public class HttpClientPlatformAutoConfiguration { /** - * Binds the platform settings once the master switch has already been proven true. + * Binds the platform settings once the capability switch has already been proven true. * *

Binding is deliberately not delegated to {@code @ConfigurationPropertiesScan}: that would * bind — and reject — HTTP client detail settings in deployments that never switched the diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientPlatformSettings.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientPlatformSettings.java index 094fc544..36848d50 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientPlatformSettings.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientPlatformSettings.java @@ -17,7 +17,7 @@ import org.springframework.boot.context.properties.bind.DefaultValue; * {@code @ConfigurationPropertiesScan} is not selective and cannot be made selective per * deployment, so an annotated class is registered — and bound, and able to fail startup — in every * deployment, including one that never makes an outbound HTTP call. That is precisely the coupling - * the master switch exists to remove, so binding is done by {@link + * the capability switch exists to remove, so binding is done by {@link * HttpClientPlatformSettingsBinder} from inside the gated auto-configuration and "off" means "never * bound". * @@ -33,14 +33,15 @@ import org.springframework.boot.context.properties.bind.DefaultValue; * hosts, body limits, TLS profile — has no usable default and is caught by startup validation * instead. * - * @param enabled master switch for the whole capability + * @param enabled capability switch for the whole capability; on unless set to {@code false}, + * because an application that selected this module wants it * @param clients the Named Client Profiles this deployment declares * @param dynamicTargets the Dynamic Target policies this deployment declares * @param rotationDrainTimeout how long a retired runtime generation may keep draining after a * certificate rotation before its pool is closed underneath whatever is still in flight */ public record HttpClientPlatformSettings( - @DefaultValue("false") boolean enabled, + @DefaultValue("true") boolean enabled, @DefaultValue List clients, @DefaultValue List dynamicTargets, @DefaultValue("30s") Duration rotationDrainTimeout) { diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientProfileAutoConfiguration.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientProfileAutoConfiguration.java index 8c5155ad..c81441c0 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientProfileAutoConfiguration.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientProfileAutoConfiguration.java @@ -36,8 +36,8 @@ import org.springframework.core.env.Environment; * Binds profiles, validates them, and publishes the runtime registry (design §27.1, §27.2). * *

Validation runs before any runtime is built, so an unsafe configuration cannot create a - * connection pool, a TLS context, or a credential before failing. With no {@code http-clients} - * entries the registry is empty and the capability holds no resources at all. + * connection pool, a TLS context, or a credential before failing. With no {@code + * app.httpclient.clients} entries the registry is empty and the capability holds no resources. */ @Configuration(proxyBeanMethods = false) public class HttpClientProfileAutoConfiguration { diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientResilienceAutoConfiguration.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientResilienceAutoConfiguration.java index 427a592a..6bfc879f 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientResilienceAutoConfiguration.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientResilienceAutoConfiguration.java @@ -14,8 +14,8 @@ import org.springframework.context.annotation.Configuration; * *

The {@link Clock} comes from the composition root rather than from here. A fallback clock * declared beside the resilience registry was harmless while this configuration was scanned - * unconditionally; behind the master switch it would have made the application's clock disappear - * whenever outbound HTTP was off, taking Redis, idempotency and the Fileserver with it. + * unconditionally; behind the capability switch it would have made the application's clock + * disappear whenever outbound HTTP was off, taking Redis, idempotency and the Fileserver with it. */ @Configuration(proxyBeanMethods = false) public class HttpClientResilienceAutoConfiguration { diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/migration/MigrationFinding.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/migration/MigrationFinding.java deleted file mode 100644 index e43820f9..00000000 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/migration/MigrationFinding.java +++ /dev/null @@ -1,37 +0,0 @@ -package dev.caskeleton.adapter.outbound.httpclient.migration; - -import java.util.Objects; - -/** - * One gap discovered while auditing an existing {@code RestTemplate} (design §26.5). - * - *

Severity is explicit so a migration can be triaged: a missing timeout is a production risk, a - * legacy converter is merely work. - */ -public record MigrationFinding(Severity severity, String code, String detail) { - - /** How urgent the finding is for the migration owner. */ - public enum Severity { - BLOCKING, - WARNING, - INFORMATIONAL - } - - public MigrationFinding { - Objects.requireNonNull(severity, "severity"); - Objects.requireNonNull(code, "code"); - Objects.requireNonNull(detail, "detail"); - } - - public static MigrationFinding blocking(String code, String detail) { - return new MigrationFinding(Severity.BLOCKING, code, detail); - } - - public static MigrationFinding warning(String code, String detail) { - return new MigrationFinding(Severity.WARNING, code, detail); - } - - public static MigrationFinding informational(String code, String detail) { - return new MigrationFinding(Severity.INFORMATIONAL, code, detail); - } -} diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/migration/RestTemplateInventory.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/migration/RestTemplateInventory.java deleted file mode 100644 index bb356396..00000000 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/migration/RestTemplateInventory.java +++ /dev/null @@ -1,37 +0,0 @@ -package dev.caskeleton.adapter.outbound.httpclient.migration; - -import java.util.List; -import java.util.Objects; - -/** - * What an existing {@code RestTemplate} actually does (design §26.5). - * - *

Migration starts with an inventory rather than a rewrite: a template usually carries - * interceptors and converters whose behaviour someone depends on, and replacing it blind is how a - * migration becomes an incident. - */ -public record RestTemplateInventory( - String requestFactoryType, - List messageConverterTypes, - List interceptorTypes, - String errorHandlerType, - String uriTemplateHandlerType, - List findings) { - - public RestTemplateInventory { - Objects.requireNonNull(requestFactoryType, "request factory type"); - Objects.requireNonNull(messageConverterTypes, "message converter types"); - Objects.requireNonNull(interceptorTypes, "interceptor types"); - Objects.requireNonNull(errorHandlerType, "error handler type"); - Objects.requireNonNull(uriTemplateHandlerType, "uri template handler type"); - Objects.requireNonNull(findings, "findings"); - messageConverterTypes = List.copyOf(messageConverterTypes); - interceptorTypes = List.copyOf(interceptorTypes); - findings = List.copyOf(findings); - } - - public boolean migratable() { - return findings.stream() - .noneMatch(finding -> finding.severity() == MigrationFinding.Severity.BLOCKING); - } -} diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/migration/RestTemplateInventoryScanner.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/migration/RestTemplateInventoryScanner.java deleted file mode 100644 index 6975590b..00000000 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/migration/RestTemplateInventoryScanner.java +++ /dev/null @@ -1,59 +0,0 @@ -package dev.caskeleton.adapter.outbound.httpclient.migration; - -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; -import org.springframework.http.client.ClientHttpRequestFactory; -import org.springframework.http.client.SimpleClientHttpRequestFactory; -import org.springframework.web.client.RestTemplate; - -/** - * Audits an existing {@code RestTemplate} before anything is changed (design §26.5). - * - *

The findings are the point: a {@code SimpleClientHttpRequestFactory} in production is design - * §31's explicitly unsupported configuration, and a template with no interceptors usually means - * timeouts and correlation are configured somewhere else — or nowhere. - */ -public final class RestTemplateInventoryScanner { - - public RestTemplateInventory scan(RestTemplate template) { - Objects.requireNonNull(template, "rest template"); - List findings = new ArrayList<>(); - - ClientHttpRequestFactory requestFactory = template.getRequestFactory(); - if (requestFactory instanceof SimpleClientHttpRequestFactory) { - findings.add( - MigrationFinding.blocking( - "SIMPLE_REQUEST_FACTORY", - "the simple request factory has no connection pool and is not supported in production")); - } - if (template.getInterceptors().isEmpty()) { - findings.add( - MigrationFinding.warning( - "NO_INTERCEPTORS", - "no interceptor is registered; confirm where correlation and timeouts are applied")); - } - if (template.getMessageConverters().isEmpty()) { - findings.add( - MigrationFinding.blocking( - "NO_MESSAGE_CONVERTERS", "the template cannot encode or decode any body")); - } - findings.add( - MigrationFinding.informational( - "TIMEOUTS_NOT_INTROSPECTABLE", - "request factory timeouts are not readable through the RestTemplate api; declare them " - + "explicitly on the target Named Client Profile")); - - return new RestTemplateInventory( - requestFactory.getClass().getName(), - template.getMessageConverters().stream() - .map(converter -> converter.getClass().getName()) - .toList(), - template.getInterceptors().stream() - .map(interceptor -> interceptor.getClass().getName()) - .toList(), - template.getErrorHandler().getClass().getName(), - template.getUriTemplateHandler().getClass().getName(), - findings); - } -} diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/migration/RestTemplateToRestClientAdapter.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/migration/RestTemplateToRestClientAdapter.java deleted file mode 100644 index c732b6ab..00000000 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/migration/RestTemplateToRestClientAdapter.java +++ /dev/null @@ -1,31 +0,0 @@ -package dev.caskeleton.adapter.outbound.httpclient.migration; - -import java.util.Objects; -import org.springframework.web.client.RestClient; -import org.springframework.web.client.RestTemplate; - -/** - * Behaviour-preserving bridge from a legacy template to a RestClient (design §26.5, D-18). - * - *

It carries the existing converters, interceptors, error handler, and URI handler across so the - * first migration step changes the API and nothing else. New platform capabilities — Dynamic - * Target, evidence-based retry, HTTP/3 — are deliberately not reachable from here: a caller that - * wants them moves to a Named Client Profile. - */ -public final class RestTemplateToRestClientAdapter { - - public RestClient adapt(RestTemplate template) { - Objects.requireNonNull(template, "rest template"); - return RestClient.builder(template).build(); - } - - /** Audit first, then adapt: a blocking finding stops the migration rather than hiding it. */ - public RestClient adaptChecked(RestTemplate template) { - RestTemplateInventory inventory = new RestTemplateInventoryScanner().scan(template); - if (!inventory.migratable()) { - throw new IllegalStateException( - "rest template cannot be migrated as-is: " + inventory.findings()); - } - return adapt(template); - } -} diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/restclient/BoundedErrorBody.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/restclient/BoundedErrorBody.java deleted file mode 100644 index 90e67085..00000000 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/restclient/BoundedErrorBody.java +++ /dev/null @@ -1,54 +0,0 @@ -package dev.caskeleton.adapter.outbound.httpclient.restclient; - -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; -import java.util.Objects; - -/** - * A strictly bounded snapshot of an error body (design §19.2). - * - *

Error bodies are read only far enough to decode an RFC 9457 document. The bytes never reach an - * exception message or a log; they exist so {@code type}/{@code title}/{@code status} can be - * parsed. - * - *

A final class rather than a record because the payload is an array and must be copied on both - * construction and access. - */ -public final class BoundedErrorBody { - - private final byte[] bytes; - private final boolean truncated; - - public BoundedErrorBody(byte[] bytes, boolean truncated) { - this.bytes = Objects.requireNonNull(bytes, "error body bytes").clone(); - this.truncated = truncated; - } - - public static BoundedErrorBody read(InputStream body, int maxBytes) throws IOException { - byte[] buffer = body.readNBytes(maxBytes); - boolean truncated = body.read() >= 0; - return new BoundedErrorBody(buffer, truncated); - } - - public static BoundedErrorBody empty() { - return new BoundedErrorBody(new byte[0], false); - } - - public byte[] bytes() { - return bytes.clone(); - } - - public boolean truncated() { - return truncated; - } - - public String utf8() { - return new String(bytes, StandardCharsets.UTF_8); - } - - @Override - public String toString() { - return "BoundedErrorBody[length=" + bytes.length + ", truncated=" + truncated + "]"; - } -} diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/spring7/HttpServiceGroupProfileResolver.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/spring7/HttpServiceGroupProfileResolver.java deleted file mode 100644 index 04590b04..00000000 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/spring7/HttpServiceGroupProfileResolver.java +++ /dev/null @@ -1,18 +0,0 @@ -package dev.caskeleton.adapter.outbound.httpclient.spring7; - -import dev.caskeleton.adapter.outbound.httpclient.api.ClientProfileName; -import java.util.Objects; - -/** - * Maps a Spring 7 HTTP Service Group name onto a Named Client Profile (design §26.4). - * - *

Group and profile share a name by construction, so a group cannot quietly acquire its own - * transport, timeout, or credential configuration parallel to the profile model. - */ -public final class HttpServiceGroupProfileResolver { - - public ClientProfileName resolve(String groupName) { - Objects.requireNonNull(groupName, "group name"); - return new ClientProfileName(groupName); - } -} diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/spring7/NamedHttpServiceGroupRegistrar.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/spring7/NamedHttpServiceGroupRegistrar.java deleted file mode 100644 index a6d031c3..00000000 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/spring7/NamedHttpServiceGroupRegistrar.java +++ /dev/null @@ -1,59 +0,0 @@ -package dev.caskeleton.adapter.outbound.httpclient.spring7; - -import dev.caskeleton.adapter.outbound.httpclient.api.ClientProfileName; -import dev.caskeleton.adapter.outbound.httpclient.service.ServiceOperationDescriptor; -import dev.caskeleton.adapter.outbound.httpclient.service.ServiceOperationDescriptorScanner; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; - -/** - * Registers several typed interfaces against one Named Client Profile (design §26.4). - * - *

Interface validation is delegated to the same scanner the Stable registries use, so a group - * cannot admit an interface the platform would otherwise reject. The group model adds grouping — - * not a second configuration system. - */ -public final class NamedHttpServiceGroupRegistrar { - - private final ServiceOperationDescriptorScanner scanner; - private final HttpServiceGroupProfileResolver profileResolver; - private final Map registeredGroups = new LinkedHashMap<>(); - private final Map, ClientProfileName> registeredInterfaces = new LinkedHashMap<>(); - - public NamedHttpServiceGroupRegistrar() { - this(new ServiceOperationDescriptorScanner(), new HttpServiceGroupProfileResolver()); - } - - public NamedHttpServiceGroupRegistrar( - ServiceOperationDescriptorScanner scanner, HttpServiceGroupProfileResolver profileResolver) { - this.scanner = Objects.requireNonNull(scanner, "descriptor scanner"); - this.profileResolver = Objects.requireNonNull(profileResolver, "profile resolver"); - } - - public void register(String groupName, Class... serviceTypes) { - Spring7GroupCompatibility.requireAvailable(); - ClientProfileName profileName = profileResolver.resolve(groupName); - registeredGroups.put(groupName, profileName); - for (Class serviceType : serviceTypes) { - List descriptors = scanner.scan(serviceType); - if (descriptors.isEmpty()) { - throw new IllegalStateException("group interface declares no operation: " + serviceType); - } - registeredInterfaces.put(serviceType, profileName); - } - } - - public ClientProfileName profileFor(Class serviceType) { - ClientProfileName profileName = registeredInterfaces.get(serviceType); - if (profileName == null) { - throw new IllegalStateException("interface is not registered in any group: " + serviceType); - } - return profileName; - } - - public Map groups() { - return Map.copyOf(registeredGroups); - } -} diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/spring7/Spring7GroupCompatibility.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/spring7/Spring7GroupCompatibility.java deleted file mode 100644 index bf20715b..00000000 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/spring7/Spring7GroupCompatibility.java +++ /dev/null @@ -1,30 +0,0 @@ -package dev.caskeleton.adapter.outbound.httpclient.spring7; - -import org.springframework.util.ClassUtils; - -/** - * Detects whether Spring 7's HTTP Service Group API is present (design D-17). - * - *

The common packages are written against the Spring 6.2 API surface; this module is the only - * place allowed to reference the Spring 7-only registry types, and the check keeps it inert on a - * 6.2 distribution instead of failing at class-load time. - */ -public final class Spring7GroupCompatibility { - - private static final String GROUP_REGISTRY_CLASS = - "org.springframework.web.service.registry.HttpServiceGroup"; - - private Spring7GroupCompatibility() {} - - public static boolean available() { - return ClassUtils.isPresent( - GROUP_REGISTRY_CLASS, Spring7GroupCompatibility.class.getClassLoader()); - } - - public static void requireAvailable() { - if (!available()) { - throw new IllegalStateException( - "spring 7 http service groups are not on the classpath; this module is optional by design"); - } - } -} diff --git a/src/adapter/outbound/httpclient/src/main/resources/config/module-defaults/httpclient.yml b/src/adapter/outbound/httpclient/src/main/resources/config/module-defaults/httpclient.yml new file mode 100644 index 00000000..8a74080f --- /dev/null +++ b/src/adapter/outbound/httpclient/src/main/resources/config/module-defaults/httpclient.yml @@ -0,0 +1,17 @@ +# 아웃바운드 HTTP client capability 설정 기본값. +# +# adapter:outbound:support 의 ModuleDefaultsEnvironmentPostProcessor 가 읽는다. 우선순위는 가장 낮아서 +# application*.yml, 환경 변수, 시스템 속성이 항상 이긴다. 이 모듈을 빌드에서 빼면 이 파일도 함께 +# 빠진다. +# +# capability switch 와 플랫폼 수준 값만 둔다. client 별 설정은 APP_HTTPCLIENT_CLIENTS_N_* 로 +# docs/httpclient/env-fields.yaml 에 따라 직접 바인딩된다. 이름 없는 list 원소를 YAML 에 두면 그 자체로 +# 잘못된 설정이 된다. +app: + httpclient: + # true | false — 모듈이 있으면 켜진다. false 로만 끈다. 켠 상태에서 client 가 하나도 없으면 + # HTTPCLIENT_ACTIVE_WITHOUT_CLIENTS 로 기동이 실패한다. + enabled: ${APP_HTTPCLIENT_ENABLED:true} + # client 별이 아니라 플랫폼 수준: 인증서 교체 뒤 은퇴한 runtime generation 이 pool 을 닫기 전까지 + # in-flight 요청을 비우는 시간. + rotation-drain-timeout: ${APP_HTTPCLIENT_ROTATION_DRAIN_TIMEOUT:30s} diff --git a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/architecture/PublicApiArchitectureTest.java b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/architecture/PublicApiArchitectureTest.java index 2aa907b1..f4960925 100644 --- a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/architecture/PublicApiArchitectureTest.java +++ b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/architecture/PublicApiArchitectureTest.java @@ -55,14 +55,22 @@ class PublicApiArchitectureTest { } @Test - void theSpring7ServiceGroupApiIsUsedOnlyInItsOwnPackage() { + void noClassUsesTheSpring7ServiceGroupApi() { ArchRuleDefinition.noClasses() - .that() - .resideOutsideOfPackage("..outbound.httpclient.spring7..") .should() .dependOnClassesThat() .resideInAPackage("org.springframework.web.service.registry..") - .as("Spring 7-only APIs stay in the optional module (design D-17)") + .as("Spring 7-only APIs are not used by the platform (design D-17)") + .check(PLATFORM); + } + + @Test + void noClassUsesRestTemplate() { + ArchRuleDefinition.noClasses() + .should() + .dependOnClassesThat() + .haveFullyQualifiedName("org.springframework.web.client.RestTemplate") + .as("RestTemplate is not used by the platform (design D-18)") .check(PLATFORM); } @@ -84,11 +92,6 @@ class PublicApiArchitectureTest { .and() .areDeclaredInClassesThat() .resideInAPackage("..outbound.httpclient..") - .and() - // The migration package exists to hand a RestClient to code being moved off RestTemplate; - // that is its stated purpose, and it is not a platform execution path. - .areDeclaredInClassesThat() - .resideOutsideOfPackage("..outbound.httpclient.migration..") .should() .haveRawReturnType( com.tngtech.archunit.core.domain.JavaClass.Predicates.assignableTo( @@ -113,10 +116,7 @@ class PublicApiArchitectureTest { .resideInAPackage("..outbound.httpclient..") .and() .resideOutsideOfPackages( - "..outbound.httpclient.restclient..", - "..outbound.httpclient.webclient..", - "..outbound.httpclient.migration..", - "..outbound.httpclient.spring7..") + "..outbound.httpclient.restclient..", "..outbound.httpclient.webclient..") .should() .dependOnClassesThat() .areAssignableTo(org.springframework.web.client.RestClient.class) @@ -127,8 +127,7 @@ class PublicApiArchitectureTest { .that() .resideInAPackage("..outbound.httpclient..") .and() - .resideOutsideOfPackages( - "..outbound.httpclient.webclient..", "..outbound.httpclient.spring7..") + .resideOutsideOfPackage("..outbound.httpclient.webclient..") .should() .dependOnClassesThat() .areAssignableTo(org.springframework.web.reactive.function.client.WebClient.class) diff --git a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientModuleDefaultsTest.java b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientModuleDefaultsTest.java new file mode 100644 index 00000000..4b79b1d0 --- /dev/null +++ b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientModuleDefaultsTest.java @@ -0,0 +1,39 @@ +package dev.caskeleton.adapter.outbound.httpclient.autoconfigure; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.adapter.outbound.support.startup.ModuleDefaultsEnvironmentPostProcessor; +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.springframework.boot.SpringApplication; +import org.springframework.core.env.MapPropertySource; +import org.springframework.core.env.StandardEnvironment; + +/** + * The module ships its settings under config/module-defaults, and a deployment's value beats them. + */ +class HttpClientModuleDefaultsTest { + + @Test + void theShippedDefaultsTurnThePlatformOn() { + StandardEnvironment environment = processed(Map.of()); + + assertThat(environment.getProperty("app.httpclient.enabled")).isEqualTo("true"); + assertThat(environment.getProperty("app.httpclient.rotation-drain-timeout")).isEqualTo("30s"); + } + + @Test + void theEnvironmentVariableTurnsItOff() { + StandardEnvironment environment = processed(Map.of("APP_HTTPCLIENT_ENABLED", "false")); + + assertThat(environment.getProperty("app.httpclient.enabled")).isEqualTo("false"); + } + + private static StandardEnvironment processed(Map deployment) { + StandardEnvironment environment = new StandardEnvironment(); + environment.getPropertySources().addFirst(new MapPropertySource("deployment", deployment)); + new ModuleDefaultsEnvironmentPostProcessor() + .postProcessEnvironment(environment, new SpringApplication()); + return environment; + } +} diff --git a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientPlatformActivationTest.java b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientPlatformActivationTest.java index 6336d847..24a27747 100644 --- a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientPlatformActivationTest.java +++ b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientPlatformActivationTest.java @@ -43,23 +43,45 @@ class HttpClientPlatformActivationTest { .withUserConfiguration(SupportingBeans.class); @Test - @DisplayName("an absent toggle holds no HTTP bean at all") - void theCapabilityIsAbsentUntilItIsExplicitlyEnabled() { + @DisplayName("present without the toggle is on") + void presentWithoutTheToggleIsOn() { + runner + .withPropertyValues(validPaymentClient()) + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context).hasSingleBean(ClientRuntimeRegistry.class); + }); + } + + @Test + @DisplayName("present with nothing configured refuses to start, naming the prefix") + void presentWithoutAnyClientFailsStartup() { runner.run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context).doesNotHaveBean(HttpClientPlatformSettings.class); - assertThat(context).doesNotHaveBean(ClientRuntimeRegistry.class); - assertThat(context).doesNotHaveBean(GenericHttpGateway.class); - assertThat(context).doesNotHaveBean(HttpServiceRegistry.class); - assertThat(context).doesNotHaveBean(ReactiveHttpServiceRegistry.class); - assertThat(context).doesNotHaveBean(ReactiveSseGateway.class); - assertThat(context).doesNotHaveBean(DynamicTargetGateway.class); - assertThat(context).doesNotHaveBean(ResilienceRegistry.class); - assertThat(context).doesNotHaveBean(CredentialProviderRegistry.class); - assertThat(context).doesNotHaveBean(TlsMaterialProvider.class); - assertThat(context).doesNotHaveBean(HttpClientActuatorEndpoint.class); - }); + context -> + assertThat(context).hasFailed().getFailure().hasStackTraceContaining("app.httpclient")); + } + + @Test + @DisplayName("a false toggle holds no HTTP bean at all") + void aFalseToggleHoldsNoHttpBean() { + runner + .withPropertyValues("app.httpclient.enabled=false") + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context).doesNotHaveBean(HttpClientPlatformSettings.class); + assertThat(context).doesNotHaveBean(ClientRuntimeRegistry.class); + assertThat(context).doesNotHaveBean(GenericHttpGateway.class); + assertThat(context).doesNotHaveBean(HttpServiceRegistry.class); + assertThat(context).doesNotHaveBean(ReactiveHttpServiceRegistry.class); + assertThat(context).doesNotHaveBean(ReactiveSseGateway.class); + assertThat(context).doesNotHaveBean(DynamicTargetGateway.class); + assertThat(context).doesNotHaveBean(ResilienceRegistry.class); + assertThat(context).doesNotHaveBean(CredentialProviderRegistry.class); + assertThat(context).doesNotHaveBean(TlsMaterialProvider.class); + assertThat(context).doesNotHaveBean(HttpClientActuatorEndpoint.class); + }); } @Test @@ -88,6 +110,7 @@ class HttpClientPlatformActivationTest { void detailSettingsAreNotBoundWhileTheCapabilityIsOff() { runner .withPropertyValues( + "app.httpclient.enabled=false", "app.httpclient.clients[0].name=payment", "app.httpclient.clients[0].timeout.total-call=not-a-duration", "app.httpclient.clients[0].transport=NOT_A_TRANSPORT", diff --git a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientPlatformEnvManifestTest.java b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientPlatformEnvManifestTest.java index c69b2cf2..4d9b87e9 100644 --- a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientPlatformEnvManifestTest.java +++ b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/autoconfigure/HttpClientPlatformEnvManifestTest.java @@ -129,11 +129,13 @@ class HttpClientPlatformEnvManifestTest { } @Test - @DisplayName("src/.env ships the platform disabled") - void theShippedEnvironmentKeepsThePlatformOff() { + @DisplayName("src/.env ships the master switch on, matching the module default") + void theShippedEnvironmentMatchesTheModuleDefault() { + // Present = on: a service that selected the module wants it, and the example must not undo + // that. assertThat(readLines(repositoryRoot().resolve("src/.env.example"))) - .as("src/.env must ship the master switch, and ship it off") - .anySatisfy(line -> assertThat(line.trim()).isEqualTo("APP_HTTPCLIENT_ENABLED=false")); + .as("src/.env must ship the master switch with the module's own default (true)") + .anySatisfy(line -> assertThat(line.trim()).isEqualTo("APP_HTTPCLIENT_ENABLED=true")); } /** Binds through the production binder, so the test exercises the real strictness rules. */ diff --git a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/migration/RestTemplateBoundaryTest.java b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/migration/RestTemplateBoundaryTest.java deleted file mode 100644 index ac0708d2..00000000 --- a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/migration/RestTemplateBoundaryTest.java +++ /dev/null @@ -1,45 +0,0 @@ -package dev.caskeleton.adapter.outbound.httpclient.migration; - -import com.tngtech.archunit.core.domain.JavaClasses; -import com.tngtech.archunit.lang.ArchRule; -import com.tngtech.archunit.lang.syntax.ArchRuleDefinition; -import dev.caskeleton.adapter.outbound.httpclient.architecture.PlatformClasses; -import org.junit.jupiter.api.Test; - -/** - * {@code RestTemplate} stays inside the migration package (design D-18, §31). - * - *

The rule lives in the test source set because ArchUnit is a test tool; the design forbids - * production modules from depending on test infrastructure. - */ -class RestTemplateBoundaryTest { - - private static final JavaClasses PLATFORM_CLASSES = PlatformClasses.production(); - - static ArchRule restTemplateIsConfinedToMigration() { - return ArchRuleDefinition.noClasses() - .that() - .resideOutsideOfPackage("..outbound.httpclient.migration..") - .should() - .dependOnClassesThat() - .haveFullyQualifiedName("org.springframework.web.client.RestTemplate") - .as("RestTemplate is permitted only inside the migration package (design D-18)"); - } - - @Test - void productionModulesCannotDependOnMigrationModule() { - restTemplateIsConfinedToMigration().check(PLATFORM_CLASSES); - } - - @Test - void migrationDoesNotReachIntoDynamicTargetOrHttp3() { - ArchRuleDefinition.noClasses() - .that() - .resideInAPackage("..outbound.httpclient.migration..") - .should() - .dependOnClassesThat() - .resideInAnyPackage("..outbound.httpclient.dynamic..", "..outbound.httpclient.http3..") - .as("the migration path must not expose new platform capabilities (design §26.5)") - .check(PLATFORM_CLASSES); - } -} diff --git a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/migration/RestTemplateToRestClientAdapterTest.java b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/migration/RestTemplateToRestClientAdapterTest.java deleted file mode 100644 index 002cfe85..00000000 --- a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/migration/RestTemplateToRestClientAdapterTest.java +++ /dev/null @@ -1,64 +0,0 @@ -package dev.caskeleton.adapter.outbound.httpclient.migration; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.outbound.httpclient.testkit.MockHttpServer; -import java.time.Duration; -import java.util.List; -import org.junit.jupiter.api.Test; -import org.springframework.http.client.SimpleClientHttpRequestFactory; -import org.springframework.web.client.RestClient; -import org.springframework.web.client.RestTemplate; - -class RestTemplateToRestClientAdapterTest { - - @Test - void preservesExistingMessageConvertersAndInterceptors() throws Exception { - try (MockHttpServer server = MockHttpServer.start()) { - server.enqueueJson(200, "\"ok\""); - RestTemplate template = new RestTemplate(); - template - .getInterceptors() - .add( - (request, body, execution) -> { - request.getHeaders().add("X-Correlation-Id", "abc"); - return execution.execute(request, body); - }); - - RestClient client = new RestTemplateToRestClientAdapter().adapt(template); - String body = client.get().uri(server.uri("/value")).retrieve().body(String.class); - - assertThat(body).isEqualTo("\"ok\""); - assertThat(server.takeRequest(Duration.ofSeconds(2)).firstHeader("X-Correlation-Id")) - .contains("abc"); - } - } - - @Test - void reportsTheSimpleRequestFactoryAsABlockingFinding() { - RestTemplate template = new RestTemplate(new SimpleClientHttpRequestFactory()); - RestTemplateInventory inventory = new RestTemplateInventoryScanner().scan(template); - - assertThat(inventory.findings()) - .extracting(MigrationFinding::code) - .contains("SIMPLE_REQUEST_FACTORY"); - assertThat(inventory.migratable()).isFalse(); - assertThatThrownBy(() -> new RestTemplateToRestClientAdapter().adaptChecked(template)) - .isInstanceOf(IllegalStateException.class); - } - - @Test - void inventoryRecordsTheCollaboratorsAMigrationMustPreserve() { - RestTemplate template = new RestTemplate(); - RestTemplateInventory inventory = new RestTemplateInventoryScanner().scan(template); - - assertThat(inventory.messageConverterTypes()).isNotEmpty(); - assertThat(inventory.errorHandlerType()).isNotBlank(); - assertThat(inventory.uriTemplateHandlerType()).isNotBlank(); - assertThat(inventory.findings()) - .extracting(MigrationFinding::code) - .contains("NO_INTERCEPTORS", "TIMEOUTS_NOT_INTROSPECTABLE"); - assertThat(List.copyOf(inventory.interceptorTypes())).isEmpty(); - } -} diff --git a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/spring7/NamedHttpServiceGroupRegistrarTest.java b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/spring7/NamedHttpServiceGroupRegistrarTest.java deleted file mode 100644 index 9692c041..00000000 --- a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/spring7/NamedHttpServiceGroupRegistrarTest.java +++ /dev/null @@ -1,39 +0,0 @@ -package dev.caskeleton.adapter.outbound.httpclient.spring7; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.outbound.httpclient.api.error.HttpConfigurationException; -import dev.caskeleton.adapter.outbound.httpclient.testkit.InvalidPostClient; -import dev.caskeleton.adapter.outbound.httpclient.testkit.UsersClient; -import org.junit.jupiter.api.Test; - -class NamedHttpServiceGroupRegistrarTest { - - @Test - void registersMultipleInterfacesAgainstOneNamedProfile() { - NamedHttpServiceGroupRegistrar registrar = new NamedHttpServiceGroupRegistrar(); - registrar.register("users", UsersClient.class); - - assertThat(registrar.profileFor(UsersClient.class).value()).isEqualTo("users"); - assertThat(registrar.groups()).containsKey("users"); - } - - @Test - void reusesTheSameInterfaceValidationAsTheStableRegistries() { - NamedHttpServiceGroupRegistrar registrar = new NamedHttpServiceGroupRegistrar(); - assertThatThrownBy(() -> registrar.register("users", InvalidPostClient.class)) - .isInstanceOf(HttpConfigurationException.class); - } - - @Test - void groupNameResolvesDirectlyToTheProfileName() { - assertThat(new HttpServiceGroupProfileResolver().resolve("catalog").value()) - .isEqualTo("catalog"); - } - - @Test - void theSpring7GroupApiIsPresentOnThisDistribution() { - assertThat(Spring7GroupCompatibility.available()).isTrue(); - } -} diff --git a/src/adapter/outbound/identifier/CLAUDE.md b/src/adapter/outbound/identifier/CLAUDE.md index c30c02f0..b33f69b0 100644 --- a/src/adapter/outbound/identifier/CLAUDE.md +++ b/src/adapter/outbound/identifier/CLAUDE.md @@ -18,19 +18,14 @@ build choices) live in [README.md](README.md). - Driven adapters for capabilities with **no external-system integration**: identifier generation/encoding today, and clock / crypto/random sources by the same rationale (feature-resource-identifier-contract §4 taxonomy). -- `UuidCodec` — UUID handling on top of the JDK `java.util.UUID` (RFC 9562 UUIDv7): - `normalize(String)` accepts a case-insensitive canonical UUID and returns the - canonical 36-character lowercase form (D3); `toUuid` / `fromUuid` convert between - the UUID string and the 128-bit `UUID` stored in the PostgreSQL `uuid` column (D10). +- `HmacUserPrincipalPseudonymizer` — `UserPrincipalPseudonymizerPort` implementation. - Kept out of `adapter-outbound` on purpose: a UUID id/codec capability is infrastructure, not an outbound integration point, so `adapter-outbound` keeps its documented meaning (external HTTP / messaging / cache / notifications). ## Allowed -- `:application-core`, `:domain-core`, `:shared-contract` (Gradle matrix). Currently - only `:domain-core` + `com.github.f4b6a3:uuid-creator` are declared in - [build.gradle](build.gradle). +- `:application-core` (declared in [build.gradle](build.gradle)); the registry entry is the SSOT. ## Forbidden @@ -43,7 +38,7 @@ build choices) live in [README.md](README.md). ## Test -Pure unit tests, no Spring context (`UuidCodecSpec`). +Pure unit tests, no Spring context (`HmacUserPrincipalPseudonymizerTest`). ```bash cd src diff --git a/src/adapter/outbound/identifier/README.md b/src/adapter/outbound/identifier/README.md index 215b177d..b9d9f4d6 100644 --- a/src/adapter/outbound/identifier/README.md +++ b/src/adapter/outbound/identifier/README.md @@ -14,15 +14,6 @@ crypto/random 소스. UUID id/코덱 능력은 인프라이지 아웃바운드 `adapter-outbound` 밖에 둬야 그 모듈의 문서화된 의미("외부 HTTP / messaging / cache / notifications")가 유지된다. -## UuidCodec - -도메인 무관 UUID 변환 유틸. JDK `java.util.UUID`(RFC 9562 UUIDv7) 위에서 동작한다. - -- `normalize(String)` — **D3**: 대소문자 무관 canonical UUID 입력을 받아 canonical 36자 소문자 - 형태로 반환. 형식 오류 UUID 에는 `IllegalArgumentException`. `null` 입력은 `null` 반환. -- `toUuid(String)` — **D10**: UUID 문자열 → 128-bit `UUID` (PostgreSQL `uuid` 컬럼용). -- `fromUuid(UUID)` — **D10**: 저장된 `UUID` → canonical 36자 소문자 UUID 문자열. - ## HmacUserPrincipalPseudonymizer `UserPrincipalPseudonymizerPort`(application-core) 의 HMAC-SHA-256 구현. @@ -52,21 +43,8 @@ salt 는 `app-bootstrap` 이 `APP_PRIVACY_PSEUDONYMIZATION_SALT` 환경변수에 ## 빌드 결정 (build.gradle) -### Groovy / Spock (C2 테스트 형태) -순수 값-코덱 동작(`UuidCodec`)은 Groovy/Spock 스펙(`src/test/groovy`)으로 명세한다. core `groovy` -플러그인이 컴파일하고, 모든 서브프로젝트에 이미 켜진 JUnit Platform(`useJUnitPlatform()`)에서 실행된다. -가드/계약 테스트(`HmacUserPrincipalPseudonymizerTest` — 생성자 가드, 정확한 예외/포맷 계약)는 설계상 -Java(`src/test/java`)로 둔다. Spock 2.4 / Groovy 4.0 variant 를 쓰며, spock-core 가 groovy.jar 를 -transitive 로 끌어오므로 data-driven `where:` 스펙에 다른 Groovy 모듈이 필요 없다. - ### implementation vs api `:application-core` 를 `implementation` 으로 선언한다(`api` 아님). adapter-identifier 가 자신의 public ABI 에 application-core 타입을 노출하지 않기 때문이다. 유일한 와이어링 소비자인 `app-bootstrap` 은 이미 자기 classpath 에 application-core 를 갖고 있다. 이 의존 edge 는 `src/build.gradle` 의 `allowedProjectDependencies['adapter-identifier']` 로 허용된다. - -### UTF-8 인코딩 고정 -한국어(비-ASCII) Spock 스펙 메서드명은 소스를 UTF-8 로 읽어야만 컴파일·리포팅이 정상이다. 이 모듈이 -비-ASCII 소스를 처음 갖는 모듈이라 컴파일 인코딩을 명시적으로 고정한다 — UTF-8 호스트에선 no-op 지만, -플랫폼 기본이 다른 fork(예: 한국어 Windows / MS949)에서 mojibake 빌드를 막는다. C2 가 더 많은 모듈로 -퍼지면 root subprojects 블록(`-parameters` 옆)으로 승격한다. diff --git a/src/adapter/outbound/identifier/src/main/java/dev/caskeleton/adapter/outbound/identifier/UuidCodec.java b/src/adapter/outbound/identifier/src/main/java/dev/caskeleton/adapter/outbound/identifier/UuidCodec.java deleted file mode 100644 index a050a2c8..00000000 --- a/src/adapter/outbound/identifier/src/main/java/dev/caskeleton/adapter/outbound/identifier/UuidCodec.java +++ /dev/null @@ -1,30 +0,0 @@ -package dev.caskeleton.adapter.outbound.identifier; - -import java.util.UUID; - -/** Domain-agnostic UUID conversion utility. See README for the design rationale. */ -public final class UuidCodec { - - private UuidCodec() {} - - /** - * Accepts a case-insensitive canonical UUID string and returns the canonical 36-character - * lowercase form; {@code null} input returns {@code null}. - * - * @throws IllegalArgumentException on a malformed UUID - */ - public static String normalize(String input) { - if (input == null) { - return null; - } - return UUID.fromString(input).toString(); - } - - public static UUID toUuid(String uuidString) { - return UUID.fromString(uuidString); - } - - public static String fromUuid(UUID uuid) { - return uuid.toString(); - } -} diff --git a/src/adapter/outbound/identifier/src/test/java/dev/caskeleton/adapter/outbound/identifier/UuidCodecTest.java b/src/adapter/outbound/identifier/src/test/java/dev/caskeleton/adapter/outbound/identifier/UuidCodecTest.java deleted file mode 100644 index a5c7aa60..00000000 --- a/src/adapter/outbound/identifier/src/test/java/dev/caskeleton/adapter/outbound/identifier/UuidCodecTest.java +++ /dev/null @@ -1,34 +0,0 @@ -package dev.caskeleton.adapter.outbound.identifier; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; - -import java.util.Locale; -import org.junit.jupiter.api.Test; - -class UuidCodecTest { - private static final String CANONICAL = "0190bd6e-7c3e-7abc-8def-0123456789ab"; - - @Test - void normalizeProducesLowercaseCanonicalUuid() { - assertEquals(CANONICAL, UuidCodec.normalize(CANONICAL)); - assertEquals(CANONICAL, UuidCodec.normalize(CANONICAL.toUpperCase(Locale.ROOT))); - } - - @Test - void normalizeReturnsNullForNullInput() { - assertNull(UuidCodec.normalize(null)); - } - - @Test - void normalizeRejectsMalformedUuid() { - assertThrows(IllegalArgumentException.class, () -> UuidCodec.normalize("not-a-uuid")); - } - - @Test - void uuidRoundTripIsLossless() { - var uuid = UuidCodec.toUuid(CANONICAL); - assertEquals(CANONICAL, UuidCodec.fromUuid(uuid)); - } -} diff --git a/src/adapter/outbound/messaging-kafka/README.md b/src/adapter/outbound/messaging-kafka/README.md new file mode 100644 index 00000000..6aa49219 --- /dev/null +++ b/src/adapter/outbound/messaging-kafka/README.md @@ -0,0 +1,54 @@ +# adapter:outbound:messaging-kafka — Kafka 발행 capability + +- Module ID: `adapter-outbound-messaging-kafka` +- Gradle path: `:adapter:outbound:messaging-kafka` +- Package: `dev.caskeleton.adapter.outbound.messaging.kafka` +- 테스트: `./gradlew :adapter:outbound:messaging-kafka:test --console=plain` + +## 제공하는 것 + +이 모듈 하나를 붙이면 Kafka 발행이 들어온다. 유스케이스는 application-core 포트만 호출한다. + +``` +adapter:outbound:messaging-kafka + ├─ LegacyKafkaMessagingRootAutoConfiguration KafkaSender seam + KafkaMessageBroker + ├─ config/module-defaults/messaging.yml (설정 기본값, support 로더가 읽음) + ├─ adapter:outbound:messaging MessagePublisher, OutboxMessagePublishPort, + │ IntegrationEventPublishPort bridge + └─ messaging:messaging-spring-boot-starter-kafka messaging platform + Kafka transport +``` + +| 포트 (application-core) | 구현 | +| --- | --- | +| `OutboxMessagePublishPort` | legacy outbox row → `KafkaMessageBroker`, canonical row → `IntegrationEventPublishPort` | +| `IntegrationEventPublishPort` | platform `EncodedMessagePublisher` (`APP_MESSAGING_PRODUCER_ID`가 있을 때만) | +| `OutboxRelayFailureReportPort` | 구조화 로그 | + +- 켜기와 끄기: 모듈이 있으면 켜진다. `APP_MESSAGING_ENABLED=false`로만 끈다. 끄면 messaging bean, + Kafka producer, 스레드가 하나도 생기지 않는다. +- 설정: `config/module-defaults/messaging.yml`을 support의 `ModuleDefaultsEnvironmentPostProcessor`가 읽는다. 우선순위가 가장 낮아서 `application*.yml`, + 환경 변수, 시스템 속성이 항상 이긴다. app-bootstrap은 이 파일을 모른다. +- broker 주소 하나(`APP_MESSAGING_KAFKA_BROKERS`)가 legacy seam(`app.messaging.kafka.brokers`)과 + platform transport(`spring.kafka.bootstrap-servers`) 양쪽에 들어간다. + +## 추가할 한 줄 + +```groovy +// app-bootstrap/build.gradle +runtimeOnly project(':adapter:outbound:messaging-kafka') // Kafka 발행 +``` + +이 줄을 지우면 발행 포트 구현, Kafka client, messaging platform, 설정 기본값이 모두 함께 빠진다. + +## 필요한 env 키 + +전체 목록과 타입은 `docs/registries/env-keys.yaml`의 `APP_MESSAGING_*` 행이 SSOT다. + +| 언제 | 키 | +| --- | --- | +| 항상 | `APP_MESSAGING_KAFKA_BROKERS` (CSV `host:port`). 비어 있으면 기동이 실패한다 | +| canonical integration event를 보낼 때 | `APP_MESSAGING_PRODUCER_ID` (배포와 무관한 논리적 서비스 이름) | +| 끌 때 | `APP_MESSAGING_ENABLED=false` | + +`APP_MESSAGING_BROKER`는 기본값이 `kafka`다. 등록된 broker가 Kafka 하나라 바꿀 일이 없다. +destination·broker profile·보안 설정은 `docs/messaging/configuration-reference.md`. diff --git a/src/adapter/outbound/messaging-kafka/build.gradle b/src/adapter/outbound/messaging-kafka/build.gradle index 962bae82..ea1bd4e9 100644 --- a/src/adapter/outbound/messaging-kafka/build.gradle +++ b/src/adapter/outbound/messaging-kafka/build.gradle @@ -3,9 +3,37 @@ plugins { id 'ca.spring-config' } +// The Kafka capability, selected by one line in app-bootstrap: +// +// runtimeOnly project(':adapter:outbound:messaging-kafka') +// +// That line brings the broker-neutral application bridge (adapter:outbound:messaging), the legacy +// KafkaSender seam in this leaf, the vendored messaging platform with its Kafka transport, and the +// capability's settings (config/module-defaults/messaging.yml). Deleting it removes all of them. + +// Every project shares the group dev.caskeleton, and the vendored transport is also named +// messaging-kafka (:messaging:messaging-kafka). Same group and name is the same module to Gradle, +// which silently substituted this project for the vendored one wherever both were reachable, so the +// platform's Kafka transport classes went missing at runtime. A group of its own keeps them apart. +group = 'dev.caskeleton.adapter' +// And a jar file name of its own: a Boot jar stores libraries in BOOT-INF/lib/ by file name, so the +// two messaging-kafka-.jar collided and an application selecting this leaf could not be +// packaged. +base { + archivesName = 'adapter-outbound-messaging-kafka' +} + dependencies { implementation project(':adapter:outbound:messaging') implementation 'org.apache.kafka:kafka-clients' implementation 'org.springframework.boot:spring-boot-autoconfigure' + + // The platform publisher behind the canonical IntegrationEventPublishPort bridge. Runtime only: + // this leaf names none of its types; the bridge reaches it through EncodedMessagePublisher. + runtimeOnly project(':messaging:messaging-spring-boot-starter-kafka') + + // The activation test boots the whole capability and names the ports it must produce. + testImplementation project(':application-core') + testImplementation project(':messaging:messaging-schema-api') } diff --git a/src/adapter/outbound/messaging-kafka/gradle.lockfile b/src/adapter/outbound/messaging-kafka/gradle.lockfile index 30e34afd..7eb9ad07 100644 --- a/src/adapter/outbound/messaging-kafka/gradle.lockfile +++ b/src/adapter/outbound/messaging-kafka/gradle.lockfile @@ -5,7 +5,6 @@ at.yawk.lz4:lz4-java:1.10.1=runtimeClasspath,testRuntimeClasspath biz.aQute.bnd:biz.aQute.bnd.annotation:7.1.0=testCompileClasspath ch.qos.logback:logback-classic:1.5.38=runtimeClasspath,testCompileClasspath,testRuntimeClasspath ch.qos.logback:logback-core:1.5.38=runtimeClasspath,testCompileClasspath,testRuntimeClasspath -com.ethlo.time:itu:1.14.0=runtimeClasspath,testRuntimeClasspath com.fasterxml.jackson.core:jackson-annotations:2.21=runtimeClasspath,testCompileClasspath,testRuntimeClasspath com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,testAnnotationProcessor com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,testAnnotationProcessor @@ -34,7 +33,6 @@ com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,testAnno com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,testAnnotationProcessor com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins com.jayway.jsonpath:json-path:2.10.0=testCompileClasspath,testRuntimeClasspath -com.networknt:json-schema-validator:3.0.2=runtimeClasspath,testRuntimeClasspath com.puppycrawl.tools:checkstyle:13.5.0=checkstyle com.vaadin.external.google:android-json:0.0.20131108.vaadin1=testCompileClasspath,testRuntimeClasspath commons-beanutils:commons-beanutils:1.11.0=checkstyle @@ -45,7 +43,9 @@ 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 io.micrometer:micrometer-commons:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +io.micrometer:micrometer-core:1.16.7=runtimeClasspath,testRuntimeClasspath io.micrometer:micrometer-observation:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +io.projectreactor:reactor-core:3.8.7=runtimeClasspath,testRuntimeClasspath jakarta.activation:jakarta.activation-api:2.1.4=testCompileClasspath,testRuntimeClasspath jakarta.annotation:jakarta.annotation-api:3.0.0=runtimeClasspath,testCompileClasspath,testRuntimeClasspath jakarta.xml.bind:jakarta.xml.bind-api:4.0.5=testCompileClasspath,testRuntimeClasspath @@ -84,6 +84,7 @@ org.codehaus.plexus:plexus-container-default:2.1.0=checkstyle org.codehaus.plexus:plexus-utils:3.3.0=checkstyle org.dom4j:dom4j:2.2.0=spotbugs org.hamcrest:hamcrest:3.0=testCompileClasspath,testRuntimeClasspath +org.hdrhistogram:HdrHistogram:2.2.2=runtimeClasspath,testRuntimeClasspath org.javassist:javassist:3.28.0-GA=checkstyle org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,compileClasspath,runtimeClasspath,testAnnotationProcessor,testCompileClasspath,testRuntimeClasspath org.junit.jupiter:junit-jupiter-api:6.0.3=testCompileClasspath,testRuntimeClasspath @@ -95,6 +96,7 @@ 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.1.0=spotbugs +org.latencyutils:LatencyUtils:2.0.3=runtimeClasspath,testRuntimeClasspath org.mockito:mockito-core:5.20.0=mockitoAgent,testCompileClasspath,testRuntimeClasspath org.mockito:mockito-junit-jupiter:5.20.0=testCompileClasspath,testRuntimeClasspath org.objenesis:objenesis:3.3=testRuntimeClasspath @@ -110,12 +112,14 @@ org.ow2.asm:asm-util:9.10.1=spotbugs org.ow2.asm:asm:9.10.1=spotbugs org.ow2.asm:asm:9.7.1=testCompileClasspath,testRuntimeClasspath org.pcollections:pcollections:4.0.1=annotationProcessor,testAnnotationProcessor +org.reactivestreams:reactive-streams:1.0.4=runtimeClasspath,testRuntimeClasspath org.reflections:reflections:0.10.2=checkstyle org.skyscreamer:jsonassert:1.5.3=testCompileClasspath,testRuntimeClasspath org.slf4j:jul-to-slf4j:2.0.18=runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.slf4j:slf4j-api:2.0.18=runtimeClasspath,spotbugs,spotbugsSlf4j,testCompileClasspath,testRuntimeClasspath org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j org.slf4j:slf4j-simple:2.0.18=checkstyle +org.springframework.boot:spring-boot-actuator:4.0.8=runtimeClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-autoconfigure:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-configuration-processor:4.0.8=annotationProcessor org.springframework.boot:spring-boot-http-converter:4.0.8=testCompileClasspath,testRuntimeClasspath @@ -144,7 +148,9 @@ org.springframework:spring-beans:7.0.9=compileClasspath,runtimeClasspath,testCom org.springframework:spring-context:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework:spring-core:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework:spring-expression:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-jdbc:7.0.9=runtimeClasspath,testRuntimeClasspath org.springframework:spring-test:7.0.9=testCompileClasspath,testRuntimeClasspath +org.springframework:spring-tx:7.0.9=runtimeClasspath,testRuntimeClasspath org.springframework:spring-web:7.0.9=testCompileClasspath,testRuntimeClasspath org.springframework:spring-webmvc:7.0.9=testCompileClasspath,testRuntimeClasspath org.xerial.snappy:snappy-java:1.1.10.7=runtimeClasspath,testRuntimeClasspath diff --git a/src/adapter/outbound/messaging-kafka/src/main/java/dev/caskeleton/adapter/outbound/messaging/kafka/LegacyKafkaMessagingRootAutoConfiguration.java b/src/adapter/outbound/messaging-kafka/src/main/java/dev/caskeleton/adapter/outbound/messaging/kafka/LegacyKafkaMessagingRootAutoConfiguration.java index e09bc150..6cddad81 100644 --- a/src/adapter/outbound/messaging-kafka/src/main/java/dev/caskeleton/adapter/outbound/messaging/kafka/LegacyKafkaMessagingRootAutoConfiguration.java +++ b/src/adapter/outbound/messaging-kafka/src/main/java/dev/caskeleton/adapter/outbound/messaging/kafka/LegacyKafkaMessagingRootAutoConfiguration.java @@ -9,9 +9,13 @@ import org.springframework.context.annotation.Import; * *

The broker-neutral messaging bridge no longer imports Kafka classes. An application that still * needs the R0 Kafka seam must deliberately add this leaf; only then can the Kafka producer/client - * enter its runtime graph. + * enter its runtime graph. Present means on; {@code app.messaging.enabled=false} turns it off. */ @AutoConfiguration -@ConditionalOnProperty(prefix = "app.messaging", name = "enabled", havingValue = "true") +@ConditionalOnProperty( + prefix = "app.messaging", + name = "enabled", + havingValue = "true", + matchIfMissing = true) @Import({KafkaSenderAutoConfiguration.class, KafkaAdapterConfig.class}) public class LegacyKafkaMessagingRootAutoConfiguration {} diff --git a/src/adapter/outbound/messaging-kafka/src/main/resources/config/module-defaults/messaging.yml b/src/adapter/outbound/messaging-kafka/src/main/resources/config/module-defaults/messaging.yml new file mode 100644 index 00000000..3dfa8d69 --- /dev/null +++ b/src/adapter/outbound/messaging-kafka/src/main/resources/config/module-defaults/messaging.yml @@ -0,0 +1,23 @@ +# Kafka capability 설정 기본값. +# +# adapter:outbound:support 의 ModuleDefaultsEnvironmentPostProcessor 가 읽는다. 우선순위는 가장 낮아서 +# application*.yml, 환경 변수, 시스템 속성이 항상 이긴다. 이 모듈을 빌드에서 빼면 이 파일도 함께 +# 빠진다. +app: + messaging: + # true | false — 모듈이 있으면 켜진다. false 로만 끈다. + enabled: ${APP_MESSAGING_ENABLED:true} + # 이 모듈을 고른 서비스는 Kafka 를 쓴다. 등록된 broker 는 kafka 하나다. + broker: ${APP_MESSAGING_BROKER:kafka} + # canonical IntegrationEventPublishPort bridge 의 producer id. 비어 있으면 bridge 가 없다. + # host/pod/process 이름에서 추측하지 않는다. + producer-id: ${APP_MESSAGING_PRODUCER_ID:} + kafka: + # CSV host:port. legacy KafkaSender seam 이 쓴다. 켠 상태에서 비어 있으면 기동이 실패한다. + brokers: ${APP_MESSAGING_KAFKA_BROKERS:} + +spring: + kafka: + # 같은 broker 주소를 messaging platform 의 Kafka transport 에도 준다. 키 하나로 두 경로가 같은 + # 클러스터를 본다. SPRING_KAFKA_BOOTSTRAP_SERVERS 를 직접 주면 그 값이 이긴다. + bootstrap-servers: ${APP_MESSAGING_KAFKA_BROKERS:} diff --git a/src/adapter/outbound/messaging-kafka/src/test/java/dev/caskeleton/adapter/outbound/messaging/kafka/KafkaCapabilityActivationTest.java b/src/adapter/outbound/messaging-kafka/src/test/java/dev/caskeleton/adapter/outbound/messaging/kafka/KafkaCapabilityActivationTest.java new file mode 100644 index 00000000..c5e30f2f --- /dev/null +++ b/src/adapter/outbound/messaging-kafka/src/test/java/dev/caskeleton/adapter/outbound/messaging/kafka/KafkaCapabilityActivationTest.java @@ -0,0 +1,85 @@ +package dev.caskeleton.adapter.outbound.messaging.kafka; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import dev.caskeleton.adapter.outbound.messaging.core.DisabledMessagePublisher; +import dev.caskeleton.adapter.outbound.messaging.core.MessageBroker; +import dev.caskeleton.adapter.outbound.messaging.core.MessagePublisher; +import dev.caskeleton.adapter.outbound.messaging.core.OutboundMessagePublisher; +import dev.caskeleton.adapter.outbound.messaging.outbox.OutboxMessagePublishAdapter; +import dev.caskeleton.application.messaging.event.IntegrationEventPublishPort; +import dev.caskeleton.application.outbox.OutboxMessagePublishPort; +import dev.caskeleton.messaging.schema.EncodedMessagePublisher; +import java.util.Arrays; +import org.junit.jupiter.api.Test; +import org.springframework.boot.WebApplicationType; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.annotation.Configuration; + +/** + * The capability as an application gets it: this module on the classpath, auto-configuration on. + * + *

Boots a real {@code SpringApplication} rather than a context runner, because the module's + * settings arrive through its environment post-processor, which a context runner never calls. + */ +class KafkaCapabilityActivationTest { + + @Test + void presentModuleIsOnAndPublishesThroughKafka() { + // given — only the broker address; everything else is the module's own default + try (ConfigurableApplicationContext context = + start("--APP_MESSAGING_KAFKA_BROKERS=localhost:1", "--APP_MESSAGING_PRODUCER_ID=orders")) { + + // then + assertThat(context.getBean(MessageBroker.class)).isInstanceOf(KafkaMessageBroker.class); + assertThat(context.getBean(MessagePublisher.class)) + .isInstanceOf(OutboundMessagePublisher.class); + assertThat(context.getBean(OutboxMessagePublishPort.class)) + .isInstanceOf(OutboxMessagePublishAdapter.class); + assertThat(context.getBeanNamesForType(EncodedMessagePublisher.class)).hasSize(1); + assertThat(context.getBeanNamesForType(IntegrationEventPublishPort.class)).hasSize(1); + } + } + + @Test + void presentModuleWithoutABrokerAddressRefusesToStart() { + assertThatThrownBy(() -> start().close()) + .satisfiesAnyOf( + failure -> + assertThat(failure).hasStackTraceContaining("spring.kafka.bootstrap-servers"), + failure -> assertThat(failure).hasStackTraceContaining("app.messaging.kafka.brokers")); + } + + @Test + void switchedOffHoldsNoMessagingBean() { + try (ConfigurableApplicationContext context = start("--APP_MESSAGING_ENABLED=false")) { + assertThat( + Arrays.stream(context.getBeanDefinitionNames()) + .map(name -> context.getBeanFactory().getType(name, false)) + .filter(type -> type != null && type != Application.class) + .map(Class::getName) + .filter( + name -> + name.startsWith("dev.caskeleton.messaging.") + || name.startsWith("dev.caskeleton.adapter.outbound.messaging.") + || name.startsWith("org.apache.kafka."))) + .isEmpty(); + assertThat(context.getBeanNamesForType(DisabledMessagePublisher.class)).isEmpty(); + } + } + + private static ConfigurableApplicationContext start(String... arguments) { + return new SpringApplicationBuilder(Application.class) + .web(WebApplicationType.NONE) + .logStartupInfo(false) + .run(arguments); + } + + // Nothing else: the module brings the shared outbound helpers it needs. + @Configuration(proxyBeanMethods = false) + @EnableAutoConfiguration + static class Application {} +} diff --git a/src/adapter/outbound/messaging/CLAUDE.md b/src/adapter/outbound/messaging/CLAUDE.md index 739da5ce..6819c1fd 100644 --- a/src/adapter/outbound/messaging/CLAUDE.md +++ b/src/adapter/outbound/messaging/CLAUDE.md @@ -13,13 +13,7 @@ Package root: `dev.caskeleton.adapter.outbound.messaging`. ## Responsibility - Implement outbound message publication and broker integration behind application/domain ports. -- Own broker settings, serialization envelope, disabled/fail-safe technical modes, and outbox - publication adaptation. -- Own the closed local contract/destination/capability binding compiler, stable catalog/settings/ - schema digests, and deterministic partition-key algorithm. Physical topics and bootstrap servers - stay in deployment settings and compiled outbound bindings. -- Own the deterministic UTF-8 envelope writer and exact-resource Draft 2020-12 registry. Schema - validation is local and precompiled; YAML and runtime network/filesystem resolution are forbidden. +- Own broker settings, disabled/fail-safe technical modes, and outbox publication adaptation. - Own structured rendering of `OutboxRelayFailureReport` through the single unconditional `Slf4jOutboxRelayFailureReportAdapter` bean. - Reuse `adapter:outbound:support` for shared technical concerns. @@ -36,42 +30,13 @@ Package root: `dev.caskeleton.adapter.outbound.messaging`. compatibility only. Do not route new canonical integration-event publication through them. - Canonical producer identity is explicit `app.messaging.producer-id`; never derive it from `spring.application.name`, host, pod, or process identity. -- Contract compilation accepts only explicitly supplied application SPI contributions; do not scan, - import sample payload classes, use `Class.forName`, or discover contracts from raw JSON/tree data. -- Snapshot each contribution accessor exactly once. Compiled contracts/publication bindings have - no public constructor and ACTIVE descriptors are created only through the canonical compile path. -- Keep adapter-local compiler/card/binding types off public instance return surfaces. Use - package-private accessors and narrowly scoped public static composition bridges; expose only - primitive/String/core values from public instance methods. -- `DISABLED` with an empty catalog/binding is a zero-resource state. The R1 compiler is intentionally - not wired to legacy `MessagingConfig`; it must not claim Kafka ACK, wire compatibility, - `ACTIVE_READY`, or R2 qualification. -- The local encoder accepts only exact registered final payload records and a closed value - vocabulary. No `Map`, raw JSON/tree, polymorphic type or custom serializer input is allowed. -- Compile and freeze the complete declared payload generic graph before encoding. Allow only the - closed scalar/enum vocabulary, `Optional`, `List`, and exact final nested records; reject - open/raw/wildcard/interface/tree types and runtime record discovery. -- Snapshot every payload record accessor exactly once, encode the payload once, and reuse those - exact trusted bytes for payload-schema validation and envelope embedding. Do not add a raw JSON - parser/generator injection path. -- Apply decimal/list/output admission before unbounded allocation: bound plain decimal digits - before `toPlainString`, check list size before bounded iteration without `toArray`, fail closed on - mutation/concurrency, and enforce output bytes while the generator writes. -- Keep the nine exact checked-in Draft 2020-12 schema/meta bytes and digests synchronized. Startup - compares those bytes, IDs, and NetworkNT runtime schema trees without assuming the validator's - `CodeSource` is a regular JAR. Strict dependency locks and `verifyDependencyPolicy` own the - NetworkNT 3.0.2 artifact provenance. -- Permit only lowercase exact `urn` root `$id` and absolute `$ref` schemes. Reject every - root-external nested `$id` key regardless of value type, and reject `$dynamicRef`, - `$dynamicAnchor`, deprecated `$recursiveRef`/`$recursiveAnchor`, and `$anchor` anywhere in the - Task 6 closed subset. -- Keep common evidence validation in test/build qualification code: validate exact schema and - generated manifest bytes with the pinned NetworkNT/`LocalJsonSchemaRegistry`, retain schema - meta-validation, and order JSON-only evidence before combined contract evidence so the combined - manifest deterministically owns the shared output. -- The adopted JDK regex engine has no proven execution timeout. Keep regex input and document - budgets finite, retain the adversarial corpus, and preserve the explicit unsupported evidence - claim until a separately reviewed bounded engine or isolation policy exists. +- The template ships no `IntegrationEventEncoderPort` implementation. The R1 contract compiler, + binding compiler, JSON Schema envelope encoder and capability card registry (`contract/`, + `destination/`, `envelope/`, `config/`) and the durable realtime fan-out adapter (`realtime/`) + were removed on 2026-09-25 (see `docs/capability-status.md`); an adopter that turns on canonical + transport provides its own encoder. +- No JSON Schema engine (NetworkNT) here. The evidence manifest schema check moved to build-tools + (`VerifyMessagingEvidenceTask`). - Do not hide use-case sequencing or business routing policy in broker adapters. - `OutboxMessagePublishAdapter` is mapping/send-only and emits no dependency log. The confirmed FAILED/DEAD transition owns the one canonical ERROR; only the general fail-open publisher keeps diff --git a/src/adapter/outbound/messaging/README.md b/src/adapter/outbound/messaging/README.md index 7f486fb7..8678c3fe 100644 --- a/src/adapter/outbound/messaging/README.md +++ b/src/adapter/outbound/messaging/README.md @@ -12,8 +12,11 @@ correlation / fail-open 의존성 로깅을 일반 publisher에서 재사용한 ## 모듈 개요 application-core의 legacy 포트(`MessagePublisher` / `OutboxMessagePublishPort`)와 canonical -`IntegrationEventPublishPort` 뒤에 두는 **선택형** 연동 어댑터다. `@ConditionalOnProperty` 로 -게이팅되고 기본 비활성이며, legacy 비활성 바인딩은 `Disabled*` 구현으로 fail-fast 한다(Layer 3). +`IntegrationEventPublishPort` 뒤에 두는 **선택형** 연동 어댑터다. 서비스는 이 모듈을 직접 고르지 않고 +`runtimeOnly project(':adapter:outbound:messaging-kafka')` 한 줄로 받는다(추가할 한 줄·env 키는 +[messaging-kafka README](../messaging-kafka/README.md)). 모듈이 있으면 켜지고 +`app.messaging.enabled=false`로만 끈다. broker가 없을 때의 legacy 바인딩은 `Disabled*` 구현으로 +fail-fast 한다(Layer 3). canonical path는 `platformbridge/PlatformIntegrationEventPublishAdapter`가 `EncodedMessagePublisher`에 위임한다. 이 path는 broker SDK나 transport SPI를 직접 보지 않는다. @@ -43,10 +46,12 @@ broker requirement도 유지한다. `app.messaging.broker` 가 설정됐는데 `MessageBroker` 빈이 없으면 startup 을 명시적 메시지로 실패시킨다(조용한 no-op 아님). settings 와 활성 빈의 `brokerId()` 불일치도 startup 실패다. -## 비활성 sentinel 두 개를 분리한 이유 +## outbox 발행 포트에는 대역이 없다 -`DisabledMessagePublisher` 와 `DisabledOutboxMessagePublisher` 는 별도 클래스다 — 한 클래스가 -두 포트를 모두 구현하면 `getBean(MessagePublisher.class)` 가 모호해진다. +`OutboxMessagePublishPort`의 대역(항상 던지는 publisher)은 두지 않는다. 대역도 bean이므로 relay +스케줄러의 조건을 채우고, relay는 모든 PENDING 행을 그 대역에 실패시켜 DEAD로 소진한다. 그래서 +모듈이 있고 켜져 있는데 broker가 비어 있고 canonical transport도 없으면 startup을 거부한다. +`DisabledMessagePublisher`(일반 발행기의 fail-fast 대역)는 남아 있다 — relay가 쓰지 않는다. ## OutboxEnvelopeJson — 손수 짠 JSON @@ -69,9 +74,9 @@ broker requirement도 유지한다. `PUBLISHED`를 기록한다. sender 예외는 fail-closed outbox 경로에서 전파되어 relay의 `FAILED/DEAD` 전이를 유발한다. -broker 설정이 blank면 두 포트는 각각 `DisabledMessagePublisher`와 -`DisabledOutboxMessagePublisher`에 바인딩된다. broker를 선택했지만 project-supplied sender가 -없거나 선택 ID와 활성 `MessageBroker.brokerId()`가 다르면 startup이 실패한다. +broker 설정이 blank면 `MessagePublisher`는 `DisabledMessagePublisher`에 바인딩되고, canonical +transport도 없으면 startup이 실패한다. broker를 선택했지만 project-supplied sender가 없거나 선택 +ID와 활성 `MessageBroker.brokerId()`가 다르면 startup이 실패한다. publisher 정상 반환 뒤 DB mark가 실패하면 row는 `IN_FLIGHT`에 남아 timeout reclaim 후 같은 event가 다시 publish될 수 있다. 현재 consumer/inbox가 없으므로 이 duplicate 가능 구간을 @@ -92,86 +97,24 @@ payload/idempotency key/envelope/exception-derived field는 받거나 렌더링 붙인다. logging 내부 `RuntimeException`은 adapter와 use case 양쪽에서 방어하므로 persisted FAILED/DEAD outcome을 바꾸지 않는다. -## Closed local binding compiler R1 +## 제거된 R1 encoder 체인 (2026-09-25) -`contract`, `destination`, `config` package는 명시적으로 주입된 -`IntegrationEventContractContribution` 목록만 사용해 contract catalog와 deployment binding을 -로컬에서 컴파일한다. payload record의 exact `Class` token, 선언 순서, schema resource/hash를 -검증하며 scan, `Class.forName`, assignable discovery, raw JSON/tree discovery를 하지 않는다. -catalog/settings/schema digest는 정렬된 semantic identity와 length-prefixed UTF-8/raw SHA-256 -bytes로 계산한다. +`contract`·`destination`·`config`(로컬 contract/binding 컴파일러, capability card registry), +`envelope`(결정적 JSON Schema envelope encoder, `LocalJsonSchemaRegistry`, pin한 Draft 2020-12 +meta-schema), `realtime`(durable fan-out adapter)은 조립하는 곳이 없어 삭제했다. 복구 경로는 +`docs/capability-status.md`의 제거 표에 있다. 그 결과 NetworkNT는 이 leaf의 production 의존성이 +아니다. -physical topic과 bootstrap server는 `DestinationBindingSettings`와 -`CompiledPublicationBinding`에만 존재한다. application contract에는 broker, topic, credential -설정이 유출되지 않는다. logical destination과 physical topic은 각각 deployment 안에서 unique다. -compiled publication binding은 package-local compiler만 만들 수 있고 active descriptor는 public -static compile 경로로만 생성한다. compiled integration-event contract도 catalog compiler만 -package-local constructor로 만들 수 있다. partition key v1은 canonical non-null tenant scope, -logical destination, aggregate type/id를 strict UTF-8 REPORT + domain-separated -length-prefixed SHA-256으로 계산하고 lowercase hex US-ASCII bytes를 반환한다. malformed -surrogate는 replacement 문자로 바꾸지 않고 거부한다. +`IntegrationEventEncoderPort`는 adopter 확장 지점으로 남는다. 템플릿은 구현체를 주지 않으므로 +`ca-skeleton.outbox.canonical-transport-enabled=true`를 켜는 adopter가 encoder bean을 직접 제공한다. -adapter 내부 compiler/card/binding 타입은 direct 또는 generic argument 형태의 public instance -response surface로 노출하지 않는다. -cross-package adapter composition이 정확한 compiled identity를 확인해야 할 때만 public static -bridge를 사용하며, instance accessor는 package-private이고 외부에 필요한 상태는 boolean/String/ -core value로만 제공한다. 이는 broker SDK뿐 아니라 adapter 자체의 조립 타입도 B7 반환 경계를 -통해 application consumer로 새지 않게 한다. +공통 build evidence manifest 검증은 build-tools로 옮겼다. 루트 `verifyMessagingContracts` +(`VerifyMessagingEvidenceTask`)가 application-core·shared-contract 두 qualification 레인 결과로 +`build/messaging-evidence/contracts-schema/manifest.json`을 쓰고, 쓴 바이트를 바로 common schema로 +검증한다(common schema 자체도 Draft 2020-12 meta-schema 검증을 먼저 통과해야 한다). 이 leaf는 그 +검증에 관여하지 않는다. -`MessagingCapabilityCardRegistry`는 first R2 tuple의 11개 ID와 각 role을 닫힌 Java vocabulary로 -제공할 뿐이다. readiness registry의 `not-implemented` 상태를 승격하거나 R2/`ACTIVE_READY`를 -주장하지 않는다. `DISABLED + empty catalog/bindings`는 client, thread, scheduler, network, -filesystem resource가 정확히 0인 descriptor다. `ACTIVE`는 empty catalog, missing/duplicate/extra -binding, unknown/mismatched card와 ordering/schema/security 완화를 resource 생성 전에 거부한다. - -## Deterministic local JSON Schema encoder candidate - -`envelope` package는 exact final `IntegrationPayload` record만 받아 frozen v1 field order로 UTF-8 -JSON을 쓴다. `Map`, raw JSON, `JsonNode`, polymorphic typing, custom serializer, assignable search는 -입력 경로에 없다. contract compiler가 선언된 generic type graph를 scalar/enum, -`Optional`/`List`/exact final nested record로만 재귀 고정하며 `Object`, interface, raw/wildcard, -generic record와 runtime record discovery를 거부한다. writer는 이 compiled graph를 따라서 각 -record accessor를 정확히 한 번 읽은 immutable snapshot을 만들고 payload를 정확히 한 번 encode한다. -schema validation에 건넨 바로 그 payload bytes를 raw JSON API 없이 envelope suffix에 삽입한다. -depth, string character/UTF-8 byte, array, object, number, payload/envelope byte limit는 writer와 -parser 양쪽에서 적용한다. output byte limit는 generator가 쓰는 bounded stream에서 allocation 전에 -강제하고, list는 size를 먼저 검사한 뒤 bounded iterator로 한 번만 snapshot한다. mutation/concurrent -access와 극단적 `BigDecimal` scale도 큰 배열/String 생성 전에 fail-closed 한다. duplicate key, -malformed UTF-8, trailing data, unpaired surrogate와 non-finite number는 replacement나 coercion -없이 거부한다. - -`LocalJsonSchemaRegistry`는 호출자가 명시적으로 제공한 exact bytes와 SHA-256만 startup에서 -Draft 2020-12 meta-schema로 검사하고 precompile한다. root `$id`와 absolute `$ref`는 lowercase -exact `urn` scheme만 허용하고 `$ref`는 동일 문서 fragment 또는 제공된 exact URN map으로 닫힌다. -HTTP/HTTPS/file/classpath/resource/jar 및 unknown absolute scheme fetch와 YAML loader는 제공하지 -않는다. public validation boundary도 UTF-8 bytes만 받는다. format assertion은 활성이다. 이 Task 6 -closed subset은 scope 추적의 모호성을 제거하기 위해 root 외 nested `$id`를 value type과 무관하게 -거부하고, `$dynamicRef`, `$dynamicAnchor`, deprecated `$recursiveRef`/`$recursiveAnchor`, `$anchor` -키워드를 어느 위치에서도 지원하지 않는다. - -Draft 2020-12 authority는 `draft/2020-12/schema` 1개와 `meta/*` 8개의 exact checked-in bytes 및 -digest로 pin한다. registry startup은 9개 digest, 각 `$id`, NetworkNT runtime schema tree를 -대조하고 하나라도 다르면 fail-closed 한다. Spring Boot executable/fat/nested JAR 배치를 깨뜨리는 -`CodeSource` regular-file/JAR 가정은 하지 않는다. NetworkNT 3.0.2 artifact provenance는 strict -Gradle dependency lock과 `verifyDependencyPolicy`가 담당한다. 이 검증은 business schema -registry나 runtime remote resolution 경로를 넓히지 않는다. - -공통 build evidence manifest는 수동 구조 검사만으로 PASS하지 않는다. test/build 전용 -`MessagingEvidenceManifestSchemaValidator`가 exact common schema와 생성된 manifest bytes를 같은 -pinned NetworkNT/`LocalJsonSchemaRegistry`로 Draft 2020-12 검증하며, common schema 자체도 -meta-schema 검증을 통과해야 한다. `verifyMessagingContracts`는 JSON-only qualification과 그 -manifest schema validation을 명시적으로 선행해 CLI task 나열 순서와 무관하게 combined manifest가 -`build/messaging-evidence/contracts-schema/manifest.json`의 최종 소유자가 된다. - -NetworkNT 3.0.2의 adopted regex 구현은 JDK regex 실행시간을 강제 중단시키는 별도 engine/timeout을 -제공하지 않는다. 따라서 현재 후보는 regex 입력 길이와 전체 document 구조를 먼저 제한하고, -pathological pattern의 작은 repository corpus를 회귀 테스트한다. 이는 JSON Schema Test -Suite/Bowtie 전체 호환이나 hostile regex 시간 상한 증명이 아니며 evidence의 -`regex-engine-timeout`, `consumer-compatibility-full-suite` unsupported claim으로 남는다. 테스트 -runtime은 remote corpus를 내려받지 않는다. - -deterministic local wire contract는 이제 canonical platform bridge의 입력으로 사용할 수 있다. -다만 production legacy relay가 아직 `OutboxEvent`를 읽기 때문에 R2 durable outbox storage/relay -cutover는 남아 있다. `KafkaSender`/legacy broker selection은 그 R0 compatibility path에서만 -authority를 유지한다. canonical path는 platform `PublishResult`의 confirmation/transmission evidence를 -application `OutboxPublishOutcome`으로 명시적으로 변환한다. +canonical path는 platform `PublishResult`의 confirmation/transmission evidence를 application +`OutboxPublishOutcome`으로 명시적으로 변환한다. production legacy relay가 아직 `OutboxEvent`를 읽기 +때문에 R2 durable outbox storage/relay cutover는 남아 있고, `KafkaSender`/legacy broker selection은 그 +R0 compatibility path에서만 authority를 유지한다. diff --git a/src/adapter/outbound/messaging/build.gradle b/src/adapter/outbound/messaging/build.gradle index b8d8b047..87b19e28 100644 --- a/src/adapter/outbound/messaging/build.gradle +++ b/src/adapter/outbound/messaging/build.gradle @@ -1,11 +1,8 @@ plugins { id 'ca.spring-library' id 'ca.spring-config' - id 'ca.dependency-policy' - id 'ca.strict-qualification' } - dependencies { implementation project(':application-core') implementation project(':shared-contract') @@ -15,22 +12,15 @@ dependencies { implementation 'org.springframework.boot:spring-boot-autoconfigure' implementation 'org.springframework.boot:spring-boot-starter-json' - implementation(libs.json.schema.validator) { - exclude group: 'com.fasterxml.jackson.dataformat', module: 'jackson-dataformat-yaml' - } implementation 'org.slf4j:slf4j-api' - // Test-only: the off-filter promises compatibility when an adopter adds Boot's broker - // auto-configuration modules. Keep those modules off production runtime, but load their actual - // AutoConfiguration.imports here so stale FQCNs fail the contract test. - testImplementation project(':adapter:outbound:messaging-kafka') - testImplementation 'org.springframework.boot:spring-boot-kafka' - testImplementation 'org.springframework.boot:spring-boot-amqp' -} -tasks.withType(Test).configureEach { - systemProperty 'messaging.commonEvidenceSchema', - rootProject.file('config/messaging/evidence/build-evidence-manifest-v1.schema.json') - .absolutePath + // Test-only: the Kafka broker template, for the broker-selection cases. Without the platform + // starter it pulls at runtime — this leaf's tests use a same-named stand-in for the platform root. + testImplementation(project(':adapter:outbound:messaging-kafka')) { + exclude group: 'dev.caskeleton', module: 'messaging-spring-boot-starter-kafka' + } + // Test-only: MessagingEvidenceSchemaValidatorTest holds the common evidence schema to Draft 2020-12. + testImplementation libs.json.schema.validator } configurations.configureEach { @@ -39,56 +29,20 @@ configurations.configureEach { exclude group: 'org.snakeyaml', module: 'snakeyaml-engine' } -// The runtime graph policy is declarative; ca.dependency-policy owns resolution and verification. -// Module presence is version-agnostic because dependency locking/BOMs own version selection. -dependencyPolicy { - absentMatching '(?i).*yaml.*', - 'Messaging JSON runtime is intentionally YAML-free.' - absentMatching 'com\\.fasterxml\\.jackson\\.core:jackson-(?:core|databind)', - 'Jackson 2 core/databind must not enter the Jackson 3 messaging runtime.' - required libs.json.schema.validator, - 'NetworkNT is the runtime JSON Schema engine.' - required libs.jackson3.core, - 'Jackson 3 core is part of the closed JSON runtime graph.' - required libs.jackson3.databind, - 'Jackson 3 databind is part of the closed JSON runtime graph.' +// The messaging runtime is Jackson 3 only and YAML-free. The excludes above remove the YAML parsers +// the graph carries today (Spring Boot's snakeyaml included); this rule fails resolution if anything +// brings Jackson 2 or any YAML module back. A `rejectAll()` constraint would not: Spring's dependency +// management overrides the version it rejects. +configurations.configureEach { + resolutionStrategy.componentSelection.all { selection -> + String id = selection.candidate.group + ':' + selection.candidate.module + if (id ==~ /(?i).*yaml.*/ || id ==~ /com\.fasterxml\.jackson\.core:jackson-(core|databind)/) { + selection.reject('the messaging runtime is Jackson 3 only and YAML-free') + } + } } -def messagingCompiledContractsQualification = extensions.getByName('strictQualification').register( - 'messagingCompiledContractsQualificationTest', - sourceSets.test, - [ - 'dev.caskeleton.adapter.outbound.messaging.config.MessagingCapabilityCardRegistryTest', - 'dev.caskeleton.adapter.outbound.messaging.contract.ContractCatalogCompilerTest', - 'dev.caskeleton.adapter.outbound.messaging.contract.ContractCatalogDigestTest', - 'dev.caskeleton.adapter.outbound.messaging.destination.DestinationBindingCompilerTest', - 'dev.caskeleton.adapter.outbound.messaging.destination.PartitionKeyV1Test' - ], - rootProject.layout.buildDirectory.dir( - 'test-results/messaging-evidence/compiled'), - rootProject.layout.buildDirectory.dir( - 'test-results/messaging-evidence-binary/compiled'), - 'Runs exact Messaging compiled-contract qualification tests.' -) -messagingCompiledContractsQualification.configure { - dependsOn ':prepareMessagingContractEvidence' -} - -def messagingJsonSchemaV1Qualification = extensions.getByName('strictQualification').register( - 'messagingJsonSchemaV1QualificationTest', - sourceSets.test, - [ - 'dev.caskeleton.adapter.outbound.messaging.envelope.LocalJsonSchemaRegistryTest', - 'dev.caskeleton.adapter.outbound.messaging.envelope.JsonSchemaIntegrationEventEncoderTest', - 'dev.caskeleton.adapter.outbound.messaging.envelope.EnvelopeAdversarialCorpusTest', - 'dev.caskeleton.adapter.outbound.messaging.qualification.MessagingEvidenceManifestSchemaValidatorTest' - ], - rootProject.layout.buildDirectory.dir( - 'test-results/messaging-evidence/json-schema'), - rootProject.layout.buildDirectory.dir( - 'test-results/messaging-evidence-binary/json-schema'), - 'Runs exact Messaging JSON Schema v1 qualification tests.' -) -messagingJsonSchemaV1Qualification.configure { - dependsOn ':prepareMessagingContractEvidence' +tasks.named('test') { + inputs.file(rootProject.file('config/messaging/evidence/build-evidence-manifest-v1.schema.json')) + .withPathSensitivity(PathSensitivity.RELATIVE) } diff --git a/src/adapter/outbound/messaging/gradle.lockfile b/src/adapter/outbound/messaging/gradle.lockfile index 776e6464..4b9ffb4f 100644 --- a/src/adapter/outbound/messaging/gradle.lockfile +++ b/src/adapter/outbound/messaging/gradle.lockfile @@ -5,7 +5,7 @@ at.yawk.lz4:lz4-java:1.10.1=testRuntimeClasspath biz.aQute.bnd:biz.aQute.bnd.annotation:7.1.0=compileClasspath,testCompileClasspath ch.qos.logback:logback-classic:1.5.38=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath ch.qos.logback:logback-core:1.5.38=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -com.ethlo.time:itu:1.14.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +com.ethlo.time:itu:1.14.0=testCompileClasspath,testRuntimeClasspath com.fasterxml.jackson.core:jackson-annotations:2.21=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,testAnnotationProcessor com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,testAnnotationProcessor @@ -34,9 +34,8 @@ com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,testAnno com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,testAnnotationProcessor com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins com.jayway.jsonpath:json-path:2.10.0=testCompileClasspath,testRuntimeClasspath -com.networknt:json-schema-validator:3.0.2=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +com.networknt:json-schema-validator:3.0.2=testCompileClasspath,testRuntimeClasspath com.puppycrawl.tools:checkstyle:13.5.0=checkstyle -com.rabbitmq:amqp-client:5.27.1=testCompileClasspath,testRuntimeClasspath com.vaadin.external.google:android-json:0.0.20131108.vaadin1=testCompileClasspath,testRuntimeClasspath commons-beanutils:commons-beanutils:1.11.0=checkstyle commons-collections:commons-collections:3.2.2=checkstyle @@ -47,17 +46,6 @@ io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,testAnnota io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,testAnnotationProcessor io.micrometer:micrometer-commons:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath io.micrometer:micrometer-observation:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.netty:netty-buffer:4.2.17.Final=testCompileClasspath,testRuntimeClasspath -io.netty:netty-codec-base:4.2.17.Final=testCompileClasspath,testRuntimeClasspath -io.netty:netty-codec-compression:4.2.17.Final=testCompileClasspath,testRuntimeClasspath -io.netty:netty-codec-marshalling:4.2.17.Final=testCompileClasspath,testRuntimeClasspath -io.netty:netty-codec-protobuf:4.2.17.Final=testCompileClasspath,testRuntimeClasspath -io.netty:netty-codec:4.2.17.Final=testCompileClasspath,testRuntimeClasspath -io.netty:netty-common:4.2.17.Final=testCompileClasspath,testRuntimeClasspath -io.netty:netty-handler:4.2.17.Final=testCompileClasspath,testRuntimeClasspath -io.netty:netty-resolver:4.2.17.Final=testCompileClasspath,testRuntimeClasspath -io.netty:netty-transport-native-unix-common:4.2.17.Final=testCompileClasspath,testRuntimeClasspath -io.netty:netty-transport:4.2.17.Final=testCompileClasspath,testRuntimeClasspath jakarta.activation:jakarta.activation-api:2.1.4=testCompileClasspath,testRuntimeClasspath jakarta.annotation:jakarta.annotation-api:3.0.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath jakarta.xml.bind:jakarta.xml.bind-api:4.0.5=testCompileClasspath,testRuntimeClasspath @@ -75,7 +63,7 @@ org.apache.commons:commons-text:1.15.0=spotbugs org.apache.commons:commons-text:1.3=checkstyle org.apache.httpcomponents:httpclient:4.5.13=checkstyle org.apache.httpcomponents:httpcore:4.4.16=checkstyle -org.apache.kafka:kafka-clients:4.1.2=testCompileClasspath,testRuntimeClasspath +org.apache.kafka:kafka-clients:4.1.2=testRuntimeClasspath org.apache.logging.log4j:log4j-api:2.25.5=compileClasspath,runtimeClasspath,spotbugs,testCompileClasspath,testRuntimeClasspath org.apache.logging.log4j:log4j-core:2.25.5=spotbugs org.apache.logging.log4j:log4j-to-slf4j:2.25.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath @@ -128,15 +116,10 @@ org.slf4j:jul-to-slf4j:2.0.18=compileClasspath,runtimeClasspath,testCompileClass org.slf4j:slf4j-api:2.0.18=compileClasspath,runtimeClasspath,spotbugs,spotbugsSlf4j,testCompileClasspath,testRuntimeClasspath org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j org.slf4j:slf4j-simple:2.0.18=checkstyle -org.springframework.amqp:spring-amqp:4.0.5=testCompileClasspath,testRuntimeClasspath -org.springframework.amqp:spring-rabbit:4.0.5=testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-amqp:4.0.8=testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-autoconfigure:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-configuration-processor:4.0.8=annotationProcessor org.springframework.boot:spring-boot-http-converter:4.0.8=testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-jackson:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-kafka:4.0.8=testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-persistence:4.0.8=testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-resttestclient:4.0.8=testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-servlet:4.0.8=testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-starter-jackson-test:4.0.8=testCompileClasspath,testRuntimeClasspath @@ -152,20 +135,16 @@ org.springframework.boot:spring-boot-starter:4.0.8=compileClasspath,runtimeClass org.springframework.boot:spring-boot-test-autoconfigure:4.0.8=testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-test:4.0.8=testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-tomcat:4.0.8=testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-transaction:4.0.8=testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-web-server:4.0.8=testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-webmvc-test:4.0.8=testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-webmvc:4.0.8=testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.kafka:spring-kafka:4.0.7=testCompileClasspath,testRuntimeClasspath org.springframework:spring-aop:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework:spring-beans:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework:spring-context:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework:spring-core:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework:spring-expression:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-messaging:7.0.9=testCompileClasspath,testRuntimeClasspath org.springframework:spring-test:7.0.9=testCompileClasspath,testRuntimeClasspath -org.springframework:spring-tx:7.0.9=testCompileClasspath,testRuntimeClasspath org.springframework:spring-web:7.0.9=testCompileClasspath,testRuntimeClasspath org.springframework:spring-webmvc:7.0.9=testCompileClasspath,testRuntimeClasspath org.xerial.snappy:snappy-java:1.1.10.7=testRuntimeClasspath diff --git a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/MessagingConfig.java b/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/MessagingConfig.java index 700d1dd3..8475ae35 100644 --- a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/MessagingConfig.java +++ b/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/MessagingConfig.java @@ -4,7 +4,6 @@ import dev.caskeleton.adapter.outbound.messaging.core.DisabledMessagePublisher; import dev.caskeleton.adapter.outbound.messaging.core.MessageBroker; import dev.caskeleton.adapter.outbound.messaging.core.MessagePublisher; import dev.caskeleton.adapter.outbound.messaging.core.OutboundMessagePublisher; -import dev.caskeleton.adapter.outbound.messaging.outbox.DisabledOutboxMessagePublisher; import dev.caskeleton.adapter.outbound.messaging.outbox.OutboxMessagePublishAdapter; import dev.caskeleton.adapter.outbound.messaging.outbox.Slf4jOutboxRelayFailureReportAdapter; import dev.caskeleton.adapter.outbound.support.FailOpenDependencyLogger; @@ -21,8 +20,13 @@ import org.springframework.context.annotation.Configuration; * Assembles both messaging ports onto the single active {@link MessageBroker} (the cache * central-assembly pattern). A broker is contributed as a * {@code @ConditionalOnProperty(app.messaging.broker=)}-gated bean, at most one active — adding - * a broker is new files only and this config never changes. With no active broker it binds the - * disabled sentinels (fail-fast); if set but no contributing bean exists, startup fails. + * a broker is new files only and this config never changes. A broker that is set but that no bean + * contributes fails startup. + * + *

The outbox publish port has no stand-in. A stand-in that throws on every call would still + * satisfy the relay scheduler's bean condition, and the relay would exhaust every PENDING row to + * DEAD against it. So a present-and-enabled bridge with a blank broker and no canonical transport + * is refused at startup: the module is here, so messaging was wanted, and nothing can publish. */ @Configuration @EnableConfigurationProperties(MessagingSettings.class) @@ -49,7 +53,11 @@ public class MessagingConfig { MessageBroker active = resolveBroker(brokerProvider, settings); IntegrationEventPublishPort canonicalPublisher = canonicalPublisherProvider.getIfAvailable(); if (active == null && canonicalPublisher == null) { - return new DisabledOutboxMessagePublisher(); + throw new IllegalStateException( + "app.messaging.enabled is on but app.messaging.broker is blank and no canonical transport" + + " is configured, so nothing can publish outbox rows — select a broker (the" + + " messaging-kafka module defaults it to kafka), set app.messaging.producer-id for the" + + " canonical transport, or set app.messaging.enabled=false"); } return new OutboxMessagePublishAdapter( java.util.Optional.ofNullable(active), diff --git a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/MessagingSettings.java b/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/MessagingSettings.java index bab5e7c4..a1d6ec26 100644 --- a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/MessagingSettings.java +++ b/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/MessagingSettings.java @@ -5,8 +5,9 @@ import org.springframework.boot.context.properties.ConfigurationProperties; /** * Messaging template selection. {@code app.messaging.broker=} chooses the single active - * {@link MessageBroker} (e.g. {@code kafka}); unset/blank = no broker = fail-fast on use (the - * disabled sentinels {@code DisabledMessagePublisher} / {@code DisabledOutboxMessagePublisher}). + * {@link MessageBroker} (e.g. {@code kafka}). Blank means no legacy broker: the generic publisher + * is the fail-fast {@code DisabledMessagePublisher}, and startup is refused unless the canonical + * transport can publish outbox rows instead. * * @param broker the active legacy broker id, matched against {@link MessageBroker#brokerId()}; * blank means the legacy broker template is disabled diff --git a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/autoconfigure/MessagingBridgeRootAutoConfiguration.java b/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/autoconfigure/MessagingBridgeRootAutoConfiguration.java index 31c6e043..716bbcc6 100644 --- a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/autoconfigure/MessagingBridgeRootAutoConfiguration.java +++ b/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/autoconfigure/MessagingBridgeRootAutoConfiguration.java @@ -3,15 +3,22 @@ package dev.caskeleton.adapter.outbound.messaging.autoconfigure; import dev.caskeleton.adapter.outbound.messaging.MessagingConfig; import dev.caskeleton.adapter.outbound.messaging.MessagingSettings; import dev.caskeleton.adapter.outbound.messaging.platformbridge.PlatformIntegrationEventPublishAdapter; +import dev.caskeleton.adapter.outbound.support.FailOpenDependencyLogger; import dev.caskeleton.application.messaging.event.IntegrationEventPublishPort; import dev.caskeleton.messaging.schema.EncodedMessagePublisher; import org.springframework.boot.autoconfigure.AutoConfiguration; +import org.springframework.boot.autoconfigure.condition.ConditionOutcome; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.autoconfigure.condition.SpringBootCondition; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ConditionContext; +import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Import; +import org.springframework.core.type.AnnotatedTypeMetadata; +import org.springframework.util.StringUtils; /** * The one place that decides whether this application publishes to a broker. @@ -21,26 +28,65 @@ import org.springframework.context.annotation.Import; * relay enabled took down startup, while a deployment that wanted no messaging at all still * assembled settings and publishers. Broker-specific client configuration is now a build-time * capability leaf; this root remains broker-neutral and only binds ports to a contributed broker. + * + *

On when present: an application that selected a messaging leaf wants messaging, so a missing + * {@code app.messaging.enabled} means on and only an explicit {@code false} turns it off. */ -@AutoConfiguration -@ConditionalOnProperty(prefix = "app.messaging", name = "enabled", havingValue = "true") +@AutoConfiguration( + afterName = "dev.caskeleton.messaging.autoconfigure.MessagingPlatformRootAutoConfiguration") +@ConditionalOnProperty( + prefix = "app.messaging", + name = "enabled", + havingValue = "true", + matchIfMissing = true) @EnableConfigurationProperties(MessagingSettings.class) @Import(MessagingConfig.class) public class MessagingBridgeRootAutoConfiguration { + /** + * The shared fail-open logger the publisher needs, so the module works wherever it is present + * rather than only where a composition root's component scan happens to reach {@code + * adapter.support}. Backs off to the one that scan registers. + */ + @Bean + @ConditionalOnMissingBean + FailOpenDependencyLogger failOpenDependencyLogger() { + return new FailOpenDependencyLogger(); + } + /** * Connects canonical application integration events to the central messaging platform. * *

Producer identity is explicit configuration. The bridge is not created when that identity is * absent, because guessing from a process name or deployment name would make the wire producer * identity environment-dependent. + * + *

{@code @ConditionalOnBean} only sees the publisher because this class is ordered after the + * platform root: auto-configurations are sorted by name first, and {@code + * dev.caskeleton.adapter…} sorts before {@code dev.caskeleton.messaging…}. */ @Bean @ConditionalOnBean(EncodedMessagePublisher.class) @ConditionalOnMissingBean(IntegrationEventPublishPort.class) - @ConditionalOnProperty(prefix = "app.messaging", name = "producer-id") + @Conditional(ProducerIdConfigured.class) public IntegrationEventPublishPort integrationEventPublishPort( EncodedMessagePublisher publisher, MessagingSettings settings) { return new PlatformIntegrationEventPublishAdapter(publisher, settings.producerId()); } + + /** + * The shipped yml always defines {@code producer-id} ({@code ${APP_MESSAGING_PRODUCER_ID:}}), so + * the key being present says nothing; only a non-blank value is configuration. + */ + static final class ProducerIdConfigured extends SpringBootCondition { + + @Override + public ConditionOutcome getMatchOutcome( + ConditionContext context, AnnotatedTypeMetadata metadata) { + String producerId = context.getEnvironment().getProperty("app.messaging.producer-id"); + return StringUtils.hasText(producerId) + ? ConditionOutcome.match("app.messaging.producer-id is set") + : ConditionOutcome.noMatch("app.messaging.producer-id is blank"); + } + } } diff --git a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/autoconfigure/MessagingOffAutoConfigurationImportFilter.java b/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/autoconfigure/MessagingOffAutoConfigurationImportFilter.java deleted file mode 100644 index 392a72e8..00000000 --- a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/autoconfigure/MessagingOffAutoConfigurationImportFilter.java +++ /dev/null @@ -1,52 +0,0 @@ -package dev.caskeleton.adapter.outbound.messaging.autoconfigure; - -import java.util.Set; -import org.springframework.boot.autoconfigure.AutoConfigurationImportFilter; -import org.springframework.boot.autoconfigure.AutoConfigurationMetadata; -import org.springframework.context.EnvironmentAware; -import org.springframework.core.env.Environment; - -/** - * Keeps Boot's broker auto-configurations out of the candidate set while messaging is off. - * - *

The Kafka and AMQP starters contribute theirs through Boot's import metadata, so a client - * library on the classpath is enough to build a connection factory, a template and a listener - * container — none of which any project condition was consulted about. It also means both brokers - * would assemble at once simply because both libraries are present, which is a different bug the - * same filter prevents. - */ -public final class MessagingOffAutoConfigurationImportFilter - implements AutoConfigurationImportFilter, EnvironmentAware { - - private static final String ENABLE_PROPERTY = "app.messaging.enabled"; - - private static final Set BROKER_AUTO_CONFIGURATIONS = - Set.of( - "org.springframework.boot.kafka.autoconfigure.KafkaAutoConfiguration", - "org.springframework.boot.kafka.autoconfigure.metrics.KafkaMetricsAutoConfiguration", - "org.springframework.boot.amqp.autoconfigure.RabbitAutoConfiguration", - "org.springframework.boot.amqp.autoconfigure.health.RabbitHealthContributorAutoConfiguration", - "org.springframework.boot.amqp.autoconfigure.metrics.RabbitMetricsAutoConfiguration"); - - private Environment environment; - - @Override - public boolean[] match(String[] candidates, AutoConfigurationMetadata metadata) { - boolean enabled = - environment != null - && "true".equalsIgnoreCase(environment.getProperty(ENABLE_PROPERTY, "false")); - boolean[] matches = new boolean[candidates.length]; - for (int index = 0; index < candidates.length; index++) { - matches[index] = - enabled - || candidates[index] == null - || !BROKER_AUTO_CONFIGURATIONS.contains(candidates[index]); - } - return matches; - } - - @Override - public void setEnvironment(Environment environment) { - this.environment = environment; - } -} diff --git a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/config/CompiledMessagingDescriptor.java b/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/config/CompiledMessagingDescriptor.java deleted file mode 100644 index b0ea8ae1..00000000 --- a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/config/CompiledMessagingDescriptor.java +++ /dev/null @@ -1,204 +0,0 @@ -package dev.caskeleton.adapter.outbound.messaging.config; - -import dev.caskeleton.adapter.outbound.messaging.contract.CompiledIntegrationEventContract; -import dev.caskeleton.adapter.outbound.messaging.contract.ContractCatalogDigest; -import dev.caskeleton.adapter.outbound.messaging.destination.CompiledPublicationBinding; -import dev.caskeleton.adapter.outbound.messaging.destination.DestinationBindingCompiler; -import dev.caskeleton.adapter.outbound.messaging.destination.DestinationBindingSettings; -import dev.caskeleton.application.messaging.contract.Sha256; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** Immutable R1 local compilation result; it owns no broker client, thread or external resource. */ -public final class CompiledMessagingDescriptor { - - private final ActivationMode activationMode; - private final List contracts; - private final List bindings; - private final Sha256 catalogDigest; - private final Sha256 settingsDigest; - private final Sha256 schemaSetDigest; - - private CompiledMessagingDescriptor( - ActivationMode activationMode, - List contracts, - List bindings, - Sha256 catalogDigest, - Sha256 settingsDigest, - Sha256 schemaSetDigest) { - if (activationMode == null - || contracts == null - || bindings == null - || catalogDigest == null - || settingsDigest == null - || schemaSetDigest == null) { - throw new IllegalArgumentException("compiled messaging descriptor fields must not be null"); - } - this.activationMode = activationMode; - this.contracts = List.copyOf(contracts); - this.bindings = List.copyOf(bindings); - this.catalogDigest = catalogDigest; - this.settingsDigest = settingsDigest; - this.schemaSetDigest = schemaSetDigest; - - if (!catalogDigest.equals(ContractCatalogDigest.compute(this.contracts))) { - throw new IllegalArgumentException("catalog digest must match the exact compiled catalog"); - } - Sha256 expectedSchemaSetDigest = - new DestinationBindingCompiler().schemaSetDigest(this.contracts); - if (!schemaSetDigest.equals(expectedSchemaSetDigest)) { - throw new IllegalArgumentException("schema digest must match the exact compiled catalog"); - } - if (activationMode == ActivationMode.DISABLED) { - if (!this.contracts.isEmpty() || !this.bindings.isEmpty()) { - throw new IllegalArgumentException( - "DISABLED descriptor requires an empty catalog and empty bindings"); - } - } else { - validateActive(this.contracts, this.bindings, settingsDigest, schemaSetDigest); - } - } - - public static CompiledMessagingDescriptor compile( - ActivationMode mode, - List contracts, - DestinationBindingSettings settings, - MessagingCapabilityCardRegistry cardRegistry) { - if (mode == null || contracts == null || settings == null || cardRegistry == null) { - throw new IllegalArgumentException("descriptor compiler inputs must not be null"); - } - DestinationBindingCompiler bindingCompiler = new DestinationBindingCompiler(); - if (mode == ActivationMode.DISABLED) { - if (!contracts.isEmpty() - || !DestinationBindingSettings.destinationsOf(settings).isEmpty() - || DestinationBindingSettings.legacyAliasesOf(settings).isPresent()) { - throw new IllegalArgumentException( - "DISABLED descriptor requires an empty catalog and empty bindings"); - } - return new CompiledMessagingDescriptor( - mode, - List.of(), - List.of(), - ContractCatalogDigest.compute(List.of()), - bindingCompiler.settingsDigest(settings), - bindingCompiler.schemaSetDigest(List.of())); - } - if (contracts.isEmpty()) { - throw new IllegalArgumentException("ACTIVE descriptor rejects an empty catalog"); - } - List bindings = - DestinationBindingCompiler.compileExact(contracts, settings, cardRegistry); - return new CompiledMessagingDescriptor( - mode, - contracts, - bindings, - ContractCatalogDigest.compute(contracts), - bindings.getFirst().settingsDigest(), - bindings.getFirst().schemaSetDigest()); - } - - ActivationMode activationMode() { - return activationMode; - } - - public boolean active() { - return activationMode == ActivationMode.ACTIVE; - } - - public boolean disabled() { - return activationMode == ActivationMode.DISABLED; - } - - List contracts() { - return contracts; - } - - List bindings() { - return bindings; - } - - /** Narrow immutable composition bridge for the exact compiled catalog. */ - public static List contractsOf( - CompiledMessagingDescriptor descriptor) { - return requireDescriptor(descriptor).contracts; - } - - /** Narrow immutable composition bridge for the exact compiled bindings. */ - public static List bindingsOf( - CompiledMessagingDescriptor descriptor) { - return requireDescriptor(descriptor).bindings; - } - - public Sha256 catalogDigest() { - return catalogDigest; - } - - public Sha256 settingsDigest() { - return settingsDigest; - } - - public Sha256 schemaSetDigest() { - return schemaSetDigest; - } - - /** Task 5 is compilation-only and therefore always allocates zero runtime resources. */ - public int resourceCount() { - return 0; - } - - private static CompiledMessagingDescriptor requireDescriptor( - CompiledMessagingDescriptor descriptor) { - if (descriptor == null) { - throw new IllegalArgumentException("compiled messaging descriptor must not be null"); - } - return descriptor; - } - - private static void validateActive( - List contracts, - List bindings, - Sha256 settingsDigest, - Sha256 schemaSetDigest) { - if (contracts.isEmpty()) { - throw new IllegalArgumentException("ACTIVE descriptor rejects an empty catalog"); - } - if (contracts.size() != bindings.size()) { - throw new IllegalArgumentException( - "ACTIVE descriptor requires exactly one binding per contract version"); - } - Map contractsByKey = new HashMap<>(); - for (CompiledIntegrationEventContract contract : contracts) { - if (contractsByKey.putIfAbsent(contract.stableKey(), contract) != null) { - throw new IllegalArgumentException( - "ACTIVE descriptor rejects duplicate contract " + contract.stableKey()); - } - } - Map bindingsByKey = new HashMap<>(); - for (CompiledPublicationBinding binding : bindings) { - CompiledIntegrationEventContract bindingContract = - CompiledPublicationBinding.contractOf(binding); - String stableKey = bindingContract.stableKey(); - CompiledIntegrationEventContract exactContract = contractsByKey.get(stableKey); - if (exactContract == null - || !exactContract.equals(bindingContract) - || bindingsByKey.putIfAbsent(stableKey, binding) != null) { - throw new IllegalArgumentException( - "ACTIVE descriptor contains a forged, duplicate or extra binding for " + stableKey); - } - if (!settingsDigest.equals(binding.settingsDigest()) - || !schemaSetDigest.equals(binding.schemaSetDigest())) { - throw new IllegalArgumentException( - "ACTIVE descriptor digest must match every compiled binding"); - } - } - if (!bindingsByKey.keySet().equals(contractsByKey.keySet())) { - throw new IllegalArgumentException("ACTIVE descriptor is missing an exact contract binding"); - } - } - - public enum ActivationMode { - DISABLED, - ACTIVE - } -} diff --git a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/config/MessagingCapabilityCardRegistry.java b/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/config/MessagingCapabilityCardRegistry.java deleted file mode 100644 index cf646bfe..00000000 --- a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/config/MessagingCapabilityCardRegistry.java +++ /dev/null @@ -1,235 +0,0 @@ -package dev.caskeleton.adapter.outbound.messaging.config; - -import java.util.ArrayList; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** Closed code vocabulary for the first producer-only R2 capability tuple. */ -public final class MessagingCapabilityCardRegistry { - - private static final List FIRST_R2 = - List.of( - new CapabilityCard("messaging-outbox-publish.v1", CardRole.SEMANTIC), - new CapabilityCard("kafka-spring-acknowledged-idempotent.v1", CardRole.PRODUCER), - new CapabilityCard("postgresql-polling-outbox.v2", CardRole.DISPATCH), - new CapabilityCard("postgresql-per-record-jit-claim.v1", CardRole.CLAIM), - new CapabilityCard("json-schema-envelope.v1", CardRole.SERIALIZATION), - new CapabilityCard("external-topic-validated.v1", CardRole.TOPIC), - new CapabilityCard("kafka-sasl-ssl-scram-sha-512.v1", CardRole.SECURITY), - new CapabilityCard("kafka-compression-none.v1", CardRole.COMPRESSION), - new CapabilityCard("per-key-normal-path-sequence-detectable.v1", CardRole.ORDERING), - new CapabilityCard("same-postgresql-transaction-resource.v1", CardRole.TRANSACTION), - new CapabilityCard( - "authenticated-internal-web-disposition.v1", CardRole.OPERATOR_CONTROL)); - - private static final Map SUPPORTED_ROLES = supportedRoles(); - - private final List cards; - private final Map cardsById; - private final ExactSelection selection; - - private MessagingCapabilityCardRegistry(List cards) { - this.cards = List.copyOf(cards); - this.cardsById = index(cards); - this.selection = selection(cards); - } - - public static MessagingCapabilityCardRegistry exactFirstR2() { - return new MessagingCapabilityCardRegistry(FIRST_R2); - } - - /** Static bridge keeps the adapter-local selection type off public instance response surfaces. */ - public static ExactSelection exactFirstR2Selection() { - return selection(FIRST_R2); - } - - public static MessagingCapabilityCardRegistry compile(List cards) { - if (cards == null) { - throw new IllegalArgumentException("capability cards must not be null"); - } - return new MessagingCapabilityCardRegistry(new ArrayList<>(cards)); - } - - List cards() { - return cards; - } - - ExactSelection selection() { - return selection; - } - - /** Selection vocabulary is not readiness evidence and never claims release eligibility. */ - public boolean claimsReleaseEligibility() { - return false; - } - - public void validate(ExactSelection candidate) { - if (candidate == null) { - throw new IllegalArgumentException("capability selection must not be null"); - } - require(candidate.semanticCardId(), CardRole.SEMANTIC); - require(candidate.producerCardId(), CardRole.PRODUCER); - require(candidate.dispatchCardId(), CardRole.DISPATCH); - require(candidate.claimCardId(), CardRole.CLAIM); - require(candidate.serializationCardId(), CardRole.SERIALIZATION); - require(candidate.topicCardId(), CardRole.TOPIC); - require(candidate.securityCardId(), CardRole.SECURITY); - require(candidate.compressionCardId(), CardRole.COMPRESSION); - require(candidate.orderingCardId(), CardRole.ORDERING); - require(candidate.transactionCardId(), CardRole.TRANSACTION); - require(candidate.operatorControlCardId(), CardRole.OPERATOR_CONTROL); - } - - private void require(String cardId, CardRole expectedRole) { - CapabilityCard card = cardsById.get(cardId); - if (card == null) { - throw new IllegalArgumentException("unknown capability card: " + cardId); - } - if (card.role() != expectedRole) { - throw new IllegalArgumentException( - "capability card role mismatch: " - + cardId - + " is " - + card.role() - + ", expected " - + expectedRole); - } - } - - private static Map index(List cards) { - Set observedIds = new HashSet<>(); - for (CapabilityCard card : cards) { - if (card != null && !observedIds.add(card.cardId())) { - throw new IllegalArgumentException("duplicate capability card: " + card.cardId()); - } - } - if (cards.size() != FIRST_R2.size()) { - throw new IllegalArgumentException("registry must contain exactly the first R2 card tuple"); - } - Map result = new HashMap<>(); - Set roles = new HashSet<>(); - for (CapabilityCard card : cards) { - if (card == null) { - throw new IllegalArgumentException("capability card must not be null"); - } - CardRole supportedRole = SUPPORTED_ROLES.get(card.cardId()); - if (supportedRole == null) { - throw new IllegalArgumentException("unknown capability card: " + card.cardId()); - } - if (supportedRole != card.role()) { - throw new IllegalArgumentException("capability card role mismatch: " + card.cardId()); - } - if (result.putIfAbsent(card.cardId(), card) != null) { - throw new IllegalArgumentException("duplicate capability card: " + card.cardId()); - } - if (!roles.add(card.role())) { - throw new IllegalArgumentException("duplicate capability card role: " + card.role()); - } - } - if (!result.keySet().equals(SUPPORTED_ROLES.keySet())) { - throw new IllegalArgumentException("registry must contain exactly the first R2 card tuple"); - } - return Map.copyOf(result); - } - - private static ExactSelection selection(List cards) { - EnumMap byRole = new EnumMap<>(CardRole.class); - cards.forEach(card -> byRole.put(card.role(), card.cardId())); - return new ExactSelection( - byRole.get(CardRole.SEMANTIC), - byRole.get(CardRole.PRODUCER), - byRole.get(CardRole.DISPATCH), - byRole.get(CardRole.CLAIM), - byRole.get(CardRole.SERIALIZATION), - byRole.get(CardRole.TOPIC), - byRole.get(CardRole.SECURITY), - byRole.get(CardRole.COMPRESSION), - byRole.get(CardRole.ORDERING), - byRole.get(CardRole.TRANSACTION), - byRole.get(CardRole.OPERATOR_CONTROL)); - } - - private static Map supportedRoles() { - Map result = new HashMap<>(); - FIRST_R2.forEach(card -> result.put(card.cardId(), card.role())); - return Map.copyOf(result); - } - - public enum CardRole { - SEMANTIC, - PRODUCER, - DISPATCH, - CLAIM, - SERIALIZATION, - TOPIC, - SECURITY, - COMPRESSION, - ORDERING, - TRANSACTION, - OPERATOR_CONTROL - } - - public static final class CapabilityCard { - - private final String cardId; - private final CardRole role; - - public CapabilityCard(String cardId, CardRole role) { - if (cardId == null || cardId.isBlank() || role == null) { - throw new IllegalArgumentException("capability card id and role must not be blank"); - } - this.cardId = cardId; - this.role = role; - } - - public String cardId() { - return cardId; - } - - CardRole role() { - return role; - } - - public String roleName() { - return role.name(); - } - } - - public record ExactSelection( - String semanticCardId, - String producerCardId, - String dispatchCardId, - String claimCardId, - String serializationCardId, - String topicCardId, - String securityCardId, - String compressionCardId, - String orderingCardId, - String transactionCardId, - String operatorControlCardId) { - - public ExactSelection { - String[] selectedIds = { - semanticCardId, - producerCardId, - dispatchCardId, - claimCardId, - serializationCardId, - topicCardId, - securityCardId, - compressionCardId, - orderingCardId, - transactionCardId, - operatorControlCardId - }; - if (java.util.Arrays.stream(selectedIds) - .anyMatch(value -> value == null || value.isBlank())) { - throw new IllegalArgumentException("selected capability card ids must not be blank"); - } - } - } -} diff --git a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/contract/CompiledIntegrationEventContract.java b/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/contract/CompiledIntegrationEventContract.java deleted file mode 100644 index a4b9608d..00000000 --- a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/contract/CompiledIntegrationEventContract.java +++ /dev/null @@ -1,263 +0,0 @@ -package dev.caskeleton.adapter.outbound.messaging.contract; - -import dev.caskeleton.application.messaging.contract.ContractDescriptor; -import dev.caskeleton.application.messaging.contract.ContractId; -import dev.caskeleton.application.messaging.contract.IntegrationPayload; -import dev.caskeleton.application.messaging.contract.SchemaResourceId; -import dev.caskeleton.application.messaging.contract.Sha256; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.lang.reflect.RecordComponent; -import java.util.HashSet; -import java.util.List; - -/** Immutable, provider-neutral result of compiling one exact integration-event contract version. */ -public final class CompiledIntegrationEventContract { - - private final ContractId contractId; - private final int payloadVersion; - private final Class exactPayloadRecordType; - private final List canonicalRecordComponentOrder; - private final SchemaResourceId payloadSchemaResource; - private final Sha256 payloadSchemaHash; - private final ContractDescriptor descriptor; - private final PayloadShape payloadShape; - - CompiledIntegrationEventContract( - ContractId contractId, - int payloadVersion, - Class exactPayloadRecordType, - List canonicalRecordComponentOrder, - SchemaResourceId payloadSchemaResource, - Sha256 payloadSchemaHash, - ContractDescriptor descriptor) { - this( - contractId, - payloadVersion, - exactPayloadRecordType, - canonicalRecordComponentOrder, - payloadSchemaResource, - payloadSchemaHash, - descriptor, - ContractCatalogCompiler.compilePayloadShape(exactPayloadRecordType)); - } - - CompiledIntegrationEventContract( - ContractId contractId, - int payloadVersion, - Class exactPayloadRecordType, - List canonicalRecordComponentOrder, - SchemaResourceId payloadSchemaResource, - Sha256 payloadSchemaHash, - ContractDescriptor descriptor, - PayloadShape payloadShape) { - if (contractId == null - || exactPayloadRecordType == null - || canonicalRecordComponentOrder == null - || payloadSchemaResource == null - || payloadSchemaHash == null - || descriptor == null - || payloadShape == null) { - throw new IllegalArgumentException("compiled contract fields must not be null"); - } - if (payloadVersion <= 0) { - throw new IllegalArgumentException("payloadVersion must be positive"); - } - List copiedComponentOrder = List.copyOf(canonicalRecordComponentOrder); - if (!exactPayloadRecordType.isRecord() - || !Modifier.isFinal(exactPayloadRecordType.getModifiers()) - || !IntegrationPayload.class.isAssignableFrom(exactPayloadRecordType)) { - throw new IllegalArgumentException( - "compiled exact payload type must be a final IntegrationPayload record"); - } - if (copiedComponentOrder.stream() - .anyMatch(component -> component == null || component.isBlank()) - || new HashSet<>(copiedComponentOrder).size() != copiedComponentOrder.size()) { - throw new IllegalArgumentException( - "compiled canonical component order must contain unique non-blank names"); - } - List reflectedComponentOrder = - java.util.Arrays.stream(exactPayloadRecordType.getRecordComponents()) - .map(RecordComponent::getName) - .toList(); - if (!copiedComponentOrder.equals(reflectedComponentOrder)) { - throw new IllegalArgumentException( - "compiled canonical component order must match the exact record type"); - } - if (payloadShape.kind != PayloadKind.RECORD - || payloadShape.exactJavaType != exactPayloadRecordType - || !payloadShape.components.stream() - .map(component -> component.name) - .toList() - .equals(copiedComponentOrder)) { - throw new IllegalArgumentException( - "compiled payload shape must match the exact root record declaration"); - } - - this.contractId = contractId; - this.payloadVersion = payloadVersion; - this.exactPayloadRecordType = exactPayloadRecordType; - this.canonicalRecordComponentOrder = copiedComponentOrder; - this.payloadSchemaResource = payloadSchemaResource; - this.payloadSchemaHash = payloadSchemaHash; - this.descriptor = descriptor; - this.payloadShape = payloadShape; - } - - public ContractId contractId() { - return contractId; - } - - public int payloadVersion() { - return payloadVersion; - } - - public Class exactPayloadRecordType() { - return exactPayloadRecordType; - } - - public List canonicalRecordComponentOrder() { - return canonicalRecordComponentOrder; - } - - public SchemaResourceId payloadSchemaResource() { - return payloadSchemaResource; - } - - public Sha256 payloadSchemaHash() { - return payloadSchemaHash; - } - - public ContractDescriptor descriptor() { - return descriptor; - } - - /** Stable semantic identity independent of Java class names and physical destinations. */ - public String stableKey() { - return contractId.value() + ":v" + payloadVersion; - } - - /** Adapter-internal bridge used by the deterministic writer without runtime type discovery. */ - public static PayloadShape payloadShapeOf(CompiledIntegrationEventContract contract) { - if (contract == null) { - throw new IllegalArgumentException("compiled contract must not be null"); - } - return contract.payloadShape; - } - - /** - * Invokes the exact accessor frozen by the catalog compiler without exposing reflection types. - */ - public static Object readPayloadComponentOnce(PayloadComponent component, Object record) { - PayloadComponent required = PayloadComponent.requireComponent(component); - if (record == null || record.getClass() != required.accessor.getDeclaringClass()) { - throw new IllegalArgumentException( - "payload component record must match the exact compiled declaring class"); - } - try { - return required.accessor.invoke(record); - } catch (IllegalAccessException | InvocationTargetException exception) { - throw new IllegalArgumentException( - "record component accessor could not be invoked: " + required.name, exception); - } - } - - /** Closed kinds accepted by the contract compiler. */ - public enum PayloadKind { - RECORD, - OPTIONAL, - LIST, - STRING, - BOOLEAN, - INTEGRAL, - DECIMAL, - ENUM - } - - /** Immutable declared type node. Public only as an adapter-package bridge; it has no mutators. */ - public static final class PayloadShape { - - private final PayloadKind kind; - private final Class exactJavaType; - private final List components; - private final PayloadShape elementShape; - - PayloadShape( - PayloadKind kind, - Class exactJavaType, - List components, - PayloadShape elementShape) { - if (kind == null || exactJavaType == null || components == null) { - throw new IllegalArgumentException("compiled payload shape fields must not be null"); - } - this.kind = kind; - this.exactJavaType = exactJavaType; - this.components = List.copyOf(components); - this.elementShape = elementShape; - } - - public static PayloadKind kindOf(PayloadShape shape) { - return requireShape(shape).kind; - } - - public static Class exactJavaTypeOf(PayloadShape shape) { - return requireShape(shape).exactJavaType; - } - - public static List componentsOf(PayloadShape shape) { - return requireShape(shape).components; - } - - public static PayloadShape elementShapeOf(PayloadShape shape) { - PayloadShape required = requireShape(shape); - if (required.elementShape == null) { - throw new IllegalArgumentException("compiled payload shape has no element shape"); - } - return required.elementShape; - } - - private static PayloadShape requireShape(PayloadShape shape) { - if (shape == null) { - throw new IllegalArgumentException("compiled payload shape must not be null"); - } - return shape; - } - } - - /** Immutable record component node with its exact compiled accessor and declared child shape. */ - public static final class PayloadComponent { - - private final String name; - private final Method accessor; - private final PayloadShape shape; - - PayloadComponent(String name, Method accessor, PayloadShape shape) { - if (name == null || name.isBlank() || accessor == null || shape == null) { - throw new IllegalArgumentException("compiled payload component fields must not be null"); - } - if (!accessor.trySetAccessible()) { - throw new IllegalArgumentException( - "compiled payload component accessor must be locally invocable"); - } - this.name = name; - this.accessor = accessor; - this.shape = shape; - } - - public static String nameOf(PayloadComponent component) { - return requireComponent(component).name; - } - - public static PayloadShape shapeOf(PayloadComponent component) { - return requireComponent(component).shape; - } - - private static PayloadComponent requireComponent(PayloadComponent component) { - if (component == null) { - throw new IllegalArgumentException("compiled payload component must not be null"); - } - return component; - } - } -} diff --git a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/contract/ContractCatalogCompiler.java b/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/contract/ContractCatalogCompiler.java deleted file mode 100644 index 66d6ab3c..00000000 --- a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/contract/ContractCatalogCompiler.java +++ /dev/null @@ -1,274 +0,0 @@ -package dev.caskeleton.adapter.outbound.messaging.contract; - -import dev.caskeleton.application.messaging.contract.ContractDescriptor; -import dev.caskeleton.application.messaging.contract.ContractId; -import dev.caskeleton.application.messaging.contract.IntegrationEventContractContribution; -import dev.caskeleton.application.messaging.contract.IntegrationPayload; -import dev.caskeleton.application.messaging.contract.LogicalDestinationId; -import dev.caskeleton.application.messaging.contract.SchemaResourceId; -import dev.caskeleton.application.messaging.contract.Sha256; -import java.lang.reflect.GenericArrayType; -import java.lang.reflect.Modifier; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.RecordComponent; -import java.lang.reflect.Type; -import java.lang.reflect.TypeVariable; -import java.lang.reflect.WildcardType; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; - -/** Fail-fast compiler for an explicitly supplied, closed integration-event contribution list. */ -public final class ContractCatalogCompiler { - - List compile( - List> contributions) { - if (contributions == null) { - throw new IllegalArgumentException("contract contributions must not be null"); - } - - Set stableKeys = new HashSet<>(); - Set schemaResources = new HashSet<>(); - Set> exactPayloadTypes = new HashSet<>(); - Map destinationsByContract = new HashMap<>(); - List compiled = new ArrayList<>(contributions.size()); - - for (IntegrationEventContractContribution contribution : contributions) { - if (contribution == null) { - throw new IllegalArgumentException("contract contribution must not be null"); - } - compiled.add( - compileOne( - contribution, - stableKeys, - schemaResources, - exactPayloadTypes, - destinationsByContract)); - } - - compiled.sort( - java.util.Comparator.comparing( - (CompiledIntegrationEventContract contract) -> contract.contractId().value()) - .thenComparingInt(CompiledIntegrationEventContract::payloadVersion)); - return List.copyOf(compiled); - } - - /** Narrow immutable composition bridge for callers in sibling messaging adapter packages. */ - public static List compileExact( - List> contributions) { - return new ContractCatalogCompiler().compile(contributions); - } - - private static CompiledIntegrationEventContract compileOne( - IntegrationEventContractContribution contribution, - Set stableKeys, - Set schemaResources, - Set> exactPayloadTypes, - Map destinationsByContract) { - ContractId contractId = contribution.contractId(); - int payloadVersion = contribution.payloadVersion(); - Class payloadType = contribution.exactPayloadRecordType(); - List declaredComponentOrder = contribution.canonicalRecordComponentOrder(); - SchemaResourceId schemaResource = contribution.payloadSchemaResource(); - Sha256 schemaHash = contribution.payloadSchemaHash(); - ContractDescriptor descriptor = contribution.descriptor(); - - if (contractId == null) { - throw new IllegalArgumentException("contractId must not be null"); - } - if (payloadVersion <= 0) { - throw new IllegalArgumentException("payload version must be positive"); - } - String stableKey = contractId.value() + ":v" + payloadVersion; - if (!stableKeys.add(stableKey)) { - throw new IllegalArgumentException("duplicate contract identity: " + stableKey); - } - - if (schemaResource == null) { - throw new IllegalArgumentException("payload schema resource must not be null"); - } - if (!schemaResources.add(schemaResource)) { - throw new IllegalArgumentException("duplicate schema resource: " + schemaResource.value()); - } - if (schemaHash == null) { - throw new IllegalArgumentException("payload schema hash must not be null"); - } - - validateExactPayloadType(payloadType); - if (!exactPayloadTypes.add(payloadType)) { - throw new IllegalArgumentException( - "duplicate exact payload record type: " + payloadType.getName()); - } - - List componentOrder = validateComponentOrder(payloadType, declaredComponentOrder); - CompiledIntegrationEventContract.PayloadShape payloadShape = compilePayloadShape(payloadType); - if (descriptor == null) { - throw new IllegalArgumentException("contract descriptor must not be null"); - } - LogicalDestinationId logicalDestination = descriptor.logicalDestination(); - LogicalDestinationId existing = - destinationsByContract.putIfAbsent(contractId, logicalDestination); - if (existing != null && !existing.equals(logicalDestination)) { - throw new IllegalArgumentException( - "logical destination drift across versions of contract " + contractId.value()); - } - - return new CompiledIntegrationEventContract( - contractId, - payloadVersion, - payloadType, - componentOrder, - schemaResource, - schemaHash, - descriptor, - payloadShape); - } - - private static void validateExactPayloadType(Class payloadType) { - if (payloadType == null) { - throw new IllegalArgumentException("exact payload record type must not be null"); - } - if (!payloadType.isRecord() || !Modifier.isFinal(payloadType.getModifiers())) { - throw new IllegalArgumentException("exact payload type must be a final Java record"); - } - if (!IntegrationPayload.class.isAssignableFrom(payloadType)) { - throw new IllegalArgumentException("exact payload record must implement IntegrationPayload"); - } - } - - private static List validateComponentOrder( - Class payloadType, List declared) { - if (declared == null) { - throw new IllegalArgumentException("canonical record component order must not be null"); - } - List copied = List.copyOf(declared); - if (copied.stream().anyMatch(value -> value == null || value.isBlank()) - || new HashSet<>(copied).size() != copied.size()) { - throw new IllegalArgumentException( - "canonical record component order must contain unique non-blank names"); - } - List actual = - java.util.Arrays.stream(payloadType.getRecordComponents()) - .map(RecordComponent::getName) - .toList(); - if (!copied.equals(actual)) { - throw new IllegalArgumentException( - "canonical record component order must exactly match record declaration order"); - } - return copied; - } - - static CompiledIntegrationEventContract.PayloadShape compilePayloadShape( - Class payloadType) { - validateExactPayloadType(payloadType); - return compileDeclaredType(payloadType, new ArrayDeque<>()); - } - - private static CompiledIntegrationEventContract.PayloadShape compileDeclaredType( - Type declaredType, ArrayDeque> recordStack) { - if (declaredType instanceof WildcardType - || declaredType instanceof TypeVariable - || declaredType instanceof GenericArrayType) { - throw unsupportedDeclaredType(declaredType); - } - if (declaredType instanceof ParameterizedType parameterized) { - Type rawType = parameterized.getRawType(); - Type[] arguments = parameterized.getActualTypeArguments(); - if (arguments.length != 1 || !(rawType instanceof Class rawClass)) { - throw unsupportedDeclaredType(declaredType); - } - if (rawClass == Optional.class) { - return new CompiledIntegrationEventContract.PayloadShape( - CompiledIntegrationEventContract.PayloadKind.OPTIONAL, - Optional.class, - List.of(), - compileDeclaredType(arguments[0], recordStack)); - } - if (rawClass == List.class) { - return new CompiledIntegrationEventContract.PayloadShape( - CompiledIntegrationEventContract.PayloadKind.LIST, - List.class, - List.of(), - compileDeclaredType(arguments[0], recordStack)); - } - throw unsupportedDeclaredType(declaredType); - } - if (!(declaredType instanceof Class declaredClass) - || declaredClass.isArray() - || declaredClass.getTypeParameters().length != 0) { - throw unsupportedDeclaredType(declaredType); - } - - CompiledIntegrationEventContract.PayloadKind scalarKind = scalarKind(declaredClass); - if (scalarKind != null) { - return new CompiledIntegrationEventContract.PayloadShape( - scalarKind, declaredClass, List.of(), null); - } - if (declaredClass == Optional.class || declaredClass == List.class) { - throw new IllegalArgumentException( - "raw Optional/List payload component types are unsupported"); - } - if (!declaredClass.isRecord() || !Modifier.isFinal(declaredClass.getModifiers())) { - throw unsupportedDeclaredType(declaredType); - } - if (recordStack.contains(declaredClass)) { - throw new IllegalArgumentException("cyclic declared payload record graph is unsupported"); - } - - recordStack.addLast(declaredClass); - List components = new ArrayList<>(); - for (RecordComponent component : declaredClass.getRecordComponents()) { - components.add( - new CompiledIntegrationEventContract.PayloadComponent( - component.getName(), - component.getAccessor(), - compileDeclaredType(component.getGenericType(), recordStack))); - } - recordStack.removeLast(); - return new CompiledIntegrationEventContract.PayloadShape( - CompiledIntegrationEventContract.PayloadKind.RECORD, declaredClass, components, null); - } - - private static CompiledIntegrationEventContract.PayloadKind scalarKind(Class type) { - if (type == String.class) { - return CompiledIntegrationEventContract.PayloadKind.STRING; - } - if (type == boolean.class || type == Boolean.class) { - return CompiledIntegrationEventContract.PayloadKind.BOOLEAN; - } - if (type == byte.class - || type == Byte.class - || type == short.class - || type == Short.class - || type == int.class - || type == Integer.class - || type == long.class - || type == Long.class - || type == BigInteger.class) { - return CompiledIntegrationEventContract.PayloadKind.INTEGRAL; - } - if (type == float.class - || type == Float.class - || type == double.class - || type == Double.class - || type == BigDecimal.class) { - return CompiledIntegrationEventContract.PayloadKind.DECIMAL; - } - if (type.isEnum()) { - return CompiledIntegrationEventContract.PayloadKind.ENUM; - } - return null; - } - - private static IllegalArgumentException unsupportedDeclaredType(Type type) { - return new IllegalArgumentException( - "unsupported declared payload component type: " + type.getTypeName()); - } -} diff --git a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/contract/ContractCatalogDigest.java b/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/contract/ContractCatalogDigest.java deleted file mode 100644 index 57cf07bc..00000000 --- a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/contract/ContractCatalogDigest.java +++ /dev/null @@ -1,91 +0,0 @@ -package dev.caskeleton.adapter.outbound.messaging.contract; - -import dev.caskeleton.application.messaging.contract.ContractDescriptor; -import dev.caskeleton.application.messaging.contract.Sha256; -import java.nio.ByteBuffer; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.Comparator; -import java.util.List; - -/** Stable SHA-256 digest of closed contract semantics, independent of caller collection order. */ -public final class ContractCatalogDigest { - - private static final byte[] DOMAIN = - "ca-skeleton.messaging.contract-catalog-digest.v1".getBytes(StandardCharsets.UTF_8); - - private ContractCatalogDigest() {} - - public static Sha256 compute(List contracts) { - if (contracts == null || contracts.stream().anyMatch(java.util.Objects::isNull)) { - throw new IllegalArgumentException("compiled contracts must not be null"); - } - MessageDigest digest = sha256(); - digest.update(DOMAIN); - digest.update((byte) 0); - - contracts.stream() - .sorted( - Comparator.comparing( - (CompiledIntegrationEventContract contract) -> contract.contractId().value()) - .thenComparingInt(CompiledIntegrationEventContract::payloadVersion)) - .forEach(contract -> updateContract(digest, contract)); - return new Sha256(digest.digest()); - } - - private static void updateContract( - MessageDigest digest, CompiledIntegrationEventContract contract) { - field(digest, "contract", contract.stableKey()); - field(digest, "contractId", contract.contractId().value()); - field(digest, "payloadVersion", Integer.toString(contract.payloadVersion())); - field(digest, "payloadType", contract.exactPayloadRecordType().getName()); - for (int index = 0; index < contract.canonicalRecordComponentOrder().size(); index++) { - field( - digest, "component[" + index + "]", contract.canonicalRecordComponentOrder().get(index)); - } - field(digest, "schemaResource", contract.payloadSchemaResource().value()); - rawField(digest, "schemaHash", contract.payloadSchemaHash().bytes()); - - ContractDescriptor descriptor = contract.descriptor(); - field(digest, "ownerModule", descriptor.ownerModule()); - field(digest, "logicalDestination", descriptor.logicalDestination().value()); - field(digest, "serializerId", descriptor.serializerId()); - field(digest, "orderingRequired", Boolean.toString(descriptor.orderingRequired())); - field(digest, "maximumPayloadBytes", Integer.toString(descriptor.maximumPayloadBytes())); - field(digest, "maximumEnvelopeBytes", Integer.toString(descriptor.maximumEnvelopeBytes())); - field(digest, "sensitivity", descriptor.sensitivityClassification().name()); - field( - digest, - "requeueHorizonSeconds", - Long.toString(descriptor.sameEventRequeueHorizon().toSeconds())); - field( - digest, - "requeueHorizonNanos", - Integer.toString(descriptor.sameEventRequeueHorizon().toNanosPart())); - } - - private static void field(MessageDigest digest, String tag, String value) { - rawField(digest, tag, value.getBytes(StandardCharsets.UTF_8)); - } - - private static void rawField(MessageDigest digest, String tag, byte[] value) { - byte[] tagBytes = tag.getBytes(StandardCharsets.UTF_8); - digest.update(unsignedLength(tagBytes.length)); - digest.update(tagBytes); - digest.update(unsignedLength(value.length)); - digest.update(value); - } - - private static byte[] unsignedLength(int length) { - return ByteBuffer.allocate(Integer.BYTES).putInt(length).array(); - } - - private static MessageDigest sha256() { - try { - return MessageDigest.getInstance("SHA-256"); - } catch (NoSuchAlgorithmException exception) { - throw new IllegalStateException("Java runtime does not provide SHA-256", exception); - } - } -} diff --git a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/destination/CompiledPublicationBinding.java b/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/destination/CompiledPublicationBinding.java deleted file mode 100644 index 43cdeb88..00000000 --- a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/destination/CompiledPublicationBinding.java +++ /dev/null @@ -1,105 +0,0 @@ -package dev.caskeleton.adapter.outbound.messaging.destination; - -import dev.caskeleton.adapter.outbound.messaging.config.MessagingCapabilityCardRegistry; -import dev.caskeleton.adapter.outbound.messaging.contract.CompiledIntegrationEventContract; -import dev.caskeleton.application.messaging.contract.LogicalDestinationId; -import dev.caskeleton.application.messaging.contract.Sha256; -import java.util.HashSet; -import java.util.List; - -/** Immutable exact contract/version to physical deployment binding compiled without I/O. */ -public final class CompiledPublicationBinding { - - private final CompiledIntegrationEventContract contract; - private final LogicalDestinationId logicalDestination; - private final String physicalTopic; - private final List bootstrapServers; - private final int effectiveMaximumRecordBytes; - private final MessagingCapabilityCardRegistry.ExactSelection selectedCards; - private final Sha256 settingsDigest; - private final Sha256 schemaSetDigest; - - CompiledPublicationBinding( - CompiledIntegrationEventContract contract, - LogicalDestinationId logicalDestination, - String physicalTopic, - List bootstrapServers, - int effectiveMaximumRecordBytes, - MessagingCapabilityCardRegistry.ExactSelection selectedCards, - Sha256 settingsDigest, - Sha256 schemaSetDigest) { - if (contract == null - || logicalDestination == null - || !logicalDestination.equals(contract.descriptor().logicalDestination()) - || !DestinationBindingSettings.DestinationBinding.validPhysicalTopic(physicalTopic) - || bootstrapServers == null - || bootstrapServers.isEmpty() - || bootstrapServers.stream() - .anyMatch( - server -> - server == null - || !DestinationBindingSettings.DestinationBinding.validBootstrapServer( - server)) - || new HashSet<>(bootstrapServers).size() != bootstrapServers.size() - || effectiveMaximumRecordBytes <= 0 - || effectiveMaximumRecordBytes > contract.descriptor().maximumEnvelopeBytes() - || selectedCards == null - || settingsDigest == null - || schemaSetDigest == null) { - throw new IllegalArgumentException("compiled publication binding fields must be canonical"); - } - MessagingCapabilityCardRegistry.exactFirstR2().validate(selectedCards); - this.contract = contract; - this.logicalDestination = logicalDestination; - this.physicalTopic = physicalTopic; - this.bootstrapServers = List.copyOf(bootstrapServers); - this.effectiveMaximumRecordBytes = effectiveMaximumRecordBytes; - this.selectedCards = selectedCards; - this.settingsDigest = settingsDigest; - this.schemaSetDigest = schemaSetDigest; - } - - CompiledIntegrationEventContract contract() { - return contract; - } - - /** Static bridge for adapter-internal composition without an instance response surface. */ - public static CompiledIntegrationEventContract contractOf(CompiledPublicationBinding binding) { - if (binding == null) { - throw new IllegalArgumentException("compiled publication binding must not be null"); - } - return binding.contract; - } - - public LogicalDestinationId logicalDestination() { - return logicalDestination; - } - - public String physicalTopic() { - return physicalTopic; - } - - public List bootstrapServers() { - return bootstrapServers; - } - - public int effectiveMaximumRecordBytes() { - return effectiveMaximumRecordBytes; - } - - MessagingCapabilityCardRegistry.ExactSelection selectedCards() { - return selectedCards; - } - - public Sha256 settingsDigest() { - return settingsDigest; - } - - public Sha256 schemaSetDigest() { - return schemaSetDigest; - } - - public String stableKey() { - return contract.stableKey() + "@" + logicalDestination.value(); - } -} diff --git a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/destination/DestinationBindingCompiler.java b/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/destination/DestinationBindingCompiler.java deleted file mode 100644 index 9759d0fb..00000000 --- a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/destination/DestinationBindingCompiler.java +++ /dev/null @@ -1,248 +0,0 @@ -package dev.caskeleton.adapter.outbound.messaging.destination; - -import dev.caskeleton.adapter.outbound.messaging.config.MessagingCapabilityCardRegistry; -import dev.caskeleton.adapter.outbound.messaging.contract.CompiledIntegrationEventContract; -import dev.caskeleton.application.messaging.contract.LogicalDestinationId; -import dev.caskeleton.application.messaging.contract.Sha256; -import java.nio.ByteBuffer; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** Pure local compiler joining exact contracts, deployment destinations and closed cards. */ -public final class DestinationBindingCompiler { - - List compile( - List contracts, - DestinationBindingSettings settings, - MessagingCapabilityCardRegistry cardRegistry) { - if (contracts == null || settings == null || cardRegistry == null) { - throw new IllegalArgumentException("binding compiler inputs must not be null"); - } - if (contracts.stream().anyMatch(java.util.Objects::isNull)) { - throw new IllegalArgumentException("compiled contracts must not contain null"); - } - cardRegistry.validate(settings.selectedCards()); - validateRequiredProfiles(settings); - if (!settings.destinations().isEmpty() && settings.legacyAliases().isPresent()) { - throw new IllegalArgumentException( - "legacy and canonical destination configuration must not be simultaneous"); - } - - Map contractsByKey = indexContracts(contracts); - Map destinations = - indexDestinations(settings.destinations()); - Map bindingByContract = - indexContractBindings(destinations.values(), contractsByKey); - - for (CompiledIntegrationEventContract contract : contracts) { - if (!bindingByContract.containsKey(contract.stableKey())) { - throw new IllegalArgumentException( - "missing exact destination binding for contract " + contract.stableKey()); - } - } - - Sha256 settingsDigest = settingsDigest(settings); - Sha256 schemaSetDigest = schemaSetDigest(contracts); - List result = new ArrayList<>(contracts.size()); - contracts.stream() - .sorted(Comparator.comparing(CompiledIntegrationEventContract::stableKey)) - .forEach( - contract -> { - DestinationBindingSettings.DestinationBinding destination = - bindingByContract.get(contract.stableKey()); - int effectiveMaximumRecordBytes = - Math.min( - contract.descriptor().maximumEnvelopeBytes(), - destination.maximumRecordBytes()); - if (effectiveMaximumRecordBytes <= 0) { - throw new IllegalArgumentException( - "effective maximum record bytes must be positive"); - } - result.add( - new CompiledPublicationBinding( - contract, - destination.logicalDestination(), - destination.physicalTopic(), - destination.bootstrapServers(), - effectiveMaximumRecordBytes, - settings.selectedCards(), - settingsDigest, - schemaSetDigest)); - }); - return List.copyOf(result); - } - - /** Narrow immutable composition bridge for callers in sibling messaging adapter packages. */ - public static List compileExact( - List contracts, - DestinationBindingSettings settings, - MessagingCapabilityCardRegistry cardRegistry) { - return new DestinationBindingCompiler().compile(contracts, settings, cardRegistry); - } - - public Sha256 settingsDigest(DestinationBindingSettings settings) { - if (settings == null) { - throw new IllegalArgumentException("destination settings must not be null"); - } - MessageDigest digest = digest("ca-skeleton.messaging.destination-settings-digest.v1"); - field(digest, "orderingRequired", Boolean.toString(settings.orderingRequired())); - field( - digest, "schemaValidationRequired", Boolean.toString(settings.schemaValidationRequired())); - field(digest, "secureTransportRequired", Boolean.toString(settings.secureTransportRequired())); - updateSelection(digest, settings.selectedCards()); - settings.destinations().stream() - .sorted(Comparator.comparing(destination -> destination.logicalDestination().value())) - .forEach(destination -> updateDestination(digest, destination)); - settings - .legacyAliases() - .ifPresent( - legacy -> { - field(digest, "legacyBroker", legacy.brokerAlias().orElse("")); - field(digest, "legacyTopic", legacy.topicAlias().orElse("")); - legacy.bootstrapServerAliases().stream() - .sorted() - .forEach(value -> field(digest, "legacyBootstrap", value)); - }); - return new Sha256(digest.digest()); - } - - public Sha256 schemaSetDigest(List contracts) { - if (contracts == null || contracts.stream().anyMatch(java.util.Objects::isNull)) { - throw new IllegalArgumentException("compiled contracts must not be null"); - } - MessageDigest digest = digest("ca-skeleton.messaging.schema-set-digest.v1"); - contracts.stream() - .sorted(Comparator.comparing(CompiledIntegrationEventContract::stableKey)) - .forEach( - contract -> { - field(digest, "contract", contract.stableKey()); - field(digest, "schemaResource", contract.payloadSchemaResource().value()); - rawField(digest, "schemaHash", contract.payloadSchemaHash().bytes()); - }); - return new Sha256(digest.digest()); - } - - private static void validateRequiredProfiles(DestinationBindingSettings settings) { - if (!settings.orderingRequired()) { - throw new IllegalArgumentException("ordering requirement cannot be relaxed"); - } - if (!settings.schemaValidationRequired()) { - throw new IllegalArgumentException("schema validation requirement cannot be relaxed"); - } - if (!settings.secureTransportRequired()) { - throw new IllegalArgumentException("security requirement cannot be relaxed"); - } - } - - private static Map indexContracts( - List contracts) { - Map result = new HashMap<>(); - for (CompiledIntegrationEventContract contract : contracts) { - if (result.putIfAbsent(contract.stableKey(), contract) != null) { - throw new IllegalArgumentException("duplicate compiled contract: " + contract.stableKey()); - } - } - return result; - } - - private static Map - indexDestinations(List destinations) { - Map result = - new HashMap<>(); - for (DestinationBindingSettings.DestinationBinding destination : destinations) { - if (result.putIfAbsent(destination.logicalDestination(), destination) != null) { - throw new IllegalArgumentException( - "duplicate destination binding: " + destination.logicalDestination().value()); - } - } - return result; - } - - private static Map indexContractBindings( - java.util.Collection destinations, - Map contractsByKey) { - Map result = new HashMap<>(); - Set usedDestinations = new HashSet<>(); - for (DestinationBindingSettings.DestinationBinding destination : destinations) { - for (DestinationBindingSettings.ContractVersion reference : destination.contracts()) { - CompiledIntegrationEventContract contract = contractsByKey.get(reference.stableKey()); - if (contract == null) { - throw new IllegalArgumentException( - "extra contract binding is not in the closed catalog: " + reference.stableKey()); - } - if (!contract.descriptor().logicalDestination().equals(destination.logicalDestination())) { - throw new IllegalArgumentException( - "contract/destination identity mismatch for " + reference.stableKey()); - } - if (result.putIfAbsent(reference.stableKey(), destination) != null) { - throw new IllegalArgumentException( - "duplicate exact contract binding: " + reference.stableKey()); - } - usedDestinations.add(destination.logicalDestination()); - } - } - if (usedDestinations.size() != destinations.size()) { - throw new IllegalArgumentException("extra destination binding has no closed contract"); - } - return result; - } - - private static void updateDestination( - MessageDigest digest, DestinationBindingSettings.DestinationBinding destination) { - field(digest, "logicalDestination", destination.logicalDestination().value()); - destination.contracts().stream() - .sorted(Comparator.comparing(DestinationBindingSettings.ContractVersion::stableKey)) - .forEach(contract -> field(digest, "contract", contract.stableKey())); - field(digest, "physicalTopic", destination.physicalTopic()); - destination.bootstrapServers().stream() - .sorted() - .forEach(server -> field(digest, "bootstrapServer", server)); - field(digest, "maximumRecordBytes", Integer.toString(destination.maximumRecordBytes())); - } - - private static void updateSelection( - MessageDigest digest, MessagingCapabilityCardRegistry.ExactSelection selection) { - field(digest, "semanticCard", selection.semanticCardId()); - field(digest, "producerCard", selection.producerCardId()); - field(digest, "dispatchCard", selection.dispatchCardId()); - field(digest, "claimCard", selection.claimCardId()); - field(digest, "serializationCard", selection.serializationCardId()); - field(digest, "topicCard", selection.topicCardId()); - field(digest, "securityCard", selection.securityCardId()); - field(digest, "compressionCard", selection.compressionCardId()); - field(digest, "orderingCard", selection.orderingCardId()); - field(digest, "transactionCard", selection.transactionCardId()); - field(digest, "operatorControlCard", selection.operatorControlCardId()); - } - - private static MessageDigest digest(String domain) { - try { - MessageDigest result = MessageDigest.getInstance("SHA-256"); - result.update(domain.getBytes(StandardCharsets.UTF_8)); - result.update((byte) 0); - return result; - } catch (NoSuchAlgorithmException exception) { - throw new IllegalStateException("Java runtime does not provide SHA-256", exception); - } - } - - private static void field(MessageDigest digest, String tag, String value) { - rawField(digest, tag, value.getBytes(StandardCharsets.UTF_8)); - } - - private static void rawField(MessageDigest digest, String tag, byte[] value) { - byte[] tagBytes = tag.getBytes(StandardCharsets.UTF_8); - digest.update(ByteBuffer.allocate(Integer.BYTES).putInt(tagBytes.length).array()); - digest.update(tagBytes); - digest.update(ByteBuffer.allocate(Integer.BYTES).putInt(value.length).array()); - digest.update(value); - } -} diff --git a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/destination/DestinationBindingSettings.java b/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/destination/DestinationBindingSettings.java deleted file mode 100644 index 8fb7ffb5..00000000 --- a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/destination/DestinationBindingSettings.java +++ /dev/null @@ -1,238 +0,0 @@ -package dev.caskeleton.adapter.outbound.messaging.destination; - -import dev.caskeleton.adapter.outbound.messaging.config.MessagingCapabilityCardRegistry; -import dev.caskeleton.application.messaging.contract.ContractId; -import dev.caskeleton.application.messaging.contract.LogicalDestinationId; -import java.util.HashSet; -import java.util.List; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; - -/** Deployment-owned, bounded canonical destination binding inputs without credential values. */ -public final class DestinationBindingSettings { - - private final List destinations; - private final MessagingCapabilityCardRegistry.ExactSelection selectedCards; - private final boolean orderingRequired; - private final boolean schemaValidationRequired; - private final boolean secureTransportRequired; - private final Optional legacyAliases; - - public DestinationBindingSettings( - List destinations, - MessagingCapabilityCardRegistry.ExactSelection selectedCards, - boolean orderingRequired, - boolean schemaValidationRequired, - boolean secureTransportRequired, - Optional legacyAliases) { - if (destinations == null || selectedCards == null || legacyAliases == null) { - throw new IllegalArgumentException("destination binding settings fields must not be null"); - } - if (destinations.stream().anyMatch(java.util.Objects::isNull)) { - throw new IllegalArgumentException("destination binding must not be null"); - } - List copiedDestinations = List.copyOf(destinations); - Set logicalDestinations = new HashSet<>(); - Set physicalTopics = new HashSet<>(); - for (DestinationBinding destination : copiedDestinations) { - if (!logicalDestinations.add(destination.logicalDestination())) { - throw new IllegalArgumentException("duplicate destination binding"); - } - if (!physicalTopics.add(destination.physicalTopic())) { - throw new IllegalArgumentException("duplicate physical topic binding"); - } - } - this.destinations = copiedDestinations; - this.selectedCards = selectedCards; - this.orderingRequired = orderingRequired; - this.schemaValidationRequired = schemaValidationRequired; - this.secureTransportRequired = secureTransportRequired; - this.legacyAliases = legacyAliases; - } - - List destinations() { - return destinations; - } - - MessagingCapabilityCardRegistry.ExactSelection selectedCards() { - return selectedCards; - } - - public boolean orderingRequired() { - return orderingRequired; - } - - public boolean schemaValidationRequired() { - return schemaValidationRequired; - } - - public boolean secureTransportRequired() { - return secureTransportRequired; - } - - Optional legacyAliases() { - return legacyAliases; - } - - /** Narrow immutable composition bridge for sibling messaging adapter packages. */ - public static List destinationsOf(DestinationBindingSettings settings) { - return requireSettings(settings).destinations; - } - - /** Narrow immutable composition bridge for sibling messaging adapter packages. */ - public static Optional legacyAliasesOf(DestinationBindingSettings settings) { - return requireSettings(settings).legacyAliases; - } - - private static DestinationBindingSettings requireSettings(DestinationBindingSettings settings) { - if (settings == null) { - throw new IllegalArgumentException("destination binding settings must not be null"); - } - return settings; - } - - public record ContractVersion(ContractId contractId, int payloadVersion) { - - public ContractVersion { - if (contractId == null || payloadVersion <= 0) { - throw new IllegalArgumentException( - "contract binding identity and positive version required"); - } - } - - public String stableKey() { - return contractId.value() + ":v" + payloadVersion; - } - } - - public static final class DestinationBinding { - - private static final int MAXIMUM_BOOTSTRAP_SERVERS = 32; - private static final String TOPIC_GRAMMAR = "[A-Za-z0-9][A-Za-z0-9._-]{0,248}"; - private static final String BOOTSTRAP_GRAMMAR = - "[A-Za-z0-9](?:[A-Za-z0-9.-]{0,251}[A-Za-z0-9])?:[1-9][0-9]{0,4}"; - private final LogicalDestinationId logicalDestination; - private final List contracts; - private final String physicalTopic; - private final List bootstrapServers; - private final int maximumRecordBytes; - - public DestinationBinding( - LogicalDestinationId logicalDestination, - List contracts, - String physicalTopic, - List bootstrapServers, - int maximumRecordBytes) { - if (logicalDestination == null - || contracts == null - || contracts.isEmpty() - || physicalTopic == null - || !physicalTopic.matches(TOPIC_GRAMMAR) - || bootstrapServers == null - || bootstrapServers.isEmpty() - || bootstrapServers.size() > MAXIMUM_BOOTSTRAP_SERVERS - || maximumRecordBytes <= 0) { - throw new IllegalArgumentException("invalid bounded canonical destination binding"); - } - contracts = List.copyOf(contracts); - if (new HashSet<>(contracts).size() != contracts.size()) { - throw new IllegalArgumentException("destination contract identities must be unique"); - } - if (bootstrapServers.stream() - .anyMatch(server -> server == null || !validBootstrapServer(server))) { - throw new IllegalArgumentException( - "bootstrap servers must be bounded host:port values without secrets"); - } - if (new HashSet<>(bootstrapServers).size() != bootstrapServers.size()) { - throw new IllegalArgumentException("bootstrap servers must be unique"); - } - this.logicalDestination = logicalDestination; - this.contracts = contracts; - this.physicalTopic = physicalTopic; - this.bootstrapServers = bootstrapServers.stream().sorted().toList(); - this.maximumRecordBytes = maximumRecordBytes; - } - - public LogicalDestinationId logicalDestination() { - return logicalDestination; - } - - List contracts() { - return contracts; - } - - public String physicalTopic() { - return physicalTopic; - } - - public List bootstrapServers() { - return bootstrapServers; - } - - public int maximumRecordBytes() { - return maximumRecordBytes; - } - - @Override - public boolean equals(Object other) { - if (this == other) { - return true; - } - if (!(other instanceof DestinationBinding that)) { - return false; - } - return maximumRecordBytes == that.maximumRecordBytes - && logicalDestination.equals(that.logicalDestination) - && contracts.equals(that.contracts) - && physicalTopic.equals(that.physicalTopic) - && bootstrapServers.equals(that.bootstrapServers); - } - - @Override - public int hashCode() { - return Objects.hash( - logicalDestination, contracts, physicalTopic, bootstrapServers, maximumRecordBytes); - } - - static boolean validPhysicalTopic(String topic) { - return topic != null && topic.matches(TOPIC_GRAMMAR); - } - - static boolean validBootstrapServer(String server) { - if (!server.matches(BOOTSTRAP_GRAMMAR)) { - return false; - } - int port = Integer.parseInt(server.substring(server.lastIndexOf(':') + 1)); - return port <= 65_535; - } - } - - /** Read-only migration aliases used solely to reject simultaneous legacy and canonical inputs. */ - public record LegacyAliases( - Optional brokerAlias, - Optional topicAlias, - List bootstrapServerAliases) { - - public LegacyAliases { - if (brokerAlias == null || topicAlias == null || bootstrapServerAliases == null) { - throw new IllegalArgumentException("legacy aliases must not be null"); - } - if (brokerAlias.filter(value -> !value.matches("[a-z][a-z0-9-]{0,95}")).isPresent() - || topicAlias.filter(value -> !DestinationBinding.validPhysicalTopic(value)).isPresent() - || bootstrapServerAliases.stream() - .anyMatch( - alias -> alias == null || !DestinationBinding.validBootstrapServer(alias))) { - throw new IllegalArgumentException( - "legacy aliases must be canonical identifiers without secrets"); - } - bootstrapServerAliases = List.copyOf(bootstrapServerAliases); - if (new HashSet<>(bootstrapServerAliases).size() != bootstrapServerAliases.size()) { - throw new IllegalArgumentException("legacy bootstrap aliases must be unique"); - } - if (brokerAlias.isEmpty() && topicAlias.isEmpty() && bootstrapServerAliases.isEmpty()) { - throw new IllegalArgumentException("at least one legacy alias must be present"); - } - } - } -} diff --git a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/destination/PartitionKeyV1.java b/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/destination/PartitionKeyV1.java deleted file mode 100644 index a6c74dbd..00000000 --- a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/destination/PartitionKeyV1.java +++ /dev/null @@ -1,132 +0,0 @@ -package dev.caskeleton.adapter.outbound.messaging.destination; - -import dev.caskeleton.application.messaging.contract.LogicalDestinationId; -import dev.caskeleton.application.messaging.event.AggregateIdentity; -import java.nio.ByteBuffer; -import java.nio.CharBuffer; -import java.nio.charset.CharacterCodingException; -import java.nio.charset.CodingErrorAction; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.Arrays; -import java.util.HexFormat; -import java.util.Objects; - -/** - * Exact domain-separated partition-key v1 algorithm shared by polling and future dispatch cards. - */ -public final class PartitionKeyV1 { - - private static final byte[] DOMAIN = - "ca-skeleton.messaging.partition-key.v1".getBytes(StandardCharsets.UTF_8); - - private PartitionKeyV1() {} - - public static Value derive( - LogicalDestinationId logicalDestination, AggregateIdentity aggregateIdentity) { - if (aggregateIdentity == null) { - throw new IllegalArgumentException("aggregate identity must not be null"); - } - return deriveCanonicalComponents( - aggregateIdentity.tenantScope(), - logicalDestination, - aggregateIdentity.aggregateType(), - aggregateIdentity.aggregateId()); - } - - /** - * Cross-language vector entry point. Callers retain ownership of their canonical component - * grammar; this method never substitutes a missing tenant scope. - */ - public static Value deriveCanonicalComponents( - String tenantScope, - LogicalDestinationId logicalDestination, - String aggregateType, - String aggregateId) { - requireBounded("tenantScope", tenantScope, 96); - if (logicalDestination == null) { - throw new IllegalArgumentException("logicalDestination must not be null"); - } - requireBounded("aggregateType", aggregateType, 64); - requireBounded("aggregateId", aggregateId, 160); - - MessageDigest digest = sha256(); - digest.update(DOMAIN); - digest.update((byte) 0); - updateLengthPrefixed(digest, strictUtf8("tenantScope", tenantScope)); - updateLengthPrefixed(digest, strictUtf8("logicalDestination", logicalDestination.value())); - updateLengthPrefixed(digest, strictUtf8("aggregateType", aggregateType)); - updateLengthPrefixed(digest, strictUtf8("aggregateId", aggregateId)); - String text = HexFormat.of().formatHex(digest.digest()); - return new Value(text, text.getBytes(StandardCharsets.US_ASCII)); - } - - private static void updateLengthPrefixed(MessageDigest digest, byte[] bytes) { - digest.update(ByteBuffer.allocate(Integer.BYTES).putInt(bytes.length).array()); - digest.update(bytes); - } - - private static byte[] strictUtf8(String field, String value) { - try { - ByteBuffer encoded = - StandardCharsets.UTF_8 - .newEncoder() - .onMalformedInput(CodingErrorAction.REPORT) - .onUnmappableCharacter(CodingErrorAction.REPORT) - .encode(CharBuffer.wrap(value)); - byte[] bytes = new byte[encoded.remaining()]; - encoded.get(bytes); - return bytes; - } catch (CharacterCodingException exception) { - throw new IllegalArgumentException(field + " must contain strict valid UTF-8", exception); - } - } - - private static void requireBounded(String field, String value, int maximumLength) { - if (value == null || value.isBlank() || value.length() > maximumLength) { - throw new IllegalArgumentException( - field + " must be a canonical non-blank value of at most " + maximumLength + " chars"); - } - } - - private static MessageDigest sha256() { - try { - return MessageDigest.getInstance("SHA-256"); - } catch (NoSuchAlgorithmException exception) { - throw new IllegalStateException("Java runtime does not provide SHA-256", exception); - } - } - - @SuppressWarnings("ArrayRecordComponent") - public record Value(String text, byte[] bytes) { - - public Value { - if (text == null - || !text.matches("[0-9a-f]{64}") - || bytes == null - || !Arrays.equals(bytes, text.getBytes(StandardCharsets.US_ASCII))) { - throw new IllegalArgumentException("partition key must be exact lower-case hex ASCII"); - } - bytes = bytes.clone(); - } - - @Override - public byte[] bytes() { - return bytes.clone(); - } - - @Override - public boolean equals(Object other) { - return this == other - || (other instanceof Value that - && text.equals(that.text) - && Arrays.equals(bytes, that.bytes)); - } - - @Override - public int hashCode() { - return 31 * Objects.hash(text) + Arrays.hashCode(bytes); - } - } -} diff --git a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/envelope/DeterministicEnvelopeWriter.java b/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/envelope/DeterministicEnvelopeWriter.java deleted file mode 100644 index 758b7177..00000000 --- a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/envelope/DeterministicEnvelopeWriter.java +++ /dev/null @@ -1,548 +0,0 @@ -package dev.caskeleton.adapter.outbound.messaging.envelope; - -import dev.caskeleton.adapter.outbound.messaging.contract.CompiledIntegrationEventContract; -import dev.caskeleton.adapter.outbound.messaging.contract.CompiledIntegrationEventContract.PayloadComponent; -import dev.caskeleton.adapter.outbound.messaging.contract.CompiledIntegrationEventContract.PayloadKind; -import dev.caskeleton.adapter.outbound.messaging.contract.CompiledIntegrationEventContract.PayloadShape; -import dev.caskeleton.application.messaging.contract.IntegrationPayload; -import dev.caskeleton.application.messaging.event.IntegrationEventDraft; -import java.io.ByteArrayOutputStream; -import java.math.BigDecimal; -import java.nio.ByteBuffer; -import java.nio.CharBuffer; -import java.nio.charset.CharacterCodingException; -import java.nio.charset.CodingErrorAction; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Optional; -import tools.jackson.core.JsonEncoding; -import tools.jackson.core.JsonGenerator; -import tools.jackson.core.ObjectWriteContext; -import tools.jackson.core.StreamWriteConstraints; -import tools.jackson.core.json.JsonFactory; - -/** - * Closed declared-shape writer for envelope v1. - * - *

Every record accessor is read exactly once into an immutable snapshot. The payload is encoded - * exactly once and those exact trusted bytes are then embedded in the envelope without any raw JSON - * parser or generator API. - */ -final class DeterministicEnvelopeWriter { - - private static final byte[] PAYLOAD_PROPERTY = - ",\"payload\":".getBytes(StandardCharsets.US_ASCII); - - private final EnvelopeAdmissionLimits limits; - private final JsonFactory jsonFactory; - - DeterministicEnvelopeWriter(EnvelopeAdmissionLimits limits) { - if (limits == null) { - throw new IllegalArgumentException("envelope admission limits must not be null"); - } - this.limits = limits; - this.jsonFactory = - JsonFactory.builder() - .streamWriteConstraints( - StreamWriteConstraints.builder().maxNestingDepth(limits.maximumDepth()).build()) - .build(); - } - - EncodedEnvelope write(IntegrationEventDraft draft, CompiledIntegrationEventContract contract) { - if (draft == null || contract == null) { - throw new IllegalArgumentException("draft and compiled contract must not be null"); - } - IntegrationPayload payload = draft.featurePayload(); - if (payload.getClass() != contract.exactPayloadRecordType()) { - throw new IllegalArgumentException( - "draft payload must have the exact registered final record class"); - } - if (!draft.contractId().equals(contract.contractId()) - || draft.payloadVersion() != contract.payloadVersion()) { - throw new IllegalArgumentException("draft identity must match the exact compiled contract"); - } - - SnapshotValue payloadSnapshot = - snapshot(CompiledIntegrationEventContract.payloadShapeOf(contract), payload, 1); - byte[] payloadBytes = - generate( - limits.maximumPayloadBytes(), generator -> writeSnapshot(generator, payloadSnapshot)); - byte[] metadataBytes = - generate( - limits.maximumEnvelopeBytes(), generator -> writeEnvelopeMetadata(generator, draft)); - byte[] envelopeBytes = embedExactPayload(metadataBytes, payloadBytes); - return new EncodedEnvelope(envelopeBytes, payloadBytes); - } - - private SnapshotValue snapshot(PayloadShape shape, Object value, int depth) { - requireDepth(depth); - PayloadKind kind = PayloadShape.kindOf(shape); - return switch (kind) { - case RECORD -> snapshotRecord(shape, value, depth); - case OPTIONAL -> snapshotOptional(shape, value, depth); - case LIST -> snapshotList(shape, value, depth); - case STRING -> snapshotString(shape, value); - case BOOLEAN -> snapshotBoolean(shape, value); - case INTEGRAL -> snapshotIntegral(shape, value); - case DECIMAL -> snapshotDecimal(shape, value); - case ENUM -> snapshotEnum(shape, value); - }; - } - - private SnapshotValue snapshotRecord(PayloadShape shape, Object value, int depth) { - Class exactType = PayloadShape.exactJavaTypeOf(shape); - if (value == null || value.getClass() != exactType) { - throw new IllegalArgumentException("exact declared final record value required"); - } - List components = PayloadShape.componentsOf(shape); - if (components.size() > limits.maximumObjectProperties()) { - throw new IllegalArgumentException("record exceeds object properties admission limit"); - } - List names = new ArrayList<>(components.size()); - List values = new ArrayList<>(components.size()); - for (PayloadComponent component : components) { - String name = PayloadComponent.nameOf(component); - requireString("record component name", name); - names.add(name); - values.add( - snapshot( - PayloadComponent.shapeOf(component), - CompiledIntegrationEventContract.readPayloadComponentOnce(component, value), - depth + 1)); - } - return SnapshotValue.object(names, values); - } - - private SnapshotValue snapshotOptional(PayloadShape shape, Object value, int depth) { - if (value == null || value.getClass() != Optional.class) { - throw new IllegalArgumentException("a non-null exact Optional value is required"); - } - Optional optional = (Optional) value; - return optional.isEmpty() - ? SnapshotValue.nullValue() - : snapshot(PayloadShape.elementShapeOf(shape), optional.get(), depth); - } - - private SnapshotValue snapshotList(PayloadShape shape, Object value, int depth) { - if (!(value instanceof List list)) { - throw new IllegalArgumentException("a value declared as List is required"); - } - int declaredSize = boundedListSize(list); - List snapshots = new ArrayList<>(declaredSize); - PayloadShape elementShape = PayloadShape.elementShapeOf(shape); - Iterator iterator = listIterator(list); - for (int index = 0; index < declaredSize; index++) { - if (!hasNext(iterator)) { - throw mutatedList(); - } - snapshots.add(snapshot(elementShape, next(iterator), depth + 1)); - } - if (hasNext(iterator)) { - throw mutatedList(); - } - return SnapshotValue.array(snapshots); - } - - private int boundedListSize(List list) { - int size; - try { - size = list.size(); - } catch (RuntimeException exception) { - throw mutatedList(exception); - } - if (size < 0 || size > limits.maximumArrayItems()) { - throw new IllegalArgumentException("list exceeds array items admission limit"); - } - return size; - } - - private static Iterator listIterator(List list) { - try { - return list.iterator(); - } catch (RuntimeException exception) { - throw mutatedList(exception); - } - } - - private static boolean hasNext(Iterator iterator) { - try { - return iterator.hasNext(); - } catch (RuntimeException exception) { - throw mutatedList(exception); - } - } - - private static Object next(Iterator iterator) { - try { - return iterator.next(); - } catch (RuntimeException exception) { - throw mutatedList(exception); - } - } - - private static IllegalArgumentException mutatedList() { - return new IllegalArgumentException("list mutated or failed during bounded snapshot"); - } - - private static IllegalArgumentException mutatedList(RuntimeException cause) { - return new IllegalArgumentException("list mutated or failed during bounded snapshot", cause); - } - - private SnapshotValue snapshotString(PayloadShape shape, Object value) { - requireExactRuntimeType(shape, value); - String text = (String) value; - requireString("string value", text); - return SnapshotValue.string(text); - } - - private SnapshotValue snapshotBoolean(PayloadShape shape, Object value) { - requireExactRuntimeType(shape, value); - return SnapshotValue.bool((Boolean) value); - } - - private SnapshotValue snapshotIntegral(PayloadShape shape, Object value) { - requireExactRuntimeType(shape, value); - String text = value.toString(); - requireNumberDigits(text); - return SnapshotValue.number(text); - } - - private SnapshotValue snapshotDecimal(PayloadShape shape, Object value) { - requireExactRuntimeType(shape, value); - BigDecimal decimal; - if (value instanceof BigDecimal exact) { - decimal = exact; - } else if (value instanceof Double floating) { - if (!Double.isFinite(floating)) { - throw new IllegalArgumentException("decimal values must be finite"); - } - decimal = BigDecimal.valueOf(floating); - } else if (value instanceof Float floating) { - if (!Float.isFinite(floating)) { - throw new IllegalArgumentException("decimal values must be finite"); - } - decimal = new BigDecimal(Float.toString(floating)); - } else { - throw new IllegalArgumentException("unsupported declared decimal runtime class"); - } - BigDecimal canonical = canonicalDecimal(decimal); - String text = canonical.toPlainString(); - requireNumberDigits(text); - return SnapshotValue.number(text); - } - - private SnapshotValue snapshotEnum(PayloadShape shape, Object value) { - requireExactRuntimeType(shape, value); - String name = ((Enum) value).name(); - requireString("enum value", name); - return SnapshotValue.string(name); - } - - private static void requireExactRuntimeType(PayloadShape shape, Object value) { - Class declared = PayloadShape.exactJavaTypeOf(shape); - Class runtimeType = wrapperType(declared); - if (value == null || value.getClass() != runtimeType) { - throw new IllegalArgumentException("payload scalar must match its exact declared type"); - } - } - - private static Class wrapperType(Class type) { - if (!type.isPrimitive()) { - return type; - } - if (type == boolean.class) { - return Boolean.class; - } - if (type == byte.class) { - return Byte.class; - } - if (type == short.class) { - return Short.class; - } - if (type == int.class) { - return Integer.class; - } - if (type == long.class) { - return Long.class; - } - if (type == float.class) { - return Float.class; - } - if (type == double.class) { - return Double.class; - } - throw new IllegalArgumentException("unsupported primitive payload component"); - } - - private void writeSnapshot(JsonGenerator generator, SnapshotValue snapshot) { - switch (snapshot.kind()) { - case NULL -> generator.writeNull(); - case STRING -> generator.writeString((String) snapshot.scalar()); - case BOOLEAN -> generator.writeBoolean((Boolean) snapshot.scalar()); - case NUMBER -> generator.writeNumber((String) snapshot.scalar()); - case ARRAY -> { - generator.writeStartArray(); - for (SnapshotValue value : snapshot.values()) { - writeSnapshot(generator, value); - } - generator.writeEndArray(); - } - case OBJECT -> { - generator.writeStartObject(); - for (int index = 0; index < snapshot.names().size(); index++) { - generator.writeName(snapshot.names().get(index)); - writeSnapshot(generator, snapshot.values().get(index)); - } - generator.writeEndObject(); - } - default -> throw new IllegalStateException("unknown immutable payload snapshot kind"); - } - } - - private void writeEnvelopeMetadata(JsonGenerator generator, IntegrationEventDraft draft) { - if (10 > limits.maximumObjectProperties()) { - throw new IllegalArgumentException("envelope exceeds object properties admission limit"); - } - generator.writeStartObject(); - generator.writeNumberProperty("envelopeVersion", 1); - writeStringProperty(generator, "eventId", draft.eventId().value()); - writeStringProperty(generator, "contractId", draft.contractId().value()); - generator.writeNumberProperty("payloadVersion", draft.payloadVersion()); - writeStringProperty(generator, "logicalDestination", draft.destinationId().value()); - generator.writeObjectPropertyStart("aggregate"); - writeStringProperty(generator, "type", draft.aggregate().aggregateType()); - writeStringProperty(generator, "id", draft.aggregate().aggregateId()); - generator.writeNumberProperty("sequence", draft.order().sequence()); - generator.writeNumberProperty("eventIndex", draft.order().eventIndex()); - generator.writeEndObject(); - writeStringProperty(generator, "occurredAt", draft.occurredAt().toString()); - writeStringProperty(generator, "correlationId", draft.correlationId()); - writeStringProperty(generator, "contentType", "application/json"); - generator.writeEndObject(); - } - - private void writeStringProperty(JsonGenerator generator, String name, String value) { - requireString(name, value); - generator.writeStringProperty(name, value); - } - - private byte[] embedExactPayload(byte[] metadataBytes, byte[] payloadBytes) { - if (metadataBytes.length < 2 || metadataBytes[metadataBytes.length - 1] != (byte) '}') { - throw new IllegalStateException("generated envelope metadata is not a JSON object"); - } - long exactLength = - (long) metadataBytes.length - 1L + PAYLOAD_PROPERTY.length + payloadBytes.length + 1L; - if (exactLength > limits.maximumEnvelopeBytes()) { - throw new IllegalArgumentException("encoded JSON exceeds byte admission limit"); - } - byte[] envelope = new byte[(int) exactLength]; - int offset = metadataBytes.length - 1; - System.arraycopy(metadataBytes, 0, envelope, 0, offset); - System.arraycopy(PAYLOAD_PROPERTY, 0, envelope, offset, PAYLOAD_PROPERTY.length); - offset += PAYLOAD_PROPERTY.length; - System.arraycopy(payloadBytes, 0, envelope, offset, payloadBytes.length); - envelope[envelope.length - 1] = (byte) '}'; - return envelope; - } - - private byte[] generate(int maximumBytes, GeneratorAction action) { - ByteArrayOutputStream output = new BoundedByteArrayOutputStream(maximumBytes); - try (JsonGenerator generator = - jsonFactory.createGenerator(ObjectWriteContext.empty(), output, JsonEncoding.UTF8)) { - action.write(generator); - } - byte[] result = output.toByteArray(); - if (result.length > maximumBytes) { - throw new IllegalArgumentException("encoded JSON exceeds byte admission limit"); - } - return result; - } - - private void requireDepth(int depth) { - if (depth > limits.maximumDepth()) { - throw new IllegalArgumentException("payload exceeds depth admission limit"); - } - } - - private void requireString(String field, String value) { - if (value == null) { - throw new IllegalArgumentException(field + " must not be null"); - } - if (value.codePointCount(0, value.length()) > limits.maximumStringCharacters()) { - throw new IllegalArgumentException(field + " exceeds string character admission limit"); - } - byte[] bytes = strictUtf8(field, value); - if (bytes.length > limits.maximumStringUtf8Bytes()) { - throw new IllegalArgumentException(field + " exceeds UTF-8 byte admission limit"); - } - } - - private static byte[] strictUtf8(String field, String value) { - try { - ByteBuffer encoded = - StandardCharsets.UTF_8 - .newEncoder() - .onMalformedInput(CodingErrorAction.REPORT) - .onUnmappableCharacter(CodingErrorAction.REPORT) - .encode(CharBuffer.wrap(value)); - byte[] bytes = new byte[encoded.remaining()]; - encoded.get(bytes); - return bytes; - } catch (CharacterCodingException exception) { - throw new IllegalArgumentException(field + " contains an unpaired surrogate", exception); - } - } - - private void requireNumberDigits(String text) { - long digits = text.codePoints().filter(Character::isDigit).count(); - if (digits > limits.maximumNumberDigits()) { - throw new IllegalArgumentException("number exceeds digits admission limit"); - } - } - - private BigDecimal canonicalDecimal(BigDecimal decimal) { - if (decimal == null) { - throw new IllegalArgumentException("decimal must not be null"); - } - BigDecimal stripped = decimal.stripTrailingZeros(); - long precision = stripped.precision(); - long scale = stripped.scale(); - long plainDigits = scale >= precision ? 1L + scale : precision + Math.max(0L, -scale); - if (plainDigits > limits.maximumNumberDigits()) { - throw new IllegalArgumentException("number exceeds digits admission limit"); - } - return stripped.scale() < 0 ? stripped.setScale(0) : stripped; - } - - @SuppressWarnings("ArrayRecordComponent") - record EncodedEnvelope(byte[] envelopeBytes, byte[] payloadBytes) { - - EncodedEnvelope { - if (envelopeBytes == null - || envelopeBytes.length == 0 - || payloadBytes == null - || payloadBytes.length == 0) { - throw new IllegalArgumentException("encoded envelope and payload bytes are required"); - } - envelopeBytes = envelopeBytes.clone(); - payloadBytes = payloadBytes.clone(); - } - - @Override - public byte[] envelopeBytes() { - return envelopeBytes.clone(); - } - - @Override - public byte[] payloadBytes() { - return payloadBytes.clone(); - } - } - - private enum SnapshotKind { - NULL, - STRING, - BOOLEAN, - NUMBER, - ARRAY, - OBJECT - } - - private static final class SnapshotValue { - - private final SnapshotKind kind; - private final Object scalar; - private final List names; - private final List values; - - private SnapshotValue( - SnapshotKind kind, Object scalar, List names, List values) { - this.kind = kind; - this.scalar = scalar; - this.names = List.copyOf(names); - this.values = List.copyOf(values); - } - - private SnapshotKind kind() { - return kind; - } - - private Object scalar() { - return scalar; - } - - private List names() { - return names; - } - - private List values() { - return values; - } - - private static SnapshotValue nullValue() { - return new SnapshotValue(SnapshotKind.NULL, null, List.of(), List.of()); - } - - private static SnapshotValue string(String value) { - return new SnapshotValue(SnapshotKind.STRING, value, List.of(), List.of()); - } - - private static SnapshotValue bool(boolean value) { - return new SnapshotValue(SnapshotKind.BOOLEAN, value, List.of(), List.of()); - } - - private static SnapshotValue number(String value) { - return new SnapshotValue(SnapshotKind.NUMBER, value, List.of(), List.of()); - } - - private static SnapshotValue array(List values) { - return new SnapshotValue(SnapshotKind.ARRAY, null, List.of(), values); - } - - private static SnapshotValue object(List names, List values) { - return new SnapshotValue(SnapshotKind.OBJECT, null, names, values); - } - } - - private static final class BoundedByteArrayOutputStream extends ByteArrayOutputStream { - - private final int maximumBytes; - - private BoundedByteArrayOutputStream(int maximumBytes) { - super(Math.min(maximumBytes, 8192)); - if (maximumBytes <= 0) { - throw new IllegalArgumentException("encoded JSON byte admission limit must be positive"); - } - this.maximumBytes = maximumBytes; - } - - @Override - public synchronized void write(int value) { - requireCapacity(1); - super.write(value); - } - - @Override - public synchronized void write(byte[] value, int offset, int length) { - if (value == null) { - throw new IllegalArgumentException("encoded JSON bytes must not be null"); - } - java.util.Objects.checkFromIndexSize(offset, length, value.length); - requireCapacity(length); - super.write(value, offset, length); - } - - private void requireCapacity(int additionalBytes) { - if ((long) count + additionalBytes > maximumBytes) { - throw new IllegalArgumentException("encoded JSON exceeds byte admission limit"); - } - } - } - - @FunctionalInterface - private interface GeneratorAction { - void write(JsonGenerator generator); - } -} diff --git a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/envelope/EnvelopeAdmissionLimits.java b/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/envelope/EnvelopeAdmissionLimits.java deleted file mode 100644 index e0fd8343..00000000 --- a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/envelope/EnvelopeAdmissionLimits.java +++ /dev/null @@ -1,56 +0,0 @@ -package dev.caskeleton.adapter.outbound.messaging.envelope; - -/** - * Closed, finite admission budgets shared by the deterministic writer and local schema validator. - */ -public record EnvelopeAdmissionLimits( - int maximumDepth, - int maximumStringCharacters, - int maximumStringUtf8Bytes, - int maximumArrayItems, - int maximumObjectProperties, - int maximumNumberDigits, - int maximumPayloadBytes, - int maximumEnvelopeBytes, - int maximumValidationErrors, - int maximumRegexInputCharacters, - int maximumReferenceDepth) { - - private static final int HARD_MAXIMUM_DEPTH = 128; - private static final int HARD_MAXIMUM_STRING_CHARACTERS = 1_000_000; - private static final int HARD_MAXIMUM_STRING_BYTES = 4_000_000; - private static final int HARD_MAXIMUM_COLLECTION_ITEMS = 100_000; - private static final int HARD_MAXIMUM_NUMBER_DIGITS = 10_000; - private static final int HARD_MAXIMUM_DOCUMENT_BYTES = 100_000_000; - private static final int HARD_MAXIMUM_VALIDATION_ERRORS = 1_000; - private static final int HARD_MAXIMUM_REFERENCE_DEPTH = 64; - - public EnvelopeAdmissionLimits { - requireFinite("maximumDepth", maximumDepth, HARD_MAXIMUM_DEPTH); - requireFinite( - "maximumStringCharacters", maximumStringCharacters, HARD_MAXIMUM_STRING_CHARACTERS); - requireFinite("maximumStringUtf8Bytes", maximumStringUtf8Bytes, HARD_MAXIMUM_STRING_BYTES); - requireFinite("maximumArrayItems", maximumArrayItems, HARD_MAXIMUM_COLLECTION_ITEMS); - requireFinite( - "maximumObjectProperties", maximumObjectProperties, HARD_MAXIMUM_COLLECTION_ITEMS); - requireFinite("maximumNumberDigits", maximumNumberDigits, HARD_MAXIMUM_NUMBER_DIGITS); - requireFinite("maximumPayloadBytes", maximumPayloadBytes, HARD_MAXIMUM_DOCUMENT_BYTES); - requireFinite("maximumEnvelopeBytes", maximumEnvelopeBytes, HARD_MAXIMUM_DOCUMENT_BYTES); - requireFinite( - "maximumValidationErrors", maximumValidationErrors, HARD_MAXIMUM_VALIDATION_ERRORS); - requireFinite( - "maximumRegexInputCharacters", maximumRegexInputCharacters, HARD_MAXIMUM_STRING_CHARACTERS); - requireFinite("maximumReferenceDepth", maximumReferenceDepth, HARD_MAXIMUM_REFERENCE_DEPTH); - if (maximumEnvelopeBytes < maximumPayloadBytes) { - throw new IllegalArgumentException( - "maximumEnvelopeBytes must be at least maximumPayloadBytes"); - } - } - - private static void requireFinite(String field, int value, int hardMaximum) { - if (value <= 0 || value > hardMaximum || value == Integer.MAX_VALUE) { - throw new IllegalArgumentException( - field + " must be a positive finite bound at most " + hardMaximum); - } - } -} diff --git a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/envelope/EnvelopeHashV1.java b/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/envelope/EnvelopeHashV1.java deleted file mode 100644 index 63b3ba7a..00000000 --- a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/envelope/EnvelopeHashV1.java +++ /dev/null @@ -1,36 +0,0 @@ -package dev.caskeleton.adapter.outbound.messaging.envelope; - -import dev.caskeleton.application.messaging.contract.Sha256; -import java.nio.ByteBuffer; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; - -/** Domain-separated exact-byte hash for the immutable v1 envelope. */ -public final class EnvelopeHashV1 { - - private static final byte[] DOMAIN = - "ca-skeleton.messaging.envelope.v1".getBytes(StandardCharsets.UTF_8); - - private EnvelopeHashV1() {} - - public static Sha256 compute(byte[] exactEnvelopeBytes) { - if (exactEnvelopeBytes == null || exactEnvelopeBytes.length == 0) { - throw new IllegalArgumentException("exact envelope bytes must not be null or empty"); - } - MessageDigest digest = sha256(); - digest.update(DOMAIN); - digest.update((byte) 0); - digest.update(ByteBuffer.allocate(Integer.BYTES).putInt(exactEnvelopeBytes.length).array()); - digest.update(exactEnvelopeBytes); - return new Sha256(digest.digest()); - } - - private static MessageDigest sha256() { - try { - return MessageDigest.getInstance("SHA-256"); - } catch (NoSuchAlgorithmException exception) { - throw new IllegalStateException("Java runtime does not provide SHA-256", exception); - } - } -} diff --git a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/envelope/JsonSchemaIntegrationEventEncoder.java b/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/envelope/JsonSchemaIntegrationEventEncoder.java deleted file mode 100644 index 5fa19d05..00000000 --- a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/envelope/JsonSchemaIntegrationEventEncoder.java +++ /dev/null @@ -1,232 +0,0 @@ -package dev.caskeleton.adapter.outbound.messaging.envelope; - -import dev.caskeleton.adapter.outbound.messaging.contract.CompiledIntegrationEventContract; -import dev.caskeleton.adapter.outbound.messaging.contract.ContractCatalogDigest; -import dev.caskeleton.adapter.outbound.messaging.destination.CompiledPublicationBinding; -import dev.caskeleton.adapter.outbound.messaging.destination.PartitionKeyV1; -import dev.caskeleton.application.messaging.contract.Sha256; -import dev.caskeleton.application.messaging.event.IntegrationEventDraft; -import dev.caskeleton.application.messaging.event.IntegrationEventEncoderPort; -import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent; -import java.nio.ByteBuffer; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** Pure local encoder joining exact compiled contracts, bindings and precompiled schemas. */ -public final class JsonSchemaIntegrationEventEncoder implements IntegrationEventEncoderPort { - - public static final String ENVELOPE_SCHEMA_RESOURCE = - "contracts/messaging/envelope/v1.schema.json"; - private static final byte[] SCHEMA_SET_DOMAIN = - "ca-skeleton.messaging.schema-set.v1".getBytes(StandardCharsets.UTF_8); - - private final Map entries; - private final LocalJsonSchemaRegistry registry; - private final DeterministicEnvelopeWriter writer; - private final EnvelopeAdmissionLimits limits; - private final String envelopeSchemaId; - private final Sha256 envelopeSchemaHash; - private final String catalogRevision; - - public JsonSchemaIntegrationEventEncoder( - List contracts, - List bindings, - LocalJsonSchemaRegistry registry, - EnvelopeAdmissionLimits limits) { - if (contracts == null - || contracts.isEmpty() - || bindings == null - || registry == null - || limits == null) { - throw new IllegalArgumentException( - "closed contracts, bindings, registry and limits are required"); - } - this.registry = registry; - this.limits = limits; - this.writer = new DeterministicEnvelopeWriter(limits); - this.envelopeSchemaId = registry.schemaId(ENVELOPE_SCHEMA_RESOURCE); - this.envelopeSchemaHash = registry.schemaHash(ENVELOPE_SCHEMA_RESOURCE); - this.catalogRevision = ContractCatalogDigest.compute(contracts).toString(); - - Map bindingByKey = new HashMap<>(); - for (CompiledPublicationBinding binding : bindings) { - if (binding == null - || bindingByKey.putIfAbsent( - CompiledPublicationBinding.contractOf(binding).stableKey(), binding) - != null) { - throw new IllegalArgumentException("bindings must be unique and non-null"); - } - } - Map indexed = new HashMap<>(); - for (CompiledIntegrationEventContract contract : contracts) { - if (contract == null) { - throw new IllegalArgumentException("compiled contract must not be null"); - } - CompiledPublicationBinding binding = bindingByKey.remove(contract.stableKey()); - if (binding == null || CompiledPublicationBinding.contractOf(binding) != contract) { - throw new IllegalArgumentException( - "each exact compiled contract requires its canonical compiled binding"); - } - Sha256 registeredPayloadHash = registry.schemaHash(contract.payloadSchemaResource().value()); - if (!registeredPayloadHash.equals(contract.payloadSchemaHash())) { - throw new IllegalArgumentException( - "compiled contract payload schema hash differs from the exact registry bytes"); - } - String payloadSchemaId = registry.schemaId(contract.payloadSchemaResource().value()); - Entry entry = - new Entry( - contract, - binding, - payloadSchemaId, - registeredPayloadHash, - schemaSetHash(envelopeSchemaHash, registeredPayloadHash)); - if (indexed.putIfAbsent(contract.stableKey(), entry) != null) { - throw new IllegalArgumentException("duplicate compiled contract identity"); - } - } - if (!bindingByKey.isEmpty()) { - throw new IllegalArgumentException("extra publication binding outside the closed catalog"); - } - this.entries = Map.copyOf(indexed); - } - - @Override - public ValidatedIntegrationEvent encode(IntegrationEventDraft draft) { - if (draft == null) { - throw new IllegalArgumentException("integration event draft must not be null"); - } - String stableKey = draft.contractId().value() + ":v" + draft.payloadVersion(); - Entry entry = entries.get(stableKey); - if (entry == null) { - throw new IllegalArgumentException("unknown exact contract and payload version"); - } - if (!draft.destinationId().equals(entry.contract().descriptor().logicalDestination()) - || !draft.destinationId().equals(entry.binding().logicalDestination())) { - throw new IllegalArgumentException("draft logical destination does not match binding"); - } - if (draft.featurePayload().getClass() != entry.contract().exactPayloadRecordType()) { - throw new IllegalArgumentException("draft payload must have the exact registered type"); - } - - DeterministicEnvelopeWriter.EncodedEnvelope encoded = writer.write(draft, entry.contract()); - byte[] payloadBytes = encoded.payloadBytes(); - byte[] envelopeBytes = encoded.envelopeBytes(); - int payloadBound = - Math.min(limits.maximumPayloadBytes(), entry.contract().descriptor().maximumPayloadBytes()); - int envelopeBound = - Math.min( - Math.min( - limits.maximumEnvelopeBytes(), - entry.contract().descriptor().maximumEnvelopeBytes()), - entry.binding().effectiveMaximumRecordBytes()); - if (payloadBytes.length > payloadBound) { - throw new IllegalArgumentException("payload exceeds effective code/deployment byte bound"); - } - if (envelopeBytes.length > envelopeBound) { - throw new IllegalArgumentException("envelope exceeds effective code/deployment byte bound"); - } - - List payloadErrors = registry.validate(entry.payloadSchemaId(), payloadBytes); - if (!payloadErrors.isEmpty()) { - throw new IllegalArgumentException( - "payload schema validation failed: " + String.join(",", payloadErrors)); - } - List envelopeErrors = registry.validate(envelopeSchemaId, envelopeBytes); - if (!envelopeErrors.isEmpty()) { - throw new IllegalArgumentException( - "envelope schema validation failed: " + String.join(",", envelopeErrors)); - } - - PartitionKeyV1.Value partitionKey = - PartitionKeyV1.derive(draft.destinationId(), draft.aggregate()); - return new ValidatedIntegrationEvent( - draft.eventId(), - draft.contractId(), - 1, - draft.payloadVersion(), - draft.destinationId(), - draft.aggregate(), - draft.order(), - draft.occurredAt(), - draft.correlationId(), - draft.causationId(), - partitionKey.text(), - partitionKey.bytes(), - envelopeBytes, - "application/json", - entry.schemaSetHash(), - EnvelopeHashV1.compute(envelopeBytes), - envelopeSchemaHash, - entry.payloadSchemaHash(), - catalogRevision, - entry.binding().settingsDigest().toString()); - } - - private static Sha256 schemaSetHash(Sha256 envelope, Sha256 payload) { - MessageDigest digest = sha256(); - digest.update(SCHEMA_SET_DOMAIN); - digest.update((byte) 0); - updateLengthPrefixed(digest, envelope.bytes()); - updateLengthPrefixed(digest, payload.bytes()); - return new Sha256(digest.digest()); - } - - private static void updateLengthPrefixed(MessageDigest digest, byte[] value) { - digest.update(ByteBuffer.allocate(Integer.BYTES).putInt(value.length).array()); - digest.update(value); - } - - private static MessageDigest sha256() { - try { - return MessageDigest.getInstance("SHA-256"); - } catch (NoSuchAlgorithmException exception) { - throw new IllegalStateException("Java runtime does not provide SHA-256", exception); - } - } - - private static final class Entry { - - private final CompiledIntegrationEventContract contract; - private final CompiledPublicationBinding binding; - private final String payloadSchemaId; - private final Sha256 payloadSchemaHash; - private final Sha256 schemaSetHash; - - private Entry( - CompiledIntegrationEventContract contract, - CompiledPublicationBinding binding, - String payloadSchemaId, - Sha256 payloadSchemaHash, - Sha256 schemaSetHash) { - this.contract = contract; - this.binding = binding; - this.payloadSchemaId = payloadSchemaId; - this.payloadSchemaHash = payloadSchemaHash; - this.schemaSetHash = schemaSetHash; - } - - private CompiledIntegrationEventContract contract() { - return contract; - } - - private CompiledPublicationBinding binding() { - return binding; - } - - private String payloadSchemaId() { - return payloadSchemaId; - } - - private Sha256 payloadSchemaHash() { - return payloadSchemaHash; - } - - private Sha256 schemaSetHash() { - return schemaSetHash; - } - } -} diff --git a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/envelope/LocalJsonSchemaRegistry.java b/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/envelope/LocalJsonSchemaRegistry.java deleted file mode 100644 index 26eaddff..00000000 --- a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/envelope/LocalJsonSchemaRegistry.java +++ /dev/null @@ -1,701 +0,0 @@ -package dev.caskeleton.adapter.outbound.messaging.envelope; - -import com.networknt.schema.Error; -import com.networknt.schema.Schema; -import com.networknt.schema.SchemaLocation; -import com.networknt.schema.SchemaRegistry; -import com.networknt.schema.SchemaRegistryConfig; -import com.networknt.schema.SpecificationVersion; -import dev.caskeleton.application.messaging.contract.Sha256; -import java.io.IOException; -import java.io.InputStream; -import java.net.URI; -import java.net.URISyntaxException; -import java.nio.ByteBuffer; -import java.nio.CharBuffer; -import java.nio.charset.CharacterCodingException; -import java.nio.charset.CodingErrorAction; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.HexFormat; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import tools.jackson.core.StreamReadConstraints; -import tools.jackson.core.StreamReadFeature; -import tools.jackson.core.json.JsonFactory; -import tools.jackson.databind.DeserializationFeature; -import tools.jackson.databind.JsonNode; -import tools.jackson.databind.ObjectMapper; -import tools.jackson.databind.json.JsonMapper; - -/** - * Immutable, startup-compiled Draft 2020-12 registry backed only by explicitly supplied bytes. - * - *

Every reference is checked before NetworkNT compilation. After construction this type exposes - * no loader, URL, file or classpath fetch operation. - */ -public final class LocalJsonSchemaRegistry { - - public static final String DRAFT_2020_12 = "https://json-schema.org/draft/2020-12/schema"; - - private static final Set KNOWN_VOCABULARIES = - Set.of( - "https://json-schema.org/draft/2020-12/vocab/core", - "https://json-schema.org/draft/2020-12/vocab/applicator", - "https://json-schema.org/draft/2020-12/vocab/unevaluated", - "https://json-schema.org/draft/2020-12/vocab/validation", - "https://json-schema.org/draft/2020-12/vocab/meta-data", - "https://json-schema.org/draft/2020-12/vocab/format-annotation", - "https://json-schema.org/draft/2020-12/vocab/format-assertion", - "https://json-schema.org/draft/2020-12/vocab/content"); - private static final Set UNSUPPORTED_CLOSED_SUBSET_KEYWORDS = - Set.of("$anchor", "$dynamicRef", "$dynamicAnchor", "$recursiveRef", "$recursiveAnchor"); - private static final String PINNED_AUTHORITY_ROOT = "contracts/messaging/meta/draft-2020-12/"; - private static final String PINNED_AUTHORITY_MANIFEST = - PINNED_AUTHORITY_ROOT + "authority.sha256"; - private static final byte[] PINNED_AUTHORITY_DOMAIN = - "ca-skeleton.messaging.draft-2020-12-authority.v1".getBytes(StandardCharsets.UTF_8); - private static final Map PINNED_META_IDS = - Map.ofEntries( - Map.entry("draft/2020-12/schema", DRAFT_2020_12), - Map.entry( - "draft/2020-12/meta/applicator", - "https://json-schema.org/draft/2020-12/meta/applicator"), - Map.entry( - "draft/2020-12/meta/content", "https://json-schema.org/draft/2020-12/meta/content"), - Map.entry("draft/2020-12/meta/core", "https://json-schema.org/draft/2020-12/meta/core"), - Map.entry( - "draft/2020-12/meta/format-annotation", - "https://json-schema.org/draft/2020-12/meta/format-annotation"), - Map.entry( - "draft/2020-12/meta/format-assertion", - "https://json-schema.org/draft/2020-12/meta/format-assertion"), - Map.entry( - "draft/2020-12/meta/meta-data", - "https://json-schema.org/draft/2020-12/meta/meta-data"), - Map.entry( - "draft/2020-12/meta/unevaluated", - "https://json-schema.org/draft/2020-12/meta/unevaluated"), - Map.entry( - "draft/2020-12/meta/validation", - "https://json-schema.org/draft/2020-12/meta/validation")); - - private final EnvelopeAdmissionLimits limits; - private final ObjectMapper mapper; - private final Map schemasById; - private final Map schemasByResource; - private final Sha256 pinnedDraft202012AuthorityHash; - - public LocalJsonSchemaRegistry( - Map exactSources, EnvelopeAdmissionLimits limits) { - if (exactSources == null || exactSources.isEmpty() || limits == null) { - throw new IllegalArgumentException( - "an explicit non-empty schema source map and limits are required"); - } - this.limits = limits; - this.mapper = strictMapper(limits); - PinnedAuthority pinnedAuthority = - loadPinnedAuthority(mapper, LocalJsonSchemaRegistry.class.getClassLoader()); - - Map parsedById = new LinkedHashMap<>(); - Map parsedByResource = new LinkedHashMap<>(); - exactSources.entrySet().stream() - .sorted(Map.Entry.comparingByKey()) - .forEach( - entry -> { - SchemaSource source = entry.getValue(); - if (source == null || !entry.getKey().equals(source.resourcePath())) { - throw new IllegalArgumentException( - "schema resource map key must equal its non-null exact source path"); - } - ParsedSource parsed = parseAndCheck(source); - if (parsedByResource.putIfAbsent(source.resourcePath(), parsed) != null) { - throw new IllegalArgumentException( - "duplicate schema resource " + source.resourcePath()); - } - if (parsedById.putIfAbsent(parsed.schemaId(), parsed) != null) { - throw new IllegalArgumentException("duplicate schema $id " + parsed.schemaId()); - } - }); - - validateAllReferences(parsedById); - SchemaRegistry registry = compileRegistry(parsedById); - validatePinnedAuthorityAgainstRuntime(registry, pinnedAuthority); - validateAgainstBundledMetaSchema(registry, parsedById.values()); - - Map byId = new LinkedHashMap<>(); - Map byResource = new LinkedHashMap<>(); - parsedById.values().stream() - .sorted(Comparator.comparing(ParsedSource::schemaId)) - .forEach( - parsed -> { - Schema compiled; - try { - compiled = registry.getSchema(SchemaLocation.of(parsed.schemaId())); - } catch (RuntimeException exception) { - throw new IllegalArgumentException( - "schema compilation failed for " + parsed.resourcePath(), exception); - } - CompiledSchema value = - new CompiledSchema( - parsed.resourcePath(), - parsed.schemaId(), - parsed.exactBytes(), - parsed.hash(), - compiled); - byId.put(parsed.schemaId(), value); - byResource.put(parsed.resourcePath(), value); - }); - this.schemasById = Map.copyOf(byId); - this.schemasByResource = Map.copyOf(byResource); - this.pinnedDraft202012AuthorityHash = pinnedAuthority.authorityHash(); - } - - public List validate(String schemaId, byte[] exactUtf8Bytes) { - if (exactUtf8Bytes == null || exactUtf8Bytes.length == 0) { - throw new IllegalArgumentException("exact UTF-8 JSON bytes must not be null or empty"); - } - if (exactUtf8Bytes.length > limits.maximumEnvelopeBytes()) { - throw new IllegalArgumentException("JSON document exceeds envelope byte admission limit"); - } - JsonNode node; - try { - node = mapper.readTree(exactUtf8Bytes); - } catch (RuntimeException exception) { - String message; - if (!strictUtf8Decodable(exactUtf8Bytes)) { - message = "malformed UTF-8"; - } else if (exception.getMessage() != null - && exception.getMessage().toLowerCase(java.util.Locale.ROOT).contains("string")) { - message = "JSON string exceeds parser admission limit"; - } else { - message = "invalid bounded JSON document"; - } - throw new IllegalArgumentException(message, exception); - } - return validate(schemaId, node); - } - - private List validate(String schemaId, JsonNode instance) { - CompiledSchema schema = schemasById.get(schemaId); - if (schema == null || instance == null) { - throw new IllegalArgumentException("unknown schema ID or null JSON tree"); - } - enforceInstanceLimits(instance, 1); - List errors; - try { - errors = schema.compiled().validate(instance); - } catch (RuntimeException exception) { - throw new IllegalArgumentException("local schema validation failed", exception); - } - return errors.stream() - .sorted( - Comparator.comparing((Error error) -> error.getInstanceLocation().toString()) - .thenComparing(Error::getKeyword)) - .limit(limits.maximumValidationErrors()) - .map( - error -> - error.getInstanceLocation() - + ":" - + (error.getKeyword() == null ? "schema" : error.getKeyword())) - .toList(); - } - - public String schemaId(String resourcePath) { - return requireResource(resourcePath).schemaId(); - } - - public Sha256 schemaHash(String resourcePath) { - return requireResource(resourcePath).hash(); - } - - public byte[] exactSchemaBytes(String resourcePath) { - return requireResource(resourcePath).exactBytes(); - } - - public Sha256 pinnedDraft202012AuthorityHash() { - return pinnedDraft202012AuthorityHash; - } - - private CompiledSchema requireResource(String resourcePath) { - CompiledSchema schema = schemasByResource.get(resourcePath); - if (schema == null) { - throw new IllegalArgumentException("unknown schema resource"); - } - return schema; - } - - private ParsedSource parseAndCheck(SchemaSource source) { - byte[] bytes = source.exactBytes(); - Sha256 actual = sha256(bytes); - if (!actual.equals(source.expectedSha256())) { - throw new IllegalArgumentException("schema checksum mismatch for " + source.resourcePath()); - } - JsonNode root; - try { - root = mapper.readTree(bytes); - } catch (RuntimeException exception) { - throw new IllegalArgumentException( - "schema is not a strict bounded JSON document: " + source.resourcePath(), exception); - } - if (!root.isObject()) { - throw new IllegalArgumentException("schema root must be an object"); - } - JsonNode dialect = root.get("$schema"); - if (dialect == null || !dialect.isString() || !DRAFT_2020_12.equals(dialect.stringValue())) { - throw new IllegalArgumentException("schema dialect must explicitly be Draft 2020-12"); - } - JsonNode identifier = root.get("$id"); - if (identifier == null || !identifier.isString()) { - throw new IllegalArgumentException("schema requires an explicit absolute immutable $id"); - } - String schemaId = requireAbsoluteImmutableId(identifier.stringValue()); - rejectUnsupportedSchemaLocations(root, true); - validateVocabulary(root.get("$vocabulary")); - return new ParsedSource(source.resourcePath(), schemaId, source.exactBytes(), actual, root); - } - - private static String requireAbsoluteImmutableId(String value) { - try { - URI id = new URI(value); - if (!id.isAbsolute() || !"urn".equals(id.getScheme()) || id.getFragment() != null) { - throw new IllegalArgumentException( - "schema $id must use the exact urn scheme and must not contain a fragment"); - } - return id.toASCIIString(); - } catch (URISyntaxException exception) { - throw new IllegalArgumentException("schema $id must be an absolute immutable URI", exception); - } - } - - private static void validateVocabulary(JsonNode vocabulary) { - if (vocabulary == null) { - return; - } - if (!vocabulary.isObject()) { - throw new IllegalArgumentException("$vocabulary must be an object"); - } - for (Map.Entry entry : vocabulary.properties()) { - if (!KNOWN_VOCABULARIES.contains(entry.getKey())) { - throw new IllegalArgumentException("unknown JSON Schema vocabulary"); - } - if (!entry.getValue().isBoolean()) { - throw new IllegalArgumentException("vocabulary declarations must be boolean"); - } - } - } - - private static void rejectUnsupportedSchemaLocations(JsonNode node, boolean root) { - if (node.isObject()) { - if (!root && node.has("$id")) { - throw new IllegalArgumentException( - "nested $id is unsupported by the closed local schema subset"); - } - for (String keyword : UNSUPPORTED_CLOSED_SUBSET_KEYWORDS) { - if (node.has(keyword)) { - throw new IllegalArgumentException( - keyword + " is unsupported by the closed local schema subset"); - } - } - node.properties().forEach(entry -> rejectUnsupportedSchemaLocations(entry.getValue(), false)); - } else if (node.isArray()) { - node.forEach(child -> rejectUnsupportedSchemaLocations(child, false)); - } - } - - private void validateAllReferences(Map parsedById) { - for (ParsedSource source : parsedById.values()) { - List roots = collectReferences(source.schemaId(), source.root()); - for (ReferenceTarget target : roots) { - validateReferenceChain(target, parsedById, new ArrayDeque<>(), 1); - } - } - } - - private void validateReferenceChain( - ReferenceTarget target, - Map sources, - ArrayDeque stack, - int depth) { - if (depth > limits.maximumReferenceDepth() || stack.contains(target)) { - throw new IllegalArgumentException("schema reference cycle/depth exceeds supported depth"); - } - ParsedSource source = sources.get(target.schemaId()); - if (source == null) { - throw new IllegalArgumentException("schema reference is not in the exact supplied $id map"); - } - JsonNode referenced = resolveFragment(source.root(), target.fragment()); - if (referenced == null) { - throw new IllegalArgumentException("schema reference fragment does not exist"); - } - stack.addLast(target); - for (ReferenceTarget nested : collectReferences(source.schemaId(), referenced)) { - validateReferenceChain(nested, sources, stack, depth + 1); - } - stack.removeLast(); - } - - private static List collectReferences(String ownerId, JsonNode node) { - List result = new ArrayList<>(); - collectReferences(ownerId, node, result); - return result; - } - - private static void collectReferences( - String ownerId, JsonNode node, List result) { - if (node.isObject()) { - JsonNode ref = node.get("$ref"); - if (ref != null) { - if (!ref.isString()) { - throw new IllegalArgumentException("$ref must be a string"); - } - result.add(parseReference(ownerId, ref.stringValue())); - } - node.properties().forEach(entry -> collectReferences(ownerId, entry.getValue(), result)); - } else if (node.isArray()) { - node.forEach(child -> collectReferences(ownerId, child, result)); - } - } - - private static ReferenceTarget parseReference(String ownerId, String value) { - try { - URI reference = new URI(value); - if (reference.isAbsolute() && !"urn".equals(reference.getScheme())) { - throw new IllegalArgumentException( - "absolute schema reference $ref must use the exact urn scheme"); - } - String fragment = reference.getRawFragment(); - if (fragment != null && !fragment.isEmpty() && !fragment.startsWith("/")) { - throw new IllegalArgumentException("only JSON Pointer schema fragments are supported"); - } - if (!reference.isAbsolute() && !value.startsWith("#")) { - throw new IllegalArgumentException("relative external schema reference forbidden"); - } - String base = - value.startsWith("#") - ? ownerId - : new URI(reference.getScheme(), reference.getSchemeSpecificPart(), null) - .toASCIIString(); - return new ReferenceTarget(base, fragment == null ? "" : fragment); - } catch (URISyntaxException exception) { - throw new IllegalArgumentException("invalid schema reference", exception); - } - } - - private static JsonNode resolveFragment(JsonNode root, String fragment) { - if (fragment.isEmpty()) { - return root; - } - JsonNode resolved = root.at(fragment); - return resolved.isMissingNode() ? null : resolved; - } - - private static SchemaRegistry compileRegistry(Map parsedById) { - Map exactSchemas = new HashMap<>(); - parsedById.forEach( - (id, source) -> - exactSchemas.put(id, new String(source.exactBytes(), StandardCharsets.UTF_8))); - SchemaRegistryConfig config = - SchemaRegistryConfig.builder() - .formatAssertionsEnabled(true) - .typeLoose(false) - .failFast(false) - .cacheRefs(true) - .build(); - try { - return SchemaRegistry.withDefaultDialect( - SpecificationVersion.DRAFT_2020_12, - builder -> builder.schemaRegistryConfig(config).schemas(exactSchemas)); - } catch (RuntimeException exception) { - throw new IllegalArgumentException( - "local Draft 2020-12 registry compilation failed", exception); - } - } - - private static void validateAgainstBundledMetaSchema( - SchemaRegistry registry, java.util.Collection sources) { - Schema metaSchema; - try { - metaSchema = registry.getSchema(SchemaLocation.of(DRAFT_2020_12)); - } catch (RuntimeException exception) { - throw new IllegalArgumentException( - "bundled Draft 2020-12 meta-schema is unavailable", exception); - } - for (ParsedSource source : sources) { - List errors = metaSchema.validate(source.root()); - if (!errors.isEmpty()) { - throw new IllegalArgumentException( - "schema fails bundled Draft 2020-12 meta-schema validation: " + source.resourcePath()); - } - } - } - - private static PinnedAuthority loadPinnedAuthority(ObjectMapper mapper, ClassLoader classLoader) { - byte[] manifestBytes = readRequiredClasspathBytes(classLoader, PINNED_AUTHORITY_MANIFEST); - String manifest; - try { - manifest = - StandardCharsets.UTF_8 - .newDecoder() - .onMalformedInput(CodingErrorAction.REPORT) - .onUnmappableCharacter(CodingErrorAction.REPORT) - .decode(ByteBuffer.wrap(manifestBytes)) - .toString(); - } catch (CharacterCodingException exception) { - throw new IllegalArgumentException( - "pinned Draft 2020-12 authority manifest is not strict UTF-8", exception); - } - - Map expectedByPath = new LinkedHashMap<>(); - for (String line : manifest.lines().toList()) { - if (!line.matches("[a-f0-9]{64} draft/2020-12/(schema|meta/[a-z-]+)")) { - throw new IllegalArgumentException( - "pinned Draft 2020-12 authority manifest has an invalid entry"); - } - String path = line.substring(66); - Sha256 expected = new Sha256(HexFormat.of().parseHex(line.substring(0, 64))); - if (expectedByPath.putIfAbsent(path, expected) != null) { - throw new IllegalArgumentException( - "pinned Draft 2020-12 authority manifest contains a duplicate path"); - } - } - if (!expectedByPath.keySet().equals(PINNED_META_IDS.keySet())) { - throw new IllegalArgumentException( - "pinned Draft 2020-12 authority manifest has an incomplete resource set"); - } - MessageDigest authorityDigest = sha256Digest(); - authorityDigest.update(PINNED_AUTHORITY_DOMAIN); - authorityDigest.update((byte) 0); - Map nodesById = new LinkedHashMap<>(); - expectedByPath.entrySet().stream() - .sorted(Map.Entry.comparingByKey()) - .forEach( - entry -> { - String path = entry.getKey(); - byte[] pinnedBytes = - readRequiredClasspathBytes(classLoader, PINNED_AUTHORITY_ROOT + path); - if (!sha256(pinnedBytes).equals(entry.getValue())) { - throw new IllegalArgumentException( - "pinned Draft 2020-12 authority checksum mismatch for " + path); - } - JsonNode node; - try { - node = mapper.readTree(pinnedBytes); - } catch (RuntimeException exception) { - throw new IllegalArgumentException( - "pinned Draft 2020-12 authority is not bounded strict JSON", exception); - } - String expectedId = PINNED_META_IDS.get(path); - JsonNode id = node.get("$id"); - if (id == null || !id.isString() || !expectedId.equals(id.stringValue())) { - throw new IllegalArgumentException( - "pinned Draft 2020-12 authority has an unexpected $id for " + path); - } - nodesById.put(expectedId, node); - updateLengthPrefixed(authorityDigest, path.getBytes(StandardCharsets.UTF_8)); - updateLengthPrefixed(authorityDigest, pinnedBytes); - }); - return new PinnedAuthority(Map.copyOf(nodesById), new Sha256(authorityDigest.digest())); - } - - private static void validatePinnedAuthorityAgainstRuntime( - SchemaRegistry registry, PinnedAuthority authority) { - for (Map.Entry entry : authority.nodesById().entrySet()) { - Schema runtimeSchema; - try { - runtimeSchema = registry.getSchema(SchemaLocation.of(entry.getKey())); - } catch (RuntimeException exception) { - throw new IllegalArgumentException( - "NetworkNT runtime is missing pinned Draft 2020-12 authority " + entry.getKey(), - exception); - } - if (!entry.getValue().equals(runtimeSchema.getSchemaNode())) { - throw new IllegalArgumentException( - "NetworkNT runtime Draft 2020-12 authority tree differs from pinned exact bytes"); - } - } - } - - private static byte[] readRequiredClasspathBytes(ClassLoader classLoader, String path) { - try (InputStream input = classLoader.getResourceAsStream(path)) { - if (input == null) { - throw new IllegalArgumentException( - "required pinned Draft 2020-12 classpath resource is missing: " + path); - } - return input.readAllBytes(); - } catch (IOException exception) { - throw new IllegalArgumentException( - "required pinned Draft 2020-12 classpath resource could not be read: " + path, exception); - } - } - - private static void updateLengthPrefixed(MessageDigest digest, byte[] value) { - digest.update(ByteBuffer.allocate(Integer.BYTES).putInt(value.length).array()); - digest.update(value); - } - - private void enforceInstanceLimits(JsonNode node, int depth) { - if (depth > limits.maximumDepth()) { - throw new IllegalArgumentException("JSON tree exceeds depth admission limit"); - } - if (node.isObject()) { - if (node.size() > limits.maximumObjectProperties()) { - throw new IllegalArgumentException("JSON object exceeds properties admission limit"); - } - for (Map.Entry entry : node.properties()) { - enforceString(entry.getKey()); - enforceInstanceLimits(entry.getValue(), depth + 1); - } - } else if (node.isArray()) { - if (node.size() > limits.maximumArrayItems()) { - throw new IllegalArgumentException("JSON array exceeds items admission limit"); - } - node.forEach(child -> enforceInstanceLimits(child, depth + 1)); - } else if (node.isString()) { - enforceString(node.stringValue()); - if (node.stringValue().codePointCount(0, node.stringValue().length()) - > limits.maximumRegexInputCharacters()) { - throw new IllegalArgumentException("JSON string exceeds regex input admission limit"); - } - } else if (node.isNumber()) { - long digits = node.toString().codePoints().filter(Character::isDigit).count(); - if (digits > limits.maximumNumberDigits()) { - throw new IllegalArgumentException("JSON number exceeds digits admission limit"); - } - if (node.isFloatingPointNumber() && !Double.isFinite(node.doubleValue())) { - throw new IllegalArgumentException("JSON number must be finite"); - } - } - } - - private void enforceString(String value) { - if (value.codePointCount(0, value.length()) > limits.maximumStringCharacters()) { - throw new IllegalArgumentException("JSON string exceeds character admission limit"); - } - byte[] bytes = strictUtf8(value); - if (bytes.length > limits.maximumStringUtf8Bytes()) { - throw new IllegalArgumentException("JSON string exceeds UTF-8 byte admission limit"); - } - } - - private static boolean strictUtf8Decodable(byte[] bytes) { - try { - StandardCharsets.UTF_8 - .newDecoder() - .onMalformedInput(CodingErrorAction.REPORT) - .onUnmappableCharacter(CodingErrorAction.REPORT) - .decode(ByteBuffer.wrap(bytes)); - return true; - } catch (CharacterCodingException exception) { - return false; - } - } - - private static byte[] strictUtf8(String value) { - try { - ByteBuffer encoded = - StandardCharsets.UTF_8 - .newEncoder() - .onMalformedInput(CodingErrorAction.REPORT) - .onUnmappableCharacter(CodingErrorAction.REPORT) - .encode(CharBuffer.wrap(value)); - byte[] result = new byte[encoded.remaining()]; - encoded.get(result); - return result; - } catch (CharacterCodingException exception) { - throw new IllegalArgumentException("JSON string contains an unpaired surrogate", exception); - } - } - - private static ObjectMapper strictMapper(EnvelopeAdmissionLimits limits) { - JsonFactory factory = - JsonFactory.builder() - .streamReadConstraints( - StreamReadConstraints.builder() - .maxNestingDepth(limits.maximumDepth()) - .maxDocumentLength(limits.maximumEnvelopeBytes()) - .maxNumberLength(limits.maximumNumberDigits()) - .maxStringLength(limits.maximumStringCharacters()) - .maxNameLength(limits.maximumStringCharacters()) - .build()) - .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) - .build(); - return JsonMapper.builder(factory) - .enable(DeserializationFeature.FAIL_ON_READING_DUP_TREE_KEY) - .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) - .build(); - } - - private static Sha256 sha256(byte[] bytes) { - return new Sha256(sha256Digest().digest(bytes)); - } - - private static MessageDigest sha256Digest() { - try { - return MessageDigest.getInstance("SHA-256"); - } catch (NoSuchAlgorithmException exception) { - throw new IllegalStateException("Java runtime does not provide SHA-256", exception); - } - } - - @SuppressWarnings("ArrayRecordComponent") - public record SchemaSource(String resourcePath, byte[] exactBytes, Sha256 expectedSha256) { - - public SchemaSource { - if (resourcePath == null - || resourcePath.isBlank() - || resourcePath.startsWith("/") - || resourcePath.contains("..") - || exactBytes == null - || exactBytes.length == 0 - || expectedSha256 == null) { - throw new IllegalArgumentException("exact local schema source fields are required"); - } - exactBytes = exactBytes.clone(); - } - - @Override - public byte[] exactBytes() { - return exactBytes.clone(); - } - } - - @SuppressWarnings("ArrayRecordComponent") - private record ParsedSource( - String resourcePath, String schemaId, byte[] exactBytes, Sha256 hash, JsonNode root) { - - private ParsedSource { - exactBytes = exactBytes.clone(); - } - - @Override - public byte[] exactBytes() { - return exactBytes.clone(); - } - } - - @SuppressWarnings("ArrayRecordComponent") - private record CompiledSchema( - String resourcePath, String schemaId, byte[] exactBytes, Sha256 hash, Schema compiled) { - - private CompiledSchema { - exactBytes = exactBytes.clone(); - } - - @Override - public byte[] exactBytes() { - return exactBytes.clone(); - } - } - - private record PinnedAuthority(Map nodesById, Sha256 authorityHash) {} - - private record ReferenceTarget(String schemaId, String fragment) {} -} diff --git a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/outbox/DisabledOutboxMessagePublisher.java b/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/outbox/DisabledOutboxMessagePublisher.java deleted file mode 100644 index 222c647a..00000000 --- a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/outbox/DisabledOutboxMessagePublisher.java +++ /dev/null @@ -1,14 +0,0 @@ -package dev.caskeleton.adapter.outbound.messaging.outbox; - -import dev.caskeleton.application.outbox.ClaimedOutboxEvent; -import dev.caskeleton.application.outbox.OutboxMessagePublishPort; -import dev.caskeleton.shared.error.AdapterDisabledException; - -/** Fail-fast outbox binding when neither legacy broker nor canonical platform transport exists. */ -public class DisabledOutboxMessagePublisher implements OutboxMessagePublishPort { - - @Override - public void publish(ClaimedOutboxEvent event) { - throw new AdapterDisabledException("messaging"); - } -} diff --git a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/outbox/Slf4jOutboxRelayFailureReportAdapter.java b/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/outbox/Slf4jOutboxRelayFailureReportAdapter.java index 329de487..9c6d897a 100644 --- a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/outbox/Slf4jOutboxRelayFailureReportAdapter.java +++ b/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/outbox/Slf4jOutboxRelayFailureReportAdapter.java @@ -2,17 +2,23 @@ package dev.caskeleton.adapter.outbound.messaging.outbox; import dev.caskeleton.application.outbox.OutboxRelayFailureReport; import dev.caskeleton.application.outbox.OutboxRelayFailureReportPort; +import dev.caskeleton.application.outbox.OutboxRelayResult; import dev.caskeleton.shared.error.OperationalError; import java.util.Objects; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.spi.LoggingEventBuilder; -/** Renders confirmed outbox relay failure transitions as one safe structured SLF4J ERROR. */ +/** + * Renders confirmed outbox relay failure transitions as one safe structured SLF4J ERROR, and a + * completion refused by the lease fence as one WARN. + */ public final class Slf4jOutboxRelayFailureReportAdapter implements OutboxRelayFailureReportPort { private static final String DEPENDENCY_TYPE = "messaging"; private static final String LOG_MESSAGE = "confirmed outbox relay failure"; + private static final String STALE_MESSAGE = + "outbox relay completion refused: the claim was taken over by another relay"; private final String dependencyName; private final Logger logger; @@ -62,4 +68,26 @@ public final class Slf4jOutboxRelayFailureReportAdapter implements OutboxRelayFa // Diagnostics are non-authoritative and must never escape into the relay. } } + + /** + * One WARN per completion the relay could not write because another relay had taken the row over: + * nothing was persisted, and the broker may have received the event twice. + */ + @Override + public void reportStaleCompletion( + String eventId, String eventType, OutboxRelayResult.Outcome attempted) { + try { + logger + .atWarn() + .addKeyValue("dependency_name", dependencyName) + .addKeyValue("dependency_type", DEPENDENCY_TYPE) + .addKeyValue("outcome", OutboxRelayResult.Outcome.STALE.name()) + .addKeyValue("attempted_outcome", attempted.name()) + .addKeyValue("event_id", eventId) + .addKeyValue("event_type", eventType) + .log(STALE_MESSAGE); + } catch (RuntimeException ignored) { + // Diagnostics are non-authoritative and must never escape into the relay. + } + } } diff --git a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/realtime/MessagingDurableFanoutAdapter.java b/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/realtime/MessagingDurableFanoutAdapter.java deleted file mode 100644 index 45f416a5..00000000 --- a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/realtime/MessagingDurableFanoutAdapter.java +++ /dev/null @@ -1,60 +0,0 @@ -package dev.caskeleton.adapter.outbound.messaging.realtime; - -import dev.caskeleton.adapter.outbound.messaging.core.MessageBroker; -import dev.caskeleton.adapter.outbound.messaging.core.OutboundMessage; -import dev.caskeleton.application.realtime.DurableFanoutPort; -import dev.caskeleton.application.realtime.DurableFanoutRecord; -import dev.caskeleton.application.realtime.DurableFanoutUnavailableException; -import java.util.Objects; - -/** - * Durable cross-node fan-out, on the messaging platform. - * - *

Fail-closed, unlike the ephemeral fan-out beside it. A caller reaching for this port has - * something a user will be told happened, so "the broker did not accept it" has to reach the caller - * — it is the only party that can decide between retrying, dropping and falling back. - * - *

The partition key is the record's, and it is the recipient rather than the channel. Keying on - * the channel would put a whole feed in one partition, which serialises every recipient behind the - * slowest one and quietly removes the parallelism the broker was chosen for. Keying on the - * recipient also gives per-recipient ordering, which is the only ordering guarantee this fan-out - * makes and the only one its consumers need. - * - *

Nothing here deduplicates. Delivery is at-least-once by construction and the receiver holds - * the deduplication state, because it is the only side that knows what it has already applied. - */ -public final class MessagingDurableFanoutAdapter implements DurableFanoutPort { - - private final MessageBroker broker; - private final String topic; - - /** - * Creates the adapter. - * - * @param broker the active broker binding - * @param topic the topic every realtime fan-out record is published to - */ - public MessagingDurableFanoutAdapter(MessageBroker broker, String topic) { - this.broker = Objects.requireNonNull(broker, "broker must not be null"); - this.topic = Objects.requireNonNull(topic, "topic must not be null"); - if (topic.isBlank()) { - throw new IllegalArgumentException("a blank topic is not a destination"); - } - } - - @Override - public void publish(DurableFanoutRecord record) { - Objects.requireNonNull(record, "record must not be null"); - OutboundMessage message = - new OutboundMessage( - topic, record.partitionKey(), RealtimeFanoutEnvelopeJson.toJson(record)); - try { - broker.send(message); - } catch (Exception failure) { - // Wrapped rather than propagated raw: the broker's own exception names its client library, - // and a caller in a transport adapter should not have to catch a Kafka type to know its - // publish failed. - throw new DurableFanoutUnavailableException(record.channel(), failure); - } - } -} diff --git a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/realtime/RealtimeFanoutEnvelopeJson.java b/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/realtime/RealtimeFanoutEnvelopeJson.java deleted file mode 100644 index b9c2da01..00000000 --- a/src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/realtime/RealtimeFanoutEnvelopeJson.java +++ /dev/null @@ -1,78 +0,0 @@ -package dev.caskeleton.adapter.outbound.messaging.realtime; - -import dev.caskeleton.application.realtime.DurableFanoutRecord; -import java.util.Objects; -import tools.jackson.databind.ObjectMapper; -import tools.jackson.databind.json.JsonMapper; -import tools.jackson.databind.node.ObjectNode; - -/** - * The wire form of a durable fan-out record. - * - *

Carries the expiry and the ordering pair alongside the payload rather than leaving them to - * broker headers. Headers are the tempting place — they are cheaper and they survive a payload - * schema change — and they are wrong here for one reason: a broker migration, a bridge, or a - * dead-letter round trip preserves the body and loses the headers. A record whose expiry lived in a - * header would arrive from a dead-letter queue looking permanently fresh. - * - *

The reader tolerates unknown fields and refuses missing ones. During a rolling deploy both - * versions are publishing, so a reader that rejected an added field would fail on everything the - * newer nodes emit, for the whole rollout. - */ -public final class RealtimeFanoutEnvelopeJson { - - private static final String VERSION = "1"; - private static final ObjectMapper MAPPER = JsonMapper.builder().build(); - - private RealtimeFanoutEnvelopeJson() {} - - /** Renders a record for the broker. */ - public static String toJson(DurableFanoutRecord record) { - Objects.requireNonNull(record, "record must not be null"); - ObjectNode root = MAPPER.createObjectNode(); - root.put("v", VERSION); - root.put("channel", record.channel().value()); - root.put("partitionKey", record.partitionKey()); - root.put("payload", record.payload()); - root.put("publishedAt", record.publishedAt().toEpochMilli()); - root.put("expiresAt", record.expiresAt().toEpochMilli()); - record.streamId().ifPresent(streamId -> root.put("streamId", streamId)); - record.position().ifPresent(position -> root.put("position", position)); - return root.toString(); - } - - /** - * Reads a record back. - * - * @throws IllegalArgumentException when the document is not a record this version can read - */ - public static DurableFanoutRecord fromJson(String json) { - Objects.requireNonNull(json, "json must not be null"); - var root = MAPPER.readTree(json); - if (!root.isObject() || !VERSION.equals(text(root, "v"))) { - throw new IllegalArgumentException("not a version " + VERSION + " realtime fan-out envelope"); - } - var streamId = root.get("streamId"); - var position = root.get("position"); - return new DurableFanoutRecord( - new dev.caskeleton.application.realtime.RealtimeChannel(text(root, "channel")), - text(root, "partitionKey"), - text(root, "payload"), - streamId == null || streamId.isNull() - ? java.util.Optional.empty() - : java.util.Optional.of(streamId.asString()), - position == null || position.isNull() - ? java.util.Optional.empty() - : java.util.Optional.of(position.asLong()), - java.time.Instant.ofEpochMilli(root.get("publishedAt").asLong()), - java.time.Instant.ofEpochMilli(root.get("expiresAt").asLong())); - } - - private static String text(tools.jackson.databind.JsonNode root, String field) { - var node = root.get(field); - if (node == null || node.isNull()) { - throw new IllegalArgumentException("a realtime fan-out envelope must carry " + field); - } - return node.asString(); - } -} diff --git a/src/adapter/outbound/messaging/src/main/resources/META-INF/spring.factories b/src/adapter/outbound/messaging/src/main/resources/META-INF/spring.factories deleted file mode 100644 index eb62f492..00000000 --- a/src/adapter/outbound/messaging/src/main/resources/META-INF/spring.factories +++ /dev/null @@ -1,2 +0,0 @@ -org.springframework.boot.autoconfigure.AutoConfigurationImportFilter=\ -dev.caskeleton.adapter.outbound.messaging.autoconfigure.MessagingOffAutoConfigurationImportFilter diff --git a/src/adapter/outbound/messaging/src/main/resources/contracts/messaging/meta/draft-2020-12/authority.sha256 b/src/adapter/outbound/messaging/src/main/resources/contracts/messaging/meta/draft-2020-12/authority.sha256 deleted file mode 100644 index 3466e466..00000000 --- a/src/adapter/outbound/messaging/src/main/resources/contracts/messaging/meta/draft-2020-12/authority.sha256 +++ /dev/null @@ -1,9 +0,0 @@ -41da76f5afb7ce062d248f762463a92f7ca47e4e0f905b224ba6afeef91ded0f draft/2020-12/schema -c4a6e4147b91fef7fea6dc058cb1bf93402f7414b76578a8b16aaf1dad6aacef draft/2020-12/meta/applicator -08343747764e4a5814262793cf4d652057a7913863c5950d43297e8e1fdac5b6 draft/2020-12/meta/content -c2d12a8e4dd11d336dfc83a3f663aa4c69f0b49b3beb094ffeb25b5316f4803d draft/2020-12/meta/core -abc775adfefd89d22358170d9bf93f4ebd2349563bbbedd60f02bef7c812bcc0 draft/2020-12/meta/format-annotation -6a5a8e13c605e3eff51f9bf8da18078880d81ff1634e391760ccc2e16ee2146f draft/2020-12/meta/format-assertion -8f76d6e14f41b9b92ef933b708cdc5144c8b5268651ad11918485fb1754f1c76 draft/2020-12/meta/meta-data -2dbfbcb73994b670b0976492adee1fffb46c21682784d2f5a4ca561f9e2d0cb4 draft/2020-12/meta/unevaluated -7010a31e541f32d2be721e2de348df75c9b36876a3ed304877fc0abda1d37a58 draft/2020-12/meta/validation diff --git a/src/adapter/outbound/messaging/src/main/resources/contracts/messaging/meta/draft-2020-12/draft/2020-12/meta/applicator b/src/adapter/outbound/messaging/src/main/resources/contracts/messaging/meta/draft-2020-12/draft/2020-12/meta/applicator deleted file mode 100644 index ca699230..00000000 --- a/src/adapter/outbound/messaging/src/main/resources/contracts/messaging/meta/draft-2020-12/draft/2020-12/meta/applicator +++ /dev/null @@ -1,48 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://json-schema.org/draft/2020-12/meta/applicator", - "$vocabulary": { - "https://json-schema.org/draft/2020-12/vocab/applicator": true - }, - "$dynamicAnchor": "meta", - - "title": "Applicator vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { - "prefixItems": { "$ref": "#/$defs/schemaArray" }, - "items": { "$dynamicRef": "#meta" }, - "contains": { "$dynamicRef": "#meta" }, - "additionalProperties": { "$dynamicRef": "#meta" }, - "properties": { - "type": "object", - "additionalProperties": { "$dynamicRef": "#meta" }, - "default": {} - }, - "patternProperties": { - "type": "object", - "additionalProperties": { "$dynamicRef": "#meta" }, - "propertyNames": { "format": "regex" }, - "default": {} - }, - "dependentSchemas": { - "type": "object", - "additionalProperties": { "$dynamicRef": "#meta" }, - "default": {} - }, - "propertyNames": { "$dynamicRef": "#meta" }, - "if": { "$dynamicRef": "#meta" }, - "then": { "$dynamicRef": "#meta" }, - "else": { "$dynamicRef": "#meta" }, - "allOf": { "$ref": "#/$defs/schemaArray" }, - "anyOf": { "$ref": "#/$defs/schemaArray" }, - "oneOf": { "$ref": "#/$defs/schemaArray" }, - "not": { "$dynamicRef": "#meta" } - }, - "$defs": { - "schemaArray": { - "type": "array", - "minItems": 1, - "items": { "$dynamicRef": "#meta" } - } - } -} diff --git a/src/adapter/outbound/messaging/src/main/resources/contracts/messaging/meta/draft-2020-12/draft/2020-12/meta/content b/src/adapter/outbound/messaging/src/main/resources/contracts/messaging/meta/draft-2020-12/draft/2020-12/meta/content deleted file mode 100644 index 2f6e056a..00000000 --- a/src/adapter/outbound/messaging/src/main/resources/contracts/messaging/meta/draft-2020-12/draft/2020-12/meta/content +++ /dev/null @@ -1,17 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://json-schema.org/draft/2020-12/meta/content", - "$vocabulary": { - "https://json-schema.org/draft/2020-12/vocab/content": true - }, - "$dynamicAnchor": "meta", - - "title": "Content vocabulary meta-schema", - - "type": ["object", "boolean"], - "properties": { - "contentEncoding": { "type": "string" }, - "contentMediaType": { "type": "string" }, - "contentSchema": { "$dynamicRef": "#meta" } - } -} diff --git a/src/adapter/outbound/messaging/src/main/resources/contracts/messaging/meta/draft-2020-12/draft/2020-12/meta/core b/src/adapter/outbound/messaging/src/main/resources/contracts/messaging/meta/draft-2020-12/draft/2020-12/meta/core deleted file mode 100644 index dfc092d9..00000000 --- a/src/adapter/outbound/messaging/src/main/resources/contracts/messaging/meta/draft-2020-12/draft/2020-12/meta/core +++ /dev/null @@ -1,51 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://json-schema.org/draft/2020-12/meta/core", - "$vocabulary": { - "https://json-schema.org/draft/2020-12/vocab/core": true - }, - "$dynamicAnchor": "meta", - - "title": "Core vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { - "$id": { - "$ref": "#/$defs/uriReferenceString", - "$comment": "Non-empty fragments not allowed.", - "pattern": "^[^#]*#?$" - }, - "$schema": { "$ref": "#/$defs/uriString" }, - "$ref": { "$ref": "#/$defs/uriReferenceString" }, - "$anchor": { "$ref": "#/$defs/anchorString" }, - "$dynamicRef": { "$ref": "#/$defs/uriReferenceString" }, - "$dynamicAnchor": { "$ref": "#/$defs/anchorString" }, - "$vocabulary": { - "type": "object", - "propertyNames": { "$ref": "#/$defs/uriString" }, - "additionalProperties": { - "type": "boolean" - } - }, - "$comment": { - "type": "string" - }, - "$defs": { - "type": "object", - "additionalProperties": { "$dynamicRef": "#meta" } - } - }, - "$defs": { - "anchorString": { - "type": "string", - "pattern": "^[A-Za-z_][-A-Za-z0-9._]*$" - }, - "uriString": { - "type": "string", - "format": "uri" - }, - "uriReferenceString": { - "type": "string", - "format": "uri-reference" - } - } -} diff --git a/src/adapter/outbound/messaging/src/main/resources/contracts/messaging/meta/draft-2020-12/draft/2020-12/meta/format-annotation b/src/adapter/outbound/messaging/src/main/resources/contracts/messaging/meta/draft-2020-12/draft/2020-12/meta/format-annotation deleted file mode 100644 index 51ef7ea1..00000000 --- a/src/adapter/outbound/messaging/src/main/resources/contracts/messaging/meta/draft-2020-12/draft/2020-12/meta/format-annotation +++ /dev/null @@ -1,14 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://json-schema.org/draft/2020-12/meta/format-annotation", - "$vocabulary": { - "https://json-schema.org/draft/2020-12/vocab/format-annotation": true - }, - "$dynamicAnchor": "meta", - - "title": "Format vocabulary meta-schema for annotation results", - "type": ["object", "boolean"], - "properties": { - "format": { "type": "string" } - } -} diff --git a/src/adapter/outbound/messaging/src/main/resources/contracts/messaging/meta/draft-2020-12/draft/2020-12/meta/format-assertion b/src/adapter/outbound/messaging/src/main/resources/contracts/messaging/meta/draft-2020-12/draft/2020-12/meta/format-assertion deleted file mode 100644 index 1a4f106c..00000000 --- a/src/adapter/outbound/messaging/src/main/resources/contracts/messaging/meta/draft-2020-12/draft/2020-12/meta/format-assertion +++ /dev/null @@ -1,11 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://json-schema.org/draft/2020-12/meta/format-assertion", - "$dynamicAnchor": "meta", - - "title": "Format vocabulary meta-schema for assertion results", - "type": ["object", "boolean"], - "properties": { - "format": { "type": "string" } - } -} diff --git a/src/adapter/outbound/messaging/src/main/resources/contracts/messaging/meta/draft-2020-12/draft/2020-12/meta/meta-data b/src/adapter/outbound/messaging/src/main/resources/contracts/messaging/meta/draft-2020-12/draft/2020-12/meta/meta-data deleted file mode 100644 index 05cbc22a..00000000 --- a/src/adapter/outbound/messaging/src/main/resources/contracts/messaging/meta/draft-2020-12/draft/2020-12/meta/meta-data +++ /dev/null @@ -1,37 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://json-schema.org/draft/2020-12/meta/meta-data", - "$vocabulary": { - "https://json-schema.org/draft/2020-12/vocab/meta-data": true - }, - "$dynamicAnchor": "meta", - - "title": "Meta-data vocabulary meta-schema", - - "type": ["object", "boolean"], - "properties": { - "title": { - "type": "string" - }, - "description": { - "type": "string" - }, - "default": true, - "deprecated": { - "type": "boolean", - "default": false - }, - "readOnly": { - "type": "boolean", - "default": false - }, - "writeOnly": { - "type": "boolean", - "default": false - }, - "examples": { - "type": "array", - "items": true - } - } -} diff --git a/src/adapter/outbound/messaging/src/main/resources/contracts/messaging/meta/draft-2020-12/draft/2020-12/meta/unevaluated b/src/adapter/outbound/messaging/src/main/resources/contracts/messaging/meta/draft-2020-12/draft/2020-12/meta/unevaluated deleted file mode 100644 index 5f62a3ff..00000000 --- a/src/adapter/outbound/messaging/src/main/resources/contracts/messaging/meta/draft-2020-12/draft/2020-12/meta/unevaluated +++ /dev/null @@ -1,15 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://json-schema.org/draft/2020-12/meta/unevaluated", - "$vocabulary": { - "https://json-schema.org/draft/2020-12/vocab/unevaluated": true - }, - "$dynamicAnchor": "meta", - - "title": "Unevaluated applicator vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { - "unevaluatedItems": { "$dynamicRef": "#meta" }, - "unevaluatedProperties": { "$dynamicRef": "#meta" } - } -} diff --git a/src/adapter/outbound/messaging/src/main/resources/contracts/messaging/meta/draft-2020-12/draft/2020-12/meta/validation b/src/adapter/outbound/messaging/src/main/resources/contracts/messaging/meta/draft-2020-12/draft/2020-12/meta/validation deleted file mode 100644 index 606b87ba..00000000 --- a/src/adapter/outbound/messaging/src/main/resources/contracts/messaging/meta/draft-2020-12/draft/2020-12/meta/validation +++ /dev/null @@ -1,98 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://json-schema.org/draft/2020-12/meta/validation", - "$vocabulary": { - "https://json-schema.org/draft/2020-12/vocab/validation": true - }, - "$dynamicAnchor": "meta", - - "title": "Validation vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { - "type": { - "anyOf": [ - { "$ref": "#/$defs/simpleTypes" }, - { - "type": "array", - "items": { "$ref": "#/$defs/simpleTypes" }, - "minItems": 1, - "uniqueItems": true - } - ] - }, - "const": true, - "enum": { - "type": "array", - "items": true - }, - "multipleOf": { - "type": "number", - "exclusiveMinimum": 0 - }, - "maximum": { - "type": "number" - }, - "exclusiveMaximum": { - "type": "number" - }, - "minimum": { - "type": "number" - }, - "exclusiveMinimum": { - "type": "number" - }, - "maxLength": { "$ref": "#/$defs/nonNegativeInteger" }, - "minLength": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, - "pattern": { - "type": "string", - "format": "regex" - }, - "maxItems": { "$ref": "#/$defs/nonNegativeInteger" }, - "minItems": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, - "uniqueItems": { - "type": "boolean", - "default": false - }, - "maxContains": { "$ref": "#/$defs/nonNegativeInteger" }, - "minContains": { - "$ref": "#/$defs/nonNegativeInteger", - "default": 1 - }, - "maxProperties": { "$ref": "#/$defs/nonNegativeInteger" }, - "minProperties": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, - "required": { "$ref": "#/$defs/stringArray" }, - "dependentRequired": { - "type": "object", - "additionalProperties": { - "$ref": "#/$defs/stringArray" - } - } - }, - "$defs": { - "nonNegativeInteger": { - "type": "integer", - "minimum": 0 - }, - "nonNegativeIntegerDefault0": { - "$ref": "#/$defs/nonNegativeInteger", - "default": 0 - }, - "simpleTypes": { - "enum": [ - "array", - "boolean", - "integer", - "null", - "number", - "object", - "string" - ] - }, - "stringArray": { - "type": "array", - "items": { "type": "string" }, - "uniqueItems": true, - "default": [] - } - } -} diff --git a/src/adapter/outbound/messaging/src/main/resources/contracts/messaging/meta/draft-2020-12/draft/2020-12/schema b/src/adapter/outbound/messaging/src/main/resources/contracts/messaging/meta/draft-2020-12/draft/2020-12/schema deleted file mode 100644 index d5e2d31c..00000000 --- a/src/adapter/outbound/messaging/src/main/resources/contracts/messaging/meta/draft-2020-12/draft/2020-12/schema +++ /dev/null @@ -1,58 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://json-schema.org/draft/2020-12/schema", - "$vocabulary": { - "https://json-schema.org/draft/2020-12/vocab/core": true, - "https://json-schema.org/draft/2020-12/vocab/applicator": true, - "https://json-schema.org/draft/2020-12/vocab/unevaluated": true, - "https://json-schema.org/draft/2020-12/vocab/validation": true, - "https://json-schema.org/draft/2020-12/vocab/meta-data": true, - "https://json-schema.org/draft/2020-12/vocab/format-annotation": true, - "https://json-schema.org/draft/2020-12/vocab/content": true - }, - "$dynamicAnchor": "meta", - - "title": "Core and Validation specifications meta-schema", - "allOf": [ - {"$ref": "meta/core"}, - {"$ref": "meta/applicator"}, - {"$ref": "meta/unevaluated"}, - {"$ref": "meta/validation"}, - {"$ref": "meta/meta-data"}, - {"$ref": "meta/format-annotation"}, - {"$ref": "meta/content"} - ], - "type": ["object", "boolean"], - "$comment": "This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.", - "properties": { - "definitions": { - "$comment": "\"definitions\" has been replaced by \"$defs\".", - "type": "object", - "additionalProperties": { "$dynamicRef": "#meta" }, - "deprecated": true, - "default": {} - }, - "dependencies": { - "$comment": "\"dependencies\" has been split and replaced by \"dependentSchemas\" and \"dependentRequired\" in order to serve their differing semantics.", - "type": "object", - "additionalProperties": { - "anyOf": [ - { "$dynamicRef": "#meta" }, - { "$ref": "meta/validation#/$defs/stringArray" } - ] - }, - "deprecated": true, - "default": {} - }, - "$recursiveAnchor": { - "$comment": "\"$recursiveAnchor\" has been replaced by \"$dynamicAnchor\".", - "$ref": "meta/core#/$defs/anchorString", - "deprecated": true - }, - "$recursiveRef": { - "$comment": "\"$recursiveRef\" has been replaced by \"$dynamicRef\".", - "$ref": "meta/core#/$defs/uriReferenceString", - "deprecated": true - } - } -} diff --git a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/MessagingConfigTest.java b/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/MessagingConfigTest.java index 98014fb8..08a92156 100644 --- a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/MessagingConfigTest.java +++ b/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/MessagingConfigTest.java @@ -1,15 +1,13 @@ package dev.caskeleton.adapter.outbound.messaging; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import dev.caskeleton.adapter.outbound.messaging.core.DisabledMessagePublisher; import dev.caskeleton.adapter.outbound.messaging.core.MessageBroker; -import dev.caskeleton.adapter.outbound.messaging.core.MessagePublisher; import dev.caskeleton.adapter.outbound.messaging.kafka.KafkaAdapterConfig; import dev.caskeleton.adapter.outbound.messaging.kafka.KafkaSender; -import dev.caskeleton.adapter.outbound.messaging.outbox.DisabledOutboxMessagePublisher; import dev.caskeleton.adapter.outbound.support.FailOpenDependencyLogger; -import dev.caskeleton.application.outbox.OutboxMessagePublishPort; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.boot.test.context.runner.ApplicationContextRunner; @@ -22,16 +20,19 @@ class MessagingConfigTest { .withUserConfiguration(MessagingConfig.class); @Test - void blankBrokerBindsDisabledSentinelsCharacterization() { + void blankBrokerWithoutCanonicalTransportIsRefusedRatherThanStoodIn() { + // A stand-in outbox publisher would satisfy the relay scheduler's bean condition and drain + // every + // PENDING row to DEAD. With nothing to publish to, the bridge refuses startup instead. runner .withPropertyValues("app.messaging.broker=") .run( context -> { - assertThat(context).hasNotFailed(); - assertThat(context.getBean(MessagePublisher.class)) - .isInstanceOf(DisabledMessagePublisher.class); - assertThat(context.getBean(OutboxMessagePublishPort.class)) - .isInstanceOf(DisabledOutboxMessagePublisher.class); + assertThat(context).hasFailed(); + assertThat(rootCause(context.getStartupFailure())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("app.messaging.broker is blank") + .hasMessageContaining("app.messaging.enabled=false"); }); } @@ -65,6 +66,19 @@ class MessagingConfigTest { + " 'other'")); } + @Test + void theDisabledPublisherFailsFastNamingMessaging() { + assertThatThrownBy( + () -> + new DisabledMessagePublisher() + .publish( + new dev.caskeleton.adapter.outbound.messaging.core.OutboundMessage( + "t", "k", "p"))) + .isInstanceOf(dev.caskeleton.shared.error.AdapterDisabledException.class) + .extracting("adapterName") + .isEqualTo("messaging"); + } + private static MessageBroker brokerReporting(String brokerId) { return new MessageBroker() { @Override diff --git a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/autoconfigure/MessagingOffAutoConfigurationImportFilterParityTest.java b/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/autoconfigure/MessagingOffAutoConfigurationImportFilterParityTest.java deleted file mode 100644 index 8d239078..00000000 --- a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/autoconfigure/MessagingOffAutoConfigurationImportFilterParityTest.java +++ /dev/null @@ -1,44 +0,0 @@ -package dev.caskeleton.adapter.outbound.messaging.autoconfigure; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.lang.reflect.Field; -import java.util.LinkedHashSet; -import java.util.Set; -import java.util.stream.Collectors; -import org.junit.jupiter.api.Test; -import org.springframework.boot.autoconfigure.AutoConfiguration; -import org.springframework.boot.context.annotation.ImportCandidates; - -/** - * Keeps the optional Boot broker compatibility filter synchronized with the actual Boot version. - * - *

The broker Boot modules are test-only here. Production deliberately depends on Spring - * Kafka/Rabbit through the messaging platform rather than on Boot's competing broker - * auto-configurations. - */ -class MessagingOffAutoConfigurationImportFilterParityTest { - - @Test - void targetListExactlyMatchesBootKafkaAndRabbitCandidates() throws Exception { - Set candidates = - ImportCandidates.load(AutoConfiguration.class, getClass().getClassLoader()) - .getCandidates() - .stream() - .filter( - name -> - name.startsWith("org.springframework.boot.kafka.autoconfigure.") - || name.startsWith("org.springframework.boot.amqp.autoconfigure.")) - .collect(Collectors.toCollection(LinkedHashSet::new)); - - Field field = - MessagingOffAutoConfigurationImportFilter.class.getDeclaredField( - "BROKER_AUTO_CONFIGURATIONS"); - field.setAccessible(true); - @SuppressWarnings("unchecked") - Set targets = new LinkedHashSet<>((Set) field.get(null)); - - assertThat(candidates).isNotEmpty(); - assertThat(targets).isEqualTo(candidates); - } -} diff --git a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/autoconfigure/MessagingPlatformBridgeAutoConfigurationTest.java b/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/autoconfigure/MessagingPlatformBridgeAutoConfigurationTest.java index dab5bd6c..16177167 100644 --- a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/autoconfigure/MessagingPlatformBridgeAutoConfigurationTest.java +++ b/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/autoconfigure/MessagingPlatformBridgeAutoConfigurationTest.java @@ -2,10 +2,16 @@ package dev.caskeleton.adapter.outbound.messaging.autoconfigure; import static org.assertj.core.api.Assertions.assertThat; +import dev.caskeleton.adapter.outbound.messaging.MessagingSettings; +import dev.caskeleton.adapter.outbound.messaging.core.MessageBroker; +import dev.caskeleton.adapter.outbound.messaging.core.OutboundMessage; import dev.caskeleton.adapter.outbound.support.FailOpenDependencyLogger; import dev.caskeleton.application.messaging.event.IntegrationEventPublishPort; +import dev.caskeleton.application.outbox.OutboxMessagePublishPort; import dev.caskeleton.messaging.schema.EncodedMessagePublisher; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; @@ -21,7 +27,8 @@ class MessagingPlatformBridgeAutoConfigurationTest { (destination, message, options) -> { throw new AssertionError("publisher is not invoked while wiring the bridge"); }) - .withPropertyValues("app.messaging.enabled=true"); + .withBean(MessageBroker.class, MessagingPlatformBridgeAutoConfigurationTest::testBroker) + .withPropertyValues("app.messaging.enabled=true", "app.messaging.broker=test"); @Test void explicitProducerIdCreatesOneCanonicalPublishBridge() { @@ -34,6 +41,60 @@ class MessagingPlatformBridgeAutoConfigurationTest { }); } + @Test + void bridgeIsAssembledAfterThePlatformRootThatProvidesThePublisher() { + // given + ApplicationContextRunner assembled = + new ApplicationContextRunner() + .withConfiguration( + AutoConfigurations.of( + MessagingBridgeRootAutoConfiguration.class, + dev.caskeleton.messaging.autoconfigure.MessagingPlatformRootAutoConfiguration + .class)) + .withBean(FailOpenDependencyLogger.class, FailOpenDependencyLogger::new) + .withPropertyValues( + "app.messaging.enabled=true", "app.messaging.producer-id=portfolio-service"); + + // when & then + assembled.run(context -> assertThat(context).hasSingleBean(IntegrationEventPublishPort.class)); + } + + @ParameterizedTest + @ValueSource(strings = {"", " "}) + void blankProducerIdLeavesTheBridgeOutWithoutFailingStartup(String producerId) { + // The shipped yml always defines the key (`${APP_MESSAGING_PRODUCER_ID:}`), so the property is + // present and blank whenever the operator has not set it. + runner + .withPropertyValues("app.messaging.producer-id=" + producerId) + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context).doesNotHaveBean(IntegrationEventPublishPort.class); + }); + } + + @Test + void presentWithoutTheSwitchIsOn() { + new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(MessagingBridgeRootAutoConfiguration.class)) + .withBean(FailOpenDependencyLogger.class, FailOpenDependencyLogger::new) + .withBean(MessageBroker.class, MessagingPlatformBridgeAutoConfigurationTest::testBroker) + .withPropertyValues("app.messaging.broker=test") + .run(context -> assertThat(context).hasSingleBean(OutboxMessagePublishPort.class)); + } + + @Test + void switchedOffHoldsNothing() { + new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(MessagingBridgeRootAutoConfiguration.class)) + .withPropertyValues("app.messaging.enabled=false") + .run( + context -> { + assertThat(context).doesNotHaveBean(MessagingSettings.class); + assertThat(context).doesNotHaveBean(OutboxMessagePublishPort.class); + }); + } + @Test void missingProducerIdDoesNotInventCanonicalPublisherIdentity() { runner.run( @@ -42,4 +103,17 @@ class MessagingPlatformBridgeAutoConfigurationTest { assertThat(context).doesNotHaveBean(IntegrationEventPublishPort.class); }); } + + /** A selected broker, so the bridge has something to publish outbox rows to. */ + private static MessageBroker testBroker() { + return new MessageBroker() { + @Override + public String brokerId() { + return "test"; + } + + @Override + public void send(OutboundMessage message) {} + }; + } } diff --git a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/config/MessagingCapabilityCardRegistryTest.java b/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/config/MessagingCapabilityCardRegistryTest.java deleted file mode 100644 index 8edcd1ef..00000000 --- a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/config/MessagingCapabilityCardRegistryTest.java +++ /dev/null @@ -1,97 +0,0 @@ -package dev.caskeleton.adapter.outbound.messaging.config; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.outbound.messaging.config.MessagingCapabilityCardRegistry.CapabilityCard; -import dev.caskeleton.adapter.outbound.messaging.config.MessagingCapabilityCardRegistry.CardRole; -import java.util.ArrayList; -import java.util.List; -import org.junit.jupiter.api.Test; - -class MessagingCapabilityCardRegistryTest { - - @Test - void exposesExactlyTheFirstR2TupleWithOneClosedCardPerRole() { - MessagingCapabilityCardRegistry registry = MessagingCapabilityCardRegistry.exactFirstR2(); - - assertThat(registry.cards()) - .extracting(CapabilityCard::cardId) - .containsExactly( - "messaging-outbox-publish.v1", - "kafka-spring-acknowledged-idempotent.v1", - "postgresql-polling-outbox.v2", - "postgresql-per-record-jit-claim.v1", - "json-schema-envelope.v1", - "external-topic-validated.v1", - "kafka-sasl-ssl-scram-sha-512.v1", - "kafka-compression-none.v1", - "per-key-normal-path-sequence-detectable.v1", - "same-postgresql-transaction-resource.v1", - "authenticated-internal-web-disposition.v1"); - assertThat(registry.cards()) - .extracting(CapabilityCard::role) - .containsExactlyInAnyOrder( - CardRole.SEMANTIC, - CardRole.PRODUCER, - CardRole.DISPATCH, - CardRole.CLAIM, - CardRole.SERIALIZATION, - CardRole.TOPIC, - CardRole.SECURITY, - CardRole.COMPRESSION, - CardRole.ORDERING, - CardRole.TRANSACTION, - CardRole.OPERATOR_CONTROL); - assertThat(registry.selection().producerCardId()) - .isEqualTo("kafka-spring-acknowledged-idempotent.v1"); - assertThat(registry.selection().serializationCardId()).isEqualTo("json-schema-envelope.v1"); - assertThat(registry.claimsReleaseEligibility()).isFalse(); - assertThatThrownBy(() -> registry.cards().add(registry.cards().getFirst())) - .isInstanceOf(UnsupportedOperationException.class); - } - - @Test - void rejectsNullUnknownConsumerCdcEosSchemaRegistryAndDuplicateCards() { - List exact = - new ArrayList<>(MessagingCapabilityCardRegistry.exactFirstR2().cards()); - - assertThatThrownBy(() -> MessagingCapabilityCardRegistry.compile(null)) - .isInstanceOf(IllegalArgumentException.class); - assertRejected(exact, new CapabilityCard("future-provider.v1", CardRole.PRODUCER), "unknown"); - assertRejected( - exact, new CapabilityCard("messaging-inbox-consume.v1", CardRole.SEMANTIC), "unknown"); - assertRejected( - exact, new CapabilityCard("messaging-cdc-dispatch.v1", CardRole.DISPATCH), "unknown"); - assertRejected( - exact, new CapabilityCard("kafka-exactly-once.v1", CardRole.PRODUCER), "unknown"); - assertRejected( - exact, new CapabilityCard("json-schema-registry.v1", CardRole.SERIALIZATION), "unknown"); - - exact.add(exact.getFirst()); - assertThatThrownBy(() -> MessagingCapabilityCardRegistry.compile(exact)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("duplicate"); - } - - @Test - void rejectsRoleSubstitutionEvenWhenTheCardIdItselfIsKnown() { - List cards = - new ArrayList<>(MessagingCapabilityCardRegistry.exactFirstR2().cards()); - cards.set( - 1, new CapabilityCard("kafka-spring-acknowledged-idempotent.v1", CardRole.SERIALIZATION)); - - assertThatThrownBy(() -> MessagingCapabilityCardRegistry.compile(cards)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("role"); - } - - private static void assertRejected( - List exact, CapabilityCard unsupported, String message) { - List cards = new ArrayList<>(exact); - cards.set(1, unsupported); - assertThatThrownBy(() -> MessagingCapabilityCardRegistry.compile(cards)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining(message); - } -} diff --git a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/contract/ContractCatalogCompilerTest.java b/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/contract/ContractCatalogCompilerTest.java deleted file mode 100644 index 9d927439..00000000 --- a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/contract/ContractCatalogCompilerTest.java +++ /dev/null @@ -1,566 +0,0 @@ -package dev.caskeleton.adapter.outbound.messaging.contract; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.application.messaging.contract.ContractDescriptor; -import dev.caskeleton.application.messaging.contract.ContractId; -import dev.caskeleton.application.messaging.contract.IntegrationEventContractContribution; -import dev.caskeleton.application.messaging.contract.IntegrationPayload; -import dev.caskeleton.application.messaging.contract.LogicalDestinationId; -import dev.caskeleton.application.messaging.contract.SchemaResourceId; -import dev.caskeleton.application.messaging.contract.Sha256; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.time.Duration; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HexFormat; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import org.junit.jupiter.api.Test; - -class ContractCatalogCompilerTest { - - private static final ContractCatalogCompiler COMPILER = new ContractCatalogCompiler(); - - @Test - void compilesAnImmutableClosedCatalogFromExactRecordTypeTokens() { - ArrayList componentOrder = new ArrayList<>(List.of("eventId", "count")); - Contribution contribution = - contribution( - "fixture.event.created", - 1, - ValidPayload.class, - componentOrder, - "contracts/messaging/fixture.event.created/v1.schema.json", - hash(1), - descriptor("fixture-events", true, 256)); - - List catalog = COMPILER.compile(List.of(contribution)); - componentOrder.set(0, "mutated"); - - assertThat(catalog).hasSize(1); - CompiledIntegrationEventContract compiled = catalog.getFirst(); - assertThat(compiled.stableKey()).isEqualTo("fixture.event.created:v1"); - assertThat(compiled.exactPayloadRecordType()).isEqualTo(ValidPayload.class); - assertThat(compiled.exactPayloadRecordType().isRecord()).isTrue(); - assertThat(Modifier.isFinal(compiled.exactPayloadRecordType().getModifiers())).isTrue(); - assertThat(compiled.canonicalRecordComponentOrder()).containsExactly("eventId", "count"); - assertThat(compiled.descriptor().logicalDestination()) - .isEqualTo(new LogicalDestinationId("fixture-events")); - assertThatThrownBy(() -> catalog.add(compiled)) - .isInstanceOf(UnsupportedOperationException.class); - assertThatThrownBy(() -> compiled.canonicalRecordComponentOrder().add("another")) - .isInstanceOf(UnsupportedOperationException.class); - } - - @Test - void rejectsNullInputsDuplicateStableSchemaAndExactPayloadIdentities() { - Contribution first = validContribution("fixture.event.created", 1); - - assertThatThrownBy(() -> COMPILER.compile(null)).isInstanceOf(IllegalArgumentException.class); - List> withNull = new ArrayList<>(); - withNull.add(first); - withNull.add(null); - assertThatThrownBy(() -> COMPILER.compile(withNull)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("contribution"); - assertThatThrownBy( - () -> COMPILER.compile(List.of(first, validContribution("fixture.event.created", 1)))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("contract"); - assertThatThrownBy( - () -> - COMPILER.compile( - List.of( - first, - contribution( - "fixture.other.created", - 1, - OtherPayload.class, - List.of("value"), - first.payloadSchemaResource().value(), - hash(2), - descriptor("fixture-events", true, 256))))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("schema"); - assertThatThrownBy( - () -> - COMPILER.compile( - List.of( - first, - contribution( - "fixture.other.created", - 1, - ValidPayload.class, - List.of("eventId", "count"), - "contracts/messaging/fixture.other.created/v1.schema.json", - hash(2), - descriptor("fixture-events", true, 256))))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("payload"); - } - - @Test - void rejectsNonPositiveVersionAndInvalidExactPayloadKinds() { - assertThatThrownBy( - () -> - COMPILER.compile( - List.of( - contribution( - "fixture.event.created", - 0, - ValidPayload.class, - List.of("eventId", "count"), - "contracts/messaging/fixture.event.created/v1.schema.json", - hash(1), - descriptor("fixture-events", true, 256))))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("version"); - assertThatThrownBy( - () -> - COMPILER.compile( - List.of( - contribution( - "fixture.event.created", - 1, - MutablePayload.class, - List.of(), - "contracts/messaging/fixture.event.created/v1.schema.json", - hash(1), - descriptor("fixture-events", true, 256))))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("record"); - assertThatThrownBy( - () -> - COMPILER.compile( - List.of( - contribution( - "fixture.event.created", - 1, - null, - List.of(), - "contracts/messaging/fixture.event.created/v1.schema.json", - hash(1), - descriptor("fixture-events", true, 256))))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("payload"); - } - - @Test - void rejectsNullBlankDuplicateAndReflectionMismatchedComponentOrders() { - assertInvalidOrder(null); - assertInvalidOrder(List.of("eventId", " ")); - assertInvalidOrder(List.of("eventId", "eventId")); - assertInvalidOrder(List.of("count", "eventId")); - assertInvalidOrder(List.of("eventId")); - assertInvalidOrder(List.of("eventId", "count", "unknown")); - } - - @Test - void rejectsMissingDescriptorsAndLogicalDestinationDriftAcrossPayloadVersions() { - assertThatThrownBy( - () -> - COMPILER.compile( - List.of( - contribution( - "fixture.event.created", - 1, - ValidPayload.class, - List.of("eventId", "count"), - "contracts/messaging/fixture.event.created/v1.schema.json", - hash(1), - null)))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("descriptor"); - - assertThatThrownBy( - () -> - COMPILER.compile( - List.of( - validContribution("fixture.event.created", 1), - contribution( - "fixture.event.created", - 2, - OtherPayload.class, - List.of("value"), - "contracts/messaging/fixture.event.created/v2.schema.json", - hash(2), - descriptor("other-events", true, 256))))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("logical destination"); - } - - @Test - void compiledContractCannotBeConstructedWithAnInvalidExactTypeOrComponentOrder() { - Contribution contribution = validContribution("fixture.event.created", 1); - - assertThatThrownBy( - () -> - new CompiledIntegrationEventContract( - contribution.contractId(), - contribution.payloadVersion(), - MutablePayload.class, - List.of(), - contribution.payloadSchemaResource(), - contribution.payloadSchemaHash(), - contribution.descriptor())) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("record"); - assertThatThrownBy( - () -> - new CompiledIntegrationEventContract( - contribution.contractId(), - contribution.payloadVersion(), - ValidPayload.class, - List.of("count", "eventId"), - contribution.payloadSchemaResource(), - contribution.payloadSchemaHash(), - contribution.descriptor())) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("component"); - } - - @Test - void compiledContractUsesOnlyAStaticPublicCompositionBridgeWithoutReflectionLeak() - throws NoSuchMethodException { - assertThat(Modifier.isFinal(CompiledIntegrationEventContract.class.getModifiers())).isTrue(); - assertThat(CompiledIntegrationEventContract.class.isRecord()).isFalse(); - assertThat(CompiledIntegrationEventContract.class.getConstructors()).isEmpty(); - assertThat(CompiledIntegrationEventContract.class.getDeclaredConstructors()) - .allSatisfy( - constructor -> assertThat(Modifier.isPublic(constructor.getModifiers())).isFalse()); - assertThat( - Modifier.isPublic( - ContractCatalogCompiler.class - .getDeclaredMethod("compile", List.class) - .getModifiers())) - .isFalse(); - assertThat( - ContractCatalogCompiler.class - .getDeclaredMethod("compileExact", List.class) - .getModifiers()) - .satisfies( - modifiers -> { - assertThat(Modifier.isPublic(modifiers)).isTrue(); - assertThat(Modifier.isStatic(modifiers)).isTrue(); - }); - assertThat( - Arrays.stream(CompiledIntegrationEventContract.class.getMethods()) - .>map(Method::getReturnType)) - .doesNotContain(Method.class); - } - - @Test - void snapshotsEveryContributionAccessorExactlyOnceIncludingAStatefulSchemaHash() { - StatefulContribution contribution = - new StatefulContribution<>( - new ContractId("fixture.event.created"), - 1, - ValidPayload.class, - List.of("eventId", "count"), - new SchemaResourceId("contracts/messaging/fixture.event.created/v1.schema.json"), - List.of(hash(1), hash(2)), - List.of(descriptor("fixture-events", true, 256))); - - CompiledIntegrationEventContract compiled = COMPILER.compile(List.of(contribution)).getFirst(); - - assertThat(compiled.payloadSchemaHash()).isEqualTo(hash(1)); - assertThat(contribution.callCounts()).containsOnly(1); - } - - @Test - void statefulDescriptorCannotBypassCrossVersionLogicalDestinationDrift() { - StatefulContribution statefulSecondVersion = - new StatefulContribution<>( - new ContractId("fixture.event.created"), - 2, - OtherPayload.class, - List.of("value"), - new SchemaResourceId("contracts/messaging/fixture.event.created/v2.schema.json"), - List.of(hash(2)), - List.of( - descriptor("other-events", true, 256), - descriptor("fixture-events", true, 256), - descriptor("other-events", true, 256))); - - assertThatThrownBy( - () -> - COMPILER.compile( - List.of(validContribution("fixture.event.created", 1), statefulSecondVersion))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("logical destination"); - } - - @Test - void recursivelyFreezesOnlyTheClosedDeclaredGenericPayloadGraph() { - Contribution contribution = - contribution( - "fixture.closed.graph", - 1, - ClosedGraphPayload.class, - List.of("name", "count", "amount", "state", "nested"), - "contracts/messaging/fixture.closed.graph/v1.schema.json", - hash(7), - descriptor("fixture-events", true, 256)); - - CompiledIntegrationEventContract contract = COMPILER.compile(List.of(contribution)).getFirst(); - CompiledIntegrationEventContract.PayloadShape root = - CompiledIntegrationEventContract.payloadShapeOf(contract); - List components = - CompiledIntegrationEventContract.PayloadShape.componentsOf(root); - - assertThat(CompiledIntegrationEventContract.PayloadShape.kindOf(root)) - .isEqualTo(CompiledIntegrationEventContract.PayloadKind.RECORD); - assertThat(CompiledIntegrationEventContract.PayloadShape.exactJavaTypeOf(root)) - .isEqualTo(ClosedGraphPayload.class); - assertThat(components.stream().map(CompiledIntegrationEventContract.PayloadComponent::nameOf)) - .containsExactly("name", "count", "amount", "state", "nested"); - CompiledIntegrationEventContract.PayloadShape optional = - CompiledIntegrationEventContract.PayloadComponent.shapeOf(components.getLast()); - assertThat(CompiledIntegrationEventContract.PayloadShape.kindOf(optional)) - .isEqualTo(CompiledIntegrationEventContract.PayloadKind.OPTIONAL); - CompiledIntegrationEventContract.PayloadShape list = - CompiledIntegrationEventContract.PayloadShape.elementShapeOf(optional); - assertThat(CompiledIntegrationEventContract.PayloadShape.kindOf(list)) - .isEqualTo(CompiledIntegrationEventContract.PayloadKind.LIST); - assertThat( - CompiledIntegrationEventContract.PayloadShape.exactJavaTypeOf( - CompiledIntegrationEventContract.PayloadShape.elementShapeOf(list))) - .isEqualTo(ClosedNested.class); - assertThatThrownBy(() -> components.add(components.getFirst())) - .isInstanceOf(UnsupportedOperationException.class); - } - - @Test - void rejectsOpenRawWildcardMapJsonTreeInterfaceAndGenericRecordGraphs() { - assertUnsupportedGraph(ObjectPayload.class, List.of("value")); - assertUnsupportedGraph(InterfacePayload.class, List.of("value")); - assertUnsupportedGraph(MapPayload.class, List.of("value")); - assertUnsupportedGraph(RawListPayload.class, List.of("value")); - assertUnsupportedGraph(WildcardListPayload.class, List.of("value")); - assertUnsupportedGraph(JsonTreePayload.class, List.of("value")); - assertUnsupportedGraph(GenericRecordPayload.class, List.of("value")); - } - - private static void assertInvalidOrder(List order) { - assertThatThrownBy( - () -> - COMPILER.compile( - List.of( - contribution( - "fixture.event.created", - 1, - ValidPayload.class, - order, - "contracts/messaging/fixture.event.created/v1.schema.json", - hash(1), - descriptor("fixture-events", true, 256))))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("component"); - } - - @SuppressWarnings({"rawtypes", "unchecked"}) - private static void assertUnsupportedGraph( - Class type, List order) { - IntegrationEventContractContribution contribution = - contribution( - "fixture.unsupported.graph", - 1, - (Class) type, - order, - "contracts/messaging/fixture.unsupported.graph/v1.schema.json", - hash(9), - descriptor("fixture-events", true, 256)); - assertThatThrownBy(() -> COMPILER.compile(List.of(contribution))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageMatching(".*(unsupported declared|raw Optional/List).*"); - } - - private static Contribution validContribution(String contractId, int version) { - return contribution( - contractId, - version, - ValidPayload.class, - List.of("eventId", "count"), - "contracts/messaging/" + contractId + "/v" + version + ".schema.json", - hash(version), - descriptor("fixture-events", true, 256)); - } - - private static ContractDescriptor descriptor( - String destination, boolean orderingRequired, int maximumEnvelopeBytes) { - return new ContractDescriptor( - "adapter-outbound-messaging", - new LogicalDestinationId(destination), - "json-schema-envelope-v1", - orderingRequired, - 128, - maximumEnvelopeBytes, - ContractDescriptor.SensitivityClassification.INTERNAL, - Duration.ofDays(7)); - } - - private static Sha256 hash(int seed) { - return new Sha256(HexFormat.of().parseHex(String.format("%064x", seed))); - } - - private static

Contribution

contribution( - String contractId, - int version, - Class

type, - List componentOrder, - String schemaResource, - Sha256 schemaHash, - ContractDescriptor descriptor) { - return new Contribution<>( - new ContractId(contractId), - version, - type, - componentOrder, - new SchemaResourceId(schemaResource), - schemaHash, - descriptor); - } - - private record Contribution

( - ContractId contractId, - int payloadVersion, - Class

exactPayloadRecordType, - List canonicalRecordComponentOrder, - SchemaResourceId payloadSchemaResource, - Sha256 payloadSchemaHash, - ContractDescriptor descriptor) - implements IntegrationEventContractContribution

{} - - private static final class StatefulContribution

- implements IntegrationEventContractContribution

{ - - private final ContractId contractId; - private final int payloadVersion; - private final Class

exactPayloadRecordType; - private final List canonicalRecordComponentOrder; - private final SchemaResourceId payloadSchemaResource; - private final List payloadSchemaHashes; - private final List descriptors; - private int contractIdCalls; - private int payloadVersionCalls; - private int exactPayloadRecordTypeCalls; - private int canonicalRecordComponentOrderCalls; - private int payloadSchemaResourceCalls; - private int payloadSchemaHashCalls; - private int descriptorCalls; - - private StatefulContribution( - ContractId contractId, - int payloadVersion, - Class

exactPayloadRecordType, - List canonicalRecordComponentOrder, - SchemaResourceId payloadSchemaResource, - List payloadSchemaHashes, - List descriptors) { - this.contractId = contractId; - this.payloadVersion = payloadVersion; - this.exactPayloadRecordType = exactPayloadRecordType; - this.canonicalRecordComponentOrder = canonicalRecordComponentOrder; - this.payloadSchemaResource = payloadSchemaResource; - this.payloadSchemaHashes = payloadSchemaHashes; - this.descriptors = descriptors; - } - - @Override - public ContractId contractId() { - contractIdCalls++; - return contractId; - } - - @Override - public int payloadVersion() { - payloadVersionCalls++; - return payloadVersion; - } - - @Override - public Class

exactPayloadRecordType() { - exactPayloadRecordTypeCalls++; - return exactPayloadRecordType; - } - - @Override - public List canonicalRecordComponentOrder() { - canonicalRecordComponentOrderCalls++; - return canonicalRecordComponentOrder; - } - - @Override - public SchemaResourceId payloadSchemaResource() { - payloadSchemaResourceCalls++; - return payloadSchemaResource; - } - - @Override - public Sha256 payloadSchemaHash() { - int index = Math.min(payloadSchemaHashCalls++, payloadSchemaHashes.size() - 1); - return payloadSchemaHashes.get(index); - } - - @Override - public ContractDescriptor descriptor() { - int index = Math.min(descriptorCalls++, descriptors.size() - 1); - return descriptors.get(index); - } - - private List callCounts() { - return List.of( - contractIdCalls, - payloadVersionCalls, - exactPayloadRecordTypeCalls, - canonicalRecordComponentOrderCalls, - payloadSchemaResourceCalls, - payloadSchemaHashCalls, - descriptorCalls); - } - } - - private record ValidPayload(String eventId, int count) implements IntegrationPayload {} - - private record OtherPayload(String value) implements IntegrationPayload {} - - private record ClosedGraphPayload( - String name, - long count, - BigDecimal amount, - GraphState state, - Optional> nested) - implements IntegrationPayload {} - - private record ClosedNested(String code, BigInteger rank) {} - - private enum GraphState { - READY - } - - private record ObjectPayload(Object value) implements IntegrationPayload {} - - private record InterfacePayload(CharSequence value) implements IntegrationPayload {} - - private record MapPayload(Map value) implements IntegrationPayload {} - - @SuppressWarnings("rawtypes") - private record RawListPayload(List value) implements IntegrationPayload {} - - private record WildcardListPayload(List value) implements IntegrationPayload {} - - private record JsonTreePayload(tools.jackson.databind.JsonNode value) - implements IntegrationPayload {} - - private record GenericRecordPayload(GenericNested value) implements IntegrationPayload {} - - private record GenericNested(T value) {} - - private static final class MutablePayload implements IntegrationPayload {} -} diff --git a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/contract/ContractCatalogDigestTest.java b/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/contract/ContractCatalogDigestTest.java deleted file mode 100644 index 1f541d4d..00000000 --- a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/contract/ContractCatalogDigestTest.java +++ /dev/null @@ -1,112 +0,0 @@ -package dev.caskeleton.adapter.outbound.messaging.contract; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.application.messaging.contract.ContractDescriptor; -import dev.caskeleton.application.messaging.contract.ContractId; -import dev.caskeleton.application.messaging.contract.IntegrationEventContractContribution; -import dev.caskeleton.application.messaging.contract.IntegrationPayload; -import dev.caskeleton.application.messaging.contract.LogicalDestinationId; -import dev.caskeleton.application.messaging.contract.SchemaResourceId; -import dev.caskeleton.application.messaging.contract.Sha256; -import java.time.Duration; -import java.util.HexFormat; -import java.util.List; -import org.junit.jupiter.api.Test; - -class ContractCatalogDigestTest { - - @Test - void digestIsDeterministicForEmptyAndInputOrderIndependentForNonEmptyCatalogs() { - CompiledIntegrationEventContract first = contract("fixture.a.created", 1, hash(1), 256); - CompiledIntegrationEventContract second = contract("fixture.b.created", 2, hash(2), 512); - - assertThat(ContractCatalogDigest.compute(List.of()).toString()) - .isEqualTo("a86e4f7991482c9ee798a606da37ae379e36d81ca2fa3c2ea190ba2b0cee1da0"); - assertThat(ContractCatalogDigest.compute(List.of(first, second))) - .isEqualTo(ContractCatalogDigest.compute(List.of(second, first))); - } - - @Test - void digestChangesForSchemaHashDescriptorAndCanonicalComponentOrderSemantics() { - CompiledIntegrationEventContract baseline = contract("fixture.a.created", 1, hash(1), 256); - CompiledIntegrationEventContract schemaChanged = contract("fixture.a.created", 1, hash(2), 256); - CompiledIntegrationEventContract descriptorChanged = - contract("fixture.a.created", 1, hash(1), 512); - CompiledIntegrationEventContract orderChanged = - compile( - contribution( - "fixture.a.created", - 1, - ReorderedDigestPayload.class, - List.of("count", "eventId"), - hash(1), - 256)); - - Sha256 digest = ContractCatalogDigest.compute(List.of(baseline)); - - assertThat(ContractCatalogDigest.compute(List.of(schemaChanged))).isNotEqualTo(digest); - assertThat(ContractCatalogDigest.compute(List.of(descriptorChanged))).isNotEqualTo(digest); - assertThat(ContractCatalogDigest.compute(List.of(orderChanged))).isNotEqualTo(digest); - } - - private static CompiledIntegrationEventContract contract( - String contractId, int version, Sha256 schemaHash, int maximumEnvelopeBytes) { - return compile( - contribution( - contractId, - version, - DigestPayload.class, - List.of("eventId", "count"), - schemaHash, - maximumEnvelopeBytes)); - } - - private static CompiledIntegrationEventContract compile( - IntegrationEventContractContribution contribution) { - return new ContractCatalogCompiler().compile(List.of(contribution)).getFirst(); - } - - private static

DigestContribution

contribution( - String contractId, - int version, - Class

payloadType, - List componentOrder, - Sha256 schemaHash, - int maximumEnvelopeBytes) { - return new DigestContribution<>( - new ContractId(contractId), - version, - payloadType, - componentOrder, - new SchemaResourceId("contracts/messaging/" + contractId + "/v" + version + ".schema.json"), - schemaHash, - new ContractDescriptor( - "adapter-outbound-messaging", - new LogicalDestinationId("fixture-events"), - "json-schema-envelope-v1", - true, - 128, - maximumEnvelopeBytes, - ContractDescriptor.SensitivityClassification.INTERNAL, - Duration.ofDays(7))); - } - - private static Sha256 hash(int seed) { - return new Sha256(HexFormat.of().parseHex(String.format("%064x", seed))); - } - - private record DigestPayload(String eventId, int count) implements IntegrationPayload {} - - private record ReorderedDigestPayload(int count, String eventId) implements IntegrationPayload {} - - private record DigestContribution

( - ContractId contractId, - int payloadVersion, - Class

exactPayloadRecordType, - List canonicalRecordComponentOrder, - SchemaResourceId payloadSchemaResource, - Sha256 payloadSchemaHash, - ContractDescriptor descriptor) - implements IntegrationEventContractContribution

{} -} diff --git a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/destination/DestinationBindingCompilerTest.java b/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/destination/DestinationBindingCompilerTest.java deleted file mode 100644 index 500efc00..00000000 --- a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/destination/DestinationBindingCompilerTest.java +++ /dev/null @@ -1,648 +0,0 @@ -package dev.caskeleton.adapter.outbound.messaging.destination; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.outbound.messaging.config.CompiledMessagingDescriptor; -import dev.caskeleton.adapter.outbound.messaging.config.MessagingCapabilityCardRegistry; -import dev.caskeleton.adapter.outbound.messaging.contract.CompiledIntegrationEventContract; -import dev.caskeleton.adapter.outbound.messaging.contract.ContractCatalogCompiler; -import dev.caskeleton.adapter.outbound.messaging.contract.ContractCatalogDigest; -import dev.caskeleton.application.messaging.contract.ContractDescriptor; -import dev.caskeleton.application.messaging.contract.ContractId; -import dev.caskeleton.application.messaging.contract.IntegrationEventContractContribution; -import dev.caskeleton.application.messaging.contract.IntegrationPayload; -import dev.caskeleton.application.messaging.contract.LogicalDestinationId; -import dev.caskeleton.application.messaging.contract.SchemaResourceId; -import dev.caskeleton.application.messaging.contract.Sha256; -import java.lang.reflect.Modifier; -import java.time.Duration; -import java.util.ArrayList; -import java.util.HexFormat; -import java.util.List; -import java.util.Optional; -import org.junit.jupiter.api.Test; - -class DestinationBindingCompilerTest { - - private static final MessagingCapabilityCardRegistry CARDS = - MessagingCapabilityCardRegistry.exactFirstR2(); - private static final DestinationBindingCompiler COMPILER = new DestinationBindingCompiler(); - - @Test - void compilesExactContractBindingWithCodeDeploymentByteIntersectionAndStableDigests() { - CompiledIntegrationEventContract contract = contract("fixture.event.created", 1, 256); - DestinationBindingSettings first = - settings( - List.of(binding("fixture-events", "fixture.events.v1", 512, ref(contract))), - MessagingCapabilityCardRegistry.exactFirstR2Selection(), - true, - true, - true, - Optional.empty()); - DestinationBindingSettings shuffledBootstrap = - settings( - List.of( - binding( - "fixture-events", - "fixture.events.v1", - 512, - List.of("broker-b:9093", "broker-a:9093"), - ref(contract))), - MessagingCapabilityCardRegistry.exactFirstR2Selection(), - true, - true, - true, - Optional.empty()); - - List result = COMPILER.compile(List.of(contract), first, CARDS); - - assertThat(result).hasSize(1); - CompiledPublicationBinding compiled = result.getFirst(); - assertThat(compiled.contract().stableKey()).isEqualTo("fixture.event.created:v1"); - assertThat(compiled.logicalDestination()).isEqualTo(contract.descriptor().logicalDestination()); - assertThat(compiled.physicalTopic()).isEqualTo("fixture.events.v1"); - assertThat(compiled.bootstrapServers()).containsExactly("broker-a:9093", "broker-b:9093"); - assertThat(compiled.effectiveMaximumRecordBytes()).isEqualTo(256); - assertThat(compiled.settingsDigest()) - .isEqualTo( - COMPILER - .compile(List.of(contract), shuffledBootstrap, CARDS) - .getFirst() - .settingsDigest()); - assertThat(compiled.schemaSetDigest()).isNotNull(); - assertThatThrownBy(() -> compiled.bootstrapServers().add("broker-c:9093")) - .isInstanceOf(UnsupportedOperationException.class); - } - - @Test - void deploymentMaximumBelowCodeMaximumWinsAndMustRemainPositive() { - CompiledIntegrationEventContract contract = contract("fixture.event.created", 1, 256); - DestinationBindingSettings settings = - settings( - List.of(binding("fixture-events", "fixture.events.v1", 192, ref(contract))), - MessagingCapabilityCardRegistry.exactFirstR2Selection(), - true, - true, - true, - Optional.empty()); - - assertThat( - COMPILER - .compile(List.of(contract), settings, CARDS) - .getFirst() - .effectiveMaximumRecordBytes()) - .isEqualTo(192); - assertThatThrownBy( - () -> - new DestinationBindingSettings.DestinationBinding( - new LogicalDestinationId("fixture-events"), - List.of(ref(contract)), - "fixture.events.v1", - List.of("broker-a:9093"), - 0)) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void settingsRejectDuplicateLogicalDestinationsInvalidPortsAndSecretShapedLegacyAliases() { - CompiledIntegrationEventContract contract = contract("fixture.event.created", 1, 256); - DestinationBindingSettings.DestinationBinding exact = - binding("fixture-events", "fixture.events.v1", 512, ref(contract)); - - assertThatThrownBy( - () -> - settings( - List.of(exact, exact), - MessagingCapabilityCardRegistry.exactFirstR2Selection(), - true, - true, - true, - Optional.empty())) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("duplicate destination"); - assertThatThrownBy( - () -> - binding( - "fixture-events", - "fixture.events.v1", - 512, - List.of("broker-a:99999"), - ref(contract))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("bootstrap"); - assertThatThrownBy( - () -> - new DestinationBindingSettings.LegacyAliases( - Optional.of("user:password"), Optional.empty(), List.of("broker-a:9093"))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("legacy"); - } - - @Test - void settingsRejectNullDestinationAndDuplicatePhysicalTopicAcrossLogicalDestinations() { - CompiledIntegrationEventContract contract = contract("fixture.event.created", 1, 256); - DestinationBindingSettings.DestinationBinding first = - binding("fixture-events", "shared.events.v1", 512, ref(contract)); - DestinationBindingSettings.DestinationBinding second = - binding( - "other-events", - "shared.events.v1", - 512, - new DestinationBindingSettings.ContractVersion( - new ContractId("fixture.other.created"), 1)); - - assertThatThrownBy( - () -> - settings( - List.of(first, second), - MessagingCapabilityCardRegistry.exactFirstR2Selection(), - true, - true, - true, - Optional.empty())) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("physical topic"); - - List withNull = new ArrayList<>(); - withNull.add(null); - assertThatThrownBy( - () -> - settings( - withNull, - MessagingCapabilityCardRegistry.exactFirstR2Selection(), - true, - true, - true, - Optional.empty())) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("destination"); - } - - @Test - void rejectsMissingDuplicateExtraAndContractDestinationMismatchedBindings() { - CompiledIntegrationEventContract contract = contract("fixture.event.created", 1, 256); - DestinationBindingSettings.DestinationBinding exact = - binding("fixture-events", "fixture.events.v1", 512, ref(contract)); - - assertThatThrownBy( - () -> - COMPILER.compile( - List.of(contract), - settings( - List.of(), - MessagingCapabilityCardRegistry.exactFirstR2Selection(), - true, - true, - true, - Optional.empty()), - CARDS)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("missing"); - assertThatThrownBy( - () -> - COMPILER.compile( - List.of(contract), - settings( - List.of(exact, exact), - MessagingCapabilityCardRegistry.exactFirstR2Selection(), - true, - true, - true, - Optional.empty()), - CARDS)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("duplicate destination"); - assertThatThrownBy( - () -> - COMPILER.compile( - List.of(contract), - settings( - List.of( - exact, - binding( - "unused-events", - "unused.events.v1", - 512, - new DestinationBindingSettings.ContractVersion( - new ContractId("fixture.unknown.created"), 1))), - MessagingCapabilityCardRegistry.exactFirstR2Selection(), - true, - true, - true, - Optional.empty()), - CARDS)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("extra"); - assertThatThrownBy( - () -> - COMPILER.compile( - List.of(contract), - settings( - List.of(binding("other-events", "other.events.v1", 512, ref(contract))), - MessagingCapabilityCardRegistry.exactFirstR2Selection(), - true, - true, - true, - Optional.empty()), - CARDS)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("identity"); - } - - @Test - void rejectsUnknownCardsRoleMismatchLegacyConflictAndRelaxedRequirements() { - CompiledIntegrationEventContract contract = contract("fixture.event.created", 1, 256); - List bindings = - List.of(binding("fixture-events", "fixture.events.v1", 512, ref(contract))); - - assertRejected( - contract, - settings( - bindings, - selectionWithProducer("future-consumer.v1"), - true, - true, - true, - Optional.empty()), - "unknown"); - assertRejected( - contract, - settings( - bindings, - selectionWithProducer( - MessagingCapabilityCardRegistry.exactFirstR2Selection().serializationCardId()), - true, - true, - true, - Optional.empty()), - "role"); - assertRejected( - contract, - settings( - bindings, - MessagingCapabilityCardRegistry.exactFirstR2Selection(), - true, - true, - true, - Optional.of( - new DestinationBindingSettings.LegacyAliases( - Optional.of("kafka"), Optional.of("legacy.topic"), List.of("legacy:9092")))), - "legacy"); - assertRejected( - contract, - settings( - bindings, - MessagingCapabilityCardRegistry.exactFirstR2Selection(), - false, - true, - true, - Optional.empty()), - "ordering"); - assertRejected( - contract, - settings( - bindings, - MessagingCapabilityCardRegistry.exactFirstR2Selection(), - true, - false, - true, - Optional.empty()), - "schema"); - assertRejected( - contract, - settings( - bindings, - MessagingCapabilityCardRegistry.exactFirstR2Selection(), - true, - true, - false, - Optional.empty()), - "security"); - } - - @Test - void disabledEmptyCatalogIsZeroResourceWhileActiveRequiresExactCatalogAndBindings() { - DestinationBindingSettings emptySettings = - settings( - List.of(), - MessagingCapabilityCardRegistry.exactFirstR2Selection(), - true, - true, - true, - Optional.empty()); - - CompiledMessagingDescriptor disabled = - CompiledMessagingDescriptor.compile( - CompiledMessagingDescriptor.ActivationMode.DISABLED, List.of(), emptySettings, CARDS); - - assertThat(CompiledMessagingDescriptor.contractsOf(disabled)).isEmpty(); - assertThat(CompiledMessagingDescriptor.bindingsOf(disabled)).isEmpty(); - assertThat(disabled.resourceCount()).isZero(); - assertThatThrownBy( - () -> - CompiledMessagingDescriptor.compile( - CompiledMessagingDescriptor.ActivationMode.ACTIVE, - List.of(), - emptySettings, - CARDS)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("empty catalog"); - - CompiledIntegrationEventContract contract = contract("fixture.event.created", 1, 256); - DestinationBindingSettings activeSettings = - settings( - List.of(binding("fixture-events", "fixture.events.v1", 512, ref(contract))), - MessagingCapabilityCardRegistry.exactFirstR2Selection(), - true, - true, - true, - Optional.empty()); - CompiledMessagingDescriptor active = - CompiledMessagingDescriptor.compile( - CompiledMessagingDescriptor.ActivationMode.ACTIVE, - List.of(contract), - activeSettings, - CARDS); - - assertThat(CompiledMessagingDescriptor.bindingsOf(active)).hasSize(1); - assertThat(active.catalogDigest()).isEqualTo(ContractCatalogDigest.compute(List.of(contract))); - assertThat(active.settingsDigest()) - .isEqualTo(CompiledMessagingDescriptor.bindingsOf(active).getFirst().settingsDigest()); - assertThat(active.schemaSetDigest()) - .isEqualTo(CompiledMessagingDescriptor.bindingsOf(active).getFirst().schemaSetDigest()); - assertThat(CompiledMessagingDescriptor.bindingsOf(active).getFirst().contract()) - .isSameAs(CompiledMessagingDescriptor.contractsOf(active).getFirst()); - assertThat(active.resourceCount()).isZero(); - } - - @Test - void compiledArtifactsExposeOnlyNarrowStaticImmutableCompositionBridges() - throws NoSuchMethodException { - assertThat(Modifier.isFinal(CompiledPublicationBinding.class.getModifiers())).isTrue(); - assertThat(Modifier.isFinal(CompiledMessagingDescriptor.class.getModifiers())).isTrue(); - assertThat(Modifier.isFinal(CompiledIntegrationEventContract.class.getModifiers())).isTrue(); - assertThat(CompiledPublicationBinding.class.isRecord()).isFalse(); - assertThat(CompiledMessagingDescriptor.class.isRecord()).isFalse(); - assertThat(CompiledIntegrationEventContract.class.isRecord()).isFalse(); - assertThat(CompiledPublicationBinding.class.getConstructors()).isEmpty(); - assertThat(CompiledMessagingDescriptor.class.getConstructors()).isEmpty(); - assertThat(CompiledIntegrationEventContract.class.getConstructors()).isEmpty(); - assertThat(CompiledPublicationBinding.class.getDeclaredConstructors()) - .allSatisfy( - constructor -> assertThat(Modifier.isPublic(constructor.getModifiers())).isFalse()); - assertThat(CompiledMessagingDescriptor.class.getDeclaredConstructors()) - .allSatisfy( - constructor -> assertThat(Modifier.isPrivate(constructor.getModifiers())).isTrue()); - assertPackagePrivateInstanceMethod( - DestinationBindingCompiler.class, - "compile", - List.class, - DestinationBindingSettings.class, - MessagingCapabilityCardRegistry.class); - assertPublicStaticMethod( - DestinationBindingCompiler.class, - "compileExact", - List.class, - DestinationBindingSettings.class, - MessagingCapabilityCardRegistry.class); - assertPackagePrivateInstanceMethod(CompiledMessagingDescriptor.class, "contracts"); - assertPackagePrivateInstanceMethod(CompiledMessagingDescriptor.class, "bindings"); - assertPublicStaticMethod( - CompiledMessagingDescriptor.class, "contractsOf", CompiledMessagingDescriptor.class); - assertPublicStaticMethod( - CompiledMessagingDescriptor.class, "bindingsOf", CompiledMessagingDescriptor.class); - assertPackagePrivateInstanceMethod(MessagingCapabilityCardRegistry.class, "cards"); - assertPackagePrivateInstanceMethod(DestinationBindingSettings.class, "destinations"); - assertPackagePrivateInstanceMethod(DestinationBindingSettings.class, "legacyAliases"); - assertPackagePrivateInstanceMethod( - DestinationBindingSettings.DestinationBinding.class, "contracts"); - - BindingContribution firstContribution = - contribution( - "fixture.event.created", - BindingPayload.class, - "contracts/messaging/fixture.event.created/v1.schema.json"); - BindingContribution duplicateSchemaContribution = - contribution( - "fixture.other.created", - AlternateBindingPayload.class, - "contracts/messaging/fixture.event.created/v1.schema.json"); - BindingContribution duplicateExactTypeContribution = - contribution( - "fixture.other.created", - BindingPayload.class, - "contracts/messaging/fixture.other.created/v1.schema.json"); - - assertThatThrownBy( - () -> - ContractCatalogCompiler.compileExact( - List.of(firstContribution, duplicateSchemaContribution))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("schema"); - assertThatThrownBy( - () -> - ContractCatalogCompiler.compileExact( - List.of(firstContribution, duplicateExactTypeContribution))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("payload"); - - CompiledIntegrationEventContract first = - ContractCatalogCompiler.compileExact(List.of(firstContribution)).getFirst(); - DestinationBindingSettings settings = - settings( - List.of(binding("fixture-events", "fixture.events.v1", 512, ref(first))), - MessagingCapabilityCardRegistry.exactFirstR2Selection(), - true, - true, - true, - Optional.empty()); - - CompiledMessagingDescriptor active = - CompiledMessagingDescriptor.compile( - CompiledMessagingDescriptor.ActivationMode.ACTIVE, List.of(first), settings, CARDS); - assertThat(CompiledMessagingDescriptor.contractsOf(active).getFirst()).isSameAs(first); - assertThat(CompiledMessagingDescriptor.bindingsOf(active).getFirst().contract()) - .isSameAs(first); - assertThatThrownBy( - () -> - new DestinationBindingSettings.DestinationBinding( - new LogicalDestinationId("fixture-events"), - List.of(ref(first)), - " ", - List.of("broker-a:9093"), - 512)) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new DestinationBindingSettings.DestinationBinding( - new LogicalDestinationId("fixture-events"), - List.of(ref(first)), - "fixture.events.v1", - List.of("user:secret@broker-a:9093"), - 512)) - .isInstanceOf(IllegalArgumentException.class); - Sha256 digest = ContractCatalogDigest.compute(List.of(first)); - assertThatThrownBy( - () -> - new CompiledPublicationBinding( - first, - new LogicalDestinationId("other-events"), - "fixture.events.v1", - List.of("broker-a:9093"), - 256, - MessagingCapabilityCardRegistry.exactFirstR2Selection(), - digest, - digest)) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new CompiledPublicationBinding( - first, - first.descriptor().logicalDestination(), - "fixture.events.v1", - List.of("broker-a:9093"), - 257, - MessagingCapabilityCardRegistry.exactFirstR2Selection(), - digest, - digest)) - .isInstanceOf(IllegalArgumentException.class); - } - - private static void assertPackagePrivateInstanceMethod( - Class owner, String methodName, Class... parameterTypes) throws NoSuchMethodException { - int modifiers = owner.getDeclaredMethod(methodName, parameterTypes).getModifiers(); - assertThat(Modifier.isPublic(modifiers)).isFalse(); - assertThat(Modifier.isStatic(modifiers)).isFalse(); - } - - private static void assertPublicStaticMethod( - Class owner, String methodName, Class... parameterTypes) throws NoSuchMethodException { - int modifiers = owner.getDeclaredMethod(methodName, parameterTypes).getModifiers(); - assertThat(Modifier.isPublic(modifiers)).isTrue(); - assertThat(Modifier.isStatic(modifiers)).isTrue(); - } - - private static void assertRejected( - CompiledIntegrationEventContract contract, - DestinationBindingSettings settings, - String message) { - assertThatThrownBy(() -> COMPILER.compile(List.of(contract), settings, CARDS)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining(message); - } - - private static DestinationBindingSettings settings( - List bindings, - MessagingCapabilityCardRegistry.ExactSelection selection, - boolean ordering, - boolean schema, - boolean security, - Optional legacy) { - return new DestinationBindingSettings(bindings, selection, ordering, schema, security, legacy); - } - - private static DestinationBindingSettings.DestinationBinding binding( - String logicalDestination, - String physicalTopic, - int maximumRecordBytes, - DestinationBindingSettings.ContractVersion... contracts) { - return binding( - logicalDestination, - physicalTopic, - maximumRecordBytes, - List.of("broker-a:9093", "broker-b:9093"), - contracts); - } - - private static DestinationBindingSettings.DestinationBinding binding( - String logicalDestination, - String physicalTopic, - int maximumRecordBytes, - List bootstrapServers, - DestinationBindingSettings.ContractVersion... contracts) { - return new DestinationBindingSettings.DestinationBinding( - new LogicalDestinationId(logicalDestination), - List.of(contracts), - physicalTopic, - bootstrapServers, - maximumRecordBytes); - } - - private static DestinationBindingSettings.ContractVersion ref( - CompiledIntegrationEventContract contract) { - return new DestinationBindingSettings.ContractVersion( - contract.contractId(), contract.payloadVersion()); - } - - private static MessagingCapabilityCardRegistry.ExactSelection selectionWithProducer( - String producer) { - MessagingCapabilityCardRegistry.ExactSelection selected = - MessagingCapabilityCardRegistry.exactFirstR2Selection(); - return new MessagingCapabilityCardRegistry.ExactSelection( - selected.semanticCardId(), - producer, - selected.dispatchCardId(), - selected.claimCardId(), - selected.serializationCardId(), - selected.topicCardId(), - selected.securityCardId(), - selected.compressionCardId(), - selected.orderingCardId(), - selected.transactionCardId(), - selected.operatorControlCardId()); - } - - private static CompiledIntegrationEventContract contract( - String contractId, int version, int maximumEnvelopeBytes) { - BindingContribution contribution = - new BindingContribution<>( - new ContractId(contractId), - version, - BindingPayload.class, - List.of("eventId"), - new SchemaResourceId( - "contracts/messaging/" + contractId + "/v" + version + ".schema.json"), - new Sha256(HexFormat.of().parseHex(String.format("%064x", version))), - descriptor("fixture-events", maximumEnvelopeBytes)); - return ContractCatalogCompiler.compileExact(List.of(contribution)).getFirst(); - } - - private static

BindingContribution

contribution( - String contractId, Class

payloadType, String schemaResource) { - return new BindingContribution<>( - new ContractId(contractId), - 1, - payloadType, - List.of("eventId"), - new SchemaResourceId(schemaResource), - new Sha256(HexFormat.of().parseHex(String.format("%064x", contractId.hashCode()))), - descriptor("fixture-events", 256)); - } - - private static ContractDescriptor descriptor(String destination, int maximumEnvelopeBytes) { - return new ContractDescriptor( - "adapter-outbound-messaging", - new LogicalDestinationId(destination), - "json-schema-envelope-v1", - true, - 128, - maximumEnvelopeBytes, - ContractDescriptor.SensitivityClassification.INTERNAL, - Duration.ofDays(7)); - } - - private record BindingPayload(String eventId) implements IntegrationPayload {} - - private record AlternateBindingPayload(String eventId) implements IntegrationPayload {} - - private record BindingContribution

( - ContractId contractId, - int payloadVersion, - Class

exactPayloadRecordType, - List canonicalRecordComponentOrder, - SchemaResourceId payloadSchemaResource, - Sha256 payloadSchemaHash, - ContractDescriptor descriptor) - implements IntegrationEventContractContribution

{} -} diff --git a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/destination/PartitionKeyV1Test.java b/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/destination/PartitionKeyV1Test.java deleted file mode 100644 index b9c9d3d7..00000000 --- a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/destination/PartitionKeyV1Test.java +++ /dev/null @@ -1,104 +0,0 @@ -package dev.caskeleton.adapter.outbound.messaging.destination; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.application.messaging.contract.LogicalDestinationId; -import dev.caskeleton.application.messaging.event.AggregateIdentity; -import java.nio.charset.StandardCharsets; -import org.junit.jupiter.api.Test; - -class PartitionKeyV1Test { - - private static final LogicalDestinationId DESTINATION = - new LogicalDestinationId("portfolio-domain-events"); - - @Test - void freezesTenantScopedGoldenVectorAsLowercaseHexAndExactAsciiBytes() { - PartitionKeyV1.Value key = - PartitionKeyV1.derive( - DESTINATION, new AggregateIdentity("tenant-a", "worklog", "worklog-42")); - - assertThat(key.text()) - .isEqualTo("0e5feab14824293a301c3e8509f23363f38a585cbcba5895c8f3a3655ca1550a") - .matches("[0-9a-f]{64}"); - assertThat(key.bytes()).hasSize(64); - assertThat(key.bytes()).isEqualTo(key.text().getBytes(StandardCharsets.US_ASCII)); - byte[] callerCopy = key.bytes(); - callerCopy[0] = 'f'; - assertThat(key.bytes()).isEqualTo(key.text().getBytes(StandardCharsets.US_ASCII)); - } - - @Test - void tenantDisabledCallerMustSupplyTheCanonicalNonNullSystemScope() { - assertThat( - PartitionKeyV1.derive( - DESTINATION, new AggregateIdentity("system", "worklog", "worklog-42")) - .text()) - .isEqualTo("449f3054afd8ba5234c160fdeca359497645ef198b166c9a380e20702748b3a6"); - - assertThatThrownBy(() -> PartitionKeyV1.derive(DESTINATION, null)) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - PartitionKeyV1.deriveCanonicalComponents( - null, DESTINATION, "worklog", "worklog-42")) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - PartitionKeyV1.deriveCanonicalComponents(" ", DESTINATION, "worklog", "worklog-42")) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void nonAsciiAggregateIdGoldenVectorUsesUtf8ByteLengthNotCharacterCount() { - assertThat( - PartitionKeyV1.deriveCanonicalComponents("tenant-a", DESTINATION, "worklog", "작업-42") - .text()) - .isEqualTo("367eee4ab006e7f16324abdd026009c257e81ece048abb62f69ccbbfe18631df"); - } - - @Test - void malformedUtf8SurrogatesAreRejectedInsteadOfCollidingWithLiteralQuestionMark() { - PartitionKeyV1.Value literalQuestionMark = - PartitionKeyV1.deriveCanonicalComponents("tenant-a", DESTINATION, "worklog", "?"); - - assertThat(literalQuestionMark.text()).matches("[0-9a-f]{64}"); - assertThatThrownBy( - () -> PartitionKeyV1.deriveCanonicalComponents("\uD800", DESTINATION, "worklog", "?")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("UTF-8"); - assertThatThrownBy( - () -> PartitionKeyV1.deriveCanonicalComponents("tenant-a", DESTINATION, "\uDC00", "?")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("UTF-8"); - assertThatThrownBy( - () -> - PartitionKeyV1.deriveCanonicalComponents( - "tenant-a", DESTINATION, "worklog", "\uD800")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("UTF-8"); - } - - @Test - void canonicalComponentsApplyTask3BoundsBeforeEncoding() { - assertThatThrownBy( - () -> - PartitionKeyV1.deriveCanonicalComponents( - "t".repeat(97), DESTINATION, "worklog", "worklog-42")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("tenantScope"); - assertThatThrownBy( - () -> - PartitionKeyV1.deriveCanonicalComponents( - "tenant-a", DESTINATION, "w".repeat(65), "worklog-42")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("aggregateType"); - assertThatThrownBy( - () -> - PartitionKeyV1.deriveCanonicalComponents( - "tenant-a", DESTINATION, "worklog", "i".repeat(161))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("aggregateId"); - } -} diff --git a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/envelope/EnvelopeAdversarialCorpusTest.java b/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/envelope/EnvelopeAdversarialCorpusTest.java deleted file mode 100644 index e0ac636a..00000000 --- a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/envelope/EnvelopeAdversarialCorpusTest.java +++ /dev/null @@ -1,334 +0,0 @@ -package dev.caskeleton.adapter.outbound.messaging.envelope; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.outbound.messaging.contract.CompiledIntegrationEventContract; -import dev.caskeleton.adapter.outbound.messaging.contract.ContractCatalogCompiler; -import dev.caskeleton.application.messaging.contract.ContractDescriptor; -import dev.caskeleton.application.messaging.contract.ContractId; -import dev.caskeleton.application.messaging.contract.IntegrationEventContractContribution; -import dev.caskeleton.application.messaging.contract.IntegrationPayload; -import dev.caskeleton.application.messaging.contract.LogicalDestinationId; -import dev.caskeleton.application.messaging.contract.SchemaResourceId; -import dev.caskeleton.application.messaging.contract.Sha256; -import dev.caskeleton.application.messaging.event.AggregateIdentity; -import dev.caskeleton.application.messaging.event.AggregateOrder; -import dev.caskeleton.application.messaging.event.EventId; -import dev.caskeleton.application.messaging.event.IntegrationEventDraft; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.time.Duration; -import java.time.Instant; -import java.util.AbstractList; -import java.util.ConcurrentModificationException; -import java.util.HexFormat; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import org.junit.jupiter.api.Test; - -/** - * Small adopted corpus: JSON-Schema-Test-Suite draft2020-12 type/required/additionalProperties and - * Bowtie-style malformed-instance scenarios. This is bounded repository evidence, not a full - * implementation compatibility claim. - */ -class EnvelopeAdversarialCorpusTest { - - private static final EnvelopeAdmissionLimits LIMITS = - new EnvelopeAdmissionLimits(8, 64, 128, 4, 10, 8, 1024, 2048, 16, 64, 4); - private static final DeterministicEnvelopeWriter WRITER = new DeterministicEnvelopeWriter(LIMITS); - - @Test - void limitsRejectZeroNegativeAndUnlimitedSentinels() { - assertThatThrownBy(() -> new EnvelopeAdmissionLimits(0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> new EnvelopeAdmissionLimits(Integer.MAX_VALUE, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("finite"); - } - - @Test - void writerRejectsMapRawTreeUnsupportedClassNonfiniteAndUnpairedSurrogate() { - assertRejected(new MapPayload(Map.of("key", "value")), "unsupported"); - assertRejected(new ObjectPayload(new Object()), "unsupported"); - assertRejected(new DoublePayload(Double.NaN), "finite"); - assertRejected(new DoublePayload(Double.POSITIVE_INFINITY), "finite"); - assertRejected(new StringPayload("\ud800"), "surrogate"); - } - - @Test - void writerEnforcesStringUtf8ArrayObjectNumberAndDepthBudgets() { - assertRejected(new StringPayload("a".repeat(65)), "string"); - assertRejected(new StringPayload("가".repeat(50)), "UTF-8"); - assertRejected(new IntegerListPayload(List.of(1, 2, 3, 4, 5)), "array"); - assertRejected( - new ManyPropertiesPayload( - new ManyProperties("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11")), - "properties"); - assertRejected(new BigIntegerPayload(new BigInteger("123456789")), "digits"); - assertRejected( - new DepthPayload( - new Depth1( - new Depth2( - new Depth3(new Depth4(new Depth5(new Depth6(new Depth7(new Depth8("x"))))))))), - "depth"); - } - - @Test - void rejectsExtremePositiveDecimalScaleBeforePlainStringAllocation() { - assertRejected( - new BigDecimalPayload(new BigDecimal(BigInteger.ONE, Integer.MAX_VALUE)), "digits"); - } - - @Test - void boundsJsonOutputDuringWritesInsteadOfOnlyInspectingTheCompletedBuffer() { - assertThat( - java.util.Arrays.stream(DeterministicEnvelopeWriter.class.getDeclaredClasses()) - .map(Class::getSimpleName)) - .contains("BoundedByteArrayOutputStream"); - EnvelopeAdmissionLimits tinyOutput = - new EnvelopeAdmissionLimits(8, 64, 128, 4, 10, 8, 16, 64, 16, 64, 4); - DeterministicEnvelopeWriter tinyWriter = new DeterministicEnvelopeWriter(tinyOutput); - - assertThatThrownBy( - () -> - tinyWriter.write( - draft(new StringPayload("1234567890")), contract(StringPayload.class))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("byte admission"); - } - - @Test - void checksListSizeBeforeIterationAndFailsClosedOnMutationOrConcurrency() { - assertRejected(new IntegerListPayload(new OversizedNoArrayList()), "array"); - assertRejected(new IntegerListPayload(new SizeDriftingList()), "mutated"); - assertRejected(new IntegerListPayload(new ConcurrentFailureList()), "mutated"); - } - - @Test - void writerUsesExactRecordOrderUtf8AndCanonicalScalarRendering() { - OrderedPayload payload = - new OrderedPayload( - "한글", new BigDecimal("12.5000"), 7, true, Optional.empty(), List.of("β", "alpha")); - DeterministicEnvelopeWriter.EncodedEnvelope encoded = - WRITER.write(draft(payload), contract(OrderedPayload.class)); - - String json = new String(encoded.envelopeBytes(), java.nio.charset.StandardCharsets.UTF_8); - assertThat(json) - .contains( - "\"payload\":{\"text\":\"한글\",\"decimal\":12.5,\"integral\":7,\"flag\":true,\"optional\":null,\"list\":[\"β\",\"alpha\"]}"); - assertThat(encoded.payloadBytes()) - .isEqualTo( - "{\"text\":\"한글\",\"decimal\":12.5,\"integral\":7,\"flag\":true,\"optional\":null,\"list\":[\"β\",\"alpha\"]}" - .getBytes(java.nio.charset.StandardCharsets.UTF_8)); - } - - @Test - void exactPayloadClassIsRequiredAndNoAssignableTypeSearchOccurs() { - CompiledIntegrationEventContract exact = contract(OrderedPayload.class); - StringPayload other = new StringPayload("value"); - - assertThatThrownBy(() -> WRITER.write(draft(other), exact)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("exact"); - } - - @SuppressWarnings("unchecked") - private static

void assertRejected(P payload, String message) { - Class

exactType = (Class

) payload.getClass(); - assertThatThrownBy(() -> WRITER.write(draft(payload), contract(exactType))) - .isInstanceOf(IllegalArgumentException.class) - .satisfies(exception -> assertThat(exception.getMessage()).containsIgnoringCase(message)); - } - - private static

IntegrationEventDraft

draft(P payload) { - return new IntegrationEventDraft<>( - new EventId("event-adversarial"), - new ContractId("test.adversarial"), - 1, - new LogicalDestinationId("test-events"), - new AggregateIdentity("tenant-a", "worklog", "W-1"), - new AggregateOrder(1, 0), - Instant.parse("2026-07-29T00:00:00Z"), - "corr-adversarial", - Optional.empty(), - payload); - } - - private static

CompiledIntegrationEventContract contract( - Class

type) { - List order = - java.util.Arrays.stream(type.getRecordComponents()) - .map(java.lang.reflect.RecordComponent::getName) - .toList(); - IntegrationEventContractContribution

contribution = - new IntegrationEventContractContribution<>() { - @Override - public ContractId contractId() { - return new ContractId("test.adversarial"); - } - - @Override - public int payloadVersion() { - return 1; - } - - @Override - public Class

exactPayloadRecordType() { - return type; - } - - @Override - public List canonicalRecordComponentOrder() { - return order; - } - - @Override - public SchemaResourceId payloadSchemaResource() { - return new SchemaResourceId("contracts/messaging/test.adversarial/v1.schema.json"); - } - - @Override - public Sha256 payloadSchemaHash() { - return new Sha256(HexFormat.of().parseHex("11".repeat(32))); - } - - @Override - public ContractDescriptor descriptor() { - return new ContractDescriptor( - "adapter-outbound-messaging", - new LogicalDestinationId("test-events"), - "json-schema-envelope-v1", - true, - 1024, - 2048, - ContractDescriptor.SensitivityClassification.INTERNAL, - Duration.ofDays(1)); - } - }; - return ContractCatalogCompiler.compileExact(List.of(contribution)).getFirst(); - } - - private record ObjectPayload(Object value) implements IntegrationPayload {} - - private record MapPayload(Map value) implements IntegrationPayload {} - - private record DoublePayload(double value) implements IntegrationPayload {} - - private record StringPayload(String value) implements IntegrationPayload {} - - private record IntegerListPayload(List value) implements IntegrationPayload {} - - private record ManyPropertiesPayload(ManyProperties value) implements IntegrationPayload {} - - private record BigIntegerPayload(BigInteger value) implements IntegrationPayload {} - - private record BigDecimalPayload(BigDecimal value) implements IntegrationPayload {} - - private record DepthPayload(Depth1 value) implements IntegrationPayload {} - - private record OrderedPayload( - String text, - BigDecimal decimal, - long integral, - boolean flag, - Optional optional, - List list) - implements IntegrationPayload {} - - private record ManyProperties( - String a, - String b, - String c, - String d, - String e, - String f, - String g, - String h, - String i, - String j, - String k) {} - - private record Depth1(Depth2 value) {} - - private record Depth2(Depth3 value) {} - - private record Depth3(Depth4 value) {} - - private record Depth4(Depth5 value) {} - - private record Depth5(Depth6 value) {} - - private record Depth6(Depth7 value) {} - - private record Depth7(Depth8 value) {} - - private record Depth8(String value) {} - - private static final class OversizedNoArrayList extends AbstractList { - - @Override - public Integer get(int index) { - throw new AssertionError("oversized list must be rejected before element access"); - } - - @Override - public int size() { - return 5; - } - - @Override - public Object[] toArray() { - throw new AssertionError("writer must not duplicate the list through toArray"); - } - } - - private static final class SizeDriftingList extends AbstractList { - - @Override - public Integer get(int index) { - return List.of(1, 2).get(index); - } - - @Override - public int size() { - return 1; - } - - @Override - public Iterator iterator() { - return List.of(1, 2).iterator(); - } - } - - private static final class ConcurrentFailureList extends AbstractList { - - @Override - public Integer get(int index) { - return 1; - } - - @Override - public int size() { - return 1; - } - - @Override - public Iterator iterator() { - return new Iterator<>() { - @Override - public boolean hasNext() { - throw new ConcurrentModificationException("fixture"); - } - - @Override - public Integer next() { - return 1; - } - }; - } - } -} diff --git a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/envelope/JsonSchemaIntegrationEventEncoderTest.java b/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/envelope/JsonSchemaIntegrationEventEncoderTest.java deleted file mode 100644 index 3d960a92..00000000 --- a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/envelope/JsonSchemaIntegrationEventEncoderTest.java +++ /dev/null @@ -1,413 +0,0 @@ -package dev.caskeleton.adapter.outbound.messaging.envelope; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.outbound.messaging.config.MessagingCapabilityCardRegistry; -import dev.caskeleton.adapter.outbound.messaging.contract.CompiledIntegrationEventContract; -import dev.caskeleton.adapter.outbound.messaging.contract.ContractCatalogCompiler; -import dev.caskeleton.adapter.outbound.messaging.destination.CompiledPublicationBinding; -import dev.caskeleton.adapter.outbound.messaging.destination.DestinationBindingCompiler; -import dev.caskeleton.adapter.outbound.messaging.destination.DestinationBindingSettings; -import dev.caskeleton.application.messaging.contract.ContractDescriptor; -import dev.caskeleton.application.messaging.contract.ContractId; -import dev.caskeleton.application.messaging.contract.IntegrationEventContractContribution; -import dev.caskeleton.application.messaging.contract.IntegrationPayload; -import dev.caskeleton.application.messaging.contract.LogicalDestinationId; -import dev.caskeleton.application.messaging.contract.SchemaResourceId; -import dev.caskeleton.application.messaging.contract.Sha256; -import dev.caskeleton.application.messaging.event.AggregateIdentity; -import dev.caskeleton.application.messaging.event.AggregateOrder; -import dev.caskeleton.application.messaging.event.EventId; -import dev.caskeleton.application.messaging.event.IntegrationEventDraft; -import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent; -import java.io.IOException; -import java.io.InputStream; -import java.math.BigDecimal; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.time.Duration; -import java.time.Instant; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.atomic.AtomicInteger; -import org.junit.jupiter.api.Test; - -class JsonSchemaIntegrationEventEncoderTest { - - private static final String ENVELOPE_RESOURCE = "contracts/messaging/envelope/v1.schema.json"; - private static final String PAYLOAD_RESOURCE = "contracts/messaging/test.event/v1.schema.json"; - private static final EnvelopeAdmissionLimits LIMITS = - new EnvelopeAdmissionLimits(16, 256, 1024, 16, 64, 64, 4096, 8192, 32, 256, 8); - - @Test - void writesAndValidatesExactCanonicalUtf8EnvelopeWithStableHashesAndRevisions() { - Fixture fixture = fixture(); - IntegrationEventDraft draft = fixture.validDraft(); - - ValidatedIntegrationEvent first = fixture.encoder().encode(draft); - ValidatedIntegrationEvent second = fixture.encoder().encode(draft); - String expected = - """ - {"envelopeVersion":1,"eventId":"event-1","contractId":"test.event","payloadVersion":1,"logicalDestination":"test-events","aggregate":{"type":"worklog","id":"W-1","sequence":3,"eventIndex":0},"occurredAt":"2026-07-29T01:02:03.123Z","correlationId":"corr-1","contentType":"application/json","payload":{"name":"정확한-UTF8","count":7,"enabled":true,"amount":12.5,"status":"READY","note":null,"tags":["alpha","β"],"nested":{"code":"N1"}}}\ - """; - - assertThat(first.envelopeBytes()).containsExactly(expected.getBytes(StandardCharsets.UTF_8)); - assertThat(second).isEqualTo(first); - assertThat(first.partitionKeyText()).matches("[0-9a-f]{64}"); - assertThat(first.schemaSetHash().toString()).matches("[0-9a-f]{64}"); - assertThat(first.envelopeSha256()).isEqualTo(EnvelopeHashV1.compute(first.envelopeBytes())); - assertThat(first.envelopeSchemaHash()) - .isEqualTo(fixture.registry().schemaHash(ENVELOPE_RESOURCE)); - assertThat(first.payloadSchemaHash()) - .isEqualTo(fixture.registry().schemaHash(PAYLOAD_RESOURCE)); - assertThat(first.contractCatalogRevision()).matches("[0-9a-f]{64}"); - assertThat(first.destinationBindingRevision()).matches("[0-9a-f]{64}"); - byte[] returned = first.envelopeBytes(); - returned[0] = 0; - assertThat(first.envelopeBytes()[0]).isEqualTo((byte) '{'); - } - - @Test - void rejectsUnknownVersionDestinationExactTypeAndSchemaInvalidPayload() { - Fixture fixture = fixture(); - IntegrationEventDraft valid = fixture.validDraft(); - - assertThatThrownBy( - () -> - fixture - .encoder() - .encode( - new IntegrationEventDraft<>( - valid.eventId(), - valid.contractId(), - 2, - valid.destinationId(), - valid.aggregate(), - valid.order(), - valid.occurredAt(), - valid.correlationId(), - valid.causationId(), - valid.featurePayload()))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("contract"); - assertThatThrownBy( - () -> - fixture - .encoder() - .encode( - new IntegrationEventDraft<>( - valid.eventId(), - valid.contractId(), - 1, - new LogicalDestinationId("other-events"), - valid.aggregate(), - valid.order(), - valid.occurredAt(), - valid.correlationId(), - valid.causationId(), - valid.featurePayload()))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("destination"); - assertThatThrownBy( - () -> - fixture - .encoder() - .encode( - new IntegrationEventDraft<>( - valid.eventId(), - valid.contractId(), - 1, - valid.destinationId(), - valid.aggregate(), - valid.order(), - valid.occurredAt(), - valid.correlationId(), - valid.causationId(), - new OtherPayload("wrong")))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("exact"); - assertThatThrownBy( - () -> - fixture - .encoder() - .encode( - new IntegrationEventDraft<>( - valid.eventId(), - valid.contractId(), - 1, - valid.destinationId(), - valid.aggregate(), - valid.order(), - valid.occurredAt(), - valid.correlationId(), - valid.causationId(), - new TestPayload( - "", - 7, - true, - new BigDecimal("12.50"), - Status.READY, - Optional.empty(), - List.of(), - new NestedPayload("N1"))))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("payload schema"); - } - - @Test - void exactEnvelopeHashHasDomainSeparatedGoldenVectorAndDefensiveShaValue() { - byte[] bytes = "abc".getBytes(StandardCharsets.UTF_8); - - Sha256 hash = EnvelopeHashV1.compute(bytes); - - assertThat(hash.toString()) - .isEqualTo("34c6935b92898e650d376a5180b6f14eeaf3c5231277629d29688d2da5caf45b"); - bytes[0] = 'z'; - assertThat(hash.toString()) - .isEqualTo("34c6935b92898e650d376a5180b6f14eeaf3c5231277629d29688d2da5caf45b"); - } - - @Test - void snapshotsStatefulMutablePayloadAccessorsOnceAndEmbedsThoseExactBytes() { - StatefulPayload.reset(); - byte[] schemaBytes = resource(PAYLOAD_RESOURCE); - StatefulContribution contribution = new StatefulContribution(sha256(schemaBytes)); - CompiledIntegrationEventContract contract = - ContractCatalogCompiler.compileExact(List.of(contribution)).getFirst(); - IntegrationEventDraft draft = - new IntegrationEventDraft<>( - new EventId("event-1"), - new ContractId("test.event"), - 1, - new LogicalDestinationId("test-events"), - new AggregateIdentity("tenant-a", "worklog", "W-1"), - new AggregateOrder(3, 0), - Instant.parse("2026-07-29T01:02:03.123Z"), - "corr-1", - Optional.empty(), - new StatefulPayload(List.of("first"))); - - DeterministicEnvelopeWriter.EncodedEnvelope encoded = - new DeterministicEnvelopeWriter(LIMITS).write(draft, contract); - String payload = new String(encoded.payloadBytes(), StandardCharsets.UTF_8); - String envelope = new String(encoded.envelopeBytes(), StandardCharsets.UTF_8); - - assertThat(StatefulPayload.accessorCalls()).isEqualTo(1); - assertThat(payload).isEqualTo("{\"tags\":[\"first\"]}"); - assertThat(envelope).endsWith("\"payload\":" + payload + "}"); - } - - private static Fixture fixture() { - byte[] payloadSchema = resource(PAYLOAD_RESOURCE); - TestContribution contribution = new TestContribution(sha256(payloadSchema)); - CompiledIntegrationEventContract contract = - ContractCatalogCompiler.compileExact(List.of(contribution)).getFirst(); - DestinationBindingSettings settings = - new DestinationBindingSettings( - List.of( - new DestinationBindingSettings.DestinationBinding( - new LogicalDestinationId("test-events"), - List.of( - new DestinationBindingSettings.ContractVersion( - new ContractId("test.event"), 1)), - "test.events.v1", - List.of("broker-a:9093"), - 8192)), - MessagingCapabilityCardRegistry.exactFirstR2Selection(), - true, - true, - true, - Optional.empty()); - CompiledPublicationBinding binding = - DestinationBindingCompiler.compileExact( - List.of(contract), settings, MessagingCapabilityCardRegistry.exactFirstR2()) - .getFirst(); - LocalJsonSchemaRegistry registry = - new LocalJsonSchemaRegistry( - Map.of( - ENVELOPE_RESOURCE, source(ENVELOPE_RESOURCE), - PAYLOAD_RESOURCE, source(PAYLOAD_RESOURCE)), - LIMITS); - return new Fixture( - registry, - new JsonSchemaIntegrationEventEncoder( - List.of(contract), List.of(binding), registry, LIMITS)); - } - - private static LocalJsonSchemaRegistry.SchemaSource source(String path) { - byte[] bytes = resource(path); - return new LocalJsonSchemaRegistry.SchemaSource(path, bytes, sha256(bytes)); - } - - private static byte[] resource(String path) { - try (InputStream input = - JsonSchemaIntegrationEventEncoderTest.class.getClassLoader().getResourceAsStream(path)) { - if (input == null) { - throw new IllegalStateException("missing test resource " + path); - } - return input.readAllBytes(); - } catch (IOException exception) { - throw new IllegalStateException(exception); - } - } - - private static Sha256 sha256(byte[] bytes) { - try { - return new Sha256(MessageDigest.getInstance("SHA-256").digest(bytes)); - } catch (NoSuchAlgorithmException exception) { - throw new IllegalStateException(exception); - } - } - - private record Fixture( - LocalJsonSchemaRegistry registry, JsonSchemaIntegrationEventEncoder encoder) { - - private IntegrationEventDraft validDraft() { - return new IntegrationEventDraft<>( - new EventId("event-1"), - new ContractId("test.event"), - 1, - new LogicalDestinationId("test-events"), - new AggregateIdentity("tenant-a", "worklog", "W-1"), - new AggregateOrder(3, 0), - Instant.parse("2026-07-29T01:02:03.123Z"), - "corr-1", - Optional.of("cause-1"), - new TestPayload( - "정확한-UTF8", - 7, - true, - new BigDecimal("12.50"), - Status.READY, - Optional.empty(), - List.of("alpha", "β"), - new NestedPayload("N1"))); - } - } - - private record TestContribution(Sha256 payloadSchemaHash) - implements IntegrationEventContractContribution { - - @Override - public ContractId contractId() { - return new ContractId("test.event"); - } - - @Override - public int payloadVersion() { - return 1; - } - - @Override - public Class exactPayloadRecordType() { - return TestPayload.class; - } - - @Override - public List canonicalRecordComponentOrder() { - return List.of("name", "count", "enabled", "amount", "status", "note", "tags", "nested"); - } - - @Override - public SchemaResourceId payloadSchemaResource() { - return new SchemaResourceId(PAYLOAD_RESOURCE); - } - - @Override - public ContractDescriptor descriptor() { - return new ContractDescriptor( - "adapter-outbound-messaging", - new LogicalDestinationId("test-events"), - "json-schema-envelope-v1", - true, - 4096, - 8192, - ContractDescriptor.SensitivityClassification.INTERNAL, - Duration.ofDays(7)); - } - } - - private record TestPayload( - String name, - int count, - boolean enabled, - BigDecimal amount, - Status status, - Optional note, - List tags, - NestedPayload nested) - implements IntegrationPayload {} - - private record OtherPayload(String value) implements IntegrationPayload {} - - private record StatefulContribution(Sha256 payloadSchemaHash) - implements IntegrationEventContractContribution { - - @Override - public ContractId contractId() { - return new ContractId("test.event"); - } - - @Override - public int payloadVersion() { - return 1; - } - - @Override - public Class exactPayloadRecordType() { - return StatefulPayload.class; - } - - @Override - public List canonicalRecordComponentOrder() { - return List.of("tags"); - } - - @Override - public SchemaResourceId payloadSchemaResource() { - return new SchemaResourceId(PAYLOAD_RESOURCE); - } - - @Override - public ContractDescriptor descriptor() { - return new ContractDescriptor( - "adapter-outbound-messaging", - new LogicalDestinationId("test-events"), - "json-schema-envelope-v1", - true, - 4096, - 8192, - ContractDescriptor.SensitivityClassification.INTERNAL, - Duration.ofDays(7)); - } - } - - private record StatefulPayload(List tags) implements IntegrationPayload { - - private static final AtomicInteger CALLS = new AtomicInteger(); - - @Override - @SuppressWarnings("UnusedMethod") - public List tags() { - return CALLS.incrementAndGet() == 1 ? tags : List.of("mutated"); - } - - private static void reset() { - CALLS.set(0); - } - - private static int accessorCalls() { - return CALLS.get(); - } - } - - private record NestedPayload(String code) {} - - private enum Status { - READY, - DONE - } -} diff --git a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/envelope/LocalJsonSchemaRegistryTest.java b/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/envelope/LocalJsonSchemaRegistryTest.java deleted file mode 100644 index ff105bfa..00000000 --- a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/envelope/LocalJsonSchemaRegistryTest.java +++ /dev/null @@ -1,393 +0,0 @@ -package dev.caskeleton.adapter.outbound.messaging.envelope; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.application.messaging.contract.Sha256; -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import org.junit.jupiter.api.Test; - -class LocalJsonSchemaRegistryTest { - - private static final String ENVELOPE_RESOURCE = "contracts/messaging/envelope/v1.schema.json"; - private static final String PAYLOAD_RESOURCE = "contracts/messaging/test.event/v1.schema.json"; - private static final String PAYLOAD_ID = "urn:dev-caskeleton:contracts:messaging:test.event:v1"; - private static final String ENVELOPE_ID = "urn:dev-caskeleton:contracts:messaging:envelope:v1"; - private static final EnvelopeAdmissionLimits LIMITS = - new EnvelopeAdmissionLimits(16, 256, 1024, 16, 64, 64, 4096, 8192, 32, 256, 8); - - @Test - void precompilesOnlyCheckedDraft202012ResourcesAndValidatesGoldenVectors() { - LocalJsonSchemaRegistry registry = registry(); - - assertThat( - registry.validate(PAYLOAD_ID, resource(PAYLOAD_RESOURCE.replace(".schema", ".valid")))) - .isEmpty(); - assertThat( - registry.validate( - PAYLOAD_ID, resource(PAYLOAD_RESOURCE.replace(".schema", ".invalid")))) - .isNotEmpty(); - assertThat(registry.schemaId(PAYLOAD_RESOURCE)).isEqualTo(PAYLOAD_ID); - assertThat(registry.schemaHash(PAYLOAD_RESOURCE)).isEqualTo(sha256(resource(PAYLOAD_RESOURCE))); - assertThat(registry.exactSchemaBytes(PAYLOAD_RESOURCE)) - .containsExactly(resource(PAYLOAD_RESOURCE)); - assertThat(registry.pinnedDraft202012AuthorityHash().toString()) - .isEqualTo("8a9c3b75ebf53edb639da470d4f213a5210a1f62015f4a705d428e8ba3649efb"); - } - - @Test - void startupAuthorityDoesNotDependOnARegularNetworkNtCodeSourceJar() { - byte[] implementation = classBytes(LocalJsonSchemaRegistry.class); - String constantPool = new String(implementation, StandardCharsets.ISO_8859_1); - - assertThat(constantPool) - .doesNotContain("getProtectionDomain") - .doesNotContain("java/util/jar/JarFile") - .doesNotContain("networknt-3.0.2.jar.sha256"); - assertThat( - LocalJsonSchemaRegistryTest.class - .getClassLoader() - .getResource("contracts/messaging/meta/draft-2020-12/networknt-3.0.2.jar.sha256")) - .isNull(); - assertThat(registry().pinnedDraft202012AuthorityHash().toString()) - .isEqualTo("8a9c3b75ebf53edb639da470d4f213a5210a1f62015f4a705d428e8ba3649efb"); - } - - @Test - void rejectsMissingRequiredNullForbiddenAndInvalidEnvelopeInstances() { - LocalJsonSchemaRegistry registry = registry(); - byte[] nullForbidden = - """ - {"name":null,"count":0,"enabled":true,"amount":1,"status":"READY", - "note":null,"tags":[],"nested":{"code":"N1"}} - """ - .getBytes(StandardCharsets.UTF_8); - - assertThat(registry.validate(PAYLOAD_ID, "{}".getBytes(StandardCharsets.UTF_8))) - .anyMatch(error -> error.contains("required")); - assertThat(registry.validate(PAYLOAD_ID, nullForbidden)) - .anyMatch(error -> error.contains("type")); - assertThat(registry.validate(ENVELOPE_ID, "{}".getBytes(StandardCharsets.UTF_8))) - .anyMatch(error -> error.contains("required")); - } - - @Test - void parserRejectsUnpairedSurrogateNonfiniteDepthAndNumberBoundsBeforeValidation() { - LocalJsonSchemaRegistry registry = registry(); - String tooDeep = "[".repeat(17) + "0" + "]".repeat(17); - String tooLongNumber = "1".repeat(65); - - assertThatThrownBy( - () -> registry.validate(PAYLOAD_ID, "\"\\uD800\"".getBytes(StandardCharsets.UTF_8))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("surrogate"); - assertThatThrownBy(() -> registry.validate(PAYLOAD_ID, "NaN".getBytes(StandardCharsets.UTF_8))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("JSON"); - assertThatThrownBy( - () -> registry.validate(PAYLOAD_ID, tooDeep.getBytes(StandardCharsets.UTF_8))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("JSON"); - assertThatThrownBy( - () -> registry.validate(PAYLOAD_ID, tooLongNumber.getBytes(StandardCharsets.UTF_8))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("JSON"); - } - - @Test - void exposesOnlyTheExactByteValidationBoundary() { - assertThat( - java.util.Arrays.stream(LocalJsonSchemaRegistry.class.getMethods()) - .filter(method -> method.getName().equals("validate")) - .map(method -> List.of(method.getParameterTypes())) - .toList()) - .containsExactly(List.of(String.class, byte[].class)); - } - - @Test - void rejectsChecksumMismatchDuplicateIdUnknownDialectAndRequiredVocabulary() { - byte[] payload = resource(PAYLOAD_RESOURCE); - assertThatThrownBy( - () -> - new LocalJsonSchemaRegistry( - Map.of( - PAYLOAD_RESOURCE, - new LocalJsonSchemaRegistry.SchemaSource( - PAYLOAD_RESOURCE, - payload, - sha256("different".getBytes(StandardCharsets.UTF_8)))), - LIMITS)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("checksum"); - - Map duplicate = new LinkedHashMap<>(); - duplicate.put(PAYLOAD_RESOURCE, source(PAYLOAD_RESOURCE)); - duplicate.put( - "contracts/messaging/duplicate/v1.schema.json", - new LocalJsonSchemaRegistry.SchemaSource( - "contracts/messaging/duplicate/v1.schema.json", payload, sha256(payload))); - assertThatThrownBy(() -> new LocalJsonSchemaRegistry(duplicate, LIMITS)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("duplicate"); - - assertRejectedSchema( - """ - {"$schema":"https://example.invalid/draft","$id":"urn:test:unknown","type":"object"} - """, - "dialect"); - assertRejectedSchema( - """ - {"$schema":"https://json-schema.org/draft/2020-12/schema", - "$id":"urn:test:vocabulary", - "$vocabulary":{"https://example.invalid/required":true}, - "type":"object"} - """, - "vocabulary"); - } - - @Test - void rejectsNonStringRootDialectAndIdentifierNodes() { - assertRejectedSchema( - """ - {"$schema":false,"$id":"urn:test:non-string-dialect","type":"object"} - """, - "dialect"); - assertRejectedSchema( - """ - {"$schema":"https://json-schema.org/draft/2020-12/schema", - "$id":false,"type":"object"} - """, - "$id"); - } - - @Test - void rejectsInvalidSchemaRemoteReferenceAndReferenceGraphBeyondConfiguredDepth() { - assertRejectedSchema( - """ - {"$schema":"https://json-schema.org/draft/2020-12/schema", - "$id":"urn:test:invalid","type":37} - """, - "schema"); - assertRejectedSchema( - """ - {"$schema":"https://json-schema.org/draft/2020-12/schema", - "$id":"urn:test:remote","$ref":"https://example.invalid/secret-schema"} - """, - "reference"); - assertRejectedSchema( - """ - {"$schema":"https://json-schema.org/draft/2020-12/schema", - "$id":"urn:test:cycle","$defs":{"a":{"$ref":"#/$defs/b"},"b":{"$ref":"#/$defs/a"}}, - "$ref":"#/$defs/a"} - """, - "depth"); - } - - @Test - void rejectsRelativeAndAbsoluteNestedSchemaIdentifiersInTheClosedSubset() { - assertRejectedSchema( - """ - {"$schema":"https://json-schema.org/draft/2020-12/schema", - "$id":"urn:test:nested-relative", - "$defs":{"nested":{"$id":"child","type":"string"}}, - "type":"object"} - """, - "nested $id"); - assertRejectedSchema( - """ - {"$schema":"https://json-schema.org/draft/2020-12/schema", - "$id":"urn:test:nested-absolute", - "$defs":{"nested":{"$id":"urn:test:nested-child","type":"string"}}, - "type":"object"} - """, - "nested $id"); - } - - @Test - void rejectsNestedSchemaIdentifierKeysRegardlessOfValueType() { - for (String nonTextIdentifier : List.of("37", "null", "{}", "false")) { - assertRejectedSchema( - """ - {"$schema":"https://json-schema.org/draft/2020-12/schema", - "$id":"urn:test:nested-non-text", - "$defs":{"nested":{"$id":%s,"type":"string"}}, - "type":"object"} - """ - .formatted(nonTextIdentifier), - "nested $id"); - } - } - - @Test - void rejectsDynamicRecursiveAndAnchorKeywordsEverywhereInTheClosedSubset() { - for (String keyword : - List.of("$dynamicRef", "$dynamicAnchor", "$recursiveRef", "$recursiveAnchor", "$anchor")) { - assertRejectedSchema( - """ - {"$schema":"https://json-schema.org/draft/2020-12/schema", - "$id":"urn:test:unsupported-keyword", - "$defs":{"nested":{"%s":"resource:external","type":"string"}}, - "type":"object"} - """ - .formatted(keyword), - keyword); - } - for (String externalTarget : List.of("classpath:external", "resource:external")) { - assertRejectedSchema( - """ - {"$schema":"https://json-schema.org/draft/2020-12/schema", - "$id":"urn:test:dynamic-ref", - "$dynamicRef":"%s", - "type":"object"} - """ - .formatted(externalTarget), - "$dynamicRef"); - } - } - - @Test - void acceptsOnlyExactUrnSchemeForRootIdentifiersAndAbsoluteReferences() { - for (String identifier : - List.of("classpath:root", "resource:root", "jar:file:test", "URN:test")) { - assertRejectedSchema( - """ - {"$schema":"https://json-schema.org/draft/2020-12/schema", - "$id":"%s","type":"object"} - """ - .formatted(identifier), - "exact urn"); - } - for (String reference : - List.of( - "classpath:external", - "resource:external", - "jar:file:test", - "https://example.invalid/schema", - "file:/tmp/schema", - "unknown:external")) { - assertRejectedSchema( - """ - {"$schema":"https://json-schema.org/draft/2020-12/schema", - "$id":"urn:test:absolute-reference", - "$ref":"%s"} - """ - .formatted(reference), - "exact urn"); - } - } - - @Test - void enablesFormatAssertionsAndReturnsDeterministicPayloadFreeErrors() { - String schema = - """ - {"$schema":"https://json-schema.org/draft/2020-12/schema", - "$id":"urn:test:format","type":"object","required":["when"], - "properties":{"when":{"type":"string","format":"date-time"}}, - "unevaluatedProperties":false} - """; - LocalJsonSchemaRegistry registry = - registryWith("contracts/messaging/format/v1.schema.json", schema); - - List first = - registry.validate( - "urn:test:format", - "{\"when\":\"not-a-time\",\"secret\":\"do-not-log\"}".getBytes(StandardCharsets.UTF_8)); - List second = - registry.validate( - "urn:test:format", - "{\"when\":\"not-a-time\",\"secret\":\"do-not-log\"}".getBytes(StandardCharsets.UTF_8)); - - assertThat(first).isEqualTo(second).isNotEmpty(); - assertThat(String.join(" ", first)).doesNotContain("do-not-log"); - } - - @Test - void rejectsDuplicateKeysMalformedUtf8TrailingGarbageAndOverBudgetRegexInputs() { - LocalJsonSchemaRegistry registry = registry(); - - assertThatThrownBy( - () -> - registry.validate( - PAYLOAD_ID, "{\"name\":\"a\",\"name\":\"b\"}".getBytes(StandardCharsets.UTF_8))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("JSON"); - assertThatThrownBy(() -> registry.validate(PAYLOAD_ID, new byte[] {(byte) 0xc3, 0x28})) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("UTF-8"); - assertThatThrownBy( - () -> registry.validate(PAYLOAD_ID, "{} trailing".getBytes(StandardCharsets.UTF_8))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("JSON"); - - String regexSchema = - """ - {"$schema":"https://json-schema.org/draft/2020-12/schema", - "$id":"urn:test:regex","type":"string","pattern":"^(a+)+$"} - """; - LocalJsonSchemaRegistry bounded = - registryWith("contracts/messaging/regex/v1.schema.json", regexSchema); - assertThatThrownBy( - () -> - bounded.validate( - "urn:test:regex", - ("\"" + "a".repeat(300) + "!\"").getBytes(StandardCharsets.UTF_8))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("string"); - } - - private static LocalJsonSchemaRegistry registry() { - return new LocalJsonSchemaRegistry( - Map.of( - ENVELOPE_RESOURCE, source(ENVELOPE_RESOURCE), - PAYLOAD_RESOURCE, source(PAYLOAD_RESOURCE)), - LIMITS); - } - - private static LocalJsonSchemaRegistry registryWith(String path, String schema) { - byte[] bytes = schema.getBytes(StandardCharsets.UTF_8); - return new LocalJsonSchemaRegistry( - Map.of(path, new LocalJsonSchemaRegistry.SchemaSource(path, bytes, sha256(bytes))), LIMITS); - } - - private static void assertRejectedSchema(String schema, String message) { - assertThatThrownBy(() -> registryWith("contracts/messaging/rejected/v1.schema.json", schema)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining(message); - } - - private static LocalJsonSchemaRegistry.SchemaSource source(String path) { - byte[] bytes = resource(path); - return new LocalJsonSchemaRegistry.SchemaSource(path, bytes, sha256(bytes)); - } - - private static byte[] resource(String path) { - try (InputStream input = - LocalJsonSchemaRegistryTest.class.getClassLoader().getResourceAsStream(path)) { - if (input == null) { - throw new IllegalStateException("missing test resource " + path); - } - return input.readAllBytes(); - } catch (IOException exception) { - throw new IllegalStateException(exception); - } - } - - private static byte[] classBytes(Class type) { - return resource(type.getName().replace('.', '/') + ".class"); - } - - private static Sha256 sha256(byte[] bytes) { - try { - return new Sha256(MessageDigest.getInstance("SHA-256").digest(bytes)); - } catch (NoSuchAlgorithmException exception) { - throw new IllegalStateException(exception); - } - } -} diff --git a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/evidence/MessagingEvidenceSchemaValidator.java b/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/evidence/MessagingEvidenceSchemaValidator.java new file mode 100644 index 00000000..fedd78dc --- /dev/null +++ b/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/evidence/MessagingEvidenceSchemaValidator.java @@ -0,0 +1,51 @@ +package dev.caskeleton.adapter.outbound.messaging.evidence; + +import com.networknt.schema.Error; +import com.networknt.schema.SchemaLocation; +import com.networknt.schema.SchemaRegistry; +import com.networknt.schema.SchemaRegistryConfig; +import com.networknt.schema.SpecificationVersion; +import java.util.List; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; + +/** + * Validates exact manifest bytes against the common Draft 2020-12 evidence schema. + * + *

The schema itself must pass Draft 2020-12 meta-validation first. NetworkNT resolves that + * meta-schema from its own jar, so nothing is fetched over the network. + */ +final class MessagingEvidenceSchemaValidator { + private static final String DRAFT_2020_12 = "https://json-schema.org/draft/2020-12/schema"; + private static final ObjectMapper JSON = + JsonMapper.builder() + .enable(DeserializationFeature.FAIL_ON_READING_DUP_TREE_KEY) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private MessagingEvidenceSchemaValidator() {} + + static List violations(byte[] exactSchemaBytes, byte[] exactManifestBytes) { + SchemaRegistry registry = + SchemaRegistry.withDefaultDialect( + SpecificationVersion.DRAFT_2020_12, + builder -> + builder.schemaRegistryConfig( + SchemaRegistryConfig.builder() + .formatAssertionsEnabled(true) + .typeLoose(false) + .failFast(false) + .build())); + JsonNode schema = JSON.readTree(exactSchemaBytes); + List schemaErrors = + registry.getSchema(SchemaLocation.of(DRAFT_2020_12)).validate(schema); + if (!schemaErrors.isEmpty()) { + return schemaErrors.stream().map(error -> "schema: " + error).toList(); + } + return registry.getSchema(schema).validate(JSON.readTree(exactManifestBytes)).stream() + .map(Error::toString) + .toList(); + } +} diff --git a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/evidence/MessagingEvidenceSchemaValidatorTest.java b/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/evidence/MessagingEvidenceSchemaValidatorTest.java new file mode 100644 index 00000000..168e76ff --- /dev/null +++ b/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/evidence/MessagingEvidenceSchemaValidatorTest.java @@ -0,0 +1,79 @@ +package dev.caskeleton.adapter.outbound.messaging.evidence; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import org.junit.jupiter.api.Test; + +/** + * The common build-evidence manifest schema (config/messaging/evidence) is valid Draft 2020-12 and + * accepts the manifest shape the R2 evidence producers are specified to write. + */ +class MessagingEvidenceSchemaValidatorTest { + + private static final Path COMMON_SCHEMA = + Path.of("../../../config/messaging/evidence/build-evidence-manifest-v1.schema.json"); + private static final String SHA256 = "sha256:" + "0".repeat(64); + private static final String VALID_MANIFEST = + """ + { + "schemaVersion": 1, + "sourceDigest": "%1$s", + "artifactDigest": "%1$s", + "producerTask": "verifyMessagingContracts", + "scenarioIds": ["scenario.one"], + "counts": {"executed": 1, "passed": 1, "failed": 0, "skipped": 0}, + "command": "./gradlew verifyMessagingContracts", + "generatedAt": "2026-07-29T00:00:00Z", + "hashes": { + "profile": "%1$s", + "catalog": "%1$s", + "schema": "%1$s", + "settings": "%1$s" + }, + "failures": [], + "skips": [], + "unsupportedClaims": [] + } + """ + .formatted(SHA256); + + @Test + void aConformingManifestPassesTheCommonSchema() throws IOException { + assertEquals(List.of(), violations(Files.readAllBytes(COMMON_SCHEMA), VALID_MANIFEST)); + } + + @Test + void aManifestWithAnUndeclaredFieldIsRejected() throws IOException { + String drifted = VALID_MANIFEST.replace("\n}", ",\n \"unexpected\": true\n}"); + + List violations = violations(Files.readAllBytes(COMMON_SCHEMA), drifted); + + assertTrue( + violations.stream().anyMatch(violation -> violation.contains("unexpected")), + violations.toString()); + } + + @Test + void aSchemaThatFailsDraft202012MetaValidationIsRejected() throws IOException { + String invalidSchema = + Files.readString(COMMON_SCHEMA).replaceFirst("\"type\"\\s*:\\s*\"object\"", "\"type\": 37"); + + List violations = + violations(invalidSchema.getBytes(StandardCharsets.UTF_8), VALID_MANIFEST); + + assertTrue( + !violations.isEmpty() && violations.stream().allMatch(v -> v.startsWith("schema: ")), + violations.toString()); + } + + private static List violations(byte[] schema, String manifest) { + return MessagingEvidenceSchemaValidator.violations( + schema, manifest.getBytes(StandardCharsets.UTF_8)); + } +} diff --git a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/outbox/Slf4jOutboxRelayFailureReportAdapterTest.java b/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/outbox/Slf4jOutboxRelayFailureReportAdapterTest.java index 917208a1..85322ffb 100644 --- a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/outbox/Slf4jOutboxRelayFailureReportAdapterTest.java +++ b/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/outbox/Slf4jOutboxRelayFailureReportAdapterTest.java @@ -9,6 +9,7 @@ import ch.qos.logback.classic.Level; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.read.ListAppender; import dev.caskeleton.application.outbox.OutboxRelayFailureReport; +import dev.caskeleton.application.outbox.OutboxRelayResult; import java.time.Instant; import java.util.LinkedHashMap; import java.util.Map; @@ -101,6 +102,30 @@ class Slf4jOutboxRelayFailureReportAdapterTest { assertThat(event.getThrowableProxy()).isNull(); } + @Test + void staleCompletionEmitsOneWarnNamingTheRefusedOutcome() { + // given + logger.setLevel(Level.WARN); + + // when + adapter.reportStaleCompletion("evt-3", "WorkLogReserved", OutboxRelayResult.Outcome.FAILED); + + // then + assertThat(appender.list) + .singleElement() + .extracting(event -> Map.entry(event.getLevel(), keyValues(event))) + .isEqualTo( + Map.entry( + Level.WARN, + Map.of( + "dependency_name", "kafka", + "dependency_type", "messaging", + "outcome", "STALE", + "attempted_outcome", "FAILED", + "event_id", "evt-3", + "event_type", "WorkLogReserved"))); + } + @Test void loggerRuntimeExceptionIsContained() { Logger throwingLogger = mock(Logger.class); diff --git a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/qualification/MessagingEvidenceManifestSchemaValidator.java b/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/qualification/MessagingEvidenceManifestSchemaValidator.java deleted file mode 100644 index 1a3fc898..00000000 --- a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/qualification/MessagingEvidenceManifestSchemaValidator.java +++ /dev/null @@ -1,68 +0,0 @@ -package dev.caskeleton.adapter.outbound.messaging.qualification; - -import dev.caskeleton.adapter.outbound.messaging.envelope.EnvelopeAdmissionLimits; -import dev.caskeleton.adapter.outbound.messaging.envelope.LocalJsonSchemaRegistry; -import dev.caskeleton.application.messaging.contract.Sha256; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.List; -import java.util.Map; - -/** - * Build/test-only validator for the common Messaging evidence manifest. - * - *

This class deliberately owns the file reads outside production runtime code. Validation uses - * the same pinned Draft 2020-12 registry as the Messaging adapter and consumes the exact schema and - * manifest bytes supplied by the build. - */ -public final class MessagingEvidenceManifestSchemaValidator { - - private static final String SCHEMA_ID = "urn:dev.caskeleton:messaging:build-evidence-manifest:v1"; - private static final String SCHEMA_RESOURCE = - "config/messaging/evidence/build-evidence-manifest-v1.schema.json"; - private static final EnvelopeAdmissionLimits LIMITS = - new EnvelopeAdmissionLimits( - 64, 4_096, 16_384, 10_000, 1_000, 1_000, 1_000_000, 1_000_000, 100, 4_096, 32); - - private MessagingEvidenceManifestSchemaValidator() {} - - public static void main(String[] arguments) { - if (arguments.length != 2) { - throw new IllegalArgumentException( - "expected exact common-schema path and generated-manifest path"); - } - try { - validate( - Files.readAllBytes(Path.of(arguments[0])), Files.readAllBytes(Path.of(arguments[1]))); - } catch (IOException exception) { - throw new IllegalStateException( - "cannot read exact Messaging evidence qualification bytes", exception); - } - } - - static void validate(byte[] exactSchemaBytes, byte[] exactManifestBytes) { - LocalJsonSchemaRegistry registry = - new LocalJsonSchemaRegistry( - Map.of( - SCHEMA_RESOURCE, - new LocalJsonSchemaRegistry.SchemaSource( - SCHEMA_RESOURCE, exactSchemaBytes, sha256(exactSchemaBytes))), - LIMITS); - List errors = registry.validate(SCHEMA_ID, exactManifestBytes); - if (!errors.isEmpty()) { - throw new IllegalArgumentException( - "generated Messaging evidence fails the common Draft 2020-12 schema: " + errors); - } - } - - private static Sha256 sha256(byte[] bytes) { - try { - return new Sha256(MessageDigest.getInstance("SHA-256").digest(bytes)); - } catch (NoSuchAlgorithmException exception) { - throw new IllegalStateException("SHA-256 is unavailable", exception); - } - } -} diff --git a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/qualification/MessagingEvidenceManifestSchemaValidatorTest.java b/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/qualification/MessagingEvidenceManifestSchemaValidatorTest.java deleted file mode 100644 index 2c0967e3..00000000 --- a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/qualification/MessagingEvidenceManifestSchemaValidatorTest.java +++ /dev/null @@ -1,81 +0,0 @@ -package dev.caskeleton.adapter.outbound.messaging.qualification; - -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import org.junit.jupiter.api.Test; - -class MessagingEvidenceManifestSchemaValidatorTest { - - private static final String SHA256 = "sha256:" + "0".repeat(64); - private static final String VALID_MANIFEST = - """ - { - "schemaVersion": 1, - "sourceDigest": "%1$s", - "artifactDigest": "%1$s", - "producerTask": "verifyMessagingContracts", - "scenarioIds": ["scenario.one"], - "counts": {"executed": 1, "passed": 1, "failed": 0, "skipped": 0}, - "command": "./gradlew verifyMessagingContracts", - "generatedAt": "2026-07-29T00:00:00Z", - "hashes": { - "profile": "%1$s", - "catalog": "%1$s", - "schema": "%1$s", - "settings": "%1$s" - }, - "failures": [], - "skips": [], - "unsupportedClaims": [] - } - """ - .formatted(SHA256); - - @Test - void validatesAConformingManifestAgainstTheExactCommonSchema() throws IOException { - assertThatCode( - () -> - MessagingEvidenceManifestSchemaValidator.validate( - commonSchemaBytes(), VALID_MANIFEST.getBytes(StandardCharsets.UTF_8))) - .doesNotThrowAnyException(); - } - - @Test - void rejectsManifestDriftThatTheCommonSchemaForbids() throws IOException { - String drifted = VALID_MANIFEST.replace("\n}", ",\n \"unexpected\": true\n}"); - - assertThatThrownBy( - () -> - MessagingEvidenceManifestSchemaValidator.validate( - commonSchemaBytes(), drifted.getBytes(StandardCharsets.UTF_8))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("common Draft 2020-12 schema"); - } - - @Test - void rejectsCommonSchemaDriftThatFailsDraft202012MetaValidation() throws IOException { - String invalidSchema = - new String(commonSchemaBytes(), StandardCharsets.UTF_8) - .replaceFirst("\"type\"\\s*:\\s*\"object\"", "\"type\": 37"); - - assertThatThrownBy( - () -> - MessagingEvidenceManifestSchemaValidator.validate( - invalidSchema.getBytes(StandardCharsets.UTF_8), - VALID_MANIFEST.getBytes(StandardCharsets.UTF_8))) - .isInstanceOf(IllegalArgumentException.class); - } - - private static byte[] commonSchemaBytes() throws IOException { - String configured = System.getProperty("messaging.commonEvidenceSchema"); - if (configured == null || configured.isBlank()) { - throw new IllegalStateException("messaging.commonEvidenceSchema test path is required"); - } - return Files.readAllBytes(Path.of(configured)); - } -} diff --git a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/messaging/autoconfigure/MessagingPlatformRootAutoConfiguration.java b/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/messaging/autoconfigure/MessagingPlatformRootAutoConfiguration.java new file mode 100644 index 00000000..0dbab8d7 --- /dev/null +++ b/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/messaging/autoconfigure/MessagingPlatformRootAutoConfiguration.java @@ -0,0 +1,25 @@ +package dev.caskeleton.messaging.autoconfigure; + +import dev.caskeleton.messaging.schema.EncodedMessagePublisher; +import org.springframework.boot.autoconfigure.AutoConfiguration; +import org.springframework.context.annotation.Bean; + +/** + * Test stand-in with the exact name of the messaging starter's root auto-configuration. + * + *

The bridge orders itself after that root by name, and Boot sorts auto-configurations + * alphabetically before applying {@code after} constraints — {@code dev.caskeleton.adapter…} comes + * before {@code dev.caskeleton.messaging…}. A stand-in with the same name reproduces that ordering + * without pulling the starter, and a broker, onto this leaf's test classpath. The starter is not on + * that classpath, so the name does not collide. + */ +@AutoConfiguration +public class MessagingPlatformRootAutoConfiguration { + + @Bean + EncodedMessagePublisher encodedMessagePublisher() { + return (destination, message, options) -> { + throw new AssertionError("publisher is not invoked while wiring the bridge"); + }; + } +} diff --git a/src/adapter/outbound/messaging/src/test/resources/contracts/messaging/test.event/v1.invalid.json b/src/adapter/outbound/messaging/src/test/resources/contracts/messaging/test.event/v1.invalid.json deleted file mode 100644 index e127ca96..00000000 --- a/src/adapter/outbound/messaging/src/test/resources/contracts/messaging/test.event/v1.invalid.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "name": "", - "count": -1, - "enabled": true, - "amount": 12.50, - "status": "UNKNOWN", - "note": null, - "tags": [], - "nested": { - "code": "N1" - }, - "unknown": "closed-schema" -} diff --git a/src/adapter/outbound/messaging/src/test/resources/contracts/messaging/test.event/v1.schema.json b/src/adapter/outbound/messaging/src/test/resources/contracts/messaging/test.event/v1.schema.json deleted file mode 100644 index 74a3d91a..00000000 --- a/src/adapter/outbound/messaging/src/test/resources/contracts/messaging/test.event/v1.schema.json +++ /dev/null @@ -1,70 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "urn:dev-caskeleton:contracts:messaging:test.event:v1", - "title": "Task 6 deterministic encoder test payload v1", - "type": "object", - "required": [ - "name", - "count", - "enabled", - "amount", - "status", - "note", - "tags", - "nested" - ], - "properties": { - "name": { - "type": "string", - "minLength": 1, - "maxLength": 64 - }, - "count": { - "type": "integer", - "minimum": 0, - "maximum": 999999 - }, - "enabled": { - "type": "boolean" - }, - "amount": { - "type": "number" - }, - "status": { - "enum": [ - "READY", - "DONE" - ] - }, - "note": { - "type": [ - "string", - "null" - ], - "maxLength": 64 - }, - "tags": { - "type": "array", - "maxItems": 8, - "items": { - "type": "string", - "maxLength": 32 - } - }, - "nested": { - "type": "object", - "required": [ - "code" - ], - "properties": { - "code": { - "type": "string", - "minLength": 1, - "maxLength": 16 - } - }, - "unevaluatedProperties": false - } - }, - "unevaluatedProperties": false -} diff --git a/src/adapter/outbound/messaging/src/test/resources/contracts/messaging/test.event/v1.valid.json b/src/adapter/outbound/messaging/src/test/resources/contracts/messaging/test.event/v1.valid.json deleted file mode 100644 index 52c2bce0..00000000 --- a/src/adapter/outbound/messaging/src/test/resources/contracts/messaging/test.event/v1.valid.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "name": "정확한-UTF8", - "count": 7, - "enabled": true, - "amount": 12.50, - "status": "READY", - "note": null, - "tags": [ - "alpha", - "β" - ], - "nested": { - "code": "N1" - } -} diff --git a/src/adapter/outbound/notification/build.gradle b/src/adapter/outbound/notification/build.gradle index 226beb1f..833e5c6a 100644 --- a/src/adapter/outbound/notification/build.gradle +++ b/src/adapter/outbound/notification/build.gradle @@ -1,7 +1,7 @@ plugins { id 'ca.spring-library' id 'ca.spring-config' - id 'ca.dependency-policy' + id 'ca.api-surface' } dependencies { @@ -14,7 +14,6 @@ dependencies { implementation 'org.springframework.boot:spring-boot-actuator' implementation 'org.springframework.boot:spring-boot-actuator-autoconfigure' implementation 'org.springframework.boot:spring-boot-health' - implementation 'org.springframework:spring-web' // Slack webhook client (RestClient) implementation 'org.slf4j:slf4j-api' // Micrometer core for the metric sink that implements NotificationMetricsPort. The sink used @@ -30,11 +29,8 @@ dependencies { // by hand to avoid one dependency would be the more dangerous choice. // - jackson-databind: provider payloads, callback bodies and the canonical variables payload are // JSON. It stays inside this adapter; application-core never sees a JSON type. - // - reactor-core: only the optional Reactor facade uses it. The core async type stays - // CompletionStage, so nothing else on this classpath depends on Reactor. implementation 'org.springframework.boot:spring-boot-starter-mail' implementation 'org.springframework.boot:spring-boot-starter-json' - implementation 'io.projectreactor:reactor-core' // JSON Schema 2020-12 validation of template variables, using the same validator and version the // messaging adapter already depends on rather than a second implementation of the same spec. // @@ -42,8 +38,8 @@ dependencies { // parser for a format this leaf never reads is surface for nothing. It does not remove YAML from // the runtime — org.yaml:snakeyaml is on this classpath via spring-boot-starter, which is how // Spring Boot reads application.yml. The comment here used to claim the stronger outcome, and - // the resolved graph had said otherwise for as long as it stood; dependencyPolicy below now - // states the claim the build can check. + // the resolved graph had said otherwise for as long as it stood; the rule below states the claim + // resolution enforces. // Thymeleaf is the reference HTML renderer, added as the engine only — not the Spring // starter, which would drag a view resolver and a servlet integration onto an outbound // adapter that renders strings and never serves a request. @@ -54,35 +50,44 @@ dependencies { exclude group: 'com.fasterxml.jackson.dataformat', module: 'jackson-dataformat-yaml' } - - testImplementation 'io.projectreactor:reactor-test' } -// The exclusion above, stated as something the build verifies rather than something a comment -// asserts. verifyDependencyPolicy resolves runtimeClasspath and fails if the coordinate is present. -dependencyPolicy { - absent 'com.fasterxml.jackson.dataformat:jackson-dataformat-yaml', - 'schemas arrive as JSON strings; a second YAML parser is surface for a format ' + - 'this leaf never reads' - absent 'tools.jackson.dataformat:jackson-dataformat-yaml', - 'the Jackson 3 coordinate of the same parser, excluded for the same reason' +// The exclusion above as something resolution enforces: this rule fails the build the moment any +// dependency brings the YAML dataformat back in. (A `rejectAll()` constraint would not: Spring's +// dependency management overrides the version it rejects.) +configurations.configureEach { + resolutionStrategy.componentSelection.all { selection -> + if (selection.candidate.module == 'jackson-dataformat-yaml') { + selection.reject('schemas arrive as JSON strings; a YAML parser is surface for a format this leaf never reads') + } + } } -// The three notification gates run with the leaf they are about. -// -// All three existed and passed for months while nothing ran them, and the cost was measurable the -// first time they were: twenty-nine environment variables bound in application.yml were absent from -// the configuration reference — the whole SMTP relay and all eight key-material purposes — and -// thirteen public types had entered the notification API surface without the reviewed baseline -// recording any of them. -// -// They ran on all 62 leaves once, which reached them 62 times and told the developer who changed -// :domain-core about the notification surface. An API surface baseline and a configuration reference -// for one adapter are that adapter's contract, so they belong to the command a developer runs after -// changing it — and the wiring is declared here, in that leaf, rather than reached into from the -// root. `.github/workflows/notification-platform.yml` also invokes all three by name. -tasks.named('check') { - dependsOn rootProject.tasks.named('verifyNotificationApiSurface') - dependsOn rootProject.tasks.named('verifyNotificationConfiguration') - dependsOn rootProject.tasks.named('verifyNotificationEvidence') +// The notification platform's public type surface (application-notification and this leaf) is a +// reviewed baseline; growth needs -PraiseNotificationApiSurfaceCeiling as well as the approval. +apiSurface { + label = 'Notification' + baseline = rootProject.file('../docs/notification/api-surface-snapshot.txt') + additionalSourceRoots = ['../../../application-notification/src/main/java'] + description = 'NTF-022 — public type surface of the notification platform (application-notification + adapter:outbound:notification).' + rationale = [ + 'Every top-level public type under the platform packages. Growth is a reviewed change.', + ] +} + +// NotificationEvidenceVerifierTest holds docs/notification/evidence-manifest.json, the support +// matrix it grades and the evidence files it names to each other. Those files are inputs of `test`, +// or Gradle would call it up to date after an edit to any of them. +def repositoryRoot = rootProject.projectDir.parentFile +tasks.named('test') { + inputs.files( + new File(repositoryRoot, 'docs/notification/evidence-manifest.json'), + new File(repositoryRoot, 'docs/notification/support-matrix.md'), + rootProject.file('adapter/outbound/persistence-jpa/build.gradle')) + .withPathSensitivity(PathSensitivity.RELATIVE) + inputs.files(fileTree(rootProject.projectDir) { + include 'adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/**' + include 'adapter/outbound/notification/src/test/java/**' + include 'application-notification/src/test/java/**' + }).withPathSensitivity(PathSensitivity.RELATIVE) } diff --git a/src/adapter/outbound/notification/gradle.lockfile b/src/adapter/outbound/notification/gradle.lockfile index e6935411..3bcf61c2 100644 --- a/src/adapter/outbound/notification/gradle.lockfile +++ b/src/adapter/outbound/notification/gradle.lockfile @@ -45,8 +45,6 @@ io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,testAnnotatio io.micrometer:micrometer-commons:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath io.micrometer:micrometer-core:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath io.micrometer:micrometer-observation:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.projectreactor:reactor-core:3.8.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.projectreactor:reactor-test:3.8.7=testCompileClasspath,testRuntimeClasspath jakarta.activation:jakarta.activation-api:2.1.4=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath jakarta.annotation:jakarta.annotation-api:3.0.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath jakarta.mail:jakarta.mail-api:2.1.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath @@ -118,7 +116,6 @@ org.ow2.asm:asm-util:9.10.1=spotbugs org.ow2.asm:asm:9.10.1=spotbugs org.ow2.asm:asm:9.7.1=testCompileClasspath,testRuntimeClasspath org.pcollections:pcollections:4.0.1=annotationProcessor,testAnnotationProcessor -org.reactivestreams:reactive-streams:1.0.4=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.reflections:reflections:0.10.2=checkstyle org.skyscreamer:jsonassert:1.5.3=testCompileClasspath,testRuntimeClasspath org.slf4j:jul-to-slf4j:2.0.18=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath @@ -160,7 +157,7 @@ org.springframework:spring-context:7.0.9=compileClasspath,runtimeClasspath,testC org.springframework:spring-core:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework:spring-expression:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework:spring-test:7.0.9=testCompileClasspath,testRuntimeClasspath -org.springframework:spring-web:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-web:7.0.9=testCompileClasspath,testRuntimeClasspath org.springframework:spring-webmvc:7.0.9=testCompileClasspath,testRuntimeClasspath org.thymeleaf:thymeleaf:3.1.5.RELEASE=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.unbescape:unbescape:1.1.6.RELEASE=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationActivationEnvironmentPostProcessor.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationActivationEnvironmentPostProcessor.java new file mode 100644 index 00000000..c53e1541 --- /dev/null +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationActivationEnvironmentPostProcessor.java @@ -0,0 +1,68 @@ +package dev.caskeleton.adapter.outbound.notification.platform.autoconfigure; + +import dev.caskeleton.adapter.outbound.support.startup.StartupOrder; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import org.springframework.boot.EnvironmentPostProcessor; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.AutoConfiguration; +import org.springframework.boot.context.annotation.ImportCandidates; +import org.springframework.boot.context.properties.bind.Bindable; +import org.springframework.boot.context.properties.bind.Binder; +import org.springframework.core.Ordered; +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.core.env.MapPropertySource; + +/** + * Makes an explicit {@code ca-skeleton.notification.platform.enabled=false} complete. + * + *

The platform's own configurations stand down on the switch, but Spring Boot's mail + * auto-configurations arrive with this module's {@code spring-boot-starter-mail} and read no switch + * of ours: given {@code spring.mail.host} they still build a {@code JavaMailSender}, test the relay + * at startup and add a {@code mail} health contributor. So an explicit off appends them to {@code + * spring.autoconfigure.exclude}, after whatever the deployment already excludes. The names are read + * from Boot's own registration file by package, as the JPA, Mongo and GraphQL modules do, so a Boot + * release that adds one is covered without an edit. + * + *

On — the default while the module is present — changes nothing. + */ +class NotificationActivationEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered { + + static final String SWITCH = "ca-skeleton.notification.platform.enabled"; + + static final String EXCLUDE = "spring.autoconfigure.exclude"; + + static final String BOOT_MAIL_PACKAGE = "org.springframework.boot.mail.autoconfigure."; + + @Override + public void postProcessEnvironment( + ConfigurableEnvironment environment, SpringApplication application) { + if ("true".equalsIgnoreCase(environment.getProperty(SWITCH, "true"))) { + return; + } + List excluded = + new ArrayList<>( + Binder.get(environment).bind(EXCLUDE, Bindable.listOf(String.class)).orElse(List.of())); + for (String candidate : + ImportCandidates.load( + AutoConfiguration.class, + NotificationActivationEnvironmentPostProcessor.class.getClassLoader())) { + if (candidate.startsWith(BOOT_MAIL_PACKAGE)) { + excluded.add(candidate); + } + } + environment + .getPropertySources() + .addFirst( + new MapPropertySource( + "notification-platform-off", Map.of(EXCLUDE, String.join(",", excluded)))); + } + + @Override + public int getOrder() { + // After the module defaults, which carry the switch, and after the database processor, which + // may already have appended to the exclusion list this one extends. + return StartupOrder.READINESS_DATABASE + 1; + } +} diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationCallbackProviderConfig.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationCallbackProviderConfig.java index 2a44e27f..8252efa5 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationCallbackProviderConfig.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationCallbackProviderConfig.java @@ -23,11 +23,21 @@ import org.springframework.context.annotation.Configuration; @ConditionalOnProperty( prefix = "ca-skeleton.notification.platform", name = "enabled", - havingValue = "true") + havingValue = "true", + matchIfMissing = true) class NotificationCallbackProviderConfig { + /** + * How many signing certificates are kept. SNS signs with one certificate per region and rotates + * rarely, so a full cache means something is cycling URLs rather than a working set is large. + */ + static final int MAX_CACHED_SNS_CERTIFICATES = 64; + /** * Default SNS certificate source, using the same bounded, no-redirect HTTP gateway as providers. + * + *

The fetch happens outside the map. It used to run inside {@code computeIfAbsent}, which + * holds a lock across the network call, and the cache had no bound on URLs a caller supplies. */ @Bean @ConditionalOnMissingBean @@ -37,37 +47,53 @@ class NotificationCallbackProviderConfig { @Override public PublicKey publicKeyFor(URI certificateUrl) { - return cache.computeIfAbsent( - certificateUrl, - uri -> { - var response = - gateway.exchange( - new NotificationHttpRequest( - "GET", uri, Map.of(), new byte[0], Duration.ofSeconds(3))); - if (!response.isSuccessful()) { - throw new IllegalStateException( - "SNS signing certificate fetch failed with HTTP " + response.statusCode()); - } - try { - X509Certificate certificate = - (X509Certificate) - CertificateFactory.getInstance("X.509") - .generateCertificate(new ByteArrayInputStream(response.body())); - return certificate.getPublicKey(); - } catch (CertificateException malformed) { - throw new IllegalArgumentException( - "SNS signing certificate is not valid X.509", malformed); - } - }); + PublicKey cached = cache.get(certificateUrl); + if (cached != null) { + return cached; + } + PublicKey fetched = fetch(certificateUrl); + if (cache.size() >= MAX_CACHED_SNS_CERTIFICATES) { + // ponytail: drop-all on overflow rather than LRU; a real working set is a handful of + // regions, so this only ever fires for a caller cycling URLs. + cache.clear(); + } + PublicKey raced = cache.putIfAbsent(certificateUrl, fetched); + return raced == null ? fetched : raced; + } + + private PublicKey fetch(URI uri) { + var response = + gateway.exchange( + new NotificationHttpRequest( + "GET", uri, Map.of(), new byte[0], Duration.ofSeconds(3))); + if (!response.isSuccessful()) { + throw new IllegalStateException( + "SNS signing certificate fetch failed with HTTP " + response.statusCode()); + } + try { + X509Certificate certificate = + (X509Certificate) + CertificateFactory.getInstance("X.509") + .generateCertificate(new ByteArrayInputStream(response.body())); + return certificate.getPublicKey(); + } catch (CertificateException malformed) { + throw new IllegalArgumentException( + "SNS signing certificate is not valid X.509", malformed); + } } }; } - /** SES callback contribution, independently available to an INGEST_ONLY deployment. */ + /** + * SES callback contribution, independently available to an INGEST_ONLY deployment. + * + *

{@code callbacks.replay-skew} bounds how old a signed SNS message may be: a signature never + * expires, so without it a captured message could be replayed indefinitely. + */ @Bean @ConditionalOnMissingBean(name = "sesProviderCallbackAssembler") public ProviderCallbackAssembler sesProviderCallbackAssembler( - SnsCertificateProvider certificates) { - return new SesProviderCallbackAssembler(certificates); + SnsCertificateProvider certificates, NotificationPlatformSettings settings) { + return new SesProviderCallbackAssembler(certificates, settings.callbacks().replaySkew()); } } diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformAutoConfiguration.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformAutoConfiguration.java index a32993a8..57921507 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformAutoConfiguration.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformAutoConfiguration.java @@ -13,14 +13,16 @@ import org.springframework.context.annotation.Import; * Boot entry point for the Notification capability. * *

The reusable Notification leaf owns its Spring composition. The application composition root - * only decides whether this artifact is present; runtime activation stays on the existing {@code - * ca-skeleton.notification.platform.enabled} switch. + * only decides whether this artifact is present. Present means on; {@code + * ca-skeleton.notification.platform.enabled=false} turns it off, and {@link + * NotificationActivationEnvironmentPostProcessor} takes Boot's mail auto-configuration off with it. */ @AutoConfiguration @ConditionalOnProperty( prefix = "ca-skeleton.notification.platform", name = "enabled", - havingValue = "true") + havingValue = "true", + matchIfMissing = true) @EnableConfigurationProperties(NotificationRoutesSettings.class) @Import({ NotificationPlatformCoreConfig.class, diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformCodecConfig.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformCodecConfig.java index 9d506220..7a2cc17e 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformCodecConfig.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformCodecConfig.java @@ -39,7 +39,8 @@ import org.springframework.context.annotation.Configuration; @ConditionalOnProperty( prefix = "ca-skeleton.notification.platform", name = "enabled", - havingValue = "true") + havingValue = "true", + matchIfMissing = true) class NotificationPlatformCodecConfig { /** Time-ordered identifiers for every notification row. */ diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformCoreConfig.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformCoreConfig.java index 0324f430..d9e9efff 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformCoreConfig.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformCoreConfig.java @@ -32,7 +32,8 @@ import org.springframework.context.annotation.Configuration; @ConditionalOnProperty( prefix = "ca-skeleton.notification.platform", name = "enabled", - havingValue = "true") + havingValue = "true", + matchIfMissing = true) class NotificationPlatformCoreConfig { /** Canonical variables codec. */ @@ -82,7 +83,7 @@ class NotificationPlatformCoreConfig { * dependency several layers away, in the deployment that first assembled the platform for real. * *

Nothing is lost by dropping it. Both configurations are reached only through the same root - * under the same master switch, so the provider exists whenever this does — and a deployment + * under the same capability switch, so the provider exists whenever this does — and a deployment * missing key material already fails at the provider itself, at startup, naming the purpose whose * key is missing. That is a better failure than a bean quietly not being created. */ diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformDispatchConfig.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformDispatchConfig.java index fb9ad764..50b409b6 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformDispatchConfig.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformDispatchConfig.java @@ -14,14 +14,9 @@ import dev.caskeleton.application.notification.platform.dispatch.DispatchOutcome import dev.caskeleton.application.notification.platform.dispatch.DispatchPipeline; import dev.caskeleton.application.notification.platform.dispatch.NotificationIdGeneratorPort; import dev.caskeleton.application.notification.platform.dispatch.RecipientDeliveryStorePort; -import dev.caskeleton.application.notification.platform.dispatch.ReconciliationGatewayPort; import dev.caskeleton.application.notification.platform.dispatch.ReconciliationJobStorePort; -import dev.caskeleton.application.notification.platform.dispatch.ReconciliationService; -import dev.caskeleton.application.notification.platform.dispatch.SyntheticEventFingerprint; -import dev.caskeleton.application.notification.platform.observation.NotificationAuditPort; import dev.caskeleton.application.notification.platform.observation.NotificationMetricsPort; import dev.caskeleton.application.notification.platform.policy.NotificationEligibilityPolicy; -import java.time.Clock; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; @@ -42,7 +37,8 @@ import org.springframework.context.annotation.Configuration; @ConditionalOnProperty( prefix = "ca-skeleton.notification.platform", name = "enabled", - havingValue = "true") + havingValue = "true", + matchIfMissing = true) class NotificationPlatformDispatchConfig { /** * The operator plane, and the narrow port it reaches runtimes through. @@ -130,28 +126,4 @@ class NotificationPlatformDispatchConfig { settings.dispatch().maxQueueAge(), settings.dispatch().shutdownGrace()); } - - /** Provider status correction. */ - @Bean - public ReconciliationService reconciliationService( - DeliveryAttemptStorePort attempts, - RecipientDeliveryStorePort recipients, - ReconciliationGatewayPort gateway, - ProviderEventLedger ledger, - ProviderEventProjectionService projection, - NotificationAuditPort audit, - NotificationMetricsPort metrics, - SyntheticEventFingerprint syntheticEventFingerprints, - Clock clock) { - return new ReconciliationService( - attempts, - recipients, - gateway, - ledger, - projection, - audit, - metrics, - syntheticEventFingerprints, - clock); - } } diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformObservabilityConfig.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformObservabilityConfig.java index 1fc59ecc..ee2fb263 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformObservabilityConfig.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformObservabilityConfig.java @@ -35,7 +35,8 @@ import org.springframework.context.annotation.Configuration; @ConditionalOnProperty( prefix = "ca-skeleton.notification.platform", name = "enabled", - havingValue = "true") + havingValue = "true", + matchIfMissing = true) class NotificationPlatformObservabilityConfig { /** Metric tag guard. */ diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformPolicyConfig.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformPolicyConfig.java index 730baec4..8fbe271d 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformPolicyConfig.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformPolicyConfig.java @@ -43,7 +43,8 @@ import org.springframework.context.annotation.Configuration; @ConditionalOnProperty( prefix = "ca-skeleton.notification.platform", name = "enabled", - havingValue = "true") + havingValue = "true", + matchIfMissing = true) class NotificationPlatformPolicyConfig { /** diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformProviderConfig.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformProviderConfig.java index ee6fae7d..83d384ab 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformProviderConfig.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformProviderConfig.java @@ -41,7 +41,8 @@ import org.springframework.context.annotation.Configuration; @ConditionalOnProperty( prefix = "ca-skeleton.notification.platform", name = "enabled", - havingValue = "true") + havingValue = "true", + matchIfMissing = true) class NotificationPlatformProviderConfig { /** diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformRegistriesConfig.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformRegistriesConfig.java index ba9fe13f..f46387fb 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformRegistriesConfig.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformRegistriesConfig.java @@ -27,7 +27,8 @@ import org.springframework.context.annotation.Configuration; @ConditionalOnProperty( prefix = "ca-skeleton.notification.platform", name = "enabled", - havingValue = "true") + havingValue = "true", + matchIfMissing = true) class NotificationPlatformRegistriesConfig { /** Projector lookup by provider family. */ diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformRuntimeConfig.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformRuntimeConfig.java index 69896a30..07d60557 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformRuntimeConfig.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformRuntimeConfig.java @@ -24,7 +24,8 @@ import org.springframework.context.annotation.Import; @ConditionalOnProperty( prefix = "ca-skeleton.notification.platform", name = "enabled", - havingValue = "true") + havingValue = "true", + matchIfMissing = true) @Import({ NotificationPlatformCodecConfig.class, NotificationPlatformObservabilityConfig.class, diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformSecretsConfig.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformSecretsConfig.java index 5aecbcbe..a07a20f4 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformSecretsConfig.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformSecretsConfig.java @@ -55,7 +55,8 @@ import org.springframework.context.annotation.Configuration; @ConditionalOnProperty( prefix = "ca-skeleton.notification.platform", name = "enabled", - havingValue = "true") + havingValue = "true", + matchIfMissing = true) @EnableConfigurationProperties(NotificationPlatformSecretsConfig.NotificationSecretsSettings.class) class NotificationPlatformSecretsConfig { diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformSettings.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformSettings.java index e0614b7b..c5af951e 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformSettings.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformSettings.java @@ -2,6 +2,7 @@ package dev.caskeleton.adapter.outbound.notification.platform.autoconfigure; import java.net.URI; import java.time.Duration; +import java.util.List; import java.util.Map; import java.util.Objects; import org.springframework.boot.context.properties.ConfigurationProperties; @@ -36,7 +37,8 @@ public record NotificationPlatformSettings( servingThresholds = servingThresholds == null ? ServingThresholds.defaults() : servingThresholds; providers = providers == null ? Map.of() : Map.copyOf(providers); - providers.forEach((id, provider) -> provider.validate(id)); + boolean callbacksEnabled = callbacks.enabled(); + providers.forEach((id, provider) -> provider.validate(id, callbacksEnabled)); } /** Source-compatible constructor for callers that rely on the original settings shape. */ @@ -256,8 +258,14 @@ public record NotificationPlatformSettings( null); } - /** Fail the boot when a profile cannot possibly work. */ - public void validate(String profileId) { + /** + * Fail the boot when a profile cannot possibly work. + * + * @param profileId the profile id + * @param callbacksEnabled whether provider callbacks are accepted, which some families need + * extra settings for + */ + public void validate(String profileId, boolean callbacksEnabled) { Objects.requireNonNull(profileId, "profileId"); if (!enabled) { return; @@ -292,7 +300,7 @@ public record NotificationPlatformSettings( "Twilio profiles require a callback signing secret reference"); case "SES" -> { require(ses != null, profileId, "SES profiles require a ses settings block"); - ses.validate(profileId); + ses.validate(profileId, callbacksEnabled); } default -> { // Providers without extra requirements are already covered by the common checks. @@ -310,15 +318,24 @@ public record NotificationPlatformSettings( /** * SES-specific transport identity. Secret access-key material stays behind the secret provider. + * + *

{@code allowedTopicArns} lists the SNS topics whose event callbacks this profile accepts. A + * valid SNS signature only proves AWS sent the message, and anyone can own a topic, so with + * callbacks on the list is required: an empty one would accept every AWS-signed message. */ public record Ses( URI endpoint, String region, String senderIdentity, String accessKeyId, - String configurationSet) { + String configurationSet, + List allowedTopicArns) { - private void validate(String profileId) { + public Ses { + allowedTopicArns = allowedTopicArns == null ? List.of() : List.copyOf(allowedTopicArns); + } + + private void validate(String profileId, boolean callbacksEnabled) { Provider.require(endpoint != null, profileId, "SES endpoint is required"); Provider.require(region != null && !region.isBlank(), profileId, "SES region is required"); Provider.require( @@ -329,6 +346,13 @@ public record NotificationPlatformSettings( accessKeyId != null && !accessKeyId.isBlank(), profileId, "SES access-key-id is required"); + Provider.require( + !callbacksEnabled + || (!allowedTopicArns.isEmpty() + && allowedTopicArns.stream().noneMatch(String::isBlank)), + profileId, + "SES allowed-topic-arns is required when callbacks are enabled: list the SNS topic ARNs" + + " this profile subscribes to, since any other AWS-signed message would be accepted"); } } } diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformWorkerConfig.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformWorkerConfig.java index b27a221d..2de2169d 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformWorkerConfig.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformWorkerConfig.java @@ -1,6 +1,5 @@ package dev.caskeleton.adapter.outbound.notification.platform.autoconfigure; -import dev.caskeleton.adapter.outbound.notification.platform.dispatch.LeaseRecoveryService; import dev.caskeleton.adapter.outbound.notification.platform.dispatch.NotificationBackgroundWorkers; import dev.caskeleton.adapter.outbound.notification.platform.dispatch.NotificationDispatchProperties; import dev.caskeleton.adapter.outbound.notification.platform.dispatch.NotificationSchedulerWorker; @@ -8,9 +7,8 @@ import dev.caskeleton.adapter.outbound.notification.platform.dispatch.ProviderEv import dev.caskeleton.adapter.outbound.notification.platform.dispatch.ReconciliationJobWorker; import dev.caskeleton.application.notification.platform.callback.ProviderEventLedger; import dev.caskeleton.application.notification.platform.callback.ProviderEventProjectionService; -import dev.caskeleton.application.notification.platform.dispatch.DeliveryAttemptStorePort; +import dev.caskeleton.application.notification.platform.dispatch.LeaseRecoveryService; import dev.caskeleton.application.notification.platform.dispatch.NotificationDispatchService; -import dev.caskeleton.application.notification.platform.dispatch.RecipientDeliveryStorePort; import dev.caskeleton.application.notification.platform.dispatch.RecipientLeaseStorePort; import dev.caskeleton.application.notification.platform.dispatch.ReconciliationJobStorePort; import dev.caskeleton.application.notification.platform.dispatch.ReconciliationService; @@ -37,7 +35,8 @@ import org.springframework.context.annotation.Configuration; @ConditionalOnProperty( prefix = "ca-skeleton.notification.platform", name = "enabled", - havingValue = "true") + havingValue = "true", + matchIfMissing = true) class NotificationPlatformWorkerConfig { /* @@ -75,41 +74,6 @@ class NotificationPlatformWorkerConfig { properties.maxAdditionalAttempts() + 1); } - /** - * Recovers deliveries a dead worker left in flight. - * - *

The class existed with no bean, no schedule and no caller. The dispatch scheduler's error - * path already assumed it: it leaves a lease to expire rather than releasing it optimistically, - * on the grounds that recovery will decide what happened. With nothing recovering, that - * deliberate choice became a permanent leak. - * - * @param leases the lease store - * @param attempts the attempt store - * @param deliveries the delivery store - * @param reconciliation reconciles an attempt whose outcome is unknown - * @param clock the clock - * @param properties the dispatch bounds - * @return the recovery service - */ - @Bean - @ConditionalOnMissingBean - public LeaseRecoveryService notificationLeaseRecoveryService( - RecipientLeaseStorePort leases, - DeliveryAttemptStorePort attempts, - RecipientDeliveryStorePort deliveries, - ReconciliationService reconciliation, - java.time.Clock clock, - NotificationDispatchProperties properties) { - return new LeaseRecoveryService( - leases, - attempts, - deliveries, - reconciliation::reconcile, - clock, - properties.leaseDuration(), - properties.claimBatchSize()); - } - /** * Projects provider events that were stored and never applied. * @@ -131,11 +95,11 @@ class NotificationPlatformWorkerConfig { * Everything that starts a thread, and therefore everything {@code INGEST_ONLY} must not have. * *

A nested configuration rather than a condition on each bean. Both beans below used to sit on - * the parent, which carried the master switch alone, and both call {@code start()} in the factory - * method — so a deployment in {@code INGEST_ONLY}, the mode whose whole purpose is to accept and - * store without delivering, started the dispatch scheduler, the lease recovery pass, the - * provider-event replay worker and the reconciliation job. It accepted requests and then tried to - * deliver them, which is the mode not existing. + * the parent, which carried the capability switch alone, and both call {@code start()} in the + * factory method — so a deployment in {@code INGEST_ONLY}, the mode whose whole purpose is to + * accept and store without delivering, started the dispatch scheduler, the lease recovery pass, + * the provider-event replay worker and the reconciliation job. It accepted requests and then + * tried to deliver them, which is the mode not existing. * *

Structural because a per-bean condition is one a future bean can forget, and the cost of * forgetting here is not a stray bean — it is a process delivering notifications that an operator diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationSmtpProviderConfig.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationSmtpProviderConfig.java index 1d29362d..1addd45e 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationSmtpProviderConfig.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationSmtpProviderConfig.java @@ -51,7 +51,7 @@ import org.springframework.mail.javamail.JavaMailSenderImpl; * envelope sender and the dispatch executor concurrency. */ @Configuration(proxyBeanMethods = false) -// The master switch is not repeated here. This configuration is reachable only through +// The capability switch is not repeated here. This configuration is reachable only through // NotificationPlatformRuntimeConfig, which the root imports under that switch, so "off" stays a // structural fact rather than a condition each new configuration has to remember. What this one // owns diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/SesProviderCallbackAssembler.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/SesProviderCallbackAssembler.java index c7115159..25cb4acf 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/SesProviderCallbackAssembler.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/SesProviderCallbackAssembler.java @@ -5,19 +5,21 @@ import dev.caskeleton.adapter.outbound.notification.platform.provider.ses.SesCal import dev.caskeleton.adapter.outbound.notification.platform.provider.ses.SesEventNormalizer; import dev.caskeleton.adapter.outbound.notification.platform.provider.ses.SnsCertificateProvider; import dev.caskeleton.adapter.outbound.notification.platform.provider.ses.SnsSignatureVerifier; +import java.time.Duration; import java.util.Objects; +import java.util.Set; /** Builds one SES/SNS callback verifier per configured SES profile. */ final class SesProviderCallbackAssembler implements ProviderCallbackAssembler { private final SnsSignatureVerifier verifier; private final SesEventNormalizer normalizer; + private final Duration replayWindow; - SesProviderCallbackAssembler(SnsCertificateProvider certificates) { - this.verifier = - new SnsSignatureVerifier( - Objects.requireNonNull(certificates, "certificates"), "amazonaws.com"); + SesProviderCallbackAssembler(SnsCertificateProvider certificates, Duration replayWindow) { + this.verifier = new SnsSignatureVerifier(Objects.requireNonNull(certificates, "certificates")); this.normalizer = new SesEventNormalizer(); + this.replayWindow = Objects.requireNonNull(replayWindow, "replayWindow"); } @Override @@ -30,6 +32,9 @@ final class SesProviderCallbackAssembler implements ProviderCallbackAssembler { String profileId, NotificationPlatformSettings.Provider profile) { Objects.requireNonNull(profileId, "profileId"); Objects.requireNonNull(profile, "profile"); - return new SesCallbackAdapter(verifier, normalizer); + // An enabled SES profile always carries its ses block, and with callbacks on its topic list is + // non-empty; both are enforced when the settings bind. + return new SesCallbackAdapter( + verifier, normalizer, Set.copyOf(profile.ses().allowedTopicArns()), replayWindow); } } diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/NotificationBackgroundWorkers.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/NotificationBackgroundWorkers.java index 3187117e..b4585d25 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/NotificationBackgroundWorkers.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/NotificationBackgroundWorkers.java @@ -1,5 +1,6 @@ package dev.caskeleton.adapter.outbound.notification.platform.dispatch; +import dev.caskeleton.application.notification.platform.dispatch.LeaseRecoveryService; import java.time.Duration; import java.util.Objects; import java.util.concurrent.Executors; diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/ProviderEventReplayWorker.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/ProviderEventReplayWorker.java index 050f8ac3..50292159 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/ProviderEventReplayWorker.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/ProviderEventReplayWorker.java @@ -69,7 +69,9 @@ public final class ProviderEventReplayWorker { projected++; } } catch (RuntimeException failure) { - ledger.markFailed(event.id(), failure.getClass().getSimpleName()); + // Through the projection service, which opens the transaction: this worker has none, and + // marking the event is a modifying query that throws without one. + projection.markFailed(event, failure.getClass().getSimpleName()); } } return projected; diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesCallbackAdapter.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesCallbackAdapter.java index d4132c66..1124d0fc 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesCallbackAdapter.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesCallbackAdapter.java @@ -8,10 +8,14 @@ import dev.caskeleton.adapter.outbound.notification.platform.template.Notificati import dev.caskeleton.application.notification.platform.api.NormalizedProviderEvent; import dev.caskeleton.application.notification.platform.api.ProviderId; import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.time.Instant; +import java.time.format.DateTimeParseException; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Set; import tools.jackson.databind.JsonNode; /** @@ -20,6 +24,11 @@ import tools.jackson.databind.JsonNode; *

A subscription confirmation is verified like any other message but produces no provider event: * confirming a topic is an operational act, and letting it into the ledger would mean an unverified * caller could add rows just by claiming to be SNS. + * + *

A valid SNS signature proves AWS sent the message, and nothing more: anyone can own a topic + * and have AWS sign for it, and a signed message stays signed forever. So the topic must be one + * this profile subscribed to, and the message must be recent, before the signature is even checked + * — which also keeps an unwanted message from triggering a certificate fetch. */ public final class SesCallbackAdapter implements ProviderCallbackAdapter { @@ -27,10 +36,26 @@ public final class SesCallbackAdapter implements ProviderCallbackAdapter { private final SnsSignatureVerifier verifier; private final SesEventNormalizer normalizer; + private final Set allowedTopicArns; + private final Duration replayWindow; - public SesCallbackAdapter(SnsSignatureVerifier verifier, SesEventNormalizer normalizer) { + /** + * Creates the adapter for one SES profile. + * + * @param verifier the SNS signature check + * @param normalizer turns an SES event into provider events + * @param allowedTopicArns the topics this profile subscribed to; any other is rejected + * @param replayWindow how far the message timestamp may be from receipt, either way + */ + public SesCallbackAdapter( + SnsSignatureVerifier verifier, + SesEventNormalizer normalizer, + Set allowedTopicArns, + Duration replayWindow) { this.verifier = Objects.requireNonNull(verifier, "verifier"); this.normalizer = Objects.requireNonNull(normalizer, "normalizer"); + this.allowedTopicArns = Set.copyOf(allowedTopicArns); + this.replayWindow = Objects.requireNonNull(replayWindow, "replayWindow"); } @Override @@ -47,6 +72,13 @@ public final class SesCallbackAdapter implements ProviderCallbackAdapter { } catch (RuntimeException unparseable) { return CallbackVerificationResult.invalid("SNS_ENVELOPE_UNPARSEABLE"); } + String topicArn = envelope.get("TopicArn"); + if (topicArn == null || !allowedTopicArns.contains(topicArn)) { + return CallbackVerificationResult.invalid("SNS_TOPIC_NOT_ALLOWED"); + } + if (!withinReplayWindow(envelope.get("Timestamp"), request.receivedAt())) { + return CallbackVerificationResult.invalid("SNS_TIMESTAMP_OUT_OF_WINDOW"); + } if (!verifier.isValid(envelope)) { return CallbackVerificationResult.invalid("SNS_SIGNATURE_MISMATCH"); } @@ -66,6 +98,18 @@ public final class SesCallbackAdapter implements ProviderCallbackAdapter { return normalizer.normalize(message); } + private boolean withinReplayWindow(String timestamp, Instant receivedAt) { + if (timestamp == null) { + return false; + } + try { + return Duration.between(Instant.parse(timestamp), receivedAt).abs().compareTo(replayWindow) + <= 0; + } catch (DateTimeParseException malformed) { + return false; + } + } + private static Map flatten(String body) { JsonNode root = NotificationJsonMapper.mapper().readTree(body); Map envelope = new LinkedHashMap<>(); diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SnsSignatureVerifier.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SnsSignatureVerifier.java index a1fa6e10..a5d1dadc 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SnsSignatureVerifier.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SnsSignatureVerifier.java @@ -12,15 +12,20 @@ import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Set; +import java.util.regex.Pattern; /** * SNS message signature verification. * - *

Two checks, and both are load-bearing. The signing certificate URL is constrained to an - * Amazon-owned host before it is fetched, because a message that names its own certificate host is + *

Two checks, and both are load-bearing. The signing certificate URL is constrained to an SNS + * regional host before it is fetched, because a message that names its own certificate host is * otherwise self-signed by whoever sent it. The canonical string is then rebuilt from the fields * SNS specifies, in its order, because signing a re-serialised body would verify our own JSON * writer rather than the message. + * + *

A valid signature proves only that AWS sent the message, not that it came from a topic this + * deployment subscribed to or that it is recent. Those checks belong to the caller that knows the + * profile ({@link SesCallbackAdapter}). */ public final class SnsSignatureVerifier { @@ -29,16 +34,21 @@ public final class SnsSignatureVerifier { private static final Set SUBSCRIPTION_FIELDS = Set.of("Message", "MessageId", "SubscribeURL", "Timestamp", "Token", "TopicArn", "Type"); - private final SnsCertificateProvider certificates; - private final String certificateHostSuffix; + /** + * The only hosts SNS serves signing certificates from: {@code sns..amazonaws.com}, plus + * the China partition's {@code .com.cn}. Any other {@code *.amazonaws.com} host is not SNS — an + * S3 bucket is {@code .s3.amazonaws.com}, anyone can create one, and it serves any object + * name, so a suffix rule let an attacker host the certificate their forged envelope verifies + * against. The middle label must be region-shaped ({@code us-east-1}, {@code us-gov-west-1}), not + * merely any label: {@code sns.s3.amazonaws.com} is the S3 bucket named {@code sns}. + */ + private static final Pattern SNS_CERTIFICATE_HOST = + Pattern.compile("sns\\.[a-z]{2}(-[a-z]+)+-[0-9]+\\.amazonaws\\.com(\\.cn)?"); - public SnsSignatureVerifier(SnsCertificateProvider certificates, String certificateHostSuffix) { + private final SnsCertificateProvider certificates; + + public SnsSignatureVerifier(SnsCertificateProvider certificates) { this.certificates = Objects.requireNonNull(certificates, "certificates"); - this.certificateHostSuffix = - Objects.requireNonNull(certificateHostSuffix, "certificateHostSuffix"); - if (certificateHostSuffix.isBlank()) { - throw new IllegalArgumentException("certificateHostSuffix"); - } } /** Verify one SNS envelope. */ @@ -76,10 +86,10 @@ public final class SnsSignatureVerifier { * Whether the certificate URL is one this verifier will fetch. * *

A suffix match is not a host check. {@code evilamazonaws.com} ends with {@code - * amazonaws.com}, so the previous version would fetch a signing certificate from an - * attacker-owned domain and then verify the envelope against it — which makes the whole signature - * check decorative. The suffix must begin at a label boundary, and the rest of the URL has to - * look like what SNS actually publishes. + * amazonaws.com}, and {@code bucket.s3.amazonaws.com} is a label-aligned subdomain anyone can + * rent — either way the envelope would be verified against a certificate the attacker served, + * which makes the whole signature check decorative. The host must be an SNS regional endpoint, + * and the rest of the URL has to look like what SNS actually publishes. */ public boolean isTrustedCertificateUrl(String certificateUrl) { try { @@ -96,11 +106,7 @@ public final class SnsSignatureVerifier { return false; } String host = uri.getHost() == null ? "" : uri.getHost().toLowerCase(Locale.ROOT); - // At a label boundary, or the suffix itself. "evilamazonaws.com".endsWith("amazonaws.com") - // is true; "evil.amazonaws.com" is the only shape that should pass. - boolean onTheSuffix = - host.equals(certificateHostSuffix) || host.endsWith("." + certificateHostSuffix); - if (!onTheSuffix) { + if (!SNS_CERTIFICATE_HOST.matcher(host).matches()) { return false; } String path = uri.getPath() == null ? "" : uri.getPath(); diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/reactor/ReactiveNotificationOrchestrator.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/reactor/ReactiveNotificationOrchestrator.java deleted file mode 100644 index bc130299..00000000 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/reactor/ReactiveNotificationOrchestrator.java +++ /dev/null @@ -1,27 +0,0 @@ -package dev.caskeleton.adapter.outbound.notification.platform.reactor; - -import dev.caskeleton.application.notification.platform.api.NotificationId; -import dev.caskeleton.application.notification.platform.api.NotificationPlan; -import dev.caskeleton.application.notification.platform.api.NotificationReceipt; -import dev.caskeleton.application.notification.platform.api.NotificationSnapshot; -import java.time.Instant; -import reactor.core.publisher.Mono; - -/** - * Optional Reactor facade. - * - *

It exists as a separate type so that Reactor stays out of the core contract: the platform's - * asynchronous type is {@code CompletionStage}, and an application that does not use Reactor never - * sees it. - */ -public interface ReactiveNotificationOrchestrator { - - /** Accept a plan. */ - Mono submit(NotificationPlan plan); - - /** Accept a scheduled plan. */ - Mono schedule(NotificationPlan plan, Instant scheduleAt); - - /** Read the projection of a notification. */ - Mono get(NotificationId notificationId); -} diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/reactor/ReactorContextBridge.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/reactor/ReactorContextBridge.java deleted file mode 100644 index 4be68bc2..00000000 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/reactor/ReactorContextBridge.java +++ /dev/null @@ -1,41 +0,0 @@ -package dev.caskeleton.adapter.outbound.notification.platform.reactor; - -import java.util.Objects; -import java.util.Optional; -import java.util.function.Supplier; -import reactor.util.context.ContextView; - -/** - * Carries selected Reactor context values across the blocking boundary. - * - *

Only the correlation id crosses. A general context copy would let request-scoped state leak - * into a worker thread that outlives the request. - */ -public final class ReactorContextBridge { - - /** Reactor context key for the correlation id. */ - public static final String CORRELATION_ID = "correlationId"; - - private final ThreadLocal currentCorrelationId = new ThreadLocal<>(); - - /** Run an action with the context's correlation id bound to the calling thread. */ - public T withContext(ContextView context, Supplier action) { - Objects.requireNonNull(context, "context"); - Objects.requireNonNull(action, "action"); - Optional correlationId = - context.hasKey(CORRELATION_ID) - ? Optional.of(String.valueOf(context.get(CORRELATION_ID))) - : Optional.empty(); - correlationId.ifPresent(currentCorrelationId::set); - try { - return action.get(); - } finally { - currentCorrelationId.remove(); - } - } - - /** Correlation id bound to the current thread, if any. */ - public Optional currentCorrelationId() { - return Optional.ofNullable(currentCorrelationId.get()); - } -} diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/reactor/ReactorNotificationOrchestrator.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/reactor/ReactorNotificationOrchestrator.java deleted file mode 100644 index 45e34dc3..00000000 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/reactor/ReactorNotificationOrchestrator.java +++ /dev/null @@ -1,74 +0,0 @@ -package dev.caskeleton.adapter.outbound.notification.platform.reactor; - -import dev.caskeleton.application.notification.platform.api.NotificationId; -import dev.caskeleton.application.notification.platform.api.NotificationOrchestrator; -import dev.caskeleton.application.notification.platform.api.NotificationPlan; -import dev.caskeleton.application.notification.platform.api.NotificationReceipt; -import dev.caskeleton.application.notification.platform.api.NotificationSnapshot; -import java.time.Instant; -import java.util.Objects; -import reactor.core.publisher.Mono; -import reactor.core.scheduler.Scheduler; -import reactor.core.scheduler.Schedulers; - -/** - * Reactor facade over the synchronous durable API. - * - *

The blocking submit runs on {@code boundedElastic}, never on an event loop, and the facade - * itself never calls {@code block()}. - * - *

Cancelling the {@code Mono} stops the caller waiting; it does not delete a notification that - * has already been committed. Undoing a durable acceptance because a subscriber went away would - * make the receipt meaningless. - */ -public final class ReactorNotificationOrchestrator implements ReactiveNotificationOrchestrator { - - private final NotificationOrchestrator delegate; - private final ReactorContextBridge contextBridge; - private final Scheduler scheduler; - - public ReactorNotificationOrchestrator( - NotificationOrchestrator delegate, ReactorContextBridge contextBridge) { - this(delegate, contextBridge, Schedulers.boundedElastic()); - } - - public ReactorNotificationOrchestrator( - NotificationOrchestrator delegate, ReactorContextBridge contextBridge, Scheduler scheduler) { - this.delegate = Objects.requireNonNull(delegate, "delegate"); - this.contextBridge = Objects.requireNonNull(contextBridge, "contextBridge"); - this.scheduler = Objects.requireNonNull(scheduler, "scheduler"); - } - - @Override - public Mono submit(NotificationPlan plan) { - Objects.requireNonNull(plan, "plan"); - return Mono.deferContextual( - context -> - Mono.fromSupplier( - () -> contextBridge.withContext(context, () -> delegate.submit(plan)))) - .subscribeOn(scheduler); - } - - @Override - public Mono schedule(NotificationPlan plan, Instant scheduleAt) { - Objects.requireNonNull(plan, "plan"); - Objects.requireNonNull(scheduleAt, "scheduleAt"); - return Mono.deferContextual( - context -> - Mono.fromSupplier( - () -> - contextBridge.withContext( - context, () -> delegate.schedule(plan, scheduleAt)))) - .subscribeOn(scheduler); - } - - @Override - public Mono get(NotificationId notificationId) { - Objects.requireNonNull(notificationId, "notificationId"); - return Mono.deferContextual( - context -> - Mono.fromSupplier( - () -> contextBridge.withContext(context, () -> delegate.get(notificationId)))) - .subscribeOn(scheduler); - } -} diff --git a/src/adapter/outbound/notification/src/main/resources/META-INF/spring.factories b/src/adapter/outbound/notification/src/main/resources/META-INF/spring.factories new file mode 100644 index 00000000..340dc063 --- /dev/null +++ b/src/adapter/outbound/notification/src/main/resources/META-INF/spring.factories @@ -0,0 +1,2 @@ +org.springframework.boot.EnvironmentPostProcessor=\ +dev.caskeleton.adapter.outbound.notification.platform.autoconfigure.NotificationActivationEnvironmentPostProcessor diff --git a/src/build-tools/src/main/java/dev/caskeleton/buildtools/notification/NotificationEvidenceVerifier.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/evidence/NotificationEvidenceVerifier.java similarity index 77% rename from src/build-tools/src/main/java/dev/caskeleton/buildtools/notification/NotificationEvidenceVerifier.java rename to src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/evidence/NotificationEvidenceVerifier.java index 652993f5..b5736d58 100644 --- a/src/build-tools/src/main/java/dev/caskeleton/buildtools/notification/NotificationEvidenceVerifier.java +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/evidence/NotificationEvidenceVerifier.java @@ -1,4 +1,4 @@ -package dev.caskeleton.buildtools.notification; +package dev.caskeleton.adapter.outbound.notification.evidence; import java.io.File; import java.io.IOException; @@ -9,13 +9,19 @@ import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Set; import tools.jackson.databind.JsonNode; import tools.jackson.databind.ObjectMapper; import tools.jackson.databind.json.JsonMapper; -/** Pure repository-policy verifier for notification support grades and their evidence. */ -public final class NotificationEvidenceVerifier { +/** + * Holds docs/notification/support-matrix.md to docs/notification/evidence-manifest.json: every + * grade the matrix assigns needs claims the manifest marks satisfied, and every satisfied claim + * names test files that exist and a lane that runs them. It was the build-tools task + * verifyNotificationEvidence. + */ +final class NotificationEvidenceVerifier { private static final ObjectMapper JSON = JsonMapper.builder().build(); private static final Map EVIDENCE_LANES = @@ -24,23 +30,22 @@ public final class NotificationEvidenceVerifier { new EvidenceLane( "adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/", "@Tag(\"jpa-contract\")", - "build-logic/src/main/java/dev/caskeleton/buildlogic/jpa/JpaTestLanesPlugin.java", + "adapter/outbound/persistence-jpa/build.gradle", List.of("jpaPlatformContractTest", "jpa-contract")), ":adapter:outbound:notification:test", - new EvidenceLane( - "adapter/outbound/notification/src/test/java/", null, null, List.of()), + new EvidenceLane("adapter/outbound/notification/src/test/java/", null, null, List.of()), ":application-notification:test", new EvidenceLane("application-notification/src/test/java/", null, null, List.of())); private NotificationEvidenceVerifier() {} - public static NotificationEvidenceResult verify( + static NotificationEvidenceResult verify( File manifestFile, File repositoryDirectory, File projectDirectory) { NotificationEvidenceManifest manifest = parseManifest(manifestFile); File matrixFile = new File(repositoryDirectory, manifest.matrixDocument()); if (!matrixFile.isFile()) { throw new IllegalStateException( - "verifyNotificationEvidence: missing support matrix " + matrixFile); + "notification evidence: missing support matrix " + matrixFile); } List problems = new ArrayList<>(); @@ -148,19 +153,19 @@ public final class NotificationEvidenceVerifier { if (knownGrades.isEmpty()) { throw new IllegalStateException( - "verifyNotificationEvidence: the manifest defines no grades, so the check would pass" + "notification evidence: the manifest defines no grades, so the check would pass" + " whatever the support matrix claims."); } if (gradeAssigningTables == 0) { throw new IllegalStateException( - "verifyNotificationEvidence: " + "notification evidence: " + matrixFile.getName() + " has no table that assigns a grade (a 'Grade' column that is not the first" + " column), so no claim in it was checked."); } if (!problems.isEmpty()) { throw new IllegalStateException( - "verifyNotificationEvidence: the support matrix claims more than the evidence proves.\n " + "notification evidence: the support matrix claims more than the evidence proves.\n " + String.join("\n ", problems) + "\n" + "Either add the artifact and mark the claim satisfied, or lower the grade. A grade" @@ -172,15 +177,14 @@ public final class NotificationEvidenceVerifier { static NotificationEvidenceManifest parseManifest(File manifestFile) { if (!manifestFile.isFile()) { - throw new IllegalStateException( - "verifyNotificationEvidence: missing manifest " + manifestFile); + throw new IllegalStateException("notification evidence: missing manifest " + manifestFile); } JsonNode root = JSON.readTree(read(manifestFile)); String matrixDocument = requiredText(root, "matrixDocument"); JsonNode claimsNode = root.get("claims"); if (claimsNode == null || !claimsNode.isObject()) { - throw new IllegalStateException("verifyNotificationEvidence: claims must be an object"); + throw new IllegalStateException("notification evidence: claims must be an object"); } List claims = new ArrayList<>(); claimsNode @@ -204,7 +208,7 @@ public final class NotificationEvidenceVerifier { JsonNode gradesNode = root.get("grades"); if (gradesNode == null || !gradesNode.isObject()) { - throw new IllegalStateException("verifyNotificationEvidence: grades must be an object"); + throw new IllegalStateException("notification evidence: grades must be an object"); } List grades = new ArrayList<>(); gradesNode @@ -301,20 +305,20 @@ public final class NotificationEvidenceVerifier { if (value == null || value.isNull()) { return null; } - if (!value.isString() || value.asText().isBlank()) { + if (!value.isString() || value.asString().isBlank()) { throw new IllegalStateException( - "verifyNotificationEvidence: optional text field '" + field + "' is invalid"); + "notification evidence: optional text field '" + field + "' is invalid"); } - return value.asText(); + return value.asString(); } private static String requiredText(JsonNode node, String field) { JsonNode value = node == null ? null : node.get(field); - if (value == null || !value.isString() || value.asText().isBlank()) { + if (value == null || !value.isString() || value.asString().isBlank()) { throw new IllegalStateException( - "verifyNotificationEvidence: required text field '" + field + "' is missing"); + "notification evidence: required text field '" + field + "' is missing"); } - return value.asText(); + return value.asString(); } private static List stringArray(JsonNode node) { @@ -322,14 +326,14 @@ public final class NotificationEvidenceVerifier { return List.of(); } if (!node.isArray()) { - throw new IllegalStateException("verifyNotificationEvidence: expected JSON array"); + throw new IllegalStateException("notification evidence: expected JSON array"); } List values = new ArrayList<>(); for (JsonNode value : node) { if (!value.isString()) { - throw new IllegalStateException("verifyNotificationEvidence: array values must be strings"); + throw new IllegalStateException("notification evidence: array values must be strings"); } - values.add(value.asText()); + values.add(value.asString()); } return List.copyOf(values); } @@ -369,4 +373,56 @@ public final class NotificationEvidenceVerifier { declarationMarkers = List.copyOf(declarationMarkers); } } + + record NotificationClaim( + String name, NotificationClaimStatus status, List lanes, List evidence) { + NotificationClaim { + Objects.requireNonNull(name, "name"); + Objects.requireNonNull(status, "status"); + lanes = List.copyOf(Objects.requireNonNull(lanes, "lanes")); + evidence = List.copyOf(Objects.requireNonNull(evidence, "evidence")); + } + } + + enum NotificationClaimStatus { + SATISFIED("satisfied"), + UNSATISFIED("unsatisfied"); + + private final String externalValue; + + NotificationClaimStatus(String externalValue) { + this.externalValue = externalValue; + } + + static NotificationClaimStatus parse(String value) { + for (NotificationClaimStatus status : values()) { + if (status.externalValue.equals(value)) { + return status; + } + } + throw new IllegalStateException("unsupported claim status '" + value + "'"); + } + } + + record NotificationEvidenceManifest( + String matrixDocument, List claims, List grades) { + NotificationEvidenceManifest { + Objects.requireNonNull(matrixDocument, "matrixDocument"); + claims = List.copyOf(claims); + grades = List.copyOf(grades); + } + } + + record NotificationEvidenceResult(int satisfiedClaimCount, String matrixFileName) { + NotificationEvidenceResult { + Objects.requireNonNull(matrixFileName, "matrixFileName"); + } + } + + record NotificationGrade(String name, List requiredClaims) { + NotificationGrade { + Objects.requireNonNull(name, "name"); + requiredClaims = List.copyOf(requiredClaims); + } + } } diff --git a/src/build-tools/src/test/java/dev/caskeleton/buildtools/notification/NotificationEvidenceVerifierTest.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/evidence/NotificationEvidenceVerifierTest.java similarity index 87% rename from src/build-tools/src/test/java/dev/caskeleton/buildtools/notification/NotificationEvidenceVerifierTest.java rename to src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/evidence/NotificationEvidenceVerifierTest.java index 4e6a4e16..992cc24f 100644 --- a/src/build-tools/src/test/java/dev/caskeleton/buildtools/notification/NotificationEvidenceVerifierTest.java +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/evidence/NotificationEvidenceVerifierTest.java @@ -1,9 +1,11 @@ -package dev.caskeleton.buildtools.notification; +package dev.caskeleton.adapter.outbound.notification.evidence; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import dev.caskeleton.adapter.outbound.notification.evidence.NotificationEvidenceVerifier.NotificationEvidenceResult; +import java.io.File; import java.nio.file.Files; import java.nio.file.Path; import org.junit.jupiter.api.Test; @@ -11,6 +13,22 @@ import org.junit.jupiter.api.io.TempDir; class NotificationEvidenceVerifierTest { + @Test + void repositorySupportMatrixClaimsNoMoreThanTheManifestProves() throws Exception { + // given + File repository = new File("../../../..").getCanonicalFile(); + + // when + NotificationEvidenceResult result = + NotificationEvidenceVerifier.verify( + new File(repository, "docs/notification/evidence-manifest.json"), + repository, + new File(repository, "src")); + + // then + assertEquals("support-matrix.md", result.matrixFileName()); + } + @Test void validGradeIsBackedBySatisfiedClaimAndExistingArtifact(@TempDir Path temp) throws Exception { Fixture fixture = fixture(temp); @@ -136,9 +154,7 @@ class NotificationEvidenceVerifierTest { Path manifest = docs.resolve("evidence-manifest.json"); Path matrix = docs.resolve("support-matrix.md"); Files.writeString( - evidence, - "final class DeliveryContractTest { @Test void provesDelivery() {}" - + " }\n"); + evidence, "final class DeliveryContractTest { @Test void provesDelivery() {}" + " }\n"); Files.writeString( manifest, """ diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationActivationEnvironmentPostProcessorTest.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationActivationEnvironmentPostProcessorTest.java new file mode 100644 index 00000000..b08f595a --- /dev/null +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationActivationEnvironmentPostProcessorTest.java @@ -0,0 +1,79 @@ +package dev.caskeleton.adapter.outbound.notification.platform.autoconfigure; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.context.properties.bind.Bindable; +import org.springframework.boot.context.properties.bind.Binder; +import org.springframework.core.env.MapPropertySource; +import org.springframework.core.env.StandardEnvironment; + +class NotificationActivationEnvironmentPostProcessorTest { + + private final NotificationActivationEnvironmentPostProcessor processor = + new NotificationActivationEnvironmentPostProcessor(); + + @Test + void offExcludesBootsMailAutoConfigurations() { + // given + StandardEnvironment environment = + environment(Map.of(NotificationActivationEnvironmentPostProcessor.SWITCH, "false")); + + // when + processor.postProcessEnvironment(environment, new SpringApplication()); + + // then + assertThat(excluded(environment)) + .containsExactlyInAnyOrder( + "org.springframework.boot.mail.autoconfigure.MailSenderAutoConfiguration", + "org.springframework.boot.mail.autoconfigure.MailSenderValidatorAutoConfiguration", + "org.springframework.boot.mail.autoconfigure.MailHealthContributorAutoConfiguration"); + } + + @Test + void offKeepsTheDeploymentsOwnExclusionsFirst() { + // given + StandardEnvironment environment = + environment( + Map.of( + NotificationActivationEnvironmentPostProcessor.SWITCH, + "false", + NotificationActivationEnvironmentPostProcessor.EXCLUDE, + "com.example.OneAutoConfiguration")); + + // when + processor.postProcessEnvironment(environment, new SpringApplication()); + + // then + assertThat(excluded(environment)) + .startsWith("com.example.OneAutoConfiguration") + .contains("org.springframework.boot.mail.autoconfigure.MailSenderAutoConfiguration"); + } + + @Test + void onByDefaultExcludesNothing() { + // given + StandardEnvironment environment = environment(Map.of()); + + // when + processor.postProcessEnvironment(environment, new SpringApplication()); + + // then + assertThat(excluded(environment)).isEmpty(); + } + + private static StandardEnvironment environment(Map properties) { + StandardEnvironment environment = new StandardEnvironment(); + environment.getPropertySources().addFirst(new MapPropertySource("test", properties)); + return environment; + } + + private static List excluded(StandardEnvironment environment) { + return Binder.get(environment) + .bind(NotificationActivationEnvironmentPostProcessor.EXCLUDE, Bindable.listOf(String.class)) + .orElse(List.of()); + } +} diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationLegacyNamespaceRetirementTest.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationLegacyNamespaceRetirementTest.java index a384e9fa..3af91f4a 100644 --- a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationLegacyNamespaceRetirementTest.java +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationLegacyNamespaceRetirementTest.java @@ -33,10 +33,6 @@ import org.junit.jupiter.api.Test; * persistence is wired, the counts below invert and the R0 removal becomes a change that takes * nothing away. Failing then is the point — it is the signal that the shim can finally be raised * and the namespace removed. - * - *

The negative half of NTF-INT-004 — that no legacy selector is documented as an activation - * switch — is already enforced by {@code MasterSwitchRegistryContractTest}, and is asserted here to - * be still in force rather than duplicated. */ class NotificationLegacyNamespaceRetirementTest { @@ -82,25 +78,6 @@ class NotificationLegacyNamespaceRetirementTest { .isPositive(); } - @Test - @DisplayName("no legacy selector is documented as an activation switch") - void noLegacySelectorIsDocumentedAsAnActivationSwitch() { - Path contract = - repositoryRoot() - .resolve( - "src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/activation/" - + "MasterSwitchRegistryContractTest.java"); - - assertThat(read(contract)) - .as( - "the negative half of NTF-INT-004 lives with the switch registry contract, where a new" - + " master switch would be added; asserted here so removing it there is visible" - + " from the task that depends on it") - .contains("APP_NOTIFICATION_SLACK_WEBHOOK_ENABLED") - .contains("APP_NOTIFICATION_GOOGLE_EMAIL_ENABLED") - .contains("doesNotContain(\"master switch\")"); - } - private static Stream notificationSources() { Path root = repositoryRoot().resolve("src/adapter/outbound/notification/src/main/java"); try (Stream walk = Files.walk(root)) { diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformCoreConfigurationTest.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformCoreConfigurationTest.java index 5a0cab46..b1f80a7c 100644 --- a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformCoreConfigurationTest.java +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformCoreConfigurationTest.java @@ -32,14 +32,16 @@ class NotificationPlatformCoreConfigurationTest { new ApplicationContextRunner().withUserConfiguration(NotificationPlatformCoreConfig.class); @Test - void thePlatformContributesNothingUntilItIsExplicitlyEnabled() { - runner.run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context).doesNotHaveBean(MessageDigestPort.class); - assertThat(context).doesNotHaveBean(TemplateVariableValidator.class); - assertThat(context).doesNotHaveBean(NotificationHttpGateway.class); - }); + void thePlatformContributesNothingWhenExplicitlyDisabled() { + runner + .withPropertyValues("ca-skeleton.notification.platform.enabled=false") + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context).doesNotHaveBean(MessageDigestPort.class); + assertThat(context).doesNotHaveBean(TemplateVariableValidator.class); + assertThat(context).doesNotHaveBean(NotificationHttpGateway.class); + }); } @Test diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformSettingsTest.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformSettingsTest.java index b43e404a..dbeb248f 100644 --- a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformSettingsTest.java +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationPlatformSettingsTest.java @@ -3,10 +3,15 @@ package dev.caskeleton.adapter.outbound.notification.platform.autoconfigure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; import java.time.Duration; +import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Test; +import org.springframework.boot.context.properties.bind.BindException; +import org.springframework.boot.context.properties.bind.Binder; +import org.springframework.boot.context.properties.source.MapConfigurationPropertySource; class NotificationPlatformSettingsTest { @@ -45,6 +50,36 @@ class NotificationPlatformSettingsTest { .hasMessageContaining("ses settings block"); } + @Test + void sesCallbacksWithoutAnAllowedTopicListFailBinding() { + // when + Throwable failure = catchThrowable(() -> bind(sesWithCallbacksEnabled())); + + // then + assertThat(failure) + .isInstanceOf(BindException.class) + .rootCause() + .hasMessageContaining("allowed-topic-arns"); + } + + @Test + void anAllowedTopicListBindsFromACommaSeparatedValue() { + // given + Map properties = sesWithCallbacksEnabled(); + properties.put( + "ca-skeleton.notification.platform.providers.ses.ses.allowed-topic-arns", + "arn:aws:sns:us-east-1:123456789012:ses-events,arn:aws:sns:eu-west-1:123456789012:ses-eu"); + + // when + NotificationPlatformSettings settings = bind(properties); + + // then + assertThat(settings.providers().get("ses").ses().allowedTopicArns()) + .containsExactly( + "arn:aws:sns:us-east-1:123456789012:ses-events", + "arn:aws:sns:eu-west-1:123456789012:ses-eu"); + } + @Test void aCallbackCapableProviderRequiresASigningSecret() { assertThatThrownBy(() -> properties(twilioWithoutSigningSecret())) @@ -123,6 +158,34 @@ class NotificationPlatformSettingsTest { .isEqualTo(100_000); } + private static NotificationPlatformSettings bind(Map properties) { + return new Binder(new MapConfigurationPropertySource(properties)) + .bind("ca-skeleton.notification.platform", NotificationPlatformSettings.class) + .get(); + } + + /** An enabled SES profile with callbacks on, complete except for the topic allowlist. */ + private static Map sesWithCallbacksEnabled() { + String prefix = "ca-skeleton.notification.platform."; + Map properties = new HashMap<>(); + properties.put(prefix + "enabled", "true"); + properties.put(prefix + "callbacks.enabled", "true"); + properties.put(prefix + "callbacks.max-body-bytes", "1024"); + properties.put(prefix + "callbacks.replay-skew", "5m"); + properties.put(prefix + "providers.ses.type", "SES"); + properties.put(prefix + "providers.ses.enabled", "true"); + properties.put(prefix + "providers.ses.environment", "PRODUCTION"); + properties.put(prefix + "providers.ses.credential-profile", "ses-key"); + properties.put(prefix + "providers.ses.timeout", "10s"); + properties.put(prefix + "providers.ses.max-concurrency", "8"); + properties.put(prefix + "providers.ses.rate-per-second", "20"); + properties.put(prefix + "providers.ses.ses.endpoint", "https://email.us-east-1.amazonaws.com"); + properties.put(prefix + "providers.ses.ses.region", "us-east-1"); + properties.put(prefix + "providers.ses.ses.sender-identity", "no-reply@example.test"); + properties.put(prefix + "providers.ses.ses.access-key-id", "AKIAEXAMPLE"); + return properties; + } + private static NotificationPlatformSettings properties( NotificationPlatformSettings.Provider provider) { return new NotificationPlatformSettings( diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationProviderAssemblyTest.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationProviderAssemblyTest.java index 2ae46951..20131eee 100644 --- a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationProviderAssemblyTest.java +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/NotificationProviderAssemblyTest.java @@ -275,7 +275,8 @@ class NotificationProviderAssemblyTest { "us-east-1", "no-reply@example.test", "AKIAEXAMPLE", - null) + null, + List.of("arn:aws:sns:us-east-1:123456789012:ses-events")) : null; return new NotificationPlatformSettings.Provider( type, diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/SesProviderRuntimeAssemblerTest.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/SesProviderRuntimeAssemblerTest.java index b24319e3..3459694e 100644 --- a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/SesProviderRuntimeAssemblerTest.java +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/SesProviderRuntimeAssemblerTest.java @@ -83,6 +83,7 @@ class SesProviderRuntimeAssemblerTest { "us-east-1", "no-reply@example.test", "AKIAEXAMPLE", + null, null)); } diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/SnsCertificateCacheTest.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/SnsCertificateCacheTest.java new file mode 100644 index 00000000..faf98bd6 --- /dev/null +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/autoconfigure/SnsCertificateCacheTest.java @@ -0,0 +1,79 @@ +package dev.caskeleton.adapter.outbound.notification.platform.autoconfigure; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.adapter.outbound.notification.platform.provider.http.NotificationHttpGateway; +import dev.caskeleton.adapter.outbound.notification.platform.provider.http.NotificationHttpResponse; +import dev.caskeleton.adapter.outbound.notification.platform.provider.ses.SnsCertificateProvider; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; +import org.junit.jupiter.api.Test; + +/** + * The SNS signing-certificate cache: it saves the fetch, and it does not grow without bound. + * + *

It was keyed by a URL the caller supplies and never evicted anything, so every distinct URL + * that passed the host check stayed in memory for the life of the process. + */ +class SnsCertificateCacheTest { + + /** A throwaway self-signed certificate; only its public key is ever read. */ + private static final String CERTIFICATE = + """ + -----BEGIN CERTIFICATE----- + MIIBjjCCATOgAwIBAgIUPz1yBmX7Q2nMyAvKr4OI9ny/r2AwCgYIKoZIzj0EAwIw + GzEZMBcGA1UEAwwQc25zLnRlc3QuaW52YWxpZDAgFw0yNjA5MjQxNzM3MThaGA8y + MTI2MDgzMTE3MzcxOFowGzEZMBcGA1UEAwwQc25zLnRlc3QuaW52YWxpZDBZMBMG + ByqGSM49AgEGCCqGSM49AwEHA0IABFmZFeFEhG2KvXlTZ40ASdAxvV5RyAqrqHqb + 7JWygPU0tpUEWzUOgEOrJJHQ02/JGEwQwkn2ksXxU14ZjykaZDKjUzBRMB0GA1Ud + DgQWBBTGpg+qbXfyX7tbOGGhpWdRHQKzcjAfBgNVHSMEGDAWgBTGpg+qbXfyX7tb + OGGhpWdRHQKzcjAPBgNVHRMBAf8EBTADAQH/MAoGCCqGSM49BAMCA0kAMEYCIQDd + vdmSN1v/QdCJFdbfis42K7yzOgTl/caoi7tgQGVqEwIhAIzssvVMM3fetLU90eGq + gh81bp3eRjpJhTiSLhV5foJJ + -----END CERTIFICATE----- + """; + + private final AtomicInteger fetches = new AtomicInteger(); + private final NotificationHttpGateway gateway = + request -> { + fetches.incrementAndGet(); + return new NotificationHttpResponse( + 200, Map.of(), CERTIFICATE.getBytes(StandardCharsets.US_ASCII)); + }; + private final SnsCertificateProvider certificates = + new NotificationCallbackProviderConfig().snsCertificateProvider(gateway); + + @Test + void aCachedCertificateIsNotFetchedAgain() { + // given + certificates.publicKeyFor(url(0)); + + // when + certificates.publicKeyFor(url(0)); + + // then + assertThat(fetches).hasValue(1); + } + + @Test + void theCacheForgetsCertificatesOnceItPassesItsBound() { + // given + int bound = NotificationCallbackProviderConfig.MAX_CACHED_SNS_CERTIFICATES; + for (int index = 0; index <= bound; index++) { + certificates.publicKeyFor(url(index)); + } + + // when + certificates.publicKeyFor(url(0)); + + // then + assertThat(fetches).hasValue(bound + 2); + } + + private static URI url(int index) { + return URI.create( + "https://sns.us-east-1.amazonaws.com/SimpleNotificationService-" + index + ".pem"); + } +} diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesCallbackAdapterTest.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesCallbackAdapterTest.java new file mode 100644 index 00000000..2febfcc8 --- /dev/null +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SesCallbackAdapterTest.java @@ -0,0 +1,128 @@ +package dev.caskeleton.adapter.outbound.notification.platform.provider.ses; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.adapter.outbound.notification.platform.callback.CallbackVerificationResult; +import dev.caskeleton.adapter.outbound.notification.platform.callback.ProviderCallbackVerificationRequest; +import dev.caskeleton.adapter.outbound.notification.platform.template.NotificationJsonMapper; +import dev.caskeleton.application.notification.platform.api.ProviderId; +import dev.caskeleton.application.notification.platform.api.ProviderProfileId; +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.Signature; +import java.time.Duration; +import java.time.Instant; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import org.junit.jupiter.api.Test; + +/** + * What a correctly signed SNS message still has to prove before it is believed. + * + *

A valid signature only says AWS sent it. Anyone can own an SNS topic and have AWS sign + * messages for it, so the topic has to be one this profile subscribed to; and a signed message + * stays signed forever, so it has to be recent. + */ +class SesCallbackAdapterTest { + + private static final Instant RECEIVED_AT = Instant.parse("2026-09-25T10:00:00Z"); + private static final String ALLOWED_TOPIC = "arn:aws:sns:us-east-1:123456789012:ses-events"; + private static final KeyPair SNS_KEYS = rsa(); + + private final SesCallbackAdapter adapter = + new SesCallbackAdapter( + new SnsSignatureVerifier(certificateUrl -> SNS_KEYS.getPublic()), + new SesEventNormalizer(), + Set.of(ALLOWED_TOPIC), + Duration.ofMinutes(5)); + + @Test + void aSignedMessageFromAnAllowedTopicIsAccepted() { + CallbackVerificationResult result = adapter.verify(request(signed(ALLOWED_TOPIC, RECEIVED_AT))); + + assertThat(result) + .extracting(CallbackVerificationResult::valid, CallbackVerificationResult::reasonCode) + .containsExactly(true, "OK"); + } + + @Test + void aSignedMessageFromAnotherTopicIsRejected() { + // given + byte[] body = signed("arn:aws:sns:us-east-1:999999999999:attacker-topic", RECEIVED_AT); + + // when + CallbackVerificationResult result = adapter.verify(request(body)); + + // then + assertThat(result) + .extracting(CallbackVerificationResult::valid, CallbackVerificationResult::reasonCode) + .containsExactly(false, "SNS_TOPIC_NOT_ALLOWED"); + } + + @Test + void aSignedMessageOlderThanTheReplayWindowIsRejected() { + // given + byte[] body = signed(ALLOWED_TOPIC, RECEIVED_AT.minus(Duration.ofMinutes(6))); + + // when + CallbackVerificationResult result = adapter.verify(request(body)); + + // then + assertThat(result) + .extracting(CallbackVerificationResult::valid, CallbackVerificationResult::reasonCode) + .containsExactly(false, "SNS_TIMESTAMP_OUT_OF_WINDOW"); + } + + private static ProviderCallbackVerificationRequest request(byte[] body) { + return new ProviderCallbackVerificationRequest( + new ProviderId("ses"), + new ProviderProfileId("ses-events"), + "https://callback.example/internal/notification/callbacks/ses/ses-events", + "POST", + Optional.of("application/json"), + Map.of(), + body, + RECEIVED_AT); + } + + /** An envelope signed the way SNS signs it, with the key the certificate provider hands out. */ + private static byte[] signed(String topicArn, Instant timestamp) { + Map envelope = new LinkedHashMap<>(); + envelope.put("Type", "Notification"); + envelope.put("MessageId", "sns-message-1"); + envelope.put("TopicArn", topicArn); + envelope.put("Timestamp", timestamp.toString()); + envelope.put( + "Message", + "{\"eventType\":\"Delivery\",\"mail\":{\"messageId\":\"ses-request-1\"}," + + "\"delivery\":{\"timestamp\":\"" + + timestamp + + "\"}}"); + envelope.put( + "SigningCertURL", "https://sns.us-east-1.amazonaws.com/SimpleNotificationService-test.pem"); + envelope.put("SignatureVersion", "2"); + try { + Signature signer = Signature.getInstance("SHA256withRSA"); + signer.initSign(SNS_KEYS.getPrivate()); + signer.update( + SnsSignatureVerifier.canonicalString(envelope).getBytes(StandardCharsets.UTF_8)); + envelope.put("Signature", Base64.getEncoder().encodeToString(signer.sign())); + } catch (GeneralSecurityException impossible) { + throw new IllegalStateException(impossible); + } + return NotificationJsonMapper.mapper().writeValueAsBytes(envelope); + } + + private static KeyPair rsa() { + try { + return KeyPairGenerator.getInstance("RSA").generateKeyPair(); + } catch (GeneralSecurityException impossible) { + throw new IllegalStateException(impossible); + } + } +} diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SnsCertificateUrlTest.java b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SnsCertificateUrlTest.java index 5ba06823..fc72db88 100644 --- a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SnsCertificateUrlTest.java +++ b/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/provider/ses/SnsCertificateUrlTest.java @@ -4,6 +4,8 @@ import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; /** * Which host the verifier will fetch a signing certificate from. @@ -14,8 +16,7 @@ import org.junit.jupiter.api.Test; */ class SnsCertificateUrlTest { - private final SnsSignatureVerifier verifier = - new SnsSignatureVerifier(certificateUrl -> null, "amazonaws.com"); + private final SnsSignatureVerifier verifier = new SnsSignatureVerifier(certificateUrl -> null); @Test @DisplayName("a genuine SNS certificate URL is accepted") @@ -26,6 +27,34 @@ class SnsCertificateUrlTest { .isTrue(); } + @ParameterizedTest + @ValueSource( + strings = { + "https://sns.us-east-1.amazonaws.com/SimpleNotificationService-abc123.pem", + "https://sns.us-gov-west-1.amazonaws.com/SimpleNotificationService-abc123.pem", + "https://sns.cn-north-1.amazonaws.com.cn/SimpleNotificationService-abc123.pem" + }) + void anSnsRegionalEndpointIsAccepted(String certificateUrl) { + assertThat(verifier.isTrustedCertificateUrl(certificateUrl)).isTrue(); + } + + @ParameterizedTest + @ValueSource( + strings = { + // Anyone can create a bucket, and S3 serves it under amazonaws.com with any object name. + "https://attacker-bucket.s3.amazonaws.com/SimpleNotificationService-x.pem", + "https://attacker-bucket.s3.us-east-1.amazonaws.com/SimpleNotificationService-x.pem", + // The S3 bucket named "sns", in the path-free and accelerated styles. + "https://sns.s3.amazonaws.com/SimpleNotificationService-x.pem", + "https://sns.s3-accelerate.amazonaws.com/SimpleNotificationService-x.pem", + "https://amazonaws.com/SimpleNotificationService-x.pem", + "https://sns.amazonaws.com/SimpleNotificationService-x.pem", + "https://sns.us-east-1.amazonaws.com.evil.example/SimpleNotificationService-x.pem" + }) + void aHostThatIsNotAnSnsRegionalEndpointIsRefused(String certificateUrl) { + assertThat(verifier.isTrustedCertificateUrl(certificateUrl)).isFalse(); + } + @Test @DisplayName("a host that merely ends with the suffix is refused") void aHostThatMerelyEndsWithTheSuffixIsRefused() { diff --git a/src/adapter/outbound/notification/src/test/resources/notification/templates/email/contract-v1.html b/src/adapter/outbound/notification/src/test/resources/notification/templates/email/contract-v1.html deleted file mode 100644 index c1000b00..00000000 --- a/src/adapter/outbound/notification/src/test/resources/notification/templates/email/contract-v1.html +++ /dev/null @@ -1,2 +0,0 @@ -

Hello {{displayName|html_text}}.

-Open contract diff --git a/src/adapter/outbound/notification/src/test/resources/notification/templates/email/contract-v1.subject.txt b/src/adapter/outbound/notification/src/test/resources/notification/templates/email/contract-v1.subject.txt deleted file mode 100644 index bea116c3..00000000 --- a/src/adapter/outbound/notification/src/test/resources/notification/templates/email/contract-v1.subject.txt +++ /dev/null @@ -1 +0,0 @@ -Contract notice for {{displayName|header}} diff --git a/src/adapter/outbound/notification/src/test/resources/notification/templates/email/contract-v1.text.txt b/src/adapter/outbound/notification/src/test/resources/notification/templates/email/contract-v1.text.txt deleted file mode 100644 index 756df6f3..00000000 --- a/src/adapter/outbound/notification/src/test/resources/notification/templates/email/contract-v1.text.txt +++ /dev/null @@ -1,2 +0,0 @@ -Hello {{displayName|text}}. -Reference: {{query|text}} diff --git a/src/adapter/outbound/notification/src/test/resources/notification/templates/slack/contract-v1.txt b/src/adapter/outbound/notification/src/test/resources/notification/templates/slack/contract-v1.txt deleted file mode 100644 index ce4b5909..00000000 --- a/src/adapter/outbound/notification/src/test/resources/notification/templates/slack/contract-v1.txt +++ /dev/null @@ -1,3 +0,0 @@ -*Alert for {{displayName|mrkdwn}}* -Audience: {{audience|plain}} -Mention: {{mention|mention}} diff --git a/src/adapter/outbound/objectstorage/README.md b/src/adapter/outbound/objectstorage/README.md index 405f192a..bf141fcf 100644 --- a/src/adapter/outbound/objectstorage/README.md +++ b/src/adapter/outbound/objectstorage/README.md @@ -30,11 +30,31 @@ It does not prove multi-node CAS, power-loss durability, production credentials/ S3 response-loss behavior, or R2 readiness. Direct transfer, multipart, quarantine, retention, and production reconciliation cards remain R0. +## 제공하는 것 · 추가할 한 줄 · env 키 + +- 제공: application-objectstorage의 semantic port 구현(`ManagedObjectPublicationPort`, 읽기/변경 + routing adapter), `filesystem-local-dev`와 S3 provider, 명시적 legacy `ObjectStoragePort` seam. + 진입점은 모듈 자신의 `AutoConfiguration.imports`에 있는 `ObjectStorageAutoConfiguration` 하나이고, + 설정 바인딩도 그 안에서 한다(composition root의 properties scan에 기대지 않는다). +- 추가할 한 줄(기본 조립에는 없다): + + ```groovy + // app-bootstrap/build.gradle + runtimeOnly project(':adapter:outbound:objectstorage') // 객체 저장소 (S3/로컬) + ``` + + 이 줄을 지우면 port 구현, provider, 설정 바인딩이 모두 함께 빠진다. +- 켜기와 끄기: 모듈이 있으면 켜진다. `app.object-storage.enabled=false`로만 끈다(그때는 명시적 + `app.object-storage.legacy.enabled=true` seam만 남을 수 있다). +- env 키: 전용 `APP_*` 키는 없다. provider·destination이 map 구조라 배포의 `application-*.yml`에 + `app.object-storage.{default-destination, providers..*, destinations..*}`를 적는다(아래 + 「Activation and routing」). 빠지면 기동 시 binding compile이 실패한다. + ## Activation and routing -The canonical namespace is `app.object-storage` and is disabled by default. Enabling it requires an -explicit provider, exact provider version, logical destination, route token, binding/policy -revisions, and bounded sizes. Settings compile fully before any selected provider creates a +The canonical namespace is `app.object-storage`. It is on when the module is present and off only +with `app.object-storage.enabled=false`. On requires an explicit provider, exact provider version, +logical destination, route token, binding/policy revisions, and bounded sizes. Settings compile fully before any selected provider creates a directory, client, thread, scheduler, or credential lookup. `filesystem-local-dev` is rejected under `prod`/`production`. Normal composition contributes only diff --git a/src/adapter/outbound/objectstorage/build.gradle b/src/adapter/outbound/objectstorage/build.gradle index e307a618..1f04d8b9 100644 --- a/src/adapter/outbound/objectstorage/build.gradle +++ b/src/adapter/outbound/objectstorage/build.gradle @@ -2,7 +2,6 @@ plugins { id 'ca.spring-library' id 'ca.spring-config' id 'ca.auxiliary-source-set' - id 'ca.strict-qualification' } // Driven adapter: provider-neutral semantic object-storage ports plus a bounded local-development @@ -41,8 +40,11 @@ dependencies { implementation 'org.springframework.boot:spring-boot-autoconfigure' implementation 'org.slf4j:slf4j-api' - implementation 'software.amazon.awssdk:s3' - implementation 'software.amazon.awssdk:netty-nio-client' + // Direct versions in the outgoing metadata as well as the module-scope BOM import (the gRPC + // leaf does the same): a composition root that selects this leaf with one runtimeOnly line + // resolves it without repeating the AWS SDK platform. + implementation "software.amazon.awssdk:s3:${libs.versions.awsSdk.get()}" + implementation "software.amazon.awssdk:netty-nio-client:${libs.versions.awsSdk.get()}" // Real MinIO/Toxiproxy infrastructure belongs only to the integration lane. @@ -61,41 +63,36 @@ tasks.named('test') { systemProperty 'objectstorage.readiness.registry', objectStorageReadinessRegistry.absolutePath } -def objectStorageMinioContractQualification = extensions.getByName('strictQualification').register( - 'objectStorageMinioContractTest', - sourceSets.integrationTest, - [ - 'dev.caskeleton.adapter.outbound.objectstorage.qualification.MinioManagedObjectContractTest' - ], - 'Runs the non-skipping exact-release MinIO managed object contract.' -) -objectStorageMinioContractQualification.configure { - shouldRunAfter tasks.named('test') -} - -def objectStorageMinioFaultQualification = extensions.getByName('strictQualification').register( - 'objectStorageMinioFaultTest', - sourceSets.integrationTest, - [ - 'dev.caskeleton.adapter.outbound.objectstorage.qualification.MinioManagedObjectFaultTest' - ], - 'Runs the non-skipping digest-pinned MinIO/Toxiproxy fault contract.' -) -objectStorageMinioFaultQualification.configure { - shouldRunAfter objectStorageMinioContractQualification +strictTestLanes { + lane('objectStorageMinioContractTest') { + integration() + sourceSet = 'integrationTest' + description = 'Runs the non-skipping exact-release MinIO managed object contract.' + requires 'dev.caskeleton.adapter.outbound.objectstorage.qualification.MinioManagedObjectContractTest' + rejectSkipped = true + jvmArgs '-Duser.timezone=UTC' + shouldRunAfter 'test' + } + lane('objectStorageMinioFaultTest') { + integration() + sourceSet = 'integrationTest' + description = 'Runs the non-skipping digest-pinned MinIO/Toxiproxy fault contract.' + requires 'dev.caskeleton.adapter.outbound.objectstorage.qualification.MinioManagedObjectFaultTest' + rejectSkipped = true + jvmArgs '-Duser.timezone=UTC' + shouldRunAfter 'objectStorageMinioContractTest' + } + lane('objectStorageAwsQualificationTest') { + integration() + sourceSet = 'objectStorageAwsQualificationTest' + description = 'Runs only with explicit protected AWS sandbox authority and exact inputs.' + requires 'dev.caskeleton.adapter.outbound.objectstorage.qualification.AwsS3DirectMutationPreconditionsTest', + 'dev.caskeleton.adapter.outbound.objectstorage.qualification.AwsS3QualificationPreconditionsTest' + rejectSkipped = true + jvmArgs '-Duser.timezone=UTC' + } } tasks.named('check') { - dependsOn objectStorageMinioContractQualification - dependsOn objectStorageMinioFaultQualification + dependsOn 'objectStorageMinioContractTest', 'objectStorageMinioFaultTest' } - -extensions.getByName('strictQualification').register( - 'objectStorageAwsQualificationTest', - sourceSets.objectStorageAwsQualificationTest, - [ - 'dev.caskeleton.adapter.outbound.objectstorage.qualification.AwsS3DirectMutationPreconditionsTest', - 'dev.caskeleton.adapter.outbound.objectstorage.qualification.AwsS3QualificationPreconditionsTest' - ], - 'Runs only with explicit protected AWS sandbox authority and exact inputs.' -) diff --git a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/ObjectStorageAutoConfiguration.java b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/ObjectStorageAutoConfiguration.java new file mode 100644 index 00000000..73de5041 --- /dev/null +++ b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/ObjectStorageAutoConfiguration.java @@ -0,0 +1,49 @@ +package dev.caskeleton.adapter.outbound.objectstorage; + +import dev.caskeleton.adapter.outbound.objectstorage.config.ObjectStorageCapabilityConfig; +import dev.caskeleton.adapter.outbound.objectstorage.config.ObjectStorageMaintenanceCapabilityConfig; +import dev.caskeleton.adapter.outbound.objectstorage.config.ObjectStorageScanMaintenanceConfig; +import org.springframework.boot.autoconfigure.AutoConfiguration; +import org.springframework.boot.autoconfigure.condition.AnyNestedCondition; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Conditional; +import org.springframework.context.annotation.Import; + +/** + * The one entry through which object storage reaches an application: this module on the classpath. + * + *

On when present. {@code app.object-storage.enabled=false} turns the canonical capability off; + * the root then stays only for the explicit legacy compatibility seam ({@code + * app.object-storage.legacy.enabled=true}), and with neither the module holds nothing — its + * settings are bound here, not by the composition root's properties scan. + */ +@AutoConfiguration +@Conditional(ObjectStorageAutoConfiguration.CapabilityOrLegacySeam.class) +@Import({ + ObjectStorageCapabilityConfig.class, + ObjectStorageScanMaintenanceConfig.class, + ObjectStorageMaintenanceCapabilityConfig.class, + ObjectStorageConfig.class +}) +public class ObjectStorageAutoConfiguration { + + static final class CapabilityOrLegacySeam extends AnyNestedCondition { + + CapabilityOrLegacySeam() { + super(ConfigurationPhase.PARSE_CONFIGURATION); + } + + @ConditionalOnProperty( + prefix = "app.object-storage", + name = "enabled", + havingValue = "true", + matchIfMissing = true) + static final class CapabilityOn {} + + @ConditionalOnProperty( + prefix = "app.object-storage.legacy", + name = "enabled", + havingValue = "true") + static final class LegacySeamOn {} + } +} diff --git a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/config/LegacyObjectAdoptionSettings.java b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/config/LegacyObjectAdoptionSettings.java deleted file mode 100644 index 69f00377..00000000 --- a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/config/LegacyObjectAdoptionSettings.java +++ /dev/null @@ -1,41 +0,0 @@ -package dev.caskeleton.adapter.outbound.objectstorage.config; - -import dev.caskeleton.application.storage.migration.LegacyObjectAdoptionRequest; -import java.nio.file.Path; -import java.time.Duration; -import org.springframework.boot.context.properties.ConfigurationProperties; - -/** Explicit isolated legacy-adoption settings; normal runtime remains disabled. */ -@ConfigurationProperties(prefix = "app.object-storage.legacy-adoption") -// The adoption settings remain active until data/API migration is complete. -@SuppressWarnings("deprecation") -public record LegacyObjectAdoptionSettings( - boolean enabled, - LegacyObjectAdoptionRequest.Mode mode, - Path reportPath, - Path reviewedManifestPath, - String reviewedManifestSha256, - int batchSize, - Duration operationTimeout) { - - public LegacyObjectAdoptionSettings { - mode = mode == null ? LegacyObjectAdoptionRequest.Mode.REPORT_ONLY : mode; - reviewedManifestSha256 = reviewedManifestSha256 == null ? "" : reviewedManifestSha256; - batchSize = batchSize == 0 ? 100 : batchSize; - operationTimeout = operationTimeout == null ? Duration.ofSeconds(30) : operationTimeout; - if (enabled - && (reportPath == null - || batchSize < 1 - || batchSize > 1000 - || operationTimeout.isZero() - || operationTimeout.isNegative() - || operationTimeout.compareTo(Duration.ofMinutes(5)) > 0)) { - throw new IllegalArgumentException("legacy adoption settings are invalid"); - } - if (enabled - && mode == LegacyObjectAdoptionRequest.Mode.APPLY - && (reviewedManifestPath == null || !reviewedManifestSha256.matches("[0-9a-f]{64}"))) { - throw new IllegalArgumentException("legacy adoption APPLY requires a reviewed manifest"); - } - } -} diff --git a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/config/ObjectStorageCapabilityConfig.java b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/config/ObjectStorageCapabilityConfig.java index cd1d0f00..8503c19e 100644 --- a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/config/ObjectStorageCapabilityConfig.java +++ b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/config/ObjectStorageCapabilityConfig.java @@ -24,18 +24,33 @@ import software.amazon.awssdk.services.s3.S3Client; public class ObjectStorageCapabilityConfig { @Bean + @ConditionalOnProperty( + prefix = "app.object-storage", + name = "enabled", + havingValue = "true", + matchIfMissing = true) @ConditionalOnMissingBean(name = "filesystemLocalDevProviderContribution") public ObjectStorageProviderContribution filesystemLocalDevProviderContribution() { return new FilesystemLocalDevProviderContribution(); } @Bean + @ConditionalOnProperty( + prefix = "app.object-storage", + name = "enabled", + havingValue = "true", + matchIfMissing = true) @ConditionalOnMissingBean(name = "s3ObjectStorageProviderContribution") public ObjectStorageProviderContribution s3ObjectStorageProviderContribution() { return new S3ObjectStorageProviderContribution(); } @Bean + @ConditionalOnProperty( + prefix = "app.object-storage", + name = "enabled", + havingValue = "true", + matchIfMissing = true) public ObjectStorageBindingCompiler objectStorageBindingCompiler( List contributions, Environment environment) { Set profiles = @@ -51,6 +66,11 @@ public class ObjectStorageCapabilityConfig { } @Bean + @ConditionalOnProperty( + prefix = "app.object-storage", + name = "enabled", + havingValue = "true", + matchIfMissing = true) public ObjectStorageCapabilityAssembler objectStorageCapabilityAssembler( List contributions, ObjectStorageBindingCompiler compiler) { @@ -58,28 +78,44 @@ public class ObjectStorageCapabilityConfig { } @Bean(destroyMethod = "close") - @ConditionalOnProperty(prefix = "app.object-storage", name = "enabled", havingValue = "true") + @ConditionalOnProperty( + prefix = "app.object-storage", + name = "enabled", + havingValue = "true", + matchIfMissing = true) public ObjectStorageCapabilityAssembler.AssembledCapability objectStorageCapability( ObjectStorageCapabilitySettings settings, ObjectStorageCapabilityAssembler assembler) { return assembler.assemble(settings); } @Bean - @ConditionalOnProperty(prefix = "app.object-storage", name = "enabled", havingValue = "true") + @ConditionalOnProperty( + prefix = "app.object-storage", + name = "enabled", + havingValue = "true", + matchIfMissing = true) public RoutingObjectMutationAdapter routingObjectMutationAdapter( ObjectStorageCapabilityAssembler.AssembledCapability capability) { return new RoutingObjectMutationAdapter(capability); } @Bean - @ConditionalOnProperty(prefix = "app.object-storage", name = "enabled", havingValue = "true") + @ConditionalOnProperty( + prefix = "app.object-storage", + name = "enabled", + havingValue = "true", + matchIfMissing = true) public ObjectPublicationHandoffService objectPublicationHandoffService( ObjectStorageCapabilityAssembler.AssembledCapability capability) { return new ObjectPublicationHandoffService(capability, java.time.Clock.systemUTC()); } @Bean - @ConditionalOnProperty(prefix = "app.object-storage", name = "enabled", havingValue = "true") + @ConditionalOnProperty( + prefix = "app.object-storage", + name = "enabled", + havingValue = "true", + matchIfMissing = true) public RoutingObjectReadAdapter routingObjectReadAdapter( ObjectStorageCapabilityAssembler.AssembledCapability capability) { return new RoutingObjectReadAdapter(capability); diff --git a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/config/ObjectStorageCapabilitySettings.java b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/config/ObjectStorageCapabilitySettings.java index 346fd88c..8783cd13 100644 --- a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/config/ObjectStorageCapabilitySettings.java +++ b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/config/ObjectStorageCapabilitySettings.java @@ -3,11 +3,15 @@ package dev.caskeleton.adapter.outbound.objectstorage.config; import java.util.LinkedHashMap; import java.util.Map; import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.context.properties.bind.DefaultValue; -/** Canonical disabled-by-default constructor-bound object-storage capability declaration. */ +/** + * Canonical constructor-bound object-storage capability declaration. On when the module is present; + * {@code enabled=false} turns the canonical capability off. + */ @ConfigurationProperties(prefix = "app.object-storage") public record ObjectStorageCapabilitySettings( - boolean enabled, + @DefaultValue("true") boolean enabled, String defaultDestination, Map providers, Map destinations, diff --git a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/config/ObjectStorageLegacyMigrationConfig.java b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/config/ObjectStorageLegacyMigrationConfig.java deleted file mode 100644 index 8ff73940..00000000 --- a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/config/ObjectStorageLegacyMigrationConfig.java +++ /dev/null @@ -1,37 +0,0 @@ -package dev.caskeleton.adapter.outbound.objectstorage.config; - -import dev.caskeleton.adapter.outbound.objectstorage.maintenance.LegacyAdoptionApprovalReplayStore; -import dev.caskeleton.adapter.outbound.objectstorage.maintenance.LegacyObjectAdoptionService; -import dev.caskeleton.adapter.outbound.objectstorage.maintenance.LegacyObjectInspector; -import dev.caskeleton.application.objectstorage.port.ManagedObjectPublicationPort; -import dev.caskeleton.application.storage.migration.LegacyObjectAdoptionPort; -import java.time.Clock; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -/** - * Explicit maintenance-only raw-locator composition. - * - *

Enabling without an isolated inspector and durable replay store fails startup. - */ -@Configuration(proxyBeanMethods = false) -@EnableConfigurationProperties(LegacyObjectAdoptionSettings.class) -@ConditionalOnProperty( - prefix = "app.object-storage.legacy-adoption", - name = "enabled", - havingValue = "true") -// This explicit adoption wiring remains active until data/API migration is complete. -@SuppressWarnings("deprecation") -public class ObjectStorageLegacyMigrationConfig { - - @Bean - public LegacyObjectAdoptionPort legacyObjectAdoptionPort( - LegacyObjectInspector inspector, - ManagedObjectPublicationPort publications, - LegacyAdoptionApprovalReplayStore replayStore, - Clock clock) { - return new LegacyObjectAdoptionService(inspector, publications, replayStore, clock); - } -} diff --git a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/config/ObjectStorageScanMaintenanceConfig.java b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/config/ObjectStorageScanMaintenanceConfig.java index 2055619b..cb95885f 100644 --- a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/config/ObjectStorageScanMaintenanceConfig.java +++ b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/config/ObjectStorageScanMaintenanceConfig.java @@ -6,7 +6,11 @@ import org.springframework.context.annotation.Configuration; /** Explicit scanner-workflow composition; absent from the normal application context. */ @Configuration(proxyBeanMethods = false) -@ConditionalOnProperty(prefix = "app.object-storage", name = "enabled", havingValue = "true") +@ConditionalOnProperty( + prefix = "app.object-storage", + name = "enabled", + havingValue = "true", + matchIfMissing = true) public class ObjectStorageScanMaintenanceConfig { @Bean diff --git a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/control/ObjectControlRecordEnvelope.java b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/control/ObjectControlRecordEnvelope.java deleted file mode 100644 index 8952f710..00000000 --- a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/control/ObjectControlRecordEnvelope.java +++ /dev/null @@ -1,45 +0,0 @@ -package dev.caskeleton.adapter.outbound.objectstorage.control; - -import java.util.Arrays; -import java.util.Objects; - -/** Defensive in-memory representation of a checksummed canonical record payload. */ -public final class ObjectControlRecordEnvelope { - - private final String sha256Digest; - private final byte[] canonicalPayload; - - public ObjectControlRecordEnvelope(String sha256Digest, byte[] canonicalPayload) { - if (sha256Digest == null || !sha256Digest.matches("[0-9a-f]{64}")) { - throw new IllegalArgumentException("envelope digest is invalid"); - } - this.sha256Digest = sha256Digest; - this.canonicalPayload = - Objects.requireNonNull(canonicalPayload, "canonicalPayload must be non-null").clone(); - } - - public String sha256Digest() { - return sha256Digest; - } - - public byte[] canonicalPayload() { - return canonicalPayload.clone(); - } - - @Override - public boolean equals(Object other) { - return other instanceof ObjectControlRecordEnvelope that - && sha256Digest.equals(that.sha256Digest) - && Arrays.equals(canonicalPayload, that.canonicalPayload); - } - - @Override - public int hashCode() { - return 31 * sha256Digest.hashCode() + Arrays.hashCode(canonicalPayload); - } - - @Override - public String toString() { - return "ObjectControlRecordEnvelope[digest=" + sha256Digest + ", payload=redacted]"; - } -} diff --git a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/maintenance/Ed25519LegacyAdoptionApprovalVerifier.java b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/maintenance/Ed25519LegacyAdoptionApprovalVerifier.java deleted file mode 100644 index 8b8b164c..00000000 --- a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/maintenance/Ed25519LegacyAdoptionApprovalVerifier.java +++ /dev/null @@ -1,119 +0,0 @@ -package dev.caskeleton.adapter.outbound.objectstorage.maintenance; - -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.storage.migration.LegacyObjectAdoptionApproval; -import dev.caskeleton.application.storage.migration.LegacyObjectAdoptionApprovalVerifierPort; -import dev.caskeleton.application.storage.migration.LegacyObjectAdoptionRequest; -import java.security.GeneralSecurityException; -import java.security.MessageDigest; -import java.security.PublicKey; -import java.security.Signature; -import java.time.Clock; -import java.time.Duration; -import java.util.HexFormat; -import java.util.Map; - -/** Fail-closed detached two-person Ed25519 approval verifier. */ -// The adoption verifier remains active until data/API migration is complete. -@SuppressWarnings("deprecation") -public final class Ed25519LegacyAdoptionApprovalVerifier - implements LegacyObjectAdoptionApprovalVerifierPort { - - private final LegacyAdoptionApprovalCodec codec; - private final Map trustedApprovers; - private final Clock clock; - private final Duration maximumValidity; - - public Ed25519LegacyAdoptionApprovalVerifier( - LegacyAdoptionApprovalCodec codec, - Map trustedApprovers, - Clock clock, - Duration maximumValidity) { - this.codec = codec; - this.trustedApprovers = Map.copyOf(trustedApprovers); - this.clock = clock; - this.maximumValidity = maximumValidity; - if (maximumValidity == null - || maximumValidity.isZero() - || maximumValidity.isNegative() - || maximumValidity.compareTo(Duration.ofDays(7)) > 0) { - throw new IllegalArgumentException("legacy adoption approval validity is invalid"); - } - } - - @Override - public LegacyObjectAdoptionApproval verify( - byte[] canonicalApprovalDocument, LegacyObjectAdoptionRequest expectedRequest) { - LegacyAdoptionApprovalDocument document = codec.decode(canonicalApprovalDocument); - if (document.schemaVersion() != 1 - || document.firstApproverKeyId().equals(document.secondApproverKeyId()) - || !document.manifestSha256().equals(expectedRequest.manifestSha256()) - || !document.legacyNamespaceDigest().equals(expectedRequest.legacyNamespaceDigest()) - || !document.targetNamespaceDigest().equals(expectedRequest.targetNamespaceDigest()) - || !document - .destination() - .equals(expectedRequest.publicationRequest().operationKey().destination().value()) - || !document - .operationEpoch() - .equals(expectedRequest.publicationRequest().operationKey().epoch().value()) - || !document - .operationId() - .equals(expectedRequest.publicationRequest().operationKey().operationId().value()) - || clock.instant().isBefore(document.notBefore()) - || !clock.instant().isBefore(document.expiresAt()) - || Duration.between(document.notBefore(), document.expiresAt()).compareTo(maximumValidity) - > 0) { - throw rejected(); - } - byte[] payload = codec.signingPayload(document); - verifySignature(document.firstApproverKeyId(), document.firstSignature(), payload); - verifySignature(document.secondApproverKeyId(), document.secondSignature(), payload); - ObjectOperationKey operation = - new ObjectOperationKey( - ObjectDestinationId.of(document.destination()), - ObjectOperationEpoch.of(document.operationEpoch()), - ObjectOperationId.of(document.operationId())); - return new LegacyObjectAdoptionApproval( - operation, - document.manifestSha256(), - document.legacyNamespaceDigest(), - ObjectDestinationId.of(document.destination()), - document.targetNamespaceDigest(), - document.notBefore(), - document.expiresAt(), - document.nonce(), - sha256Hex(canonicalApprovalDocument)); - } - - private void verifySignature(String keyId, byte[] signature, byte[] payload) { - PublicKey key = trustedApprovers.get(keyId); - if (key == null) { - throw rejected(); - } - try { - Signature verifier = Signature.getInstance("Ed25519"); - verifier.initVerify(key); - verifier.update(payload); - if (!verifier.verify(signature)) { - throw rejected(); - } - } catch (GeneralSecurityException exception) { - throw new IllegalArgumentException("legacy adoption approval is rejected", exception); - } - } - - private static String sha256Hex(byte[] value) { - try { - return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); - } catch (GeneralSecurityException exception) { - throw new IllegalStateException("SHA-256 must be available", exception); - } - } - - private static IllegalArgumentException rejected() { - return new IllegalArgumentException("legacy adoption approval is rejected"); - } -} diff --git a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/maintenance/LegacyAdoptionApprovalCodec.java b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/maintenance/LegacyAdoptionApprovalCodec.java deleted file mode 100644 index 4332c6cc..00000000 --- a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/maintenance/LegacyAdoptionApprovalCodec.java +++ /dev/null @@ -1,169 +0,0 @@ -package dev.caskeleton.adapter.outbound.objectstorage.maintenance; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.EOFException; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.time.Instant; -import java.util.Arrays; - -/** Strict JDK-only length-prefixed canonical binary codec. */ -public final class LegacyAdoptionApprovalCodec { - - private static final int MAXIMUM_DOCUMENT_BYTES = 64 * 1024; - private static final int MAXIMUM_FIELD_BYTES = 1024; - private static final int MAXIMUM_SIGNATURE_BYTES = 256; - - public byte[] signingPayload(LegacyAdoptionApprovalDocument document) { - return write( - output -> { - output.writeInt(document.schemaVersion()); - string(output, document.destination()); - string(output, document.operationEpoch()); - string(output, document.operationId()); - string(output, document.manifestSha256()); - string(output, document.legacyNamespaceDigest()); - string(output, document.targetNamespaceDigest()); - string(output, "APPLY"); - output.writeLong(document.notBefore().toEpochMilli()); - output.writeLong(document.expiresAt().toEpochMilli()); - string(output, document.nonce()); - string(output, document.firstApproverKeyId()); - string(output, document.secondApproverKeyId()); - }); - } - - public byte[] encode(LegacyAdoptionApprovalDocument document) { - byte[] payload = signingPayload(document); - byte[] encoded = - write( - output -> { - bytes(output, payload, MAXIMUM_DOCUMENT_BYTES); - bytes(output, document.firstSignature(), MAXIMUM_SIGNATURE_BYTES); - bytes(output, document.secondSignature(), MAXIMUM_SIGNATURE_BYTES); - }); - if (encoded.length > MAXIMUM_DOCUMENT_BYTES) { - throw invalid(); - } - return encoded; - } - - public LegacyAdoptionApprovalDocument decode(byte[] encoded) { - if (encoded == null || encoded.length == 0 || encoded.length > MAXIMUM_DOCUMENT_BYTES) { - throw invalid(); - } - try { - DataInputStream document = new DataInputStream(new ByteArrayInputStream(encoded)); - byte[] payload = bytes(document, MAXIMUM_DOCUMENT_BYTES); - byte[] firstSignature = bytes(document, MAXIMUM_SIGNATURE_BYTES); - byte[] secondSignature = bytes(document, MAXIMUM_SIGNATURE_BYTES); - if (document.read() != -1) { - throw invalid(); - } - DataInputStream input = new DataInputStream(new ByteArrayInputStream(payload)); - int schema = input.readInt(); - String destination = string(input); - String epoch = string(input); - String operation = string(input); - String manifest = string(input); - String legacyNamespace = string(input); - String targetNamespace = string(input); - if (!"APPLY".equals(string(input))) { - throw invalid(); - } - Instant notBefore = Instant.ofEpochMilli(input.readLong()); - Instant expiresAt = Instant.ofEpochMilli(input.readLong()); - String nonce = string(input); - String firstKey = string(input); - String secondKey = string(input); - if (input.read() != -1) { - throw invalid(); - } - LegacyAdoptionApprovalDocument decoded = - new LegacyAdoptionApprovalDocument( - schema, - destination, - epoch, - operation, - manifest, - legacyNamespace, - targetNamespace, - notBefore, - expiresAt, - nonce, - firstKey, - secondKey, - firstSignature, - secondSignature); - if (!Arrays.equals(encoded, encode(decoded))) { - throw invalid(); - } - return decoded; - } catch (IOException | RuntimeException exception) { - if (exception instanceof IllegalArgumentException illegal) { - throw illegal; - } - throw new IllegalArgumentException("legacy adoption approval document is invalid", exception); - } - } - - private static byte[] write(IoConsumer writer) { - try { - ByteArrayOutputStream bytes = new ByteArrayOutputStream(); - try (DataOutputStream output = new DataOutputStream(bytes)) { - writer.accept(output); - } - return bytes.toByteArray(); - } catch (IOException exception) { - throw new IllegalStateException("in-memory approval encoding failed", exception); - } - } - - private static void string(DataOutputStream output, String value) throws IOException { - if (value == null) { - throw invalid(); - } - bytes(output, value.getBytes(StandardCharsets.UTF_8), MAXIMUM_FIELD_BYTES); - } - - private static String string(DataInputStream input) throws IOException { - byte[] bytes = bytes(input, MAXIMUM_FIELD_BYTES); - String value = new String(bytes, StandardCharsets.UTF_8); - if (!Arrays.equals(bytes, value.getBytes(StandardCharsets.UTF_8))) { - throw invalid(); - } - return value; - } - - private static void bytes(DataOutputStream output, byte[] value, int maximum) throws IOException { - if (value == null || value.length == 0 || value.length > maximum) { - throw invalid(); - } - output.writeInt(value.length); - output.write(value); - } - - private static byte[] bytes(DataInputStream input, int maximum) throws IOException { - int length = input.readInt(); - if (length < 1 || length > maximum) { - throw invalid(); - } - byte[] value = input.readNBytes(length); - if (value.length != length) { - throw new EOFException("approval field is truncated"); - } - return value; - } - - private static IllegalArgumentException invalid() { - return new IllegalArgumentException("legacy adoption approval document is invalid"); - } - - @FunctionalInterface - private interface IoConsumer { - void accept(T value) throws IOException; - } -} diff --git a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/maintenance/LegacyAdoptionApprovalDocument.java b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/maintenance/LegacyAdoptionApprovalDocument.java deleted file mode 100644 index a96a2a89..00000000 --- a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/maintenance/LegacyAdoptionApprovalDocument.java +++ /dev/null @@ -1,112 +0,0 @@ -package dev.caskeleton.adapter.outbound.objectstorage.maintenance; - -import java.time.Instant; -import java.util.Arrays; - -/** Detached canonical two-signature approval document for reviewed APPLY execution. */ -public final class LegacyAdoptionApprovalDocument { - - private final int schemaVersion; - private final String destination; - private final String operationEpoch; - private final String operationId; - private final String manifestSha256; - private final String legacyNamespaceDigest; - private final String targetNamespaceDigest; - private final Instant notBefore; - private final Instant expiresAt; - private final String nonce; - private final String firstApproverKeyId; - private final String secondApproverKeyId; - private final byte[] firstSignature; - private final byte[] secondSignature; - - public LegacyAdoptionApprovalDocument( - int schemaVersion, - String destination, - String operationEpoch, - String operationId, - String manifestSha256, - String legacyNamespaceDigest, - String targetNamespaceDigest, - Instant notBefore, - Instant expiresAt, - String nonce, - String firstApproverKeyId, - String secondApproverKeyId, - byte[] firstSignature, - byte[] secondSignature) { - this.schemaVersion = schemaVersion; - this.destination = destination; - this.operationEpoch = operationEpoch; - this.operationId = operationId; - this.manifestSha256 = manifestSha256; - this.legacyNamespaceDigest = legacyNamespaceDigest; - this.targetNamespaceDigest = targetNamespaceDigest; - this.notBefore = notBefore; - this.expiresAt = expiresAt; - this.nonce = nonce; - this.firstApproverKeyId = firstApproverKeyId; - this.secondApproverKeyId = secondApproverKeyId; - this.firstSignature = - firstSignature == null ? null : Arrays.copyOf(firstSignature, firstSignature.length); - this.secondSignature = - secondSignature == null ? null : Arrays.copyOf(secondSignature, secondSignature.length); - } - - public int schemaVersion() { - return schemaVersion; - } - - public String destination() { - return destination; - } - - public String operationEpoch() { - return operationEpoch; - } - - public String operationId() { - return operationId; - } - - public String manifestSha256() { - return manifestSha256; - } - - public String legacyNamespaceDigest() { - return legacyNamespaceDigest; - } - - public String targetNamespaceDigest() { - return targetNamespaceDigest; - } - - public Instant notBefore() { - return notBefore; - } - - public Instant expiresAt() { - return expiresAt; - } - - public String nonce() { - return nonce; - } - - public String firstApproverKeyId() { - return firstApproverKeyId; - } - - public String secondApproverKeyId() { - return secondApproverKeyId; - } - - public byte[] firstSignature() { - return firstSignature == null ? null : Arrays.copyOf(firstSignature, firstSignature.length); - } - - public byte[] secondSignature() { - return secondSignature == null ? null : Arrays.copyOf(secondSignature, secondSignature.length); - } -} diff --git a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/maintenance/LegacyAdoptionApprovalReplayRecord.java b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/maintenance/LegacyAdoptionApprovalReplayRecord.java deleted file mode 100644 index 9c19cf8a..00000000 --- a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/maintenance/LegacyAdoptionApprovalReplayRecord.java +++ /dev/null @@ -1,39 +0,0 @@ -package dev.caskeleton.adapter.outbound.objectstorage.maintenance; - -import dev.caskeleton.application.objectstorage.identity.ObjectOperationKey; -import java.time.Instant; - -/** Durable nonce binding; no raw locator or provider location may enter this record. */ -public record LegacyAdoptionApprovalReplayRecord( - String nonce, - ObjectOperationKey operationKey, - String manifestSha256, - String namespaceBindingDigest, - String approvalDigest, - State state, - Instant updatedAt, - long revision) { - - public LegacyAdoptionApprovalReplayRecord { - if (nonce == null - || !nonce.matches("[A-Za-z0-9_-]{16,128}") - || operationKey == null - || !hex64(manifestSha256) - || !hex64(namespaceBindingDigest) - || !hex64(approvalDigest) - || state == null - || updatedAt == null - || revision < 0) { - throw new IllegalArgumentException("legacy adoption replay record is invalid"); - } - } - - public enum State { - CLAIMED, - TERMINAL - } - - private static boolean hex64(String value) { - return value != null && value.matches("[0-9a-f]{64}"); - } -} diff --git a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/maintenance/LegacyAdoptionApprovalReplayStore.java b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/maintenance/LegacyAdoptionApprovalReplayStore.java deleted file mode 100644 index 83b67717..00000000 --- a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/maintenance/LegacyAdoptionApprovalReplayStore.java +++ /dev/null @@ -1,16 +0,0 @@ -package dev.caskeleton.adapter.outbound.objectstorage.maintenance; - -/** Durable compare-and-set nonce replay boundary. */ -public interface LegacyAdoptionApprovalReplayStore { - - ClaimResult claim(LegacyAdoptionApprovalReplayRecord proposed); - - void markTerminal( - String nonce, long expectedRevision, LegacyAdoptionApprovalReplayRecord terminal); - - enum ClaimResult { - CLAIMED, - EXACT_REPLAY, - TERMINAL_REPLAY - } -} diff --git a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/maintenance/LegacyObjectAdoptionService.java b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/maintenance/LegacyObjectAdoptionService.java deleted file mode 100644 index 93dc1eba..00000000 --- a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/maintenance/LegacyObjectAdoptionService.java +++ /dev/null @@ -1,122 +0,0 @@ -package dev.caskeleton.adapter.outbound.objectstorage.maintenance; - -import dev.caskeleton.application.objectstorage.model.ObjectMutationOutcome; -import dev.caskeleton.application.objectstorage.port.ManagedObjectPublicationPort; -import dev.caskeleton.application.storage.migration.LegacyObjectAdoptionApproval; -import dev.caskeleton.application.storage.migration.LegacyObjectAdoptionPort; -import dev.caskeleton.application.storage.migration.LegacyObjectAdoptionReceipt; -import dev.caskeleton.application.storage.migration.LegacyObjectAdoptionRequest; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.time.Clock; -import java.util.HexFormat; - -/** Report-first legacy inspection and reviewed, operation-keyed adoption apply. */ -// The adoption mechanism remains active until data/API migration is complete. -@SuppressWarnings("deprecation") -public final class LegacyObjectAdoptionService implements LegacyObjectAdoptionPort { - - private final LegacyObjectInspector inspector; - private final ManagedObjectPublicationPort publications; - private final LegacyAdoptionApprovalReplayStore replayStore; - private final Clock clock; - - public LegacyObjectAdoptionService( - LegacyObjectInspector inspector, - ManagedObjectPublicationPort publications, - LegacyAdoptionApprovalReplayStore replayStore, - Clock clock) { - this.inspector = inspector; - this.publications = publications; - this.replayStore = replayStore; - this.clock = clock; - } - - @Override - public LegacyObjectAdoptionReceipt adopt(LegacyObjectAdoptionRequest request) { - LegacyObjectInspection inspected = inspector.inspect(request.locator()); - if (!inspected.contentIdentity().equals(request.publicationRequest().contentIdentity()) - || !inspected.mediaType().equals(request.publicationRequest().declaredMediaType())) { - throw new IllegalArgumentException("legacy object differs from the reviewed manifest"); - } - if (request.mode() == LegacyObjectAdoptionRequest.Mode.REPORT_ONLY) { - return new LegacyObjectAdoptionReceipt( - request.publicationRequest().operationKey(), - inspected.contentIdentity(), - inspected.mediaType(), - inspected.exactVersion(), - null, - null, - ObjectMutationOutcome.NO_CHANGE, - clock.instant()); - } - - LegacyObjectAdoptionApproval approval = requireApproval(request); - String namespaceBinding = - sha256Hex(request.legacyNamespaceDigest() + ":" + request.targetNamespaceDigest()); - LegacyAdoptionApprovalReplayRecord replay = - new LegacyAdoptionApprovalReplayRecord( - approval.nonce(), - approval.operationKey(), - approval.manifestSha256(), - namespaceBinding, - approval.approvalDigest(), - LegacyAdoptionApprovalReplayRecord.State.CLAIMED, - clock.instant(), - 0); - LegacyAdoptionApprovalReplayStore.ClaimResult claim = replayStore.claim(replay); - var published = publications.publish(request.publicationRequest(), inspected.producer()); - if (claim != LegacyAdoptionApprovalReplayStore.ClaimResult.TERMINAL_REPLAY) { - replayStore.markTerminal( - replay.nonce(), - replay.revision(), - new LegacyAdoptionApprovalReplayRecord( - replay.nonce(), - replay.operationKey(), - replay.manifestSha256(), - replay.namespaceBindingDigest(), - replay.approvalDigest(), - LegacyAdoptionApprovalReplayRecord.State.TERMINAL, - clock.instant(), - replay.revision() + 1)); - } - return new LegacyObjectAdoptionReceipt( - published.operationKey(), - published.contentIdentity(), - published.mediaType(), - inspected.exactVersion(), - published.reference(), - published.exactVersion(), - published.outcome(), - published.appliedAt()); - } - - private LegacyObjectAdoptionApproval requireApproval(LegacyObjectAdoptionRequest request) { - LegacyObjectAdoptionApproval approval = request.approval(); - if (approval == null - || !approval.operationKey().equals(request.publicationRequest().operationKey()) - || !approval.manifestSha256().equals(request.manifestSha256()) - || !approval.legacyNamespaceDigest().equals(request.legacyNamespaceDigest()) - || !approval - .targetDestination() - .equals(request.publicationRequest().operationKey().destination()) - || !approval.targetNamespaceDigest().equals(request.targetNamespaceDigest()) - || clock.instant().isBefore(approval.notBefore()) - || !clock.instant().isBefore(approval.expiresAt())) { - throw new IllegalArgumentException( - "legacy adoption approval does not authorize this request"); - } - return approval; - } - - private static String sha256Hex(String value) { - try { - return HexFormat.of() - .formatHex( - MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8))); - } catch (NoSuchAlgorithmException exception) { - throw new IllegalStateException("SHA-256 must be available", exception); - } - } -} diff --git a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/maintenance/LegacyObjectInspection.java b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/maintenance/LegacyObjectInspection.java deleted file mode 100644 index e11be710..00000000 --- a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/maintenance/LegacyObjectInspection.java +++ /dev/null @@ -1,20 +0,0 @@ -package dev.caskeleton.adapter.outbound.objectstorage.maintenance; - -import dev.caskeleton.application.objectstorage.content.ObjectContentProducer; -import dev.caskeleton.application.objectstorage.identity.ObjectVersionToken; -import dev.caskeleton.application.objectstorage.model.ObjectContentIdentity; -import dev.caskeleton.application.objectstorage.model.ObjectMediaType; - -/** Exact immutable inspection result; the raw locator is deliberately absent. */ -public record LegacyObjectInspection( - ObjectContentIdentity contentIdentity, - ObjectMediaType mediaType, - ObjectVersionToken exactVersion, - ObjectContentProducer producer) { - - public LegacyObjectInspection { - if (contentIdentity == null || mediaType == null || exactVersion == null || producer == null) { - throw new IllegalArgumentException("legacy object inspection is incomplete"); - } - } -} diff --git a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/maintenance/LegacyObjectInspector.java b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/maintenance/LegacyObjectInspector.java deleted file mode 100644 index d518feee..00000000 --- a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/maintenance/LegacyObjectInspector.java +++ /dev/null @@ -1,12 +0,0 @@ -package dev.caskeleton.adapter.outbound.objectstorage.maintenance; - -import dev.caskeleton.application.storage.migration.LegacyObjectLocator; - -/** Privileged legacy namespace reader used only by explicit migration composition. */ -@FunctionalInterface -// The adoption mechanism remains active until data/API migration is complete. -@SuppressWarnings("deprecation") -public interface LegacyObjectInspector { - - LegacyObjectInspection inspect(LegacyObjectLocator locator); -} diff --git a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/readiness/ObjectStorageCapabilityCard.java b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/readiness/ObjectStorageCapabilityCard.java deleted file mode 100644 index 354ba7ec..00000000 --- a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/readiness/ObjectStorageCapabilityCard.java +++ /dev/null @@ -1,41 +0,0 @@ -package dev.caskeleton.adapter.outbound.objectstorage.readiness; - -import java.util.Arrays; -import java.util.Set; -import java.util.stream.Collectors; - -/** Frozen object-storage capability-card identities; no module-wide readiness card exists. */ -public enum ObjectStorageCapabilityCard { - MANAGED_UPLOAD_SINGLE("object-storage-managed-upload-single"), - MANAGED_UPLOAD_MULTIPART("object-storage-managed-upload-multipart"), - MANAGED_DOWNLOAD("object-storage-managed-download"), - DIRECT_UPLOAD_SINGLE("object-storage-direct-upload-single"), - DIRECT_UPLOAD_MULTIPART("object-storage-direct-upload-multipart"), - DIRECT_DOWNLOAD("object-storage-direct-download"), - QUARANTINE_PUBLICATION("object-storage-quarantine-publication"), - RETENTION("object-storage-retention"), - RECONCILIATION("object-storage-reconciliation"); - - private final String cardId; - - ObjectStorageCapabilityCard(String cardId) { - this.cardId = cardId; - } - - public String cardId() { - return cardId; - } - - public static ObjectStorageCapabilityCard parse(String cardId) { - return Arrays.stream(values()) - .filter(candidate -> candidate.cardId.equals(cardId)) - .findFirst() - .orElseThrow(() -> new IllegalArgumentException("unknown object-storage capability card")); - } - - public static Set cardIds() { - return Arrays.stream(values()) - .map(ObjectStorageCapabilityCard::cardId) - .collect(Collectors.toUnmodifiableSet()); - } -} diff --git a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/readiness/ObjectStorageCapabilityEvidence.java b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/readiness/ObjectStorageCapabilityEvidence.java deleted file mode 100644 index 55e5092e..00000000 --- a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/readiness/ObjectStorageCapabilityEvidence.java +++ /dev/null @@ -1,71 +0,0 @@ -package dev.caskeleton.adapter.outbound.objectstorage.readiness; - -import java.time.LocalDate; -import java.util.List; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; - -/** One exact, bounded readiness claim validated against live provider/task registries. */ -public record ObjectStorageCapabilityEvidence( - ObjectStorageCapabilityCard card, - String providerType, - String providerVersion, - String destinationProfile, - ObjectStorageReadinessLevel claimedLevel, - String evidenceRevision, - Optional evidenceExpiresOn, - List requiredTasks, - List limitations) { - - public ObjectStorageCapabilityEvidence { - Objects.requireNonNull(card, "card must be non-null"); - Objects.requireNonNull(claimedLevel, "claimedLevel must be non-null"); - Objects.requireNonNull(evidenceExpiresOn, "evidenceExpiresOn must be non-null"); - requiredTasks = List.copyOf(Objects.requireNonNull(requiredTasks, "requiredTasks")); - limitations = List.copyOf(Objects.requireNonNull(limitations, "limitations")); - } - - public void validate(Set knownProviders, Set availableTasks) { - Objects.requireNonNull(knownProviders, "knownProviders must be non-null"); - Objects.requireNonNull(availableTasks, "availableTasks must be non-null"); - requireToken("provider type", providerType); - requireToken("provider version", providerVersion); - requireToken("destination profile", destinationProfile); - requireToken("evidence revision", evidenceRevision); - if (!knownProviders.contains(providerType)) { - throw invalid("unknown provider"); - } - if ("filesystem-local-dev".equals(providerType) - && (claimedLevel == ObjectStorageReadinessLevel.R2 - || claimedLevel == ObjectStorageReadinessLevel.R3)) { - throw invalid("filesystem-local-dev cannot claim above R1"); - } - if (requiredTasks.isEmpty() - || requiredTasks.stream().anyMatch(task -> !availableTasks.contains(task))) { - throw invalid("required readiness task is absent"); - } - if (limitations.isEmpty() - || limitations.stream().anyMatch(value -> value == null || value.isBlank())) { - throw invalid("provider limitations must be explicit"); - } - if ((claimedLevel == ObjectStorageReadinessLevel.R2 - || claimedLevel == ObjectStorageReadinessLevel.R3) - && evidenceExpiresOn.isEmpty()) { - throw invalid("R2/R3 evidence requires an expiry"); - } - } - - private static void requireToken(String label, String value) { - if (value == null - || value.isBlank() - || value.length() > 128 - || !value.matches("[a-zA-Z0-9][a-zA-Z0-9._:/-]*")) { - throw invalid(label + " is invalid"); - } - } - - private static IllegalArgumentException invalid(String message) { - return new IllegalArgumentException("object-storage readiness claim is invalid: " + message); - } -} diff --git a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/readiness/ObjectStorageReadinessLevel.java b/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/readiness/ObjectStorageReadinessLevel.java deleted file mode 100644 index 8f6f807c..00000000 --- a/src/adapter/outbound/objectstorage/src/main/java/dev/caskeleton/adapter/outbound/objectstorage/readiness/ObjectStorageReadinessLevel.java +++ /dev/null @@ -1,9 +0,0 @@ -package dev.caskeleton.adapter.outbound.objectstorage.readiness; - -/** Evidence maturity for one exact capability/provider/version/destination-profile tuple. */ -public enum ObjectStorageReadinessLevel { - R0, - R1, - R2, - R3 -} diff --git a/src/adapter/outbound/objectstorage/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/src/adapter/outbound/objectstorage/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports new file mode 100644 index 00000000..788b03d7 --- /dev/null +++ b/src/adapter/outbound/objectstorage/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports @@ -0,0 +1 @@ +dev.caskeleton.adapter.outbound.objectstorage.ObjectStorageAutoConfiguration diff --git a/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/ObjectStorageAutoConfigurationTest.java b/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/ObjectStorageAutoConfigurationTest.java new file mode 100644 index 00000000..d79c9d2b --- /dev/null +++ b/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/ObjectStorageAutoConfigurationTest.java @@ -0,0 +1,89 @@ +package dev.caskeleton.adapter.outbound.objectstorage; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.adapter.outbound.objectstorage.config.ObjectStorageCapabilitySettings; +import dev.caskeleton.application.objectstorage.port.ManagedObjectPublicationPort; +import dev.caskeleton.application.storage.ObjectStoragePort; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; + +/** Object storage reaches an application through its own auto-configuration entry, and only it. */ +class ObjectStorageAutoConfigurationTest { + + private final ApplicationContextRunner runner = + new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(ObjectStorageAutoConfiguration.class)); + + @TempDir Path root; + + @Test + void theRootIsRegisteredInTheModulesOwnImportsFile() throws IOException { + try (InputStream imports = + getClass() + .getClassLoader() + .getResourceAsStream( + "META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports")) { + assertThat(imports).isNotNull(); + assertThat(new String(imports.readAllBytes(), StandardCharsets.UTF_8)) + .contains(ObjectStorageAutoConfiguration.class.getName()); + } + } + + @Test + void presentWithoutTheSwitchIsOn() { + runner + .withPropertyValues(localDestination(root)) + .run(context -> assertThat(context).hasSingleBean(ManagedObjectPublicationPort.class)); + } + + @Test + void switchedOffHoldsNothingIncludingItsSettings() { + runner + .withPropertyValues("app.object-storage.enabled=false") + .withPropertyValues(localDestination(root)) + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context).doesNotHaveBean(ObjectStorageCapabilitySettings.class); + assertThat(context).doesNotHaveBean(ManagedObjectPublicationPort.class); + }); + } + + @Test + @SuppressWarnings("removal") + void theExplicitLegacySeamStillAssemblesWithTheCapabilityOff() { + runner + .withPropertyValues( + "app.object-storage.enabled=false", + "app.object-storage.legacy.enabled=true", + "app.object-storage.legacy.backend=filesystem", + "app.object-storage.legacy.base-path=" + root) + .run( + context -> { + assertThat(context).hasSingleBean(ObjectStoragePort.class); + assertThat(context).doesNotHaveBean(ManagedObjectPublicationPort.class); + }); + } + + private static String[] localDestination(Path root) { + return new String[] { + "app.object-storage.default-destination=poster", + "app.object-storage.providers.local.type=filesystem-local-dev", + "app.object-storage.providers.local.version=jdk-21", + "app.object-storage.providers.local.root=" + root, + "app.object-storage.providers.local.maximum-object-bytes=1KB", + "app.object-storage.providers.local.chunk-bytes=64B", + "app.object-storage.destinations.poster.provider-ref=local", + "app.object-storage.destinations.poster.route-token=0123456789ab", + "app.object-storage.destinations.poster.binding-revision=binding-v1", + "app.object-storage.destinations.poster.policy-revision=policy-v1" + }; + } +} diff --git a/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/config/ObjectStorageEnvManifestTest.java b/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/config/ObjectStorageEnvManifestTest.java index 204fd710..c6d75846 100644 --- a/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/config/ObjectStorageEnvManifestTest.java +++ b/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/config/ObjectStorageEnvManifestTest.java @@ -30,7 +30,6 @@ class ObjectStorageEnvManifestTest { Set expected = new TreeSet<>(); collectRecord(ObjectStorageCapabilitySettings.class, "", expected); - collectRecord(LegacyObjectAdoptionSettings.class, "legacy-adoption", expected); expected.add("scan-maintenance.enabled"); assertThat(manifest.keySet()).containsExactlyInAnyOrderElementsOf(expected); diff --git a/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/config/ObjectStorageLegacyMigrationConfigTest.java b/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/config/ObjectStorageLegacyMigrationConfigTest.java deleted file mode 100644 index 4effeb8c..00000000 --- a/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/config/ObjectStorageLegacyMigrationConfigTest.java +++ /dev/null @@ -1,66 +0,0 @@ -package dev.caskeleton.adapter.outbound.objectstorage.config; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; - -import dev.caskeleton.adapter.outbound.objectstorage.maintenance.LegacyAdoptionApprovalReplayStore; -import dev.caskeleton.adapter.outbound.objectstorage.maintenance.LegacyObjectInspector; -import dev.caskeleton.application.objectstorage.port.ManagedObjectPublicationPort; -import dev.caskeleton.application.storage.migration.LegacyObjectAdoptionPort; -import java.time.Clock; -import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.runner.ApplicationContextRunner; - -// This named adoption wiring suite remains until data/API migration completes. -@SuppressWarnings("deprecation") -class ObjectStorageLegacyMigrationConfigTest { - - @Test - void normalDisabledContextExposesNoRawLocatorPort() { - new ApplicationContextRunner() - .withUserConfiguration(ObjectStorageLegacyMigrationConfig.class) - .withPropertyValues("app.object-storage.legacy-adoption.enabled=false") - .run(context -> assertThat(context).doesNotHaveBean(LegacyObjectAdoptionPort.class)); - } - - @Test - void explicitReportOnlyMaintenanceCompositionCreatesOnePort() { - new ApplicationContextRunner() - .withUserConfiguration(ObjectStorageLegacyMigrationConfig.class) - .withBean(LegacyObjectInspector.class, () -> mock(LegacyObjectInspector.class)) - .withBean( - ManagedObjectPublicationPort.class, () -> mock(ManagedObjectPublicationPort.class)) - .withBean( - LegacyAdoptionApprovalReplayStore.class, - () -> mock(LegacyAdoptionApprovalReplayStore.class)) - .withBean(Clock.class, Clock::systemUTC) - .withPropertyValues( - "app.object-storage.legacy-adoption.enabled=true", - "app.object-storage.legacy-adoption.mode=REPORT_ONLY", - "app.object-storage.legacy-adoption.report-path=build/adoption-report.json", - "app.object-storage.legacy-adoption.batch-size=10") - .run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context).hasSingleBean(LegacyObjectAdoptionPort.class); - }); - } - - @Test - void applyWithoutReviewedManifestFailsClosed() { - new ApplicationContextRunner() - .withUserConfiguration(ObjectStorageLegacyMigrationConfig.class) - .withBean(LegacyObjectInspector.class, () -> mock(LegacyObjectInspector.class)) - .withBean( - ManagedObjectPublicationPort.class, () -> mock(ManagedObjectPublicationPort.class)) - .withBean( - LegacyAdoptionApprovalReplayStore.class, - () -> mock(LegacyAdoptionApprovalReplayStore.class)) - .withBean(Clock.class, Clock::systemUTC) - .withPropertyValues( - "app.object-storage.legacy-adoption.enabled=true", - "app.object-storage.legacy-adoption.mode=APPLY", - "app.object-storage.legacy-adoption.report-path=build/adoption-report.json") - .run(context -> assertThat(context).hasFailed()); - } -} diff --git a/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/maintenance/LegacyAdoptionApprovalVerifierTest.java b/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/maintenance/LegacyAdoptionApprovalVerifierTest.java deleted file mode 100644 index 4e1d4286..00000000 --- a/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/maintenance/LegacyAdoptionApprovalVerifierTest.java +++ /dev/null @@ -1,145 +0,0 @@ -package dev.caskeleton.adapter.outbound.objectstorage.maintenance; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -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.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 dev.caskeleton.application.objectstorage.request.ObjectPublishRequest; -import dev.caskeleton.application.outbound.CallBudget; -import dev.caskeleton.application.storage.migration.LegacyObjectAdoptionRequest; -import dev.caskeleton.application.storage.migration.LegacyObjectLocator; -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.Signature; -import java.time.Clock; -import java.time.Duration; -import java.time.Instant; -import java.time.ZoneOffset; -import java.util.EnumSet; -import java.util.Map; -import org.junit.jupiter.api.Test; - -// This named adoption verifier suite remains until data/API migration completes. -@SuppressWarnings("deprecation") -class LegacyAdoptionApprovalVerifierTest { - - private static final Instant NOW = Instant.parse("2026-07-29T00:00:00Z"); - private static final String HEX_A = "a".repeat(64); - private static final String HEX_B = "b".repeat(64); - private static final String HEX_C = "c".repeat(64); - - @Test - void verifiesCanonicalExactBindingWithTwoDistinctTrustedApprovers() throws Exception { - KeyPair first = KeyPairGenerator.getInstance("Ed25519").generateKeyPair(); - KeyPair second = KeyPairGenerator.getInstance("Ed25519").generateKeyPair(); - LegacyAdoptionApprovalCodec codec = new LegacyAdoptionApprovalCodec(); - LegacyObjectAdoptionRequest request = request(); - LegacyAdoptionApprovalDocument unsigned = - document("approver-a", "approver-b", new byte[64], new byte[64]); - byte[] payload = codec.signingPayload(unsigned); - LegacyAdoptionApprovalDocument signed = - document("approver-a", "approver-b", sign(first, payload), sign(second, payload)); - byte[] encoded = codec.encode(signed); - - var verifier = - new Ed25519LegacyAdoptionApprovalVerifier( - codec, - Map.of( - "approver-a", first.getPublic(), - "approver-b", second.getPublic()), - Clock.fixed(NOW, ZoneOffset.UTC), - Duration.ofHours(1)); - var approval = verifier.verify(encoded, request); - - assertThat(approval.operationKey()).isEqualTo(request.publicationRequest().operationKey()); - assertThat(approval.manifestSha256()).isEqualTo(HEX_A); - assertThat(approval.approvalDigest()).matches("[0-9a-f]{64}"); - } - - @Test - void rejectsDuplicateApproverAndAnyBindingTamper() throws Exception { - KeyPair first = KeyPairGenerator.getInstance("Ed25519").generateKeyPair(); - LegacyAdoptionApprovalCodec codec = new LegacyAdoptionApprovalCodec(); - LegacyAdoptionApprovalDocument unsigned = - document("approver-a", "approver-a", new byte[64], new byte[64]); - byte[] signature = sign(first, codec.signingPayload(unsigned)); - byte[] encoded = codec.encode(document("approver-a", "approver-a", signature, signature)); - var verifier = - new Ed25519LegacyAdoptionApprovalVerifier( - codec, - Map.of("approver-a", first.getPublic()), - Clock.fixed(NOW, ZoneOffset.UTC), - Duration.ofHours(1)); - - assertThatThrownBy(() -> verifier.verify(encoded, request())) - .isInstanceOf(IllegalArgumentException.class); - - encoded[encoded.length - 1] ^= 1; - assertThatThrownBy(() -> verifier.verify(encoded, request())) - .isInstanceOf(IllegalArgumentException.class); - } - - private static LegacyAdoptionApprovalDocument document( - String firstKey, String secondKey, byte[] firstSignature, byte[] secondSignature) { - return new LegacyAdoptionApprovalDocument( - 1, - "poster", - "poster-image-v1", - "adoption-operation-1", - HEX_A, - HEX_B, - HEX_C, - NOW.minusSeconds(60), - NOW.plusSeconds(600), - "nonce-0123456789abcdef", - firstKey, - secondKey, - firstSignature, - secondSignature); - } - - private static byte[] sign(KeyPair key, byte[] payload) throws Exception { - Signature signer = Signature.getInstance("Ed25519"); - signer.initSign(key.getPrivate()); - signer.update(payload); - return signer.sign(); - } - - private static LegacyObjectAdoptionRequest request() { - return new LegacyObjectAdoptionRequest( - LegacyObjectLocator.of("legacy/posters/image.png"), - publishRequest(), - HEX_A, - HEX_B, - HEX_C, - LegacyObjectAdoptionRequest.Mode.APPLY, - null); - } - - private static ObjectPublishRequest publishRequest() { - return new ObjectPublishRequest( - new ObjectOperationKey( - ObjectDestinationId.of("poster"), - ObjectOperationEpoch.of("poster-image-v1"), - ObjectOperationId.of("adoption-operation-1")), - ObjectMediaType.of("image/png"), - new ObjectContentIdentity(3, ObjectDigest.sha256(new byte[] {1, 2, 3})), - ObjectPublicationRequirement.INTEGRITY_VERIFIED, - ObjectRetentionRequirement.NONE, - ObjectEncryptionRequirement.PROVIDER_MANAGED, - EnumSet.noneOf( - dev.caskeleton.application.objectstorage.model.ObjectCapabilityRequirement.class), - CallBudget.fromNow(Duration.ofSeconds(10)), - CancellationView.never()); - } -} diff --git a/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/maintenance/LegacyObjectAdoptionServiceTest.java b/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/maintenance/LegacyObjectAdoptionServiceTest.java deleted file mode 100644 index e062e3f3..00000000 --- a/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/maintenance/LegacyObjectAdoptionServiceTest.java +++ /dev/null @@ -1,109 +0,0 @@ -package dev.caskeleton.adapter.outbound.objectstorage.maintenance; - -import static org.assertj.core.api.Assertions.assertThat; - -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.identity.ObjectVersionToken; -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.ObjectRetentionRequirement; -import dev.caskeleton.application.objectstorage.request.ObjectPublishRequest; -import dev.caskeleton.application.outbound.CallBudget; -import dev.caskeleton.application.storage.migration.LegacyObjectAdoptionRequest; -import dev.caskeleton.application.storage.migration.LegacyObjectLocator; -import java.time.Clock; -import java.time.Duration; -import java.time.Instant; -import java.time.ZoneOffset; -import java.util.EnumSet; -import java.util.concurrent.atomic.AtomicInteger; -import org.junit.jupiter.api.Test; - -// This named adoption characterization suite remains until data/API migration completes. -@SuppressWarnings("deprecation") -class LegacyObjectAdoptionServiceTest { - - private static final Instant NOW = Instant.parse("2026-07-29T00:00:00Z"); - private static final ObjectContentIdentity CONTENT = - new ObjectContentIdentity(3, ObjectDigest.sha256(new byte[] {1, 2, 3})); - private static final ObjectVersionToken VERSION = - ObjectVersionToken.parse("osv1.0123456789ab.0123456789abcdefghjkmnpqrs.6678c6821f"); - - @Test - void reportOnlyInspectsExactEvidenceAndPerformsNoMutation() { - AtomicInteger publications = new AtomicInteger(); - AtomicInteger replays = new AtomicInteger(); - LegacyObjectLocator locator = LegacyObjectLocator.of("legacy/posters/private.png"); - LegacyObjectAdoptionService service = - new LegacyObjectAdoptionService( - ignored -> - new LegacyObjectInspection( - CONTENT, - ObjectMediaType.of("image/png"), - VERSION, - (context, sink) -> sink.write(new byte[] {1, 2, 3}, 0, 3)), - (request, producer) -> { - publications.incrementAndGet(); - throw new AssertionError("report mode must not publish"); - }, - new LegacyAdoptionApprovalReplayStore() { - @Override - public ClaimResult claim(LegacyAdoptionApprovalReplayRecord proposed) { - replays.incrementAndGet(); - return ClaimResult.CLAIMED; - } - - @Override - public void markTerminal( - String nonce, - long expectedRevision, - LegacyAdoptionApprovalReplayRecord terminal) { - throw new AssertionError("report mode must not mutate replay state"); - } - }, - Clock.fixed(NOW, ZoneOffset.UTC)); - - var receipt = - service.adopt( - new LegacyObjectAdoptionRequest( - locator, - publishRequest(), - "a".repeat(64), - "b".repeat(64), - "c".repeat(64), - LegacyObjectAdoptionRequest.Mode.REPORT_ONLY, - null)); - - assertThat(receipt.outcome()).isEqualTo(ObjectMutationOutcome.NO_CHANGE); - assertThat(receipt.contentIdentity()).isEqualTo(CONTENT); - assertThat(receipt.adoptedReference()).isNull(); - assertThat(locator.toString()).doesNotContain("legacy/posters"); - assertThat(publications).hasValue(0); - assertThat(replays).hasValue(0); - } - - private static ObjectPublishRequest publishRequest() { - return new ObjectPublishRequest( - new ObjectOperationKey( - ObjectDestinationId.of("poster"), - ObjectOperationEpoch.of("poster-image-v1"), - ObjectOperationId.of("adoption-operation-1")), - ObjectMediaType.of("image/png"), - CONTENT, - ObjectPublicationRequirement.INTEGRITY_VERIFIED, - ObjectRetentionRequirement.NONE, - ObjectEncryptionRequirement.PROVIDER_MANAGED, - EnumSet.noneOf( - dev.caskeleton.application.objectstorage.model.ObjectCapabilityRequirement.class), - CallBudget.fromNow(Duration.ofSeconds(10)), - CancellationView.never()); - } -} diff --git a/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/readiness/ObjectStorageReadinessRegistryTest.java b/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/readiness/ObjectStorageReadinessRegistryTest.java index 644ef8e9..72af3930 100644 --- a/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/readiness/ObjectStorageReadinessRegistryTest.java +++ b/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/readiness/ObjectStorageReadinessRegistryTest.java @@ -1,123 +1,202 @@ package dev.caskeleton.adapter.outbound.objectstorage.readiness; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.junit.jupiter.params.provider.Arguments.arguments; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.time.LocalDate; +import java.time.format.DateTimeParseException; +import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Optional; import java.util.Set; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import java.util.stream.Stream; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.yaml.snakeyaml.LoaderOptions; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.SafeConstructor; +/** + * Semantic owner of {@code docs/registries/object-storage-readiness.yaml}: every row names a known + * card, a deployable provider and an existing task, and claims no more than its evidence allows. + */ class ObjectStorageReadinessRegistryTest { + private static final Set ROW_KEYS = + Set.of( + "card_id", + "provider_type", + "provider_version", + "destination_profile", + "claimed_level", + "evidence_revision", + "evidence_expires_on", + "required_tasks", + "limitations"); + private static final List TOKEN_KEYS = + List.of("provider_type", "provider_version", "destination_profile", "evidence_revision"); + private static final Pattern TOKEN = Pattern.compile("[a-zA-Z0-9][a-zA-Z0-9._:/-]{0,127}"); + private static final Set LEVELS = Set.of("R0", "R1", "R2", "R3"); private static final Set AVAILABLE_TASKS = Set.of(":application-core:check", ":adapter:outbound:objectstorage:check"); private static final Set KNOWN_PROVIDERS = ObjectStorageDeploymentReadiness.providerTypes(); + private static final Map FROZEN_LEVELS = + Map.of( + "object-storage-managed-upload-single", "R1", + "object-storage-managed-upload-multipart", "R0", + "object-storage-managed-download", "R1", + "object-storage-direct-upload-single", "R0", + "object-storage-direct-upload-multipart", "R0", + "object-storage-direct-download", "R0", + "object-storage-quarantine-publication", "R0", + "object-storage-retention", "R0", + "object-storage-reconciliation", "R0"); @Test - void registryHasTheFrozenNineCardsAndOnlyEvidencedClaims() throws Exception { - Map registry = loadRegistry(); - assertThat(registry).containsOnlyKeys("schema_version", "claims"); - assertThat(registry.get("schema_version")).isEqualTo(1); + void everyRegistryRowIsEvidenced() throws Exception { + // given + List> rows = rows(); - List claims = claims(registry); - assertThat(claims) - .extracting(claim -> claim.card().cardId()) - .containsExactlyInAnyOrderElementsOf(ObjectStorageCapabilityCard.cardIds()); - assertThat(claims).allSatisfy(claim -> claim.validate(KNOWN_PROVIDERS, AVAILABLE_TASKS)); - assertThat(claims) - .filteredOn(claim -> claim.claimedLevel() == ObjectStorageReadinessLevel.R1) - .extracting(claim -> claim.card().cardId()) - .containsExactlyInAnyOrder( - "object-storage-managed-upload-single", "object-storage-managed-download"); - assertThat(claims) - .filteredOn( - claim -> - claim.card() == ObjectStorageCapabilityCard.DIRECT_UPLOAD_SINGLE - || claim.card() == ObjectStorageCapabilityCard.DIRECT_UPLOAD_MULTIPART - || claim.card() == ObjectStorageCapabilityCard.DIRECT_DOWNLOAD - || claim.card() == ObjectStorageCapabilityCard.QUARANTINE_PUBLICATION - || claim.card() == ObjectStorageCapabilityCard.RETENTION - || claim.card() == ObjectStorageCapabilityCard.RECONCILIATION) - .allMatch(claim -> claim.claimedLevel() == ObjectStorageReadinessLevel.R0); + // when + List found = rows.stream().flatMap(row -> problems(row).stream()).toList(); + + // then + assertThat(found).isEmpty(); } @Test - void validatorRejectsUnknownGlobalOrOverclaimedRows() { - assertThatIllegalArgumentException() - .isThrownBy(() -> ObjectStorageCapabilityCard.parse("objectstorage")); - assertThatIllegalArgumentException() - .isThrownBy(() -> ObjectStorageCapabilityCard.parse("object-storage-unknown")); + void registryHasTheFrozenNineCardsAtTheirLevels() throws Exception { + // given + List> rows = rows(); - ObjectStorageCapabilityEvidence missingIdentity = - evidence( - ObjectStorageCapabilityCard.MANAGED_UPLOAD_SINGLE, - ObjectStorageReadinessLevel.R1, - "", - "", - Optional.empty(), - List.of("bounded local stream")); - assertThatIllegalArgumentException() - .isThrownBy(() -> missingIdentity.validate(KNOWN_PROVIDERS, AVAILABLE_TASKS)); + // when + Map levels = + rows.stream() + .collect( + Collectors.toMap(row -> text(row, "card_id"), row -> text(row, "claimed_level"))); - ObjectStorageCapabilityEvidence expiredR2 = - evidence( - ObjectStorageCapabilityCard.MANAGED_UPLOAD_SINGLE, - ObjectStorageReadinessLevel.R2, - "filesystem-local-dev", - "local-managed-integrity", - Optional.empty(), - List.of("single-process only")); - assertThatIllegalArgumentException() - .isThrownBy(() -> expiredR2.validate(KNOWN_PROVIDERS, AVAILABLE_TASKS)); + // then + assertThat(levels).containsExactlyInAnyOrderEntriesOf(FROZEN_LEVELS); + } - ObjectStorageCapabilityEvidence unknownProvider = - evidence( - ObjectStorageCapabilityCard.MANAGED_DOWNLOAD, - ObjectStorageReadinessLevel.R1, - "unknown-provider", - "local-managed-integrity", - Optional.empty(), - List.of("local only")); - assertThatIllegalArgumentException() - .isThrownBy(() -> unknownProvider.validate(KNOWN_PROVIDERS, AVAILABLE_TASKS)); + @ParameterizedTest + @MethodSource("overclaims") + void anUnknownOrOverclaimedRowIsNamed(String key, Object value, String problem) { + // given + Map row = new HashMap<>(validRow()); + row.put(key, value); - ObjectStorageCapabilityEvidence absentTask = - new ObjectStorageCapabilityEvidence( - ObjectStorageCapabilityCard.MANAGED_DOWNLOAD, - "filesystem-local-dev", - "jdk-21", - "local-managed-integrity", - ObjectStorageReadinessLevel.R1, - "batch-b", - Optional.empty(), - List.of(":missing:readinessTask"), - List.of("local only")); - assertThatIllegalArgumentException() - .isThrownBy(() -> absentTask.validate(KNOWN_PROVIDERS, AVAILABLE_TASKS)); + // when + List found = problems(row); - ObjectStorageCapabilityEvidence noLimitations = - evidence( - ObjectStorageCapabilityCard.MANAGED_DOWNLOAD, - ObjectStorageReadinessLevel.R1, - "filesystem-local-dev", - "local-managed-integrity", - Optional.empty(), - List.of()); - assertThatIllegalArgumentException() - .isThrownBy(() -> noLimitations.validate(KNOWN_PROVIDERS, AVAILABLE_TASKS)); + // then + assertThat(found).contains(problem); + } + + static Stream overclaims() { + return Stream.of( + arguments("card_id", "objectstorage", "unknown card objectstorage"), + arguments("card_id", "object-storage-unknown", "unknown card object-storage-unknown"), + arguments("provider_version", "", "invalid provider_version"), + arguments("provider_type", "unknown-provider", "unknown provider unknown-provider"), + arguments("claimed_level", "R9", "unknown level R9"), + arguments("claimed_level", "R2", "R2/R3 evidence without an expiry"), + arguments("claimed_level", "R3", "filesystem-local-dev above R1"), + arguments("evidence_expires_on", "soon", "invalid expiry soon"), + arguments("required_tasks", List.of(":missing:readinessTask"), "required task absent"), + arguments("limitations", List.of(), "limitations not explicit")); + } + + private static List problems(Map row) { + List problems = new ArrayList<>(); + if (!row.keySet().equals(ROW_KEYS)) { + problems.add("row keys " + row.keySet()); + } + String card = text(row, "card_id"); + if (!FROZEN_LEVELS.containsKey(card)) { + problems.add("unknown card " + card); + } + for (String key : TOKEN_KEYS) { + if (!TOKEN.matcher(text(row, key)).matches()) { + problems.add("invalid " + key); + } + } + String provider = text(row, "provider_type"); + if (!KNOWN_PROVIDERS.contains(provider)) { + problems.add("unknown provider " + provider); + } + String level = text(row, "claimed_level"); + if (!LEVELS.contains(level)) { + problems.add("unknown level " + level); + } + String expiry = text(row, "evidence_expires_on"); + if (!expiry.isBlank()) { + try { + LocalDate.parse(expiry); + } catch (DateTimeParseException invalid) { + problems.add("invalid expiry " + expiry); + } + } + boolean aboveR1 = level.equals("R2") || level.equals("R3"); + if (aboveR1 && provider.equals("filesystem-local-dev")) { + problems.add("filesystem-local-dev above R1"); + } + if (aboveR1 && expiry.isBlank()) { + problems.add("R2/R3 evidence without an expiry"); + } + List tasks = texts(row, "required_tasks"); + if (tasks.isEmpty() || !AVAILABLE_TASKS.containsAll(tasks)) { + problems.add("required task absent"); + } + List limitations = texts(row, "limitations"); + if (limitations.isEmpty() || limitations.stream().anyMatch(String::isBlank)) { + problems.add("limitations not explicit"); + } + return problems; + } + + private static Map validRow() { + return Map.of( + "card_id", "object-storage-managed-download", + "provider_type", "filesystem-local-dev", + "provider_version", "jdk-21", + "destination_profile", "local-managed-integrity", + "claimed_level", "R1", + "evidence_revision", "batch-b", + "evidence_expires_on", "", + "required_tasks", List.of(":adapter:outbound:objectstorage:check"), + "limitations", List.of("local only")); + } + + private static String text(Map row, String key) { + Object value = row.get(key); + return value == null ? "" : value.toString(); + } + + private static List texts(Map row, String key) { + if (!(row.get(key) instanceof List values)) { + return List.of(); + } + return values.stream().map(value -> value == null ? "" : value.toString()).toList(); } @SuppressWarnings("unchecked") + private static List> rows() throws Exception { + Map registry = loadRegistry(); + assertThat(registry).containsOnlyKeys("schema_version", "claims"); + assertThat(registry.get("schema_version")).isEqualTo(1); + return (List>) registry.get("claims"); + } + private static Map loadRegistry() throws Exception { Path path = registryPath(); LoaderOptions options = new LoaderOptions(); @@ -141,57 +220,4 @@ class ObjectStorageReadinessRegistryTest { } return registry; } - - @SuppressWarnings("unchecked") - private static List claims(Map registry) { - return ((List>) registry.get("claims")) - .stream().map(ObjectStorageReadinessRegistryTest::claim).toList(); - } - - @SuppressWarnings("unchecked") - private static ObjectStorageCapabilityEvidence claim(Map row) { - assertThat(row) - .containsOnlyKeys( - "card_id", - "provider_type", - "provider_version", - "destination_profile", - "claimed_level", - "evidence_revision", - "evidence_expires_on", - "required_tasks", - "limitations"); - String expiry = (String) row.get("evidence_expires_on"); - return new ObjectStorageCapabilityEvidence( - ObjectStorageCapabilityCard.parse((String) row.get("card_id")), - (String) row.get("provider_type"), - (String) row.get("provider_version"), - (String) row.get("destination_profile"), - ObjectStorageReadinessLevel.valueOf((String) row.get("claimed_level")), - (String) row.get("evidence_revision"), - expiry == null || expiry.isBlank() - ? Optional.empty() - : Optional.of(LocalDate.parse(expiry)), - (List) row.get("required_tasks"), - (List) row.get("limitations")); - } - - private static ObjectStorageCapabilityEvidence evidence( - ObjectStorageCapabilityCard card, - ObjectStorageReadinessLevel level, - String provider, - String profile, - Optional expiry, - List limitations) { - return new ObjectStorageCapabilityEvidence( - card, - provider, - "jdk-21", - profile, - level, - "batch-b", - expiry, - List.of(":adapter:outbound:objectstorage:check"), - limitations); - } } diff --git a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/FileserverJpaPersistenceConfig.java b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/FileserverJpaPersistenceConfig.java index 20a3a6a1..f355e71f 100644 --- a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/FileserverJpaPersistenceConfig.java +++ b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/FileserverJpaPersistenceConfig.java @@ -23,7 +23,7 @@ import org.springframework.data.jpa.repository.config.EnableJpaRepositories; * condition; the entity metadata did not, so "disabled" meant two different things one annotation * apart. * - *

The condition is the same master switch those beans use, so disabled means one thing + *

The condition is the same capability switch those beans use, so disabled means one thing * everywhere: no entity metadata, no repository beans, no schema expectation. * *

This is now the leaf's own auto-configuration root rather than an {@code @Import} of the JPA @@ -41,7 +41,11 @@ import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @AutoConfiguration( beforeName = "dev.caskeleton.adapter.outbound.persistence.autoconfigure.PersistenceJpaAutoConfiguration") -@ConditionalOnProperty(prefix = "app.fileserver-platform", name = "enabled", havingValue = "true") +@ConditionalOnProperty( + prefix = "app.fileserver-platform", + name = "enabled", + havingValue = "true", + matchIfMissing = true) @EntityScan(basePackages = "dev.caskeleton.adapter.outbound.persistence.fileserver") @EnableJpaRepositories(basePackages = "dev.caskeleton.adapter.outbound.persistence.fileserver") @ComponentScan(basePackages = "dev.caskeleton.adapter.outbound.persistence.fileserver") diff --git a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaCleanupQueue.java b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaCleanupQueue.java index 97702eaf..564e6aeb 100644 --- a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaCleanupQueue.java +++ b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaCleanupQueue.java @@ -33,7 +33,11 @@ import org.springframework.stereotype.Repository; * both columns nullable for that reason; which one is set is what tells the worker where to look. */ @Repository -@ConditionalOnProperty(prefix = "app.fileserver-platform", name = "enabled", havingValue = "true") +@ConditionalOnProperty( + prefix = "app.fileserver-platform", + name = "enabled", + havingValue = "true", + matchIfMissing = true) public class JpaCleanupQueue implements CleanupQueue { /** After this many failed attempts an item stops being rescheduled. */ diff --git a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaContentReferenceLedger.java b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaContentReferenceLedger.java index a0f8017e..ede316ed 100644 --- a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaContentReferenceLedger.java +++ b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaContentReferenceLedger.java @@ -15,7 +15,11 @@ import org.springframework.stereotype.Repository; * reclaimed by a second, unrelated deletion path. */ @Repository -@ConditionalOnProperty(prefix = "app.fileserver-platform", name = "enabled", havingValue = "true") +@ConditionalOnProperty( + prefix = "app.fileserver-platform", + name = "enabled", + havingValue = "true", + matchIfMissing = true) public class JpaContentReferenceLedger implements ContentReferenceLedger { private final JpaFileRepository files; diff --git a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaFileMetadataStore.java b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaFileMetadataStore.java index f453fdad..0f7b1b62 100644 --- a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaFileMetadataStore.java +++ b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaFileMetadataStore.java @@ -39,7 +39,11 @@ import org.springframework.stereotype.Repository; * worth having. */ @Repository -@ConditionalOnProperty(prefix = "app.fileserver-platform", name = "enabled", havingValue = "true") +@ConditionalOnProperty( + prefix = "app.fileserver-platform", + name = "enabled", + havingValue = "true", + matchIfMissing = true) public class JpaFileMetadataStore implements FileMetadataStore { private final JpaFileRepository files; diff --git a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaFileQuotaService.java b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaFileQuotaService.java index 1a70b91a..e38ba919 100644 --- a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaFileQuotaService.java +++ b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaFileQuotaService.java @@ -23,7 +23,11 @@ import org.springframework.stereotype.Repository; * already expired or was released can never be extended or committed. */ @Repository -@ConditionalOnProperty(prefix = "app.fileserver-platform", name = "enabled", havingValue = "true") +@ConditionalOnProperty( + prefix = "app.fileserver-platform", + name = "enabled", + havingValue = "true", + matchIfMissing = true) public class JpaFileQuotaService implements FileQuotaService { private final FileserverQuotaRepository reservations; diff --git a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaQuotaCommitGateway.java b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaQuotaCommitGateway.java index c5b55b7a..d4e3e1bc 100644 --- a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaQuotaCommitGateway.java +++ b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaQuotaCommitGateway.java @@ -35,7 +35,11 @@ import org.springframework.stereotype.Repository; * silently drifts below the truth. */ @Repository -@ConditionalOnProperty(prefix = "app.fileserver-platform", name = "enabled", havingValue = "true") +@ConditionalOnProperty( + prefix = "app.fileserver-platform", + name = "enabled", + havingValue = "true", + matchIfMissing = true) public class JpaQuotaCommitGateway implements QuotaCommitGateway { private static final Limit OLDEST = Limit.of(1); diff --git a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaQuotaReclaimGateway.java b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaQuotaReclaimGateway.java index d0d4952f..75d8d3db 100644 --- a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaQuotaReclaimGateway.java +++ b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaQuotaReclaimGateway.java @@ -27,7 +27,11 @@ import org.springframework.stereotype.Repository; * was already understated, which a negative balance would not fix. */ @Repository -@ConditionalOnProperty(prefix = "app.fileserver-platform", name = "enabled", havingValue = "true") +@ConditionalOnProperty( + prefix = "app.fileserver-platform", + name = "enabled", + havingValue = "true", + matchIfMissing = true) public class JpaQuotaReclaimGateway implements QuotaReclaimGateway { private static final Limit RECLAIM_PAGE = Limit.of(64); diff --git a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaRecoveryQueue.java b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaRecoveryQueue.java index 72f16b07..515da852 100644 --- a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaRecoveryQueue.java +++ b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaRecoveryQueue.java @@ -26,7 +26,11 @@ import org.springframework.stereotype.Repository; * record of what the system concluded disappears with the item. */ @Repository -@ConditionalOnProperty(prefix = "app.fileserver-platform", name = "enabled", havingValue = "true") +@ConditionalOnProperty( + prefix = "app.fileserver-platform", + name = "enabled", + havingValue = "true", + matchIfMissing = true) public class JpaRecoveryQueue implements RecoveryQueue { private static final String STATUS_PENDING = "PENDING"; diff --git a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaStagingUploadLocator.java b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaStagingUploadLocator.java index c8ed8f93..edcfe0b9 100644 --- a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaStagingUploadLocator.java +++ b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaStagingUploadLocator.java @@ -19,7 +19,11 @@ import org.springframework.stereotype.Repository; * that as live evidence would tell reconciliation the upload is resumable when it is not. */ @Repository -@ConditionalOnProperty(prefix = "app.fileserver-platform", name = "enabled", havingValue = "true") +@ConditionalOnProperty( + prefix = "app.fileserver-platform", + name = "enabled", + havingValue = "true", + matchIfMissing = true) public class JpaStagingUploadLocator implements StagingUploadLocator { private static final Limit NEWEST = Limit.of(1); diff --git a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaUploadSessionStore.java b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaUploadSessionStore.java index 1465f5ed..0d55c45a 100644 --- a/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaUploadSessionStore.java +++ b/src/adapter/outbound/persistence-fileserver/src/main/java/dev/caskeleton/adapter/outbound/persistence/fileserver/JpaUploadSessionStore.java @@ -34,7 +34,11 @@ import org.springframework.stereotype.Repository; * the staged bytes of an upload a writer was about to take a lease on. */ @Repository -@ConditionalOnProperty(prefix = "app.fileserver-platform", name = "enabled", havingValue = "true") +@ConditionalOnProperty( + prefix = "app.fileserver-platform", + name = "enabled", + havingValue = "true", + matchIfMissing = true) public class JpaUploadSessionStore implements UploadSessionStore { private final JpaUploadSessionRepository sessions; diff --git a/src/adapter/outbound/persistence-jpa/CLAUDE.md b/src/adapter/outbound/persistence-jpa/CLAUDE.md index 0eab70da..4573d5a9 100644 --- a/src/adapter/outbound/persistence-jpa/CLAUDE.md +++ b/src/adapter/outbound/persistence-jpa/CLAUDE.md @@ -28,16 +28,24 @@ packages. | Platform package | Owns | |---|---| -| `autoconfigure` | package-private Boot composition root/runtime: vendor and optional-store imports, transaction executor/retry wiring, and composition factories. It is intentionally not exported as public API | -| `api` (+ `.capability`, `.error`, `.query`, `.transaction`) | framework-free contracts: operation and query names, the stable error hierarchy, transaction and retry profiles, keyset cursors | -| `transaction` | commit evidence, the Spring executor, full-transaction retry, completion-unknown reconciliation | +| `autoconfigure` | package-private Boot composition root/runtime: vendor and optional-store imports and provider runtime beans. It is intentionally not exported as public API | +| `api` (+ `.capability`, `.error`, `.query`, `.transaction`) | framework-free contracts: operation and query names, the stable error hierarchy, commit-completion evidence, keyset cursors | +| `transaction` | `SpringTransactionPort`, the one transaction engine (`TransactionPort` over Spring's `PlatformTransactionManager`) | | `springdata` | repository fragments, safe sort, fetch plans, keyset execution, stream guard | | `hibernate` (+ `.batch`, `.bulk`, `.stateless`) | statement inspector, statistics, batch, bulk DML, stateless session | -| `postgresql` (+ `.error`, `.lock`, `.constraint`, `.json`, `.array`, `.range`, `.write`, `.copy`) | SQLSTATE classification, locks and work claims, JSONB, arrays and ranges, upserts, COPY | -| `migration` | Flyway policy, validate gate, concurrent-index guard | -| `auditing`, `cache`, `envers`, `querydsl`, `security`, `observation` | opt-in capabilities and the runtime-role verifier | -| `experimental` | multi-tenancy, RLS, read replica, forward-compatibility lanes — all flag-gated | -| `testkit` (`src/testkit/java`) | ArchUnit rules, fixtures, query/plan assertions, PostgreSQL matrix, failure injection | +| `postgresql` (+ `.error`, `.lock`, `.constraint`, `.json`, `.array`, `.range`, `.copy`) | SQLSTATE classification, lock options, JSONB, arrays and ranges, COPY | +| `migration` | `FlywaySchemaPolicy` (composed by the `startup` package's dangerous-configuration guard) | +| `startup` | package-private startup policy (`JpaStartupAutoConfiguration`): Flyway migration strategy, datasource env/product checks, OSIV/DDL/Hikari/TLS/H2 guards, the `jpaplatform` actuator view, the readiness `db` contribution. Moved here from app-bootstrap | +| `cache`, `envers`, `querydsl`, `security`, `observation` | opt-in library capabilities and the runtime-role verifier | +| `experimental` | multi-tenancy, RLS, schema/database tenancy, read replica — library code a deployment constructs itself; no flag turns it on | +| `testkit` (`src/testFixtures/java`) | ArchUnit rules, fixtures, query/plan assertions, PostgreSQL matrix, failure injection, Flyway validate gate and concurrent-index inspector | + +`springdata`, `hibernate` (`.batch`, `.bulk`, `.stateless`, statement inspector), `postgresql` +(`.error`, `.lock`, `.constraint`, `.json`, `.array`, `.range`, `.copy`), `api.query`, `envers`, +`querydsl`, `cache`, `observation` and `experimental` are **library API**: no configuration composes +them, and a service calls them from its own adapter leaf, which takes this leaf as `implementation`. +The entry points and the test that proves each one are listed in [README.md](README.md) +"라이브러리 API". ### Spring composition ownership @@ -45,26 +53,45 @@ packages. package-private entries: `PersistenceJpaAutoConfiguration` and `PersistenceJpaRuntimeConfig`. Because Boot loads those candidates independently, **both** require `ca-skeleton.persistence-jpa.enabled=true`. The first owns vendor/entity/repository and -capability-store imports. The second additionally honors `app.jpa-platform.addons-enabled` and is -ordered after Spring's datasource/JPA transaction-manager auto-configuration so -`@ConditionalOnBean` sees the actual transaction manager before deciding whether to create -`SpringJpaTransactionExecutor` and `FullTransactionRetryCoordinator`. Never rely on the first -candidate's condition to gate the sibling import candidate. +capability-store imports. The second contributes only the provider runtime beans +(`HibernateProviderPolicy`, `PostgreSqlRuntimeRoleVerifier`). The +transaction engine is `SpringTransactionPort` alone; the second engine +(`SpringJpaTransactionExecutor`/`FullTransactionRetryCoordinator`) was removed on 2026-09-25 — see +`docs/capability-status.md`. Never rely on the first candidate's condition to gate the sibling +import candidate. -The same split applies to owner-safe PostgreSQL idempotency: this leaf constructs the concrete PostgreSQL store behind IdempotencyStorePortV2, while app-bootstrap owns provider selection, TTL/lease/codec policy, executor construction, and exclusivity validation. +`enabled=false` is a full off, not a bean-only one: `JpaActivationEnvironmentPostProcessor` (this +leaf's `spring.factories`) appends Boot's `jdbc`/`hibernate`/`data.jpa`/`flyway` auto-configurations +to `spring.autoconfigure.exclude`, so no DataSource, pool, EntityManagerFactory or Flyway exists. -Do not move application deployment policy into this leaf merely because it mentions JPA. -`app-bootstrap/autoconfigure/jpa` intentionally retains migration startup sequencing, resolved -datasource/version validation, OSIV/DDL safety, and the sanitized management endpoint/report. The -leaf must have zero imports from `dev.caskeleton.bootstrap`, and new composition helpers under -`autoconfigure` remain package-private so `verifyJpaApiSurface` does not grow by wiring accident. +The same split applies to owner-safe PostgreSQL idempotency: this leaf constructs the concrete +PostgreSQL store behind `IdempotencyStorePort` (`PostgreSqlIdempotencyStoreConfig`, active only with +`ca-skeleton.capabilities.idempotency.provider=postgresql`), while app-bootstrap owns provider +selection, TTL/lease/codec policy, executor construction, and exclusivity validation. With that +provider the leaf also applies the `db/migration/jpa/core` + `db/migration/jpa/idempotency` Flyway +streams and activates the capability registry row at startup (`IdempotencySchemaStream`, skipped +when `ca-skeleton.runtime.migration-on-startup=false`), refuses a non-PostgreSQL data source, and +runs `IdempotencyReaper`. There is no V1/JDBC idempotency store and no `jdbc` provider value. + +This module is a capability selected by one build line (`runtimeOnly +project(':adapter:outbound:persistence-jpa')`); the template's default composition does not carry it. +Everything that only makes sense with a relational store therefore lives here and turns on with the +module: migration startup sequencing, resolved datasource/version validation, OSIV/DDL/pool/TLS/vendor +safety, the sanitized management endpoint/report (`startup`), the metered multi-instance lock +(`lock`), the readiness `db` contribution and the shipped settings +(`config/module-defaults/persistence-jpa.yml`). Use-case assembly does not: the outbox relay stays in +app-bootstrap because a driven adapter must not construct or call a use case. The leaf must have +zero imports from `dev.caskeleton.bootstrap`; startup failures go through `adapter:outbound:support` +(`support.startup`), and new composition helpers stay package-private so `verifyJpaApiSurface` does +not grow by wiring accident. ### Non-negotiables - No `GenericRepository` and no platform base repository. Domains own their repositories. - `TransactionCompletionUnknownException` is never retried. `JpaFailureContext` refuses to - represent a retryable completion-unknown failure, so a policy bug cannot produce one. -- Retry re-runs the whole use case in a new transaction and a new Persistence Context. + represent a retryable completion-unknown failure, and `SpringTransactionPort` retries nothing. +- A caller that retries re-runs the whole use case in a new transaction and a new Persistence + Context. - OSIV is false in every runtime profile; Flyway owns schema change and Hibernate only validates. - Metric tags, exception messages, and logs carry no SQL parameters, entity ids, tenant ids, or PII. - Contracts run against real PostgreSQL. H2 never satisfies one. @@ -76,7 +103,7 @@ cd src ./gradlew :adapter:outbound:persistence-jpa:test # hermetic unit lane ./gradlew :adapter:outbound:persistence-jpa:jpaPlatformContractTest # real PostgreSQL ./gradlew :adapter:outbound:persistence-jpa:jpaPlatformMigrationTest # Flyway upgrade scenarios -./gradlew :adapter:outbound:persistence-jpa:jpaPlatformFailureTest # deadlock, commit ambiguity +./gradlew :adapter:outbound:persistence-jpa:jpaPlatformFailureTest # deadlock ./gradlew :adapter:outbound:persistence-jpa:jpaPlatformQueryPlanTest # EXPLAIN structure ./gradlew :adapter:outbound:persistence-jpa:jpaPlatformSecurityTest # runtime role privileges ./gradlew :adapter:outbound:persistence-jpa:jpaPlatformPoolContractTest # pool behaviour @@ -99,22 +126,24 @@ nobody tested. - Spring Data repositories. - Persistence mappers. - Repository adapter implementations. -- Outbox transport-only compatibility: raw `NewOutboxEvent` append belongs only to `LegacyOutboxAppendPort`; canonical `OutboxAppendPort` persists `ValidatedIntegrationEvent` exact bytes. Partial canonical metadata must fail closed and this path must not activate `POLLING_V2`. -- Owner-safe outbox V2 storage is canonical-aligned but remains a dark candidate: `NewOutboxEventV2` wraps one `ValidatedIntegrationEvent`, the PostgreSQL V2 event row preserves exact envelope `BYTEA` plus tenant/hash/revision metadata, aggregate ordering is tenant-scoped, and `ClaimedOutboxDelivery` reconstructs the canonical event without re-encoding. Pre-canonical or partially canonical rows fail closed. `PostgreSqlPollingDeliveryAdapter` is not a Spring component, no V2 scheduler is composed, and production publication authority remains `LEGACY_POLLING` until a separate cutover proves backlog/drain readiness. +- Outbox transport-only compatibility: raw `NewOutboxEvent` append belongs only to `LegacyOutboxAppendPort`; canonical `OutboxAppendPort` persists `ValidatedIntegrationEvent` exact bytes. Partial canonical metadata must fail closed. +- Outbox relay fencing: `claimBatch` records the claiming relay (`lease_owner`) and increments + `lease_token` under the claim's row lock (`V17`); `markPublished`/`markFailed`/`markDead` are one + conditional UPDATE on `event_id` + `IN_FLIGHT` + owner + token and return `APPLIED`/`STALE`. A + completion never loads and overwrites a row. The V2 outbox generation was deleted on 2026-09-25 + (`docs/capability-status.md`). - `TransactionPort` implementation (`SpringTransactionPort`) — the bridge between application transactional intent and Spring's `PlatformTransactionManager`. - Audit-metadata base + actor seam (`audit/AuditableEntity`, `audit/AuditContextPort`, `audit/DomainContextAuditContextPort`) — see "Persistence auditing contract" below. - Vendor SPI extension points shared by all RDBMS vendors: - `outbox/OutboxClaimRepository` — vendor module implements claim strategy (e.g. FOR UPDATE SKIP LOCKED). - - `idempotency/IdempotencyClaimRepository` — vendor implements insert-or-expired-reclaim. - `failure/SqlStateErrorMapping` — vendor module contributes vendor-specific SQLState rows. - - `transaction/TransactionLocalTimeoutConfigurer` — vendor applies statement/lock guards. ## Vendor selection Two vendor compositions live in this module, each in its own subpackage, each registering the same -four SPI beans: +two SPI beans (outbox claim, SQLState mapping): | Vendor | Package | Selected by | Schema owner | | --- | --- | --- | --- | @@ -125,20 +154,17 @@ four SPI beans: startup instead of loading neither composition and surfacing as a missing `OutboxClaimRepository`. The profiles state the choice: `application-local.yml`, `application-dev.yml` and `application-prod.yml` all default to PostgreSQL. H2 is an explicit developer opt-out selected by -the `bootRunH2` task. `PersistenceVendorProdSafetyValidator` (app-bootstrap) refuses H2 under prod -whatever property source supplies it. +the `bootRunH2` task. `PersistenceVendorProdSafetyValidator` (`startup`) refuses H2 under prod +whatever property source supplies it. Under `bootRunH2` the idempotency provider must be `disabled` +or `redis`: the `postgresql` provider refuses an H2 data source at startup. H2 is the local-development datastore, not a second production target. It has no migration tree, so -tables that exist only in migrations — capability schema registry, polling-delivery and inbox -streams, the Spring Integration lock table — do not exist under it. Vendor concurrency and migration +tables that exist only in migrations — capability schema registry, the Spring Integration lock table — do not exist under it. Vendor concurrency and migration fidelity stay with `postgresqlIntegrationTest`. -Two H2 statements diverge from PostgreSQL and the reasons are measured, not assumed (H2 2.4.240): - -- the outbox claim is identical — H2 accepts `FOR UPDATE SKIP LOCKED` and genuinely skips locked - rows, so the claim keeps its meaning; -- the idempotency claim is not — H2 has no `INSERT ... ON CONFLICT ... RETURNING`, so it is a - `MERGE ... USING` with the same three outcomes. `H2ClaimSqlTest` executes both against a real H2. +The outbox claim is the one vendor statement H2 runs, and it is identical — H2 2.4.240 accepts +`FOR UPDATE SKIP LOCKED` and genuinely skips locked rows, so the claim keeps its meaning. +`H2ClaimSqlTest` executes it against a real H2. H2 has no idempotency store. ### Capability-gated stores @@ -156,11 +182,13 @@ should not exist. - `:application-core` - `:domain-core` - `:shared-contract` +- `:adapter:outbound:support` (typed startup failures, EnvironmentPostProcessor order, readiness + group, module-defaults loader) - Spring Data JPA and Spring transaction. ## Forbidden -- `adapter-web`, `adapter-outbound`, or `app-bootstrap`. +- `adapter-web`, `app-bootstrap`, or any outbound adapter other than `adapter:outbound:support`. - Presentation DTOs. - Business policy decisions. - Use case orchestration hidden inside persistence adapters. @@ -262,8 +290,8 @@ fields under `..domain..`). - **Capture = Manual explicit-set (D1 current default).** The repository adapter constructor-injects `Clock` (D4) and `AuditContextPort` (D5) and stamps audit on `save`: INSERT (null version) → `initializeAudit(now, actor)`; UPDATE (non-null version) → - carry the persisted `created_*` forward + `applyModification(now, actor)`. This mirrors - the `IdempotencyStoreAdapter` precedent. `created_*` is `updatable = false`. + carry the persisted `created_*` forward + `applyModification(now, actor)`. + `created_*` is `updatable = false`. - **Actor seam.** `AuditContextPort.currentActor()` reads the runtime-context-propagation seam and falls back to `"system"` when no principal is bound (scheduler / Flyway / anonymous). The actor's value semantics are owned by feature-authentication-authorization-contract diff --git a/src/adapter/outbound/persistence-jpa/README.md b/src/adapter/outbound/persistence-jpa/README.md index 01ba9500..73fb7bba 100644 --- a/src/adapter/outbound/persistence-jpa/README.md +++ b/src/adapter/outbound/persistence-jpa/README.md @@ -8,6 +8,94 @@ Code 매트릭스, auditing 계약, 분산 락 provider 선택표)의 SSOT 는 [ "왜 이렇게 했나"가 궁금할 때 본다. 표가 CLAUDE.md 에 있으면 여기서는 중복하지 않고 그 근거만 적는다. +## capability 모듈로 쓰기 — 제공하는 것, 추가할 한 줄, 필요한 env + +템플릿 기본 조립에는 이 모듈이 없다. 관계형 저장소가 필요한 서비스는 `app-bootstrap/build.gradle`에 +한 줄을 넣는다. + +```groovy +runtimeOnly project(':adapter:outbound:persistence-jpa') +``` + +그 줄을 지우면 아래 전부가 함께 사라진다. 다른 파일은 고치지 않는다. + +**제공하는 것** (모듈이 있으면 켜진다. `APP_PERSISTENCE_JPA_ENABLED=false`면 완전히 꺼진다: 이 모듈의 +bean과 함께 Boot의 JDBC·Hibernate·Spring Data JPA·Flyway 자동 설정도 `spring.autoconfigure.exclude`에 +추가되므로 DataSource·풀·EntityManagerFactory·Flyway가 만들어지지 않고 DB 없이 기동한다. 그래서 DB가 +필요한 다른 capability(notification·fileserver 저장소, messaging JDBC outbox/inbox 등)와 함께 끌 수는 없다) + +- 포트 구현: `TransactionPort`(`SpringTransactionPort`), `DistributedLockPort`(단일 인스턴스는 + in-process, `APP_MULTI_INSTANCE_ENABLED=true`면 JDBC `INT_LOCK` + `MeteredDistributedLockPort` + 데코레이터 = `distributedLockProvider`), outbox store(`OutboxStorePort`, `APP_OUTBOX_ENABLED=true`), + PostgreSQL 멱등성 store(`APP_IDEMPOTENCY_PROVIDER=postgresql`), audit·operation·live-event store. +- 엔티티/리포지토리 스캔, vendor 조립(PostgreSQL 기본, H2는 개발용), Flyway 위치. +- 기동 정책(`startup` 패키지, `JpaStartupAutoConfiguration`): Flyway 마이그레이션 전략 + (`migrationStartupRunner`, 실패 시 exit 70), datasource env 확인(exit 78), 실제 DB 제품·버전 확인, + OSIV·DDL·Hikari·TLS·H2 금지 가드(prod exit 71), `/actuator/jpaplatform`(actuator가 있을 때만). +- 스위치의 환경 처리(`JpaActivationEnvironmentPostProcessor`, 모듈의 `spring.factories`): 켜져 있으면 + readiness 그룹에 `db` 추가, 꺼져 있으면 Boot의 `jdbc`·`hibernate`·`data.jpa`·`flyway` 자동 설정 패키지를 + `spring.autoconfigure.exclude`에 추가(기존 값은 유지). +- 기본 설정 `config/module-defaults/persistence-jpa.yml`(`spring.datasource/flyway/jpa`, + `ca-skeleton.persistence*`, `ca-skeleton.lock.*`, `ca-skeleton.outbox.*`, + `ca-skeleton.realtime.replay.*`, `ca-skeleton.runtime.migration-on-startup`). support 모듈의 + `ModuleDefaultsEnvironmentPostProcessor`가 가장 낮은 우선순위로 읽으므로 애플리케이션 설정과 + 환경변수가 언제나 이긴다. + +outbox **relay**(스케줄러)는 이 모듈이 아니라 합성 루트의 `OutboxConfig`가 조립한다. use case를 +만들고 구동하는 일은 driven adapter의 몫이 아니기 때문이다. 그 설정은 이 모듈이 주는 +`OutboxStorePort`와 messaging이 주는 `OutboxMessagePublishPort`가 모두 있을 때만 켜진다. + +애플리케이션이 제공해야 하는 bean: `Clock`, `DomainContextPropagator`(app-bootstrap과 +sample-portfolio가 제공). + +**필요한 env 키** (`src/.env.example`, 레지스트리 `docs/registries/env-keys.yaml`) + +| 용도 | 키 | +|---|---| +| 연결(필수) | `APP_DATASOURCE_URL`, `APP_DATASOURCE_USERNAME`, `APP_DATASOURCE_PASSWORD`(prod 필수 secret), `APP_DATASOURCE_DRIVER` | +| 스위치·vendor | `APP_PERSISTENCE_JPA_ENABLED`(기본 true), `APP_PERSISTENCE_VENDOR`(`postgresql`\|`h2`), `APP_FLYWAY_ENABLED`, `APP_MIGRATION_ON_STARTUP` | +| 풀 | `APP_DATASOURCE_POOL_MAX_SIZE`, `APP_DATASOURCE_POOL_MIN_IDLE`, `APP_DATASOURCE_CONNECTION_TIMEOUT`, `APP_DATASOURCE_POOL_IDLE_TIMEOUT`, `APP_DATASOURCE_POOL_MAX_LIFETIME` | +| JPA | `APP_DATASOURCE_DDL_AUTO`, `APP_DATASOURCE_SHOW_SQL`, `APP_DATASOURCE_FORMAT_SQL`, `APP_DATASOURCE_OPEN_IN_VIEW`, `APP_JPA_HIBERNATE_*` | +| 선택 기능 | `APP_OUTBOX_ENABLED`, `APP_OUTBOX_RELAY_ENABLED`, `APP_OUTBOX_CANONICAL_TRANSPORT_ENABLED`, `APP_MULTI_INSTANCE_ENABLED`(합성 루트 소유, 락 provider 선택), `APP_IDEMPOTENCY_PROVIDER=postgresql`, `APP_REALTIME_REPLAY_ENABLED`, `APP_REALTIME_REPLAY_RETENTION` | + +## 라이브러리 API — 서비스의 어댑터 leaf에서 `implementation`으로 받아 직접 호출 + +아래 타입은 어떤 설정도 bean으로 만들지 않는다. 쓰려면 서비스의 어댑터 leaf가 +`implementation project(':adapter:outbound:persistence-jpa')`를 선언하고(registry +`allowed_dependencies`에 그 edge가 있어야 한다) 자기 코드에서 생성·호출한다. `runtimeOnly`로는 +컴파일되지 않는다(AGENTS.md capability 규칙의 라이브러리형 예외). Querydsl·Envers는 이 leaf에서 +`compileOnly`이므로 쓰는 서비스가 `com.querydsl:querydsl-jpa:5.1.0:jakarta`·`org.hibernate.orm:hibernate-envers`를 +직접 추가한다. "PG"는 `postgresqlIntegrationTest`(실제 PostgreSQL) 테스트다. + +| 패키지 | 진입점 | 동작을 증명하는 테스트 | +|---|---|---| +| `springdata` | `JpaRepositoryFragmentSupport`(커스텀 fragment 베이스) + `RegisteredQuery` | `JpaRepositoryFragmentSupportTest` | +| `springdata` | `SafeSortRegistry`·`SafeSortMapper`(클라이언트 정렬 → 등록 컬럼) | `SafeSortMapperTest`, `KeysetOrderingContractTest` | +| `springdata`, `api.query` | `JpaKeysetQuerySupport`·`KeysetPredicateBuilder` + `KeysetPageRequest`·`KeysetSlice` | `JpaKeysetQuerySupportTest`, `KeysetSliceAssemblerTest`, `KeysetOrderingContractTest` | +| `springdata` | `FetchPlanApplier` + `EntityGraphCatalog` | `FetchPlanApplierTest` | +| `springdata` | `JpaStreamExecutor` + `ScrollPolicy` | `JpaStreamExecutorTest`, `ScrollPolicyTest` | +| `api.query` | `SignedJsonCursorCodec`(서비스가 `CursorPayloadCodec` 구현), `QueryName` | `SignedJsonCursorCodecTest`, `QueryNameTest` | +| `hibernate.batch` | `HibernateJpaBatchExecutor` + `JpaBatchProfile`·`HibernateStatisticsCollector`·`JdbcBatchCounter` | `HibernateJpaBatchExecutorTest`, `HibernateBatchConfigurationGuardTest`, `HibernateStatisticsCollectorTest`, PG `HibernateJpaBatchExecutorIntegrationTest` | +| `hibernate.bulk` | `HibernateBulkDmlExecutor` | PG `HibernateBulkDmlExecutorIntegrationTest` | +| `hibernate.stateless` | `HibernateStatelessSessionRunner` | PG `HibernateStatelessSessionRunnerIntegrationTest` | +| `hibernate` | `NamedStatementInspector`(`spring.jpa.properties.hibernate.session_factory.statement_inspector`로 켬) | `NamedStatementInspectorTest` | +| `postgresql.error` | `PostgreSqlExceptionTranslator.with(PostgreSqlConstraintCatalog)` → `api.error` 예외 계층 | `PostgreSqlFailureClassifierTest`, `PostgreSqlConstraintCatalogTest`, PG `PostgreSqlSqlStateContractTest`·`ConstraintRaceContractTest` | +| `postgresql.lock` | `PostgreSqlLockExceptionTranslator.standard()`, `PostgreSqlLockOptions` | `PostgreSqlLockOptionsTest`, PG `PostgreSqlPessimisticLockContractTest` | +| `postgresql.json` | `PostgreSqlJsonQuerySupport` + `JsonDocumentCodec`·`JsonDocument` | PG `PostgreSqlJsonbContractTest` | +| `postgresql.array`, `.range` | `PostgreSqlArraySupport`, `PgRange`·`PgRangeCodec` | `PgRangeTest`, PG `PostgreSqlArrayRangeContractTest` | +| `postgresql.copy` | `RegisteredPostgreSqlCopyLoader`(admin DataSource + `CopyAdminCapability`) | PG `PostgreSqlCopyLoaderIntegrationTest` | +| `envers` | `HibernateEnversHistoryReader`, `EnversConfigurationGuard` | PG `EnversHistoryContractTest` | +| `querydsl` | `PredicatePolicy`, `QueryPage`(서비스가 만든 `JPAQuery` 앞에서 검사) | `PredicatePolicyTest` | +| `cache` | `HibernateCacheGuard`, `HibernateCachePolicy`, `CacheRegionCatalog` | `HibernateCacheGuardTest` | +| `observation` | `MicrometerQueryObservation`(위 executor에 `QueryObservation`으로 전달), `SqlDiagnosticRedactor` | `JpaObservabilityContractTest`, `JpaMetricTagsTest` | +| `experimental` | tenant·RLS·schema·database·replica 진입점 — 목록은 `docs/jpa/experimental-support-matrix.md` | `ExperimentalFailClosedTest`, PG `platform/experimental/*` | + +metric은 기본으로 하나도 나오지 않는다. `jpa.query.*`는 서비스가 `MicrometerQueryObservation`을 +넘길 때만 기록된다(`docs/jpa/observability.md`). 2026-09-25에 지운 항목(단일 구현 인터페이스, +아무도 읽지 않는 `app.jpa-platform.addons-enabled`·`backend.jpa.experimental.*`, main의 +promotion gate, 생성하는 곳 없는 `JpaTransactionObservation` 등)은 `docs/capability-status.md` +"제거된 코드"에 있다. + ## transaction — `SpringTransactionPort` ### 왜 모드별 템플릿을 미리 만들어 두나 @@ -37,8 +125,7 @@ write template을 재사용한다. 차이는 실행 전 precondition이다. `@Column` 이다 — Spring Data 의 `@CreatedDate`/`@LastModifiedDate`/`@CreatedBy`/`@LastModifiedBy` 도, `@EntityListeners(AuditingEntityListener.class)` 도 **붙이지 않는다**. 퍼시스턴스 어댑터가 `initializeAudit`(INSERT) 와 `carryCreation` + `applyModification`(UPDATE)로 명시적으로 값을 -세팅한다. 공유 `Clock` 빈(D4)과 `AuditContextPort` actor(D5)를 재사용하는 방식으로, -`IdempotencyStoreAdapter` 가 생성자 주입 `Clock` 으로 row 를 재구성하는 선례와 동일하다. +세팅한다. 공유 `Clock` 빈(D4)과 `AuditContextPort` actor(D5)를 재사용한다. - INSERT 는 `created_*` 와 `updated_*` 를 같은 `now`/`actor` 로 찍는다. NOT NULL 인 `updated_*` 를 신규 row 에서 채우기 위함이며, JPA-auditing 의 `modifyOnCreate` 기본동작에 의존하지 않는다. @@ -109,46 +196,31 @@ failure translation contract 다. 여기서는 SPI 구조와 fallback 근거만 - 변환된 carrier 의 진단 메시지에 SQLState 를 넣는 건 server-log 전용이다(web 어댑터가 절대 surface 하지 않음) — triage 를 돕되 클라이언트로 새지 않는다. -## idempotency — `IdempotencyStoreAdapter` 외 +## idempotency — PostgreSQL provider -스키마는 Flyway(`V1__idempotency_record.sql`)가 소유하고 엔티티는 그것을 매핑만 한다. +`ca-skeleton.capabilities.idempotency.provider=postgresql` 일 때만 켜진다 +(`autoconfigure/PostgreSqlIdempotencyStoreConfig`). 이 leaf 는 `IdempotencyStorePort` 구현 +(`PostgreSqlOwnerSafeIdempotencyStore`) 하나만 내놓고, executor 는 app-bootstrap +`IdempotencyProviderSelectionConfig` 가 만든다. V1 JDBC store 와 `jdbc` provider 값은 없다. -### 동시성 중재 (D7 insert-or-read) -`tryBegin` 은 `uq_idempotency_scope` unique 제약을 동시성 중재자로 쓴다 — 동시 중복은 insert 를 -잃고 `false` 를 받는다. lookup 과 flush 사이에 다른 호출자가 끼어들면 -`DataIntegrityViolationException` 으로 잡아 `false` 를 반환한다(`saveAndFlush` 의 flush 가 unique -제약 검사를 그 자리에서 강제한다). 같은 scope 의 만료 row 는 insert 전에 reclaim(delete)해, stale -record 가 새 요청을 영구히 막지 못하게 한다. 이 delete + insert 는 호출자 트랜잭션(use case 가 -`TransactionPort` 로 소유) 안에서 도는 것을 전제로 atomic 하다. - -### 엔티티 불변/스코프 (D3 / §B / §F) -- `tenant` 은 절대 `null` 이 아니다(single-tenant 는 빈 문자열). PostgreSQL 은 NULL 을 서로 - distinct 로 취급하므로, null 을 허용하면 single-tenant row 의 unique scope dedup 이 깨진다. - 매퍼가 `null` 애플리케이션 tenant ↔ row 의 `""` 를 왕복시킨다. -- `status = COMPLETED` 가 되면 `responsePayload` / `responseRef` 중 정확히 하나만 채워진다(§F - ≤8KB inline / >8KB ref). -- 엔티티에 setter 가 없는 건 의도다: 상태 전이 때 row 를 재구성·재저장한다(Vernon Option A) — - 애플리케이션 관점에서 엔티티를 immutable 로 유지한다. - -### §F responseRef split & 만료 -- `complete` 의 §F 분기: payload ≤ 8KB 는 row 에 inline 저장, 더 크면 - `IdempotencyResponseObjectStore`(와이어링된 경우)로 offload 하고 reference 만 보관한다. object - store 가 없으면 큰 payload 도 경고와 함께 inline 으로 안전 degrade 한다(D9 프로젝트 선택). -- 만료는 세 곳에서 강제된다: read(`find` 가 만료 row 를 부재로 취급), reclaim(`tryBegin` 이 만료 - row 를 재claim 전에 delete), 그리고 `IdempotencyReaper`. reaper 는 유일한 만료 수단이 아니라 - 테이블 성장을 묶는 backstop 이다. reaper 의 고정 interval 과 clock-skew 미처리는 source-mandated - 가 아니다(프로젝트 선택 — 부하 하 cadence 측정 필요). - -### `IdempotencyResponseObjectStore` 는 왜 optional 인가 (D9 프로젝트 선택) -8KB 임계와 object-store 분리는 cited normative basis 가 없고 production 빈도도 미측정이다. -S3 호환 클라이언트가 템플릿에 없으므로 어댑터는 이 포트를 optional 로 취급한다 — 빈이 없으면 inline -DB 저장으로 fallback. 실제 구현(S3 / GCS / MinIO)을 와이어링하면 offload 가 활성화된다. +- **스키마**: 기본 테이블은 primary Flyway(`db/migration/postgresql/V1__idempotency_record.sql`)가, + owner-safe 컬럼은 `db/migration/jpa/idempotency` stream 이 소유한다. 기동 시 + `IdempotencySchemaStream` 이 `db/migration/jpa/core` → `db/migration/jpa/idempotency` 순서로 + 적용하고 capability registry 행을 `ACTIVE` 로 올린다. 알림 capability 의 + `NotificationSchemaStream` 과 같은 방식이다. `ca-skeleton.runtime.migration-on-startup=false` + 면 건너뛰고, 운영자가 적용·활성화할 때까지 store 가 fail closed 한다. +- **PostgreSQL 전용**: data source 가 PostgreSQL 이 아니면 기동을 거부한다. `bootRunH2` 는 + provider 를 `disabled` 나 `redis` 로 둔다. +- **응답 크기**: 완료 응답은 8 KiB 이하만 행에 inline 저장하고, 넘으면 거부한다. +- **만료**: store 가 완료·실패 때 `expires_at` 을 앞으로 옮기고, `IdempotencyReaper` + (`IdempotencyRecordJpaRepository` 사용, 기본 10분 간격 `reaper-interval`)가 지난 행을 지운다. + reaper 는 provider 가 `postgresql` 일 때만 돈다. ## outbox — `OutboxStoreAdapter` 외 스키마는 Flyway(`V3__outbox_event.sql`)가 소유하고, MSG-015 transport-only cutover를 위한 `V13__outbox_canonical_transport_compatibility.sql`이 기존 row를 깨지 않으면서 canonical metadata와 -exact `BYTEA envelope_bytes`를 additive하게 확장한다. 이 V13은 `POLLING_V2` authority 전환이 아니다. +exact `BYTEA envelope_bytes`를 additive하게 확장한다. append 경계도 명시적으로 분리된다. `LegacyOutboxAppendPort`는 기존 `NewOutboxEvent` compatibility producer 전용이고, `OutboxAppendPort`는 `ValidatedIntegrationEvent`만 받는다. @@ -183,19 +255,37 @@ eligible row(I3/I4/I6): - `FAILED` — `next_attempt_at <= now`(backoff 경과) - `IN_FLIGHT` — `next_attempt_at <= now`(orphaned row) -### `markPublished` / `markFailed` / `markDead` 는 왜 row 부재 시 throw 하나 -row 가 없으면 `IllegalStateException` 을 던진다. relay 가 방금 같은 서비스 인스턴스에서 claim 한 -row 이므로, 부재는 프로그래밍/동시성 버그다. 조용히 no-op 하면 row 가 영원히 `IN_FLIGHT` 로 남아 -그 aggregate 의 FIFO 큐를 막고, 호출자나 로그에 아무 신호도 남지 않는다(markFailed 는 relay 가 -재시도 예약을 믿게, markDead 는 runbook 가시성·수동 DEAD 해결을 막게 된다). +### claim lease와 fencing token (`V17`) +in-flight timeout이 지나면 다른 relay가 `IN_FLIGHT` row를 다시 claim한다. 예전 완료 처리는 +`event_id`만으로 row를 읽어 status를 덮어썼고 claim·publish·완료가 서로 다른 transaction이라, +timeout을 넘겨 멈췄던 relay A가 relay B의 결과를 덮을 수 있었다 — B가 PUBLISHED로 만든 row를 +A가 FAILED로 바꾸면 다시 발행되고(중복 전달), A의 늦은 PUBLISHED는 B의 실패를 가린다. + +- **claim**: `claimBatch(owner, ...)`가 row lock(`FOR UPDATE SKIP LOCKED`)을 쥔 상태에서 + `lease_owner = owner`, `lease_token = lease_token + 1`을 기록하고 `OutboxLease(event, owner, + token)`을 돌려준다. owner는 relay 인스턴스(`PublishPendingOutboxEventsUseCase`)마다 한 번 만든 + UUID다. +- **완료**: `markPublished/markFailed/markDead(lease)`는 한 문장의 조건부 UPDATE다 — + `WHERE event_id = ? AND status = 'IN_FLIGHT' AND lease_owner = ? AND lease_token = ?`. + owner는 비우고 token은 그대로 둔다(token은 증가만 한다). 1 row면 `APPLIED`, 0 row면 `STALE`. + `findById` + setter 경로와 `@Version`은 쓰지 않는다. +- **STALE은 예외가 아니다**: row의 결과는 지금 lease를 가진 relay가 쓴다. use case는 결과를 + `OutboxRelayResult.Outcome.STALE`로 남기고 `OutboxRelayFailureReportPort.reportStaleCompletion` + 으로 알린 뒤 다음 이벤트로 넘어간다. FAILED/DEAD report는 보내지 않는다(아무것도 저장되지 + 않았다). `outbox.publisher.published.total{outcome=STALE}`이 0보다 크면 in-flight timeout이 + relay 정지 시간보다 짧다는 뜻이고, broker는 그 이벤트를 두 번 받았을 수 있다. +- row가 없을 때도 0 row라 `STALE`이다. 예전처럼 throw하지 않는 이유: fencing 뒤에는 0 row가 + "다른 relay가 가져감"이라는 정상 결과이고, 그 row는 가져간 relay가 끝내거나 timeout 뒤 다시 + claim되므로 FIFO 큐가 막히지 않는다. ### `OutboxEventEntity` 의 결정 - **`AuditableEntity` 미상속(D6 — infra 엔티티).** `IdempotencyRecordEntity` 처럼 outbox row 는 도메인 애그리거트가 아니라 인프라 record 다. 자체 temporal 필드(`occurred_at`, `next_attempt_at`)가 도메인 의미를 갖고, generic `created_at`/`updated_at` audit 컬럼과 섞이면 안 된다. -- **mutating setter 노출은 의도.** relay 어댑터가 managed 엔티티 위에서 상태(status / - attempt_count / next_attempt_at)를 전이시키되 full reload-and-replace 없이 한다. outbox 어댑터만 +- **mutating setter 노출은 의도.** claim은 lock된 managed 엔티티 위에서 상태(status / + attempt_count / next_attempt_at / lease)를 전이시킨다. 완료는 setter가 아니라 lease 조건부 + bulk UPDATE다. outbox 어댑터만 이 필드를 건드리고, 모든 mutation 이 use case 소유 `TransactionPort.inWrite()` 경계 안에서 돌기에 안전하다. - **`next_attempt_at` dual-purpose(I6 — 추가 컬럼 없음):** @@ -224,11 +314,18 @@ cadence 측정 필요). retention 한 값은 reaper-local 이라 `@Value` 로 ## JPA production capability candidate -`src/config/jpa/readiness-cards.yaml`이 15개 capability와 7개 독립 schema stream의 -machine-readable SSOT다. `selected` base card와 `implemented-candidate` reliability card를 +`src/config/jpa/readiness-cards.yaml`이 capability와 독립 schema stream의 +machine-readable SSOT다(개수는 registry가 소유한다). `selected` base card와 `implemented-candidate` reliability card를 구분하며, 실제 PostgreSQL 테스트 통과만으로 immutable 운영 evidence가 필요한 R2를 주장하지 않는다. +적용된 versioned migration은 수정하지 않는다. Flyway가 기동할 때마다 checksum을 검사하므로 +바꾼 파일은 이미 그것을 적용한 모든 DB의 기동을 막는다. 변경은 새 버전으로 추가하고, +`src/test/resources/db/applied-migrations.sha256`에 한 줄을 더한다 +(`AppliedMigrationImmutabilityTest`가 검사). 2026-09-23~25 사이에 수정본 `postgresql/V9`·`V13`을 +적용해 만든 개발 DB는 원복된 파일과 checksum이 다르므로 한 번 `flyway repair`가 필요하다. 그 +사이 수정본이 바꾸려던 `char(64)→varchar(64)`는 `V16`이 한다. + 독립 Flyway stream은 broad `classpath:db/migration`으로 함께 실행하지 않는다. 각 stream은 자기 location/history table을 사용하고 non-empty schema adoption 때 version 0 baseline을 명시한 뒤 V1부터 실행한다. @@ -236,12 +333,9 @@ machine-readable SSOT다. `selected` base card와 `implemented-candidate` reliab | Capability | Location | History table | 상태 | |---|---|---|---| | core/adoption | `db/migration/jpa/core` | `flyway_jpa_core_history` | selected candidate | -| idempotency V2 | `db/migration/jpa/idempotency` | `flyway_jpa_idempotency_history` | implemented-candidate | -| outbox storage V2 | `db/migration/jpa/outbox-storage` | `flyway_jpa_outbox_storage_history` | implemented-candidate | -| polling delivery V2 | `db/migration/jpa/outbox-polling` | `flyway_jpa_outbox_polling_history` | implemented-candidate | -| inbox V1 | `db/migration/jpa/inbox` | `flyway_jpa_inbox_history` | implemented-candidate | +| idempotency | `db/migration/jpa/idempotency` | `flyway_jpa_idempotency_history` | implemented-candidate | -### owner-safe idempotency V2 +### owner-safe idempotency `PostgreSqlOwnerSafeIdempotencyStore`는 row lock을 얻은 뒤 `clock_timestamp()`를 평가한다. claim takeover와 start/renew/complete/fail/release는 scope/state/owner/attempt/claim operation/ @@ -249,35 +343,19 @@ state revision을 SQL predicate로 다시 검증한다. expired `CLAIMED`만 tak `EXECUTING`은 `ABANDONED`로 닫고 reconciliation을 요구한다. raw client key는 저장하지 않고 versioned HMAC scope digest만 쓴다. -### immutable outbox storage와 polling delivery V2 +### outbox V2 (삭제됨) -`PostgreSqlImmutableOutboxAppendAdapter`는 publication control을 `FOR SHARE`로 잠근 상태에서 -compact global identity guard와 partitioned immutable envelope를 같은 business transaction에 -기록한다. cutover는 control `FOR UPDATE`와 충돌하므로 시작된 append를 추월하지 못하며, target -authority 활성화 뒤 legacy V1 writer trigger가 실패한다. - -polling mode일 때 database trigger가 initial `outbox_delivery_v2` row를 같은 transaction에 -생성한다. `PostgreSqlPollingDeliveryAdapter`는 bounded `FOR UPDATE SKIP LOCKED` claim, -aggregate version/ordinal strict-order head gate, owner/token/attempt/version/epoch completion -CAS를 사용한다. broker 호출은 transaction 밖이고 duplicate publish 가능성은 stable event ID로 -consumer inbox에서 처리한다. - -### same-store inbox - -`PostgreSqlSameStoreInboxAdapter`의 transactional claim은 business mutation/outgoing outbox/ -completion과 caller의 한 primary write transaction에 참여한다. received lease expiry는 takeover할 -수 있지만 processing lease expiry는 blind retry하지 않고 recovery-required terminal state로 -보낸다. broker ACK는 commit 이후에만 실행한다. +immutable outbox storage·polling delivery V2(`jpa/outbox-storage`, `jpa/outbox-polling` stream과 +그 adapter)는 어떤 composition도 location을 설정한 적 없는 미조립 세대라 2026-09-25에 삭제했다 +(`docs/capability-status.md` "제거된 코드"). 실제로 도는 v1 `outbox_event` relay가 V2의 +owner/token CAS를 이어받았다(위 "claim lease와 fencing token"). ### 실제 PostgreSQL task -base 6개 task 외에 다음 candidate task가 Docker 부재 시 skip이 아니라 실패하도록 등록돼 있다. +base task 외에 다음 candidate task가 Docker 부재 시 skip이 아니라 실패하도록 등록돼 있다. ```text postgresqlIdempotencyIntegrationTest -postgresqlOutboxStorageIntegrationTest -postgresqlOutboxPollingIntegrationTest -postgresqlInboxIntegrationTest ``` ### evidence manifest와 R2 gate @@ -290,7 +368,7 @@ duplicate selector와 다른 card task 차용을 mutation test로 거절한다. ./gradlew :adapter:outbound:persistence-jpa:verifyJpaCandidateEvidence --console=plain ``` -위 task는 active card 11개의 producer를 실행하고 JUnit XML에서 exact selector와 +위 task는 active card의 producer를 실행하고 JUnit XML에서 exact selector와 executed/skipped/failure/error 수를 읽는다. 각 manifest는 source revision/dirty digest, prerequisite manifest ID, PostgreSQL image digest, pgjdbc/Hibernate/Flyway version, topology와 migration/dispatch metadata를 담고 다음 위치에 canonical JSON SHA-256 이름으로 생성된다. @@ -308,8 +386,8 @@ build/jpa-evidence/manifests//.json untrusted CA·expired certificate 경로 - persistence failure의 HTTP/log/span redaction - fresh/legacy adoption, interrupted migration forward recovery, N/N-1 additive rolling shape -- serialization/deadlock/lock/statement timeout, pool exhaustion, commit transport 단절 -- idempotency/outbox/inbox 독립 stream의 disabled/first-enable/disable/re-enable/interrupted +- deadlock, action 실패 rollback, `inNew` 독립 commit, commit transport 단절(재시도 없음) +- idempotency 등 독립 stream의 disabled/first-enable/disable/re-enable/interrupted lifecycle 각 manifest는 그래도 candidate profile, dirty source와 아직 R2가 아닌 prerequisite를 @@ -372,10 +450,11 @@ provider 선택표(flag → bean → registry)의 SSOT 는 CLAUDE.md(또는 app- 경로는 만료가 없어 그 `close()` 가 이 예외를 던질 수 없다. ### `DistributedLockPersistenceConfig` 와이어링 결정 -- `jdbcDistributedLock` 빈은 일부러 `@Primary` 가 아니고 이름도 `distributedLockProvider` 가 - 아니다. app-bootstrap 이 이를 metrics 데코레이터(`MeteredDistributedLockPort`)로 감싸 - `@Primary`/`distributedLockProvider` 빈을 노출한다. 이렇게 해서 SI 타입이 컴파일 타임에 - adapter-persistence 위 레이어에 보이지 않게 유지된다(SI 는 `implementation` 의존). +- `jdbcDistributedLock` 빈은 일부러 `@Primary` 가 아니다. 같은 설정이 이를 metrics + 데코레이터(`MeteredDistributedLockPort`, package-private)로 감싸 `@Primary` + `distributedLockProvider` 빈으로 노출한다. 예전에는 app-bootstrap의 `DistributedLockConfig`가 + 감쌌지만, JDBC 락이 있을 때만 의미가 있는 코드라 이 모듈로 옮겼다. SI 타입은 여전히 이 모듈 + 밖으로 보이지 않는다(SI 는 `implementation` 의존). - `DefaultLockRepository` 는 `InitializingBean`/`SmartLifecycle` 을 구현해 Spring 이 lifecycle 을 자동 관리하고, `ApplicationContextAware` 로 `PlatformTransactionManager` 를 auto-discover 한다. app-bootstrap Testcontainers 테스트가 와이어링 갭을 드러내면 부트스트랩이 `setTransactionManager` @@ -387,8 +466,133 @@ provider 선택표(flag → bean → registry)의 SSOT 는 CLAUDE.md(또는 app- `DistributedLock.tryLock(waitTime, leaseTtl)` 로 전달한다. ### `LockSettings` -`ca-skeleton.lock.*` 에서 바인딩되는 yaml-only 기본값이다. 새 `APP_*` env 키가 아니므로 -`env-keys.yaml` 엔트리가 필요 없다. bootstrap 의 `@ConfigurationPropertiesScan` 으로 잡혀 -`@EnableConfigurationProperties` 명시가 필요 없다. cross-field invariant: `leaseTtl >= waitTime` +`ca-skeleton.lock.*` 에서 바인딩되는 yaml-only 기본값이다(`config/module-defaults/persistence-jpa.yml`). +새 `APP_*` env 키가 아니므로 `env-keys.yaml` 엔트리가 필요 없다. `DistributedLockPersistenceConfig`의 +`@EnableConfigurationProperties`가 바인딩한다. cross-field invariant: `leaseTtl >= waitTime` 이어야 한다 — TTL 이 waitTime 보다 먼저 만료되면 첫 holder 의 보호작업이 끝나기 전에 두 번째 holder 가 락을 잡을 수 있다. + +### `MeteredDistributedLockPort` (app-bootstrap에서 이동) +- **`DistributedLockPort`를 감싸는 얇은 Micrometer 데코레이터다.** `tryAcquire` 호출마다 + `lock.acquisition` 카운터를 `outcome` 태그와 함께 1 증가시킨다. 태그 값은 세 가지: `acquired`(락 + 획득 성공, 위임 핸들 반환), `timeout`(`LockAcquisitionTimeoutException` 발생), `error`(그 외 모든 + `RuntimeException` 발생). 메트릭 이름과 태그 값은 `docs/registries/metrics.yaml`의 `lock.acquisition` + 행과 일치해야 한다. +- **리스 만료(lease-expiry) CME 흡수.** 보유자가 `close()`를 호출하기 전에 리스(저장소 TTL)가 + 만료되면 그 락 행은 이미 다른 인스턴스가 회수해 갔을 수 있고, 그 시점에 내부 `JdbcLock.unlock()`은 + `ConcurrentModificationException`(CME)을 던진다. 이 예외를 호출자의 `finally { lock.close(); }` + 블록 밖으로 그대로 전파하면 보호 구간(critical section)에서 발생한 본래 예외를 가려버린다 + (masking). 그래서 CME 만 잡아 WARN 로그를 남기고 태그 없는 `lock.lease.expired` 카운터를 1 + 증가시킨 뒤 `close()`는 정상 복귀시킨다. 이렇게 해야 신호(로그+메트릭)는 남기면서도 호출자의 정상 + 흐름과 예외 전파를 방해하지 않는다. 오직 `ConcurrentModificationException`만 흡수하며, DB 장애 같은 + 다른 예외(예: `DataAccessResourceFailureException`)는 리스 만료 신호가 아니므로 손대지 않고 그대로 + 전파한다. +- **MeterRegistry 부재 시 no-op.** 레지스트리를 `ObjectProvider.getIfAvailable()`로 해석하므로 + 클래스패스에 `MeterRegistry` 빈이 없으면(Actuator 미탑재) 모든 메트릭 연산이 조용히 no-op 이 + 된다. `BackgroundJobMetrics` 선례와 동일한 패턴이다. +- **메트릭 실패가 락 경로를 절대 깨뜨리지 않음.** 카운터 등록·증가는 모두 try/catch 로 감싸 예외를 + 로깅 후 삼킨다(log-and-swallow). Micrometer 쪽 실패가 락 획득·보유·실패 보고를 막는 일은 없어야 + 하기 때문이다. + +--- + +## startup — 관계형 기동 정책 (app-bootstrap에서 이동) + +`JpaStartupAutoConfiguration`(package-private, 모듈 스위치 `ca-skeleton.persistence-jpa.enabled` +아래)이 아래 가드를 등록한다. 전부 `adapter:outbound:support`의 `StartupFailures`로 실패하므로 exit +코드(78/70/71)와 구조화 로그 필드(`startup.phase`/`error.code`/`error.category`)는 옮기기 전과 같다. +`migrationStartupRunner`는 `@ConditionalOnMissingBean(FlywayMigrationStrategy)`라, 자기 전략을 둔 +애플리케이션(sample-portfolio의 두 번째 마이그레이션 스트림)에는 끼어들지 않는다. + +### FlywayProdSafetyValidator +- **`prod` 프로파일에서 Flyway 안전장치가 꺼지지 못하도록 런타임에서 강제한다.** Flyway 옵션은 + `application.yml`에 안전값으로 고정돼 있지만(`baseline-on-migrate=false`, `out-of-order=false`, + `clean-disabled=true`), 환경별 override 가 프로덕션에서 이 값을 조용히 되돌릴 수 있다. 이 검증기는 + 그런 override 를 시작 시점에 잡아 `PROFILE_MISMATCH`(exit 71)로 부팅을 막는다. +- **금지하는 옵션은 각각 "복구 불가능한 위험" 때문이다.** `baseline-on-migrate=true`는 누락된 + 마이그레이션을 감지하는 안전망을 없애고, `out-of-order=true`는 개발자 간 마이그레이션 적용 순서 + 일관성을 깨며, `clean-disabled=false`는 스키마 전체를 드롭하는 파괴적 `clean` 명령을 다시 + 활성화한다. +- **프로파일 비교는 대소문자를 무시한다.** `SPRING_PROFILES_ACTIVE=PROD`처럼 대문자 오타가 나도 + 가드가 우회되지 않게 하기 위함이다. +- **Flyway repair 는 가드 대상이 아니다.** repair 는 property 가 아니라 Flyway 명령이고 스켈레톤은 + repair 호출 경로 자체를 배선하지 않으므로, "prod 에서 repair 금지"는 런타임 트리거가 없는 + 문서화된 정책으로 남는다. 부분 스키마 복구는 in-prod Flyway repair 가 아니라 + runbook(`runbook://migration/manual-recovery`)을 통한 수동 복구로 가도록 실패 메시지에 명시한다. + (프로젝트가 repair 경로를 추가한다면 동일하게 prod 게이트 + non-prod 감사 로그를 걸어야 한다.) + +### RequiredEnvironmentValidator +- **datasource 연결 환경변수를 마이그레이션 실행 전에 검증해 부팅을 빨리 실패시킨다.** Flyway + forward-only 마이그레이션은 context refresh 동안 애플리케이션 datasource 에 대해 실행된다. 연결 + 환경변수가 빠져 있으면 마이그레이션은 시작 단계 구분자 없이 불투명한 driver/connection 에러로 + 한참 뒤에야 실패한다. 이 검증기는 그것을 명시적인 env 검증 실패(`STARTUP_VALIDATION_FAILED`, + exit 78)로 바꿔, 누락된 운영자용 env 키를 전부 이름으로 짚어준다. +- **검증 범위를 datasource 3종(url/username/driver)으로 의도적으로 좁혔다.** 이것들이 이 브랜치가 + 소유하는 마이그레이션 전제조건이기 때문이다. app-name(`BootstrapSettings`), issuer-uri(security + settings) 등 다른 필수값은 각 모듈의 가드가 책임지므로 여기서 중복 검증하지 않는다. +- **값이 없거나(blank) 공백이면 모두 "누락"으로 본다.** spring-dotenv 에서 미설정 placeholder + `${...}`가 빈 문자열로 해석되기 때문에, null 뿐 아니라 blank 도 누락으로 처리해야 빈틈이 없다. +- **메시지는 env 키 이름순으로 정렬해 출력한다.** Map 순회 순서와 무관하게 결정적이고 안정적인 실패 + 메시지를 보장하기 위함이다. + +### `JpaStartupAutoConfiguration` (옛 `MigrationStartupConfig`·`PersistenceJpaRootAutoConfiguration`·`JpaPlatformRuntimeAutoConfiguration`) +- **마이그레이션 전략과 관계형 기동 가드를 한곳에 모은다.** app-bootstrap에서는 네 개 설정 클래스와 + `RuntimeSafetyConfig`의 validator 목록에 흩어져 있었고, JPA 스위치를 합성 루트가 알아야 했다. + `JpaPlatformAutoConfiguration`(플랫폼 조립 factory)은 지웠고, 보고서 조립은 `JpaPlatformReport`로 + 옮겼다. +- **`migrationStartupRunner` 빈 이름은 유지한다.** Spring Boot Flyway 오토컨피규레이션이 + `migrate()`를 위임하는 `FlywayMigrationStrategy`다. + +### MigrationStartupRunner +- **`FlywayMigrationStrategy`로 등록해 context refresh 중에 마이그레이션을 직접 실행한다(오토컨피그 + 기본값을 그대로 두지 않는다).** refresh 안에서 실행한다는 것은 마이그레이션이 완료되거나 부팅을 + 실패시키는 일이 애플리케이션이 readiness 를 보고하기 *전에* 일어난다는 뜻이다. 따라서 절반만 + 마이그레이션된 스키마가 트래픽을 받는 일이 구조적으로 없다(actuator readiness probe 의 형태 + 자체는 health-lifecycle 브랜치가 소유하고, 여기서는 "마이그레이션 → ready" 순서만 책임진다). +- **`FlywayException`을 `MigrationFailedException`(exit 70)으로 번역한다.** 일반적이고 구분 안 되는 + 스택트레이스 대신 구조화된 `MIGRATION_FAILED` 로그와 표준 exit 코드를 남기기 위함이다. +- **멀티 인스턴스에서는 in-app 마이그레이션 + Flyway 자체 schema-history 락에 의존하는 것이 기본 + 전략이다.** 여러 레플리카의 동시 `migrate()`를 Flyway 의 락이 직렬화한다. 대안인 "in-app + 마이그레이션을 끄고 플랫폼 one-shot Job 으로 돌리기"는 "migration=Job"을 강제하는 공개 표준이 + 없는 배포 선택이라 스켈레톤 기본값이 아니다. Job 으로 돌리는 프로젝트는 이 빈의 `migrate()`를 + no-op 으로 만들면 된다. + +### HikariPoolConstraintValidator +- **HikariCP 노브 사이의 상호 제약을 부팅 실패로 바꾼다.** Hikari/Tomcat 은 잘못된 값을 결국 + 거부하지만 pool/connector 초기화 시점에 난해한 메시지로만 거부한다. 이 검증기는 계약을 일찍·명확 + 하게 만든다: resolved Spring property 를 읽고, 위반을 모두 모아 운영자가 실제로 설정한 `APP_*` + 환경 키를 메시지에 담아 `IllegalStateException`을 던진다. 속성이 *없으면* 건너뛰고(placeholder/ + 프레임워크 기본값이 소유), *있을 때만* 검사한다. +- **강제하는 제약과 그 숫자의 근거.** `connection-timeout >= 250ms`(너무 짧으면 정상 연결도 타임 + 아웃). `validation-timeout < connection-timeout`(둘 다 있을 때; validation-timeout 기본 5000ms 가 + 흔한 connection-timeout 5s/5000ms 와 같아지는 충돌을 해소). `keepalive-time < max-lifetime`(둘 다 + 있을 때; keepalive 가 lifetime 보다 길면 의미 없음). `leak-detection-threshold`는 0(비활성)이 + 아니라면 `>= 2000ms`(너무 작으면 정상 사용을 누수로 오탐). +- **Spring Boot와 같은 Duration 문법을 검증한다.** `env-keys.yaml`의 `connection-timeout` + 기본값은 `5s`인데 `src/.env`는 `30000`(ms)을 준다. resolved 값을 `String`으로 읽은 뒤 + `DurationStyle`로 plain milliseconds, simple duration(`5s`)과 ISO-8601(`PT5S`)을 같은 + milliseconds 계약으로 변환한다. present-but-invalid 값은 부재로 조용히 취급하지 않고 property + 이름을 포함한 startup validation failure로 거절한다. +- **env 키가 아직 없는 노브는 "env key pending" 문구를 쓴다.** `connection-timeout` / + `max-lifetime`만 `env-keys.yaml`에 등록돼 있고, greenfield 노브(validation-timeout, keepalive-time, + leak-detection-threshold)는 env 키가 없다. 없는 키 이름을 지어내는 대신 pending 문구를 메시지에 넣는다. + +### OpenInViewSafetyValidator +- **OSIV(Open Session In View) OFF 를 hard stop 으로 강제한다.** OSIV 가 켜져 있으면 Hibernate + 세션이 view 렌더링까지 열려 있어, presentation 레이어에서 lazy 연관을 건드리면 거기서 조용히 DB + 쿼리가 나간다 — 이것이 정확히 금지된 레이어 경계 위반이다. Spring Boot 는 + `spring.jpa.open-in-view`가 암묵 기본값일 때 WARN 만 찍을 뿐 명시적으로 `true`로 설정한 배포는 + 막지 못한다. WARN 은 놓치기 쉬우므로, resolved 값이 `true`면 운영자가 실제 설정한 + `APP_DATASOURCE_OPEN_IN_VIEW` 키를 메시지에 담아 부팅을 실패시킨다. +- **읽기만 하고 re-bind 하지 않으며, 부재 값은 Spring 기본에 맡긴다.** `SmartInitializingSingleton` + 으로 한 번만 검사하고, 값이 *없으면* Spring Boot 기본(이 스켈레톤은 `application.yml`에서 OSIV off + 가 기본)에 맡기며 *있는 `true`*만 거부한다. + +### JpaSchemaSafetyValidator +- **Flyway를 production physical schema의 유일한 writer로 유지한다.** `prod` profile에서는 + `spring.jpa.hibernate.ddl-auto`가 `none` 또는 `validate`일 때만 허용한다. `update`, `create`, + `create-drop` 또는 그 밖의 값이면 `APP_DATASOURCE_DDL_AUTO`를 이름으로 포함한 + `PROFILE_MISMATCH`로 부팅을 중단한다. +- **local 개발 편의와 production 권위를 분리한다.** non-prod profile의 `update`/`create`는 이 + validator가 막지 않는다. prod profile 비교와 mode 비교는 대소문자를 무시해 `PROD`/`UPDATE` + 같은 변형도 guard를 우회하지 못한다. diff --git a/src/adapter/outbound/persistence-jpa/build.gradle b/src/adapter/outbound/persistence-jpa/build.gradle index d40cf578..84453058 100644 --- a/src/adapter/outbound/persistence-jpa/build.gradle +++ b/src/adapter/outbound/persistence-jpa/build.gradle @@ -3,7 +3,6 @@ plugins { id 'ca.spring-config' id 'java-test-fixtures' id 'ca.jpa-evidence' - id 'ca.jpa-test-lanes' id 'ca.auxiliary-source-set' id 'ca.api-surface' } @@ -41,6 +40,15 @@ dependencies { // were a package in this leaf, and that is how every application with a database also resolved // the Fileserver use cases. They are `adapter:outbound:persistence-fileserver` now. implementation project(':shared-contract') + // Typed startup failures, the EnvironmentPostProcessor order, the readiness-group merge and the + // module-defaults loader this leaf's startup policy and shipped settings go through. + implementation project(':adapter:outbound:support') + // Structured fields on the migration, relay and lock log lines (StructuredArguments). + implementation libs.logstash.logback.encoder + // The read-only /actuator/jpaplatform view. compileOnly: this module does not bring actuator; + // the endpoint is registered only when the application already has it. + compileOnly 'org.springframework.boot:spring-boot-actuator' + testImplementation 'org.springframework.boot:spring-boot-actuator' implementation 'org.springframework.boot:spring-boot-starter-data-jpa' // feature-distributed-lock-contract: Spring Integration JDBC LockRegistry backs the @@ -60,8 +68,8 @@ dependencies { runtimeOnly 'com.h2database:h2' // JPA platform observability (design §37). Micrometer's observation API already arrives with - // Spring; the meter registry does not, and the platform's transaction/query/retry metrics need - // it. Version managed by the Spring Boot BOM. + // Spring; the meter registry does not, and MicrometerQueryObservation (library API, not composed) + // needs it. Version managed by the Spring Boot BOM. implementation 'io.micrometer:micrometer-core' // Querydsl and Envers are Advanced opt-ins (design §4.2): the platform implements their @@ -85,6 +93,14 @@ dependencies { // dependency graph — the thing Build Composition governs — is untouched. postgresqlIntegrationTestImplementation project(':adapter:outbound:persistence-fileserver') postgresqlIntegrationTestImplementation project(':application-fileserver') + // The provider-event replay worker lives in the notification adapter and only fails against a + // real JPA stack with no caller transaction, so its real-DB test runs here beside the + // notification stores. Test scope only, like the Fileserver edge. Non-transitive: the worker + // needs only application-notification, which this lane already has, and the adapter's + // mail/Thymeleaf/actuator graph has no business on a database lane. + postgresqlIntegrationTestImplementation(project(':adapter:outbound:notification')) { + transitive = false + } postgresqlIntegrationTestImplementation testFixtures(project(':application-core')) postgresqlIntegrationTestImplementation 'org.testcontainers:testcontainers-postgresql' postgresqlIntegrationTestImplementation 'org.testcontainers:testcontainers-junit-jupiter' @@ -119,10 +135,66 @@ dependencies { jpaPlatformPerformanceTestRuntimeOnly 'org.postgresql:postgresql' } -// PostgreSQL readiness, tagged platform, and pool-contract lanes are owned by -// `ca.jpa-test-lanes`. Their metadata is represented as Java records, so task names, selectors, -// tags, descriptions and runtime property wiring are compiled rather than assembled from Groovy Maps. -// The security lane includes the runtime-role namespace-denial method selector in that typed model. +// Real-PostgreSQL lanes. A readiness lane runs one named class (the security lane also names the +// runtime-role namespace-denial method), a platform lane selects a tag, and the pool lane has a +// source set of its own. jpa-release.yml and config/jpa/*.{json,yaml} name these tasks. +def jpaEvidenceImage = providers.gradleProperty('jpaPostgreSqlEvidenceImage').orElse('postgres:16-alpine').get() +def jpaMatrixVersions = providers.gradleProperty('jpa.matrix.versions').orElse('16').get() +def readinessLanes = [ + postgresqlLifecycleIntegrationTest : ['PostgreSqlLifecycleIntegrationTest'], + postgresqlSecurityBaselineIntegrationTest : ['PostgreSqlSecurityBaselineIntegrationTest', + 'runtimeRoleCannotCreateInApplicationSchemaOrTempAndUsesTrustedSearchPath'], + postgresqlMigrationIntegrationTest : ['PostgreSqlMigrationIntegrationTest'], + postgresqlIntLockMigrationCompatibilityIntegrationTest : ['PostgreSqlIntLockMigrationCompatibilityIntegrationTest'], + postgresqlTransactionIntegrationTest : ['PostgreSqlTransactionIntegrationTest'], + postgresqlDistributedLockIntegrationTest : ['PostgreSqlDistributedLockIntegrationTest'], + postgresqlAggregateIntegrationTest : ['PostgreSqlAggregateIntegrationTest'], + postgresqlQueryIntegrationTest : ['PostgreSqlQueryIntegrationTest'], + postgresqlIdempotencyIntegrationTest : ['PostgreSqlIdempotencyIntegrationTest'], + postgresqlLegacyOutboxAppendTransactionalIntegrationTest: ['PostgreSqlLegacyOutboxAppendTransactionalIntegrationTest'], + postgresqlLegacyOutboxConcurrentRelayIntegrationTest : ['PostgreSqlLegacyOutboxConcurrentRelayIntegrationTest'], + postgresqlLegacyOutboxRowLifecycleIntegrationTest : ['PostgreSqlLegacyOutboxRowLifecycleIntegrationTest'], + postgresqlFileserverMigrationIntegrationTest : ['PostgreSqlFileserverMigrationIntegrationTest'], + postgresqlFileserverMetadataIntegrationTest : ['PostgreSqlFileserverMetadataStoreIntegrationTest'], + postgresqlFileserverReclamationIntegrationTest : ['PostgreSqlFileserverReclamationIntegrationTest'], + postgresqlNotificationSchemaActivationIntegrationTest : ['PostgreSqlNotificationSchemaActivationIntegrationTest'], +] +def platformLanes = [ + jpaPlatformContractTest : ['jpa-contract', 'Runs the JPA platform contract suite against real PostgreSQL (design §40).'], + jpaPlatformMigrationTest: ['jpa-migration', 'Runs the Flyway upgrade snapshot scenarios (design §31).'], + jpaPlatformFailureTest : ['jpa-failure', 'Reproduces deadlock, serialization, and commit-ambiguity failures (design §39).'], + jpaPlatformQueryPlanTest: ['jpa-queryplan', 'Asserts query plan structure and planner estimate error (design §33).'], + jpaPlatformSecurityTest : ['jpa-security', 'Verifies runtime role privileges and search_path safety (design §36).'], +] +strictTestLanes { + readinessLanes.each { taskName, selection -> + String testClass = 'dev.caskeleton.adapter.outbound.persistence.readiness.' + selection[0] + lane(taskName) { + integration() + sourceSet = 'postgresqlIntegrationTest' + description = 'Runs the no-skip real PostgreSQL readiness scenario ' + testClass + '.' + requires testClass + selection.drop(1).each { method -> requires testClass + '.' + method } + jvmArgs '-Duser.timezone=UTC', '-Djpa.evidence.postgresql.image=' + jpaEvidenceImage + } + } + platformLanes.each { taskName, selection -> + lane(taskName) { + integration() + sourceSet = 'postgresqlIntegrationTest' + tag = selection[0] + description = selection[1] + jvmArgs '-Duser.timezone=UTC' + systemProperty 'jpa.matrix.versions', jpaMatrixVersions + } + } + lane('jpaPlatformPoolContractTest') { + performance() + sourceSet = 'jpaPlatformPerformanceTest' + description = 'Verifies Hikari pool and REQUIRES_NEW connection behaviour (design §38).' + jvmArgs '-Duser.timezone=UTC' + } +} tasks.named('postgresqlSecurityBaselineIntegrationTest') { // Cross-leaf task edge: see the handoff. verifyCleanArchitectureDependencies inspects @@ -150,6 +222,12 @@ tasks.named('test') { inputs.dir(new File(rootProject.projectDir.parentFile, '.github/workflows')) inputs.file(file('build.gradle')) inputs.dir(file('src/jpaPlatformPerformanceTest/java')) + // JpaAdopterApiSurfaceTest: every other leaf's production sources and the adopter baseline. + inputs.file(new File(rootProject.projectDir.parentFile, 'docs/architecture/jpa-adopter-api-surface.txt')) + inputs.files(fileTree(rootProject.projectDir) { + include '**/src/main/java/**/*.java' + exclude '**/build/**', 'adapter/outbound/persistence-jpa/**', 'adapter/outbound/persistence-fileserver/**' + }).withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName('adopterSources') } // verifyJpaApiSurface — every public type this leaf exposes is a committed decision. @@ -178,9 +256,9 @@ apiSurface { -// The JPA readiness registry describes this platform's lanes and resolves their task paths, so it -// runs with this leaf's `check` rather than with all 62. The task itself is registered by -// the ca.jpa-qualification plugin from build-tools, which the root applies. -tasks.named('check') { +// The JPA readiness registry describes this platform's lanes and resolves their task paths. It runs +// in the main-branch stage (`mainCheck`), not in `check`. The task itself is registered by the +// ca.jpa-qualification plugin from build-tools, which the root applies. +tasks.named('mainCheck') { dependsOn rootProject.tasks.named('verifyJpaReadinessRegistry') } diff --git a/src/adapter/outbound/persistence-jpa/gradle.lockfile b/src/adapter/outbound/persistence-jpa/gradle.lockfile index e55a23e8..35516576 100644 --- a/src/adapter/outbound/persistence-jpa/gradle.lockfile +++ b/src/adapter/outbound/persistence-jpa/gradle.lockfile @@ -78,6 +78,7 @@ jaxen:jaxen:2.0.6=spotbugs net.bytebuddy:byte-buddy-agent:1.17.8=jpaPlatformPerformanceTestCompileClasspath,jpaPlatformPerformanceTestRuntimeClasspath,postgresqlIntegrationTestCompileClasspath,postgresqlIntegrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath net.bytebuddy:byte-buddy:1.17.8=jpaPlatformPerformanceTestCompileClasspath,jpaPlatformPerformanceTestRuntimeClasspath,postgresqlIntegrationTestCompileClasspath,postgresqlIntegrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath net.java.dev.jna:jna:5.18.1=jpaPlatformPerformanceTestCompileClasspath,jpaPlatformPerformanceTestRuntimeClasspath,postgresqlIntegrationTestCompileClasspath,postgresqlIntegrationTestRuntimeClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +net.logstash.logback:logstash-logback-encoder:8.0=compileClasspath,jpaPlatformPerformanceTestCompileClasspath,jpaPlatformPerformanceTestRuntimeClasspath,postgresqlIntegrationTestCompileClasspath,postgresqlIntegrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath net.minidev:accessors-smart:2.6.0=jpaPlatformPerformanceTestCompileClasspath,jpaPlatformPerformanceTestRuntimeClasspath,postgresqlIntegrationTestCompileClasspath,postgresqlIntegrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath net.minidev:json-smart:2.6.0=jpaPlatformPerformanceTestCompileClasspath,jpaPlatformPerformanceTestRuntimeClasspath,postgresqlIntegrationTestCompileClasspath,postgresqlIntegrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath net.sf.saxon:Saxon-HE:12.9=checkstyle,spotbugs @@ -159,6 +160,7 @@ org.slf4j:jul-to-slf4j:2.0.18=compileClasspath,jpaPlatformPerformanceTestCompile org.slf4j:slf4j-api:2.0.18=compileClasspath,jpaPlatformPerformanceTestCompileClasspath,jpaPlatformPerformanceTestRuntimeClasspath,postgresqlIntegrationTestCompileClasspath,postgresqlIntegrationTestRuntimeClasspath,runtimeClasspath,spotbugs,spotbugsSlf4j,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j org.slf4j:slf4j-simple:2.0.18=checkstyle +org.springframework.boot:spring-boot-actuator:4.0.8=compileClasspath,jpaPlatformPerformanceTestCompileClasspath,jpaPlatformPerformanceTestRuntimeClasspath,postgresqlIntegrationTestCompileClasspath,postgresqlIntegrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-autoconfigure:4.0.8=compileClasspath,jpaPlatformPerformanceTestCompileClasspath,jpaPlatformPerformanceTestRuntimeClasspath,postgresqlIntegrationTestCompileClasspath,postgresqlIntegrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath org.springframework.boot:spring-boot-configuration-processor:4.0.8=annotationProcessor org.springframework.boot:spring-boot-data-commons:4.0.8=compileClasspath,jpaPlatformPerformanceTestCompileClasspath,jpaPlatformPerformanceTestRuntimeClasspath,postgresqlIntegrationTestCompileClasspath,postgresqlIntegrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/capability/CapabilitySupport.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/capability/CapabilitySupport.java index 290b8948..e8e05215 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/capability/CapabilitySupport.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/capability/CapabilitySupport.java @@ -42,7 +42,7 @@ public record CapabilitySupport( return new CapabilitySupport(capability, SupportLevel.ADVANCED, List.of(constraints)); } - /** Declares a capability that is only reachable behind an experimental feature flag. */ + /** Declares a capability that is experimental library code, never composed by default. */ public static CapabilitySupport experimental(JpaCapability capability, String... constraints) { return new CapabilitySupport(capability, SupportLevel.EXPERIMENTAL, List.of(constraints)); } diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/capability/JpaCapability.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/capability/JpaCapability.java index 77a4ffd3..a1c58017 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/capability/JpaCapability.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/capability/JpaCapability.java @@ -9,9 +9,6 @@ package dev.caskeleton.adapter.outbound.persistence.api.capability; */ public enum JpaCapability { - /** Full use-case retry in a new transaction and a new Persistence Context (design §19). */ - TRANSACTION_RETRY("transaction.retry"), - /** Commit-phase evidence tracking that yields completion-unknown instead of a guess (§17). */ COMPLETION_EVIDENCE("transaction.completion-evidence"), @@ -21,9 +18,6 @@ public enum JpaCapability { /** Verified JDBC batch execution with bounded Persistence Context growth (§28). */ BATCH("write.jdbc-batch"), - /** Registered PostgreSQL {@code ON CONFLICT} / {@code RETURNING} writes (§8.3). */ - POSTGRESQL_NATIVE_WRITE("postgresql.native-write"), - /** Flyway-owned schema with a fail-closed Hibernate validate gate (§31). */ SCHEMA_GATE("migration.schema-gate"), @@ -33,9 +27,6 @@ public enum JpaCapability { /** Opt-in Hibernate Envers entity history (§35). */ ENVERS("history.envers"), - /** PostgreSQL {@code FOR UPDATE SKIP LOCKED} queue claims (§21.3). */ - POSTGRESQL_WORK_CLAIM("postgresql.work-claim"), - /** Versioned JSONB document mapping and registered path queries (§8.3). */ POSTGRESQL_JSONB("postgresql.jsonb"), @@ -54,7 +45,7 @@ public enum JpaCapability { /** Runtime database role and {@code search_path} verification (§36). */ RUNTIME_ROLE_VERIFICATION("security.runtime-role"), - /** Bounded-tag metrics, tracing, and redacted SQL diagnostics (§37). */ + /** Bounded-tag query metrics and redacted SQL diagnostics (§37). */ OBSERVABILITY("observability.jpa"); private final String id; diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/capability/SupportLevel.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/capability/SupportLevel.java index 0f7ec46c..e6a4509c 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/capability/SupportLevel.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/capability/SupportLevel.java @@ -14,7 +14,7 @@ public enum SupportLevel { /** Available, but requires an explicit module dependency, registration, or capability token. */ ADVANCED, - /** Behind a {@code backend.jpa.experimental.*} flag; never part of the Stable composition. */ + /** Library code a deployment calls itself; never part of the Stable composition. */ EXPERIMENTAL, /** Explicitly out of scope (design §4.4); selecting it is a configuration error. */ diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/error/SqlExceptionSqlStateResolver.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/error/SqlExceptionSqlStateResolver.java index 6eac9cfa..0fe92f42 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/error/SqlExceptionSqlStateResolver.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/error/SqlExceptionSqlStateResolver.java @@ -5,8 +5,10 @@ import java.util.IdentityHashMap; import java.util.Optional; /** - * The vendor-neutral {@link SqlStateResolver}: walks the cause chain for a {@link SQLException} and - * reads its {@linkplain SQLException#getSQLState() SQLSTATE}. + * Extracts the SQLSTATE from a provider exception chain (design §18.2): walks the cause chain for a + * {@link SQLException} and reads its {@linkplain SQLException#getSQLState() SQLSTATE}. It reads + * structured driver fields only and never parses a localized message, which changes with server + * locale and version. * *

{@link SQLException#getNextException()} is followed as well as {@link Throwable#getCause()}. * Drivers chain batch failures through {@code getNextException}, and the state that explains the @@ -16,11 +18,11 @@ import java.util.Optional; * Hibernate, JDBC, the driver — and a chain that loops back on itself would otherwise hang the * thread that is trying to report an error. */ -public final class SqlExceptionSqlStateResolver implements SqlStateResolver { +public final class SqlExceptionSqlStateResolver { private static final int MAX_DEPTH = 64; - @Override + /** The SQLSTATE this failure carries, when the chain exposes one. */ public Optional resolve(Throwable failure) { IdentityHashMap seen = new IdentityHashMap<>(); Throwable current = failure; diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/error/SqlStateResolver.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/error/SqlStateResolver.java deleted file mode 100644 index 7fa59c30..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/error/SqlStateResolver.java +++ /dev/null @@ -1,17 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.api.error; - -import java.util.Optional; - -/** - * Extracts the SQLSTATE from a provider exception chain (design §18.2). - * - *

This is an SPI so the transaction module never depends on a vendor package: the commit-phase - * classifier needs a SQLSTATE, not a PostgreSQL driver. Implementations must read structured driver - * fields and must never parse a localized message, which changes with server locale and version. - */ -@FunctionalInterface -public interface SqlStateResolver { - - /** The SQLSTATE this failure carries, when the chain exposes one. */ - Optional resolve(Throwable failure); -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/error/VendorFailureTranslator.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/error/VendorFailureTranslator.java deleted file mode 100644 index 196fe6a5..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/error/VendorFailureTranslator.java +++ /dev/null @@ -1,33 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.api.error; - -import dev.caskeleton.adapter.outbound.persistence.api.PersistenceOperationName; -import java.time.Duration; - -/** - * Turns a vendor's raw failure into a classified one. - * - *

Declared in {@code api} so the vendor-neutral transaction package can call a vendor translator - * without naming one. Depending on {@code postgresql} directly from {@code transaction} closes a - * cycle — the PostgreSQL configuration already depends on the transaction package for its SPI — and - * a cycle between two packages the module map describes as layered has to be unpicked from both - * ends before either can move. - */ -@FunctionalInterface -public interface VendorFailureTranslator { - - /** - * Classifies one failure. - * - * @param failure what the attempt threw - * @param operation the registered operation the attempt served - * @param attempt the 1-based attempt number - * @param elapsed how long the attempt ran - * @param traceId the current trace identifier, or {@code null} - */ - JpaPersistenceException translate( - Throwable failure, - PersistenceOperationName operation, - int attempt, - Duration elapsed, - String traceId); -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/query/CursorCodec.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/query/CursorCodec.java deleted file mode 100644 index d8a5fa0f..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/query/CursorCodec.java +++ /dev/null @@ -1,22 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.api.query; - -/** - * Encodes and decodes an opaque page cursor (design §27.3). - * - *

A cursor crosses the trust boundary: it is handed to a client and comes back. An - * implementation must therefore treat {@link #decode(String)} input as hostile and reject anything - * it did not produce, rather than parsing whatever arrives. - */ -public interface CursorCodec { - - /** Encodes a cursor into a client-safe, tamper-evident token. */ - String encode(C cursor); - - /** - * Decodes a token this codec produced. - * - * @throws IllegalArgumentException if the token is malformed, of an unknown version, or its - * signature does not verify - */ - C decode(String encoded); -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/query/SignedJsonCursorCodec.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/query/SignedJsonCursorCodec.java index 7c306cd8..e00104ac 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/query/SignedJsonCursorCodec.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/query/SignedJsonCursorCodec.java @@ -23,7 +23,7 @@ import javax.crypto.spec.SecretKeySpec; *

Verification is constant-time via {@link MessageDigest#isEqual}. A short-circuiting comparison * here leaks the correct MAC one byte at a time. */ -public final class SignedJsonCursorCodec implements CursorCodec { +public final class SignedJsonCursorCodec { /** The only cursor version this codec issues and accepts. */ public static final String VERSION = "v1"; @@ -59,7 +59,7 @@ public final class SignedJsonCursorCodec implements CursorCodec { /** HMAC-SHA256 produces exactly this many bytes. */ private static final int MAC_LENGTH_BYTES = 32; - @Override + /** Encodes a cursor into a client-safe, tamper-evident token. */ public String encode(C cursor) { Objects.requireNonNull(cursor, "cursor"); byte[] json = payloadCodec.toJson(cursor).getBytes(StandardCharsets.UTF_8); @@ -79,7 +79,13 @@ public final class SignedJsonCursorCodec implements CursorCodec { return token; } - @Override + /** + * Decodes a token this codec produced. The input crosses the trust boundary, so anything this + * codec did not produce is rejected rather than parsed. + * + * @throws IllegalArgumentException if the token is malformed, of an unknown version, or its + * signature does not verify + */ public C decode(String encoded) { if (encoded == null || encoded.isBlank()) { throw new IllegalArgumentException("cursor must not be blank"); diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/transaction/IsolationLevel.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/transaction/IsolationLevel.java deleted file mode 100644 index 63f5c16d..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/transaction/IsolationLevel.java +++ /dev/null @@ -1,22 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.api.transaction; - -/** - * The isolation levels the Stable platform exposes (design §9.2, §16.2). - * - *

{@code READ_UNCOMMITTED} is absent: PostgreSQL treats it as {@code READ COMMITTED}, so - * offering it would let a profile claim an isolation the database never provides. - */ -public enum IsolationLevel { - - /** Whatever the connection is configured with; on PostgreSQL that is read committed. */ - DEFAULT, - - /** The Stable default for both read and write profiles. */ - READ_COMMITTED, - - /** Snapshot-stable reads within the transaction. */ - REPEATABLE_READ, - - /** Full serializability; expect {@code 40001} and pair it with a retry profile. */ - SERIALIZABLE -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/transaction/JitterMode.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/transaction/JitterMode.java deleted file mode 100644 index 0f78400a..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/transaction/JitterMode.java +++ /dev/null @@ -1,19 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.api.transaction; - -/** - * How retry backoff is randomised (design §19.3). - * - *

Jitter is not cosmetic here: without it, every contender in a deadlock or serialization storm - * recomputes the same backoff and collides again at the same instant. - */ -public enum JitterMode { - - /** Deterministic backoff. Only appropriate for tests and single-writer work. */ - NONE, - - /** Uniform in {@code [0, backoff]} — the strongest de-synchronisation. */ - FULL, - - /** Uniform in {@code [backoff/2, backoff]} — keeps a floor under the wait. */ - EQUAL -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/transaction/JpaRetryPolicy.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/transaction/JpaRetryPolicy.java deleted file mode 100644 index 06962452..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/transaction/JpaRetryPolicy.java +++ /dev/null @@ -1,22 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.api.transaction; - -import dev.caskeleton.adapter.outbound.persistence.api.error.JpaPersistenceException; - -/** - * Decides what may be done about one failed attempt (design §9.4). - * - *

A policy classifies; it never executes. Keeping the decision separate from the retry loop is - * what makes "completion unknown is never retried" a property that can be unit-tested without a - * database. - */ -@FunctionalInterface -public interface JpaRetryPolicy { - - /** - * Classifies a failure into a disposition, a backoff, and a bounded reason. - * - * @param failure the stable failure produced by the exception translator - * @param attempt the 1-based attempt that produced it - */ - RetryDecision classify(JpaPersistenceException failure, TransactionAttempt attempt); -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/transaction/JpaTransactionExecutor.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/transaction/JpaTransactionExecutor.java deleted file mode 100644 index 49a7ac1e..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/transaction/JpaTransactionExecutor.java +++ /dev/null @@ -1,24 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.api.transaction; - -import dev.caskeleton.adapter.outbound.persistence.api.PersistenceOperationName; -import java.util.function.Supplier; - -/** - * Runs one unit of work inside exactly one transaction described by a profile (design §9.3). - * - *

This interface owns the transaction boundary and nothing else. Retry is deliberately not part - * of it: a retry that reused the same executor call would reuse the same Persistence Context, which - * is precisely the bug the design forbids. The retry coordinator calls this interface again, - * getting a new transaction and a new context each time. - */ -public interface JpaTransactionExecutor { - - /** - * Executes {@code work} inside one transaction configured by {@code profile}. - * - * @param operation the registered, bounded identity used for observation and policy lookup - * @param profile propagation, isolation, timeout, and read-only for this single transaction - * @param work the unit of work; it must be safe to run again from scratch in a new transaction - */ - T execute(PersistenceOperationName operation, TransactionProfile profile, Supplier work); -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/transaction/PropagationMode.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/transaction/PropagationMode.java deleted file mode 100644 index 4775b7d0..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/transaction/PropagationMode.java +++ /dev/null @@ -1,25 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.api.transaction; - -/** - * The propagation values the Stable platform supports (design §9.2, §16.1). - * - *

The list is deliberately short. {@code NESTED}, {@code SUPPORTS}, {@code NOT_SUPPORTED}, and - * {@code NEVER} are absent because each one silently changes whether the caller's work is inside a - * transaction at all, which is the kind of ambiguity this platform exists to remove. - */ -public enum PropagationMode { - - /** Join the caller's transaction, or start one. The Stable default. */ - REQUIRED, - - /** Require the caller to already own a transaction; refuse to start one. */ - MANDATORY, - - /** - * Suspend the caller's transaction and run in a new one. - * - *

Opt-in only: it acquires a second physical connection while pinning the first, so a profile - * using it must be paired with the pool-pressure evidence in design §38. - */ - REQUIRES_NEW -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/transaction/RetryDecision.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/transaction/RetryDecision.java deleted file mode 100644 index 22fbf95b..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/transaction/RetryDecision.java +++ /dev/null @@ -1,54 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.api.transaction; - -import java.time.Duration; -import java.util.Objects; - -/** - * The outcome of classifying one failed attempt (design §9.4). - * - *

The {@code reason} is a bounded diagnostic string chosen by the policy, never a provider - * message, so it is safe to log and to use as a low-cardinality metric tag. - */ -public record RetryDecision(RetryDisposition disposition, Duration delay, String reason) { - - public RetryDecision { - Objects.requireNonNull(disposition, "disposition"); - Objects.requireNonNull(delay, "delay"); - Objects.requireNonNull(reason, "reason"); - if (delay.isNegative()) { - throw new IllegalArgumentException("retry delay must not be negative"); - } - if (disposition != RetryDisposition.RETRY_FULL_TRANSACTION && !delay.isZero()) { - throw new IllegalArgumentException("only a full transaction retry may carry a delay"); - } - if (reason.isBlank()) { - throw new IllegalArgumentException("retry decision requires a reason"); - } - } - - /** Re-run the whole use case after the supplied backoff. */ - public static RetryDecision retry(Duration delay) { - return new RetryDecision( - RetryDisposition.RETRY_FULL_TRANSACTION, delay, "retryable persistence failure"); - } - - /** Re-run the whole use case after the supplied backoff, with an explicit reason. */ - public static RetryDecision retry(Duration delay, String reason) { - return new RetryDecision(RetryDisposition.RETRY_FULL_TRANSACTION, delay, reason); - } - - /** Hand the failure to reconciliation; the commit outcome is not known. */ - public static RetryDecision reconcile(String reason) { - return new RetryDecision(RetryDisposition.RECONCILE, Duration.ZERO, reason); - } - - /** Surface the failure; re-running it cannot help. */ - public static RetryDecision fail(String reason) { - return new RetryDecision(RetryDisposition.FAIL, Duration.ZERO, reason); - } - - /** Whether this decision asks for another full-transaction attempt. */ - public boolean retrying() { - return disposition == RetryDisposition.RETRY_FULL_TRANSACTION; - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/transaction/RetryDisposition.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/transaction/RetryDisposition.java deleted file mode 100644 index 7a92df59..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/transaction/RetryDisposition.java +++ /dev/null @@ -1,19 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.api.transaction; - -/** - * What the platform may do about a failed attempt (design §9.4). - * - *

{@link #RECONCILE} exists so that "we do not know" is a first-class outcome rather than a - * retry in disguise. - */ -public enum RetryDisposition { - - /** Re-run the entire use case in a new transaction and a new Persistence Context. */ - RETRY_FULL_TRANSACTION, - - /** Hand the failure to domain-specific reconciliation; never re-run it automatically. */ - RECONCILE, - - /** Surface the failure to the caller. */ - FAIL -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/transaction/RetryEventListener.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/transaction/RetryEventListener.java deleted file mode 100644 index 14c57f08..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/transaction/RetryEventListener.java +++ /dev/null @@ -1,45 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.api.transaction; - -import dev.caskeleton.adapter.outbound.persistence.api.PersistenceOperationName; -import dev.caskeleton.adapter.outbound.persistence.api.error.JpaPersistenceException; - -/** - * Attempt-level events from the retry coordinator (design §19, §37). - * - *

The split between attempt events and the one terminal event is deliberate. Logging every - * retried attempt at WARN turns a healthy, self-correcting contention pattern into a page; the - * attempt events belong in metrics, and only the final outcome is worth a log line. - * - *

Declared in {@code api} because both sides need it and neither should depend on the other. - * While it lived in {@code transaction}, the observation package imported it — so the package whose - * whole job is to watch the platform was a dependency of nothing and a dependent of the engine, - * which is the wrong way round for a cross-cutting SPI and closes a loop the moment the engine - * wants to report anything. - */ -public interface RetryEventListener { - - /** One attempt failed and a decision has been made about it. */ - default void onAttemptFailed( - PersistenceOperationName operation, - TransactionAttempt attempt, - JpaPersistenceException failure, - RetryDecision decision) { - // metrics-only by default - } - - /** The logical operation succeeded, possibly after retries. */ - default void onSucceeded(PersistenceOperationName operation, int attempts) { - // metrics-only by default - } - - /** The logical operation ended in failure and will be surfaced to the caller. */ - default void onGaveUp( - PersistenceOperationName operation, int attempts, JpaPersistenceException failure) { - // metrics-only by default - } - - /** A listener that records nothing; used when no observability module is installed. */ - static RetryEventListener noop() { - return new RetryEventListener() {}; - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/transaction/RetryProfile.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/transaction/RetryProfile.java deleted file mode 100644 index b7eda520..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/transaction/RetryProfile.java +++ /dev/null @@ -1,112 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.api.transaction; - -import dev.caskeleton.adapter.outbound.persistence.api.error.FailureCategory; -import java.time.Duration; -import java.util.EnumSet; -import java.util.Objects; -import java.util.Set; -import java.util.regex.Pattern; - -/** - * A named, bounded retry budget (design §19.3). - * - *

The profile is a value, not a strategy object: it says how many attempts are allowed, how the - * backoff grows, how it is jittered, and which failure categories are eligible at all. The decision - * to use it belongs to {@link JpaRetryPolicy}. - * - *

One category can never appear in {@code retryableFailures}: {@link - * FailureCategory#COMPLETION_UNKNOWN}. A profile that listed it would let configuration re-run work - * that may already be committed, so the constructor rejects it outright rather than trusting review - * to catch it. - */ -public record RetryProfile( - String name, - int maxAttempts, - Duration initialBackoff, - Duration maxBackoff, - double multiplier, - JitterMode jitter, - Set retryableFailures) { - - /** Profile names are bounded because they become metric tags. */ - private static final Pattern NAME = Pattern.compile("[a-z][a-z0-9.-]{2,63}"); - - /** The categories a profile is allowed to opt into (design §19.1). */ - private static final Set ELIGIBLE = - Set.of( - FailureCategory.SERIALIZATION_FAILURE, - FailureCategory.DEADLOCK, - FailureCategory.OPTIMISTIC_CONFLICT, - FailureCategory.LOCK_NOT_AVAILABLE, - FailureCategory.CONNECTION_UNAVAILABLE); - - public RetryProfile { - Objects.requireNonNull(name, "name"); - Objects.requireNonNull(initialBackoff, "initialBackoff"); - Objects.requireNonNull(maxBackoff, "maxBackoff"); - Objects.requireNonNull(jitter, "jitter"); - Objects.requireNonNull(retryableFailures, "retryableFailures"); - if (!NAME.matcher(name).matches()) { - throw new IllegalArgumentException("invalid retry profile name"); - } - if (maxAttempts < 1) { - throw new IllegalArgumentException("maxAttempts must be at least 1"); - } - if (initialBackoff.isNegative() || maxBackoff.isNegative()) { - throw new IllegalArgumentException("retry backoff must not be negative"); - } - if (maxBackoff.compareTo(initialBackoff) < 0) { - throw new IllegalArgumentException("maxBackoff must not be smaller than initialBackoff"); - } - if (!Double.isFinite(multiplier) || multiplier < 1.0d) { - throw new IllegalArgumentException("retry multiplier must be finite and at least 1.0"); - } - if (retryableFailures.contains(FailureCategory.COMPLETION_UNKNOWN)) { - throw new IllegalArgumentException( - "completion unknown is never a retryable failure category"); - } - for (FailureCategory category : retryableFailures) { - if (!ELIGIBLE.contains(category)) { - throw new IllegalArgumentException("failure category is not retry eligible: " + category); - } - } - retryableFailures = - retryableFailures.isEmpty() ? Set.of() : Set.copyOf(EnumSet.copyOf(retryableFailures)); - } - - /** - * A profile that never retries. - * - *

This is the default for any transaction profile that has not opted in, so an operation is - * only re-run when someone decided it may be. - */ - public static RetryProfile none() { - return new RetryProfile( - "none", 1, Duration.ZERO, Duration.ZERO, 1.0d, JitterMode.NONE, Set.of()); - } - - /** The Stable write default: bounded exponential backoff over the contention categories. */ - public static RetryProfile boundedContention(String name, int maxAttempts) { - return new RetryProfile( - name, - maxAttempts, - Duration.ofMillis(20), - Duration.ofMillis(500), - 2.0d, - JitterMode.FULL, - Set.of( - FailureCategory.SERIALIZATION_FAILURE, - FailureCategory.DEADLOCK, - FailureCategory.OPTIMISTIC_CONFLICT)); - } - - /** Whether this profile permits more than the first attempt. */ - public boolean enabled() { - return maxAttempts > 1 && !retryableFailures.isEmpty(); - } - - /** Whether the supplied category is eligible under this profile. */ - public boolean allows(FailureCategory category) { - return retryableFailures.contains(category); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/transaction/TransactionAttempt.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/transaction/TransactionAttempt.java deleted file mode 100644 index 003c22e5..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/transaction/TransactionAttempt.java +++ /dev/null @@ -1,43 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.api.transaction; - -import java.time.Duration; -import java.time.Instant; -import java.util.Objects; - -/** - * One physical attempt at a logical use case (design §19.2). - * - *

{@code number} is 1-based: the first execution is attempt 1, not a retry. {@code startedAt} is - * the instant that attempt began, which is what lets the retry coordinator enforce an overall - * deadline rather than only an attempt count. - */ -public record TransactionAttempt(int number, Instant startedAt) { - - public TransactionAttempt { - Objects.requireNonNull(startedAt, "startedAt"); - if (number < 1) { - throw new IllegalArgumentException("transaction attempt number must be at least 1"); - } - } - - /** The first attempt at a use case. */ - public static TransactionAttempt first(Instant startedAt) { - return new TransactionAttempt(1, startedAt); - } - - /** The attempt that follows this one, beginning at the supplied instant. */ - public TransactionAttempt next(Instant instant) { - return new TransactionAttempt(number + 1, instant); - } - - /** How long this attempt has been running as of {@code now}. */ - public Duration elapsedAt(Instant now) { - Duration elapsed = Duration.between(startedAt, now); - return elapsed.isNegative() ? Duration.ZERO : elapsed; - } - - /** Whether this is the first execution rather than a retry. */ - public boolean isFirst() { - return number == 1; - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/transaction/TransactionProfile.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/transaction/TransactionProfile.java deleted file mode 100644 index ef117445..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/api/transaction/TransactionProfile.java +++ /dev/null @@ -1,80 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.api.transaction; - -import java.time.Duration; -import java.util.Objects; -import java.util.regex.Pattern; - -/** - * A named, immutable description of one transaction boundary (design §9.2). - * - *

A write profile must carry a positive, finite timeout. An unbounded write transaction is how a - * single stuck statement holds a connection, a lock, and a row version indefinitely, so the type - * refuses to represent one. Read profiles may leave the timeout at zero, meaning "the connection - * default applies". - */ -public record TransactionProfile( - String name, - PropagationMode propagation, - IsolationLevel isolation, - Duration timeout, - boolean readOnly, - RetryProfile retryProfile) { - - /** Profile names are bounded because they become metric tags. */ - private static final Pattern NAME = Pattern.compile("[a-z][a-z0-9.-]{2,63}"); - - public TransactionProfile { - Objects.requireNonNull(name, "name"); - Objects.requireNonNull(propagation, "propagation"); - Objects.requireNonNull(isolation, "isolation"); - Objects.requireNonNull(retryProfile, "retryProfile"); - if (!NAME.matcher(name).matches()) { - throw new IllegalArgumentException("invalid transaction profile name"); - } - if (!readOnly && (timeout == null || timeout.isZero() || timeout.isNegative())) { - throw new IllegalArgumentException("write transaction requires positive timeout"); - } - if (timeout == null) { - timeout = Duration.ZERO; - } - if (timeout.isNegative()) { - throw new IllegalArgumentException("transaction timeout must not be negative"); - } - if (readOnly && retryProfile.enabled() && propagation == PropagationMode.REQUIRES_NEW) { - throw new IllegalArgumentException( - "a read-only REQUIRES_NEW profile must not carry a retry budget"); - } - } - - /** The Stable write default: {@code REQUIRED + READ_COMMITTED} with no retry budget. */ - public static TransactionProfile write(String name, Duration timeout) { - return new TransactionProfile( - name, - PropagationMode.REQUIRED, - IsolationLevel.READ_COMMITTED, - timeout, - false, - RetryProfile.none()); - } - - /** The Stable read default: {@code REQUIRED + READ_COMMITTED}, read-only, no retry budget. */ - public static TransactionProfile read(String name, Duration timeout) { - return new TransactionProfile( - name, - PropagationMode.REQUIRED, - IsolationLevel.READ_COMMITTED, - timeout, - true, - RetryProfile.none()); - } - - /** Returns a copy of this profile carrying the supplied retry budget. */ - public TransactionProfile withRetryProfile(RetryProfile profile) { - return new TransactionProfile(name, propagation, isolation, timeout, readOnly, profile); - } - - /** Whether the timeout is a real bound rather than "use the connection default". */ - public boolean hasTimeout() { - return !timeout.isZero(); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/JpaObservabilityAutoConfiguration.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/JpaObservabilityAutoConfiguration.java deleted file mode 100644 index 96ae817b..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/JpaObservabilityAutoConfiguration.java +++ /dev/null @@ -1,80 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.autoconfigure; - -import dev.caskeleton.adapter.outbound.persistence.api.query.NoopQueryObservation; -import dev.caskeleton.adapter.outbound.persistence.api.query.QueryObservation; -import dev.caskeleton.adapter.outbound.persistence.api.transaction.RetryEventListener; -import dev.caskeleton.adapter.outbound.persistence.observation.JpaRetryObservation; -import dev.caskeleton.adapter.outbound.persistence.observation.JpaTransactionObservation; -import dev.caskeleton.adapter.outbound.persistence.observation.MicrometerQueryObservation; -import io.micrometer.core.instrument.MeterRegistry; -import java.util.Objects; -import java.util.Optional; - -/** - * Composes the observability half of the platform (design §37). - * - *

Separate from {@link JpaPlatformAutoConfiguration} because it backs off separately, and - * because it is the only part of the platform that is genuinely optional at runtime: an application - * with no {@link MeterRegistry} gets the no-op observation and everything else still works. That is - * why {@link NoopQueryObservation} exists rather than a nullable registry — a null check at every - * call site is how "observe when a registry is present" becomes two divergent code paths. - * - *

The persistence-unit tag is required rather than defaulted. It is the dimension that separates - * two data sources in the same application, and a default of {@code "default"} makes them - * indistinguishable exactly when someone is trying to tell them apart. - */ -final class JpaObservabilityAutoConfiguration { - - private final Optional registry; - private final String persistenceUnit; - - /** - * @param registry the meter registry, or empty when the application installs none - * @param persistenceUnit the bounded name distinguishing this persistence unit from others - */ - JpaObservabilityAutoConfiguration(Optional registry, String persistenceUnit) { - this.registry = Objects.requireNonNull(registry, "registry"); - this.persistenceUnit = Objects.requireNonNull(persistenceUnit, "persistenceUnit"); - } - - /** Query observation, or the no-op when no registry is installed. */ - public QueryObservation queryObservation() { - return registry - .map(meters -> new MicrometerQueryObservation(meters, persistenceUnit)) - .orElseGet(NoopQueryObservation::instance); - } - - /** Transaction observation, when a registry is installed. */ - public Optional transactionObservation() { - return registry.map(meters -> new JpaTransactionObservation(meters, persistenceUnit)); - } - - /** - * The retry listener, or the no-op when no registry is installed. - * - *

Retry attempts are metrics rather than log lines: an optimistic conflict is the expected - * cost of concurrency, and logging each at WARN pages someone for a system working as designed. - */ - public RetryEventListener retryListener() { - return registry - .map(meters -> new JpaRetryObservation(meters, persistenceUnit)) - .orElseGet(RetryEventListener::noop); - } - - /** - * The bounded persistence-unit tag every meter this configuration creates carries. - * - *

Hibernate statistics are collected inside the persistence leaf, through {@code - * HibernateStatisticsCollector.of(sessionFactory, batchCounter)}. Building it here would put - * {@code org.hibernate} on the composition root's compile classpath, and this repository keeps - * ORM types inside the persistence leaf. - */ - public String persistenceUnit() { - return persistenceUnit; - } - - /** Whether a meter registry is installed at all. */ - public boolean instrumented() { - return registry.isPresent(); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/JpaTransactionAutoConfiguration.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/JpaTransactionAutoConfiguration.java deleted file mode 100644 index 33f363c6..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/JpaTransactionAutoConfiguration.java +++ /dev/null @@ -1,117 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.autoconfigure; - -import dev.caskeleton.adapter.outbound.persistence.api.error.VendorFailureTranslator; -import dev.caskeleton.adapter.outbound.persistence.api.transaction.JpaRetryPolicy; -import dev.caskeleton.adapter.outbound.persistence.api.transaction.RetryEventListener; -import dev.caskeleton.adapter.outbound.persistence.api.transaction.RetryProfile; -import dev.caskeleton.adapter.outbound.persistence.transaction.CommitFailureClassifier; -import dev.caskeleton.adapter.outbound.persistence.transaction.DefaultJpaRetryPolicy; -import dev.caskeleton.adapter.outbound.persistence.transaction.FullTransactionRetryCoordinator; -import dev.caskeleton.adapter.outbound.persistence.transaction.OptimisticConflictTranslator; -import dev.caskeleton.adapter.outbound.persistence.transaction.PersistenceFailureTranslatorChain; -import dev.caskeleton.adapter.outbound.persistence.transaction.RetrySleeper; -import dev.caskeleton.adapter.outbound.persistence.transaction.SpringJpaTransactionExecutor; -import dev.caskeleton.adapter.outbound.persistence.transaction.ThreadRetrySleeper; -import java.time.Clock; -import java.time.Duration; -import java.util.Objects; -import org.springframework.transaction.PlatformTransactionManager; - -/** - * Composes the transaction half of the platform (design §9.3, §17, §19). - * - *

Separate from {@link JpaPlatformAutoConfiguration} because it backs off separately. An - * application that already installs its own {@link PlatformTransactionManager} — a JTA setup, a - * chained manager across two data sources — must keep it, and the rest of the platform is still - * useful to it. Folding the two together would make "I have my own transaction manager" mean "I get - * none of the platform". - * - *

Plain construction rather than Spring auto-configuration: this repository's composition root - * owns wiring, and an adapter leaf that auto-configured a transaction manager would silently - * replace one the application had deliberately chosen. - * - *

There is no declarative retry annotation any more. {@code @RetryableJpaTransaction} lived in - * the persistence leaf and documented itself as something an application service would put on its - * own methods — which application-core cannot do without importing an outbound adapter and - * inverting the dependency this architecture is built on. The canonical boundary is {@code - * PolicyTransactionPort.inTransaction(TransactionRequest, Supplier)}; the retry coordinator below - * is what implements it, not a second way to ask for the same thing. - */ -final class JpaTransactionAutoConfiguration { - - /** How long a logical operation may keep retrying before the budget is spent regardless. */ - public static final Duration DEFAULT_MAX_RETRY_ELAPSED = Duration.ofSeconds(30); - - private final Clock clock; - - JpaTransactionAutoConfiguration(Clock clock) { - this.clock = Objects.requireNonNull(clock, "clock"); - } - - /** - * The commit-phase classifier the evidence-aware transaction manager is built with. - * - *

The manager itself is constructed inside the persistence leaf, through {@code - * EvidenceAwareJpaTransactionManager.standard(entityManagerFactory, clock)}. The composition root - * deliberately does not do it here: that would require {@code jakarta.persistence} and {@code - * org.hibernate} on the composition root's compile classpath, and this repository keeps ORM types - * inside the persistence leaf. What the root owns is the decision — whether to install the - * platform's manager at all — and the classifier it uses. - */ - public CommitFailureClassifier commitFailureClassifier() { - return CommitFailureClassifier.standard(clock); - } - - /** The programmatic transaction boundary, with no vendor classification. */ - public SpringJpaTransactionExecutor transactionExecutor( - PlatformTransactionManager transactionManager) { - return new SpringJpaTransactionExecutor(transactionManager, clock); - } - - /** - * The programmatic transaction boundary that classifies its attempts with a vendor's SQLSTATEs. - * - *

The overload above builds the catalog-free chain, whose vendor stage returns the failure - * unchanged. That is the honest answer when no vendor translator exists, and it is the wrong one - * whenever a vendor is composed: a 40001 or 40P01 stays a raw {@code DataAccessException}, never - * becomes a {@code JpaPersistenceException}, and so never reaches the retry coordinator's catch. - * Contention then goes unretried in exactly the deployments that have a database. - * - * @param vendorFailures the composed vendor's SQLSTATE translator - */ - public SpringJpaTransactionExecutor transactionExecutor( - PlatformTransactionManager transactionManager, VendorFailureTranslator vendorFailures) { - return new SpringJpaTransactionExecutor( - transactionManager, - clock, - new PersistenceFailureTranslatorChain( - OptimisticConflictTranslator.withoutCatalog(), vendorFailures)); - } - - /** - * The retry coordinator for one retry profile. - * - *

The policy and the coordinator's budget are built from the same profile on purpose. - * Configuring them independently is how a deployment ends up with a policy that says "retry" and - * a budget that permits one attempt — which looks like retry being broken rather than like a - * misconfiguration. - */ - public FullTransactionRetryCoordinator retryCoordinator( - SpringJpaTransactionExecutor executor, - RetryProfile retryProfile, - RetryEventListener listener) { - return retryCoordinator(executor, DefaultJpaRetryPolicy.forProfile(retryProfile), listener); - } - - /** The retry coordinator for an application-supplied policy. */ - public FullTransactionRetryCoordinator retryCoordinator( - SpringJpaTransactionExecutor executor, JpaRetryPolicy policy, RetryEventListener listener) { - return new FullTransactionRetryCoordinator( - executor, policy, retrySleeper(), clock, DEFAULT_MAX_RETRY_ELAPSED, listener); - } - - /** The production sleeper; tests substitute a recording one. */ - public RetrySleeper retrySleeper() { - return new ThreadRetrySleeper(); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PersistenceJpaAutoConfiguration.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PersistenceJpaAutoConfiguration.java index 0460f1c2..461b1fd2 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PersistenceJpaAutoConfiguration.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PersistenceJpaAutoConfiguration.java @@ -10,12 +10,19 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Import; -/** Capability-owned Spring entry point for relational persistence. */ +/** + * Capability-owned Spring entry point for relational persistence. + * + *

On whenever this module is on the classpath: selecting the module is the decision, and {@code + * ca-skeleton.persistence-jpa.enabled=false} is only the escape hatch for a deployment that ships + * the jar but must not use it. + */ @AutoConfiguration @ConditionalOnProperty( prefix = "ca-skeleton.persistence-jpa", name = "enabled", - havingValue = "true") + havingValue = "true", + matchIfMissing = true) @EnableConfigurationProperties(PersistenceVendorSettings.class) @Import({ JpaAdapterComponentsConfig.class, diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PersistenceJpaRuntimeConfig.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PersistenceJpaRuntimeConfig.java index 0ce18dee..3951a1dd 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PersistenceJpaRuntimeConfig.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PersistenceJpaRuntimeConfig.java @@ -1,20 +1,12 @@ package dev.caskeleton.adapter.outbound.persistence.autoconfigure; -import dev.caskeleton.adapter.outbound.persistence.api.error.VendorFailureTranslator; -import dev.caskeleton.adapter.outbound.persistence.api.transaction.RetryEventListener; import dev.caskeleton.adapter.outbound.persistence.hibernate.HibernateProviderPolicy; import dev.caskeleton.adapter.outbound.persistence.security.PostgreSqlRuntimeRoleVerifier; -import dev.caskeleton.adapter.outbound.persistence.transaction.FullTransactionRetryCoordinator; -import dev.caskeleton.adapter.outbound.persistence.transaction.SpringJpaTransactionExecutor; -import java.time.Clock; -import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.autoconfigure.AutoConfiguration; -import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; -import org.springframework.transaction.PlatformTransactionManager; /** Reusable JPA provider/runtime composition owned by the persistence leaf. */ @AutoConfiguration( @@ -26,8 +18,8 @@ import org.springframework.transaction.PlatformTransactionManager; @ConditionalOnProperty( prefix = "ca-skeleton.persistence-jpa", name = "enabled", - havingValue = "true") -@ConditionalOnProperty(prefix = "app.jpa-platform", name = "addons-enabled", matchIfMissing = true) + havingValue = "true", + matchIfMissing = true) class PersistenceJpaRuntimeConfig { @Bean @@ -41,37 +33,4 @@ class PersistenceJpaRuntimeConfig { PostgreSqlRuntimeRoleVerifier postgreSqlRuntimeRoleVerifier() { return new PostgreSqlRuntimeRoleVerifier(); } - - @Bean - @ConditionalOnMissingBean - RetryEventListener jpaRetryEventListener() { - return RetryEventListener.noop(); - } - - @Bean - @ConditionalOnMissingBean - @ConditionalOnBean(PlatformTransactionManager.class) - SpringJpaTransactionExecutor jpaTransactionExecutor( - PlatformTransactionManager transactionManager, - Clock clock, - ObjectProvider vendorFailures) { - JpaTransactionAutoConfiguration composition = new JpaTransactionAutoConfiguration(clock); - VendorFailureTranslator vendor = vendorFailures.getIfAvailable(); - return vendor == null - ? composition.transactionExecutor(transactionManager) - : composition.transactionExecutor(transactionManager, vendor); - } - - @Bean - @ConditionalOnMissingBean - @ConditionalOnBean(SpringJpaTransactionExecutor.class) - FullTransactionRetryCoordinator jpaRetryCoordinator( - SpringJpaTransactionExecutor executor, RetryEventListener retryListener, Clock clock) { - return new JpaTransactionAutoConfiguration(clock) - .retryCoordinator( - executor, - dev.caskeleton.adapter.outbound.persistence.api.transaction.RetryProfile - .boundedContention("jpa-platform-default", 3), - retryListener); - } } diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PostgreSqlIdempotencyStoreConfig.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PostgreSqlIdempotencyStoreConfig.java index 5c51d603..9a72bb76 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PostgreSqlIdempotencyStoreConfig.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PostgreSqlIdempotencyStoreConfig.java @@ -1,21 +1,43 @@ package dev.caskeleton.adapter.outbound.persistence.autoconfigure; +import dev.caskeleton.adapter.outbound.persistence.postgresql.idempotency.IdempotencySchemaStream; import dev.caskeleton.adapter.outbound.persistence.postgresql.idempotency.PostgreSqlOwnerSafeIdempotencyStore; -import dev.caskeleton.application.idempotency.v2.IdempotencyStorePortV2; +import dev.caskeleton.application.idempotency.IdempotencyStorePort; +import javax.sql.DataSource; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.core.JdbcOperations; +import org.springframework.scheduling.annotation.EnableScheduling; -/** Concrete PostgreSQL owner-safe idempotency store composition. */ +/** + * The PostgreSQL idempotency provider: the owner-safe store, the schema stream it needs, and (via + * {@code @EnableScheduling}) the scanned {@code IdempotencyReaper} that purges expired rows. The + * executor that drives the store is assembled once by the composition root. + */ @Configuration(proxyBeanMethods = false) +@EnableScheduling @ConditionalOnProperty( name = "ca-skeleton.capabilities.idempotency.provider", havingValue = "postgresql") class PostgreSqlIdempotencyStoreConfig { @Bean - IdempotencyStorePortV2 postgreSqlOwnerSafeIdempotencyStore(JdbcOperations jdbc) { + IdempotencyStorePort postgreSqlOwnerSafeIdempotencyStore(JdbcOperations jdbc) { return new PostgreSqlOwnerSafeIdempotencyStore(jdbc); } + + /** + * Applies the stream at startup unless the deployment migrates out of band ({@code + * ca-skeleton.runtime.migration-on-startup=false}); the store then fails closed until an operator + * applies and activates it. + */ + @Bean + @ConditionalOnProperty( + name = "ca-skeleton.runtime.migration-on-startup", + havingValue = "true", + matchIfMissing = true) + IdempotencySchemaStream idempotencySchemaStream(DataSource dataSource) { + return new IdempotencySchemaStream(dataSource); + } } diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/config/JpaAdapterComponentsConfig.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/config/JpaAdapterComponentsConfig.java index 35713251..e39e3410 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/config/JpaAdapterComponentsConfig.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/config/JpaAdapterComponentsConfig.java @@ -1,7 +1,9 @@ package dev.caskeleton.adapter.outbound.persistence.config; +import org.springframework.boot.context.TypeExcludeFilter; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.FilterType; /** * Registers the JPA adapter's scanned components, which nothing registered (JPA-INT-006). @@ -25,14 +27,14 @@ import org.springframework.context.annotation.Configuration; * directly by its own tests. * *

So the scan is restored, narrowed to the packages it should always have covered and reachable - * only through {@code PersistenceJpaRootAutoConfiguration}, which carries the JPA master switch. - * Off is still structural. + * only through the leaf's own {@code PersistenceJpaAutoConfiguration}, which carries the JPA + * capability switch. Off is still structural. * *

Two packages are deliberately absent: * *

    - *
  • {@code ..persistence.fileserver} — gated on its own capability switch, scanned by {@link - * dev.caskeleton.adapter.outbound.persistence.fileserver.FileserverJpaPersistenceConfig}; + *
  • {@code ..persistence.fileserver} — gated on its own capability switch, scanned by {@code + * FileserverJpaPersistenceConfig} in the {@code persistence-fileserver} leaf; *
  • {@code ..persistence.notification} — assembled explicitly, bean by bean, by {@code * NotificationJpaPersistenceFacade}. *
@@ -48,9 +50,8 @@ import org.springframework.context.annotation.Configuration; * qualified {@code jdbcDistributedLock} that only that configuration declares. * *

Each package's {@code @ConfigurationProperties} type is enabled by a configuration inside that - * same package — {@code JpaTransactionConfig} for {@code JpaTransactionSettings}, {@code - * DistributedLockPersistenceConfig} for {@code LockSettings} — rather than from here. Enabling them - * centrally would give {@code config} an edge to {@code lock} and {@code transaction} that the + * same package — {@code DistributedLockPersistenceConfig} for {@code LockSettings} — rather than + * from here. Enabling it centrally would give {@code config} an edge to {@code lock} that the * module map does not grant it, and the map is right: this class knows which packages to scan, not * what is inside them. They need enabling at all because {@code @ConfigurationPropertiesScan} * excludes this tree as deliberately as {@code @ComponentScan} does. @@ -66,5 +67,9 @@ import org.springframework.context.annotation.Configuration; "dev.caskeleton.adapter.outbound.persistence.operation", "dev.caskeleton.adapter.outbound.persistence.outbox", "dev.caskeleton.adapter.outbound.persistence.transaction" - }) + }, + // Boot's hook for keeping a test's own configuration classes out of an application scan — the + // filter @SpringBootApplication declares for the same reason. + excludeFilters = + @ComponentScan.Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class)) public class JpaAdapterComponentsConfig {} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/config/PersistenceJpaConfig.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/config/PersistenceJpaConfig.java index b067c335..74125feb 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/config/PersistenceJpaConfig.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/config/PersistenceJpaConfig.java @@ -18,8 +18,10 @@ import org.springframework.data.jpa.repository.config.EnableJpaRepositories; * those entities into the persistence unit unconditionally, and {@code ddl-auto=validate} then * looked for {@code notification_request} and {@code fs_cleanup_item} in deployments that had * switched both capabilities off — failing the boot over capabilities they had declined. {@code - * NotificationJpaPersistenceConfig} and {@code FileserverJpaPersistenceConfig} own those scans, - * each behind the same switch its adapter beans already carried. + * NotificationJpaPersistenceConfig} (imported by {@code NotificationJpaPersistenceFacade}) and + * {@code FileserverJpaPersistenceConfig} (the {@code persistence-fileserver} leaf's own + * auto-configuration) own those scans, each behind the same switch its adapter beans already + * carried. * *

The fileserver case was the more expensive of the two: it blocked every JPA-on Compose lane, * and it was invisible under H2, whose {@code create-drop} builds whatever the entities describe. @@ -27,9 +29,8 @@ import org.springframework.data.jpa.repository.config.EnableJpaRepositories; * *

Neither gated configuration is imported from here, and neither is found by a component scan: * {@code dev.caskeleton.adapter.outbound.persistence..*} is excluded from the composition root's - * scan by design, and {@code config} is allowed to depend on {@code api} alone. The composition - * root registers them, which is where the decision belongs — it is the only place that knows both - * which capabilities are on and which JPA vendor is composed. + * scan by design, and {@code config} is allowed to depend on {@code api} alone. Each capability's + * own configuration registers its scan, behind that capability's switch. * *

A new always-installed sub-package must be added here; leaving it out is a silent omission * rather than a compile error, which is what {@code PersistenceEntityScanCoverageTest} checks. diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/envers/EnversHistoryReader.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/envers/EnversHistoryReader.java deleted file mode 100644 index cc5ca2de..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/envers/EnversHistoryReader.java +++ /dev/null @@ -1,22 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.envers; - -import java.util.List; - -/** - * Reads the recorded revisions of an audited entity (design §35). - * - *

Read-only by construction. History is append-only: it is written by the revision listener as a - * side effect of ordinary writes, and an API that could modify it would make the record something - * an application bug can rewrite. - */ -public interface EnversHistoryReader { - - /** - * The revisions recorded for one entity instance, oldest first. - * - *

An entity that is not enrolled for history returns an empty list rather than throwing — - * "this entity has no history" is a legitimate answer, and the enrolment check belongs to {@link - * EnversConfigurationGuard} at startup. - */ - List> revisions(Class entityType, Object id); -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/envers/HibernateEnversHistoryReader.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/envers/HibernateEnversHistoryReader.java index 2e0e1320..258a2466 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/envers/HibernateEnversHistoryReader.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/envers/HibernateEnversHistoryReader.java @@ -24,7 +24,7 @@ import org.hibernate.envers.query.AuditEntity; * per revision turns a history page into 1+N database round trips as the entity accumulates * changes. */ -public final class HibernateEnversHistoryReader implements EnversHistoryReader { +public final class HibernateEnversHistoryReader { private final EntityManager entityManager; private final EnversHistoryPolicy policy; @@ -34,7 +34,13 @@ public final class HibernateEnversHistoryReader implements EnversHistoryReader { this.policy = Objects.requireNonNull(policy, "policy"); } - @Override + /** + * The revisions recorded for one entity instance, oldest first. + * + *

An entity that is not enrolled for history returns an empty list rather than throwing — + * "this entity has no history" is a legitimate answer, and the enrolment check belongs to {@link + * EnversConfigurationGuard} at startup. + */ public List> revisions(Class entityType, Object id) { Objects.requireNonNull(entityType, "entityType"); Objects.requireNonNull(id, "id"); diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/ExperimentalFeature.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/ExperimentalFeature.java deleted file mode 100644 index 53412167..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/ExperimentalFeature.java +++ /dev/null @@ -1,47 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.experimental; - -/** - * The experimental capabilities and the flag each one requires (experimental plan §Global - * Constraints). - * - *

Every one of these is off unless its flag is explicitly true. The flag is not a convenience: - * these features change tenant isolation, read consistency, or the provider version, and each is - * only as safe as the evidence suite that has run against it. - */ -public enum ExperimentalFeature { - - /** Shared-schema multi-tenancy with a tenant column. */ - MULTITENANCY_COLUMN("backend.jpa.experimental.multitenancy-column"), - - /** PostgreSQL row-level-security tenant isolation. */ - MULTITENANCY_RLS("backend.jpa.experimental.multitenancy-rls"), - - /** Schema-per-tenant isolation. */ - MULTITENANCY_SCHEMA("backend.jpa.experimental.multitenancy-schema"), - - /** Database-per-tenant isolation. */ - MULTITENANCY_DATABASE("backend.jpa.experimental.multitenancy-database"), - - /** Consistency-aware read replica routing. */ - READ_REPLICA("backend.jpa.experimental.read-replica"), - - /** Jakarta Persistence 4.0 compatibility lane. */ - JAKARTA_PERSISTENCE_4("backend.jpa.experimental.jakarta-persistence-4"), - - /** Hibernate ORM 8 compatibility lane. */ - HIBERNATE_8("backend.jpa.experimental.hibernate-8"), - - /** PostgreSQL 19 compatibility lane. */ - POSTGRESQL_19("backend.jpa.experimental.postgresql-19"); - - private final String property; - - ExperimentalFeature(String property) { - this.property = property; - } - - /** The property that must be {@code true} for this feature to run. */ - public String property() { - return property; - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/ExperimentalFeatureGate.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/ExperimentalFeatureGate.java deleted file mode 100644 index c44ed078..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/ExperimentalFeatureGate.java +++ /dev/null @@ -1,34 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.experimental; - -import java.util.Map; -import java.util.Objects; - -/** - * Fails closed when an experimental module is present but its flag is not set (experimental plan - * Task 1). - * - *

Presence on the classpath is not consent. An experimental module can arrive transitively, and - * a tenant-isolation or replica-routing feature that switched itself on because a jar was present - * would be the worst possible default. The gate makes the absence of a decision an error rather - * than an activation. - */ -public final class ExperimentalFeatureGate { - - /** - * Fails unless {@code feature} is explicitly enabled. - * - * @throws IllegalStateException naming the exact property that must be set - */ - public void requireEnabled(ExperimentalFeature feature, Map flags) { - Objects.requireNonNull(feature, "feature"); - Objects.requireNonNull(flags, "flags"); - if (!Boolean.TRUE.equals(flags.get(feature.property()))) { - throw new IllegalStateException(feature.property() + "=true is required"); - } - } - - /** Whether a feature is explicitly enabled. */ - public boolean isEnabled(ExperimentalFeature feature, Map flags) { - return Boolean.TRUE.equals(flags.get(feature.property())); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/database/TenantEntityManagerFactoryRegistry.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/database/TenantEntityManagerFactoryRegistry.java deleted file mode 100644 index 136126df..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/database/TenantEntityManagerFactoryRegistry.java +++ /dev/null @@ -1,62 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.experimental.database; - -import dev.caskeleton.adapter.outbound.persistence.experimental.tenant.TenantId; -import jakarta.persistence.EntityManagerFactory; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.function.Function; - -/** - * One {@code EntityManagerFactory} per tenant database (experimental plan Task 5). - * - *

Database-per-tenant needs a factory per tenant, not merely a data source per tenant: an {@code - * EntityManagerFactory} owns the dialect, the schema validation result, and the second-level cache, - * and none of those are shareable across databases that may be on different versions or at - * different migration states. - * - *

That is also the cost. Each factory carries its own metamodel and caches, so the tenant - * ceiling here is about memory as much as about connections. - */ -public final class TenantEntityManagerFactoryRegistry implements AutoCloseable { - - private final Map factories = new LinkedHashMap<>(); - private final Function factoryBuilder; - private final TenantDataSourceRegistry dataSources; - - public TenantEntityManagerFactoryRegistry( - Function factoryBuilder, - TenantDataSourceRegistry dataSources) { - this.factoryBuilder = Objects.requireNonNull(factoryBuilder, "factoryBuilder"); - this.dataSources = Objects.requireNonNull(dataSources, "dataSources"); - } - - /** The tenant's factory, building it — and its pool — on first use. */ - public synchronized EntityManagerFactory require(TenantId tenant) { - Objects.requireNonNull(tenant, "tenant"); - dataSources.require(tenant); - return factories.computeIfAbsent(tenant, factoryBuilder); - } - - /** Closes and forgets a tenant's factory and pool. */ - public synchronized void evict(TenantId tenant) { - EntityManagerFactory removed = factories.remove(tenant); - if (removed != null) { - TenantDataSourceLifecycle.drainAndClose(removed); - } - dataSources.evict(tenant); - } - - /** The tenants with an open factory. */ - public synchronized Set openTenants() { - return Set.copyOf(factories.keySet()); - } - - @Override - public synchronized void close() { - factories.values().forEach(TenantDataSourceLifecycle::drainAndClose); - factories.clear(); - dataSources.close(); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/next/CompatibilityLane.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/next/CompatibilityLane.java deleted file mode 100644 index 940ef33d..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/next/CompatibilityLane.java +++ /dev/null @@ -1,38 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.experimental.next; - -import dev.caskeleton.adapter.outbound.persistence.api.capability.SupportLevel; -import java.util.Objects; - -/** - * One forward-compatibility lane (experimental plan Tasks 7-9). - * - *

{@code publicationEnabled} is always false for a lane. A lane exists to find out whether the - * platform still works on a newer specification, provider, or server; publishing an artifact - * compiled in one would let a consumer depend on that answer before it exists. - */ -public record CompatibilityLane( - String name, SupportLevel supportLevel, boolean publicationEnabled) { - - public CompatibilityLane { - Objects.requireNonNull(name, "name"); - Objects.requireNonNull(supportLevel, "supportLevel"); - if (name.isBlank()) { - throw new IllegalArgumentException("a compatibility lane requires a name"); - } - if (publicationEnabled && supportLevel == SupportLevel.EXPERIMENTAL) { - throw new IllegalArgumentException( - "an experimental lane must not publish artifacts under Stable coordinates"); - } - } - - /** An experimental, non-publishing lane. */ - public static CompatibilityLane experimental(String name) { - return new CompatibilityLane(name, SupportLevel.EXPERIMENTAL, false); - } - - /** The three lanes the experimental plan defines. */ - public static java.util.List defined() { - return java.util.List.of( - experimental("jpa4"), experimental("hibernate8"), experimental("postgresql19")); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/next/ExperimentalPromotionGate.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/next/ExperimentalPromotionGate.java deleted file mode 100644 index ec6b06e9..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/next/ExperimentalPromotionGate.java +++ /dev/null @@ -1,26 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.experimental.next; - -import java.util.Objects; - -/** - * Decides whether an experimental feature may be considered for Stable (experimental plan Task 9). - * - *

Technical evidence is checked first, then the reviewed ADR. Both are required, and the ADR is - * not a formality: the technical suites establish that a thing works, and the ADR records that - * someone decided the platform should promise it — including the support burden that promise - * carries. - */ -public final class ExperimentalPromotionGate { - - /** The promotion decision for the supplied evidence. */ - public PromotionDecision evaluate(PromotionEvidence evidence) { - Objects.requireNonNull(evidence, "evidence"); - if (!evidence.allTechnicalGatesPassed()) { - return PromotionDecision.BLOCKED_TECHNICAL; - } - if (!evidence.reviewedAdr()) { - return PromotionDecision.BLOCKED_MISSING_ADR; - } - return PromotionDecision.ELIGIBLE_FOR_STABLE_REVIEW; - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/next/HibernateCompatibilityPolicy.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/next/HibernateCompatibilityPolicy.java deleted file mode 100644 index dd02bef6..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/next/HibernateCompatibilityPolicy.java +++ /dev/null @@ -1,41 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.experimental.next; - -import dev.caskeleton.adapter.outbound.persistence.hibernate.HibernateProviderPolicy; -import java.util.List; - -/** - * Which provider versions are Stable and which are only exercised in a lane (experimental plan Task - * 8). - * - *

A lane result never changes the Stable gate. If Hibernate 8 generates different SQL for the - * collection-fetch pagination contract, that is a finding about Hibernate 8 — the 7.x gate keeps - * asserting what 7.x must do, because that is what deployments are running. - */ -public final class HibernateCompatibilityPolicy { - - private final HibernateProviderPolicy providerPolicy; - - public HibernateCompatibilityPolicy(HibernateProviderPolicy providerPolicy) { - this.providerPolicy = providerPolicy; - } - - /** A policy over the provider on this classpath. */ - public static HibernateCompatibilityPolicy fromClasspath() { - return new HibernateCompatibilityPolicy(HibernateProviderPolicy.fromClasspath()); - } - - /** The provider version the design declares Stable. */ - public String stableProvider() { - return providerPolicy.stableProvider(); - } - - /** The provider versions that may only run in a compatibility lane. */ - public List experimentalProviders() { - return providerPolicy.experimentalProviders(); - } - - /** Whether a provider version may replace the Stable one without a promotion. */ - public boolean mayReplaceStableProvider(String version) { - return !providerPolicy.isExperimental(version); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/next/PromotionDecision.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/next/PromotionDecision.java deleted file mode 100644 index 3e6fc114..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/next/PromotionDecision.java +++ /dev/null @@ -1,20 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.experimental.next; - -/** - * Whether an experimental feature may be considered for Stable (experimental plan Task 9). - * - *

The blocked states are distinct because they need different work. A technical block needs - * evidence; a missing ADR needs a decision. Collapsing them into one "not yet" hides which of the - * two is actually outstanding. - */ -public enum PromotionDecision { - - /** One or more evidence suites have not passed. */ - BLOCKED_TECHNICAL, - - /** Every suite passed, but no reviewed ADR records the decision. */ - BLOCKED_MISSING_ADR, - - /** Evidence and decision are both in place; Stable review may begin. */ - ELIGIBLE_FOR_STABLE_REVIEW -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/next/PromotionEvidence.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/next/PromotionEvidence.java deleted file mode 100644 index ca2dd501..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/next/PromotionEvidence.java +++ /dev/null @@ -1,61 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.experimental.next; - -/** - * The evidence a promotion requires (experimental plan Task 9). - * - *

Version availability is not on this list, and its absence is the point. "PostgreSQL 19 is out" - * is a fact about the world; "our contracts pass on it" is a fact about this platform, and only the - * second one justifies changing what the support matrix promises. - */ -public record PromotionEvidence( - boolean compatibility, - boolean security, - boolean failure, - boolean migration, - boolean performance, - boolean reviewedAdr) { - - /** Evidence with nothing yet gathered. */ - public static PromotionEvidence none() { - return new PromotionEvidence(false, false, false, false, false, false); - } - - /** A builder-style copy with the compatibility suite recorded. */ - public PromotionEvidence withCompatibility(boolean passed) { - return new PromotionEvidence(passed, security, failure, migration, performance, reviewedAdr); - } - - /** A builder-style copy with the security suite recorded. */ - public PromotionEvidence withSecurity(boolean passed) { - return new PromotionEvidence( - compatibility, passed, failure, migration, performance, reviewedAdr); - } - - /** A builder-style copy with the failure-injection suite recorded. */ - public PromotionEvidence withFailure(boolean passed) { - return new PromotionEvidence( - compatibility, security, passed, migration, performance, reviewedAdr); - } - - /** A builder-style copy with the migration suite recorded. */ - public PromotionEvidence withMigration(boolean passed) { - return new PromotionEvidence( - compatibility, security, failure, passed, performance, reviewedAdr); - } - - /** A builder-style copy with the performance suite recorded. */ - public PromotionEvidence withPerformance(boolean passed) { - return new PromotionEvidence(compatibility, security, failure, migration, passed, reviewedAdr); - } - - /** A builder-style copy with the reviewed ADR recorded. */ - public PromotionEvidence withReviewedAdr(boolean reviewed) { - return new PromotionEvidence( - compatibility, security, failure, migration, performance, reviewed); - } - - /** Whether every technical suite has passed. */ - public boolean allTechnicalGatesPassed() { - return compatibility && security && failure && migration && performance; - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/replica/ConsistencyAwareDataSourceRouter.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/replica/ConsistencyAwareDataSourceRouter.java index 60bf43c9..284059d3 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/replica/ConsistencyAwareDataSourceRouter.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/replica/ConsistencyAwareDataSourceRouter.java @@ -1,7 +1,5 @@ package dev.caskeleton.adapter.outbound.persistence.experimental.replica; -import dev.caskeleton.adapter.outbound.persistence.experimental.ExperimentalFeature; -import dev.caskeleton.adapter.outbound.persistence.experimental.ExperimentalFeatureGate; import java.util.Objects; /** @@ -22,38 +20,14 @@ import java.util.Objects; * mean two connections to two databases inside one unit of work, with no relationship between what * each of them sees. * - *

Constructed only through {@code enabledBy}, and the constructor is package-private so that is - * the only way. The gate's own documentation says that having this class on the classpath is not - * consent to run it — but nothing enforced that: the public constructor meant one {@code new} was a - * complete bypass, and replica routing is exactly the kind of behaviour whose accidental activation - * is invisible until it routes a read somewhere wrong. + *

Nothing constructs this class for you: a deployment that routes reads to a replica creates one + * in its own code, and that {@code new} is the opt-in. */ public final class ConsistencyAwareDataSourceRouter { private final ReplicaLagMonitor lagMonitor; - /** - * The only way to obtain one. - * - *

The gate is asked before anything is constructed, so a deployment that never set the flag - * cannot end up holding an instance. Taking the gate as a parameter rather than consulting a - * static makes the requirement part of the signature: a caller cannot forget an argument the - * compiler insists on. - * - * @param gate the experimental consent gate - * @param flags the deployment's experimental flags - * @throws IllegalStateException naming the property that must be set - */ - public static ConsistencyAwareDataSourceRouter enabledBy( - ExperimentalFeatureGate gate, - java.util.Map flags, - ReplicaLagMonitor lagMonitor) { - java.util.Objects.requireNonNull(gate, "gate") - .requireEnabled(ExperimentalFeature.READ_REPLICA, flags); - return new ConsistencyAwareDataSourceRouter(lagMonitor); - } - - ConsistencyAwareDataSourceRouter(ReplicaLagMonitor lagMonitor) { + public ConsistencyAwareDataSourceRouter(ReplicaLagMonitor lagMonitor) { this.lagMonitor = Objects.requireNonNull(lagMonitor, "lagMonitor"); } diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/rls/RlsAdminBypassToken.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/rls/RlsAdminBypassToken.java deleted file mode 100644 index 5ea5a955..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/rls/RlsAdminBypassToken.java +++ /dev/null @@ -1,28 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.experimental.rls; - -import java.util.Objects; -import java.util.regex.Pattern; - -/** - * The audited identity a cross-tenant RLS bypass runs under (experimental plan Task 3). - * - *

A bypass needs a separate DataSource, connected as a role that RLS does not apply to. Sharing - * the runtime DataSource would mean the bypass role is the role every ordinary request already - * uses, at which point the policies protect nothing. - */ -public record RlsAdminBypassToken(String operator, String reason) { - - private static final Pattern OPERATOR = Pattern.compile("[A-Za-z0-9._:-]{1,64}"); - private static final int MAX_REASON_LENGTH = 256; - - public RlsAdminBypassToken { - Objects.requireNonNull(operator, "operator"); - Objects.requireNonNull(reason, "reason"); - if (!OPERATOR.matcher(operator).matches()) { - throw new IllegalArgumentException("invalid bypass operator identity"); - } - if (reason.isBlank() || reason.length() > MAX_REASON_LENGTH) { - throw new IllegalArgumentException("a bypass requires a present, bounded reason"); - } - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/rls/RlsTenantSessionBinder.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/rls/RlsTenantSessionBinder.java index 51ae31c9..ceade3e8 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/rls/RlsTenantSessionBinder.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/rls/RlsTenantSessionBinder.java @@ -1,7 +1,5 @@ package dev.caskeleton.adapter.outbound.persistence.experimental.rls; -import dev.caskeleton.adapter.outbound.persistence.experimental.ExperimentalFeature; -import dev.caskeleton.adapter.outbound.persistence.experimental.ExperimentalFeatureGate; import dev.caskeleton.adapter.outbound.persistence.experimental.tenant.TenantId; import jakarta.persistence.EntityManager; import java.util.Objects; @@ -19,11 +17,8 @@ import java.util.Objects; *

The tenant is bound as a parameter, never concatenated. A tenant id is externally influenced * data, and {@code set_config} takes a string. * - *

Constructed only through {@code enabledBy}, and the constructor is package-private so that is - * the only way. The gate's own documentation says that having this class on the classpath is not - * consent to run it — but nothing enforced that: the public constructor meant one {@code new} was a - * complete bypass, and row-level security tenant binding is exactly the kind of behaviour whose - * accidental activation is invisible until it routes a read somewhere wrong. + *

Nothing constructs this class for you: a deployment that wants RLS tenant binding creates one + * in its own adapter code, and that {@code new} is the opt-in. */ public final class RlsTenantSessionBinder { @@ -33,27 +28,6 @@ public final class RlsTenantSessionBinder { /** Transaction-local binding; the {@code true} argument is what scopes it to the transaction. */ private static final String BIND_SQL = "select set_config('app.tenant_id', ?, true)"; - /** - * The only way to obtain one. - * - *

The gate is asked before anything is constructed, so a deployment that never set the flag - * cannot end up holding an instance. Taking the gate as a parameter rather than consulting a - * static makes the requirement part of the signature: a caller cannot forget an argument the - * compiler insists on. - * - * @param gate the experimental consent gate - * @param flags the deployment's experimental flags - * @throws IllegalStateException naming the property that must be set - */ - public static RlsTenantSessionBinder enabledBy( - ExperimentalFeatureGate gate, java.util.Map flags) { - Objects.requireNonNull(gate, "gate") - .requireEnabled(ExperimentalFeature.MULTITENANCY_RLS, flags); - return new RlsTenantSessionBinder(); - } - - RlsTenantSessionBinder() {} - /** Binds {@code tenant} for the remainder of the current transaction. */ public void bind(EntityManager entityManager, TenantId tenant) { Objects.requireNonNull(entityManager, "entityManager"); diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/schema/SchemaTenantMigrationOrchestrator.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/schema/SchemaTenantMigrationOrchestrator.java index 8b16405a..098ed950 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/schema/SchemaTenantMigrationOrchestrator.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/schema/SchemaTenantMigrationOrchestrator.java @@ -1,7 +1,5 @@ package dev.caskeleton.adapter.outbound.persistence.experimental.schema; -import dev.caskeleton.adapter.outbound.persistence.experimental.ExperimentalFeature; -import dev.caskeleton.adapter.outbound.persistence.experimental.ExperimentalFeatureGate; import dev.caskeleton.adapter.outbound.persistence.experimental.tenant.TenantId; import java.util.LinkedHashMap; import java.util.List; @@ -25,11 +23,8 @@ import org.flywaydb.core.api.output.MigrateResult; * mismatch on one tenant is the same evidence it is anywhere else, and repairing it here would * erase it N times over. * - *

Constructed only through {@code enabledBy}, and the constructor is package-private so that is - * the only way. The gate's own documentation says that having this class on the classpath is not - * consent to run it — but nothing enforced that: the public constructor meant one {@code new} was a - * complete bypass, and schema-per-tenant migration is exactly the kind of behaviour whose - * accidental activation is invisible until it routes a read somewhere wrong. + *

Nothing constructs this class for you: a deployment that runs schema-per-tenant creates one in + * its own code, and that {@code new} is the opt-in. */ public final class SchemaTenantMigrationOrchestrator { @@ -38,30 +33,7 @@ public final class SchemaTenantMigrationOrchestrator { private final String migrationLocation; private final Map status = new LinkedHashMap<>(); - /** - * The only way to obtain one. - * - *

The gate is asked before anything is constructed, so a deployment that never set the flag - * cannot end up holding an instance. Taking the gate as a parameter rather than consulting a - * static makes the requirement part of the signature: a caller cannot forget an argument the - * compiler insists on. - * - * @param gate the experimental consent gate - * @param flags the deployment's experimental flags - * @throws IllegalStateException naming the property that must be set - */ - public static SchemaTenantMigrationOrchestrator enabledBy( - ExperimentalFeatureGate gate, - java.util.Map flags, - DataSource dataSource, - SchemaTenantRegistry registry, - String migrationLocation) { - java.util.Objects.requireNonNull(gate, "gate") - .requireEnabled(ExperimentalFeature.MULTITENANCY_SCHEMA, flags); - return new SchemaTenantMigrationOrchestrator(dataSource, registry, migrationLocation); - } - - SchemaTenantMigrationOrchestrator( + public SchemaTenantMigrationOrchestrator( DataSource dataSource, SchemaTenantRegistry registry, String migrationLocation) { this.dataSource = Objects.requireNonNull(dataSource, "dataSource"); this.registry = Objects.requireNonNull(registry, "registry"); diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/tenant/TenantEntityListenerGuard.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/tenant/TenantEntityListenerGuard.java deleted file mode 100644 index e35f5995..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/experimental/tenant/TenantEntityListenerGuard.java +++ /dev/null @@ -1,55 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.experimental.tenant; - -import jakarta.persistence.PrePersist; -import jakarta.persistence.PreUpdate; -import java.util.Objects; -import java.util.function.BiConsumer; -import java.util.function.Function; - -/** - * Stamps and verifies the tenant column on every write (experimental plan Task 2). - * - *

Reads are only half the isolation problem. A write with the wrong tenant column — or with none - * — inserts a row that the writing tenant cannot see and another tenant can. The listener stamps - * the bound tenant on insert and refuses an update that would move a row between tenants. - * - * @param the tenant-scoped entity type - */ -public final class TenantEntityListenerGuard { - - private final Function tenantReader; - private final BiConsumer tenantWriter; - - public TenantEntityListenerGuard( - Function tenantReader, BiConsumer tenantWriter) { - this.tenantReader = Objects.requireNonNull(tenantReader, "tenantReader"); - this.tenantWriter = Objects.requireNonNull(tenantWriter, "tenantWriter"); - } - - /** Stamps the bound tenant onto a new row. */ - @PrePersist - public void stampOnInsert(T entity) { - Objects.requireNonNull(entity, "entity"); - TenantId bound = TenantContext.require(); - TenantId existing = tenantReader.apply(entity); - if (existing == null) { - tenantWriter.accept(entity, bound); - return; - } - requireSameTenant(existing, bound); - } - - /** Refuses an update that would move a row to another tenant. */ - @PreUpdate - public void verifyOnUpdate(T entity) { - Objects.requireNonNull(entity, "entity"); - requireSameTenant(tenantReader.apply(entity), TenantContext.require()); - } - - private static void requireSameTenant(TenantId entityTenant, TenantId boundTenant) { - if (entityTenant == null || !entityTenant.equals(boundTenant)) { - throw new IllegalStateException( - "a write must stay within the bound tenant; cross-tenant writes are refused"); - } - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/h2/H2FailureTranslator.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/h2/H2FailureTranslator.java deleted file mode 100644 index 099512b1..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/h2/H2FailureTranslator.java +++ /dev/null @@ -1,63 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.h2; - -import dev.caskeleton.adapter.outbound.persistence.api.PersistenceOperationName; -import dev.caskeleton.adapter.outbound.persistence.api.error.DeadlockDetectedException; -import dev.caskeleton.adapter.outbound.persistence.api.error.FailureCategory; -import dev.caskeleton.adapter.outbound.persistence.api.error.JpaFailureContext; -import dev.caskeleton.adapter.outbound.persistence.api.error.JpaPersistenceException; -import dev.caskeleton.adapter.outbound.persistence.api.error.SerializationFailureException; -import dev.caskeleton.adapter.outbound.persistence.api.error.SqlExceptionSqlStateResolver; -import dev.caskeleton.adapter.outbound.persistence.api.error.SqlStateResolver; -import dev.caskeleton.adapter.outbound.persistence.api.error.VendorFailureTranslator; -import java.time.Duration; -import java.util.Objects; - -/** - * Classifies the contention SQLSTATEs the local H2 composition can surface. - * - *

H2 is not the production concurrency-fidelity database, but the local runtime still uses the - * same full-transaction retry coordinator. Leaving this SPI absent made every H2 contention failure - * bypass that coordinator entirely, so local behaviour contradicted the platform contract. - */ -final class H2FailureTranslator implements VendorFailureTranslator { - - private final SqlStateResolver sqlStateResolver; - - public H2FailureTranslator() { - this(new SqlExceptionSqlStateResolver()); - } - - H2FailureTranslator(SqlStateResolver sqlStateResolver) { - this.sqlStateResolver = Objects.requireNonNull(sqlStateResolver, "sqlStateResolver"); - } - - @Override - public JpaPersistenceException translate( - Throwable failure, - PersistenceOperationName operation, - int attempt, - Duration elapsed, - String traceId) { - Objects.requireNonNull(failure, "failure"); - Objects.requireNonNull(operation, "operation"); - - String sqlState = sqlStateResolver.resolve(failure).orElse(JpaFailureContext.NO_SQL_STATE); - Duration boundedElapsed = elapsed == null ? Duration.ZERO : elapsed; - - return switch (sqlState) { - case "40001" -> - new SerializationFailureException( - JpaFailureContext.retryable(operation, sqlState, attempt, boundedElapsed, traceId), - failure); - case "40P01" -> - new DeadlockDetectedException( - JpaFailureContext.retryable(operation, sqlState, attempt, boundedElapsed, traceId), - failure); - default -> - new JpaPersistenceException( - FailureCategory.UNKNOWN, - JpaFailureContext.terminal(operation, sqlState, attempt, boundedElapsed, traceId), - failure); - }; - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/h2/H2IdempotencyClaimRepository.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/h2/H2IdempotencyClaimRepository.java deleted file mode 100644 index 7c7cac59..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/h2/H2IdempotencyClaimRepository.java +++ /dev/null @@ -1,96 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.h2; - -import dev.caskeleton.adapter.outbound.persistence.idempotency.IdempotencyClaimRepository; -import dev.caskeleton.adapter.outbound.persistence.idempotency.entity.IdempotencyRecordEntity; -import jakarta.persistence.EntityManager; -import java.time.Instant; -import java.util.Optional; -import java.util.UUID; -import org.jspecify.annotations.Nullable; - -/** - * H2 atomic scope claim. - * - *

H2 has no {@code INSERT ... ON CONFLICT ... DO UPDATE ... RETURNING}, so the PostgreSQL - * statement does not port. The standard {@code MERGE ... USING} does, and carries the same meaning - * in one statement: - * - *

    - *
  • no row for the scope → {@code WHEN NOT MATCHED} inserts the claim (1 row); - *
  • a live row → neither branch fires (0 rows), so the caller lost to a live winner; - *
  • an expired row → {@code WHEN MATCHED AND expires_at <= now} takes it over (1 row). - *
- * - *

One statement rather than select-then-insert is what keeps the SPI's promise not to poison the - * caller transaction: a losing claim returns zero updated rows, never a constraint violation the - * surrounding transaction would have to absorb. - * - *

No {@code RETURNING} is needed. The PostgreSQL statement returns {@code EXCLUDED.id}, which is - * the proposed id on both branches, so a claimed row is always this caller's proposed id. - */ -public final class H2IdempotencyClaimRepository implements IdempotencyClaimRepository { - - private static final String CLAIM_SQL = - """ - MERGE INTO idempotency_record t - USING (VALUES ( - CAST(:id AS uuid), CAST(:tenant AS varchar(128)), CAST(:principal AS varchar(256)), - CAST(:idempotencyKey AS varchar(256)), CAST(:useCaseName AS varchar(256)), - CAST(:requestHash AS varchar(64)), - CAST(:createdAt AS timestamp(6) with time zone), - CAST(:expiresAt AS timestamp(6) with time zone) - )) AS s (id, tenant, principal, idempotency_key, use_case_name, - request_hash, created_at, expires_at) - ON t.tenant = s.tenant - AND t.principal = s.principal - AND t.idempotency_key = s.idempotency_key - AND t.use_case_name = s.use_case_name - WHEN MATCHED AND t.expires_at <= :now THEN UPDATE SET - id = s.id, - request_hash = s.request_hash, - status = 'IN_FLIGHT', - response_payload = NULL, - response_ref = NULL, - created_at = s.created_at, - expires_at = s.expires_at - WHEN NOT MATCHED THEN INSERT ( - id, tenant, principal, idempotency_key, use_case_name, - request_hash, status, response_payload, response_ref, created_at, expires_at - ) VALUES ( - s.id, s.tenant, s.principal, s.idempotency_key, s.use_case_name, - s.request_hash, 'IN_FLIGHT', NULL, NULL, s.created_at, s.expires_at - ) - """; - - private final EntityManager entityManager; - - public H2IdempotencyClaimRepository(EntityManager entityManager) { - this.entityManager = entityManager; - } - - @Override - public Optional tryClaim( - IdempotencyRecordEntity proposed, - Instant now, - @Nullable IdempotencyRecordEntity exactExpiredEntity) { - // Same detach as the PostgreSQL path: a managed copy of the row this statement is about to - // overwrite would be flushed back over the claim at commit. - if (exactExpiredEntity != null && entityManager.contains(exactExpiredEntity)) { - entityManager.detach(exactExpiredEntity); - } - int claimed = - entityManager - .createNativeQuery(CLAIM_SQL) - .setParameter("id", proposed.getId()) - .setParameter("tenant", proposed.getTenant()) - .setParameter("principal", proposed.getPrincipal()) - .setParameter("idempotencyKey", proposed.getIdempotencyKey()) - .setParameter("useCaseName", proposed.getUseCaseName()) - .setParameter("requestHash", proposed.getRequestHash()) - .setParameter("createdAt", proposed.getCreatedAt()) - .setParameter("expiresAt", proposed.getExpiresAt()) - .setParameter("now", now) - .executeUpdate(); - return claimed == 1 ? Optional.of(proposed.getId()) : Optional.empty(); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/h2/H2LocalTimeoutConfigurer.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/h2/H2LocalTimeoutConfigurer.java deleted file mode 100644 index b17781e2..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/h2/H2LocalTimeoutConfigurer.java +++ /dev/null @@ -1,55 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.h2; - -import dev.caskeleton.adapter.outbound.persistence.transaction.EffectiveTransactionTimeouts; -import dev.caskeleton.adapter.outbound.persistence.transaction.TransactionLocalTimeoutConfigurer; -import java.time.Duration; -import java.util.Objects; -import org.springframework.jdbc.core.JdbcOperations; - -/** - * Applies H2's timeout guards to the connection bound to the current transaction. - * - *

Two differences from the PostgreSQL configurer, both inherent to H2 rather than choices: - * - *

    - *
  • Session scope, not transaction scope. PostgreSQL takes {@code set_config(..., true)} - * — a value that reverts at transaction end. H2's {@code SET} is session-wide and outlives - * the transaction on a pooled connection. It is not left stale in practice because the - * transaction port applies these before every transaction, so each one overwrites the last; a - * connection borrowed outside that path keeps the previous transaction's guard. - *
  • No idle-in-transaction guard. H2 has no counterpart to {@code - * idle_in_transaction_session_timeout}, so that budget cannot be pushed into the database - * here. It is left to the caller-side deadline the transaction port already enforces, rather - * than silently reported as applied. - *
- * - *

The millisecond values are inlined because H2's {@code SET} takes no bind parameter. They - * arrive as {@link Duration}s from validated settings, never from request input, and a negative one - * is rejected below rather than concatenated. - */ -public final class H2LocalTimeoutConfigurer implements TransactionLocalTimeoutConfigurer { - - private static final String STATEMENT_TIMEOUT_SQL = "SET QUERY_TIMEOUT "; - private static final String LOCK_TIMEOUT_SQL = "SET LOCK_TIMEOUT "; - - private final JdbcOperations jdbcOperations; - - public H2LocalTimeoutConfigurer(JdbcOperations jdbcOperations) { - this.jdbcOperations = Objects.requireNonNull(jdbcOperations, "jdbcOperations must be non-null"); - } - - @Override - public void apply(EffectiveTransactionTimeouts timeouts) { - Objects.requireNonNull(timeouts, "timeouts must be non-null"); - apply(STATEMENT_TIMEOUT_SQL, "statementTimeout", timeouts.statementTimeout()); - apply(LOCK_TIMEOUT_SQL, "lockTimeout", timeouts.lockTimeout()); - } - - private void apply(String command, String name, Duration timeout) { - long milliseconds = timeout.toMillis(); - if (milliseconds < 0) { - throw new IllegalArgumentException(name + " must not be negative, but was " + timeout); - } - jdbcOperations.execute(command + milliseconds); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/h2/H2PersistenceConfig.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/h2/H2PersistenceConfig.java index 45641dee..27146084 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/h2/H2PersistenceConfig.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/h2/H2PersistenceConfig.java @@ -1,18 +1,14 @@ package dev.caskeleton.adapter.outbound.persistence.h2; -import dev.caskeleton.adapter.outbound.persistence.api.error.VendorFailureTranslator; import dev.caskeleton.adapter.outbound.persistence.config.PersistenceJpaConfig; import dev.caskeleton.adapter.outbound.persistence.config.PersistenceVendorSettings; import dev.caskeleton.adapter.outbound.persistence.failure.SqlStateErrorMapping; -import dev.caskeleton.adapter.outbound.persistence.idempotency.IdempotencyClaimRepository; import dev.caskeleton.adapter.outbound.persistence.outbox.OutboxClaimRepository; -import dev.caskeleton.adapter.outbound.persistence.transaction.TransactionLocalTimeoutConfigurer; import jakarta.persistence.EntityManager; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; -import org.springframework.jdbc.core.JdbcOperations; /** * H2 vendor persistence configuration — the same four SPI beans the PostgreSQL vendor registers, @@ -55,20 +51,4 @@ public class H2PersistenceConfig { public SqlStateErrorMapping h2SqlStateErrorMapping() { return new H2SqlStateErrorMapping(); } - - @Bean - public VendorFailureTranslator h2VendorFailureTranslator() { - return new H2FailureTranslator(); - } - - @Bean - public TransactionLocalTimeoutConfigurer transactionLocalTimeoutConfigurer( - JdbcOperations jdbcOperations) { - return new H2LocalTimeoutConfigurer(jdbcOperations); - } - - @Bean - public IdempotencyClaimRepository idempotencyClaimRepository(EntityManager entityManager) { - return new H2IdempotencyClaimRepository(entityManager); - } } diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/hibernate/batch/HibernateJpaBatchExecutor.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/hibernate/batch/HibernateJpaBatchExecutor.java index 4ac3ba4f..041fe45f 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/hibernate/batch/HibernateJpaBatchExecutor.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/hibernate/batch/HibernateJpaBatchExecutor.java @@ -19,7 +19,7 @@ import org.hibernate.Session; * outside one rather than letting each flush auto-commit, which would leave a partially imported * data set behind on failure with no way to roll it back. */ -public final class HibernateJpaBatchExecutor implements JpaBatchExecutor { +public final class HibernateJpaBatchExecutor { private final EntityManager entityManager; private final HibernateStatisticsCollector statistics; @@ -32,7 +32,11 @@ public final class HibernateJpaBatchExecutor implements JpaBatchExecutor { this.configurationGuard = new HibernateBatchConfigurationGuard(); } - @Override + /** + * Persists every item exactly once, flushing and clearing on the profile's boundaries. + * + * @param persister applies the actual persist call for one item + */ public BatchExecutionResult persist( JpaBatchProfile profile, Iterable items, Consumer persister) { Objects.requireNonNull(profile, "profile"); diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/hibernate/batch/JpaBatchExecutor.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/hibernate/batch/JpaBatchExecutor.java deleted file mode 100644 index f5a122fb..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/hibernate/batch/JpaBatchExecutor.java +++ /dev/null @@ -1,22 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.hibernate.batch; - -import java.util.function.Consumer; - -/** - * Persists many entities under a named batch profile (design §28). - * - *

The executor owns the flush and clear boundaries; the caller owns the transaction. That split - * is deliberate: flushing is a Persistence Context concern the profile decides, while committing is - * a use-case decision, and an executor that committed on its own would break the "application - * service owns the transaction boundary" rule the whole platform rests on. - */ -public interface JpaBatchExecutor { - - /** - * Persists every item exactly once, flushing and clearing on the profile's boundaries. - * - * @param persister applies the actual persist call for one item - */ - BatchExecutionResult persist( - JpaBatchProfile profile, Iterable items, Consumer persister); -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/hibernate/batch/JpaBatchProfileRegistry.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/hibernate/batch/JpaBatchProfileRegistry.java deleted file mode 100644 index c38502c6..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/hibernate/batch/JpaBatchProfileRegistry.java +++ /dev/null @@ -1,63 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.hibernate.batch; - -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Set; - -/** - * The bounded set of batch profiles an application declares (design §28.2). - * - *

Fail-closed lookup, for the same reason as the transaction profile registry: falling back to a - * default would let a mistyped profile name run an import with somebody else's flush boundary. - */ -public final class JpaBatchProfileRegistry { - - private final Map byName; - - public JpaBatchProfileRegistry(Map profiles) { - Objects.requireNonNull(profiles, "profiles"); - Map copy = new LinkedHashMap<>(); - profiles.forEach( - (name, profile) -> { - Objects.requireNonNull(name, "profile name"); - Objects.requireNonNull(profile, "profile"); - if (!name.equals(profile.name())) { - throw new IllegalArgumentException( - "registry key '" + name + "' does not match profile name '" + profile.name() + "'"); - } - copy.put(name, profile); - }); - this.byName = Map.copyOf(copy); - } - - /** A registry built from profiles that already carry their own names. */ - public static JpaBatchProfileRegistry of(JpaBatchProfile... profiles) { - Map byName = new LinkedHashMap<>(); - for (JpaBatchProfile profile : profiles) { - if (byName.put(profile.name(), profile) != null) { - throw new IllegalArgumentException("duplicate batch profile: " + profile.name()); - } - } - return new JpaBatchProfileRegistry(byName); - } - - /** - * The profile registered under {@code name}. - * - * @throws IllegalArgumentException when no profile is registered under that name - */ - public JpaBatchProfile require(String name) { - JpaBatchProfile profile = byName.get(name); - if (profile == null) { - throw new IllegalArgumentException( - "unregistered batch profile '" + name + "'; registered profiles are " + names()); - } - return profile; - } - - /** The registered profile names, in declaration order. */ - public Set names() { - return byName.keySet(); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/hibernate/bulk/BulkDmlExecutor.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/hibernate/bulk/BulkDmlExecutor.java deleted file mode 100644 index 5fbd1e95..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/hibernate/bulk/BulkDmlExecutor.java +++ /dev/null @@ -1,22 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.hibernate.bulk; - -import java.util.function.IntSupplier; - -/** - * Runs a bulk DML statement with the flush and clear ordering the design requires (design §29). - * - *

Bulk DML bypasses the Persistence Context entirely: no entity callbacks run, no - * {@code @Version} is checked, and no managed entity is updated. Those are not incidental - * limitations — they are why bulk DML is fast — but they mean the surrounding context must be - * reconciled by hand, which is what this executor exists to guarantee. - */ -public interface BulkDmlExecutor { - - /** - * Flushes, runs {@code statement}, clears, and verifies the affected-row expectation. - * - * @param statement executes the bulk statement and returns its affected-row count - */ - BulkDmlResult execute( - BulkOperationName name, IntSupplier statement, AffectedRowsExpectation expectation); -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/hibernate/bulk/HibernateBulkDmlExecutor.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/hibernate/bulk/HibernateBulkDmlExecutor.java index 3cbaa735..19089f18 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/hibernate/bulk/HibernateBulkDmlExecutor.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/hibernate/bulk/HibernateBulkDmlExecutor.java @@ -25,7 +25,7 @@ import java.util.function.IntSupplier; * standing between a bug and a table-wide write. Verification happens inside the caller's * transaction so the rollback is still available. */ -public final class HibernateBulkDmlExecutor implements BulkDmlExecutor { +public final class HibernateBulkDmlExecutor { private final EntityManager entityManager; private final QueryObservation observation; @@ -45,7 +45,11 @@ public final class HibernateBulkDmlExecutor implements BulkDmlExecutor { Map.copyOf(Objects.requireNonNull(registeredOperations, "registeredOperations")); } - @Override + /** + * Flushes, runs {@code statement}, clears, and verifies the affected-row expectation. + * + * @param statement executes the bulk statement and returns its affected-row count + */ public BulkDmlResult execute( BulkOperationName name, IntSupplier statement, AffectedRowsExpectation expectation) { Objects.requireNonNull(name, "name"); diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/hibernate/stateless/HibernateStatelessSessionRunner.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/hibernate/stateless/HibernateStatelessSessionRunner.java index c27e07d0..00f8aa30 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/hibernate/stateless/HibernateStatelessSessionRunner.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/hibernate/stateless/HibernateStatelessSessionRunner.java @@ -20,7 +20,7 @@ import org.hibernate.Transaction; *

Only registered work names may run, and each carries a declared row cap. An admin bulk path * without a cap is how a maintenance job becomes an outage. */ -public final class HibernateStatelessSessionRunner implements StatelessSessionRunner { +public final class HibernateStatelessSessionRunner { private final SessionFactory sessionFactory; private final Set registeredWork; @@ -31,7 +31,15 @@ public final class HibernateStatelessSessionRunner implements StatelessSessionRu this.registeredWork = Set.copyOf(Objects.requireNonNull(registeredWork, "registeredWork")); } - @Override + /** + * Runs {@code work} in its own stateless session and transaction. + * + *

The work reports how many rows it touched, and exceeding {@code maxRows} rolls the + * transaction back. + * + * @param maxRows the row cap for this unit of work + * @throws StatelessRowCapExceededException when the work touched more, after rolling back + */ public T execute( StatelessWorkName name, long maxRows, diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/hibernate/stateless/StatelessSessionRunner.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/hibernate/stateless/StatelessSessionRunner.java deleted file mode 100644 index f9e298a4..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/hibernate/stateless/StatelessSessionRunner.java +++ /dev/null @@ -1,36 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.hibernate.stateless; - -import java.util.function.Function; -import org.hibernate.StatelessSession; - -/** - * Runs bulk work through a Hibernate {@code StatelessSession} (design §30.1). - * - *

A stateless session has no Persistence Context: no dirty checking, no cascade, no first-level - * cache, no lazy loading, and no automatic version increment. Those absences are why it stays flat - * in memory over millions of rows, and they are also why objects it returns are detached copies — - * loading the same row twice yields two unrelated instances. - * - *

It is therefore opt-in and never the default repository implementation. Code written against - * ordinary JPA semantics behaves subtly differently here, and the difference shows up as missing - * updates rather than as an error. - */ -public interface StatelessSessionRunner { - - /** - * Runs {@code work} in its own stateless session and transaction. - * - *

The work reports how many rows it touched, and exceeding {@code maxRows} rolls the - * transaction back. The cap used to be a positive-number check and nothing else: a caller - * declared a bound, the runner validated the number, and the work then touched however many rows - * it liked. On the one session type chosen for work that can be enormous, that is the bound - * nobody was applying. - * - * @param maxRows the row cap for this unit of work - * @throws StatelessRowCapExceededException when the work touched more, after rolling back - */ - T execute( - StatelessWorkName name, - long maxRows, - Function> work); -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/IdempotencyClaimRepository.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/IdempotencyClaimRepository.java deleted file mode 100644 index d0b41d15..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/IdempotencyClaimRepository.java +++ /dev/null @@ -1,20 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.idempotency; - -import dev.caskeleton.adapter.outbound.persistence.idempotency.entity.IdempotencyRecordEntity; -import java.time.Instant; -import java.util.Optional; -import java.util.UUID; -import org.jspecify.annotations.Nullable; - -/** Vendor-neutral SPI for a transaction-safe insert-or-expired-reclaim claim. */ -public interface IdempotencyClaimRepository { - - /** - * Returns the new/reclaimed record ID when this caller won, or empty for a live winner. - * Implementations must not poison the caller transaction on an ordinary uniqueness race. - */ - Optional tryClaim( - IdempotencyRecordEntity proposed, - Instant now, - @Nullable IdempotencyRecordEntity exactExpiredEntity); -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/IdempotencyReaper.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/IdempotencyReaper.java index 3461d791..7adb7609 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/IdempotencyReaper.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/IdempotencyReaper.java @@ -9,11 +9,14 @@ import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; /** - * Periodically deletes expired idempotency records. A backstop that bounds table growth — expiry is - * also enforced lazily on read and on reclaim (see README "idempotency"). + * Periodically deletes idempotency rows whose {@code expires_at} has passed. The PostgreSQL store + * moves {@code expires_at} forward on every completion and failure, and a claim is reset in place + * rather than re-inserted, so this is the only thing that bounds table growth. */ @Component -@ConditionalOnProperty(name = "ca-skeleton.capabilities.idempotency.provider", havingValue = "jdbc") +@ConditionalOnProperty( + name = "ca-skeleton.capabilities.idempotency.provider", + havingValue = "postgresql") public class IdempotencyReaper { private static final Logger log = LoggerFactory.getLogger(IdempotencyReaper.class); @@ -26,7 +29,7 @@ public class IdempotencyReaper { this.clock = clock; } - @Scheduled(fixedDelayString = "${ca-skeleton.idempotency.reaper-interval:PT10M}") + @Scheduled(fixedDelayString = "${ca-skeleton.capabilities.idempotency.reaper-interval:PT10M}") @Transactional public int reap() { int purged = repository.deleteExpired(clock.instant()); diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/IdempotencyRecordJpaRepository.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/IdempotencyRecordJpaRepository.java index ad4277cf..df7c0dc2 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/IdempotencyRecordJpaRepository.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/IdempotencyRecordJpaRepository.java @@ -2,33 +2,16 @@ package dev.caskeleton.adapter.outbound.persistence.idempotency; import dev.caskeleton.adapter.outbound.persistence.idempotency.entity.IdempotencyRecordEntity; import java.time.Instant; -import java.util.Optional; import java.util.UUID; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; -/** - * Spring Data repository for {@link IdempotencyRecordEntity}: lookup by scope, delete by scope, and - * the reaper's expiry purge. - */ +/** Spring Data repository for {@link IdempotencyRecordEntity}: the reaper's expiry purge. */ public interface IdempotencyRecordJpaRepository extends JpaRepository { - Optional findByTenantAndPrincipalAndIdempotencyKeyAndUseCaseName( - String tenant, String principal, String idempotencyKey, String useCaseName); - - @Modifying - @Query( - "delete from IdempotencyRecordEntity e where e.tenant = :tenant and e.principal = :principal " - + "and e.idempotencyKey = :idempotencyKey and e.useCaseName = :useCaseName") - int deleteByScope( - @Param("tenant") String tenant, - @Param("principal") String principal, - @Param("idempotencyKey") String idempotencyKey, - @Param("useCaseName") String useCaseName); - /** Reaper / TTL boundary (§E): purge every record whose expiry is at/before {@code now}. */ @Modifying @Query("delete from IdempotencyRecordEntity e where e.expiresAt <= :now") diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/IdempotencyResponseObjectStore.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/IdempotencyResponseObjectStore.java deleted file mode 100644 index 4f435c03..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/IdempotencyResponseObjectStore.java +++ /dev/null @@ -1,15 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.idempotency; - -/** - * Optional seam for offloading a large idempotent response body to an object store. With no bean - * wired, {@link IdempotencyStoreAdapter} falls back to inline DB storage (D9 is UNSUPPORTED — see - * README "idempotency"). Wire a real implementation (S3 / GCS / MinIO) to activate the offload. - */ -public interface IdempotencyResponseObjectStore { - - /** Persist {@code payload}, returning the storage reference kept in the DB row. */ - String put(String payload); - - /** Resolve a previously stored reference back to the full payload for replay. */ - String get(String reference); -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/IdempotencyStoreAdapter.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/IdempotencyStoreAdapter.java deleted file mode 100644 index b343c689..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/IdempotencyStoreAdapter.java +++ /dev/null @@ -1,192 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.idempotency; - -import dev.caskeleton.adapter.outbound.persistence.idempotency.entity.IdempotencyRecordEntity; -import dev.caskeleton.adapter.outbound.persistence.idempotency.mapper.IdempotencyRecordEntityMapper; -import dev.caskeleton.application.idempotency.IdempotencyRecord; -import dev.caskeleton.application.idempotency.IdempotencyScope; -import dev.caskeleton.application.idempotency.IdempotencyStorePort; -import dev.caskeleton.application.idempotency.RequestFingerprint; -import dev.caskeleton.application.idempotency.StoredResponse; -import java.nio.charset.StandardCharsets; -import java.time.Clock; -import java.time.Instant; -import java.util.Optional; -import java.util.UUID; -import org.jspecify.annotations.Nullable; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.dao.DataIntegrityViolationException; -import org.springframework.stereotype.Repository; - -/** - * DB-backed {@link IdempotencyStorePort}. {@link #tryBegin} uses the {@code uq_idempotency_scope} - * unique constraint as the concurrency arbiter; {@link #complete} applies the §F inline/ref payload - * split. See README "idempotency" for the concurrency and §F rationale. - */ -@Repository -@ConditionalOnProperty(name = "ca-skeleton.capabilities.idempotency.provider", havingValue = "jdbc") -public class IdempotencyStoreAdapter implements IdempotencyStorePort { - - /** §F threshold: payloads up to this size are stored inline in the DB row. */ - static final int INLINE_MAX_BYTES = 8 * 1024; - - private static final Logger log = LoggerFactory.getLogger(IdempotencyStoreAdapter.class); - - private final IdempotencyRecordJpaRepository repository; - private final @Nullable IdempotencyResponseObjectStore objectStore; - private final @Nullable IdempotencyClaimRepository claimRepository; - private final Clock clock; - - public IdempotencyStoreAdapter( - IdempotencyRecordJpaRepository repository, - @Nullable IdempotencyResponseObjectStore objectStore, - Clock clock) { - this(repository, objectStore, null, clock); - } - - @Autowired - public IdempotencyStoreAdapter( - IdempotencyRecordJpaRepository repository, - @Nullable IdempotencyResponseObjectStore objectStore, - @Nullable IdempotencyClaimRepository claimRepository, - Clock clock) { - this.repository = repository; - this.objectStore = objectStore; - this.claimRepository = claimRepository; - this.clock = clock; - } - - @Override - public boolean tryBegin( - IdempotencyScope scope, RequestFingerprint fingerprint, Instant expiresAt) { - // Runs in the caller's transaction (use case owns the boundary via TransactionPort). - Optional existing = lookup(scope); - if (existing.isPresent()) { - IdempotencyRecordEntity row = existing.get(); - if (clock.instant().isBefore(row.getExpiresAt())) { - return false; // a live record already owns the scope - } - } - IdempotencyRecordEntity claim = - new IdempotencyRecordEntity( - UUID.randomUUID(), - IdempotencyRecordEntityMapper.tenantColumn(scope), - scope.principal(), - scope.idempotencyKey(), - scope.useCaseName(), - fingerprint.hex(), - "IN_FLIGHT", - null, - null, - clock.instant(), - expiresAt); - if (claimRepository != null) { - Optional claimed = - claimRepository.tryClaim(claim, clock.instant(), existing.orElse(null)); - if (claimed.isEmpty()) { - return false; - } - IdempotencyRecordEntity reloaded = - repository - .findById(claimed.orElseThrow()) - .orElseThrow(() -> new IllegalStateException("claimed idempotency row is absent")); - if (!reloaded.getRequestHash().equals(fingerprint.hex())) { - throw new IllegalStateException("claimed idempotency row conflicts"); - } - return true; - } - existing.ifPresent(repository::delete); - try { - repository.saveAndFlush(claim); // flush forces the unique-constraint check now - return true; - } catch (DataIntegrityViolationException raceLost) { - // Another caller inserted between the lookup and the flush — they own it. - return false; - } - } - - @Override - public Optional find(IdempotencyScope scope, Instant now) { - Optional row = lookup(scope); - if (row.isEmpty()) { - return Optional.empty(); - } - IdempotencyRecordEntity entity = row.get(); - if (!now.isBefore(entity.getExpiresAt())) { - return Optional.empty(); // expired → treated as absent (§E); reaper / tryBegin purge it - } - return Optional.of(IdempotencyRecordEntityMapper.toRecord(entity, resolvePayload(entity))); - } - - @Override - public void complete(IdempotencyScope scope, StoredResponse response) { - IdempotencyRecordEntity row = - lookup(scope) - .orElseThrow( - () -> - new IllegalStateException( - "no in-flight idempotency record to complete for " + scope.storageKey())); - - String payload = response.payload(); - String inline = null; - String ref = null; - if (exceedsInlineThreshold(payload) && objectStore != null) { - ref = objectStore.put(payload); - } else { - if (exceedsInlineThreshold(payload)) { - log.warn( - "idempotency response exceeds {}B but no object store is configured; " - + "storing inline (feature-rate-limit-idempotency-contract §F seam)", - INLINE_MAX_BYTES); - } - inline = payload; - } - - repository.save( - new IdempotencyRecordEntity( - row.getId(), - row.getTenant(), - row.getPrincipal(), - row.getIdempotencyKey(), - row.getUseCaseName(), - row.getRequestHash(), - "COMPLETED", - inline, - ref, - row.getCreatedAt(), - row.getExpiresAt())); - } - - @Override - public void discard(IdempotencyScope scope) { - repository.deleteByScope( - IdempotencyRecordEntityMapper.tenantColumn(scope), - scope.principal(), - scope.idempotencyKey(), - scope.useCaseName()); - } - - private Optional lookup(IdempotencyScope scope) { - return repository.findByTenantAndPrincipalAndIdempotencyKeyAndUseCaseName( - IdempotencyRecordEntityMapper.tenantColumn(scope), - scope.principal(), - scope.idempotencyKey(), - scope.useCaseName()); - } - - private String resolvePayload(IdempotencyRecordEntity entity) { - if (entity.getResponsePayload() != null) { - return entity.getResponsePayload(); - } - if (entity.getResponseRef() != null && objectStore != null) { - return objectStore.get(entity.getResponseRef()); - } - return null; // IN_FLIGHT row, or a ref with no object store to resolve it - } - - private static boolean exceedsInlineThreshold(String payload) { - return payload.getBytes(StandardCharsets.UTF_8).length > INLINE_MAX_BYTES; - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/mapper/IdempotencyRecordEntityMapper.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/mapper/IdempotencyRecordEntityMapper.java deleted file mode 100644 index 934fa5be..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/mapper/IdempotencyRecordEntityMapper.java +++ /dev/null @@ -1,47 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.idempotency.mapper; - -import dev.caskeleton.adapter.outbound.persistence.idempotency.entity.IdempotencyRecordEntity; -import dev.caskeleton.application.idempotency.IdempotencyRecord; -import dev.caskeleton.application.idempotency.IdempotencyScope; -import dev.caskeleton.application.idempotency.IdempotencyStatus; -import dev.caskeleton.application.idempotency.RequestFingerprint; -import dev.caskeleton.application.idempotency.StoredResponse; - -/** - * Pure translation between the {@link IdempotencyRecordEntity} row and the application {@link - * IdempotencyRecord} — no business policy. The {@code tenant} dimension round-trips through an - * empty string ({@code null} ↔ {@code ""}); see README "idempotency" for why. - */ -public final class IdempotencyRecordEntityMapper { - - private IdempotencyRecordEntityMapper() {} - - /** Empty string on the row represents "no tenant" (single-tenant triple scope). */ - public static String tenantColumn(IdempotencyScope scope) { - return scope.tenant() == null ? "" : scope.tenant(); - } - - public static IdempotencyScope toScope(IdempotencyRecordEntity e) { - String tenant = (e.getTenant() == null || e.getTenant().isEmpty()) ? null : e.getTenant(); - return IdempotencyScope.of(tenant, e.getPrincipal(), e.getIdempotencyKey(), e.getUseCaseName()); - } - - /** - * Build the application record from a row. {@code resolvedPayload} is the fully materialized - * response (already read back from the object store when the row only held a reference). - */ - public static IdempotencyRecord toRecord(IdempotencyRecordEntity e, String resolvedPayload) { - IdempotencyStatus status = IdempotencyStatus.valueOf(e.getStatus()); - StoredResponse response = - (status == IdempotencyStatus.COMPLETED && resolvedPayload != null) - ? new StoredResponse(resolvedPayload) - : null; - return new IdempotencyRecord( - toScope(e), - new RequestFingerprint(e.getRequestHash()), - status, - response, - e.getCreatedAt(), - e.getExpiresAt()); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/lock/DistributedLockPersistenceConfig.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/lock/DistributedLockPersistenceConfig.java index 7281cd3b..f25d7139 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/lock/DistributedLockPersistenceConfig.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/lock/DistributedLockPersistenceConfig.java @@ -1,7 +1,10 @@ package dev.caskeleton.adapter.outbound.persistence.lock; import dev.caskeleton.application.lock.DistributedLockPort; +import io.micrometer.core.instrument.MeterRegistry; import javax.sql.DataSource; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; @@ -13,9 +16,9 @@ import org.springframework.integration.support.locks.DefaultLockRegistry; /** * Spring wiring for the distributed-lock infrastructure: in-process {@link DefaultLockRegistry} by - * default, JDBC {@link JdbcLockRegistry} when {@code multi-instance-enabled=true}. The JDBC bean is - * deliberately not {@code @Primary} so app-bootstrap can wrap it in a metrics decorator. See README - * "lock" for the provider-selection and wiring rationale. + * default, JDBC {@link JdbcLockRegistry} when {@code multi-instance-enabled=true}, wrapped in the + * {@link MeteredDistributedLockPort} metrics decorator as the primary {@code + * distributedLockProvider}. See README "lock" for the provider-selection and wiring rationale. */ @Configuration(proxyBeanMethods = false) // LockSettings is bound here rather than by the composition root's @ConfigurationPropertiesScan, @@ -61,10 +64,7 @@ public class DistributedLockPersistenceConfig { return new JdbcLockRegistry(lockRepository, settings.leaseTtl()); } - /** - * JDBC-backed adapter; named {@code jdbcDistributedLock} for app-bootstrap to wrap (not - * {@code @Primary}). - */ + /** JDBC-backed adapter; named {@code jdbcDistributedLock} and wrapped below (not primary). */ @Bean("jdbcDistributedLock") @ConditionalOnProperty( prefix = "ca-skeleton.runtime", @@ -74,4 +74,21 @@ public class DistributedLockPersistenceConfig { JdbcLockRegistry jdbcLockRegistry, LockSettings settings) { return new LockRegistryDistributedLockAdapter(jdbcLockRegistry, settings.leaseTtl()); } + + /** + * The multi-instance provider every caller receives: the JDBC adapter behind the metrics + * decorator. The bean name {@code distributedLockProvider} is the contract with the composition + * root's {@code StartupSafetyValidator} — do not rename. + */ + @Bean(name = "distributedLockProvider") + @Primary + @ConditionalOnProperty( + prefix = "ca-skeleton.runtime", + name = "multi-instance-enabled", + havingValue = "true") + DistributedLockPort distributedLockProvider( + @Qualifier("jdbcDistributedLock") DistributedLockPort jdbcDistributedLock, + ObjectProvider meterRegistry) { + return new MeteredDistributedLockPort(jdbcDistributedLock, meterRegistry); + } } diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/lock/MeteredDistributedLockPort.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/lock/MeteredDistributedLockPort.java similarity index 93% rename from src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/lock/MeteredDistributedLockPort.java rename to src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/lock/MeteredDistributedLockPort.java index 7e58bb0a..64283af4 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/lock/MeteredDistributedLockPort.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/lock/MeteredDistributedLockPort.java @@ -1,11 +1,11 @@ -package dev.caskeleton.bootstrap.autoconfigure.lock; +package dev.caskeleton.adapter.outbound.persistence.lock; import static net.logstash.logback.argument.StructuredArguments.kv; +import dev.caskeleton.adapter.outbound.support.startup.RuntimeWarnings; import dev.caskeleton.application.lock.DistributedLock; import dev.caskeleton.application.lock.DistributedLockPort; import dev.caskeleton.application.lock.LockAcquisitionTimeoutException; -import dev.caskeleton.bootstrap.runtime.RuntimeWarnings; import io.micrometer.core.instrument.Counter; import io.micrometer.core.instrument.MeterRegistry; import java.time.Duration; @@ -18,7 +18,7 @@ import org.springframework.beans.factory.ObjectProvider; * Metrics decorator for {@link DistributedLockPort}. Metric failures are logged-and-swallowed so * they never affect the lock path. See README for the design rationale. */ -public final class MeteredDistributedLockPort implements DistributedLockPort { +final class MeteredDistributedLockPort implements DistributedLockPort { private static final Logger log = LoggerFactory.getLogger(MeteredDistributedLockPort.class); @@ -33,7 +33,7 @@ public final class MeteredDistributedLockPort implements DistributedLockPort { private final DistributedLockPort delegate; private final MeterRegistry registry; // null when no MeterRegistry on classpath - public MeteredDistributedLockPort( + MeteredDistributedLockPort( DistributedLockPort delegate, ObjectProvider meterRegistryProvider) { this.delegate = delegate; this.registry = meterRegistryProvider.getIfAvailable(); diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/migration/FailedConcurrentIndexRecovery.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/migration/FailedConcurrentIndexRecovery.java deleted file mode 100644 index 3ce5433b..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/migration/FailedConcurrentIndexRecovery.java +++ /dev/null @@ -1,81 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.migration; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; -import javax.sql.DataSource; - -/** - * Reports invalid indexes left behind by a failed concurrent build, and refuses to clean them up - * (design §32). - * - *

A failed {@code CREATE INDEX CONCURRENTLY} leaves an index marked {@code indisvalid = false}. - * It is not used by the planner but it is maintained by every write, so it costs write - * throughput while providing nothing. - * - *

Dropping it automatically at startup is exactly what this class does not do. An invalid index - * can also mean a build is still running, and the two are indistinguishable from the catalog alone - * — so an automatic drop would race a concurrent build that was about to finish, on every instance - * of a rolling deploy at once. The recovery is a report with the statement an operator can run. - */ -public final class FailedConcurrentIndexRecovery { - - private static final String INVALID_INDEX_QUERY = - """ - select i.relname as index_name, n.nspname as schema_name - from pg_index x - join pg_class i on i.oid = x.indexrelid - join pg_namespace n on n.oid = i.relnamespace - where x.indisvalid = false - and n.nspname = current_schema() - order by n.nspname, i.relname - """; - - private final DataSource dataSource; - - public FailedConcurrentIndexRecovery(DataSource dataSource) { - this.dataSource = Objects.requireNonNull(dataSource, "dataSource"); - } - - /** The invalid indexes in the current schema, as bounded {@code schema.index} names. */ - public List invalidIndexes() { - List invalid = new ArrayList<>(); - try (Connection connection = dataSource.getConnection(); - PreparedStatement statement = connection.prepareStatement(INVALID_INDEX_QUERY); - ResultSet rows = statement.executeQuery()) { - while (rows.next()) { - invalid.add(rows.getString("schema_name") + '.' + rows.getString("index_name")); - } - } catch (SQLException failure) { - throw new IllegalStateException("invalid index catalog could not be read", failure); - } - return List.copyOf(invalid); - } - - /** - * A bounded recovery report for an operator. - * - *

The report contains the statements to run, not the effect of running them. Every entry is a - * {@code DROP INDEX CONCURRENTLY}, which is itself non-transactional and must be run outside a - * migration. - */ - public String recoveryReport() { - List invalid = invalidIndexes(); - if (invalid.isEmpty()) { - return "no invalid indexes"; - } - StringBuilder report = new StringBuilder(128); - report - .append(invalid.size()) - .append(" invalid index(es) from a failed concurrent build. Confirm no build is running,") - .append(" then run each statement outside a migration:\n"); - for (String index : invalid) { - report.append(" drop index concurrently if exists ").append(index).append(";\n"); - } - return report.toString(); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/migration/NonTransactionalMigrationPolicy.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/migration/NonTransactionalMigrationPolicy.java deleted file mode 100644 index a6460bad..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/migration/NonTransactionalMigrationPolicy.java +++ /dev/null @@ -1,38 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.migration; - -import java.util.Objects; -import java.util.Set; - -/** - * Which migrations are declared non-transactional, and how that declaration is made (design §32). - * - *

Flyway takes the declaration from a companion {@code .conf} file next to the script. Modelling - * it here as a registry as well means the inspector can check a migration before Flyway ever runs - * it, in a unit test, rather than discovering the mismatch during a deployment. - */ -public record NonTransactionalMigrationPolicy(Set nonTransactionalMigrations) { - - /** The Flyway configuration key that marks a migration non-transactional. */ - public static final String EXECUTE_IN_TRANSACTION_KEY = "executeInTransaction"; - - public NonTransactionalMigrationPolicy { - nonTransactionalMigrations = - Set.copyOf( - Objects.requireNonNull(nonTransactionalMigrations, "nonTransactionalMigrations")); - } - - /** A policy with no non-transactional migrations declared. */ - public static NonTransactionalMigrationPolicy none() { - return new NonTransactionalMigrationPolicy(Set.of()); - } - - /** Whether Flyway will wrap this migration in a transaction. */ - public boolean executesInTransaction(String migrationName) { - return !nonTransactionalMigrations.contains(migrationName); - } - - /** The companion configuration line a non-transactional migration needs. */ - public String companionConfiguration() { - return EXECUTE_IN_TRANSACTION_KEY + "=false"; - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/migration/SchemaVersionSnapshot.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/migration/SchemaVersionSnapshot.java deleted file mode 100644 index 55c09646..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/migration/SchemaVersionSnapshot.java +++ /dev/null @@ -1,35 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.migration; - -import java.time.Instant; -import java.util.Objects; -import java.util.Optional; - -/** - * The schema version a database is on, as the migration history reports it (design §31). - * - *

{@code pending} is carried separately from {@code current} because "which version am I on" and - * "is anything unapplied" are different questions with different answers during a rolling deploy: - * an instance can be on the right version and still see pending migrations another instance is - * mid-way through applying. - */ -public record SchemaVersionSnapshot( - String current, int pendingMigrations, Instant observedAt, boolean valid) { - - public SchemaVersionSnapshot { - Objects.requireNonNull(observedAt, "observedAt"); - current = current == null ? "" : current; - if (pendingMigrations < 0) { - throw new IllegalArgumentException("pending migrations must not be negative"); - } - } - - /** The applied version, when any migration has been applied. */ - public Optional appliedVersion() { - return current.isEmpty() ? Optional.empty() : Optional.of(current); - } - - /** Whether the schema is fully migrated and validated. */ - public boolean upToDate() { - return valid && pendingMigrations == 0; - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/NotificationJpaPersistenceConfig.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/NotificationJpaPersistenceConfig.java index ffdccbb0..41d9f1b8 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/NotificationJpaPersistenceConfig.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/NotificationJpaPersistenceConfig.java @@ -15,8 +15,8 @@ import org.springframework.data.jpa.repository.config.EnableJpaRepositories; * not created — the switch was off and the capability still decided whether the application could * start. * - *

The condition is the same master switch the adapter beans use, so "disabled" means one thing - * everywhere: no entity metadata, no repository beans, no schema expectation. + *

The condition is the same capability switch the adapter beans use, so "disabled" means one + * thing everywhere: no entity metadata, no repository beans, no schema expectation. */ @Configuration(proxyBeanMethods = false) @ConditionalOnProperty( diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/configuration/NotificationJpaPersistenceFacade.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/configuration/NotificationJpaPersistenceFacade.java index 790ce9b6..b31d2f56 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/configuration/NotificationJpaPersistenceFacade.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/configuration/NotificationJpaPersistenceFacade.java @@ -72,7 +72,7 @@ import org.springframework.jdbc.core.JdbcOperations; * package, or reducing its visibility, broke the composition root's compile. The root now imports * this one facade, and what it assembles stays the leaf's own business. * - *

The master switch used to gate these beans and nothing else. The entities were scanned + *

The capability switch used to gate these beans and nothing else. The entities were scanned * unconditionally by {@code PersistenceJpaConfig}, and the schema stream — which lives outside the * default Flyway location — had no activation check at all. So a deployment with the feature off * still failed {@code ddl-auto=validate} on tables it had deliberately not created, and one with diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/crypto/DirectAeadNotificationPayloadCrypto.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/crypto/DirectAeadNotificationPayloadCrypto.java deleted file mode 100644 index 4583b15b..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/crypto/DirectAeadNotificationPayloadCrypto.java +++ /dev/null @@ -1,115 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.notification.crypto; - -import java.security.GeneralSecurityException; -import java.security.SecureRandom; -import java.util.Arrays; -import java.util.Objects; -import javax.crypto.Cipher; -import javax.crypto.spec.GCMParameterSpec; -import javax.crypto.spec.SecretKeySpec; - -/** Direct AES-256-GCM field encryption with a fresh 96-bit nonce and 128-bit tag. */ -public final class DirectAeadNotificationPayloadCrypto { - - private static final String ALGORITHM = "AES-256-GCM"; - private static final String TRANSFORMATION = "AES/GCM/NoPadding"; - private static final String PROFILE = "notification-direct-aead-v1"; - private static final String AAD_REVISION = "notification-aad-v1"; - private static final int TAG_BITS = 128; - - private final NotificationKeyMaterialProvider keys; - private final SecureRandom random; - - public DirectAeadNotificationPayloadCrypto( - NotificationKeyMaterialProvider keys, SecureRandom random) { - this.keys = Objects.requireNonNull(keys, "notification key provider must be non-null"); - this.random = Objects.requireNonNull(random, "notification secure random must be non-null"); - } - - public NotificationCiphertext encrypt( - byte[] plaintext, - NotificationCiphertext.AadContext context, - String keyReference, - String keyVersion) { - Objects.requireNonNull(plaintext, "notification plaintext must be non-null"); - Objects.requireNonNull(context, "notification AAD context must be non-null"); - if (plaintext.length < 1 || plaintext.length > 10_000_000) { - throw new IllegalArgumentException("notification plaintext must contain 1..10000000 bytes"); - } - requireProfile(context); - byte[] nonce = new byte[12]; - random.nextBytes(nonce); - try (NotificationKeyMaterialHandle handle = keys.acquire(keyReference, keyVersion)) { - byte[] encrypted = - handle.readBytes( - material -> transform(Cipher.ENCRYPT_MODE, material, nonce, context, plaintext)); - return new NotificationCiphertext( - ALGORITHM, - handle.keyReference(), - handle.keyVersion(), - PROFILE, - AAD_REVISION, - nonce, - encrypted); - } - } - - public byte[] decrypt( - NotificationCiphertext encrypted, NotificationCiphertext.AadContext context) { - Objects.requireNonNull(encrypted, "notification ciphertext must be non-null"); - Objects.requireNonNull(context, "notification AAD context must be non-null"); - requireProfile(context); - if (!ALGORITHM.equals(encrypted.algorithm()) - || !PROFILE.equals(encrypted.cryptoProfileVersion()) - || !AAD_REVISION.equals(encrypted.aadRevision())) { - throw new NotificationCryptoException( - "notification ciphertext cryptographic profile is unsupported"); - } - try (NotificationKeyMaterialHandle handle = - keys.acquire(encrypted.keyReference(), encrypted.keyVersion())) { - return handle.readBytes( - material -> - transform( - Cipher.DECRYPT_MODE, - material, - encrypted.nonce(), - context, - encrypted.ciphertext())); - } catch (NotificationCryptoException failure) { - throw failure; - } catch (RuntimeException failure) { - throw new NotificationCryptoException( - "notification ciphertext authentication failed", failure); - } - } - - private static byte[] transform( - int mode, - byte[] material, - byte[] nonce, - NotificationCiphertext.AadContext context, - byte[] input) { - if (material.length != 32) { - throw new NotificationCryptoException( - "notification AES-256 key revision has an invalid length"); - } - byte[] keyCopy = material.clone(); - try { - Cipher cipher = Cipher.getInstance(TRANSFORMATION); - cipher.init(mode, new SecretKeySpec(keyCopy, "AES"), new GCMParameterSpec(TAG_BITS, nonce)); - cipher.updateAAD(context.canonicalBytes()); - return cipher.doFinal(input); - } catch (GeneralSecurityException failure) { - throw new NotificationCryptoException( - "notification ciphertext authentication failed", failure); - } finally { - Arrays.fill(keyCopy, (byte) 0); - } - } - - private static void requireProfile(NotificationCiphertext.AadContext context) { - if (!PROFILE.equals(context.cryptoProfileVersion())) { - throw new NotificationCryptoException("notification AAD crypto profile is unsupported"); - } - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/crypto/NotificationCiphertext.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/crypto/NotificationCiphertext.java deleted file mode 100644 index 72d0b3da..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/crypto/NotificationCiphertext.java +++ /dev/null @@ -1,164 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.notification.crypto; - -import java.nio.ByteBuffer; -import java.nio.charset.StandardCharsets; -import java.util.Arrays; -import java.util.Objects; -import java.util.Optional; - -/** Non-secret AES-GCM metadata and ciphertext; mutable arrays are defensively copied. */ -@SuppressWarnings( - "ArrayRecordComponent") // constructor/accessor copies preserve the public record API -public record NotificationCiphertext( - String algorithm, - String keyReference, - String keyVersion, - String cryptoProfileVersion, - String aadRevision, - byte[] nonce, - byte[] ciphertext) { - - public NotificationCiphertext { - if (!"AES-256-GCM".equals(algorithm)) { - throw new IllegalArgumentException("notification ciphertext algorithm must be AES-256-GCM"); - } - keyReference = - NotificationKeyMaterialHandle.requireSlug( - "notification ciphertext key reference", keyReference); - keyVersion = - NotificationKeyMaterialHandle.requireSlug( - "notification ciphertext key version", keyVersion); - cryptoProfileVersion = - NotificationKeyMaterialHandle.requireSlug( - "notification crypto profile version", cryptoProfileVersion); - aadRevision = - NotificationKeyMaterialHandle.requireSlug("notification AAD revision", aadRevision); - Objects.requireNonNull(nonce, "notification ciphertext nonce must be non-null"); - Objects.requireNonNull(ciphertext, "notification ciphertext bytes must be non-null"); - if (nonce.length != 12 || ciphertext.length < 17 || ciphertext.length > 10_000_016) { - throw new IllegalArgumentException( - "notification ciphertext nonce/tag/payload bounds are invalid"); - } - nonce = nonce.clone(); - ciphertext = ciphertext.clone(); - } - - @Override - public byte[] nonce() { - return nonce.clone(); - } - - @Override - public byte[] ciphertext() { - return ciphertext.clone(); - } - - @Override - public boolean equals(Object other) { - if (this == other) { - return true; - } - if (!(other instanceof NotificationCiphertext that)) { - return false; - } - return algorithm.equals(that.algorithm) - && keyReference.equals(that.keyReference) - && keyVersion.equals(that.keyVersion) - && cryptoProfileVersion.equals(that.cryptoProfileVersion) - && aadRevision.equals(that.aadRevision) - && Arrays.equals(nonce, that.nonce) - && Arrays.equals(ciphertext, that.ciphertext); - } - - @Override - public int hashCode() { - int result = - Objects.hash(algorithm, keyReference, keyVersion, cryptoProfileVersion, aadRevision); - result = 31 * result + Arrays.hashCode(nonce); - return 31 * result + Arrays.hashCode(ciphertext); - } - - @Override - public String toString() { - return "NotificationCiphertext[algorithm=" - + algorithm - + ", keyReference=" - + keyReference - + ", keyVersion=" - + keyVersion - + ", cryptoProfileVersion=" - + cryptoProfileVersion - + ", aadRevision=" - + aadRevision - + ", nonce=, ciphertext=]"; - } - - /** Exact approved length-prefixed AAD hierarchy for one encrypted notification field. */ - public record AadContext( - String schemaTable, - String recordId, - String notificationId, - Optional deliveryId, - Optional attemptId, - String fieldPurpose, - String providerBindingRevision, - String cryptoProfileVersion) { - - public AadContext { - if (schemaTable == null || !schemaTable.matches("[a-z][a-z0-9_]{0,62}")) { - throw new IllegalArgumentException( - "notification AAD table must match [a-z][a-z0-9_]{0,62}"); - } - recordId = requireOpaque("notification AAD record ID", recordId); - notificationId = requireOpaque("notification AAD notification ID", notificationId); - deliveryId = requireOptional("notification AAD delivery ID", deliveryId); - attemptId = requireOptional("notification AAD attempt ID", attemptId); - fieldPurpose = - NotificationKeyMaterialHandle.requireSlug("notification AAD field purpose", fieldPurpose); - providerBindingRevision = - NotificationKeyMaterialHandle.requireSlug( - "notification AAD provider binding revision", providerBindingRevision); - cryptoProfileVersion = - NotificationKeyMaterialHandle.requireSlug( - "notification AAD crypto profile", cryptoProfileVersion); - } - - byte[] canonicalBytes() { - java.io.ByteArrayOutputStream output = new java.io.ByteArrayOutputStream(); - update(output, schemaTable); - update(output, recordId); - update(output, notificationId); - updateOptional(output, deliveryId); - updateOptional(output, attemptId); - update(output, fieldPurpose); - update(output, providerBindingRevision); - update(output, cryptoProfileVersion); - return output.toByteArray(); - } - - private static Optional requireOptional(String field, Optional value) { - Objects.requireNonNull(value, field + " container must be non-null"); - return value.map(item -> requireOpaque(field, item)); - } - - private static String requireOpaque(String field, String value) { - if (value == null || !value.matches("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}")) { - throw new IllegalArgumentException( - field + " must contain 1..128 opaque identifier characters"); - } - return value; - } - - private static void update(java.io.ByteArrayOutputStream output, String value) { - byte[] bytes = value.getBytes(StandardCharsets.UTF_8); - output.writeBytes(ByteBuffer.allocate(Integer.BYTES).putInt(bytes.length).array()); - output.writeBytes(bytes); - } - - private static void updateOptional( - java.io.ByteArrayOutputStream output, Optional value) { - output.write(value.isPresent() ? 1 : 0); - value.ifPresent(item -> update(output, item)); - } - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/crypto/NotificationCryptoException.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/crypto/NotificationCryptoException.java deleted file mode 100644 index 5e85dfe0..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/crypto/NotificationCryptoException.java +++ /dev/null @@ -1,15 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.notification.crypto; - -/** Redacted fail-closed notification cryptographic operation error. */ -public final class NotificationCryptoException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - public NotificationCryptoException(String safeMessage) { - super(safeMessage); - } - - public NotificationCryptoException(String safeMessage, Throwable cause) { - super(safeMessage, cause); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/crypto/NotificationHmacDigester.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/crypto/NotificationHmacDigester.java deleted file mode 100644 index 67b0c318..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/crypto/NotificationHmacDigester.java +++ /dev/null @@ -1,127 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.notification.crypto; - -import java.nio.ByteBuffer; -import java.nio.charset.StandardCharsets; -import java.security.GeneralSecurityException; -import java.security.MessageDigest; -import java.util.Arrays; -import java.util.HashSet; -import java.util.HexFormat; -import java.util.List; -import java.util.Objects; -import javax.crypto.Mac; -import javax.crypto.spec.SecretKeySpec; - -/** Purpose-separated length-prefixed HMAC-SHA-256 over non-secret canonical tuple fields. */ -public final class NotificationHmacDigester { - - private static final String ALGORITHM = "HmacSHA256"; - private static final int MAXIMUM_VERIFICATION_VERSIONS = 4; - - private final NotificationKeyMaterialProvider keys; - - public NotificationHmacDigester(NotificationKeyMaterialProvider keys) { - this.keys = Objects.requireNonNull(keys, "notification HMAC key provider must be non-null"); - } - - public Digest digest( - String purpose, List fields, String keyReference, String keyVersion) { - byte[] canonical = canonical(purpose, fields); - try (NotificationKeyMaterialHandle handle = keys.acquire(keyReference, keyVersion)) { - String value = - handle.readBytes(material -> HexFormat.of().formatHex(hmac(material, canonical))); - return new Digest(handle.keyReference(), handle.keyVersion(), value); - } finally { - Arrays.fill(canonical, (byte) 0); - } - } - - public boolean verify(Digest expected, String purpose, List fields) { - Objects.requireNonNull(expected, "expected notification HMAC must be non-null"); - List versions = - List.copyOf( - Objects.requireNonNull( - keys.verificationVersions(expected.keyReference()), - "notification HMAC verification versions must be non-null")); - if (versions.isEmpty() - || versions.size() > MAXIMUM_VERIFICATION_VERSIONS - || new HashSet<>(versions).size() != versions.size()) { - throw new NotificationCryptoException( - "notification HMAC verification key set must be unique and bounded"); - } - if (!versions.contains(expected.keyVersion())) { - return false; - } - Digest actual = digest(purpose, fields, expected.keyReference(), expected.keyVersion()); - return MessageDigest.isEqual( - HexFormat.of().parseHex(expected.value()), HexFormat.of().parseHex(actual.value())); - } - - private static byte[] canonical(String purpose, List fields) { - if (purpose == null || !purpose.matches("[a-z][a-z0-9-]{0,62}")) { - throw new IllegalArgumentException( - "notification HMAC purpose must match [a-z][a-z0-9-]{0,62}"); - } - Objects.requireNonNull(fields, "notification HMAC fields must be non-null"); - if (fields.isEmpty() || fields.size() > 32) { - throw new IllegalArgumentException("notification HMAC fields must contain 1..32 entries"); - } - java.io.ByteArrayOutputStream output = new java.io.ByteArrayOutputStream(); - update(output, purpose); - output.writeBytes(ByteBuffer.allocate(Integer.BYTES).putInt(fields.size()).array()); - fields.forEach( - field -> { - if (field == null || field.length() > 4_096) { - throw new IllegalArgumentException( - "notification HMAC field must contain at most 4096 characters"); - } - update(output, field); - }); - return output.toByteArray(); - } - - private static byte[] hmac(byte[] material, byte[] canonical) { - if (material.length < 32) { - throw new NotificationCryptoException("notification HMAC key revision has an invalid length"); - } - byte[] keyCopy = material.clone(); - try { - Mac mac = Mac.getInstance(ALGORITHM); - mac.init(new SecretKeySpec(keyCopy, ALGORITHM)); - return mac.doFinal(canonical); - } catch (GeneralSecurityException failure) { - throw new NotificationCryptoException("notification HMAC operation failed", failure); - } finally { - Arrays.fill(keyCopy, (byte) 0); - } - } - - private static void update(java.io.ByteArrayOutputStream output, String value) { - byte[] bytes = value.getBytes(StandardCharsets.UTF_8); - output.writeBytes(ByteBuffer.allocate(Integer.BYTES).putInt(bytes.length).array()); - output.writeBytes(bytes); - } - - public record Digest(String keyReference, String keyVersion, String value) { - - public Digest { - keyReference = - NotificationKeyMaterialHandle.requireSlug( - "notification HMAC key reference", keyReference); - keyVersion = - NotificationKeyMaterialHandle.requireSlug("notification HMAC key version", keyVersion); - if (value == null || !value.matches("[0-9a-f]{64}")) { - throw new IllegalArgumentException("notification HMAC value must be lowercase SHA-256 hex"); - } - } - - @Override - public String toString() { - return "Digest[keyReference=" - + keyReference - + ", keyVersion=" - + keyVersion - + ", value=]"; - } - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/crypto/NotificationKeyMaterialHandle.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/crypto/NotificationKeyMaterialHandle.java deleted file mode 100644 index 842aae40..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/crypto/NotificationKeyMaterialHandle.java +++ /dev/null @@ -1,71 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.notification.crypto; - -import java.util.Arrays; -import java.util.Objects; -import java.util.function.Function; - -/** Operation-scoped mutable key copy that wipes on close and rejects use after close. */ -public final class NotificationKeyMaterialHandle implements AutoCloseable { - - private final String keyReference; - private final String keyVersion; - private final byte[] material; - private boolean closed; - - private NotificationKeyMaterialHandle(String keyReference, String keyVersion, byte[] material) { - this.keyReference = requireSlug("notification key reference", keyReference); - this.keyVersion = requireSlug("notification key version", keyVersion); - this.material = material; - } - - public static NotificationKeyMaterialHandle fromBytes( - String keyReference, String keyVersion, byte[] material) { - Objects.requireNonNull(material, "notification key material must be non-null"); - if (material.length < 32 || material.length > 65_536) { - throw new IllegalArgumentException("notification key material must contain 32..65536 bytes"); - } - return new NotificationKeyMaterialHandle(keyReference, keyVersion, material.clone()); - } - - public String keyReference() { - return keyReference; - } - - public String keyVersion() { - return keyVersion; - } - - public synchronized T readBytes(Function reader) { - Objects.requireNonNull(reader, "notification key reader must be non-null"); - if (closed) { - throw new IllegalStateException("notification key material handle is closed"); - } - return reader.apply(material); - } - - @Override - public synchronized void close() { - if (!closed) { - Arrays.fill(material, (byte) 0); - closed = true; - } - } - - @Override - public synchronized String toString() { - return "NotificationKeyMaterialHandle[keyReference=" - + keyReference - + ", keyVersion=" - + keyVersion - + ", material=, closed=" - + closed - + "]"; - } - - static String requireSlug(String field, String value) { - if (value == null || !value.matches("[a-z][a-z0-9.-]{0,62}")) { - throw new IllegalArgumentException(field + " must match [a-z][a-z0-9.-]{0,62}"); - } - return value; - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/crypto/NotificationKeyMaterialProvider.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/crypto/NotificationKeyMaterialProvider.java deleted file mode 100644 index ff668d54..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/crypto/NotificationKeyMaterialProvider.java +++ /dev/null @@ -1,13 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.notification.crypto; - -import java.util.List; - -/** - * Acquires versioned mutable key copies and declares bounded current-plus-retiring verification. - */ -public interface NotificationKeyMaterialProvider { - - NotificationKeyMaterialHandle acquire(String keyReference, String keyVersion); - - List verificationVersions(String keyReference); -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/AdminOperationResultPayloadCodec.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/AdminOperationResultPayloadCodec.java index 68442cec..bb483633 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/AdminOperationResultPayloadCodec.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/AdminOperationResultPayloadCodec.java @@ -15,6 +15,8 @@ import java.util.Base64; import java.util.List; import java.util.Optional; import java.util.UUID; +import java.util.regex.Matcher; +import java.util.regex.Pattern; /** * Versioned persistence codec for an admin operation's exact replay result. @@ -30,6 +32,15 @@ final class AdminOperationResultPayloadCodec { private static final String PREFIX = "{\"v\":1,\"payload\":\""; private static final String SUFFIX = "\"}"; + /** + * The column is {@code jsonb}, which stores a parsed document and renders it back with its own + * whitespace ({@code {"v": 1, "payload": "..."}}), so the envelope is matched as JSON rather than + * as the exact string {@link #encode} wrote. + */ + private static final Pattern STORED = + Pattern.compile( + "\\{\\s*\"v\"\\s*:\\s*1\\s*,\\s*\"payload\"\\s*:\\s*\"([A-Za-z0-9_-]*)\"\\s*\\}"); + String encode(AdminOperationResult result) { try { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); @@ -54,10 +65,11 @@ final class AdminOperationResultPayloadCodec { } AdminOperationResult decode(String json) { - if (json == null || !json.startsWith(PREFIX) || !json.endsWith(SUFFIX)) { + Matcher stored = json == null ? null : STORED.matcher(json.strip()); + if (stored == null || !stored.matches()) { throw new IllegalStateException("stored admin result payload has an unsupported shape"); } - String encoded = json.substring(PREFIX.length(), json.length() - SUFFIX.length()); + String encoded = stored.group(1); final byte[] bytes; try { bytes = Base64.getUrlDecoder().decode(encoded); diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/observation/JpaRetryObservation.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/observation/JpaRetryObservation.java deleted file mode 100644 index daaa1ead..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/observation/JpaRetryObservation.java +++ /dev/null @@ -1,85 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.observation; - -import dev.caskeleton.adapter.outbound.persistence.api.PersistenceOperationName; -import dev.caskeleton.adapter.outbound.persistence.api.error.JpaPersistenceException; -import dev.caskeleton.adapter.outbound.persistence.api.transaction.RetryDecision; -import dev.caskeleton.adapter.outbound.persistence.api.transaction.RetryEventListener; -import dev.caskeleton.adapter.outbound.persistence.api.transaction.TransactionAttempt; -import io.micrometer.core.instrument.Counter; -import io.micrometer.core.instrument.DistributionSummary; -import io.micrometer.core.instrument.MeterRegistry; -import java.util.Objects; - -/** - * Turns retry attempts into metrics instead of log noise (design §19, §37). - * - *

A retried attempt is not a warning. Optimistic conflicts and serialization failures are the - * expected cost of concurrency, and logging each one at WARN pages someone for a system that is - * working exactly as designed — after which the retry log gets filtered out, taking the genuinely - * interesting entries with it. - * - *

What is worth alerting on is the shape of the distribution: attempts per operation rising, or - * exhaustion appearing at all. Both are here as metrics. - */ -public final class JpaRetryObservation implements RetryEventListener { - - /** Counter for individual failed attempts. */ - public static final String ATTEMPT_METER = "jpa.retry.attempt"; - - /** Summary of how many attempts each completed operation needed. */ - public static final String ATTEMPTS_PER_OPERATION_METER = "jpa.retry.attempts"; - - /** Counter for operations that exhausted their budget or hit a non-retryable failure. */ - public static final String EXHAUSTED_METER = "jpa.retry.exhausted"; - - private final MeterRegistry registry; - private final String persistenceUnit; - - public JpaRetryObservation(MeterRegistry registry, String persistenceUnit) { - this.registry = Objects.requireNonNull(registry, "registry"); - this.persistenceUnit = Objects.requireNonNull(persistenceUnit, "persistenceUnit"); - LowCardinality.requireRegistered(persistenceUnit); - } - - @Override - public void onAttemptFailed( - PersistenceOperationName operation, - TransactionAttempt attempt, - JpaPersistenceException failure, - RetryDecision decision) { - Counter.builder(ATTEMPT_METER) - .tags( - JpaMetricTags.failure( - persistenceUnit, - operation.value(), - JpaMetricTags.NONE, - failure.category().name()) - .toTags()) - .tag("retry.disposition", decision.disposition().name()) - .register(registry) - .increment(); - } - - @Override - public void onSucceeded(PersistenceOperationName operation, int attempts) { - DistributionSummary.builder(ATTEMPTS_PER_OPERATION_METER) - .tags( - JpaMetricTags.success(persistenceUnit, operation.value(), JpaMetricTags.NONE).toTags()) - .register(registry) - .record(attempts); - } - - @Override - public void onGaveUp( - PersistenceOperationName operation, int attempts, JpaPersistenceException failure) { - var tags = - JpaMetricTags.failure( - persistenceUnit, operation.value(), JpaMetricTags.NONE, failure.category().name()) - .toTags(); - DistributionSummary.builder(ATTEMPTS_PER_OPERATION_METER) - .tags(tags) - .register(registry) - .record(attempts); - Counter.builder(EXHAUSTED_METER).tags(tags).register(registry).increment(); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/observation/JpaTransactionObservation.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/observation/JpaTransactionObservation.java deleted file mode 100644 index 615c7194..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/observation/JpaTransactionObservation.java +++ /dev/null @@ -1,89 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.observation; - -import dev.caskeleton.adapter.outbound.persistence.api.PersistenceOperationName; -import dev.caskeleton.adapter.outbound.persistence.api.error.JpaPersistenceException; -import io.micrometer.core.instrument.Counter; -import io.micrometer.core.instrument.MeterRegistry; -import io.micrometer.core.instrument.Timer; -import java.time.Duration; -import java.util.Objects; - -/** - * Records the transaction-level measurements the design names (design §37). - * - *

Completion-unknown gets its own counter rather than being folded into the failure count. It is - * the one outcome that means a human has to look: every other failure is a transaction that - * definitely did not happen, while this one is a transaction that may have. Burying it in a general - * failure rate is how it stops being noticed. - */ -public final class JpaTransactionObservation { - - /** Timer for transaction duration. */ - public static final String DURATION_METER = "jpa.transaction.duration"; - - /** Counter for transactions that rolled back. */ - public static final String ROLLBACK_METER = "jpa.transaction.rollback"; - - /** Counter for transactions that exceeded their timeout. */ - public static final String TIMEOUT_METER = "jpa.transaction.timeout"; - - /** Counter for transactions whose commit outcome could not be determined. */ - public static final String COMPLETION_UNKNOWN_METER = "jpa.transaction.completion.unknown"; - - private final MeterRegistry registry; - private final String persistenceUnit; - - public JpaTransactionObservation(MeterRegistry registry, String persistenceUnit) { - this.registry = Objects.requireNonNull(registry, "registry"); - this.persistenceUnit = Objects.requireNonNull(persistenceUnit, "persistenceUnit"); - LowCardinality.requireRegistered(persistenceUnit); - } - - /** Records a transaction that committed. */ - public void recordCommitted(PersistenceOperationName operation, Duration elapsed) { - Objects.requireNonNull(operation, "operation"); - Objects.requireNonNull(elapsed, "elapsed"); - Timer.builder(DURATION_METER) - .tags( - JpaMetricTags.success(persistenceUnit, operation.value(), JpaMetricTags.NONE).toTags()) - .register(registry) - .record(elapsed); - } - - /** Records a transaction that rolled back, categorised by the platform's failure category. */ - public void recordRolledBack( - PersistenceOperationName operation, Duration elapsed, JpaPersistenceException failure) { - Objects.requireNonNull(operation, "operation"); - Objects.requireNonNull(failure, "failure"); - var tags = - JpaMetricTags.failure( - persistenceUnit, operation.value(), JpaMetricTags.NONE, failure.category().name()) - .toTags(); - Timer.builder(DURATION_METER).tags(tags).register(registry).record(elapsed); - Counter.builder(ROLLBACK_METER).tags(tags).register(registry).increment(); - } - - /** Records a transaction that exceeded its timeout. */ - public void recordTimedOut(PersistenceOperationName operation) { - Objects.requireNonNull(operation, "operation"); - Counter.builder(TIMEOUT_METER) - .tags( - JpaMetricTags.failure( - persistenceUnit, operation.value(), JpaMetricTags.NONE, "TRANSACTION_TIMEOUT") - .toTags()) - .register(registry) - .increment(); - } - - /** Records a transaction whose commit outcome is unknown and now needs reconciliation. */ - public void recordCompletionUnknown(PersistenceOperationName operation) { - Objects.requireNonNull(operation, "operation"); - Counter.builder(COMPLETION_UNKNOWN_METER) - .tags( - JpaMetricTags.failure( - persistenceUnit, operation.value(), JpaMetricTags.NONE, "COMPLETION_UNKNOWN") - .toTags()) - .register(registry) - .increment(); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationJpaRepository.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationJpaRepository.java index 573cbd52..6028e891 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationJpaRepository.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationJpaRepository.java @@ -29,7 +29,36 @@ public interface DurableOperationJpaRepository Optional findByOperationIdAndPrincipal( String operationId, String principal); - /** Reads the row an identical submission already created. */ + /** + * Records a submission unless one with the same scope already exists. + * + *

{@code ON CONFLICT DO NOTHING} rather than an insert that may raise. A unique violation + * leaves the PostgreSQL transaction aborted, and the caller still has to read the operation that + * holds the scope in that same transaction. + */ + @Modifying(clearAutomatically = true, flushAutomatically = true) + @Query( + value = + """ + INSERT INTO durable_operation + (operation_id, tenant, principal, operation_name, request_hash, payload, state, + submitted_at, expires_at) + VALUES (:operationId, :tenant, :principal, :operationName, :requestHash, :payload, + 'PENDING', :submittedAt, :expiresAt) + ON CONFLICT (tenant, principal, operation_name, request_hash) DO NOTHING + """, + nativeQuery = true) + void submitIfAbsent( + @Param("operationId") String operationId, + @Param("tenant") String tenant, + @Param("principal") String principal, + @Param("operationName") String operationName, + @Param("requestHash") String requestHash, + @Param("payload") String payload, + @Param("submittedAt") Instant submittedAt, + @Param("expiresAt") Instant expiresAt); + + /** Reads the row that holds a submission scope. */ Optional findByTenantAndPrincipalAndOperationNameAndRequestHash( String tenant, String principal, String operationName, String requestHash); diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationStoreAdapter.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationStoreAdapter.java index 30deb1c7..aca86c3a 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationStoreAdapter.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationStoreAdapter.java @@ -14,7 +14,6 @@ import java.time.Duration; import java.time.Instant; import java.util.List; import java.util.Optional; -import org.springframework.dao.DataIntegrityViolationException; import org.springframework.stereotype.Repository; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -44,38 +43,30 @@ public class DurableOperationStoreAdapter implements DurableOperationStorePort { public DurableOperation submit(DurableOperationSubmission submission) { requireCallerTransaction("submit"); String tenant = submission.tenantId() == null ? "" : submission.tenantId(); - try { - DurableOperationEntity saved = - repository.saveAndFlush( - new DurableOperationEntity( - submission.operationId().value(), - tenant, - submission.principal(), - submission.operationName(), - submission.fingerprint().hex(), - submission.payload(), - submission.submittedAt(), - submission.expiresAt())); - return toDomain(saved); - } catch (DataIntegrityViolationException duplicate) { - // The unique constraint is the arbiter, not a prior read: two identical submissions can - // reach this line at the same instant, and only one of them can win. The loser reads the - // winner's row rather than reporting a conflict, which is the whole point of resubmission - // being safe. - return repository - .findByTenantAndPrincipalAndOperationNameAndRequestHash( - tenant, - submission.principal(), - submission.operationName(), - submission.fingerprint().hex()) - .map(DurableOperationStoreAdapter::toDomain) - .orElseThrow( - () -> - new IllegalStateException( - "the unique constraint rejected a submission but no matching operation" - + " exists; the constraint and this lookup disagree on scope", - duplicate)); - } + // Insert-or-nothing on the scope, then read whichever row holds it. Catching the unique + // violation instead does not work on PostgreSQL: the violation aborts the caller's transaction + // (25P02), and the read of the winning row is refused along with everything after it. + repository.submitIfAbsent( + submission.operationId().value(), + tenant, + submission.principal(), + submission.operationName(), + submission.fingerprint().hex(), + submission.payload(), + submission.submittedAt(), + submission.expiresAt()); + return repository + .findByTenantAndPrincipalAndOperationNameAndRequestHash( + tenant, + submission.principal(), + submission.operationName(), + submission.fingerprint().hex()) + .map(DurableOperationStoreAdapter::toDomain) + .orElseThrow( + () -> + new IllegalStateException( + "no operation holds the scope right after inserting it; the insert's" + + " conflict target and this lookup disagree on scope")); } @Override diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/operation/entity/DurableOperationEntity.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/operation/entity/DurableOperationEntity.java index 7d04cfbc..ada5974d 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/operation/entity/DurableOperationEntity.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/operation/entity/DurableOperationEntity.java @@ -100,38 +100,6 @@ public class DurableOperationEntity { protected DurableOperationEntity() {} - /** - * A newly submitted operation. - * - * @param operationId the identity - * @param tenant the tenant, empty string when not tenant scoped - * @param principal who submitted it - * @param operationName what work this is - * @param requestHash the semantic fingerprint - * @param payload the serialized request - * @param submittedAt when it was accepted - * @param expiresAt when the record stops being available - */ - public DurableOperationEntity( - String operationId, - String tenant, - String principal, - String operationName, - String requestHash, - String payload, - Instant submittedAt, - Instant expiresAt) { - this.operationId = operationId; - this.tenant = tenant; - this.principal = principal; - this.operationName = operationName; - this.requestHash = requestHash; - this.payload = payload; - this.state = "PENDING"; - this.submittedAt = submittedAt; - this.expiresAt = expiresAt; - } - /** The identity. */ public String getOperationId() { return operationId; diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/CanonicalOutboxAppendAdapter.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/CanonicalOutboxAppendAdapter.java index 4f4e249c..b7cfe173 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/CanonicalOutboxAppendAdapter.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/CanonicalOutboxAppendAdapter.java @@ -41,7 +41,7 @@ final class CanonicalOutboxAppendAdapter implements OutboxAppendPort { OutboxEventEntity entity = new OutboxEventEntity(); - // Legacy compatibility projection retained while LEGACY_POLLING owns the row lifecycle. + // Legacy compatibility projection retained while the v1 relay owns the row lifecycle. entity.setEventId(event.eventId().value()); entity.setAggregateId(event.aggregate().aggregateId()); entity.setEventType(event.contractId().value()); diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/OutboxEventJpaRepository.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/OutboxEventJpaRepository.java index a2fd792a..4297828f 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/OutboxEventJpaRepository.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/OutboxEventJpaRepository.java @@ -22,6 +22,35 @@ public interface OutboxEventJpaRepository extends JpaRepository countGroupedByStatus(); diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/OutboxStoreAdapter.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/OutboxStoreAdapter.java index 097bf024..337b0c1c 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/OutboxStoreAdapter.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/OutboxStoreAdapter.java @@ -12,8 +12,10 @@ import dev.caskeleton.application.outbox.CanonicalClaimedOutboxEvent; import dev.caskeleton.application.outbox.ClaimedOutboxEvent; import dev.caskeleton.application.outbox.LegacyOutboxAppendPort; import dev.caskeleton.application.outbox.NewOutboxEvent; +import dev.caskeleton.application.outbox.OutboxCompletion; import dev.caskeleton.application.outbox.OutboxEvent; import dev.caskeleton.application.outbox.OutboxEventStatus; +import dev.caskeleton.application.outbox.OutboxLease; import dev.caskeleton.application.outbox.OutboxStorePort; import java.nio.ByteBuffer; import java.nio.charset.CharacterCodingException; @@ -69,8 +71,13 @@ public class OutboxStoreAdapter implements LegacyOutboxAppendPort, OutboxStorePo repository.save(entity); } + /** + * The claim repository returns the rows locked ({@code FOR UPDATE SKIP LOCKED}) until this + * transaction commits, so incrementing the token here cannot race another relay's claim. + */ @Override - public List claimBatch(int batchSize, Instant now, Duration inFlightTimeout) { + public List claimBatch( + String owner, int batchSize, Instant now, Duration inFlightTimeout) { requireTransaction("claimBatch"); List eligible = claimRepository.claimEligible(now, batchSize); return eligible.stream() @@ -79,52 +86,45 @@ public class OutboxStoreAdapter implements LegacyOutboxAppendPort, OutboxStorePo entity.setStatus(OutboxEventStatus.IN_FLIGHT.name()); entity.setAttemptCount(entity.getAttemptCount() + 1); entity.setNextAttemptAt(now.plus(inFlightTimeout)); - return toClaimedOutboxEvent(entity); + entity.setLeaseOwner(owner); + entity.setLeaseToken(entity.getLeaseToken() + 1); + return new OutboxLease(toClaimedOutboxEvent(entity), owner, entity.getLeaseToken()); }) .toList(); } /** - * Marks the event as published. Throws {@link IllegalStateException} if the row is missing — a - * missing just-claimed row is a bug, and a silent no-op would wedge the aggregate's FIFO queue - * (see README "outbox"). + * One conditional UPDATE, no load-and-set: it applies only while the lease still holds the row + * (see README "outbox"). Zero rows is {@link OutboxCompletion#STALE}, not an error — the relay + * that superseded this lease owns the row now. */ @Override - public void markPublished(String eventId) { + public OutboxCompletion markPublished(OutboxLease lease) { requireTransaction("markPublished"); - repository - .findById(eventId) - .orElseThrow(() -> new IllegalStateException("outbox row not found for eventId=" + eventId)) - .setStatus(OutboxEventStatus.PUBLISHED.name()); + return completion( + repository.completeLease( + lease.eventId(), lease.owner(), lease.token(), OutboxEventStatus.PUBLISHED.name())); } - /** - * Marks the event as failed and schedules the next retry. Throws if the row is missing (see - * {@link #markPublished}). - */ + /** Marks the leased row FAILED with its next attempt time; see {@link #markPublished}. */ @Override - public void markFailed(String eventId, Instant nextAttemptAt) { + public OutboxCompletion markFailed(OutboxLease lease, Instant nextAttemptAt) { requireTransaction("markFailed"); - OutboxEventEntity entity = - repository - .findById(eventId) - .orElseThrow( - () -> new IllegalStateException("outbox row not found for eventId=" + eventId)); - entity.setStatus(OutboxEventStatus.FAILED.name()); - entity.setNextAttemptAt(nextAttemptAt); + return completion( + repository.failLease(lease.eventId(), lease.owner(), lease.token(), nextAttemptAt)); } - /** - * Marks the event as dead-lettered after retries are exhausted. Throws if the row is missing (see - * {@link #markPublished}). - */ + /** Marks the leased row DEAD; see {@link #markPublished}. */ @Override - public void markDead(String eventId) { + public OutboxCompletion markDead(OutboxLease lease) { requireTransaction("markDead"); - repository - .findById(eventId) - .orElseThrow(() -> new IllegalStateException("outbox row not found for eventId=" + eventId)) - .setStatus(OutboxEventStatus.DEAD.name()); + return completion( + repository.completeLease( + lease.eventId(), lease.owner(), lease.token(), OutboxEventStatus.DEAD.name())); + } + + private static OutboxCompletion completion(int updatedRows) { + return updatedRows == 1 ? OutboxCompletion.APPLIED : OutboxCompletion.STALE; } private static void requireTransaction(String operation) { diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/entity/OutboxEventEntity.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/entity/OutboxEventEntity.java index 3dad6f76..aa35cc98 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/entity/OutboxEventEntity.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/entity/OutboxEventEntity.java @@ -10,9 +10,10 @@ import org.hibernate.type.SqlTypes; /** * JPA row for the {@code outbox_event} table; schema owned by Flyway ({@code V3__outbox_event.sql} - * + additive canonical metadata in {@code V13__outbox_canonical_transport_compatibility.sql}). Does - * not extend {@code AuditableEntity} (infra record, not a domain aggregate) and exposes mutating - * setters on purpose (relay transitions state in-place). + * + additive canonical metadata in {@code V13__outbox_canonical_transport_compatibility.sql} + the + * relay lease in {@code V17__outbox_event_lease_fencing.sql}). Does not extend {@code + * AuditableEntity} (infra record, not a domain aggregate) and exposes mutating setters on purpose + * (relay transitions state in-place). */ @Entity @Table(name = "outbox_event") @@ -46,6 +47,14 @@ public class OutboxEventEntity { @Column(name = "next_attempt_at", nullable = false) private Instant nextAttemptAt; + /** Relay holding the current IN_FLIGHT claim; cleared by the completion (V17). */ + @Column(name = "lease_owner", length = 160) + private String leaseOwner; + + /** Fencing token: every claim increments it and nothing resets it (V17). */ + @Column(name = "lease_token", nullable = false) + private long leaseToken; + @Column(name = "correlation_id", nullable = false, length = 128, updatable = false) private String correlationId; @@ -174,6 +183,22 @@ public class OutboxEventEntity { this.nextAttemptAt = nextAttemptAt; } + public String getLeaseOwner() { + return leaseOwner; + } + + public void setLeaseOwner(String leaseOwner) { + this.leaseOwner = leaseOwner; + } + + public long getLeaseToken() { + return leaseToken; + } + + public void setLeaseToken(long leaseToken) { + this.leaseToken = leaseToken; + } + public String getCorrelationId() { return correlationId; } diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/PostgreSqlIdempotencyClaimRepository.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/PostgreSqlIdempotencyClaimRepository.java deleted file mode 100644 index e210c55f..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/PostgreSqlIdempotencyClaimRepository.java +++ /dev/null @@ -1,70 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.postgresql; - -import dev.caskeleton.adapter.outbound.persistence.idempotency.IdempotencyClaimRepository; -import dev.caskeleton.adapter.outbound.persistence.idempotency.entity.IdempotencyRecordEntity; -import jakarta.persistence.EntityManager; -import java.time.Instant; -import java.util.Optional; -import java.util.UUID; -import org.jspecify.annotations.Nullable; - -/** PostgreSQL atomic scope claim using the named V1 unique constraint. */ -public final class PostgreSqlIdempotencyClaimRepository implements IdempotencyClaimRepository { - - private static final String CLAIM_SQL = - """ - INSERT INTO idempotency_record ( - id, tenant, principal, idempotency_key, use_case_name, - request_hash, status, response_payload, response_ref, created_at, expires_at - ) VALUES ( - :id, :tenant, :principal, :idempotencyKey, :useCaseName, - :requestHash, 'IN_FLIGHT', NULL, NULL, :createdAt, :expiresAt - ) - ON CONFLICT ON CONSTRAINT uq_idempotency_scope - DO UPDATE SET - id = EXCLUDED.id, - request_hash = EXCLUDED.request_hash, - status = 'IN_FLIGHT', - response_payload = NULL, - response_ref = NULL, - created_at = EXCLUDED.created_at, - expires_at = EXCLUDED.expires_at - WHERE idempotency_record.expires_at <= :now - RETURNING id - """; - - private final EntityManager entityManager; - - public PostgreSqlIdempotencyClaimRepository(EntityManager entityManager) { - this.entityManager = entityManager; - } - - @Override - public Optional tryClaim( - IdempotencyRecordEntity proposed, - Instant now, - @Nullable IdempotencyRecordEntity exactExpiredEntity) { - if (exactExpiredEntity != null && entityManager.contains(exactExpiredEntity)) { - entityManager.detach(exactExpiredEntity); - } - @SuppressWarnings("unchecked") - java.util.List rows = - entityManager - .createNativeQuery(CLAIM_SQL) - .setParameter("id", proposed.getId()) - .setParameter("tenant", proposed.getTenant()) - .setParameter("principal", proposed.getPrincipal()) - .setParameter("idempotencyKey", proposed.getIdempotencyKey()) - .setParameter("useCaseName", proposed.getUseCaseName()) - .setParameter("requestHash", proposed.getRequestHash()) - .setParameter("createdAt", proposed.getCreatedAt()) - .setParameter("expiresAt", proposed.getExpiresAt()) - .setParameter("now", now) - .getResultList(); - if (rows.isEmpty()) { - return Optional.empty(); - } - Object id = rows.getFirst(); - return Optional.of(id instanceof UUID uuid ? uuid : UUID.fromString(id.toString())); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/PostgreSqlLocalTimeoutConfigurer.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/PostgreSqlLocalTimeoutConfigurer.java deleted file mode 100644 index 31a15cea..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/PostgreSqlLocalTimeoutConfigurer.java +++ /dev/null @@ -1,36 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.postgresql; - -import dev.caskeleton.adapter.outbound.persistence.transaction.EffectiveTransactionTimeouts; -import dev.caskeleton.adapter.outbound.persistence.transaction.TransactionLocalTimeoutConfigurer; -import java.time.Duration; -import java.util.Objects; -import org.springframework.jdbc.core.JdbcOperations; - -/** Applies finite PostgreSQL timeout guards to the current transaction only. */ -public final class PostgreSqlLocalTimeoutConfigurer implements TransactionLocalTimeoutConfigurer { - - private static final String STATEMENT_TIMEOUT_SQL = - "select set_config('statement_timeout', ?, true)"; - private static final String LOCK_TIMEOUT_SQL = "select set_config('lock_timeout', ?, true)"; - private static final String IDLE_TIMEOUT_SQL = - "select set_config('idle_in_transaction_session_timeout', ?, true)"; - - private final JdbcOperations jdbcOperations; - - public PostgreSqlLocalTimeoutConfigurer(JdbcOperations jdbcOperations) { - this.jdbcOperations = Objects.requireNonNull(jdbcOperations, "jdbcOperations must be non-null"); - } - - @Override - public void apply(EffectiveTransactionTimeouts timeouts) { - Objects.requireNonNull(timeouts, "timeouts must be non-null"); - apply(STATEMENT_TIMEOUT_SQL, timeouts.statementTimeout()); - apply(LOCK_TIMEOUT_SQL, timeouts.lockTimeout()); - apply(IDLE_TIMEOUT_SQL, timeouts.idleGuardTimeout()); - } - - private void apply(String sql, Duration timeout) { - String value = timeout.toMillis() + "ms"; - jdbcOperations.queryForObject(sql, String.class, value); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/PostgreSqlPersistenceConfig.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/PostgreSqlPersistenceConfig.java index a8d4f2ff..b389c76d 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/PostgreSqlPersistenceConfig.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/PostgreSqlPersistenceConfig.java @@ -1,23 +1,15 @@ package dev.caskeleton.adapter.outbound.persistence.postgresql; -import dev.caskeleton.adapter.outbound.persistence.api.error.VendorFailureTranslator; import dev.caskeleton.adapter.outbound.persistence.config.PersistenceJpaConfig; import dev.caskeleton.adapter.outbound.persistence.config.PersistenceVendorSettings; import dev.caskeleton.adapter.outbound.persistence.failure.SqlStateErrorMapping; -import dev.caskeleton.adapter.outbound.persistence.idempotency.IdempotencyClaimRepository; import dev.caskeleton.adapter.outbound.persistence.outbox.OutboxClaimRepository; -import dev.caskeleton.adapter.outbound.persistence.postgresql.constraint.PostgreSqlConstraintCatalog; -import dev.caskeleton.adapter.outbound.persistence.postgresql.error.ConstraintCatalog; -import dev.caskeleton.adapter.outbound.persistence.postgresql.error.PostgreSqlExceptionTranslator; -import dev.caskeleton.adapter.outbound.persistence.transaction.TransactionLocalTimeoutConfigurer; import jakarta.persistence.EntityManager; -import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.flyway.autoconfigure.FlywayConfigurationCustomizer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; -import org.springframework.jdbc.core.JdbcOperations; /** * PostgreSQL vendor persistence configuration: registers the vendor {@code @Bean}s. See the module @@ -52,42 +44,6 @@ public class PostgreSqlPersistenceConfig { return new PostgreSqlSqlStateErrorMapping(); } - @Bean - public TransactionLocalTimeoutConfigurer transactionLocalTimeoutConfigurer( - JdbcOperations jdbcOperations) { - return new PostgreSqlLocalTimeoutConfigurer(jdbcOperations); - } - - @Bean - public IdempotencyClaimRepository idempotencyClaimRepository(EntityManager entityManager) { - return new PostgreSqlIdempotencyClaimRepository(entityManager); - } - - /** - * The SQLSTATE translator the transaction executor classifies attempt failures with. - * - *

Nothing registered one, so every composition got {@code - * PersistenceFailureTranslatorChain.withoutCatalogs()} — a chain whose vendor stage returns the - * failure unchanged. A serialization failure (40001) or a deadlock (40P01) therefore left an - * attempt as a raw Spring {@code DataAccessException}, missed the retry coordinator's {@code - * JpaPersistenceException} catch, and was never retried. The unit fixtures were green because - * they threw an already-classified exception. - * - *

The catalog is taken from whatever the application registered and falls back to the empty - * one. An empty catalog still classifies the SQLSTATE — which is what retry depends on — and - * resolves constraint names to the unknown code, which is the correct answer for a constraint the - * application never registered. - * - * @param catalogs the application's registered constraint catalog, if it has one - * @return the vendor translator - */ - @Bean - public VendorFailureTranslator postgreSqlVendorFailureTranslator( - ObjectProvider catalogs) { - return PostgreSqlExceptionTranslator.with( - catalogs.getIfAvailable(PostgreSqlConstraintCatalog::empty)); - } - /** * The vendor's migration location, as a default rather than as an override. * diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/constraint/PostgreSqlConstraintCatalog.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/constraint/PostgreSqlConstraintCatalog.java index ab72eea1..e103715d 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/constraint/PostgreSqlConstraintCatalog.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/constraint/PostgreSqlConstraintCatalog.java @@ -2,7 +2,6 @@ package dev.caskeleton.adapter.outbound.persistence.postgresql.constraint; import dev.caskeleton.adapter.outbound.persistence.api.error.ConstraintCode; import dev.caskeleton.adapter.outbound.persistence.api.error.ConstraintViolationDetails; -import dev.caskeleton.adapter.outbound.persistence.postgresql.error.ConstraintCatalog; import java.util.LinkedHashMap; import java.util.Locale; import java.util.Map; @@ -22,7 +21,7 @@ import java.util.Set; * Registering that name is all a migration has to do — which is exactly why the catalog maps names * rather than trying to model constraint semantics. */ -public final class PostgreSqlConstraintCatalog implements ConstraintCatalog { +public final class PostgreSqlConstraintCatalog { private final Map byDatabaseName; @@ -48,7 +47,7 @@ public final class PostgreSqlConstraintCatalog implements ConstraintCatalog { return new PostgreSqlConstraintCatalog(Map.of()); } - @Override + /** The registered code for a physical constraint name, or the unknown code. */ public ConstraintCode resolve(String databaseConstraintName) { if (databaseConstraintName == null || databaseConstraintName.isBlank()) { return ConstraintViolationDetails.UNKNOWN_CODE; diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/constraint/PostgreSqlConstraintViolationTranslator.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/constraint/PostgreSqlConstraintViolationTranslator.java index 93d5ee3a..3b28a773 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/constraint/PostgreSqlConstraintViolationTranslator.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/constraint/PostgreSqlConstraintViolationTranslator.java @@ -9,7 +9,6 @@ import dev.caskeleton.adapter.outbound.persistence.api.error.JpaFailureContext; import dev.caskeleton.adapter.outbound.persistence.api.error.JpaPersistenceException; import dev.caskeleton.adapter.outbound.persistence.api.error.NotNullConstraintViolationException; import dev.caskeleton.adapter.outbound.persistence.api.error.UniqueConstraintViolationException; -import dev.caskeleton.adapter.outbound.persistence.postgresql.error.ConstraintCatalog; import dev.caskeleton.adapter.outbound.persistence.postgresql.error.PostgreSqlServerErrorFields; import java.util.Objects; import java.util.Optional; @@ -25,9 +24,9 @@ import java.util.Optional; */ public final class PostgreSqlConstraintViolationTranslator { - private final ConstraintCatalog catalog; + private final PostgreSqlConstraintCatalog catalog; - public PostgreSqlConstraintViolationTranslator(ConstraintCatalog catalog) { + public PostgreSqlConstraintViolationTranslator(PostgreSqlConstraintCatalog catalog) { this.catalog = Objects.requireNonNull(catalog, "catalog"); } diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/copy/PostgreSqlCopyLoader.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/copy/PostgreSqlCopyLoader.java deleted file mode 100644 index 79faba1d..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/copy/PostgreSqlCopyLoader.java +++ /dev/null @@ -1,21 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.postgresql.copy; - -import java.io.InputStream; - -/** - * Streams a bounded source into a registered {@code COPY} statement (design §30). - * - *

This is a J4 admin capability, not a repository method. {@code COPY} bypasses the Persistence - * Context, entity callbacks, optimistic version checks, and Envers entirely — the rows appear in - * the table with none of the invariants ordinary writes go through. That is exactly why it is fast, - * and exactly why it is reachable only under an admin capability with a registered statement. - */ -public interface PostgreSqlCopyLoader { - - /** - * Loads {@code source} through the statement registered for {@code operation}. - * - * @throws IllegalStateException when the load exceeds any bound in {@code limits} - */ - CopyResult load(CopyOperationName operation, InputStream source, CopyLimits limits); -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/copy/RegisteredPostgreSqlCopyLoader.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/copy/RegisteredPostgreSqlCopyLoader.java index fa83d4d7..545c7ae5 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/copy/RegisteredPostgreSqlCopyLoader.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/copy/RegisteredPostgreSqlCopyLoader.java @@ -27,7 +27,7 @@ import javax.sql.DataSource; * one — the runtime role is verified to have no DDL and is not the role that should be * mass-inserting either. */ -public final class RegisteredPostgreSqlCopyLoader implements PostgreSqlCopyLoader { +public final class RegisteredPostgreSqlCopyLoader { private static final String PG_CONNECTION = "org.postgresql.PGConnection"; private static final String COPY_API_ACCESSOR = "getCopyAPI"; @@ -49,7 +49,11 @@ public final class RegisteredPostgreSqlCopyLoader implements PostgreSqlCopyLoade this.clock = Objects.requireNonNull(clock, "clock"); } - @Override + /** + * Loads {@code source} through the statement registered for {@code operation}. + * + * @throws IllegalStateException when the load exceeds any bound in {@code limits} + */ public CopyResult load(CopyOperationName operation, InputStream source, CopyLimits limits) { Objects.requireNonNull(operation, "operation"); Objects.requireNonNull(source, "source"); diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/error/ConstraintCatalog.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/error/ConstraintCatalog.java deleted file mode 100644 index ca9bfd8f..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/error/ConstraintCatalog.java +++ /dev/null @@ -1,19 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.postgresql.error; - -import dev.caskeleton.adapter.outbound.persistence.api.error.ConstraintCode; - -/** - * Maps a physical database constraint name to the application's registered {@link ConstraintCode} - * (design §22.4). - * - *

The catalog is bounded. An unmapped constraint resolves to the unknown code rather than being - * passed through, because the server-reported name is unbounded input: it becomes an error code, a - * log field, and potentially a metric tag, and a migration that adds an index would otherwise widen - * all three without review. - */ -@FunctionalInterface -public interface ConstraintCatalog { - - /** The registered code for a physical constraint name, or the unknown code. */ - ConstraintCode resolve(String databaseConstraintName); -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/error/PostgreSqlExceptionTranslator.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/error/PostgreSqlExceptionTranslator.java index af979cf3..9bd69437 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/error/PostgreSqlExceptionTranslator.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/error/PostgreSqlExceptionTranslator.java @@ -14,9 +14,8 @@ import dev.caskeleton.adapter.outbound.persistence.api.error.QueryTimeoutExcepti import dev.caskeleton.adapter.outbound.persistence.api.error.SchemaMismatchException; import dev.caskeleton.adapter.outbound.persistence.api.error.SerializationFailureException; import dev.caskeleton.adapter.outbound.persistence.api.error.SqlExceptionSqlStateResolver; -import dev.caskeleton.adapter.outbound.persistence.api.error.SqlStateResolver; import dev.caskeleton.adapter.outbound.persistence.api.error.TransactionTimeoutException; -import dev.caskeleton.adapter.outbound.persistence.api.error.VendorFailureTranslator; +import dev.caskeleton.adapter.outbound.persistence.postgresql.constraint.PostgreSqlConstraintCatalog; import dev.caskeleton.adapter.outbound.persistence.postgresql.constraint.PostgreSqlConstraintViolationTranslator; import java.time.Duration; import java.util.Objects; @@ -30,19 +29,19 @@ import java.util.Objects; * *

An unclassified SQLSTATE becomes a plain {@link JpaPersistenceException} in the {@link * FailureCategory#UNKNOWN} category rather than being mapped to the nearest-looking type. A wrong - * guess here does real damage: classify an unknown state as a serialization failure and the retry - * coordinator will happily re-run a write that already succeeded. + * guess here does real damage: classify an unknown state as a serialization failure and a caller + * that retries serialization failures will happily re-run a write that already succeeded. */ -public final class PostgreSqlExceptionTranslator implements VendorFailureTranslator { +public final class PostgreSqlExceptionTranslator { private final PostgreSqlFailureClassifier classifier; private final PostgreSqlConstraintViolationTranslator constraintTranslator; - private final SqlStateResolver sqlStateResolver; + private final SqlExceptionSqlStateResolver sqlStateResolver; public PostgreSqlExceptionTranslator( PostgreSqlFailureClassifier classifier, - ConstraintCatalog constraintCatalog, - SqlStateResolver sqlStateResolver) { + PostgreSqlConstraintCatalog constraintCatalog, + SqlExceptionSqlStateResolver sqlStateResolver) { this.classifier = Objects.requireNonNull(classifier, "classifier"); this.constraintTranslator = new PostgreSqlConstraintViolationTranslator( @@ -51,7 +50,7 @@ public final class PostgreSqlExceptionTranslator implements VendorFailureTransla } /** A translator using the standard classifier and the supplied constraint catalog. */ - public static PostgreSqlExceptionTranslator with(ConstraintCatalog catalog) { + public static PostgreSqlExceptionTranslator with(PostgreSqlConstraintCatalog catalog) { return new PostgreSqlExceptionTranslator( new PostgreSqlFailureClassifier(), catalog, new SqlExceptionSqlStateResolver()); } @@ -64,7 +63,6 @@ public final class PostgreSqlExceptionTranslator implements VendorFailureTransla * @param elapsed how long the attempt ran * @param traceId the current trace identifier, or {@code null} */ - @Override public JpaPersistenceException translate( Throwable failure, PersistenceOperationName operation, diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/error/PostgreSqlFailureClassifier.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/error/PostgreSqlFailureClassifier.java index 24afb0af..17322e0f 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/error/PostgreSqlFailureClassifier.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/error/PostgreSqlFailureClassifier.java @@ -12,8 +12,8 @@ import dev.caskeleton.adapter.outbound.persistence.api.error.FailureCategory; * *

Note what is deliberately not here: connection-class ({@code 08*}) states map to * {@link FailureCategory#CONNECTION_UNAVAILABLE}, not to completion-unknown. Whether a connection - * loss left the commit undetermined depends on the transaction phase, which only the commit-phase - * evidence in {@code CommitFailureClassifier} knows (design §17.2). + * loss left the commit undetermined depends on the transaction phase, which a SQLSTATE alone does + * not carry (design §17.2). */ public final class PostgreSqlFailureClassifier { diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/IdempotencyClaimGateway.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/IdempotencyClaimGateway.java index 99688068..1121b2b9 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/IdempotencyClaimGateway.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/IdempotencyClaimGateway.java @@ -1,6 +1,6 @@ package dev.caskeleton.adapter.outbound.persistence.postgresql.idempotency; -import dev.caskeleton.application.idempotency.v2.IdempotencyClaimRequest; +import dev.caskeleton.application.idempotency.IdempotencyClaimRequest; import java.util.Objects; import java.util.UUID; import org.springframework.jdbc.core.JdbcOperations; diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/IdempotencyRecordRow.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/IdempotencyRecordRow.java index b7409d07..2010aa1f 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/IdempotencyRecordRow.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/IdempotencyRecordRow.java @@ -1,6 +1,6 @@ package dev.caskeleton.adapter.outbound.persistence.postgresql.idempotency; -import dev.caskeleton.application.idempotency.v2.IdempotencyState; +import dev.caskeleton.application.idempotency.IdempotencyState; import java.time.Instant; /** diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/IdempotencyRowMapper.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/IdempotencyRowMapper.java index d4d24a87..78e67adc 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/IdempotencyRowMapper.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/IdempotencyRowMapper.java @@ -1,6 +1,6 @@ package dev.caskeleton.adapter.outbound.persistence.postgresql.idempotency; -import dev.caskeleton.application.idempotency.v2.IdempotencyState; +import dev.caskeleton.application.idempotency.IdempotencyState; import java.sql.ResultSet; import java.sql.SQLException; import java.time.Instant; diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/IdempotencySchemaStream.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/IdempotencySchemaStream.java new file mode 100644 index 00000000..ff06258b --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/IdempotencySchemaStream.java @@ -0,0 +1,97 @@ +package dev.caskeleton.adapter.outbound.persistence.postgresql.idempotency; + +import java.util.Objects; +import javax.sql.DataSource; +import org.flywaydb.core.Flyway; +import org.springframework.beans.factory.SmartInitializingSingleton; +import org.springframework.jdbc.core.ConnectionCallback; +import org.springframework.jdbc.core.JdbcTemplate; + +/** + * Applies and activates the owner-safe idempotency schema, so selecting {@code provider=postgresql} + * works on a fresh PostgreSQL without a manual operator step. + * + *

The primary Flyway migrates {@code db/migration/postgresql} only. The owner-safe columns live + * in {@code db/migration/jpa/idempotency}, whose version series overlaps the primary one, so it + * keeps its own history table. It requires the {@code jpa-flyway-migration} row that {@code + * db/migration/jpa/core} writes, so that stream is applied first. Both are forward-only and + * idempotent: a database an operator already migrated reports zero migrations executed. + * + *

The stream installs the capability as {@code INSTALLED_INACTIVE}; the store refuses to run + * until it is {@code ACTIVE}. Selecting the provider is the operator's decision to activate it, so + * this promotes it. A row in any other state is left alone. + * + *

Runs after every singleton is built, so the primary migration (which creates {@code + * idempotency_record} and {@code capability_schema_registry}) has already run. + */ +public final class IdempotencySchemaStream implements SmartInitializingSingleton { + + /** The owner-safe stream. */ + public static final String LOCATION = "classpath:db/migration/jpa/idempotency"; + + /** The owner-safe stream's history table. */ + public static final String HISTORY_TABLE = "flyway_jpa_idempotency_history"; + + static final String CORE_LOCATION = "classpath:db/migration/jpa/core"; + static final String CORE_HISTORY_TABLE = "flyway_jpa_core_history"; + + private static final String PROMOTE_SQL = + """ + update capability_schema_registry + set lifecycle_state = 'ACTIVE', updated_at = clock_timestamp() + where capability_id = 'jpa-idempotency-owner-safe-v2' + and core_epoch = 1 + and feature_revision = 2 + and lifecycle_state = 'INSTALLED_INACTIVE' + """; + + private final DataSource dataSource; + + public IdempotencySchemaStream(DataSource dataSource) { + this.dataSource = Objects.requireNonNull(dataSource, "dataSource"); + } + + @Override + public void afterSingletonsInstantiated() { + apply(); + } + + /** + * Refuses a non-PostgreSQL data source, then applies both streams and activates the capability. + * + * @throws IllegalStateException naming the vendor found, when it is not PostgreSQL + */ + public void apply() { + JdbcTemplate jdbc = new JdbcTemplate(dataSource); + String product = + jdbc.execute( + (ConnectionCallback) + connection -> connection.getMetaData().getDatabaseProductName()); + if (!"PostgreSQL".equalsIgnoreCase(product)) { + throw new IllegalStateException( + "ca-skeleton.capabilities.idempotency.provider=postgresql requires PostgreSQL; this data" + + " source reports " + + product + + ". Select disabled or redis instead."); + } + migrate(CORE_LOCATION, CORE_HISTORY_TABLE); + migrate(LOCATION, HISTORY_TABLE); + jdbc.update(PROMOTE_SQL); + } + + private void migrate(String location, String historyTable) { + Flyway.configure() + .dataSource(dataSource) + .locations(location) + .table(historyTable) + // Baseline 0 only lets Flyway start a second history table in a non-empty schema; every + // real migration (V1 onward) still runs. + .baselineVersion("0") + .baselineOnMigrate(true) + .outOfOrder(false) + .cleanDisabled(true) + .validateOnMigrate(true) + .load() + .migrate(); + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/IdempotencyTransitionGateway.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/IdempotencyTransitionGateway.java index 07571331..3f5df002 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/IdempotencyTransitionGateway.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/IdempotencyTransitionGateway.java @@ -1,6 +1,6 @@ package dev.caskeleton.adapter.outbound.persistence.postgresql.idempotency; -import dev.caskeleton.application.idempotency.v2.IdempotencyOwner; +import dev.caskeleton.application.idempotency.IdempotencyOwner; import java.time.Duration; import java.util.Objects; import org.springframework.jdbc.core.JdbcOperations; diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/PostgreSqlOwnerSafeIdempotencyStore.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/PostgreSqlOwnerSafeIdempotencyStore.java index dc576383..497808b5 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/PostgreSqlOwnerSafeIdempotencyStore.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/PostgreSqlOwnerSafeIdempotencyStore.java @@ -1,23 +1,23 @@ package dev.caskeleton.adapter.outbound.persistence.postgresql.idempotency; +import dev.caskeleton.application.idempotency.IdempotencyClaimAttempt; +import dev.caskeleton.application.idempotency.IdempotencyClaimOutcome; +import dev.caskeleton.application.idempotency.IdempotencyClaimRequest; +import dev.caskeleton.application.idempotency.IdempotencyCompleteOutcome; +import dev.caskeleton.application.idempotency.IdempotencyFailOutcome; +import dev.caskeleton.application.idempotency.IdempotencyFailureDisposition; +import dev.caskeleton.application.idempotency.IdempotencyInspection; +import dev.caskeleton.application.idempotency.IdempotencyInspectionOutcome; +import dev.caskeleton.application.idempotency.IdempotencyInspectionRequest; +import dev.caskeleton.application.idempotency.IdempotencyMutationResult; +import dev.caskeleton.application.idempotency.IdempotencyOwner; +import dev.caskeleton.application.idempotency.IdempotencyReleaseOutcome; +import dev.caskeleton.application.idempotency.IdempotencyRenewOutcome; +import dev.caskeleton.application.idempotency.IdempotencyScopeDigest; +import dev.caskeleton.application.idempotency.IdempotencyStartOutcome; +import dev.caskeleton.application.idempotency.IdempotencyState; +import dev.caskeleton.application.idempotency.IdempotencyStorePort; import dev.caskeleton.application.idempotency.StoredResponse; -import dev.caskeleton.application.idempotency.v2.IdempotencyClaimAttempt; -import dev.caskeleton.application.idempotency.v2.IdempotencyClaimOutcome; -import dev.caskeleton.application.idempotency.v2.IdempotencyClaimRequest; -import dev.caskeleton.application.idempotency.v2.IdempotencyCompleteOutcome; -import dev.caskeleton.application.idempotency.v2.IdempotencyFailOutcome; -import dev.caskeleton.application.idempotency.v2.IdempotencyFailureDisposition; -import dev.caskeleton.application.idempotency.v2.IdempotencyInspection; -import dev.caskeleton.application.idempotency.v2.IdempotencyInspectionOutcome; -import dev.caskeleton.application.idempotency.v2.IdempotencyInspectionRequest; -import dev.caskeleton.application.idempotency.v2.IdempotencyMutationResult; -import dev.caskeleton.application.idempotency.v2.IdempotencyOwner; -import dev.caskeleton.application.idempotency.v2.IdempotencyReleaseOutcome; -import dev.caskeleton.application.idempotency.v2.IdempotencyRenewOutcome; -import dev.caskeleton.application.idempotency.v2.IdempotencyScopeDigest; -import dev.caskeleton.application.idempotency.v2.IdempotencyStartOutcome; -import dev.caskeleton.application.idempotency.v2.IdempotencyState; -import dev.caskeleton.application.idempotency.v2.IdempotencyStorePortV2; import dev.caskeleton.application.transaction.OperationId; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; @@ -52,13 +52,11 @@ import org.springframework.jdbc.core.JdbcOperations; * *

Deliberately carries no Spring stereotype. Both composition roots component-scan {@code * dev.caskeleton.adapter}, so a {@code @Repository} here would be registered in every deployment - * regardless of which idempotency provider was selected: {@code provider=jdbc} would acquire an - * owner-safe V2 store it never asked for, and {@code provider=redis} a second one beside its own. - * Both counts are what {@code IdempotencyProviderSelectionConfig} refuses, so a scan-registered - * store means neither selection can start. The persistence leaf composition root builds it for - * {@code provider=postgresql} and only while the JPA capability is enabled. + * regardless of which idempotency provider was selected — {@code provider=redis} would acquire a + * second store beside its own, which the composition root refuses. The persistence leaf builds it + * for {@code provider=postgresql} and only while the JPA capability is enabled. */ -public class PostgreSqlOwnerSafeIdempotencyStore implements IdempotencyStorePortV2 { +public class PostgreSqlOwnerSafeIdempotencyStore implements IdempotencyStorePort { static final int INLINE_RESPONSE_MAX_BYTES = 8 * 1024; diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/inbox/PostgreSqlSameStoreInboxAdapter.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/inbox/PostgreSqlSameStoreInboxAdapter.java deleted file mode 100644 index e864e67d..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/inbox/PostgreSqlSameStoreInboxAdapter.java +++ /dev/null @@ -1,596 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.postgresql.inbox; - -import dev.caskeleton.application.inbox.InboxClaimAttempt; -import dev.caskeleton.application.inbox.InboxClaimOutcome; -import dev.caskeleton.application.inbox.InboxClaimRequest; -import dev.caskeleton.application.inbox.InboxOwner; -import dev.caskeleton.application.inbox.InboxOwnerTransition; -import dev.caskeleton.application.inbox.InboxScopeDigest; -import dev.caskeleton.application.inbox.InboxState; -import dev.caskeleton.application.inbox.InboxStorePort; -import dev.caskeleton.application.inbox.InboxTransitionOutcome; -import dev.caskeleton.application.transaction.OperationId; -import java.nio.ByteBuffer; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.SecureRandom; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.time.Duration; -import java.time.Instant; -import java.time.OffsetDateTime; -import java.util.HexFormat; -import java.util.List; -import java.util.Objects; -import java.util.Optional; -import javax.sql.DataSource; -import org.springframework.jdbc.core.JdbcOperations; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.transaction.support.TransactionSynchronizationManager; - -/** - * PostgreSQL same-store inbox. - * - *

Claim, business mutation, optional outgoing outbox append, and completion are intended to run - * inside one caller-owned transaction. Broker acknowledgement is deliberately outside this port. - * - *

Deliberately carries no Spring stereotype. Both composition roots component-scan {@code - * dev.caskeleton.adapter}, so a {@code @Repository} here became a bean in every deployment — - * including one running H2, which has no migration tree at all, and one that never applied {@code - * db/migration/jpa/inbox}. The bean existed, its tables did not, and the failure arrived either at - * the first call as vendor-specific SQL against a missing relation, or at startup under {@code - * ddl-auto=validate}. A candidate implementation that nobody selected should not be composed. - * - *

Composing it is a configuration's decision: the PostgreSQL provider must be selected, the - * capability enabled, and {@code jpa-inbox-same-store-v1} promoted to ACTIVE. Until such a - * configuration exists, the integration tests construct it directly. - */ -public class PostgreSqlSameStoreInboxAdapter implements InboxStorePort { - - private static final Duration MAXIMUM_RETENTION = Duration.ofDays(30); - private static final String DB_NOW_SQL = "select clock_timestamp()"; - - private static final String ACTIVE_CAPABILITY_SQL = - """ - select count(*) - from capability_schema_registry - where capability_id = 'jpa-inbox-same-store-v1' - and core_epoch = 1 - and feature_revision = 1 - and lifecycle_state = 'ACTIVE' - """; - - private static final String INSERT_SQL = - """ - insert into inbox_record_v1 ( - scope_hash, - message_intent_digest, - state, - state_revision, - owner_token, - attempt, - claim_operation_id, - processing_lease_until, - last_operation_id, - last_transition_kind, - last_result_digest, - terminal_at, - retention_until, - created_at, - updated_at - ) - select - ?, ?, 'RECEIVED', 0, ?, 1, ?, - db_now + (? * interval '1 millisecond'), - null, null, null, null, - db_now + (? * interval '1 millisecond'), - db_now, db_now - from (select clock_timestamp() as db_now) authority - on conflict (scope_hash) do nothing - """; - - private static final String SELECT_SQL = - """ - select scope_hash, message_intent_digest, state, state_revision, owner_token, attempt, - claim_operation_id, processing_lease_until, last_operation_id, - last_transition_kind, last_result_digest, terminal_at, retention_until - from inbox_record_v1 - where scope_hash = ? - """; - - private static final String SELECT_FOR_UPDATE_SQL = SELECT_SQL + " for update"; - - private static final String RESET_SQL = - """ - update inbox_record_v1 - set message_intent_digest = ?, - state = 'RECEIVED', - state_revision = state_revision + 1, - owner_token = ?, - attempt = attempt + 1, - claim_operation_id = ?, - processing_lease_until = clock_timestamp() + (? * interval '1 millisecond'), - last_operation_id = null, - last_transition_kind = null, - last_result_digest = null, - terminal_at = null, - retention_until = clock_timestamp() + (? * interval '1 millisecond'), - updated_at = clock_timestamp() - where scope_hash = ? - and state = ? - and state_revision = ? - """; - - private static final String EXPIRE_PROCESSING_SQL = - """ - update inbox_record_v1 - set state = 'DEAD', - state_revision = state_revision + 1, - last_operation_id = claim_operation_id, - last_transition_kind = 'EXPIRED_PROCESSING', - last_result_digest = ?, - terminal_at = clock_timestamp(), - updated_at = clock_timestamp() - where scope_hash = ? - and state = 'PROCESSING' - and owner_token = ? - and attempt = ? - and claim_operation_id = ? - and state_revision = ? - """; - - private static final String START_SQL = - """ - update inbox_record_v1 - set state = 'PROCESSING', - state_revision = state_revision + 1, - last_operation_id = ?, - last_transition_kind = 'START', - last_result_digest = ?, - updated_at = clock_timestamp() - where scope_hash = ? - and state = 'RECEIVED' - and owner_token = ? - and attempt = ? - and claim_operation_id = ? - and state_revision = ? - and processing_lease_until > clock_timestamp() - """; - - private static final String COMPLETE_SQL = - """ - update inbox_record_v1 - set state = 'COMPLETED', - state_revision = state_revision + 1, - last_operation_id = ?, - last_transition_kind = 'COMPLETE', - last_result_digest = ?, - terminal_at = clock_timestamp(), - updated_at = clock_timestamp() - where scope_hash = ? - and state = 'PROCESSING' - and owner_token = ? - and attempt = ? - and claim_operation_id = ? - and state_revision = ? - """; - - private static final String FAIL_SQL = - """ - update inbox_record_v1 - set state = ?, - state_revision = state_revision + 1, - last_operation_id = ?, - last_transition_kind = ?, - last_result_digest = ?, - terminal_at = case when ? = 'DEAD' then clock_timestamp() else null end, - retention_until = clock_timestamp() + (? * interval '1 millisecond'), - processing_lease_until = clock_timestamp(), - updated_at = clock_timestamp() - where scope_hash = ? - and state = 'PROCESSING' - and owner_token = ? - and attempt = ? - and claim_operation_id = ? - and state_revision = ? - """; - - private final DataSource dataSource; - private final JdbcOperations jdbc; - private final SecureRandom secureRandom; - - public PostgreSqlSameStoreInboxAdapter(DataSource dataSource) { - this(dataSource, new JdbcTemplate(dataSource), new SecureRandom()); - } - - PostgreSqlSameStoreInboxAdapter( - DataSource dataSource, JdbcOperations jdbc, SecureRandom secureRandom) { - this.dataSource = Objects.requireNonNull(dataSource, "dataSource"); - this.jdbc = Objects.requireNonNull(jdbc, "jdbc"); - this.secureRandom = Objects.requireNonNull(secureRandom, "secureRandom"); - } - - @Override - public InboxClaimAttempt newClaimAttempt(OperationId operationId) { - Objects.requireNonNull(operationId, "operationId"); - byte[] token = new byte[32]; - secureRandom.nextBytes(token); - return new InboxClaimAttempt(HexFormat.of().formatHex(token), operationId); - } - - @Override - public InboxClaimOutcome claim(InboxClaimRequest request) { - Objects.requireNonNull(request, "request"); - requireSameResourcePrimaryWriteTransaction(); - requireActiveCapability(); - int inserted = - jdbc.update( - INSERT_SQL, - request.scope().value(), - request.messageIntentDigest(), - request.claimAttempt().ownerToken(), - request.claimAttempt().operationId().value(), - request.processingLease().toMillis(), - request.terminalRetention().toMillis()); - InboxRow row = findForUpdate(request.scope()).orElseThrow(this::indeterminate); - Instant dbNow = databaseNowAfterLock(); - if (inserted == 1) { - return new InboxClaimOutcome.Acquired(owner(row), row.processingLeaseUntil()); - } - if ((row.state() == InboxState.COMPLETED || row.state() == InboxState.DEAD) - && !dbNow.isBefore(row.retentionUntil())) { - return resetClaim(request, row); - } - if (!row.messageIntentDigest().equals(request.messageIntentDigest())) { - return new InboxClaimOutcome.IntentMismatch(); - } - if (sameClaimAttempt(row, request.claimAttempt())) { - if (row.state() == InboxState.COMPLETED) { - return new InboxClaimOutcome.Completed(); - } - return new InboxClaimOutcome.ReplayedAcquire(owner(row), row.processingLeaseUntil()); - } - if (row.ownerToken().equals(request.claimAttempt().ownerToken())) { - return new InboxClaimOutcome.OwnerOperationConflict(); - } - if (row.state() == InboxState.COMPLETED) { - return new InboxClaimOutcome.Completed(); - } - if ((row.state() == InboxState.RECEIVED && !dbNow.isBefore(row.processingLeaseUntil())) - || row.state() == InboxState.RETRYABLE) { - return resetClaim(request, row); - } - if (row.state() == InboxState.PROCESSING && !dbNow.isBefore(row.processingLeaseUntil())) { - expireProcessing(row); - return new InboxClaimOutcome.RecoveryRequired(row.attempt()); - } - if (row.state() == InboxState.DEAD) { - return new InboxClaimOutcome.RecoveryRequired(row.attempt()); - } - Duration retryAfter = - row.processingLeaseUntil().isAfter(dbNow) - ? Duration.between(dbNow, row.processingLeaseUntil()) - : Duration.ZERO; - return new InboxClaimOutcome.InProgress(retryAfter, row.attempt()); - } - - @Override - public InboxOwnerTransition markProcessing(InboxOwner owner, OperationId operationId) { - Objects.requireNonNull(owner, "owner"); - Objects.requireNonNull(operationId, "operationId"); - requireSameResourcePrimaryWriteTransaction(); - InboxRow row = findForUpdate(owner.scope()).orElse(null); - if (row == null) { - return transition(InboxTransitionOutcome.ABSENT, null); - } - if (isDuplicate(row, "START", operationId)) { - return transition(InboxTransitionOutcome.PROCESSING_STARTED, owner(row)); - } - InboxTransitionOutcome mismatch = classifyMismatch(row, owner, InboxState.RECEIVED); - if (mismatch != null) { - return transition(mismatch, null); - } - int updated = - jdbc.update( - START_SQL, - operationId.value(), - transitionDigest("START", operationId, owner), - owner.scope().value(), - owner.ownerToken(), - owner.attempt(), - owner.claimOperationId().value(), - owner.stateRevision()); - return updated == 1 - ? transition( - InboxTransitionOutcome.PROCESSING_STARTED, - owner.withStateRevision(owner.stateRevision() + 1)) - : transition(InboxTransitionOutcome.NOT_OWNER, null); - } - - @Override - public InboxTransitionOutcome complete(InboxOwner owner, OperationId operationId) { - Objects.requireNonNull(owner, "owner"); - Objects.requireNonNull(operationId, "operationId"); - requireSameResourcePrimaryWriteTransaction(); - InboxRow row = findForUpdate(owner.scope()).orElse(null); - if (row == null) { - return InboxTransitionOutcome.ABSENT; - } - String digest = transitionDigest("COMPLETE", operationId, owner); - InboxTransitionOutcome duplicate = classifyDuplicate(row, "COMPLETE", operationId, digest); - if (duplicate != null) { - return duplicate; - } - InboxTransitionOutcome mismatch = classifyMismatch(row, owner, InboxState.PROCESSING); - if (mismatch != null) { - return mismatch; - } - int updated = - jdbc.update( - COMPLETE_SQL, - operationId.value(), - digest, - owner.scope().value(), - owner.ownerToken(), - owner.attempt(), - owner.claimOperationId().value(), - owner.stateRevision()); - return updated == 1 ? InboxTransitionOutcome.COMPLETED : InboxTransitionOutcome.RESULT_CONFLICT; - } - - @Override - public InboxTransitionOutcome markRetryable( - InboxOwner owner, Duration retention, OperationId operationId) { - return fail(owner, retention, operationId, InboxState.RETRYABLE); - } - - @Override - public InboxTransitionOutcome markDead( - InboxOwner owner, Duration retention, OperationId operationId) { - return fail(owner, retention, operationId, InboxState.DEAD); - } - - private InboxTransitionOutcome fail( - InboxOwner owner, Duration retention, OperationId operationId, InboxState target) { - Objects.requireNonNull(owner, "owner"); - Objects.requireNonNull(operationId, "operationId"); - requirePositiveRetention(retention); - requireSameResourcePrimaryWriteTransaction(); - InboxRow row = findForUpdate(owner.scope()).orElse(null); - if (row == null) { - return InboxTransitionOutcome.ABSENT; - } - String kind = target == InboxState.RETRYABLE ? "RETRYABLE" : "DEAD"; - String digest = transitionDigest(kind, operationId, owner); - InboxTransitionOutcome duplicate = classifyDuplicate(row, kind, operationId, digest); - if (duplicate != null) { - return duplicate; - } - InboxTransitionOutcome mismatch = classifyMismatch(row, owner, InboxState.PROCESSING); - if (mismatch != null) { - return mismatch; - } - int updated = - jdbc.update( - FAIL_SQL, - target.name(), - operationId.value(), - kind, - digest, - target.name(), - retention.toMillis(), - owner.scope().value(), - owner.ownerToken(), - owner.attempt(), - owner.claimOperationId().value(), - owner.stateRevision()); - if (updated != 1) { - return InboxTransitionOutcome.RESULT_CONFLICT; - } - return target == InboxState.RETRYABLE - ? InboxTransitionOutcome.RETRYABLE - : InboxTransitionOutcome.DEAD; - } - - private InboxClaimOutcome resetClaim(InboxClaimRequest request, InboxRow row) { - int updated = - jdbc.update( - RESET_SQL, - request.messageIntentDigest(), - request.claimAttempt().ownerToken(), - request.claimAttempt().operationId().value(), - request.processingLease().toMillis(), - request.terminalRetention().toMillis(), - request.scope().value(), - row.state().name(), - row.stateRevision()); - if (updated != 1) { - throw indeterminate(); - } - InboxRow reset = findForUpdate(request.scope()).orElseThrow(this::indeterminate); - return new InboxClaimOutcome.TakenOver(owner(reset), reset.processingLeaseUntil()); - } - - private void expireProcessing(InboxRow row) { - String resultDigest = digestFields("EXPIRED_PROCESSING", row.claimOperationId()); - int updated = - jdbc.update( - EXPIRE_PROCESSING_SQL, - resultDigest, - row.scopeHash(), - row.ownerToken(), - row.attempt(), - row.claimOperationId(), - row.stateRevision()); - if (updated != 1) { - throw indeterminate(); - } - } - - private InboxTransitionOutcome classifyMismatch( - InboxRow row, InboxOwner owner, InboxState expectedState) { - if (!sameOwnerIdentity(row, owner)) { - return InboxTransitionOutcome.NOT_OWNER; - } - if (row.stateRevision() != owner.stateRevision()) { - return InboxTransitionOutcome.STALE_REVISION; - } - if (row.state() != expectedState) { - return InboxTransitionOutcome.INVALID_STATE; - } - return null; - } - - private static InboxTransitionOutcome classifyDuplicate( - InboxRow row, String kind, OperationId operationId, String digest) { - if (kind.equals(row.lastTransitionKind()) - && operationId.value().equals(row.lastOperationId())) { - return digest.equals(row.lastResultDigest()) - ? InboxTransitionOutcome.ALREADY_APPLIED_SAME_OPERATION - : InboxTransitionOutcome.RESULT_CONFLICT; - } - return null; - } - - private Optional findForUpdate(InboxScopeDigest scope) { - return queryOne(SELECT_FOR_UPDATE_SQL, scope); - } - - private Optional queryOne(String sql, InboxScopeDigest scope) { - List rows = jdbc.query(sql, this::mapRow, scope.value()); - if (rows.size() > 1) { - throw new IllegalStateException("multiple inbox rows for one scope"); - } - return rows.stream().findFirst(); - } - - private InboxRow mapRow(ResultSet resultSet, int rowNumber) throws SQLException { - return new InboxRow( - resultSet.getString("scope_hash"), - resultSet.getString("message_intent_digest"), - InboxState.valueOf(resultSet.getString("state")), - resultSet.getLong("state_revision"), - resultSet.getString("owner_token"), - resultSet.getLong("attempt"), - resultSet.getString("claim_operation_id"), - resultSet.getObject("processing_lease_until", OffsetDateTime.class).toInstant(), - resultSet.getString("last_operation_id"), - resultSet.getString("last_transition_kind"), - resultSet.getString("last_result_digest"), - nullableInstant(resultSet, "terminal_at"), - resultSet.getObject("retention_until", OffsetDateTime.class).toInstant()); - } - - private Instant databaseNowAfterLock() { - OffsetDateTime value = jdbc.queryForObject(DB_NOW_SQL, OffsetDateTime.class); - if (value == null) { - throw new IllegalStateException("PostgreSQL returned no authoritative database time"); - } - return value.toInstant(); - } - - private void requireActiveCapability() { - Integer active = jdbc.queryForObject(ACTIVE_CAPABILITY_SQL, Integer.class); - if (active == null || active != 1) { - throw new IllegalStateException( - "jpa-inbox-same-store-v1 is not active at core epoch 1/revision 1"); - } - } - - private void requireSameResourcePrimaryWriteTransaction() { - if (!TransactionSynchronizationManager.isActualTransactionActive() - || TransactionSynchronizationManager.isCurrentTransactionReadOnly() - || !TransactionSynchronizationManager.hasResource(dataSource)) { - throw new IllegalStateException( - "same-store inbox mutation requires the adapter datasource primary write transaction"); - } - } - - private static void requirePositiveRetention(Duration retention) { - Objects.requireNonNull(retention, "retention"); - if (retention.isZero() - || retention.isNegative() - || retention.compareTo(MAXIMUM_RETENTION) > 0) { - throw new IllegalArgumentException( - "retention must be positive and at most " + MAXIMUM_RETENTION); - } - } - - private static boolean sameClaimAttempt(InboxRow row, InboxClaimAttempt attempt) { - return row.ownerToken().equals(attempt.ownerToken()) - && row.claimOperationId().equals(attempt.operationId().value()); - } - - private static boolean sameOwnerIdentity(InboxRow row, InboxOwner owner) { - return row.scopeHash().equals(owner.scope().value()) - && row.ownerToken().equals(owner.ownerToken()) - && row.attempt() == owner.attempt() - && row.claimOperationId().equals(owner.claimOperationId().value()); - } - - private static boolean isDuplicate(InboxRow row, String kind, OperationId operationId) { - return kind.equals(row.lastTransitionKind()) - && operationId.value().equals(row.lastOperationId()); - } - - private static InboxOwner owner(InboxRow row) { - return new InboxOwner( - new InboxScopeDigest(row.scopeHash()), - row.ownerToken(), - row.attempt(), - row.stateRevision(), - new OperationId(row.claimOperationId())); - } - - private static InboxOwnerTransition transition(InboxTransitionOutcome outcome, InboxOwner owner) { - return new InboxOwnerTransition(outcome, Optional.ofNullable(owner)); - } - - private static String transitionDigest(String kind, OperationId operationId, InboxOwner owner) { - return digestFields( - kind, - operationId.value(), - owner.ownerToken(), - Long.toString(owner.attempt()), - Long.toString(owner.stateRevision())); - } - - static String digestFields(String... fields) { - try { - MessageDigest digest = MessageDigest.getInstance("SHA-256"); - for (String field : fields) { - byte[] bytes = Objects.toString(field, "").getBytes(StandardCharsets.UTF_8); - digest.update(ByteBuffer.allocate(Integer.BYTES).putInt(bytes.length).array()); - digest.update(bytes); - } - return HexFormat.of().formatHex(digest.digest()); - } catch (NoSuchAlgorithmException exception) { - throw new IllegalStateException("SHA-256 unavailable", exception); - } - } - - private static Instant nullableInstant(ResultSet resultSet, String column) throws SQLException { - OffsetDateTime value = resultSet.getObject(column, OffsetDateTime.class); - return value == null ? null : value.toInstant(); - } - - private IllegalStateException indeterminate() { - return new IllegalStateException("same-store inbox transition is indeterminate"); - } - - private record InboxRow( - String scopeHash, - String messageIntentDigest, - InboxState state, - long stateRevision, - String ownerToken, - long attempt, - String claimOperationId, - Instant processingLeaseUntil, - String lastOperationId, - String lastTransitionKind, - String lastResultDigest, - Instant terminalAt, - Instant retentionUntil) {} -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/lock/LockWaitObservation.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/lock/LockWaitObservation.java deleted file mode 100644 index d4844280..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/lock/LockWaitObservation.java +++ /dev/null @@ -1,36 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.postgresql.lock; - -import dev.caskeleton.adapter.outbound.persistence.api.PersistenceOperationName; -import java.time.Duration; - -/** - * Records how long lock acquisition actually waited (design §21). - * - *

Lock waits are invisible in ordinary query timings: the statement duration includes the wait, - * so a slow endpoint looks like a slow query rather than contention. Measuring the wait separately - * is what distinguishes "this query needs an index" from "two transactions take these rows in - * opposite order". - */ -public interface LockWaitObservation { - - /** A lock was acquired after waiting {@code waited}. */ - void acquired(PersistenceOperationName operation, Duration waited); - - /** A lock was refused — by {@code NOWAIT} or by timeout — after waiting {@code waited}. */ - void refused(PersistenceOperationName operation, Duration waited, boolean nowait); - - /** An observation that records nothing. */ - static LockWaitObservation noop() { - return new LockWaitObservation() { - @Override - public void acquired(PersistenceOperationName operation, Duration waited) { - // no telemetry backend is installed - } - - @Override - public void refused(PersistenceOperationName operation, Duration waited, boolean nowait) { - // no telemetry backend is installed - } - }; - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/lock/PostgreSqlLockExceptionTranslator.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/lock/PostgreSqlLockExceptionTranslator.java index 56e76d15..899369be 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/lock/PostgreSqlLockExceptionTranslator.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/lock/PostgreSqlLockExceptionTranslator.java @@ -6,7 +6,6 @@ import dev.caskeleton.adapter.outbound.persistence.api.error.JpaFailureContext; import dev.caskeleton.adapter.outbound.persistence.api.error.JpaPersistenceException; import dev.caskeleton.adapter.outbound.persistence.api.error.PessimisticLockTimeoutException; import dev.caskeleton.adapter.outbound.persistence.api.error.SqlExceptionSqlStateResolver; -import dev.caskeleton.adapter.outbound.persistence.api.error.SqlStateResolver; import dev.caskeleton.adapter.outbound.persistence.postgresql.error.PostgreSqlState; import java.time.Duration; import java.util.Objects; @@ -24,9 +23,9 @@ import java.util.Optional; */ public final class PostgreSqlLockExceptionTranslator { - private final SqlStateResolver sqlStateResolver; + private final SqlExceptionSqlStateResolver sqlStateResolver; - public PostgreSqlLockExceptionTranslator(SqlStateResolver sqlStateResolver) { + public PostgreSqlLockExceptionTranslator(SqlExceptionSqlStateResolver sqlStateResolver) { this.sqlStateResolver = Objects.requireNonNull(sqlStateResolver, "sqlStateResolver"); } diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/lock/PostgreSqlWorkClaimExecutor.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/lock/PostgreSqlWorkClaimExecutor.java deleted file mode 100644 index b123cbfc..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/lock/PostgreSqlWorkClaimExecutor.java +++ /dev/null @@ -1,105 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.postgresql.lock; - -import jakarta.persistence.EntityManager; -import jakarta.persistence.Query; -import java.time.Clock; -import java.time.Duration; -import java.time.Instant; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.function.BiFunction; - -/** - * Claims disjoint batches of queue rows using {@code FOR UPDATE SKIP LOCKED} (design §21.3). - * - *

Only registered queues are claimable, and each queue's statement is fixed at registration. - * Nothing the caller passes reaches the SQL text: the batch size and the lease expiry are bound as - * parameters, and the queue name selects a statement rather than being interpolated into one. - * - *

The lease is computed here and written by the same statement that takes the claim. Handing - * back a claim whose lease was set by a later statement would leave a window where the row is - * locked by this transaction but marked as owned by nobody. - */ -public final class PostgreSqlWorkClaimExecutor implements WorkClaimExecutor { - - /** The batch size parameter every registered claim statement binds. */ - public static final String BATCH_SIZE_PARAMETER = "batchSize"; - - /** The lease expiry parameter every registered claim statement binds. */ - public static final String LEASE_UNTIL_PARAMETER = "leaseUntil"; - - /** The lease owner parameter every registered claim statement binds. */ - public static final String LEASE_OWNER_PARAMETER = "leaseOwner"; - - private static final int MAX_BATCH_SIZE = 1_000; - - private final EntityManager entityManager; - private final Map queues; - private final BiFunction> rowMapper; - private final String leaseOwner; - private final Clock clock; - - /** - * @param queues the registered queues; a name outside this map cannot be claimed - * @param rowMapper turns one claimed row and its lease expiry into a {@link WorkClaim} - * @param leaseOwner the bounded identity written into each claimed row - */ - public PostgreSqlWorkClaimExecutor( - EntityManager entityManager, - Map queues, - BiFunction> rowMapper, - String leaseOwner, - Clock clock) { - this.entityManager = Objects.requireNonNull(entityManager, "entityManager"); - this.queues = Map.copyOf(Objects.requireNonNull(queues, "queues")); - this.rowMapper = Objects.requireNonNull(rowMapper, "rowMapper"); - this.leaseOwner = Objects.requireNonNull(leaseOwner, "leaseOwner"); - this.clock = Objects.requireNonNull(clock, "clock"); - if (leaseOwner.isBlank()) { - throw new IllegalArgumentException("lease owner must not be blank"); - } - } - - @Override - public List> claimNextBatch(WorkQueueName queue, int size, Duration lease) { - Objects.requireNonNull(queue, "queue"); - Objects.requireNonNull(lease, "lease"); - if (size < 1 || size > MAX_BATCH_SIZE) { - throw new IllegalArgumentException( - "claim batch size must be between 1 and " + MAX_BATCH_SIZE); - } - if (lease.isZero() || lease.isNegative()) { - throw new IllegalArgumentException("claim lease must be positive"); - } - WorkQueueDefinition definition = queues.get(queue); - if (definition == null) { - throw new IllegalArgumentException("unregistered work queue: " + queue.value()); - } - - Instant leaseUntil = clock.instant().plus(lease); - Query query = entityManager.createNativeQuery(definition.claimSql()); - query.setParameter(BATCH_SIZE_PARAMETER, size); - query.setParameter(LEASE_UNTIL_PARAMETER, leaseUntil); - query.setParameter(LEASE_OWNER_PARAMETER, leaseOwner); - - List rows = query.getResultList(); - return rows.stream().map(row -> rowMapper.apply(toColumns(row), leaseUntil)).toList(); - } - - /** The registered queue names this executor can claim from. */ - public java.util.Set registeredQueues() { - return queues.keySet(); - } - - /** - * Normalises a native-query row into a column array. - * - *

JPA returns a bare value rather than a one-element array when the statement projects a - * single column, so a mapper written against {@code Object[]} would fail only for single-column - * queues — the easiest shape to get wrong and the hardest to notice. - */ - private static Object[] toColumns(Object row) { - return row instanceof Object[] columns ? columns : new Object[] {row}; - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/lock/WorkClaim.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/lock/WorkClaim.java deleted file mode 100644 index 43939171..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/lock/WorkClaim.java +++ /dev/null @@ -1,31 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.postgresql.lock; - -import java.time.Instant; -import java.util.Objects; - -/** - * One row a worker successfully claimed, with the lease that proves it (design §21.3). - * - *

The lease owner and expiry are returned from the same transaction that took the claim. A - * worker that had to ask afterwards "did I get it, and until when?" would be reading state another - * worker may already have reclaimed. - * - * @param the claimed payload type - * @param the claimed row's identifier type - */ -public record WorkClaim(K id, T payload, String leaseOwner, Instant leaseUntil) { - - public WorkClaim { - Objects.requireNonNull(id, "id"); - Objects.requireNonNull(leaseOwner, "leaseOwner"); - Objects.requireNonNull(leaseUntil, "leaseUntil"); - if (leaseOwner.isBlank()) { - throw new IllegalArgumentException("lease owner must not be blank"); - } - } - - /** Whether the lease is still valid at {@code now}. */ - public boolean leaseValidAt(Instant now) { - return now.isBefore(leaseUntil); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/lock/WorkClaimExecutor.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/lock/WorkClaimExecutor.java deleted file mode 100644 index d0b0de21..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/lock/WorkClaimExecutor.java +++ /dev/null @@ -1,27 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.postgresql.lock; - -import java.time.Duration; -import java.util.List; - -/** - * Claims a batch of rows from a registered queue (design §21.3). - * - *

This is a queue API, not a general "skip locked reads" switch. {@code FOR UPDATE SKIP LOCKED} - * deliberately returns an incomplete view of the table: it is correct for handing disjoint work to - * competing workers, and silently wrong for anything that needs to see every matching row. Exposing - * it as a repository flag would let that second use appear by accident, so it is reachable only - * through a named queue. - * - * @param the claimed payload type - * @param the claimed row's identifier type - */ -public interface WorkClaimExecutor { - - /** - * Claims up to {@code size} rows, leasing each for {@code lease}. - * - *

Must run inside the caller's transaction: the claim and the lease write are the same - * transaction, or another worker can take a row this one believes it owns. - */ - List> claimNextBatch(WorkQueueName queue, int size, Duration lease); -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/lock/WorkQueueDefinition.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/lock/WorkQueueDefinition.java deleted file mode 100644 index 6fbd709b..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/lock/WorkQueueDefinition.java +++ /dev/null @@ -1,43 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.postgresql.lock; - -import java.util.Locale; -import java.util.Objects; - -/** - * The fixed claim statement registered for one work queue (design §21.3). - * - *

The SQL is supplied at registration and never assembled from a request. The constructor - * refuses a statement that does not both skip locked rows and impose a deterministic order: - * - *

    - *
  • Without {@code SKIP LOCKED}, competing workers block on each other instead of taking - * disjoint work, which is the opposite of what a claim query is for. - *
  • Without {@code ORDER BY}, PostgreSQL may return rows in any order, so priority is whatever - * the plan happened to produce and starvation is unreproducible. - *
- */ -public record WorkQueueDefinition(WorkQueueName name, String claimSql) { - - public WorkQueueDefinition { - Objects.requireNonNull(name, "name"); - Objects.requireNonNull(claimSql, "claimSql"); - String normalized = claimSql.toLowerCase(Locale.ROOT); - if (!normalized.contains("skip locked")) { - throw new IllegalArgumentException( - "queue '" + name.value() + "' claim SQL must use FOR UPDATE SKIP LOCKED"); - } - if (!normalized.contains("order by")) { - throw new IllegalArgumentException( - "queue '" + name.value() + "' claim SQL must impose a deterministic ORDER BY"); - } - // No source-token check here. This used to search the finished statement for {@code "' +"} — - // a Java concatenation operator, which the compiler has already evaluated and removed by the - // time any string reaches this constructor. The guard could only ever fire on a statement that - // literally contained those characters, and never on the dynamic construction it was written - // to prevent. - // - // Statements come from the registered catalog and take parameters through typed binders, so - // there is no runtime path that assembles one. Forbidding dynamic construction is a rule about - // source, and ArchUnit and review are where source rules live. - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/lock/WorkQueueName.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/lock/WorkQueueName.java deleted file mode 100644 index bbebbb03..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/lock/WorkQueueName.java +++ /dev/null @@ -1,26 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.postgresql.lock; - -import java.util.regex.Pattern; - -/** - * The registered identity of a claimable work queue (design §21.3). - * - *

A queue name is a registry key, not a table name. The claim SQL for each queue is fixed at - * registration, so the name selects a pre-approved statement instead of being interpolated into one - * — the difference between a queue registry and SQL injection through a queue parameter. - */ -public record WorkQueueName(String value) { - - private static final Pattern FORMAT = Pattern.compile("[a-z][a-z0-9.-]{2,63}"); - - public WorkQueueName { - if (value == null || !FORMAT.matcher(value).matches()) { - throw new IllegalArgumentException("invalid work queue name"); - } - } - - @Override - public String toString() { - return value; - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/outbox/CanonicalOutboxEventRowMapper.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/outbox/CanonicalOutboxEventRowMapper.java deleted file mode 100644 index 7022e5e6..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/outbox/CanonicalOutboxEventRowMapper.java +++ /dev/null @@ -1,130 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.postgresql.outbox; - -import dev.caskeleton.application.messaging.contract.ContractId; -import dev.caskeleton.application.messaging.contract.LogicalDestinationId; -import dev.caskeleton.application.messaging.contract.Sha256; -import dev.caskeleton.application.messaging.event.AggregateIdentity; -import dev.caskeleton.application.messaging.event.AggregateOrder; -import dev.caskeleton.application.messaging.event.EventId; -import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent; -import java.nio.ByteBuffer; -import java.nio.charset.CharacterCodingException; -import java.nio.charset.CodingErrorAction; -import java.nio.charset.StandardCharsets; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.time.OffsetDateTime; -import java.util.Arrays; -import java.util.HexFormat; -import java.util.Optional; - -/** Shared fail-closed mapping for canonical rows in the dark owner-safe V2 outbox candidate. */ -final class CanonicalOutboxEventRowMapper { - - private CanonicalOutboxEventRowMapper() {} - - static String compatibilityPayload(ValidatedIntegrationEvent event) { - return strictUtf8(event.envelopeBytes(), event.eventId().value()); - } - - static ValidatedIntegrationEvent read(ResultSet resultSet) throws SQLException { - String eventId = resultSet.getString("event_id"); - byte[] envelopeBytes = resultSet.getBytes("envelope_bytes"); - Integer envelopeVersion = resultSet.getObject("envelope_version", Integer.class); - String tenantScope = resultSet.getString("tenant_scope"); - String schemaSetHash = resultSet.getString("schema_set_hash"); - String envelopeSha256 = resultSet.getString("envelope_sha256"); - String envelopeSchemaHash = resultSet.getString("envelope_schema_hash"); - String payloadSchemaHash = resultSet.getString("payload_schema_hash"); - String contractCatalogRevision = resultSet.getString("contract_catalog_revision"); - String destinationBindingRevision = resultSet.getString("destination_binding_revision"); - - if (envelopeBytes == null - || envelopeVersion == null - || tenantScope == null - || schemaSetHash == null - || envelopeSha256 == null - || envelopeSchemaHash == null - || payloadSchemaHash == null - || contractCatalogRevision == null - || destinationBindingRevision == null) { - throw new IllegalStateException( - "outbox V2 row is pre-canonical or incomplete for eventId=" + eventId); - } - - String payload = resultSet.getString("payload"); - String payloadDigest = resultSet.getString("payload_digest"); - String compatibilityPayload = strictUtf8(envelopeBytes, eventId); - if (!compatibilityPayload.equals(payload) || !envelopeSha256.equals(payloadDigest)) { - throw new IllegalStateException( - "canonical outbox V2 compatibility projection mismatch for eventId=" + eventId); - } - - String traceParent = resultSet.getString("trace_parent"); - if (traceParent != null) { - throw new IllegalStateException( - "canonical outbox V2 row must not invent trace context for eventId=" + eventId); - } - - String partitionKey = resultSet.getString("partition_key"); - try { - return new ValidatedIntegrationEvent( - new EventId(eventId), - new ContractId(resultSet.getString("event_type")), - envelopeVersion, - resultSet.getInt("event_schema"), - new LogicalDestinationId(resultSet.getString("logical_destination")), - new AggregateIdentity( - tenantScope, - resultSet.getString("aggregate_type"), - resultSet.getString("aggregate_id")), - new AggregateOrder( - resultSet.getLong("aggregate_version"), resultSet.getInt("event_ordinal")), - resultSet.getObject("occurred_at", OffsetDateTime.class).toInstant(), - resultSet.getString("correlation_id"), - Optional.ofNullable(resultSet.getString("causation_id")), - partitionKey, - partitionKey.getBytes(StandardCharsets.US_ASCII), - envelopeBytes, - resultSet.getString("content_type"), - digest(schemaSetHash, "schema_set_hash", eventId), - digest(envelopeSha256, "envelope_sha256", eventId), - digest(envelopeSchemaHash, "envelope_schema_hash", eventId), - digest(payloadSchemaHash, "payload_schema_hash", eventId), - contractCatalogRevision, - destinationBindingRevision); - } catch (IllegalArgumentException exception) { - throw new IllegalStateException( - "invalid canonical outbox V2 metadata for eventId=" + eventId, exception); - } - } - - private static Sha256 digest(String hex, String field, String eventId) { - try { - return new Sha256(HexFormat.of().parseHex(hex)); - } catch (IllegalArgumentException exception) { - throw new IllegalStateException( - "invalid " + field + " for canonical outbox V2 eventId=" + eventId, exception); - } - } - - private static String strictUtf8(byte[] bytes, String eventId) { - try { - String decoded = - StandardCharsets.UTF_8 - .newDecoder() - .onMalformedInput(CodingErrorAction.REPORT) - .onUnmappableCharacter(CodingErrorAction.REPORT) - .decode(ByteBuffer.wrap(bytes)) - .toString(); - if (!Arrays.equals(decoded.getBytes(StandardCharsets.UTF_8), bytes)) { - throw new IllegalArgumentException( - "canonical envelope UTF-8 projection does not round-trip for eventId=" + eventId); - } - return decoded; - } catch (CharacterCodingException exception) { - throw new IllegalArgumentException( - "canonical envelope must be valid UTF-8 for eventId=" + eventId, exception); - } - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/outbox/PostgreSqlImmutableOutboxAppendAdapter.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/outbox/PostgreSqlImmutableOutboxAppendAdapter.java deleted file mode 100644 index a1da6cac..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/outbox/PostgreSqlImmutableOutboxAppendAdapter.java +++ /dev/null @@ -1,376 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.postgresql.outbox; - -import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent; -import dev.caskeleton.application.outbox.v2.NewOutboxEventV2; -import dev.caskeleton.application.outbox.v2.OutboxAppendOutcome; -import dev.caskeleton.application.outbox.v2.OutboxAppendPortV2; -import dev.caskeleton.application.outbox.v2.OutboxAppendReceipt; -import dev.caskeleton.application.outbox.v2.OutboxDispatchAuthority; -import dev.caskeleton.application.outbox.v2.OutboxPublicationAuthority; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.time.Instant; -import java.time.LocalDate; -import java.time.OffsetDateTime; -import java.util.List; -import java.util.Objects; -import java.util.Optional; -import javax.sql.DataSource; -import org.springframework.jdbc.core.JdbcOperations; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.transaction.support.TransactionSynchronizationManager; - -/** - * PostgreSQL immutable outbox V2 append implementation. - * - *

The active publication control row is held {@code FOR SHARE} until the caller's transaction - * finishes. Identity and envelope inserts therefore cannot straddle an authority cutover. - * - *

Deliberately carries no Spring stereotype. Both composition roots component-scan {@code - * dev.caskeleton.adapter}, so a {@code @Repository} here became a bean in every deployment — - * including one running H2, which has no migration tree at all, and one that never applied {@code - * db/migration/jpa/outbox-storage}. The bean existed, its tables did not, and the failure arrived - * either at the first call as vendor-specific SQL against a missing relation, or at startup under - * {@code ddl-auto=validate}. A candidate implementation that nobody selected should not be - * composed. - * - *

Composing it is a configuration's decision: the PostgreSQL provider must be selected, the - * capability enabled, and {@code jpa-outbox-storage-v2} promoted to ACTIVE. Until such a - * configuration exists, the integration tests construct it directly. - */ -public class PostgreSqlImmutableOutboxAppendAdapter implements OutboxAppendPortV2 { - - private static final String ACTIVE_CAPABILITY_SQL = - """ - select count(*) - from capability_schema_registry - where capability_id = 'jpa-outbox-storage-v2' - and core_epoch = 1 - and feature_revision = 2 - and lifecycle_state = 'ACTIVE' - """; - - private static final String LOCK_CONTROL_SQL = - """ - select control.active_epoch, control.active_authority - from outbox_publication_control_v2 control - join outbox_publication_cutover_v2 cutover - on cutover.scope_id = control.scope_id - and cutover.active_epoch = control.active_epoch - and cutover.active_authority = control.active_authority - where control.scope_id = 'PRIMARY' - and control.state = 'ACTIVE' - for share of control - """; - - private static final String INSERT_IDENTITY_SQL = - """ - insert into outbox_event_identity_v2 ( - event_id, - tenant_scope, - aggregate_type, - aggregate_id, - aggregate_version, - event_ordinal, - retention_bucket, - created_at - ) - select ?, ?, ?, ?, ?, ?, (db_now at time zone 'UTC')::date, db_now - from (select clock_timestamp() as db_now) authority - on conflict do nothing - returning retention_bucket, created_at - """; - - private static final String INSERT_EVENT_SQL = - """ - insert into outbox_event_log_v2 ( - retention_bucket, - event_id, - aggregate_type, - aggregate_id, - aggregate_version, - event_ordinal, - event_type, - event_schema, - logical_destination, - partition_key, - publication_epoch, - dispatch_authority, - content_type, - correlation_id, - causation_id, - occurred_at, - payload, - payload_digest, - trace_parent, - created_at, - tenant_scope, - envelope_version, - envelope_bytes, - schema_set_hash, - envelope_sha256, - envelope_schema_hash, - payload_schema_hash, - contract_catalog_revision, - destination_binding_revision - ) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, null, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - """; - - private static final String FIND_EVENT_SQL = - """ - select identity.event_id, - identity.aggregate_type, - identity.aggregate_id, - identity.aggregate_version, - identity.event_ordinal, - identity.retention_bucket, - event.event_type, - event.event_schema, - event.logical_destination, - event.partition_key, - event.publication_epoch, - event.dispatch_authority, - event.content_type, - event.correlation_id, - event.causation_id, - event.occurred_at, - event.payload, - event.payload_digest, - event.trace_parent, - event.tenant_scope, - event.envelope_version, - event.envelope_bytes, - event.schema_set_hash, - event.envelope_sha256, - event.envelope_schema_hash, - event.payload_schema_hash, - event.contract_catalog_revision, - event.destination_binding_revision - from outbox_event_identity_v2 identity - left join outbox_event_log_v2 event - on event.event_id = identity.event_id - and event.retention_bucket = identity.retention_bucket - where identity.event_id = ? - """; - - private static final String FIND_ORDERING_IDENTITY_SQL = - """ - select event_id - from outbox_event_identity_v2 - where tenant_scope = ? - and aggregate_type = ? - and aggregate_id = ? - and aggregate_version = ? - and event_ordinal = ? - """; - - private final DataSource dataSource; - private final JdbcOperations jdbc; - - public PostgreSqlImmutableOutboxAppendAdapter(DataSource dataSource) { - this(dataSource, new JdbcTemplate(dataSource)); - } - - PostgreSqlImmutableOutboxAppendAdapter(DataSource dataSource, JdbcOperations jdbc) { - this.dataSource = Objects.requireNonNull(dataSource, "dataSource"); - this.jdbc = Objects.requireNonNull(jdbc, "jdbc"); - } - - @Override - public OutboxAppendReceipt append(NewOutboxEventV2 event) { - Objects.requireNonNull(event, "event"); - requireSameResourcePrimaryWriteTransaction(); - ValidatedIntegrationEvent canonical = event.event(); - String compatibilityPayload = CanonicalOutboxEventRowMapper.compatibilityPayload(canonical); - requireActiveCapability(); - PublicationControl control = lockPublicationControl(); - OutboxDispatchAuthority dispatchAuthority = dispatchAuthority(control.authority()); - - List inserted = - jdbc.query( - INSERT_IDENTITY_SQL, - (resultSet, rowNumber) -> - new IdentityInsert( - resultSet.getObject("retention_bucket", LocalDate.class), - resultSet.getObject("created_at", OffsetDateTime.class).toInstant()), - event.eventId(), - event.event().aggregate().tenantScope(), - event.aggregateType(), - event.aggregateId(), - event.aggregateVersion(), - event.eventOrdinal()); - - if (inserted.isEmpty()) { - return classifyExisting(event); - } - IdentityInsert identity = inserted.getFirst(); - int envelopeInserted = - jdbc.update( - INSERT_EVENT_SQL, - identity.retentionBucket(), - event.eventId(), - event.aggregateType(), - event.aggregateId(), - event.aggregateVersion(), - event.eventOrdinal(), - event.eventType(), - event.eventSchema(), - event.logicalDestination(), - event.partitionKey(), - control.activeEpoch(), - dispatchAuthority.name(), - event.contentType(), - event.correlationId(), - event.causationId(), - OffsetDateTime.ofInstant(event.occurredAt(), java.time.ZoneOffset.UTC), - compatibilityPayload, - canonical.envelopeSha256().toString(), - OffsetDateTime.ofInstant(identity.createdAt(), java.time.ZoneOffset.UTC), - canonical.aggregate().tenantScope(), - canonical.envelopeVersion(), - canonical.envelopeBytes(), - canonical.schemaSetHash().toString(), - canonical.envelopeSha256().toString(), - canonical.envelopeSchemaHash().toString(), - canonical.payloadSchemaHash().toString(), - canonical.contractCatalogRevision(), - canonical.destinationBindingRevision()); - if (envelopeInserted != 1) { - throw new IllegalStateException("immutable outbox event envelope insert affected no row"); - } - return new OutboxAppendReceipt( - OutboxAppendOutcome.APPENDED, - event.eventId(), - identity.retentionBucket(), - control.activeEpoch(), - dispatchAuthority); - } - - private OutboxAppendReceipt classifyExisting(NewOutboxEventV2 requested) { - Optional byId = findEvent(requested.eventId()); - if (byId.isPresent()) { - StoredEvent stored = byId.get(); - OutboxAppendOutcome outcome = - sameIntent(stored, requested) - ? OutboxAppendOutcome.ALREADY_APPENDED_SAME_EVENT - : OutboxAppendOutcome.EVENT_ID_CONFLICT; - return new OutboxAppendReceipt( - outcome, - stored.eventId(), - stored.retentionBucket(), - stored.publicationEpoch(), - stored.dispatchAuthority()); - } - - List orderingOwner = - jdbc.query( - FIND_ORDERING_IDENTITY_SQL, - (resultSet, rowNumber) -> resultSet.getString("event_id"), - requested.event().aggregate().tenantScope(), - requested.aggregateType(), - requested.aggregateId(), - requested.aggregateVersion(), - requested.eventOrdinal()); - if (!orderingOwner.isEmpty()) { - PublicationControl control = lockPublicationControl(); - return new OutboxAppendReceipt( - OutboxAppendOutcome.AGGREGATE_ORDER_CONFLICT, - requested.eventId(), - currentRetentionBucket(), - control.activeEpoch(), - dispatchAuthority(control.authority())); - } - throw new IllegalStateException( - "outbox identity insert lost without an event-ID or aggregate-order conflict"); - } - - private Optional findEvent(String eventId) { - List rows = jdbc.query(FIND_EVENT_SQL, this::mapStoredEvent, eventId); - if (rows.size() > 1) { - throw new IllegalStateException("multiple immutable outbox identities for one event ID"); - } - return rows.stream().findFirst(); - } - - private StoredEvent mapStoredEvent(ResultSet resultSet, int rowNumber) throws SQLException { - String dispatch = resultSet.getString("dispatch_authority"); - if (dispatch == null) { - throw new IllegalStateException( - "outbox identity exists without its same-transaction immutable envelope"); - } - return new StoredEvent( - CanonicalOutboxEventRowMapper.read(resultSet), - resultSet.getObject("retention_bucket", LocalDate.class), - resultSet.getLong("publication_epoch"), - OutboxDispatchAuthority.valueOf(dispatch)); - } - - private PublicationControl lockPublicationControl() { - List rows = - jdbc.query( - LOCK_CONTROL_SQL, - (resultSet, rowNumber) -> - new PublicationControl( - resultSet.getLong("active_epoch"), - OutboxPublicationAuthority.valueOf(resultSet.getString("active_authority")))); - if (rows.size() != 1) { - throw new IllegalStateException( - "outbox publication control has no exact active immutable sentinel"); - } - return rows.getFirst(); - } - - private LocalDate currentRetentionBucket() { - return jdbc.queryForObject( - "select (clock_timestamp() at time zone 'UTC')::date", LocalDate.class); - } - - private void requireActiveCapability() { - Integer active = jdbc.queryForObject(ACTIVE_CAPABILITY_SQL, Integer.class); - if (active == null || active != 1) { - throw new IllegalStateException( - "jpa-outbox-storage-v2 is not active at core epoch 1/revision 2"); - } - } - - private void requireSameResourcePrimaryWriteTransaction() { - if (!TransactionSynchronizationManager.isActualTransactionActive()) { - throw new IllegalStateException( - "outbox V2 append requires an active primary write transaction"); - } - if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { - throw new IllegalStateException("outbox V2 append rejects a read-only transaction"); - } - if (!TransactionSynchronizationManager.hasResource(dataSource)) { - throw new IllegalStateException( - "outbox V2 append transaction is not bound to the adapter datasource"); - } - } - - private static OutboxDispatchAuthority dispatchAuthority(OutboxPublicationAuthority authority) { - return switch (authority) { - case LEGACY_POLLING -> OutboxDispatchAuthority.LEGACY_SHADOW; - case POLLING_V2 -> OutboxDispatchAuthority.POLLING_V2; - case CDC -> OutboxDispatchAuthority.CDC; - }; - } - - private static boolean sameIntent(StoredEvent stored, NewOutboxEventV2 requested) { - return stored.event().equals(requested.event()); - } - - private record PublicationControl(long activeEpoch, OutboxPublicationAuthority authority) {} - - private record IdentityInsert(LocalDate retentionBucket, Instant createdAt) {} - - private record StoredEvent( - ValidatedIntegrationEvent event, - LocalDate retentionBucket, - long publicationEpoch, - OutboxDispatchAuthority dispatchAuthority) { - - String eventId() { - return event.eventId().value(); - } - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/outbox/PostgreSqlPollingDeliveryAdapter.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/outbox/PostgreSqlPollingDeliveryAdapter.java deleted file mode 100644 index 13455905..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/outbox/PostgreSqlPollingDeliveryAdapter.java +++ /dev/null @@ -1,549 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.postgresql.outbox; - -import dev.caskeleton.application.outbox.v2.ClaimedOutboxDelivery; -import dev.caskeleton.application.outbox.v2.OutboxDeliveryClaimRequest; -import dev.caskeleton.application.outbox.v2.OutboxDeliveryOwner; -import dev.caskeleton.application.outbox.v2.OutboxDeliveryTransition; -import dev.caskeleton.application.outbox.v2.OutboxDeliveryTransitionOutcome; -import dev.caskeleton.application.outbox.v2.OutboxPollingDeliveryPortV2; -import java.nio.ByteBuffer; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.SecureRandom; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.time.Instant; -import java.time.LocalDate; -import java.time.OffsetDateTime; -import java.time.ZoneOffset; -import java.util.HexFormat; -import java.util.List; -import java.util.Objects; -import java.util.regex.Pattern; -import javax.sql.DataSource; -import org.springframework.jdbc.core.JdbcOperations; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.transaction.support.TransactionSynchronizationManager; - -/** - * PostgreSQL {@code SKIP LOCKED} polling relay with strict aggregate order and owner-safe CAS. - * - *

Deliberately carries no Spring stereotype. Both composition roots component-scan {@code - * dev.caskeleton.adapter}, so a {@code @Repository} here became a bean in every deployment — - * including one running H2, which has no migration tree at all, and one that never applied {@code - * db/migration/jpa/outbox-polling}. The bean existed, its tables did not, and the failure arrived - * either at the first call as vendor-specific SQL against a missing relation, or at startup under - * {@code ddl-auto=validate}. A candidate implementation that nobody selected should not be - * composed. - * - *

Composing it is a configuration's decision: the PostgreSQL provider must be selected, the - * capability enabled, and {@code jpa-outbox-polling-delivery-v2} promoted to ACTIVE. Until such a - * configuration exists, the integration tests construct it directly. - */ -public class PostgreSqlPollingDeliveryAdapter implements OutboxPollingDeliveryPortV2 { - - private static final Pattern ERROR_CODE = Pattern.compile("[A-Z][A-Z0-9_.-]{0,63}"); - - private static final String ACTIVE_CAPABILITIES_SQL = - """ - select count(*) - from capability_schema_registry - where capability_id in ( - 'jpa-outbox-storage-v2', - 'jpa-outbox-polling-delivery-v2' - ) - and core_epoch = 1 - and feature_revision = 2 - and lifecycle_state = 'ACTIVE' - """; - - private static final String CLAIM_SQL = - """ - with authority as ( - select control.active_epoch - from outbox_publication_control_v2 control - join outbox_publication_cutover_v2 cutover - on cutover.scope_id = control.scope_id - and cutover.active_epoch = control.active_epoch - and cutover.active_authority = control.active_authority - where control.scope_id = 'PRIMARY' - and control.state = 'ACTIVE' - and control.active_authority = 'POLLING_V2' - for share of control - ), - db_clock as ( - select clock_timestamp() as db_now - ), - eligible as ( - select delivery.retention_bucket, delivery.event_id, delivery.destination - from outbox_delivery_v2 delivery - join outbox_event_log_v2 event - on event.retention_bucket = delivery.retention_bucket - and event.event_id = delivery.event_id - cross join authority - cross join db_clock - where delivery.destination = ? - and delivery.publication_epoch = authority.active_epoch - and ( - (delivery.state in ('PENDING', 'RETRY_WAIT') - and delivery.next_attempt_at <= db_clock.db_now) - or - (delivery.state = 'CLAIMED' - and delivery.claim_until <= db_clock.db_now) - ) - and not exists ( - select 1 - from outbox_delivery_v2 prior_delivery - join outbox_event_log_v2 prior_event - on prior_event.retention_bucket = prior_delivery.retention_bucket - and prior_event.event_id = prior_delivery.event_id - where prior_delivery.destination = delivery.destination - and prior_event.tenant_scope = event.tenant_scope - and prior_event.aggregate_type = event.aggregate_type - and prior_event.aggregate_id = event.aggregate_id - and ( - prior_event.aggregate_version, - prior_event.event_ordinal - ) < ( - event.aggregate_version, - event.event_ordinal - ) - and prior_delivery.state <> 'PUBLISHED' - ) - order by event.created_at, event.event_id - for update of delivery skip locked - limit ? - ), - claimed as ( - update outbox_delivery_v2 delivery - set state = 'CLAIMED', - claim_owner = ?, - claim_token = ?, - claim_until = db_clock.db_now + (? * interval '1 millisecond'), - attempt = delivery.attempt + 1, - version = delivery.version + 1, - updated_at = db_clock.db_now - from eligible, db_clock - where delivery.retention_bucket = eligible.retention_bucket - and delivery.event_id = eligible.event_id - and delivery.destination = eligible.destination - returning delivery.* - ) - select claimed.retention_bucket, - claimed.event_id, - claimed.destination, - claimed.claim_owner, - claimed.claim_token, - claimed.attempt, - claimed.version, - claimed.publication_epoch, - claimed.created_at as delivery_created_at, - event.created_at as event_created_at, - event.event_type, - event.event_schema, - event.logical_destination, - event.aggregate_type, - event.aggregate_id, - event.aggregate_version, - event.event_ordinal, - event.partition_key, - event.content_type, - event.correlation_id, - event.causation_id, - event.occurred_at, - event.payload, - event.payload_digest, - event.trace_parent, - event.tenant_scope, - event.envelope_version, - event.envelope_bytes, - event.schema_set_hash, - event.envelope_sha256, - event.envelope_schema_hash, - event.payload_schema_hash, - event.contract_catalog_revision, - event.destination_binding_revision - from claimed - join outbox_event_log_v2 event - on event.retention_bucket = claimed.retention_bucket - and event.event_id = claimed.event_id - order by event.created_at, event.event_id - """; - - private static final String MARK_PUBLISHED_SQL = - """ - update outbox_delivery_v2 delivery - set state = 'PUBLISHED', - claim_owner = null, - claim_token = null, - claim_until = null, - last_operation_id = ?, - last_result_digest = ?, - published_at = clock_timestamp(), - version = version + 1, - updated_at = clock_timestamp() - where retention_bucket = ? - and event_id = ? - and destination = ? - and state = 'CLAIMED' - and claim_owner = ? - and claim_token = ? - and attempt = ? - and version = ? - and publication_epoch = ? - and exists ( - select 1 - from outbox_publication_control_v2 control - join outbox_publication_cutover_v2 cutover - on cutover.scope_id = control.scope_id - and cutover.active_epoch = control.active_epoch - and cutover.active_authority = control.active_authority - where control.scope_id = 'PRIMARY' - and control.state = 'ACTIVE' - and control.active_authority = 'POLLING_V2' - and control.active_epoch = delivery.publication_epoch - ) - """; - - private static final String MARK_RETRY_SQL = - """ - update outbox_delivery_v2 delivery - set state = 'RETRY_WAIT', - claim_owner = null, - claim_token = null, - claim_until = null, - next_attempt_at = ?, - last_error_code = ?, - last_operation_id = ?, - last_result_digest = ?, - version = version + 1, - updated_at = clock_timestamp() - where retention_bucket = ? - and event_id = ? - and destination = ? - and state = 'CLAIMED' - and claim_owner = ? - and claim_token = ? - and attempt = ? - and version = ? - and publication_epoch = ? - and exists ( - select 1 - from outbox_publication_control_v2 control - where control.scope_id = 'PRIMARY' - and control.state = 'ACTIVE' - and control.active_authority = 'POLLING_V2' - and control.active_epoch = delivery.publication_epoch - ) - """; - - private static final String MARK_DEAD_SQL = - """ - update outbox_delivery_v2 delivery - set state = 'DEAD', - claim_owner = null, - claim_token = null, - claim_until = null, - last_error_code = ?, - last_operation_id = ?, - last_result_digest = ?, - dead_at = clock_timestamp(), - version = version + 1, - updated_at = clock_timestamp() - where retention_bucket = ? - and event_id = ? - and destination = ? - and state = 'CLAIMED' - and claim_owner = ? - and claim_token = ? - and attempt = ? - and version = ? - and publication_epoch = ? - and exists ( - select 1 - from outbox_publication_control_v2 control - where control.scope_id = 'PRIMARY' - and control.state = 'ACTIVE' - and control.active_authority = 'POLLING_V2' - and control.active_epoch = delivery.publication_epoch - ) - """; - - private static final String INSPECT_SQL = - """ - select delivery.state, - delivery.claim_owner, - delivery.claim_token, - delivery.attempt, - delivery.version, - delivery.publication_epoch, - delivery.last_operation_id, - delivery.last_result_digest, - control.active_epoch, - control.active_authority, - control.state as authority_state - from outbox_delivery_v2 delivery - cross join outbox_publication_control_v2 control - where delivery.retention_bucket = ? - and delivery.event_id = ? - and delivery.destination = ? - and control.scope_id = 'PRIMARY' - """; - - private final DataSource dataSource; - private final JdbcOperations jdbc; - private final SecureRandom secureRandom; - - public PostgreSqlPollingDeliveryAdapter(DataSource dataSource) { - this(dataSource, new JdbcTemplate(dataSource), new SecureRandom()); - } - - PostgreSqlPollingDeliveryAdapter( - DataSource dataSource, JdbcOperations jdbc, SecureRandom secureRandom) { - this.dataSource = Objects.requireNonNull(dataSource, "dataSource"); - this.jdbc = Objects.requireNonNull(jdbc, "jdbc"); - this.secureRandom = Objects.requireNonNull(secureRandom, "secureRandom"); - } - - @Override - public List claimBatch(OutboxDeliveryClaimRequest request) { - Objects.requireNonNull(request, "request"); - requireSameResourcePrimaryWriteTransaction(); - requireActiveCapabilities(); - String claimToken = newClaimToken(); - return jdbc.query( - CLAIM_SQL, - this::mapClaim, - request.destination(), - request.batchSize(), - request.claimOwner(), - claimToken, - request.claimLease().toMillis()); - } - - @Override - public OutboxDeliveryTransitionOutcome markPublished(OutboxDeliveryTransition transition) { - Objects.requireNonNull(transition, "transition"); - requireSameResourcePrimaryWriteTransaction(); - String digest = transitionDigest("PUBLISHED", transition, null); - OutboxDeliveryOwner owner = transition.owner(); - int updated = - jdbc.update( - MARK_PUBLISHED_SQL, - transition.operationId().value(), - digest, - owner.retentionBucket(), - owner.eventId(), - owner.destination(), - owner.claimOwner(), - owner.claimToken(), - owner.attempt(), - owner.version(), - owner.publicationEpoch()); - return updated == 1 - ? OutboxDeliveryTransitionOutcome.PUBLISHED - : classifyFailedTransition(transition, digest); - } - - @Override - public OutboxDeliveryTransitionOutcome markRetryable( - OutboxDeliveryTransition transition, Instant nextAttemptAt, String errorCode) { - Objects.requireNonNull(transition, "transition"); - Objects.requireNonNull(nextAttemptAt, "nextAttemptAt"); - requireErrorCode(errorCode); - requireSameResourcePrimaryWriteTransaction(); - String digest = transitionDigest("RETRY_WAIT", transition, errorCode); - OutboxDeliveryOwner owner = transition.owner(); - int updated = - jdbc.update( - MARK_RETRY_SQL, - OffsetDateTime.ofInstant(nextAttemptAt, ZoneOffset.UTC), - errorCode, - transition.operationId().value(), - digest, - owner.retentionBucket(), - owner.eventId(), - owner.destination(), - owner.claimOwner(), - owner.claimToken(), - owner.attempt(), - owner.version(), - owner.publicationEpoch()); - return updated == 1 - ? OutboxDeliveryTransitionOutcome.RETRY_SCHEDULED - : classifyFailedTransition(transition, digest); - } - - @Override - public OutboxDeliveryTransitionOutcome markDead( - OutboxDeliveryTransition transition, String errorCode) { - Objects.requireNonNull(transition, "transition"); - requireErrorCode(errorCode); - requireSameResourcePrimaryWriteTransaction(); - String digest = transitionDigest("DEAD", transition, errorCode); - OutboxDeliveryOwner owner = transition.owner(); - int updated = - jdbc.update( - MARK_DEAD_SQL, - errorCode, - transition.operationId().value(), - digest, - owner.retentionBucket(), - owner.eventId(), - owner.destination(), - owner.claimOwner(), - owner.claimToken(), - owner.attempt(), - owner.version(), - owner.publicationEpoch()); - return updated == 1 - ? OutboxDeliveryTransitionOutcome.DEAD - : classifyFailedTransition(transition, digest); - } - - private ClaimedOutboxDelivery mapClaim(ResultSet resultSet, int rowNumber) throws SQLException { - OutboxDeliveryOwner owner = - new OutboxDeliveryOwner( - resultSet.getObject("retention_bucket", LocalDate.class), - resultSet.getString("event_id"), - resultSet.getString("destination"), - resultSet.getString("claim_owner"), - resultSet.getString("claim_token"), - resultSet.getInt("attempt"), - resultSet.getLong("version"), - resultSet.getLong("publication_epoch")); - var event = CanonicalOutboxEventRowMapper.read(resultSet); - if (!owner.destination().equals(event.logicalDestinationId().value())) { - throw new IllegalStateException( - "claimed outbox destination does not match canonical event for eventId=" - + owner.eventId()); - } - return new ClaimedOutboxDelivery( - owner, - event, - resultSet.getObject("event_created_at", OffsetDateTime.class).toInstant(), - resultSet.getObject("delivery_created_at", OffsetDateTime.class).toInstant()); - } - - private OutboxDeliveryTransitionOutcome classifyFailedTransition( - OutboxDeliveryTransition transition, String requestedDigest) { - OutboxDeliveryOwner owner = transition.owner(); - List rows = - jdbc.query( - INSPECT_SQL, - (resultSet, rowNumber) -> - new DeliveryState( - resultSet.getString("state"), - resultSet.getString("claim_owner"), - resultSet.getString("claim_token"), - resultSet.getInt("attempt"), - resultSet.getLong("version"), - resultSet.getLong("publication_epoch"), - resultSet.getString("last_operation_id"), - resultSet.getString("last_result_digest"), - resultSet.getLong("active_epoch"), - resultSet.getString("active_authority"), - resultSet.getString("authority_state")), - owner.retentionBucket(), - owner.eventId(), - owner.destination()); - if (rows.isEmpty()) { - return OutboxDeliveryTransitionOutcome.ABSENT; - } - DeliveryState row = rows.getFirst(); - if (transition.operationId().value().equals(row.lastOperationId())) { - return requestedDigest.equals(row.lastResultDigest()) - ? OutboxDeliveryTransitionOutcome.ALREADY_APPLIED_SAME_OPERATION - : OutboxDeliveryTransitionOutcome.RESULT_CONFLICT; - } - if (!"ACTIVE".equals(row.authorityState()) - || !"POLLING_V2".equals(row.activeAuthority()) - || row.activeEpoch() != row.publicationEpoch()) { - return OutboxDeliveryTransitionOutcome.AUTHORITY_MISMATCH; - } - if (!Objects.equals(owner.claimOwner(), row.claimOwner()) - || !Objects.equals(owner.claimToken(), row.claimToken()) - || owner.attempt() != row.attempt()) { - return OutboxDeliveryTransitionOutcome.NOT_OWNER; - } - if (!"CLAIMED".equals(row.state())) { - return OutboxDeliveryTransitionOutcome.NOT_CLAIMED; - } - if (owner.version() != row.version()) { - return OutboxDeliveryTransitionOutcome.STALE_VERSION; - } - return OutboxDeliveryTransitionOutcome.RESULT_CONFLICT; - } - - private void requireActiveCapabilities() { - Integer active = jdbc.queryForObject(ACTIVE_CAPABILITIES_SQL, Integer.class); - if (active == null || active != 2) { - throw new IllegalStateException( - "outbox storage and polling delivery V2 must both be active at revision 2"); - } - } - - private void requireSameResourcePrimaryWriteTransaction() { - if (!TransactionSynchronizationManager.isActualTransactionActive() - || TransactionSynchronizationManager.isCurrentTransactionReadOnly() - || !TransactionSynchronizationManager.hasResource(dataSource)) { - throw new IllegalStateException( - "polling delivery mutation requires the adapter datasource primary write transaction"); - } - } - - private String newClaimToken() { - byte[] bytes = new byte[32]; - secureRandom.nextBytes(bytes); - return HexFormat.of().formatHex(bytes); - } - - private static void requireErrorCode(String errorCode) { - if (errorCode == null || !ERROR_CODE.matcher(errorCode).matches()) { - throw new IllegalArgumentException( - "error code must be 1-64 uppercase ASCII letters, digits, dot, dash, or underscore"); - } - } - - private static String transitionDigest( - String kind, OutboxDeliveryTransition transition, String detail) { - OutboxDeliveryOwner owner = transition.owner(); - return digestFields( - kind, - transition.operationId().value(), - owner.eventId(), - owner.destination(), - owner.claimToken(), - Integer.toString(owner.attempt()), - Long.toString(owner.version()), - Objects.toString(detail, "")); - } - - static String digestFields(String... fields) { - try { - MessageDigest digest = MessageDigest.getInstance("SHA-256"); - for (String field : fields) { - byte[] bytes = Objects.toString(field, "").getBytes(StandardCharsets.UTF_8); - digest.update(ByteBuffer.allocate(Integer.BYTES).putInt(bytes.length).array()); - digest.update(bytes); - } - return HexFormat.of().formatHex(digest.digest()); - } catch (NoSuchAlgorithmException exception) { - throw new IllegalStateException("SHA-256 unavailable", exception); - } - } - - private record DeliveryState( - String state, - String claimOwner, - String claimToken, - int attempt, - long version, - long publicationEpoch, - String lastOperationId, - String lastResultDigest, - long activeEpoch, - String activeAuthority, - String authorityState) {} -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/range/PgRangeJdbcType.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/range/PgRangeJdbcType.java deleted file mode 100644 index a8b05b03..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/range/PgRangeJdbcType.java +++ /dev/null @@ -1,78 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.postgresql.range; - -import java.sql.CallableStatement; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Types; -import org.hibernate.type.descriptor.ValueBinder; -import org.hibernate.type.descriptor.ValueExtractor; -import org.hibernate.type.descriptor.WrapperOptions; -import org.hibernate.type.descriptor.java.JavaType; -import org.hibernate.type.descriptor.jdbc.BasicBinder; -import org.hibernate.type.descriptor.jdbc.BasicExtractor; -import org.hibernate.type.descriptor.jdbc.JdbcType; - -/** - * Binds and extracts a PostgreSQL range column through its literal representation (design §8.3). - * - *

The value is sent as {@link Types#OTHER} carrying the range literal. That is what lets the - * server parse it as {@code tstzrange}, {@code daterange}, or any other range type without this - * class having to know which one the column is — the range literal is the same shape for - * all of them, and the column's declared type decides the parse. - * - *

Sending it as a plain string instead would make the server see {@code text}, and the insert - * fails with a cast error rather than storing a range. - */ -public class PgRangeJdbcType implements JdbcType { - - private static final long serialVersionUID = 1L; - - /** The shared instance; the type is stateless. */ - public static final PgRangeJdbcType INSTANCE = new PgRangeJdbcType(); - - @Override - public int getJdbcTypeCode() { - return Types.OTHER; - } - - @Override - public ValueBinder getBinder(JavaType javaType) { - return new BasicBinder(javaType, this) { - @Override - protected void doBind(PreparedStatement st, X value, int index, WrapperOptions options) - throws SQLException { - st.setObject(index, javaType.unwrap(value, String.class, options), Types.OTHER); - } - - @Override - protected void doBind(CallableStatement st, X value, String name, WrapperOptions options) - throws SQLException { - st.setObject(name, javaType.unwrap(value, String.class, options), Types.OTHER); - } - }; - } - - @Override - public ValueExtractor getExtractor(JavaType javaType) { - return new BasicExtractor(javaType, this) { - @Override - protected X doExtract(ResultSet rs, int paramIndex, WrapperOptions options) - throws SQLException { - return javaType.wrap(rs.getString(paramIndex), options); - } - - @Override - protected X doExtract(CallableStatement statement, int index, WrapperOptions options) - throws SQLException { - return javaType.wrap(statement.getString(index), options); - } - - @Override - protected X doExtract(CallableStatement statement, String name, WrapperOptions options) - throws SQLException { - return javaType.wrap(statement.getString(name), options); - } - }; - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/range/PostgreSqlRangeQuerySupport.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/range/PostgreSqlRangeQuerySupport.java deleted file mode 100644 index 84dbb0b9..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/range/PostgreSqlRangeQuerySupport.java +++ /dev/null @@ -1,64 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.postgresql.range; - -import jakarta.persistence.EntityManager; -import jakarta.persistence.Query; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; - -/** - * Runs registered range overlap and containment queries with the range bound as a parameter (design - * §8.3). - * - *

Overlap ({@code &&}) and containment ({@code @>}) are separate registrations rather than a - * flag, because they mean different things and are usually served by different predicates on - * different indexes. Collapsing them into one parameterised operator would put an operator name - * into the SQL text from a caller-supplied value. - * - * @param the endpoint type - */ -public final class PostgreSqlRangeQuerySupport> { - - /** The parameter name every registered range statement binds. */ - public static final String RANGE_PARAMETER = "range"; - - private final EntityManager entityManager; - private final PgRangeCodec codec; - private final Map registeredStatements; - - /** - * @param registeredStatements the fixed SQL for each registered range query, keyed by query name - */ - public PostgreSqlRangeQuerySupport( - EntityManager entityManager, - PgRangeCodec codec, - Map registeredStatements) { - this.entityManager = Objects.requireNonNull(entityManager, "entityManager"); - this.codec = Objects.requireNonNull(codec, "codec"); - this.registeredStatements = - Map.copyOf(Objects.requireNonNull(registeredStatements, "registeredStatements")); - } - - /** - * Runs the registered statement {@code queryName} with {@code range} bound as its parameter. - * - * @throws IllegalArgumentException when the query name is not registered - */ - public List execute(String queryName, PgRange range) { - Objects.requireNonNull(queryName, "queryName"); - Objects.requireNonNull(range, "range"); - String sql = registeredStatements.get(queryName); - if (sql == null) { - throw new IllegalArgumentException("unregistered range query: " + queryName); - } - Query query = entityManager.createNativeQuery(sql); - query.setParameter(RANGE_PARAMETER, codec.format(range)); - return query.getResultList(); - } - - /** The registered range query names. */ - public Set registeredQueries() { - return registeredStatements.keySet(); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/write/NativeWriteName.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/write/NativeWriteName.java deleted file mode 100644 index 4497dd0e..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/write/NativeWriteName.java +++ /dev/null @@ -1,25 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.postgresql.write; - -import java.util.regex.Pattern; - -/** - * The registered identity of a native write statement (design §8.3). - * - *

Native writes are registered by name so the SQL is fixed at deployment time. The name selects - * a statement; it is never part of one. - */ -public record NativeWriteName(String value) { - - private static final Pattern FORMAT = Pattern.compile("[a-z][a-z0-9.-]{2,63}"); - - public NativeWriteName { - if (value == null || !FORMAT.matcher(value).matches()) { - throw new IllegalArgumentException("invalid native write name"); - } - } - - @Override - public String toString() { - return value; - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/write/PostgreSqlUpsertExecutor.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/write/PostgreSqlUpsertExecutor.java deleted file mode 100644 index d31c9342..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/write/PostgreSqlUpsertExecutor.java +++ /dev/null @@ -1,23 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.postgresql.write; - -/** - * Executes one registered {@code INSERT ... ON CONFLICT ... RETURNING} statement (design §8.3). - * - *

An upsert is the correct answer to a create race precisely because it makes the database - * decide. The alternative — read, branch, then write — cannot be made correct by any amount of - * application logic, because another transaction can commit between the read and the write. - * - * @param the command type carrying the bound parameter values - * @param the projected value the statement returns - */ -public interface PostgreSqlUpsertExecutor { - - /** - * Runs the registered statement for {@code operation}. - * - *

Must run inside the caller's transaction, and implementations must reconcile the Persistence - * Context afterwards: a native write is invisible to the first-level cache, so a managed entity - * loaded before the upsert is stale the moment it completes. - */ - UpsertResult execute(NativeWriteName operation, C command); -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/write/RegisteredPostgreSqlUpsertExecutor.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/write/RegisteredPostgreSqlUpsertExecutor.java deleted file mode 100644 index 145baeaa..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/write/RegisteredPostgreSqlUpsertExecutor.java +++ /dev/null @@ -1,83 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.postgresql.write; - -import jakarta.persistence.EntityManager; -import jakarta.persistence.Query; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; - -/** - * Runs registered {@code INSERT ... ON CONFLICT ... RETURNING} statements (design §8.3). - * - *

Two things happen around the statement that are easy to leave out and expensive to leave out. - * - *

First, the Persistence Context is flushed before the write. A native statement goes straight - * to the database, so any pending managed change that has not been flushed would be written - * after the upsert and would overwrite it. - * - *

Second, the context is cleared afterwards. The upsert changed rows the context may already - * hold, and Hibernate has no way to know: a managed entity loaded before the call would keep - * serving pre-upsert values, and flushing it later would write them back. - * - * @param the command type carrying the values to bind - * @param the projected value the statement returns - */ -public final class RegisteredPostgreSqlUpsertExecutor - implements PostgreSqlUpsertExecutor { - - private final EntityManager entityManager; - private final Map> statements; - - public RegisteredPostgreSqlUpsertExecutor( - EntityManager entityManager, - Map> statements) { - this.entityManager = Objects.requireNonNull(entityManager, "entityManager"); - this.statements = Map.copyOf(Objects.requireNonNull(statements, "statements")); - } - - @Override - public UpsertResult execute(NativeWriteName operation, C command) { - Objects.requireNonNull(operation, "operation"); - RegisteredUpsertStatement statement = statements.get(operation); - if (statement == null) { - throw new IllegalArgumentException("unregistered native write: " + operation.value()); - } - - entityManager.flush(); - Query query = entityManager.createNativeQuery(statement.sql()); - statement.binder().accept(query, command); - List rows = query.getResultList(); - entityManager.clear(); - - if (rows.isEmpty()) { - // ON CONFLICT DO NOTHING returns no row. The write did not happen, and reporting it as an - // update would tell the caller a row exists in a state it does not. - return UpsertResult.undetermined(null); - } - Object[] columns = toColumns(rows.get(0)); - R projection = statement.projector().apply(columns); - return new UpsertResult<>(dispositionOf(statement, columns), projection); - } - - /** The registered native write names this executor can run. */ - public Set registeredWrites() { - return statements.keySet(); - } - - private static WriteDisposition dispositionOf( - RegisteredUpsertStatement statement, Object[] columns) { - if (!statement.reportsDisposition() || statement.dispositionColumnIndex() >= columns.length) { - return WriteDisposition.UNDETERMINED; - } - Object flag = columns[statement.dispositionColumnIndex()]; - if (flag instanceof Boolean inserted) { - return inserted ? WriteDisposition.INSERTED : WriteDisposition.UPDATED; - } - return WriteDisposition.UNDETERMINED; - } - - private static Object[] toColumns(Object row) { - return row instanceof Object[] columns ? columns : new Object[] {row}; - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/write/RegisteredUpsertStatement.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/write/RegisteredUpsertStatement.java deleted file mode 100644 index b307afb6..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/write/RegisteredUpsertStatement.java +++ /dev/null @@ -1,49 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.postgresql.write; - -import jakarta.persistence.Query; -import java.util.Locale; -import java.util.Objects; -import java.util.function.BiConsumer; -import java.util.function.Function; - -/** - * One upsert registered at deployment time (design §8.3). - * - *

The SQL is fixed here; the caller supplies only values, through {@code binder}. The - * constructor refuses a statement that is not an {@code ON CONFLICT} upsert, because the whole - * point of this registry is that the conflict handling is the database's and not a read-then-write - * dance in the application. - * - * @param dispositionColumnIndex the 0-based column of a boolean "was inserted" flag, or {@code -1} - * when the statement cannot report it. PostgreSQL exposes it as {@code (xmax = 0) AS inserted} - * in the {@code RETURNING} list; a statement that omits it must report {@link - * WriteDisposition#UNDETERMINED} rather than assume one. - * @param the command type carrying the values to bind - * @param the projected value the statement returns - */ -public record RegisteredUpsertStatement( - String sql, - UpsertConflictTarget conflictTarget, - BiConsumer binder, - Function projector, - int dispositionColumnIndex) { - - public RegisteredUpsertStatement { - Objects.requireNonNull(sql, "sql"); - Objects.requireNonNull(conflictTarget, "conflictTarget"); - Objects.requireNonNull(binder, "binder"); - Objects.requireNonNull(projector, "projector"); - String normalized = sql.toLowerCase(Locale.ROOT); - if (!normalized.contains("insert into") || !normalized.contains("on conflict")) { - throw new IllegalArgumentException("a registered upsert must be an INSERT ... ON CONFLICT"); - } - if (dispositionColumnIndex < -1) { - throw new IllegalArgumentException("disposition column index must be -1 or a column index"); - } - } - - /** Whether this statement can report insert-versus-update. */ - public boolean reportsDisposition() { - return dispositionColumnIndex >= 0; - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/write/UpsertConflictTarget.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/write/UpsertConflictTarget.java deleted file mode 100644 index b58a3688..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/write/UpsertConflictTarget.java +++ /dev/null @@ -1,42 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.postgresql.write; - -import java.util.List; -import java.util.Objects; -import java.util.regex.Pattern; - -/** - * The registered conflict target and update column set of one upsert (design §8.3). - * - *

Both are fixed at registration and validated as identifiers. {@code ON CONFLICT} targets and - * column lists cannot be bound as parameters — they are part of the statement — so accepting them - * from a caller would mean building SQL from input. Registering them keeps the statement constant - * and makes the blast radius of each upsert reviewable. - * - *

An empty update column set is rejected. {@code ON CONFLICT DO UPDATE SET} with nothing to set - * is not valid SQL, and the intent it usually stands for — {@code DO NOTHING} — is a different - * statement with a different return, so it must be registered as one. - */ -public record UpsertConflictTarget(List conflictColumns, List updateColumns) { - - /** Unquoted PostgreSQL identifiers only; anything else is not a column this may target. */ - private static final Pattern IDENTIFIER = Pattern.compile("[a-z_][a-z0-9_]{0,62}"); - - public UpsertConflictTarget { - conflictColumns = List.copyOf(Objects.requireNonNull(conflictColumns, "conflictColumns")); - updateColumns = List.copyOf(Objects.requireNonNull(updateColumns, "updateColumns")); - if (conflictColumns.isEmpty()) { - throw new IllegalArgumentException("an upsert requires at least one conflict column"); - } - if (updateColumns.isEmpty()) { - throw new IllegalArgumentException("an upsert requires at least one update column"); - } - conflictColumns.forEach(UpsertConflictTarget::requireIdentifier); - updateColumns.forEach(UpsertConflictTarget::requireIdentifier); - } - - private static void requireIdentifier(String column) { - if (column == null || !IDENTIFIER.matcher(column).matches()) { - throw new IllegalArgumentException("invalid upsert column identifier: " + column); - } - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/write/UpsertResult.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/write/UpsertResult.java deleted file mode 100644 index 7ed6a25b..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/write/UpsertResult.java +++ /dev/null @@ -1,41 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.postgresql.write; - -import java.util.Objects; -import java.util.Optional; - -/** - * What one registered upsert produced (design §8.3). - * - * @param the projected value the statement returned - */ -public record UpsertResult(WriteDisposition disposition, R value) { - - public UpsertResult { - Objects.requireNonNull(disposition, "disposition"); - } - - /** A row that did not previously exist. */ - public static UpsertResult inserted(R value) { - return new UpsertResult<>(WriteDisposition.INSERTED, value); - } - - /** A row that existed and was updated by the conflict action. */ - public static UpsertResult updated(R value) { - return new UpsertResult<>(WriteDisposition.UPDATED, value); - } - - /** A statement that cannot say which happened. */ - public static UpsertResult undetermined(R value) { - return new UpsertResult<>(WriteDisposition.UNDETERMINED, value); - } - - /** The returned projection, when the statement returned one. */ - public Optional projection() { - return Optional.ofNullable(value); - } - - /** Whether the row was newly created. */ - public boolean created() { - return disposition == WriteDisposition.INSERTED; - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/write/WriteDisposition.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/write/WriteDisposition.java deleted file mode 100644 index daf7e619..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/postgresql/write/WriteDisposition.java +++ /dev/null @@ -1,20 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.postgresql.write; - -/** - * What an upsert actually did (design §8.3). - * - *

The distinction is business-visible: "created" and "already existed and was updated" usually - * emit different events, and an upsert that reports only "ok" forces the caller to run a second - * query to find out which happened — the very race the upsert was chosen to avoid. - */ -public enum WriteDisposition { - - /** The row did not exist and was inserted. */ - INSERTED, - - /** The row existed and the conflict action updated it. */ - UPDATED, - - /** The statement cannot report which happened, and the caller must not assume. */ - UNDETERMINED -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/querydsl/QuerydslJpaSupport.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/querydsl/QuerydslJpaSupport.java deleted file mode 100644 index 1e659368..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/querydsl/QuerydslJpaSupport.java +++ /dev/null @@ -1,55 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.querydsl; - -import com.querydsl.core.types.EntityPath; -import com.querydsl.core.types.Predicate; -import com.querydsl.jpa.impl.JPAQuery; -import com.querydsl.jpa.impl.JPAQueryFactory; -import dev.caskeleton.adapter.outbound.persistence.api.query.QueryName; -import java.util.Objects; - -/** - * The bounded entry point for Querydsl collection queries (design §23.2). - * - *

Querydsl is an Advanced opt-in and is {@code compileOnly} for this leaf, so the Stable runtime - * classpath never carries it. A deployment that wants it adds the artifact; one that does not is - * unaffected by the existence of this class. - * - *

Every query built here is bounded and named. The bound is checked before the query is - * assembled rather than after, so a predicate-free query never reaches the database at all, and the - * name is attached as a SQL comment so the statement is identifiable on the server. - */ -public final class QuerydslJpaSupport { - - /** The Hibernate hint that carries a comment into the generated SQL. */ - private static final String COMMENT_HINT = "org.hibernate.comment"; - - private final JPAQueryFactory queryFactory; - - public QuerydslJpaSupport(JPAQueryFactory queryFactory) { - this.queryFactory = Objects.requireNonNull(queryFactory, "queryFactory"); - } - - /** - * Builds a bounded, named collection query. - * - * @throws IllegalArgumentException when the query would be unbounded - */ - public JPAQuery select( - QueryName name, EntityPath root, Predicate predicate, QueryPage page) { - Objects.requireNonNull(name, "name"); - Objects.requireNonNull(root, "root"); - Objects.requireNonNull(page, "page"); - PredicatePolicy.requireBounded(predicate, page); - - JPAQuery query = queryFactory.selectFrom(root); - if (predicate != null) { - query = query.where(predicate); - } - return query.offset(page.offset()).limit(page.size()).setHint(COMMENT_HINT, name.value()); - } - - /** The factory this support class builds queries from. */ - public JPAQueryFactory queryFactory() { - return queryFactory; - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/springdata/EntityManagerAccess.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/springdata/EntityManagerAccess.java deleted file mode 100644 index 6f75e4dc..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/springdata/EntityManagerAccess.java +++ /dev/null @@ -1,19 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.springdata; - -import jakarta.persistence.EntityManager; - -/** - * The narrow seam through which a domain-owned repository fragment reaches its {@link - * EntityManager} (design §23.3). - * - *

The platform deliberately does not hand an {@code EntityManager} to arbitrary code. Exposing - * it widely is how {@code persist}, {@code merge}, and {@code createQuery} calls end up in - * application services and controllers, and at that point the transaction boundary and the fetch - * plan stop being decisions anyone made. - */ -@FunctionalInterface -public interface EntityManagerAccess { - - /** The entity manager bound to the current transaction. */ - EntityManager entityManager(); -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/springdata/SpecificationPolicy.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/springdata/SpecificationPolicy.java deleted file mode 100644 index b96d8138..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/springdata/SpecificationPolicy.java +++ /dev/null @@ -1,52 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.springdata; - -import java.util.Objects; -import org.springframework.data.domain.Pageable; -import org.springframework.data.jpa.domain.Specification; - -/** - * The rules a dynamic {@link Specification} query must satisfy before it runs (design §23.2). - * - *

A specification with no predicate is a full table scan wearing a builder's clothing. It is - * usually the result of every optional filter being absent — a search screen submitted empty — and - * it looks harmless in code review because no single line is wrong. Requiring either a predicate or - * an explicit "yes, scan everything" token makes that case a decision instead of an accident. - * - *

A page bound is required for the same reason: an unbounded collection query hydrates whatever - * the table happens to hold today. - */ -public final class SpecificationPolicy { - - /** The explicit opt-in a caller must pass to run a predicate-free query. */ - public static final String ALLOW_UNBOUNDED_TOKEN = "allow-unbounded-scan"; - - private SpecificationPolicy() {} - - /** - * Fails when the specification is unbounded without an explicit opt-in. - * - * @param allowUnboundedToken {@link #ALLOW_UNBOUNDED_TOKEN} to permit a predicate-free query - * @throws IllegalArgumentException when the query would be unbounded - */ - public static void requireBounded( - Specification specification, Pageable pageable, String allowUnboundedToken) { - Objects.requireNonNull(pageable, "pageable"); - if (pageable.isUnpaged()) { - throw new IllegalArgumentException( - "a specification query requires a bounded page; unpaged reads whatever the table holds"); - } - if (specification == null && !ALLOW_UNBOUNDED_TOKEN.equals(allowUnboundedToken)) { - throw new IllegalArgumentException( - "a specification query requires a bounded predicate, or the explicit '" - + ALLOW_UNBOUNDED_TOKEN - + "' token"); - } - } - - /** Fails when the specification has no predicate at all. */ - public static void requirePredicate(Specification specification) { - if (specification == null) { - throw new IllegalArgumentException("a specification query requires a bounded predicate"); - } - } -} diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/startup/FlywayProdSafetyValidator.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/FlywayProdSafetyValidator.java similarity index 87% rename from src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/startup/FlywayProdSafetyValidator.java rename to src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/FlywayProdSafetyValidator.java index 80057168..e15a7db2 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/startup/FlywayProdSafetyValidator.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/FlywayProdSafetyValidator.java @@ -1,6 +1,8 @@ -package dev.caskeleton.bootstrap.runtime.startup; +package dev.caskeleton.adapter.outbound.persistence.startup; import dev.caskeleton.adapter.outbound.support.runtime.RuntimeProfileSnapshot; +import dev.caskeleton.adapter.outbound.support.startup.StartupPhase; +import dev.caskeleton.adapter.outbound.support.startup.StartupValidationContext; import org.springframework.beans.factory.SmartInitializingSingleton; import org.springframework.core.env.Environment; @@ -8,7 +10,7 @@ import org.springframework.core.env.Environment; * Keeps the Flyway prod safety nets on; raises PROFILE_MISMATCH (exit 71) when an override * re-enables a forbidden option. See README for the design rationale. */ -public class FlywayProdSafetyValidator implements SmartInitializingSingleton { +class FlywayProdSafetyValidator implements SmartInitializingSingleton { static final String BASELINE_ON_MIGRATE_KEY = "spring.flyway.baseline-on-migrate"; static final String OUT_OF_ORDER_KEY = "spring.flyway.out-of-order"; diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/HikariPoolConstraintValidator.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/HikariPoolConstraintValidator.java similarity index 81% rename from src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/HikariPoolConstraintValidator.java rename to src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/HikariPoolConstraintValidator.java index ebcde5fe..6c793aee 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/HikariPoolConstraintValidator.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/HikariPoolConstraintValidator.java @@ -1,8 +1,8 @@ -package dev.caskeleton.bootstrap.runtime; +package dev.caskeleton.adapter.outbound.persistence.startup; -import dev.caskeleton.bootstrap.runtime.startup.StartupFailures; -import dev.caskeleton.bootstrap.runtime.startup.StartupPhase; -import dev.caskeleton.bootstrap.runtime.startup.StartupValidationContext; +import dev.caskeleton.adapter.outbound.support.startup.StartupFailures; +import dev.caskeleton.adapter.outbound.support.startup.StartupPhase; +import dev.caskeleton.adapter.outbound.support.startup.StartupValidationContext; import java.time.temporal.ChronoUnit; import org.springframework.beans.factory.SmartInitializingSingleton; import org.springframework.boot.convert.DurationStyle; @@ -13,13 +13,15 @@ import org.springframework.core.env.Environment; * Spring properties as a {@link SmartInitializingSingleton}; an absent property is skipped. See * README for the design rationale. */ -public class HikariPoolConstraintValidator implements SmartInitializingSingleton { +class HikariPoolConstraintValidator implements SmartInitializingSingleton { static final String CONNECTION_TIMEOUT_KEY = "spring.datasource.hikari.connection-timeout"; static final String VALIDATION_TIMEOUT_KEY = "spring.datasource.hikari.validation-timeout"; static final String KEEPALIVE_TIME_KEY = "spring.datasource.hikari.keepalive-time"; static final String MAX_LIFETIME_KEY = "spring.datasource.hikari.max-lifetime"; static final String LEAK_DETECTION_KEY = "spring.datasource.hikari.leak-detection-threshold"; + static final String MAX_POOL_SIZE_KEY = "spring.datasource.hikari.maximum-pool-size"; + static final String MIN_IDLE_KEY = "spring.datasource.hikari.minimum-idle"; // Operator-facing env keys, so a boot failure names the APP_* variable the operator set. // Knobs without a registered env key emit ENV_KEY_PENDING instead of a fabricated name. @@ -38,6 +40,21 @@ public class HikariPoolConstraintValidator implements SmartInitializingSingleton StartupValidationContext violations = StartupValidationContext.forPhase(StartupPhase.ENV_VALIDATION); + // Pool sizing: absent is skipped (the framework default owns it), no lenient default otherwise. + Integer maxPoolSize = environment.getProperty(MAX_POOL_SIZE_KEY, Integer.class); + if (maxPoolSize != null && maxPoolSize < 1) { + violations.reject( + "APP_DATASOURCE_POOL_MAX_SIZE (" + + MAX_POOL_SIZE_KEY + + ") must be >= 1, was " + + maxPoolSize); + } + Integer minIdle = environment.getProperty(MIN_IDLE_KEY, Integer.class); + if (minIdle != null && minIdle < 0) { + violations.reject( + "APP_DATASOURCE_POOL_MIN_IDLE (" + MIN_IDLE_KEY + ") must be >= 0, was " + minIdle); + } + Long connectionTimeout = parseMillis(CONNECTION_TIMEOUT_KEY, environment.getProperty(CONNECTION_TIMEOUT_KEY)); Long validationTimeout = diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaActivationEnvironmentPostProcessor.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaActivationEnvironmentPostProcessor.java new file mode 100644 index 00000000..7c0214ad --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaActivationEnvironmentPostProcessor.java @@ -0,0 +1,85 @@ +package dev.caskeleton.adapter.outbound.persistence.startup; + +import dev.caskeleton.adapter.outbound.support.startup.ReadinessGroup; +import dev.caskeleton.adapter.outbound.support.startup.StartupOrder; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import org.springframework.boot.EnvironmentPostProcessor; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.AutoConfiguration; +import org.springframework.boot.context.annotation.ImportCandidates; +import org.springframework.boot.context.properties.bind.Bindable; +import org.springframework.boot.context.properties.bind.Binder; +import org.springframework.core.Ordered; +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.core.env.MapPropertySource; + +/** + * What the module switch, {@code ca-skeleton.persistence-jpa.enabled}, decides before any bean + * exists. + * + *

On (the default while the module is present): the {@code db} health contributor joins + * the readiness group. {@code validate-group-membership} is on, so a static {@code + * readiness.include: readinessState,db} would be a deployment that cannot boot without a database; + * membership is contributed by the module that creates the pool instead. + * + *

Off: this module's own auto-configurations stand down on their switch, but Spring + * Boot's JDBC, Hibernate, Spring Data JPA and Flyway auto-configurations arrive with this module's + * dependencies and read no switch of ours. Left alone they would bind {@code spring.datasource.*}, + * build a Hikari pool, and have Hibernate and Flyway open a connection — so "off" would still need + * a database. An explicit off therefore appends them to {@code spring.autoconfigure.exclude}, after + * whatever the deployment already excludes. The names are read from Boot's own registration files + * by package, as the Mongo and GraphQL modules do, so a Boot release that adds one is covered + * without an edit. + * + *

Boot's transaction, persistence-exception-translation and Spring Data commons + * auto-configurations are left alone: other stores share them, and without a transaction manager or + * a repository of this module's they create nothing. + */ +class JpaActivationEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered { + + static final String DB_CONTRIBUTOR = "db"; + + static final String EXCLUDE = "spring.autoconfigure.exclude"; + + /** Boot auto-configuration packages this module's dependencies bring and its switch owns. */ + static final List BOOT_RELATIONAL_PACKAGES = + List.of( + "org.springframework.boot.jdbc.autoconfigure.", + "org.springframework.boot.hibernate.autoconfigure.", + "org.springframework.boot.data.jpa.autoconfigure.", + "org.springframework.boot.flyway.autoconfigure."); + + @Override + public void postProcessEnvironment( + ConfigurableEnvironment environment, SpringApplication application) { + if (JpaStartupAutoConfiguration.enabled(environment)) { + ReadinessGroup.include(environment, "databaseReadinessGroup", DB_CONTRIBUTOR); + return; + } + List excluded = + new ArrayList<>( + Binder.get(environment).bind(EXCLUDE, Bindable.listOf(String.class)).orElse(List.of())); + for (String candidate : + ImportCandidates.load( + AutoConfiguration.class, + JpaActivationEnvironmentPostProcessor.class.getClassLoader())) { + if (BOOT_RELATIONAL_PACKAGES.stream().anyMatch(candidate::startsWith)) { + excluded.add(candidate); + } + } + environment + .getPropertySources() + .addFirst( + new MapPropertySource( + "persistence-jpa-off", Map.of(EXCLUDE, String.join(",", excluded)))); + } + + @Override + public int getOrder() { + // After the module defaults, which carry this module's switch, and after the Redis processor, + // so the two readiness appends chain deterministically instead of racing for the same property. + return StartupOrder.READINESS_DATABASE; + } +} diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/jpa/JpaDangerousConfigurationGuard.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaDangerousConfigurationGuard.java similarity index 89% rename from src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/jpa/JpaDangerousConfigurationGuard.java rename to src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaDangerousConfigurationGuard.java index 7f647fbc..5e130df5 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/jpa/JpaDangerousConfigurationGuard.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaDangerousConfigurationGuard.java @@ -1,8 +1,8 @@ -package dev.caskeleton.bootstrap.autoconfigure.jpa; +package dev.caskeleton.adapter.outbound.persistence.startup; import dev.caskeleton.adapter.outbound.persistence.migration.FlywaySchemaPolicy; import dev.caskeleton.adapter.outbound.support.runtime.RuntimeProfileSnapshot; -import dev.caskeleton.bootstrap.runtime.startup.StartupFailures; +import dev.caskeleton.adapter.outbound.support.startup.StartupFailures; import java.util.List; import java.util.Objects; import org.springframework.core.env.Environment; @@ -20,10 +20,10 @@ import org.springframework.core.env.Environment; * produces a schema that is neither the old one nor the one the migrations describe — and it does * so silently, on whichever instance starts first. * - *

This guard extends the existing per-setting validators in {@code bootstrap.runtime} to the - * whole non-local profile set, so a staging deployment is held to the same rule as production. + *

This guard extends the per-setting validators in this package to the whole non-local profile + * set, so a staging deployment is held to the same rule as production. */ -public final class JpaDangerousConfigurationGuard { +final class JpaDangerousConfigurationGuard { /** The property that enables Open Session In View. */ public static final String OPEN_IN_VIEW_KEY = "spring.jpa.open-in-view"; diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/jpa/JpaDataSourceProfileValidator.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaDataSourceProfileValidator.java similarity index 90% rename from src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/jpa/JpaDataSourceProfileValidator.java rename to src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaDataSourceProfileValidator.java index 10ecbfe8..c12f2947 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/jpa/JpaDataSourceProfileValidator.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaDataSourceProfileValidator.java @@ -1,6 +1,6 @@ -package dev.caskeleton.bootstrap.autoconfigure.jpa; +package dev.caskeleton.adapter.outbound.persistence.startup; -import dev.caskeleton.bootstrap.runtime.startup.StartupFailures; +import dev.caskeleton.adapter.outbound.support.startup.StartupFailures; import java.sql.Connection; import java.sql.SQLException; import java.util.Objects; @@ -28,11 +28,10 @@ import javax.sql.DataSource; * HikariPoolConstraintValidator}, which already reads {@code spring.datasource.hikari.*} — the * namespace that actually builds the pool — and enforces the acquisition floor and the inter-knob * constraints. Duplicating that would be a second opinion on the same properties, and two - * validators of one thing is how the parallel namespace started. This class no longer names a pool - * type at all, which also keeps HikariCP off app-bootstrap's production classpath, where the build - * file deliberately does not put it. + * validators of one thing is how the parallel namespace started. This class names no pool type at + * all. */ -public final class JpaDataSourceProfileValidator { +final class JpaDataSourceProfileValidator { private final PostgreSqlVersionPolicy versionPolicy; diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/jpa/JpaPlatformEndpoint.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaPlatformEndpoint.java similarity index 93% rename from src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/jpa/JpaPlatformEndpoint.java rename to src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaPlatformEndpoint.java index 232add53..b4a0dc1f 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/jpa/JpaPlatformEndpoint.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaPlatformEndpoint.java @@ -1,4 +1,4 @@ -package dev.caskeleton.bootstrap.autoconfigure.jpa; +package dev.caskeleton.adapter.outbound.persistence.startup; import java.util.Objects; import java.util.function.Supplier; @@ -18,7 +18,7 @@ import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; * change when something has gone wrong. */ @Endpoint(id = "jpaplatform") -public class JpaPlatformEndpoint { +class JpaPlatformEndpoint { private final Supplier reportSupplier; diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaPlatformReport.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaPlatformReport.java new file mode 100644 index 00000000..8819fc2f --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaPlatformReport.java @@ -0,0 +1,145 @@ +package dev.caskeleton.adapter.outbound.persistence.startup; + +import dev.caskeleton.adapter.outbound.persistence.api.capability.CapabilitySupport; +import dev.caskeleton.adapter.outbound.persistence.api.capability.JpaCapability; +import dev.caskeleton.adapter.outbound.persistence.hibernate.HibernateProviderPolicy; +import dev.caskeleton.adapter.outbound.persistence.security.DatabasePrivilegeReport; +import dev.caskeleton.adapter.outbound.persistence.security.PostgreSqlRuntimeRoleVerifier; +import java.sql.Connection; +import java.sql.SQLException; +import java.util.List; +import java.util.Objects; +import javax.sql.DataSource; +import org.springframework.core.env.Environment; + +/** + * What the JPA platform is willing to say about itself over HTTP (design §37). + * + *

The interesting part of this type is what it cannot hold. There is no JDBC URL, no username, + * no password, no SQL, and no entity catalog — an actuator endpoint is reachable by anyone who + * reaches the management port, and every one of those would be a free reconnaissance answer. + * + *

What it does report is what an operator actually needs during an incident: which database + * major version is behind this instance, which provider, which schema version, and whether the + * safety properties this platform depends on are holding. + */ +record JpaPlatformReport( + String databaseProduct, + int databaseMajorVersion, + String providerVersion, + String schemaVersion, + boolean openInViewDisabled, + boolean runtimeRoleVerified, + List capabilities) { + + public JpaPlatformReport { + Objects.requireNonNull(databaseProduct, "databaseProduct"); + Objects.requireNonNull(providerVersion, "providerVersion"); + schemaVersion = schemaVersion == null ? "unknown" : schemaVersion; + capabilities = List.copyOf(Objects.requireNonNull(capabilities, "capabilities")); + } + + /** + * Builds the report, deriving only bounded values from the privilege report. + * + *

The privilege report's {@code currentUser} and {@code searchPath} are deliberately reduced + * to a single boolean here: an operator needs to know the runtime role passed verification, not + * which role it is. + */ + public static JpaPlatformReport sanitized( + String databaseProduct, + int databaseMajorVersion, + String providerVersion, + String schemaVersion, + boolean openInViewDisabled, + DatabasePrivilegeReport privileges, + List capabilities) { + return new JpaPlatformReport( + databaseProduct, + databaseMajorVersion, + providerVersion, + schemaVersion, + openInViewDisabled, + privileges != null && !privileges.holdsCreatePrivilege(), + capabilities); + } + + /** Whether every safety property this platform depends on is currently holding. */ + public boolean safe() { + return openInViewDisabled && runtimeRoleVerified; + } + + /** + * The capabilities this platform actually provides. Only Stable modules are composed; Querydsl, + * Envers, the second-level cache, and COPY are Advanced or admin capabilities that require their + * own dependency and their own explicit opt-in (design §4.2, §8.4). + */ + static List platformCapabilities() { + return List.of( + CapabilitySupport.advanced( + JpaCapability.COMPLETION_EVIDENCE, + "requires an application-owned completion-evidence/reconciliation composition"), + CapabilitySupport.stable(JpaCapability.KEYSET_PAGINATION), + CapabilitySupport.advanced( + JpaCapability.BATCH, + "requires hibernate.jdbc.batch_size > 0, ordering settings, statistics and JDBC batch instrumentation"), + CapabilitySupport.stable(JpaCapability.SCHEMA_GATE), + CapabilitySupport.stable(JpaCapability.RUNTIME_ROLE_VERIFICATION), + CapabilitySupport.advanced( + JpaCapability.OBSERVABILITY, + "requires explicit metrics/statistics collector composition"), + CapabilitySupport.advanced(JpaCapability.POSTGRESQL_JSONB, "requires a registered path"), + CapabilitySupport.advanced( + JpaCapability.POSTGRESQL_ARRAY_RANGE, "binds through JDBC in the caller's adapter"), + CapabilitySupport.advanced(JpaCapability.BULK_DML, "requires a registered operation"), + CapabilitySupport.advanced( + JpaCapability.STATELESS_SESSION, "requires registered work and a row cap"), + CapabilitySupport.advanced( + JpaCapability.POSTGRESQL_COPY, "requires the admin credential and a registered COPY"), + CapabilitySupport.advanced(JpaCapability.L2_CACHE, "requires an enrolled region catalog"), + CapabilitySupport.advanced( + JpaCapability.ENVERS, "requires the Envers dependency and a retention policy")); + } + + /** + * Reads the report the actuator endpoint serves. + * + *

A failure to reach the database or read the runtime role is reported as "unavailable" or + * "not verified" rather than propagated: an unreachable database must not turn the diagnostic + * endpoint into a second outage. + */ + static JpaPlatformReport read( + DataSource dataSource, + String schemaVersion, + Environment environment, + HibernateProviderPolicy providerPolicy, + PostgreSqlRuntimeRoleVerifier roleVerifier) { + Objects.requireNonNull(dataSource, "dataSource"); + String product = "unknown"; + int majorVersion = 0; + try (Connection connection = dataSource.getConnection()) { + product = connection.getMetaData().getDatabaseProductName(); + majorVersion = connection.getMetaData().getDatabaseMajorVersion(); + } catch (SQLException unreachable) { + product = "unavailable"; + } + DatabasePrivilegeReport privileges; + try { + privileges = roleVerifier.verify(dataSource); + } catch (IllegalStateException unverified) { + privileges = null; + } + boolean openInViewDisabled = + !Boolean.TRUE.equals( + environment.getProperty( + JpaDangerousConfigurationGuard.OPEN_IN_VIEW_KEY, Boolean.class)); + return sanitized( + product, + majorVersion, + providerPolicy.runtimeVersion(), + schemaVersion, + openInViewDisabled, + privileges, + platformCapabilities()); + } +} diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/jpa/JpaSafetySettings.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaSafetySettings.java similarity index 92% rename from src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/jpa/JpaSafetySettings.java rename to src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaSafetySettings.java index b364e205..3592cae8 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/jpa/JpaSafetySettings.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaSafetySettings.java @@ -1,4 +1,4 @@ -package dev.caskeleton.bootstrap.autoconfigure.jpa; +package dev.caskeleton.adapter.outbound.persistence.startup; import dev.caskeleton.shared.runtime.RuntimeEnvironment; import java.util.Set; @@ -6,7 +6,7 @@ import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.bind.DefaultValue; /** - * The JPA safety switches the composition root binds (design §15, §31). + * The JPA safety switches this module binds (design §15, §31). * *

{@code enabled} defaults to {@code true}, declared rather than implied. A primitive {@code * boolean} binds to {@code false} when the property is absent, so this record said "the defaults @@ -19,7 +19,7 @@ import org.springframework.boot.context.properties.bind.DefaultValue; * that "on in local" cannot silently expand to another runtime environment when policy changes. */ @ConfigurationProperties(prefix = "app.jpa-platform") -public record JpaSafetySettings( +record JpaSafetySettings( @DefaultValue("true") boolean enabled, Set localConvenienceProfiles, Set schemaMutatingProfiles) { diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/JpaSchemaSafetyValidator.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaSchemaSafetyValidator.java similarity index 88% rename from src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/JpaSchemaSafetyValidator.java rename to src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaSchemaSafetyValidator.java index c5c1c54b..730aaadb 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/JpaSchemaSafetyValidator.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaSchemaSafetyValidator.java @@ -1,7 +1,7 @@ -package dev.caskeleton.bootstrap.runtime; +package dev.caskeleton.adapter.outbound.persistence.startup; import dev.caskeleton.adapter.outbound.support.runtime.RuntimeProfileSnapshot; -import dev.caskeleton.bootstrap.runtime.startup.StartupFailures; +import dev.caskeleton.adapter.outbound.support.startup.StartupFailures; import java.util.Locale; import java.util.Set; import org.springframework.beans.factory.SmartInitializingSingleton; @@ -11,7 +11,7 @@ import org.springframework.core.env.Environment; * Prevents Hibernate from becoming a production schema writer. Flyway owns the physical schema; * production may only disable Hibernate DDL or validate the schema. */ -public class JpaSchemaSafetyValidator implements SmartInitializingSingleton { +class JpaSchemaSafetyValidator implements SmartInitializingSingleton { static final String DDL_AUTO_KEY = "spring.jpa.hibernate.ddl-auto"; static final String DDL_AUTO_ENV_KEY = "APP_DATASOURCE_DDL_AUTO"; diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaStartupAutoConfiguration.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaStartupAutoConfiguration.java new file mode 100644 index 00000000..e9c64c98 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaStartupAutoConfiguration.java @@ -0,0 +1,166 @@ +package dev.caskeleton.adapter.outbound.persistence.startup; + +import dev.caskeleton.adapter.outbound.persistence.config.PersistenceVendorSettings; +import dev.caskeleton.adapter.outbound.persistence.hibernate.HibernateProviderPolicy; +import dev.caskeleton.adapter.outbound.persistence.migration.FlywaySchemaPolicy; +import dev.caskeleton.adapter.outbound.persistence.security.PostgreSqlRuntimeRoleVerifier; +import java.sql.SQLException; +import javax.sql.DataSource; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.boot.autoconfigure.AutoConfiguration; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.boot.flyway.autoconfigure.FlywayMigrationStrategy; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; + +/** + * The startup policy relational persistence runs under: migration sequencing, the resolved + * datasource check, the OSIV / DDL / pool / TLS / vendor guards, and the sanitized management view. + * + *

It used to be the composition root's, split over four configurations and a validator list, and + * guarded by a switch the root had to know about. It is this module's now, so an application that + * selects the module gets the guards with it and an application that removes the module keeps none + * of them. Every guard raises a typed startup failure from {@code support.startup}, so exit codes + * and the structured failure log are unchanged. + */ +@AutoConfiguration +@ConditionalOnProperty( + prefix = "ca-skeleton.persistence-jpa", + name = "enabled", + havingValue = "true", + matchIfMissing = true) +@EnableConfigurationProperties(JpaSafetySettings.class) +class JpaStartupAutoConfiguration { + + /** The module switch: on while the module is present unless a deployment turns it off. */ + static final String ENABLED_PROPERTY = "ca-skeleton.persistence-jpa.enabled"; + + static boolean enabled(Environment environment) { + return Boolean.parseBoolean(environment.getProperty(ENABLED_PROPERTY, "true").trim()); + } + + /** + * Runs Flyway during refresh, before readiness, and turns a failure into exit 70. + * + *

The bean name is what Flyway auto-configuration looks up. An application that supplies its + * own strategy — the sample runs a second migration stream — keeps it. + */ + @Bean + @ConditionalOnMissingBean(FlywayMigrationStrategy.class) + FlywayMigrationStrategy migrationStartupRunner(Environment environment) { + return new MigrationStartupRunner( + environment.getProperty("ca-skeleton.runtime.migration-on-startup", Boolean.class, true)); + } + + /** Env-validation (exit 78): datasource connection env present before migration runs. */ + @Bean + RequiredEnvironmentValidator requiredEnvironmentValidator(Environment environment) { + return new RequiredEnvironmentValidator(environment); + } + + /** Profile check (exit 71): forbidden Flyway options stay off under the prod profile. */ + @Bean + FlywayProdSafetyValidator flywayProdSafetyValidator(Environment environment) { + return new FlywayProdSafetyValidator(environment); + } + + @Bean + OpenInViewSafetyValidator openInViewSafetyValidator(Environment environment) { + return new OpenInViewSafetyValidator(environment); + } + + @Bean + JpaSchemaSafetyValidator jpaSchemaSafetyValidator(Environment environment) { + return new JpaSchemaSafetyValidator(environment); + } + + @Bean + PostgreSqlTransportSecurityValidator postgreSqlTransportSecurityValidator( + Environment environment) { + return new PostgreSqlTransportSecurityValidator(environment); + } + + @Bean + PersistenceVendorProdSafetyValidator persistenceVendorProdSafetyValidator( + Environment environment) { + return new PersistenceVendorProdSafetyValidator(environment); + } + + @Bean + HikariPoolConstraintValidator hikariPoolConstraintValidator(Environment environment) { + return new HikariPoolConstraintValidator(environment); + } + + /** The datasource product and version validator. */ + @Bean + JpaDataSourceProfileValidator jpaDataSourceProfileValidator() { + return new JpaDataSourceProfileValidator(new PostgreSqlVersionPolicy()); + } + + /** + * Validates the datasource the application actually resolved. PostgreSQL validation opens a + * connection during startup; the H2 development vendor skips the product check. + */ + @Bean + InitializingBean jpaResolvedDataSourceCheck( + JpaDataSourceProfileValidator validator, DataSource dataSource, Environment environment) { + String vendor = + environment.getProperty(PersistenceVendorSettings.VENDOR_PROPERTY, "postgresql").trim(); + return () -> validator.validateResolved(dataSource, "postgresql".equalsIgnoreCase(vendor)); + } + + /** The guard for the two settings that quietly break production. */ + @Bean + JpaDangerousConfigurationGuard jpaDangerousConfigurationGuard(JpaSafetySettings safety) { + return new JpaDangerousConfigurationGuard(safety, FlywaySchemaPolicy.standard()); + } + + /** Runs the dangerous-configuration guard during refresh rather than at the first request. */ + @Bean + InitializingBean jpaPlatformStartupCheck( + JpaDangerousConfigurationGuard guard, Environment environment) { + return () -> guard.validate(environment); + } + + /** + * The read-only actuator view. Only when actuator is present: this module does not bring it, and + * exposure is still governed by the application's own {@code management.endpoints} policy. + */ + @Configuration(proxyBeanMethods = false) + @ConditionalOnClass(name = "org.springframework.boot.actuate.endpoint.annotation.Endpoint") + static class JpaPlatformEndpointConfiguration { + + @Bean + @ConditionalOnMissingBean + JpaPlatformEndpoint jpaPlatformEndpoint( + DataSource dataSource, + Environment environment, + HibernateProviderPolicy providerPolicy, + PostgreSqlRuntimeRoleVerifier roleVerifier) { + // Computed per request: the report names the live schema version, and a value captured at + // boot would keep reporting the version the application started with. + return new JpaPlatformEndpoint( + () -> + JpaPlatformReport.read( + dataSource, + schemaVersion(dataSource), + environment, + providerPolicy, + roleVerifier)); + } + + private static String schemaVersion(DataSource dataSource) { + try (var connection = dataSource.getConnection()) { + return connection.getMetaData().getDatabaseProductVersion(); + } catch (SQLException unavailable) { + // "unknown" is honest; failing the endpoint over a transient connection problem would turn + // a diagnostic into an outage. + return "unknown"; + } + } + } +} diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/startup/MigrationStartupRunner.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/MigrationStartupRunner.java similarity index 71% rename from src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/startup/MigrationStartupRunner.java rename to src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/MigrationStartupRunner.java index 5b4a3c66..10811b78 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/startup/MigrationStartupRunner.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/MigrationStartupRunner.java @@ -1,8 +1,10 @@ -package dev.caskeleton.bootstrap.runtime.startup; +package dev.caskeleton.adapter.outbound.persistence.startup; import static net.logstash.logback.argument.StructuredArguments.kv; -import dev.caskeleton.bootstrap.settings.RuntimeSafetySettings; +import dev.caskeleton.adapter.outbound.support.startup.MigrationFailedException; +import dev.caskeleton.adapter.outbound.support.startup.StartupFailures; +import dev.caskeleton.adapter.outbound.support.startup.StartupPhase; import org.flywaydb.core.Flyway; import org.flywaydb.core.api.FlywayException; import org.flywaydb.core.api.output.MigrateResult; @@ -15,20 +17,24 @@ import org.springframework.boot.flyway.autoconfigure.FlywayMigrationStrategy; * a {@link FlywayException} into a {@link MigrationFailedException} (exit 70). See README for the * design rationale. */ -public class MigrationStartupRunner implements FlywayMigrationStrategy { +class MigrationStartupRunner implements FlywayMigrationStrategy { private static final Logger log = LoggerFactory.getLogger("dev.caskeleton.bootstrap.runtime.startup"); - private final RuntimeSafetySettings settings; + private final boolean migrationOnStartup; - public MigrationStartupRunner(RuntimeSafetySettings settings) { - this.settings = settings; + /** + * @param migrationOnStartup {@code ca-skeleton.runtime.migration-on-startup}; {@code false} + * leaves the migration to an out-of-band run + */ + MigrationStartupRunner(boolean migrationOnStartup) { + this.migrationOnStartup = migrationOnStartup; } @Override public void migrate(Flyway flyway) { - if (!settings.migrationOnStartup()) { + if (!migrationOnStartup) { log.info( "startup phase {}: in-app Flyway migration is disabled via configuration (ca-skeleton.runtime.migration-on-startup=false)", kv("startup.phase", StartupPhase.MIGRATION.wireName())); diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/OpenInViewSafetyValidator.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/OpenInViewSafetyValidator.java similarity index 87% rename from src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/OpenInViewSafetyValidator.java rename to src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/OpenInViewSafetyValidator.java index 833364ef..c41d3835 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/OpenInViewSafetyValidator.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/OpenInViewSafetyValidator.java @@ -1,6 +1,6 @@ -package dev.caskeleton.bootstrap.runtime; +package dev.caskeleton.adapter.outbound.persistence.startup; -import dev.caskeleton.bootstrap.runtime.startup.StartupFailures; +import dev.caskeleton.adapter.outbound.support.startup.StartupFailures; import org.springframework.beans.factory.SmartInitializingSingleton; import org.springframework.core.env.Environment; @@ -10,7 +10,7 @@ import org.springframework.core.env.Environment; * to Spring Boot's default and only a present {@code true} is rejected. See README for the design * rationale. */ -public class OpenInViewSafetyValidator implements SmartInitializingSingleton { +class OpenInViewSafetyValidator implements SmartInitializingSingleton { static final String OPEN_IN_VIEW_KEY = "spring.jpa.open-in-view"; static final String ENV_KEY = "APP_DATASOURCE_OPEN_IN_VIEW"; diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/PersistenceVendorProdSafetyValidator.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/PersistenceVendorProdSafetyValidator.java similarity index 93% rename from src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/PersistenceVendorProdSafetyValidator.java rename to src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/PersistenceVendorProdSafetyValidator.java index b7e86e6e..1ca4ff7d 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/PersistenceVendorProdSafetyValidator.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/PersistenceVendorProdSafetyValidator.java @@ -1,7 +1,7 @@ -package dev.caskeleton.bootstrap.runtime; +package dev.caskeleton.adapter.outbound.persistence.startup; import dev.caskeleton.adapter.outbound.support.runtime.RuntimeProfileSnapshot; -import dev.caskeleton.bootstrap.runtime.startup.StartupFailures; +import dev.caskeleton.adapter.outbound.support.startup.StartupFailures; import java.util.Locale; import org.springframework.beans.factory.SmartInitializingSingleton; import org.springframework.core.env.Environment; @@ -30,7 +30,7 @@ import org.springframework.core.env.Environment; *

Scoped to H2 by name rather than asserting "must be PostgreSQL", so a fork that adds a third * production-grade vendor is not blocked by this validator. */ -public final class PersistenceVendorProdSafetyValidator implements SmartInitializingSingleton { +final class PersistenceVendorProdSafetyValidator implements SmartInitializingSingleton { static final String VENDOR_KEY = "ca-skeleton.persistence.vendor"; static final String JDBC_URL_KEY = "spring.datasource.url"; diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/PostgreSqlTransportSecurityValidator.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/PostgreSqlTransportSecurityValidator.java similarity index 92% rename from src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/PostgreSqlTransportSecurityValidator.java rename to src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/PostgreSqlTransportSecurityValidator.java index 986ba89f..93dfe927 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/PostgreSqlTransportSecurityValidator.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/PostgreSqlTransportSecurityValidator.java @@ -1,7 +1,7 @@ -package dev.caskeleton.bootstrap.runtime; +package dev.caskeleton.adapter.outbound.persistence.startup; import dev.caskeleton.adapter.outbound.support.runtime.RuntimeProfileSnapshot; -import dev.caskeleton.bootstrap.runtime.startup.StartupFailures; +import dev.caskeleton.adapter.outbound.support.startup.StartupFailures; import java.util.ArrayList; import java.util.List; import java.util.Locale; @@ -16,7 +16,7 @@ import org.springframework.core.env.Environment; *

The validator never includes a JDBC URL in its failure because URLs can carry credentials, * endpoints, and database names. */ -public final class PostgreSqlTransportSecurityValidator implements SmartInitializingSingleton { +final class PostgreSqlTransportSecurityValidator implements SmartInitializingSingleton { static final String JDBC_URL_KEY = "spring.datasource.url"; static final String JDBC_URL_ENV_KEY = "APP_DATASOURCE_URL"; diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/jpa/PostgreSqlVersionPolicy.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/PostgreSqlVersionPolicy.java similarity index 90% rename from src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/jpa/PostgreSqlVersionPolicy.java rename to src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/PostgreSqlVersionPolicy.java index 940d849d..7fc71aab 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/jpa/PostgreSqlVersionPolicy.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/PostgreSqlVersionPolicy.java @@ -1,6 +1,6 @@ -package dev.caskeleton.bootstrap.autoconfigure.jpa; +package dev.caskeleton.adapter.outbound.persistence.startup; -import dev.caskeleton.bootstrap.runtime.startup.StartupFailures; +import dev.caskeleton.adapter.outbound.support.startup.StartupFailures; import java.sql.DatabaseMetaData; import java.sql.SQLException; import java.util.Set; @@ -13,7 +13,7 @@ import java.util.Set; * suite that ran on 16, 17, and 18, and a deployment on 19 is outside the evidence whether or not * it happens to behave. */ -public final class PostgreSqlVersionPolicy { +final class PostgreSqlVersionPolicy { /** The major versions the Stable contract suite covers. */ private static final Set STABLE = Set.of(16, 17, 18); diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/startup/RequiredEnvironmentValidator.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/RequiredEnvironmentValidator.java similarity index 85% rename from src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/startup/RequiredEnvironmentValidator.java rename to src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/RequiredEnvironmentValidator.java index bb48f8d8..4df50014 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/startup/RequiredEnvironmentValidator.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/RequiredEnvironmentValidator.java @@ -1,5 +1,7 @@ -package dev.caskeleton.bootstrap.runtime.startup; +package dev.caskeleton.adapter.outbound.persistence.startup; +import dev.caskeleton.adapter.outbound.support.startup.StartupPhase; +import dev.caskeleton.adapter.outbound.support.startup.StartupValidationContext; import java.util.Map; import org.springframework.beans.factory.SmartInitializingSingleton; import org.springframework.core.env.Environment; @@ -9,7 +11,7 @@ import org.springframework.core.env.Environment; * migration fails with an opaque driver error. Absent or blank counts as missing. See README for * the design rationale. */ -public class RequiredEnvironmentValidator implements SmartInitializingSingleton { +class RequiredEnvironmentValidator implements SmartInitializingSingleton { /** Spring property key → operator-facing env key (named in the failure message). */ static final Map REQUIRED_DATASOURCE_ENV = diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/BackoffCalculator.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/BackoffCalculator.java deleted file mode 100644 index bd2ae900..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/BackoffCalculator.java +++ /dev/null @@ -1,77 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.transaction; - -import dev.caskeleton.adapter.outbound.persistence.api.transaction.JitterMode; -import dev.caskeleton.adapter.outbound.persistence.api.transaction.RetryProfile; -import java.time.Duration; -import java.util.Objects; -import java.util.random.RandomGenerator; - -/** - * Computes the wait before the next attempt (design §19.3). - * - *

Growth is exponential and capped, then jittered. The jitter is the part that matters under the - * failures this platform retries: a deadlock or serialization storm has every contender failing at - * the same instant, so an unjittered backoff schedules them all to collide again together, and the - * retry budget burns down without any of them making progress. - * - *

The random source is injected so the calculator is deterministic under test; production passes - * a thread-safe generator. - */ -public final class BackoffCalculator { - - private final RetryProfile profile; - private final RandomGenerator random; - - public BackoffCalculator(RetryProfile profile, RandomGenerator random) { - this.profile = Objects.requireNonNull(profile, "profile"); - this.random = Objects.requireNonNull(random, "random"); - } - - /** A calculator using the platform's shared thread-safe random source. */ - public static BackoffCalculator forProfile(RetryProfile profile) { - return new BackoffCalculator(profile, RandomGenerator.getDefault()); - } - - /** - * The delay to wait after {@code attemptNumber} failed. - * - * @param attemptNumber the 1-based attempt that just failed - */ - public Duration forAttempt(int attemptNumber) { - if (attemptNumber < 1) { - throw new IllegalArgumentException("attempt number must be at least 1"); - } - long baseMillis = profile.initialBackoff().toMillis(); - if (baseMillis <= 0L) { - return Duration.ZERO; - } - double scaled = baseMillis * Math.pow(profile.multiplier(), attemptNumber - 1.0d); - long capped = - Math.min((long) Math.min(scaled, Long.MAX_VALUE), profile.maxBackoff().toMillis()); - return Duration.ofMillis(jitter(Math.max(capped, 0L))); - } - - private long jitter(long millis) { - if (millis == 0L) { - return 0L; - } - return switch (profile.jitter()) { - case NONE -> millis; - case FULL -> random.nextLong(millis + 1L); - case EQUAL -> { - long half = millis / 2L; - yield half + random.nextLong(millis - half + 1L); - } - }; - } - - /** The profile this calculator applies. */ - public RetryProfile profile() { - return profile; - } - - /** The mode used to randomise the computed backoff. */ - public JitterMode jitterMode() { - return profile.jitter(); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/CommitFailureClassifier.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/CommitFailureClassifier.java deleted file mode 100644 index 68165b9d..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/CommitFailureClassifier.java +++ /dev/null @@ -1,147 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.transaction; - -import dev.caskeleton.adapter.outbound.persistence.api.PersistenceOperationName; -import dev.caskeleton.adapter.outbound.persistence.api.error.JpaFailureContext; -import dev.caskeleton.adapter.outbound.persistence.api.error.SqlExceptionSqlStateResolver; -import dev.caskeleton.adapter.outbound.persistence.api.error.SqlStateResolver; -import dev.caskeleton.adapter.outbound.persistence.api.error.TransactionCompletionUnknownException; -import dev.caskeleton.adapter.outbound.persistence.api.transaction.TransactionCompletionEvidence; -import java.io.IOException; -import java.net.SocketException; -import java.sql.SQLNonTransientConnectionException; -import java.sql.SQLRecoverableException; -import java.sql.SQLTransientConnectionException; -import java.time.Clock; -import java.time.Duration; -import java.time.Instant; -import java.util.IdentityHashMap; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; - -/** - * Decides whether a failure raised while committing means "the commit outcome is unknown" (design - * §17.2). - * - *

The rule is narrow on purpose. A failure becomes {@link TransactionCompletionUnknownException} - * only when it happened during the commit phase and the driver could not tell us which way - * the transaction went — SQLSTATE {@code 40003}, a connection-class ({@code 08*}) failure, a - * server-termination state ({@code 57P01}-{@code 57P03}), or a transport-level break. Everything - * else is returned unchanged so the ordinary exception translator classifies it. - * - *

Widening this rule is tempting and wrong. Marking every commit-phase connection error as - * completion-unknown pushes ordinary pool exhaustion and server restarts into the reconciliation - * queue, which trains operators to clear that queue without reading it — and the one entry that - * mattered gets cleared with the rest. - */ -public final class CommitFailureClassifier { - - /** SQLSTATE for "statement completion unknown". */ - private static final String COMPLETION_UNKNOWN_STATE = "40003"; - - /** SQLSTATE class 08 is "connection exception". */ - private static final String CONNECTION_CLASS = "08"; - - /** - * States for a backend that went away while the commit was in flight. - * - *

These are not class 08, because class 08 is about the client's connection attempt while - * these are the server announcing its own termination — but for a commit the consequence is - * identical and worse: {@code 57P01} is what a terminated backend, a fast shutdown, or a failover - * reports, and the commit record may already be in the WAL when it arrives. Treating them as - * ordinary failures is how a possibly-committed transaction gets re-run. - * - *

{@code 57P02} (crash shutdown) and {@code 57P03} (cannot connect now) are included for the - * same reason: whatever the server did with the in-flight commit, the client did not learn it. - */ - private static final Set SERVER_TERMINATION_STATES = Set.of("57P01", "57P02", "57P03"); - - private static final int MAX_DEPTH = 64; - - private final SqlStateResolver sqlStateResolver; - private final Clock clock; - - public CommitFailureClassifier(SqlStateResolver sqlStateResolver, Clock clock) { - this.sqlStateResolver = Objects.requireNonNull(sqlStateResolver, "sqlStateResolver"); - this.clock = Objects.requireNonNull(clock, "clock"); - } - - /** The vendor-neutral classifier used when no driver-specific resolver is installed. */ - public static CommitFailureClassifier standard(Clock clock) { - return new CommitFailureClassifier(new SqlExceptionSqlStateResolver(), clock); - } - - /** - * Translates a commit-phase failure. - * - * @param failure the exception the provider threw from its commit - * @return {@link TransactionCompletionUnknownException} when the outcome is undetermined, or - * {@code failure} unchanged when it is not - */ - public RuntimeException translateCommitFailure(RuntimeException failure) { - Objects.requireNonNull(failure, "failure"); - Optional frame = TransactionEvidenceContext.current(); - Optional sqlState = sqlStateResolver.resolve(failure); - if (!indicatesUnknownCompletion(sqlState, failure)) { - return failure; - } - Instant now = clock.instant(); - PersistenceOperationName operation = - frame.map(TransactionEvidenceFrame::operation).orElse(UnknownOperation.NAME); - Duration elapsed = - frame.map(present -> between(present.startedAt(), now)).orElse(Duration.ZERO); - int attempt = frame.map(TransactionEvidenceFrame::attempt).orElse(1); - JpaFailureContext context = - JpaFailureContext.completionUnknown( - operation, sqlState.orElse(JpaFailureContext.NO_SQL_STATE), attempt, elapsed, null); - return new TransactionCompletionUnknownException( - context, - frame.flatMap(TransactionEvidenceFrame::reconciliationKey).orElse(null), - TransactionCompletionEvidence.UNKNOWN, - failure); - } - - /** - * Whether this failure leaves the commit outcome undetermined. - * - *

Exposed for the contract tests, which assert the rule directly rather than by constructing a - * provider exception for every driver variant. - */ - public boolean indicatesUnknownCompletion(Optional sqlState, Throwable failure) { - if (sqlState.isPresent()) { - String state = sqlState.get(); - if (COMPLETION_UNKNOWN_STATE.equals(state)) { - return true; - } - if (state.startsWith(CONNECTION_CLASS)) { - return true; - } - if (SERVER_TERMINATION_STATES.contains(state)) { - return true; - } - } - return hasTransportBreak(failure); - } - - private static Duration between(Instant startedAt, Instant now) { - Duration elapsed = Duration.between(startedAt, now); - return elapsed.isNegative() ? Duration.ZERO : elapsed; - } - - private static boolean hasTransportBreak(Throwable failure) { - IdentityHashMap seen = new IdentityHashMap<>(); - Throwable current = failure; - int depth = 0; - while (current != null && depth++ < MAX_DEPTH && seen.put(current, Boolean.TRUE) == null) { - if (current instanceof SocketException - || current instanceof IOException - || current instanceof SQLRecoverableException - || current instanceof SQLTransientConnectionException - || current instanceof SQLNonTransientConnectionException) { - return true; - } - current = current.getCause(); - } - return false; - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/CompletionUnknownRecord.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/CompletionUnknownRecord.java deleted file mode 100644 index eaca91c7..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/CompletionUnknownRecord.java +++ /dev/null @@ -1,68 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.transaction; - -import dev.caskeleton.adapter.outbound.persistence.api.PersistenceOperationName; -import dev.caskeleton.adapter.outbound.persistence.api.error.TransactionCompletionUnknownException; -import dev.caskeleton.adapter.outbound.persistence.api.transaction.TransactionCompletionEvidence; -import java.time.Instant; -import java.util.Objects; -import java.util.Optional; - -/** - * The durable handoff written when a transaction's commit outcome could not be determined (design - * §17.4). - * - *

Everything here is bounded: the registered operation, the SQLSTATE, the application's - * transaction key, the evidence phase, and the time. There are deliberately no SQL parameters and - * no row data — this record lands in a durable queue that operators read, and the transaction key - * is the handle they use to look the real state up. - */ -public record CompletionUnknownRecord( - PersistenceOperationName operation, - String transactionKey, - String sqlState, - TransactionCompletionEvidence evidence, - int attempt, - Instant occurredAt, - String traceId) { - - public CompletionUnknownRecord { - Objects.requireNonNull(operation, "operation"); - Objects.requireNonNull(sqlState, "sqlState"); - Objects.requireNonNull(evidence, "evidence"); - Objects.requireNonNull(occurredAt, "occurredAt"); - transactionKey = transactionKey == null ? "" : transactionKey; - traceId = traceId == null ? "" : traceId; - if (attempt < 1) { - throw new IllegalArgumentException("attempt must be at least 1"); - } - } - - /** Builds the record from the failure the platform raised. */ - public static CompletionUnknownRecord from( - TransactionCompletionUnknownException failure, Instant occurredAt) { - Objects.requireNonNull(failure, "failure"); - return new CompletionUnknownRecord( - failure.context().operation(), - failure.transactionKey().orElse(null), - failure.context().sqlState(), - failure.evidence(), - failure.context().transactionAttempt(), - occurredAt, - failure.context().traceId()); - } - - /** The application's reconciliation key, when the unit of work bound one. */ - public Optional reconciliationKey() { - return transactionKey.isEmpty() ? Optional.empty() : Optional.of(transactionKey); - } - - /** - * Whether this record can be reconciled automatically. - * - *

Without a transaction key there is nothing to look the outcome up by, so the record needs a - * human with the operation name and the timestamp. - */ - public boolean reconcilable() { - return !transactionKey.isEmpty(); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/CompletionUnknownRecorder.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/CompletionUnknownRecorder.java deleted file mode 100644 index bc9ee0fa..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/CompletionUnknownRecorder.java +++ /dev/null @@ -1,22 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.transaction; - -import dev.caskeleton.adapter.outbound.persistence.api.error.TransactionCompletionUnknownException; - -/** - * Durably hands an unknown-completion transaction to reconciliation (design §17.4). - * - *

The channel is chosen by the application and must be outside the transaction whose outcome is - * unknown. Writing the record through the same connection that may or may not have committed would - * make the audit trail share the failure it is supposed to document. - */ -@FunctionalInterface -public interface CompletionUnknownRecorder { - - /** - * Records the failure for later reconciliation. - * - *

Implementations must not invoke the original use case. This method observes; it never - * repairs. - */ - void record(TransactionCompletionUnknownException failure); -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/DefaultJpaRetryPolicy.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/DefaultJpaRetryPolicy.java deleted file mode 100644 index 5c192488..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/DefaultJpaRetryPolicy.java +++ /dev/null @@ -1,71 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.transaction; - -import dev.caskeleton.adapter.outbound.persistence.api.error.FailureCategory; -import dev.caskeleton.adapter.outbound.persistence.api.error.JpaPersistenceException; -import dev.caskeleton.adapter.outbound.persistence.api.error.TransactionCompletionUnknownException; -import dev.caskeleton.adapter.outbound.persistence.api.transaction.JpaRetryPolicy; -import dev.caskeleton.adapter.outbound.persistence.api.transaction.RetryDecision; -import dev.caskeleton.adapter.outbound.persistence.api.transaction.RetryProfile; -import dev.caskeleton.adapter.outbound.persistence.api.transaction.TransactionAttempt; -import java.util.Objects; - -/** - * The Stable retry classification (design §19.1). - * - *

The order of the checks is the contract, not an implementation detail: - * - *

    - *
  1. Completion unknown reconciles. It is checked first so no later rule can reach it. - *
  2. A failure the translator marked non-retryable fails. The profile's allowlist widens which - * categories may be retried; it does not overrule a verdict about this failure. The - * allowlist used to be checked first, so a profile that opted into a category could revive a - * failure the classifier had already called terminal. - *
  3. Only categories the profile explicitly opted into retry. - *
  4. Everything else fails, including unknown SQLSTATEs. Retrying a failure nobody classified is - * how an unrecognised error becomes duplicate writes. - *
- */ -public final class DefaultJpaRetryPolicy implements JpaRetryPolicy { - - private final RetryProfile profile; - private final BackoffCalculator backoff; - - public DefaultJpaRetryPolicy(RetryProfile profile, BackoffCalculator backoff) { - this.profile = Objects.requireNonNull(profile, "profile"); - this.backoff = Objects.requireNonNull(backoff, "backoff"); - } - - /** A policy for {@code profile} using the platform's shared random source for jitter. */ - public static DefaultJpaRetryPolicy forProfile(RetryProfile profile) { - return new DefaultJpaRetryPolicy(profile, BackoffCalculator.forProfile(profile)); - } - - @Override - public RetryDecision classify(JpaPersistenceException failure, TransactionAttempt attempt) { - Objects.requireNonNull(failure, "failure"); - Objects.requireNonNull(attempt, "attempt"); - - if (failure instanceof TransactionCompletionUnknownException - || failure.category() == FailureCategory.COMPLETION_UNKNOWN) { - return RetryDecision.reconcile("transaction completion is unknown"); - } - if (!profile.enabled()) { - return RetryDecision.fail("retry is not enabled for this transaction profile"); - } - if (!failure.retryable()) { - // The classifier looked at this failure; the profile only knows category names. - return RetryDecision.fail("failure was classified as non-retryable"); - } - FailureCategory category = failure.category(); - if (!profile.allows(category)) { - return RetryDecision.fail("non-retryable persistence failure"); - } - return RetryDecision.retry( - backoff.forAttempt(attempt.number()), "retrying whole transaction for " + category); - } - - /** The profile whose budget and eligible categories this policy applies. */ - public RetryProfile profile() { - return profile; - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/EffectiveTransactionTimeouts.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/EffectiveTransactionTimeouts.java deleted file mode 100644 index 3ad5ac6b..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/EffectiveTransactionTimeouts.java +++ /dev/null @@ -1,25 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.transaction; - -import java.time.Duration; -import java.util.Objects; - -/** PostgreSQL transaction-local timeouts bounded by the remaining absolute deadline. */ -public record EffectiveTransactionTimeouts( - Duration statementTimeout, Duration lockTimeout, Duration idleGuardTimeout) { - - public EffectiveTransactionTimeouts { - requirePositive(statementTimeout, "statementTimeout"); - requirePositive(lockTimeout, "lockTimeout"); - requirePositive(idleGuardTimeout, "idleGuardTimeout"); - if (lockTimeout.compareTo(statementTimeout) >= 0) { - throw new IllegalArgumentException("lockTimeout must be less than statementTimeout"); - } - } - - private static void requirePositive(Duration duration, String name) { - Objects.requireNonNull(duration, name + " must be non-null"); - if (duration.isZero() || duration.isNegative()) { - throw new IllegalArgumentException(name + " must be positive"); - } - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/EvidenceAwareJpaTransactionManager.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/EvidenceAwareJpaTransactionManager.java deleted file mode 100644 index 0671cf0d..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/EvidenceAwareJpaTransactionManager.java +++ /dev/null @@ -1,79 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.transaction; - -import dev.caskeleton.adapter.outbound.persistence.api.transaction.TransactionCompletionEvidence; -import jakarta.persistence.EntityManagerFactory; -import java.time.Clock; -import java.util.Objects; -import org.springframework.orm.jpa.JpaTransactionManager; -import org.springframework.transaction.TransactionDefinition; -import org.springframework.transaction.support.DefaultTransactionStatus; - -/** - * A {@link JpaTransactionManager} that records how far each transaction got, so a commit failure - * can be classified as "rolled back" or "outcome unknown" instead of guessed (design §17.2). - * - *

The phase is marked {@link TransactionCompletionEvidence#COMMITTING} immediately before the - * provider commit and never after. That ordering is the whole mechanism: if the JVM, the network, - * or the server dies inside {@code super.doCommit}, the last thing written is "we asked, we do not - * know", which is exactly the state that must not be mistaken for a rollback. - * - *

Evidence is cleared on every path — commit success, commit failure, rollback, and cleanup. A - * frame left behind on a pooled thread would attach this transaction's phase to the next unrelated - * unit of work that thread picks up. - */ -public class EvidenceAwareJpaTransactionManager extends JpaTransactionManager { - - private static final long serialVersionUID = 1L; - - private final transient CommitFailureClassifier classifier; - - public EvidenceAwareJpaTransactionManager( - EntityManagerFactory entityManagerFactory, CommitFailureClassifier classifier) { - super(Objects.requireNonNull(entityManagerFactory, "entityManagerFactory")); - this.classifier = Objects.requireNonNull(classifier, "classifier"); - } - - /** Builds a manager with the vendor-neutral commit classifier. */ - public static EvidenceAwareJpaTransactionManager standard( - EntityManagerFactory entityManagerFactory, Clock clock) { - return new EvidenceAwareJpaTransactionManager( - entityManagerFactory, CommitFailureClassifier.standard(clock)); - } - - @Override - protected void doBegin(Object transaction, TransactionDefinition definition) { - super.doBegin(transaction, definition); - TransactionEvidenceContext.mark(TransactionCompletionEvidence.ACTIVE); - } - - @Override - protected void doCommit(DefaultTransactionStatus status) { - TransactionEvidenceContext.mark(TransactionCompletionEvidence.COMMITTING); - try { - super.doCommit(status); - TransactionEvidenceContext.mark(TransactionCompletionEvidence.COMMITTED); - } catch (RuntimeException failure) { - TransactionEvidenceContext.mark(TransactionCompletionEvidence.UNKNOWN); - throw classifier.translateCommitFailure(failure); - } finally { - // Deliberately not cleared here. The executor's scope owns the frame's lifetime; a second - // owner popping was how an inner REQUIRES_NEW transaction deleted its outer frame. - } - } - - @Override - protected void doRollback(DefaultTransactionStatus status) { - try { - super.doRollback(status); - TransactionEvidenceContext.mark(TransactionCompletionEvidence.ROLLED_BACK); - } finally { - // Deliberately not cleared here. The executor's scope owns the frame's lifetime; a second - // owner popping was how an inner REQUIRES_NEW transaction deleted its outer frame. - } - } - - /** The classifier this manager applies to commit-phase failures. */ - public CommitFailureClassifier commitFailureClassifier() { - return classifier; - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/FullTransactionRetryCoordinator.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/FullTransactionRetryCoordinator.java deleted file mode 100644 index 25de0494..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/FullTransactionRetryCoordinator.java +++ /dev/null @@ -1,117 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.transaction; - -import dev.caskeleton.adapter.outbound.persistence.api.PersistenceOperationName; -import dev.caskeleton.adapter.outbound.persistence.api.error.JpaPersistenceException; -import dev.caskeleton.adapter.outbound.persistence.api.transaction.JpaRetryPolicy; -import dev.caskeleton.adapter.outbound.persistence.api.transaction.RetryDecision; -import dev.caskeleton.adapter.outbound.persistence.api.transaction.RetryDisposition; -import dev.caskeleton.adapter.outbound.persistence.api.transaction.RetryEventListener; -import dev.caskeleton.adapter.outbound.persistence.api.transaction.TransactionAttempt; -import dev.caskeleton.adapter.outbound.persistence.api.transaction.TransactionProfile; -import java.time.Clock; -import java.time.Duration; -import java.time.Instant; -import java.util.Objects; -import java.util.function.Supplier; - -/** - * Re-runs a whole use case in a brand new transaction after a retryable failure (design §19.2). - * - *

The unit of retry is the entire use case, not the failed statement. That is the only correct - * granularity for optimistic conflicts and serialization failures: the attempt failed because the - * state it computed against is no longer the committed state, so re-issuing the same statement - * would compute the same wrong answer. Re-entering the executor gives the next attempt a new - * transaction and a new Persistence Context, which is what forces the domain rules to run again - * against reloaded data. - * - *

Two failures are never retried here regardless of budget: a completion-unknown failure, which - * goes to reconciliation, and anything the policy classifies as {@link RetryDisposition#FAIL}. - */ -public final class FullTransactionRetryCoordinator { - - private final SpringJpaTransactionExecutor transactionExecutor; - - /* - * The legacy constructor still accepts a fallback policy so existing composition code keeps its - * source shape. TransactionProfile now requires a retry profile, so that fallback is validated - * but never participates in retry decisions. - */ - - private final RetrySleeper sleeper; - private final Clock clock; - private final Duration defaultMaxElapsed; - private final RetryEventListener listener; - - public FullTransactionRetryCoordinator( - SpringJpaTransactionExecutor transactionExecutor, - JpaRetryPolicy fallbackRetryPolicy, - RetrySleeper sleeper, - Clock clock, - Duration defaultMaxElapsed, - RetryEventListener listener) { - this.transactionExecutor = Objects.requireNonNull(transactionExecutor, "transactionExecutor"); - Objects.requireNonNull(fallbackRetryPolicy, "fallbackRetryPolicy"); - this.sleeper = Objects.requireNonNull(sleeper, "sleeper"); - this.clock = Objects.requireNonNull(clock, "clock"); - this.defaultMaxElapsed = Objects.requireNonNull(defaultMaxElapsed, "defaultMaxElapsed"); - this.listener = Objects.requireNonNull(listener, "listener"); - if (defaultMaxElapsed.isNegative()) { - throw new IllegalArgumentException("defaultMaxElapsed must not be negative"); - } - } - - /** Executes the use case, retrying the whole transaction while the profile's budget allows. */ - public T execute( - PersistenceOperationName operation, TransactionProfile profile, Supplier work) { - return execute(operation, profile, work, null); - } - - /** - * Executes the use case with a reconciliation key bound to every attempt. - * - * @param transactionKey the key a completion-unknown record will carry, or {@code null} - */ - public T execute( - PersistenceOperationName operation, - TransactionProfile profile, - Supplier work, - String transactionKey) { - Objects.requireNonNull(operation, "operation"); - Objects.requireNonNull(profile, "profile"); - Objects.requireNonNull(work, "work"); - - // One profile decides everything about this call: which failures are retryable, how long to - // wait, and how many attempts remain. - JpaRetryPolicy retryPolicy = DefaultJpaRetryPolicy.forProfile(profile.retryProfile()); - RetryBudget budget = RetryBudget.forProfile(profile.retryProfile(), defaultMaxElapsed); - Instant operationStartedAt = clock.instant(); - - for (int attemptNumber = 1; ; attemptNumber++) { - TransactionAttempt attempt = new TransactionAttempt(attemptNumber, clock.instant()); - try { - T result = - transactionExecutor.execute(operation, profile, work, attemptNumber, transactionKey); - listener.onSucceeded(operation, attemptNumber); - return result; - } catch (JpaPersistenceException failure) { - RetryDecision decision = retryPolicy.classify(failure, attempt); - listener.onAttemptFailed(operation, attempt, failure, decision); - if (!decision.retrying()) { - listener.onGaveUp(operation, attemptNumber, failure); - throw failure; - } - Duration elapsed = elapsedSince(operationStartedAt); - if (!budget.allowsAnotherAttempt(attemptNumber, elapsed, decision.delay())) { - listener.onGaveUp(operation, attemptNumber, failure); - throw failure; - } - sleeper.sleep(decision.delay()); - } - } - } - - private Duration elapsedSince(Instant start) { - Duration elapsed = Duration.between(start, clock.instant()); - return elapsed.isNegative() ? Duration.ZERO : elapsed; - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/JpaTransactionConfig.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/JpaTransactionConfig.java deleted file mode 100644 index 94ee8609..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/JpaTransactionConfig.java +++ /dev/null @@ -1,24 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.transaction; - -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Configuration; - -/** - * Binds {@link JpaTransactionSettings}, which nothing bound. - * - *

{@link SpringTransactionPort} takes it as a constructor argument, and the composition root's - * {@code @ConfigurationPropertiesScan} deliberately excludes this tree so a deployment with JPA off - * binds no persistence settings. That exclusion left the type unbound in deployments with JPA - * on as well, so the transaction port could not be constructed at all — it surfaced as an - * unsatisfied dependency the first time a capability that opens a transaction was assembled. - * - *

It lives in this package, next to the settings and the component that needs them, because the - * module map grants {@code config} an edge to {@code api} only; a central enablement would need - * edges into every package whose settings it named. - * - *

Reached through {@code JpaAdapterComponentsConfig}'s scan, so it is registered exactly when - * the JPA master switch is on. - */ -@Configuration(proxyBeanMethods = false) -@EnableConfigurationProperties(JpaTransactionSettings.class) -public class JpaTransactionConfig {} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/JpaTransactionSettings.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/JpaTransactionSettings.java deleted file mode 100644 index 1804a722..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/JpaTransactionSettings.java +++ /dev/null @@ -1,103 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.transaction; - -import java.time.Duration; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.boot.context.properties.bind.ConstructorBinding; -import org.springframework.validation.annotation.Validated; - -/** Finite deadline and PostgreSQL transaction-local timeout policy. */ -@Validated -@ConfigurationProperties(prefix = "ca-skeleton.jpa.transaction") -public record JpaTransactionSettings( - Duration transactionTimeout, - Duration beginBudget, - Duration minimumActionWindow, - Duration completionMargin, - Duration statementTimeout, - Duration lockTimeout, - Duration idleGuardTimeout, - Duration transactionMargin, - Duration lockMargin, - Duration retryBaseDelay, - Duration retryMaximumDelay, - Integer retryMaximumAttempts) { - - private static final Duration MAXIMUM = Duration.ofDays(1); - - @ConstructorBinding - public JpaTransactionSettings { - transactionTimeout = - defaulted(transactionTimeout, Duration.ofSeconds(30), "transaction-timeout"); - beginBudget = defaulted(beginBudget, Duration.ofMillis(250), "begin-budget"); - minimumActionWindow = - defaulted(minimumActionWindow, Duration.ofSeconds(1), "minimum-action-window"); - completionMargin = defaulted(completionMargin, Duration.ofMillis(500), "completion-margin"); - statementTimeout = defaulted(statementTimeout, Duration.ofSeconds(10), "statement-timeout"); - lockTimeout = defaulted(lockTimeout, Duration.ofSeconds(2), "lock-timeout"); - idleGuardTimeout = defaulted(idleGuardTimeout, Duration.ofSeconds(15), "idle-guard-timeout"); - transactionMargin = defaulted(transactionMargin, Duration.ofMillis(250), "transaction-margin"); - lockMargin = defaulted(lockMargin, Duration.ofMillis(100), "lock-margin"); - retryBaseDelay = defaulted(retryBaseDelay, Duration.ofMillis(10), "retry-base-delay"); - retryMaximumDelay = defaulted(retryMaximumDelay, Duration.ofMillis(50), "retry-maximum-delay"); - retryMaximumAttempts = retryMaximumAttempts == null ? 2 : retryMaximumAttempts; - - if (statementTimeout.compareTo(transactionTimeout) > 0) { - throw new IllegalArgumentException( - "ca-skeleton.jpa.transaction.statement-timeout must be <= transaction-timeout"); - } - if (lockTimeout.compareTo(statementTimeout) >= 0) { - throw new IllegalArgumentException( - "ca-skeleton.jpa.transaction.lock-timeout must be < statement-timeout"); - } - if (transactionMargin.compareTo(statementTimeout) >= 0) { - throw new IllegalArgumentException( - "ca-skeleton.jpa.transaction.transaction-margin must be < statement-timeout"); - } - if (lockMargin.compareTo(statementTimeout.minus(lockTimeout)) >= 0) { - throw new IllegalArgumentException( - "ca-skeleton.jpa.transaction.lock-margin must leave lock-timeout below statement-timeout"); - } - if (retryBaseDelay.compareTo(retryMaximumDelay) > 0) { - throw new IllegalArgumentException( - "ca-skeleton.jpa.transaction.retry-base-delay must be <= retry-maximum-delay"); - } - if (retryMaximumAttempts < 1 || retryMaximumAttempts > 5) { - throw new IllegalArgumentException( - "ca-skeleton.jpa.transaction.retry-maximum-attempts must be between 1 and 5"); - } - } - - public JpaTransactionSettings( - Duration transactionTimeout, - Duration beginBudget, - Duration minimumActionWindow, - Duration completionMargin, - Duration statementTimeout, - Duration lockTimeout, - Duration idleGuardTimeout, - Duration transactionMargin, - Duration lockMargin) { - this( - transactionTimeout, - beginBudget, - minimumActionWindow, - completionMargin, - statementTimeout, - lockTimeout, - idleGuardTimeout, - transactionMargin, - lockMargin, - null, - null, - null); - } - - private static Duration defaulted(Duration value, Duration fallback, String name) { - Duration selected = value == null ? fallback : value; - if (selected.isZero() || selected.isNegative() || selected.compareTo(MAXIMUM) > 0) { - throw new IllegalArgumentException( - "ca-skeleton.jpa.transaction." + name + " must be in (0, 1 day]"); - } - return selected; - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/OptimisticConflictTranslator.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/OptimisticConflictTranslator.java deleted file mode 100644 index 3378fecf..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/OptimisticConflictTranslator.java +++ /dev/null @@ -1,114 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.transaction; - -import dev.caskeleton.adapter.outbound.persistence.api.PersistenceOperationName; -import dev.caskeleton.adapter.outbound.persistence.api.error.JpaFailureContext; -import dev.caskeleton.adapter.outbound.persistence.api.error.OptimisticConflictException; -import jakarta.persistence.OptimisticLockException; -import java.time.Duration; -import java.util.IdentityHashMap; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; -import org.springframework.dao.OptimisticLockingFailureException; - -/** - * Turns a provider optimistic-locking failure into the stable {@link OptimisticConflictException} - * (design §20). - * - *

The conflict can surface at flush or at commit, and through at least three exception types - * depending on whether Spring, Hibernate, or Jakarta Persistence raised it, so the whole cause - * chain is inspected rather than only the outermost exception. - * - *

The conflicting entity type is resolved through a registered catalog and is otherwise dropped. - * Provider exceptions carry the entity instance and its identifier; copying either into - * the stable failure would put a row key into every log line and metric tag that failure produces. - */ -public final class OptimisticConflictTranslator { - - private static final int MAX_DEPTH = 64; - - private final Set registeredEntityTypes; - - /** - * @param registeredEntityTypes the bounded set of entity simple names that may be reported - */ - public OptimisticConflictTranslator(Set registeredEntityTypes) { - this.registeredEntityTypes = - Set.copyOf(Objects.requireNonNull(registeredEntityTypes, "registeredEntityTypes")); - } - - /** A translator that reports no entity type at all. */ - public static OptimisticConflictTranslator withoutCatalog() { - return new OptimisticConflictTranslator(Set.of()); - } - - /** Whether this failure chain is an optimistic conflict. */ - public boolean isOptimisticConflict(Throwable failure) { - return walk(failure) != null; - } - - /** - * Translates the failure, or returns empty when it is not an optimistic conflict. - * - * @param operation the registered operation the failing attempt served - * @param attempt the 1-based attempt number - * @param elapsed how long the attempt ran - */ - public Optional translate( - Throwable failure, - PersistenceOperationName operation, - int attempt, - Duration elapsed, - String traceId) { - Throwable conflict = walk(failure); - if (conflict == null) { - return Optional.empty(); - } - JpaFailureContext context = - JpaFailureContext.retryable( - operation, JpaFailureContext.NO_SQL_STATE, attempt, elapsed, traceId); - return Optional.of(new OptimisticConflictException(context, conflict)); - } - - /** - * The conflicting entity type, when the provider named one that is in the catalog. - * - *

An unregistered type is reported as empty rather than passed through, so a new entity cannot - * silently widen the tag set of every optimistic-conflict metric. - */ - public Optional conflictingEntityType(Class entityType) { - if (entityType == null) { - return Optional.empty(); - } - String simpleName = entityType.getSimpleName(); - return registeredEntityTypes.contains(simpleName) ? Optional.of(simpleName) : Optional.empty(); - } - - private static Throwable walk(Throwable failure) { - IdentityHashMap seen = new IdentityHashMap<>(); - Throwable current = failure; - int depth = 0; - while (current != null && depth++ < MAX_DEPTH && seen.put(current, Boolean.TRUE) == null) { - if (current instanceof OptimisticLockException - || current instanceof OptimisticLockingFailureException - || isHibernateStaleState(current)) { - return current; - } - current = current.getCause(); - } - return null; - } - - /** - * Recognises Hibernate's stale-state exceptions by name. - * - *

Matching by name rather than by type keeps this class off Hibernate's API surface: the - * transaction module is provider-neutral by design, and a compile-time reference here would make - * the whole retry path depend on the ORM implementation. - */ - private static boolean isHibernateStaleState(Throwable candidate) { - String name = candidate.getClass().getName(); - return "org.hibernate.StaleObjectStateException".equals(name) - || "org.hibernate.StaleStateException".equals(name); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/PersistenceFailureTranslatorChain.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/PersistenceFailureTranslatorChain.java deleted file mode 100644 index 10f6f957..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/PersistenceFailureTranslatorChain.java +++ /dev/null @@ -1,127 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.transaction; - -import dev.caskeleton.adapter.outbound.persistence.api.PersistenceOperationName; -import dev.caskeleton.adapter.outbound.persistence.api.error.JpaPersistenceException; -import dev.caskeleton.adapter.outbound.persistence.api.error.OptimisticConflictException; -import dev.caskeleton.adapter.outbound.persistence.api.error.VendorFailureTranslator; -import java.time.Duration; -import java.util.Objects; -import java.util.Optional; - -/** - * The single place a raw failure becomes a classified one. - * - *

The retry coordinator catches {@link JpaPersistenceException} and nothing else, and the - * executor ran the transaction template without translating anything. So the failures contention - * actually produces — Hibernate's {@code OptimisticLockException}, Spring's {@code - * OptimisticLockingFailureException}, a raw serialization or deadlock {@code DataAccessException} — - * left the executor untranslated, missed the coordinator's catch entirely, and were never retried. - * The unit fixtures passed because they threw an already-translated exception. - * - *

The order is the contract: - * - *

    - *
  1. An already-classified failure passes through unchanged. Re-translating one would rebuild - * its context and lose the attempt, key and completion verdict it already carries. - *
  2. Optimistic conflicts, which are provider exceptions with no SQLSTATE, so no SQLSTATE-based - * translator can recognise them. - *
  3. Vendor SQLSTATE, which covers serialization failure, deadlock and the constraint families. - *
  4. Anything else is returned untouched. A domain exception, an assertion failure or a {@code - * NullPointerException} is not a persistence failure, and dressing it as one would make a - * programming error look retryable. - *
- * - *

Every translator is handed the same operation, attempt, elapsed and trace values from one - * call, so two translators cannot describe the same attempt differently. - */ -public final class PersistenceFailureTranslatorChain { - - private final OptimisticConflictTranslator optimisticConflicts; - private final VendorFailureTranslator vendorFailures; - - /** - * Creates the chain. - * - * @param optimisticConflicts recognises provider optimistic-lock exceptions - * @param vendorFailures classifies SQLSTATEs and registered constraints - */ - public PersistenceFailureTranslatorChain( - OptimisticConflictTranslator optimisticConflicts, VendorFailureTranslator vendorFailures) { - this.optimisticConflicts = Objects.requireNonNull(optimisticConflicts, "optimisticConflicts"); - this.vendorFailures = Objects.requireNonNull(vendorFailures, "vendorFailures"); - } - - /** - * A chain with no vendor translator, for a composition that has not supplied one. - * - *

Vendor-free by construction: naming a vendor here would put the transaction package back in - * the cycle {@link VendorFailureTranslator} exists to break. A composition that wants SQLSTATE - * classification passes its vendor's translator in. - */ - public static PersistenceFailureTranslatorChain withoutCatalogs() { - return new PersistenceFailureTranslatorChain( - OptimisticConflictTranslator.withoutCatalog(), NO_VENDOR_TRANSLATOR); - } - - /** The marker returned when no vendor translator is configured. */ - private static final VendorFailureTranslator NO_VENDOR_TRANSLATOR = - (failure, operation, attempt, elapsed, traceId) -> null; - - /** - * Classifies one failure. - * - * @param failure what the attempt threw - * @param operation the registered operation the attempt served - * @param attempt the 1-based attempt number - * @param elapsed how long the attempt ran - * @param traceId the current trace identifier, or {@code null} - * @return the classified failure, or the original when it is not a persistence failure - */ - public Throwable translate( - Throwable failure, - PersistenceOperationName operation, - int attempt, - Duration elapsed, - String traceId) { - - Objects.requireNonNull(failure, "failure"); - Objects.requireNonNull(operation, "operation"); - Objects.requireNonNull(elapsed, "elapsed"); - - if (failure instanceof JpaPersistenceException alreadyClassified) { - return alreadyClassified; - } - Optional conflict = - optimisticConflicts.translate(failure, operation, attempt, elapsed, traceId); - if (conflict.isPresent()) { - return conflict.get(); - } - if (hasSqlState(failure)) { - JpaPersistenceException classified = - vendorFailures.translate(failure, operation, attempt, elapsed, traceId); - // A composition that supplied no vendor translator still gets its failure back unchanged, and - // the coordinator treats it as it treats anything it cannot classify: terminally. - return classified == null ? failure : classified; - } - return failure; - } - - /** - * Whether a SQLSTATE is reachable from this failure. - * - *

Asked before delegating, because the vendor translator answers for everything it is given — - * and a failure with no SQLSTATE is not a database failure it should be classifying. - */ - private static boolean hasSqlState(Throwable failure) { - for (Throwable current = failure; current != null; current = current.getCause()) { - if (current instanceof java.sql.SQLException sqlException - && sqlException.getSQLState() != null) { - return true; - } - if (current == current.getCause()) { - break; - } - } - return false; - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/RetryBudget.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/RetryBudget.java deleted file mode 100644 index ea5a2b68..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/RetryBudget.java +++ /dev/null @@ -1,53 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.transaction; - -import dev.caskeleton.adapter.outbound.persistence.api.transaction.RetryProfile; -import java.time.Duration; -import java.util.Objects; - -/** - * The two independent bounds on retrying one logical use case (design §19.2). - * - *

Attempt count alone is not a bound. Three attempts against a lock that takes ten seconds to - * time out is a thirty-second call, and the caller upstream gave up long ago. The elapsed bound is - * what keeps retry from outliving the request that asked for it. - */ -public record RetryBudget(int maxAttempts, Duration maxElapsed) { - - public RetryBudget { - Objects.requireNonNull(maxElapsed, "maxElapsed"); - if (maxAttempts < 1) { - throw new IllegalArgumentException("maxAttempts must be at least 1"); - } - if (maxElapsed.isNegative()) { - throw new IllegalArgumentException("maxElapsed must not be negative"); - } - } - - /** The budget a profile allows, bounded additionally by an overall deadline. */ - public static RetryBudget forProfile(RetryProfile profile, Duration maxElapsed) { - Objects.requireNonNull(profile, "profile"); - return new RetryBudget(profile.maxAttempts(), maxElapsed); - } - - /** A budget that permits exactly one attempt. */ - public static RetryBudget single() { - return new RetryBudget(1, Duration.ZERO); - } - - /** - * Whether another attempt is permitted. - * - * @param completedAttempts how many attempts have already run - * @param elapsed how long the logical operation has been running - * @param nextDelay the backoff that would be waited before the next attempt - */ - public boolean allowsAnotherAttempt(int completedAttempts, Duration elapsed, Duration nextDelay) { - if (completedAttempts >= maxAttempts) { - return false; - } - if (maxElapsed.isZero()) { - return true; - } - return elapsed.plus(nextDelay).compareTo(maxElapsed) < 0; - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/RetrySleeper.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/RetrySleeper.java deleted file mode 100644 index 194abe4b..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/RetrySleeper.java +++ /dev/null @@ -1,23 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.transaction; - -import java.time.Duration; - -/** - * The seam the retry coordinator waits through (design §19.3). - * - *

It exists so backoff is testable. A retry suite that really slept would either take minutes or - * be tuned down to backoffs so short that they no longer exercise the ordering they are meant to - * prove. - */ -@FunctionalInterface -public interface RetrySleeper { - - /** - * Waits for {@code delay} before the next attempt. - * - *

Implementations must not hold a JDBC connection or a Persistence Context while waiting: the - * attempt's transaction has already ended, and holding either would turn backoff into pool - * pressure (design §19.2). - */ - void sleep(Duration delay); -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringJpaTransactionExecutor.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringJpaTransactionExecutor.java deleted file mode 100644 index e2e5cd72..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringJpaTransactionExecutor.java +++ /dev/null @@ -1,105 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.transaction; - -import dev.caskeleton.adapter.outbound.persistence.api.PersistenceOperationName; -import dev.caskeleton.adapter.outbound.persistence.api.transaction.JpaTransactionExecutor; -import dev.caskeleton.adapter.outbound.persistence.api.transaction.TransactionProfile; -import java.time.Clock; -import java.time.Duration; -import java.time.Instant; -import java.util.Objects; -import java.util.function.Supplier; -import org.springframework.transaction.PlatformTransactionManager; -import org.springframework.transaction.support.TransactionTemplate; - -/** - * Runs one unit of work inside one transaction described by a profile (design §9.3). - * - *

A fresh {@link TransactionTemplate} is built per call. Reusing a shared, mutated template is - * the classic way concurrent callers end up executing under each other's isolation level or - * read-only flag, because the reconfiguration and the execution are not atomic. - * - *

This class does not retry. Retry lives in {@link FullTransactionRetryCoordinator}, which calls - * back into here for every attempt precisely so each attempt gets a new transaction and a new - * Persistence Context (design §19.2). - */ -public final class SpringJpaTransactionExecutor implements JpaTransactionExecutor { - - private final PlatformTransactionManager transactionManager; - private final Clock clock; - private final PersistenceFailureTranslatorChain failureTranslators; - - /** An executor translating raw failures with the default, catalog-free chain. */ - public SpringJpaTransactionExecutor(PlatformTransactionManager transactionManager, Clock clock) { - this(transactionManager, clock, PersistenceFailureTranslatorChain.withoutCatalogs()); - } - - /** - * Creates the executor. - * - * @param failureTranslators classifies what an attempt threw, at the attempt boundary - */ - public SpringJpaTransactionExecutor( - PlatformTransactionManager transactionManager, - Clock clock, - PersistenceFailureTranslatorChain failureTranslators) { - this.transactionManager = Objects.requireNonNull(transactionManager, "transactionManager"); - this.clock = Objects.requireNonNull(clock, "clock"); - this.failureTranslators = Objects.requireNonNull(failureTranslators, "failureTranslators"); - } - - @Override - public T execute( - PersistenceOperationName operation, TransactionProfile profile, Supplier work) { - return execute(operation, profile, work, 1, null); - } - - /** - * Executes one attempt, recording which attempt it is and which reconciliation key it carries. - * - *

The retry coordinator uses this overload so a completion-unknown failure raised on attempt - * three reports attempt three and the caller's transaction key, rather than defaulting to the - * first attempt with no key. - * - * @param attempt the 1-based attempt number - * @param transactionKey the application's reconciliation key, or {@code null} when none is bound - */ - public T execute( - PersistenceOperationName operation, - TransactionProfile profile, - Supplier work, - int attempt, - String transactionKey) { - Objects.requireNonNull(operation, "operation"); - Objects.requireNonNull(profile, "profile"); - Objects.requireNonNull(work, "work"); - TransactionTemplate template = new TransactionTemplate(transactionManager); - TransactionDefinitionMapper.apply(template, profile); - // One owner for the frame's lifetime. The manager marks phases and pops nothing, so a nested - // REQUIRES_NEW transaction can no longer delete the frame belonging to the one it suspended. - try (TransactionEvidenceScope scope = - TransactionEvidenceContext.begin(operation, transactionKey, clock.instant(), attempt)) { - Instant attemptStartedAt = clock.instant(); - try { - return template.execute(status -> work.get()); - } catch (RuntimeException failure) { - // Translated at the attempt boundary, which is the only place that knows the operation, the - // attempt number and how long it ran. Without this the retry coordinator — which catches - // JpaPersistenceException — never saw an optimistic conflict or a raw serialization - // failure, and production contention went unretried while the fixtures passed. - Throwable translated = - failureTranslators.translate( - failure, - operation, - attempt, - Duration.between(attemptStartedAt, clock.instant()), - TransactionEvidenceContext.current() - .flatMap(TransactionEvidenceFrame::reconciliationKey) - .orElse(null)); - if (translated instanceof RuntimeException runtime) { - throw runtime; - } - throw failure; - } - } - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringPolicyTransactionPort.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringPolicyTransactionPort.java deleted file mode 100644 index 905397e8..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringPolicyTransactionPort.java +++ /dev/null @@ -1,290 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.transaction; - -import dev.caskeleton.adapter.outbound.persistence.failure.PersistenceExceptionTranslator; -import dev.caskeleton.application.transaction.OperationId; -import dev.caskeleton.application.transaction.TransactionAdmissionException; -import dev.caskeleton.application.transaction.TransactionPhase; -import dev.caskeleton.application.transaction.TransactionPolicyId; -import dev.caskeleton.application.transaction.TransactionRequest; -import dev.caskeleton.application.transaction.TransactionResult; -import java.util.Locale; -import java.util.Objects; -import java.util.Optional; -import java.util.function.LongSupplier; -import java.util.function.Supplier; -import org.springframework.core.Ordered; -import org.springframework.transaction.PlatformTransactionManager; -import org.springframework.transaction.TransactionDefinition; -import org.springframework.transaction.TransactionStatus; -import org.springframework.transaction.UnexpectedRollbackException; -import org.springframework.transaction.support.DefaultTransactionDefinition; -import org.springframework.transaction.support.TransactionSynchronization; -import org.springframework.transaction.support.TransactionSynchronizationManager; - -/** Internal Spring executor for the application-owned named transaction policies. */ -final class SpringPolicyTransactionPort { - - private final PlatformTransactionManager transactionManager; - private final LongSupplier monotonicNanos; - private final TransactionDeadlineCalculator deadlineCalculator; - private final TransactionRetryBackoff retryBackoff; - private final TransactionLocalTimeoutConfigurer localTimeoutConfigurer; - private final PersistenceExceptionTranslator exceptionTranslator; - - SpringPolicyTransactionPort( - PlatformTransactionManager transactionManager, - LongSupplier monotonicNanos, - TransactionDeadlineCalculator deadlineCalculator, - TransactionRetryBackoff retryBackoff, - TransactionLocalTimeoutConfigurer localTimeoutConfigurer, - PersistenceExceptionTranslator exceptionTranslator) { - this.transactionManager = - Objects.requireNonNull(transactionManager, "transactionManager must be non-null"); - this.monotonicNanos = Objects.requireNonNull(monotonicNanos, "monotonicNanos must be non-null"); - this.deadlineCalculator = - Objects.requireNonNull(deadlineCalculator, "deadlineCalculator must be non-null"); - this.retryBackoff = Objects.requireNonNull(retryBackoff, "retryBackoff must be non-null"); - this.localTimeoutConfigurer = - Objects.requireNonNull(localTimeoutConfigurer, "localTimeoutConfigurer must be non-null"); - this.exceptionTranslator = - Objects.requireNonNull(exceptionTranslator, "exceptionTranslator must be non-null"); - } - - TransactionResult execute(TransactionRequest request, Supplier action) { - Objects.requireNonNull(request, "request must be non-null"); - Objects.requireNonNull(action, "action must be non-null"); - - PolicySpec policy = policy(request.policyId()); - if (policy.replicaRequired()) { - throw new TransactionAdmissionException( - "replica transaction policy is unavailable until the replica capability is qualified"); - } - - int attempt = 1; - while (true) { - AttemptResult attemptResult = executeOnce(request, action, policy); - if (!shouldRetry(request.policyId(), attemptResult, attempt)) { - return attemptResult.result(); - } - if (!retryBackoff.pauseBeforeRetry(request.callBudget(), attempt)) { - return attemptResult.result(); - } - attempt++; - } - } - - private AttemptResult executeOnce( - TransactionRequest request, Supplier action, PolicySpec policy) { - TransactionStartBudget startBudget = - deadlineCalculator.beforeAcquisition(request.callBudget(), monotonicNanos.getAsLong()); - DefaultTransactionDefinition definition = definition(request.policyId(), startBudget, policy); - TransactionStatus status; - try { - status = transactionManager.getTransaction(definition); - } catch (RuntimeException failure) { - throw new TransactionAdmissionException( - "transaction acquisition failed before application work started", failure); - } - - PhaseTracker tracker = new PhaseTracker(); - tracker.observe(TransactionPhase.CONNECTION_ACQUIRED); - boolean physicalOwner = status.isNewTransaction(); - PhaseSentinel sentinel = registerSentinelIfPossible(physicalOwner, tracker); - tracker.observe(TransactionPhase.ACTIVE); - - try { - EffectiveTransactionTimeouts effectiveTimeouts = - deadlineCalculator.afterBegin( - request.callBudget(), monotonicNanos.getAsLong(), startBudget); - localTimeoutConfigurer.apply(effectiveTimeouts); - } catch (RuntimeException localTimeoutFailure) { - return new AttemptResult<>( - rollback(status, request.operationId(), tracker, localTimeoutFailure), physicalOwner); - } - - T value; - try { - value = action.get(); - } catch (RuntimeException actionFailure) { - return new AttemptResult<>( - rollback(status, request.operationId(), tracker, actionFailure), physicalOwner); - } - - tracker.observe(TransactionPhase.COMMIT_REQUESTED); - try { - transactionManager.commit(status); - } catch (RuntimeException commitFailure) { - if (sentinel.commitAcknowledged()) { - return new AttemptResult<>( - new TransactionResult.CommittedWithPostCommitFailure<>( - value, request.operationId(), commitFailure), - physicalOwner); - } - if (sentinel.rolledBack() - || commitFailure instanceof UnexpectedRollbackException - || TransactionRetryClassifier.isReplayCandidate(commitFailure)) { - return new AttemptResult<>( - new TransactionResult.DeterminateRollback<>(translate(commitFailure)), physicalOwner); - } - return new AttemptResult<>( - new TransactionResult.Indeterminate<>( - request.operationId(), tracker.lastObserved(), Optional.empty()), - physicalOwner); - } - - if (!physicalOwner) { - return new AttemptResult<>(new TransactionResult.Participating<>(value), false); - } - tracker.observe(TransactionPhase.COMMIT_ACKED); - return new AttemptResult<>( - new TransactionResult.Committed<>(value, request.operationId()), true); - } - - private boolean shouldRetry( - TransactionPolicyId policyId, AttemptResult attemptResult, int attempt) { - if (policyId != TransactionPolicyId.COMMAND_SERIALIZABLE_REPLAY_SAFE - || !attemptResult.physicalOwner() - || attempt >= retryBackoff.maximumAttempts() - || Thread.currentThread().isInterrupted()) { - return false; - } - TransactionResult result = attemptResult.result(); - if (result instanceof TransactionResult.DeterminateRollback rollback) { - return TransactionRetryClassifier.isReplayCandidate(rollback.failure()); - } - return false; - } - - private TransactionResult rollback( - TransactionStatus status, - Optional operationId, - PhaseTracker tracker, - RuntimeException actionFailure) { - try { - transactionManager.rollback(status); - return new TransactionResult.DeterminateRollback<>(translate(actionFailure)); - } catch (RuntimeException rollbackFailure) { - actionFailure.addSuppressed(rollbackFailure); - return new TransactionResult.Indeterminate<>( - operationId, tracker.lastObserved(), Optional.empty()); - } - } - - private RuntimeException translate(RuntimeException failure) { - return exceptionTranslator.translate(failure).map(RuntimeException.class::cast).orElse(failure); - } - - private DefaultTransactionDefinition definition( - TransactionPolicyId policyId, TransactionStartBudget startBudget, PolicySpec policy) { - DefaultTransactionDefinition definition = new DefaultTransactionDefinition(); - definition.setName("application-" + policyId.name().toLowerCase(Locale.ROOT)); - definition.setPropagationBehavior(policy.propagation()); - definition.setIsolationLevel(policy.isolation()); - definition.setReadOnly(policy.readOnly()); - definition.setTimeout(startBudget.springTimeoutSeconds()); - return definition; - } - - private static PolicySpec policy(TransactionPolicyId policyId) { - return switch (policyId) { - case COMMAND_DEFAULT, INBOX_AND_HANDLER -> - required(TransactionDefinition.ISOLATION_READ_COMMITTED, false); - case COMMAND_SERIALIZABLE_REPLAY_SAFE -> - required(TransactionDefinition.ISOLATION_SERIALIZABLE, false); - case QUERY_PRIMARY -> required(TransactionDefinition.ISOLATION_READ_COMMITTED, true); - case QUERY_REPLICA_ELIGIBLE -> - new PolicySpec( - TransactionDefinition.PROPAGATION_REQUIRED, - TransactionDefinition.ISOLATION_READ_COMMITTED, - true, - true); - case OUTBOX_APPEND -> required(TransactionDefinition.ISOLATION_READ_COMMITTED, false); - case MAINTENANCE_NEW -> - new PolicySpec( - TransactionDefinition.PROPAGATION_REQUIRES_NEW, - TransactionDefinition.ISOLATION_READ_COMMITTED, - false, - false); - }; - } - - private static PolicySpec required(int isolation, boolean readOnly) { - return new PolicySpec(TransactionDefinition.PROPAGATION_REQUIRED, isolation, readOnly, false); - } - - private static PhaseSentinel registerSentinelIfPossible( - boolean physicalOwner, PhaseTracker tracker) { - PhaseSentinel sentinel = new PhaseSentinel(tracker); - if (physicalOwner && TransactionSynchronizationManager.isSynchronizationActive()) { - TransactionSynchronizationManager.registerSynchronization(sentinel); - } - return sentinel; - } - - private record PolicySpec( - int propagation, int isolation, boolean readOnly, boolean replicaRequired) {} - - private record AttemptResult(TransactionResult result, boolean physicalOwner) { - - private AttemptResult { - Objects.requireNonNull(result, "result must be non-null"); - } - } - - private static final class PhaseTracker { - - private TransactionPhase lastObserved = TransactionPhase.ROUTE_ADMISSION; - - private void observe(TransactionPhase phase) { - lastObserved = phase; - } - - private TransactionPhase lastObserved() { - return lastObserved; - } - } - - // Not `implements TransactionSynchronization, Ordered`: TransactionSynchronization already - // extends Ordered, so naming it again says nothing and reads as though the ordering were - // this class's own idea rather than part of the callback contract it implements. - private static final class PhaseSentinel implements TransactionSynchronization { - - private final PhaseTracker tracker; - private boolean commitAcknowledged; - private int completionStatus = STATUS_UNKNOWN; - - private PhaseSentinel(PhaseTracker tracker) { - this.tracker = tracker; - } - - @Override - public int getOrder() { - return Ordered.HIGHEST_PRECEDENCE; - } - - @Override - public void beforeCommit(boolean readOnly) { - tracker.observe(TransactionPhase.FLUSHED); - } - - @Override - public void afterCommit() { - commitAcknowledged = true; - tracker.observe(TransactionPhase.COMMIT_ACKED); - } - - @Override - public void afterCompletion(int status) { - completionStatus = status; - tracker.observe(TransactionPhase.SYNCHRONIZATION_CLEANUP); - } - - private boolean commitAcknowledged() { - return commitAcknowledged || completionStatus == STATUS_COMMITTED; - } - - private boolean rolledBack() { - return completionStatus == STATUS_ROLLED_BACK; - } - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransactionPort.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransactionPort.java index fc29296e..4e54f6ec 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransactionPort.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransactionPort.java @@ -4,16 +4,11 @@ import dev.caskeleton.adapter.outbound.persistence.failure.PersistenceExceptionT import dev.caskeleton.adapter.outbound.persistence.failure.StandardSqlStateErrorMapping; import dev.caskeleton.application.transaction.Isolation; import dev.caskeleton.application.transaction.NestedRootTransactionRejectedException; -import dev.caskeleton.application.transaction.PolicyTransactionPort; import dev.caskeleton.application.transaction.TransactionMode; -import dev.caskeleton.application.transaction.TransactionRequest; -import dev.caskeleton.application.transaction.TransactionResult; -import java.time.Duration; +import dev.caskeleton.application.transaction.TransactionPort; import java.util.Locale; -import java.util.function.LongSupplier; import java.util.function.Supplier; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; @@ -21,95 +16,25 @@ import org.springframework.transaction.support.TransactionSynchronizationManager import org.springframework.transaction.support.TransactionTemplate; /** - * Spring-backed {@link PolicyTransactionPort}: one pre-built {@link TransactionTemplate} per mode, - * all pinned to {@link Isolation#READ_COMMITTED}. See README "transaction" for why the templates - * are pre-built (mutable-template race) and CLAUDE.md for the mode table. + * Spring-backed {@link TransactionPort}: one pre-built {@link TransactionTemplate} per mode, all + * pinned to {@link Isolation#READ_COMMITTED}. See README "transaction" for why the templates are + * pre-built (mutable-template race) and CLAUDE.md for the mode table. */ @Component -public class SpringTransactionPort implements PolicyTransactionPort { +public class SpringTransactionPort implements TransactionPort { private final TransactionTemplate writeTemplate; private final TransactionTemplate readTemplate; private final TransactionTemplate requiresNewTemplate; - private final SpringPolicyTransactionPort policyExecutor; private final PersistenceExceptionTranslator exceptionTranslator; public SpringTransactionPort(PlatformTransactionManager transactionManager) { - this( - transactionManager, - System::nanoTime, - TransactionDeadlineCalculator.withoutAcquisitionEnvelope( - new JpaTransactionSettings(null, null, null, null, null, null, null, null, null)), - ignored -> {}, - defaultExceptionTranslator()); - } - - SpringTransactionPort( - PlatformTransactionManager transactionManager, LongSupplier monotonicNanos) { - this( - transactionManager, - monotonicNanos, - TransactionDeadlineCalculator.withoutAcquisitionEnvelope( - new JpaTransactionSettings(null, null, null, null, null, null, null, null, null)), - ignored -> {}, - defaultExceptionTranslator()); + this(transactionManager, defaultExceptionTranslator()); } @Autowired public SpringTransactionPort( PlatformTransactionManager transactionManager, - JpaTransactionSettings settings, - TransactionLocalTimeoutConfigurer localTimeoutConfigurer, - @Value("${spring.datasource.hikari.connection-timeout:5000}") - long connectionAcquisitionTimeoutMillis, - PersistenceExceptionTranslator exceptionTranslator) { - this( - transactionManager, - System::nanoTime, - new TransactionDeadlineCalculator( - connectionAcquisitionTimeout(connectionAcquisitionTimeoutMillis), settings), - TransactionRetryBackoff.production( - settings, - connectionAcquisitionTimeout(connectionAcquisitionTimeoutMillis), - System::nanoTime), - localTimeoutConfigurer, - exceptionTranslator); - } - - SpringTransactionPort( - PlatformTransactionManager transactionManager, - LongSupplier monotonicNanos, - TransactionDeadlineCalculator deadlineCalculator, - TransactionLocalTimeoutConfigurer localTimeoutConfigurer) { - this( - transactionManager, - monotonicNanos, - deadlineCalculator, - localTimeoutConfigurer, - defaultExceptionTranslator()); - } - - SpringTransactionPort( - PlatformTransactionManager transactionManager, - LongSupplier monotonicNanos, - TransactionDeadlineCalculator deadlineCalculator, - TransactionLocalTimeoutConfigurer localTimeoutConfigurer, - PersistenceExceptionTranslator exceptionTranslator) { - this( - transactionManager, - monotonicNanos, - deadlineCalculator, - TransactionRetryBackoff.production(defaultSettings(), monotonicNanos), - localTimeoutConfigurer, - exceptionTranslator); - } - - SpringTransactionPort( - PlatformTransactionManager transactionManager, - LongSupplier monotonicNanos, - TransactionDeadlineCalculator deadlineCalculator, - TransactionRetryBackoff retryBackoff, - TransactionLocalTimeoutConfigurer localTimeoutConfigurer, PersistenceExceptionTranslator exceptionTranslator) { this.writeTemplate = template( @@ -129,20 +54,12 @@ public class SpringTransactionPort implements PolicyTransactionPort { TransactionMode.REQUIRES_NEW, TransactionDefinition.PROPAGATION_REQUIRES_NEW, false); - this.policyExecutor = - new SpringPolicyTransactionPort( - transactionManager, - monotonicNanos, - deadlineCalculator, - retryBackoff, - localTimeoutConfigurer, - exceptionTranslator); this.exceptionTranslator = exceptionTranslator; } @Override public T inWrite(Supplier action) { - return executeLegacy(writeTemplate, action); + return execute(writeTemplate, action); } @Override @@ -150,22 +67,17 @@ public class SpringTransactionPort implements PolicyTransactionPort { if (TransactionSynchronizationManager.isActualTransactionActive()) { throw new NestedRootTransactionRejectedException(); } - return executeLegacy(writeTemplate, action); + return execute(writeTemplate, action); } @Override public T inRead(Supplier action) { - return executeLegacy(readTemplate, action); + return execute(readTemplate, action); } @Override public T inNew(Supplier action) { - return executeLegacy(requiresNewTemplate, action); - } - - @Override - public TransactionResult inTransaction(TransactionRequest request, Supplier action) { - return policyExecutor.execute(request, action); + return execute(requiresNewTemplate, action); } private static TransactionTemplate template( @@ -181,15 +93,7 @@ public class SpringTransactionPort implements PolicyTransactionPort { return template; } - private static Duration connectionAcquisitionTimeout(long milliseconds) { - if (milliseconds <= 0) { - throw new IllegalArgumentException( - "spring.datasource.hikari.connection-timeout must be a positive millisecond value"); - } - return Duration.ofMillis(milliseconds); - } - - private T executeLegacy(TransactionTemplate template, Supplier action) { + private T execute(TransactionTemplate template, Supplier action) { try { return template.execute(status -> action.get()); } catch (RuntimeException failure) { @@ -216,8 +120,4 @@ public class SpringTransactionPort implements PolicyTransactionPort { return new PersistenceExceptionTranslator( java.util.List.of(new StandardSqlStateErrorMapping())); } - - private static JpaTransactionSettings defaultSettings() { - return new JpaTransactionSettings(null, null, null, null, null, null, null, null, null); - } } diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/ThreadRetrySleeper.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/ThreadRetrySleeper.java deleted file mode 100644 index 8147263a..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/ThreadRetrySleeper.java +++ /dev/null @@ -1,26 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.transaction; - -import java.time.Duration; - -/** - * The production {@link RetrySleeper}: parks the calling thread. - * - *

An interrupt is honoured rather than swallowed. Restoring the interrupt flag and aborting the - * retry is what lets a shutdown actually stop work that is between attempts, instead of waiting out - * every remaining backoff first. - */ -public final class ThreadRetrySleeper implements RetrySleeper { - - @Override - public void sleep(Duration delay) { - if (delay == null || delay.isZero() || delay.isNegative()) { - return; - } - try { - Thread.sleep(delay.toMillis()); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - throw new IllegalStateException("retry backoff was interrupted", interrupted); - } - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/TransactionDeadlineCalculator.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/TransactionDeadlineCalculator.java deleted file mode 100644 index 4a71a98d..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/TransactionDeadlineCalculator.java +++ /dev/null @@ -1,114 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.transaction; - -import dev.caskeleton.application.outbound.CallBudget; -import dev.caskeleton.application.transaction.TransactionAdmissionException; -import java.time.Duration; -import java.util.Objects; - -/** Computes conservative Spring and PostgreSQL timeout windows from one monotonic deadline. */ -final class TransactionDeadlineCalculator { - - private static final long NANOS_PER_MILLISECOND = Duration.ofMillis(1).toNanos(); - private static final long NANOS_PER_SECOND = Duration.ofSeconds(1).toNanos(); - - private final Duration connectionTimeout; - private final JpaTransactionSettings settings; - private final boolean ignoreAcquisitionEnvelope; - - TransactionDeadlineCalculator(Duration connectionTimeout, JpaTransactionSettings settings) { - this(connectionTimeout, settings, false); - } - - private TransactionDeadlineCalculator( - Duration connectionTimeout, - JpaTransactionSettings settings, - boolean ignoreAcquisitionEnvelope) { - this.connectionTimeout = - Objects.requireNonNull(connectionTimeout, "connectionTimeout must be non-null"); - this.settings = Objects.requireNonNull(settings, "settings must be non-null"); - this.ignoreAcquisitionEnvelope = ignoreAcquisitionEnvelope; - if (connectionTimeout.isNegative()) { - throw new IllegalArgumentException("connectionTimeout must not be negative"); - } - } - - static TransactionDeadlineCalculator withoutAcquisitionEnvelope(JpaTransactionSettings settings) { - return new TransactionDeadlineCalculator(Duration.ZERO, settings, true); - } - - TransactionStartBudget beforeAcquisition(CallBudget callBudget, long nowNanos) { - Objects.requireNonNull(callBudget, "callBudget must be non-null"); - long remainingNanos = callBudget.remainingNanosAt(nowNanos); - long requiredNanos = - ignoreAcquisitionEnvelope - ? 0 - : sumNanos( - connectionTimeout, - settings.beginBudget(), - settings.minimumActionWindow(), - settings.completionMargin()); - if (remainingNanos < requiredNanos) { - throw new TransactionAdmissionException( - "remaining call budget cannot contain pool acquisition, begin, action, and completion"); - } - - long safeTransactionNanos = - ignoreAcquisitionEnvelope - ? remainingNanos - : remainingNanos - - connectionTimeout.toNanos() - - settings.beginBudget().toNanos() - - settings.completionMargin().toNanos(); - long boundedNanos = Math.min(safeTransactionNanos, settings.transactionTimeout().toNanos()); - int timeoutSeconds = (int) Math.min(Integer.MAX_VALUE, boundedNanos / NANOS_PER_SECOND); - if (timeoutSeconds < 1) { - throw new TransactionAdmissionException( - "at least one second must remain for the Spring transaction timeout"); - } - return new TransactionStartBudget(timeoutSeconds, nowNanos); - } - - EffectiveTransactionTimeouts afterBegin( - CallBudget callBudget, long nowNanos, TransactionStartBudget startBudget) { - Objects.requireNonNull(callBudget, "callBudget must be non-null"); - Objects.requireNonNull(startBudget, "startBudget must be non-null"); - long elapsedNanos = Math.max(0, nowNanos - startBudget.acquisitionStartedNanos()); - long springRemainingNanos = - (long) startBudget.springTimeoutSeconds() * NANOS_PER_SECOND - elapsedNanos; - long callRemainingNanos = callBudget.remainingNanosAt(nowNanos); - long completionNanos = ignoreAcquisitionEnvelope ? 0 : settings.completionMargin().toNanos(); - long transactionMarginNanos = - ignoreAcquisitionEnvelope ? 0 : settings.transactionMargin().toNanos(); - long lockMarginNanos = ignoreAcquisitionEnvelope ? 1 : settings.lockMargin().toNanos(); - - long statementWindowNanos = - Math.min(callRemainingNanos - completionNanos, springRemainingNanos) - - transactionMarginNanos; - long statementNanos = Math.min(settings.statementTimeout().toNanos(), statementWindowNanos); - long lockNanos = Math.min(settings.lockTimeout().toNanos(), statementNanos - lockMarginNanos); - long idleNanos = - Math.min(settings.idleGuardTimeout().toNanos(), callRemainingNanos - completionNanos); - if (statementNanos < NANOS_PER_MILLISECOND - || lockNanos < NANOS_PER_MILLISECOND - || idleNanos < NANOS_PER_MILLISECOND) { - throw new TransactionAdmissionException( - "remaining call budget after transaction begin cannot contain local timeout windows"); - } - - return new EffectiveTransactionTimeouts( - Duration.ofNanos(statementNanos), Duration.ofNanos(lockNanos), Duration.ofNanos(idleNanos)); - } - - private static long sumNanos(Duration... durations) { - long result = 0; - try { - for (Duration duration : durations) { - result = Math.addExact(result, duration.toNanos()); - } - return result; - } catch (ArithmeticException exception) { - throw new IllegalArgumentException( - "transaction deadline settings exceed the supported range", exception); - } - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/TransactionDefinitionMapper.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/TransactionDefinitionMapper.java deleted file mode 100644 index bdaa8bf9..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/TransactionDefinitionMapper.java +++ /dev/null @@ -1,87 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.transaction; - -import dev.caskeleton.adapter.outbound.persistence.api.transaction.IsolationLevel; -import dev.caskeleton.adapter.outbound.persistence.api.transaction.PropagationMode; -import dev.caskeleton.adapter.outbound.persistence.api.transaction.TransactionProfile; -import java.time.Duration; -import java.util.Objects; -import org.springframework.transaction.TransactionDefinition; -import org.springframework.transaction.support.DefaultTransactionDefinition; -import org.springframework.transaction.support.TransactionTemplate; - -/** - * Translates a {@link TransactionProfile} into the Spring transaction definition it describes - * (design §9.2). - * - *

Timeouts round up to whole seconds. Spring's definition is second-granular, so a 1500 - * ms profile has to become either 1 s or 2 s; truncating would silently give the caller a shorter - * guard than the profile promised, and a write transaction that is cut off early is the failure - * mode this platform is trying to prevent. Rounding up is the direction that keeps the promise, and - * a profile expressed in whole seconds is unaffected. - */ -public final class TransactionDefinitionMapper { - - private TransactionDefinitionMapper() {} - - /** Applies {@code profile} to {@code template}, which must not be shared between calls. */ - public static void apply(TransactionTemplate template, TransactionProfile profile) { - Objects.requireNonNull(template, "template"); - Objects.requireNonNull(profile, "profile"); - template.setName(profile.name()); - template.setPropagationBehavior(propagationOf(profile.propagation())); - template.setIsolationLevel(isolationOf(profile.isolation())); - template.setReadOnly(profile.readOnly()); - template.setTimeout(timeoutSecondsOf(profile.timeout())); - } - - /** Builds a standalone definition for callers that drive a transaction manager directly. */ - public static TransactionDefinition definitionOf(TransactionProfile profile) { - Objects.requireNonNull(profile, "profile"); - DefaultTransactionDefinition definition = new DefaultTransactionDefinition(); - definition.setName(profile.name()); - definition.setPropagationBehavior(propagationOf(profile.propagation())); - definition.setIsolationLevel(isolationOf(profile.isolation())); - definition.setReadOnly(profile.readOnly()); - definition.setTimeout(timeoutSecondsOf(profile.timeout())); - return definition; - } - - /** The Spring propagation constant for a supported {@link PropagationMode}. */ - public static int propagationOf(PropagationMode mode) { - return switch (mode) { - case REQUIRED -> TransactionDefinition.PROPAGATION_REQUIRED; - case MANDATORY -> TransactionDefinition.PROPAGATION_MANDATORY; - case REQUIRES_NEW -> TransactionDefinition.PROPAGATION_REQUIRES_NEW; - }; - } - - /** The Spring isolation constant for a supported {@link IsolationLevel}. */ - public static int isolationOf(IsolationLevel level) { - return switch (level) { - case DEFAULT -> TransactionDefinition.ISOLATION_DEFAULT; - case READ_COMMITTED -> TransactionDefinition.ISOLATION_READ_COMMITTED; - case REPEATABLE_READ -> TransactionDefinition.ISOLATION_REPEATABLE_READ; - case SERIALIZABLE -> TransactionDefinition.ISOLATION_SERIALIZABLE; - }; - } - - /** - * The whole-second timeout Spring accepts, rounded up, or the connection default for zero. - * - * @throws IllegalArgumentException when the profile asks for more seconds than Spring can carry - */ - public static int timeoutSecondsOf(Duration timeout) { - Objects.requireNonNull(timeout, "timeout"); - if (timeout.isZero()) { - return TransactionDefinition.TIMEOUT_DEFAULT; - } - if (timeout.isNegative()) { - throw new IllegalArgumentException("transaction timeout must not be negative"); - } - long seconds = timeout.plusNanos(999_999_999L).toSeconds(); - if (seconds > Integer.MAX_VALUE) { - throw new IllegalArgumentException("transaction timeout exceeds the supported range"); - } - return (int) seconds; - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/TransactionEvidenceContext.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/TransactionEvidenceContext.java deleted file mode 100644 index ffdab76b..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/TransactionEvidenceContext.java +++ /dev/null @@ -1,152 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.transaction; - -import dev.caskeleton.adapter.outbound.persistence.api.PersistenceOperationName; -import dev.caskeleton.adapter.outbound.persistence.api.transaction.TransactionCompletionEvidence; -import java.time.Instant; -import java.util.ArrayDeque; -import java.util.Deque; -import java.util.Optional; - -/** - * Thread-bound record of how far the current transaction has got (design §17.2). - * - *

The state is a stack rather than a single value because {@code REQUIRES_NEW} suspends an outer - * transaction and begins an inner one on the same thread. With a single slot, the inner - * transaction's commit would overwrite the outer transaction's phase, and a later commit failure on - * the outer one would be classified against evidence that belongs to work that already finished. - * - *

Every path clears what it pushed, and a {@link TransactionEvidenceScope} is what proves it - * did. Two owners used to pop: the transaction manager cleared its frame on commit and rollback, - * and the executor's {@code finally} cleared the top frame whenever its operation and attempt - * matched. For a {@code REQUIRES_NEW} inner transaction under an outer one with the same operation - * and the same attempt number — which the default path always produces, since both are attempt 1 — - * the inner manager popped the inner frame and the executor then popped the outer one, mistaking it - * for its own. A later commit failure on the outer transaction was reported with no operation, - * attempt 1 and no reconciliation key. - * - *

So a scope carries an identity, closing it pops only when that identity is on top, and the - * manager marks phases without popping anything. A leaked frame is worse than no frame: pooled - * request threads would carry a stale "COMMITTING" into unrelated work, and the platform would - * report completion-unknown for a transaction that never existed. - */ -public final class TransactionEvidenceContext { - - /** - * Plain, not {@code withInitial}. An initialising thread-local installs a value on every read, so - * a read after the last frame was cleared re-registered exactly what {@code clear()} had removed. - */ - private static final ThreadLocal> FRAMES = new ThreadLocal<>(); - - private TransactionEvidenceContext() {} - - /** - * Pushes a frame for a transaction that is about to begin. - * - * @param operation the registered operation this transaction serves - * @param transactionKey the application's reconciliation key, or {@code null} when none is bound - * @param startedAt when the attempt began - * @param attempt the 1-based attempt number - */ - public static TransactionEvidenceScope begin( - PersistenceOperationName operation, String transactionKey, Instant startedAt, int attempt) { - TransactionEvidenceFrame frame = - TransactionEvidenceFrame.notStarted(operation, transactionKey, startedAt, attempt); - Deque frames = FRAMES.get(); - if (frames == null) { - frames = new ArrayDeque<>(); - FRAMES.set(frames); - } - frames.push(frame); - return new TransactionEvidenceScope(frames.size()); - } - - /** - * Advances the innermost frame to a new phase; a no-op when no transaction is bound. - * - *

Marking replaces the frame value, so the scope's identity has to travel with it — otherwise - * every phase change would orphan the token that owns the frame. - */ - public static void mark(TransactionCompletionEvidence evidence) { - Deque frames = rawFrames(); - if (frames == null) { - return; - } - TransactionEvidenceFrame current = frames.peek(); - if (current == null) { - return; - } - frames.pop(); - frames.push(current.at(evidence)); - } - - /** - * The innermost frame, when a transaction is bound to this thread. - * - *

Reads never create the thread-local. {@code FRAMES.get()} on a {@code withInitial} local - * installs an empty deque, so a read after the last frame was cleared re-registered exactly the - * value {@link #clear()} had just removed — and the leak this class documents came back through - * the accessor meant to observe it. - */ - public static Optional current() { - Deque frames = rawFrames(); - return frames == null ? Optional.empty() : Optional.ofNullable(frames.peek()); - } - - /** The innermost phase, or {@link TransactionCompletionEvidence#NOT_STARTED} when unbound. */ - public static TransactionCompletionEvidence evidence() { - return current() - .map(TransactionEvidenceFrame::evidence) - .orElse(TransactionCompletionEvidence.NOT_STARTED); - } - - /** - * Pops the innermost frame and removes the thread-local once the stack is empty. - * - *

Removing the empty deque matters on pooled threads: {@link ThreadLocal#withInitial} keeps a - * strong reference from the thread to the value, so leaving empty deques behind is a slow leak - * across every request thread in the pool. - */ - public static void clear() { - Deque frames = rawFrames(); - if (frames == null) { - return; - } - frames.poll(); - if (frames.isEmpty()) { - FRAMES.remove(); - } - } - - /** Whether this thread still holds a raw thread-local value; for tests asserting no leak. */ - public static boolean hasRawThreadLocalValue() { - return rawFrames() != null; - } - - /** The frames, without installing anything. */ - static Deque rawFrames() { - return FRAMES.get(); - } - - /** - * Pops one frame only when the scope's own frame is on top. - * - *

Out-of-order closing does not pop somebody else's frame. It reports {@code false} instead, - * and the caller decides what to do with a lifecycle that did not nest. - */ - static boolean closeIfOnTop(TransactionEvidenceScope scope) { - Deque frames = rawFrames(); - if (frames == null || frames.isEmpty() || !scope.ownsTopOf(frames.size())) { - return false; - } - frames.pop(); - if (frames.isEmpty()) { - FRAMES.remove(); - } - return true; - } - - /** Drops every frame on this thread. Intended for test teardown and error recovery only. */ - public static void clearAll() { - FRAMES.remove(); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/TransactionEvidenceFrame.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/TransactionEvidenceFrame.java deleted file mode 100644 index 079ec258..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/TransactionEvidenceFrame.java +++ /dev/null @@ -1,55 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.transaction; - -import dev.caskeleton.adapter.outbound.persistence.api.PersistenceOperationName; -import dev.caskeleton.adapter.outbound.persistence.api.transaction.TransactionCompletionEvidence; -import java.time.Instant; -import java.util.Objects; -import java.util.Optional; - -/** - * What is known about one physical transaction while it is running (design §17.1). - * - *

The frame is immutable; advancing the phase produces a new frame. That is deliberate: a - * mutable phase field is exactly the thing that gets written from a callback after the transaction - * has already been cleaned up, leaving the next unit of work on that thread reading a stale - * "COMMITTED". - */ -public record TransactionEvidenceFrame( - PersistenceOperationName operation, - String transactionKey, - Instant startedAt, - int attempt, - TransactionCompletionEvidence evidence) { - - public TransactionEvidenceFrame { - Objects.requireNonNull(operation, "operation"); - Objects.requireNonNull(startedAt, "startedAt"); - Objects.requireNonNull(evidence, "evidence"); - if (attempt < 1) { - throw new IllegalArgumentException("attempt must be at least 1"); - } - transactionKey = transactionKey == null ? "" : transactionKey.trim(); - } - - /** A frame for a transaction that has not begun yet. */ - public static TransactionEvidenceFrame notStarted( - PersistenceOperationName operation, String transactionKey, Instant startedAt, int attempt) { - return new TransactionEvidenceFrame( - operation, transactionKey, startedAt, attempt, TransactionCompletionEvidence.NOT_STARTED); - } - - /** The same transaction, observed at a later phase. */ - public TransactionEvidenceFrame at(TransactionCompletionEvidence phase) { - return new TransactionEvidenceFrame(operation, transactionKey, startedAt, attempt, phase); - } - - /** The application-chosen reconciliation key, when one was bound. */ - public Optional reconciliationKey() { - return transactionKey.isEmpty() ? Optional.empty() : Optional.of(transactionKey); - } - - /** Whether the provider has been asked to commit but has not answered. */ - public boolean committing() { - return evidence == TransactionCompletionEvidence.COMMITTING; - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/TransactionEvidenceScope.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/TransactionEvidenceScope.java deleted file mode 100644 index f68e62c0..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/TransactionEvidenceScope.java +++ /dev/null @@ -1,54 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.transaction; - -/** - * Ownership of one evidence frame, released exactly once by whoever pushed it. - * - *

Two owners used to pop. The transaction manager cleared its frame on commit and on rollback, - * and the executor's {@code finally} cleared the top frame whenever its operation and attempt - * matched — which, for a {@code REQUIRES_NEW} inner transaction nested under an outer one with the - * same operation and the same attempt number, described the outer frame just as accurately. The - * inner manager popped the inner frame, the executor then popped the outer one believing it was its - * own, and a subsequent commit failure on the outer transaction was reported with no operation, - * attempt 1, and no reconciliation key. - * - *

A scope is bound to its position in the stack rather than to the frame's contents, because the - * contents change: every phase transition replaces the frame value. Depth does not, and in a - * strictly nested lifecycle the frame at the depth this scope pushed is this scope's frame. - * - *

Closing out of order pops nothing. That is deliberate: a lifecycle that did not nest is a bug, - * and deleting an unrelated frame to paper over it is how the original defect looked from the - * outside. - */ -public final class TransactionEvidenceScope implements AutoCloseable { - - private final int depth; - private boolean released; - - TransactionEvidenceScope(int depth) { - this.depth = depth; - } - - /** Whether a stack of this size has this scope's frame on top. */ - boolean ownsTopOf(int currentDepth) { - return currentDepth == depth; - } - - /** - * Releases this scope's frame, if it is still the innermost one. - * - *

Idempotent: a second close does nothing rather than popping whatever has since arrived. - */ - @Override - public void close() { - if (released) { - return; - } - released = true; - TransactionEvidenceContext.closeIfOnTop(this); - } - - /** Whether this scope has already been released. */ - public boolean released() { - return released; - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/TransactionLocalTimeoutConfigurer.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/TransactionLocalTimeoutConfigurer.java deleted file mode 100644 index 147a2401..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/TransactionLocalTimeoutConfigurer.java +++ /dev/null @@ -1,8 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.transaction; - -/** Vendor implementation applies timeout values to the active physical transaction. */ -@FunctionalInterface -public interface TransactionLocalTimeoutConfigurer { - - void apply(EffectiveTransactionTimeouts timeouts); -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/TransactionProfileRegistry.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/TransactionProfileRegistry.java deleted file mode 100644 index a7d5afa8..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/TransactionProfileRegistry.java +++ /dev/null @@ -1,70 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.transaction; - -import dev.caskeleton.adapter.outbound.persistence.api.transaction.TransactionProfile; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Set; - -/** - * The bounded set of transaction profiles an application declares (design §9.2). - * - *

Lookup is fail-closed: an unregistered name throws rather than falling back to a default. A - * default would mean a typo in a profile name of {@code "order-wrtie"} silently runs with someone - * else's isolation, timeout, and retry budget. - */ -public final class TransactionProfileRegistry { - - private final Map byName; - - public TransactionProfileRegistry(Map profiles) { - Objects.requireNonNull(profiles, "profiles"); - Map copy = new LinkedHashMap<>(); - profiles.forEach( - (name, profile) -> { - Objects.requireNonNull(name, "profile name"); - Objects.requireNonNull(profile, "profile"); - if (!name.equals(profile.name())) { - throw new IllegalArgumentException( - "registry key '" + name + "' does not match profile name '" + profile.name() + "'"); - } - copy.put(name, profile); - }); - this.byName = Map.copyOf(copy); - } - - /** A registry built from profiles that already carry their own names. */ - public static TransactionProfileRegistry of(TransactionProfile... profiles) { - Map byName = new LinkedHashMap<>(); - for (TransactionProfile profile : profiles) { - if (byName.put(profile.name(), profile) != null) { - throw new IllegalArgumentException("duplicate transaction profile: " + profile.name()); - } - } - return new TransactionProfileRegistry(byName); - } - - /** - * The profile registered under {@code name}. - * - * @throws IllegalArgumentException when no profile is registered under that name - */ - public TransactionProfile require(String name) { - TransactionProfile profile = byName.get(name); - if (profile == null) { - throw new IllegalArgumentException( - "unregistered transaction profile '" + name + "'; registered profiles are " + names()); - } - return profile; - } - - /** Whether a profile is registered under {@code name}. */ - public boolean contains(String name) { - return byName.containsKey(name); - } - - /** The registered profile names, in declaration order. */ - public Set names() { - return byName.keySet(); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/TransactionRetryBackoff.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/TransactionRetryBackoff.java deleted file mode 100644 index 34723da7..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/TransactionRetryBackoff.java +++ /dev/null @@ -1,121 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.transaction; - -import dev.caskeleton.application.outbound.CallBudget; -import java.time.Duration; -import java.util.Objects; -import java.util.concurrent.ThreadLocalRandom; -import java.util.concurrent.locks.LockSupport; -import java.util.function.LongSupplier; - -/** Bounded exponential full-jitter pause constrained by the caller's absolute budget. */ -final class TransactionRetryBackoff { - - @FunctionalInterface - interface NanosSleeper { - void sleep(long nanos); - } - - @FunctionalInterface - interface JitterSource { - long nextLong(long exclusiveBound); - } - - private final JpaTransactionSettings settings; - private final LongSupplier monotonicNanos; - private final NanosSleeper sleeper; - private final JitterSource jitter; - private final long minimumNextAttemptNanos; - - TransactionRetryBackoff( - JpaTransactionSettings settings, - LongSupplier monotonicNanos, - NanosSleeper sleeper, - JitterSource jitter) { - this(settings, Duration.ZERO, monotonicNanos, sleeper, jitter); - } - - TransactionRetryBackoff( - JpaTransactionSettings settings, - Duration connectionAcquisitionTimeout, - LongSupplier monotonicNanos, - NanosSleeper sleeper, - JitterSource jitter) { - this.settings = Objects.requireNonNull(settings, "settings"); - Objects.requireNonNull(connectionAcquisitionTimeout, "connectionAcquisitionTimeout"); - if (connectionAcquisitionTimeout.isNegative()) { - throw new IllegalArgumentException("connectionAcquisitionTimeout must not be negative"); - } - this.monotonicNanos = Objects.requireNonNull(monotonicNanos, "monotonicNanos"); - this.sleeper = Objects.requireNonNull(sleeper, "sleeper"); - this.jitter = Objects.requireNonNull(jitter, "jitter"); - try { - this.minimumNextAttemptNanos = - Math.addExact( - connectionAcquisitionTimeout.toNanos(), - Math.addExact( - settings.minimumActionWindow().toNanos(), - Math.addExact( - settings.beginBudget().toNanos(), settings.completionMargin().toNanos()))); - } catch (ArithmeticException exception) { - throw new IllegalArgumentException( - "retry minimum attempt window exceeds long range", exception); - } - } - - static TransactionRetryBackoff production( - JpaTransactionSettings settings, LongSupplier monotonicNanos) { - return production(settings, Duration.ZERO, monotonicNanos); - } - - static TransactionRetryBackoff production( - JpaTransactionSettings settings, - Duration connectionAcquisitionTimeout, - LongSupplier monotonicNanos) { - return new TransactionRetryBackoff( - settings, - connectionAcquisitionTimeout, - monotonicNanos, - LockSupport::parkNanos, - bound -> ThreadLocalRandom.current().nextLong(bound)); - } - - boolean pauseBeforeRetry(CallBudget callBudget, int completedAttempts) { - Objects.requireNonNull(callBudget, "callBudget"); - if (completedAttempts < 1 || Thread.currentThread().isInterrupted()) { - return false; - } - long cappedDelayNanos = cappedExponentialDelay(completedAttempts); - long jitteredDelayNanos = jitter.nextLong(cappedDelayNanos + 1); - long remainingNanos = callBudget.remainingNanosAt(monotonicNanos.getAsLong()); - if (remainingNanos <= saturatedAdd(jitteredDelayNanos, minimumNextAttemptNanos)) { - return false; - } - if (jitteredDelayNanos > 0) { - sleeper.sleep(jitteredDelayNanos); - } - return !Thread.currentThread().isInterrupted() - && callBudget.remainingNanosAt(monotonicNanos.getAsLong()) > minimumNextAttemptNanos; - } - - int maximumAttempts() { - return settings.retryMaximumAttempts(); - } - - private long cappedExponentialDelay(int completedAttempts) { - long baseNanos = settings.retryBaseDelay().toNanos(); - long maximumNanos = settings.retryMaximumDelay().toNanos(); - int shift = Math.min(completedAttempts - 1, 62); - if (baseNanos > (maximumNanos >> shift)) { - return maximumNanos; - } - return Math.min(maximumNanos, baseNanos << shift); - } - - private static long saturatedAdd(long left, long right) { - try { - return Math.addExact(left, right); - } catch (ArithmeticException ignored) { - return Long.MAX_VALUE; - } - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/TransactionRetryClassifier.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/TransactionRetryClassifier.java deleted file mode 100644 index f7b9526e..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/TransactionRetryClassifier.java +++ /dev/null @@ -1,25 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.transaction; - -import java.sql.SQLException; - -/** Fail-closed SQLState classifier for replay-safe whole-transaction retries. */ -final class TransactionRetryClassifier { - - private static final String SERIALIZATION_FAILURE = "40001"; - private static final String POSTGRESQL_DEADLOCK = "40P01"; - - private TransactionRetryClassifier() {} - - static boolean isReplayCandidate(Throwable failure) { - for (Throwable current = failure; current != null; current = current.getCause()) { - if (current instanceof SQLException sqlException) { - String sqlState = sqlException.getSQLState(); - return SERIALIZATION_FAILURE.equals(sqlState) || POSTGRESQL_DEADLOCK.equals(sqlState); - } - if (current.getCause() == current) { - return false; - } - } - return false; - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/TransactionStartBudget.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/TransactionStartBudget.java deleted file mode 100644 index 129ddd35..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/TransactionStartBudget.java +++ /dev/null @@ -1,11 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.transaction; - -/** Conservative Spring transaction timeout selected before pool acquisition. */ -public record TransactionStartBudget(int springTimeoutSeconds, long acquisitionStartedNanos) { - - public TransactionStartBudget { - if (springTimeoutSeconds < 1) { - throw new IllegalArgumentException("springTimeoutSeconds must be positive"); - } - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/UnknownOperation.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/UnknownOperation.java deleted file mode 100644 index dafbed73..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/UnknownOperation.java +++ /dev/null @@ -1,19 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.transaction; - -import dev.caskeleton.adapter.outbound.persistence.api.PersistenceOperationName; - -/** - * The registered placeholder used when a failure arrives with no bound operation. - * - *

A failure context requires an operation name. Inventing one from the call stack or the SQL - * would be unbounded, and leaving it null would push a null check into every consumer, so an - * unattributed failure is reported under this fixed, registered name instead. - */ -public final class UnknownOperation { - - /** The bounded operation name used for failures raised outside any registered operation. */ - public static final PersistenceOperationName NAME = - new PersistenceOperationName("jpa.unattributed"); - - private UnknownOperation() {} -} diff --git a/src/adapter/outbound/persistence-jpa/src/main/resources/META-INF/spring.factories b/src/adapter/outbound/persistence-jpa/src/main/resources/META-INF/spring.factories new file mode 100644 index 00000000..89c14d50 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/main/resources/META-INF/spring.factories @@ -0,0 +1,2 @@ +org.springframework.boot.EnvironmentPostProcessor=\ +dev.caskeleton.adapter.outbound.persistence.startup.JpaActivationEnvironmentPostProcessor diff --git a/src/adapter/outbound/persistence-jpa/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/src/adapter/outbound/persistence-jpa/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports index 20d91dbe..7859507f 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports +++ b/src/adapter/outbound/persistence-jpa/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports @@ -1,2 +1,3 @@ dev.caskeleton.adapter.outbound.persistence.autoconfigure.PersistenceJpaAutoConfiguration dev.caskeleton.adapter.outbound.persistence.autoconfigure.PersistenceJpaRuntimeConfig +dev.caskeleton.adapter.outbound.persistence.startup.JpaStartupAutoConfiguration diff --git a/src/adapter/outbound/persistence-jpa/src/main/resources/config/module-defaults/persistence-jpa.yml b/src/adapter/outbound/persistence-jpa/src/main/resources/config/module-defaults/persistence-jpa.yml new file mode 100644 index 00000000..ab2fb8bf --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/main/resources/config/module-defaults/persistence-jpa.yml @@ -0,0 +1,203 @@ +# persistence-jpa 모듈이 가져오는 기본 설정. 이 모듈을 runtimeOnly 로 고르면 함께 들어오고, 그 줄을 +# 지우면 함께 사라진다. +# +# ModuleDefaultsEnvironmentPostProcessor(adapter:outbound:support)가 가장 낮은 우선순위로 읽는다. +# application*.yml, 환경변수, 명령행 인자가 언제나 이긴다. 여기서 하는 일은 APP_* 환경변수를 +# 하이픈이 든 속성 트리에 연결하고 안전한 기본값을 두는 것뿐이다. +spring: + datasource: + # jdbc URL: jdbc:postgresql://host:5432/db + url: ${APP_DATASOURCE_URL} + username: ${APP_DATASOURCE_USERNAME} + password: ${APP_DATASOURCE_PASSWORD} + driver-class-name: ${APP_DATASOURCE_DRIVER:org.postgresql.Driver} + hikari: + # D1 (feature-database-connection-pool-contract): small-pool axiom + PostgreSQL formula + # starting point (maximumPoolSize = cores * 2 + effective_spindle_count, adjust via load + # test). Fixed-size pool recommended (minimumIdle = maximumPoolSize). Must satisfy + # application-port D12 REQUIRES_NEW lower bound: + # maxPoolSize >= concurrent_threads * (1 + max_inNew_depth) + 1 + # Value owner: feature-env-driven-runtime-configuration (APP_DATASOURCE_POOL_MAX_SIZE). + # integer >= 1 + maximum-pool-size: ${APP_DATASOURCE_POOL_MAX_SIZE:10} + # D1: fixed-size pool recommended (minimumIdle = maximumPoolSize per HikariCP #HIKARI-CFG-C8). + # Current registry value min-idle=2 is a MIN_IDLE_POLICY_DRIFT vs the fixed-size + # recommendation; value alignment is delegated to feature-env-driven-runtime-configuration. + # integer >= 0 + minimum-idle: ${APP_DATASOURCE_POOL_MIN_IDLE:2} + # D2 (HIKARI-CFG-C1): fail-fast pin — reject pool-starved threads quickly rather than + # holding them for 30 s (HikariCP default). Must be >= 250 ms (enforced at startup by + # HikariPoolConstraintValidator). Typical synchronous HTTP path value: a few seconds. + # PLAIN MILLISECONDS ONLY. This key binds onto HikariConfig#setConnectionTimeout, which takes + # a long, so the binder rejects "5s" outright: `failed to convert java.lang.String to long`. + # It shipped as "5s" and every prod and dev deployment failed to start on it, while local + # passed because application-local.yml overrides the value — so only a prod lane could find + # it. HikariPoolConstraintValidator reads this key with DurationStyle and therefore accepts + # "5s" happily; that tolerance is what made the wrong default look supported, and it is + # recorded as an open Section A finding rather than quietly changed here. + connection-timeout: ${APP_DATASOURCE_CONNECTION_TIMEOUT:5000} + # milliseconds + idle-timeout: ${APP_DATASOURCE_POOL_IDLE_TIMEOUT:600000} + # D3 (HIKARI-CFG-C2): must be several seconds shorter than the DB/infrastructure idle + # timeout (DB wait_timeout, PgBouncer idle_transaction_timeout, firewall NAT timeout). + # Current default (30 min) is a placeholder until the actual DB wait_timeout is confirmed + # (see §Claims "DB wait_timeout 미확인" — needs-confirmation). Recommended: DB_idle_limit + # minus at least 60 s as a conservative margin. Value owner: feature-env-driven. + # milliseconds + max-lifetime: ${APP_DATASOURCE_POOL_MAX_LIFETIME:1800000} + # D4 (HIKARI-CFG-C4): greenfield — ping idle connections to prevent NAT/firewall/DB + # idle-kill from silently dropping them. Constraint: keepalive-time < max-lifetime + # (enforced by HikariPoolConstraintValidator). Provisional literal 120 000 ms (2 min); + # adjust once actual DB/firewall idle timeout is confirmed (§Claims). + # UNSUPPORTED_IMPL_DECISION: literal value is a provisional policy default. + # New env key APP_DATASOURCE_KEEPALIVE_TIME registration delegated to + # feature-env-driven-runtime-configuration. + keepalive-time: 120000 + # D5 (HIKARI-CFG-C5): greenfield — enable connection leak early warning. Value must be + # >= 2000 ms to activate (enforced by HikariPoolConstraintValidator; 0 = disabled). + # Provisional literal 30 000 ms (30 s) — chosen well above the estimated longest normal + # transaction (~5 s) to avoid false positives on legitimate slow operations. + # UNSUPPORTED_IMPL_DECISION: literal value is a provisional policy default. + # New env key APP_DATASOURCE_LEAK_DETECTION_THRESHOLD delegated to + # feature-env-driven-runtime-configuration. + leak-detection-threshold: 30000 + # D7 (HIKARI-CFG-C6): greenfield — must be < connection-timeout (HIKARI-CFG-C6), + # enforced by HikariPoolConstraintValidator. Resolves VALIDATION_TIMEOUT_CONFLICT: + # HikariCP default 5000 ms equals connection-timeout 5 s / 5000 ms → constraint + # violation. Provisional literal 3000 ms satisfies the constraint for connection-timeout + # values >= 3001 ms. + # UNSUPPORTED_IMPL_DECISION: literal value is a provisional policy default. + # New env key APP_DATASOURCE_VALIDATION_TIMEOUT delegated to + # feature-env-driven-runtime-configuration. + validation-timeout: 3000 + # D6 (HIKARI-CFG-C7): greenfield — keep positive (default = 1 ms) to fail fast when DB + # is unavailable at startup. Aligns with runtime-health startup validation and project-note + # §9 "잘못된 env 값 startup fail-fast" policy. Negative value disables fail-fast (allowed + # only in orchestration environments where DB may start after the app — coordinate with + # runtime-health-lifecycle branch). + # UNSUPPORTED_IMPL_DECISION: literal value is a provisional policy default. + # New env key APP_DATASOURCE_INIT_FAIL_TIMEOUT delegated to + # feature-env-driven-runtime-configuration. + initialization-fail-timeout: 1 + # --------------------------------------------------------------------------- + # D8 (feature-database-connection-pool-contract) — SLOW QUERY DETECTION + # POLICY ONLY — no library dependency added here. Implementation is DEFERRED + # pending local verification (TODO #3: confirm ParameterTransformer masking + # applies to slow-query listener output). + # + # Baseline (app layer, param-safe): + # datasource-proxy SlowQueryListener + ParameterTransformer ([REDACTED] masking). + # Requires the datasource-proxy / spring-boot-data-source-decorator dependency + # and a @Bean ParameterTransformer; deferred until masking behavior on slow-query + # output is locally verified. + # + # Production augment (DBA-owned): + # DB-side log_min_duration_statement — parameters included in extended-protocol + # output (PostgreSQL official security warning). DBA controls and redacts. + # + # Dev only (PROD-FORBIDDEN): + # Hibernate SQL_SLOW (LOG_QUERIES_SLOWER_THAN_MS) logs materialized SQL with + # substituted parameters — violates the "SQL/param 로그 금지" hard rule from + # feature-persistence-failure-baseline. NEVER enable in prod. + # + # Rejected: + # P6Spy — no built-in masking API; effective SQL exposes parameters by default + # with no safe override. Rejected per D8 (#C3/#C4). + # --------------------------------------------------------------------------- + # --------------------------------------------------------------------------- + # Flyway forward-only migration (feature-migration-startup-contract D1/D2/D4). + # Flyway runs during context refresh (Spring Boot autoconfig + the + # migrationStartupRunner FlywayMigrationStrategy), BEFORE the app reports + # readiness — so migration is inherently readiness-gated (D5): a failed or + # in-progress migration can never serve traffic. + # + # The three options below are PINNED, not env-driven: they are forbidden under + # prod (D2/D4) and a static pin means a future Flyway/Spring Boot default flip + # cannot silently re-enable them (same reasoning as spring.mvc.problemdetails. + # enabled above). FlywayProdSafetyValidator fails the boot (exit 71) if any + # per-environment override re-enables them under the prod profile. + # --------------------------------------------------------------------------- + flyway: + # false: never auto-baseline an existing schema — keep the missing-migration + # safety net (FLYWAY-C6). Enabling under prod is forbidden (D4). + baseline-on-migrate: false + # false: reject out-of-order migrations — preserve cross-developer ordering + # consistency (FLYWAY-C5). Enabling under prod is forbidden (D4). + out-of-order: false + # true: keep Flyway `clean` (drops the whole schema) disarmed. Disabling this + # under prod is forbidden — clean is destructive. + clean-disabled: true + jpa: + hibernate: + # none | validate | update | create | create-drop + # prod accepts only none|validate; JpaSchemaSafetyValidator rejects schema-writing modes. + ddl-auto: ${APP_DATASOURCE_DDL_AUTO:validate} + # true | false + show-sql: ${APP_DATASOURCE_SHOW_SQL:false} + # true | false (don't enable in prod) + open-in-view: ${APP_DATASOURCE_OPEN_IN_VIEW:false} + properties: + hibernate: + # true | false (paired with show-sql) + format_sql: ${APP_DATASOURCE_FORMAT_SQL:false} + # Advanced JPA batch/fetch/measurement knobs. Defaults preserve Hibernate's off state. + # HibernateJpaBatchExecutor requires batch_size > 0 and generate_statistics=true so it can prove + # batching happened instead of trusting a configuration value. + jdbc: + batch_size: ${APP_JPA_HIBERNATE_BATCH_SIZE:0} + order_inserts: ${APP_JPA_HIBERNATE_ORDER_INSERTS:false} + order_updates: ${APP_JPA_HIBERNATE_ORDER_UPDATES:false} + default_batch_fetch_size: ${APP_JPA_HIBERNATE_DEFAULT_BATCH_FETCH_SIZE:0} + generate_statistics: ${APP_JPA_HIBERNATE_GENERATE_STATISTICS:false} + +ca-skeleton: + persistence-jpa: + # true | false — on while this module is on the classpath. false switches it fully off: this + # module's beans and Boot's JDBC/Hibernate/Spring Data JPA/Flyway auto-configurations + # (JpaActivationEnvironmentPostProcessor), so no datasource is bound or connected. + enabled: ${APP_PERSISTENCE_JPA_ENABLED:true} + persistence: + # postgresql | h2 — the vendor composition (claim SQL, SQLState mapping, Flyway location). + vendor: ${APP_PERSISTENCE_VENDOR:postgresql} + runtime: + # true | false (whether to run Flyway migrations automatically at startup) + migration-on-startup: ${APP_MIGRATION_ON_STARTUP:true} + # feature-distributed-lock-contract D5 — distributed lock acquisition contract (try-lock + + # finite wait + lease TTL). Bound to LockSettings. Plain values, not APP_* env keys; the code + # defaults in LockSettings mirror these. + lock: + wait-time: 3s + lease-ttl: 30s + realtime: + replay: + # PostgreSQL-backed retained event history. Disabled unless a composition actually publishes + # events into the store and exposes replay/resume semantics. + enabled: ${APP_REALTIME_REPLAY_ENABLED:false} + retention: ${APP_REALTIME_REPLAY_RETENTION:1h} + outbox: + # feature-domain-event-outbox-contract I11 — all six values are literal defaults; + # NO env placeholders (spec: 신규 env key 없음). Bound into OutboxProperties. + # true | false — enable/disable the relay scheduler (OutboxRelayScheduler). + # The scheduler starts only when a publishing capability contributes an + # OutboxMessagePublishPort, so an environment without one keeps its PENDING rows instead of + # failing every claim and exhausting them to DEAD. + # true | false — the capability switch. Off means no outbox settings, validator, leader token, + # metrics, or store binding at all; relay-enabled below only decides whether the scheduler runs. + # Conflating the two meant a relay-off deployment still assembled an OutboxMetrics over a store + # port that a database-less deployment does not have. + enabled: ${APP_OUTBOX_ENABLED:false} + relay-enabled: ${APP_OUTBOX_RELAY_ENABLED:false} + # Transport-only MSG-015 cutover gate. It does not start a second relay. + # When true, startup also requires the canonical IntegrationEventPublishPort. + canonical-transport-enabled: ${APP_OUTBOX_CANONICAL_TRANSPORT_ENABLED:false} + # ISO-8601 duration — how often the relay polls for pending rows + poll-interval: PT5S + # integer >= 1 — maximum rows claimed per relay cycle + batch-size: 20 + # ISO-8601 duration — IN_FLIGHT orphan visibility window (I6: next_attempt_at reuse) + in-flight-timeout: PT5M + # ISO-8601 duration — read also by adapter-persistence OutboxReaper @Scheduled + reaper-interval: PT10M + # ISO-8601 duration — PUBLISHED row retention before reaper deletes them (I3) + # read also by adapter-persistence OutboxReaper via ${ca-skeleton.outbox.published-retention:P7D} + published-retention: P7D diff --git a/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/jpa/inbox/V1__initialize_same_store_inbox.sql b/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/jpa/inbox/V1__initialize_same_store_inbox.sql deleted file mode 100644 index e0479be4..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/jpa/inbox/V1__initialize_same_store_inbox.sql +++ /dev/null @@ -1,70 +0,0 @@ --- Same-store inbox state machine. The scope hash is the canonical digest of --- consumer-group/handler/tenant/message-ID; raw broker metadata is not persisted here. - -DO $$ -BEGIN - IF NOT EXISTS ( - SELECT 1 - FROM capability_schema_registry - WHERE capability_id = 'jpa-flyway-migration' - AND core_epoch >= 1 - AND lifecycle_state = 'ACTIVE' - ) THEN - RAISE EXCEPTION 'same-store inbox requires active core epoch 1'; - END IF; -END -$$; - -CREATE TABLE inbox_record_v1 ( - scope_hash char(64) NOT NULL, - message_intent_digest char(64) NOT NULL, - state varchar(16) NOT NULL, - state_revision bigint NOT NULL, - owner_token varchar(128) NOT NULL, - attempt bigint NOT NULL, - claim_operation_id varchar(128) NOT NULL, - processing_lease_until timestamptz NOT NULL, - last_operation_id varchar(128), - last_transition_kind varchar(32), - last_result_digest char(64), - terminal_at timestamptz, - retention_until timestamptz NOT NULL, - created_at timestamptz NOT NULL, - updated_at timestamptz NOT NULL, - CONSTRAINT pk_inbox_record_v1 PRIMARY KEY (scope_hash), - CONSTRAINT ck_inbox_record_v1_state - CHECK (state IN ('RECEIVED', 'PROCESSING', 'COMPLETED', 'RETRYABLE', 'DEAD')), - CONSTRAINT ck_inbox_record_v1_revision CHECK (state_revision >= 0), - CONSTRAINT ck_inbox_record_v1_attempt CHECK (attempt > 0), - CONSTRAINT ck_inbox_record_v1_terminal - CHECK ( - (state IN ('COMPLETED', 'DEAD') AND terminal_at IS NOT NULL) - OR (state NOT IN ('COMPLETED', 'DEAD') AND terminal_at IS NULL) - ) -); - -CREATE INDEX ix_inbox_record_v1_lease - ON inbox_record_v1 (state, processing_lease_until) - WHERE state IN ('RECEIVED', 'PROCESSING'); - -CREATE INDEX ix_inbox_record_v1_terminal - ON inbox_record_v1 (state, terminal_at, retention_until) - WHERE state IN ('COMPLETED', 'DEAD', 'RETRYABLE'); - -INSERT INTO capability_schema_registry ( - capability_id, - schema_stream, - installation_origin, - core_epoch, - feature_revision, - lifecycle_state -) -SELECT - 'jpa-inbox-same-store-v1', - 'db/migration/jpa/inbox', - installation_origin, - 1, - 1, - 'INSTALLED_INACTIVE' -FROM capability_schema_registry -WHERE capability_id = 'jpa-flyway-migration'; diff --git a/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/jpa/outbox-polling/V1__initialize_polling_delivery_v2.sql b/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/jpa/outbox-polling/V1__initialize_polling_delivery_v2.sql deleted file mode 100644 index e00203a6..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/jpa/outbox-polling/V1__initialize_polling_delivery_v2.sql +++ /dev/null @@ -1,152 +0,0 @@ --- Mutable polling delivery state, separated from the immutable outbox identity/envelope. - -DO $$ -BEGIN - IF to_regclass('public.outbox_event_log_v2') IS NULL - OR to_regclass('public.outbox_publication_control_v2') IS NULL THEN - RAISE EXCEPTION 'polling delivery V2 requires outbox storage V2'; - END IF; - IF NOT EXISTS ( - SELECT 1 - FROM capability_schema_registry - WHERE capability_id = 'jpa-outbox-storage-v2' - AND core_epoch = 1 - AND feature_revision = 2 - ) THEN - RAISE EXCEPTION 'polling delivery V2 requires outbox storage revision 2'; - END IF; -END -$$; - -CREATE TABLE outbox_delivery_v2 ( - retention_bucket date NOT NULL, - event_id varchar(64) NOT NULL, - destination varchar(256) NOT NULL, - publication_epoch bigint NOT NULL, - state varchar(16) NOT NULL, - claim_owner varchar(128), - claim_token char(64), - claim_until timestamptz, - attempt integer NOT NULL, - next_attempt_at timestamptz NOT NULL, - last_error_code varchar(64), - last_operation_id varchar(128), - last_result_digest char(64), - published_at timestamptz, - dead_at timestamptz, - version bigint NOT NULL, - created_at timestamptz NOT NULL, - updated_at timestamptz NOT NULL, - CONSTRAINT pk_outbox_delivery_v2 - PRIMARY KEY (retention_bucket, event_id, destination), - CONSTRAINT fk_outbox_delivery_v2_event - FOREIGN KEY (retention_bucket, event_id) - REFERENCES outbox_event_log_v2 (retention_bucket, event_id), - CONSTRAINT ck_outbox_delivery_v2_epoch CHECK (publication_epoch > 0), - CONSTRAINT ck_outbox_delivery_v2_state - CHECK (state IN ('PENDING', 'CLAIMED', 'PUBLISHED', 'RETRY_WAIT', 'DEAD')), - CONSTRAINT ck_outbox_delivery_v2_attempt CHECK (attempt >= 0), - CONSTRAINT ck_outbox_delivery_v2_version CHECK (version >= 0), - CONSTRAINT ck_outbox_delivery_v2_state_shape - CHECK ( - (state = 'CLAIMED' - AND claim_owner IS NOT NULL - AND claim_token IS NOT NULL - AND claim_until IS NOT NULL - AND published_at IS NULL - AND dead_at IS NULL) - OR - (state <> 'CLAIMED' - AND claim_owner IS NULL - AND claim_token IS NULL - AND claim_until IS NULL) - ), - CONSTRAINT ck_outbox_delivery_v2_terminal_shape - CHECK ( - (state = 'PUBLISHED' AND published_at IS NOT NULL AND dead_at IS NULL) - OR (state = 'DEAD' AND dead_at IS NOT NULL AND published_at IS NULL) - OR (state NOT IN ('PUBLISHED', 'DEAD') - AND published_at IS NULL - AND dead_at IS NULL) - ) -); - -CREATE INDEX ix_outbox_delivery_v2_claim - ON outbox_delivery_v2 (destination, next_attempt_at, created_at) - WHERE state IN ('PENDING', 'RETRY_WAIT', 'CLAIMED'); - -CREATE INDEX ix_outbox_delivery_v2_terminal - ON outbox_delivery_v2 (state, published_at, dead_at) - WHERE state IN ('PUBLISHED', 'DEAD'); - -CREATE OR REPLACE FUNCTION create_polling_delivery_v2() -RETURNS trigger -LANGUAGE plpgsql -AS $$ -BEGIN - IF NEW.dispatch_authority = 'POLLING_V2' THEN - INSERT INTO outbox_delivery_v2 ( - retention_bucket, - event_id, - destination, - publication_epoch, - state, - claim_owner, - claim_token, - claim_until, - attempt, - next_attempt_at, - last_error_code, - last_operation_id, - last_result_digest, - published_at, - dead_at, - version, - created_at, - updated_at - ) VALUES ( - NEW.retention_bucket, - NEW.event_id, - NEW.logical_destination, - NEW.publication_epoch, - 'PENDING', - null, - null, - null, - 0, - NEW.created_at, - null, - null, - null, - null, - null, - 0, - NEW.created_at, - NEW.created_at - ); - END IF; - RETURN NEW; -END -$$; - -CREATE TRIGGER trg_create_polling_delivery_v2 -AFTER INSERT ON outbox_event_log_v2 -FOR EACH ROW EXECUTE FUNCTION create_polling_delivery_v2(); - -INSERT INTO capability_schema_registry ( - capability_id, - schema_stream, - installation_origin, - core_epoch, - feature_revision, - lifecycle_state -) -SELECT - 'jpa-outbox-polling-delivery-v2', - 'db/migration/jpa/outbox-polling', - installation_origin, - 1, - 2, - 'INSTALLED_INACTIVE' -FROM capability_schema_registry -WHERE capability_id = 'jpa-flyway-migration'; diff --git a/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/jpa/outbox-polling/V2__widen_canonical_event_id.sql b/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/jpa/outbox-polling/V2__widen_canonical_event_id.sql deleted file mode 100644 index 702f7201..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/jpa/outbox-polling/V2__widen_canonical_event_id.sql +++ /dev/null @@ -1,13 +0,0 @@ --- Canonical EventId permits up to 96 characters. This migration is safe whether storage V2 --- already widened an existing polling table or polling V1 was installed after storage V2. - -ALTER TABLE outbox_delivery_v2 - DROP CONSTRAINT IF EXISTS fk_outbox_delivery_v2_event; - -ALTER TABLE outbox_delivery_v2 - ALTER COLUMN event_id TYPE varchar(96); - -ALTER TABLE outbox_delivery_v2 - ADD CONSTRAINT fk_outbox_delivery_v2_event - FOREIGN KEY (retention_bucket, event_id) - REFERENCES outbox_event_log_v2 (retention_bucket, event_id); diff --git a/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/jpa/outbox-storage/V1__initialize_or_adopt.sql b/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/jpa/outbox-storage/V1__initialize_or_adopt.sql deleted file mode 100644 index e4021031..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/jpa/outbox-storage/V1__initialize_or_adopt.sql +++ /dev/null @@ -1,330 +0,0 @@ --- Immutable outbox storage V2. Publication authority remains LEGACY_POLLING after adoption until --- an explicit cutover transaction writes the next immutable sentinel and advances the control row. - -DO $$ -BEGIN - IF NOT EXISTS ( - SELECT 1 - FROM capability_schema_registry - WHERE capability_id = 'jpa-flyway-migration' - AND core_epoch >= 1 - AND lifecycle_state = 'ACTIVE' - ) THEN - RAISE EXCEPTION 'jpa outbox storage V2 requires active core epoch 1'; - END IF; - IF to_regclass('public.outbox_event') IS NULL - AND NOT EXISTS ( - SELECT 1 - FROM capability_schema_registry - WHERE capability_id = 'jpa-flyway-migration' - AND installation_origin = 'FRESH' - ) THEN - RAISE EXCEPTION 'legacy adoption requires the compatible outbox_event'; - END IF; -END -$$; - -CREATE TABLE IF NOT EXISTS outbox_event ( - event_id varchar(64) NOT NULL, - aggregate_id varchar(256) NOT NULL, - event_type varchar(256) NOT NULL, - payload text NOT NULL, - occurred_at timestamptz NOT NULL, - status varchar(16) NOT NULL, - attempt_count integer NOT NULL DEFAULT 0, - next_attempt_at timestamptz NOT NULL, - correlation_id varchar(64) NOT NULL, - idempotency_key varchar(256) NOT NULL, - CONSTRAINT pk_outbox_event PRIMARY KEY (event_id) -); - -CREATE INDEX IF NOT EXISTS ix_outbox_event_eligible ON outbox_event (next_attempt_at) - WHERE status IN ('PENDING', 'FAILED', 'IN_FLIGHT'); -CREATE INDEX IF NOT EXISTS ix_outbox_event_aggregate_occurred - ON outbox_event (aggregate_id, occurred_at); -CREATE INDEX IF NOT EXISTS ix_outbox_event_published_occurred ON outbox_event (occurred_at) - WHERE status = 'PUBLISHED'; -CREATE INDEX IF NOT EXISTS ix_outbox_event_status_occurred ON outbox_event (status, occurred_at); - -CREATE TABLE outbox_publication_control_v2 ( - scope_id varchar(32) NOT NULL, - active_epoch bigint NOT NULL, - active_authority varchar(32) NOT NULL, - state varchar(16) NOT NULL, - revision bigint NOT NULL, - updated_at timestamptz NOT NULL, - CONSTRAINT pk_outbox_publication_control_v2 PRIMARY KEY (scope_id), - CONSTRAINT ck_outbox_publication_control_v2_scope CHECK (scope_id = 'PRIMARY'), - CONSTRAINT ck_outbox_publication_control_v2_epoch CHECK (active_epoch > 0), - CONSTRAINT ck_outbox_publication_control_v2_authority - CHECK (active_authority IN ('LEGACY_POLLING', 'POLLING_V2', 'CDC')), - CONSTRAINT ck_outbox_publication_control_v2_state - CHECK (state IN ('PREPARING', 'ACTIVE', 'DRAINING')), - CONSTRAINT ck_outbox_publication_control_v2_revision CHECK (revision >= 0) -); - -CREATE TABLE outbox_publication_cutover_v2 ( - scope_id varchar(32) NOT NULL, - active_epoch bigint NOT NULL, - previous_epoch bigint NOT NULL, - transition_kind varchar(32) NOT NULL, - active_authority varchar(32) NOT NULL, - legacy_row_count bigint NOT NULL, - legacy_pending_count bigint NOT NULL, - legacy_digest char(64) NOT NULL, - schema_manifest_id varchar(128) NOT NULL, - external_manifest_id varchar(128), - activated_at timestamptz NOT NULL, - CONSTRAINT pk_outbox_publication_cutover_v2 PRIMARY KEY (scope_id, active_epoch), - CONSTRAINT fk_outbox_publication_cutover_v2_scope - FOREIGN KEY (scope_id) REFERENCES outbox_publication_control_v2 (scope_id), - CONSTRAINT ck_outbox_publication_cutover_v2_epoch - CHECK (active_epoch > 0 AND previous_epoch = active_epoch - 1), - CONSTRAINT ck_outbox_publication_cutover_v2_kind - CHECK (transition_kind IN ('GENESIS_FRESH', 'GENESIS_LEGACY', 'CUTOVER')), - CONSTRAINT ck_outbox_publication_cutover_v2_authority - CHECK (active_authority IN ('LEGACY_POLLING', 'POLLING_V2', 'CDC')), - CONSTRAINT ck_outbox_publication_cutover_v2_counts - CHECK (legacy_row_count >= 0 AND legacy_pending_count >= 0) -); - -CREATE TABLE outbox_event_identity_v2 ( - event_id varchar(64) NOT NULL, - aggregate_type varchar(128) NOT NULL, - aggregate_id varchar(256) NOT NULL, - aggregate_version bigint NOT NULL, - event_ordinal integer NOT NULL, - retention_bucket date NOT NULL, - created_at timestamptz NOT NULL, - CONSTRAINT pk_outbox_event_identity_v2 PRIMARY KEY (event_id), - CONSTRAINT uq_outbox_event_identity_v2_aggregate_order - UNIQUE (aggregate_type, aggregate_id, aggregate_version, event_ordinal), - CONSTRAINT uq_outbox_event_identity_v2_bucket UNIQUE (event_id, retention_bucket), - CONSTRAINT ck_outbox_event_identity_v2_version CHECK (aggregate_version > 0), - CONSTRAINT ck_outbox_event_identity_v2_ordinal CHECK (event_ordinal BETWEEN 0 AND 1023) -); - -CREATE TABLE outbox_event_log_v2 ( - retention_bucket date NOT NULL, - event_id varchar(64) NOT NULL, - aggregate_type varchar(128) NOT NULL, - aggregate_id varchar(256) NOT NULL, - aggregate_version bigint NOT NULL, - event_ordinal integer NOT NULL, - event_type varchar(256) NOT NULL, - event_schema integer NOT NULL, - logical_destination varchar(256) NOT NULL, - partition_key varchar(256) NOT NULL, - publication_epoch bigint NOT NULL, - dispatch_authority varchar(32) NOT NULL, - content_type varchar(128) NOT NULL, - correlation_id varchar(128) NOT NULL, - causation_id varchar(128), - occurred_at timestamptz NOT NULL, - payload text NOT NULL, - payload_digest char(64) NOT NULL, - trace_parent varchar(256), - created_at timestamptz NOT NULL, - CONSTRAINT pk_outbox_event_log_v2 PRIMARY KEY (retention_bucket, event_id), - CONSTRAINT fk_outbox_event_log_v2_identity - FOREIGN KEY (event_id, retention_bucket) - REFERENCES outbox_event_identity_v2 (event_id, retention_bucket), - CONSTRAINT ck_outbox_event_log_v2_schema CHECK (event_schema > 0), - CONSTRAINT ck_outbox_event_log_v2_epoch CHECK (publication_epoch > 0), - CONSTRAINT ck_outbox_event_log_v2_authority - CHECK (dispatch_authority IN ('LEGACY_SHADOW', 'POLLING_V2', 'CDC')), - CONSTRAINT ck_outbox_event_log_v2_payload_size - CHECK (octet_length(payload) BETWEEN 1 AND 1048576) -); - --- Retention is lifecycle policy, not a pretend partitioning feature. Until the platform owns a --- partition creation/rotation job, a plain table is cheaper and avoids parking every row in a --- DEFAULT partition that later has to be drained before real range partitions can be attached. - -CREATE INDEX ix_outbox_event_log_v2_aggregate_order - ON outbox_event_log_v2 ( - aggregate_type, - aggregate_id, - aggregate_version, - event_ordinal - ); - -CREATE OR REPLACE FUNCTION enforce_outbox_event_v2_authority() -RETURNS trigger -LANGUAGE plpgsql -AS $$ -DECLARE - control_epoch bigint; - control_authority varchar(32); - control_state varchar(16); - expected_dispatch varchar(32); -BEGIN - SELECT active_epoch, active_authority, state - INTO control_epoch, control_authority, control_state - FROM outbox_publication_control_v2 - WHERE scope_id = 'PRIMARY'; - - IF control_state <> 'ACTIVE' THEN - RAISE EXCEPTION 'outbox publication authority is not ACTIVE'; - END IF; - - expected_dispatch := CASE control_authority - WHEN 'LEGACY_POLLING' THEN 'LEGACY_SHADOW' - WHEN 'POLLING_V2' THEN 'POLLING_V2' - WHEN 'CDC' THEN 'CDC' - END; - - IF NEW.publication_epoch <> control_epoch - OR NEW.dispatch_authority <> expected_dispatch THEN - RAISE EXCEPTION 'outbox publication epoch or dispatch authority mismatch'; - END IF; - RETURN NEW; -END -$$; - -CREATE TRIGGER trg_outbox_event_v2_authority -BEFORE INSERT ON outbox_event_log_v2 -FOR EACH ROW EXECUTE FUNCTION enforce_outbox_event_v2_authority(); - -CREATE OR REPLACE FUNCTION fence_legacy_outbox_writer() -RETURNS trigger -LANGUAGE plpgsql -AS $$ -DECLARE - control_authority varchar(32); - control_state varchar(16); -BEGIN - SELECT active_authority, state - INTO control_authority, control_state - FROM outbox_publication_control_v2 - WHERE scope_id = 'PRIMARY'; - - -- Normal legacy ownership permits the legacy writer. During DRAINING, the legacy relay may - -- still finish or delete rows it already owns, but it may not create new work. Once the new - -- authority is ACTIVE every legacy mutation is fenced. - IF control_authority = 'LEGACY_POLLING' AND control_state = 'ACTIVE' THEN - RETURN NULL; - END IF; - IF control_state = 'DRAINING' AND TG_OP IN ('UPDATE', 'DELETE') THEN - RETURN NULL; - END IF; - - RAISE EXCEPTION 'legacy outbox writer is fenced after authority cutover'; -END -$$; - -CREATE TRIGGER trg_fence_legacy_outbox_writer -BEFORE INSERT OR UPDATE OR DELETE ON outbox_event -FOR EACH STATEMENT EXECUTE FUNCTION fence_legacy_outbox_writer(); - -CREATE OR REPLACE FUNCTION reject_outbox_cutover_mutation() -RETURNS trigger -LANGUAGE plpgsql -AS $$ -BEGIN - RAISE EXCEPTION 'outbox publication cutover sentinel is immutable'; -END -$$; - -CREATE TRIGGER trg_reject_outbox_cutover_mutation -BEFORE UPDATE OR DELETE ON outbox_publication_cutover_v2 -FOR EACH ROW EXECUTE FUNCTION reject_outbox_cutover_mutation(); - -INSERT INTO outbox_publication_control_v2 ( - scope_id, - active_epoch, - active_authority, - state, - revision, - updated_at -) VALUES ( - 'PRIMARY', - 1, - 'LEGACY_POLLING', - 'ACTIVE', - 0, - clock_timestamp() -); - -WITH legacy AS ( - SELECT - count(*) AS row_count, - count(*) FILTER (WHERE status <> 'PUBLISHED') AS pending_count, - coalesce(min(event_id), '') AS first_event_id, - coalesce(max(event_id), '') AS last_event_id, - coalesce( - sum( - hashtextextended( - event_id || ':' || status || ':' || attempt_count::text, - 0 - ) - ), - 0 - ) AS intent_summary - FROM outbox_event -), -origin AS ( - SELECT installation_origin - FROM capability_schema_registry - WHERE capability_id = 'jpa-flyway-migration' -) -INSERT INTO outbox_publication_cutover_v2 ( - scope_id, - active_epoch, - previous_epoch, - transition_kind, - active_authority, - legacy_row_count, - legacy_pending_count, - legacy_digest, - schema_manifest_id, - external_manifest_id, - activated_at -) -SELECT - 'PRIMARY', - 1, - 0, - CASE installation_origin - WHEN 'FRESH' THEN 'GENESIS_FRESH' - ELSE 'GENESIS_LEGACY' - END, - 'LEGACY_POLLING', - row_count, - pending_count, - encode( - sha256( - convert_to( - row_count::text - || ':' || pending_count::text - || ':' || first_event_id - || ':' || last_event_id - || ':' || intent_summary::text, - 'UTF8' - ) - ), - 'hex' - ), - 'jpa-outbox-storage-v2-schema-revision-2', - null, - clock_timestamp() -FROM legacy -CROSS JOIN origin; - -INSERT INTO capability_schema_registry ( - capability_id, - schema_stream, - installation_origin, - core_epoch, - feature_revision, - lifecycle_state -) -SELECT - 'jpa-outbox-storage-v2', - 'db/migration/jpa/outbox-storage', - installation_origin, - 1, - 2, - 'INSTALLED_INACTIVE' -FROM capability_schema_registry -WHERE capability_id = 'jpa-flyway-migration'; diff --git a/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/jpa/outbox-storage/V2__canonical_envelope_alignment.sql b/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/jpa/outbox-storage/V2__canonical_envelope_alignment.sql deleted file mode 100644 index 148a72cb..00000000 --- a/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/jpa/outbox-storage/V2__canonical_envelope_alignment.sql +++ /dev/null @@ -1,159 +0,0 @@ -DO $$ -BEGIN - IF to_regclass('public.outbox_delivery_v2') IS NOT NULL THEN - ALTER TABLE outbox_delivery_v2 - DROP CONSTRAINT IF EXISTS fk_outbox_delivery_v2_event; - END IF; -END -$$; - --- Align the dark owner-safe V2 event store with ValidatedIntegrationEvent. --- Existing pre-canonical V2 rows remain an explicit compatibility generation: all new canonical --- columns are NULL. New canonical rows must provide the complete shape. - -ALTER TABLE outbox_event_log_v2 - DROP CONSTRAINT fk_outbox_event_log_v2_identity; - -ALTER TABLE outbox_event_identity_v2 - DROP CONSTRAINT uq_outbox_event_identity_v2_aggregate_order, - DROP CONSTRAINT ck_outbox_event_identity_v2_ordinal, - ALTER COLUMN event_id TYPE varchar(96), - ADD COLUMN tenant_scope varchar(96); - -CREATE UNIQUE INDEX uq_outbox_event_identity_v2_legacy_aggregate_order - ON outbox_event_identity_v2 ( - aggregate_type, aggregate_id, aggregate_version, event_ordinal - ) - WHERE tenant_scope IS NULL; - -CREATE UNIQUE INDEX uq_outbox_event_identity_v2_canonical_aggregate_order - ON outbox_event_identity_v2 ( - tenant_scope, aggregate_type, aggregate_id, aggregate_version, event_ordinal - ) - WHERE tenant_scope IS NOT NULL; - -ALTER TABLE outbox_event_identity_v2 - ADD CONSTRAINT ck_outbox_event_identity_v2_ordinal CHECK (event_ordinal >= 0), - ADD CONSTRAINT ck_outbox_event_identity_v2_tenant_scope CHECK ( - tenant_scope IS NULL - OR tenant_scope ~ '^[a-z0-9]+([._:-][a-z0-9]+)*$' - ), - ADD CONSTRAINT uq_outbox_event_identity_v2_canonical_shape UNIQUE ( - event_id, - retention_bucket, - tenant_scope, - aggregate_type, - aggregate_id, - aggregate_version, - event_ordinal - ); - -DO $$ -BEGIN - IF to_regclass('public.outbox_delivery_v2') IS NOT NULL THEN - ALTER TABLE outbox_delivery_v2 - ALTER COLUMN event_id TYPE varchar(96); - END IF; -END -$$; - -ALTER TABLE outbox_event_log_v2 - ALTER COLUMN event_id TYPE varchar(96), - ADD COLUMN tenant_scope varchar(96), - ADD COLUMN envelope_version integer, - ADD COLUMN envelope_bytes bytea, - ADD COLUMN schema_set_hash char(64), - ADD COLUMN envelope_sha256 char(64), - ADD COLUMN envelope_schema_hash char(64), - ADD COLUMN payload_schema_hash char(64), - ADD COLUMN contract_catalog_revision varchar(96), - ADD COLUMN destination_binding_revision varchar(96); - -ALTER TABLE outbox_event_log_v2 - ADD CONSTRAINT fk_outbox_event_log_v2_identity - FOREIGN KEY ( - event_id, - retention_bucket, - tenant_scope, - aggregate_type, - aggregate_id, - aggregate_version, - event_ordinal - ) - REFERENCES outbox_event_identity_v2 ( - event_id, - retention_bucket, - tenant_scope, - aggregate_type, - aggregate_id, - aggregate_version, - event_ordinal - ), - ADD CONSTRAINT ck_outbox_event_log_v2_canonical_shape CHECK ( - ( - tenant_scope IS NULL - AND envelope_version IS NULL - AND envelope_bytes IS NULL - AND schema_set_hash IS NULL - AND envelope_sha256 IS NULL - AND envelope_schema_hash IS NULL - AND payload_schema_hash IS NULL - AND contract_catalog_revision IS NULL - AND destination_binding_revision IS NULL - ) - OR - ( - tenant_scope IS NOT NULL - AND envelope_version IS NOT NULL - AND envelope_bytes IS NOT NULL - AND schema_set_hash IS NOT NULL - AND envelope_sha256 IS NOT NULL - AND envelope_schema_hash IS NOT NULL - AND payload_schema_hash IS NOT NULL - AND contract_catalog_revision IS NOT NULL - AND destination_binding_revision IS NOT NULL - ) - ), - ADD CONSTRAINT ck_outbox_event_log_v2_canonical_values CHECK ( - envelope_bytes IS NULL - OR ( - event_id ~ '^[A-Za-z0-9][A-Za-z0-9._:-]*$' - AND tenant_scope ~ '^[a-z0-9]+([._:-][a-z0-9]+)*$' - AND length(aggregate_type) <= 64 - AND aggregate_type ~ '^[a-z][a-z0-9]*([.-][a-z0-9]+)*$' - AND length(aggregate_id) <= 160 - AND aggregate_id ~ '^[A-Za-z0-9][A-Za-z0-9._:-]*$' - AND event_type ~ '^[a-z][a-z0-9]*(-[a-z0-9]+)*(\.[a-z][a-z0-9]*(-[a-z0-9]+)*)+$' - AND length(logical_destination) <= 96 - AND logical_destination ~ '^[a-z][a-z0-9]*(-[a-z0-9]+)*$' - AND partition_key ~ '^[0-9a-f]{64}$' - AND length(content_type) <= 96 - AND envelope_version > 0 - AND event_schema > 0 - AND aggregate_version > 0 - AND event_ordinal >= 0 - AND schema_set_hash ~ '^[0-9a-f]{64}$' - AND envelope_sha256 ~ '^[0-9a-f]{64}$' - AND envelope_schema_hash ~ '^[0-9a-f]{64}$' - AND payload_schema_hash ~ '^[0-9a-f]{64}$' - AND contract_catalog_revision ~ '^[a-z0-9][a-z0-9._:-]{0,95}$' - AND destination_binding_revision ~ '^[a-z0-9][a-z0-9._:-]{0,95}$' - AND correlation_id ~ '^[A-Za-z0-9][A-Za-z0-9._:-]*$' - AND (causation_id IS NULL OR causation_id ~ '^[A-Za-z0-9][A-Za-z0-9._:-]*$') - AND octet_length(envelope_bytes) BETWEEN 1 AND 1048576 - AND convert_to(payload, 'UTF8') = envelope_bytes - AND payload_digest = envelope_sha256 - AND trace_parent IS NULL - ) - ); - -DO $$ -BEGIN - IF to_regclass('public.outbox_delivery_v2') IS NOT NULL THEN - ALTER TABLE outbox_delivery_v2 - ADD CONSTRAINT fk_outbox_delivery_v2_event - FOREIGN KEY (retention_bucket, event_id) - REFERENCES outbox_event_log_v2 (retention_bucket, event_id); - END IF; -END -$$; diff --git a/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/postgresql/V13__outbox_canonical_transport_compatibility.sql b/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/postgresql/V13__outbox_canonical_transport_compatibility.sql index 84591a9d..f00b50b8 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/postgresql/V13__outbox_canonical_transport_compatibility.sql +++ b/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/postgresql/V13__outbox_canonical_transport_compatibility.sql @@ -15,13 +15,13 @@ ALTER TABLE outbox_event ADD COLUMN aggregate_type varchar(64), ADD COLUMN aggregate_sequence bigint, ADD COLUMN event_index integer, - ADD COLUMN partition_key varchar(64), + ADD COLUMN partition_key char(64), ADD COLUMN envelope_bytes bytea, ADD COLUMN content_type varchar(96), - ADD COLUMN schema_set_hash varchar(64), - ADD COLUMN envelope_sha256 varchar(64), - ADD COLUMN envelope_schema_hash varchar(64), - ADD COLUMN payload_schema_hash varchar(64), + ADD COLUMN schema_set_hash char(64), + ADD COLUMN envelope_sha256 char(64), + ADD COLUMN envelope_schema_hash char(64), + ADD COLUMN payload_schema_hash char(64), ADD COLUMN contract_catalog_revision varchar(96), ADD COLUMN destination_binding_revision varchar(96), ADD COLUMN causation_id varchar(128); @@ -68,7 +68,7 @@ ALTER TABLE outbox_event AND contract_catalog_revision IS NOT NULL AND destination_binding_revision IS NOT NULL ) - ) NOT VALID, + ), ADD CONSTRAINT ck_outbox_event_canonical_versions CHECK ( envelope_version IS NULL OR ( @@ -77,10 +77,10 @@ ALTER TABLE outbox_event AND aggregate_sequence > 0 AND event_index >= 0 ) - ) NOT VALID, + ), ADD CONSTRAINT ck_outbox_event_canonical_partition_key CHECK ( partition_key IS NULL OR partition_key ~ '^[0-9a-f]{64}$' - ) NOT VALID, + ), ADD CONSTRAINT ck_outbox_event_canonical_hashes CHECK ( schema_set_hash IS NULL OR ( @@ -89,10 +89,10 @@ ALTER TABLE outbox_event AND envelope_schema_hash ~ '^[0-9a-f]{64}$' AND payload_schema_hash ~ '^[0-9a-f]{64}$' ) - ) NOT VALID, + ), ADD CONSTRAINT ck_outbox_event_canonical_envelope_bytes CHECK ( envelope_bytes IS NULL OR octet_length(envelope_bytes) > 0 - ) NOT VALID, + ), ADD CONSTRAINT ck_outbox_event_canonical_required_text CHECK ( contract_id IS NULL OR ( @@ -104,7 +104,7 @@ ALTER TABLE outbox_event AND btrim(contract_catalog_revision) <> '' AND btrim(destination_binding_revision) <> '' ) - ) NOT VALID; + ); COMMENT ON COLUMN outbox_event.envelope_bytes IS 'Exact canonical ValidatedIntegrationEvent envelope bytes. Never reconstructed from payload.'; diff --git a/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/postgresql/V16__outbox_canonical_hash_columns_varchar.sql b/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/postgresql/V16__outbox_canonical_hash_columns_varchar.sql new file mode 100644 index 00000000..95387b7f --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/postgresql/V16__outbox_canonical_hash_columns_varchar.sql @@ -0,0 +1,13 @@ +-- V13 created the canonical hash columns as char(64). The JPA mapping is String(length = 64), which +-- Hibernate validates as varchar, so ddl-auto=validate rejected a database migrated through V13. +-- Every stored value is exactly 64 hex characters, so widening keeps the data unchanged; on a +-- database whose columns are already varchar(64) this is a no-op. +-- +-- The change belongs here rather than in V13: V13 has been applied, and Flyway refuses to start a +-- database whose applied migration no longer matches the checksum it recorded. +ALTER TABLE outbox_event + ALTER COLUMN partition_key TYPE varchar(64), + ALTER COLUMN schema_set_hash TYPE varchar(64), + ALTER COLUMN envelope_sha256 TYPE varchar(64), + ALTER COLUMN envelope_schema_hash TYPE varchar(64), + ALTER COLUMN payload_schema_hash TYPE varchar(64); diff --git a/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/postgresql/V17__outbox_event_lease_fencing.sql b/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/postgresql/V17__outbox_event_lease_fencing.sql new file mode 100644 index 00000000..43119ae1 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/postgresql/V17__outbox_event_lease_fencing.sql @@ -0,0 +1,19 @@ +-- Lease owner and fencing token for the relay claim. +-- +-- A claim expires after the in-flight timeout, and the relay's completions matched on event_id +-- alone, so a relay that stalled past its claim could still write: +-- +-- relay A claims the row and calls the broker +-- the claim expires; relay B reclaims the row, publishes, and records PUBLISHED +-- relay A's broker call finally fails and it records FAILED over the top +-- +-- The row is claimable again and the event is published a second time. A longer timeout lowers the +-- odds; it does not turn a GC pause or a slow broker into a constraint. The token does: every claim +-- increments it, every completion names the claim it belongs to, and a superseded relay's +-- completion matches no row. +-- +-- The default fills existing rows without a rewrite; the first claim increments it. +ALTER TABLE outbox_event + ADD COLUMN lease_owner VARCHAR(160), + ADD COLUMN lease_token BIGINT NOT NULL DEFAULT 0 + CONSTRAINT ck_outbox_event_lease_token CHECK (lease_token >= 0); diff --git a/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/postgresql/V9__widen_capability_schema_stream.sql b/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/postgresql/V9__widen_capability_schema_stream.sql index 6107ad23..22e1e0e7 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/postgresql/V9__widen_capability_schema_stream.sql +++ b/src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/postgresql/V9__widen_capability_schema_stream.sql @@ -1,10 +1,9 @@ -- The adoption copy of db/migration/jpa/core/V2: same widening, applied by the default location. -- --- Historical note: this migration was originally numbered V9 because the sample application --- merged its V2/V7/V8 migrations into the same Flyway stream. The sample now owns a separate --- flyway_sample_schema_history, so future production versions are no longer constrained by sample --- numbering. This existing version remains V9 because renumbering an applied production migration --- would invalidate Flyway history. +-- Numbered V9, not V8 or V7. `db/migration/postgresql` and `db/sample-migration` are merged into +-- one Flyway location list by the sample composition root, so the two trees share a single version +-- space: the sample already owns V2, V7 and V8. A duplicate version is not a merge conflict Flyway +-- resolves — it refuses to start at all. -- -- Both locations create capability_schema_registry, so both have to grow the column. A deployment -- that migrated through only one of them would otherwise still reject a stream path over 32 diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationStoreAdapterContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationStoreAdapterContractTest.java new file mode 100644 index 00000000..3a840c9e --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationStoreAdapterContractTest.java @@ -0,0 +1,132 @@ +package dev.caskeleton.adapter.outbound.persistence.operation; + +import dev.caskeleton.adapter.outbound.persistence.operation.entity.DurableOperationEntity; +import dev.caskeleton.adapter.outbound.persistence.platform.JpaPlatformContractSupport; +import dev.caskeleton.adapter.outbound.persistence.transaction.SpringTransactionPort; +import dev.caskeleton.application.operation.DurableOperationStorePort; +import dev.caskeleton.application.operation.testkit.DurableOperationStoreContract; +import dev.caskeleton.application.transaction.TransactionPort; +import jakarta.persistence.EntityManagerFactory; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Map; +import java.util.function.Supplier; +import javax.sql.DataSource; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; +import org.springframework.transaction.PlatformTransactionManager; + +/** + * The shipped adapter, through Spring Data and a Spring transaction, against real PostgreSQL. + * + *

The raw-SQL {@link DurableOperationStoreContractTest} proves the schema; this proves the code + * that talks to it. A resubmission only breaks where PostgreSQL aborts the transaction after a + * constraint violation, so no fake can stand in here. + */ +@Tag("jpa-contract") +class DurableOperationStoreAdapterContractTest extends DurableOperationStoreContract { + + private static JpaPlatformContractSupport support; + private static AnnotationConfigApplicationContext context; + + @BeforeAll + static void start() throws SQLException, IOException { + support = JpaPlatformContractSupport.start(); + execute(migration()); + context = new AnnotationConfigApplicationContext(); + context.getBeanFactory().registerSingleton("dataSource", support.dataSource()); + context.register(AdapterConfiguration.class); + context.refresh(); + } + + @AfterAll + static void stop() { + if (context != null) { + context.close(); + } + if (support != null) { + support.close(); + } + } + + @BeforeEach + void empty() throws SQLException { + execute("TRUNCATE durable_operation"); + } + + @Override + protected DurableOperationStorePort store() { + return context.getBean(DurableOperationStoreAdapter.class); + } + + @Override + protected T inTransaction(Supplier work) { + return context.getBean(TransactionPort.class).inWrite(work); + } + + private static void execute(String sql) throws SQLException { + try (Connection connection = support.connection(); + Statement statement = connection.createStatement()) { + statement.execute(sql); + } + } + + private static String migration() throws IOException { + try (InputStream resource = + DurableOperationStoreAdapterContractTest.class + .getClassLoader() + .getResourceAsStream("db/migration/postgresql/V11__durable_operation.sql")) { + if (resource == null) { + throw new IOException("the durable operation migration is missing from the classpath"); + } + return new String(resource.readAllBytes(), StandardCharsets.UTF_8); + } + } + + @Configuration + @EnableJpaRepositories(basePackageClasses = DurableOperationJpaRepository.class) + static class AdapterConfiguration { + + @Bean + LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) { + LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean(); + factory.setDataSource(dataSource); + factory.setPackagesToScan(DurableOperationEntity.class.getPackageName()); + factory.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); + factory.setJpaPropertyMap( + Map.of( + "hibernate.hbm2ddl.auto", "validate", + "hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect")); + return factory; + } + + @Bean + PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) { + return new JpaTransactionManager(entityManagerFactory); + } + + @Bean + TransactionPort transactionPort(PlatformTransactionManager transactionManager) { + return new SpringTransactionPort(transactionManager); + } + + @Bean + DurableOperationStoreAdapter durableOperationStoreAdapter( + DurableOperationJpaRepository repository) { + return new DurableOperationStoreAdapter(repository); + } + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/platform/CommitAmbiguityContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/platform/CommitAmbiguityContractTest.java deleted file mode 100644 index c6b6c565..00000000 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/platform/CommitAmbiguityContractTest.java +++ /dev/null @@ -1,165 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.platform; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.adapter.outbound.persistence.api.PersistenceOperationName; -import dev.caskeleton.adapter.outbound.persistence.api.error.TransactionCompletionUnknownException; -import dev.caskeleton.adapter.outbound.persistence.api.transaction.TransactionCompletionEvidence; -import dev.caskeleton.adapter.outbound.persistence.testkit.failure.PostgreSqlFailureScenario; -import dev.caskeleton.adapter.outbound.persistence.transaction.CommitFailureClassifier; -import dev.caskeleton.adapter.outbound.persistence.transaction.TransactionEvidenceContext; -import java.sql.Connection; -import java.sql.SQLException; -import java.sql.Statement; -import java.time.Clock; -import java.util.Optional; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -/** - * The commit-ambiguity contract: a lost commit is not a rollback (design §17.2, §39). - * - *

The connection is killed from the server side with {@code pg_terminate_backend} while - * a transaction is open. That produces a real transport break on a real commit path, which is the - * only way to observe what the driver actually reports — a mocked exception would only prove the - * code handles the exception the test author expected. - * - *

What this asserts is the platform's rule: a commit-phase break becomes completion-unknown, - * with {@code retryable=false}, and the reconciliation key survives. A break before the commit does - * not. - */ -@Tag("jpa-failure") -class CommitAmbiguityContractTest { - - private static final PersistenceOperationName OPERATION = - new PersistenceOperationName("payment.commit"); - - private static JpaPlatformContractSupport support; - - private final CommitFailureClassifier classifier = - CommitFailureClassifier.standard(Clock.systemUTC()); - - @BeforeAll - static void startServer() throws SQLException { - support = JpaPlatformContractSupport.start(); - try (Connection connection = support.connection(); - Statement statement = connection.createStatement()) { - statement.execute("create table ambiguous_row (id bigserial primary key)"); - } - } - - @AfterEach - void clearEvidence() { - TransactionEvidenceContext.clearAll(); - } - - @AfterAll - static void stopServer() { - if (support != null) { - support.close(); - } - } - - @Test - @DisplayName("the three commit injection points are distinct and only two are ambiguous") - void commitAmbiguityHasThreeDistinctInjectionPoints() { - assertThat(PostgreSqlFailureScenario.commitPoints()) - .containsExactly( - PostgreSqlFailureScenario.BEFORE_COMMIT, - PostgreSqlFailureScenario.DURING_COMMIT, - PostgreSqlFailureScenario.AFTER_SERVER_COMMIT_BEFORE_RESPONSE); - assertThat(PostgreSqlFailureScenario.BEFORE_COMMIT.leavesOutcomeUnknown()).isFalse(); - } - - @Test - @DisplayName("a connection killed mid-transaction becomes completion unknown at commit") - void killedConnectionDuringCommitBecomesCompletionUnknown() throws SQLException { - TransactionEvidenceContext.begin(OPERATION, "payment-42", java.time.Instant.now(), 1); - TransactionEvidenceContext.mark(TransactionCompletionEvidence.COMMITTING); - - SQLException transportBreak = commitOnAKilledConnection(); - - RuntimeException translated = - classifier.translateCommitFailure( - new IllegalStateException("commit failed", transportBreak)); - - assertThat(translated).isInstanceOf(TransactionCompletionUnknownException.class); - var unknown = (TransactionCompletionUnknownException) translated; - assertThat(unknown.context().completionUnknown()).isTrue(); - assertThat(unknown.context().retryable()) - .as("a possibly-committed write is never re-run automatically") - .isFalse(); - assertThat(unknown.transactionKey()).contains("payment-42"); - assertThat(unknown.evidence()).isEqualTo(TransactionCompletionEvidence.UNKNOWN); - } - - @Test - @DisplayName("a terminated backend reports 57P01, which is not a connection-class state") - void terminatedBackendReports57P01() throws SQLException { - SQLException transportBreak = commitOnAKilledConnection(); - - // This is why the contract runs against a real server. 57P01 (admin_shutdown) is what - // PostgreSQL actually sends when the backend is terminated mid-commit — not class 08, which is - // what a reasonable reading of "the connection broke" predicts. A classifier built on that - // prediction treats a possibly-committed transaction as an ordinary failure. - assertThat(transportBreak.getSQLState()).isEqualTo("57P01"); - assertThat(transportBreak.getSQLState()).doesNotStartWith("08"); - assertThat( - classifier.indicatesUnknownCompletion( - Optional.of(transportBreak.getSQLState()), transportBreak)) - .isTrue(); - } - - @Test - @DisplayName("an ordinary constraint violation at commit is not completion unknown") - void ordinaryConstraintViolationIsNotCompletionUnknown() { - var violation = new SQLException("duplicate key", "23505"); - - assertThat(classifier.indicatesUnknownCompletion(Optional.of("23505"), violation)) - .as("widening the rule would bury the real reconciliation entries in noise") - .isFalse(); - assertThat(classifier.translateCommitFailure(new IllegalStateException("commit", violation))) - .isNotInstanceOf(TransactionCompletionUnknownException.class); - } - - /** - * Opens a transaction, terminates its backend from another connection, then commits. - * - *

Terminating the backend rather than closing the socket locally is what makes this a genuine - * loss of the acknowledgement: the client learns the connection is gone only when it asks. - */ - private static SQLException commitOnAKilledConnection() throws SQLException { - try (Connection victim = support.connection()) { - victim.setAutoCommit(false); - int backendPid; - try (Statement statement = victim.createStatement()) { - statement.execute("insert into ambiguous_row default values"); - try (var rows = statement.executeQuery("select pg_backend_pid()")) { - rows.next(); - backendPid = rows.getInt(1); - } - } - - terminateBackend(backendPid); - - try { - victim.commit(); - throw new AssertionError("the commit unexpectedly succeeded on a terminated backend"); - } catch (SQLException lost) { - return lost; - } - } - } - - private static void terminateBackend(int backendPid) throws SQLException { - try (Connection killer = support.connection(); - var statement = killer.prepareStatement("select pg_terminate_backend(?)")) { - statement.setInt(1, backendPid); - statement.execute(); - } - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/platform/FlywayUpgradeContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/platform/FlywayUpgradeContractTest.java index 0c2484ee..a4d59bff 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/platform/FlywayUpgradeContractTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/platform/FlywayUpgradeContractTest.java @@ -4,7 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import dev.caskeleton.adapter.outbound.persistence.api.error.SchemaMismatchException; -import dev.caskeleton.adapter.outbound.persistence.migration.FlywayValidationGate; +import dev.caskeleton.adapter.outbound.persistence.testkit.migration.FlywayValidationGate; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/platform/OptimisticRetryIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/platform/OptimisticRetryIntegrationTest.java deleted file mode 100644 index ee268ee2..00000000 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/platform/OptimisticRetryIntegrationTest.java +++ /dev/null @@ -1,174 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.platform; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.adapter.outbound.persistence.testkit.lifecycle.LifecycleChild; -import dev.caskeleton.adapter.outbound.persistence.testkit.lifecycle.LifecycleParent; -import dev.caskeleton.adapter.outbound.persistence.transaction.OptimisticConflictTranslator; -import jakarta.persistence.EntityManager; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.SQLException; -import java.time.Duration; -import java.util.ArrayList; -import java.util.List; -import java.util.Set; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -/** - * A retried optimistic conflict recomputes against reloaded state (design §19.2, §20). - * - *

This is the contract that justifies the whole full-transaction retry design. A concurrent - * writer bumps the version between the read and the flush; the first attempt fails; the second - * attempt must load the new state, not the state the first attempt cached. A - * statement-level retry, or a retry reusing the Persistence Context, would recompute against the - * stale value and silently overwrite the concurrent write. - */ -@Tag("jpa-contract") -class OptimisticRetryIntegrationTest { - - private static JpaPlatformContractSupport support; - private static JpaPlatformEntityManagerSupport jpa; - - @BeforeAll - static void startServer() { - support = JpaPlatformContractSupport.start(); - jpa = - JpaPlatformEntityManagerSupport.open(support, LifecycleParent.class, LifecycleChild.class); - } - - @AfterAll - static void stopServer() { - if (jpa != null) { - jpa.close(); - } - if (support != null) { - support.close(); - } - } - - @Test - @DisplayName("the second attempt reloads and recomputes against the concurrent write") - void secondAttemptReloadsAndRecomputesAggregate() throws SQLException { - Long id = persistParent("optimistic-1"); - List persistenceContextIdentities = new ArrayList<>(); - - // Attempt 1 reads, a concurrent writer commits, attempt 1 fails, attempt 2 reloads. - boolean succeeded = false; - RuntimeException lastFailure = null; - for (int attempt = 1; attempt <= 2 && !succeeded; attempt++) { - try (EntityManager entityManager = jpa.entityManager()) { - persistenceContextIdentities.add(System.identityHashCode(entityManager)); - entityManager.getTransaction().begin(); - LifecycleParent parent = entityManager.find(LifecycleParent.class, id); - long observedVersion = parent.version(); - - if (attempt == 1) { - bumpVersionInAnotherTransaction(id); - } - - parent.rename(parent.label() + "+" + observedVersion); - try { - entityManager.getTransaction().commit(); - succeeded = true; - } catch (RuntimeException conflict) { - lastFailure = conflict; - if (entityManager.getTransaction().isActive()) { - entityManager.getTransaction().rollback(); - } - } - } - } - - assertThat(persistenceContextIdentities).hasSize(2); - assertThat(succeeded).as("the second attempt must succeed against reloaded state").isTrue(); - assertThat(persistenceContextIdentities) - .as("every attempt runs in a new Persistence Context") - .hasSize(2) - .doesNotHaveDuplicates(); - assertThat( - new OptimisticConflictTranslator(Set.of("LifecycleParent")) - .isOptimisticConflict(lastFailure)) - .as("the first attempt really failed on the version check") - .isTrue(); - } - - @Test - @DisplayName("the conflict is translated without carrying the entity id") - void conflictIsTranslatedWithoutTheEntityId() throws SQLException { - Long id = persistParent("optimistic-2"); - var translator = new OptimisticConflictTranslator(Set.of("LifecycleParent")); - - RuntimeException conflict = provokeConflict(id); - var translated = - translator - .translate(conflict, UnknownOperationName.ORDER_PLACE, 1, Duration.ZERO, null) - .orElseThrow(); - - assertThat(translated.retryable()).isTrue(); - assertThat(translated.getMessage()).doesNotContain(String.valueOf(id)); - } - - @Test - @DisplayName("only registered entity types are reportable") - void onlyRegisteredEntityTypesAreReportable() { - var translator = new OptimisticConflictTranslator(Set.of("LifecycleParent")); - - assertThat(translator.conflictingEntityType(LifecycleParent.class)).contains("LifecycleParent"); - assertThat(translator.conflictingEntityType(LifecycleChild.class)).isEmpty(); - } - - private static RuntimeException provokeConflict(Long id) throws SQLException { - try (EntityManager entityManager = jpa.entityManager()) { - entityManager.getTransaction().begin(); - LifecycleParent parent = entityManager.find(LifecycleParent.class, id); - bumpVersionInAnotherTransaction(id); - parent.rename("conflicting"); - try { - entityManager.getTransaction().commit(); - throw new AssertionError("the version check did not reject the stale write"); - } catch (RuntimeException conflict) { - if (entityManager.getTransaction().isActive()) { - entityManager.getTransaction().rollback(); - } - return conflict; - } - } - } - - /** Commits a competing update on its own connection, bumping the row's version. */ - private static void bumpVersionInAnotherTransaction(Long id) throws SQLException { - try (Connection connection = support.connection(); - PreparedStatement statement = - connection.prepareStatement( - "update jpa_lifecycle_parent set version = version + 1," - + " label = 'concurrent' where id = ?")) { - statement.setLong(1, id); - statement.executeUpdate(); - } - } - - private static Long persistParent(String label) { - return jpa.inTransaction( - entityManager -> { - var parent = new LifecycleParent(label); - entityManager.persist(parent); - return parent.id(); - }); - } - - /** The registered operation this contract attributes its failures to. */ - private static final class UnknownOperationName { - - static final dev.caskeleton.adapter.outbound.persistence.api.PersistenceOperationName - ORDER_PLACE = - new dev.caskeleton.adapter.outbound.persistence.api.PersistenceOperationName( - "order.place"); - - private UnknownOperationName() {} - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/platform/PostgreSqlMigrationUpgradeContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/platform/PostgreSqlMigrationUpgradeContractTest.java index 01309e0b..c28a222d 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/platform/PostgreSqlMigrationUpgradeContractTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/platform/PostgreSqlMigrationUpgradeContractTest.java @@ -3,9 +3,9 @@ package dev.caskeleton.adapter.outbound.persistence.platform; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import dev.caskeleton.adapter.outbound.persistence.migration.ConcurrentIndexMigrationInspector; -import dev.caskeleton.adapter.outbound.persistence.migration.FlywayValidationGate; -import dev.caskeleton.adapter.outbound.persistence.migration.MigrationResource; +import dev.caskeleton.adapter.outbound.persistence.testkit.migration.ConcurrentIndexMigrationInspector; +import dev.caskeleton.adapter.outbound.persistence.testkit.migration.FlywayValidationGate; +import dev.caskeleton.adapter.outbound.persistence.testkit.migration.MigrationResource; import dev.caskeleton.adapter.outbound.persistence.testkit.migration.MigrationScenario; import java.sql.Connection; import java.sql.SQLException; diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/platform/experimental/ReadAfterWriteRoutingContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/platform/experimental/ReadAfterWriteRoutingContractTest.java index 9942f498..e14ed2b1 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/platform/experimental/ReadAfterWriteRoutingContractTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/platform/experimental/ReadAfterWriteRoutingContractTest.java @@ -2,8 +2,6 @@ package dev.caskeleton.adapter.outbound.persistence.platform.experimental; import static org.assertj.core.api.Assertions.assertThat; -import dev.caskeleton.adapter.outbound.persistence.experimental.ExperimentalFeature; -import dev.caskeleton.adapter.outbound.persistence.experimental.ExperimentalFeatureGate; import dev.caskeleton.adapter.outbound.persistence.experimental.replica.ConsistencyAwareDataSourceRouter; import dev.caskeleton.adapter.outbound.persistence.experimental.replica.ConsistencyToken; import dev.caskeleton.adapter.outbound.persistence.experimental.replica.ReadConsistency; @@ -50,11 +48,7 @@ class ReadAfterWriteRoutingContractTest { @Test @DisplayName("a write always goes to the primary") void writeAlwaysGoesToThePrimary() { - var router = - ConsistencyAwareDataSourceRouter.enabledBy( - new ExperimentalFeatureGate(), - java.util.Map.of(ExperimentalFeature.READ_REPLICA.property(), true), - caughtUp()); + var router = new ConsistencyAwareDataSourceRouter(caughtUp()); var decision = router.route(TransactionContext.writing(), ReadConsistency.eventual()); @@ -65,11 +59,7 @@ class ReadAfterWriteRoutingContractTest { @Test @DisplayName("a locking read goes to the primary even under eventual consistency") void lockingReadGoesToThePrimary() { - var router = - ConsistencyAwareDataSourceRouter.enabledBy( - new ExperimentalFeatureGate(), - java.util.Map.of(ExperimentalFeature.READ_REPLICA.property(), true), - caughtUp()); + var router = new ConsistencyAwareDataSourceRouter(caughtUp()); assertThat(router.route(TransactionContext.lockingRead(), ReadConsistency.eventual()).target()) .as("a replica cannot hold a lock the primary will honour") @@ -81,11 +71,7 @@ class ReadAfterWriteRoutingContractTest { void readBehindItsOwnWriteIsRoutedToThePrimary() throws SQLException { Instant writtenAt = commitAndReadServerTime(); var token = ConsistencyToken.at(writtenAt); - var router = - ConsistencyAwareDataSourceRouter.enabledBy( - new ExperimentalFeatureGate(), - java.util.Map.of(ExperimentalFeature.READ_REPLICA.property(), true), - stuckAt(writtenAt.minusSeconds(5))); + var router = new ConsistencyAwareDataSourceRouter(stuckAt(writtenAt.minusSeconds(5))); var decision = router.route(TransactionContext.readOnly(), ReadConsistency.after(token)); @@ -98,11 +84,7 @@ class ReadAfterWriteRoutingContractTest { void readWhoseReplicaHasCaughtUpIsRoutedToTheReplica() throws SQLException { Instant writtenAt = commitAndReadServerTime(); var token = ConsistencyToken.at(writtenAt); - var router = - ConsistencyAwareDataSourceRouter.enabledBy( - new ExperimentalFeatureGate(), - java.util.Map.of(ExperimentalFeature.READ_REPLICA.property(), true), - stuckAt(writtenAt.plusSeconds(1))); + var router = new ConsistencyAwareDataSourceRouter(stuckAt(writtenAt.plusSeconds(1))); assertThat(router.route(TransactionContext.readOnly(), ReadConsistency.after(token)).target()) .isEqualTo(ReplicaTarget.REPLICA); @@ -112,11 +94,7 @@ class ReadAfterWriteRoutingContractTest { @DisplayName("bounded staleness compares against the measured lag, not a guess") void boundedStalenessComparesAgainstTheMeasuredLag() throws SQLException { Instant now = serverNow(); - var router = - ConsistencyAwareDataSourceRouter.enabledBy( - new ExperimentalFeatureGate(), - java.util.Map.of(ExperimentalFeature.READ_REPLICA.property(), true), - stuckAt(now.minusSeconds(30))); + var router = new ConsistencyAwareDataSourceRouter(stuckAt(now.minusSeconds(30))); assertThat( router diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/platform/experimental/SchemaTenantMigrationContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/platform/experimental/SchemaTenantMigrationContractTest.java index 1a7461c7..33ef5210 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/platform/experimental/SchemaTenantMigrationContractTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/platform/experimental/SchemaTenantMigrationContractTest.java @@ -5,8 +5,6 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; -import dev.caskeleton.adapter.outbound.persistence.experimental.ExperimentalFeature; -import dev.caskeleton.adapter.outbound.persistence.experimental.ExperimentalFeatureGate; import dev.caskeleton.adapter.outbound.persistence.experimental.schema.SchemaMultiTenantConnectionProvider; import dev.caskeleton.adapter.outbound.persistence.experimental.schema.SchemaTenantMigrationOrchestrator; import dev.caskeleton.adapter.outbound.persistence.experimental.schema.SchemaTenantRegistry; @@ -161,12 +159,8 @@ class SchemaTenantMigrationContractTest { private static SchemaTenantMigrationOrchestrator orchestrator( SchemaTenantRegistry registry, Path migrations) { - return SchemaTenantMigrationOrchestrator.enabledBy( - new ExperimentalFeatureGate(), - java.util.Map.of(ExperimentalFeature.MULTITENANCY_SCHEMA.property(), true), - support.dataSource(), - registry, - "filesystem:" + migrations.toAbsolutePath()); + return new SchemaTenantMigrationOrchestrator( + support.dataSource(), registry, "filesystem:" + migrations.toAbsolutePath()); } private static void write(Path directory, String name, String sql) throws Exception { diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/CanonicalOutboxV2TestFixture.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/CanonicalOutboxV2TestFixture.java deleted file mode 100644 index cafdcdcc..00000000 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/CanonicalOutboxV2TestFixture.java +++ /dev/null @@ -1,84 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.readiness; - -import dev.caskeleton.application.messaging.contract.ContractId; -import dev.caskeleton.application.messaging.contract.LogicalDestinationId; -import dev.caskeleton.application.messaging.contract.Sha256; -import dev.caskeleton.application.messaging.event.AggregateIdentity; -import dev.caskeleton.application.messaging.event.AggregateOrder; -import dev.caskeleton.application.messaging.event.EventId; -import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent; -import dev.caskeleton.application.outbox.v2.NewOutboxEventV2; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.time.Instant; -import java.util.Optional; - -final class CanonicalOutboxV2TestFixture { - - static final String DESTINATION = "portfolio-events"; - - private CanonicalOutboxV2TestFixture() {} - - static NewOutboxEventV2 event( - String eventId, long aggregateSequence, int eventIndex, String envelopeJson) { - return event(eventId, "tenant-a", aggregateSequence, eventIndex, envelopeJson); - } - - static NewOutboxEventV2 event( - String eventId, - String tenantScope, - long aggregateSequence, - int eventIndex, - String envelopeJson) { - return event( - eventId, - tenantScope, - aggregateSequence, - eventIndex, - envelopeJson.getBytes(StandardCharsets.UTF_8)); - } - - static NewOutboxEventV2 event( - String eventId, - String tenantScope, - long aggregateSequence, - int eventIndex, - byte[] envelopeBytes) { - String partitionKey = "a".repeat(64); - return new NewOutboxEventV2( - new ValidatedIntegrationEvent( - new EventId(eventId), - new ContractId("portfolio.worklog.changed"), - 1, - 1, - new LogicalDestinationId(DESTINATION), - new AggregateIdentity(tenantScope, "worklog", "work-log-42"), - new AggregateOrder(aggregateSequence, eventIndex), - Instant.parse("2026-07-28T12:00:00Z"), - "correlation-1", - Optional.empty(), - partitionKey, - partitionKey.getBytes(StandardCharsets.US_ASCII), - envelopeBytes, - "application/json", - sha("schema-set"), - sha(envelopeBytes), - sha("envelope-schema"), - sha("payload-schema"), - "catalog-r1", - "binding-r1")); - } - - private static Sha256 sha(String value) { - return sha(value.getBytes(StandardCharsets.UTF_8)); - } - - private static Sha256 sha(byte[] value) { - try { - return new Sha256(MessageDigest.getInstance("SHA-256").digest(value)); - } catch (NoSuchAlgorithmException exception) { - throw new IllegalStateException("SHA-256 unavailable", exception); - } - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/LegacyOutboxDrainContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/LegacyOutboxDrainContractTest.java deleted file mode 100644 index 3aa7921a..00000000 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/LegacyOutboxDrainContractTest.java +++ /dev/null @@ -1,142 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.readiness; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import org.flywaydb.core.Flyway; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; -import org.springframework.dao.DataAccessException; -import org.springframework.jdbc.core.JdbcTemplate; - -@Tag("jpa-contract") -class LegacyOutboxDrainContractTest { - - @Test - void drainingLetsTheLegacyRelayFinishExistingRowsButRejectsNewWork() { - try (PostgreSqlReadinessSupport database = PostgreSqlReadinessSupport.start()) { - migrate(database, "classpath:db/migration/postgresql", "flyway_schema_history", false); - migrate(database, "classpath:db/migration/jpa/core", "flyway_jpa_core_history", true); - migrate( - database, - "classpath:db/migration/jpa/outbox-storage", - "flyway_jpa_outbox_storage_history", - true); - - JdbcTemplate jdbc = new JdbcTemplate(database.dataSource()); - jdbc.update( - """ - insert into outbox_event( - event_id, aggregate_id, event_type, payload, occurred_at, status, - attempt_count, next_attempt_at, correlation_id, idempotency_key - ) values ( - 'legacy-existing', 'order-42', 'order.created', '{}', clock_timestamp(), 'PENDING', - 0, clock_timestamp(), 'corr-42', 'idem-42' - ) - """); - - jdbc.update( - """ - update outbox_publication_control_v2 - set active_authority = 'POLLING_V2', - state = 'DRAINING', - revision = revision + 1, - updated_at = clock_timestamp() - where scope_id = 'PRIMARY' - """); - - assertThat( - jdbc.update( - "update outbox_event set status = 'PUBLISHED' " - + "where event_id = 'legacy-existing'")) - .isOne(); - assertThat( - jdbc.queryForObject( - "select status from outbox_event where event_id = 'legacy-existing'", - String.class)) - .isEqualTo("PUBLISHED"); - - assertThatThrownBy( - () -> - jdbc.update( - """ - insert into outbox_event( - event_id, aggregate_id, event_type, payload, occurred_at, status, - attempt_count, next_attempt_at, correlation_id, idempotency_key - ) values ( - 'legacy-new', 'order-43', 'order.created', '{}', clock_timestamp(), - 'PENDING', 0, clock_timestamp(), 'corr-43', 'idem-43' - ) - """)) - .isInstanceOf(DataAccessException.class) - .hasMessageContaining("legacy outbox writer is fenced"); - } - } - - @Test - void installedStorageUsesAStatementFenceARealSha256DigestAndNoFakePartitioning() { - try (PostgreSqlReadinessSupport database = PostgreSqlReadinessSupport.start()) { - migrate(database, "classpath:db/migration/postgresql", "flyway_schema_history", false); - migrate(database, "classpath:db/migration/jpa/core", "flyway_jpa_core_history", true); - migrate( - database, - "classpath:db/migration/jpa/outbox-storage", - "flyway_jpa_outbox_storage_history", - true); - - JdbcTemplate jdbc = new JdbcTemplate(database.dataSource()); - assertThat( - jdbc.queryForObject( - """ - select action_orientation - from information_schema.triggers - where event_object_schema = 'public' - and event_object_table = 'outbox_event' - and trigger_name = 'trg_fence_legacy_outbox_writer' - limit 1 - """, - String.class)) - .isEqualTo("STATEMENT"); - - assertThat( - jdbc.queryForObject( - """ - select exists( - select 1 - from pg_partitioned_table p - join pg_class c on c.oid = p.partrelid - where c.relname = 'outbox_event_log_v2' - ) - """, - Boolean.class)) - .isFalse(); - - assertThat( - jdbc.queryForObject( - """ - select legacy_digest - from outbox_publication_cutover_v2 - where scope_id = 'PRIMARY' and active_epoch = 1 - """, - String.class)) - .matches("[0-9a-f]{64}"); - } - } - - private static void migrate( - PostgreSqlReadinessSupport database, - String location, - String historyTable, - boolean independent) { - Flyway.configure() - .dataSource(database.dataSource()) - .locations(location) - .table(historyTable) - .baselineVersion("0") - .baselineDescription("legacy-outbox-drain-contract") - .baselineOnMigrate(independent) - .outOfOrder(false) - .load() - .migrate(); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/LegacyOutboxIntegrationSupport.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/LegacyOutboxIntegrationSupport.java index 4fe81e33..3328c8d1 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/LegacyOutboxIntegrationSupport.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/LegacyOutboxIntegrationSupport.java @@ -14,6 +14,7 @@ import jakarta.persistence.EntityManagerFactory; import java.time.Clock; import java.time.Duration; import java.util.Properties; +import java.util.UUID; import java.util.random.RandomGenerator; import javax.sql.DataSource; import org.flywaydb.core.Flyway; @@ -182,7 +183,8 @@ final class LegacyOutboxIntegrationSupport { new OutboxBackoffPolicy(RandomGenerator.getDefault()), clock, BATCH_SIZE_CONTRACT, - IN_FLIGHT_TIMEOUT); + IN_FLIGHT_TIMEOUT, + UUID.randomUUID().toString()); } // ---- helpers ---- diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlBaseStreamUpgradeIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlBaseStreamUpgradeIntegrationTest.java index b770c04d..75a2c0d9 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlBaseStreamUpgradeIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlBaseStreamUpgradeIntegrationTest.java @@ -3,7 +3,7 @@ package dev.caskeleton.adapter.outbound.persistence.readiness; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import dev.caskeleton.adapter.outbound.persistence.migration.FlywayValidationGate; +import dev.caskeleton.adapter.outbound.persistence.testkit.migration.FlywayValidationGate; import dev.caskeleton.adapter.outbound.persistence.testkit.migration.MigrationContractRunner; import dev.caskeleton.adapter.outbound.persistence.testkit.migration.MigrationScenario; import javax.sql.DataSource; diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlIdempotencyIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlIdempotencyIntegrationTest.java index 80959482..7e676444 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlIdempotencyIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlIdempotencyIntegrationTest.java @@ -3,20 +3,20 @@ package dev.caskeleton.adapter.outbound.persistence.readiness; import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.adapter.outbound.persistence.postgresql.idempotency.PostgreSqlOwnerSafeIdempotencyStore; +import dev.caskeleton.application.idempotency.IdempotencyClaimAttempt; +import dev.caskeleton.application.idempotency.IdempotencyClaimOutcome; +import dev.caskeleton.application.idempotency.IdempotencyClaimRequest; +import dev.caskeleton.application.idempotency.IdempotencyCompleteOutcome; +import dev.caskeleton.application.idempotency.IdempotencyFailOutcome; +import dev.caskeleton.application.idempotency.IdempotencyFailureDisposition; +import dev.caskeleton.application.idempotency.IdempotencyInspectionOutcome; +import dev.caskeleton.application.idempotency.IdempotencyInspectionRequest; +import dev.caskeleton.application.idempotency.IdempotencyOwner; +import dev.caskeleton.application.idempotency.IdempotencyRenewOutcome; +import dev.caskeleton.application.idempotency.IdempotencyScopeDigest; +import dev.caskeleton.application.idempotency.IdempotencyStartOutcome; import dev.caskeleton.application.idempotency.RequestFingerprint; import dev.caskeleton.application.idempotency.StoredResponse; -import dev.caskeleton.application.idempotency.v2.IdempotencyClaimAttempt; -import dev.caskeleton.application.idempotency.v2.IdempotencyClaimOutcome; -import dev.caskeleton.application.idempotency.v2.IdempotencyClaimRequest; -import dev.caskeleton.application.idempotency.v2.IdempotencyCompleteOutcome; -import dev.caskeleton.application.idempotency.v2.IdempotencyFailOutcome; -import dev.caskeleton.application.idempotency.v2.IdempotencyFailureDisposition; -import dev.caskeleton.application.idempotency.v2.IdempotencyInspectionOutcome; -import dev.caskeleton.application.idempotency.v2.IdempotencyInspectionRequest; -import dev.caskeleton.application.idempotency.v2.IdempotencyOwner; -import dev.caskeleton.application.idempotency.v2.IdempotencyRenewOutcome; -import dev.caskeleton.application.idempotency.v2.IdempotencyScopeDigest; -import dev.caskeleton.application.idempotency.v2.IdempotencyStartOutcome; import dev.caskeleton.application.transaction.OperationId; import java.nio.charset.StandardCharsets; import java.time.Duration; diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlIdempotencyUniqueScopeIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlIdempotencyUniqueScopeIntegrationTest.java deleted file mode 100644 index 99d3ddf9..00000000 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlIdempotencyUniqueScopeIntegrationTest.java +++ /dev/null @@ -1,191 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.readiness; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.adapter.outbound.persistence.failure.PersistenceExceptionTranslator; -import dev.caskeleton.adapter.outbound.persistence.failure.StandardSqlStateErrorMapping; -import dev.caskeleton.adapter.outbound.persistence.postgresql.PostgreSqlSqlStateErrorMapping; -import dev.caskeleton.shared.error.OperationalError; -import dev.caskeleton.shared.error.PersistenceFailureException; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.SQLException; -import java.util.List; -import java.util.Optional; -import java.util.UUID; -import javax.sql.DataSource; -import org.flywaydb.core.Flyway; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; -import org.springframework.dao.DataIntegrityViolationException; - -/** - * PostgreSQL contract test that pins the DDL → unique-scope → SQLState → error-code chain for - * {@code idempotency_record} (feature-persistence-multi-db-extensibility, commit E). - * - *

Coverage gap this test fills

- * - *
    - *
  • Outbox, lock, and owner-safe idempotency behavior have separate PostgreSQL provider suites. - *
  • This test pins the legacy {@code uq_idempotency_scope} unique constraint (columns: {@code - * tenant, principal, idempotency_key, use_case_name}, defined in {@code - * V1__idempotency_record.sql}) is exercised against a real PostgreSQL instance so that a - * duplicate insert provably produces SQLState {@code 23505}, and the production {@link - * PersistenceExceptionTranslator} chain maps it to {@link - * OperationalError#DB_UNIQUE_VIOLATION}. - *
- * - *

Scope (non-speculative)

- * - * This test verifies the PostgreSQL vendor's actual behaviour — it is not a shared-fixture - * abstraction. A DB-neutral shared fixture would require a second RDBMS vendor on the test - * classpath to have any validation value; that is deferred until a second vendor is added (C-1: - * avoid paying the abstraction cost before the validator exists). - * - *

Translator composition

- * - * The {@link PersistenceExceptionTranslator} is constructed with {@code List.of(new - * StandardSqlStateErrorMapping(), new PostgreSqlSqlStateErrorMapping())} — the same composition - * used by the PostgreSQL persistence adapter. This exercises the "DDL unique constraint → PG - * SQLState 23505 → DB_UNIQUE_VIOLATION" end-to-end chain with a real PostgreSQL error. - */ -class PostgreSqlIdempotencyUniqueScopeIntegrationTest { - - private static PostgreSqlReadinessSupport postgres; - private static DataSource sharedDataSource; - - /** Production translator composition: standard SQLSTATE rows plus PostgreSQL vendor rows. */ - private static final PersistenceExceptionTranslator TRANSLATOR = - new PersistenceExceptionTranslator( - List.of(new StandardSqlStateErrorMapping(), new PostgreSqlSqlStateErrorMapping())); - - @BeforeAll - static void setup() { - postgres = PostgreSqlReadinessSupport.start(); - sharedDataSource = postgres.dataSource(); - - // The legacy PostgreSQL migration stream owns idempotency_record and its unique scope. - Flyway.configure() - .dataSource(sharedDataSource) - .locations("classpath:db/migration/postgresql") - .load() - .migrate(); - } - - @AfterAll - static void teardown() { - if (postgres != null) { - postgres.close(); - } - } - - // ========================================================================= - // Contract 1 — DDL unique constraint fires as SQLState 23505 - // ========================================================================= - - /** - * Inserting a second row with the same (tenant, principal, idempotency_key, use_case_name) scope - * must cause PostgreSQL to report SQLState {@code 23505} (unique_violation). This pins the DDL - * side of the "DDL → SQLState → error-code" chain. - * - *

The insert uses plain JDBC so the {@link SQLException} is observed directly, without any ORM - * exception-translation layer in between. This keeps the contract readable and avoids sensitivity - * to Hibernate's own exception-wrapping behaviour. - */ - @Test - void duplicateScopeInsertProducesSqlstate23505() throws Exception { - String nonce = uniqueNonce(); - insertRow(sharedDataSource, nonce); // first row — must succeed - - SQLException caught = null; - try { - insertRow(sharedDataSource, nonce); // duplicate scope — must fail - } catch (SQLException ex) { - caught = ex; - } - - assertThat((Throwable) caught).as("duplicate scope insert must throw SQLException").isNotNull(); - assertThat(caught.getSQLState()) - .as("SQLState must be 23505 (PostgreSQL unique_violation)") - .isEqualTo("23505"); - } - - // ========================================================================= - // Contract 2 — DDL 23505 → DB_UNIQUE_VIOLATION (full chain) - // ========================================================================= - - /** - * A {@link DataIntegrityViolationException} wrapping a {@link SQLException} with SQLState {@code - * 23505} (as Spring Data JPA produces at the repository boundary in production) must classify to - * {@link OperationalError#DB_UNIQUE_VIOLATION} via the production {@link - * PersistenceExceptionTranslator}. This pins the complete "DDL unique constraint → PG SQLState - * 23505 → DB_UNIQUE_VIOLATION" chain. - * - *

The {@link SQLException} is obtained from a real PostgreSQL duplicate-insert so the SQLState - * comes from the actual driver, not a fabricated fixture. - */ - @Test - void duplicateScopeClassifiesToDbUniqueViolation() throws Exception { - String nonce = uniqueNonce(); - insertRow(sharedDataSource, nonce); // first row - - SQLException pgEx = null; - try { - insertRow(sharedDataSource, nonce); // duplicate — harvests the real PG exception - } catch (SQLException ex) { - pgEx = ex; - } - - assertThat((Throwable) pgEx) - .as("duplicate insert must throw a real PostgreSQL SQLException") - .isNotNull(); - assertThat(pgEx.getSQLState()).as("real PG SQLState must be 23505").isEqualTo("23505"); - - // Wrap it the same way Spring Data JPA does at the repository boundary. - DataIntegrityViolationException springWrapped = - new DataIntegrityViolationException("unique constraint violation", pgEx); - - Optional result = TRANSLATOR.translate(springWrapped); - assertThat(result) - .as("TRANSLATOR must classify the wrapped 23505 to a PersistenceFailureException") - .isPresent(); - assertThat(result.get().errorCode()) - .as( - "SQLState 23505 from idempotency_record unique scope must classify to DB_UNIQUE_VIOLATION") - .isEqualTo(OperationalError.DB_UNIQUE_VIOLATION); - } - - // ========================================================================= - // helpers - // ========================================================================= - - /** Returns a unique nonce so each test method gets its own scope bucket. */ - private static String uniqueNonce() { - return String.valueOf(System.nanoTime()); - } - - /** - * Inserts one {@code idempotency_record} row via plain JDBC. The scope columns ({@code tenant}, - * {@code principal}, {@code idempotency_key}, {@code use_case_name}) are keyed to {@code nonce}. - * The PK ({@code id}) is always a fresh UUID so only the unique scope constraint, not the PK, can - * fire on a duplicate call. - * - * @throws SQLException propagated directly so the test can inspect the SQLState - */ - private static void insertRow(DataSource ds, String nonce) throws SQLException { - String sql = - "INSERT INTO idempotency_record " - + "(id, tenant, principal, idempotency_key, use_case_name, " - + " request_hash, status, created_at, expires_at) " - + "VALUES (?, '', ?, ?, 'TestUseCase', ?, 'PENDING', now(), now() + interval '1 hour')"; - try (Connection conn = ds.getConnection(); - PreparedStatement ps = conn.prepareStatement(sql)) { - ps.setObject(1, UUID.randomUUID()); - ps.setString(2, "test-principal-" + nonce); - ps.setString(3, "test-key-" + nonce); - ps.setString(4, "a".repeat(64)); - ps.executeUpdate(); - } - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlInboxIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlInboxIntegrationTest.java deleted file mode 100644 index 100ff1a0..00000000 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlInboxIntegrationTest.java +++ /dev/null @@ -1,280 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.readiness; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.outbound.persistence.postgresql.inbox.PostgreSqlSameStoreInboxAdapter; -import dev.caskeleton.application.inbox.InboxClaimAttempt; -import dev.caskeleton.application.inbox.InboxClaimOutcome; -import dev.caskeleton.application.inbox.InboxClaimRequest; -import dev.caskeleton.application.inbox.InboxOwner; -import dev.caskeleton.application.inbox.InboxScopeDigest; -import dev.caskeleton.application.inbox.InboxTransitionOutcome; -import dev.caskeleton.application.transaction.OperationId; -import java.time.Duration; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import org.flywaydb.core.Flyway; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.datasource.DataSourceTransactionManager; -import org.springframework.transaction.support.TransactionTemplate; - -class PostgreSqlInboxIntegrationTest { - - private static final InboxScopeDigest SCOPE = new InboxScopeDigest("a".repeat(64)); - private static final String INTENT = "b".repeat(64); - - private static PostgreSqlReadinessSupport postgres; - private static JdbcTemplate jdbc; - private static TransactionTemplate transactions; - private static PostgreSqlSameStoreInboxAdapter inbox; - - @BeforeAll - static void startAndMigratePostgreSql() { - PostgreSqlReadinessSupport.assertDockerAvailable(); - postgres = PostgreSqlReadinessSupport.start(); - migrate("classpath:db/migration/postgresql", "flyway_schema_history"); - migrateIndependent( - "classpath:db/migration/jpa/core", "flyway_jpa_core_history", "explicit-jpa-core-adoption"); - migrateIndependent( - "classpath:db/migration/jpa/inbox", - "flyway_jpa_inbox_history", - "explicit-jpa-inbox-adoption"); - - jdbc = new JdbcTemplate(postgres.dataSource()); - transactions = new TransactionTemplate(new DataSourceTransactionManager(postgres.dataSource())); - inbox = new PostgreSqlSameStoreInboxAdapter(postgres.dataSource()); - jdbc.update( - "update capability_schema_registry set lifecycle_state = 'ACTIVE' " - + "where capability_id = 'jpa-inbox-same-store-v1'"); - jdbc.execute( - "create table inbox_business_probe (" - + "scope_hash char(64) primary key, mutation_count integer not null)"); - } - - @AfterAll - static void stopPostgreSql() { - if (postgres != null) { - postgres.close(); - } - } - - @BeforeEach - void clearRows() { - jdbc.update("delete from inbox_record_v1"); - jdbc.update("delete from inbox_business_probe"); - } - - @Test - void claimBusinessMutationAndCompletionCommitOrRollbackAsOneUnit() { - InboxClaimAttempt rolledBackAttempt = inbox.newClaimAttempt(new OperationId("claim-rollback")); - assertThatThrownBy( - () -> - transactions.executeWithoutResult( - ignored -> { - InboxOwner owner = - ((InboxClaimOutcome.Acquired) - inbox.claim(request(rolledBackAttempt, Duration.ofSeconds(5)))) - .owner(); - owner = - inbox - .markProcessing(owner, new OperationId("start-rollback")) - .owner() - .orElseThrow(); - jdbc.update( - "insert into inbox_business_probe(scope_hash, mutation_count) " - + "values (?, 1)", - SCOPE.value()); - throw new IllegalStateException("rollback"); - })) - .isInstanceOf(IllegalStateException.class); - assertThat(jdbc.queryForObject("select count(*) from inbox_record_v1", Integer.class)).isZero(); - assertThat(jdbc.queryForObject("select count(*) from inbox_business_probe", Integer.class)) - .isZero(); - - InboxClaimAttempt committedAttempt = inbox.newClaimAttempt(new OperationId("claim-commit")); - transactions.executeWithoutResult( - ignored -> { - InboxOwner owner = - ((InboxClaimOutcome.Acquired) - inbox.claim(request(committedAttempt, Duration.ofSeconds(5)))) - .owner(); - owner = - inbox.markProcessing(owner, new OperationId("start-commit")).owner().orElseThrow(); - jdbc.update( - "insert into inbox_business_probe(scope_hash, mutation_count) values (?, 1)", - SCOPE.value()); - assertThat(inbox.complete(owner, new OperationId("complete-commit"))) - .isEqualTo(InboxTransitionOutcome.COMPLETED); - }); - - InboxClaimOutcome redelivery = - transactions.execute( - ignored -> - inbox.claim( - request( - inbox.newClaimAttempt(new OperationId("claim-redelivery")), - Duration.ofSeconds(5)))); - assertThat(redelivery).isInstanceOf(InboxClaimOutcome.Completed.class); - assertThat( - jdbc.queryForObject( - "select mutation_count from inbox_business_probe where scope_hash = ?", - Integer.class, - SCOPE.value())) - .isEqualTo(1); - } - - @Test - void expiredReceivedCanBeTakenOverButStaleOwnerCannotStart() { - InboxOwner stale = - transactions.execute( - ignored -> - ((InboxClaimOutcome.Acquired) - inbox.claim( - request( - inbox.newClaimAttempt(new OperationId("claim-old")), - Duration.ofMillis(25)))) - .owner()); - jdbc.queryForObject("select pg_sleep(0.05)", Object.class); - - InboxClaimOutcome takeover = - transactions.execute( - ignored -> - inbox.claim( - request( - inbox.newClaimAttempt(new OperationId("claim-new")), - Duration.ofSeconds(5)))); - assertThat(takeover) - .isInstanceOfSatisfying( - InboxClaimOutcome.TakenOver.class, - result -> assertThat(result.owner().attempt()).isEqualTo(2)); - assertThat( - transactions - .execute(ignored -> inbox.markProcessing(stale, new OperationId("stale-start"))) - .outcome()) - .isEqualTo(InboxTransitionOutcome.NOT_OWNER); - } - - @Test - void expiredProcessingRequiresRecoveryInsteadOfBlindTakeover() { - InboxClaimAttempt attempt = inbox.newClaimAttempt(new OperationId("claim-processing")); - transactions.executeWithoutResult( - ignored -> { - InboxOwner owner = - ((InboxClaimOutcome.Acquired) inbox.claim(request(attempt, Duration.ofMillis(25)))) - .owner(); - inbox.markProcessing(owner, new OperationId("start-processing")); - }); - jdbc.queryForObject("select pg_sleep(0.05)", Object.class); - - InboxClaimOutcome outcome = - transactions.execute( - ignored -> - inbox.claim( - request( - inbox.newClaimAttempt(new OperationId("claim-after-unknown")), - Duration.ofSeconds(5)))); - assertThat(outcome).isInstanceOf(InboxClaimOutcome.RecoveryRequired.class); - assertThat( - jdbc.queryForObject( - "select state from inbox_record_v1 where scope_hash = ?", - String.class, - SCOPE.value())) - .isEqualTo("DEAD"); - } - - @Test - void takeoverCannotPassTheOwnerRowWhileBusinessTransactionIsOpen() throws Exception { - CountDownLatch firstCompletedInsideTransaction = new CountDownLatch(1); - CountDownLatch allowCommit = new CountDownLatch(1); - InboxClaimRequest first = - request(inbox.newClaimAttempt(new OperationId("claim-first")), Duration.ofMillis(25)); - InboxClaimRequest second = - request(inbox.newClaimAttempt(new OperationId("claim-second")), Duration.ofSeconds(5)); - - try (var executor = Executors.newVirtualThreadPerTaskExecutor()) { - Future firstHandler = - executor.submit( - () -> { - transactions.executeWithoutResult( - ignored -> { - InboxOwner owner = ((InboxClaimOutcome.Acquired) inbox.claim(first)).owner(); - owner = - inbox - .markProcessing(owner, new OperationId("start-first")) - .owner() - .orElseThrow(); - jdbc.update( - "insert into inbox_business_probe(scope_hash, mutation_count) " - + "values (?, 1)", - SCOPE.value()); - assertThat(inbox.complete(owner, new OperationId("complete-first"))) - .isEqualTo(InboxTransitionOutcome.COMPLETED); - firstCompletedInsideTransaction.countDown(); - await(allowCommit); - }); - return null; - }); - firstCompletedInsideTransaction.await(); - Future competing = - executor.submit(() -> transactions.execute(ignored -> inbox.claim(second))); - assertThat(competing.isDone()).isFalse(); - allowCommit.countDown(); - firstHandler.get(); - assertThat(competing.get()).isInstanceOf(InboxClaimOutcome.Completed.class); - } - - assertThat(jdbc.queryForObject("select count(*) from inbox_business_probe", Integer.class)) - .isEqualTo(1); - } - - @Test - void optionalStreamLifecycleIsNonDestructiveAndRecoversInterruptedMigration() throws Exception { - PostgreSqlOptionalStreamLifecycle.verify(PostgreSqlOptionalStreamLifecycle.inbox()); - } - - private static InboxClaimRequest request(InboxClaimAttempt attempt, Duration processingLease) { - return new InboxClaimRequest(SCOPE, INTENT, attempt, processingLease, Duration.ofDays(7)); - } - - private static void migrate(String location, String historyTable) { - Flyway.configure() - .dataSource(postgres.dataSource()) - .locations(location) - .table(historyTable) - .baselineOnMigrate(false) - .outOfOrder(false) - .load() - .migrate(); - } - - private static void migrateIndependent( - String location, String historyTable, String baselineDescription) { - Flyway flyway = - Flyway.configure() - .dataSource(postgres.dataSource()) - .locations(location) - .table(historyTable) - .baselineVersion("0") - .baselineDescription(baselineDescription) - .baselineOnMigrate(false) - .outOfOrder(false) - .load(); - flyway.baseline(); - flyway.migrate(); - } - - private static void await(CountDownLatch latch) { - try { - latch.await(); - } catch (InterruptedException exception) { - Thread.currentThread().interrupt(); - throw new IllegalStateException("test synchronization interrupted", exception); - } - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlLegacyOutboxConcurrentRelayIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlLegacyOutboxConcurrentRelayIntegrationTest.java index c900c0d7..7a883450 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlLegacyOutboxConcurrentRelayIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlLegacyOutboxConcurrentRelayIntegrationTest.java @@ -2,11 +2,15 @@ package dev.caskeleton.adapter.outbound.persistence.readiness; import static org.assertj.core.api.Assertions.assertThat; +import dev.caskeleton.adapter.outbound.persistence.outbox.OutboxStoreAdapter; import dev.caskeleton.application.outbox.LegacyOutboxAppendPort; import dev.caskeleton.application.outbox.NewOutboxEvent; +import dev.caskeleton.application.outbox.OutboxEventStatus; import dev.caskeleton.application.outbox.OutboxRelayResult; +import dev.caskeleton.application.outbox.OutboxStorePort; import dev.caskeleton.application.outbox.PublishPendingOutboxEventsCommand; import dev.caskeleton.application.outbox.PublishPendingOutboxEventsUseCase; +import dev.caskeleton.application.outbox.testkit.OutboxLeaseFencingContract; import dev.caskeleton.application.transaction.TransactionPort; import java.time.Clock; import java.time.Instant; @@ -21,11 +25,15 @@ import java.util.concurrent.atomic.AtomicInteger; import javax.sql.DataSource; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.jdbc.core.JdbcTemplate; /** - * Integration test #5 — multi-instance relay (leader-election via SKIP LOCKED). + * Integration test #5 — multi-instance relay (leader-election via SKIP LOCKED), plus the lease + * fencing contract ({@link OutboxLeaseFencingContract}) against the real adapter and claim SQL: a + * relay that stalls past its in-flight timeout cannot overwrite the relay that took its row over. * *

Spec: PENDING 1000 rows, 2 independent Spring contexts, relay driven concurrently; total * publishes = 1000 and no eventId published twice. @@ -34,20 +42,31 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext * ConcurrentHashMap}. Both relay loops run until the store is drained (claimedCount == 0 for both * instances). Then assert total = 1000, duplicates = 0. */ -class PostgreSqlLegacyOutboxConcurrentRelayIntegrationTest { +class PostgreSqlLegacyOutboxConcurrentRelayIntegrationTest extends OutboxLeaseFencingContract { private static PostgreSqlReadinessSupport postgres; private static DataSource sharedDataSource; + private static AnnotationConfigApplicationContext contractContext; @BeforeAll static void setup() { postgres = PostgreSqlReadinessSupport.start(); sharedDataSource = postgres.dataSource(); LegacyOutboxIntegrationSupport.migrate(sharedDataSource); + contractContext = + LegacyOutboxIntegrationSupport.buildContext(sharedDataSource, e -> {}, Clock.systemUTC()); + } + + @BeforeEach + void emptyOutbox() { + new JdbcTemplate(sharedDataSource).execute("TRUNCATE outbox_event"); } @AfterAll static void cleanup() { + if (contractContext != null) { + contractContext.close(); + } if (postgres != null) { postgres.close(); } @@ -144,6 +163,29 @@ class PostgreSqlLegacyOutboxConcurrentRelayIntegrationTest { .isEqualTo(1000); } + @Override + protected OutboxStorePort store() { + return contractContext.getBean(OutboxStoreAdapter.class); + } + + @Override + protected LegacyOutboxAppendPort append() { + return contractContext.getBean(OutboxStoreAdapter.class); + } + + @Override + protected TransactionPort transactions() { + return contractContext.getBean(TransactionPort.class); + } + + @Override + protected OutboxEventStatus statusOf(String eventId) { + return OutboxEventStatus.valueOf( + new JdbcTemplate(sharedDataSource) + .queryForObject( + "select status from outbox_event where event_id = ?", String.class, eventId)); + } + /** Runs the relay in a loop until claimedCount == 0 (store drained). */ private int drainRelay(PublishPendingOutboxEventsUseCase relay) { int total = 0; diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlLegacyOutboxRowLifecycleIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlLegacyOutboxRowLifecycleIntegrationTest.java index 06b08dd6..c04b92f3 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlLegacyOutboxRowLifecycleIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlLegacyOutboxRowLifecycleIntegrationTest.java @@ -5,11 +5,11 @@ import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.adapter.outbound.persistence.outbox.OutboxEventJpaRepository; import dev.caskeleton.adapter.outbound.persistence.outbox.OutboxReaper; import dev.caskeleton.adapter.outbound.persistence.outbox.OutboxStoreAdapter; -import dev.caskeleton.application.outbox.ClaimedOutboxEvent; import dev.caskeleton.application.outbox.LegacyOutboxAppendPort; import dev.caskeleton.application.outbox.NewOutboxEvent; import dev.caskeleton.application.outbox.OutboxBackoffPolicy; import dev.caskeleton.application.outbox.OutboxEventStatus; +import dev.caskeleton.application.outbox.OutboxLease; import dev.caskeleton.application.outbox.OutboxMessagePublishPort; import dev.caskeleton.application.outbox.OutboxRelayResult; import dev.caskeleton.application.outbox.PublishPendingOutboxEventsCommand; @@ -21,6 +21,7 @@ import java.time.Instant; import java.time.ZoneOffset; import java.util.List; import java.util.Map; +import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.random.RandomGenerator; @@ -592,7 +593,7 @@ class PostgreSqlLegacyOutboxRowLifecycleIntegrationTest { }); // Claim the row but do NOT mark it published (simulates relay crash) - tx.inWrite(() -> store.claimBatch(1, t0, Duration.ofSeconds(30))); + tx.inWrite(() -> store.claimBatch("crashed-relay", 1, t0, Duration.ofSeconds(30))); // Verify it's now IN_FLIGHT Map afterClaim = store.countByStatus(); @@ -610,7 +611,8 @@ class PostgreSqlLegacyOutboxRowLifecycleIntegrationTest { new OutboxBackoffPolicy(RandomGenerator.getDefault()), reclaimClock, LegacyOutboxIntegrationSupport.BATCH_SIZE_CONTRACT, - LegacyOutboxIntegrationSupport.IN_FLIGHT_TIMEOUT); + LegacyOutboxIntegrationSupport.IN_FLIGHT_TIMEOUT, + UUID.randomUUID().toString()); OutboxRelayResult reclaimResult = reclaimRelay.handle(PublishPendingOutboxEventsCommand.INSTANCE); @@ -651,14 +653,10 @@ class PostgreSqlLegacyOutboxRowLifecycleIntegrationTest { }); // Claim and mark as PUBLISHED - List claimed = - tx.inWrite(() -> store.claimBatch(1, eventTime, Duration.ofSeconds(1))); + List claimed = + tx.inWrite(() -> store.claimBatch("reaper-test", 1, eventTime, Duration.ofSeconds(1))); assertThat(claimed).hasSize(1); - tx.inWrite( - () -> { - store.markPublished(eventId); - return null; - }); + tx.inWrite(() -> store.markPublished(claimed.getFirst())); // Verify it's PUBLISHED Map before = store.countByStatus(); @@ -700,7 +698,8 @@ class PostgreSqlLegacyOutboxRowLifecycleIntegrationTest { new OutboxBackoffPolicy(RandomGenerator.getDefault()), Clock.fixed(clockInstant, ZoneOffset.UTC), LegacyOutboxIntegrationSupport.BATCH_SIZE_CONTRACT, - LegacyOutboxIntegrationSupport.IN_FLIGHT_TIMEOUT); + LegacyOutboxIntegrationSupport.IN_FLIGHT_TIMEOUT, + UUID.randomUUID().toString()); } private static NewOutboxEvent newEvent(String eventId, String aggregateId, Clock clock) { diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlMigrationIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlMigrationIntegrationTest.java index 5a07c452..f855a55a 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlMigrationIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlMigrationIntegrationTest.java @@ -48,7 +48,17 @@ class PostgreSqlMigrationIntegrationTest { .migrate(); assertThat(appliedVersions(postgres, "flyway_schema_history")) - .containsExactly("1", "3", "4", "5", "6", "9", "10", "11", "12", "13", "14", "15"); + .containsExactly( + "1", "3", "4", "5", "6", "9", "10", "11", "12", "13", "14", "15", "16", "17"); + assertThat( + singleValue( + postgres, + "select string_agg(distinct data_type, ',') from information_schema.columns " + + "where table_name = 'outbox_event' and column_name in ('partition_key', " + + "'schema_set_hash', 'envelope_sha256', 'envelope_schema_hash', " + + "'payload_schema_hash')")) + .as("V16 widens V13's char(64) hash columns to the varchar Hibernate validates") + .isEqualTo("character varying"); Flyway coreStream = Flyway.configure() diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationBackgroundPassIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationBackgroundPassIntegrationTest.java new file mode 100644 index 00000000..6a5f4566 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationBackgroundPassIntegrationTest.java @@ -0,0 +1,553 @@ +package dev.caskeleton.adapter.outbound.persistence.readiness; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.adapter.outbound.notification.platform.dispatch.ProviderEventReplayWorker; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.DeliveryAttemptJpaRepository; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaDeliveryAttemptStore; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaProviderEventLedger; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaRecipientDeliveryStore; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.JpaRecipientLeaseStore; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.NotificationRecordMapper; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.ProviderEventJpaRepository; +import dev.caskeleton.adapter.outbound.persistence.notification.platform.RecipientDeliveryJpaRepository; +import dev.caskeleton.adapter.outbound.persistence.transaction.SpringTransactionPort; +import dev.caskeleton.application.notification.platform.api.DeliveryAttemptId; +import dev.caskeleton.application.notification.platform.api.NormalizedEventType; +import dev.caskeleton.application.notification.platform.api.NormalizedProviderEvent; +import dev.caskeleton.application.notification.platform.api.ProviderId; +import dev.caskeleton.application.notification.platform.api.ProviderProfileId; +import dev.caskeleton.application.notification.platform.api.delivery.DeliveryOutcome; +import dev.caskeleton.application.notification.platform.api.delivery.EvidenceLevel; +import dev.caskeleton.application.notification.platform.callback.DeliveryAttemptSnapshot; +import dev.caskeleton.application.notification.platform.callback.DeliveryProjection; +import dev.caskeleton.application.notification.platform.callback.ProjectionResult; +import dev.caskeleton.application.notification.platform.callback.ProviderEventProjectionService; +import dev.caskeleton.application.notification.platform.callback.ProviderEventProjector; +import dev.caskeleton.application.notification.platform.callback.ProviderEventRecord; +import dev.caskeleton.application.notification.platform.dispatch.LeaseRecoveryService; +import dev.caskeleton.application.notification.platform.dispatch.NotificationRoutingPlanCodecPort; +import dev.caskeleton.application.notification.platform.dispatch.NotificationVariablesCodecPort; +import dev.caskeleton.application.notification.platform.dispatch.ReconciliationGatewayPort; +import dev.caskeleton.application.notification.platform.dispatch.ReconciliationService; +import dev.caskeleton.application.notification.platform.dispatch.SyntheticEventFingerprint; +import dev.caskeleton.application.notification.platform.observation.NotificationMetricsPort; +import dev.caskeleton.application.notification.platform.policy.RouteCandidate; +import dev.caskeleton.application.notification.platform.provider.ReconciliationResult; +import dev.caskeleton.application.notification.platform.security.NotificationPayloadProtection; +import dev.caskeleton.application.transaction.TransactionPort; +import jakarta.persistence.EntityManagerFactory; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.sql.Timestamp; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import javax.sql.DataSource; +import org.flywaydb.core.Flyway; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +/** + * The background passes, run the way the scheduler runs them: with no transaction around them. + * + *

Recovery, replay and reconciliation called {@code @Modifying} repository queries straight from + * the pass, and a modifying JPA query outside a transaction throws. The scheduler logs the failure + * and tries again next interval, so every pass failed and nothing said so. The fencing test beside + * this one hid it by opening the transaction itself; here the only transaction boundary is the one + * production code opens through {@link TransactionPort}. + */ +@Tag("jpa-contract") +class PostgreSqlNotificationBackgroundPassIntegrationTest { + + private static final String PROFILE = "email-main"; + private static final Duration STALE_AFTER = Duration.ofSeconds(30); + + private static PostgreSqlReadinessSupport database; + private static AnnotationConfigApplicationContext context; + + private final Clock clock = Clock.systemUTC(); + private JdbcTemplate jdbc; + private TransactionPort transactions; + private JpaDeliveryAttemptStore attempts; + private JpaProviderEventLedger ledger; + private ProviderEventProjectionService projection; + private ReconciliationService reconciliation; + + @BeforeAll + static void startDatabase() { + database = PostgreSqlReadinessSupport.start(); + migrate(database.dataSource()); + context = new AnnotationConfigApplicationContext(); + context.getBeanFactory().registerSingleton("dataSource", database.dataSource()); + context.register(NotificationJpa.class); + context.refresh(); + } + + @AfterAll + static void stopDatabase() { + if (context != null) { + context.close(); + } + if (database != null) { + database.close(); + } + } + + @BeforeEach + void assemble() { + jdbc = new JdbcTemplate(database.dataSource()); + jdbc.execute( + "TRUNCATE notification_provider_event, notification_delivery_attempt," + + " notification_recipient_delivery, notification_contact_point, notification_request" + + " CASCADE"); + transactions = new SpringTransactionPort(context.getBean(PlatformTransactionManager.class)); + RecipientDeliveryJpaRepository recipients = + context.getBean(RecipientDeliveryJpaRepository.class); + attempts = + new JpaDeliveryAttemptStore( + context.getBean(DeliveryAttemptJpaRepository.class), + recipients, + (profile, requestId) -> sha256Hex(requestId), + clock); + ledger = + new JpaProviderEventLedger( + context.getBean(ProviderEventJpaRepository.class), + attempts, + (profile, requestId) -> sha256Hex(requestId), + new EmptyAttributes(), + UUID::randomUUID); + projection = + new ProviderEventProjectionService( + ledger, + providerId -> + switch (providerId.value()) { + case "ses" -> Optional.of(new DeliveredProjector(providerId)); + case "broken" -> Optional.of(new ThrowingProjector(providerId)); + default -> Optional.empty(); + }, + attempts, + attempts, + (attempt, facts) -> {}, + transactions, + new NoMetrics()); + reconciliation = + new ReconciliationService( + attempts, + deliveries(recipients), + new ConfirmingGateway(), + ledger, + projection, + event -> {}, + new NoMetrics(), + new SyntheticEventFingerprint( + PostgreSqlNotificationBackgroundPassIntegrationTest::sha256), + transactions, + clock); + } + + @Test + void recoveryRequeuesADeliveryAbandonedBeforeAnyAttempt() { + // given + UUID delivery = + insertDelivery("DISPATCHING", Instant.now().minus(Duration.ofMinutes(10)), null); + + // when + recovery().recoverOnce(); + + // then + assertThat(deliveryState(delivery)).isEqualTo("READY_TO_DISPATCH"); + } + + @Test + void recoveryRetiresADeliveryWhoseWindowClosed() { + // given + UUID delivery = + insertDelivery("READY_TO_DISPATCH", null, Instant.now().minus(Duration.ofMinutes(1))); + + // when + recovery().recoverOnce(); + + // then + assertThat(deliveryState(delivery)).isEqualTo("EXPIRED"); + } + + @Test + void recoveryRecordsTheProvidersAnswerForAnAttemptThatMayHaveBeenSent() { + // given + UUID delivery = + insertDelivery("DISPATCHING", Instant.now().minus(Duration.ofMinutes(10)), null); + UUID attempt = insertStartedAttempt(delivery, "ses", null); + + // when + recovery().recoverOnce(); + + // then + assertThat(eventOf(attempt)).containsExactly("RECONCILIATION", "APPLIED"); + } + + @Test + void reconciliationRecordsAConfirmedAnswerOutsideAnyCallerTransaction() { + // given + UUID delivery = insertDelivery("RECONCILIATION_REQUIRED", null, null); + UUID attempt = insertStartedAttempt(delivery, "ses", null); + + // when + reconciliation.reconcile(new DeliveryAttemptId(attempt)); + + // then + assertThat(eventOf(attempt)).containsExactly("RECONCILIATION", "APPLIED"); + } + + @Test + void replayBindsAndProjectsACallbackThatArrivedBeforeItsAttempt() { + // given + String requestHash = sha256Hex("ses-request-1"); + UUID delivery = insertDelivery("COMPLETED", null, null); + UUID attempt = insertStartedAttempt(delivery, "ses", requestHash); + UUID event = insertPendingEvent(null, requestHash); + + // when + replay().replayOnce(); + + // then + assertThat(eventRow(event)).containsExactly(attempt.toString(), "APPLIED", null); + } + + @Test + void replayMarksAnEventWithNoProjectorFailed() { + // given + UUID delivery = insertDelivery("COMPLETED", null, null); + UUID attempt = insertStartedAttempt(delivery, "orphan", null); + UUID event = insertPendingEvent(attempt, null); + + // when + replay().replayOnce(); + + // then + assertThat(eventRow(event)).containsExactly(attempt.toString(), "FAILED", "NO_PROJECTOR"); + } + + @Test + void replayMarksAnEventWhoseProjectionThrowsFailed() { + // given + UUID delivery = insertDelivery("COMPLETED", null, null); + UUID attempt = insertStartedAttempt(delivery, "broken", null); + UUID event = insertPendingEvent(attempt, null); + + // when + replay().replayOnce(); + + // then + assertThat(eventRow(event)) + .containsExactly(attempt.toString(), "FAILED", "IllegalStateException"); + } + + private LeaseRecoveryService recovery() { + return new LeaseRecoveryService( + new JpaRecipientLeaseStore(context.getBean(RecipientDeliveryJpaRepository.class), clock), + attempts, + deliveries(context.getBean(RecipientDeliveryJpaRepository.class)), + reconciliation::reconcile, + transactions, + clock, + STALE_AFTER, + 10); + } + + private ProviderEventReplayWorker replay() { + return new ProviderEventReplayWorker(ledger, projection, 10); + } + + private JpaRecipientDeliveryStore deliveries(RecipientDeliveryJpaRepository recipients) { + return new JpaRecipientDeliveryStore( + recipients, + new NotificationRecordMapper(new EmptyRoutingPlans(), new EmptyAttributes(), new Opaque()), + clock); + } + + private static void migrate(DataSource dataSource) { + Flyway core = + Flyway.configure() + .dataSource(dataSource) + .locations("classpath:db/migration/jpa/core") + .table("flyway_jpa_core_history") + .baselineVersion("0") + .baselineDescription("core baseline") + .load(); + core.baseline(); + core.migrate(); + new JdbcTemplate(dataSource) + .update( + "update capability_schema_registry set lifecycle_state = 'ACTIVE' " + + "where capability_id = ?", + "jpa-flyway-migration"); + Flyway notification = + Flyway.configure() + .dataSource(dataSource) + .locations("classpath:db/migration/jpa/notification-platform") + .table("flyway_jpa_notification_history") + .baselineVersion("0") + .baselineDescription("notification baseline") + .load(); + notification.baseline(); + notification.migrate(); + } + + private UUID insertDelivery(String state, Instant leaseUntil, Instant expiresAt) { + UUID request = UUID.randomUUID(); + UUID delivery = UUID.randomUUID(); + jdbc.update( + "insert into notification_request (id, tenant_id, idempotency_key, request_fingerprint," + + " category, template_id, template_version, strategy_type, variables_payload," + + " request_status, metadata_json, created_at, updated_at)" + + " values (?, 'tenant-a', ?, ?, 'TRANSACTIONAL', 'welcome', 1, 'SingleRoute', ''," + + " 'VALIDATED', '{}'::jsonb, now(), now())", + request, + "idem-" + request, + "0".repeat(64)); + jdbc.update( + "insert into notification_recipient_delivery (id, notification_id, tenant_id," + + " recipient_ref, routing_plan_json, route_cursor, delivery_state, submission_outcome," + + " delivery_outcome, evidence_level, attempt_count, next_dispatch_at, lease_owner," + + " lease_until, expires_at, created_at, updated_at)" + + " values (?, ?, 'tenant-a', 'user-1', '[]'::jsonb, 0, ?, 'NOT_SUBMITTED', 'UNKNOWN'," + + " 'PLATFORM_QUEUED', 0, now(), ?, ?, ?, now(), now())", + delivery, + request, + state, + leaseUntil == null ? null : "dead-worker", + leaseUntil == null ? null : Timestamp.from(leaseUntil), + expiresAt == null ? null : Timestamp.from(expiresAt)); + return delivery; + } + + /** An attempt that started and never completed: the provider may or may not have it. */ + private UUID insertStartedAttempt(UUID delivery, String providerId, String requestHash) { + UUID contact = UUID.randomUUID(); + UUID attempt = UUID.randomUUID(); + jdbc.update( + "insert into notification_contact_point (id, tenant_id, owner_ref, type, environment," + + " ciphertext, nonce, lookup_hmac, key_id, status, created_at, updated_at)" + + " values (?, 'tenant-a', 'user-1', 'EMAIL', 'PRODUCTION', ?, ?, ?, 'key-1', 'ACTIVE'," + + " now(), now())", + contact, + new byte[] {1, 2, 3}, + new byte[] {4, 5, 6}, + UUID.randomUUID().toString().replace("-", "").repeat(2)); + jdbc.update( + "insert into notification_delivery_attempt (id, recipient_delivery_id, contact_point_id," + + " attempt_no, channel, provider_id, provider_profile_id, provider_request_id_hash," + + " request_started, request_started_certainty, request_body_committed," + + " request_body_committed_certainty, provider_response_received," + + " provider_response_received_certainty, submission_outcome, delivery_outcome," + + " confirmation, evidence_level, started_at, credential_generation," + + " rendered_content_digest, created_at, updated_at)" + + " values (?, ?, ?, 1, 'EMAIL', ?, ?, ?, true, 'PROVEN', false, 'UNKNOWN', false," + + " 'UNKNOWN', 'NOT_SUBMITTED', 'UNKNOWN', 'AMBIGUOUS', 'PLATFORM_QUEUED', now(), 1, ?," + + " now(), now())", + attempt, + delivery, + contact, + providerId, + PROFILE, + requestHash, + "0".repeat(64)); + return attempt; + } + + private UUID insertPendingEvent(UUID attempt, String requestHash) { + UUID event = UUID.randomUUID(); + jdbc.update( + "insert into notification_provider_event (id, provider_profile_id, event_fingerprint," + + " provider_request_id_hash, attempt_id, event_type, provider_native_type," + + " event_source, received_at, signature_verified, raw_payload_digest," + + " projection_status)" + + " values (?, ?, ?, ?, ?, 'DELIVERY_CONFIRMED', 'Delivery', 'CALLBACK', now(), true," + + " ?, 'PENDING')", + event, + PROFILE, + sha256Hex(event.toString()), + requestHash, + attempt, + "0".repeat(64)); + return event; + } + + private String deliveryState(UUID delivery) { + return jdbc.queryForObject( + "select delivery_state from notification_recipient_delivery where id = ?", + String.class, + delivery); + } + + private List eventOf(UUID attempt) { + return jdbc + .query( + "select event_source, projection_status from notification_provider_event" + + " where attempt_id = ?", + (row, index) -> List.of(row.getString(1), row.getString(2)), + attempt) + .stream() + .findFirst() + .orElse(List.of()); + } + + private List eventRow(UUID event) { + return jdbc.queryForObject( + "select attempt_id::text, projection_status, projection_error_code" + + " from notification_provider_event where id = ?", + (row, index) -> + java.util.Arrays.asList(row.getString(1), row.getString(2), row.getString(3)), + event); + } + + private static byte[] sha256(byte[] input) { + try { + return MessageDigest.getInstance("SHA-256").digest(input); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static String sha256Hex(String value) { + return java.util.HexFormat.of() + .formatHex(sha256(value.getBytes(java.nio.charset.StandardCharsets.UTF_8))); + } + + /** The notification entities and repositories, wired the way the production scan wires them. */ + @Configuration + @EnableTransactionManagement + @EnableJpaRepositories( + basePackages = "dev.caskeleton.adapter.outbound.persistence.notification.platform") + static class NotificationJpa { + + @Bean + LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) { + LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean(); + factory.setDataSource(dataSource); + factory.setPackagesToScan( + "dev.caskeleton.adapter.outbound.persistence.notification.platform"); + factory.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); + factory.setJpaPropertyMap( + Map.of( + "hibernate.hbm2ddl.auto", "validate", + "hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect")); + return factory; + } + + @Bean + PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) { + return new JpaTransactionManager(entityManagerFactory); + } + } + + /** The provider always knows the answer: it delivered. */ + private static final class ConfirmingGateway implements ReconciliationGatewayPort { + + @Override + public boolean supports(ProviderProfileId profileId) { + return true; + } + + @Override + public ReconciliationResult reconcile(DeliveryAttemptSnapshot attempt) { + return new ReconciliationResult.Confirmed( + new NormalizedProviderEvent( + NormalizedEventType.DELIVERY_CONFIRMED, + "Delivery", + Optional.of("provider-event-" + attempt.attemptId().value()), + Optional.empty(), + Optional.of(Instant.parse("2026-09-25T00:00:00Z")), + Map.of())); + } + } + + private record DeliveredProjector(ProviderId providerId) implements ProviderEventProjector { + + @Override + public ProjectionResult project( + DeliveryAttemptSnapshot attempt, ProviderEventRecord event, DeliveryProjection current) { + return ProjectionResult.applied( + current.withDelivery(DeliveryOutcome.DELIVERED, EvidenceLevel.DEVICE_DELIVERED), + "DELIVERED"); + } + } + + private record ThrowingProjector(ProviderId providerId) implements ProviderEventProjector { + + @Override + public ProjectionResult project( + DeliveryAttemptSnapshot attempt, ProviderEventRecord event, DeliveryProjection current) { + throw new IllegalStateException("projector defect"); + } + } + + private static final class EmptyAttributes implements NotificationVariablesCodecPort { + + @Override + public String encode(Map variables) { + return "{}"; + } + + @Override + public Map decode(String payload) { + return Map.of(); + } + } + + private static final class EmptyRoutingPlans implements NotificationRoutingPlanCodecPort { + + @Override + public String encode(List routes) { + return "[]"; + } + + @Override + public List decode(String payload) { + return List.of(); + } + } + + private static final class Opaque implements NotificationPayloadProtection { + + @Override + public byte[] protect(byte[] plaintext) { + return plaintext.clone(); + } + + @Override + public byte[] reveal(byte[] envelope) { + return envelope.clone(); + } + } + + private static final class NoMetrics implements NotificationMetricsPort { + + @Override + public void increment(String metricName, Map tags) {} + + @Override + public void record(String metricName, Map tags, Duration value) {} + + @Override + public void gauge(String metricName, Map tags, double value) {} + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOptionalStreamLifecycle.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOptionalStreamLifecycle.java index 6828c7b1..21550c10 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOptionalStreamLifecycle.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOptionalStreamLifecycle.java @@ -46,44 +46,6 @@ final class PostgreSqlOptionalStreamLifecycle { List.of()); } - static Stream outboxStorage() { - return new Stream( - "jpa-outbox-storage-v2", - "classpath:db/migration/jpa/outbox-storage", - "flyway_jpa_outbox_storage_history", - 2, - List.of( - "outbox_event", - "outbox_publication_control_v2", - "outbox_publication_cutover_v2", - "outbox_event_identity_v2", - "outbox_event_log_v2"), - List.of("0", "1", "2"), - List.of()); - } - - static Stream outboxPolling() { - return new Stream( - "jpa-outbox-polling-delivery-v2", - "classpath:db/migration/jpa/outbox-polling", - "flyway_jpa_outbox_polling_history", - 2, - List.of("outbox_delivery_v2"), - List.of("0", "1", "2"), - List.of(outboxStorage())); - } - - static Stream inbox() { - return new Stream( - "jpa-inbox-same-store-v1", - "classpath:db/migration/jpa/inbox", - "flyway_jpa_inbox_history", - 1, - List.of("inbox_record_v1"), - List.of("0", "1"), - List.of()); - } - static Stream fileserver() { return new Stream( "jpa-fileserver-metadata-v1", @@ -150,71 +112,6 @@ final class PostgreSqlOptionalStreamLifecycle { verifyInterruptedRecovery(stream); } - static void verifyOutboxStorageUpgradeWithExistingPollingV1() { - try (PostgreSqlReadinessSupport database = PostgreSqlReadinessSupport.start()) { - Stream core = - new Stream( - "jpa-flyway-migration", - "classpath:db/migration/jpa/core", - "flyway_jpa_core_history", - 1, - List.of("capability_schema_registry"), - List.of("0", "1", "2"), - List.of()); - migrateAndActivate(database, core); - - Stream storage = outboxStorage(); - Flyway storageV1 = - Flyway.configure() - .dataSource(database.dataSource()) - .locations(storage.location()) - .table(storage.historyTable()) - .baselineVersion("0") - .baselineDescription("explicit-outbox-storage-v1-upgrade-order") - .baselineOnMigrate(false) - .outOfOrder(false) - .target("1") - .load(); - storageV1.baseline(); - storageV1.migrate(); - JdbcTemplate jdbc = new JdbcTemplate(database.dataSource()); - setLifecycle(jdbc, storage.cardId(), "ACTIVE"); - - Stream polling = outboxPolling(); - Flyway pollingV1 = - Flyway.configure() - .dataSource(database.dataSource()) - .locations(polling.location()) - .table(polling.historyTable()) - .baselineVersion("0") - .baselineDescription("explicit-outbox-polling-v1-upgrade-order") - .baselineOnMigrate(false) - .outOfOrder(false) - .target("1") - .load(); - pollingV1.baseline(); - pollingV1.migrate(); - setLifecycle(jdbc, polling.cardId(), "ACTIVE"); - - Flyway storageLatest = independent(database, storage); - storageLatest.migrate(); - - assertThat(characterMaximumLength(jdbc, "outbox_event_identity_v2", "event_id")) - .isEqualTo(96); - assertThat(characterMaximumLength(jdbc, "outbox_event_log_v2", "event_id")).isEqualTo(96); - assertThat(characterMaximumLength(jdbc, "outbox_delivery_v2", "event_id")).isEqualTo(96); - - Flyway pollingLatest = independent(database, polling); - pollingLatest.migrate(); - pollingLatest.validate(); - - assertThat(appliedVersions(jdbc, storage.historyTable())) - .containsExactlyElementsOf(storage.migratedVersions()); - assertThat(appliedVersions(jdbc, polling.historyTable())) - .containsExactlyElementsOf(polling.migratedVersions()); - } - } - private static void verifyFreshDisabledEnableDisableReEnable(Stream stream) throws Exception { try (PostgreSqlReadinessSupport database = PostgreSqlReadinessSupport.start()) { prepareFreshCoreAndPrerequisites(database, stream); @@ -330,20 +227,6 @@ final class PostgreSqlOptionalStreamLifecycle { "select to_regclass(?) is not null", Boolean.class, "public." + relation)); } - private static int characterMaximumLength(JdbcTemplate jdbc, String table, String column) { - Integer length = - jdbc.queryForObject( - "select character_maximum_length from information_schema.columns " - + "where table_schema = 'public' and table_name = ? and column_name = ?", - Integer.class, - table, - column); - if (length == null) { - throw new IllegalStateException("missing varchar column " + table + "." + column); - } - return length; - } - private static int markerCount(JdbcTemplate jdbc, String cardId) { return jdbc.queryForObject( "select count(*) from capability_schema_registry where capability_id = ?", diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxPollingIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxPollingIntegrationTest.java deleted file mode 100644 index 9642049a..00000000 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxPollingIntegrationTest.java +++ /dev/null @@ -1,353 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.readiness; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.outbound.persistence.postgresql.outbox.PostgreSqlImmutableOutboxAppendAdapter; -import dev.caskeleton.adapter.outbound.persistence.postgresql.outbox.PostgreSqlPollingDeliveryAdapter; -import dev.caskeleton.application.outbox.v2.ClaimedOutboxDelivery; -import dev.caskeleton.application.outbox.v2.NewOutboxEventV2; -import dev.caskeleton.application.outbox.v2.OutboxDeliveryClaimRequest; -import dev.caskeleton.application.outbox.v2.OutboxDeliveryTransition; -import dev.caskeleton.application.outbox.v2.OutboxDeliveryTransitionOutcome; -import dev.caskeleton.application.transaction.OperationId; -import java.time.Duration; -import java.util.List; -import org.flywaydb.core.Flyway; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.datasource.DataSourceTransactionManager; -import org.springframework.transaction.support.TransactionTemplate; - -class PostgreSqlOutboxPollingIntegrationTest { - - private static PostgreSqlReadinessSupport postgres; - private static JdbcTemplate jdbc; - private static TransactionTemplate transactions; - private static PostgreSqlImmutableOutboxAppendAdapter append; - private static PostgreSqlPollingDeliveryAdapter delivery; - - @BeforeAll - static void startAndMigratePostgreSql() { - PostgreSqlReadinessSupport.assertDockerAvailable(); - postgres = PostgreSqlReadinessSupport.start(); - migrate("classpath:db/migration/postgresql", "flyway_schema_history"); - migrateIndependent( - "classpath:db/migration/jpa/core", "flyway_jpa_core_history", "explicit-jpa-core-adoption"); - migrateIndependent( - "classpath:db/migration/jpa/outbox-storage", - "flyway_jpa_outbox_storage_history", - "explicit-jpa-outbox-storage-adoption"); - migrateIndependent( - "classpath:db/migration/jpa/outbox-polling", - "flyway_jpa_outbox_polling_history", - "explicit-jpa-outbox-polling-adoption"); - - jdbc = new JdbcTemplate(postgres.dataSource()); - transactions = new TransactionTemplate(new DataSourceTransactionManager(postgres.dataSource())); - append = new PostgreSqlImmutableOutboxAppendAdapter(postgres.dataSource()); - delivery = new PostgreSqlPollingDeliveryAdapter(postgres.dataSource()); - jdbc.update( - "update capability_schema_registry set lifecycle_state = 'ACTIVE' " - + "where capability_id in (" - + "'jpa-outbox-storage-v2', 'jpa-outbox-polling-delivery-v2')"); - transactions.executeWithoutResult(ignored -> cutoverToPollingV2()); - } - - @AfterAll - static void stopPostgreSql() { - if (postgres != null) { - postgres.close(); - } - } - - @BeforeEach - void clearRows() { - jdbc.update("delete from outbox_delivery_v2"); - jdbc.update("delete from outbox_event_log_v2"); - jdbc.update("delete from outbox_event_identity_v2"); - } - - @Test - void eventAndInitialDeliveryAreInsertedInTheSameBusinessTransaction() { - assertThatThrownBy(() -> append.append(event("event-no-tx", 1))) - .isInstanceOf(IllegalStateException.class); - - assertThatThrownBy( - () -> - transactions.executeWithoutResult( - ignored -> { - append.append(event("event-rollback", 1)); - throw new IllegalStateException("rollback"); - })) - .isInstanceOf(IllegalStateException.class); - assertThat(jdbc.queryForObject("select count(*) from outbox_event_log_v2", Integer.class)) - .isZero(); - assertThat(jdbc.queryForObject("select count(*) from outbox_delivery_v2", Integer.class)) - .isZero(); - - transactions.executeWithoutResult(ignored -> append.append(event("event-commit", 1))); - assertThat(jdbc.queryForObject("select count(*) from outbox_event_log_v2", Integer.class)) - .isEqualTo(1); - assertThat(jdbc.queryForObject("select count(*) from outbox_delivery_v2", Integer.class)) - .isEqualTo(1); - } - - @Test - void strictAggregateOrderClaimsOnlyTheHeadUntilItIsPublished() { - transactions.executeWithoutResult( - ignored -> { - append.append(event("event-v1", 1)); - append.append(event("event-v2", 2)); - }); - - List first = - transactions.execute( - ignored -> - delivery.claimBatch( - new OutboxDeliveryClaimRequest( - CanonicalOutboxV2TestFixture.DESTINATION, - "relay-1", - 10, - Duration.ofSeconds(30)))); - assertThat(first).extracting(item -> item.owner().eventId()).containsExactly("event-v1"); - assertThat(first.getFirst().event()).isEqualTo(event("event-v1", 1).event()); - - OutboxDeliveryTransition transition = - new OutboxDeliveryTransition(first.getFirst().owner(), new OperationId("publish-event-v1")); - transactions.executeWithoutResult( - ignored -> { - assertThat(delivery.markPublished(transition)) - .isEqualTo(OutboxDeliveryTransitionOutcome.PUBLISHED); - assertThat(delivery.markPublished(transition)) - .isEqualTo(OutboxDeliveryTransitionOutcome.ALREADY_APPLIED_SAME_OPERATION); - }); - - List second = - transactions.execute( - ignored -> - delivery.claimBatch( - new OutboxDeliveryClaimRequest( - CanonicalOutboxV2TestFixture.DESTINATION, - "relay-1", - 10, - Duration.ofSeconds(30)))); - assertThat(second).extracting(item -> item.owner().eventId()).containsExactly("event-v2"); - } - - @Test - void strictAggregateOrderingDoesNotCrossTenantBoundaries() { - transactions.executeWithoutResult( - ignored -> { - append.append( - CanonicalOutboxV2TestFixture.event( - "tenant-a-v1", "tenant-a", 1, 0, "{\"tenant\":\"a\",\"v\":1}")); - append.append( - CanonicalOutboxV2TestFixture.event( - "tenant-a-v2", "tenant-a", 2, 0, "{\"tenant\":\"a\",\"v\":2}")); - append.append( - CanonicalOutboxV2TestFixture.event( - "tenant-b-v1", "tenant-b", 1, 0, "{\"tenant\":\"b\",\"v\":1}")); - }); - - List heads = - transactions.execute( - ignored -> - delivery.claimBatch( - new OutboxDeliveryClaimRequest( - CanonicalOutboxV2TestFixture.DESTINATION, - "relay-tenant", - 10, - Duration.ofSeconds(30)))); - - assertThat(heads) - .extracting(item -> item.owner().eventId()) - .containsExactlyInAnyOrder("tenant-a-v1", "tenant-b-v1"); - assertThat(heads) - .extracting(item -> item.event().aggregate().tenantScope()) - .containsExactlyInAnyOrder("tenant-a", "tenant-b"); - } - - @Test - void preCanonicalRowCannotBeClaimedAsACanonicalDelivery() { - transactions.executeWithoutResult( - ignored -> insertPreCanonicalPollingRow("event-pre-canonical-claim", "{\"legacy\":true}")); - - assertThatThrownBy( - () -> - transactions.execute( - ignored -> - delivery.claimBatch( - new OutboxDeliveryClaimRequest( - CanonicalOutboxV2TestFixture.DESTINATION, - "relay-pre-canonical", - 1, - Duration.ofSeconds(30))))) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("pre-canonical") - .hasMessageContaining("event-pre-canonical-claim"); - - assertThat( - jdbc.queryForObject( - "select state from outbox_delivery_v2 where event_id = 'event-pre-canonical-claim'", - String.class)) - .isEqualTo("PENDING"); - } - - @Test - void publishAckLossReclaimsTheStableEventIdButRejectsTheStaleOwner() { - transactions.executeWithoutResult(ignored -> append.append(event("event-ack-loss", 1))); - ClaimedOutboxDelivery first = - transactions - .execute( - ignored -> - delivery.claimBatch( - new OutboxDeliveryClaimRequest( - CanonicalOutboxV2TestFixture.DESTINATION, - "relay-old", - 1, - Duration.ofMillis(25)))) - .getFirst(); - jdbc.queryForObject("select pg_sleep(0.05)", Object.class); - - ClaimedOutboxDelivery reclaimed = - transactions - .execute( - ignored -> - delivery.claimBatch( - new OutboxDeliveryClaimRequest( - CanonicalOutboxV2TestFixture.DESTINATION, - "relay-new", - 1, - Duration.ofSeconds(30)))) - .getFirst(); - - assertThat(reclaimed.owner().eventId()).isEqualTo(first.owner().eventId()); - assertThat(reclaimed.owner().attempt()).isEqualTo(2); - OutboxDeliveryTransitionOutcome staleResult = - transactions.execute( - ignored -> - delivery.markPublished( - new OutboxDeliveryTransition(first.owner(), new OperationId("stale-publish")))); - assertThat(staleResult).isEqualTo(OutboxDeliveryTransitionOutcome.NOT_OWNER); - } - - @Test - void retryWaitUsesTheRequestedScheduleAndDeadHeadBlocksTheAggregate() { - transactions.executeWithoutResult( - ignored -> { - append.append(event("event-retry-v1", 1)); - append.append(event("event-retry-v2", 2)); - }); - ClaimedOutboxDelivery head = - transactions - .execute( - ignored -> - delivery.claimBatch( - new OutboxDeliveryClaimRequest( - CanonicalOutboxV2TestFixture.DESTINATION, - "relay-1", - 10, - Duration.ofSeconds(30)))) - .getFirst(); - OutboxDeliveryTransition dead = - new OutboxDeliveryTransition(head.owner(), new OperationId("dead-head")); - OutboxDeliveryTransitionOutcome deadResult = - transactions.execute(ignored -> delivery.markDead(dead, "BROKER.PERMANENT")); - assertThat(deadResult).isEqualTo(OutboxDeliveryTransitionOutcome.DEAD); - - List blocked = - transactions.execute( - ignored -> - delivery.claimBatch( - new OutboxDeliveryClaimRequest( - CanonicalOutboxV2TestFixture.DESTINATION, - "relay-1", - 10, - Duration.ofSeconds(30)))); - assertThat(blocked).isEmpty(); - } - - @Test - void optionalStreamLifecycleIsNonDestructiveAndRecoversInterruptedMigration() throws Exception { - PostgreSqlOptionalStreamLifecycle.verify(PostgreSqlOptionalStreamLifecycle.outboxPolling()); - } - - private static void insertPreCanonicalPollingRow(String eventId, String payload) { - jdbc.update( - "insert into outbox_event_identity_v2(" - + "event_id, tenant_scope, aggregate_type, aggregate_id, aggregate_version, " - + "event_ordinal, retention_bucket, created_at" - + ") values (?, null, 'worklog', 'work-log-42', 1, 0, current_date, clock_timestamp())", - eventId); - jdbc.update( - "insert into outbox_event_log_v2(" - + "retention_bucket, event_id, aggregate_type, aggregate_id, aggregate_version, " - + "event_ordinal, event_type, event_schema, logical_destination, partition_key, " - + "publication_epoch, dispatch_authority, content_type, correlation_id, causation_id, " - + "occurred_at, payload, payload_digest, trace_parent, created_at" - + ") values (current_date, ?, 'worklog', 'work-log-42', 1, 0, 'LegacyEvent', 1, ?, " - + "'legacy-key', 2, 'POLLING_V2', 'application/json', 'correlation-1', null, " - + "clock_timestamp(), ?, ?, null, clock_timestamp())", - eventId, - CanonicalOutboxV2TestFixture.DESTINATION, - payload, - "0".repeat(64)); - } - - private static void cutoverToPollingV2() { - jdbc.queryForObject( - "select active_epoch from outbox_publication_control_v2 " - + "where scope_id = 'PRIMARY' for update", - Long.class); - jdbc.update( - "insert into outbox_publication_cutover_v2(" - + "scope_id, active_epoch, previous_epoch, transition_kind, active_authority, " - + "legacy_row_count, legacy_pending_count, legacy_digest, schema_manifest_id, " - + "external_manifest_id, activated_at" - + ") values (" - + "'PRIMARY', 2, 1, 'CUTOVER', 'POLLING_V2', 0, 0, ?, " - + "'jpa-outbox-storage-v2-schema-revision-2', null, clock_timestamp())", - "0".repeat(64)); - jdbc.update( - "update outbox_publication_control_v2 " - + "set active_epoch = 2, active_authority = 'POLLING_V2', " - + "revision = 1, updated_at = clock_timestamp() " - + "where scope_id = 'PRIMARY' and active_epoch = 1"); - } - - private static NewOutboxEventV2 event(String eventId, long aggregateVersion) { - return CanonicalOutboxV2TestFixture.event( - eventId, aggregateVersion, 0, "{\"version\":" + aggregateVersion + "}"); - } - - private static void migrate(String location, String historyTable) { - Flyway.configure() - .dataSource(postgres.dataSource()) - .locations(location) - .table(historyTable) - .baselineOnMigrate(false) - .outOfOrder(false) - .load() - .migrate(); - } - - private static void migrateIndependent( - String location, String historyTable, String baselineDescription) { - Flyway flyway = - Flyway.configure() - .dataSource(postgres.dataSource()) - .locations(location) - .table(historyTable) - .baselineVersion("0") - .baselineDescription(baselineDescription) - .baselineOnMigrate(false) - .outOfOrder(false) - .load(); - flyway.baseline(); - flyway.migrate(); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxStorageIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxStorageIntegrationTest.java deleted file mode 100644 index 06915957..00000000 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxStorageIntegrationTest.java +++ /dev/null @@ -1,457 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.readiness; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.outbound.persistence.postgresql.outbox.PostgreSqlImmutableOutboxAppendAdapter; -import dev.caskeleton.application.outbox.v2.NewOutboxEventV2; -import dev.caskeleton.application.outbox.v2.OutboxAppendOutcome; -import dev.caskeleton.application.outbox.v2.OutboxAppendReceipt; -import dev.caskeleton.application.outbox.v2.OutboxDispatchAuthority; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import org.flywaydb.core.Flyway; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.MethodOrderer; -import org.junit.jupiter.api.Order; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestInfo; -import org.junit.jupiter.api.TestMethodOrder; -import org.springframework.dao.DataAccessException; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.datasource.DataSourceTransactionManager; -import org.springframework.transaction.support.TransactionTemplate; - -@TestMethodOrder(MethodOrderer.OrderAnnotation.class) -class PostgreSqlOutboxStorageIntegrationTest { - - private static PostgreSqlReadinessSupport postgres; - private static JdbcTemplate jdbc; - private static TransactionTemplate transactions; - private static PostgreSqlImmutableOutboxAppendAdapter adapter; - - @BeforeAll - static void startAndMigratePostgreSql() { - PostgreSqlReadinessSupport.assertDockerAvailable(); - postgres = PostgreSqlReadinessSupport.start(); - migrate("classpath:db/migration/postgresql", "flyway_schema_history"); - migrateIndependent( - "classpath:db/migration/jpa/core", "flyway_jpa_core_history", "explicit-jpa-core-adoption"); - migrateIndependent( - "classpath:db/migration/jpa/outbox-storage", - "flyway_jpa_outbox_storage_history", - "explicit-jpa-outbox-storage-adoption"); - - jdbc = new JdbcTemplate(postgres.dataSource()); - transactions = new TransactionTemplate(new DataSourceTransactionManager(postgres.dataSource())); - adapter = new PostgreSqlImmutableOutboxAppendAdapter(postgres.dataSource()); - jdbc.update( - "update capability_schema_registry set lifecycle_state = 'ACTIVE' " - + "where capability_id = 'jpa-outbox-storage-v2'"); - jdbc.execute( - "create table outbox_business_probe (" - + "aggregate_id varchar(256) primary key, mutation_count integer not null)"); - } - - @AfterAll - static void stopPostgreSql() { - if (postgres != null) { - postgres.close(); - } - } - - @BeforeEach - void clearRowsAndRestoreLegacyAuthority(TestInfo testInfo) { - if (testInfo - .getTestMethod() - .filter( - method -> - method - .getName() - .equals( - "optionalStreamLifecycleIsNonDestructiveAndRecoversInterruptedMigration")) - .isPresent()) { - return; - } - jdbc.update("delete from outbox_event_log_v2"); - jdbc.update("delete from outbox_event_identity_v2"); - jdbc.update("delete from outbox_business_probe"); - jdbc.update( - "update outbox_publication_control_v2 " - + "set active_epoch = 1, active_authority = 'LEGACY_POLLING', " - + "state = 'ACTIVE', revision = 0, updated_at = clock_timestamp() " - + "where scope_id = 'PRIMARY'"); - jdbc.update("delete from outbox_publication_cutover_v2 where active_epoch > 1"); - } - - @Test - @Order(1) - void appendRequiresTheCallerSameDatasourceWriteTransaction() { - assertThatThrownBy(() -> adapter.append(event("event-no-tx", 1, 0, "{}"))) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("active primary write transaction"); - } - - @Test - @Order(2) - void immutableIdentityEnvelopeAndBusinessMutationCommitOrRollbackTogether() { - assertThatThrownBy( - () -> - transactions.executeWithoutResult( - ignored -> { - jdbc.update( - "insert into outbox_business_probe(aggregate_id, mutation_count) " - + "values ('work-log-42', 1)"); - adapter.append(event("event-rollback", 1, 0, "{\"rollback\":true}")); - throw new IllegalStateException("force rollback"); - })) - .isInstanceOf(IllegalStateException.class) - .hasMessage("force rollback"); - assertThat(jdbc.queryForObject("select count(*) from outbox_event_identity_v2", Integer.class)) - .isZero(); - assertThat(jdbc.queryForObject("select count(*) from outbox_business_probe", Integer.class)) - .isZero(); - - NewOutboxEventV2 committed = event("event-commit", 1, 0, "{\"ok\":true}"); - OutboxAppendReceipt appended = - transactions.execute( - ignored -> { - jdbc.update( - "insert into outbox_business_probe(aggregate_id, mutation_count) " - + "values ('work-log-42', 1)"); - return adapter.append(committed); - }); - - assertThat(appended.outcome()).isEqualTo(OutboxAppendOutcome.APPENDED); - assertThat(appended.dispatchAuthority()).isEqualTo(OutboxDispatchAuthority.LEGACY_SHADOW); - assertThat(jdbc.queryForObject("select count(*) from outbox_event_log_v2", Integer.class)) - .isEqualTo(1); - assertThat(jdbc.queryForObject("select count(*) from outbox_business_probe", Integer.class)) - .isEqualTo(1); - assertThat( - jdbc.queryForObject( - "select envelope_bytes from outbox_event_log_v2 where event_id = 'event-commit'", - byte[].class)) - .containsExactly(committed.event().envelopeBytes()); - assertThat( - jdbc.queryForMap( - "select tenant_scope, envelope_version, schema_set_hash, envelope_sha256, " - + "envelope_schema_hash, payload_schema_hash, contract_catalog_revision, " - + "destination_binding_revision from outbox_event_log_v2 " - + "where event_id = 'event-commit'")) - .containsEntry("tenant_scope", committed.event().aggregate().tenantScope()) - .containsEntry("envelope_version", committed.event().envelopeVersion()) - .containsEntry("schema_set_hash", committed.event().schemaSetHash().toString()) - .containsEntry("envelope_sha256", committed.event().envelopeSha256().toString()) - .containsEntry("envelope_schema_hash", committed.event().envelopeSchemaHash().toString()) - .containsEntry("payload_schema_hash", committed.event().payloadSchemaHash().toString()) - .containsEntry("contract_catalog_revision", committed.event().contractCatalogRevision()) - .containsEntry( - "destination_binding_revision", committed.event().destinationBindingRevision()); - } - - @Test - @Order(3) - void duplicateIdentityDistinguishesSameEventIdConflictAndAggregateOrderConflict() { - NewOutboxEventV2 original = event("event-1", 7, 0, "{\"value\":1}"); - OutboxAppendReceipt first = transactions.execute(ignored -> adapter.append(original)); - OutboxAppendReceipt replay = transactions.execute(ignored -> adapter.append(original)); - OutboxAppendReceipt eventIdConflict = - transactions.execute(ignored -> adapter.append(event("event-1", 7, 0, "{\"value\":2}"))); - OutboxAppendReceipt orderConflict = - transactions.execute( - ignored -> adapter.append(event("event-other", 7, 0, "{\"value\":1}"))); - - assertThat(first.outcome()).isEqualTo(OutboxAppendOutcome.APPENDED); - assertThat(replay.outcome()).isEqualTo(OutboxAppendOutcome.ALREADY_APPENDED_SAME_EVENT); - assertThat(eventIdConflict.outcome()).isEqualTo(OutboxAppendOutcome.EVENT_ID_CONFLICT); - assertThat(orderConflict.outcome()).isEqualTo(OutboxAppendOutcome.AGGREGATE_ORDER_CONFLICT); - assertThat(jdbc.queryForObject("select count(*) from outbox_event_identity_v2", Integer.class)) - .isEqualTo(1); - } - - @Test - @Order(8) - void canonicalEventLogCannotDriftFromItsImmutableTenantAggregateIdentity() { - NewOutboxEventV2 canonical = - CanonicalOutboxV2TestFixture.event( - "event-identity-fk", "tenant-a", 3, 1, "{\"identity\":true}"); - transactions.executeWithoutResult(ignored -> adapter.append(canonical)); - - assertThatThrownBy( - () -> - jdbc.update( - "update outbox_event_log_v2 set tenant_scope = 'tenant-b' " - + "where event_id = 'event-identity-fk'")) - .isInstanceOf(DataAccessException.class); - } - - @Test - @Order(9) - void invalidUtf8EnvelopeFailsBeforeWritingAnIdentity() { - NewOutboxEventV2 invalid = - CanonicalOutboxV2TestFixture.event( - "event-invalid-utf8", "tenant-a", 1, 0, new byte[] {(byte) 0xC3, (byte) 0x28}); - - assertThatThrownBy(() -> transactions.executeWithoutResult(ignored -> adapter.append(invalid))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("UTF-8"); - assertThat(jdbc.queryForObject("select count(*) from outbox_event_identity_v2", Integer.class)) - .isZero(); - } - - @Test - @Order(10) - void publicationControlShareLockPreventsCutoverFromOvertakingAnAppend() throws Exception { - CountDownLatch appendHasLockedControl = new CountDownLatch(1); - CountDownLatch allowAppendCommit = new CountDownLatch(1); - - try (var executor = Executors.newVirtualThreadPerTaskExecutor()) { - Future append = - executor.submit( - () -> { - transactions.executeWithoutResult( - ignored -> { - OutboxAppendReceipt receipt = - adapter.append(event("event-before-cutover", 1, 0, "{}")); - assertThat(receipt.dispatchAuthority()) - .isEqualTo(OutboxDispatchAuthority.LEGACY_SHADOW); - appendHasLockedControl.countDown(); - await(allowAppendCommit); - }); - return null; - }); - - appendHasLockedControl.await(); - Future cutover = - executor.submit( - () -> { - transactions.executeWithoutResult(ignored -> cutoverToPollingV2()); - return null; - }); - - assertThat(cutover.isDone()).isFalse(); - allowAppendCommit.countDown(); - append.get(); - cutover.get(); - } - - OutboxAppendReceipt afterCutover = - transactions.execute(ignored -> adapter.append(event("event-after-cutover", 2, 0, "{}"))); - assertThat(afterCutover.publicationEpoch()).isEqualTo(2); - assertThat(afterCutover.dispatchAuthority()).isEqualTo(OutboxDispatchAuthority.POLLING_V2); - - assertThatThrownBy( - () -> - jdbc.update( - "insert into outbox_event(" - + "event_id, aggregate_id, event_type, payload, occurred_at, status, " - + "attempt_count, next_attempt_at, correlation_id, idempotency_key" - + ") values (" - + "'legacy-after-cutover', 'work-log-42', 'Legacy', '{}', " - + "clock_timestamp(), 'PENDING', 0, clock_timestamp(), 'c', 'i')")) - .isInstanceOf(DataAccessException.class) - .hasMessageContaining("legacy outbox writer is fenced"); - } - - @Test - @Order(4) - void canonicalAggregateOrderingIsTenantScoped() { - OutboxAppendReceipt tenantA = - transactions.execute( - ignored -> - adapter.append( - CanonicalOutboxV2TestFixture.event( - "tenant-a-event", "tenant-a", 11, 0, "{\"tenant\":\"a\"}"))); - OutboxAppendReceipt tenantB = - transactions.execute( - ignored -> - adapter.append( - CanonicalOutboxV2TestFixture.event( - "tenant-b-event", "tenant-b", 11, 0, "{\"tenant\":\"b\"}"))); - - assertThat(tenantA.outcome()).isEqualTo(OutboxAppendOutcome.APPENDED); - assertThat(tenantB.outcome()).isEqualTo(OutboxAppendOutcome.APPENDED); - assertThat(jdbc.queryForObject("select count(*) from outbox_event_identity_v2", Integer.class)) - .isEqualTo(2); - } - - @Test - @Order(5) - void canonicalEventIdSupportsTheFullNinetySixCharacterBound() { - String eventId = "e".repeat(96); - - OutboxAppendReceipt receipt = - transactions.execute(ignored -> adapter.append(event(eventId, 1, 0, "{\"id\":96}"))); - - assertThat(receipt.outcome()).isEqualTo(OutboxAppendOutcome.APPENDED); - assertThat( - jdbc.queryForObject( - "select event_id from outbox_event_log_v2 where event_id = ?", - String.class, - eventId)) - .isEqualTo(eventId); - } - - @Test - @Order(6) - void canonicalReplayFailsClosedForAPreCanonicalV2Row() { - transactions.executeWithoutResult( - ignored -> - insertPreCanonicalRow( - "event-pre-canonical", "worklog", "work-log-42", 1, 0, "{\"legacy\":true}")); - - assertThatThrownBy( - () -> - transactions.executeWithoutResult( - ignored -> - adapter.append(event("event-pre-canonical", 1, 0, "{\"legacy\":true}")))) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("pre-canonical") - .hasMessageContaining("event-pre-canonical"); - } - - @Test - @Order(7) - void databaseRejectsAPartiallyCanonicalV2Row() { - assertThatThrownBy( - () -> - transactions.executeWithoutResult( - ignored -> { - insertIdentity("event-partial", "tenant-a", "worklog", "work-log-42", 1, 0); - jdbc.update( - "insert into outbox_event_log_v2(" - + "retention_bucket, event_id, aggregate_type, aggregate_id, " - + "aggregate_version, event_ordinal, event_type, event_schema, " - + "logical_destination, partition_key, publication_epoch, " - + "dispatch_authority, content_type, correlation_id, causation_id, " - + "occurred_at, payload, payload_digest, trace_parent, created_at, " - + "tenant_scope" - + ") values (current_date, ?, 'worklog', 'work-log-42', 1, 0, " - + "'LegacyEvent', 1, 'legacy.destination', 'legacy-key', 1, " - + "'LEGACY_SHADOW', 'application/json', 'correlation-1', null, " - + "clock_timestamp(), '{}', ?, null, clock_timestamp(), 'tenant-a')", - "event-partial", - "0".repeat(64)); - })) - .isInstanceOf(DataAccessException.class); - } - - @Test - @Order(11) - void optionalStreamLifecycleIsNonDestructiveAndRecoversInterruptedMigration() throws Exception { - PostgreSqlOptionalStreamLifecycle.verify(PostgreSqlOptionalStreamLifecycle.outboxStorage()); - PostgreSqlOptionalStreamLifecycle.verifyOutboxStorageUpgradeWithExistingPollingV1(); - } - - private static void insertPreCanonicalRow( - String eventId, - String aggregateType, - String aggregateId, - long aggregateVersion, - int eventOrdinal, - String payload) { - insertIdentity(eventId, null, aggregateType, aggregateId, aggregateVersion, eventOrdinal); - jdbc.update( - "insert into outbox_event_log_v2(" - + "retention_bucket, event_id, aggregate_type, aggregate_id, aggregate_version, " - + "event_ordinal, event_type, event_schema, logical_destination, partition_key, " - + "publication_epoch, dispatch_authority, content_type, correlation_id, causation_id, " - + "occurred_at, payload, payload_digest, trace_parent, created_at" - + ") values (current_date, ?, ?, ?, ?, ?, 'LegacyEvent', 1, " - + "'legacy.destination', 'legacy-key', 1, 'LEGACY_SHADOW', 'application/json', " - + "'correlation-1', null, clock_timestamp(), ?, ?, null, clock_timestamp())", - eventId, - aggregateType, - aggregateId, - aggregateVersion, - eventOrdinal, - payload, - "0".repeat(64)); - } - - private static void insertIdentity( - String eventId, - String tenantScope, - String aggregateType, - String aggregateId, - long aggregateVersion, - int eventOrdinal) { - jdbc.update( - "insert into outbox_event_identity_v2(" - + "event_id, tenant_scope, aggregate_type, aggregate_id, aggregate_version, " - + "event_ordinal, retention_bucket, created_at" - + ") values (?, ?, ?, ?, ?, ?, current_date, clock_timestamp())", - eventId, - tenantScope, - aggregateType, - aggregateId, - aggregateVersion, - eventOrdinal); - } - - private static void cutoverToPollingV2() { - jdbc.queryForObject( - "select active_epoch from outbox_publication_control_v2 " - + "where scope_id = 'PRIMARY' for update", - Long.class); - jdbc.update( - "insert into outbox_publication_cutover_v2(" - + "scope_id, active_epoch, previous_epoch, transition_kind, active_authority, " - + "legacy_row_count, legacy_pending_count, legacy_digest, schema_manifest_id, " - + "external_manifest_id, activated_at" - + ") values (" - + "'PRIMARY', 2, 1, 'CUTOVER', 'POLLING_V2', 0, 0, ?, " - + "'jpa-outbox-storage-v2-schema-revision-2', null, clock_timestamp())", - "0".repeat(64)); - jdbc.update( - "update outbox_publication_control_v2 " - + "set active_epoch = 2, active_authority = 'POLLING_V2', " - + "revision = revision + 1, updated_at = clock_timestamp() " - + "where scope_id = 'PRIMARY' and active_epoch = 1 and revision = 0"); - } - - private static NewOutboxEventV2 event( - String eventId, long aggregateVersion, int ordinal, String payload) { - return CanonicalOutboxV2TestFixture.event(eventId, aggregateVersion, ordinal, payload); - } - - private static void migrate(String location, String historyTable) { - Flyway.configure() - .dataSource(postgres.dataSource()) - .locations(location) - .table(historyTable) - .baselineOnMigrate(false) - .outOfOrder(false) - .load() - .migrate(); - } - - private static void migrateIndependent( - String location, String historyTable, String baselineDescription) { - Flyway flyway = - Flyway.configure() - .dataSource(postgres.dataSource()) - .locations(location) - .table(historyTable) - .baselineVersion("0") - .baselineDescription(baselineDescription) - .baselineOnMigrate(false) - .outOfOrder(false) - .load(); - flyway.baseline(); - flyway.migrate(); - } - - private static void await(CountDownLatch latch) { - try { - latch.await(); - } catch (InterruptedException exception) { - Thread.currentThread().interrupt(); - throw new IllegalStateException("test synchronization interrupted", exception); - } - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlTransactionIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlTransactionIntegrationTest.java index 36c6434a..9261edf3 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlTransactionIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlTransactionIntegrationTest.java @@ -1,21 +1,12 @@ package dev.caskeleton.adapter.outbound.persistence.readiness; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; import dev.caskeleton.adapter.outbound.persistence.failure.PersistenceExceptionTranslator; import dev.caskeleton.adapter.outbound.persistence.failure.StandardSqlStateErrorMapping; -import dev.caskeleton.adapter.outbound.persistence.postgresql.PostgreSqlLocalTimeoutConfigurer; import dev.caskeleton.adapter.outbound.persistence.postgresql.PostgreSqlSqlStateErrorMapping; -import dev.caskeleton.adapter.outbound.persistence.transaction.JpaTransactionSettings; import dev.caskeleton.adapter.outbound.persistence.transaction.SpringTransactionPort; -import dev.caskeleton.application.outbound.CallBudget; -import dev.caskeleton.application.transaction.OperationId; -import dev.caskeleton.application.transaction.TransactionAdmissionException; -import dev.caskeleton.application.transaction.TransactionOutcome; -import dev.caskeleton.application.transaction.TransactionPolicyId; -import dev.caskeleton.application.transaction.TransactionRequest; -import dev.caskeleton.application.transaction.TransactionResult; import dev.caskeleton.shared.error.OperationalError; import dev.caskeleton.shared.error.PersistenceFailureException; import java.sql.Connection; @@ -23,21 +14,29 @@ import java.sql.SQLException; import java.sql.Statement; import java.time.Duration; import java.util.List; -import java.util.Optional; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DataSourceTransactionManager; +/** + * {@code SpringTransactionPort} against real PostgreSQL. + * + *

The port is plain Spring {@code TransactionTemplate} per mode. What a real database adds over + * the unit tests is the part a recording transaction manager cannot show: that a rollback really + * removes the row, that {@code inNew} really commits on its own connection while the caller's + * transaction rolls back, and that a commit the server never acknowledged surfaces as a failure and + * is not replayed. + */ class PostgreSqlTransactionIntegrationTest { private static PostgreSqlReadinessSupport postgres; @@ -47,13 +46,9 @@ class PostgreSqlTransactionIntegrationTest { PostgreSqlReadinessSupport.assertDockerAvailable(); postgres = PostgreSqlReadinessSupport.start(); postgres.execute("create table readiness_tx(id bigint primary key)"); - postgres.execute("create table readiness_serial(id bigint primary key)"); postgres.execute( "create table readiness_deadlock(id bigint primary key, value bigint not null)"); postgres.execute("insert into readiness_deadlock(id, value) values (1, 0), (2, 0)"); - postgres.execute( - "create table readiness_lock_timeout(id bigint primary key, value bigint not null)"); - postgres.execute("insert into readiness_lock_timeout(id, value) values (1, 0)"); postgres.execute("create table readiness_commit_uncertain(id bigint primary key)"); postgres.execute( "create function readiness_pause_commit() returns trigger language plpgsql as $$ " @@ -73,75 +68,51 @@ class PostgreSqlTransactionIntegrationTest { } @Test - void appliesTransactionLocalTimeoutsBeforeWorkAndResetsThemAfterCommit() { + void inWriteActionFailureRollsBackTheWrite() { + // given JdbcTemplate jdbc = new JdbcTemplate(postgres.dataSource()); - SpringTransactionPort port = transactionPort(jdbc); + SpringTransactionPort port = transactionPort(); - TransactionResult result = - port.inTransaction( - request("tx-local-timeout"), - () -> { - String statementTimeout = - jdbc.queryForObject("select current_setting('statement_timeout')", String.class); - String lockTimeout = - jdbc.queryForObject("select current_setting('lock_timeout')", String.class); - assertThat(statementTimeout).isNotEqualTo("0"); - assertThat(lockTimeout).isNotEqualTo("0"); - jdbc.update("insert into readiness_tx(id) values (?)", 1L); - return "committed"; - }); + // when + Throwable thrown = + catchThrowable( + () -> + port.inWrite( + () -> { + jdbc.update("insert into readiness_tx(id) values (?)", 2L); + throw new IllegalStateException("rollback"); + })); - assertThat(result.outcome()).isEqualTo(TransactionOutcome.COMMITTED); - assertThat(jdbc.queryForObject("select current_setting('statement_timeout')", String.class)) - .isEqualTo("0"); - } - - @Test - void actionFailureProducesAConfirmedRollback() { - JdbcTemplate jdbc = new JdbcTemplate(postgres.dataSource()); - SpringTransactionPort port = transactionPort(jdbc); - - TransactionResult result = - port.inTransaction( - request("tx-rollback"), - () -> { - jdbc.update("insert into readiness_tx(id) values (?)", 2L); - throw new IllegalStateException("rollback"); - }); - - assertThat(result.outcome()).isEqualTo(TransactionOutcome.DETERMINATE_ROLLBACK); + // then + assertThat(thrown).isInstanceOf(IllegalStateException.class).hasMessage("rollback"); assertThat( jdbc.queryForObject("select count(*) from readiness_tx where id = ?", Long.class, 2L)) .isZero(); } @Test - @Timeout(15) - void serializableConflictIsRetriedOnlyByTheReplaySafePolicy() throws Exception { + void inNewCommitsIndependentlyOfTheCallersRollback() { + // given JdbcTemplate jdbc = new JdbcTemplate(postgres.dataSource()); - SpringTransactionPort port = transactionPort(jdbc); - CyclicBarrier firstAttemptBarrier = new CyclicBarrier(2); - AtomicInteger actionCalls = new AtomicInteger(); - try (ExecutorService executor = Executors.newFixedThreadPool(2)) { - Future> first = - executor.submit( - () -> - serializableInsert( - port, jdbc, 101L, "serial-first", actionCalls, firstAttemptBarrier)); - Future> second = - executor.submit( - () -> - serializableInsert( - port, jdbc, 102L, "serial-second", actionCalls, firstAttemptBarrier)); + SpringTransactionPort port = transactionPort(); - assertThat(first.get(10, TimeUnit.SECONDS).outcome()).isEqualTo(TransactionOutcome.COMMITTED); - assertThat(second.get(10, TimeUnit.SECONDS).outcome()) - .isEqualTo(TransactionOutcome.COMMITTED); - } + // when + Throwable thrown = + catchThrowable( + () -> + port.inWrite( + () -> { + jdbc.update("insert into readiness_tx(id) values (?)", 10L); + port.inNew(() -> jdbc.update("insert into readiness_tx(id) values (?)", 11L)); + throw new IllegalStateException("caller rolls back"); + })); - assertThat(actionCalls).hasValue(3); - assertThat(jdbc.queryForObject("select count(*) from readiness_serial", Long.class)) - .isEqualTo(2L); + // then + assertThat(thrown).hasMessage("caller rolls back"); + assertThat( + jdbc.queryForList( + "select id from readiness_tx where id in (10, 11) order by id", Long.class)) + .containsExactly(11L); } @Test @@ -169,89 +140,13 @@ class PostgreSqlTransactionIntegrationTest { } } + /** Also runs in the {@code jpa-failure} lane, the {@code completion-unknown-no-retry} gate. */ @Test + @Tag("jpa-failure") @Timeout(15) - void lockAndStatementTimeoutsRollbackWithinTheConfiguredBounds() throws Exception { + void connectionLossDuringCommitSurfacesAsAFailureAndIsNeverRetried() throws Exception { JdbcTemplate jdbc = new JdbcTemplate(postgres.dataSource()); - JpaTransactionSettings settings = - new JpaTransactionSettings( - Duration.ofSeconds(3), - Duration.ofMillis(300), - Duration.ofMillis(100), - Duration.ofMillis(100), - Duration.ofMillis(600), - Duration.ofMillis(200), - Duration.ofSeconds(1), - Duration.ofMillis(100), - Duration.ofMillis(50), - Duration.ofMillis(10), - Duration.ofMillis(10), - 1); - SpringTransactionPort port = transactionPort(postgres, jdbc, settings); - - try (Connection blocker = postgres.connection(); - Statement lock = blocker.createStatement()) { - blocker.setAutoCommit(false); - lock.execute("update readiness_lock_timeout set value = value + 1 where id = 1"); - long started = System.nanoTime(); - TransactionResult lockResult = - port.inTransaction( - request("tx-lock-timeout"), - () -> - jdbc.update("update readiness_lock_timeout set value = value + 1 where id = 1")); - assertThat(lockResult.outcome()).isEqualTo(TransactionOutcome.DETERMINATE_ROLLBACK); - assertThat(sqlState(failure(lockResult))).isEqualTo("55P03"); - assertThat(Duration.ofNanos(System.nanoTime() - started)) - .isBetween(Duration.ofMillis(100), Duration.ofSeconds(2)); - blocker.rollback(); - } - - long started = System.nanoTime(); - TransactionResult statementResult = - port.inTransaction( - request("tx-statement-timeout"), - () -> jdbc.queryForObject("select pg_sleep(2) is null", Boolean.class)); - assertThat(statementResult.outcome()).isEqualTo(TransactionOutcome.DETERMINATE_ROLLBACK); - assertThat(sqlState(failure(statementResult))).isEqualTo("57014"); - assertThat(Duration.ofNanos(System.nanoTime() - started)) - .isBetween(Duration.ofMillis(300), Duration.ofSeconds(2)); - } - - @Test - @Timeout(10) - void poolExhaustionRejectsBeforeApplicationWorkStarts() throws Exception { - try (PostgreSqlReadinessSupport constrained = PostgreSqlReadinessSupport.start(1, 300); - Connection held = constrained.connection()) { - JdbcTemplate jdbc = new JdbcTemplate(constrained.dataSource()); - SpringTransactionPort port = - transactionPort( - constrained, - jdbc, - new JpaTransactionSettings(null, null, null, null, null, null, null, null, null)); - AtomicBoolean applicationWorkStarted = new AtomicBoolean(); - long started = System.nanoTime(); - - assertThatThrownBy( - () -> - port.inTransaction( - request("tx-pool-exhaustion"), - () -> { - applicationWorkStarted.set(true); - return "must-not-run"; - })) - .isInstanceOf(TransactionAdmissionException.class) - .hasMessageContaining("before application work started"); - assertThat(applicationWorkStarted).isFalse(); - assertThat(Duration.ofNanos(System.nanoTime() - started)) - .isBetween(Duration.ofMillis(250), Duration.ofSeconds(2)); - } - } - - @Test - @Timeout(15) - void connectionLossDuringCommitIsIndeterminateAndNeverBlindlyRetried() throws Exception { - JdbcTemplate jdbc = new JdbcTemplate(postgres.dataSource()); - SpringTransactionPort port = transactionPort(jdbc); + SpringTransactionPort port = transactionPort(); AtomicInteger backendPid = new AtomicInteger(); AtomicInteger actionCalls = new AtomicInteger(); try (ExecutorService killer = Executors.newSingleThreadExecutor()) { @@ -281,70 +176,29 @@ class PostgreSqlTransactionIntegrationTest { return false; }); - TransactionResult result = - port.inTransaction( - request(TransactionPolicyId.COMMAND_SERIALIZABLE_REPLAY_SAFE, "tx-commit-uncertain"), - () -> { - actionCalls.incrementAndGet(); - backendPid.set(jdbc.queryForObject("select pg_backend_pid()", Integer.class)); - jdbc.update("insert into readiness_commit_uncertain(id) values (?)", 1L); - return 1L; - }); + Throwable thrown = + catchThrowable( + () -> + port.inWrite( + () -> { + actionCalls.incrementAndGet(); + backendPid.set( + jdbc.queryForObject("select pg_backend_pid()", Integer.class)); + jdbc.update("insert into readiness_commit_uncertain(id) values (?)", 1L); + return 1L; + })); assertThat(terminated.get(5, TimeUnit.SECONDS)).isTrue(); - assertThat(result.outcome()).isEqualTo(TransactionOutcome.INDETERMINATE); + assertThat(thrown).isInstanceOf(RuntimeException.class); assertThat(actionCalls).hasValue(1); assertThat(jdbc.queryForObject("select count(*) from readiness_commit_uncertain", Long.class)) .isZero(); } } - private static SpringTransactionPort transactionPort(JdbcTemplate jdbc) { - return transactionPort( - postgres, - jdbc, - new JpaTransactionSettings(null, null, null, null, null, null, null, null, null)); - } - - private static SpringTransactionPort transactionPort( - PostgreSqlReadinessSupport database, JdbcTemplate jdbc, JpaTransactionSettings settings) { + private static SpringTransactionPort transactionPort() { return new SpringTransactionPort( - new DataSourceTransactionManager(database.dataSource()), - settings, - new PostgreSqlLocalTimeoutConfigurer(jdbc), - database.dataSource().getConnectionTimeout(), - translator()); - } - - private static TransactionRequest request(String operationId) { - return request(TransactionPolicyId.COMMAND_DEFAULT, operationId); - } - - private static TransactionRequest request(TransactionPolicyId policyId, String operationId) { - return new TransactionRequest( - policyId, - CallBudget.fromNow(Duration.ofSeconds(10)), - Optional.empty(), - Optional.of(new OperationId(operationId))); - } - - private static TransactionResult serializableInsert( - SpringTransactionPort port, - JdbcTemplate jdbc, - long id, - String operationId, - AtomicInteger actionCalls, - CyclicBarrier firstAttemptBarrier) { - return port.inTransaction( - request(TransactionPolicyId.COMMAND_SERIALIZABLE_REPLAY_SAFE, operationId), - () -> { - jdbc.queryForObject("select count(*) from readiness_serial", Long.class); - if (actionCalls.incrementAndGet() <= 2) { - await(firstAttemptBarrier); - } - jdbc.update("insert into readiness_serial(id) values (?)", id); - return id; - }); + new DataSourceTransactionManager(postgres.dataSource()), translator()); } private static SQLException deadlockParticipant( @@ -367,28 +221,6 @@ class PostgreSqlTransactionIntegrationTest { } } - private static void await(CyclicBarrier barrier) { - try { - barrier.await(); - } catch (Exception exception) { - throw new IllegalStateException("transaction concurrency barrier failed", exception); - } - } - - private static RuntimeException failure(TransactionResult result) { - assertThat(result).isInstanceOf(TransactionResult.DeterminateRollback.class); - return ((TransactionResult.DeterminateRollback) result).failure(); - } - - private static String sqlState(Throwable failure) { - for (Throwable current = failure; current != null; current = current.getCause()) { - if (current instanceof SQLException sqlException) { - return sqlException.getSQLState(); - } - } - return null; - } - private static PersistenceExceptionTranslator translator() { return new PersistenceExceptionTranslator( List.of(new StandardSqlStateErrorMapping(), new PostgreSqlSqlStateErrorMapping())); diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/CandidateAdapterCompositionTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/CandidateAdapterCompositionTest.java index b0bab31a..ed6e06b8 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/CandidateAdapterCompositionTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/CandidateAdapterCompositionTest.java @@ -2,53 +2,23 @@ package dev.caskeleton.adapter.outbound.persistence; import static org.assertj.core.api.Assertions.assertThat; -import dev.caskeleton.adapter.outbound.persistence.postgresql.inbox.PostgreSqlSameStoreInboxAdapter; -import dev.caskeleton.adapter.outbound.persistence.postgresql.outbox.PostgreSqlImmutableOutboxAppendAdapter; -import dev.caskeleton.adapter.outbound.persistence.postgresql.outbox.PostgreSqlPollingDeliveryAdapter; -import java.lang.annotation.Annotation; -import java.util.List; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import org.springframework.stereotype.Component; import org.springframework.stereotype.Repository; /** * A candidate implementation nobody selected must not be composed. * - *

Both composition roots component-scan {@code dev.caskeleton.adapter}, so a {@code @Repository} - * on a PostgreSQL-only adapter became a bean in every deployment — including one running H2, which - * has no migration tree at all, and one that never applied the optional stream those adapters read. - * The bean existed and its tables did not: the failure surfaced as vendor-specific SQL against a - * missing relation, or as a boot failure under {@code ddl-auto=validate}. - * - *

{@code PostgreSqlOwnerSafeIdempotencyStore} already had its stereotype removed for exactly - * this reason, with the reasoning written on the class. These three did not. + *

{@code CaSkeletonApplication} excludes {@code dev.caskeleton.adapter.outbound.persistence..*} + * from its component scan, but {@code SamplePortfolioApplication} scans all of {@code + * dev.caskeleton}. So a {@code @Repository} on a PostgreSQL-only adapter becomes a bean there — + * including under H2, which has no migration tree at all, and in a database that never applied the + * optional stream the adapter reads. The bean exists and its tables do not: the failure surfaces as + * vendor-specific SQL against a missing relation, or as a boot failure under {@code + * ddl-auto=validate}. */ class CandidateAdapterCompositionTest { - private static final List> CANDIDATE_ADAPTERS = - List.of( - PostgreSqlSameStoreInboxAdapter.class, - PostgreSqlImmutableOutboxAppendAdapter.class, - PostgreSqlPollingDeliveryAdapter.class); - - private static final List> COMPOSING_STEREOTYPES = - List.of(Repository.class, Component.class, org.springframework.stereotype.Service.class); - - @Test - @DisplayName("no PostgreSQL candidate adapter is composed by a component scan") - void noCandidateAdapterIsComposedByAComponentScan() { - for (Class adapter : CANDIDATE_ADAPTERS) { - for (Class stereotype : COMPOSING_STEREOTYPES) { - assertThat(adapter.getAnnotation(stereotype)) - .as( - "%s carries @%s, so every deployment builds it — H2 included", - adapter.getSimpleName(), stereotype.getSimpleName()) - .isNull(); - } - } - } - @Test @DisplayName("the idempotency store that already fixed this stays fixed") void theIdempotencyStoreThatAlreadyFixedThisStaysFixed() { diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/JpaAdopterApiSurfaceTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/JpaAdopterApiSurfaceTest.java new file mode 100644 index 00000000..b7312de5 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/JpaAdopterApiSurfaceTest.java @@ -0,0 +1,92 @@ +package dev.caskeleton.adapter.outbound.persistence; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.IOException; +import java.nio.file.FileVisitResult; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.SimpleFileVisitor; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.junit.jupiter.api.Test; + +/** + * Production code outside this leaf imports only the persistence types the adopter baseline lists. + * + *

A language-level public type is not a compatibility promise; the baseline is. The leaves that + * own JPA persistence implementations (this one and persistence-fileserver) are the implementation + * rather than adopters of it. The build declares every production source and the baseline as inputs + * of {@code test}. + */ +class JpaAdopterApiSurfaceTest { + + private static final Path SOURCE_ROOT = Path.of("../../..").toAbsolutePath().normalize(); + private static final Path BASELINE = + SOURCE_ROOT.resolve("../docs/architecture/jpa-adopter-api-surface.txt"); + private static final Pattern IMPORT = + Pattern.compile( + "^\\s*import\\s+(dev\\.caskeleton\\.adapter\\.outbound\\.persistence\\.[A-Za-z0-9_$.]+)\\s*;\\s*$"); + private static final List OWNERS = + List.of("adapter/outbound/persistence-jpa/", "adapter/outbound/persistence-fileserver/"); + + @Test + void productionCodeElsewhereImportsOnlyTheReviewedAdopterSurface() throws IOException { + // given + Set allowed = new TreeSet<>(); + for (String line : Files.readAllLines(BASELINE)) { + if (!line.isBlank() && !line.startsWith("#")) { + allowed.add(line.trim()); + } + } + + // when + Set unreviewed = new TreeSet<>(); + for (Path source : adopterSources()) { + for (String line : Files.readAllLines(source)) { + Matcher matcher = IMPORT.matcher(line); + if (matcher.matches() && !allowed.contains(matcher.group(1))) { + unreviewed.add(SOURCE_ROOT.relativize(source) + ": " + matcher.group(1)); + } + } + } + + // then + assertThat(unreviewed).isEmpty(); + } + + private static List adopterSources() throws IOException { + List sources = new ArrayList<>(); + Files.walkFileTree( + SOURCE_ROOT, + new SimpleFileVisitor<>() { + @Override + public FileVisitResult preVisitDirectory(Path directory, BasicFileAttributes attributes) { + String name = directory.getFileName() == null ? "" : directory.getFileName().toString(); + String path = SOURCE_ROOT.relativize(directory).toString().replace('\\', '/') + "/"; + boolean skipped = + name.equals("build") + || name.startsWith(".") + || OWNERS.stream().anyMatch(path::startsWith); + return skipped && !directory.equals(SOURCE_ROOT) + ? FileVisitResult.SKIP_SUBTREE + : FileVisitResult.CONTINUE; + } + + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) { + String path = file.toString().replace('\\', '/'); + if (path.endsWith(".java") && path.contains("/src/main/java/")) { + sources.add(file); + } + return FileVisitResult.CONTINUE; + } + }); + return sources; + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/JpaModuleBoundaryTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/JpaModuleBoundaryTest.java index 36b06722..5cb1cc20 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/JpaModuleBoundaryTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/JpaModuleBoundaryTest.java @@ -126,6 +126,9 @@ class JpaModuleBoundaryTest { Map.entry("querydsl", Set.of("api", "springdata")), Map.entry("security", Set.of("api")), Map.entry("springdata", Set.of("api", "hibernate")), + // The startup policy relational persistence runs under — migration sequencing and the + // OSIV/DDL/pool/TLS/vendor guards — which the composition root used to own. + Map.entry("startup", Set.of("api", "config", "hibernate", "migration", "security")), Map.entry("transaction", Set.of("api", "failure"))); /** diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/api/transaction/TransactionProfileTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/api/transaction/TransactionProfileTest.java deleted file mode 100644 index 645d6539..00000000 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/api/transaction/TransactionProfileTest.java +++ /dev/null @@ -1,90 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.api.transaction; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.outbound.persistence.api.error.FailureCategory; -import java.time.Duration; -import java.util.Set; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** Plan Task 5 — transaction and retry profiles refuse unsafe shapes (design §9.2, §19.3). */ -class TransactionProfileTest { - - @Test - @DisplayName("a write profile requires a positive, finite timeout") - void writeProfileRequiresFiniteTimeout() { - assertThatThrownBy( - () -> - new TransactionProfile( - "write", - PropagationMode.REQUIRED, - IsolationLevel.READ_COMMITTED, - Duration.ZERO, - false, - RetryProfile.none())) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("positive timeout"); - } - - @Test - @DisplayName("a read profile may leave the timeout to the connection default") - void readProfileMayOmitTimeout() { - var profile = TransactionProfile.read("order.read", Duration.ZERO); - - assertThat(profile.readOnly()).isTrue(); - assertThat(profile.hasTimeout()).isFalse(); - } - - @Test - @DisplayName("a retry profile can never opt into completion unknown") - void retryProfileRejectsCompletionUnknown() { - assertThatThrownBy( - () -> - new RetryProfile( - "unsafe", - 3, - Duration.ofMillis(10), - Duration.ofMillis(100), - 2.0d, - JitterMode.FULL, - Set.of(FailureCategory.COMPLETION_UNKNOWN))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("never a retryable failure category"); - } - - @Test - @DisplayName("a retry profile rejects a category that is not retry eligible") - void retryProfileRejectsIneligibleCategory() { - assertThatThrownBy( - () -> - new RetryProfile( - "unsafe", - 3, - Duration.ofMillis(10), - Duration.ofMillis(100), - 2.0d, - JitterMode.FULL, - Set.of(FailureCategory.UNIQUE_CONSTRAINT))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("not retry eligible"); - } - - @Test - @DisplayName("maxAttempts must be at least one") - void retryProfileRequiresAtLeastOneAttempt() { - assertThatThrownBy( - () -> - new RetryProfile( - "none", 0, Duration.ZERO, Duration.ZERO, 1.0d, JitterMode.NONE, Set.of())) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("the none profile permits exactly one attempt") - void noneProfileIsSingleAttempt() { - assertThat(RetryProfile.none().enabled()).isFalse(); - assertThat(RetryProfile.none().maxAttempts()).isEqualTo(1); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PersistenceJpaAutoConfigurationTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PersistenceJpaAutoConfigurationTest.java index 2346d67a..c0ee0b79 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PersistenceJpaAutoConfigurationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PersistenceJpaAutoConfigurationTest.java @@ -24,7 +24,7 @@ import org.springframework.core.annotation.AnnotatedElementUtils; class PersistenceJpaAutoConfigurationTest { @Test - void leafRootIsARealBootAutoConfigurationUnderTheMasterSwitch() { + void leafRootIsARealBootAutoConfigurationUnderTheModuleSwitch() { assertThat( AnnotatedElementUtils.hasAnnotation( PersistenceJpaAutoConfiguration.class, AutoConfiguration.class)) @@ -36,6 +36,9 @@ class PersistenceJpaAutoConfigurationTest { assertThat(condition.prefix()).isEqualTo("ca-skeleton.persistence-jpa"); assertThat(condition.name()).containsExactly("enabled"); assertThat(condition.havingValue()).isEqualTo("true"); + assertThat(condition.matchIfMissing()) + .as("on while the module is present; the switch is only the escape hatch") + .isTrue(); } @Test @@ -51,6 +54,7 @@ class PersistenceJpaAutoConfigurationTest { void packagePrivateLeafRootLoadsThroughBootAutoConfigurationWhenDisabled() { new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(PersistenceJpaAutoConfiguration.class)) + .withPropertyValues("ca-skeleton.persistence-jpa.enabled=false") .run(context -> assertThat(context).hasNotFailed()); } @@ -86,7 +90,9 @@ class PersistenceJpaAutoConfigurationTest { assertThat(Files.isRegularFile(resource)).as("%s", resource).isTrue(); assertThat(Files.readString(resource, StandardCharsets.UTF_8)) .contains(PersistenceJpaAutoConfiguration.class.getName()) - .contains(PersistenceJpaRuntimeConfig.class.getName()); + .contains(PersistenceJpaRuntimeConfig.class.getName()) + .contains( + "dev.caskeleton.adapter.outbound.persistence.startup.JpaStartupAutoConfiguration"); } private static Path leafRoot() { diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PersistenceJpaCapabilityAssemblyTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PersistenceJpaCapabilityAssemblyTest.java new file mode 100644 index 00000000..76bfecc8 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PersistenceJpaCapabilityAssemblyTest.java @@ -0,0 +1,216 @@ +package dev.caskeleton.adapter.outbound.persistence.autoconfigure; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.application.idempotency.IdempotencyStorePort; +import dev.caskeleton.application.lock.DistributedLockPort; +import dev.caskeleton.application.outbox.OutboxStorePort; +import dev.caskeleton.application.transaction.TransactionPort; +import dev.caskeleton.shared.concurrency.DomainContextPropagator; +import dev.caskeleton.shared.concurrency.DomainContextPropagatorFactory; +import dev.caskeleton.shared.concurrency.DomainContextStrategy; +import jakarta.persistence.EntityManagerFactory; +import java.io.IOException; +import java.time.Clock; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.UUID; +import javax.sql.DataSource; +import org.flywaydb.core.Flyway; +import org.junit.jupiter.api.Test; +import org.springframework.boot.SpringBootConfiguration; +import org.springframework.boot.WebApplicationType; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.context.TypeExcludeFilter; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.core.type.classreading.MetadataReader; +import org.springframework.core.type.classreading.MetadataReaderFactory; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.transaction.PlatformTransactionManager; + +/** + * The module on the classpath is the whole decision: a plain Boot application with nothing but the + * core beans an application provides gets relational persistence, its switches and its startup + * policy from this module's own auto-configuration and shipped defaults. + * + *

These cases used to be app-bootstrap system tests against the shipped composition. The shipped + * composition no longer contains this module, so the proof lives with the module. H2 keeps it free + * of a container; the PostgreSQL behaviour is the {@code postgresqlIntegrationTest} lane's. + */ +class PersistenceJpaCapabilityAssemblyTest { + + @Test + void theModuleAloneAssemblesTransactionsAndTheSingleInstanceLock() { + try (ConfigurableApplicationContext context = start()) { + assertThat(context.getBeansOfType(TransactionPort.class)).hasSize(1); + assertThat(context.getBean(DistributedLockPort.class)) + .isSameAs(context.getBean("inProcessDistributedLock")); + assertThat(context.containsBean("migrationStartupRunner")).isTrue(); + assertThat(context.getEnvironment().getProperty("ca-skeleton.persistence-jpa.enabled")) + .as("the switch the module ships, on while it is present") + .isEqualTo("true"); + assertThat( + context + .getEnvironment() + .getProperty("management.endpoint.health.group.readiness.include")) + .as("the database joins readiness with the module that creates it") + .contains("db"); + } + } + + @Test + void multiInstanceLockIsTheMeteredJdbcProvider() { + try (ConfigurableApplicationContext context = + start("--ca-skeleton.runtime.multi-instance-enabled=true")) { + assertThat(context.containsBean("jdbcDistributedLock")).isTrue(); + assertThat(context.getBean("distributedLockProvider").getClass().getSimpleName()) + .as("every caller gets the JDBC provider behind the metrics decorator") + .isEqualTo("MeteredDistributedLockPort"); + assertThat(context.getBean(DistributedLockPort.class)) + .isSameAs(context.getBean("distributedLockProvider")); + } + } + + @Test + void theOutboxSwitchBringsTheStoreTheApplicationRelaysFrom() { + try (ConfigurableApplicationContext context = start("--ca-skeleton.outbox.enabled=true")) { + assertThat(context.getBeansOfType(OutboxStorePort.class)).hasSize(1); + } + try (ConfigurableApplicationContext context = start()) { + assertThat(context.getBeansOfType(OutboxStorePort.class)) + .as("the shipped default keeps the outbox off") + .isEmpty(); + } + } + + /** + * Wiring only: {@code migration-on-startup=false}, so the PostgreSQL schema stream (which refuses + * H2) is not built. The fresh-PostgreSQL replay is the integration lane's. + */ + @Test + void postgresqlIdempotencyStoreArrivesWithTheModule() { + try (ConfigurableApplicationContext context = + start("--ca-skeleton.capabilities.idempotency.provider=postgresql")) { + assertThat(context.getBeansOfType(IdempotencyStorePort.class)).hasSize(1); + } + } + + /** + * No datasource setting at all: the shipped defaults leave the URL to {@code APP_DATASOURCE_URL}, + * so any relational auto-configuration still running would fail to bind it or to connect. + */ + @Test + void theSwitchTurnsTheModuleAndBootsRelationalStackOffWithoutADatabase() { + // when + try (ConfigurableApplicationContext context = + boot(List.of("--ca-skeleton.persistence-jpa.enabled=false"))) { + + // then + assertThat(relationalOrModuleBeans(context)).isEmpty(); + } + } + + private static ConfigurableApplicationContext start(String... overrides) { + List arguments = + new ArrayList<>( + List.of( + "--ca-skeleton.persistence.vendor=h2", + "--spring.datasource.url=jdbc:h2:mem:" + + UUID.randomUUID() + + ";MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1", + "--spring.datasource.username=sa", + "--spring.datasource.password=", + "--spring.datasource.driver-class-name=org.h2.Driver", + "--spring.flyway.enabled=false", + "--spring.jpa.hibernate.ddl-auto=create-drop", + "--ca-skeleton.runtime.migration-on-startup=false")); + arguments.addAll(List.of(overrides)); + return boot(arguments); + } + + private static ConfigurableApplicationContext boot(List overrides) { + List arguments = + new ArrayList<>( + List.of( + "--spring.main.banner-mode=off", + // create-drop is a local convenience; the module's own guard refuses it elsewhere. + "--spring.profiles.active=test", + "--spring.config.name=persistence-jpa-assembly-test-has-no-config-file", + "--management.endpoint.health.group.readiness.include=readinessState")); + arguments.addAll(overrides); + return new SpringApplicationBuilder(Application.class) + .web(WebApplicationType.NONE) + // The module scans its own packages, and on this test classpath those packages also hold + // other tests' fixture configurations. An application jar holds none. + .initializers( + context -> + context + .getBeanFactory() + .registerSingleton("testSourceExcludeFilter", new TestSourceExcludeFilter())) + .run(arguments.toArray(String[]::new)); + } + + /** + * Every bean that is part of a relational stack or that this module contributed, by name. The + * test's own configuration is not the module's. + */ + private static List relationalOrModuleBeans(ConfigurableApplicationContext context) { + List> relational = + List.of( + DataSource.class, + EntityManagerFactory.class, + Flyway.class, + JdbcTemplate.class, + PlatformTransactionManager.class, + TransactionPort.class); + return Arrays.stream(context.getBeanDefinitionNames()) + .filter( + name -> { + Class type = context.getType(name); + return type != null + && (relational.stream().anyMatch(kind -> kind.isAssignableFrom(type)) + || (type.getName().startsWith("dev.caskeleton.adapter.outbound.persistence.") + && !type.getName() + .startsWith(PersistenceJpaCapabilityAssemblyTest.class.getName()))); + }) + .toList(); + } + + /** An application that provides the core beans every capability may rely on, and nothing else. */ + @SpringBootConfiguration + @EnableAutoConfiguration + static class Application { + + @Bean + Clock clock() { + return Clock.systemUTC(); + } + + @Bean + DomainContextPropagator domainContextPropagator() { + return DomainContextPropagatorFactory.create(DomainContextStrategy.THREAD_LOCAL); + } + } + + private static final class TestSourceExcludeFilter extends TypeExcludeFilter { + + @Override + public boolean match(MetadataReader metadataReader, MetadataReaderFactory factory) + throws IOException { + return metadataReader.getResource().getURL().getPath().contains("/build/classes/java/test/"); + } + + @Override + public boolean equals(Object other) { + return other instanceof TestSourceExcludeFilter; + } + + @Override + public int hashCode() { + return TestSourceExcludeFilter.class.hashCode(); + } + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PersistenceJpaRuntimeConfigTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PersistenceJpaRuntimeConfigTest.java index e1e390bd..e8d18a24 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PersistenceJpaRuntimeConfigTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PersistenceJpaRuntimeConfigTest.java @@ -1,50 +1,24 @@ package dev.caskeleton.adapter.outbound.persistence.autoconfigure; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import dev.caskeleton.adapter.outbound.persistence.api.PersistenceOperationName; -import dev.caskeleton.adapter.outbound.persistence.api.error.FailureCategory; -import dev.caskeleton.adapter.outbound.persistence.api.error.JpaPersistenceException; -import dev.caskeleton.adapter.outbound.persistence.api.error.VendorFailureTranslator; -import dev.caskeleton.adapter.outbound.persistence.api.transaction.TransactionProfile; import dev.caskeleton.adapter.outbound.persistence.hibernate.HibernateProviderPolicy; -import dev.caskeleton.adapter.outbound.persistence.postgresql.constraint.PostgreSqlConstraintCatalog; -import dev.caskeleton.adapter.outbound.persistence.postgresql.error.PostgreSqlExceptionTranslator; import dev.caskeleton.adapter.outbound.persistence.security.PostgreSqlRuntimeRoleVerifier; -import dev.caskeleton.adapter.outbound.persistence.transaction.FullTransactionRetryCoordinator; -import dev.caskeleton.adapter.outbound.persistence.transaction.SpringJpaTransactionExecutor; -import java.sql.SQLException; -import java.time.Clock; -import java.time.Duration; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.dao.TransientDataAccessResourceException; -import org.springframework.transaction.PlatformTransactionManager; -import org.springframework.transaction.support.AbstractPlatformTransactionManager; -import org.springframework.transaction.support.DefaultTransactionStatus; class PersistenceJpaRuntimeConfigTest { - private static final PersistenceOperationName OPERATION = - new PersistenceOperationName("order.write"); - private static final TransactionProfile PROFILE = - TransactionProfile.write("order.write", Duration.ofSeconds(3)); - private final ApplicationContextRunner runner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(PersistenceJpaRuntimeConfig.class)) - .withBean(Clock.class, Clock::systemUTC) .withPropertyValues("ca-skeleton.persistence-jpa.enabled=true"); @Test - void masterSwitchOffContributesNoRuntimeBeans() { + void moduleSwitchOffContributesNoRuntimeBeans() { new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(PersistenceJpaRuntimeConfig.class)) - .withBean(Clock.class, Clock::systemUTC) .withPropertyValues("ca-skeleton.persistence-jpa.enabled=false") .run( context -> @@ -53,17 +27,6 @@ class PersistenceJpaRuntimeConfigTest { .doesNotHaveBean(PostgreSqlRuntimeRoleVerifier.class)); } - @Test - void addonsSwitchOffContributesNoRuntimeBeansEvenWhenJpaIsOn() { - runner - .withPropertyValues("app.jpa-platform.addons-enabled=false") - .run( - context -> - assertThat(context) - .doesNotHaveBean(HibernateProviderPolicy.class) - .doesNotHaveBean(PostgreSqlRuntimeRoleVerifier.class)); - } - @Test void providerRuntimeBeansAreLeafOwned() { runner.run( @@ -73,73 +36,6 @@ class PersistenceJpaRuntimeConfigTest { .hasSingleBean(PostgreSqlRuntimeRoleVerifier.class)); } - @Test - void transactionManagerBringsExecutorAndRetryCoordinator() { - runner - .withUserConfiguration(TransactionManagerConfiguration.class) - .run( - context -> - assertThat(context) - .hasSingleBean(SpringJpaTransactionExecutor.class) - .hasSingleBean(FullTransactionRetryCoordinator.class)); - } - - @Test - void withoutTransactionManagerRetryBacksOff() { - runner.run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context).doesNotHaveBean(FullTransactionRetryCoordinator.class); - }); - } - - @Test - void composedVendorTranslatorClassifiesAttemptFailure() { - runner - .withUserConfiguration(TransactionManagerConfiguration.class) - .withBean( - VendorFailureTranslator.class, - () -> PostgreSqlExceptionTranslator.with(PostgreSqlConstraintCatalog.empty())) - .run( - context -> { - SpringJpaTransactionExecutor executor = - context.getBean(SpringJpaTransactionExecutor.class); - - assertThatThrownBy( - () -> - executor.execute( - OPERATION, - PROFILE, - PersistenceJpaRuntimeConfigTest::throwSerializationConflict)) - .isInstanceOfSatisfying( - JpaPersistenceException.class, - classified -> { - assertThat(classified.category()) - .isEqualTo(FailureCategory.SERIALIZATION_FAILURE); - assertThat(classified.retryable()).isTrue(); - }); - }); - } - - @Test - void noVendorTranslatorLeavesFailureUnclassified() { - runner - .withUserConfiguration(TransactionManagerConfiguration.class) - .run( - context -> { - SpringJpaTransactionExecutor executor = - context.getBean(SpringJpaTransactionExecutor.class); - - assertThatThrownBy( - () -> - executor.execute( - OPERATION, - PROFILE, - PersistenceJpaRuntimeConfigTest::throwSerializationConflict)) - .isInstanceOf(TransientDataAccessResourceException.class); - }); - } - @Test void applicationOverrideWins() { runner @@ -149,33 +45,4 @@ class PersistenceJpaRuntimeConfigTest { assertThat(context.getBean(HibernateProviderPolicy.class).runtimeVersion()) .isEqualTo("7.0.0-custom")); } - - private static Object throwSerializationConflict() { - throw new TransientDataAccessResourceException( - "could not serialize access", new SQLException("could not serialize access", "40001")); - } - - @Configuration(proxyBeanMethods = false) - static class TransactionManagerConfiguration { - - @Bean - PlatformTransactionManager transactionManager() { - return new AbstractPlatformTransactionManager() { - @Override - protected Object doGetTransaction() { - return new Object(); - } - - @Override - protected void doBegin( - Object transaction, org.springframework.transaction.TransactionDefinition definition) {} - - @Override - protected void doCommit(DefaultTransactionStatus status) {} - - @Override - protected void doRollback(DefaultTransactionStatus status) {} - }; - } - } } diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PostgreSqlIdempotencyStoreConfigTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PostgreSqlIdempotencyStoreConfigTest.java index 51fe9613..84ddced1 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PostgreSqlIdempotencyStoreConfigTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PostgreSqlIdempotencyStoreConfigTest.java @@ -2,35 +2,43 @@ package dev.caskeleton.adapter.outbound.persistence.autoconfigure; import static org.assertj.core.api.Assertions.assertThat; +import dev.caskeleton.adapter.outbound.persistence.postgresql.idempotency.IdempotencySchemaStream; import dev.caskeleton.adapter.outbound.persistence.postgresql.idempotency.PostgreSqlOwnerSafeIdempotencyStore; -import dev.caskeleton.application.idempotency.v2.IdempotencyStorePortV2; +import dev.caskeleton.application.idempotency.IdempotencyStorePort; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.jdbc.core.JdbcOperations; class PostgreSqlIdempotencyStoreConfigTest { + // In-app migration off: the stream needs a live PostgreSQL, which the integration lane covers. private final ApplicationContextRunner runner = new ApplicationContextRunner() .withUserConfiguration(PostgreSqlIdempotencyStoreConfig.class) - .withBean(JdbcOperations.class, () -> org.mockito.Mockito.mock(JdbcOperations.class)); + .withBean(JdbcOperations.class, () -> org.mockito.Mockito.mock(JdbcOperations.class)) + .withPropertyValues("ca-skeleton.runtime.migration-on-startup=false"); @Test void postgresqlSelectionComposesTheConcreteStoreBehindTheApplicationPort() { runner .withPropertyValues("ca-skeleton.capabilities.idempotency.provider=postgresql") .run( - context -> { - assertThat(context).hasSingleBean(IdempotencyStorePortV2.class); - assertThat(context.getBean(IdempotencyStorePortV2.class)) - .isInstanceOf(PostgreSqlOwnerSafeIdempotencyStore.class); - }); + context -> + assertThat(context.getBean(IdempotencyStorePort.class)) + .isInstanceOf(PostgreSqlOwnerSafeIdempotencyStore.class)); + } + + @Test + void migrationOffLeavesTheSchemaStreamToTheOperator() { + runner + .withPropertyValues("ca-skeleton.capabilities.idempotency.provider=postgresql") + .run(context -> assertThat(context).doesNotHaveBean(IdempotencySchemaStream.class)); } @Test void otherSelectionsDoNotComposeThePostgresqlStore() { runner .withPropertyValues("ca-skeleton.capabilities.idempotency.provider=redis") - .run(context -> assertThat(context).doesNotHaveBean(IdempotencyStorePortV2.class)); + .run(context -> assertThat(context).doesNotHaveBean(IdempotencyStorePort.class)); } } diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/config/PersistenceEntityScanCoverageTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/config/PersistenceEntityScanCoverageTest.java index 11c3cadf..538f800c 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/config/PersistenceEntityScanCoverageTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/config/PersistenceEntityScanCoverageTest.java @@ -59,6 +59,8 @@ class PersistenceEntityScanCoverageTest { "autoconfigure", // Vendor-selection configuration only. "config", + // Startup guards and the management view: no entity, no repository. + "startup", "h2", // The opt-in capability, scanned by its own gated configuration instead. Fileserver was // the second one and is not listed because the package is gone from this leaf entirely. diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/experimental/ExperimentalEntryConsentTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/experimental/ExperimentalEntryConsentTest.java deleted file mode 100644 index 1c73049d..00000000 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/experimental/ExperimentalEntryConsentTest.java +++ /dev/null @@ -1,96 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.experimental; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.outbound.persistence.experimental.replica.ConsistencyAwareDataSourceRouter; -import dev.caskeleton.adapter.outbound.persistence.experimental.rls.RlsTenantSessionBinder; -import dev.caskeleton.adapter.outbound.persistence.experimental.schema.SchemaTenantMigrationOrchestrator; -import java.lang.reflect.Constructor; -import java.lang.reflect.Modifier; -import java.util.List; -import java.util.Map; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * The experimental entry points cannot be obtained without stating consent. - * - *

{@code experimental/**} ships inside the main artifact — there is no separate variant — so the - * only thing standing between a deployment and tenant isolation, RLS binding or replica routing is - * whether the code can be constructed. The gate documents that presence on the classpath is not - * consent, and for a while nothing enforced it: a public constructor made one {@code new} a - * complete bypass of the flag the gate exists to require. - * - *

So the check is on the constructor, not on the gate's own logic. A gate that fails correctly - * when asked is worth nothing if the caller never has to ask, and the gate's unit tests cannot see - * that difference because they always ask. - */ -class ExperimentalEntryConsentTest { - - /** The behaviour-bearing entry points; the surrounding value types are not activations. */ - private static final List> ENTRY_POINTS = - List.of( - ConsistencyAwareDataSourceRouter.class, - RlsTenantSessionBinder.class, - SchemaTenantMigrationOrchestrator.class); - - private final ExperimentalFeatureGate gate = new ExperimentalFeatureGate(); - - @Test - @DisplayName("no experimental entry point can be constructed from outside its package") - void noEntryPointCanBeConstructedFromOutsideItsPackage() { - for (Class entryPoint : ENTRY_POINTS) { - for (Constructor constructor : entryPoint.getDeclaredConstructors()) { - assertThat(Modifier.isPublic(constructor.getModifiers())) - .as( - "%s has a public constructor, so one `new` bypasses the flag entirely", - entryPoint.getSimpleName()) - .isFalse(); - } - } - } - - @Test - @DisplayName("every experimental entry point offers a gate-taking factory and nothing else") - void everyEntryPointOffersAGateTakingFactory() { - for (Class entryPoint : ENTRY_POINTS) { - assertThat(entryPoint.getDeclaredMethods()) - .as("%s must be obtainable, and only through the gate", entryPoint.getSimpleName()) - .anySatisfy( - method -> { - assertThat(method.getName()).isEqualTo("enabledBy"); - assertThat(method.getReturnType()).isEqualTo(entryPoint); - assertThat(method.getParameterTypes()[0]).isEqualTo(ExperimentalFeatureGate.class); - }); - } - } - - @Test - @DisplayName("the RLS binder refuses to exist when its flag is absent") - void theRlsBinderRefusesToExistWithoutItsFlag() { - assertThatThrownBy(() -> RlsTenantSessionBinder.enabledBy(gate, Map.of())) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining(ExperimentalFeature.MULTITENANCY_RLS.property()); - } - - @Test - @DisplayName("the RLS binder refuses to exist when another feature's flag is the one that is on") - void theRlsBinderRefusesAnotherFeaturesFlag() { - assertThatThrownBy( - () -> - RlsTenantSessionBinder.enabledBy( - gate, Map.of(ExperimentalFeature.READ_REPLICA.property(), true))) - .as("consent is per feature; one experimental flag is not consent to all of them") - .isInstanceOf(IllegalStateException.class); - } - - @Test - @DisplayName("the RLS binder is obtainable once its own flag is explicitly true") - void theRlsBinderIsObtainableWithItsOwnFlag() { - assertThat( - RlsTenantSessionBinder.enabledBy( - gate, Map.of(ExperimentalFeature.MULTITENANCY_RLS.property(), true))) - .isNotNull(); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/experimental/ExperimentalFeatureGateTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/experimental/ExperimentalFailClosedTest.java similarity index 71% rename from src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/experimental/ExperimentalFeatureGateTest.java rename to src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/experimental/ExperimentalFailClosedTest.java index 672dcf85..5daf7f8f 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/experimental/ExperimentalFeatureGateTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/experimental/ExperimentalFailClosedTest.java @@ -21,30 +21,14 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -/** - * Experimental plan Tasks 1-9 — every experimental capability is off and fail-closed by default. - */ -class ExperimentalFeatureGateTest { - - private final ExperimentalFeatureGate gate = new ExperimentalFeatureGate(); +/** Experimental plan Tasks 2-6 — every experimental building block fails closed. */ +class ExperimentalFailClosedTest { @AfterEach void clearTenant() { TenantContext.clear(); } - @Test - @DisplayName("a feature is disabled unless its flag is explicitly true") - void featureIsDisabledUnlessExplicitlyEnabled() { - assertThatThrownBy(() -> gate.requireEnabled(ExperimentalFeature.MULTITENANCY_COLUMN, Map.of())) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("backend.jpa.experimental.multitenancy-column=true"); - - gate.requireEnabled( - ExperimentalFeature.MULTITENANCY_COLUMN, - Map.of("backend.jpa.experimental.multitenancy-column", true)); - } - @Test @DisplayName("an absent tenant context is an error, never a default") void tenantContextIsFailClosed() { @@ -131,31 +115,7 @@ class ExperimentalFeatureGateTest { private record FixedLagMonitor(Optional replayedThrough, Optional lag) implements ReplicaLagMonitor {} - /** - * A router obtained the only way a deployment can obtain one. - * - *

The constructor is package-private and the factory demands the gate. That is the whole point - * of JPA-018: the gate documented that having this class on the classpath is not consent, and a - * public constructor made one {@code new} a complete bypass. - */ private static ConsistencyAwareDataSourceRouter router(ReplicaLagMonitor lagMonitor) { - return ConsistencyAwareDataSourceRouter.enabledBy( - new ExperimentalFeatureGate(), - java.util.Map.of(ExperimentalFeature.READ_REPLICA.property(), true), - lagMonitor); - } - - @Test - @DisplayName("without the flag, no router can be obtained at all") - void withoutTheFlagNoRouterCanBeObtained() { - assertThatThrownBy( - () -> - ConsistencyAwareDataSourceRouter.enabledBy( - new ExperimentalFeatureGate(), - java.util.Map.of(), - new FixedLagMonitor(Optional.empty(), Optional.empty()))) - .as("classpath presence is not consent, and it used to be enough") - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining(ExperimentalFeature.READ_REPLICA.property()); + return new ConsistencyAwareDataSourceRouter(lagMonitor); } } diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/experimental/next/CompatibilityLaneDefinitionTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/experimental/next/CompatibilityLaneDefinitionTest.java deleted file mode 100644 index 1ba5412c..00000000 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/experimental/next/CompatibilityLaneDefinitionTest.java +++ /dev/null @@ -1,39 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.experimental.next; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.outbound.persistence.api.capability.SupportLevel; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** Experimental plan Task 7 — a lane is experimental and publishes nothing. */ -class CompatibilityLaneDefinitionTest { - - @Test - @DisplayName("the JPA 4 lane is experimental and separate from Stable publication") - void jpaFourLaneIsExperimentalAndSeparateFromStablePublication() { - var lane = CompatibilityLane.experimental("jpa4"); - - assertThat(lane.publicationEnabled()).isFalse(); - assertThat(lane.supportLevel()).isEqualTo(SupportLevel.EXPERIMENTAL); - } - - @Test - @DisplayName("all three lanes are defined and none publishes") - void allThreeLanesAreDefinedAndNonePublishes() { - assertThat(CompatibilityLane.defined()) - .extracting(CompatibilityLane::name) - .containsExactly("jpa4", "hibernate8", "postgresql19"); - assertThat(CompatibilityLane.defined()) - .allSatisfy(lane -> assertThat(lane.publicationEnabled()).isFalse()); - } - - @Test - @DisplayName("an experimental lane that tries to publish is refused") - void experimentalLaneMayNotPublish() { - assertThatThrownBy(() -> new CompatibilityLane("jpa4", SupportLevel.EXPERIMENTAL, true)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("Stable coordinates"); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/experimental/next/ExperimentalPromotionGateTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/experimental/next/ExperimentalPromotionGateTest.java deleted file mode 100644 index c1f5eafb..00000000 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/experimental/next/ExperimentalPromotionGateTest.java +++ /dev/null @@ -1,71 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.experimental.next; - -import static org.assertj.core.api.Assertions.assertThat; - -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** Experimental plan Task 9 — promotion requires evidence and a reviewed decision. */ -class ExperimentalPromotionGateTest { - - private final ExperimentalPromotionGate gate = new ExperimentalPromotionGate(); - - @Test - @DisplayName("promotion requires all evidence and a reviewed ADR") - void promotionRequiresAllEvidenceAndReviewedAdr() { - var evidence = - PromotionEvidence.none() - .withCompatibility(true) - .withSecurity(true) - .withFailure(true) - .withMigration(true) - .withPerformance(true) - .withReviewedAdr(false); - - assertThat(gate.evaluate(evidence)).isEqualTo(PromotionDecision.BLOCKED_MISSING_ADR); - } - - @Test - @DisplayName("complete evidence with a reviewed ADR is eligible for Stable review") - void completeEvidenceIsEligible() { - var evidence = - PromotionEvidence.none() - .withCompatibility(true) - .withSecurity(true) - .withFailure(true) - .withMigration(true) - .withPerformance(true) - .withReviewedAdr(true); - - assertThat(gate.evaluate(evidence)).isEqualTo(PromotionDecision.ELIGIBLE_FOR_STABLE_REVIEW); - } - - @Test - @DisplayName("a reviewed ADR alone does not promote anything") - void reviewedAdrAloneIsBlockedTechnically() { - assertThat(gate.evaluate(PromotionEvidence.none().withReviewedAdr(true))) - .isEqualTo(PromotionDecision.BLOCKED_TECHNICAL); - } - - @Test - @DisplayName("each missing suite blocks technically on its own") - void eachMissingSuiteBlocksOnItsOwn() { - var complete = - PromotionEvidence.none() - .withCompatibility(true) - .withSecurity(true) - .withFailure(true) - .withMigration(true) - .withPerformance(true) - .withReviewedAdr(true); - - assertThat(gate.evaluate(complete.withSecurity(false))) - .isEqualTo(PromotionDecision.BLOCKED_TECHNICAL); - assertThat(gate.evaluate(complete.withFailure(false))) - .isEqualTo(PromotionDecision.BLOCKED_TECHNICAL); - assertThat(gate.evaluate(complete.withMigration(false))) - .isEqualTo(PromotionDecision.BLOCKED_TECHNICAL); - assertThat(gate.evaluate(complete.withPerformance(false))) - .isEqualTo(PromotionDecision.BLOCKED_TECHNICAL); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/experimental/next/Hibernate8CompatibilityTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/experimental/next/Hibernate8CompatibilityTest.java index 65eb84cc..10ab750a 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/experimental/next/Hibernate8CompatibilityTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/experimental/next/Hibernate8CompatibilityTest.java @@ -2,13 +2,12 @@ package dev.caskeleton.adapter.outbound.persistence.experimental.next; import static org.assertj.core.api.Assertions.assertThat; -import dev.caskeleton.adapter.outbound.persistence.api.capability.SupportLevel; import org.hibernate.Version; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; /** - * Experimental plan Task 8 — the Hibernate 8 lane. + * The Hibernate 8 probe that {@code .github/workflows/jpa-next.yml} runs. * *

The provider version is read from Hibernate itself rather than from the build file, because * the build file states an intent and the classpath states the fact. Dependency resolution, @@ -16,50 +15,11 @@ import org.junit.jupiter.api.Test; */ class Hibernate8CompatibilityTest { - private static final String STABLE_MAJOR = "7."; - @Test - @DisplayName("the lane is defined, experimental, and never publishes") - void laneIsDefinedExperimentalAndNonPublishing() { - CompatibilityLane lane = - CompatibilityLane.defined().stream() - .filter(candidate -> candidate.name().equals("hibernate8")) - .findFirst() - .orElseThrow(); - - assertThat(lane.supportLevel()).isEqualTo(SupportLevel.EXPERIMENTAL); - assertThat(lane.publicationEnabled()).isFalse(); - } - - @Test - @DisplayName("the resolved provider is the Stable major, not an experimental one") + @DisplayName("the resolved provider is the Stable 7.x major") void resolvedProviderIsTheStableMajor() { assertThat(Version.getVersionString()) .as("the platform's Stable answer is only valid for the provider it was measured against") - .startsWith(STABLE_MAJOR); - } - - @Test - @DisplayName("Hibernate 8 may not silently replace the Stable provider") - void hibernate8MayNotSilentlyReplaceTheStableProvider() { - var policy = HibernateCompatibilityPolicy.fromClasspath(); - - assertThat(policy.stableProvider()).startsWith(STABLE_MAJOR); - assertThat(policy.mayReplaceStableProvider("8.0.0")) - .as("a provider major that no contract has run against is not a drop-in") - .isFalse(); - // The policy enumerates majors, not point releases: what a lane covers is a provider - // generation, and 8.0.1 is no more measured than 8.0.0 was. - assertThat(policy.experimentalProviders()).contains("8"); - } - - @Test - @DisplayName("the Hibernate 8 lane is not executable until the provider is on the classpath") - void laneIsNotExecutableUntilTheProviderExists() { - assertThat(Version.getVersionString().startsWith("8.")) - .as( - "when this fails, Hibernate 8 is resolved and the lane must actually be run before the" - + " platform claims anything about it") - .isFalse(); + .startsWith("7."); } } diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/experimental/next/HibernateCompatibilityPolicyTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/experimental/next/HibernateCompatibilityPolicyTest.java deleted file mode 100644 index e7b5e082..00000000 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/experimental/next/HibernateCompatibilityPolicyTest.java +++ /dev/null @@ -1,45 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.experimental.next; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.adapter.outbound.persistence.hibernate.HibernateProviderPolicy; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** Experimental plan Task 8 — a lane result never replaces the Stable provider. */ -class HibernateCompatibilityPolicyTest { - - private final HibernateCompatibilityPolicy policy = - new HibernateCompatibilityPolicy(new HibernateProviderPolicy("7.1.8.Final")); - - @Test - @DisplayName("Hibernate 8 cannot replace the Stable provider without a promotion") - void hibernateEightCannotReplaceStableProviderWithoutPromotion() { - assertThat(policy.stableProvider()).isEqualTo("7.4"); - assertThat(policy.experimentalProviders()).contains("8"); - assertThat(policy.mayReplaceStableProvider("8.0.0.Final")).isFalse(); - } - - @Test - @DisplayName("a 7.x provider is not experimental") - void sevenIsNotExperimental() { - assertThat(policy.mayReplaceStableProvider("7.1.8.Final")).isTrue(); - } - - @Test - @DisplayName("the declared baseline and the resolved runtime are held apart") - void declaredBaselineAndRuntimeAreHeldApart() { - var provider = new HibernateProviderPolicy("7.1.8.Final"); - - assertThat(provider.stableProvider()).isEqualTo("7.4"); - assertThat(provider.runtimeMinorVersion()).isEqualTo("7.1"); - assertThat(provider.driftsFromDeclaredBaseline()).isTrue(); - assertThat(provider.report()).contains("declaredStable=7.4").contains("runtime=7.1.8.Final"); - } - - @Test - @DisplayName("a runtime matching the declared baseline reports no drift") - void matchingRuntimeReportsNoDrift() { - assertThat(new HibernateProviderPolicy("7.4.1.Final").driftsFromDeclaredBaseline()).isFalse(); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/experimental/next/Jpa4CompatibilityTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/experimental/next/Jpa4CompatibilityTest.java index 8d281730..61c98fc2 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/experimental/next/Jpa4CompatibilityTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/experimental/next/Jpa4CompatibilityTest.java @@ -1,73 +1,27 @@ package dev.caskeleton.adapter.outbound.persistence.experimental.next; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import dev.caskeleton.adapter.outbound.persistence.api.capability.SupportLevel; import java.util.Optional; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; /** - * Experimental plan Task 7 — the Jakarta Persistence 4 lane. + * The Jakarta Persistence 4 probe that {@code .github/workflows/jpa-next.yml} runs. * - *

JPA 4 is not released, so this lane cannot run against it. That is exactly why the test is - * here: a lane whose target does not exist must report "not executable", never "passed". The - * detection reads the specification version off the API actually on the classpath, so the day JPA 4 - * lands the assertion inverts and forces someone to run the lane rather than letting the platform - * quietly claim compatibility it never measured. + *

JPA 4 is not released, so nothing can run against it. The probe reads the specification + * version off the API actually on the classpath, so the day a dependency upgrade brings JPA 4 in it + * fails and forces someone to run the contracts rather than letting the platform quietly claim + * compatibility it never measured. */ class Jpa4CompatibilityTest { private static final String STABLE_SPECIFICATION = "3.2"; @Test - @DisplayName("the lane is defined, experimental, and never publishes") - void laneIsDefinedExperimentalAndNonPublishing() { - CompatibilityLane lane = laneNamed("jpa4"); - - assertThat(lane.supportLevel()).isEqualTo(SupportLevel.EXPERIMENTAL); - assertThat(lane.publicationEnabled()) - .as("publishing from a lane would let consumers depend on an unmeasured answer") - .isFalse(); - } - - @Test - @DisplayName("an experimental lane cannot be configured to publish") - void experimentalLaneCannotBeConfiguredToPublish() { - assertThatThrownBy(() -> new CompatibilityLane("jpa4", SupportLevel.EXPERIMENTAL, true)) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("the platform still compiles against the Stable specification") + @DisplayName("the platform still compiles against the Stable 3.2 specification") void platformStillCompilesAgainstTheStableSpecification() { - Optional specification = specificationVersionOnClasspath(); - - assertThat(specification) - .as("the Jakarta Persistence API jar must declare the specification it implements") - .isPresent(); - assertThat(specification).contains(STABLE_SPECIFICATION); - } - - @Test - @DisplayName("the JPA 4 lane is not executable until the specification is on the classpath") - void laneIsNotExecutableUntilTheSpecificationExists() { - boolean targetPresent = - specificationVersionOnClasspath().filter(version -> version.startsWith("4.")).isPresent(); - - assertThat(targetPresent) - .as( - "when this fails, Jakarta Persistence 4 is present and the lane must actually be run" - + " before the platform claims anything about it") - .isFalse(); - } - - private static CompatibilityLane laneNamed(String name) { - return CompatibilityLane.defined().stream() - .filter(lane -> lane.name().equals(name)) - .findFirst() - .orElseThrow(() -> new AssertionError("no compatibility lane named " + name)); + assertThat(specificationVersionOnClasspath()).contains(STABLE_SPECIFICATION); } /** The specification version declared by the Jakarta Persistence API actually resolved. */ diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/experimental/next/PostgreSql19CompatibilityTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/experimental/next/PostgreSql19CompatibilityTest.java index beb5f7ee..1be2c1aa 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/experimental/next/PostgreSql19CompatibilityTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/experimental/next/PostgreSql19CompatibilityTest.java @@ -1,16 +1,14 @@ package dev.caskeleton.adapter.outbound.persistence.experimental.next; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import dev.caskeleton.adapter.outbound.persistence.api.capability.SupportLevel; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; /** - * Experimental plan Task 9 — the PostgreSQL 19 lane. + * The PostgreSQL 19 probe that {@code .github/workflows/jpa-next.yml} runs. * - *

Unlike the specification and provider lanes, this one has no artifact to detect: a server + *

Unlike the specification and provider probes, this one has no artifact to detect: a server * version is only observable by starting one. So the assertion is about the support matrix instead * — 19 must not appear in it, and the runtime policy must refuse a server reporting it, because a * major nobody ran the contracts against is not a supported major regardless of how well it happens @@ -20,29 +18,6 @@ class PostgreSql19CompatibilityTest { private static final int UNMEASURED_MAJOR = 19; - @Test - @DisplayName("the lane is defined, experimental, and never publishes") - void laneIsDefinedExperimentalAndNonPublishing() { - CompatibilityLane lane = - CompatibilityLane.defined().stream() - .filter(candidate -> candidate.name().equals("postgresql19")) - .findFirst() - .orElseThrow(); - - assertThat(lane.supportLevel()).isEqualTo(SupportLevel.EXPERIMENTAL); - assertThat(lane.publicationEnabled()).isFalse(); - } - - @Test - @DisplayName("the three defined lanes are exactly the plan's three, all non-publishing") - void definedLanesAreExactlyThePlansThree() { - assertThat(CompatibilityLane.defined()) - .extracting(CompatibilityLane::name) - .containsExactly("jpa4", "hibernate8", "postgresql19"); - assertThat(CompatibilityLane.defined()) - .allSatisfy(lane -> assertThat(lane.publicationEnabled()).isFalse()); - } - @Test @DisplayName("an unmeasured server major is not in the Stable support matrix") void unmeasuredServerMajorIsNotInTheStableMatrix() { @@ -52,18 +27,6 @@ class PostgreSql19CompatibilityTest { .containsExactly(16, 17, 18); } - @Test - @DisplayName("a lane may not be promoted to Stable while it is still a lane") - void laneMayNotBePromotedWhileStillALane() { - assertThatThrownBy(() -> new CompatibilityLane("postgresql19", SupportLevel.EXPERIMENTAL, true)) - .isInstanceOf(IllegalArgumentException.class); - - // A Stable lane is representable — that is what promotion produces — but only once the - // contracts have been run and the matrix updated, which is the promotion gate's job. - var promoted = new CompatibilityLane("postgresql19", SupportLevel.STABLE, true); - assertThat(promoted.publicationEnabled()).isTrue(); - } - /** * The majors the Stable contracts actually run against. * diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/h2/H2ClaimSqlTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/h2/H2ClaimSqlTest.java index 8ada120f..e2dcad91 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/h2/H2ClaimSqlTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/h2/H2ClaimSqlTest.java @@ -2,16 +2,12 @@ package dev.caskeleton.adapter.outbound.persistence.h2; import static org.assertj.core.api.Assertions.assertThat; -import dev.caskeleton.adapter.outbound.persistence.idempotency.entity.IdempotencyRecordEntity; import dev.caskeleton.adapter.outbound.persistence.outbox.entity.OutboxEventEntity; import jakarta.persistence.EntityManager; import jakarta.persistence.EntityManagerFactory; -import java.time.Duration; import java.time.Instant; import java.util.List; -import java.util.Optional; import java.util.Properties; -import java.util.UUID; import java.util.function.Function; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; @@ -26,9 +22,7 @@ import org.springframework.transaction.support.TransactionTemplate; /** * Runs the H2 vendor claim statements against a real H2, because their risk is dialect acceptance - * rather than branch logic. The idempotency claim in particular is not a translation of the - * PostgreSQL statement — H2 has no {@code ON CONFLICT ... RETURNING}, so it is a {@code MERGE ... - * USING}, and only an execution proves that the substitution kept the three outcomes intact. + * rather than branch logic. * *

In-memory and process-local, so this stays an ordinary unit test: no container, no network, * nothing to skip when Docker is absent. Real-PostgreSQL fidelity remains the job of the {@code @@ -36,10 +30,6 @@ import org.springframework.transaction.support.TransactionTemplate; */ class H2ClaimSqlTest { - private static final String TENANT = "tenant-a"; - private static final String PRINCIPAL = "principal-a"; - private static final String USE_CASE = "PlaceOrder"; - private static LocalContainerEntityManagerFactoryBean factoryBean; private static EntityManagerFactory entityManagerFactory; private static TransactionTemplate transactionTemplate; @@ -66,9 +56,7 @@ class H2ClaimSqlTest { factoryBean = new LocalContainerEntityManagerFactoryBean(); factoryBean.setDataSource(dataSource); factoryBean.setPersistenceUnitName("h2-claim-sql"); - factoryBean.setPackagesToScan( - "dev.caskeleton.adapter.outbound.persistence.idempotency.entity", - "dev.caskeleton.adapter.outbound.persistence.outbox.entity"); + factoryBean.setPackagesToScan("dev.caskeleton.adapter.outbound.persistence.outbox.entity"); factoryBean.setJpaVendorAdapter(vendorAdapter); factoryBean.setJpaProperties(jpaProperties); factoryBean.afterPropertiesSet(); @@ -89,47 +77,11 @@ class H2ClaimSqlTest { now = Instant.parse("2026-08-12T00:00:00Z"); inTransaction( entityManager -> { - entityManager.createQuery("DELETE FROM IdempotencyRecordEntity").executeUpdate(); entityManager.createQuery("DELETE FROM OutboxEventEntity").executeUpdate(); return null; }); } - @Test - void claimsAFreeScope() { - UUID proposed = UUID.randomUUID(); - - Optional claimed = tryClaim(proposed, "key-1", now.plus(Duration.ofHours(1)), now); - - assertThat(claimed).contains(proposed); - assertThat(storedStatus("key-1")).isEqualTo("IN_FLIGHT"); - } - - @Test - void losesToALiveClaimOnTheSameScope() { - UUID winner = UUID.randomUUID(); - tryClaim(winner, "key-2", now.plus(Duration.ofHours(1)), now); - - Optional second = - tryClaim(UUID.randomUUID(), "key-2", now.plus(Duration.ofHours(1)), now); - - assertThat(second).as("a live winner must not be displaced").isEmpty(); - assertThat(storedId("key-2")).isEqualTo(winner); - } - - @Test - void takesOverAnExpiredClaimOnTheSameScope() { - UUID abandoned = UUID.randomUUID(); - Instant expiry = now.plus(Duration.ofHours(1)); - tryClaim(abandoned, "key-3", expiry, now); - - UUID reclaimer = UUID.randomUUID(); - Optional retaken = tryClaim(reclaimer, "key-3", expiry.plus(Duration.ofHours(2)), expiry); - - assertThat(retaken).contains(reclaimer); - assertThat(storedId("key-3")).isEqualTo(reclaimer); - } - @Test void claimsOnlyTheOldestUnpublishedEventPerAggregate() { inTransaction( @@ -159,49 +111,11 @@ class H2ClaimSqlTest { assertThat(claimEligible(now, 10)).isEmpty(); } - private Optional tryClaim(UUID id, String key, Instant expiresAt, Instant asOf) { - return inTransaction( - entityManager -> - new H2IdempotencyClaimRepository(entityManager) - .tryClaim( - new IdempotencyRecordEntity( - id, - TENANT, - PRINCIPAL, - key, - USE_CASE, - "request-hash", - "IN_FLIGHT", - null, - null, - asOf, - expiresAt), - asOf, - null)); - } - private List claimEligible(Instant asOf, int limit) { return inTransaction( entityManager -> new H2OutboxClaimRepository(entityManager).claimEligible(asOf, limit)); } - private String storedStatus(String key) { - return inTransaction(entityManager -> stored(entityManager, key).getStatus()); - } - - private UUID storedId(String key) { - return inTransaction(entityManager -> stored(entityManager, key).getId()); - } - - private static IdempotencyRecordEntity stored(EntityManager entityManager, String key) { - return entityManager - .createQuery( - "SELECT r FROM IdempotencyRecordEntity r WHERE r.idempotencyKey = :key", - IdempotencyRecordEntity.class) - .setParameter("key", key) - .getSingleResult(); - } - private static OutboxEventEntity event( String eventId, String aggregateId, Instant occurredAt, Instant nextAttemptAt) { OutboxEventEntity entity = new OutboxEventEntity(); diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/h2/H2FailureTranslatorTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/h2/H2FailureTranslatorTest.java deleted file mode 100644 index bdf4a3d2..00000000 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/h2/H2FailureTranslatorTest.java +++ /dev/null @@ -1,51 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.h2; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.adapter.outbound.persistence.api.PersistenceOperationName; -import dev.caskeleton.adapter.outbound.persistence.api.error.FailureCategory; -import java.sql.SQLException; -import java.time.Duration; -import org.junit.jupiter.api.Test; -import org.springframework.dao.TransientDataAccessResourceException; - -class H2FailureTranslatorTest { - - private static final PersistenceOperationName OPERATION = - new PersistenceOperationName("order.write"); - - private final H2FailureTranslator translator = new H2FailureTranslator(); - - @Test - void serializationFailureIsRetryable() { - var translated = - translator.translate(failure("40001"), OPERATION, 1, Duration.ofMillis(4), null); - - assertThat(translated.category()).isEqualTo(FailureCategory.SERIALIZATION_FAILURE); - assertThat(translated.retryable()).isTrue(); - assertThat(translated.context().sqlState()).isEqualTo("40001"); - } - - @Test - void deadlockStateIsRetryableWhenSurfaced() { - var translated = - translator.translate(failure("40P01"), OPERATION, 2, Duration.ofMillis(7), "trace-1"); - - assertThat(translated.category()).isEqualTo(FailureCategory.DEADLOCK); - assertThat(translated.retryable()).isTrue(); - assertThat(translated.context().transactionAttempt()).isEqualTo(2); - } - - @Test - void unknownStateIsNotInventedIntoARetryableCategory() { - var translated = translator.translate(failure("HY000"), OPERATION, 1, Duration.ZERO, null); - - assertThat(translated.category()).isEqualTo(FailureCategory.UNKNOWN); - assertThat(translated.retryable()).isFalse(); - } - - private static RuntimeException failure(String sqlState) { - return new TransientDataAccessResourceException( - "database contention", new SQLException("driver detail", sqlState)); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/hibernate/HibernateProviderPolicyTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/hibernate/HibernateProviderPolicyTest.java new file mode 100644 index 00000000..18871abe --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/hibernate/HibernateProviderPolicyTest.java @@ -0,0 +1,42 @@ +package dev.caskeleton.adapter.outbound.persistence.hibernate; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +/** The declared Stable provider and the resolved runtime are held apart (design §3.1, §26). */ +class HibernateProviderPolicyTest { + + @ParameterizedTest + @CsvSource({"8.0.0.Final, true", "7.1.8.Final, false"}) + @DisplayName("only Hibernate 8 is an experimental provider") + void onlyHibernateEightIsExperimental(String version, boolean experimental) { + assertThat(new HibernateProviderPolicy("7.1.8.Final").isExperimental(version)) + .isEqualTo(experimental); + } + + @Test + @DisplayName("a 7.1 runtime is reported as drifting from the declared 7.4 baseline") + void runtimeBehindTheDeclaredBaselineIsReportedAsDrift() { + // when + var provider = new HibernateProviderPolicy("7.1.8.Final"); + + // then + assertThat(provider) + .extracting( + HibernateProviderPolicy::stableProvider, + HibernateProviderPolicy::runtimeMinorVersion, + HibernateProviderPolicy::driftsFromDeclaredBaseline, + HibernateProviderPolicy::report) + .containsExactly("7.4", "7.1", true, "declaredStable=7.4 runtime=7.1.8.Final"); + } + + @Test + @DisplayName("a runtime matching the declared baseline reports no drift") + void matchingRuntimeReportsNoDrift() { + assertThat(new HibernateProviderPolicy("7.4.1.Final").driftsFromDeclaredBaseline()).isFalse(); + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/hibernate/NamedStatementInspectorTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/hibernate/NamedStatementInspectorTest.java new file mode 100644 index 00000000..cc3e3dbf --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/hibernate/NamedStatementInspectorTest.java @@ -0,0 +1,28 @@ +package dev.caskeleton.adapter.outbound.persistence.hibernate; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.adapter.outbound.persistence.api.query.QueryName; +import org.junit.jupiter.api.Test; + +/** The inspector only reads the query name the library executors bind (design §37). */ +class NamedStatementInspectorTest { + + private final NamedStatementInspector inspector = new NamedStatementInspector(); + + @Test + void boundQueryNameIsPrefixedAsAComment() { + // when + String inspected = + QueryNameContext.with( + new QueryName("order.find-recent"), () -> inspector.inspect("select 1")); + + // then + assertThat(inspected).isEqualTo("/* order.find-recent */ select 1"); + } + + @Test + void statementWithoutABoundQueryNameIsUnchanged() { + assertThat(inspector.inspect("select 1")).isEqualTo("select 1"); + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/idempotency/IdempotencyActivationContractTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/idempotency/IdempotencyActivationContractTest.java index 8662c514..fe58d979 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/idempotency/IdempotencyActivationContractTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/idempotency/IdempotencyActivationContractTest.java @@ -8,15 +8,17 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; class IdempotencyActivationContractTest { @Test - void jdbcIdempotencyRequiresAnExplicitProviderProperty() { - assertExplicit(IdempotencyStoreAdapter.class); - assertExplicit(IdempotencyReaper.class); - } + void reaperRunsOnlyWhenThePostgresqlProviderIsSelected() { + // when + ConditionalOnProperty condition = + IdempotencyReaper.class.getAnnotation(ConditionalOnProperty.class); - private static void assertExplicit(Class type) { - ConditionalOnProperty condition = type.getAnnotation(ConditionalOnProperty.class); - assertThat(condition).isNotNull(); - assertThat(condition.havingValue()).isEqualTo("jdbc"); - assertThat(condition.matchIfMissing()).isFalse(); + // then + assertThat(condition) + .extracting( + c -> c.name()[0], + ConditionalOnProperty::havingValue, + ConditionalOnProperty::matchIfMissing) + .containsExactly("ca-skeleton.capabilities.idempotency.provider", "postgresql", false); } } diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/idempotency/IdempotencyStoreAdapterTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/idempotency/IdempotencyStoreAdapterTest.java deleted file mode 100644 index df1c1ae3..00000000 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/idempotency/IdempotencyStoreAdapterTest.java +++ /dev/null @@ -1,206 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.idempotency; - -import static java.nio.charset.StandardCharsets.UTF_8; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import dev.caskeleton.adapter.outbound.persistence.idempotency.entity.IdempotencyRecordEntity; -import dev.caskeleton.application.idempotency.IdempotencyRecord; -import dev.caskeleton.application.idempotency.IdempotencyScope; -import dev.caskeleton.application.idempotency.IdempotencyStatus; -import dev.caskeleton.application.idempotency.RequestFingerprint; -import dev.caskeleton.application.idempotency.StoredResponse; -import java.time.Clock; -import java.time.Duration; -import java.time.Instant; -import java.time.ZoneOffset; -import java.util.Optional; -import java.util.UUID; -import org.junit.jupiter.api.Test; -import org.mockito.ArgumentCaptor; -import org.springframework.dao.DataIntegrityViolationException; - -class IdempotencyStoreAdapterTest { - - private static final Instant NOW = Instant.parse("2026-06-09T12:00:00Z"); - private static final Clock CLOCK = Clock.fixed(NOW, ZoneOffset.UTC); - private static final IdempotencyScope SCOPE = - IdempotencyScope.of("user-1", "key-1", "CreateWorkLogUseCase"); - private static final RequestFingerprint FP = RequestFingerprint.ofSha256("body".getBytes(UTF_8)); - private static final Instant EXPIRES = NOW.plus(Duration.ofHours(24)); - - private final IdempotencyRecordJpaRepository repo = mock(IdempotencyRecordJpaRepository.class); - - private IdempotencyStoreAdapter adapter(IdempotencyResponseObjectStore objectStore) { - return new IdempotencyStoreAdapter(repo, objectStore, CLOCK); - } - - private IdempotencyStoreAdapter vendorAdapter(IdempotencyClaimRepository claims) { - return new IdempotencyStoreAdapter(repo, null, claims, CLOCK); - } - - private IdempotencyRecordEntity entity( - String status, Instant expiresAt, String payload, String ref) { - return new IdempotencyRecordEntity( - UUID.randomUUID(), - "", - "user-1", - "key-1", - "CreateWorkLogUseCase", - FP.hex(), - status, - payload, - ref, - NOW, - expiresAt); - } - - @Test - void tryBeginWinsWhenNoRecordExists() { - when(repo.findByTenantAndPrincipalAndIdempotencyKeyAndUseCaseName( - "", "user-1", "key-1", "CreateWorkLogUseCase")) - .thenReturn(Optional.empty()); - - boolean won = adapter(null).tryBegin(SCOPE, FP, EXPIRES); - - assertThat(won).isTrue(); - ArgumentCaptor saved = - ArgumentCaptor.forClass(IdempotencyRecordEntity.class); - verify(repo).saveAndFlush(saved.capture()); - assertThat(saved.getValue().getStatus()).isEqualTo("IN_FLIGHT"); - assertThat(saved.getValue().getRequestHash()).isEqualTo(FP.hex()); - assertThat(saved.getValue().getTenant()).isEqualTo(""); - } - - @Test - void tryBeginLosesWhenALiveRecordExists() { - when(repo.findByTenantAndPrincipalAndIdempotencyKeyAndUseCaseName(any(), any(), any(), any())) - .thenReturn(Optional.of(entity("IN_FLIGHT", NOW.plus(Duration.ofHours(1)), null, null))); - - assertThat(adapter(null).tryBegin(SCOPE, FP, EXPIRES)).isFalse(); - verify(repo, never()).saveAndFlush(any()); - } - - @Test - void tryBeginReclaimsAnExpiredRecordThenWins() { - IdempotencyRecordEntity expired = entity("COMPLETED", NOW.minusSeconds(1), "stale", null); - when(repo.findByTenantAndPrincipalAndIdempotencyKeyAndUseCaseName(any(), any(), any(), any())) - .thenReturn(Optional.of(expired)); - - assertThat(adapter(null).tryBegin(SCOPE, FP, EXPIRES)).isTrue(); - verify(repo).delete(expired); - verify(repo).saveAndFlush(any()); - } - - @Test - void vendorClaimReclaimsWithoutDeleteInsertOrTransactionPoisoning() { - IdempotencyRecordEntity expired = entity("COMPLETED", NOW.minusSeconds(1), "stale", null); - IdempotencyClaimRepository claims = mock(IdempotencyClaimRepository.class); - when(repo.findByTenantAndPrincipalAndIdempotencyKeyAndUseCaseName(any(), any(), any(), any())) - .thenReturn(Optional.of(expired)); - when(claims.tryClaim(any(), any(), any())) - .thenAnswer( - invocation -> { - IdempotencyRecordEntity proposed = invocation.getArgument(0); - when(repo.findById(proposed.getId())).thenReturn(Optional.of(proposed)); - return Optional.of(proposed.getId()); - }); - - assertThat(vendorAdapter(claims).tryBegin(SCOPE, FP, EXPIRES)).isTrue(); - - verify(repo, never()).delete(any()); - verify(repo, never()).saveAndFlush(any()); - verify(claims).tryClaim(any(), any(), org.mockito.Mockito.same(expired)); - } - - @Test - void tryBeginLosesOnUniqueConstraintRace() { - when(repo.findByTenantAndPrincipalAndIdempotencyKeyAndUseCaseName(any(), any(), any(), any())) - .thenReturn(Optional.empty()); - when(repo.saveAndFlush(any())) - .thenThrow(new DataIntegrityViolationException("uq_idempotency_scope")); - - assertThat(adapter(null).tryBegin(SCOPE, FP, EXPIRES)).isFalse(); - } - - @Test - void findTreatsExpiredRowAsAbsent() { - when(repo.findByTenantAndPrincipalAndIdempotencyKeyAndUseCaseName(any(), any(), any(), any())) - .thenReturn(Optional.of(entity("COMPLETED", NOW.minusSeconds(1), "x", null))); - - assertThat(adapter(null).find(SCOPE, NOW)).isEmpty(); - } - - @Test - void findMapsALiveCompletedRowWithInlinePayload() { - when(repo.findByTenantAndPrincipalAndIdempotencyKeyAndUseCaseName(any(), any(), any(), any())) - .thenReturn(Optional.of(entity("COMPLETED", EXPIRES, "{\"ok\":true}", null))); - - Optional found = adapter(null).find(SCOPE, NOW); - - assertThat(found) - .hasValueSatisfying( - r -> { - assertThat(r.status()).isEqualTo(IdempotencyStatus.COMPLETED); - assertThat(r.response().payload()).isEqualTo("{\"ok\":true}"); - assertThat(r.fingerprint()).isEqualTo(FP); - }); - } - - @Test - void completeStoresSmallPayloadInline() { - when(repo.findByTenantAndPrincipalAndIdempotencyKeyAndUseCaseName(any(), any(), any(), any())) - .thenReturn(Optional.of(entity("IN_FLIGHT", EXPIRES, null, null))); - - adapter(null).complete(SCOPE, new StoredResponse("small-body")); - - ArgumentCaptor saved = - ArgumentCaptor.forClass(IdempotencyRecordEntity.class); - verify(repo).save(saved.capture()); - assertThat(saved.getValue().getStatus()).isEqualTo("COMPLETED"); - assertThat(saved.getValue().getResponsePayload()).isEqualTo("small-body"); - assertThat(saved.getValue().getResponseRef()).isNull(); - } - - @Test - void completeOffloadsLargePayloadToObjectStore() { - IdempotencyResponseObjectStore objectStore = mock(IdempotencyResponseObjectStore.class); - when(objectStore.put(any())).thenReturn("s3://bucket/key-1"); - when(repo.findByTenantAndPrincipalAndIdempotencyKeyAndUseCaseName(any(), any(), any(), any())) - .thenReturn(Optional.of(entity("IN_FLIGHT", EXPIRES, null, null))); - String large = "x".repeat(IdempotencyStoreAdapter.INLINE_MAX_BYTES + 1); - - adapter(objectStore).complete(SCOPE, new StoredResponse(large)); - - ArgumentCaptor saved = - ArgumentCaptor.forClass(IdempotencyRecordEntity.class); - verify(repo).save(saved.capture()); - assertThat(saved.getValue().getResponseRef()).isEqualTo("s3://bucket/key-1"); - assertThat(saved.getValue().getResponsePayload()).isNull(); - } - - @Test - void completeFallsBackToInlineWhenLargeButNoObjectStore() { - when(repo.findByTenantAndPrincipalAndIdempotencyKeyAndUseCaseName(any(), any(), any(), any())) - .thenReturn(Optional.of(entity("IN_FLIGHT", EXPIRES, null, null))); - String large = "x".repeat(IdempotencyStoreAdapter.INLINE_MAX_BYTES + 1); - - adapter(null).complete(SCOPE, new StoredResponse(large)); - - ArgumentCaptor saved = - ArgumentCaptor.forClass(IdempotencyRecordEntity.class); - verify(repo).save(saved.capture()); - assertThat(saved.getValue().getResponsePayload()).isEqualTo(large); - assertThat(saved.getValue().getResponseRef()).isNull(); - } - - @Test - void discardDeletesByScope() { - adapter(null).discard(SCOPE); - verify(repo).deleteByScope("", "user-1", "key-1", "CreateWorkLogUseCase"); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/lock/DistributedLockPersistenceConfigTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/lock/DistributedLockPersistenceConfigTest.java index 2cffc36e..4bdf35d1 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/lock/DistributedLockPersistenceConfigTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/lock/DistributedLockPersistenceConfigTest.java @@ -30,6 +30,7 @@ class DistributedLockPersistenceConfigTest { assertThat(context).hasSingleBean(DistributedLockPort.class); assertThat(context).hasBean("inProcessDistributedLock"); assertThat(context).doesNotHaveBean("jdbcDistributedLock"); + assertThat(context).doesNotHaveBean("distributedLockProvider"); }); } @@ -43,6 +44,11 @@ class DistributedLockPersistenceConfigTest { assertThat(context).doesNotHaveBean("inProcessDistributedLock"); assertThat(context.getBean("jdbcDistributedLock")) .isInstanceOf(DistributedLockPort.class); + // Every caller gets the JDBC provider behind the metrics decorator. + assertThat(context.getBean("distributedLockProvider")) + .isInstanceOf(MeteredDistributedLockPort.class); + assertThat(context.getBean(DistributedLockPort.class)) + .isSameAs(context.getBean("distributedLockProvider")); }); } } diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/BootstrapStructuredRuntimeLoggingTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/lock/MeteredDistributedLockPortLoggingTest.java similarity index 66% rename from src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/BootstrapStructuredRuntimeLoggingTest.java rename to src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/lock/MeteredDistributedLockPortLoggingTest.java index 8bc783d8..b43b1830 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/BootstrapStructuredRuntimeLoggingTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/lock/MeteredDistributedLockPortLoggingTest.java @@ -1,8 +1,6 @@ -package dev.caskeleton.bootstrap.runtime; +package dev.caskeleton.adapter.outbound.persistence.lock; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Logger; @@ -11,13 +9,7 @@ import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.read.ListAppender; import dev.caskeleton.application.lock.DistributedLock; import dev.caskeleton.application.lock.DistributedLockPort; -import dev.caskeleton.application.outbox.PublishPendingOutboxEventsCommand; -import dev.caskeleton.application.outbox.PublishPendingOutboxEventsUseCase; -import dev.caskeleton.bootstrap.autoconfigure.lock.MeteredDistributedLockPort; -import dev.caskeleton.bootstrap.autoconfigure.outbox.OutboxMetrics; -import dev.caskeleton.bootstrap.autoconfigure.outbox.OutboxRelayScheduler; import io.micrometer.core.instrument.MeterRegistry; -import java.time.Clock; import java.time.Duration; import java.util.Arrays; import java.util.ConcurrentModificationException; @@ -27,29 +19,8 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.support.DefaultListableBeanFactory; -class BootstrapStructuredRuntimeLoggingTest { - - @Test - void outboxRelayUnexpectedFailureCarriesNextTickDispositionWithoutInventedErrorCode() { - PublishPendingOutboxEventsUseCase relay = mock(PublishPendingOutboxEventsUseCase.class); - OutboxMetrics metrics = mock(OutboxMetrics.class); - when(relay.handle(PublishPendingOutboxEventsCommand.INSTANCE)) - .thenThrow(new IllegalStateException("unexpected")); - - try (CapturedLogger captured = capture(OutboxRelayScheduler.class)) { - new OutboxRelayScheduler(relay, metrics, Clock.systemUTC()).relay(); - - ILoggingEvent event = captured.singleEvent(); - assertThat(event.getLevel()).isEqualTo(Level.ERROR); - String arguments = renderedArguments(event); - assertThat(arguments) - .contains("capability=outbox") - .contains("operation=relay") - .contains("retry.disposition=next-tick") - .doesNotContain("error.code="); - assertThat(event.getThrowableProxy()).isNotNull(); - } - } +/** The lease-expiry warning is classified by bounded fields, never by the unbounded lock key. */ +class MeteredDistributedLockPortLoggingTest { @Test void leaseExpiryWarningCarriesBoundedClassificationWithoutStructuredLockKey() { diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/lock/MeteredDistributedLockPortTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/lock/MeteredDistributedLockPortTest.java similarity index 99% rename from src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/lock/MeteredDistributedLockPortTest.java rename to src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/lock/MeteredDistributedLockPortTest.java index 5c42324d..cbfdaada 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/lock/MeteredDistributedLockPortTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/lock/MeteredDistributedLockPortTest.java @@ -1,4 +1,4 @@ -package dev.caskeleton.bootstrap.autoconfigure.lock; +package dev.caskeleton.adapter.outbound.persistence.lock; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/AppliedMigrationImmutabilityTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/AppliedMigrationImmutabilityTest.java new file mode 100644 index 00000000..87c59834 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/AppliedMigrationImmutabilityTest.java @@ -0,0 +1,90 @@ +package dev.caskeleton.adapter.outbound.persistence.migration; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.Map; +import java.util.TreeMap; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; + +/** + * A versioned migration that may have been applied is frozen: Flyway validates its checksum on + * every start, so editing it in place stops every database that already ran the old bytes. Changes + * go into a new version. The manifest pins every versioned file; a new migration is pinned when it + * is added. + */ +class AppliedMigrationImmutabilityTest { + + private static final Path MIGRATIONS = Path.of("src/main/resources/db/migration"); + private static final Path MANIFEST = Path.of("src/test/resources/db/applied-migrations.sha256"); + + @Test + void appliedMigrationsKeepTheBytesTheyWereAppliedWith() throws IOException { + // given + Map pinned = pinnedChecksums(); + + // when + Map actual = currentChecksums(); + + // then + assertThat(actual) + .as("an applied migration changed; add a new version instead of editing it") + .containsAllEntriesOf(pinned); + } + + @Test + void everyVersionedMigrationIsPinned() throws IOException { + // given + Map pinned = pinnedChecksums(); + + // when + Map actual = currentChecksums(); + + // then + assertThat(pinned.keySet()) + .as("pin a new migration in %s when it is added", MANIFEST) + .containsAll(actual.keySet()); + } + + private static Map pinnedChecksums() throws IOException { + Map pinned = new TreeMap<>(); + for (String line : Files.readAllLines(MANIFEST, StandardCharsets.UTF_8)) { + if (line.isBlank() || line.startsWith("#")) { + continue; + } + String[] fields = line.trim().split("\\s+", 2); + pinned.put(fields[1], fields[0]); + } + return pinned; + } + + private static Map currentChecksums() throws IOException { + Map checksums = new TreeMap<>(); + try (Stream files = Files.walk(MIGRATIONS)) { + for (Path file : + files.filter(path -> path.getFileName().toString().matches("V\\d+__.+\\.sql")).toList()) { + checksums.put( + MIGRATIONS.relativize(file).toString().replace('\\', '/'), + sha256(Files.readString(file))); + } + } + return checksums; + } + + /** Line endings are normalized so a CRLF checkout does not read as an edited migration. */ + private static String sha256(String content) { + try { + byte[] normalized = content.replace("\r\n", "\n").getBytes(StandardCharsets.UTF_8); + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(normalized)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/FlywaySchemaPolicyTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/FlywaySchemaPolicyTest.java new file mode 100644 index 00000000..a0d6c3c9 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/FlywaySchemaPolicyTest.java @@ -0,0 +1,33 @@ +package dev.caskeleton.adapter.outbound.persistence.migration; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** Flyway owns schema change; production validates rather than migrating (design §31). */ +class FlywaySchemaPolicyTest { + + @Test + @DisplayName("ddl-auto values that mutate a deployed schema are refused") + void refusesSchemaMutatingDdlAuto() { + var policy = FlywaySchemaPolicy.standard(); + + assertThatThrownBy(() -> policy.requirePermittedDdlAuto("update")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Flyway owns schema change"); + policy.requirePermittedDdlAuto("validate"); + policy.requirePermittedDdlAuto("none"); + } + + @Test + @DisplayName("production validates rather than migrating at startup") + void productionValidatesOnly() { + var policy = FlywaySchemaPolicy.standard(); + + assertThat(policy.modeFor("prod")).isEqualTo(SchemaManagementMode.VALIDATE_ONLY); + assertThat(policy.modeFor("local")).isEqualTo(SchemaManagementMode.MIGRATE_ON_STARTUP); + assertThat(policy.modeFor("unknown-profile")).isEqualTo(SchemaManagementMode.VALIDATE_ONLY); + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/OutboxStorageMigrationSafetyTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/OutboxStorageMigrationSafetyTest.java deleted file mode 100644 index 64a724a7..00000000 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/OutboxStorageMigrationSafetyTest.java +++ /dev/null @@ -1,57 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.migration; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; -import org.junit.jupiter.api.Test; - -class OutboxStorageMigrationSafetyTest { - - private static final String V1 = "db/migration/jpa/outbox-storage/V1__initialize_or_adopt.sql"; - - @Test - void legacyFenceRunsOncePerStatementAndKeepsTheDrainPathOpen() throws IOException { - String migration = normalized(resource(V1)); - - assertThat(migration) - .contains( - "BEFORE INSERT OR UPDATE OR DELETE ON outbox_event FOR EACH STATEMENT EXECUTE FUNCTION" - + " fence_legacy_outbox_writer()"); - assertThat(migration).contains("control_state = 'DRAINING' AND TG_OP IN ('UPDATE', 'DELETE')"); - assertThat(migration) - .doesNotContain( - "BEFORE INSERT OR UPDATE OR DELETE ON outbox_event FOR EACH ROW EXECUTE FUNCTION" - + " fence_legacy_outbox_writer()"); - } - - @Test - void legacyCutoverDigestDoesNotMaterializeTheWholeOutbox() throws IOException { - String migration = normalized(resource(V1)); - - assertThat(migration).doesNotContain("string_agg("); - assertThat(migration).contains("sha256("); - assertThat(migration).contains("encode("); - } - - @Test - void eventLogDoesNotPretendToBePartitionManagedWithoutAPartitionLifecycle() throws IOException { - String migration = normalized(resource(V1)); - - assertThat(migration).doesNotContain("PARTITION BY RANGE"); - assertThat(migration).doesNotContain("PARTITION OF outbox_event_log_v2 DEFAULT"); - } - - private static String normalized(String value) { - return value.replaceAll("\\s+", " ").trim(); - } - - private static String resource(String name) throws IOException { - try (InputStream stream = - OutboxStorageMigrationSafetyTest.class.getClassLoader().getResourceAsStream(name)) { - assertThat(stream).as("missing migration resource %s", name).isNotNull(); - return new String(stream.readAllBytes(), StandardCharsets.UTF_8); - } - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/PostgreSqlConstraintMigrationSafetyTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/PostgreSqlConstraintMigrationSafetyTest.java index ec96f743..3cda350d 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/PostgreSqlConstraintMigrationSafetyTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/PostgreSqlConstraintMigrationSafetyTest.java @@ -9,41 +9,32 @@ import org.junit.jupiter.api.Test; class PostgreSqlConstraintMigrationSafetyTest { - private static final String V13 = - "db/migration/postgresql/V13__outbox_canonical_transport_compatibility.sql"; private static final String V14 = "db/migration/postgresql/V14__validate_outbox_canonical_constraints.sql"; + private static final String V16 = + "db/migration/postgresql/V16__outbox_canonical_hash_columns_varchar.sql"; @Test - void canonicalHashColumnsMatchTheJpaVarcharContract() throws IOException { - String migration = resource(V13); + void canonicalHashColumnsAreWidenedToTheJpaVarcharContract() throws IOException { + // given + String migration = resource(V16).replaceAll("\\s+", " "); - String normalized = migration.replaceAll("\\s+", " "); - for (String column : + // when + java.util.List unwidened = java.util.List.of( - "partition_key", - "schema_set_hash", - "envelope_sha256", - "envelope_schema_hash", - "payload_schema_hash")) { - assertThat(normalized) - .as("%s must validate as the String(length=64) mapping Hibernate sees", column) - .contains("ADD COLUMN " + column + " varchar(64)"); - } - assertThat(migration).doesNotMatch("(?s).*\\bchar\\s*\\(64\\).*"); - } + "partition_key", + "schema_set_hash", + "envelope_sha256", + "envelope_schema_hash", + "payload_schema_hash") + .stream() + .filter(column -> !migration.contains("ALTER COLUMN " + column + " TYPE varchar(64)")) + .toList(); - @Test - void additiveOutboxChecksAreIntroducedNotValid() throws IOException { - String migration = resource(V13); - - assertThat(count(migration, "ADD CONSTRAINT ck_outbox_event_")).isEqualTo(6); - assertThat(count(migration, "NOT VALID")) - .as( - "adding a validating CHECK to an adopted table scans every existing row while holding " - + "an ACCESS EXCLUSIVE lock; each additive V13 check must be introduced NOT VALID") - .isEqualTo(6); - assertThat(migration).doesNotContain("VALIDATE CONSTRAINT"); + // then + assertThat(unwidened) + .as("V13 created these as char(64); Hibernate validates String(length=64) as varchar") + .isEmpty(); } @Test @@ -52,8 +43,8 @@ class PostgreSqlConstraintMigrationSafetyTest { assertThat(count(migration, "VALIDATE CONSTRAINT ck_outbox_event_canonical_")) .as( - "validation belongs in the follow-up migration so V13 can add the checks without " - + "scanning every existing row under the stronger ALTER TABLE lock") + "V14 validates every canonical check: a no-op where V13 created them valid, and the " + + "step that closes them on a database repaired after running the NOT VALID V13") .isEqualTo(6); assertThat(migration).doesNotContain("ADD CONSTRAINT"); } diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/crypto/NotificationHmacDigesterTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/crypto/NotificationHmacDigesterTest.java deleted file mode 100644 index e0a6772b..00000000 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/crypto/NotificationHmacDigesterTest.java +++ /dev/null @@ -1,72 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.notification.crypto; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.util.List; -import org.junit.jupiter.api.Test; - -class NotificationHmacDigesterTest { - - @Test - void purposeAndLengthPrefixesSeparateAmbiguousTuplesAndOrdering() { - NotificationHmacDigester digester = - new NotificationHmacDigester(NotificationPayloadCryptoTest.InMemoryKeys.standard()); - - NotificationHmacDigester.Digest split = - digester.digest("intent-dedupe-v1", List.of("a", "bc"), "alias-key", "hmac-r2"); - NotificationHmacDigester.Digest joined = - digester.digest("intent-dedupe-v1", List.of("ab", "c"), "alias-key", "hmac-r2"); - NotificationHmacDigester.Digest reordered = - digester.digest("intent-dedupe-v1", List.of("bc", "a"), "alias-key", "hmac-r2"); - NotificationHmacDigester.Digest otherPurpose = - digester.digest("recipient-alias-v1", List.of("a", "bc"), "alias-key", "hmac-r2"); - - assertThat(split.value()).matches("[0-9a-f]{64}"); - assertThat(split.value()) - .isNotEqualTo(joined.value()) - .isNotEqualTo(reordered.value()) - .isNotEqualTo(otherPurpose.value()); - assertThat(split.toString()).doesNotContain(split.value()); - } - - @Test - void currentAndBoundedRetiringVersionsVerifyWhileUnknownAndOversizedSetsFailClosed() { - NotificationHmacDigester digester = - new NotificationHmacDigester(NotificationPayloadCryptoTest.InMemoryKeys.standard()); - NotificationHmacDigester.Digest retiring = - digester.digest( - "intent-dedupe-v1", List.of("tenant-42", "scope-42"), "alias-key", "hmac-r1"); - - assertThat(digester.verify(retiring, "intent-dedupe-v1", List.of("tenant-42", "scope-42"))) - .isTrue(); - assertThat(digester.verify(retiring, "recipient-alias-v1", List.of("tenant-42", "scope-42"))) - .isFalse(); - assertThat( - digester.verify( - new NotificationHmacDigester.Digest("alias-key", "hmac-r9", retiring.value()), - "intent-dedupe-v1", - List.of("tenant-42", "scope-42"))) - .isFalse(); - - NotificationKeyMaterialProvider oversized = - new NotificationKeyMaterialProvider() { - @Override - public NotificationKeyMaterialHandle acquire(String reference, String version) { - return NotificationKeyMaterialHandle.fromBytes( - reference, version, NotificationPayloadCryptoTest.InMemoryKeys.HMAC_R2); - } - - @Override - public List verificationVersions(String reference) { - return List.of("hmac-r1", "hmac-r2", "hmac-r3", "hmac-r4", "hmac-r5"); - } - }; - assertThatThrownBy( - () -> - new NotificationHmacDigester(oversized) - .verify(retiring, "intent-dedupe-v1", List.of("tenant-42", "scope-42"))) - .isInstanceOf(NotificationCryptoException.class) - .hasMessageContaining("bounded"); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/crypto/NotificationPayloadCryptoTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/crypto/NotificationPayloadCryptoTest.java deleted file mode 100644 index baf5ce73..00000000 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/crypto/NotificationPayloadCryptoTest.java +++ /dev/null @@ -1,215 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.notification.crypto; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.nio.charset.StandardCharsets; -import java.security.SecureRandom; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.atomic.AtomicReference; -import org.junit.jupiter.api.Test; - -class NotificationPayloadCryptoTest { - - @Test - void aes256GcmUsesFreshNonceExactMetadataAndContextBoundLengthPrefixedAad() { - InMemoryKeys keys = InMemoryKeys.standard(); - DirectAeadNotificationPayloadCrypto crypto = - new DirectAeadNotificationPayloadCrypto(keys, new SecureRandom()); - NotificationCiphertext.AadContext context = context("record-42", "parameters"); - byte[] plaintext = "recipient-secret-value".getBytes(StandardCharsets.UTF_8); - - NotificationCiphertext first = crypto.encrypt(plaintext, context, "payload-key", "payload-r2"); - NotificationCiphertext second = crypto.encrypt(plaintext, context, "payload-key", "payload-r2"); - - assertThat(first.algorithm()).isEqualTo("AES-256-GCM"); - assertThat(first.cryptoProfileVersion()).isEqualTo("notification-direct-aead-v1"); - assertThat(first.aadRevision()).isEqualTo("notification-aad-v1"); - assertThat(first.nonce()).hasSize(12).isNotEqualTo(second.nonce()); - assertThat(crypto.decrypt(first, context)).isEqualTo(plaintext); - assertThat(first.toString()) - .doesNotContain("recipient-secret-value") - .doesNotContain(Arrays.toString(InMemoryKeys.PAYLOAD_R2)); - } - - @Test - void tupleFieldSwapsCiphertextSwapsAndWrongKeyRevisionFailAuthenticationAndStayRedacted() { - InMemoryKeys keys = InMemoryKeys.standard(); - DirectAeadNotificationPayloadCrypto crypto = - new DirectAeadNotificationPayloadCrypto(keys, new SecureRandom()); - NotificationCiphertext.AadContext parameters = context("record-42", "parameters"); - NotificationCiphertext.AadContext recipient = context("record-43", "recipient"); - NotificationCiphertext encrypted = - crypto.encrypt( - "secret-A".getBytes(StandardCharsets.UTF_8), parameters, "payload-key", "payload-r2"); - NotificationCiphertext other = - crypto.encrypt( - "secret-B".getBytes(StandardCharsets.UTF_8), recipient, "payload-key", "payload-r2"); - - assertThatThrownBy(() -> crypto.decrypt(encrypted, recipient)) - .isInstanceOf(NotificationCryptoException.class) - .hasMessageContaining("authentication") - .hasMessageNotContaining("secret-A") - .hasMessageNotContaining("secret-B"); - NotificationCiphertext swapped = - new NotificationCiphertext( - encrypted.algorithm(), - encrypted.keyReference(), - encrypted.keyVersion(), - encrypted.cryptoProfileVersion(), - encrypted.aadRevision(), - other.nonce(), - other.ciphertext()); - assertThatThrownBy(() -> crypto.decrypt(swapped, parameters)) - .isInstanceOf(NotificationCryptoException.class) - .hasMessageContaining("authentication"); - NotificationCiphertext wrongVersion = - new NotificationCiphertext( - encrypted.algorithm(), - encrypted.keyReference(), - "payload-r1", - encrypted.cryptoProfileVersion(), - encrypted.aadRevision(), - encrypted.nonce(), - encrypted.ciphertext()); - assertThatThrownBy(() -> crypto.decrypt(wrongVersion, parameters)) - .isInstanceOf(NotificationCryptoException.class) - .hasMessageNotContaining(Arrays.toString(InMemoryKeys.PAYLOAD_R1)); - } - - @Test - void acquiredMutableKeyHandleWipesOnCloseAndRejectsUseAfterClose() { - AtomicReference borrowed = new AtomicReference<>(); - NotificationKeyMaterialHandle handle = - NotificationKeyMaterialHandle.fromBytes( - "payload-key", "payload-r2", InMemoryKeys.PAYLOAD_R2); - handle.readBytes( - bytes -> { - borrowed.set(bytes); - return null; - }); - - handle.close(); - - assertThat(borrowed.get()).containsOnly((byte) 0); - assertThatThrownBy(() -> handle.readBytes(bytes -> bytes.length)) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("closed"); - assertThat(handle.toString()).doesNotContain(Arrays.toString(InMemoryKeys.PAYLOAD_R2)); - } - - @Test - void notificationCiphertextCopiesNonceAndCiphertextConstructorInputsAndAccessors() { - byte[] nonce = new byte[12]; - byte[] ciphertext = new byte[17]; - nonce[0] = 1; - ciphertext[0] = 2; - - NotificationCiphertext value = ciphertext(nonce, ciphertext); - nonce[0] = 9; - ciphertext[0] = 8; - - assertThat(value.nonce()[0]).isEqualTo((byte) 1); - assertThat(value.ciphertext()[0]).isEqualTo((byte) 2); - - byte[] nonceAccessorValue = value.nonce(); - byte[] ciphertextAccessorValue = value.ciphertext(); - nonceAccessorValue[0] = 7; - ciphertextAccessorValue[0] = 6; - - assertThat(value.nonce()[0]).isEqualTo((byte) 1); - assertThat(value.ciphertext()[0]).isEqualTo((byte) 2); - } - - @Test - void notificationCiphertextUsesArrayContentForEqualityAndHashCode() { - NotificationCiphertext first = ciphertext(new byte[12], new byte[17]); - NotificationCiphertext equalCopy = ciphertext(new byte[12], new byte[17]); - - assertThat(first).isEqualTo(equalCopy).hasSameHashCodeAs(equalCopy); - } - - @Test - void notificationCiphertextToStringRedactsNonceAndCiphertextBytes() { - byte[] nonce = new byte[12]; - byte[] ciphertext = new byte[17]; - nonce[0] = 1; - ciphertext[0] = 2; - - String rendered = ciphertext(nonce, ciphertext).toString(); - - assertThat(rendered) - .contains("nonce=", "ciphertext=") - .doesNotContain(Arrays.toString(nonce), Arrays.toString(ciphertext)); - } - - private static NotificationCiphertext ciphertext(byte[] nonce, byte[] ciphertext) { - return new NotificationCiphertext( - "AES-256-GCM", - "payload-key", - "payload-r2", - "notification-direct-aead-v1", - "notification-aad-v1", - nonce, - ciphertext); - } - - private static NotificationCiphertext.AadContext context(String recordId, String purpose) { - return new NotificationCiphertext.AadContext( - "notification_intent", - recordId, - "intent-42", - Optional.of("delivery-42"), - Optional.of("attempt-42"), - purpose, - "provider-binding-r3", - "notification-direct-aead-v1"); - } - - static final class InMemoryKeys implements NotificationKeyMaterialProvider { - - static final byte[] PAYLOAD_R1 = "1".repeat(32).getBytes(StandardCharsets.US_ASCII); - static final byte[] PAYLOAD_R2 = "2".repeat(32).getBytes(StandardCharsets.US_ASCII); - static final byte[] HMAC_R1 = "3".repeat(32).getBytes(StandardCharsets.US_ASCII); - static final byte[] HMAC_R2 = "4".repeat(32).getBytes(StandardCharsets.US_ASCII); - - private final Map keys; - private final Map> verificationVersions; - - private InMemoryKeys(Map keys, Map> verificationVersions) { - this.keys = keys; - this.verificationVersions = verificationVersions; - } - - static InMemoryKeys standard() { - return new InMemoryKeys( - Map.of( - "payload-key:payload-r1", - PAYLOAD_R1, - "payload-key:payload-r2", - PAYLOAD_R2, - "alias-key:hmac-r1", - HMAC_R1, - "alias-key:hmac-r2", - HMAC_R2), - Map.of("alias-key", List.of("hmac-r2", "hmac-r1"))); - } - - @Override - public NotificationKeyMaterialHandle acquire(String keyReference, String keyVersion) { - byte[] key = keys.get(keyReference + ":" + keyVersion); - if (key == null) { - throw new NotificationCryptoException("notification key revision is unavailable"); - } - return NotificationKeyMaterialHandle.fromBytes(keyReference, keyVersion, key); - } - - @Override - public List verificationVersions(String keyReference) { - return verificationVersions.getOrDefault(keyReference, List.of()); - } - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/AdminOperationResultPayloadCodecTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/AdminOperationResultPayloadCodecTest.java new file mode 100644 index 00000000..b7626610 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/platform/AdminOperationResultPayloadCodecTest.java @@ -0,0 +1,29 @@ +package dev.caskeleton.adapter.outbound.persistence.notification.platform; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.application.notification.platform.admin.AdminOperationResult; +import java.util.List; +import java.util.Optional; +import org.junit.jupiter.api.Test; + +class AdminOperationResultPayloadCodecTest { + + private final AdminOperationResultPayloadCodec codec = new AdminOperationResultPayloadCodec(); + + @Test + void aPayloadReadBackFromJsonbDecodesToTheStoredResult() { + // given + AdminOperationResult stored = + new AdminOperationResult( + "op-1", false, 2, Optional.empty(), Optional.empty(), Optional.empty(), List.of("OK")); + // PostgreSQL jsonb re-renders the document with a space after every ':' and ','. + String jsonbRendered = codec.encode(stored).replace("\":", "\": ").replace(",\"", ", \""); + + // when + AdminOperationResult decoded = codec.decode(jsonbRendered); + + // then + assertThat(decoded).isEqualTo(stored); + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/observation/JpaObservabilityContractTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/observation/JpaObservabilityContractTest.java index 59d8f72e..bc333d84 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/observation/JpaObservabilityContractTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/observation/JpaObservabilityContractTest.java @@ -6,16 +6,12 @@ import dev.caskeleton.adapter.outbound.persistence.api.PersistenceOperationName; import dev.caskeleton.adapter.outbound.persistence.api.error.ConstraintCode; import dev.caskeleton.adapter.outbound.persistence.api.error.ConstraintViolationDetails; import dev.caskeleton.adapter.outbound.persistence.api.error.JpaFailureContext; -import dev.caskeleton.adapter.outbound.persistence.api.error.SerializationFailureException; import dev.caskeleton.adapter.outbound.persistence.api.error.UniqueConstraintViolationException; import dev.caskeleton.adapter.outbound.persistence.api.query.QueryName; import dev.caskeleton.adapter.outbound.persistence.api.query.QueryScope; -import dev.caskeleton.adapter.outbound.persistence.api.transaction.RetryDecision; -import dev.caskeleton.adapter.outbound.persistence.api.transaction.TransactionAttempt; import io.micrometer.core.instrument.Tag; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.time.Duration; -import java.time.Instant; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -73,71 +69,6 @@ class JpaObservabilityContractTest { .isEqualTo(2_000.0d); } - @Test - @DisplayName("completion unknown gets its own counter, not the general failure counter") - void completionUnknownHasItsOwnCounter() { - var observation = new JpaTransactionObservation(registry, "orders"); - - observation.recordCompletionUnknown(OPERATION); - - assertThat(registry.find(JpaTransactionObservation.COMPLETION_UNKNOWN_METER).counter().count()) - .isEqualTo(1.0d); - assertThat(registry.find(JpaTransactionObservation.ROLLBACK_METER).counter()).isNull(); - } - - @Test - @DisplayName("a rollback records both duration and the rollback counter") - void rollbackRecordsDurationAndCounter() { - var observation = new JpaTransactionObservation(registry, "orders"); - - observation.recordRolledBack( - OPERATION, - Duration.ofMillis(12), - new SerializationFailureException( - JpaFailureContext.retryable(OPERATION, "40001", 1, Duration.ZERO, null))); - - assertThat(registry.find(JpaTransactionObservation.ROLLBACK_METER).counter().count()) - .isEqualTo(1.0d); - assertThat(registry.find(JpaTransactionObservation.DURATION_METER).timer().count()) - .isEqualTo(1L); - } - - @Test - @DisplayName("a retried attempt is a metric, not a log line") - void retryAttemptIsAMetric() { - var observation = new JpaRetryObservation(registry, "orders"); - var failure = - new SerializationFailureException( - JpaFailureContext.retryable(OPERATION, "40001", 1, Duration.ZERO, null)); - - observation.onAttemptFailed( - OPERATION, - new TransactionAttempt(1, Instant.EPOCH), - failure, - RetryDecision.retry(Duration.ofMillis(10))); - observation.onSucceeded(OPERATION, 2); - - assertThat(registry.find(JpaRetryObservation.ATTEMPT_METER).counter().count()).isEqualTo(1.0d); - assertThat(registry.find(JpaRetryObservation.ATTEMPTS_PER_OPERATION_METER).summary().max()) - .isEqualTo(2.0d); - assertThat(registry.find(JpaRetryObservation.EXHAUSTED_METER).counter()).isNull(); - } - - @Test - @DisplayName("giving up increments the exhausted counter") - void givingUpIncrementsExhausted() { - var observation = new JpaRetryObservation(registry, "orders"); - - observation.onGaveUp( - OPERATION, - 3, - new SerializationFailureException( - JpaFailureContext.retryable(OPERATION, "40001", 3, Duration.ZERO, null))); - - assertThat(registry.find(JpaRetryObservation.EXHAUSTED_METER).counter().count()) - .isEqualTo(1.0d); - } - private static UniqueConstraintViolationException uniqueViolation() { return new UniqueConstraintViolationException( JpaFailureContext.terminal(OPERATION, "23505", 1, Duration.ZERO, null), diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/OutboxStoreAdapterTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/OutboxStoreAdapterTest.java index 68f40d8e..1d9f544c 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/OutboxStoreAdapterTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/OutboxStoreAdapterTest.java @@ -7,20 +7,21 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import dev.caskeleton.adapter.outbound.persistence.outbox.entity.OutboxEventEntity; import dev.caskeleton.application.outbox.CanonicalClaimedOutboxEvent; -import dev.caskeleton.application.outbox.ClaimedOutboxEvent; import dev.caskeleton.application.outbox.NewOutboxEvent; +import dev.caskeleton.application.outbox.OutboxCompletion; import dev.caskeleton.application.outbox.OutboxEvent; import dev.caskeleton.application.outbox.OutboxEventStatus; +import dev.caskeleton.application.outbox.OutboxLease; import java.time.Duration; import java.time.Instant; import java.util.List; import java.util.Map; -import java.util.Optional; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -62,6 +63,24 @@ class OutboxStoreAdapterTest { // ---- helper ---- + private static final String OWNER = "relay-1"; + + private static OutboxLease lease(String eventId) { + return new OutboxLease( + new OutboxEvent( + eventId, + "UserCreated", + "agg-1", + "{}", + NOW, + "corr-1", + "idem-1", + OutboxEventStatus.IN_FLIGHT, + 1), + OWNER, + 1); + } + private static NewOutboxEvent newEvent(String eventId) { return new NewOutboxEvent(eventId, "UserCreated", "agg-1", "{}", NOW, "corr-1", "idem-1"); } @@ -144,17 +163,17 @@ class OutboxStoreAdapterTest { .isInstanceOf(IllegalStateException.class) .hasMessageContaining("append") .hasMessageContaining("active caller transaction"); - assertThatThrownBy(() -> adapter.claimBatch(1, NOW, IN_FLIGHT_TIMEOUT)) + assertThatThrownBy(() -> adapter.claimBatch(OWNER, 1, NOW, IN_FLIGHT_TIMEOUT)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("claimBatch") .hasMessageContaining("active caller transaction"); - assertThatThrownBy(() -> adapter.markPublished("evt-guard")) + assertThatThrownBy(() -> adapter.markPublished(lease("evt-guard"))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("markPublished"); - assertThatThrownBy(() -> adapter.markFailed("evt-guard", NOW.plusSeconds(1))) + assertThatThrownBy(() -> adapter.markFailed(lease("evt-guard"), NOW.plusSeconds(1))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("markFailed"); - assertThatThrownBy(() -> adapter.markDead("evt-guard")) + assertThatThrownBy(() -> adapter.markDead(lease("evt-guard"))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("markDead"); } @@ -164,31 +183,52 @@ class OutboxStoreAdapterTest { OutboxEventEntity entity = pendingEntity("evt-002"); when(claimRepo.claimEligible(eq(NOW), eq(2))).thenReturn(List.of(entity)); - List claimed = adapter.claimBatch(2, NOW, IN_FLIGHT_TIMEOUT); + List claimed = adapter.claimBatch(OWNER, 2, NOW, IN_FLIGHT_TIMEOUT); - // status and attemptCount updated on entity + // status, attemptCount and the lease updated on the locked entity assertThat(entity.getStatus()).isEqualTo("IN_FLIGHT"); assertThat(entity.getAttemptCount()).isEqualTo(1); assertThat(entity.getNextAttemptAt()).isEqualTo(NOW.plus(IN_FLIGHT_TIMEOUT)); + assertThat(entity.getLeaseOwner()).isEqualTo(OWNER); + assertThat(entity.getLeaseToken()).isEqualTo(1); + assertThat(claimed.get(0).token()).isEqualTo(1); // returned OutboxEvent reflects post-transition state assertThat(claimed).hasSize(1); - OutboxEvent result = (OutboxEvent) claimed.get(0); + OutboxEvent result = (OutboxEvent) claimed.get(0).event(); assertThat(result.eventId()).isEqualTo("evt-002"); assertThat(result.status()).isEqualTo(OutboxEventStatus.IN_FLIGHT); assertThat(result.attemptCount()).isEqualTo(1); } + @Test + void reclaimTakesTheRowOverWithTheNextToken() { + // given + OutboxEventEntity orphan = pendingEntity("evt-orphan"); + orphan.setStatus("IN_FLIGHT"); + orphan.setLeaseOwner("stalled-relay"); + orphan.setLeaseToken(4); + when(claimRepo.claimEligible(eq(NOW), eq(1))).thenReturn(List.of(orphan)); + + // when + OutboxLease lease = adapter.claimBatch(OWNER, 1, NOW, IN_FLIGHT_TIMEOUT).getFirst(); + + // then + assertThat( + List.of(lease.owner(), lease.token(), orphan.getLeaseOwner(), orphan.getLeaseToken())) + .containsExactly(OWNER, 5L, OWNER, 5L); + } + @Test void claimBatchMapsCompleteCanonicalMetadataToCanonicalClaim() { OutboxEventEntity entity = canonicalPendingEntity("01994e11-4d88-7000-8000-000000000001"); when(claimRepo.claimEligible(eq(NOW), eq(2))).thenReturn(List.of(entity)); - List claimed = adapter.claimBatch(2, NOW, IN_FLIGHT_TIMEOUT); + List claimed = adapter.claimBatch(OWNER, 2, NOW, IN_FLIGHT_TIMEOUT); assertThat(claimed).hasSize(1); - assertThat(claimed.getFirst()).isInstanceOf(CanonicalClaimedOutboxEvent.class); - CanonicalClaimedOutboxEvent result = (CanonicalClaimedOutboxEvent) claimed.getFirst(); + assertThat(claimed.getFirst().event()).isInstanceOf(CanonicalClaimedOutboxEvent.class); + CanonicalClaimedOutboxEvent result = (CanonicalClaimedOutboxEvent) claimed.getFirst().event(); assertThat(result.event().eventId().value()).isEqualTo("01994e11-4d88-7000-8000-000000000001"); assertThat(result.event().contractId().value()).isEqualTo("portfolio.worklog.reserved"); assertThat(result.event().aggregate().tenantScope()).isEqualTo("tenant-a"); @@ -207,7 +247,7 @@ class OutboxStoreAdapterTest { entity.setEnvelopeVersion(1); when(claimRepo.claimEligible(eq(NOW), eq(1))).thenReturn(List.of(entity)); - assertThatThrownBy(() -> adapter.claimBatch(1, NOW, IN_FLIGHT_TIMEOUT)) + assertThatThrownBy(() -> adapter.claimBatch(OWNER, 1, NOW, IN_FLIGHT_TIMEOUT)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("partial canonical") .hasMessageContaining("partial-canonical"); @@ -217,7 +257,7 @@ class OutboxStoreAdapterTest { void claimBatchReturnsEmptyWhenRepoReturnsNothing() { when(claimRepo.claimEligible(any(), anyInt())).thenReturn(List.of()); - assertThat(adapter.claimBatch(5, NOW, IN_FLIGHT_TIMEOUT)).isEmpty(); + assertThat(adapter.claimBatch(OWNER, 5, NOW, IN_FLIGHT_TIMEOUT)).isEmpty(); } /** @@ -246,54 +286,52 @@ class OutboxStoreAdapterTest { when(claimRepo.claimEligible(eq(NOW), eq(10))).thenReturn(List.of(head, tail)); - List claimed = adapter.claimBatch(10, NOW, IN_FLIGHT_TIMEOUT); + List claimed = adapter.claimBatch(OWNER, 10, NOW, IN_FLIGHT_TIMEOUT); // Adapter must return both rows — no in-memory FIFO filtering assertThat(claimed) .hasSize(2) - .extracting(ClaimedOutboxEvent::eventId) + .extracting(OutboxLease::eventId) .containsExactly("evt-head", "evt-tail"); } - // ---- markPublished ---- + // ---- completions: one conditional UPDATE under the lease ---- @Test - void markPublishedUpdatesStatusToPublished() { - OutboxEventEntity entity = pendingEntity("evt-003"); - entity.setStatus("IN_FLIGHT"); - when(repo.findById("evt-003")).thenReturn(Optional.of(entity)); + void markPublishedCompletesOnlyUnderTheLease() { + when(repo.completeLease("evt-003", OWNER, 1, "PUBLISHED")).thenReturn(1); - adapter.markPublished("evt-003"); - - assertThat(entity.getStatus()).isEqualTo("PUBLISHED"); + assertThat(adapter.markPublished(lease("evt-003"))).isEqualTo(OutboxCompletion.APPLIED); } - // ---- markFailed ---- - @Test - void markFailedSetsFailedStatusAndNextAttemptAt() { - OutboxEventEntity entity = pendingEntity("evt-004"); - entity.setStatus("IN_FLIGHT"); - when(repo.findById("evt-004")).thenReturn(Optional.of(entity)); + void markFailedCompletesOnlyUnderTheLeaseAndSchedulesTheRetry() { Instant retryAt = NOW.plus(Duration.ofSeconds(30)); + when(repo.failLease("evt-004", OWNER, 1, retryAt)).thenReturn(1); - adapter.markFailed("evt-004", retryAt); - - assertThat(entity.getStatus()).isEqualTo("FAILED"); - assertThat(entity.getNextAttemptAt()).isEqualTo(retryAt); + assertThat(adapter.markFailed(lease("evt-004"), retryAt)).isEqualTo(OutboxCompletion.APPLIED); } - // ---- markDead ---- - @Test - void markDeadSetsDeadStatus() { - OutboxEventEntity entity = pendingEntity("evt-005"); - entity.setStatus("IN_FLIGHT"); - when(repo.findById("evt-005")).thenReturn(Optional.of(entity)); + void markDeadCompletesOnlyUnderTheLease() { + when(repo.completeLease("evt-005", OWNER, 1, "DEAD")).thenReturn(1); - adapter.markDead("evt-005"); + assertThat(adapter.markDead(lease("evt-005"))).isEqualTo(OutboxCompletion.APPLIED); + } - assertThat(entity.getStatus()).isEqualTo("DEAD"); + /** + * Zero rows means the lease no longer holds the row — another relay reclaimed it after the + * in-flight timeout, or it is already complete. That relay owns the row, so this is a result, not + * an error, and nothing is loaded and overwritten. + */ + @Test + void aCompletionThatMatchesNoRowIsStale() { + when(repo.completeLease("evt-stale", OWNER, 1, "PUBLISHED")).thenReturn(0); + + OutboxCompletion completion = adapter.markPublished(lease("evt-stale")); + + assertThat(completion).isEqualTo(OutboxCompletion.STALE); + verify(repo, never()).findById(any()); } // ---- countByStatus ---- @@ -336,51 +374,4 @@ class OutboxStoreAdapterTest { assertThat(adapter.oldestUnpublishedAgeSecondsByEventType(NOW)).isEmpty(); } - - // ---- missing-entity guard (fail-closed consistency) ---- - - /** - * When the outbox row is not found during markPublished, the adapter must throw {@link - * IllegalStateException} with the eventId in the message instead of silently doing nothing. A - * silent no-op leaves the row IN_FLIGHT forever, blocking the aggregate's FIFO queue with no - * error observable by the relay. - */ - @Test - void markPublishedThrowsWhenEventIdNotFound() { - when(repo.findById("missing-evt")).thenReturn(Optional.empty()); - - assertThatThrownBy(() -> adapter.markPublished("missing-evt")) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("missing-evt"); - } - - /** - * When the outbox row is not found during markFailed, the adapter must throw {@link - * IllegalStateException} with the eventId in the message. A silent no-op would leave the relay - * believing a retry is scheduled while the row remains IN_FLIGHT, blocking the aggregate queue - * and producing no error log. - */ - @Test - void markFailedThrowsWhenEventIdNotFound() { - when(repo.findById("missing-evt")).thenReturn(Optional.empty()); - Instant retryAt = NOW.plus(Duration.ofSeconds(30)); - - assertThatThrownBy(() -> adapter.markFailed("missing-evt", retryAt)) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("missing-evt"); - } - - /** - * When the outbox row is not found during markDead, the adapter must throw {@link - * IllegalStateException} with the eventId in the message. A silent no-op would leave the row - * IN_FLIGHT instead of DEAD, preventing runbook-level visibility and manual resolution. - */ - @Test - void markDeadThrowsWhenEventIdNotFound() { - when(repo.findById("missing-evt")).thenReturn(Optional.empty()); - - assertThatThrownBy(() -> adapter.markDead("missing-evt")) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("missing-evt"); - } } diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/OutboxMasterSwitchWiringContractTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/OutboxSwitchWiringContractTest.java similarity index 67% rename from src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/OutboxMasterSwitchWiringContractTest.java rename to src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/OutboxSwitchWiringContractTest.java index 90c3a4a7..06537afa 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/OutboxMasterSwitchWiringContractTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/outbox/OutboxSwitchWiringContractTest.java @@ -7,19 +7,21 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.core.annotation.AnnotatedElementUtils; /** Pins the structural outbox-off contract at the JPA adapter boundary. */ -class OutboxMasterSwitchWiringContractTest { +class OutboxSwitchWiringContractTest { @Test - void legacyStoreAndReaperRequireTheOutboxMasterSwitch() { - assertOutboxMasterSwitch(OutboxStoreAdapter.class); - assertOutboxMasterSwitch(OutboxReaper.class); + void legacyStoreAndReaperRequireTheOutboxSwitch() { + assertOutboxSwitch(OutboxStoreAdapter.class); + assertOutboxSwitch(OutboxReaper.class); } - private static void assertOutboxMasterSwitch(Class type) { + private static void assertOutboxSwitch(Class type) { ConditionalOnProperty condition = AnnotatedElementUtils.findMergedAnnotation(type, ConditionalOnProperty.class); - assertThat(condition).as(type.getSimpleName() + " must be outbox-master-gated").isNotNull(); + assertThat(condition) + .as(type.getSimpleName() + " must be gated by the outbox switch") + .isNotNull(); assertThat(condition.prefix()).isEqualTo("ca-skeleton.outbox"); assertThat(condition.name()).containsExactly("enabled"); assertThat(condition.havingValue()).isEqualTo("true"); diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/postgresql/PostgreSqlLocalTimeoutConfigurerTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/postgresql/PostgreSqlLocalTimeoutConfigurerTest.java deleted file mode 100644 index ab1792e6..00000000 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/postgresql/PostgreSqlLocalTimeoutConfigurerTest.java +++ /dev/null @@ -1,47 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.postgresql; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.adapter.outbound.persistence.transaction.EffectiveTransactionTimeouts; -import java.lang.reflect.Proxy; -import java.time.Duration; -import java.util.ArrayList; -import java.util.List; -import org.junit.jupiter.api.Test; -import org.springframework.jdbc.core.JdbcOperations; - -class PostgreSqlLocalTimeoutConfigurerTest { - - @Test - void usesParameterizedTransactionLocalSetConfigCalls() { - List invocations = new ArrayList<>(); - JdbcOperations jdbcOperations = - (JdbcOperations) - Proxy.newProxyInstance( - JdbcOperations.class.getClassLoader(), - new Class[] {JdbcOperations.class}, - (proxy, method, arguments) -> { - if (method.getName().equals("queryForObject")) { - Object[] parameters = (Object[]) arguments[2]; - invocations.add(new Invocation((String) arguments[0], (String) parameters[0])); - return parameters[0]; - } - throw new UnsupportedOperationException(method.getName()); - }); - PostgreSqlLocalTimeoutConfigurer configurer = - new PostgreSqlLocalTimeoutConfigurer(jdbcOperations); - - configurer.apply( - new EffectiveTransactionTimeouts( - Duration.ofMillis(2_500), Duration.ofMillis(750), Duration.ofSeconds(5))); - - assertThat(invocations) - .containsExactly( - new Invocation("select set_config('statement_timeout', ?, true)", "2500ms"), - new Invocation("select set_config('lock_timeout', ?, true)", "750ms"), - new Invocation( - "select set_config('idle_in_transaction_session_timeout', ?, true)", "5000ms")); - } - - private record Invocation(String sql, String value) {} -} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/postgresql/PostgreSqlVendorFailureTranslatorRegistrationTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/postgresql/PostgreSqlVendorFailureTranslatorRegistrationTest.java deleted file mode 100644 index f56a0ea4..00000000 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/postgresql/PostgreSqlVendorFailureTranslatorRegistrationTest.java +++ /dev/null @@ -1,130 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.postgresql; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.adapter.outbound.persistence.api.PersistenceOperationName; -import dev.caskeleton.adapter.outbound.persistence.api.error.ConstraintCode; -import dev.caskeleton.adapter.outbound.persistence.api.error.FailureCategory; -import dev.caskeleton.adapter.outbound.persistence.api.error.JpaPersistenceException; -import dev.caskeleton.adapter.outbound.persistence.api.error.UniqueConstraintViolationException; -import dev.caskeleton.adapter.outbound.persistence.api.error.VendorFailureTranslator; -import dev.caskeleton.adapter.outbound.persistence.postgresql.constraint.PostgreSqlConstraintCatalog; -import dev.caskeleton.adapter.outbound.persistence.postgresql.error.ConstraintCatalog; -import dev.caskeleton.adapter.outbound.persistence.postgresql.error.PostgreSqlExceptionTranslator; -import java.sql.SQLException; -import java.time.Duration; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.NoSuchBeanDefinitionException; -import org.springframework.beans.factory.ObjectProvider; - -/** - * The vendor composition supplies the translator the transaction executor classifies with. - * - *

Nothing registered a {@link VendorFailureTranslator}, so every executor was built with the - * catalog-free chain, whose vendor stage returns failures unchanged. A 40001 or 40P01 stayed a raw - * {@code DataAccessException}, missed the retry coordinator's {@code JpaPersistenceException} - * catch, and was never retried — while {@code PostgreSqlExceptionTranslator}, the class that knows - * how to classify both, had no production caller at all. - */ -class PostgreSqlVendorFailureTranslatorRegistrationTest { - - private static final PersistenceOperationName OPERATION = - new PersistenceOperationName("order.write"); - - private static final ConstraintCode ACTIVE_EMAIL = new ConstraintCode("user.active-email.unique"); - - private final PostgreSqlPersistenceConfig configuration = new PostgreSqlPersistenceConfig(); - - @Test - @DisplayName("a serialization failure is classified as retryable contention") - void aSerializationFailureIsClassifiedAsRetryable() { - JpaPersistenceException classified = - translate(absent(), new SQLException("could not serialize access", "40001")); - - assertThat(classified.category()).isEqualTo(FailureCategory.SERIALIZATION_FAILURE); - assertThat(classified.retryable()) - .as("the coordinator retries what is marked retryable, and nothing else") - .isTrue(); - } - - @Test - @DisplayName("a deadlock is classified as retryable contention") - void aDeadlockIsClassifiedAsRetryable() { - JpaPersistenceException classified = - translate(absent(), new SQLException("deadlock detected", "40P01")); - - assertThat(classified.category()).isEqualTo(FailureCategory.DEADLOCK); - assertThat(classified.retryable()).isTrue(); - } - - @Test - @DisplayName("a unique violation is classified and stays terminal") - void aUniqueViolationStaysTerminal() { - JpaPersistenceException classified = - translate(absent(), new SQLException("duplicate key", "23505")); - - assertThat(classified).isInstanceOf(UniqueConstraintViolationException.class); - assertThat(classified.retryable()) - .as("retrying a duplicate key writes the row a second time") - .isFalse(); - } - - /** - * A registered catalog is taken, and its absence is not an error. - * - *

The catalog is optional on purpose: an empty one still classifies the SQLSTATE, which is - * what retry depends on, and resolves every constraint name to the unknown code — the right - * answer for a constraint the application never registered. Requiring one would make a relational - * deployment fail to start over an error-reporting detail. - */ - @Test - @DisplayName("the application's own constraint catalog is taken when it registered one") - void theApplicationsCatalogIsTakenWhenPresent() { - ConstraintCatalog registered = - new PostgreSqlConstraintCatalog(Map.of("ux_user_active_email", ACTIVE_EMAIL)); - - assertThat(configuration.postgreSqlVendorFailureTranslator(available(registered))) - .isInstanceOf(PostgreSqlExceptionTranslator.class); - assertThat(configuration.postgreSqlVendorFailureTranslator(absent())) - .isInstanceOf(PostgreSqlExceptionTranslator.class); - } - - private JpaPersistenceException translate( - ObjectProvider catalogs, Throwable failure) { - return configuration - .postgreSqlVendorFailureTranslator(catalogs) - .translate(failure, OPERATION, 1, Duration.ZERO, null); - } - - /** An application that registered no catalog of its own. */ - private static ObjectProvider absent() { - return provider(List.of()); - } - - /** An application that registered exactly one. */ - private static ObjectProvider available(ConstraintCatalog catalog) { - return provider(List.of(catalog)); - } - - private static ObjectProvider provider(List candidates) { - return new ObjectProvider<>() { - - @Override - public ConstraintCatalog getObject() { - if (candidates.isEmpty()) { - throw new NoSuchBeanDefinitionException(ConstraintCatalog.class); - } - return candidates.get(0); - } - - @Override - public Iterator iterator() { - return candidates.iterator(); - } - }; - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/OwnerSafeIdempotencyPreconditionTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/OwnerSafeIdempotencyPreconditionTest.java index 02427be4..0f9b83f1 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/OwnerSafeIdempotencyPreconditionTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/postgresql/idempotency/OwnerSafeIdempotencyPreconditionTest.java @@ -9,9 +9,9 @@ import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import dev.caskeleton.application.idempotency.IdempotencyClaimRequest; +import dev.caskeleton.application.idempotency.IdempotencyScopeDigest; import dev.caskeleton.application.idempotency.RequestFingerprint; -import dev.caskeleton.application.idempotency.v2.IdempotencyClaimRequest; -import dev.caskeleton.application.idempotency.v2.IdempotencyScopeDigest; import dev.caskeleton.application.transaction.OperationId; import java.nio.charset.StandardCharsets; import java.sql.Connection; @@ -109,7 +109,7 @@ class OwnerSafeIdempotencyPreconditionTest { return new IdempotencyClaimRequest( SCOPE, RequestFingerprint.ofSha256("request".getBytes(StandardCharsets.UTF_8)), - new dev.caskeleton.application.idempotency.v2.IdempotencyClaimAttempt( + new dev.caskeleton.application.idempotency.IdempotencyClaimAttempt( "c".repeat(64), new OperationId("claim-precondition")), Duration.ofSeconds(30), Duration.ofHours(1), diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/postgresql/inbox/PostgreSqlInboxTransitionDigestTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/postgresql/inbox/PostgreSqlInboxTransitionDigestTest.java deleted file mode 100644 index 8aa508ca..00000000 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/postgresql/inbox/PostgreSqlInboxTransitionDigestTest.java +++ /dev/null @@ -1,14 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.postgresql.inbox; - -import static org.assertj.core.api.Assertions.assertThat; - -import org.junit.jupiter.api.Test; - -class PostgreSqlInboxTransitionDigestTest { - - @Test - void lengthFramingKeepsDelimiterContainingFieldsUnambiguous() { - assertThat(PostgreSqlSameStoreInboxAdapter.digestFields("a|b", "c")) - .isNotEqualTo(PostgreSqlSameStoreInboxAdapter.digestFields("a", "b|c")); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/postgresql/lock/PostgreSqlLockOptionsTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/postgresql/lock/PostgreSqlLockOptionsTest.java index e1839ffd..ec031242 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/postgresql/lock/PostgreSqlLockOptionsTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/postgresql/lock/PostgreSqlLockOptionsTest.java @@ -8,7 +8,7 @@ import java.time.Duration; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -/** Plan Tasks 30-31 — lock intent and queue claims are explicit (design §21). */ +/** Plan Task 30 — lock intent is explicit (design §21). */ class PostgreSqlLockOptionsTest { @Test @@ -39,26 +39,4 @@ class PostgreSqlLockOptionsTest { LockModeType.PESSIMISTIC_WRITE, Duration.ofSeconds(2), true)) .isInstanceOf(IllegalArgumentException.class); } - - @Test - @DisplayName("a claim statement must skip locked rows and impose an order") - void claimStatementIsValidated() { - var queue = new WorkQueueName("outbox.delivery"); - - assertThatThrownBy( - () -> new WorkQueueDefinition(queue, "select id from outbox order by id for update")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("SKIP LOCKED"); - - assertThatThrownBy( - () -> new WorkQueueDefinition(queue, "select id from outbox for update skip locked")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("ORDER BY"); - - var valid = - new WorkQueueDefinition( - queue, - "select id from outbox order by priority, id limit :batchSize for update skip locked"); - assertThat(valid.name()).isEqualTo(queue); - } } diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/postgresql/outbox/PostgreSqlOutboxTransitionDigestTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/postgresql/outbox/PostgreSqlOutboxTransitionDigestTest.java deleted file mode 100644 index b7b43005..00000000 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/postgresql/outbox/PostgreSqlOutboxTransitionDigestTest.java +++ /dev/null @@ -1,14 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.postgresql.outbox; - -import static org.assertj.core.api.Assertions.assertThat; - -import org.junit.jupiter.api.Test; - -class PostgreSqlOutboxTransitionDigestTest { - - @Test - void lengthFramingKeepsDelimiterContainingFieldsUnambiguous() { - assertThat(PostgreSqlPollingDeliveryAdapter.digestFields("a|b", "c")) - .isNotEqualTo(PostgreSqlPollingDeliveryAdapter.digestFields("a", "b|c")); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/querydsl/QuerydslJpaSupportTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/querydsl/PredicatePolicyTest.java similarity index 98% rename from src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/querydsl/QuerydslJpaSupportTest.java rename to src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/querydsl/PredicatePolicyTest.java index 1b489597..0903a64c 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/querydsl/QuerydslJpaSupportTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/querydsl/PredicatePolicyTest.java @@ -9,7 +9,7 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; /** Plan Task 20 — a Querydsl collection query is bounded or it does not run (design §23.2). */ -class QuerydslJpaSupportTest { +class PredicatePolicyTest { @Test @DisplayName("a predicate-free collection query is refused") diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/startup/FlywayProdSafetyValidatorTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/FlywayProdSafetyValidatorTest.java similarity index 96% rename from src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/startup/FlywayProdSafetyValidatorTest.java rename to src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/FlywayProdSafetyValidatorTest.java index 70c8b0bd..5f87347c 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/startup/FlywayProdSafetyValidatorTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/FlywayProdSafetyValidatorTest.java @@ -1,7 +1,8 @@ -package dev.caskeleton.bootstrap.runtime.startup; +package dev.caskeleton.adapter.outbound.persistence.startup; import static org.assertj.core.api.Assertions.assertThat; +import dev.caskeleton.adapter.outbound.support.startup.ProfileMismatchException; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.assertj.AssertableApplicationContext; import org.springframework.boot.test.context.runner.ApplicationContextRunner; diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/HikariPoolConstraintValidatorTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/HikariPoolConstraintValidatorTest.java similarity index 87% rename from src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/HikariPoolConstraintValidatorTest.java rename to src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/HikariPoolConstraintValidatorTest.java index e2e549c9..948df969 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/HikariPoolConstraintValidatorTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/HikariPoolConstraintValidatorTest.java @@ -1,8 +1,8 @@ -package dev.caskeleton.bootstrap.runtime; +package dev.caskeleton.adapter.outbound.persistence.startup; import static org.assertj.core.api.Assertions.assertThat; -import dev.caskeleton.bootstrap.runtime.startup.StartupValidationException; +import dev.caskeleton.adapter.outbound.support.startup.StartupValidationException; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; @@ -21,6 +21,32 @@ class HikariPoolConstraintValidatorTest { // --- D2 / HIKARI-CFG-C1: connection-timeout >= 250 --- + @Test + void nonPositivePoolSizeFailsStartupNamingTheAppKey() { + runner + .withPropertyValues("spring.datasource.hikari.maximum-pool-size=0") + .run( + context -> { + assertThat(context).hasFailed(); + assertThat(context.getStartupFailure()) + .isInstanceOf(StartupValidationException.class) + .hasStackTraceContaining("APP_DATASOURCE_POOL_MAX_SIZE") + .hasStackTraceContaining(">= 1"); + }); + } + + @Test + void negativeMinimumIdleFailsStartupNamingTheAppKey() { + runner + .withPropertyValues("spring.datasource.hikari.minimum-idle=-1") + .run( + context -> { + assertThat(context).hasFailed(); + assertThat(context.getStartupFailure()) + .hasStackTraceContaining("APP_DATASOURCE_POOL_MIN_IDLE"); + }); + } + @Test void connectionTimeoutBelowMinimumFailsStartup() { runner diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaActivationEnvironmentPostProcessorTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaActivationEnvironmentPostProcessorTest.java new file mode 100644 index 00000000..49d8b974 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaActivationEnvironmentPostProcessorTest.java @@ -0,0 +1,113 @@ +package dev.caskeleton.adapter.outbound.persistence.startup; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.adapter.outbound.support.startup.ReadinessGroup; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.context.properties.bind.Bindable; +import org.springframework.boot.context.properties.bind.Binder; +import org.springframework.core.env.MapPropertySource; +import org.springframework.core.env.StandardEnvironment; + +class JpaActivationEnvironmentPostProcessorTest { + + private final JpaActivationEnvironmentPostProcessor processor = + new JpaActivationEnvironmentPostProcessor(); + + @Test + void offExcludesBootsRelationalAutoConfigurationsButNotTheSharedTransactionOne() { + // given + StandardEnvironment environment = + environment(Map.of("ca-skeleton.persistence-jpa.enabled", "false")); + + // when + processor.postProcessEnvironment(environment, new SpringApplication()); + + // then + assertThat(excluded(environment)) + .contains( + "org.springframework.boot.jdbc.autoconfigure.DataSourceAutoConfiguration", + "org.springframework.boot.jdbc.autoconfigure.DataSourceTransactionManagerAutoConfiguration", + "org.springframework.boot.jdbc.autoconfigure.JdbcTemplateAutoConfiguration", + "org.springframework.boot.jdbc.autoconfigure.health" + + ".DataSourceHealthContributorAutoConfiguration", + "org.springframework.boot.hibernate.autoconfigure.HibernateJpaAutoConfiguration", + "org.springframework.boot.data.jpa.autoconfigure.DataJpaRepositoriesAutoConfiguration", + "org.springframework.boot.flyway.autoconfigure.FlywayAutoConfiguration") + .doesNotContain( + "org.springframework.boot.transaction.autoconfigure.TransactionAutoConfiguration"); + } + + @Test + void offKeepsTheDeploymentsOwnExclusionsFirst() { + // given + StandardEnvironment environment = + environment( + Map.of( + "ca-skeleton.persistence-jpa.enabled", + "false", + JpaActivationEnvironmentPostProcessor.EXCLUDE, + "com.example.OneAutoConfiguration")); + + // when + processor.postProcessEnvironment(environment, new SpringApplication()); + + // then + assertThat(excluded(environment)) + .startsWith("com.example.OneAutoConfiguration") + .contains("org.springframework.boot.jdbc.autoconfigure.DataSourceAutoConfiguration"); + } + + @Test + void offLeavesTheDatabaseOutOfReadiness() { + // given + StandardEnvironment environment = + environment(Map.of("ca-skeleton.persistence-jpa.enabled", "false")); + + // when + processor.postProcessEnvironment(environment, new SpringApplication()); + + // then + assertThat(environment.getProperty(ReadinessGroup.INCLUDE_PROPERTY)).isNull(); + } + + @Test + void onByDefaultExcludesNothing() { + // given + StandardEnvironment environment = environment(Map.of()); + + // when + processor.postProcessEnvironment(environment, new SpringApplication()); + + // then + assertThat(excluded(environment)).isEmpty(); + } + + @Test + void onByDefaultAddsTheDatabaseToReadiness() { + // given + StandardEnvironment environment = environment(Map.of()); + + // when + processor.postProcessEnvironment(environment, new SpringApplication()); + + // then + assertThat(environment.getProperty(ReadinessGroup.INCLUDE_PROPERTY)) + .isEqualTo(JpaActivationEnvironmentPostProcessor.DB_CONTRIBUTOR); + } + + private static StandardEnvironment environment(Map properties) { + StandardEnvironment environment = new StandardEnvironment(); + environment.getPropertySources().addFirst(new MapPropertySource("test", properties)); + return environment; + } + + private static List excluded(StandardEnvironment environment) { + return Binder.get(environment) + .bind(JpaActivationEnvironmentPostProcessor.EXCLUDE, Bindable.listOf(String.class)) + .orElse(List.of()); + } +} diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/jpa/JpaDangerousConfigurationGuardTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaDangerousConfigurationGuardTest.java similarity index 98% rename from src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/jpa/JpaDangerousConfigurationGuardTest.java rename to src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaDangerousConfigurationGuardTest.java index 76e070cd..f589e5cb 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/jpa/JpaDangerousConfigurationGuardTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaDangerousConfigurationGuardTest.java @@ -1,4 +1,4 @@ -package dev.caskeleton.bootstrap.autoconfigure.jpa; +package dev.caskeleton.adapter.outbound.persistence.startup; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/jpa/JpaDataSourceProfileValidatorTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaDataSourceProfileValidatorTest.java similarity index 97% rename from src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/jpa/JpaDataSourceProfileValidatorTest.java rename to src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaDataSourceProfileValidatorTest.java index 9c562aa7..53a4d226 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/jpa/JpaDataSourceProfileValidatorTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaDataSourceProfileValidatorTest.java @@ -1,4 +1,4 @@ -package dev.caskeleton.bootstrap.autoconfigure.jpa; +package dev.caskeleton.adapter.outbound.persistence.startup; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/jpa/JpaPlatformAutoConfigurationTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaPlatformReportTest.java similarity index 80% rename from src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/jpa/JpaPlatformAutoConfigurationTest.java rename to src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaPlatformReportTest.java index 56d3a321..cd66c8bb 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/jpa/JpaPlatformAutoConfigurationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaPlatformReportTest.java @@ -1,28 +1,19 @@ -package dev.caskeleton.bootstrap.autoconfigure.jpa; +package dev.caskeleton.adapter.outbound.persistence.startup; import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.adapter.outbound.persistence.api.capability.CapabilitySupport; import dev.caskeleton.adapter.outbound.persistence.api.capability.JpaCapability; import dev.caskeleton.adapter.outbound.persistence.api.capability.SupportLevel; -import dev.caskeleton.adapter.outbound.persistence.hibernate.HibernateProviderPolicy; import dev.caskeleton.adapter.outbound.persistence.security.DatabasePrivilegeReport; -import dev.caskeleton.adapter.outbound.persistence.security.PostgreSqlRuntimeRoleVerifier; import java.util.List; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import org.springframework.mock.env.MockEnvironment; /** * Plan Task 52 — the platform report is sanitized and the capability list is honest (design §37). */ -class JpaPlatformAutoConfigurationTest { - - private final JpaPlatformAutoConfiguration configuration = - new JpaPlatformAutoConfiguration( - new MockEnvironment(), - new HibernateProviderPolicy("7.1.8.Final"), - new PostgreSqlRuntimeRoleVerifier()); +class JpaPlatformReportTest { @Test @DisplayName("the report carries no JDBC URL, username, password, or SQL") @@ -35,7 +26,7 @@ class JpaPlatformAutoConfigurationTest { "V6", true, new DatabasePrivilegeReport("app_runtime", "app, pg_catalog", false, false), - configuration.capabilities()); + JpaPlatformReport.platformCapabilities()); assertThat(report.toString()) .doesNotContain("jdbc:") @@ -56,7 +47,7 @@ class JpaPlatformAutoConfigurationTest { "V6", true, new DatabasePrivilegeReport("app_runtime", "app", true, false), - configuration.capabilities()); + JpaPlatformReport.platformCapabilities()); assertThat(report.runtimeRoleVerified()).isFalse(); assertThat(report.safe()).isFalse(); @@ -67,7 +58,13 @@ class JpaPlatformAutoConfigurationTest { void unavailablePrivilegeReportIsNotVerified() { var report = JpaPlatformReport.sanitized( - "unavailable", 0, "7.1.8.Final", null, true, null, configuration.capabilities()); + "unavailable", + 0, + "7.1.8.Final", + null, + true, + null, + JpaPlatformReport.platformCapabilities()); assertThat(report.runtimeRoleVerified()).isFalse(); assertThat(report.schemaVersion()).isEqualTo("unknown"); @@ -76,12 +73,12 @@ class JpaPlatformAutoConfigurationTest { @Test @DisplayName("only Stable capabilities are usable without a further opt-in") void onlyStableCapabilitiesAreUsableByDefault() { - List capabilities = configuration.capabilities(); + List capabilities = JpaPlatformReport.platformCapabilities(); assertThat(capabilities) .filteredOn(CapabilitySupport::usableByDefault) .extracting(CapabilitySupport::capability) - .contains(JpaCapability.TRANSACTION_RETRY, JpaCapability.SCHEMA_GATE) + .contains(JpaCapability.SCHEMA_GATE, JpaCapability.KEYSET_PAGINATION) .doesNotContain( JpaCapability.COMPLETION_EVIDENCE, JpaCapability.BATCH, @@ -94,7 +91,7 @@ class JpaPlatformAutoConfigurationTest { @Test @DisplayName("unassembled evidence, batch, and observability primitives are Advanced") void unassembledPlatformPrimitivesAreAdvanced() { - assertThat(configuration.capabilities()) + assertThat(JpaPlatformReport.platformCapabilities()) .filteredOn( capability -> capability.capability() == JpaCapability.COMPLETION_EVIDENCE @@ -106,7 +103,7 @@ class JpaPlatformAutoConfigurationTest { @Test @DisplayName("COPY, Envers, and the L2 cache are Advanced, never Stable") void optionalCapabilitiesAreAdvanced() { - assertThat(configuration.capabilities()) + assertThat(JpaPlatformReport.platformCapabilities()) .filteredOn( capability -> capability.capability() == JpaCapability.POSTGRESQL_COPY diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/jpa/JpaResolvedDataSourceValidationTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaResolvedDataSourceValidationTest.java similarity index 99% rename from src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/jpa/JpaResolvedDataSourceValidationTest.java rename to src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaResolvedDataSourceValidationTest.java index 5fb8f027..f5b0ade0 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/jpa/JpaResolvedDataSourceValidationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaResolvedDataSourceValidationTest.java @@ -1,4 +1,4 @@ -package dev.caskeleton.bootstrap.autoconfigure.jpa; +package dev.caskeleton.adapter.outbound.persistence.startup; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/JpaSchemaSafetyValidatorTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaSchemaSafetyValidatorTest.java similarity index 96% rename from src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/JpaSchemaSafetyValidatorTest.java rename to src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaSchemaSafetyValidatorTest.java index f60e33e6..74a6f756 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/JpaSchemaSafetyValidatorTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaSchemaSafetyValidatorTest.java @@ -1,8 +1,8 @@ -package dev.caskeleton.bootstrap.runtime; +package dev.caskeleton.adapter.outbound.persistence.startup; import static org.assertj.core.api.Assertions.assertThat; -import dev.caskeleton.bootstrap.runtime.startup.ProfileMismatchException; +import dev.caskeleton.adapter.outbound.support.startup.ProfileMismatchException; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.springframework.boot.test.context.runner.ApplicationContextRunner; diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/jpa/JpaPlatformRuntimeAutoConfigurationTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaStartupAutoConfigurationTest.java similarity index 63% rename from src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/jpa/JpaPlatformRuntimeAutoConfigurationTest.java rename to src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaStartupAutoConfigurationTest.java index 18f5ba39..6ef8d44f 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/jpa/JpaPlatformRuntimeAutoConfigurationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaStartupAutoConfigurationTest.java @@ -1,4 +1,4 @@ -package dev.caskeleton.bootstrap.autoconfigure.jpa; +package dev.caskeleton.adapter.outbound.persistence.startup; import static org.assertj.core.api.Assertions.assertThat; @@ -7,50 +7,77 @@ import dev.caskeleton.adapter.outbound.persistence.security.PostgreSqlRuntimeRol import java.lang.reflect.Proxy; import java.sql.Connection; import java.sql.DatabaseMetaData; -import java.time.Clock; import javax.sql.DataSource; +import org.flywaydb.core.Flyway; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.flyway.autoconfigure.FlywayMigrationStrategy; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.datasource.AbstractDataSource; -class JpaPlatformRuntimeAutoConfigurationTest { +/** The startup policy arrives with the module, and the module switch removes all of it. */ +class JpaStartupAutoConfigurationTest { private final ApplicationContextRunner runner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(JpaPlatformRuntimeAutoConfiguration.class)) - .withBean(Clock.class, Clock::systemUTC) + .withConfiguration(AutoConfigurations.of(JpaStartupAutoConfiguration.class)) .withBean(HibernateProviderPolicy.class, HibernateProviderPolicy::fromClasspath) - .withBean(PostgreSqlRuntimeRoleVerifier.class, PostgreSqlRuntimeRoleVerifier::new); + .withBean(PostgreSqlRuntimeRoleVerifier.class, PostgreSqlRuntimeRoleVerifier::new) + .withPropertyValues( + "spring.datasource.url=jdbc:postgresql://db.invalid:5432/app", + "spring.datasource.username=app", + "spring.datasource.driver-class-name=org.postgresql.Driver"); @Test - void applicationSafetyAndManagementBeansExistWhenAddonIsEnabled() { + void applicationSafetyAndManagementBeansExist() { runner .withUserConfiguration(DataSourceConfiguration.class) .withPropertyValues("spring.jpa.open-in-view=false") .run( - context -> - assertThat(context) - .hasSingleBean(JpaPlatformAutoConfiguration.class) - .hasSingleBean(JpaDangerousConfigurationGuard.class) - .hasSingleBean(JpaDataSourceProfileValidator.class) - .hasSingleBean(JpaPlatformEndpoint.class) - .hasSingleBean(JpaSafetySettings.class)); + context -> { + assertThat(context) + .hasNotFailed() + .hasSingleBean(JpaDangerousConfigurationGuard.class) + .hasSingleBean(JpaDataSourceProfileValidator.class) + .hasSingleBean(JpaPlatformEndpoint.class) + .hasSingleBean(JpaSafetySettings.class) + .hasSingleBean(OpenInViewSafetyValidator.class) + .hasSingleBean(JpaSchemaSafetyValidator.class) + .hasSingleBean(PostgreSqlTransportSecurityValidator.class) + .hasSingleBean(PersistenceVendorProdSafetyValidator.class) + .hasSingleBean(HikariPoolConstraintValidator.class) + .hasSingleBean(RequiredEnvironmentValidator.class) + .hasSingleBean(FlywayProdSafetyValidator.class); + assertThat(context.getBean("migrationStartupRunner")) + .isInstanceOf(MigrationStartupRunner.class); + }); } @Test - void addonSwitchTurnsOnlyApplicationSafetyAndManagementOff() { + void theModuleSwitchRemovesThePolicy() { runner .withUserConfiguration(DataSourceConfiguration.class) - .withPropertyValues("app.jpa-platform.addons-enabled=false") + .withPropertyValues("ca-skeleton.persistence-jpa.enabled=false") .run( context -> assertThat(context) - .doesNotHaveBean(JpaPlatformAutoConfiguration.class) .doesNotHaveBean(JpaDangerousConfigurationGuard.class) - .doesNotHaveBean(JpaPlatformEndpoint.class)); + .doesNotHaveBean(RequiredEnvironmentValidator.class) + .doesNotHaveBean("migrationStartupRunner")); + } + + @Test + void anApplicationMigrationStrategyWins() { + runner + .withUserConfiguration(DataSourceConfiguration.class) + .withBean("sampleMigrationStrategy", FlywayMigrationStrategy.class, () -> Flyway::migrate) + .run( + context -> { + assertThat(context).hasSingleBean(FlywayMigrationStrategy.class); + assertThat(context).doesNotHaveBean("migrationStartupRunner"); + }); } @Test diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/startup/MigrationStartupRunnerTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/MigrationStartupRunnerTest.java similarity index 93% rename from src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/startup/MigrationStartupRunnerTest.java rename to src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/MigrationStartupRunnerTest.java index 27b9f2bf..8585e05e 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/startup/MigrationStartupRunnerTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/MigrationStartupRunnerTest.java @@ -1,4 +1,4 @@ -package dev.caskeleton.bootstrap.runtime.startup; +package dev.caskeleton.adapter.outbound.persistence.startup; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -11,7 +11,7 @@ import static org.mockito.Mockito.when; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.read.ListAppender; -import dev.caskeleton.bootstrap.settings.RuntimeSafetySettings; +import dev.caskeleton.adapter.outbound.support.startup.MigrationFailedException; import java.util.Arrays; import java.util.stream.Collectors; import org.flywaydb.core.Flyway; @@ -33,8 +33,7 @@ import org.springframework.context.SmartLifecycle; */ class MigrationStartupRunnerTest { - private final RuntimeSafetySettings settings = new RuntimeSafetySettings(false, true); - private final MigrationStartupRunner runner = new MigrationStartupRunner(settings); + private final MigrationStartupRunner runner = new MigrationStartupRunner(true); @Test void migrationGatesReadinessByRunningAsARefreshTimeStrategyNotAPostReadyHook() { @@ -106,8 +105,7 @@ class MigrationStartupRunnerTest { @Test void migrateWhenMigrationOnStartupIsFalseBypassesMigrationExecution() { - RuntimeSafetySettings bypassSettings = new RuntimeSafetySettings(false, false); - MigrationStartupRunner bypassRunner = new MigrationStartupRunner(bypassSettings); + MigrationStartupRunner bypassRunner = new MigrationStartupRunner(false); Flyway flyway = mock(Flyway.class); bypassRunner.migrate(flyway); diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/OpenInViewSafetyValidatorTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/OpenInViewSafetyValidatorTest.java similarity index 93% rename from src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/OpenInViewSafetyValidatorTest.java rename to src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/OpenInViewSafetyValidatorTest.java index b854c78c..ef3ecdbd 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/OpenInViewSafetyValidatorTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/OpenInViewSafetyValidatorTest.java @@ -1,8 +1,8 @@ -package dev.caskeleton.bootstrap.runtime; +package dev.caskeleton.adapter.outbound.persistence.startup; import static org.assertj.core.api.Assertions.assertThat; -import dev.caskeleton.bootstrap.runtime.startup.StartupValidationException; +import dev.caskeleton.adapter.outbound.support.startup.StartupValidationException; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/PersistenceVendorProdSafetyValidatorTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/PersistenceVendorProdSafetyValidatorTest.java similarity index 96% rename from src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/PersistenceVendorProdSafetyValidatorTest.java rename to src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/PersistenceVendorProdSafetyValidatorTest.java index 45330d86..d5b2646c 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/PersistenceVendorProdSafetyValidatorTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/PersistenceVendorProdSafetyValidatorTest.java @@ -1,8 +1,8 @@ -package dev.caskeleton.bootstrap.runtime; +package dev.caskeleton.adapter.outbound.persistence.startup; import static org.assertj.core.api.Assertions.assertThat; -import dev.caskeleton.bootstrap.runtime.startup.ProfileMismatchException; +import dev.caskeleton.adapter.outbound.support.startup.ProfileMismatchException; import java.io.PrintWriter; import java.io.StringWriter; import org.junit.jupiter.api.Test; diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/PostgreSqlTransportSecurityValidatorTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/PostgreSqlTransportSecurityValidatorTest.java similarity index 96% rename from src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/PostgreSqlTransportSecurityValidatorTest.java rename to src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/PostgreSqlTransportSecurityValidatorTest.java index 49d114fc..efd06b45 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/PostgreSqlTransportSecurityValidatorTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/PostgreSqlTransportSecurityValidatorTest.java @@ -1,8 +1,8 @@ -package dev.caskeleton.bootstrap.runtime; +package dev.caskeleton.adapter.outbound.persistence.startup; import static org.assertj.core.api.Assertions.assertThat; -import dev.caskeleton.bootstrap.runtime.startup.ProfileMismatchException; +import dev.caskeleton.adapter.outbound.support.startup.ProfileMismatchException; import java.io.PrintWriter; import java.io.StringWriter; import org.junit.jupiter.api.Test; diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/startup/RequiredEnvironmentValidatorTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/RequiredEnvironmentValidatorTest.java similarity index 93% rename from src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/startup/RequiredEnvironmentValidatorTest.java rename to src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/RequiredEnvironmentValidatorTest.java index 971d2554..8b723a5e 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/startup/RequiredEnvironmentValidatorTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/RequiredEnvironmentValidatorTest.java @@ -1,7 +1,9 @@ -package dev.caskeleton.bootstrap.runtime.startup; +package dev.caskeleton.adapter.outbound.persistence.startup; import static org.assertj.core.api.Assertions.assertThat; +import dev.caskeleton.adapter.outbound.support.startup.StartupErrorCode; +import dev.caskeleton.adapter.outbound.support.startup.StartupValidationException; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.assertj.AssertableApplicationContext; import org.springframework.boot.test.context.runner.ApplicationContextRunner; diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/ConcurrentIndexMigrationInspectorTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/ConcurrentIndexMigrationInspectorTest.java similarity index 71% rename from src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/ConcurrentIndexMigrationInspectorTest.java rename to src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/ConcurrentIndexMigrationInspectorTest.java index 58c139be..80760982 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/ConcurrentIndexMigrationInspectorTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/ConcurrentIndexMigrationInspectorTest.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.persistence.migration; +package dev.caskeleton.adapter.outbound.persistence.testkit.migration; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -60,26 +60,4 @@ class ConcurrentIndexMigrationInspectorTest { .isInstanceOf(IllegalStateException.class) .hasMessageContaining("mixes a concurrent index statement"); } - - @Test - @DisplayName("ddl-auto values that mutate a deployed schema are refused") - void refusesSchemaMutatingDdlAuto() { - var policy = FlywaySchemaPolicy.standard(); - - assertThatThrownBy(() -> policy.requirePermittedDdlAuto("update")) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("Flyway owns schema change"); - policy.requirePermittedDdlAuto("validate"); - policy.requirePermittedDdlAuto("none"); - } - - @Test - @DisplayName("production validates rather than migrating at startup") - void productionValidatesOnly() { - var policy = FlywaySchemaPolicy.standard(); - - assertThat(policy.modeFor("prod")).isEqualTo(SchemaManagementMode.VALIDATE_ONLY); - assertThat(policy.modeFor("local")).isEqualTo(SchemaManagementMode.MIGRATE_ON_STARTUP); - assertThat(policy.modeFor("unknown-profile")).isEqualTo(SchemaManagementMode.VALIDATE_ONLY); - } } diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/FlywayValidationGateTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/FlywayValidationGateTest.java similarity index 98% rename from src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/FlywayValidationGateTest.java rename to src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/FlywayValidationGateTest.java index 9947d43f..0c08526d 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/FlywayValidationGateTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/FlywayValidationGateTest.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.persistence.migration; +package dev.caskeleton.adapter.outbound.persistence.testkit.migration; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/BackoffCalculatorTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/BackoffCalculatorTest.java deleted file mode 100644 index 5b13ad4a..00000000 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/BackoffCalculatorTest.java +++ /dev/null @@ -1,77 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.transaction; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.adapter.outbound.persistence.api.error.FailureCategory; -import dev.caskeleton.adapter.outbound.persistence.api.transaction.JitterMode; -import dev.caskeleton.adapter.outbound.persistence.api.transaction.RetryProfile; -import java.time.Duration; -import java.util.Set; -import java.util.random.RandomGenerator; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** Plan Task 8 — backoff grows, is capped, and is jittered (design §19.3). */ -class BackoffCalculatorTest { - - private static final RandomGenerator FIXED_RANDOM = new FixedRandom(); - - @Test - @DisplayName("backoff grows exponentially and stops at the cap") - void growsExponentiallyAndCaps() { - var profile = - new RetryProfile( - "order.write", - 5, - Duration.ofMillis(20), - Duration.ofMillis(100), - 2.0d, - JitterMode.NONE, - Set.of(FailureCategory.SERIALIZATION_FAILURE)); - var calculator = new BackoffCalculator(profile, FIXED_RANDOM); - - assertThat(calculator.forAttempt(1)).isEqualTo(Duration.ofMillis(20)); - assertThat(calculator.forAttempt(2)).isEqualTo(Duration.ofMillis(40)); - assertThat(calculator.forAttempt(3)).isEqualTo(Duration.ofMillis(80)); - assertThat(calculator.forAttempt(4)).isEqualTo(Duration.ofMillis(100)); - assertThat(calculator.forAttempt(9)).isEqualTo(Duration.ofMillis(100)); - } - - @Test - @DisplayName("equal jitter keeps a floor under the wait") - void equalJitterKeepsAFloor() { - var profile = - new RetryProfile( - "order.write", - 5, - Duration.ofMillis(100), - Duration.ofMillis(100), - 1.0d, - JitterMode.EQUAL, - Set.of(FailureCategory.DEADLOCK)); - var calculator = new BackoffCalculator(profile, FIXED_RANDOM); - - assertThat(calculator.forAttempt(1)).isBetween(Duration.ofMillis(50), Duration.ofMillis(100)); - } - - @Test - @DisplayName("a profile with no backoff waits not at all") - void zeroBackoffIsZero() { - assertThat(BackoffCalculator.forProfile(RetryProfile.none()).forAttempt(1)) - .isEqualTo(Duration.ZERO); - } - - /** Always returns the lower bound, so jitter is deterministic under test. */ - private static final class FixedRandom implements RandomGenerator { - - @Override - public long nextLong() { - return 0L; - } - - @Override - public long nextLong(long bound) { - return 0L; - } - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/CommitFailureClassifierTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/CommitFailureClassifierTest.java deleted file mode 100644 index 84dafc6d..00000000 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/CommitFailureClassifierTest.java +++ /dev/null @@ -1,80 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.transaction; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.adapter.outbound.persistence.api.PersistenceOperationName; -import dev.caskeleton.adapter.outbound.persistence.api.error.TransactionCompletionUnknownException; -import java.io.IOException; -import java.sql.SQLException; -import java.time.Clock; -import java.time.Instant; -import java.time.ZoneOffset; -import java.util.Optional; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** Plan Task 6 — only a commit-phase break becomes completion unknown (design §17.2). */ -class CommitFailureClassifierTest { - - private static final PersistenceOperationName OPERATION = - new PersistenceOperationName("payment.commit"); - - private final Clock clock = Clock.fixed(Instant.parse("2026-08-11T00:00:00Z"), ZoneOffset.UTC); - private final CommitFailureClassifier classifier = CommitFailureClassifier.standard(clock); - - @AfterEach - void clearEvidence() { - TransactionEvidenceContext.clearAll(); - } - - @Test - @DisplayName("a lost connection during commit becomes completion unknown") - void connectionLossDuringCommitBecomesCompletionUnknown() { - TransactionEvidenceContext.begin(OPERATION, "payment-42", clock.instant(), 1); - - RuntimeException translated = - classifier.translateCommitFailure( - new IllegalStateException("commit failed", new IOException("connection reset"))); - - assertThat(translated).isInstanceOf(TransactionCompletionUnknownException.class); - TransactionCompletionUnknownException unknown = - (TransactionCompletionUnknownException) translated; - assertThat(unknown.context().completionUnknown()).isTrue(); - assertThat(unknown.context().retryable()).isFalse(); - assertThat(unknown.transactionKey()).contains("payment-42"); - } - - @Test - @DisplayName("SQLSTATE 40003 becomes completion unknown") - void statementCompletionUnknownStateIsHonoured() { - TransactionEvidenceContext.begin(OPERATION, null, clock.instant(), 1); - - RuntimeException translated = - classifier.translateCommitFailure( - new IllegalStateException("commit failed", new SQLException("failed", "40003"))); - - assertThat(translated).isInstanceOf(TransactionCompletionUnknownException.class); - } - - @Test - @DisplayName("an ordinary constraint failure at commit is returned unchanged") - void ordinaryCommitFailureIsNotEscalated() { - TransactionEvidenceContext.begin(OPERATION, null, clock.instant(), 1); - RuntimeException original = - new IllegalStateException("commit failed", new SQLException("duplicate", "23505")); - - assertThat(classifier.translateCommitFailure(original)).isSameAs(original); - } - - @Test - @DisplayName("the rule is asserted directly, without a driver exception") - void ruleIsIndependentlyAssertable() { - assertThat(classifier.indicatesUnknownCompletion(Optional.of("40003"), new RuntimeException())) - .isTrue(); - assertThat(classifier.indicatesUnknownCompletion(Optional.of("08006"), new RuntimeException())) - .isTrue(); - assertThat(classifier.indicatesUnknownCompletion(Optional.of("23505"), new RuntimeException())) - .isFalse(); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/CompletionUnknownRecorderTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/CompletionUnknownRecorderTest.java deleted file mode 100644 index 61613ddb..00000000 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/CompletionUnknownRecorderTest.java +++ /dev/null @@ -1,94 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.transaction; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.adapter.outbound.persistence.api.PersistenceOperationName; -import dev.caskeleton.adapter.outbound.persistence.api.error.JpaFailureContext; -import dev.caskeleton.adapter.outbound.persistence.api.error.TransactionCompletionUnknownException; -import dev.caskeleton.adapter.outbound.persistence.api.transaction.TransactionCompletionEvidence; -import dev.caskeleton.application.transaction.CompletionResolution; -import dev.caskeleton.application.transaction.TransactionCompletionResolver; -import java.time.Duration; -import java.time.Instant; -import java.util.ArrayList; -import java.util.List; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** Plan Task 10 — recording an unknown outcome observes; it never repairs (design §17.4). */ -class CompletionUnknownRecorderTest { - - private static final PersistenceOperationName OPERATION = - new PersistenceOperationName("payment.commit"); - - private final List audit = new ArrayList<>(); - private final List originalUseCaseInvocations = new ArrayList<>(); - - private final CompletionUnknownRecorder recorder = - failure -> audit.add(CompletionUnknownRecord.from(failure, Instant.EPOCH)); - - @Test - @DisplayName("the record is written and the original use case is not re-invoked") - void recordsUnknownWithoutRetryingOriginalWork() { - recorder.record(completionUnknown("payment-42")); - - assertThat(audit).hasSize(1); - assertThat(audit.get(0).transactionKey()).isEqualTo("payment-42"); - assertThat(originalUseCaseInvocations).isEmpty(); - } - - @Test - @DisplayName("the record carries the operation, SQLSTATE, attempt, and evidence") - void recordCarriesTheReconciliationHandles() { - recorder.record(completionUnknown("payment-42")); - - CompletionUnknownRecord record = audit.get(0); - assertThat(record.operation()).isEqualTo(OPERATION); - assertThat(record.sqlState()).isEqualTo("40003"); - assertThat(record.attempt()).isEqualTo(1); - assertThat(record.evidence()).isEqualTo(TransactionCompletionEvidence.UNKNOWN); - assertThat(record.occurredAt()).isEqualTo(Instant.EPOCH); - assertThat(record.reconcilable()).isTrue(); - } - - @Test - @DisplayName("a record with no transaction key needs a human rather than a resolver") - void recordWithoutKeyIsNotAutomaticallyReconcilable() { - recorder.record(completionUnknown(null)); - - assertThat(audit.get(0).reconcilable()).isFalse(); - assertThat(audit.get(0).reconciliationKey()).isEmpty(); - } - - @Test - @DisplayName("resolution keeps an inconclusive answer available") - void resolutionKeepsStillUnknown() { - assertThat(CompletionResolution.values()) - .containsExactly( - CompletionResolution.COMMITTED, - CompletionResolution.NOT_COMMITTED, - CompletionResolution.STILL_UNKNOWN); - } - - @Test - @DisplayName("a resolver reads evidence and never re-runs the original work") - void resolverOnlyReadsEvidence() { - TransactionCompletionResolver resolver = - key -> - "payment-42".equals(key) - ? CompletionResolution.COMMITTED - : CompletionResolution.STILL_UNKNOWN; - - assertThat(resolver.resolve("payment-42")).isEqualTo(CompletionResolution.COMMITTED); - assertThat(resolver.resolve("payment-99")).isEqualTo(CompletionResolution.STILL_UNKNOWN); - assertThat(originalUseCaseInvocations).isEmpty(); - } - - private static TransactionCompletionUnknownException completionUnknown(String transactionKey) { - return new TransactionCompletionUnknownException( - JpaFailureContext.completionUnknown(OPERATION, "40003", 1, Duration.ZERO, null), - transactionKey, - TransactionCompletionEvidence.UNKNOWN, - null); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/DefaultJpaRetryPolicyTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/DefaultJpaRetryPolicyTest.java deleted file mode 100644 index 783f44e6..00000000 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/DefaultJpaRetryPolicyTest.java +++ /dev/null @@ -1,77 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.transaction; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.adapter.outbound.persistence.api.PersistenceOperationName; -import dev.caskeleton.adapter.outbound.persistence.api.error.ConstraintCode; -import dev.caskeleton.adapter.outbound.persistence.api.error.ConstraintViolationDetails; -import dev.caskeleton.adapter.outbound.persistence.api.error.JpaFailureContext; -import dev.caskeleton.adapter.outbound.persistence.api.error.SerializationFailureException; -import dev.caskeleton.adapter.outbound.persistence.api.error.TransactionCompletionUnknownException; -import dev.caskeleton.adapter.outbound.persistence.api.error.UniqueConstraintViolationException; -import dev.caskeleton.adapter.outbound.persistence.api.transaction.RetryDisposition; -import dev.caskeleton.adapter.outbound.persistence.api.transaction.RetryProfile; -import dev.caskeleton.adapter.outbound.persistence.api.transaction.TransactionAttempt; -import dev.caskeleton.adapter.outbound.persistence.api.transaction.TransactionCompletionEvidence; -import java.time.Duration; -import java.time.Instant; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** Plan Task 29 — the retry classification order is the contract (design §19.1). */ -class DefaultJpaRetryPolicyTest { - - private static final PersistenceOperationName OPERATION = - new PersistenceOperationName("order.place"); - private static final TransactionAttempt ATTEMPT = - new TransactionAttempt(1, Instant.parse("2026-08-11T00:00:00Z")); - - private final DefaultJpaRetryPolicy policy = - DefaultJpaRetryPolicy.forProfile(RetryProfile.boundedContention("order.write", 3)); - - @Test - @DisplayName("completion unknown reconciles and is never retried") - void completionUnknownReconciles() { - var failure = - new TransactionCompletionUnknownException( - JpaFailureContext.completionUnknown(OPERATION, "40003", 1, Duration.ZERO, null), - TransactionCompletionEvidence.UNKNOWN, - null); - - assertThat(policy.classify(failure, ATTEMPT).disposition()) - .isEqualTo(RetryDisposition.RECONCILE); - } - - @Test - @DisplayName("an eligible contention failure retries the whole transaction") - void contentionFailureRetries() { - var failure = - new SerializationFailureException( - JpaFailureContext.retryable(OPERATION, "40001", 1, Duration.ZERO, null)); - - assertThat(policy.classify(failure, ATTEMPT).disposition()) - .isEqualTo(RetryDisposition.RETRY_FULL_TRANSACTION); - } - - @Test - @DisplayName("a constraint violation is never retried") - void constraintViolationFails() { - var failure = - new UniqueConstraintViolationException( - JpaFailureContext.terminal(OPERATION, "23505", 1, Duration.ZERO, null), - ConstraintViolationDetails.of(new ConstraintCode("user.email.unique"))); - - assertThat(policy.classify(failure, ATTEMPT).disposition()).isEqualTo(RetryDisposition.FAIL); - } - - @Test - @DisplayName("a profile with no retry budget always fails") - void disabledProfileAlwaysFails() { - var disabled = DefaultJpaRetryPolicy.forProfile(RetryProfile.none()); - var failure = - new SerializationFailureException( - JpaFailureContext.retryable(OPERATION, "40001", 1, Duration.ZERO, null)); - - assertThat(disabled.classify(failure, ATTEMPT).disposition()).isEqualTo(RetryDisposition.FAIL); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/EvidenceAwareJpaTransactionManagerTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/EvidenceAwareJpaTransactionManagerTest.java deleted file mode 100644 index 456ed944..00000000 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/EvidenceAwareJpaTransactionManagerTest.java +++ /dev/null @@ -1,144 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.transaction; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.outbound.persistence.api.PersistenceOperationName; -import dev.caskeleton.adapter.outbound.persistence.api.error.JpaPersistenceException; -import dev.caskeleton.adapter.outbound.persistence.api.error.TransactionCompletionUnknownException; -import dev.caskeleton.adapter.outbound.persistence.api.transaction.TransactionCompletionEvidence; -import java.io.IOException; -import java.sql.SQLException; -import java.time.Clock; -import java.time.Instant; -import java.time.ZoneOffset; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * Plan Task 6 — the commit phase is marked before the provider is asked, not after (design §17.2). - * - *

The manager itself needs an {@code EntityManagerFactory}, so what is asserted here is the - * mechanism the manager delegates to: the evidence stack and the classifier that reads it. The - * manager's own {@code doCommit} ordering is exercised end to end by the commit-ambiguity contract - * on a real server, which is the only place a genuinely lost acknowledgement can be produced. - */ -class EvidenceAwareJpaTransactionManagerTest { - - private static final PersistenceOperationName OPERATION = - new PersistenceOperationName("payment.commit"); - - private final Clock clock = Clock.fixed(Instant.parse("2026-08-11T00:00:00Z"), ZoneOffset.UTC); - private final CommitFailureClassifier classifier = CommitFailureClassifier.standard(clock); - - @AfterEach - void clearEvidence() { - TransactionEvidenceContext.clearAll(); - } - - @Test - @DisplayName("a connection loss while COMMITTING becomes completion unknown") - void connectionLossDuringCommitBecomesCompletionUnknown() { - TransactionEvidenceContext.begin(OPERATION, "payment-42", clock.instant(), 1); - TransactionEvidenceContext.mark(TransactionCompletionEvidence.COMMITTING); - - RuntimeException translated = - classifier.translateCommitFailure( - new IllegalStateException("commit failed", new IOException("connection reset"))); - - assertThat(translated).isInstanceOf(TransactionCompletionUnknownException.class); - assertThat(((JpaPersistenceException) translated).context().completionUnknown()).isTrue(); - } - - @Test - @DisplayName("the phase advances NOT_STARTED to ACTIVE to COMMITTING to COMMITTED") - void phaseAdvancesThroughTheCommitLifecycle() { - TransactionEvidenceContext.begin(OPERATION, null, clock.instant(), 1); - assertThat(TransactionEvidenceContext.evidence()) - .isEqualTo(TransactionCompletionEvidence.NOT_STARTED); - - TransactionEvidenceContext.mark(TransactionCompletionEvidence.ACTIVE); - assertThat(TransactionEvidenceContext.evidence()) - .isEqualTo(TransactionCompletionEvidence.ACTIVE); - - TransactionEvidenceContext.mark(TransactionCompletionEvidence.COMMITTING); - assertThat(TransactionEvidenceContext.evidence()) - .isEqualTo(TransactionCompletionEvidence.COMMITTING); - - TransactionEvidenceContext.mark(TransactionCompletionEvidence.COMMITTED); - assertThat(TransactionEvidenceContext.evidence()) - .isEqualTo(TransactionCompletionEvidence.COMMITTED); - } - - @Test - @DisplayName("a nested REQUIRES_NEW frame does not overwrite the outer transaction's phase") - void nestedFrameDoesNotOverwriteTheOuterPhase() { - TransactionEvidenceContext.begin(OPERATION, "outer", clock.instant(), 1); - TransactionEvidenceContext.mark(TransactionCompletionEvidence.ACTIVE); - - TransactionEvidenceContext.begin(OPERATION, "inner", clock.instant(), 1); - TransactionEvidenceContext.mark(TransactionCompletionEvidence.COMMITTED); - TransactionEvidenceContext.clear(); - - assertThat(TransactionEvidenceContext.evidence()) - .isEqualTo(TransactionCompletionEvidence.ACTIVE); - assertThat(TransactionEvidenceContext.current().orElseThrow().reconciliationKey()) - .contains("outer"); - } - - @Test - @DisplayName("clearing the last frame removes the thread-local entirely") - void clearingTheLastFrameRemovesTheThreadLocal() { - TransactionEvidenceContext.begin(OPERATION, null, clock.instant(), 1); - TransactionEvidenceContext.clear(); - - assertThat(TransactionEvidenceContext.current()).isEmpty(); - assertThat(TransactionEvidenceContext.evidence()) - .isEqualTo(TransactionCompletionEvidence.NOT_STARTED); - } - - @Test - @DisplayName("an ordinary commit-phase failure is rethrown unchanged") - void ordinaryCommitFailureIsRethrownUnchanged() { - TransactionEvidenceContext.begin(OPERATION, null, clock.instant(), 1); - TransactionEvidenceContext.mark(TransactionCompletionEvidence.COMMITTING); - RuntimeException original = - new IllegalStateException("commit failed", new SQLException("check", "23514")); - - assertThat(classifier.translateCommitFailure(original)).isSameAs(original); - } - - @Test - @DisplayName("the translated failure carries the operation and the reconciliation key") - void translatedFailureCarriesTheReconciliationHandle() { - TransactionEvidenceContext.begin(OPERATION, "payment-42", clock.instant(), 3); - TransactionEvidenceContext.mark(TransactionCompletionEvidence.COMMITTING); - - var failure = - (TransactionCompletionUnknownException) - classifier.translateCommitFailure( - new IllegalStateException("lost", new SQLException("lost", "40003"))); - - assertThat(failure.context().operation()).isEqualTo(OPERATION); - assertThat(failure.context().transactionAttempt()).isEqualTo(3); - assertThat(failure.transactionKey()).contains("payment-42"); - assertThat(failure.evidence()).isEqualTo(TransactionCompletionEvidence.UNKNOWN); - } - - @Test - @DisplayName("a failure with no bound frame is attributed to the registered placeholder") - void unattributedFailureUsesThePlaceholderOperation() { - var failure = - (TransactionCompletionUnknownException) - classifier.translateCommitFailure( - new IllegalStateException("lost", new SQLException("lost", "40003"))); - - assertThat(failure.context().operation()).isEqualTo(UnknownOperation.NAME); - assertThatThrownBy( - () -> { - throw failure; - }) - .isInstanceOf(TransactionCompletionUnknownException.class); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/FullTransactionRetryCoordinatorTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/FullTransactionRetryCoordinatorTest.java deleted file mode 100644 index 64b0563f..00000000 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/FullTransactionRetryCoordinatorTest.java +++ /dev/null @@ -1,149 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.transaction; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.outbound.persistence.api.PersistenceOperationName; -import dev.caskeleton.adapter.outbound.persistence.api.error.JpaFailureContext; -import dev.caskeleton.adapter.outbound.persistence.api.error.SerializationFailureException; -import dev.caskeleton.adapter.outbound.persistence.api.error.TransactionCompletionUnknownException; -import dev.caskeleton.adapter.outbound.persistence.api.transaction.RetryEventListener; -import dev.caskeleton.adapter.outbound.persistence.api.transaction.RetryProfile; -import dev.caskeleton.adapter.outbound.persistence.api.transaction.TransactionCompletionEvidence; -import dev.caskeleton.adapter.outbound.persistence.api.transaction.TransactionProfile; -import java.time.Clock; -import java.time.Duration; -import java.time.Instant; -import java.time.ZoneOffset; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.atomic.AtomicInteger; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.springframework.transaction.PlatformTransactionManager; -import org.springframework.transaction.TransactionDefinition; -import org.springframework.transaction.TransactionStatus; -import org.springframework.transaction.support.SimpleTransactionStatus; - -/** Plan Task 8 — every attempt is a new transaction (design §19.2). */ -class FullTransactionRetryCoordinatorTest { - - private static final PersistenceOperationName OPERATION = - new PersistenceOperationName("order.place"); - - private final Clock clock = Clock.fixed(Instant.parse("2026-08-11T00:00:00Z"), ZoneOffset.UTC); - private final CountingTransactionManager transactionManager = new CountingTransactionManager(); - private final List slept = new ArrayList<>(); - - private static TransactionProfile writeProfile(RetryProfile retryProfile) { - return TransactionProfile.write("order.write", Duration.ofSeconds(5)) - .withRetryProfile(retryProfile); - } - - private FullTransactionRetryCoordinator coordinator(RetryProfile retryProfile) { - var executor = new SpringJpaTransactionExecutor(transactionManager, clock); - return new FullTransactionRetryCoordinator( - executor, - DefaultJpaRetryPolicy.forProfile(retryProfile), - slept::add, - clock, - Duration.ofSeconds(30), - RetryEventListener.noop()); - } - - @Test - @DisplayName("a retried use case runs again in a brand new transaction") - void retriesWholeUseCaseInANewTransaction() { - AtomicInteger invocations = new AtomicInteger(); - - String result = - coordinator(RetryProfile.boundedContention("order.write", 3)) - .execute( - OPERATION, - writeProfile(RetryProfile.boundedContention("order.write", 3)), - () -> { - if (invocations.incrementAndGet() == 1) { - throw new SerializationFailureException( - JpaFailureContext.retryable(OPERATION, "40001", 1, Duration.ZERO, null)); - } - return "ok"; - }); - - assertThat(result).isEqualTo("ok"); - assertThat(invocations.get()).isEqualTo(2); - assertThat(transactionManager.begun()).isEqualTo(2); - assertThat(slept).hasSize(1); - } - - @Test - @DisplayName("a completion-unknown failure is surfaced, never retried") - void completionUnknownIsNeverRetried() { - AtomicInteger invocations = new AtomicInteger(); - - assertThatThrownBy( - () -> - coordinator(RetryProfile.boundedContention("order.write", 3)) - .execute( - OPERATION, - writeProfile(RetryProfile.boundedContention("order.write", 3)), - () -> { - invocations.incrementAndGet(); - throw new TransactionCompletionUnknownException( - JpaFailureContext.completionUnknown( - OPERATION, "40003", 1, Duration.ZERO, null), - TransactionCompletionEvidence.UNKNOWN, - null); - })) - .isInstanceOf(TransactionCompletionUnknownException.class); - - assertThat(invocations.get()).isEqualTo(1); - } - - @Test - @DisplayName("the attempt budget bounds how many times the use case runs") - void attemptBudgetIsEnforced() { - AtomicInteger invocations = new AtomicInteger(); - - assertThatThrownBy( - () -> - coordinator(RetryProfile.boundedContention("order.write", 3)) - .execute( - OPERATION, - writeProfile(RetryProfile.boundedContention("order.write", 3)), - () -> { - invocations.incrementAndGet(); - throw new SerializationFailureException( - JpaFailureContext.retryable( - OPERATION, "40001", 1, Duration.ZERO, null)); - })) - .isInstanceOf(SerializationFailureException.class); - - assertThat(invocations.get()).isEqualTo(3); - } - - /** Counts how many physical transactions were begun. */ - private static final class CountingTransactionManager implements PlatformTransactionManager { - - private int begun; - - @Override - public TransactionStatus getTransaction(TransactionDefinition definition) { - begun++; - return new SimpleTransactionStatus(); - } - - @Override - public void commit(TransactionStatus status) { - // nothing to commit in the unit lane - } - - @Override - public void rollback(TransactionStatus status) { - // nothing to roll back in the unit lane - } - - int begun() { - return begun; - } - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/JpaTransactionSettingsTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/JpaTransactionSettingsTest.java deleted file mode 100644 index 45b65084..00000000 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/JpaTransactionSettingsTest.java +++ /dev/null @@ -1,69 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.transaction; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.time.Duration; -import org.junit.jupiter.api.Test; - -class JpaTransactionSettingsTest { - - @Test - void suppliesFiniteDefaultsWithTheRequiredTimeoutHierarchy() { - JpaTransactionSettings settings = - new JpaTransactionSettings(null, null, null, null, null, null, null, null, null); - - assertThat(settings.lockTimeout()).isLessThan(settings.statementTimeout()); - assertThat(settings.statementTimeout()).isLessThanOrEqualTo(settings.transactionTimeout()); - assertThat(settings.beginBudget()).isPositive(); - assertThat(settings.minimumActionWindow()).isPositive(); - assertThat(settings.completionMargin()).isPositive(); - } - - @Test - void rejectsNonPositiveValuesAndInvalidHierarchy() { - assertThatThrownBy( - () -> - settings( - Duration.ZERO, - Duration.ofSeconds(10), - Duration.ofSeconds(2), - Duration.ofSeconds(15))) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - settings( - Duration.ofSeconds(30), - Duration.ofSeconds(10), - Duration.ofSeconds(10), - Duration.ofSeconds(15))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("lock-timeout"); - assertThatThrownBy( - () -> - settings( - Duration.ofSeconds(5), - Duration.ofSeconds(10), - Duration.ofSeconds(2), - Duration.ofSeconds(15))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("statement-timeout"); - } - - private static JpaTransactionSettings settings( - Duration transactionTimeout, - Duration statementTimeout, - Duration lockTimeout, - Duration idleGuardTimeout) { - return new JpaTransactionSettings( - transactionTimeout, - Duration.ofMillis(250), - Duration.ofSeconds(1), - Duration.ofMillis(500), - statementTimeout, - lockTimeout, - idleGuardTimeout, - Duration.ofMillis(250), - Duration.ofMillis(100)); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/PersistenceFailureTranslatorChainTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/PersistenceFailureTranslatorChainTest.java deleted file mode 100644 index b76e3c64..00000000 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/PersistenceFailureTranslatorChainTest.java +++ /dev/null @@ -1,153 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.transaction; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.adapter.outbound.persistence.api.PersistenceOperationName; -import dev.caskeleton.adapter.outbound.persistence.api.error.FailureCategory; -import dev.caskeleton.adapter.outbound.persistence.api.error.JpaPersistenceException; -import dev.caskeleton.adapter.outbound.persistence.api.error.OptimisticConflictException; -import java.sql.SQLException; -import java.time.Duration; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * What the retry coordinator can actually see. - * - *

It catches {@link JpaPersistenceException}. The executor ran the transaction template and - * translated nothing, so the failures contention really produces — Hibernate's {@code - * OptimisticLockException}, Spring's {@code OptimisticLockingFailureException}, a raw serialization - * or deadlock {@code SQLException} — went straight past the catch and were never retried. Every - * unit fixture passed, because each threw an exception that had already been translated by hand. - */ -class PersistenceFailureTranslatorChainTest { - - private static final PersistenceOperationName OPERATION = - new PersistenceOperationName("order.write"); - - /** - * The chain a PostgreSQL composition builds. - * - *

The vendor translator arrives from outside. The chain used to construct the PostgreSQL one - * itself, which pointed the vendor-neutral transaction package at the vendor package while the - * vendor configuration pointed back for its SPI — the cycle JPA-015 is about. - */ - private final PersistenceFailureTranslatorChain chain = - new PersistenceFailureTranslatorChain( - dev.caskeleton.adapter.outbound.persistence.transaction.OptimisticConflictTranslator - .withoutCatalog(), - dev.caskeleton.adapter.outbound.persistence.postgresql.error.PostgreSqlExceptionTranslator - .with( - dev.caskeleton.adapter.outbound.persistence.postgresql.constraint - .PostgreSqlConstraintCatalog.empty())); - - @Test - @DisplayName("a raw serialization failure becomes a retryable persistence failure") - void aRawSerializationFailureIsTranslated() { - Throwable translated = translate(new SQLException("could not serialize access", "40001")); - - assertThat(translated).isInstanceOf(JpaPersistenceException.class); - JpaPersistenceException classified = (JpaPersistenceException) translated; - assertThat(classified.category()).isEqualTo(FailureCategory.SERIALIZATION_FAILURE); - assertThat(classified.retryable()) - .as( - "this is the failure the coordinator exists to retry, and it used to escape untranslated") - .isTrue(); - } - - @Test - @DisplayName("a raw deadlock becomes a retryable persistence failure") - void aRawDeadlockIsTranslated() { - Throwable translated = translate(new SQLException("deadlock detected", "40P01")); - - assertThat(translated).isInstanceOf(JpaPersistenceException.class); - assertThat(((JpaPersistenceException) translated).category()) - .isEqualTo(FailureCategory.DEADLOCK); - } - - @Test - @DisplayName("a unique violation is classified and is not retryable") - void aUniqueViolationIsClassifiedAndNotRetryable() { - Throwable translated = translate(new SQLException("duplicate key", "23505")); - - assertThat(translated).isInstanceOf(JpaPersistenceException.class); - JpaPersistenceException classified = (JpaPersistenceException) translated; - assertThat(classified.category()).isEqualTo(FailureCategory.UNIQUE_CONSTRAINT); - assertThat(classified.retryable()) - .as("re-running a duplicate insert produces the same duplicate") - .isFalse(); - } - - @Test - @DisplayName("a provider optimistic-lock exception is recognised without a SQLSTATE") - void aProviderOptimisticLockExceptionIsRecognised() { - Throwable translated = translate(new jakarta.persistence.OptimisticLockException("stale")); - - assertThat(translated) - .as("an optimistic conflict carries no SQLSTATE, so no SQLSTATE translator can see it") - .isInstanceOf(OptimisticConflictException.class); - assertThat(((JpaPersistenceException) translated).retryable()).isTrue(); - } - - @Test - @DisplayName("Spring's optimistic-locking failure is recognised too") - void springsOptimisticLockingFailureIsRecognised() { - Throwable translated = - translate(new org.springframework.dao.OptimisticLockingFailureException("stale")); - - assertThat(translated).isInstanceOf(OptimisticConflictException.class); - } - - @Test - @DisplayName("an already-classified failure passes through unchanged") - void anAlreadyClassifiedFailurePassesThroughUnchanged() { - JpaPersistenceException original = - (JpaPersistenceException) translate(new SQLException("deadlock detected", "40P01")); - - Throwable again = chain.translate(original, OPERATION, 7, Duration.ofSeconds(2), "trace-b"); - - assertThat(again) - .as("re-translating would rebuild the context and lose the attempt it already carries") - .isSameAs(original); - } - - @Test - @DisplayName("a non-persistence failure is propagated with its identity intact") - void aNonPersistenceFailureIsPropagatedUnchanged() { - IllegalStateException domainFailure = new IllegalStateException("order already shipped"); - - assertThat(translate(domainFailure)) - .as( - "dressing a programming or domain error as a persistence failure makes it look retryable") - .isSameAs(domainFailure); - - NullPointerException programmingError = new NullPointerException(); - assertThat(translate(programmingError)).isSameAs(programmingError); - } - - @Test - @DisplayName("the attempt, elapsed and trace come from one call, not from each translator") - void theAttemptAndElapsedComeFromOneCall() { - JpaPersistenceException classified = - (JpaPersistenceException) translate(new SQLException("deadlock detected", "40P01")); - - assertThat(classified.context().transactionAttempt()).isEqualTo(3); - assertThat(classified.context().elapsed()).isEqualTo(Duration.ofMillis(250)); - } - - private Throwable translate(Throwable failure) { - return chain.translate(failure, OPERATION, 3, Duration.ofMillis(250), "trace-a"); - } - - @Test - @DisplayName("with no vendor translator, a SQLSTATE failure is returned unchanged") - void withNoVendorTranslatorASqlStateFailureIsReturnedUnchanged() { - SQLException raw = new SQLException("deadlock detected", "40P01"); - - assertThat( - PersistenceFailureTranslatorChain.withoutCatalogs() - .translate(raw, OPERATION, 1, Duration.ZERO, null)) - .as("a composition with no vendor rows must not have one invented for it") - .isSameAs(raw); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/RetryBudgetTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/RetryBudgetTest.java deleted file mode 100644 index dea927b1..00000000 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/RetryBudgetTest.java +++ /dev/null @@ -1,41 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.transaction; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.adapter.outbound.persistence.api.transaction.RetryProfile; -import java.time.Duration; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** Plan Task 8 — attempts and elapsed time are independent bounds (design §19.2). */ -class RetryBudgetTest { - - @Test - @DisplayName("the attempt count bounds retrying") - void attemptsBoundRetrying() { - var budget = new RetryBudget(3, Duration.ofSeconds(30)); - - assertThat(budget.allowsAnotherAttempt(2, Duration.ZERO, Duration.ZERO)).isTrue(); - assertThat(budget.allowsAnotherAttempt(3, Duration.ZERO, Duration.ZERO)).isFalse(); - } - - @Test - @DisplayName("the elapsed deadline bounds retrying even with attempts left") - void elapsedDeadlineBoundsRetrying() { - var budget = new RetryBudget(10, Duration.ofSeconds(1)); - - assertThat(budget.allowsAnotherAttempt(1, Duration.ofMillis(900), Duration.ofMillis(50))) - .isTrue(); - assertThat(budget.allowsAnotherAttempt(1, Duration.ofMillis(900), Duration.ofMillis(200))) - .isFalse(); - } - - @Test - @DisplayName("a zero deadline means no elapsed bound at all") - void zeroDeadlineMeansNoElapsedBound() { - var budget = - RetryBudget.forProfile(RetryProfile.boundedContention("order.write", 5), Duration.ZERO); - - assertThat(budget.allowsAnotherAttempt(1, Duration.ofHours(1), Duration.ofHours(1))).isTrue(); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringJpaTransactionExecutorTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringJpaTransactionExecutorTest.java deleted file mode 100644 index 5dee6f59..00000000 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringJpaTransactionExecutorTest.java +++ /dev/null @@ -1,163 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.transaction; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.adapter.outbound.persistence.api.PersistenceOperationName; -import dev.caskeleton.adapter.outbound.persistence.api.transaction.IsolationLevel; -import dev.caskeleton.adapter.outbound.persistence.api.transaction.PropagationMode; -import dev.caskeleton.adapter.outbound.persistence.api.transaction.RetryProfile; -import dev.caskeleton.adapter.outbound.persistence.api.transaction.TransactionProfile; -import java.sql.Connection; -import java.time.Clock; -import java.time.Duration; -import java.time.Instant; -import java.time.ZoneOffset; -import java.util.ArrayList; -import java.util.List; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.springframework.transaction.PlatformTransactionManager; -import org.springframework.transaction.TransactionDefinition; -import org.springframework.transaction.TransactionStatus; -import org.springframework.transaction.support.SimpleTransactionStatus; - -/** - * Plan Task 7 — a profile maps to exactly one transaction, configured as declared (design §9.3). - */ -class SpringJpaTransactionExecutorTest { - - private static final PersistenceOperationName OPERATION = - new PersistenceOperationName("report.read"); - - private final Clock clock = Clock.fixed(Instant.parse("2026-08-11T00:00:00Z"), ZoneOffset.UTC); - private final RecordingTransactionManager transactionProbe = new RecordingTransactionManager(); - private final SpringJpaTransactionExecutor executor = - new SpringJpaTransactionExecutor(transactionProbe, clock); - - @AfterEach - void clearEvidence() { - TransactionEvidenceContext.clearAll(); - } - - @Test - @DisplayName("a serializable read-only profile reaches the manager unchanged") - void mapsSerializableReadOnlyProfile() { - var profile = - new TransactionProfile( - "report.read", - PropagationMode.REQUIRED, - IsolationLevel.SERIALIZABLE, - Duration.ofSeconds(3), - true, - RetryProfile.none()); - - executor.execute(OPERATION, profile, () -> null); - - assertThat(transactionProbe.isolation()).isEqualTo(Connection.TRANSACTION_SERIALIZABLE); - assertThat(transactionProbe.readOnly()).isTrue(); - assertThat(transactionProbe.timeoutSeconds()).isEqualTo(3); - assertThat(transactionProbe.name()).isEqualTo("report.read"); - } - - @Test - @DisplayName("each call builds its own definition rather than mutating a shared template") - void eachCallGetsItsOwnDefinition() { - executor.execute(OPERATION, TransactionProfile.read("report.read", Duration.ZERO), () -> null); - executor.execute( - OPERATION, TransactionProfile.write("report.write", Duration.ofSeconds(9)), () -> null); - - assertThat(transactionProbe.definitions()).hasSize(2); - assertThat(transactionProbe.definitions().get(0).isReadOnly()).isTrue(); - assertThat(transactionProbe.definitions().get(1).isReadOnly()).isFalse(); - assertThat(transactionProbe.definitions().get(1).getTimeout()).isEqualTo(9); - } - - @Test - @DisplayName("the operation is bound as evidence for the duration of the call") - void bindsTheOperationAsEvidence() { - var seen = new ArrayList(); - - executor.execute( - OPERATION, - TransactionProfile.read("report.read", Duration.ZERO), - () -> { - TransactionEvidenceContext.current().ifPresent(frame -> seen.add(frame.operation())); - return null; - }); - - assertThat(seen).containsExactly(OPERATION); - } - - @Test - @DisplayName("the evidence frame does not outlive the call") - void doesNotLeakTheEvidenceFrame() { - executor.execute(OPERATION, TransactionProfile.read("report.read", Duration.ZERO), () -> null); - - assertThat(TransactionEvidenceContext.current()).isEmpty(); - } - - @Test - @DisplayName("the attempt number and transaction key reach the evidence frame") - void recordsAttemptAndTransactionKey() { - var attempts = new ArrayList(); - - executor.execute( - OPERATION, - TransactionProfile.write("report.write", Duration.ofSeconds(5)), - () -> { - TransactionEvidenceContext.current().ifPresent(frame -> attempts.add(frame.attempt())); - return null; - }, - 3, - "report-42"); - - assertThat(attempts).containsExactly(3); - } - - /** Captures the definition each transaction was begun with. */ - private static final class RecordingTransactionManager implements PlatformTransactionManager { - - private final List definitions = new ArrayList<>(); - - @Override - public TransactionStatus getTransaction(TransactionDefinition definition) { - definitions.add(definition); - return new SimpleTransactionStatus(); - } - - @Override - public void commit(TransactionStatus status) { - // nothing to commit in the unit lane - } - - @Override - public void rollback(TransactionStatus status) { - // nothing to roll back in the unit lane - } - - List definitions() { - return definitions; - } - - private TransactionDefinition last() { - return definitions.get(definitions.size() - 1); - } - - int isolation() { - return last().getIsolationLevel(); - } - - boolean readOnly() { - return last().isReadOnly(); - } - - int timeoutSeconds() { - return last().getTimeout(); - } - - String name() { - return last().getName(); - } - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringPolicyTransactionPortTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringPolicyTransactionPortTest.java deleted file mode 100644 index b8b7c946..00000000 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringPolicyTransactionPortTest.java +++ /dev/null @@ -1,397 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.transaction; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.application.outbound.CallBudget; -import dev.caskeleton.application.transaction.OperationId; -import dev.caskeleton.application.transaction.ReadConsistency; -import dev.caskeleton.application.transaction.TransactionAdmissionException; -import dev.caskeleton.application.transaction.TransactionOutcome; -import dev.caskeleton.application.transaction.TransactionPhase; -import dev.caskeleton.application.transaction.TransactionPolicyId; -import dev.caskeleton.application.transaction.TransactionRequest; -import dev.caskeleton.application.transaction.TransactionResult; -import java.sql.SQLException; -import java.time.Duration; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicReference; -import org.junit.jupiter.api.Test; -import org.springframework.dao.DataAccessResourceFailureException; -import org.springframework.transaction.PlatformTransactionManager; -import org.springframework.transaction.TransactionDefinition; -import org.springframework.transaction.TransactionException; -import org.springframework.transaction.TransactionStatus; -import org.springframework.transaction.UnexpectedRollbackException; -import org.springframework.transaction.support.SimpleTransactionStatus; - -class SpringPolicyTransactionPortTest { - - private static final long NOW = 10_000L; - private static final OperationId OPERATION_ID = new OperationId("operation-42"); - - @Test - void commandDefaultUsesRequiredReadCommittedPrimaryShapeAndReturnsCommitted() { - RecordingTransactionManager tm = new RecordingTransactionManager(true); - SpringTransactionPort port = new SpringTransactionPort(tm, () -> NOW); - - TransactionResult result = - port.inTransaction( - commandRequest(TransactionPolicyId.COMMAND_DEFAULT, Duration.ofSeconds(5)), () -> "ok"); - - assertThat(result).isInstanceOf(TransactionResult.Committed.class); - assertThat(result.outcome()).isEqualTo(TransactionOutcome.COMMITTED); - TransactionDefinition definition = tm.definitions.getFirst(); - assertThat(definition.getPropagationBehavior()) - .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRED); - assertThat(definition.getIsolationLevel()) - .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); - assertThat(definition.isReadOnly()).isFalse(); - assertThat(definition.getTimeout()).isEqualTo(5); - } - - @Test - void serializableReplaySafePolicyPinsSerializableIsolation() { - RecordingTransactionManager tm = new RecordingTransactionManager(true); - SpringTransactionPort port = new SpringTransactionPort(tm, () -> NOW); - - port.inTransaction( - commandRequest(TransactionPolicyId.COMMAND_SERIALIZABLE_REPLAY_SAFE, Duration.ofSeconds(5)), - () -> "ok"); - - assertThat(tm.definitions.getFirst().getIsolationLevel()) - .isEqualTo(TransactionDefinition.ISOLATION_SERIALIZABLE); - } - - @Test - void primaryQueryIsReadOnlyAndDoesNotRequireAnOperationId() { - RecordingTransactionManager tm = new RecordingTransactionManager(true); - SpringTransactionPort port = new SpringTransactionPort(tm, () -> NOW); - TransactionRequest request = - new TransactionRequest( - TransactionPolicyId.QUERY_PRIMARY, - CallBudget.after(NOW, Duration.ofSeconds(5)), - Optional.of(ReadConsistency.STRONG), - Optional.empty()); - - TransactionResult result = port.inTransaction(request, () -> "query"); - - assertThat(result.outcome()).isEqualTo(TransactionOutcome.COMMITTED); - assertThat(tm.definitions.getFirst().isReadOnly()).isTrue(); - } - - @Test - void maintenancePolicyUsesRequiresNew() { - RecordingTransactionManager tm = new RecordingTransactionManager(true); - SpringTransactionPort port = new SpringTransactionPort(tm, () -> NOW); - - port.inTransaction( - commandRequest(TransactionPolicyId.MAINTENANCE_NEW, Duration.ofSeconds(5)), () -> "ok"); - - assertThat(tm.definitions.getFirst().getPropagationBehavior()) - .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - } - - @Test - void participatingRequiredBoundaryNeverClaimsCommit() { - RecordingTransactionManager tm = new RecordingTransactionManager(false); - SpringTransactionPort port = new SpringTransactionPort(tm, () -> NOW); - - TransactionResult result = - port.inTransaction( - commandRequest(TransactionPolicyId.COMMAND_DEFAULT, Duration.ofSeconds(5)), - () -> "pending"); - - assertThat(result).isInstanceOf(TransactionResult.Participating.class); - assertThat(result.outcome()).isEqualTo(TransactionOutcome.PARTICIPATING_PENDING_OUTER); - } - - @Test - void actionFailureWithConfirmedRollbackIsDeterminate() { - RecordingTransactionManager tm = new RecordingTransactionManager(true); - SpringTransactionPort port = new SpringTransactionPort(tm, () -> NOW); - - TransactionResult result = - port.inTransaction( - commandRequest(TransactionPolicyId.COMMAND_DEFAULT, Duration.ofSeconds(5)), - () -> { - throw new IllegalStateException("action failed"); - }); - - assertThat(result).isInstanceOf(TransactionResult.DeterminateRollback.class); - assertThat(result.outcome()).isEqualTo(TransactionOutcome.DETERMINATE_ROLLBACK); - assertThat(tm.rollbacks).isOne(); - } - - @Test - // The anonymous TransactionException is a local failure stand-in; it never leaves the test. - @SuppressWarnings("serial") - void commitFailureWithoutAckIsIndeterminateAndIsNeverReplayed() { - RecordingTransactionManager tm = new RecordingTransactionManager(true); - tm.commitFailure = new TransactionException("connection lost during commit") {}; - SpringTransactionPort port = new SpringTransactionPort(tm, () -> NOW); - int[] calls = {0}; - - TransactionResult result = - port.inTransaction( - commandRequest( - TransactionPolicyId.COMMAND_SERIALIZABLE_REPLAY_SAFE, Duration.ofSeconds(5)), - () -> { - calls[0]++; - return "uncertain"; - }); - - assertThat(result).isInstanceOf(TransactionResult.Indeterminate.class); - assertThat(result.outcome()).isEqualTo(TransactionOutcome.INDETERMINATE); - assertThat(((TransactionResult.Indeterminate) result).lastObservedPhase()) - .isEqualTo(TransactionPhase.COMMIT_REQUESTED); - assertThat(calls[0]).isOne(); - } - - @Test - // The anonymous TransactionException is a local failure stand-in; it never leaves the test. - @SuppressWarnings("serial") - void serializationFailureReportedByCommitIsDeterminateAndReplaySafe() { - RecordingTransactionManager tm = new RecordingTransactionManager(true); - tm.commitFailure = - new TransactionException("serialization rejected at commit", dataFailure("40001")) {}; - SpringTransactionPort port = new SpringTransactionPort(tm, () -> NOW); - int[] calls = {0}; - - TransactionResult result = - port.inTransaction( - commandRequest( - TransactionPolicyId.COMMAND_SERIALIZABLE_REPLAY_SAFE, Duration.ofSeconds(5)), - () -> { - calls[0]++; - if (calls[0] > 1) { - tm.commitFailure = null; - } - return "replayed"; - }); - - assertThat(result.outcome()).isEqualTo(TransactionOutcome.COMMITTED); - assertThat(calls[0]).isEqualTo(2); - assertThat(tm.definitions).hasSize(2); - } - - @Test - void unexpectedRollbackIsDeterminate() { - RecordingTransactionManager tm = new RecordingTransactionManager(true); - tm.commitFailure = new UnexpectedRollbackException("rollback-only"); - SpringTransactionPort port = new SpringTransactionPort(tm, () -> NOW); - - TransactionResult result = - port.inTransaction( - commandRequest(TransactionPolicyId.COMMAND_DEFAULT, Duration.ofSeconds(5)), - () -> "rolled back"); - - assertThat(result.outcome()).isEqualTo(TransactionOutcome.DETERMINATE_ROLLBACK); - } - - @Test - void insufficientBudgetRejectsBeforeTransactionManagerAcquisition() { - RecordingTransactionManager tm = new RecordingTransactionManager(true); - SpringTransactionPort port = new SpringTransactionPort(tm, () -> NOW); - - assertThatThrownBy( - () -> - port.inTransaction( - commandRequest(TransactionPolicyId.COMMAND_DEFAULT, Duration.ofMillis(999)), - () -> "must-not-run")) - .isInstanceOf(TransactionAdmissionException.class) - .hasMessageContaining("one second"); - assertThat(tm.definitions).isEmpty(); - } - - @Test - void transactionTimeoutUsesAConservativeWholeSecondFloor() { - RecordingTransactionManager tm = new RecordingTransactionManager(true); - SpringTransactionPort port = new SpringTransactionPort(tm, () -> NOW); - - port.inTransaction( - commandRequest(TransactionPolicyId.COMMAND_DEFAULT, Duration.ofMillis(2_999)), () -> "ok"); - - assertThat(tm.definitions.getFirst().getTimeout()).isEqualTo(2); - } - - @Test - void unavailableReplicaPolicyFailsBeforeOpeningATransaction() { - RecordingTransactionManager tm = new RecordingTransactionManager(true); - SpringTransactionPort port = new SpringTransactionPort(tm, () -> NOW); - TransactionRequest request = - new TransactionRequest( - TransactionPolicyId.QUERY_REPLICA_ELIGIBLE, - CallBudget.after(NOW, Duration.ofSeconds(5)), - Optional.of(ReadConsistency.EVENTUAL), - Optional.empty()); - - assertThatThrownBy(() -> port.inTransaction(request, () -> "must-not-run")) - .isInstanceOf(TransactionAdmissionException.class) - .hasMessageContaining("replica"); - assertThat(tm.definitions).isEmpty(); - } - - @Test - void appliesLocalTimeoutsBeforeTheBusinessAction() { - RecordingTransactionManager tm = new RecordingTransactionManager(true); - JpaTransactionSettings settings = - new JpaTransactionSettings(null, null, null, null, null, null, null, null, null); - AtomicReference configured = new AtomicReference<>(); - SpringTransactionPort port = - new SpringTransactionPort( - tm, - () -> NOW, - TransactionDeadlineCalculator.withoutAcquisitionEnvelope(settings), - configured::set); - - TransactionResult result = - port.inTransaction( - commandRequest(TransactionPolicyId.COMMAND_DEFAULT, Duration.ofSeconds(20)), - () -> { - assertThat(configured.get()).isNotNull(); - return "configured"; - }); - - assertThat(result.outcome()).isEqualTo(TransactionOutcome.COMMITTED); - assertThat(configured.get().statementTimeout()).isEqualTo(Duration.ofSeconds(10)); - } - - @Test - void localTimeoutFailureRollsBackBeforeTheBusinessAction() { - RecordingTransactionManager tm = new RecordingTransactionManager(true); - AtomicBoolean actionCalled = new AtomicBoolean(); - JpaTransactionSettings settings = - new JpaTransactionSettings(null, null, null, null, null, null, null, null, null); - SpringTransactionPort port = - new SpringTransactionPort( - tm, - () -> NOW, - TransactionDeadlineCalculator.withoutAcquisitionEnvelope(settings), - ignored -> { - throw new IllegalStateException("local timeout failed"); - }); - - TransactionResult result = - port.inTransaction( - commandRequest(TransactionPolicyId.COMMAND_DEFAULT, Duration.ofSeconds(20)), - () -> { - actionCalled.set(true); - return "must-not-run"; - }); - - assertThat(result.outcome()).isEqualTo(TransactionOutcome.DETERMINATE_ROLLBACK); - assertThat(actionCalled).isFalse(); - assertThat(tm.rollbacks).isOne(); - } - - @Test - void replaySafeSerializablePolicyRetriesOnlyADeterminateSerializationRollback() { - RecordingTransactionManager tm = new RecordingTransactionManager(true); - SpringTransactionPort port = new SpringTransactionPort(tm, () -> NOW); - int[] calls = {0}; - - TransactionResult result = - port.inTransaction( - commandRequest( - TransactionPolicyId.COMMAND_SERIALIZABLE_REPLAY_SAFE, Duration.ofSeconds(5)), - () -> { - calls[0]++; - if (calls[0] == 1) { - throw dataFailure("40001"); - } - return "replayed"; - }); - - assertThat(result.outcome()).isEqualTo(TransactionOutcome.COMMITTED); - assertThat(calls[0]).isEqualTo(2); - assertThat(tm.rollbacks).isOne(); - assertThat(tm.definitions).hasSize(2); - } - - @Test - void participatingSerializableBoundaryNeverRetriesInsideTheAmbientTransaction() { - RecordingTransactionManager tm = new RecordingTransactionManager(false); - SpringTransactionPort port = new SpringTransactionPort(tm, () -> NOW); - int[] calls = {0}; - - TransactionResult result = - port.inTransaction( - commandRequest( - TransactionPolicyId.COMMAND_SERIALIZABLE_REPLAY_SAFE, Duration.ofSeconds(5)), - () -> { - calls[0]++; - if (calls[0] == 1) { - throw dataFailure("40001"); - } - return "must-not-replay-inside-ambient-transaction"; - }); - - assertThat(result).isInstanceOf(TransactionResult.DeterminateRollback.class); - assertThat(calls[0]).isOne(); - assertThat(tm.definitions).hasSize(1); - } - - @Test - void ordinaryCommandNeverRetriesTheSameSerializationFailure() { - RecordingTransactionManager tm = new RecordingTransactionManager(true); - SpringTransactionPort port = new SpringTransactionPort(tm, () -> NOW); - int[] calls = {0}; - - TransactionResult result = - port.inTransaction( - commandRequest(TransactionPolicyId.COMMAND_DEFAULT, Duration.ofSeconds(5)), - () -> { - calls[0]++; - throw dataFailure("40001"); - }); - - assertThat(result.outcome()).isEqualTo(TransactionOutcome.DETERMINATE_ROLLBACK); - assertThat(calls[0]).isOne(); - } - - private static TransactionRequest commandRequest( - TransactionPolicyId policyId, Duration duration) { - return new TransactionRequest( - policyId, CallBudget.after(NOW, duration), Optional.empty(), Optional.of(OPERATION_ID)); - } - - private static DataAccessResourceFailureException dataFailure(String sqlState) { - return new DataAccessResourceFailureException( - "database operation failed", new SQLException("sanitized", sqlState)); - } - - private static final class RecordingTransactionManager implements PlatformTransactionManager { - - private final boolean newTransaction; - private final List definitions = new ArrayList<>(); - private int rollbacks; - private RuntimeException commitFailure; - - private RecordingTransactionManager(boolean newTransaction) { - this.newTransaction = newTransaction; - } - - @Override - public TransactionStatus getTransaction(TransactionDefinition definition) - throws TransactionException { - definitions.add(definition); - return new SimpleTransactionStatus(newTransaction); - } - - @Override - public void commit(TransactionStatus status) throws TransactionException { - if (commitFailure != null) { - throw commitFailure; - } - } - - @Override - public void rollback(TransactionStatus status) throws TransactionException { - rollbacks++; - } - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/TransactionDeadlineCalculatorTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/TransactionDeadlineCalculatorTest.java deleted file mode 100644 index abc0b1b4..00000000 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/TransactionDeadlineCalculatorTest.java +++ /dev/null @@ -1,84 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.transaction; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.application.outbound.CallBudget; -import dev.caskeleton.application.transaction.TransactionAdmissionException; -import java.time.Duration; -import org.junit.jupiter.api.Test; - -class TransactionDeadlineCalculatorTest { - - private static final long NOW = 1_000_000L; - private static final JpaTransactionSettings SETTINGS = - new JpaTransactionSettings( - Duration.ofSeconds(30), - Duration.ofMillis(250), - Duration.ofSeconds(1), - Duration.ofMillis(500), - Duration.ofSeconds(10), - Duration.ofSeconds(2), - Duration.ofSeconds(15), - Duration.ofMillis(250), - Duration.ofMillis(100)); - - @Test - void rejectsBeforePoolWhenTheAcquisitionAndActionEnvelopeDoesNotFit() { - TransactionDeadlineCalculator calculator = - new TransactionDeadlineCalculator(Duration.ofSeconds(3), SETTINGS); - CallBudget insufficient = CallBudget.after(NOW, Duration.ofMillis(4_749)); - - assertThatThrownBy(() -> calculator.beforeAcquisition(insufficient, NOW)) - .isInstanceOf(TransactionAdmissionException.class) - .hasMessageContaining("pool acquisition"); - } - - @Test - void springTimeoutUsesSafeWholeSecondFloorAtBoundary() { - TransactionDeadlineCalculator calculator = - TransactionDeadlineCalculator.withoutAcquisitionEnvelope(SETTINGS); - - assertThatThrownBy( - () -> calculator.beforeAcquisition(CallBudget.after(NOW, Duration.ofMillis(999)), NOW)) - .isInstanceOf(TransactionAdmissionException.class); - assertThat( - calculator - .beforeAcquisition(CallBudget.after(NOW, Duration.ofSeconds(1)), NOW) - .springTimeoutSeconds()) - .isOne(); - assertThat( - calculator - .beforeAcquisition(CallBudget.after(NOW, Duration.ofMillis(1_001)), NOW) - .springTimeoutSeconds()) - .isOne(); - } - - @Test - void computesStatementLockAndIdleTimeoutsInsideTheRemainingWindow() { - TransactionDeadlineCalculator calculator = - new TransactionDeadlineCalculator(Duration.ofSeconds(3), SETTINGS); - CallBudget budget = CallBudget.after(NOW, Duration.ofSeconds(20)); - TransactionStartBudget start = calculator.beforeAcquisition(budget, NOW); - - EffectiveTransactionTimeouts effective = - calculator.afterBegin(budget, NOW + Duration.ofSeconds(1).toNanos(), start); - - assertThat(effective.statementTimeout()).isEqualTo(Duration.ofSeconds(10)); - assertThat(effective.lockTimeout()).isEqualTo(Duration.ofSeconds(2)); - assertThat(effective.idleGuardTimeout()).isEqualTo(Duration.ofSeconds(15)); - } - - @Test - void poolWaitOvershootFailsBeforeLocalTimeoutOrBusinessStatement() { - TransactionDeadlineCalculator calculator = - new TransactionDeadlineCalculator(Duration.ofSeconds(3), SETTINGS); - CallBudget budget = CallBudget.after(NOW, Duration.ofSeconds(6)); - TransactionStartBudget start = calculator.beforeAcquisition(budget, NOW); - - assertThatThrownBy( - () -> calculator.afterBegin(budget, NOW + Duration.ofMillis(5_800).toNanos(), start)) - .isInstanceOf(TransactionAdmissionException.class) - .hasMessageContaining("after transaction begin"); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/TransactionDefinitionMapperTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/TransactionDefinitionMapperTest.java deleted file mode 100644 index caf43074..00000000 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/TransactionDefinitionMapperTest.java +++ /dev/null @@ -1,69 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.transaction; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.outbound.persistence.api.transaction.IsolationLevel; -import dev.caskeleton.adapter.outbound.persistence.api.transaction.PropagationMode; -import dev.caskeleton.adapter.outbound.persistence.api.transaction.RetryProfile; -import dev.caskeleton.adapter.outbound.persistence.api.transaction.TransactionProfile; -import java.sql.Connection; -import java.time.Duration; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.springframework.transaction.TransactionDefinition; - -/** Plan Task 7 — a profile maps to exactly the definition it describes (design §9.2). */ -class TransactionDefinitionMapperTest { - - @Test - @DisplayName("a serializable read-only profile maps isolation, read-only, and timeout") - void mapsSerializableReadOnlyProfile() { - var profile = - new TransactionProfile( - "report.read", - PropagationMode.REQUIRED, - IsolationLevel.SERIALIZABLE, - Duration.ofSeconds(3), - true, - RetryProfile.none()); - - TransactionDefinition definition = TransactionDefinitionMapper.definitionOf(profile); - - assertThat(definition.getIsolationLevel()).isEqualTo(Connection.TRANSACTION_SERIALIZABLE); - assertThat(definition.isReadOnly()).isTrue(); - assertThat(definition.getTimeout()).isEqualTo(3); - } - - @Test - @DisplayName("a sub-second timeout rounds up rather than truncating to zero") - void subSecondTimeoutRoundsUp() { - assertThat(TransactionDefinitionMapper.timeoutSecondsOf(Duration.ofMillis(1500))).isEqualTo(2); - assertThat(TransactionDefinitionMapper.timeoutSecondsOf(Duration.ofMillis(1))).isEqualTo(1); - } - - @Test - @DisplayName("a zero timeout means the connection default") - void zeroTimeoutIsTheConnectionDefault() { - assertThat(TransactionDefinitionMapper.timeoutSecondsOf(Duration.ZERO)) - .isEqualTo(TransactionDefinition.TIMEOUT_DEFAULT); - } - - @Test - @DisplayName("a negative timeout is rejected") - void negativeTimeoutIsRejected() { - assertThatThrownBy(() -> TransactionDefinitionMapper.timeoutSecondsOf(Duration.ofSeconds(-1))) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - @DisplayName("each supported propagation maps to its Spring constant") - void mapsEveryPropagation() { - assertThat(TransactionDefinitionMapper.propagationOf(PropagationMode.REQUIRED)) - .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRED); - assertThat(TransactionDefinitionMapper.propagationOf(PropagationMode.MANDATORY)) - .isEqualTo(TransactionDefinition.PROPAGATION_MANDATORY); - assertThat(TransactionDefinitionMapper.propagationOf(PropagationMode.REQUIRES_NEW)) - .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/TransactionEvidenceScopeTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/TransactionEvidenceScopeTest.java deleted file mode 100644 index 5e0b71da..00000000 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/TransactionEvidenceScopeTest.java +++ /dev/null @@ -1,128 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.transaction; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.adapter.outbound.persistence.api.PersistenceOperationName; -import dev.caskeleton.adapter.outbound.persistence.api.transaction.TransactionCompletionEvidence; -import java.time.Instant; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * One owner per evidence frame. - * - *

Two owners popped: the transaction manager on commit and rollback, and the executor's {@code - * finally} whenever the top frame's operation and attempt matched its own. A {@code REQUIRES_NEW} - * inner transaction under an outer one has the same operation and — on the default path, where both - * are attempt 1 — the same attempt number, so the executor's check described the outer frame - * exactly as well as its own. The outer frame was deleted, and the outer transaction's later commit - * failure was reported as an unattributed attempt 1 with no reconciliation key. - */ -class TransactionEvidenceScopeTest { - - private static final PersistenceOperationName OPERATION = - new PersistenceOperationName("order.write"); - private static final Instant NOW = Instant.parse("2026-08-14T00:00:00Z"); - - @AfterEach - void clearThread() { - TransactionEvidenceContext.clearAll(); - } - - @Test - @DisplayName("an inner scope closing leaves the outer frame intact") - void anInnerScopeClosingLeavesTheOuterFrameIntact() { - try (var outer = TransactionEvidenceContext.begin(OPERATION, "order-42", NOW, 1)) { - try (var inner = TransactionEvidenceContext.begin(OPERATION, "order-42-inner", NOW, 1)) { - assertThat(inner.released()).isFalse(); - } - - assertThat(TransactionEvidenceContext.current()).isPresent(); - assertThat( - TransactionEvidenceContext.current() - .flatMap(TransactionEvidenceFrame::reconciliationKey)) - .as("the outer transaction's key must survive the inner one finishing") - .contains("order-42"); - assertThat(outer.released()).isFalse(); - } - - assertThat(TransactionEvidenceContext.current()).isEmpty(); - } - - @Test - @DisplayName("marking a phase does not detach the frame from its scope") - void markingAPhaseDoesNotDetachTheFrameFromItsScope() { - try (var scope = TransactionEvidenceContext.begin(OPERATION, "order-42", NOW, 3)) { - TransactionEvidenceContext.mark(TransactionCompletionEvidence.COMMITTING); - - assertThat(TransactionEvidenceContext.evidence()) - .isEqualTo(TransactionCompletionEvidence.COMMITTING); - assertThat(scope.released()).isFalse(); - } - - assertThat(TransactionEvidenceContext.current()).isEmpty(); - } - - @Test - @DisplayName("closing out of order pops nothing rather than somebody else's frame") - void closingOutOfOrderPopsNothing() { - var outer = TransactionEvidenceContext.begin(OPERATION, "outer", NOW, 1); - var inner = TransactionEvidenceContext.begin(OPERATION, "inner", NOW, 1); - - outer.close(); - - assertThat( - TransactionEvidenceContext.current() - .flatMap(TransactionEvidenceFrame::reconciliationKey)) - .as("a lifecycle that did not nest is a bug; deleting an unrelated frame hides it") - .contains("inner"); - - inner.close(); - assertThat(TransactionEvidenceContext.current()) - .as("the outer frame is still there, because its close refused") - .isPresent(); - } - - @Test - @DisplayName("a second close is a no-op") - void aSecondCloseIsANoOp() { - var outer = TransactionEvidenceContext.begin(OPERATION, "outer", NOW, 1); - var inner = TransactionEvidenceContext.begin(OPERATION, "inner", NOW, 1); - - inner.close(); - inner.close(); - - assertThat( - TransactionEvidenceContext.current() - .flatMap(TransactionEvidenceFrame::reconciliationKey)) - .contains("outer"); - outer.close(); - } - - @Test - @DisplayName("no raw thread-local value survives a completed scope") - void noRawThreadLocalValueSurvivesACompletedScope() { - try (var ignored = TransactionEvidenceContext.begin(OPERATION, "order-42", NOW, 1)) { - assertThat(TransactionEvidenceContext.hasRawThreadLocalValue()).isTrue(); - } - - assertThat(TransactionEvidenceContext.hasRawThreadLocalValue()) - .as("a pooled thread must not carry an empty deque into unrelated work") - .isFalse(); - } - - @Test - @DisplayName("reading after the last frame does not re-register the thread-local") - void readingAfterTheLastFrameDoesNotReRegisterTheThreadLocal() { - TransactionEvidenceContext.begin(OPERATION, "order-42", NOW, 1).close(); - - assertThat(TransactionEvidenceContext.current()).isEmpty(); - assertThat(TransactionEvidenceContext.evidence()) - .isEqualTo(TransactionCompletionEvidence.NOT_STARTED); - - assertThat(TransactionEvidenceContext.hasRawThreadLocalValue()) - .as("withInitial installed a value on every read, undoing the removal it was asked about") - .isFalse(); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/TransactionProfileRegistryTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/TransactionProfileRegistryTest.java deleted file mode 100644 index 57097f83..00000000 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/TransactionProfileRegistryTest.java +++ /dev/null @@ -1,44 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.transaction; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.outbound.persistence.api.transaction.TransactionProfile; -import java.time.Duration; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** Plan Task 9 — profile lookup is fail-closed (design §9.2). */ -class TransactionProfileRegistryTest { - - private final TransactionProfileRegistry registry = - TransactionProfileRegistry.of( - TransactionProfile.write("order.write", Duration.ofSeconds(5)), - TransactionProfile.read("order.read", Duration.ZERO)); - - @Test - @DisplayName("a registered profile resolves") - void resolvesRegisteredProfile() { - assertThat(registry.require("order.write").readOnly()).isFalse(); - assertThat(registry.require("order.read").readOnly()).isTrue(); - } - - @Test - @DisplayName("a mistyped profile name fails rather than falling back to a default") - void unregisteredProfileFails() { - assertThatThrownBy(() -> registry.require("order.wrtie")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("unregistered transaction profile"); - } - - @Test - @DisplayName("a duplicate registration is rejected") - void duplicateRegistrationFails() { - assertThatThrownBy( - () -> - TransactionProfileRegistry.of( - TransactionProfile.write("order.write", Duration.ofSeconds(5)), - TransactionProfile.write("order.write", Duration.ofSeconds(9)))) - .isInstanceOf(IllegalArgumentException.class); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/TransactionRetryBackoffTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/TransactionRetryBackoffTest.java deleted file mode 100644 index 0853eaae..00000000 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/TransactionRetryBackoffTest.java +++ /dev/null @@ -1,128 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.transaction; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.application.outbound.CallBudget; -import java.time.Duration; -import java.util.concurrent.atomic.AtomicLong; -import org.junit.jupiter.api.Test; - -class TransactionRetryBackoffTest { - - @Test - void appliesBoundedFullJitterOnlyWhenTheAbsoluteBudgetCanContainTheNextAttempt() { - AtomicLong now = new AtomicLong(1_000); - AtomicLong slept = new AtomicLong(); - JpaTransactionSettings settings = - new JpaTransactionSettings( - null, - null, - null, - null, - null, - null, - null, - null, - null, - Duration.ofMillis(20), - Duration.ofMillis(80), - 3); - TransactionRetryBackoff backoff = - new TransactionRetryBackoff( - settings, - now::get, - nanos -> { - slept.addAndGet(nanos); - now.addAndGet(nanos); - }, - bound -> bound - 1); - - boolean retry = backoff.pauseBeforeRetry(CallBudget.after(now.get(), Duration.ofSeconds(5)), 1); - - assertThat(retry).isTrue(); - assertThat(slept.get()).isEqualTo(Duration.ofMillis(20).toNanos()); - } - - @Test - void refusesToSleepWhenBackoffWouldConsumeTheMinimumNextAttemptWindow() { - AtomicLong now = new AtomicLong(1_000); - AtomicLong slept = new AtomicLong(); - JpaTransactionSettings settings = - new JpaTransactionSettings( - null, - null, - null, - null, - null, - null, - null, - null, - null, - Duration.ofMillis(20), - Duration.ofMillis(80), - 3); - TransactionRetryBackoff backoff = - new TransactionRetryBackoff(settings, now::get, slept::addAndGet, bound -> bound - 1); - - boolean retry = - backoff.pauseBeforeRetry(CallBudget.after(now.get(), Duration.ofMillis(200)), 1); - - assertThat(retry).isFalse(); - assertThat(slept).hasValue(0); - } - - @Test - void reservesConnectionAcquisitionEnvelopeForTheNextAttempt() { - AtomicLong now = new AtomicLong(1_000); - AtomicLong slept = new AtomicLong(); - JpaTransactionSettings settings = - new JpaTransactionSettings( - null, - null, - null, - null, - null, - null, - null, - null, - null, - Duration.ofMillis(20), - Duration.ofMillis(80), - 3); - TransactionRetryBackoff backoff = - new TransactionRetryBackoff( - settings, Duration.ofSeconds(1), now::get, slept::addAndGet, bound -> bound - 1); - - boolean retry = backoff.pauseBeforeRetry(CallBudget.after(now.get(), Duration.ofSeconds(2)), 1); - - assertThat(retry).isFalse(); - assertThat(slept).hasValue(0); - } - - @Test - void exponentialDelayIsCappedBeforeJitter() { - AtomicLong now = new AtomicLong(1_000); - AtomicLong slept = new AtomicLong(); - JpaTransactionSettings settings = - new JpaTransactionSettings( - null, - null, - null, - null, - null, - null, - null, - null, - null, - Duration.ofMillis(20), - Duration.ofMillis(30), - 4); - TransactionRetryBackoff backoff = - new TransactionRetryBackoff(settings, now::get, slept::addAndGet, bound -> bound - 1); - - backoff.pauseBeforeRetry(CallBudget.after(now.get(), Duration.ofSeconds(5)), 3); - - assertThat(slept).hasValue(Duration.ofMillis(30).toNanos()); - assertThat(backoff.maximumAttempts()).isEqualTo(4); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/TransactionRetryClassifierTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/TransactionRetryClassifierTest.java deleted file mode 100644 index 96b71b4c..00000000 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/transaction/TransactionRetryClassifierTest.java +++ /dev/null @@ -1,41 +0,0 @@ -package dev.caskeleton.adapter.outbound.persistence.transaction; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.sql.SQLException; -import org.junit.jupiter.api.Test; -import org.springframework.dao.DataAccessResourceFailureException; - -class TransactionRetryClassifierTest { - - @Test - void onlySerializationAndDeadlockStatesAreWholeTransactionReplayCandidates() { - assertThat(TransactionRetryClassifier.isReplayCandidate(failure("40001"))).isTrue(); - assertThat(TransactionRetryClassifier.isReplayCandidate(failure("40P01"))).isTrue(); - assertThat(TransactionRetryClassifier.isReplayCandidate(failure("23505"))).isFalse(); - assertThat(TransactionRetryClassifier.isReplayCandidate(failure("08007"))).isFalse(); - } - - @Test - // The anonymous exception exists to build a self-referential cause chain in place; it is never - // serialized. - @SuppressWarnings("serial") - void selfReferentialOrMissingCauseChainsFailClosed() { - RuntimeException selfReferential = - new RuntimeException("loop") { - @Override - public synchronized Throwable getCause() { - return this; - } - }; - - assertThat(TransactionRetryClassifier.isReplayCandidate(selfReferential)).isFalse(); - assertThat(TransactionRetryClassifier.isReplayCandidate(new IllegalStateException("no sql"))) - .isFalse(); - } - - private static DataAccessResourceFailureException failure(String sqlState) { - return new DataAccessResourceFailureException( - "database operation failed", new SQLException("sanitized", sqlState)); - } -} diff --git a/src/adapter/outbound/persistence-jpa/src/test/resources/db/applied-migrations.sha256 b/src/adapter/outbound/persistence-jpa/src/test/resources/db/applied-migrations.sha256 new file mode 100644 index 00000000..6b605c49 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/test/resources/db/applied-migrations.sha256 @@ -0,0 +1,31 @@ +# SHA-256 (LF-normalized) of every versioned migration in src/main/resources/db/migration. +# An applied migration is never edited: Flyway validates its checksum on every start. +# Add a line when adding a migration; change a line only for a file no database can have applied. +741916fa569f4d90c20cad3f9c1e1a4aab70971f72265f4713b9710fa9db9a10 jpa/core/V1__initialize_or_adopt.sql +18dd16fe7f7cc902da8947b5ce830b06d6cd7833ba2d431e72105d6f7fce6021 jpa/core/V2__widen_capability_schema_stream.sql +2ba4214941a5563613b0dcc4f7cbf5f1278e342b900268721466e4bdeaa2fef2 jpa/idempotency/V1__expand_owner_safe_v2.sql +95be788589f01e32c9179acc80817e227e81805f8d518e8a9ac36e1c31b51da7 jpa/idempotency/V2__request_hash_varchar.sql +4379872989af0c97b937ff48527c788a2ba0216218d4df9435eba8c6e053ad8d jpa/notification-platform/V10__variables_payload_envelope_guard.sql +1ac7cc1c2509868eb0ce202e1917bb36846f98f17ad4922abe3fac0ef128199b jpa/notification-platform/V1__notification_platform_core.sql +0add67aa23580e51712f84fabe9b09e08401ef708cfa1b3292b120fdb5c12fa2 jpa/notification-platform/V2__notification_platform_contact_template_policy.sql +f5b98598a59cc4376f5d233b410f8a5ae9f3cd94156291ebdf2d0da5a66f34ef jpa/notification-platform/V3__notification_platform_inbox_admin.sql +4ef3bb9928e3870c9c3d47d41d9ac8db61e679eb9a20c4e275bd6e54c592748c jpa/notification-platform/V4__notification_platform_alignment_and_activation.sql +ff01b7ad09bc4db6d9797a104e3ca1dc88ff753bdc98719fd65d11443ecb6fcd jpa/notification-platform/V5__notification_recipient_expiry.sql +db82463d7718ecd3378a63d04685766a5f8a83c806bc82b4d9b2f04fb961d26d jpa/notification-platform/V6__notification_projection_facts.sql +b44e4e8612295b425c58223313611f762ac2fe0b3abb6dc79c94133b704aabd5 jpa/notification-platform/V7__notification_collapse.sql +c5f9c638c6d5b7768e803a23b3f16e9e0a5e09918c0838ed9c81cb6d9524ec9c jpa/notification-platform/V8__notification_admin_claim.sql +5fb1b1f8086249491b5fca40051a9ec60442e8226fe45f7c5a0f0056c8c5c07c jpa/notification-platform/V9__notification_evidence_certainty.sql +1f90005a2afb7eab905bba56e99c72698cf37a4b7e8b270d392c838e8226161d postgresql/V10__idempotency_request_hash_varchar.sql +74458691063ba3b5b6c1f8616ae255e99bd768218c9e8e3e7f0dc31e26983b20 postgresql/V11__durable_operation.sql +047108ca9163e704c50694a43b420b0e469f9b03fcca61a0efeac2bcfc96ccba postgresql/V12__live_event_log.sql +4f7f002601a13ef876a0fc04c8391d64ff9931c28e1f5e71cb8b2c92bfaff00d postgresql/V13__outbox_canonical_transport_compatibility.sql +6bb63fc01e43368d2cf86c0e0da5a0c22c35f2148cfc324e3e466e80fc098958 postgresql/V14__validate_outbox_canonical_constraints.sql +50e386675474ed09bd5317d160021c0e20cb61b2db52a90bc6d86bf703e7de7b postgresql/V15__live_event_stream_position.sql +1a5983c9212d6c155f0d7bea802bd9cd9c1055f3f0b055ba4168601146eeac0d postgresql/V16__outbox_canonical_hash_columns_varchar.sql +b8f571e6cada72a8f2776f4462509ce4b535c964c75b1c3cfb34b9dc07446d59 postgresql/V17__outbox_event_lease_fencing.sql +8ab106731d4d04d3719da0692069947736dc490ca46aa5a3ea9bdf65a5d956dc postgresql/V1__idempotency_record.sql +6b62a01a4eeb792b81015b4810ecc6f3f021e0a17dea50c871493f7694d4f0b9 postgresql/V3__outbox_event.sql +c57ab8a35a10079190ad8a563be58fae4147c9406c5bb752debb6998324ccdf6 postgresql/V4__int_lock.sql +6298a86a7bbe832bc7470d0cb771f31a64130c28b2b17754f8aaad5fa2e0f307 postgresql/V5__int_lock_expired_after.sql +e06eac70d11503b68fb949d0ff579353729bc00b1d846302363110375e81d8eb postgresql/V6__capability_schema_registry_adoption.sql +a7e997170496c0008e586c62191883ae629710319bf96b2aaedceb9b77b46845 postgresql/V9__widen_capability_schema_stream.sql diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/migration/ConcurrentIndexMigrationInspector.java b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/ConcurrentIndexMigrationInspector.java similarity index 97% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/migration/ConcurrentIndexMigrationInspector.java rename to src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/ConcurrentIndexMigrationInspector.java index 8662995b..715b5a0c 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/migration/ConcurrentIndexMigrationInspector.java +++ b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/ConcurrentIndexMigrationInspector.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.persistence.migration; +package dev.caskeleton.adapter.outbound.persistence.testkit.migration; import java.util.Locale; import java.util.Objects; diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/migration/FlywayValidationGate.java b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/FlywayValidationGate.java similarity index 97% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/migration/FlywayValidationGate.java rename to src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/FlywayValidationGate.java index f365a320..1ebe3b60 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/migration/FlywayValidationGate.java +++ b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/FlywayValidationGate.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.persistence.migration; +package dev.caskeleton.adapter.outbound.persistence.testkit.migration; import dev.caskeleton.adapter.outbound.persistence.api.PersistenceOperationName; import dev.caskeleton.adapter.outbound.persistence.api.error.JpaFailureContext; diff --git a/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/MigrationContractRunner.java b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/MigrationContractRunner.java index 008714f3..30cf9693 100644 --- a/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/MigrationContractRunner.java +++ b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/MigrationContractRunner.java @@ -1,6 +1,5 @@ package dev.caskeleton.adapter.outbound.persistence.testkit.migration; -import dev.caskeleton.adapter.outbound.persistence.migration.FlywayValidationGate; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/migration/MigrationResource.java b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/MigrationResource.java similarity index 87% rename from src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/migration/MigrationResource.java rename to src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/MigrationResource.java index eb798036..614452af 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/migration/MigrationResource.java +++ b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/MigrationResource.java @@ -1,4 +1,4 @@ -package dev.caskeleton.adapter.outbound.persistence.migration; +package dev.caskeleton.adapter.outbound.persistence.testkit.migration; import java.util.Objects; diff --git a/src/adapter/outbound/persistence-mongo/CLAUDE.md b/src/adapter/outbound/persistence-mongo/CLAUDE.md index ff41250d..c6e89d28 100644 --- a/src/adapter/outbound/persistence-mongo/CLAUDE.md +++ b/src/adapter/outbound/persistence-mongo/CLAUDE.md @@ -19,9 +19,10 @@ design package's assumed module layout onto this leaf lives in business domain. Real forks add their own document, repository, mapper, and application/domain port implementation. - It does **not** reimplement idempotency / outbox / lock on Mongo (those stay JPA-only). -- Opt-in: `MongoPersistenceConfig` re-imports the Mongo auto-configuration (`@ImportAutoConfiguration`) - only when `ca-skeleton.persistence-mongo.enabled=true` (default off). `MongoPlatformAutoConfiguration` - is gated on the same flag. The connection URI and database come from Spring's standard +- On when present: `MongoRootAutoConfiguration` and everything it imports run unless + `ca-skeleton.persistence-mongo.enabled=false` (`matchIfMissing = true`; the shipped + `config/mongo.yml` maps `APP_PERSISTENCE_MONGO_ENABLED`, default `true`). Absent from the build is + the ordinary off state. The connection URI and database come from Spring's standard `spring.mongodb.*` settings; platform profiles come from `ca-skeleton.persistence-mongo.platform.*`. The connection source is fail-closed: either `spring.mongodb.uri` / @@ -30,9 +31,14 @@ design package's assumed module layout onto this leaf lives in `MongoProfileClientSettingsAutoConfiguration` applies `MongoClientSettingsFactory` to Boot's actual `MongoClientSettings.Builder` at lowest precedence, so its TLS, Stable API, timeout and pool policy overrides generic defaults. -- `MongoOptInAutoConfigurationImportFilter`, registered through `META-INF/spring.factories`, blocks - Boot 4's classpath-driven sync/reactive/data/repository/health/metrics Mongo auto-configuration - when the module enable flag is absent or false. +- `MongoDefaultsEnvironmentPostProcessor`, registered through `META-INF/spring.factories`, loads + `config/mongo.yml` at lowest precedence and, on an explicit `enabled=false`, appends Boot 4's + Mongo auto-configurations (read from Boot's own registration files) to + `spring.autoconfigure.exclude`. +- Two kinds of surface. Auto-configured beans (listed in README.md "자동 구성") turn on with + `enabled=true`. Everything else is **library API** (README.md "라이브러리 API"): a service's own + adapter leaf takes this leaf as `implementation` and constructs the type. Library API is not + registered as a bean and has no property of its own. - Mongo health integration is leaf-owned. MongoRootAutoConfiguration imports the internal MongoPlatformHealthConfiguration, which adapts MongoPlatformHealthIndicator to Boot's HealthIndicator SPI under the stable bean name mongoPlatformHealthContributor. Application Actuator exposure policy still decides external endpoint exposure. ## Allowed @@ -43,20 +49,16 @@ design package's assumed module layout onto this leaf lives in `verifyCleanArchitectureDependencies` only checks that resolved edges are a subset of the declared ones, so an unused permission passes every run; `MongoRegistryPermissionParityTest` checks the other direction and fails when the two sets differ. -- The composition root declares `implementation(project(':adapter:outbound:persistence-mongo'))` — - with the reactive starter and the reactivestreams driver excluded, because there is no reactive - port in the shipped Stable scope. Consequently `ReactiveExecution`, `reactive/**` and the - driver-side change-stream source are unreachable in the default bootJar; their isolated tests are - library qualification, not proof of shipped runtime reachability. A fork adopting them must remove - both excludes, restore the reactive runtime graph and add a composition-level qualification. - The actual Gradle runtime graph is the runtime SSOT; - runtime classpath, so the membership cannot drift from what the jar carries. Property-only - activation therefore works here: the switch turns on a module that already ships, and shipping it - off is not the same contract as leaving it out, because absence cannot be reversed at deploy time - and hides every gating defect. `sample-portfolio` does not carry it. -- External includes the Mongo starters, spring-boot-autoconfigure, spring-boot-health, micrometer-core, slf4j-api, and the configuration processor. Jackson annotations are compile-only because Boot Health carries Jackson annotations while runtime JSON serialization remains application-owned. +- A service selects the leaf with one commented-out line in `app-bootstrap/build.gradle`, + `runtimeOnly project(':adapter:outbound:persistence-mongo')`; the default composition does not + carry it. The leaf is imperative only: the reactive twin (`reactive/**`, reactive + transactions/sessions), the change-stream consumer and the change-stream-to-messaging bridge were + removed on 2026-09-25 (see `docs/capability-status.md`), so the leaf carries neither the reactive + starter nor the reactive-streams driver (`MongoReactiveDriverAbsenceTest`). `sample-portfolio` + does not carry it. +- External includes the (sync) Mongo starter, spring-boot-autoconfigure, spring-boot-health, micrometer-core, slf4j-api, and the configuration processor. Jackson annotations are compile-only because Boot Health carries Jackson annotations while runtime JSON serialization remains application-owned. Versions come from the shared Spring Boot BOM; never pin the driver directly. -- Test-only: ArchUnit, reactor-test, Testcontainers (`mongodb`, `toxiproxy`). +- Test-only: ArchUnit, Testcontainers (`mongodb`, `toxiproxy`). ## Forbidden @@ -74,8 +76,8 @@ These reproduce the design's module dependency table. Breaking one fails the bui framework-free core contract; `api/package-info.java` records why. - No Stable package may depend on `…mongo.advanced..`. - No production package may depend on `…mongo.testkit..`. -- `imperative` ↛ `reactive`, `query` ↛ `aggregation`, `schema` ↛ execution packages, - `observation` ↛ execution packages, `migration` ↛ `migration.flamingock`. +- `query` ↛ `aggregation`, `schema` ↛ execution packages, `observation` ↛ execution packages, + `migration` ↛ `migration.flamingock`. ### Consistency-bound templates @@ -119,7 +121,7 @@ credential is a local for one call rather than a field, a bean property or a log When `platform.profiles` is non-empty, adoption is intentionally fail-closed. In one composition change provide the data-plane `MongoCredentialResolver` plus `MongoTopologyProbe`, `MongoSecurityProfile`, admin `MongoCredentialReference`, and `MongoSchemaVersionRange`; README.md -contains the complete 17-field production profile example. Supplying profiles piecemeal and +contains the complete 14-field production profile example. Supplying profiles piecemeal and discovering these requirements one startup failure at a time is not an accepted adoption path. Not shipped: the resolver implementation (a fork wires its own secret store), and the TLS lane @@ -127,18 +129,6 @@ Not shipped: the resolver implementation (a fork wires its own secret store), an certificates. Rotation ordering — new generation ready, traffic switch, old lease drain, close — is covered by `MongoClientGenerationConcurrencyTest`. -### Change-stream lifecycle - -`MongoChangeStreamPipeline` owns ordering: it drives events through `MongoChangeStreamRunner` with -`concatMap` and refuses any event behind its cluster-time high-water mark, so a checkpoint write -always means "everything up to here is done". Callers must feed it a `Flux` in stream order rather -than calling `runOne` themselves. - -The driver-side source — `watch`, `resumeAfter`/`startAfter`, cursor lifetime and reconnection — is -**not** shipped. A fork wires its `MongoChangeStreamSubscription` to the driver and feeds the -pipeline; the resume checkpoint it must pass back is `MongoResumeCheckpointStore`'s. Saying this -plainly is the point: the policy and value objects here do not add up to a running consumer. - ### Platform invariants that are not stylistic - Transaction body retry and commit retry are **separate loops**: a new session per body attempt, and @@ -153,20 +143,22 @@ plainly is the point: the policy and value objects here do not add up to a runni `@MongoAdvancedPolicy`, and an entry point takes a `MongoAdvancedCapabilityGuard` and calls `require` before it exists. `MongoAdvancedRules` enforces both halves; the classification rule is what keeps "we gate the executable ones" from meaning "the ones somebody remembered". -- The flags are bound from `ca-skeleton.persistence-mongo.advanced..enabled` by - `MongoAdvancedProperties`. `MongoAdvancedConfiguration` is imported by name, never auto-loaded: - the Stable lane must reference nothing under `..advanced..`. -- `MongoSearchOperations`, `MongoVectorSearchOperations` and `MongoTimeSeriesOperations` are - **scaffold** — contracts with no implementation in this repository. A fork supplies the Atlas or - time-series deployment and the implementation. +- The flags have no configuration property. The Advanced types are library API: the adopter's + adapter builds `MongoAdvancedCapabilityFlags` and the guard in code. The Stable auto-configuration + must reference nothing under `..advanced..`. +- Every setting key this leaf binds must change behaviour. A key that nothing reads, or one whose + only effect is to fail startup, is deleted rather than documented (AGENTS.md capability rule 3); + `docs/capability-status.md` records what was removed and why. +- An interface ships only with an implementation in this leaf. Search, vector, time series and + GridFS were contract-only and were removed on 2026-09-25. - Observation tags are limited to `MongoObservationConvention`'s allowlist. ## Tests -`MongoPersistenceConfigTest` proves default/false behavior through an actual -`@EnableAutoConfiguration` context, typed enablement binding, and enabled infrastructure with a -mock `MongoClient` plus a real `MongoTemplate` without a network connection. It must keep passing — -the platform additions are opt-in and must not turn the module on by existing. +`MongoCapabilityActivationTest` boots a real `SpringApplication` and proves present = on and an +explicit `enabled=false` = no client, template or platform bean (Boot's Mongo auto-configuration +included). `MongoPersistenceConfigTest` covers typed enablement binding and enabled infrastructure +with a mock `MongoClient` plus a real `MongoTemplate` without a network connection. Hermetic contract tests carry `@Tag("mongodb-contract")` and run in `mongoStableContractTest`, which `check` depends on. Container lanes carry `mongodb-replicaset` / `mongodb-failover` and run only in diff --git a/src/adapter/outbound/persistence-mongo/README.md b/src/adapter/outbound/persistence-mongo/README.md index 8d5d13f3..fe51e0c6 100644 --- a/src/adapter/outbound/persistence-mongo/README.md +++ b/src/adapter/outbound/persistence-mongo/README.md @@ -9,20 +9,27 @@ document/repository/mapper와 application 또는 domain port 구현을 추가할 매핑했는지는 [docs/mongodb/repository-adaptation.md](../../../../docs/mongodb/repository-adaptation.md)가 단일 기록이다. +## 제공하는 것 · 추가할 한 줄 · env 키 + +- 제공: `MongoClient`, `MongoTemplate`, 선택한 typed profile의 client 설정, 플랫폼 정책 bean + (아래 「자동 구성」), health contributor. 설정 기본값 `config/mongo.yml`을 모듈이 직접 읽는다 + (`MongoDefaultsEnvironmentPostProcessor`, 우선순위 가장 낮음). +- 추가할 한 줄: + + ```groovy + // app-bootstrap/build.gradle + runtimeOnly project(':adapter:outbound:persistence-mongo') // Mongo + ``` + + 이 줄을 지우면 client, template, 설정 기본값이 모두 함께 빠진다. 기본 조립에는 없다. +- 켜기와 끄기: 모듈이 있으면 켜진다. `APP_PERSISTENCE_MONGO_ENABLED=false`로만 끈다. 끄면 이 모듈의 + bean뿐 아니라 Spring Boot의 Mongo 자동 설정(`org.springframework.boot.mongodb.*`, + `org.springframework.boot.data.mongodb.*`)도 `spring.autoconfigure.exclude`로 빠진다. +- 필요한 env 키(`docs/registries/env-keys.yaml` SSOT): `APP_PERSISTENCE_MONGO_ACTIVE_PROFILE`, 그리고 + `SPRING_MONGODB_URI` 또는 선택한 profile의 `uri-secret` + `MongoCredentialResolver` bean. + ## 활성화 -### shipped runtime에 들어 있고, property가 그 스위치다 - -`app-bootstrap`은 이 leaf에 project dependency를 둔다(`src/app-bootstrap/build.gradle`; reactive -starter와 reactivestreams driver는 exclude). runtime 포함 여부의 SSOT는 이 실제 Gradle graph이고 -`MongoRegistryPermissionParityTest`는 composition edge가 존재하는지도 확인한다. 그래서 -`ca-skeleton.persistence-mongo.enabled=true`는 없는 모듈을 부르는 property가 아니라 이미 application -classpath에 들어 있는 모듈을 켜는 master switch다. - -빠져 있는 모듈은 꺼진 모듈과 같은 계약이 아니다. 부재는 배포 시점에 되돌릴 수 없고, gating 결함을 -전부 가린다. 존재하지 않는 코드는 자기 condition이 무엇이라고 말하든 bean을 하나도 들고 있지 않기 -때문이다. `sample-portfolio`는 이 leaf를 싣지 않는다. - `allowed_dependencies`는 `[]`다. 이 leaf는 어떤 project dependency도 쓰지 않으므로 — `domain-core`/`application-core`/`shared-contract`를 열어 두는 것은 "언젠가 쓸지도 모른다"를 registry가 미리 허용해 주는 것이었다. `verifyCleanArchitectureDependencies`는 실제 edge가 허용 집합의 부분집합인지만 @@ -30,7 +37,7 @@ classpath에 들어 있는 모듈을 켜는 master switch다. 허용 집합과 build가 선언한 project dependency가 정확히 같은지 — 를 확인한다. 실제 도메인 Mongo adapter가 application port를 구현하게 되면 build와 registry를 같은 변경에서 함께 넓힌다. -기본값은 비활성이다. 활성화한 배포는 connection source를 명시해야 하며 driver의 +켜진 배포는 connection source를 명시해야 하며 driver의 `mongodb://localhost:27017/test` 기본값으로 떨어지는 경로는 startup에서 거부한다. 표준 Boot 4 경로는 `SPRING_MONGODB_URI`가 relaxed binding으로 `spring.mongodb.uri`에 들어가는 방식이다. @@ -59,7 +66,7 @@ composition-owned bean을 함께 준비해야 한다. - `MongoSchemaVersionRange` 즉 client 생성에 필요한 resolver 하나와 platform startup validator가 요구하는 네 입력을 한 번에 -구성해야 한다. production profile의 17개 component는 다음 형태다. +구성해야 한다. production profile의 14개 component는 다음 형태다. ```yaml ca-skeleton: @@ -73,7 +80,6 @@ ca-skeleton: topology: REPLICA_SET production: true stable-api-strict: true - consistency-default: PRIMARY_MAJORITY server-selection-timeout: 3s connect-timeout: 2s socket-read-timeout: 5s @@ -82,24 +88,15 @@ ca-skeleton: pool-max-size: 40 pool-max-wait-time: 500ms uuid-representation: STANDARD - decimal-representation: DECIMAL128 - runtime-auto-create-indexes: false tls-required: true authentication-required: true ``` -### reactive / change-stream reachability +### 명령형 전용 -기본 `app-bootstrap`은 `spring-boot-starter-data-mongodb-reactive`와 -`mongodb-driver-reactivestreams`를 의도적으로 exclude한다. 따라서 이 저장소의 shipped runtime에서는 -`ReactiveMongoTemplate`이 존재하지 않고 `MongoPlatformAutoConfiguration.ReactiveExecution`도 활성화될 -수 없다. `reactive/**`, reactive cursor, driver-backed change-stream source는 **leaf에 있는 확장 코드이지 -현재 bootJar의 실행 기능이 아니다**. - -fork가 reactive Mongo를 실제로 채택하려면 두 exclude를 composition에서 제거하고 reactive starter/driver를 -runtime graph에 복구한 뒤, `ReactiveMongoTemplate` 조립과 별도 qualification을 함께 추가해야 한다. -change stream은 그 이후에도 `watch`/resume/cursor lifecycle source가 별도로 필요하다. 단위 테스트에서 -reactive template을 직접 주입해 녹색인 것은 shipped composition reachability 증거가 아니다. +이 leaf는 명령형(`MongoTemplate`) 경로만 제공한다. reactive 실행 경로, change stream consumer, +change-stream→messaging bridge는 2026-09-25에 삭제했다(`docs/capability-status.md` 「제거된 코드」). +reactive starter와 reactive-streams driver도 의존하지 않는다. 활성화 시 `MongoPersistenceConfig`가 Spring Boot의 Mongo client 및 data auto-configuration을 명시적으로 가져와 `MongoClient`와 `MongoTemplate`을 구성하고, `MongoPlatformAutoConfiguration`이 @@ -107,23 +104,71 @@ reactive template을 직접 주입해 녹색인 것은 shipped composition reach repository scanning은 템플릿이 임의로 소유하지 않는다. 실제 consumer가 자신의 repository package와 composition을 명시해야 한다. -Mongo starter는 classpath만으로도 Boot auto-configuration 후보를 등록하므로 config의 조건만으로는 -기본 비활성을 보장할 수 없다. `MongoOptInAutoConfigurationImportFilter`가 Boot 4의 sync/reactive -client, data, repository, health, metrics Mongo auto-configuration을 default/false에서 후보군에서 -제외한다. 필터는 Boot 4가 `AutoConfigurationImportFilter`를 찾는 `META-INF/spring.factories`에 -등록되어 있으며, `enabled=true`일 때는 후보를 그대로 허용한다. +Mongo starter는 classpath만으로도 Boot auto-configuration 후보를 등록하므로, 이 모듈의 조건만으로는 +`enabled=false`를 지킬 수 없다. `enabled=false`이면 `MongoDefaultsEnvironmentPostProcessor`가 Boot의 +Mongo auto-configuration 이름을 Boot 자신의 등록 파일에서 읽어 배포가 이미 둔 +`spring.autoconfigure.exclude` 값 뒤에 붙인다. 모듈이 없으면 Boot의 Mongo 모듈도 classpath에 없다. `MongoPersistenceSettings`는 모듈 opt-in만 소유한다. URI, database, credential은 Spring의 표준 `spring.mongodb.*` 설정을 사용한다. 플랫폼 profile은 -`ca-skeleton.persistence-mongo.platform.*` (`MongoPlatformProperties`)이 소유한다. +`ca-skeleton.persistence-mongo.platform.*` (`MongoPlatformSettings`)이 소유한다. + +## 자동 구성 — 모듈이 있고 `enabled=false`가 아니면 bean으로 등록된다 + +`MongoRootAutoConfiguration`, `MongoProfileClientSettingsAutoConfiguration`(`AutoConfiguration.imports`)과 +그것이 가져오는 설정이 등록하는 것: + +- Boot의 `MongoClient`/`MongoTemplate`(`MongoPersistenceConfig`), 선택된 typed profile의 client 설정 + (`MongoClientSettingsFactory`: TLS, Stable API, timeout, pool, UUID 표현) +- BSON 변환기와 type mapper(`MongoMappingConfiguration`), `MongoTypeRepresentationManifest` +- `MongoConsistencyRegistry`, `MongoConsistencyBinder`, `MongoCollectionProfileRegistry` +- `DefaultMongoImperativeExecutor`, `MongoAtomicOperationsTemplate`, `MongoBulkExecutor`, + `MongoAtomicPolicyRegistry`, `MongoBudgetEnforcer` +- `MongoFailureClassifier`, `MongoFailureTranslator`, `MongoOperationObserver`, driver 관측 listener +- startup 검증(`MongoTopologyProbe` bean이 있을 때 `MongoStartupValidator`), profile이 있는데 probe가 + 없으면 기동 거부, `MongoClientGenerationRegistry`(`MongoCredentialRotationPolicy` bean이 있을 때), + `MongoPlatformHealthIndicator` + health contributor + +설정 키는 `ca-skeleton.persistence-mongo.enabled`, `.active-profile`, `.platform.transactions`, +`.platform.required-secondaries`, `.platform.profiles..*`(위 예시의 14개)뿐이다. + +## 라이브러리 API — 서비스의 어댑터 leaf에서 `implementation`으로 받아 직접 호출 + +bean으로 등록되지 않고 설정 키도 없다. 서비스의 Mongo 어댑터 leaf가 이 leaf를 `implementation`으로 +받아 생성자로 만든다(AGENTS.md capability 규칙의 라이브러리형 예외). 테스트 열은 그 진입점을 검증하는 이 leaf의 테스트다. + +| 패키지 | 진입점 | 테스트 | +|---|---|---| +| `transaction` | `MongoTransactionRetryCoordinator`, `MongoTransactionScope`, `SpringMongoTransactionSessionFactory` | `MongoTransactionRetryCoordinatorTest`, `CleanupFailureIsReportedTest`, `MongoTransactionScopeTest`, `MongoSessionAcquisitionTest` | +| `transaction.session` | `SpringMongoCausalSessionExecutor` | `MongoCausalSessionExecutorTest` | +| `imperative.revision` | `VersionedMongoUpdater` | `VersionedMongoUpdaterTest` | +| `query` | `PolicyAwareMongoQueryBuilder`, `MongoQueryPolicy` | `PolicyAwareMongoQueryBuilderTest`, `LiteralSearchIsExpressibleTest` | +| `query.pagination` | `MongoKeysetQueryBuilder`, `MongoKeysetCursorCodec` | `MongoKeysetQueryBuilderTest`, `MongoKeysetCursorTypeTest`, `MongoKeysetPageRequestBoundsTest` | +| `aggregation` | `MongoAggregationProfile`, `MongoAggregationPlan` | `PolicyAwareMongoAggregationExecutorTest` | +| `schema.*` | `MongoManifestRegistry`, `MongoIndexDiffEngine`, `MongoValidatorApplyPolicy`, `MongoDocumentModelValidator`, `MongoTtlPolicyValidator` | `schema/**Test` 5개 | +| `migration` (+ `flamingock`) | `MongoMigrationRunner`, `MongoCollectionMigrationLedger`, `MongoCollectionMigrationLock`, `FlamingockMongoMigrationAdapter` | `MongoMigrationRunnerTest`, `MongoMigrationFencingTest`, `FlamingockMongoMigrationAdapterTest`, `mongoMigrationTest` lane | +| `security` (+ `admin`) | `MongoSecurityProfileValidator`, `MongoAdminGateway`, `MongoAdminRuntimeGuard` | `security/**Test` 5개, `mongoSecurityIntegrationTest` lane | +| `nativecap` | `PolicyAwareMongoNativeGateway` | `PolicyAwareMongoNativeGatewayTest` | +| `advanced.sharding` (+ `admin`) | `ShardAwareQueryValidator`, `ShardKeyAnalyzer`, `ReshardApproval` | `ShardAwareQueryValidatorTest`, `ShardKeyAnalyzerTest` | +| `advanced.encryption` | `MongoCsfleProfile`, `MongoCsfleFieldPolicy`, `MongoQueryableEncryptionProfile`, `MongoEncryptionMetadataOwnership` | `MongoEncryptionContractTest` | +| `advanced.tenancy` | `MongoTenantPredicateInjector`, `MongoTenantManifestValidator`, `MongoTenantClientRegistry`, `MongoTenantLifecyclePolicy`, `MongoTenantMigrationCoordinator` | `MongoTenancyContractTest`, `MongoAdvancedCapabilityGuardTest` | + +Advanced 진입점(`@MongoAdvancedEntryPoint`)은 생성자에서 `MongoAdvancedCapabilityGuard`를 받는다. +guard는 서비스 코드가 `MongoAdvancedCapabilityFlags.allDisabled().withEnabled(...)`로 만든다. 이것을 +켜는 설정 키는 없다. + +테스트가 없는 진입점 — 이 leaf 안에 호출자도 테스트도 없다. 쓰기 전에 서비스 어댑터 쪽에서 계약 +테스트를 먼저 붙인다: `SpringMongoTransactionExecutor`, `PolicyAwareMongoAggregationExecutor`, +`SpringMongoGeospatialOperations`, `MongoCsfleClientFactory`, +`MongoQueryableEncryptionCollectionManager`, `MongoShardingAdminGateway`. ## 노출 계층 (D1–D4) | 계층 | 내용 | Client | |---|---|---| | D1 표준 document 영속성 | Spring Data repository, typed query, mapping manifest, atomic update, optimistic revision | Stable API V1 strict | -| D2 고급 document 연산 | `MongoTemplate`, transaction/session, bulk, aggregation, keyset cursor, change stream | Stable API V1 strict | -| D3 명시적 capability | native BSON, time series, search/vector, CSFLE/QE, shard-aware | capability client | +| D2 고급 document 연산 | `MongoTemplate`, transaction/session, bulk, aggregation, keyset cursor | Stable API V1 strict | +| D3 명시적 capability | native BSON, CSFLE/QE, shard-aware | capability client | | D4 admin plane | collection, validator, index, migration, shard, repair | admin client + 별도 credential | D3는 raw client escape가 아니다. `PolicyAwareMongoNativeGateway`가 capability → database profile → @@ -137,28 +182,28 @@ command category → D4 차단 순서를 고정한다. | `api` (+ `capability`, `consistency`, `error`, `mapping`, `observation`, `profile`, `schema`) | framework 없는 core 계약. Spring/driver/BSON/Reactor import 금지 (ArchUnit) | | `mapping` (+ `type`), `failure` | Spring Data 통합, BSON 표현 manifest, 실패 분류·변환 | | `imperative` (+ `atomic`, `bulk`, `revision`) | 명령형 실행, update operator, bulk 부분 결과, optimistic revision | -| `reactive` (+ `cursor`) | 반응형 실행, cursor lease/guard | | `query` (+ `budget`, `pagination`) | query guardrail, operation budget, keyset pagination | | `aggregation` | 등록된 pipeline plan과 risk 등급 | | `transaction` (+ `retry`, `session`) | transaction 실행, body/commit 분리 retry, causal session | | `schema` (+ `index`, `manifest`, `model`, `ttl`, `validation`) | document model·index·validator manifest와 diff/apply, TTL 정책 | -| `changestream` (+ `projector`, `recovery`) | at-least-once projector, resume checkpoint, history-lost 처리 | | `geo` | GeoJSON / 2dsphere | | `migration` (+ `flamingock`) | checksum·lock·precondition 기반 migration runner | | `observation` | driver-native command/pool/SDAM 관측, tag allowlist, redaction | | `security` (+ `admin`), `nativecap` | 역할·credential·TLS profile, admin plane, native capability gateway | -| `autoconfigure` | Boot auto-configuration, startup validation, client generation, release gate | -| `advanced/**` | opt-in Advanced/Experimental capability (sharding, time series, CSFLE, QE, search, vector, tenancy, bridge, GridFS) | -| `architecture` | fork가 자기 코드에 적용하는 `@MongoOperation` marker와 ArchUnit rule set | +| `autoconfigure` | Boot auto-configuration, startup validation, client generation | +| `advanced/**` | opt-in Advanced/Experimental 라이브러리 (sharding, CSFLE, QE, tenancy) | + +`@MongoOperation` marker와 fork용 ArchUnit rule set(`architecture`, `testkit`)은 production이 아니라 +`testFixtures` source set에 있다. ## 의존성 경계 - production project dependency 없음 -- Spring Boot MongoDB starter(sync/reactive), configuration processor, Micrometer, SLF4J만 사용 +- Spring Boot MongoDB starter(sync), configuration processor, Micrometer, SLF4J만 사용 - JPA persistence adapter 및 다른 adapter와 의존 관계 없음 - idempotency, outbox, distributed lock은 기존 JPA adapter 책임을 유지 -- 패키지 간 방향은 `MongoModuleBoundaryTest`(ArchUnit) 10개 규칙이 강제한다: core-api는 framework - 무의존, Stable은 Advanced에 의존 금지, production은 testkit에 의존 금지, imperative↛reactive, +- 패키지 간 방향은 `MongoModuleBoundaryTest`(ArchUnit)가 강제한다: core-api는 framework + 무의존, Stable은 Advanced에 의존 금지, production은 testkit에 의존 금지, query↛aggregation, schema↛execution, observability↛execution, migration↛flamingock ## 테스트 lane @@ -199,11 +244,9 @@ bash scripts/verify-mongodb-advanced.sh - [docs/mongodb/consistency-transaction-guide.md](../../../../docs/mongodb/consistency-transaction-guide.md) - [docs/mongodb/query-aggregation-guide.md](../../../../docs/mongodb/query-aggregation-guide.md) - [docs/mongodb/schema-index-migration-guide.md](../../../../docs/mongodb/schema-index-migration-guide.md) -- [docs/mongodb/change-stream-guide.md](../../../../docs/mongodb/change-stream-guide.md) - [docs/mongodb/security-observability.md](../../../../docs/mongodb/security-observability.md) - Runbook: [failover](../../../../docs/mongodb/runbooks/failover.md) · - [unknown-commit](../../../../docs/mongodb/runbooks/unknown-commit.md) · - [history-lost](../../../../docs/mongodb/runbooks/history-lost.md) + [unknown-commit](../../../../docs/mongodb/runbooks/unknown-commit.md) - ADR: [001 platform boundary](../../../../docs/adr/ADR-MONGO-001-platform-boundary.md) · [002 BSON representation](../../../../docs/adr/ADR-MONGO-002-bson-representation.md) · [003 transaction retry](../../../../docs/adr/ADR-MONGO-003-transaction-retry.md) · diff --git a/src/adapter/outbound/persistence-mongo/build.gradle b/src/adapter/outbound/persistence-mongo/build.gradle index 8b18224f..533beca4 100644 --- a/src/adapter/outbound/persistence-mongo/build.gradle +++ b/src/adapter/outbound/persistence-mongo/build.gradle @@ -3,7 +3,6 @@ plugins { id 'ca.spring-config' id 'java-test-fixtures' id 'ca.auxiliary-source-set' - id 'ca.mongo-verification' id 'ca.api-surface' } @@ -24,13 +23,11 @@ plugins { // Driver and Spring Data MongoDB versions come from the Spring Boot BOM applied to every module in // src/build.gradle (design §4: "개별 Driver 버전 override 금지"), so nothing here pins them. description = 'Outbound adapter: MongoDB document persistence platform (manifests, atomic writes, ' + - 'consistency profiles, guardrails, change streams)' + 'consistency profiles, guardrails)' dependencies { // D1/D2 imperative execution path and the mapping subsystem. implementation 'org.springframework.boot:spring-boot-starter-data-mongodb' - // D1/D2 reactive execution path: reactive template, cursors and change streams (design §20). - implementation 'org.springframework.boot:spring-boot-starter-data-mongodb-reactive' // The starter package registers auto-configuration and binds typed properties. implementation 'org.springframework.boot:spring-boot-autoconfigure' // Actuator health SPI bridge owned by the Mongo starter (MNG-007). @@ -46,7 +43,6 @@ dependencies { // The design's module dependency table is enforced as package rules, so ArchUnit is what keeps // "packages instead of modules" from meaning "no boundary at all". testImplementation libs.archunit.junit5 - testImplementation 'io.projectreactor:reactor-test' } // Shared test code lives in src/testFixtures, per ADR-BUILD-001. This leaf is the first migration @@ -88,7 +84,6 @@ auxiliarySourceSets { // reviewable — the same model the GraphQL leaf already uses. dependencies { testFixturesImplementation libs.archunit.junit5 - testFixturesImplementation 'io.projectreactor:reactor-test' testFixturesImplementation 'org.assertj:assertj-core' testFixturesImplementation 'org.mongodb:bson' // The ArchUnit rule pack names Spring Data's Repository marker in a rule, so it needs the @@ -118,9 +113,8 @@ dependencies { // // `mongodb-contract` is excluded here too. It was not, and `check` depends on both `test` and // `mongoStableContractTest`, so every one of the 382 hermetic contract tests ran twice on a fresh -// build — once in each task. The two lanes are now disjoint by construction, and -// `MongoTestLaneDisjointnessTest` asserts it against the JUnit XML rather than trusting this -// comment. +// build — once in each task. The two lanes are disjoint by construction: `test` excludes the tag +// and the lane selects only it. tasks.named('test', Test) { useJUnitPlatform { excludeTags 'mongodb-contract' @@ -135,8 +129,8 @@ strictTestLanes { integration() sourceSet = 'mongoIntegrationTest' tag = 'mongodb-replicaset' - description = 'Single-node replica set contract lane: mapping, atomic write, transaction, ' + - 'change stream (design §29).' + description = 'Single-node replica set contract lane: mapping, atomic write, transaction ' + + '(design §29).' systemProperty 'mongodb.primary.image', providers.gradleProperty('mongoPrimaryImage').orElse('mongo:8.0.16').get() systemProperty 'mongodb.compatibility.image', @@ -200,6 +194,7 @@ strictTestLanes { tag = 'mongodb-contract' description = 'Hermetic stable contract suite: manifests, guardrails, retry scopes, ' + 'redaction (design §30).' + rejectSkipped = true } // Driven by its own source set rather than a tag: for this shape the source set is the @@ -224,13 +219,16 @@ strictTestLanes { // `check` gains only the hermetic lanes. The Docker-backed ones stay opt-in for the reason above. tasks.named('check') { - dependsOn 'mongoStableContractTest', 'verifyMongoTestLaneDisjointness', - 'verifyMongoReleaseContractLanes' + dependsOn 'mongoStableContractTest' } -// The two verification tasks are registered by `ca.mongo-verification`. The leaf owns only -// the semantic lane selection above and the lifecycle dependency below; JSON/JUnit parsing and -// evidence decisions live in typed Java build tooling. +// MongoTestLaneContractTest reads the integration sources' lane tags and the release-contract +// manifest; both are inputs here, or Gradle would call `test` up to date after editing either. +tasks.named('test') { + inputs.dir('src/mongoIntegrationTest/java').withPathSensitivity(PathSensitivity.RELATIVE) + inputs.file(rootProject.file('config/mongodb/release-contracts.json')) + .withPathSensitivity(PathSensitivity.RELATIVE) +} // verifyMongoApiSurface — every public type this leaf exposes is a committed decision. diff --git a/src/adapter/outbound/persistence-mongo/gradle.lockfile b/src/adapter/outbound/persistence-mongo/gradle.lockfile index 23b07974..22eef319 100644 --- a/src/adapter/outbound/persistence-mongo/gradle.lockfile +++ b/src/adapter/outbound/persistence-mongo/gradle.lockfile @@ -55,8 +55,8 @@ io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,mongoIntegrat io.micrometer:micrometer-commons:1.16.7=compileClasspath,mongoIntegrationTestCompileClasspath,mongoIntegrationTestRuntimeClasspath,mongoPerformanceTestCompileClasspath,mongoPerformanceTestRuntimeClasspath,mongoProviderTestkitCompileClasspath,mongoProviderTestkitRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath io.micrometer:micrometer-core:1.16.7=compileClasspath,mongoIntegrationTestCompileClasspath,mongoIntegrationTestRuntimeClasspath,mongoPerformanceTestCompileClasspath,mongoPerformanceTestRuntimeClasspath,mongoProviderTestkitCompileClasspath,mongoProviderTestkitRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath io.micrometer:micrometer-observation:1.16.7=compileClasspath,mongoIntegrationTestCompileClasspath,mongoIntegrationTestRuntimeClasspath,mongoPerformanceTestCompileClasspath,mongoPerformanceTestRuntimeClasspath,mongoProviderTestkitCompileClasspath,mongoProviderTestkitRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -io.projectreactor:reactor-core:3.8.7=compileClasspath,mongoIntegrationTestCompileClasspath,mongoIntegrationTestRuntimeClasspath,mongoPerformanceTestCompileClasspath,mongoPerformanceTestRuntimeClasspath,mongoProviderTestkitCompileClasspath,mongoProviderTestkitRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -io.projectreactor:reactor-test:3.8.7=mongoIntegrationTestCompileClasspath,mongoIntegrationTestRuntimeClasspath,mongoPerformanceTestCompileClasspath,mongoPerformanceTestRuntimeClasspath,mongoProviderTestkitCompileClasspath,mongoProviderTestkitRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +io.projectreactor:reactor-core:3.8.7=testkitCompileClasspath,testkitRuntimeClasspath +io.projectreactor:reactor-test:3.8.7=testkitCompileClasspath,testkitRuntimeClasspath jakarta.activation:jakarta.activation-api:2.1.4=mongoIntegrationTestCompileClasspath,mongoIntegrationTestRuntimeClasspath,mongoPerformanceTestCompileClasspath,mongoPerformanceTestRuntimeClasspath,mongoProviderTestkitCompileClasspath,mongoProviderTestkitRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath jakarta.annotation:jakarta.annotation-api:3.0.0=compileClasspath,mongoIntegrationTestCompileClasspath,mongoIntegrationTestRuntimeClasspath,mongoPerformanceTestCompileClasspath,mongoPerformanceTestRuntimeClasspath,mongoProviderTestkitCompileClasspath,mongoProviderTestkitRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath jakarta.xml.bind:jakarta.xml.bind-api:4.0.5=mongoIntegrationTestCompileClasspath,mongoIntegrationTestRuntimeClasspath,mongoPerformanceTestCompileClasspath,mongoPerformanceTestRuntimeClasspath,mongoProviderTestkitCompileClasspath,mongoProviderTestkitRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath @@ -115,7 +115,7 @@ org.mockito:mockito-junit-jupiter:5.20.0=mongoIntegrationTestCompileClasspath,mo org.mongodb:bson-record-codec:5.6.5=mongoIntegrationTestRuntimeClasspath,mongoPerformanceTestRuntimeClasspath,mongoProviderTestkitRuntimeClasspath,runtimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitRuntimeClasspath org.mongodb:bson:5.6.5=compileClasspath,mongoIntegrationTestCompileClasspath,mongoIntegrationTestRuntimeClasspath,mongoPerformanceTestCompileClasspath,mongoPerformanceTestRuntimeClasspath,mongoProviderTestkitCompileClasspath,mongoProviderTestkitRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath org.mongodb:mongodb-driver-core:5.6.5=compileClasspath,mongoIntegrationTestCompileClasspath,mongoIntegrationTestRuntimeClasspath,mongoPerformanceTestCompileClasspath,mongoPerformanceTestRuntimeClasspath,mongoProviderTestkitCompileClasspath,mongoProviderTestkitRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.mongodb:mongodb-driver-reactivestreams:5.6.5=compileClasspath,mongoIntegrationTestCompileClasspath,mongoIntegrationTestRuntimeClasspath,mongoPerformanceTestCompileClasspath,mongoPerformanceTestRuntimeClasspath,mongoProviderTestkitCompileClasspath,mongoProviderTestkitRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +org.mongodb:mongodb-driver-reactivestreams:5.6.5=testkitCompileClasspath,testkitRuntimeClasspath org.mongodb:mongodb-driver-sync:5.6.5=compileClasspath,mongoIntegrationTestCompileClasspath,mongoIntegrationTestRuntimeClasspath,mongoPerformanceTestCompileClasspath,mongoPerformanceTestRuntimeClasspath,mongoProviderTestkitCompileClasspath,mongoProviderTestkitRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath org.objenesis:objenesis:3.3=mongoIntegrationTestRuntimeClasspath,mongoPerformanceTestRuntimeClasspath,mongoProviderTestkitRuntimeClasspath,testRuntimeClasspath,testkitRuntimeClasspath org.opentest4j:opentest4j:1.3.0=mongoIntegrationTestCompileClasspath,mongoIntegrationTestRuntimeClasspath,mongoPerformanceTestCompileClasspath,mongoPerformanceTestRuntimeClasspath,mongoProviderTestkitCompileClasspath,mongoProviderTestkitRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath @@ -130,7 +130,7 @@ org.ow2.asm:asm-util:9.10.1=spotbugs org.ow2.asm:asm:9.10.1=spotbugs org.ow2.asm:asm:9.7.1=mongoIntegrationTestCompileClasspath,mongoIntegrationTestRuntimeClasspath,mongoPerformanceTestCompileClasspath,mongoPerformanceTestRuntimeClasspath,mongoProviderTestkitCompileClasspath,mongoProviderTestkitRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath org.pcollections:pcollections:4.0.1=annotationProcessor,mongoIntegrationTestAnnotationProcessor,mongoPerformanceTestAnnotationProcessor,mongoProviderTestkitAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor,testkitAnnotationProcessor -org.reactivestreams:reactive-streams:1.0.4=compileClasspath,mongoIntegrationTestCompileClasspath,mongoIntegrationTestRuntimeClasspath,mongoPerformanceTestCompileClasspath,mongoPerformanceTestRuntimeClasspath,mongoProviderTestkitCompileClasspath,mongoProviderTestkitRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +org.reactivestreams:reactive-streams:1.0.4=testkitCompileClasspath,testkitRuntimeClasspath org.reflections:reflections:0.10.2=checkstyle org.rnorth.duct-tape:duct-tape:1.0.8=mongoIntegrationTestCompileClasspath,mongoIntegrationTestRuntimeClasspath,mongoPerformanceTestCompileClasspath,mongoPerformanceTestRuntimeClasspath,mongoProviderTestkitCompileClasspath,mongoProviderTestkitRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath org.skyscreamer:jsonassert:1.5.3=mongoIntegrationTestCompileClasspath,mongoIntegrationTestRuntimeClasspath,mongoPerformanceTestCompileClasspath,mongoPerformanceTestRuntimeClasspath,mongoProviderTestkitCompileClasspath,mongoProviderTestkitRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath @@ -147,10 +147,10 @@ org.springframework.boot:spring-boot-http-converter:4.0.8=mongoIntegrationTestCo org.springframework.boot:spring-boot-jackson:4.0.8=mongoIntegrationTestCompileClasspath,mongoIntegrationTestRuntimeClasspath,mongoPerformanceTestCompileClasspath,mongoPerformanceTestRuntimeClasspath,mongoProviderTestkitCompileClasspath,mongoProviderTestkitRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath org.springframework.boot:spring-boot-mongodb:4.0.8=compileClasspath,mongoIntegrationTestCompileClasspath,mongoIntegrationTestRuntimeClasspath,mongoPerformanceTestCompileClasspath,mongoPerformanceTestRuntimeClasspath,mongoProviderTestkitCompileClasspath,mongoProviderTestkitRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath org.springframework.boot:spring-boot-persistence:4.0.8=compileClasspath,mongoIntegrationTestCompileClasspath,mongoIntegrationTestRuntimeClasspath,mongoPerformanceTestCompileClasspath,mongoPerformanceTestRuntimeClasspath,mongoProviderTestkitCompileClasspath,mongoProviderTestkitRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.springframework.boot:spring-boot-reactor:4.0.8=compileClasspath,mongoIntegrationTestCompileClasspath,mongoIntegrationTestRuntimeClasspath,mongoPerformanceTestCompileClasspath,mongoPerformanceTestRuntimeClasspath,mongoProviderTestkitCompileClasspath,mongoProviderTestkitRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +org.springframework.boot:spring-boot-reactor:4.0.8=testkitCompileClasspath,testkitRuntimeClasspath org.springframework.boot:spring-boot-resttestclient:4.0.8=mongoIntegrationTestCompileClasspath,mongoIntegrationTestRuntimeClasspath,mongoPerformanceTestCompileClasspath,mongoPerformanceTestRuntimeClasspath,mongoProviderTestkitCompileClasspath,mongoProviderTestkitRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath org.springframework.boot:spring-boot-servlet:4.0.8=mongoIntegrationTestCompileClasspath,mongoIntegrationTestRuntimeClasspath,mongoPerformanceTestCompileClasspath,mongoPerformanceTestRuntimeClasspath,mongoProviderTestkitCompileClasspath,mongoProviderTestkitRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath -org.springframework.boot:spring-boot-starter-data-mongodb-reactive:4.0.8=compileClasspath,mongoIntegrationTestCompileClasspath,mongoIntegrationTestRuntimeClasspath,mongoPerformanceTestCompileClasspath,mongoPerformanceTestRuntimeClasspath,mongoProviderTestkitCompileClasspath,mongoProviderTestkitRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath +org.springframework.boot:spring-boot-starter-data-mongodb-reactive:4.0.8=testkitCompileClasspath,testkitRuntimeClasspath org.springframework.boot:spring-boot-starter-data-mongodb:4.0.8=compileClasspath,mongoIntegrationTestCompileClasspath,mongoIntegrationTestRuntimeClasspath,mongoPerformanceTestCompileClasspath,mongoPerformanceTestRuntimeClasspath,mongoProviderTestkitCompileClasspath,mongoProviderTestkitRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath org.springframework.boot:spring-boot-starter-jackson-test:4.0.8=mongoIntegrationTestCompileClasspath,mongoIntegrationTestRuntimeClasspath,mongoPerformanceTestCompileClasspath,mongoPerformanceTestRuntimeClasspath,mongoProviderTestkitCompileClasspath,mongoProviderTestkitRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath org.springframework.boot:spring-boot-starter-jackson:4.0.8=mongoIntegrationTestCompileClasspath,mongoIntegrationTestRuntimeClasspath,mongoPerformanceTestCompileClasspath,mongoPerformanceTestRuntimeClasspath,mongoProviderTestkitCompileClasspath,mongoProviderTestkitRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,testkitCompileClasspath,testkitRuntimeClasspath diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/MongoDefaultsEnvironmentPostProcessor.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/MongoDefaultsEnvironmentPostProcessor.java new file mode 100644 index 00000000..7d5194b2 --- /dev/null +++ b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/MongoDefaultsEnvironmentPostProcessor.java @@ -0,0 +1,126 @@ +package dev.caskeleton.adapter.outbound.mongo; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import org.springframework.boot.EnvironmentPostProcessor; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.AutoConfiguration; +import org.springframework.boot.context.annotation.ImportCandidates; +import org.springframework.boot.context.config.ConfigDataEnvironmentPostProcessor; +import org.springframework.boot.context.properties.bind.Bindable; +import org.springframework.boot.context.properties.bind.Binder; +import org.springframework.boot.env.YamlPropertySourceLoader; +import org.springframework.core.Ordered; +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.core.env.Environment; +import org.springframework.core.env.MapPropertySource; +import org.springframework.core.io.ClassPathResource; + +/** + * Contributes this module's shipped settings, {@code config/mongo.yml}, and honours an explicit + * off. + * + *

The settings are added last, below every configuration file, profile and environment variable, + * so a deployment's own value always wins. + * + *

The module is on when present. {@code ca-skeleton.persistence-mongo.enabled=false} turns off + * {@link MongoRootAutoConfiguration}, but Spring Boot's own Mongo auto-configurations come with the + * driver on the classpath and read no switch of ours — left alone they would still build a client + * and a template. So an explicit off also excludes them, by adding them to {@code + * spring.autoconfigure.exclude} alongside whatever the deployment already excludes. The names are + * read from Boot's own registration files, not listed here, so a Boot release that adds one is + * covered without an edit. + * + *

An on module must also say where to connect before anything is built — see {@link + * #requireConnectionSource}. That runs here rather than in a bean because a client created without + * a source quietly dials the driver's {@code localhost} default. + */ +public class MongoDefaultsEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered { + + static final String RESOURCE = "config/mongo.yml"; + + static final String SWITCH = "ca-skeleton.persistence-mongo.enabled"; + + static final String ACTIVE_PROFILE = "ca-skeleton.persistence-mongo.active-profile"; + + private static final String EXCLUDE = "spring.autoconfigure.exclude"; + + private static final List BOOT_MONGO_PACKAGES = + List.of( + "org.springframework.boot.mongodb.autoconfigure.", + "org.springframework.boot.data.mongodb.autoconfigure."); + + @Override + public void postProcessEnvironment( + ConfigurableEnvironment environment, SpringApplication application) { + ClassLoader classLoader = MongoDefaultsEnvironmentPostProcessor.class.getClassLoader(); + try { + new YamlPropertySourceLoader() + .load( + "persistence-mongo-defaults (" + RESOURCE + ")", + new ClassPathResource(RESOURCE, classLoader)) + .forEach(environment.getPropertySources()::addLast); + } catch (IOException failure) { + throw new UncheckedIOException("failed to read " + RESOURCE, failure); + } + + String enabled = environment.getProperty(SWITCH); + if (enabled == null || "true".equalsIgnoreCase(enabled)) { + requireConnectionSource(environment); + return; + } + List excluded = + new ArrayList<>( + Binder.get(environment).bind(EXCLUDE, Bindable.listOf(String.class)).orElse(List.of())); + for (String candidate : ImportCandidates.load(AutoConfiguration.class, classLoader)) { + if (BOOT_MONGO_PACKAGES.stream().anyMatch(candidate::startsWith)) { + excluded.add(candidate); + } + } + environment + .getPropertySources() + .addFirst( + new MapPropertySource( + "persistence-mongo-off", Map.of(EXCLUDE, String.join(",", excluded)))); + } + + /** + * Refuses an on module that has not chosen exactly one profile and an explicit connection source. + * + *

The source is either Spring's standard {@code spring.mongodb.uri} or the active profile's + * {@code uri-secret}. With neither, the driver would connect to its own {@code localhost} + * default, which is a deployment talking to a database nobody chose. + * + * @param environment the resolved environment, module defaults included + * @throws IllegalStateException naming the property to set + */ + static void requireConnectionSource(Environment environment) { + String profile = environment.getProperty(ACTIVE_PROFILE, "").trim(); + if (profile.isEmpty()) { + throw new IllegalStateException( + SWITCH + + "=true needs exactly one profile; set " + + ACTIVE_PROFILE + + " (APP_PERSISTENCE_MONGO_ACTIVE_PROFILE)."); + } + String profileSecret = + "ca-skeleton.persistence-mongo.platform.profiles." + profile + ".uri-secret"; + if (environment.getProperty("spring.mongodb.uri", "").isBlank() + && environment.getProperty(profileSecret, "").isBlank()) { + throw new IllegalStateException( + SWITCH + + "=true has no explicit MongoDB connection source; set spring.mongodb.uri" + + " (SPRING_MONGODB_URI) or " + + profileSecret + + "."); + } + } + + @Override + public int getOrder() { + return ConfigDataEnvironmentPostProcessor.ORDER + 1; + } +} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/MongoOptInAutoConfigurationImportFilter.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/MongoOptInAutoConfigurationImportFilter.java deleted file mode 100644 index 732b0794..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/MongoOptInAutoConfigurationImportFilter.java +++ /dev/null @@ -1,59 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo; - -import java.util.Set; -import org.springframework.boot.autoconfigure.AutoConfigurationImportFilter; -import org.springframework.boot.autoconfigure.AutoConfigurationMetadata; -import org.springframework.context.EnvironmentAware; -import org.springframework.core.env.Environment; - -/** - * Prevents Spring Boot's classpath-driven Mongo auto-configurations from bypassing this module's - * explicit opt-in property. - * - *

The Mongo starter contributes its auto-configurations directly through Boot's import metadata. - * Consequently, conditioning only {@link MongoPersistenceConfig} is insufficient: a normal - * {@code @EnableAutoConfiguration} application would still create a client and template. This - * filter keeps all Boot 4 sync, reactive, repository, health, and metrics Mongo imports out of the - * candidate set until {@code ca-skeleton.persistence-mongo.enabled=true}. - */ -public final class MongoOptInAutoConfigurationImportFilter - implements AutoConfigurationImportFilter, EnvironmentAware { - - private static final String ENABLE_PROPERTY = "ca-skeleton.persistence-mongo.enabled"; - - private static final Set MONGO_AUTO_CONFIGURATIONS = - Set.of( - "org.springframework.boot.mongodb.autoconfigure.MongoAutoConfiguration", - "org.springframework.boot.mongodb.autoconfigure.MongoReactiveAutoConfiguration", - "org.springframework.boot.mongodb.autoconfigure.health.MongoHealthContributorAutoConfiguration", - "org.springframework.boot.mongodb.autoconfigure.health.MongoReactiveHealthContributorAutoConfiguration", - "org.springframework.boot.mongodb.autoconfigure.metrics.MongoMetricsAutoConfiguration", - "org.springframework.boot.data.mongodb.autoconfigure.DataMongoAutoConfiguration", - "org.springframework.boot.data.mongodb.autoconfigure.DataMongoReactiveAutoConfiguration", - "org.springframework.boot.data.mongodb.autoconfigure.DataMongoReactiveRepositoriesAutoConfiguration", - "org.springframework.boot.data.mongodb.autoconfigure.DataMongoRepositoriesAutoConfiguration"); - - private Environment environment; - - @Override - public boolean[] match( - String[] autoConfigurationClasses, AutoConfigurationMetadata autoConfigurationMetadata) { - boolean enabled = - environment != null - && "true".equalsIgnoreCase(environment.getProperty(ENABLE_PROPERTY, "false")); - boolean[] matches = new boolean[autoConfigurationClasses.length]; - for (int index = 0; index < autoConfigurationClasses.length; index++) { - String autoConfigurationClass = autoConfigurationClasses[index]; - matches[index] = - enabled - || autoConfigurationClass == null - || !MONGO_AUTO_CONFIGURATIONS.contains(autoConfigurationClass); - } - return matches; - } - - @Override - public void setEnvironment(Environment environment) { - this.environment = environment; - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/MongoPersistenceConfig.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/MongoPersistenceConfig.java index baf04e33..0d979181 100644 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/MongoPersistenceConfig.java +++ b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/MongoPersistenceConfig.java @@ -21,7 +21,8 @@ import org.springframework.context.annotation.Configuration; @ConditionalOnProperty( prefix = "ca-skeleton.persistence-mongo", name = "enabled", - havingValue = "true") + havingValue = "true", + matchIfMissing = true) @EnableConfigurationProperties(MongoPersistenceSettings.class) @ImportAutoConfiguration({MongoAutoConfiguration.class, DataMongoAutoConfiguration.class}) public class MongoPersistenceConfig {} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/MongoPersistenceSettings.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/MongoPersistenceSettings.java index 5a96723d..b1b1c359 100644 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/MongoPersistenceSettings.java +++ b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/MongoPersistenceSettings.java @@ -22,11 +22,11 @@ import org.springframework.boot.context.properties.ConfigurationProperties; public class MongoPersistenceSettings { /** - * Whether to activate the MongoDB scaffolding. Defaults to {@code false} so the driver never - * connects when the module is merely present on the classpath; a fork opts in explicitly, and - * {@link MongoPersistenceConfig} re-imports the Mongo auto-configuration only then. + * Whether to activate the MongoDB scaffolding. Defaults to {@code true}: an application that + * selected this module wants MongoDB. {@code false} turns off the platform and, through {@link + * MongoDefaultsEnvironmentPostProcessor}, Spring Boot's own Mongo auto-configuration as well. */ - private boolean enabled = false; + private boolean enabled = true; public boolean isEnabled() { return enabled; diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/MongoRootAutoConfiguration.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/MongoRootAutoConfiguration.java index e0d58498..2eb2b815 100644 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/MongoRootAutoConfiguration.java +++ b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/MongoRootAutoConfiguration.java @@ -10,24 +10,22 @@ import org.springframework.context.annotation.Import; /** * The one place that decides whether this application talks to MongoDB. * - *

Three things behaved like the master before this: the auto-configuration import filter, a - * component-scanned persistence configuration, and the platform auto-configuration — each reading - * the same property, and each able to assemble something the others believed was off. The filter - * keeps its job of holding Boot's own Mongo auto-configurations out of the candidate set, because - * that has to happen before any project condition is evaluated; what it no longer is, is an - * authority. + *

On when present: an application that selected this module wants MongoDB, so a missing {@code + * ca-skeleton.persistence-mongo.enabled} means on. {@code false} turns this root off, and {@link + * MongoDefaultsEnvironmentPostProcessor} excludes Spring Boot's own Mongo auto-configurations in + * the same case, so an explicit off leaves no client, template or pool behind. * - *

It sits in the leaf root, not in {@code autoconfigure}, because it names the opt-in - * configuration and the enablement settings that live here — and the root package already names - * {@code autoconfigure}. Declaring the edge both ways would make the module's package graph cyclic, - * which its boundary test refuses; the leaf root is where this file belongs by that graph's own - * description, "the opt-in filter and the Spring configuration entry points". + *

It sits in the leaf root, not in {@code autoconfigure}, because it names the configuration and + * the enablement settings that live here — and the root package already names {@code + * autoconfigure}. Declaring the edge both ways would make the module's package graph cyclic, which + * its boundary test refuses. */ @AutoConfiguration @ConditionalOnProperty( prefix = "ca-skeleton.persistence-mongo", name = "enabled", - havingValue = "true") + havingValue = "true", + matchIfMissing = true) @EnableConfigurationProperties(MongoPersistenceSettings.class) @Import({ MongoPersistenceConfig.class, diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/MongoAdvancedCapabilityFlags.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/MongoAdvancedCapabilityFlags.java index cf0b5808..b5b5209d 100644 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/MongoAdvancedCapabilityFlags.java +++ b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/MongoAdvancedCapabilityFlags.java @@ -7,24 +7,21 @@ import java.util.Map; import java.util.Objects; /** - * The per-capability opt-in switch for everything Advanced (advanced plan Task 1). + * The per-capability opt-in set for the Advanced library types. * - *

Every Advanced capability is off unless explicitly enabled. That is not caution for its own - * sake: each of these needs something the Stable lane does not have — a sharded cluster, an Atlas - * deployment, a KMS, a separate credential — and a capability that wires itself because its code is - * on the classpath will fail at the first call rather than at startup. + *

Every Advanced capability is off unless the code that constructs an entry point enables it. + * There is no configuration property behind these flags: the Advanced types are library API that a + * service's own adapter constructs, so the service's composition is where it states which + * capability it has the topology, credential and provider for. * - *

The Stable starter references nothing in this package, so no Advanced capability can arrive as - * a transitive dependency of ordinary document persistence. + *

The Stable auto-configuration references nothing in this package, so no Advanced capability + * can arrive as a transitive dependency of ordinary document persistence. */ // Classified a policy because it is the gating mechanism: the flag set itself holds no client and // issues no command, and gating the guard behind the guard has no bottom. @MongoAdvancedPolicy public final class MongoAdvancedCapabilityFlags { - /** The configuration prefix each capability's flag lives under. */ - public static final String PROPERTY_PREFIX = "ca-skeleton.persistence-mongo.advanced"; - private final Map enabled; private MongoAdvancedCapabilityFlags(Map enabled) { @@ -36,7 +33,7 @@ public final class MongoAdvancedCapabilityFlags { return new MongoAdvancedCapabilityFlags(new EnumMap<>(MongoCapability.class)); } - /** A flag set built from configuration. */ + /** A flag set built from an explicit map. */ public static MongoAdvancedCapabilityFlags of(Map flags) { Objects.requireNonNull(flags, "flags"); return new MongoAdvancedCapabilityFlags(new EnumMap<>(flags)); @@ -57,7 +54,7 @@ public final class MongoAdvancedCapabilityFlags { /** * Fails when a capability is used without being enabled. * - * @throws MongoOperationRejectedException naming the property that would enable it + * @throws MongoOperationRejectedException naming the capability that is not enabled */ public void require(MongoCapability capability) { if (!isEnabled(capability)) { @@ -65,20 +62,9 @@ public final class MongoAdvancedCapabilityFlags { "advanced.capability", "capability " + capability - + " is an opt-in Advanced module; set " - + propertyFor(capability) - + "=true and provide the topology, credential and provider it requires"); + + " is an opt-in Advanced module; enable it on the MongoAdvancedCapabilityFlags the" + + " guard is built from, and provide the topology, credential and provider it" + + " requires"); } } - - /** The configuration property that enables a capability. */ - public static String propertyFor(MongoCapability capability) { - return PROPERTY_PREFIX - + '.' - + Objects.requireNonNull(capability, "capability") - .name() - .toLowerCase(java.util.Locale.ROOT) - .replace('_', '-') - + ".enabled"; - } } diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/MongoAdvancedPromotionEvidence.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/MongoAdvancedPromotionEvidence.java deleted file mode 100644 index 1042d08e..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/MongoAdvancedPromotionEvidence.java +++ /dev/null @@ -1,61 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.advanced; - -import java.util.LinkedHashSet; -import java.util.Objects; -import java.util.Set; - -/** - * What promoting an Advanced capability requires (advanced plan Task 15). - * - *

{@code actual-topology} is the category that cannot be substituted. Every other kind of - * evidence can be produced in CI; sharding, search, vector and encryption behave differently on a - * real cluster or a real provider, and that difference is the whole reason they are Advanced rather - * than Stable. - */ -public record MongoAdvancedPromotionEvidence(Set requiredCategories, Set supplied) { - - /** The categories every promotion must supply. */ - public static final Set REQUIRED = - Set.of("stable-platform", "actual-topology", "security", "migration", "failure", "runbook"); - - public MongoAdvancedPromotionEvidence { - Objects.requireNonNull(requiredCategories, "requiredCategories"); - Objects.requireNonNull(supplied, "supplied"); - requiredCategories = Set.copyOf(requiredCategories); - supplied = Set.copyOf(supplied); - } - - /** The standard requirement set with nothing supplied yet. */ - public static MongoAdvancedPromotionEvidence fixture() { - return new MongoAdvancedPromotionEvidence(REQUIRED, Set.of()); - } - - /** Returns a copy with one more category supplied. */ - public MongoAdvancedPromotionEvidence with(String category) { - Set updated = new LinkedHashSet<>(supplied); - updated.add(Objects.requireNonNull(category, "category")); - return new MongoAdvancedPromotionEvidence(requiredCategories, updated); - } - - /** - * Asserts one category is supplied. - * - * @throws IllegalStateException naming the missing category - */ - public void require(String category) { - if (!supplied.contains(Objects.requireNonNull(category, "category"))) { - throw new IllegalStateException( - "the MongoDB Advanced promotion gate is missing '" - + category - + "' evidence; the required categories are " - + requiredCategories); - } - } - - /** The categories still missing. */ - public Set missing() { - Set missing = new LinkedHashSet<>(requiredCategories); - missing.removeAll(supplied); - return Set.copyOf(missing); - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/MongoAdvancedPromotionGate.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/MongoAdvancedPromotionGate.java deleted file mode 100644 index 98a57ef8..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/MongoAdvancedPromotionGate.java +++ /dev/null @@ -1,47 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.advanced; - -import java.util.Objects; - -/** - * The check that decides whether an Advanced capability may be promoted (advanced plan Task 15). - * - *

Promotion to Stable changes the support level, not the dependency boundary: a promoted - * capability is still an opt-in module until a separate starter ADR says otherwise. Conflating the - * two would mean a promotion silently adds a dependency — and a topology requirement — to every - * deployment that only wanted ordinary document persistence. - */ -@MongoAdvancedPolicy -public final class MongoAdvancedPromotionGate { - - /** - * Verifies one capability's promotion evidence. - * - * @throws IllegalStateException naming the first missing category - */ - public void verify(MongoAdvancedPromotionEvidence evidence) { - Objects.requireNonNull(evidence, "evidence"); - evidence.require("stable-platform"); - evidence.require("actual-topology"); - evidence.require("security"); - // `migration` was in MongoAdvancedPromotionEvidence.REQUIRED and not here, so the gate demanded - // five of the six categories it declares. A promotion could pass with no migration evidence at - // all — which is the shape MNG-008 names: a gate that certifies more than it ran. - evidence.require("migration"); - evidence.require("failure"); - evidence.require("runbook"); - } - - /** True when every required category is supplied. */ - public boolean passes(MongoAdvancedPromotionEvidence evidence) { - return Objects.requireNonNull(evidence, "evidence").missing().isEmpty(); - } - - /** - * Whether promotion adds the capability to the Stable starter's dependencies. - * - *

Always false; that needs its own ADR. - */ - public boolean addsStarterDependency() { - return false; - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/autoconfigure/MongoAdvancedConfiguration.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/autoconfigure/MongoAdvancedConfiguration.java deleted file mode 100644 index fbaf4fa7..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/autoconfigure/MongoAdvancedConfiguration.java +++ /dev/null @@ -1,43 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.advanced.autoconfigure; - -import dev.caskeleton.adapter.outbound.mongo.advanced.MongoAdvancedCapabilityGuard; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -/** - * Turns the Advanced configuration into the guard every entry point takes. - * - *

Deliberately not an auto-configuration and not listed in {@code - * AutoConfiguration.imports}. The Stable lane must reference nothing under {@code ..advanced..} — - * the module boundary test enforces it — and an auto-configuration that Boot loads because the - * classes are on the classpath is exactly the accident the opt-in exists to prevent. A composition - * root that wants Advanced capabilities imports this class by name, which is itself an opt-in. - * - *

Gated on the module switch as well, because an Advanced capability without the Mongo platform - * underneath it has nothing to be advanced over. - */ -@Configuration(proxyBeanMethods = false) -@ConditionalOnProperty( - prefix = "ca-skeleton.persistence-mongo", - name = "enabled", - havingValue = "true") -@EnableConfigurationProperties(MongoAdvancedSettings.class) -public class MongoAdvancedConfiguration { - - /** - * The single guard the module's entry points are constructed with. - * - *

It exists even when nothing is enabled: a guard over an empty flag set is what refuses, and - * omitting the bean would turn "capability disabled" into "no such bean", which reads as a wiring - * mistake rather than as the deliberate answer it is. - */ - @Bean - @ConditionalOnMissingBean - public MongoAdvancedCapabilityGuard mongoAdvancedCapabilityGuard( - MongoAdvancedSettings properties) { - return new MongoAdvancedCapabilityGuard(properties.toFlags()); - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/autoconfigure/MongoAdvancedSettings.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/autoconfigure/MongoAdvancedSettings.java deleted file mode 100644 index ecd0d65b..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/autoconfigure/MongoAdvancedSettings.java +++ /dev/null @@ -1,49 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.advanced.autoconfigure; - -import dev.caskeleton.adapter.outbound.mongo.advanced.MongoAdvancedCapabilityFlags; -import dev.caskeleton.adapter.outbound.mongo.api.capability.MongoCapability; -import java.util.EnumMap; -import java.util.Map; -import org.springframework.boot.context.properties.ConfigurationProperties; - -/** - * The Advanced opt-in switches, as typed configuration. - * - *

{@link MongoAdvancedCapabilityFlags} knew how to answer "is this enabled" and how to name the - * property that would enable it, and nothing ever read that property. The flags were built in test - * code and by whoever constructed an entry point by hand, so a deployment could set {@code - * ca-skeleton.persistence-mongo.advanced.sharding.enabled=true} and change nothing at all. - * - *

Bound one level above the Advanced prefix so the path an operator sets is exactly the path - * {@link MongoAdvancedCapabilityFlags#propertyFor} names in its refusal message; {@code - * MongoAdvancedConfigurationTest} asserts the two cannot drift apart. - * - *

The map is keyed by the capability enum, so an unknown capability name fails binding at - * startup instead of being ignored — which matters more than usual here, because the failure mode - * of a misspelt Advanced flag is a capability that stays off while its operator believes it is on. - */ -@ConfigurationProperties(MongoAdvancedSettings.PREFIX) -public record MongoAdvancedSettings(Map advanced) { - - /** The module prefix; the {@code advanced} component completes the documented property path. */ - public static final String PREFIX = "ca-skeleton.persistence-mongo"; - - public MongoAdvancedSettings { - advanced = advanced == null || advanced.isEmpty() ? Map.of() : Map.copyOf(advanced); - } - - /** Nothing enabled — the default for a deployment that configures no Advanced capability. */ - public static MongoAdvancedSettings none() { - return new MongoAdvancedSettings(Map.of()); - } - - /** The flag set this configuration describes. */ - public MongoAdvancedCapabilityFlags toFlags() { - Map enabled = new EnumMap<>(MongoCapability.class); - advanced.forEach((capability, settings) -> enabled.put(capability, settings.enabled())); - return MongoAdvancedCapabilityFlags.of(enabled); - } - - /** One capability's switch. */ - public record CapabilitySwitch(boolean enabled) {} -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/bridge/MongoBridgeCheckpointPolicy.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/bridge/MongoBridgeCheckpointPolicy.java deleted file mode 100644 index 879181c1..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/bridge/MongoBridgeCheckpointPolicy.java +++ /dev/null @@ -1,35 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.advanced.bridge; - -/** - * When the bridge may advance its MongoDB checkpoint (advanced plan Task 12). - * - *

Only after the broker has accepted the message. Advancing on a failed publish loses the event - * with no trace — the change stream moves past it and nothing will ever redeliver it — so the - * bridge chooses duplicates over loss here, exactly as the projector does. - */ -public enum MongoBridgeCheckpointPolicy { - - /** Advance only after the broker accepted the message. */ - AFTER_PUBLISH_CONFIRMED, - - /** - * Advance after an ambiguous publish result. - * - *

Valid only when the message id is deterministic and the consumer deduplicates, because the - * message may or may not have been accepted. - */ - AFTER_PUBLISH_AMBIGUOUS_WITH_DEDUPLICATION; - - /** - * True when the checkpoint may advance given this publish outcome. - * - * @param published whether the broker confirmed acceptance - * @param ambiguous whether the publish result was unknown - */ - public boolean mayAdvance(boolean published, boolean ambiguous) { - if (published) { - return true; - } - return ambiguous && this == AFTER_PUBLISH_AMBIGUOUS_WITH_DEDUPLICATION; - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/bridge/MongoBridgeOutboxPolicy.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/bridge/MongoBridgeOutboxPolicy.java deleted file mode 100644 index 50563d09..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/bridge/MongoBridgeOutboxPolicy.java +++ /dev/null @@ -1,46 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.advanced.bridge; - -/** - * When a change stream bridge is not enough (advanced plan Task 12). - * - *

The bridge publishes after the write is committed, so there is a window in which the write - * exists and the event does not. For most integrations that is fine — the event arrives late. It is - * not fine when the event must exist if and only if the write does, and the only way to get that is - * to write the event in the same transaction as the data, which is a transactional outbox. - * - *

Stated as a policy rather than a comment because the distinction is easy to get wrong in the - * direction that looks like it works. - */ -public enum MongoBridgeOutboxPolicy { - - /** - * At-least-once publication after commit is acceptable. - * - *

The consumer tolerates duplicates and a delay, and no business rule depends on the event - * existing exactly when the write does. - */ - CHANGE_STREAM_SUFFICIENT, - - /** - * The event and the write must be atomic. - * - *

Use a transactional outbox: write the event document in the same transaction as the data and - * publish from the outbox. - */ - OUTBOX_REQUIRED; - - /** True when a change stream bridge can serve this integration. */ - public boolean bridgeSufficient() { - return this == CHANGE_STREAM_SUFFICIENT; - } - - /** - * Chooses a policy from the integration's requirements. - * - * @param eventMustBeAtomicWithWrite whether a consumer may ever observe the write without the - * event - */ - public static MongoBridgeOutboxPolicy forRequirement(boolean eventMustBeAtomicWithWrite) { - return eventMustBeAtomicWithWrite ? OUTBOX_REQUIRED : CHANGE_STREAM_SUFFICIENT; - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/bridge/MongoChangeMessagingBridge.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/bridge/MongoChangeMessagingBridge.java deleted file mode 100644 index f7e56364..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/bridge/MongoChangeMessagingBridge.java +++ /dev/null @@ -1,87 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.advanced.bridge; - -import dev.caskeleton.adapter.outbound.mongo.advanced.MongoAdvancedCapabilityGuard; -import dev.caskeleton.adapter.outbound.mongo.advanced.MongoAdvancedEntryPoint; -import dev.caskeleton.adapter.outbound.mongo.api.capability.MongoCapability; -import dev.caskeleton.adapter.outbound.mongo.changestream.MongoChangeEventIdentity; -import dev.caskeleton.adapter.outbound.mongo.changestream.MongoResumeCheckpoint; -import dev.caskeleton.adapter.outbound.mongo.changestream.MongoResumeCheckpointStore; -import java.util.Objects; -import org.bson.BsonDocument; -import reactor.core.publisher.Mono; - -/** - * Publishes mapped integration events and checkpoints only after the broker accepts (advanced plan - * Task 12). - * - *

A failed publish leaves the MongoDB checkpoint untouched, so the change is redelivered. That - * is the same trade the change stream projector makes — duplicates rather than loss — and it works - * for the same reason: the message id is derived from the change identity, so a redelivered change - * produces a message the consumer can recognise as one it has already seen. - */ -@MongoAdvancedEntryPoint(MongoCapability.CHANGE_STREAM) -public final class MongoChangeMessagingBridge { - - private final MongoChangeToIntegrationEventMapper mapper; - - private final MongoIntegrationEventPublisher publisher; - - private final MongoResumeCheckpointStore checkpoints; - - private final MongoBridgeCheckpointPolicy checkpointPolicy; - - public MongoChangeMessagingBridge( - MongoAdvancedCapabilityGuard guard, - MongoChangeToIntegrationEventMapper mapper, - MongoIntegrationEventPublisher publisher, - MongoResumeCheckpointStore checkpoints, - MongoBridgeCheckpointPolicy checkpointPolicy) { - Objects.requireNonNull(guard, "guard").require(MongoChangeMessagingBridge.class); - this.mapper = Objects.requireNonNull(mapper, "mapper"); - this.publisher = Objects.requireNonNull(publisher, "publisher"); - this.checkpoints = Objects.requireNonNull(checkpoints, "checkpoints"); - this.checkpointPolicy = Objects.requireNonNull(checkpointPolicy, "checkpointPolicy"); - } - - /** - * Handles one change event. - * - *

A change the mapper does not map still advances the checkpoint: it was considered and found - * uninteresting, which is different from having failed to publish it. - */ - public Mono handle( - MongoChangeEventIdentity identity, BsonDocument change, MongoResumeCheckpoint checkpoint) { - Objects.requireNonNull(identity, "identity"); - Objects.requireNonNull(change, "change"); - Objects.requireNonNull(checkpoint, "checkpoint"); - - MongoIntegrationEventEnvelope envelope = mapper.map(identity, change); - if (envelope == null) { - return checkpoints.save(checkpoint); - } - // The broker's own answer decides whether the checkpoint moves. The constants that used to be - // passed here made both of the policy's branches unreachable. - return publisher - .publish(envelope) - .flatMap( - result -> - advanceIfAllowed(checkpoint, result.published(), result.ambiguous()) - .then( - result.definitelyNotDelivered() - // A refused publish is a failure, not a quiet non-advance: leaving the - // checkpoint behind and returning success makes the stream replay the - // same change forever with nothing reporting why. - ? Mono.error( - new IllegalStateException( - "the broker refused the integration event for change " - + identity)) - : Mono.empty())); - } - - private Mono advanceIfAllowed( - MongoResumeCheckpoint checkpoint, boolean published, boolean ambiguous) { - return checkpointPolicy.mayAdvance(published, ambiguous) - ? checkpoints.save(checkpoint) - : Mono.empty(); - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/bridge/MongoChangeToIntegrationEventMapper.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/bridge/MongoChangeToIntegrationEventMapper.java deleted file mode 100644 index 6e01fc62..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/bridge/MongoChangeToIntegrationEventMapper.java +++ /dev/null @@ -1,24 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.advanced.bridge; - -import dev.caskeleton.adapter.outbound.mongo.changestream.MongoChangeEventIdentity; -import org.bson.BsonDocument; - -/** - * Turns a physical change into a business event (advanced plan Task 12). - * - *

This mapper is the boundary the design refuses to remove. A MongoDB change event exposes the - * collection's field names, its update descriptions and its storage layout; publishing it as an - * integration contract makes every consumer depend on all three, so renaming a field becomes a - * breaking change to an external API. - * - *

The event type, schema version and message id are the mapper's own decisions, not derived from - * the change document, which is what lets the storage layout change without the contract changing. - */ -@FunctionalInterface -public interface MongoChangeToIntegrationEventMapper { - - /** - * Maps one change event, or returns {@code null} when the change is not externally interesting. - */ - MongoIntegrationEventEnvelope map(MongoChangeEventIdentity identity, BsonDocument change); -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/bridge/MongoIntegrationEventEnvelope.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/bridge/MongoIntegrationEventEnvelope.java deleted file mode 100644 index d02e9b22..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/bridge/MongoIntegrationEventEnvelope.java +++ /dev/null @@ -1,37 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.advanced.bridge; - -import java.util.Map; -import java.util.Objects; - -/** - * A stable integration event, ready to publish (advanced plan Task 12). - * - *

The platform's own envelope rather than the messaging module's type: this leaf may not depend - * on a sibling adapter, so the composition root adapts this to whatever the messaging platform - * publishes. The adaptation is one mapper; the alternative would be a dependency edge the - * architecture registry forbids. - * - *

{@code messageId} is derived from the change event identity, so a redelivered change produces - * the same message id and the consumer's deduplication works. - */ -public record MongoIntegrationEventEnvelope( - String eventType, int schemaVersion, String messageId, Map payload) { - - public MongoIntegrationEventEnvelope { - Objects.requireNonNull(eventType, "eventType"); - Objects.requireNonNull(messageId, "messageId"); - Objects.requireNonNull(payload, "payload"); - payload = Map.copyOf(payload); - if (eventType.isBlank()) { - throw new IllegalArgumentException("an integration event needs a type"); - } - if (schemaVersion < 1) { - throw new IllegalArgumentException("an integration event schema version starts at 1"); - } - if (messageId.isBlank()) { - throw new IllegalArgumentException( - "an integration event needs a deterministic message id so a redelivered change produces " - + "the same message"); - } - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/bridge/MongoIntegrationEventPublisher.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/bridge/MongoIntegrationEventPublisher.java deleted file mode 100644 index f092848c..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/bridge/MongoIntegrationEventPublisher.java +++ /dev/null @@ -1,25 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.advanced.bridge; - -import reactor.core.publisher.Mono; - -/** - * The outbound port the bridge publishes through (advanced plan Task 12). - * - *

Declared here rather than imported from the messaging adapter, because the architecture - * registry does not permit an edge between two outbound adapters. The composition root implements - * this against whichever messaging platform is wired. - */ -@FunctionalInterface -public interface MongoIntegrationEventPublisher { - - /** - * Publishes one event and reports what the broker said. - * - *

Returns a result rather than {@code Mono}. Completion alone cannot distinguish a - * confirmed publish from an acknowledgement that timed out after the message left, and the - * bridge's checkpoint policy needs exactly that distinction: advancing a resume checkpoint on an - * ambiguous publish loses the change if the message never arrived, because a change stream does - * not offer again what the checkpoint has passed. - */ - Mono publish(MongoIntegrationEventEnvelope envelope); -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/bridge/MongoPublishResult.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/bridge/MongoPublishResult.java deleted file mode 100644 index da8c3a9c..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/bridge/MongoPublishResult.java +++ /dev/null @@ -1,51 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.advanced.bridge; - -/** - * What the broker adapter actually said about a publish. - * - *

The bridge passed the constants {@code published=true, ambiguous=false} into its checkpoint - * policy on every successful completion. The policy therefore had two parameters and one possible - * pair of arguments: it could express "hold the checkpoint until the broker confirms" and "hold it - * when the outcome is ambiguous", and neither branch was reachable. A broker that accepted a - * connection and then lost the message, or one whose acknowledgement timed out after the message - * left, advanced the resume checkpoint exactly as a confirmed publish would — and the change stream - * never replays what the checkpoint has passed. - * - * @param published whether the broker confirmed it holds the message - * @param ambiguous whether the outcome is unknown — sent, unacknowledged, possibly delivered - */ -public record MongoPublishResult(boolean published, boolean ambiguous) { - - public MongoPublishResult { - if (published && ambiguous) { - throw new IllegalArgumentException( - "a confirmed publish is not ambiguous; reporting both leaves the checkpoint policy no" - + " decision to make"); - } - } - - /** The broker confirmed it holds the message. */ - public static MongoPublishResult confirmed() { - return new MongoPublishResult(true, false); - } - - /** - * The message may or may not have been delivered. - * - *

The case the constants erased. Advancing a resume checkpoint here loses the change if the - * message never arrived, and the change stream will not offer it again. - */ - public static MongoPublishResult unknown() { - return new MongoPublishResult(false, true); - } - - /** The broker refused it, and nothing was delivered. */ - public static MongoPublishResult failed() { - return new MongoPublishResult(false, false); - } - - /** Whether this result is a definite non-delivery. */ - public boolean definitelyNotDelivered() { - return !published && !ambiguous; - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/encryption/csfle/MongoDataKeyResolver.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/encryption/csfle/MongoDataKeyResolver.java deleted file mode 100644 index 47de1e2b..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/encryption/csfle/MongoDataKeyResolver.java +++ /dev/null @@ -1,28 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.advanced.encryption.csfle; - -import java.util.Optional; - -/** - * Resolves the data key a field is encrypted with (advanced plan Task 6). - * - *

An interface rather than a lookup table, because the key for a field can depend on the tenant. - * Per-tenant keys are what make "delete this tenant's data" achievable by destroying one key - * instead of finding every document. - * - *

Implementations return an alias, never key material. The driver resolves the alias against the - * key vault; the platform never holds a plaintext key. - */ -public interface MongoDataKeyResolver { - - /** The key alias for a field, optionally scoped to a tenant. */ - Optional resolveKeyAlias(String collection, String fieldPath, String tenantKey); - - /** A resolver that always returns the field policy's declared alias. */ - static MongoDataKeyResolver fixed(MongoCsfleProfile profile) { - return (collection, fieldPath, tenantKey) -> - profile.fields().stream() - .filter(field -> field.fieldPath().equals(fieldPath)) - .map(MongoCsfleFieldPolicy::keyAlias) - .findFirst(); - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/gridfs/MongoGridFsCompatibilityReader.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/gridfs/MongoGridFsCompatibilityReader.java deleted file mode 100644 index f48ecabd..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/gridfs/MongoGridFsCompatibilityReader.java +++ /dev/null @@ -1,45 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.advanced.gridfs; - -import java.io.InputStream; - -/** - * Read-only access to legacy GridFS content (advanced plan Task 13, design D-14). - * - *

There is no upload method, and that is deliberate. Offering one would make GridFS a live file - * platform again, and the migration this module exists to perform would never finish — new files - * would keep arriving in the place everything is being moved out of. - */ -public interface MongoGridFsCompatibilityReader { - - /** Opens a legacy file for reading. */ - GridFsLegacyContent open(String legacyId); - - /** - * One legacy GridFS file. - * - * @param legacyId the GridFS file id - * @param filename the stored filename - * @param sizeBytes the file length - * @param checksum the stored checksum, or an empty string when GridFS recorded none - * @param content the byte stream this record owns - */ - record GridFsLegacyContent( - String legacyId, String filename, long sizeBytes, String checksum, InputStream content) - implements java.io.Closeable { - - /** - * Closes the underlying stream. - * - *

The record used to say "which the caller closes" and the migration job did not: it handed - * the stream to a writer and returned. Every migrated file leaked a GridFS cursor, and a corpus - * migration is measured in hundreds of thousands of files. Being {@link java.io.Closeable} is - * what lets the owner use try-with-resources instead of remembering. - */ - @Override - public void close() throws java.io.IOException { - if (content != null) { - content.close(); - } - } - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/gridfs/MongoGridFsMigrationCheckpoint.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/gridfs/MongoGridFsMigrationCheckpoint.java deleted file mode 100644 index 9a64c88c..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/gridfs/MongoGridFsMigrationCheckpoint.java +++ /dev/null @@ -1,106 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.advanced.gridfs; - -import java.time.Instant; -import java.util.Objects; - -/** - * How far a GridFS migration has progressed (advanced plan Task 13). - * - *

Migrating a file corpus is measured in hours or days, so the checkpoint is what makes the job - * survivable across deployments. Failures are tracked as ids rather than as a count, because "forty - * files failed" is not something anyone can act on and "these forty ids failed" is. - * - *

Poison objects. An id that fails every retry pass — a truncated GridFS file, - * a checksum that will never match — stays on the list and keeps its slot. That is deliberate: the - * list is bounded and full is an error, so a poison object eventually stops the migration and - * demands a decision rather than being retried forever in the background. Resolving one means - * either migrating it or removing it from the corpus by hand; both are operator actions, and both - * are visible. - */ -public record MongoGridFsMigrationCheckpoint( - String lastSuccessfullyProcessedLegacyId, - long migratedCount, - java.util.List failedObjects, - Instant updatedAt) { - - /** - * How many failed ids the queue keeps. - * - *

Bounded because the queue is a retry list, not a log. An unbounded list of failures on a - * corpus migration grows with the corpus, and a checkpoint document that grows without limit - * eventually cannot be written at all — at which point the migration loses its position as well - * as its failures. - */ - public static final int MAXIMUM_TRACKED_FAILURES = 1_000; - - public MongoGridFsMigrationCheckpoint { - Objects.requireNonNull(lastSuccessfullyProcessedLegacyId, "lastSuccessfullyProcessedLegacyId"); - Objects.requireNonNull(failedObjects, "failedObjects"); - Objects.requireNonNull(updatedAt, "updatedAt"); - failedObjects = java.util.List.copyOf(failedObjects); - if (migratedCount < 0) { - throw new IllegalArgumentException("the migrated count must not be negative"); - } - if (failedObjects.size() > MAXIMUM_TRACKED_FAILURES) { - throw new IllegalArgumentException( - "a checkpoint tracks at most " + MAXIMUM_TRACKED_FAILURES + " failed objects"); - } - } - - /** The checkpoint before anything has been migrated. */ - public static MongoGridFsMigrationCheckpoint start(Instant now) { - return new MongoGridFsMigrationCheckpoint("", 0, java.util.List.of(), now); - } - - /** The checkpoint after one successful file. */ - public MongoGridFsMigrationCheckpoint migrated(String legacyId, Instant now) { - return new MongoGridFsMigrationCheckpoint(legacyId, migratedCount + 1, failedObjects, now); - } - - /** - * The checkpoint after one failed file. - * - *

The resume position does not advance. It used to: the field was named {@code - * lastMigratedLegacyId} and the failure path wrote the failed id into it, so a restart resumed - * from a file that had never been migrated and treated everything before it as done. The failed - * id goes on its own list instead, which is what a retry pass reads. - * - * @throws IllegalStateException when the failure list is full, because silently dropping a failed - * id is losing a file - */ - public MongoGridFsMigrationCheckpoint failed(String legacyId, Instant now) { - Objects.requireNonNull(legacyId, "legacyId"); - if (failedObjects.contains(legacyId)) { - return new MongoGridFsMigrationCheckpoint( - lastSuccessfullyProcessedLegacyId, migratedCount, failedObjects, now); - } - if (failedObjects.size() == MAXIMUM_TRACKED_FAILURES) { - throw new IllegalStateException( - "the GridFS migration has " - + MAXIMUM_TRACKED_FAILURES - + " unresolved failed objects; the run stops rather than dropping ids, because a" - + " dropped id is a file nobody will look for again"); - } - java.util.List failures = new java.util.ArrayList<>(failedObjects); - failures.add(legacyId); - return new MongoGridFsMigrationCheckpoint( - lastSuccessfullyProcessedLegacyId, migratedCount, failures, now); - } - - /** The checkpoint after a failed object was migrated on a retry pass. */ - public MongoGridFsMigrationCheckpoint resolved(String legacyId, Instant now) { - java.util.List failures = new java.util.ArrayList<>(failedObjects); - failures.remove(Objects.requireNonNull(legacyId, "legacyId")); - return new MongoGridFsMigrationCheckpoint(legacyId, migratedCount + 1, failures, now); - } - - /** How many objects failed and have not been resolved. */ - public long failedCount() { - return failedObjects.size(); - } - - /** True when every file processed so far succeeded. */ - public boolean clean() { - return failedObjects.isEmpty(); - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/gridfs/MongoGridFsMigrationJob.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/gridfs/MongoGridFsMigrationJob.java deleted file mode 100644 index 6ab3e4e5..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/gridfs/MongoGridFsMigrationJob.java +++ /dev/null @@ -1,86 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.advanced.gridfs; - -import dev.caskeleton.adapter.outbound.mongo.advanced.MongoAdvancedCapabilityGuard; -import dev.caskeleton.adapter.outbound.mongo.advanced.MongoAdvancedEntryPoint; -import dev.caskeleton.adapter.outbound.mongo.api.capability.MongoCapability; -import java.time.Clock; -import java.util.Objects; -import java.util.Optional; -import java.util.function.BiFunction; -import java.util.function.Consumer; - -/** - * Copies legacy GridFS content into the file source of truth (advanced plan Task 13). - * - *

Verify before switching, and never delete here. The order is copy, verify size and checksum, - * then write the new reference — so a mismatch leaves the document pointing at GridFS, where the - * bytes still are. Deleting the source is a separate, audited cleanup phase that runs after the - * references have been switched and observed. - * - *

The legacy id is the deterministic identity, so re-running the job over an already-migrated - * file produces the same content key rather than a second copy. - */ -@MongoAdvancedEntryPoint(MongoCapability.GRIDFS_COMPATIBILITY) -public final class MongoGridFsMigrationJob { - - private final MongoGridFsCompatibilityReader reader; - - private final BiFunction< - String, MongoGridFsCompatibilityReader.GridFsLegacyContent, MongoGridFsObjectReference> - contentStoreWriter; - - private final Consumer referenceWriter; - - private final Clock clock; - - public MongoGridFsMigrationJob( - MongoGridFsCompatibilityReader reader, - BiFunction< - String, - MongoGridFsCompatibilityReader.GridFsLegacyContent, - MongoGridFsObjectReference> - contentStoreWriter, - Consumer referenceWriter, - MongoAdvancedCapabilityGuard guard, - Clock clock) { - this.reader = Objects.requireNonNull(reader, "reader"); - this.contentStoreWriter = Objects.requireNonNull(contentStoreWriter, "contentStoreWriter"); - this.referenceWriter = Objects.requireNonNull(referenceWriter, "referenceWriter"); - this.clock = Objects.requireNonNull(clock, "clock"); - Objects.requireNonNull(guard, "guard").require(MongoGridFsMigrationJob.class); - } - - /** - * Migrates one file. - * - * @return the new reference when the copy verified, empty when it did not - */ - public Optional migrate(String legacyId) { - Objects.requireNonNull(legacyId, "legacyId"); - // try-with-resources: the reader's contract says the stream belongs to whoever opened it, and - // this job opened it. Handing it to a writer and returning leaked one GridFS cursor per file, - // which on a corpus migration is the whole corpus. - try (MongoGridFsCompatibilityReader.GridFsLegacyContent source = reader.open(legacyId)) { - MongoGridFsObjectReference written = contentStoreWriter.apply(legacyId, source); - if (!written.matches(source.sizeBytes(), source.checksum())) { - // The source stays exactly where it is: the document still references GridFS, so nothing is - // lost and the file can be retried. - return Optional.empty(); - } - referenceWriter.accept(written); - return Optional.of(written); - } catch (java.io.IOException closeFailed) { - throw new java.io.UncheckedIOException( - "the legacy GridFS stream for " + legacyId + " could not be closed", closeFailed); - } - } - - /** Migrates one file and folds the outcome into a checkpoint. */ - public MongoGridFsMigrationCheckpoint migrate( - String legacyId, MongoGridFsMigrationCheckpoint checkpoint) { - Objects.requireNonNull(checkpoint, "checkpoint"); - return migrate(legacyId).isPresent() - ? checkpoint.migrated(legacyId, clock.instant()) - : checkpoint.failed(legacyId, clock.instant()); - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/gridfs/MongoGridFsObjectReference.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/gridfs/MongoGridFsObjectReference.java deleted file mode 100644 index 58dec8cf..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/gridfs/MongoGridFsObjectReference.java +++ /dev/null @@ -1,33 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.advanced.gridfs; - -import java.util.Objects; - -/** - * The reference that replaces a GridFS file after migration (advanced plan Task 13, design D-14). - * - *

The document keeps a reference; the bytes live in the file source of truth. That is the whole - * point of the migration: GridFS makes MongoDB a file server, which means file storage competes - * with the working set for cache and with the oplog for replication bandwidth. - */ -public record MongoGridFsObjectReference( - String legacyGridFsId, String contentKey, long sizeBytes, String checksum) { - - public MongoGridFsObjectReference { - Objects.requireNonNull(legacyGridFsId, "legacyGridFsId"); - Objects.requireNonNull(contentKey, "contentKey"); - Objects.requireNonNull(checksum, "checksum"); - if (sizeBytes < 0) { - throw new IllegalArgumentException("a content size must not be negative"); - } - if (checksum.isBlank()) { - throw new IllegalArgumentException( - "a migrated reference needs a checksum; without one the copy cannot be verified and the " - + "source cannot safely be deleted"); - } - } - - /** True when a target object matches this reference's size and checksum. */ - public boolean matches(long targetSizeBytes, String targetChecksum) { - return sizeBytes == targetSizeBytes && checksum.equals(targetChecksum); - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/search/MongoSearchIndexDescriptor.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/search/MongoSearchIndexDescriptor.java deleted file mode 100644 index 3f201c08..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/search/MongoSearchIndexDescriptor.java +++ /dev/null @@ -1,38 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.advanced.search; - -import dev.caskeleton.adapter.outbound.mongo.schema.manifest.MongoMetadataOwnership; -import java.util.List; -import java.util.Objects; - -/** - * A search index declaration (advanced plan Task 8). - * - *

Owned by {@link MongoMetadataOwnership#SEARCH_MANAGED}, so ordinary index drift cleanup leaves - * it alone: a search index is not a b-tree index, it does not appear in {@code listIndexes}, and - * the subsystem that maintains it has its own admin plane. - */ -public record MongoSearchIndexDescriptor( - String name, String collection, List searchablePaths, String analyzer) { - - public MongoSearchIndexDescriptor { - Objects.requireNonNull(name, "name"); - Objects.requireNonNull(collection, "collection"); - Objects.requireNonNull(searchablePaths, "searchablePaths"); - Objects.requireNonNull(analyzer, "analyzer"); - searchablePaths = List.copyOf(searchablePaths); - if (searchablePaths.isEmpty()) { - throw new IllegalArgumentException("a search index needs at least one searchable path"); - } - } - - /** A search index over the given paths using the standard analyzer. */ - public static MongoSearchIndexDescriptor standard( - String name, String collection, List searchablePaths) { - return new MongoSearchIndexDescriptor(name, collection, searchablePaths, "lucene.standard"); - } - - /** Who owns this index for drift purposes. Always the search subsystem. */ - public MongoMetadataOwnership metadataOwnership() { - return MongoMetadataOwnership.SEARCH_MANAGED; - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/search/MongoSearchIndexState.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/search/MongoSearchIndexState.java deleted file mode 100644 index 3b4f8250..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/search/MongoSearchIndexState.java +++ /dev/null @@ -1,32 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.advanced.search; - -/** - * The lifecycle of a search or vector index (advanced plan Task 8). - * - *

Creation returns as soon as the request is accepted, and the index then builds asynchronously. - * A query against a {@code BUILDING} index does not fail — it returns partial results — so a - * deployment that queries immediately after creating gets a search feature that silently misses - * documents and then quietly starts working. - */ -public enum MongoSearchIndexState { - - /** The creation request was accepted. */ - CREATED, - - /** The index is being built. Queries would return partial results. */ - BUILDING, - - /** The index is complete and safe to query. */ - READY, - - /** The build failed. */ - FAILED, - - /** The index is being removed. */ - DELETING; - - /** True when queries against this index return complete results. */ - public boolean queryable() { - return this == READY; - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/search/MongoSearchOperations.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/search/MongoSearchOperations.java deleted file mode 100644 index d8c87417..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/search/MongoSearchOperations.java +++ /dev/null @@ -1,28 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.advanced.search; - -import dev.caskeleton.adapter.outbound.mongo.api.MongoOperationContext; -import java.util.List; - -/** - * Full-text search against a {@code READY} index (advanced plan Task 8). - * - *

Legacy {@code $text} is deliberately not routed here. The two have different relevance models - * and different index requirements, so silently redirecting a {@code $text} query to Search would - * change result ordering for every caller that was relying on the old behaviour. - * - *

Scaffold. This repository ships no implementation of {@code - * MongoSearchOperations}. The contract is here so a fork wiring Atlas Search has a shape to - * implement and a place for the platform's rules to attach; it needs an Atlas deployment with a - * configured search index, none of which this template provides. Read a method signature as a - * specification, not as an available capability — an interface with no implementation cannot be - * injected, and treating it as shipped behaviour is how "the platform supports search" becomes true - * in a document and false in a deployment. - */ -public interface MongoSearchOperations { - - /** Runs a search query, refusing if the index is not ready. */ - List search(MongoOperationContext context, MongoSearchQuery query, Class documentType); - - /** The current state of a search index. */ - MongoSearchIndexState indexState(String indexName); -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/search/MongoSearchQuery.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/search/MongoSearchQuery.java deleted file mode 100644 index f371ff53..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/search/MongoSearchQuery.java +++ /dev/null @@ -1,57 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.advanced.search; - -import dev.caskeleton.adapter.outbound.mongo.api.error.MongoOperationRejectedException; -import java.util.List; -import java.util.Objects; -import java.util.Set; - -/** - * A bounded, allowlisted search query (advanced plan Task 8). - * - *

Search paths are allowlisted for the same reason ordinary query fields are: {@code $search} - * runs against whatever the index covers, and an index built over a whole document covers fields - * the caller was never meant to search — or to learn the existence of from a hit count. - */ -public record MongoSearchQuery( - String indexName, List paths, String queryText, int resultLimit) { - - /** The largest result set a search query may request. */ - public static final int MAX_RESULT_LIMIT = 200; - - /** The longest query text accepted. */ - public static final int MAX_QUERY_LENGTH = 512; - - public MongoSearchQuery { - Objects.requireNonNull(indexName, "indexName"); - Objects.requireNonNull(paths, "paths"); - Objects.requireNonNull(queryText, "queryText"); - paths = List.copyOf(paths); - if (paths.isEmpty()) { - throw new IllegalArgumentException("a search query needs at least one path"); - } - if (queryText.length() > MAX_QUERY_LENGTH) { - throw MongoOperationRejectedException.of( - "search.query", - "the search text is " + queryText.length() + " characters, above " + MAX_QUERY_LENGTH); - } - if (resultLimit <= 0 || resultLimit > MAX_RESULT_LIMIT) { - throw MongoOperationRejectedException.of( - "search.query", "a search query needs a result limit between 1 and " + MAX_RESULT_LIMIT); - } - } - - /** - * Checks the query's paths against the index's allowlist. - * - * @throws MongoOperationRejectedException when a path is not searchable - */ - public void requireAllowedPaths(Set allowedPaths) { - Objects.requireNonNull(allowedPaths, "allowedPaths"); - for (String path : paths) { - if (!allowedPaths.contains(path)) { - throw MongoOperationRejectedException.of( - "search.query", "path '" + path + "' is not on this index's searchable allowlist"); - } - } - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/search/MongoSearchReadinessGate.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/search/MongoSearchReadinessGate.java deleted file mode 100644 index fa4737ae..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/search/MongoSearchReadinessGate.java +++ /dev/null @@ -1,37 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.advanced.search; - -import dev.caskeleton.adapter.outbound.mongo.advanced.MongoAdvancedPolicy; -import dev.caskeleton.adapter.outbound.mongo.api.error.MongoOperationRejectedException; -import java.util.Objects; - -/** - * Refuses to query an index that is not {@code READY} (advanced plan Task 8). - * - *

The distinction this gate enforces is the one the API makes easy to miss: "the index was - * created" and "the index can answer queries" are different states, separated by a build that can - * take minutes on a large collection. - */ -@MongoAdvancedPolicy -public final class MongoSearchReadinessGate { - - /** - * Checks an index state before a query runs. - * - * @throws MongoOperationRejectedException when the index cannot return complete results - */ - public void requireReady(MongoSearchIndexState state) { - Objects.requireNonNull(state, "state"); - if (!state.queryable()) { - throw MongoOperationRejectedException.of( - "search.readiness", - "the search index is " - + state - + ", not READY; querying it now returns partial results rather than an error"); - } - } - - /** True when a query may run against this index. */ - public boolean queryable(MongoSearchIndexState state) { - return Objects.requireNonNull(state, "state").queryable(); - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/tenancy/database/MongoTenantDatabaseResolver.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/tenancy/database/MongoTenantDatabaseResolver.java deleted file mode 100644 index c1abb429..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/tenancy/database/MongoTenantDatabaseResolver.java +++ /dev/null @@ -1,18 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.advanced.tenancy.database; - -import dev.caskeleton.adapter.outbound.mongo.advanced.tenancy.shared.MongoTenantContext; -import dev.caskeleton.adapter.outbound.mongo.api.DatabaseProfileName; - -/** - * Maps a tenant to its database profile (advanced plan Task 11). - * - *

The mapping comes from a trusted registry, never from request input. Deriving a database name - * from a header or a token claim makes the database name attacker-controlled, and a database name - * is the one string that decides which tenant's data a query reads. - */ -@FunctionalInterface -public interface MongoTenantDatabaseResolver { - - /** The database profile for a tenant. */ - DatabaseProfileName resolve(MongoTenantContext tenant); -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/tenancy/shared/TenantScopedMongoOperations.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/tenancy/shared/TenantScopedMongoOperations.java deleted file mode 100644 index 19c752c2..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/tenancy/shared/TenantScopedMongoOperations.java +++ /dev/null @@ -1,39 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.advanced.tenancy.shared; - -import dev.caskeleton.adapter.outbound.mongo.api.MongoOperationContext; -import dev.caskeleton.adapter.outbound.mongo.imperative.atomic.AtomicFilter; -import dev.caskeleton.adapter.outbound.mongo.imperative.atomic.AtomicUpdate; -import dev.caskeleton.adapter.outbound.mongo.imperative.atomic.AtomicUpdateResult; -import java.util.List; -import java.util.Optional; -import org.springframework.data.mongodb.core.query.Query; - -/** - * Operations that cannot run without a tenant predicate (advanced plan Task 10). - * - *

Every method takes the tenant context explicitly rather than reading it from a thread or a - * request scope. An implicit lookup is invisible at the call site, which means a background job, a - * scheduled task or a message consumer can run tenant-scoped code with no tenant and nothing in the - * code says so. - */ -public interface TenantScopedMongoOperations { - - /** Finds documents belonging to the tenant. */ - List find( - MongoOperationContext context, - Optional tenant, - Query query, - Class documentType); - - /** Updates one of the tenant's documents. */ - AtomicUpdateResult updateOne( - MongoOperationContext context, - Optional tenant, - AtomicFilter filter, - AtomicUpdate update, - Class documentType); - - /** Deletes one of the tenant's documents. */ - long deleteOne( - MongoOperationContext context, Optional tenant, AtomicFilter filter); -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/timeseries/MongoTimeSeriesCapability.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/timeseries/MongoTimeSeriesCapability.java deleted file mode 100644 index d3964e66..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/timeseries/MongoTimeSeriesCapability.java +++ /dev/null @@ -1,24 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.advanced.timeseries; - -/** - * A capability a time series collection may or may not have. - * - *

Named so a caller can ask, rather than call a method that always throws. Four public methods - * whose entire body was {@code throw new UnsupportedOperationException} are an API that cannot be - * used correctly: every call site is either dead code or a bug, and the compiler cannot tell which. - * What a caller actually needs is the answer, and the reason. - */ -public enum MongoTimeSeriesCapability { - - /** Change streams. Time series collections are bucketed, so a change is not a measurement. */ - CHANGE_STREAM, - - /** JSON Schema validators. The stored bucket is not the document the writer supplied. */ - SCHEMA_VALIDATOR, - - /** Client-side field level encryption. */ - FIELD_LEVEL_ENCRYPTION, - - /** Transactional writes. */ - TRANSACTIONAL_WRITE -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/timeseries/MongoTimeSeriesCapabilityValidator.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/timeseries/MongoTimeSeriesCapabilityValidator.java deleted file mode 100644 index 25660770..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/timeseries/MongoTimeSeriesCapabilityValidator.java +++ /dev/null @@ -1,70 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.advanced.timeseries; - -import dev.caskeleton.adapter.outbound.mongo.advanced.MongoAdvancedPolicy; -import java.util.Objects; - -/** - * What a time series collection can and cannot do. - * - *

This class used to expose four public methods whose entire body was {@code throw new - * UnsupportedOperationException}. An API like that cannot be used correctly: every call site is - * either dead code or a bug, and nothing distinguishes them — a caller who genuinely needs change - * streams learns so at runtime, in production, from an exception that names a limitation of the - * storage engine rather than a mistake in their design. - * - *

So the question is answerable instead. {@link #supportFor} returns the verdict and the reason, - * and a descriptor that requires an unsupported capability is rejected at validation time — before - * the collection exists, which is when the choice can still be changed. - */ -@MongoAdvancedPolicy -public final class MongoTimeSeriesCapabilityValidator { - - /** - * Whether a time series collection offers a capability. - * - * @param capability the capability in question - */ - public MongoTimeSeriesSupport supportFor(MongoTimeSeriesCapability capability) { - Objects.requireNonNull(capability, "capability"); - return switch (capability) { - case CHANGE_STREAM -> - MongoTimeSeriesSupport.unsupported( - capability, - "a time series collection stores buckets, so a change event describes a bucket" - + " rather than a measurement; stream the source of the measurements instead"); - case SCHEMA_VALIDATOR -> - MongoTimeSeriesSupport.unsupported( - capability, - "the stored bucket is not the document the writer supplied, so a JSON Schema" - + " validator would validate something the application never wrote; validate" - + " measurements before they are written"); - case FIELD_LEVEL_ENCRYPTION -> - MongoTimeSeriesSupport.unsupported( - capability, - "client-side field level encryption is not available on time series collections"); - case TRANSACTIONAL_WRITE -> - MongoTimeSeriesSupport.unsupported( - capability, "time series writes do not participate in a transaction"); - }; - } - - /** - * Rejects a descriptor that asks for something a time series collection cannot do. - * - * @throws IllegalArgumentException naming the capability and why it is unavailable - */ - public void requireSupported( - MongoTimeSeriesDescriptor descriptor, MongoTimeSeriesCapability capability) { - Objects.requireNonNull(descriptor, "descriptor"); - MongoTimeSeriesSupport support = supportFor(capability); - if (!support.supported()) { - throw new IllegalArgumentException( - "a time series collection on " - + descriptor.timeField() - + " cannot provide " - + capability - + ": " - + support.reason()); - } - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/timeseries/MongoTimeSeriesDescriptor.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/timeseries/MongoTimeSeriesDescriptor.java deleted file mode 100644 index edc4892d..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/timeseries/MongoTimeSeriesDescriptor.java +++ /dev/null @@ -1,52 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.advanced.timeseries; - -import java.time.Duration; -import java.util.Objects; -import java.util.Optional; - -/** - * A time series collection's shape (advanced plan Task 5). - * - *

A separate descriptor rather than a variant of the ordinary collection manifest, because a - * time series collection does not inherit the ordinary contract: it has no schema validator, no - * change stream, no CSFLE, and its update and delete support is restricted. Modelling it as "a - * collection with a flag" would let all of those be configured and silently ignored. - */ -public record MongoTimeSeriesDescriptor( - String timeField, - String metaField, - MongoTimeSeriesGranularity granularity, - Duration retention) { - - public MongoTimeSeriesDescriptor { - Objects.requireNonNull(timeField, "timeField"); - Objects.requireNonNull(granularity, "granularity"); - if (timeField.isBlank()) { - throw new IllegalArgumentException("a time series collection needs an explicit timeField"); - } - if (retention != null && retention.isNegative()) { - throw new IllegalArgumentException("a time series retention must not be negative"); - } - } - - /** The common shape: a time field, a metadata field and minute granularity. */ - public static MongoTimeSeriesDescriptor standard(String timeField, String metaField) { - return new MongoTimeSeriesDescriptor( - timeField, metaField, MongoTimeSeriesGranularity.MINUTES, null); - } - - /** The metadata field, when the collection declares one. */ - public Optional meta() { - return Optional.ofNullable(metaField).filter(field -> !field.isBlank()); - } - - /** - * The retention window, when one is declared. - * - *

Time series retention is TTL-based, so it carries the same caveat as any TTL: it reclaims - * space eventually and is not a scheduler. - */ - public Optional retentionWindow() { - return Optional.ofNullable(retention); - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/timeseries/MongoTimeSeriesGranularity.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/timeseries/MongoTimeSeriesGranularity.java deleted file mode 100644 index e89ca8f9..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/timeseries/MongoTimeSeriesGranularity.java +++ /dev/null @@ -1,33 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.advanced.timeseries; - -import java.time.Duration; - -/** - * How far apart a time series collection expects consecutive measurements (advanced plan Task 5). - * - *

Granularity decides the bucket span, and a wrong choice is expensive in both directions: too - * coarse and each bucket holds too many measurements to read efficiently, too fine and the - * collection carries a bucket per measurement plus its overhead. - */ -public enum MongoTimeSeriesGranularity { - - /** Measurements arrive seconds apart. */ - SECONDS(Duration.ofHours(1)), - - /** Measurements arrive minutes apart. */ - MINUTES(Duration.ofHours(24)), - - /** Measurements arrive hours apart. */ - HOURS(Duration.ofDays(30)); - - private final Duration bucketSpan; - - MongoTimeSeriesGranularity(Duration bucketSpan) { - this.bucketSpan = bucketSpan; - } - - /** The time span one bucket covers at this granularity. */ - public Duration bucketSpan() { - return bucketSpan; - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/timeseries/MongoTimeSeriesOperations.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/timeseries/MongoTimeSeriesOperations.java deleted file mode 100644 index 6649eff9..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/timeseries/MongoTimeSeriesOperations.java +++ /dev/null @@ -1,34 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.advanced.timeseries; - -import dev.caskeleton.adapter.outbound.mongo.api.MongoOperationContext; -import java.time.Instant; -import java.util.List; - -/** - * The operations a time series collection actually supports (advanced plan Task 5). - * - *

Insert and range read, and nothing else. There is no update or delete method because MongoDB's - * support for both is restricted on time series collections, and an API that offered them would be - * offering something that fails at runtime depending on the server version and the fields touched. - * - *

Scaffold. This repository ships no implementation of {@code - * MongoTimeSeriesOperations}. The contract is here so a fork wiring time series collections has a - * shape to implement and a place for the platform's rules to attach; it needs a collection created - * with a time-series specification, none of which this template provides. Read a method signature - * as a specification, not as an available capability — an interface with no implementation cannot - * be injected, and treating it as shipped behaviour is how "the platform supports search" becomes - * true in a document and false in a deployment. - */ -public interface MongoTimeSeriesOperations { - - /** Appends measurements. */ - void insertAll(MongoOperationContext context, List measurements, Class measurementType); - - /** Reads measurements in a bounded time range, which is the query shape buckets are built for. */ - List findInRange( - MongoOperationContext context, - Instant from, - Instant to, - Class measurementType, - int resultLimit); -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/timeseries/MongoTimeSeriesSupport.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/timeseries/MongoTimeSeriesSupport.java deleted file mode 100644 index 31a09875..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/timeseries/MongoTimeSeriesSupport.java +++ /dev/null @@ -1,40 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.advanced.timeseries; - -import java.util.Objects; -import java.util.Optional; - -/** - * Whether a capability is supported, and why not when it is not. - * - * @param capability the capability asked about - * @param supported whether a time series collection offers it - * @param reason why not, when it is unsupported; empty when it is supported - */ -public record MongoTimeSeriesSupport( - MongoTimeSeriesCapability capability, boolean supported, String reason) { - - public MongoTimeSeriesSupport { - Objects.requireNonNull(capability, "capability"); - Objects.requireNonNull(reason, "reason"); - if (supported == !reason.isBlank()) { - throw new IllegalArgumentException( - "an unsupported capability states why, and a supported one has nothing to explain"); - } - } - - /** The capability is available. */ - public static MongoTimeSeriesSupport supported(MongoTimeSeriesCapability capability) { - return new MongoTimeSeriesSupport(capability, true, ""); - } - - /** The capability is not available, for this reason. */ - public static MongoTimeSeriesSupport unsupported( - MongoTimeSeriesCapability capability, String reason) { - return new MongoTimeSeriesSupport(capability, false, reason); - } - - /** The reason, when there is one. */ - public Optional explanation() { - return reason.isBlank() ? Optional.empty() : Optional.of(reason); - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/vector/MongoEmbedding.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/vector/MongoEmbedding.java deleted file mode 100644 index abf5bd6a..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/vector/MongoEmbedding.java +++ /dev/null @@ -1,65 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.advanced.vector; - -import dev.caskeleton.adapter.outbound.mongo.advanced.MongoAdvancedPolicy; -import java.util.Objects; - -/** - * An embedding bound to the index it was produced for (advanced plan Task 9). - * - *

{@link #forIndex} is the only way to build one, so a dimension mismatch cannot reach a query. - * MongoDB rejects a wrong-length vector, but the more common mistake — a vector of the right length - * from a different model — is caught here only by the index binding, which is why the factory takes - * the descriptor rather than a bare length. - */ -@MongoAdvancedPolicy -public final class MongoEmbedding { - - private final float[] values; - - private final MongoVectorIndexDescriptor index; - - private MongoEmbedding(float[] values, MongoVectorIndexDescriptor index) { - this.values = values; - this.index = index; - } - - /** - * Binds a vector to an index. - * - * @throws IllegalArgumentException when the vector's length is not the index's dimension - */ - public static MongoEmbedding forIndex(MongoVectorIndexDescriptor index, float[] values) { - Objects.requireNonNull(index, "index"); - Objects.requireNonNull(values, "values"); - if (values.length != index.dimensions()) { - throw new IllegalArgumentException( - "embedding has " - + values.length - + " dimensions but index '" - + index.name() - + "' expects " - + index.dimensions()); - } - return new MongoEmbedding(values.clone(), index); - } - - /** A defensive copy of the vector. */ - public float[] values() { - return values.clone(); - } - - /** The index this embedding was produced for. */ - public MongoVectorIndexDescriptor index() { - return index; - } - - /** The number of dimensions. */ - public int dimensions() { - return values.length; - } - - @Override - public String toString() { - return "MongoEmbedding[index=" + index.name() + ", dimensions=" + values.length + "]"; - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/vector/MongoVectorIndexDescriptor.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/vector/MongoVectorIndexDescriptor.java deleted file mode 100644 index efde94ad..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/vector/MongoVectorIndexDescriptor.java +++ /dev/null @@ -1,53 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.advanced.vector; - -import java.util.Objects; - -/** - * A vector index declaration (advanced plan Task 9). - * - *

Dimension and similarity metric are part of the index contract, not query parameters. Querying - * a cosine index with vectors produced for a dot-product model returns results — ranked by the - * wrong notion of similarity — so the mismatch has to be caught at the type level rather than - * observed in the output. - */ -public record MongoVectorIndexDescriptor( - String name, String path, int dimensions, MongoVectorSimilarity similarity) { - - /** The largest embedding dimension the platform accepts. */ - public static final int MAX_DIMENSIONS = 4096; - - public MongoVectorIndexDescriptor { - Objects.requireNonNull(name, "name"); - Objects.requireNonNull(path, "path"); - Objects.requireNonNull(similarity, "similarity"); - if (dimensions <= 0 || dimensions > MAX_DIMENSIONS) { - throw new IllegalArgumentException( - "an embedding dimension must be between 1 and " + MAX_DIMENSIONS); - } - } - - /** A cosine-similarity index. */ - public static MongoVectorIndexDescriptor cosine(String path, int dimensions) { - return new MongoVectorIndexDescriptor( - "ix_vector_" + path.replace('.', '_'), path, dimensions, MongoVectorSimilarity.COSINE); - } - - /** A dot-product index. */ - public static MongoVectorIndexDescriptor dotProduct(String path, int dimensions) { - return new MongoVectorIndexDescriptor( - "ix_vector_" + path.replace('.', '_'), path, dimensions, MongoVectorSimilarity.DOT_PRODUCT); - } - - /** How similarity is measured by this index. */ - public enum MongoVectorSimilarity { - - /** Angle between vectors; magnitude-independent. */ - COSINE, - - /** Dot product; magnitude matters. */ - DOT_PRODUCT, - - /** Euclidean distance. */ - EUCLIDEAN - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/vector/MongoVectorQuery.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/vector/MongoVectorQuery.java deleted file mode 100644 index 8f8a9623..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/vector/MongoVectorQuery.java +++ /dev/null @@ -1,62 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.advanced.vector; - -import dev.caskeleton.adapter.outbound.mongo.api.error.MongoOperationRejectedException; -import java.time.Duration; -import java.util.Objects; -import java.util.Set; - -/** - * A bounded approximate-nearest-neighbour query (advanced plan Task 9). - * - *

{@code numCandidates} is the accuracy-versus-cost dial: the search examines that many - * candidates and returns the best {@code limit} of them. It has to exceed the limit — asking for 10 - * results from 10 candidates is not an approximate search, it is an arbitrary one — and it has to - * be bounded, because the cost grows with it. - */ -public record MongoVectorQuery( - MongoEmbedding queryVector, - int limit, - int numCandidates, - Set filterFields, - Duration timeout) { - - /** The largest candidate pool the platform allows. */ - public static final int MAX_CANDIDATES = 10_000; - - /** The largest result set the platform allows. */ - public static final int MAX_LIMIT = 100; - - public MongoVectorQuery { - Objects.requireNonNull(queryVector, "queryVector"); - Objects.requireNonNull(filterFields, "filterFields"); - Objects.requireNonNull(timeout, "timeout"); - filterFields = Set.copyOf(filterFields); - if (limit <= 0 || limit > MAX_LIMIT) { - throw MongoOperationRejectedException.of( - "vector.query", "a vector query needs a limit between 1 and " + MAX_LIMIT); - } - if (numCandidates > MAX_CANDIDATES) { - throw MongoOperationRejectedException.of( - "vector.query", "numCandidates is above the ceiling of " + MAX_CANDIDATES); - } - if (numCandidates <= limit) { - throw MongoOperationRejectedException.of( - "vector.query", - "numCandidates (" - + numCandidates - + ") must exceed the limit (" - + limit - + "); otherwise the search returns whatever it examined rather than the nearest"); - } - if (timeout.isZero() || timeout.isNegative()) { - throw MongoOperationRejectedException.of( - "vector.query", "a vector query needs a positive timeout"); - } - } - - /** A query with the platform's default candidate ratio. */ - public static MongoVectorQuery nearest(MongoEmbedding queryVector, int limit) { - return new MongoVectorQuery( - queryVector, limit, Math.min(limit * 20, MAX_CANDIDATES), Set.of(), Duration.ofSeconds(2)); - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/vector/MongoVectorSearchBenchmarkGate.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/vector/MongoVectorSearchBenchmarkGate.java deleted file mode 100644 index a8677d6e..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/vector/MongoVectorSearchBenchmarkGate.java +++ /dev/null @@ -1,60 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.advanced.vector; - -import java.util.LinkedHashSet; -import java.util.Objects; -import java.util.Set; - -/** - * What a vector search deployment must prove before promotion (advanced plan Tasks 9, 15). - * - *

Functional success is not evidence for vector search. An approximate index returns results for - * any query; whether they are the right results depends on recall, which cannot be observed from - * the application side. So the gate requires a measured recall against a known-answer set, - * alongside the usual latency and memory bounds. - */ -public record MongoVectorSearchBenchmarkGate( - double minimumRecallAtK, long maximumP99Millis, long maximumIndexMemoryBytes) { - - /** The platform's default bar: 90% recall@10, 200 ms p99. */ - public static MongoVectorSearchBenchmarkGate standard() { - return new MongoVectorSearchBenchmarkGate(0.9, 200, 4L * 1024 * 1024 * 1024); - } - - public MongoVectorSearchBenchmarkGate { - if (minimumRecallAtK <= 0 || minimumRecallAtK > 1) { - throw new IllegalArgumentException("recall must be a fraction between 0 and 1"); - } - if (maximumP99Millis <= 0 || maximumIndexMemoryBytes <= 0) { - throw new IllegalArgumentException("benchmark bounds must be positive"); - } - } - - /** The bounds a measured run failed, empty when it passed. */ - public Set failures( - double measuredRecall, long measuredP99Millis, long measuredIndexMemoryBytes) { - Set failures = new LinkedHashSet<>(); - if (measuredRecall < minimumRecallAtK) { - failures.add("recall " + measuredRecall + " below " + minimumRecallAtK); - } - if (measuredP99Millis > maximumP99Millis) { - failures.add("p99 " + measuredP99Millis + "ms above " + maximumP99Millis + "ms"); - } - if (measuredIndexMemoryBytes > maximumIndexMemoryBytes) { - failures.add( - "index memory " + measuredIndexMemoryBytes + " above " + maximumIndexMemoryBytes); - } - return Set.copyOf(failures); - } - - /** True when a measured run clears every bound. */ - public boolean passes( - double measuredRecall, long measuredP99Millis, long measuredIndexMemoryBytes) { - return failures(measuredRecall, measuredP99Millis, measuredIndexMemoryBytes).isEmpty(); - } - - /** The evidence categories a promotion must supply. */ - public static Set requiredEvidence() { - return Objects.requireNonNull( - Set.of("index-readiness", "recall", "latency", "memory", "actual-topology")); - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/vector/MongoVectorSearchOperations.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/vector/MongoVectorSearchOperations.java deleted file mode 100644 index c4f034b9..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/advanced/vector/MongoVectorSearchOperations.java +++ /dev/null @@ -1,37 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.advanced.vector; - -import dev.caskeleton.adapter.outbound.mongo.advanced.search.MongoSearchIndexState; -import dev.caskeleton.adapter.outbound.mongo.api.MongoOperationContext; -import java.util.List; - -/** - * Vector similarity search against a {@code READY} index (advanced plan Task 9). - * - *

Results carry a named score contract rather than the provider's raw number. A raw score is - * only interpretable against the index's similarity metric, and a caller that thresholds on it is - * coupled to a metric that can change when the index is rebuilt. - * - *

Scaffold. This repository ships no implementation of {@code - * MongoVectorSearchOperations}. The contract is here so a fork wiring Atlas Vector Search has a - * shape to implement and a place for the platform's rules to attach; it needs an Atlas deployment, - * a vector index and an embedding model, none of which this template provides. Read a method - * signature as a specification, not as an available capability — an interface with no - * implementation cannot be injected, and treating it as shipped behaviour is how "the platform - * supports search" becomes true in a document and false in a deployment. - */ -public interface MongoVectorSearchOperations { - - /** Runs a vector query, refusing if the index is not ready. */ - List> search( - MongoOperationContext context, MongoVectorQuery query, Class documentType); - - /** The current state of a vector index. */ - MongoSearchIndexState indexState(String indexName); - - /** - * One result and its interpreted score. - * - * @param the document type - */ - record MongoVectorHit(T document, double normalizedScore, String scoreContract) {} -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/api/error/MongoBulkPartialFailureException.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/api/error/MongoBulkPartialFailureException.java deleted file mode 100644 index effc3aa8..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/api/error/MongoBulkPartialFailureException.java +++ /dev/null @@ -1,45 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.api.error; - -import java.io.Serial; - -/** - * A bulk write partially succeeded (design §19.2). - * - *

A first-class type rather than a generic write failure, because the recovery is the opposite - * of the usual one: the successful items must not be re-run. The counts here are what a - * caller needs to decide that; the per-item detail stays in the bulk result, which the caller - * already holds. - */ -public final class MongoBulkPartialFailureException extends MongoPersistenceException { - - @Serial private static final long serialVersionUID = 1L; - - private final int requested; - - private final int succeeded; - - private final int failed; - - public MongoBulkPartialFailureException( - MongoFailureContext failureContext, int requested, int succeeded, int failed) { - super("the bulk write partially succeeded; do not re-run the successful items", failureContext); - this.requested = requested; - this.succeeded = succeeded; - this.failed = failed; - } - - /** How many operations the caller submitted. */ - public int requested() { - return requested; - } - - /** How many the server confirmed. These must not be replayed. */ - public int succeeded() { - return succeeded; - } - - /** How many failed and are eligible for a targeted retry. */ - public int failed() { - return failed; - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/api/error/MongoTimeoutException.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/api/error/MongoTimeoutException.java index 15b9eb23..c5663e36 100644 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/api/error/MongoTimeoutException.java +++ b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/api/error/MongoTimeoutException.java @@ -20,7 +20,7 @@ public final class MongoTimeoutException extends MongoPersistenceException { /** * Creates the exception from a client-side timeout. * - * @param cause the underlying timeout, kept so a reactive stack trace still names its source + * @param cause the underlying timeout, kept so the stack trace still names its source */ public MongoTimeoutException(MongoFailureContext failureContext, Throwable cause) { super("the MongoDB operation exceeded its deadline", failureContext); diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/api/mapping/MongoIdRepresentation.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/api/mapping/MongoIdRepresentation.java deleted file mode 100644 index 0e1a0bfa..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/api/mapping/MongoIdRepresentation.java +++ /dev/null @@ -1,21 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.api.mapping; - -/** - * How a collection stores its {@code _id} (design §10). - * - *

Declared per collection rather than inferred, because the two representations are not - * interchangeable: {@code "507f1f77bcf86cd799439011"} and {@code - * ObjectId("507f1f77bcf86cd799439011")} are different BSON values and never match each other in a - * query. - */ -public enum MongoIdRepresentation { - - /** The identifier is stored verbatim as a BSON string. Never silently coerced. */ - STRING, - - /** The identifier is a MongoDB-generated {@code ObjectId}. Suitable for Mongo-internal keys. */ - OBJECT_ID, - - /** The identifier is a UUID stored as BSON binary subtype 4. */ - BINARY_UUID -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/api/package-info.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/api/package-info.java index 1a6b495f..d50e0c0d 100644 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/api/package-info.java +++ b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/api/package-info.java @@ -5,7 +5,7 @@ *

Nothing in this package or its subpackages may reference Spring, the MongoDB Java Driver, BSON * or Reactor. That rule is what lets the semantics — operation identity, consistency profiles, * execution outcomes, the error hierarchy, the BSON representation manifest, schema versions — be - * shared by the imperative path, the reactive path and the tests without any of them dragging a - * transport dependency into the others. {@code MongoModuleBoundaryTest} enforces it. + * shared by the execution path and the tests without either dragging a transport dependency into + * the other. {@code MongoModuleBoundaryTest} enforces it. */ package dev.caskeleton.adapter.outbound.mongo.api; diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/autoconfigure/MongoDriverObservabilityAutoConfiguration.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/autoconfigure/MongoDriverObservabilityAutoConfiguration.java index 37e77469..ba63f2d4 100644 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/autoconfigure/MongoDriverObservabilityAutoConfiguration.java +++ b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/autoconfigure/MongoDriverObservabilityAutoConfiguration.java @@ -28,7 +28,8 @@ import org.springframework.context.annotation.Bean; @ConditionalOnProperty( prefix = "ca-skeleton.persistence-mongo", name = "enabled", - havingValue = "true") + havingValue = "true", + matchIfMissing = true) public class MongoDriverObservabilityAutoConfiguration { /** The customizer Boot applies when it builds the client. */ diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/autoconfigure/MongoPlatformAutoConfiguration.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/autoconfigure/MongoPlatformAutoConfiguration.java index 882c156c..bfba006c 100644 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/autoconfigure/MongoPlatformAutoConfiguration.java +++ b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/autoconfigure/MongoPlatformAutoConfiguration.java @@ -33,17 +33,18 @@ import org.springframework.data.mongodb.core.MongoTemplate; * MongoDB gets no beans and no driver connection — the module being on the classpath is not * consent. * - *

Advanced capabilities are absent by construction: sharding, time series, encryption, search - * and tenancy are separate packages that no bean here references, so they cannot arrive - * transitively. The admin gateway is absent for the same reason, and deliberately: it is - * constructed by a migration or deployment job with its own credential. + *

Advanced capabilities are absent by construction: sharding, encryption and tenancy are library + * packages that no bean here references, so they cannot arrive transitively. The admin gateway is + * absent for the same reason, and deliberately: it is constructed by a migration or deployment job + * with its own credential. */ @org.springframework.context.annotation.Configuration(proxyBeanMethods = false) @ConditionalOnClass(MongoTemplate.class) @ConditionalOnProperty( prefix = "ca-skeleton.persistence-mongo", name = "enabled", - havingValue = "true") + havingValue = "true", + matchIfMissing = true) @EnableConfigurationProperties(MongoPlatformSettings.class) @Import(MongoMappingConfiguration.class) public class MongoPlatformAutoConfiguration { @@ -170,138 +171,6 @@ public class MongoPlatformAutoConfiguration { executor, policies); } - /** - * The reactive execution path, when a deployment has a reactive template. - * - *

The reactive half shipped and was wired by nothing. {@code DefaultReactiveMongoExecutor}, - * the reactive consistency binder and the reactive session factory were beans in no - * configuration, so a deployment that switched the platform on got the blocking path and a set of - * reactive classes that no configuration could construct — including the {@code .timeout(...)} - * translation and the result-budget cursor guard the platform was credited with. - * - *

Nested and conditioned on {@code ReactiveMongoTemplate} being present *and* declared as a - * bean. The class is on this leaf's compile classpath either way, so a class condition alone - * would try to build the reactive path in a servlet-only deployment that has no reactive - * template, and fail its startup for a capability it never asked for. - */ - @org.springframework.context.annotation.Configuration(proxyBeanMethods = false) - @ConditionalOnClass(org.springframework.data.mongodb.core.ReactiveMongoTemplate.class) - @ConditionalOnBean(org.springframework.data.mongodb.core.ReactiveMongoTemplate.class) - public static class ReactiveExecution { - - /** - * Binds read and write settings per profile on the reactive template. - * - * @param template the reactive template - * @param registry the consistency registry - * @return the reactive binder - */ - /** - * The driver-facing half of a change stream subscription. - * - *

No production code opened a change stream at all. The checkpoint store, the resume - * position, the recovery policy, the invalidate conversion, the ordered pipeline and the - * projector all shipped with passing unit tests and a deployment had no way to run any of them, - * so the at-least-once consumer contract the design describes was unreachable. - */ - @Bean - @ConditionalOnMissingBean - public dev.caskeleton.adapter.outbound.mongo.changestream.consumer.MongoChangeStreamSource - mongoChangeStreamSource( - org.springframework.data.mongodb.core.ReactiveMongoTemplate template, - MongoCollectionProfileRegistry collections) { - return new dev.caskeleton.adapter.outbound.mongo.changestream.consumer - .SpringReactiveChangeStreamSource(template, collections); - } - - /** - * One subscription, wired end to end. - * - *

Conditional on the pieces only a deployment can supply — what to project, where to record - * that it was projected, how to protect the stored token, and which collection to watch. The - * platform cannot invent a projector, so a consumer that appears without one would be a - * subscription reading a stream into nothing. - */ - @Bean - @ConditionalOnMissingBean - @org.springframework.boot.autoconfigure.condition.ConditionalOnBean({ - dev.caskeleton.adapter.outbound.mongo.changestream.MongoChangeStreamSubscription.class, - dev.caskeleton.adapter.outbound.mongo.changestream.MongoResumeCheckpointStore.class, - dev.caskeleton.adapter.outbound.mongo.changestream.MongoResumeTokenCodec.class, - dev.caskeleton.adapter.outbound.mongo.changestream.projector.MongoChangeProjector.class, - dev.caskeleton.adapter.outbound.mongo.changestream.projector.MongoChangeDeduplicationStore - .class - }) - public dev.caskeleton.adapter.outbound.mongo.changestream.consumer - .ReactiveMongoChangeStreamConsumer - reactiveMongoChangeStreamConsumer( - dev.caskeleton.adapter.outbound.mongo.changestream.MongoChangeStreamSubscription - subscription, - dev.caskeleton.adapter.outbound.mongo.changestream.consumer.MongoChangeStreamSource - source, - dev.caskeleton.adapter.outbound.mongo.changestream.MongoResumeCheckpointStore - checkpoints, - dev.caskeleton.adapter.outbound.mongo.changestream.MongoResumeTokenCodec tokens, - dev.caskeleton.adapter.outbound.mongo.changestream.projector.MongoChangeProjector - projector, - dev.caskeleton.adapter.outbound.mongo.changestream.projector - .MongoChangeDeduplicationStore - deduplication) { - return new dev.caskeleton.adapter.outbound.mongo.changestream.consumer - .ReactiveMongoChangeStreamConsumer( - subscription, - source, - checkpoints, - tokens, - new dev.caskeleton.adapter.outbound.mongo.changestream.MongoChangeStreamPipeline( - new dev.caskeleton.adapter.outbound.mongo.changestream.projector - .MongoChangeStreamRunner(projector, deduplication, checkpoints)), - new dev.caskeleton.adapter.outbound.mongo.changestream.recovery - .MongoChangeStreamRecoveryPolicy(), - new dev.caskeleton.adapter.outbound.mongo.changestream.recovery - .MongoInvalidateRecovery()); - } - - @Bean - @ConditionalOnMissingBean - public dev.caskeleton.adapter.outbound.mongo.reactive.ReactiveMongoConsistencyBinder - reactiveMongoConsistencyBinder( - org.springframework.data.mongodb.core.ReactiveMongoTemplate template, - dev.caskeleton.adapter.outbound.mongo.api.consistency.MongoConsistencyRegistry registry, - org.springframework.context.ApplicationContext applicationContext) { - // The same support contract the imperative binder gets. Without it a document written through - // the reactive executor skips auditing and BeforeConvertCallback while the same document - // written through an ordinary reactive repository does not — two documents, one mapping. - return new dev.caskeleton.adapter.outbound.mongo.reactive.ReactiveMongoConsistencyBinder( - template, - registry, - dev.caskeleton.adapter.outbound.mongo.imperative.MongoTemplateSupportContract.inContext( - applicationContext)); - } - - /** - * The single reactive execution path. - * - * @param consistency the reactive binder - * @param collections the collection profile registry - * @param translator the failure translator - * @param observer the operation observer - * @return the reactive executor - */ - @Bean - @ConditionalOnMissingBean - public dev.caskeleton.adapter.outbound.mongo.reactive.DefaultReactiveMongoExecutor - mongoReactiveExecutor( - dev.caskeleton.adapter.outbound.mongo.reactive.ReactiveMongoConsistencyBinder - consistency, - MongoCollectionProfileRegistry collections, - MongoFailureTranslator translator, - MongoOperationObserver observer) { - return new dev.caskeleton.adapter.outbound.mongo.reactive.DefaultReactiveMongoExecutor( - consistency, collections, translator, observer); - } - } - /** Lets a caller tighten a registered budget, never loosen it. */ @Bean @ConditionalOnMissingBean @@ -352,16 +221,7 @@ public class MongoPlatformAutoConfiguration { + " the startup validator cannot answer with only part of its inputs"); } new MongoStartupValidator( - properties, - probe, - security, - admin, - // From settings, not literals. These were `true, true`, which told the validator that - // transactions and change streams were both wanted whatever the deployment had - // configured — and then validated the topology against that invented answer. - properties.transactions(), - properties.changeStreams(), - versions) + properties, probe, security, admin, properties.transactions(), versions) .validate(); }; } diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/autoconfigure/MongoPlatformSettings.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/autoconfigure/MongoPlatformSettings.java index e0798665..1d2ac008 100644 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/autoconfigure/MongoPlatformSettings.java +++ b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/autoconfigure/MongoPlatformSettings.java @@ -19,15 +19,12 @@ import org.springframework.boot.context.properties.ConfigurationProperties; * *

{@code transactions} is a subordinate switch, off until a deployment asks for it; when on, the * startup validator verifies the data-plane credential's real replica-set capability rather than - * assuming it. Both it and {@code changeStreams} used to be literal {@code true}s passed into - * {@link MongoStartupValidator}, which told the validator that two capabilities were wanted - * whatever the deployment had configured. + * assuming it. */ @ConfigurationProperties("ca-skeleton.persistence-mongo.platform") public record MongoPlatformSettings( Map profiles, boolean transactions, - boolean changeStreams, Integer requiredSecondaries) { /** @@ -45,11 +42,6 @@ public record MongoPlatformSettings( // configured no platform profile yet must still start, so binding treats "no profiles" as an // empty map instead of a binding failure. profiles = profiles == null ? Map.of() : Map.copyOf(profiles); - if (changeStreams) { - throw MongoOperationRejectedException.of( - "config.change-streams", - "change streams are not an activatable platform capability in this composition"); - } // Absent means the platform default, and a negative count is refused rather than clamped: a // requirement of -1 is not a lenient requirement, it is a typo, and reading it as "no // secondaries needed" is how a health view comes to report a cluster it never checked. @@ -65,7 +57,7 @@ public record MongoPlatformSettings( /** An empty configuration, for a deployment that has not opted the platform in. */ public static MongoPlatformSettings empty() { - return new MongoPlatformSettings(Map.of(), false, false, null); + return new MongoPlatformSettings(Map.of(), false, null); } /** diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/autoconfigure/MongoProfileProperties.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/autoconfigure/MongoProfileProperties.java index 6d93540d..6105790f 100644 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/autoconfigure/MongoProfileProperties.java +++ b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/autoconfigure/MongoProfileProperties.java @@ -1,8 +1,6 @@ package dev.caskeleton.adapter.outbound.mongo.autoconfigure; -import dev.caskeleton.adapter.outbound.mongo.api.consistency.MongoConsistencyProfile; import dev.caskeleton.adapter.outbound.mongo.api.error.MongoOperationRejectedException; -import dev.caskeleton.adapter.outbound.mongo.api.mapping.MongoDecimalRepresentation; import dev.caskeleton.adapter.outbound.mongo.api.mapping.MongoUuidRepresentation; import dev.caskeleton.adapter.outbound.mongo.api.profile.MongoTopology; import dev.caskeleton.adapter.outbound.mongo.security.MongoCredentialReference; @@ -17,7 +15,7 @@ import java.util.Objects; * image, in every log line that dumps the environment, and in the crash report — and rotating it * becomes a redeploy. * - *

Mapping representation is validated here too, because it cannot be changed later: the + *

The UUID representation is validated here too, because it cannot be changed later: the * representation is baked into every document already written. */ public record MongoProfileProperties( @@ -25,7 +23,6 @@ public record MongoProfileProperties( MongoTopology topology, boolean production, boolean stableApiStrict, - MongoConsistencyProfile consistencyDefault, Duration serverSelectionTimeout, Duration connectTimeout, Duration socketReadTimeout, @@ -34,22 +31,18 @@ public record MongoProfileProperties( int poolMaxSize, Duration poolMaxWaitTime, MongoUuidRepresentation uuidRepresentation, - MongoDecimalRepresentation decimalRepresentation, - boolean runtimeAutoCreateIndexes, boolean tlsRequired, boolean authenticationRequired) { public MongoProfileProperties { Objects.requireNonNull(uriSecret, "uriSecret"); Objects.requireNonNull(topology, "topology"); - Objects.requireNonNull(consistencyDefault, "consistencyDefault"); Objects.requireNonNull(serverSelectionTimeout, "serverSelectionTimeout"); Objects.requireNonNull(connectTimeout, "connectTimeout"); Objects.requireNonNull(socketReadTimeout, "socketReadTimeout"); Objects.requireNonNull(operationTimeout, "operationTimeout"); Objects.requireNonNull(poolMaxWaitTime, "poolMaxWaitTime"); Objects.requireNonNull(uuidRepresentation, "uuidRepresentation"); - Objects.requireNonNull(decimalRepresentation, "decimalRepresentation"); } /** The platform's production defaults, with the URI as supplied. */ @@ -59,7 +52,6 @@ public record MongoProfileProperties( MongoTopology.REPLICA_SET, true, true, - MongoConsistencyProfile.PRIMARY_MAJORITY, Duration.ofSeconds(3), Duration.ofSeconds(2), Duration.ofSeconds(5), @@ -68,20 +60,17 @@ public record MongoProfileProperties( 40, Duration.ofMillis(500), MongoUuidRepresentation.STANDARD, - MongoDecimalRepresentation.DECIMAL128, - false, true, true); } - /** The local development defaults: a single-node replica set, no TLS, indexes applied freely. */ + /** The local development defaults: a single-node replica set, no TLS, no authentication. */ public static MongoProfileProperties local(String uriSecret) { return new MongoProfileProperties( uriSecret, MongoTopology.REPLICA_SET, false, true, - MongoConsistencyProfile.PRIMARY_MAJORITY, Duration.ofSeconds(3), Duration.ofSeconds(2), Duration.ofSeconds(5), @@ -90,8 +79,6 @@ public record MongoProfileProperties( 10, Duration.ofMillis(500), MongoUuidRepresentation.STANDARD, - MongoDecimalRepresentation.DECIMAL128, - true, false, false); } @@ -120,18 +107,10 @@ public record MongoProfileProperties( throw MongoOperationRejectedException.of( "config.stable-api", "a production D1/D2 profile must pin Stable API V1 in strict mode"); } - if (production && runtimeAutoCreateIndexes) { - throw MongoOperationRejectedException.of( - "config.index", - "runtime auto index creation is not permitted in production; an index build is an " - + "I/O-heavy operation that would start on every replica at whatever moment the " - + "rollout reached it"); - } - if (!uuidRepresentation.writable() || !decimalRepresentation.writable()) { + if (!uuidRepresentation.writable()) { throw MongoOperationRejectedException.of( "config.mapping", - "the profile selects a read-only representation for UUID or decimal; new writes need " - + "STANDARD and DECIMAL128"); + "the profile selects a read-only UUID representation; new writes need STANDARD"); } if (poolMinSize < 0 || poolMaxSize <= 0 || poolMinSize > poolMaxSize) { throw MongoOperationRejectedException.of( diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/autoconfigure/MongoStartupValidator.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/autoconfigure/MongoStartupValidator.java index 4e30b7da..1e17868e 100644 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/autoconfigure/MongoStartupValidator.java +++ b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/autoconfigure/MongoStartupValidator.java @@ -31,8 +31,6 @@ public final class MongoStartupValidator { private final boolean transactionsEnabled; - private final boolean changeStreamsEnabled; - private final MongoSchemaVersionRange schemaVersionRange; public MongoStartupValidator( @@ -41,14 +39,12 @@ public final class MongoStartupValidator { MongoSecurityProfile runtimeSecurity, MongoCredentialReference adminCredential, boolean transactionsEnabled, - boolean changeStreamsEnabled, MongoSchemaVersionRange schemaVersionRange) { this.properties = Objects.requireNonNull(properties, "properties"); this.probe = Objects.requireNonNull(probe, "probe"); this.runtimeSecurity = Objects.requireNonNull(runtimeSecurity, "runtimeSecurity"); this.adminCredential = adminCredential; this.transactionsEnabled = transactionsEnabled; - this.changeStreamsEnabled = changeStreamsEnabled; this.schemaVersionRange = Objects.requireNonNull(schemaVersionRange, "schemaVersionRange"); } @@ -101,13 +97,6 @@ public final class MongoStartupValidator { + capabilities.require(MongoCapability.TRANSACTION).constraints() + "; a REPLICA_SET, SHARDED or ATLAS topology is required"); } - if (changeStreamsEnabled && !capabilities.isStable(MongoCapability.CHANGE_STREAM)) { - throw MongoOperationRejectedException.of( - "startup.capability", - "change streams are enabled but unavailable here: " - + capabilities.require(MongoCapability.CHANGE_STREAM).constraints() - + "; a REPLICA_SET, SHARDED or ATLAS topology is required"); - } } private void requireDistinctAdminCredential() { diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/MongoChangeEventIdentity.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/MongoChangeEventIdentity.java deleted file mode 100644 index 55410c37..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/MongoChangeEventIdentity.java +++ /dev/null @@ -1,97 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.changestream; - -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.HexFormat; -import java.util.Objects; - -/** - * A stable identity for one change event (design §20.2, §35). - * - *

Change streams are at-least-once: a resume after a failover redelivers events the projector - * may already have applied. Deduplication therefore needs an identity that is the same across - * redeliveries — which the resume token is not, since it encodes the reading position rather than - * the event. - * - *

The identity is derived from cluster time, namespace, document key and operation type, and - * then hashed. Hashing is what lets the identity be stored and compared without the document key — - * a business identifier — sitting in a deduplication table in plaintext. - */ -public record MongoChangeEventIdentity(String value) { - - /** - * ASCII unit separator. - * - *

A control character cannot appear in a namespace, a cluster time or an operation type, so no - * combination of field values can be rearranged to forge another event's identity. - */ - private static final String SEPARATOR = String.valueOf((char) 0x1F); - - public MongoChangeEventIdentity { - Objects.requireNonNull(value, "value"); - if (value.isBlank()) { - throw new IllegalArgumentException("a change event identity must not be blank"); - } - } - - /** - * Derives the identity of one event. - * - * @param clusterTime the event's cluster time, as {@code seconds.increment} - * @param namespace the database and collection the event came from - * @param documentKey the event's document key, in canonical extended JSON - * @param operationType the change operation, such as {@code insert} or {@code update} - */ - public static MongoChangeEventIdentity of( - String clusterTime, String namespace, String documentKey, String operationType) { - return of(clusterTime, namespace, documentKey, operationType, ""); - } - - /** - * Derives the identity of one event, including its position within a transaction. - * - *

Cluster time, namespace, document key and operation type are not unique. A transaction that - * updates the same document twice produces two events sharing all four, and the deduplication - * store then treats the second as a redelivery of the first and drops it — a lost change, not a - * duplicate avoided. - * - *

MongoDB's own event carries what distinguishes them: {@code txnNumber} and {@code lsid} - * within a transaction, and the operation's index in the applied-ops batch. Passing that - * discriminator in keeps the identity stable across redeliveries — the same event always yields - * the same discriminator — while separating distinct events that happen to agree on everything - * else. - * - * @param discriminator the event's within-transaction position, or an empty string outside one - */ - public static MongoChangeEventIdentity of( - String clusterTime, - String namespace, - String documentKey, - String operationType, - String discriminator) { - Objects.requireNonNull(clusterTime, "clusterTime"); - Objects.requireNonNull(namespace, "namespace"); - Objects.requireNonNull(documentKey, "documentKey"); - Objects.requireNonNull(operationType, "operationType"); - Objects.requireNonNull(discriminator, "discriminator"); - return new MongoChangeEventIdentity( - sha256( - String.join( - SEPARATOR, clusterTime, namespace, documentKey, operationType, discriminator))); - } - - private static String sha256(String material) { - try { - MessageDigest digest = MessageDigest.getInstance("SHA-256"); - return HexFormat.of().formatHex(digest.digest(material.getBytes(StandardCharsets.UTF_8))); - } catch (NoSuchAlgorithmException unavailable) { - throw new IllegalStateException("SHA-256 is required to derive change event identities"); - } - } - - @Override - public String toString() { - return value; - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/MongoChangeStreamPipeline.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/MongoChangeStreamPipeline.java deleted file mode 100644 index 2a41c567..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/MongoChangeStreamPipeline.java +++ /dev/null @@ -1,85 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.changestream; - -import dev.caskeleton.adapter.outbound.mongo.changestream.projector.MongoChangeProjectionResult; -import dev.caskeleton.adapter.outbound.mongo.changestream.projector.MongoChangeStreamRunner; -import java.util.Objects; -import java.util.concurrent.atomic.AtomicReference; -import org.bson.BsonDocument; -import reactor.core.publisher.Flux; - -/** - * Drives one subscription's events through the runner, in order, one at a time. - * - *

The runner exposed {@code runOne} per event and nothing owned the sequence. A caller that - * subscribed with {@code flatMap} — the ordinary way to run reactive work — had events B and C in - * flight while A was still projecting, and each of them advanced the checkpoint on completion. If - * the process died after B's checkpoint and before A finished, the resume position had already - * passed A: the change stream never replays what the checkpoint has passed, so A was lost - * permanently and nothing recorded that it had been. - * - *

{@code concatMap} is what makes the ordering a property of the pipeline rather than of every - * caller remembering. It subscribes to the next event only after the previous one has completed, so - * a checkpoint write always means "everything up to here is done". - * - *

The position is also guarded: a checkpoint that would move backwards is refused rather than - * written. Nothing in the reactive contract prevents a late completion from arriving after an - * earlier one, and a checkpoint that regresses replays work that has already been applied. - */ -public final class MongoChangeStreamPipeline { - - private final MongoChangeStreamRunner runner; - - private final AtomicReference highWaterMark = new AtomicReference<>(); - - public MongoChangeStreamPipeline(MongoChangeStreamRunner runner) { - this.runner = Objects.requireNonNull(runner, "runner"); - } - - /** - * Processes a stream of events strictly in order. - * - * @param events the raw events, in the order the change stream produced them - */ - public Flux process(Flux events) { - Objects.requireNonNull(events, "events"); - return events.concatMap(this::processOne); - } - - private Flux processOne(MongoChangeEvent event) { - if (!advancesPosition(event.clusterTime())) { - // Behind the high-water mark: a redelivery of something already processed, or an event that - // arrived out of order. Running it would move the resume checkpoint backwards, which replays - // work that has already been applied. - return Flux.empty(); - } - return runner.runOne(event.identity(), event.change(), event.checkpoint()).flux(); - } - - private boolean advancesPosition(MongoClusterTime candidate) { - MongoClusterTime previous = - highWaterMark.getAndAccumulate( - candidate, - (current, next) -> current == null || next.isAfter(current) ? next : current); - return previous == null || candidate.isAfter(previous); - } - - /** The furthest cluster time this pipeline has accepted. */ - public MongoClusterTime highWaterMark() { - return highWaterMark.get(); - } - - /** One event as the pipeline sees it. */ - public record MongoChangeEvent( - MongoChangeEventIdentity identity, - BsonDocument change, - MongoResumeCheckpoint checkpoint, - MongoClusterTime clusterTime) { - - public MongoChangeEvent { - Objects.requireNonNull(identity, "identity"); - Objects.requireNonNull(change, "change"); - Objects.requireNonNull(checkpoint, "checkpoint"); - Objects.requireNonNull(clusterTime, "clusterTime"); - } - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/MongoChangeStreamState.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/MongoChangeStreamState.java deleted file mode 100644 index 462398af..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/MongoChangeStreamState.java +++ /dev/null @@ -1,35 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.changestream; - -/** - * The lifecycle state of one change stream subscription (design §20.1). - * - *

{@code HISTORY_LOST} is separate from {@code FAILED} because it is the one state the platform - * refuses to recover from on its own. Resuming from "now" after the oplog has rolled past the - * stored token silently discards every change in between — the projection then looks healthy and is - * quietly wrong, which is worse than a stopped consumer somebody has to look at. - */ -public enum MongoChangeStreamState { - - /** Opening the stream and resolving the resume position. */ - STARTING, - - /** Consuming events. */ - RUNNING, - - /** Recovering from a resumable failure such as a primary failover. */ - RESUMING, - - /** The oplog no longer contains the stored resume position. Consumption stops. */ - HISTORY_LOST, - - /** A non-resumable failure. Consumption stops. */ - FAILED, - - /** Stopped deliberately. */ - STOPPED; - - /** True when the platform may resume without an operator decision. */ - public boolean autoResumable() { - return this == RUNNING || this == RESUMING || this == STARTING; - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/MongoChangeStreamSubscription.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/MongoChangeStreamSubscription.java deleted file mode 100644 index 52fc1fde..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/MongoChangeStreamSubscription.java +++ /dev/null @@ -1,55 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.changestream; - -import dev.caskeleton.adapter.outbound.mongo.api.CollectionProfileName; -import java.time.Duration; -import java.util.Objects; - -/** - * How one change stream subscription is configured (design §20.1). - * - *

Batch size and maximum await time are both bounded. A change stream is a long-lived cursor: an - * unbounded batch buys throughput with heap, and an unbounded await time makes a stalled stream - * indistinguishable from an idle one, so nothing ever alerts. - * - *

These two cursor knobs are part of the platform subscription contract for driver-level change - * stream sources. Spring Data MongoDB 5.0.7 does not expose either knob through {@code - * ChangeStreamOptions}; {@code SpringReactiveChangeStreamSource} therefore documents that - * limitation explicitly and is not an activatable release composition. - */ -public record MongoChangeStreamSubscription( - String subscriptionProfile, - CollectionProfileName collectionProfile, - int batchSize, - Duration maxAwaitTime, - boolean fullDocumentBeforeChange) { - - /** The largest batch a change stream subscription may request. */ - public static final int MAX_BATCH_SIZE = 1000; - - public MongoChangeStreamSubscription { - Objects.requireNonNull(subscriptionProfile, "subscriptionProfile"); - Objects.requireNonNull(collectionProfile, "collectionProfile"); - Objects.requireNonNull(maxAwaitTime, "maxAwaitTime"); - if (subscriptionProfile.isBlank()) { - throw new IllegalArgumentException("a subscription needs a profile name"); - } - if (batchSize <= 0 || batchSize > MAX_BATCH_SIZE) { - throw new IllegalArgumentException( - "a change stream batch size must be between 1 and " + MAX_BATCH_SIZE); - } - if (maxAwaitTime.isZero() || maxAwaitTime.isNegative()) { - throw new IllegalArgumentException("a change stream max await time must be positive"); - } - } - - /** A subscription with the platform's default bounds. */ - public static MongoChangeStreamSubscription of( - String subscriptionProfile, String collectionProfile) { - return new MongoChangeStreamSubscription( - subscriptionProfile, - new CollectionProfileName(collectionProfile), - 100, - Duration.ofSeconds(1), - false); - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/MongoClusterTime.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/MongoClusterTime.java deleted file mode 100644 index b9cb4a34..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/MongoClusterTime.java +++ /dev/null @@ -1,53 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.changestream; - -import java.util.Objects; - -/** - * A MongoDB timestamp: seconds since the epoch, and an increment within that second. - * - *

Compared numerically on both components. Comparing the printed form as text puts {@code - * 1700000000.10} before {@code 1700000000.9}, which is exactly the case a busy second produces — so - * a text comparison would report an event as older than one it actually follows and the pipeline - * would drop it. - */ -public record MongoClusterTime(long seconds, int increment) - implements Comparable { - - public MongoClusterTime { - if (seconds < 0 || increment < 0) { - throw new IllegalArgumentException("a cluster time has no negative components"); - } - } - - /** Parses the {@code seconds.increment} form the change stream reports. */ - public static MongoClusterTime parse(String reported) { - Objects.requireNonNull(reported, "reported"); - int dot = reported.indexOf('.'); - if (dot <= 0 || dot == reported.length() - 1) { - throw new IllegalArgumentException("'" + reported + "' is not a cluster time"); - } - try { - return new MongoClusterTime( - Long.parseLong(reported.substring(0, dot)), - Integer.parseInt(reported.substring(dot + 1))); - } catch (NumberFormatException notNumeric) { - throw new IllegalArgumentException("'" + reported + "' is not a cluster time"); - } - } - - /** True when this cluster time is strictly later than the other. */ - public boolean isAfter(MongoClusterTime other) { - return compareTo(Objects.requireNonNull(other, "other")) > 0; - } - - @Override - public int compareTo(MongoClusterTime other) { - int bySeconds = Long.compare(seconds, other.seconds); - return bySeconds != 0 ? bySeconds : Integer.compare(increment, other.increment); - } - - @Override - public String toString() { - return seconds + "." + increment; - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/MongoResumeCheckpoint.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/MongoResumeCheckpoint.java deleted file mode 100644 index 240d4117..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/MongoResumeCheckpoint.java +++ /dev/null @@ -1,100 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.changestream; - -import dev.caskeleton.adapter.outbound.mongo.api.schema.DocumentSchemaVersion; -import java.util.Base64; -import java.util.Objects; - -/** - * A durable, opaque change stream position (design §20.2, §20.3). - * - *

The token is held as encoded ciphertext and never rendered. A resume token encodes the cluster - * time and the document key of the last event, so printing one into a log leaks both the shape and - * the timing of production writes — which is why the design lists it among the forbidden telemetry - * values. {@link #toString()} reports only the token's length. - * - *

The cluster identity and schema version are stored alongside it. Replaying a token issued by a - * different cluster does not fail cleanly at the server, so the check has to happen here. - */ -public record MongoResumeCheckpoint( - String subscriptionProfile, - String encodedToken, - String clusterIdentity, - DocumentSchemaVersion schemaVersion, - MongoResumePosition position) { - - public MongoResumeCheckpoint { - Objects.requireNonNull(subscriptionProfile, "subscriptionProfile"); - Objects.requireNonNull(encodedToken, "encodedToken"); - Objects.requireNonNull(clusterIdentity, "clusterIdentity"); - Objects.requireNonNull(schemaVersion, "schemaVersion"); - Objects.requireNonNull(position, "position"); - if (encodedToken.isEmpty()) { - throw new IllegalArgumentException("a resume checkpoint needs a token"); - } - } - - /** A checkpoint for an ordinary resume, with the cluster identity still to be filled in. */ - public static MongoResumeCheckpoint encrypted(String subscriptionProfile, byte[] ciphertext) { - return new MongoResumeCheckpoint( - subscriptionProfile, - encode(ciphertext), - "", - new DocumentSchemaVersion(1), - MongoResumePosition.RESUME_AFTER); - } - - /** A checkpoint recorded after an invalidate event, which must be resumed with startAfter. */ - public static MongoResumeCheckpoint afterInvalidate( - String subscriptionProfile, byte[] ciphertext) { - return new MongoResumeCheckpoint( - subscriptionProfile, - encode(ciphertext), - "", - new DocumentSchemaVersion(1), - MongoResumePosition.START_AFTER); - } - - private static String encode(byte[] ciphertext) { - Objects.requireNonNull(ciphertext, "ciphertext"); - if (ciphertext.length == 0) { - throw new IllegalArgumentException("a resume checkpoint needs a token"); - } - return Base64.getEncoder().withoutPadding().encodeToString(ciphertext); - } - - /** The stored ciphertext. Decrypting it is the checkpoint store's responsibility. */ - public byte[] ciphertext() { - return Base64.getDecoder().decode(encodedToken); - } - - /** Returns a copy bound to a cluster identity. */ - public MongoResumeCheckpoint withClusterIdentity(String identity) { - return new MongoResumeCheckpoint( - subscriptionProfile, - encodedToken, - Objects.requireNonNull(identity, "identity"), - schemaVersion, - position); - } - - /** True when this checkpoint was issued by the given cluster. */ - public boolean belongsTo(String identity) { - return clusterIdentity.equals(Objects.requireNonNull(identity, "identity")); - } - - /** Describes the checkpoint without any part of the token. */ - @Override - public String toString() { - return "MongoResumeCheckpoint[subscription=" - + subscriptionProfile - + ", cluster=" - + clusterIdentity - + ", schemaVersion=" - + schemaVersion - + ", position=" - + position - + ", tokenChars=" - + encodedToken.length() - + "]"; - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/MongoResumeCheckpointStore.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/MongoResumeCheckpointStore.java deleted file mode 100644 index ccac8af5..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/MongoResumeCheckpointStore.java +++ /dev/null @@ -1,24 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.changestream; - -import java.util.Optional; -import reactor.core.publisher.Mono; - -/** - * Durable storage for change stream positions (design §20.2). - * - *

The store must survive a process restart, because that is the only thing standing between a - * consumer restart and a full reprojection. It also has to be written after the projection - * succeeds — the runner enforces that ordering, and this interface exists so nothing else can write - * a checkpoint out of band. - */ -public interface MongoResumeCheckpointStore { - - /** The stored position for a subscription, if one exists. */ - Mono> load(String subscriptionProfile); - - /** Stores a position. Called only after the projection for that event has completed. */ - Mono save(MongoResumeCheckpoint checkpoint); - - /** Discards a stored position, used by an operator-driven rebuild. */ - Mono clear(String subscriptionProfile); -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/MongoResumePosition.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/MongoResumePosition.java deleted file mode 100644 index 22ee8f03..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/MongoResumePosition.java +++ /dev/null @@ -1,18 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.changestream; - -/** - * Which resume option a stored checkpoint must be replayed with (design §20.3). - * - *

The two are not interchangeable. {@code resumeAfter} refuses a token taken from an invalidate - * event, so a subscription that stores the position without also storing which option produced it - * cannot be restarted after a collection was dropped or renamed — precisely the case where - * restarting matters. - */ -public enum MongoResumePosition { - - /** Ordinary resume from the last processed event. */ - RESUME_AFTER, - - /** Resume after an invalidate event, which {@code resumeAfter} cannot express. */ - START_AFTER -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/MongoResumeTokenCodec.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/MongoResumeTokenCodec.java deleted file mode 100644 index 52b776c4..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/MongoResumeTokenCodec.java +++ /dev/null @@ -1,38 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.changestream; - -import org.bson.BsonDocument; - -/** - * Turns a driver resume token into a durable checkpoint and back (design §20.2). - * - *

A resume token encodes the cluster time and the document key of the last event, so it is - * production write timing and production identifiers in one opaque-looking string. The checkpoint - * holds it as ciphertext for that reason, and this is the boundary where the conversion happens: - * without it, a consumer wanting to resume would have to decode the stored bytes itself, which is - * how "the checkpoint is encrypted" quietly becomes "the checkpoint is base64". - * - *

There is no default implementation. How a deployment protects the token — which key, which - * rotation — is not something this leaf can decide on its behalf, and a built-in that merely - * encoded would be worse than none: it would satisfy the type and none of the reason for it. - */ -public interface MongoResumeTokenCodec { - - /** - * Stores a token as a checkpoint. - * - * @param subscriptionProfile the subscription the position belongs to - * @param token the driver's resume token - * @param position which resume option the token must be replayed with - * @return the durable checkpoint - */ - MongoResumeCheckpoint encode( - String subscriptionProfile, BsonDocument token, MongoResumePosition position); - - /** - * Recovers the token a checkpoint stands for. - * - * @param checkpoint the stored checkpoint - * @return the driver's resume token - */ - BsonDocument decode(MongoResumeCheckpoint checkpoint); -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/consumer/MongoChangeStreamSource.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/consumer/MongoChangeStreamSource.java deleted file mode 100644 index 76e71016..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/consumer/MongoChangeStreamSource.java +++ /dev/null @@ -1,54 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.changestream.consumer; - -import dev.caskeleton.adapter.outbound.mongo.changestream.MongoChangeStreamSubscription; -import dev.caskeleton.adapter.outbound.mongo.changestream.MongoResumePosition; -import java.util.Optional; -import org.bson.BsonDocument; -import org.springframework.data.mongodb.core.ChangeStreamEvent; -import org.springframework.data.mongodb.core.query.Query; -import reactor.core.publisher.Flux; - -/** - * Opens the driver's change stream at a stated position. - * - *

A seam rather than a call, because everything worth testing about a change stream consumer — - * what it resumes from, what it does with an invalidate, what it does when history is lost — is - * about the sequence around the stream and not about the stream itself. Testing that sequence - * against a live replica set turns a lifecycle assertion into a container. - */ -@FunctionalInterface -public interface MongoChangeStreamSource { - - /** - * Opens the stream. - * - * @param subscription the subscription's configuration - * @param resumeFrom the position to resume from, absent when starting fresh - * @return the events, in the order the server produced them - */ - Flux> open( - MongoChangeStreamSubscription subscription, Optional resumeFrom); - - /** - * A stored position and the option it must be replayed with. - * - *

The two travel together because they are not independent: {@code resumeAfter} refuses a - * token that came from an invalidate event, so a position without its option cannot be replayed - * in exactly the case where replaying matters. - * - * @param token the driver's resume token - * @param position the resume option the token was recorded under - */ - record ResumeFrom(BsonDocument token, MongoResumePosition position) { - - public ResumeFrom { - java.util.Objects.requireNonNull(token, "token"); - java.util.Objects.requireNonNull(position, "position"); - } - } - - /** The query a subscription watches; unfiltered unless a deployment narrows it. */ - static Query everything() { - return new Query(); - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/consumer/ReactiveMongoChangeStreamConsumer.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/consumer/ReactiveMongoChangeStreamConsumer.java deleted file mode 100644 index 5d2c6513..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/consumer/ReactiveMongoChangeStreamConsumer.java +++ /dev/null @@ -1,221 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.changestream.consumer; - -import com.mongodb.client.model.changestream.OperationType; -import dev.caskeleton.adapter.outbound.mongo.changestream.MongoChangeEventIdentity; -import dev.caskeleton.adapter.outbound.mongo.changestream.MongoChangeStreamPipeline; -import dev.caskeleton.adapter.outbound.mongo.changestream.MongoChangeStreamState; -import dev.caskeleton.adapter.outbound.mongo.changestream.MongoChangeStreamSubscription; -import dev.caskeleton.adapter.outbound.mongo.changestream.MongoClusterTime; -import dev.caskeleton.adapter.outbound.mongo.changestream.MongoResumeCheckpoint; -import dev.caskeleton.adapter.outbound.mongo.changestream.MongoResumeCheckpointStore; -import dev.caskeleton.adapter.outbound.mongo.changestream.MongoResumePosition; -import dev.caskeleton.adapter.outbound.mongo.changestream.MongoResumeTokenCodec; -import dev.caskeleton.adapter.outbound.mongo.changestream.projector.MongoChangeProjectionResult; -import dev.caskeleton.adapter.outbound.mongo.changestream.recovery.MongoChangeStreamRecoveryDecision; -import dev.caskeleton.adapter.outbound.mongo.changestream.recovery.MongoChangeStreamRecoveryPolicy; -import dev.caskeleton.adapter.outbound.mongo.changestream.recovery.MongoInvalidateRecovery; -import dev.caskeleton.adapter.outbound.mongo.failure.MongoDriverFailureView; -import java.util.Objects; -import java.util.Optional; -import java.util.concurrent.atomic.AtomicReference; -import org.bson.BsonDocument; -import org.springframework.data.mongodb.core.ChangeStreamEvent; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; - -/** - * One change stream subscription, from stored position to stored position (design §20). - * - *

Every part of this lifecycle existed and nothing joined them. The checkpoint store, the resume - * position, the recovery policy, the invalidate conversion, the ordered pipeline and the projector - * were separate classes with passing unit tests, and no production code opened a change stream at - * all — so the at-least-once consumer contract the design describes was a set of components a - * deployment had no way to run. The pieces were correct and the capability did not exist. - * - *

What this owns is the order: load the checkpoint, choose the resume option it was recorded - * under, open the stream there, hand the events to the pipeline one at a time, and store the new - * position only after a projection has succeeded. An invalidate is converted to a {@code - * startAfter} position at the moment it arrives, because afterwards the distinction cannot be - * recovered. A lost history stops the subscription rather than restarting it from now, which would - * produce a projection that is missing an unknown range of changes and reports itself as healthy. - */ -public final class ReactiveMongoChangeStreamConsumer { - - private final MongoChangeStreamSubscription subscription; - - private final MongoChangeStreamSource source; - - private final MongoResumeCheckpointStore checkpoints; - - private final MongoResumeTokenCodec tokens; - - private final MongoChangeStreamPipeline pipeline; - - private final MongoChangeStreamRecoveryPolicy recovery; - - private final MongoInvalidateRecovery invalidates; - - private final AtomicReference state = - new AtomicReference<>(MongoChangeStreamState.STOPPED); - - private final AtomicReference requiredRunbook = new AtomicReference<>(""); - - public ReactiveMongoChangeStreamConsumer( - MongoChangeStreamSubscription subscription, - MongoChangeStreamSource source, - MongoResumeCheckpointStore checkpoints, - MongoResumeTokenCodec tokens, - MongoChangeStreamPipeline pipeline, - MongoChangeStreamRecoveryPolicy recovery, - MongoInvalidateRecovery invalidates) { - this.subscription = Objects.requireNonNull(subscription, "subscription"); - this.source = Objects.requireNonNull(source, "source"); - this.checkpoints = Objects.requireNonNull(checkpoints, "checkpoints"); - this.tokens = Objects.requireNonNull(tokens, "tokens"); - this.pipeline = Objects.requireNonNull(pipeline, "pipeline"); - this.recovery = Objects.requireNonNull(recovery, "recovery"); - this.invalidates = Objects.requireNonNull(invalidates, "invalidates"); - } - - /** - * Runs the subscription until it is stopped or a failure the platform will not resume from. - * - * @return the projection result of every event this consumer handled - */ - public Flux run() { - return Mono.fromRunnable(() -> state.set(MongoChangeStreamState.STARTING)) - .thenMany(Flux.defer(this::openAndConsume)) - .onErrorResume(this::recoverFrom); - } - - /** The subscription's current lifecycle state. */ - public MongoChangeStreamState state() { - return state.get(); - } - - /** The runbook an operator needs when this subscription has stopped, empty while it runs. */ - public String requiredRunbook() { - return requiredRunbook.get(); - } - - private Flux openAndConsume() { - return checkpoints - .load(subscription.subscriptionProfile()) - .map(this::resumeFrom) - .flatMapMany( - resumeFrom -> { - state.set(MongoChangeStreamState.RUNNING); - return pipeline.process(source.open(subscription, resumeFrom).flatMap(this::toEvent)); - }); - } - - private Optional resumeFrom( - Optional stored) { - return stored.map( - checkpoint -> { - // The option the position was recorded under, not the option this call happens to want: - // replaying an invalidate token with resumeAfter is refused by the server, and the - // failure it produces names neither the subscription nor the reason. - invalidates.requireCorrectResumeOption(checkpoint, checkpoint.position()); - return new MongoChangeStreamSource.ResumeFrom( - tokens.decode(checkpoint), checkpoint.position()); - }); - } - - private Mono toEvent( - ChangeStreamEvent event) { - BsonDocument token = - event.getResumeToken() == null ? null : event.getResumeToken().asDocument(); - if (token == null) { - return Mono.error( - new IllegalStateException( - "a change event arrived without a resume token; there is no position to store and" - + " continuing would advance the subscription past an event it cannot resume at")); - } - // An invalidate closes the stream, and its token is the one thing `resumeAfter` refuses. The - // option is decided here, while the event says which it is; by restart time the stored token - // looks like any other and the distinction is gone. - MongoResumePosition position = - event.getOperationType() == OperationType.INVALIDATE - ? MongoResumePosition.START_AFTER - : MongoResumePosition.RESUME_AFTER; - MongoResumeCheckpoint checkpoint = - tokens.encode(subscription.subscriptionProfile(), token, position); - return Mono.just( - new MongoChangeStreamPipeline.MongoChangeEvent( - identityOf(event), rawOf(event), checkpoint, clusterTimeOf(event))); - } - - private MongoChangeEventIdentity identityOf(ChangeStreamEvent event) { - var raw = event.getRaw(); - String namespace = - (event.getDatabaseName() == null ? "" : event.getDatabaseName()) - + '.' - + (event.getCollectionName() == null ? "" : event.getCollectionName()); - String documentKey = - raw == null || raw.getDocumentKey() == null ? "" : raw.getDocumentKey().toJson(); - // The transaction coordinates are what separate two updates to one document inside one - // transaction: without them the two events share cluster time, namespace, key and operation, - // and the second is discarded as a redelivery of the first. - String withinTransaction = - raw == null || raw.getTxnNumber() == null - ? "" - : raw.getTxnNumber().getValue() - + ":" - + (raw.getLsid() == null ? "" : raw.getLsid().toJson()); - return MongoChangeEventIdentity.of( - clusterTimeOf(event).toString(), - namespace, - documentKey, - event.getOperationType() == null ? "unknown" : event.getOperationType().getValue(), - withinTransaction); - } - - private static BsonDocument rawOf(ChangeStreamEvent event) { - var raw = event.getRaw(); - return raw == null || raw.getFullDocument() == null - ? new BsonDocument() - : raw.getFullDocument().toBsonDocument(); - } - - private static MongoClusterTime clusterTimeOf(ChangeStreamEvent event) { - var timestamp = event.getBsonTimestamp(); - return timestamp == null - ? new MongoClusterTime(0, 0) - : new MongoClusterTime(timestamp.getTime(), timestamp.getInc()); - } - - private Flux recoverFrom(Throwable failure) { - MongoChangeStreamRecoveryDecision decision = decisionFor(failure); - if (!decision.autoResume()) { - state.set(decision.state()); - requiredRunbook.set(decision.requiredRunbook()); - return Flux.error(failure); - } - state.set(MongoChangeStreamState.RESUMING); - // Reopened from the stored checkpoint rather than from where the stream stopped: the last - // position that was written is the last event a projection completed for, and anything after - // it must be delivered again. - return Flux.defer(this::openAndConsume).onErrorResume(this::haltOn); - } - - private Flux haltOn(Throwable failure) { - MongoChangeStreamRecoveryDecision decision = decisionFor(failure); - state.set(decision.autoResume() ? MongoChangeStreamState.FAILED : decision.state()); - requiredRunbook.set( - decision.requiredRunbook().isBlank() - ? MongoChangeStreamRecoveryPolicy.FAILURE_RUNBOOK - : decision.requiredRunbook()); - return Flux.error(failure); - } - - private MongoChangeStreamRecoveryDecision decisionFor(Throwable failure) { - if (failure instanceof com.mongodb.MongoException driverFailure) { - return recovery.onFailure(MongoDriverFailureView.from(driverFailure)); - } - // Anything that is not a driver failure came from the projection or the checkpoint store, and - // resuming a stream does not fix either. - return MongoChangeStreamRecoveryDecision.halt( - MongoChangeStreamState.FAILED, MongoChangeStreamRecoveryPolicy.FAILURE_RUNBOOK); - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/consumer/SpringReactiveChangeStreamSource.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/consumer/SpringReactiveChangeStreamSource.java deleted file mode 100644 index ac7cfd4d..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/consumer/SpringReactiveChangeStreamSource.java +++ /dev/null @@ -1,76 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.changestream.consumer; - -import com.mongodb.client.model.changestream.FullDocument; -import com.mongodb.client.model.changestream.FullDocumentBeforeChange; -import dev.caskeleton.adapter.outbound.mongo.changestream.MongoChangeStreamSubscription; -import dev.caskeleton.adapter.outbound.mongo.changestream.MongoResumePosition; -import dev.caskeleton.adapter.outbound.mongo.imperative.MongoCollectionProfileRegistry; -import java.util.Objects; -import java.util.Optional; -import org.springframework.data.mongodb.core.ChangeStreamEvent; -import org.springframework.data.mongodb.core.ChangeStreamOptions; -import org.springframework.data.mongodb.core.ReactiveMongoTemplate; -import reactor.core.publisher.Flux; - -/** - * The driver-facing half of a change stream subscription. - * - *

Deliberately thin: it turns a stored position into the driver's options and opens the cursor. - * Everything that decides what happens next lives in the consumer, so the lifecycle can be - * exercised without a replica set and this class has nothing left to get wrong except the mapping - * it is named for. - * - *

The collection is resolved through the profile registry rather than named directly, so a - * subscription cannot watch a collection the platform does not know about — which is also the only - * way the physical name stays a deployment decision. - * - *

Spring Data MongoDB 5.0.7's {@link ChangeStreamOptions} exposes resume/full-document options - * but not driver {@code batchSize} or {@code maxAwaitTime}. This source therefore must not be - * treated as satisfying those subscription bounds; the platform configuration rejects change-stream - * activation until a driver-level source can carry the complete contract. - */ -public final class SpringReactiveChangeStreamSource implements MongoChangeStreamSource { - - private final ReactiveMongoTemplate template; - - private final MongoCollectionProfileRegistry collections; - - public SpringReactiveChangeStreamSource( - ReactiveMongoTemplate template, MongoCollectionProfileRegistry collections) { - this.template = Objects.requireNonNull(template, "template"); - this.collections = Objects.requireNonNull(collections, "collections"); - } - - @Override - public Flux> open( - MongoChangeStreamSubscription subscription, Optional resumeFrom) { - Objects.requireNonNull(subscription, "subscription"); - Objects.requireNonNull(resumeFrom, "resumeFrom"); - - return template - .changeStream(org.bson.Document.class) - .watchCollection(collections.require(subscription.collectionProfile())) - .resumeAt(optionsFor(subscription, resumeFrom)) - .listen(); - } - - private static ChangeStreamOptions optionsFor( - MongoChangeStreamSubscription subscription, Optional resumeFrom) { - ChangeStreamOptions.ChangeStreamOptionsBuilder options = - ChangeStreamOptions.builder() - .fullDocumentLookup(FullDocument.UPDATE_LOOKUP) - .fullDocumentBeforeChangeLookup( - subscription.fullDocumentBeforeChange() - ? FullDocumentBeforeChange.WHEN_AVAILABLE - : FullDocumentBeforeChange.OFF); - resumeFrom.ifPresent( - from -> { - if (from.position() == MongoResumePosition.START_AFTER) { - options.startAfter(from.token()); - } else { - options.resumeAfter(from.token()); - } - }); - return options.build(); - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/projector/MongoChangeClaim.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/projector/MongoChangeClaim.java deleted file mode 100644 index 8a7ba018..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/projector/MongoChangeClaim.java +++ /dev/null @@ -1,25 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.changestream.projector; - -/** - * What one attempt to claim a change event got. - * - *

The store used to answer a question — "has this been projected?" — and take an instruction — - * "it has been projected now". Between those two calls the runner projected, and two subscribers - * that read {@code false} at the same time both projected: the deduplication that exists precisely - * because redelivery is guaranteed did not survive concurrency, which is the one condition it was - * built for. - * - *

A claim replaces the read with an atomic transition, so exactly one caller can be told to - * proceed. - */ -public enum MongoChangeClaim { - - /** This caller owns the event for the duration of its lease and must project it. */ - CLAIMED, - - /** Another caller already projected it to completion; nothing to do. */ - ALREADY_COMPLETED, - - /** Another caller holds an unexpired lease. Not an error, and not a completion. */ - BUSY -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/projector/MongoChangeDeduplicationStore.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/projector/MongoChangeDeduplicationStore.java deleted file mode 100644 index 43032013..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/projector/MongoChangeDeduplicationStore.java +++ /dev/null @@ -1,50 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.changestream.projector; - -import dev.caskeleton.adapter.outbound.mongo.changestream.MongoChangeEventIdentity; -import java.time.Duration; -import reactor.core.publisher.Mono; - -/** - * The durable claim on a change event (design §20.2). - * - *

Needed because the checkpoint is written after the projection, which is what prevents event - * loss and therefore guarantees duplicates on restart. The store is what keeps those duplicates - * from repeating a side effect. - * - *

This used to be {@code alreadyProjected} followed by {@code markProjected} — a read, then the - * projection, then a write. Two subscribers reading {@code false} at the same time both projected. - * The replacement is a three-state claim: exactly one caller is told to proceed, and the others are - * told whether the work is finished or merely in progress. The distinction matters at the - * checkpoint: a completed event may be passed, an in-progress one may not. - * - *

The claim carries a lease, so a caller that dies between claiming and completing does not park - * the event forever. Entries are expected to expire; the window that matters is bounded by how far - * a resume can rewind, not by the retention of the projection itself. - * - *

Implementations must make {@code tryClaim} atomic — a conditional upsert, not a find followed - * by an insert — and must never complete empty. An empty completion is a protocol violation the - * runner turns into an error rather than reading it as "no". - */ -public interface MongoChangeDeduplicationStore { - - /** - * Atomically claims an event for this caller. - * - * @param lease how long this claim is honoured before another caller may take it - */ - Mono tryClaim(MongoChangeEventIdentity identity, Duration lease); - - /** - * Marks a claimed event finished, so later claims answer {@link - * MongoChangeClaim#ALREADY_COMPLETED}. - */ - Mono complete(MongoChangeEventIdentity identity); - - /** - * Gives up a claim without completing it. - * - *

Called when the projection failed or was parked. Releasing is what turns "this caller - * crashed" into "another caller may retry now" rather than "wait for the lease to expire". - */ - Mono releaseOrExpire(MongoChangeEventIdentity identity); -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/projector/MongoChangeProjectionResult.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/projector/MongoChangeProjectionResult.java deleted file mode 100644 index ba15c66e..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/projector/MongoChangeProjectionResult.java +++ /dev/null @@ -1,65 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.changestream.projector; - -import java.util.Objects; - -/** - * What a projector did with one event (design §20.2, §35). - * - *

{@code SKIPPED_DUPLICATE} is distinct from {@code APPLIED} because both are successes and only - * one of them changed anything. Reporting them separately is what lets a duplicate rate be observed - * — and a duplicate rate that suddenly rises is the first visible sign of a resume loop. - */ -public record MongoChangeProjectionResult(Outcome outcome, String detail) { - - public MongoChangeProjectionResult { - Objects.requireNonNull(outcome, "outcome"); - Objects.requireNonNull(detail, "detail"); - } - - /** The projection ran and changed state. */ - public static MongoChangeProjectionResult applied() { - return new MongoChangeProjectionResult(Outcome.APPLIED, ""); - } - - /** The event had already been applied; nothing changed. */ - public static MongoChangeProjectionResult duplicate() { - return new MongoChangeProjectionResult(Outcome.SKIPPED_DUPLICATE, ""); - } - - /** - * Another worker holds the claim; this caller did nothing. - * - *

Not a success and not a failure. The checkpoint must not advance past it: the holder may - * still fail, and a checkpoint that has passed the event is a change the stream will never - * replay. - */ - public static MongoChangeProjectionResult busy() { - return new MongoChangeProjectionResult(Outcome.CLAIMED_ELSEWHERE, ""); - } - - /** The event could not be interpreted and was routed to the parking workflow. */ - public static MongoChangeProjectionResult parked(String reason) { - return new MongoChangeProjectionResult(Outcome.PARKED, reason); - } - - /** True when the checkpoint may advance past this event. */ - public boolean allowsCheckpointAdvance() { - return outcome != Outcome.PARKED && outcome != Outcome.CLAIMED_ELSEWHERE; - } - - /** What happened to the event. */ - public enum Outcome { - - /** The projection ran and changed state. */ - APPLIED, - - /** The event was already applied. */ - SKIPPED_DUPLICATE, - - /** The event was malformed and was parked for operator review. */ - PARKED, - - /** Another worker holds the claim and this caller did nothing. */ - CLAIMED_ELSEWHERE - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/projector/MongoChangeProjector.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/projector/MongoChangeProjector.java deleted file mode 100644 index 75e656da..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/projector/MongoChangeProjector.java +++ /dev/null @@ -1,23 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.changestream.projector; - -import dev.caskeleton.adapter.outbound.mongo.changestream.MongoChangeEventIdentity; -import org.bson.BsonDocument; -import reactor.core.publisher.Mono; - -/** - * Applies one physical change event to an internal projection (design §20.4, D-12). - * - *

The projector receives the raw BSON change and must not forward it anywhere external. A change - * event's shape is a MongoDB implementation detail — field names, update descriptions, the presence - * of {@code fullDocument} — and publishing it as an integration contract couples every consumer to - * this collection's storage layout, so a schema migration becomes a breaking API change. - * - *

Implementations must be idempotent. The runner checkpoints after a successful projection, so - * redelivery of an already-applied event is normal rather than exceptional. - */ -@FunctionalInterface -public interface MongoChangeProjector { - - /** Projects one event. Must be idempotent with respect to the identity. */ - Mono project(MongoChangeEventIdentity identity, BsonDocument change); -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/projector/MongoChangeStreamRunner.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/projector/MongoChangeStreamRunner.java deleted file mode 100644 index 8a49dd99..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/projector/MongoChangeStreamRunner.java +++ /dev/null @@ -1,124 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.changestream.projector; - -import dev.caskeleton.adapter.outbound.mongo.changestream.MongoChangeEventIdentity; -import dev.caskeleton.adapter.outbound.mongo.changestream.MongoResumeCheckpoint; -import dev.caskeleton.adapter.outbound.mongo.changestream.MongoResumeCheckpointStore; -import java.util.Objects; -import org.bson.BsonDocument; -import reactor.core.publisher.Mono; - -/** - * Projects one event, then checkpoints — in that order (design §20.2). - * - *

The ordering is the entire contract. Checkpointing first would mean a crash between the two - * loses the event permanently, with no trace: the stream resumes past a change that was never - * projected. Projecting first means a crash redelivers the event, which the deduplication store and - * an idempotent projector absorb. - * - *

So the platform chooses duplicates over loss, and then removes the duplicates. A failed - * projection leaves the previous checkpoint exactly where it was. - */ -public final class MongoChangeStreamRunner { - - private final MongoChangeProjector projector; - - private final MongoChangeDeduplicationStore deduplication; - - private final MongoResumeCheckpointStore checkpoints; - - /** How long a claim is honoured when the caller does not say. */ - public static final java.time.Duration DEFAULT_LEASE = java.time.Duration.ofMinutes(5); - - private final java.time.Duration lease; - - public MongoChangeStreamRunner( - MongoChangeProjector projector, - MongoChangeDeduplicationStore deduplication, - MongoResumeCheckpointStore checkpoints) { - this(projector, deduplication, checkpoints, DEFAULT_LEASE); - } - - public MongoChangeStreamRunner( - MongoChangeProjector projector, - MongoChangeDeduplicationStore deduplication, - MongoResumeCheckpointStore checkpoints, - java.time.Duration lease) { - this.projector = Objects.requireNonNull(projector, "projector"); - this.deduplication = Objects.requireNonNull(deduplication, "deduplication"); - this.checkpoints = Objects.requireNonNull(checkpoints, "checkpoints"); - this.lease = Objects.requireNonNull(lease, "lease"); - if (lease.isNegative() || lease.isZero()) { - throw new IllegalArgumentException("a claim lease must be positive"); - } - } - - /** - * Handles one event end to end. - * - * @param identity the redelivery-stable identity of the event - * @param change the raw change document - * @param checkpoint the position to store once the projection has succeeded - */ - public Mono runOne( - MongoChangeEventIdentity identity, BsonDocument change, MongoResumeCheckpoint checkpoint) { - Objects.requireNonNull(identity, "identity"); - Objects.requireNonNull(change, "change"); - Objects.requireNonNull(checkpoint, "checkpoint"); - - return deduplication - .tryClaim(identity, lease) - .switchIfEmpty(Mono.error(emptyFrom("the deduplication store", "tryClaim"))) - .flatMap(claim -> apply(claim, identity, change)) - .flatMap( - result -> - result.allowsCheckpointAdvance() - ? checkpoints.save(checkpoint).thenReturn(result) - : Mono.just(result)); - } - - private Mono apply( - MongoChangeClaim claim, MongoChangeEventIdentity identity, BsonDocument change) { - return switch (claim) { - case ALREADY_COMPLETED -> Mono.just(MongoChangeProjectionResult.duplicate()); - // BUSY is not a duplicate. The holder may still fail, and answering "duplicate" here would - // advance the checkpoint past an event nothing has projected yet. - case BUSY -> Mono.just(MongoChangeProjectionResult.busy()); - case CLAIMED -> projectAndComplete(identity, change); - }; - } - - private Mono projectAndComplete( - MongoChangeEventIdentity identity, BsonDocument change) { - return projector - .project(identity, change) - .switchIfEmpty(Mono.error(emptyFrom("the projector", "project"))) - .flatMap( - result -> - result.allowsCheckpointAdvance() - ? deduplication.complete(identity).thenReturn(result) - : release(identity).thenReturn(result)) - // A failed projection gives the claim back rather than holding it until the lease expires, - // so the next delivery can retry immediately instead of reporting BUSY for the lease. - .onErrorResume(failure -> release(identity).then(Mono.error(failure))); - } - - private Mono release(MongoChangeEventIdentity identity) { - return deduplication.releaseOrExpire(identity).onErrorResume(ignored -> Mono.empty()); - } - - /** - * An empty completion is a protocol violation, not an answer. - * - *

{@code Mono} that completes empty used to flow straight through {@code flatMap}: - * the runner returned empty, the caller saw no result, no projection ran and no checkpoint moved - * — and nothing anywhere reported a problem. - */ - private static IllegalStateException emptyFrom(String component, String method) { - return new IllegalStateException( - component - + " completed " - + method - + " without a value; an empty result is indistinguishable from a decision and the" - + " runner will not treat it as one"); - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/recovery/MongoChangeHistoryLostException.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/recovery/MongoChangeHistoryLostException.java deleted file mode 100644 index a956f31f..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/recovery/MongoChangeHistoryLostException.java +++ /dev/null @@ -1,35 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.changestream.recovery; - -import dev.caskeleton.adapter.outbound.mongo.api.error.MongoFailureContext; -import dev.caskeleton.adapter.outbound.mongo.api.error.MongoPersistenceException; -import java.io.Serial; -import java.util.Objects; - -/** - * The oplog no longer contains the stored resume position (design §20.3). - * - *

A dedicated type because the recovery is a business decision, not a technical one. The - * platform could resume from "now" — the driver makes it easy — and the projection would silently - * miss every change that fell off the oplog. The only honest options are rebuilding the projection - * or reconciling it against the source, and both need someone to choose. - */ -public final class MongoChangeHistoryLostException extends MongoPersistenceException { - - @Serial private static final long serialVersionUID = 1L; - - private final String subscriptionProfile; - - public MongoChangeHistoryLostException( - MongoFailureContext failureContext, String subscriptionProfile) { - super( - "the change stream's resume position is no longer in the oplog; consumption stopped rather " - + "than restarting from now and silently skipping the gap", - failureContext); - this.subscriptionProfile = Objects.requireNonNull(subscriptionProfile, "subscriptionProfile"); - } - - /** The subscription whose history was lost. */ - public String subscriptionProfile() { - return subscriptionProfile; - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/recovery/MongoChangeStreamRecoveryDecision.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/recovery/MongoChangeStreamRecoveryDecision.java deleted file mode 100644 index 8b02975c..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/recovery/MongoChangeStreamRecoveryDecision.java +++ /dev/null @@ -1,36 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.changestream.recovery; - -import dev.caskeleton.adapter.outbound.mongo.changestream.MongoChangeStreamState; -import java.util.Objects; - -/** - * What to do about a change stream failure (design §20.3). - * - *

{@code autoResume} and {@code requiredRunbook} are both present because the interesting case - * needs both answers: the platform will not resume, and a human needs to know which procedure - * applies. A decision that only says "stopped" leaves the on-call engineer to work out whether the - * projection can be rebuilt, and from what. - */ -public record MongoChangeStreamRecoveryDecision( - MongoChangeStreamState state, boolean autoResume, String requiredRunbook) { - - public MongoChangeStreamRecoveryDecision { - Objects.requireNonNull(state, "state"); - Objects.requireNonNull(requiredRunbook, "requiredRunbook"); - if (!autoResume && requiredRunbook.isBlank() && state != MongoChangeStreamState.STOPPED) { - throw new IllegalArgumentException( - "a decision that stops consumption must name the runbook that resolves it"); - } - } - - /** Resume automatically from the stored checkpoint. */ - public static MongoChangeStreamRecoveryDecision resume() { - return new MongoChangeStreamRecoveryDecision(MongoChangeStreamState.RESUMING, true, ""); - } - - /** Stop and wait for an operator. */ - public static MongoChangeStreamRecoveryDecision halt( - MongoChangeStreamState state, String runbook) { - return new MongoChangeStreamRecoveryDecision(state, false, runbook); - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/recovery/MongoChangeStreamRecoveryPolicy.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/recovery/MongoChangeStreamRecoveryPolicy.java deleted file mode 100644 index fe947e6c..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/recovery/MongoChangeStreamRecoveryPolicy.java +++ /dev/null @@ -1,67 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.changestream.recovery; - -import dev.caskeleton.adapter.outbound.mongo.changestream.MongoChangeStreamState; -import dev.caskeleton.adapter.outbound.mongo.failure.MongoDriverFailureView; -import java.util.Objects; - -/** - * Decides how a change stream reacts to each kind of failure (design §20.3). - * - *

Three classes with three different answers. A resumable network or election failure resumes - * automatically, because the stored token is still valid. An invalidate — a dropped or renamed - * collection — needs {@code startAfter} rather than {@code resumeAfter}, which the driver will not - * do implicitly. A lost history needs a human. - */ -public final class MongoChangeStreamRecoveryPolicy { - - /** Runbook for a subscription whose oplog history was lost. */ - public static final String HISTORY_LOST_RUNBOOK = "docs/mongodb/runbooks/history-lost.md"; - - /** Runbook for a subscription that failed for a non-resumable reason. */ - public static final String FAILURE_RUNBOOK = "docs/mongodb/runbooks/failover.md"; - - /** - * The decision for a lost oplog history. - * - *

Never auto-resumes. The alternative — restarting from the current time — produces a - * projection that is missing an unknown range of changes and reports itself as healthy. - */ - public MongoChangeStreamRecoveryDecision onHistoryLost(String subscriptionProfile) { - Objects.requireNonNull(subscriptionProfile, "subscriptionProfile"); - return MongoChangeStreamRecoveryDecision.halt( - MongoChangeStreamState.HISTORY_LOST, HISTORY_LOST_RUNBOOK); - } - - /** The decision for a resumable failure such as a primary failover. */ - public MongoChangeStreamRecoveryDecision onResumableFailure() { - return MongoChangeStreamRecoveryDecision.resume(); - } - - /** - * The decision for an invalidate event. - * - *

Resumes, but the checkpoint the caller stores must be a {@code startAfter} position — the - * subscription is otherwise unresumable, because {@code resumeAfter} rejects an invalidate token. - */ - public MongoChangeStreamRecoveryDecision onInvalidate() { - return MongoChangeStreamRecoveryDecision.resume(); - } - - /** The decision for a failure the platform cannot classify as resumable. */ - public MongoChangeStreamRecoveryDecision onFailure(MongoDriverFailureView failure) { - Objects.requireNonNull(failure, "failure"); - if (failure.hasServerCode() && isHistoryLost(failure.serverCode())) { - return MongoChangeStreamRecoveryDecision.halt( - MongoChangeStreamState.HISTORY_LOST, HISTORY_LOST_RUNBOOK); - } - if (failure.hasLabel("ResumableChangeStreamError")) { - return MongoChangeStreamRecoveryDecision.resume(); - } - return MongoChangeStreamRecoveryDecision.halt(MongoChangeStreamState.FAILED, FAILURE_RUNBOOK); - } - - /** {@code ChangeStreamHistoryLost} and {@code ChangeStreamFatalError}. */ - private static boolean isHistoryLost(int serverCode) { - return serverCode == 286 || serverCode == 280; - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/recovery/MongoInvalidateRecovery.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/recovery/MongoInvalidateRecovery.java deleted file mode 100644 index 88ca505e..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/changestream/recovery/MongoInvalidateRecovery.java +++ /dev/null @@ -1,46 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.changestream.recovery; - -import dev.caskeleton.adapter.outbound.mongo.changestream.MongoResumeCheckpoint; -import dev.caskeleton.adapter.outbound.mongo.changestream.MongoResumePosition; -import java.util.Objects; - -/** - * Turns an invalidate event into a resumable position (design §20.3). - * - *

An invalidate closes the change stream — the collection was dropped, renamed, or the database - * dropped. Its token cannot be replayed with {@code resumeAfter}; only {@code startAfter} accepts - * it. Recording that at the moment the invalidate arrives is what keeps the subscription - * restartable, because by the time the restart is attempted the distinction is no longer - * recoverable. - */ -public final class MongoInvalidateRecovery { - - /** Converts the invalidate token into a checkpoint marked for {@code startAfter}. */ - public MongoResumeCheckpoint checkpointFor(String subscriptionProfile, byte[] invalidateToken) { - Objects.requireNonNull(subscriptionProfile, "subscriptionProfile"); - Objects.requireNonNull(invalidateToken, "invalidateToken"); - return MongoResumeCheckpoint.afterInvalidate(subscriptionProfile, invalidateToken); - } - - /** - * Rejects a checkpoint that would be replayed with the wrong resume option. - * - * @throws IllegalStateException when an invalidate checkpoint is about to be used with {@code - * resumeAfter} - */ - public void requireCorrectResumeOption( - MongoResumeCheckpoint checkpoint, MongoResumePosition intended) { - Objects.requireNonNull(checkpoint, "checkpoint"); - Objects.requireNonNull(intended, "intended"); - if (checkpoint.position() != intended) { - throw new IllegalStateException( - "checkpoint for subscription '" - + checkpoint.subscriptionProfile() - + "' must be replayed with " - + checkpoint.position() - + " but " - + intended - + " was requested"); - } - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/client/MongoProfileClientSettingsAutoConfiguration.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/client/MongoProfileClientSettingsAutoConfiguration.java index 2e060051..55ca29aa 100644 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/client/MongoProfileClientSettingsAutoConfiguration.java +++ b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/client/MongoProfileClientSettingsAutoConfiguration.java @@ -23,7 +23,8 @@ import org.springframework.core.env.Environment; @ConditionalOnProperty( prefix = "ca-skeleton.persistence-mongo", name = "enabled", - havingValue = "true") + havingValue = "true", + matchIfMissing = true) class MongoProfileClientSettingsAutoConfiguration { @Bean("mongoTopologyRefreshCustomizer") diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/imperative/MongoTemplateSupportContract.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/imperative/MongoTemplateSupportContract.java index 46631b1b..2643cee5 100644 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/imperative/MongoTemplateSupportContract.java +++ b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/imperative/MongoTemplateSupportContract.java @@ -44,28 +44,6 @@ public record MongoTemplateSupportContract( null, WriteResultChecking.NONE, true, Objects.requireNonNull(context, "context")); } - /** - * Applies this contract to a derived reactive template. - * - *

The reactive binder derived its templates with read preference and write concern only, so a - * document written through the reactive executor skipped auditing and {@code - * BeforeConvertCallback} while the same document written through an ordinary reactive repository - * did not. The imperative half was fixed and the reactive half was left, which stopped being - * theoretical when the reactive execution path was wired. - * - * @param template the derived reactive template - */ - public void applyTo(org.springframework.data.mongodb.core.ReactiveMongoTemplate template) { - Objects.requireNonNull(template, "template"); - if (writeConcernResolver != null) { - template.setWriteConcernResolver(writeConcernResolver); - } - template.setWriteResultChecking( - writeResultChecking == null ? WriteResultChecking.NONE : writeResultChecking); - template.setEntityLifecycleEventsEnabled(entityLifecycleEventsEnabled); - context().ifPresent(template::setApplicationContext); - } - /** Applies this contract to a derived template. */ public void applyTo(MongoTemplate template) { Objects.requireNonNull(template, "template"); diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/mapping/MongoMappingConfiguration.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/mapping/MongoMappingConfiguration.java index 9ff05497..f8dde11a 100644 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/mapping/MongoMappingConfiguration.java +++ b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/mapping/MongoMappingConfiguration.java @@ -28,7 +28,8 @@ import org.springframework.data.mongodb.core.convert.MongoCustomConversions; @ConditionalOnProperty( prefix = "ca-skeleton.persistence-mongo", name = "enabled", - havingValue = "true") + havingValue = "true", + matchIfMissing = true) public class MongoMappingConfiguration { /** The deployment's representation manifest. Override the bean to change it deliberately. */ diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/reactive/BoundReactiveScopedOperations.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/reactive/BoundReactiveScopedOperations.java deleted file mode 100644 index 2db9df01..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/reactive/BoundReactiveScopedOperations.java +++ /dev/null @@ -1,66 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.reactive; - -import java.util.Objects; -import org.springframework.data.mongodb.core.ReactiveMongoOperations; -import org.springframework.data.mongodb.core.aggregation.Aggregation; -import org.springframework.data.mongodb.core.query.Query; -import org.springframework.data.mongodb.core.query.Update; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; - -/** {@link ReactiveScopedMongoOperations} over one physical collection. */ -final class BoundReactiveScopedOperations implements ReactiveScopedMongoOperations { - - private final String collection; - - private final ReactiveMongoOperations operations; - - BoundReactiveScopedOperations(String collection, ReactiveMongoOperations operations) { - this.collection = Objects.requireNonNull(collection, "collection"); - this.operations = Objects.requireNonNull(operations, "operations"); - } - - @Override - public String collection() { - return collection; - } - - @Override - public Mono findOne(Query query, Class documentType) { - return operations.findOne(query, documentType, collection); - } - - @Override - public Flux findMany(Query query, Class documentType) { - return operations.find(query, documentType, collection); - } - - @Override - public Mono count(Query query, Class documentType) { - return operations.count(query, documentType, collection); - } - - @Override - public Mono insert(T document) { - return operations.insert(document, collection); - } - - @Override - public Mono updateOne(Query query, Update update, Class documentType) { - return operations - .updateFirst(query, update, documentType, collection) - .map(result -> result.getModifiedCount()); - } - - @Override - public Mono deleteOne(Query query, Class documentType) { - return operations - .remove(query, documentType, collection) - .map(result -> result.getDeletedCount()); - } - - @Override - public Flux aggregate(Aggregation aggregation, Class resultType) { - return operations.aggregate(aggregation, collection, resultType); - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/reactive/DefaultReactiveMongoExecutor.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/reactive/DefaultReactiveMongoExecutor.java deleted file mode 100644 index 292b1e01..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/reactive/DefaultReactiveMongoExecutor.java +++ /dev/null @@ -1,222 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.reactive; - -import com.mongodb.MongoException; -import dev.caskeleton.adapter.outbound.mongo.api.MongoOperationContext; -import dev.caskeleton.adapter.outbound.mongo.api.MongoOperationType; -import dev.caskeleton.adapter.outbound.mongo.api.error.MongoOperationRejectedException; -import dev.caskeleton.adapter.outbound.mongo.api.error.MongoPersistenceException; -import dev.caskeleton.adapter.outbound.mongo.api.observation.MongoOperationObservation; -import dev.caskeleton.adapter.outbound.mongo.api.observation.MongoOperationObserver; -import dev.caskeleton.adapter.outbound.mongo.failure.MongoDriverFailureView; -import dev.caskeleton.adapter.outbound.mongo.failure.MongoFailureTranslator; -import dev.caskeleton.adapter.outbound.mongo.imperative.MongoCollectionProfileRegistry; -import java.time.Duration; -import java.util.Objects; -import org.springframework.dao.DataAccessException; -import org.springframework.data.mongodb.core.ReactiveMongoOperations; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; -import reactor.util.context.Context; - -/** - * The reactive execution scope (design §26). - * - *

Three properties the blocking path gets for free and this one has to arrange explicitly. - * - *

The observation scope is a Reactor resource, so it closes on completion, on error and - * on cancellation — and cancellation is the common case here, because an HTTP client that - * disconnects cancels the chain. - * - *

The timeout is applied to the assembled publisher, so it covers the work rather than the - * assembly. A deadline applied before subscription would measure how long it took to build a - * lambda. - * - *

Context travels through Reactor Context, because the chain changes threads at every operator - * boundary and a thread-local set at subscription is gone by the time the driver responds. - */ -public final class DefaultReactiveMongoExecutor implements ReactiveMongoExecutor { - - private final ReactiveMongoConsistencyBinder consistency; - - private final MongoCollectionProfileRegistry collections; - - private final MongoFailureTranslator translator; - - private final MongoOperationObserver observer; - - public DefaultReactiveMongoExecutor( - ReactiveMongoConsistencyBinder consistency, - MongoCollectionProfileRegistry collections, - MongoFailureTranslator translator, - MongoOperationObserver observer) { - this.consistency = Objects.requireNonNull(consistency, "consistency"); - this.collections = Objects.requireNonNull(collections, "collections"); - this.translator = Objects.requireNonNull(translator, "translator"); - this.observer = Objects.requireNonNull(observer, "observer"); - } - - @Override - public Mono execute(MongoOperationContext context, ReactiveMongoCallback callback) { - return execute(context, MongoOperationType.UNKNOWN, callback); - } - - /** Runs an operation that produces at most one element, declaring its operation type. */ - public Mono execute( - MongoOperationContext context, - MongoOperationType operationType, - ReactiveMongoCallback callback) { - Objects.requireNonNull(context, "context"); - Objects.requireNonNull(operationType, "operationType"); - Objects.requireNonNull(callback, "callback"); - - return Mono.using( - () -> observer.start(context, operationType), - observation -> - Mono.from(callback.doInMongo(access(context))) - .timeout(context.timeout()) - // A read is not a confirmed write. Recording every success as WRITE_CONFIRMED - // made the metric that answers "are writes being acknowledged" count reads. - .doOnSuccess( - value -> - observation.success( - dev.caskeleton.adapter.outbound.mongo.imperative.MongoCompletion - .successOutcomeFor(operationType))) - .onErrorMap(failure -> translate(context, operationType, observation, failure)) - .contextWrite(contextOf(context, observation)), - MongoOperationObservation::close) - .onErrorMap(failure -> translate(context, operationType, null, failure)); - } - - @Override - public Flux executeMany(MongoOperationContext context, ReactiveMongoCallback callback) { - return executeMany(context, MongoOperationType.FIND, callback); - } - - /** Runs an operation that produces a bounded stream, declaring its operation type. */ - public Flux executeMany( - MongoOperationContext context, - MongoOperationType operationType, - ReactiveMongoCallback callback) { - Objects.requireNonNull(context, "context"); - Objects.requireNonNull(operationType, "operationType"); - Objects.requireNonNull(callback, "callback"); - - return Flux.using( - () -> observer.start(context, operationType), - observation -> - Flux.from(callback.doInMongo(access(context))) - .timeout(context.timeout()) - .doOnComplete( - () -> - observation.success( - dev.caskeleton.adapter.outbound.mongo.imperative.MongoCompletion - .successOutcomeFor(operationType))) - .onErrorMap(failure -> translate(context, operationType, observation, failure)) - .contextWrite(contextOf(context, observation)), - MongoOperationObservation::close) - .onErrorMap(failure -> translate(context, operationType, null, failure)); - } - - private static Context contextOf( - MongoOperationContext context, MongoOperationObservation observation) { - return Context.of( - ReactiveMongoContextKeys.OPERATION_CONTEXT, - context, - ReactiveMongoContextKeys.OBSERVATION, - observation); - } - - private ReactiveMongoCollectionAccess access(MongoOperationContext context) { - String physicalCollection = collections.require(context.collectionProfile()); - ReactiveMongoOperations operations = consistency.templateFor(context.consistency()); - return new ScopedAccess(physicalCollection, operations); - } - - private Throwable translate( - MongoOperationContext context, - MongoOperationType operationType, - MongoOperationObservation observation, - Throwable failure) { - if (failure instanceof MongoPersistenceException alreadyTranslated) { - if (observation != null) { - observation.failure(alreadyTranslated.failureContext()); - } - return alreadyTranslated; - } - if (failure instanceof java.util.concurrent.TimeoutException reactorTimeout) { - // Reactor's own timeout, not the driver's. It used to escape as a raw - // java.util.concurrent.TimeoutException — a type no caller of this platform is told about, - // and one that carries no operation, no outcome and no observation. The failure was also - // never recorded, because this method returned before reaching the observer. - MongoPersistenceException timedOut = - new dev.caskeleton.adapter.outbound.mongo.api.error.MongoTimeoutException( - dev.caskeleton.adapter.outbound.mongo.api.error.MongoFailureContext.timedOut( - context.operationName(), operationType, context.timeout()), - reactorTimeout); - if (observation != null) { - observation.failure(timedOut.failureContext()); - } - return timedOut; - } - MongoException driverFailure = asDriverFailure(failure); - if (driverFailure == null) { - return failure; - } - MongoPersistenceException translated = - translator.translate( - context, operationType, Duration.ZERO, MongoDriverFailureView.from(driverFailure), 1); - if (observation != null) { - observation.failure(translated.failureContext().withTraceId(observation.traceId())); - } - return translated; - } - - private static MongoException asDriverFailure(Throwable failure) { - if (failure instanceof MongoException driverFailure) { - return driverFailure; - } - if (failure instanceof DataAccessException springFailure - && springFailure.getCause() instanceof MongoException driverFailure) { - return driverFailure; - } - return null; - } - - /** The collection access handed to a reactive callback. */ - private static final class ScopedAccess implements ReactiveMongoCollectionAccess { - - private final String physicalCollection; - - private final ReactiveMongoOperations operations; - - private ScopedAccess(String physicalCollection, ReactiveMongoOperations operations) { - this.physicalCollection = physicalCollection; - this.operations = operations; - } - - @Override - public String collection() { - return physicalCollection; - } - - @Override - public String collection(String requestedCollection) { - Objects.requireNonNull(requestedCollection, "requestedCollection"); - if (!physicalCollection.equals(requestedCollection)) { - throw MongoOperationRejectedException.of( - "collection.scope", - "this operation is scoped to collection '" - + physicalCollection - + "' and may not reach '" - + requestedCollection - + "'"); - } - return physicalCollection; - } - - @Override - public ReactiveScopedMongoOperations scoped() { - return new BoundReactiveScopedOperations(physicalCollection, operations); - } - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/reactive/ReactiveMongoCallback.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/reactive/ReactiveMongoCallback.java deleted file mode 100644 index 76bd226f..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/reactive/ReactiveMongoCallback.java +++ /dev/null @@ -1,18 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.reactive; - -import org.reactivestreams.Publisher; - -/** - * The body of one reactive operation (design §26). - * - *

Returns a {@link Publisher} rather than a value, so the work is deferred until subscription - * and the timeout, context and cancellation the executor applies actually cover it. - * - * @param the element type - */ -@FunctionalInterface -public interface ReactiveMongoCallback { - - /** Builds the publisher for this operation. */ - Publisher doInMongo(ReactiveMongoCollectionAccess access); -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/reactive/ReactiveMongoCollectionAccess.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/reactive/ReactiveMongoCollectionAccess.java deleted file mode 100644 index 94b00b51..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/reactive/ReactiveMongoCollectionAccess.java +++ /dev/null @@ -1,32 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.reactive; - -import dev.caskeleton.adapter.outbound.mongo.api.error.MongoOperationRejectedException; - -/** - * The reactive counterpart of the imperative collection scope (design §26). - * - *

Same rule, same reason: the operation named one collection profile, so the callback reaches - * that collection and no other. Keeping the two APIs symmetrical is what lets a team move a use - * case between the blocking and reactive paths without re-deriving its guardrails. - */ -public interface ReactiveMongoCollectionAccess { - - /** The physical collection the operation's profile resolves to. */ - String collection(); - - /** - * Confirms that the callback is asking for the collection this operation was scoped to. - * - * @throws MongoOperationRejectedException when the requested collection is a different one - */ - String collection(String requestedCollection); - - /** - * The operations this callback may perform. - * - *

Scoped, like the imperative side: the raw {@code ReactiveMongoOperations} accessor this - * replaced could reach any collection in the database, which made {@link #collection(String)} a - * check the caller had to opt into. - */ - ReactiveScopedMongoOperations scoped(); -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/reactive/ReactiveMongoConsistencyBinder.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/reactive/ReactiveMongoConsistencyBinder.java deleted file mode 100644 index e34ebe97..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/reactive/ReactiveMongoConsistencyBinder.java +++ /dev/null @@ -1,113 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.reactive; - -import com.mongodb.ReadConcern; -import com.mongodb.ReadConcernLevel; -import com.mongodb.ReadPreference; -import com.mongodb.WriteConcern; -import dev.caskeleton.adapter.outbound.mongo.api.consistency.MongoConsistencyDescriptor; -import dev.caskeleton.adapter.outbound.mongo.api.consistency.MongoConsistencyProfile; -import dev.caskeleton.adapter.outbound.mongo.api.consistency.MongoConsistencyRegistry; -import java.util.EnumMap; -import java.util.Map; -import java.util.Objects; -import org.springframework.data.mongodb.core.ReactiveMongoTemplate; -import org.springframework.data.mongodb.core.query.Query; - -/** - * The reactive counterpart of the imperative consistency binder (design §7.2, §26). - * - *

Sharing the descriptor registry with the blocking path is what keeps the two from drifting: a - * profile means the same read preference, read concern and write concern on both, so moving a use - * case between them cannot silently change its durability. - */ -public final class ReactiveMongoConsistencyBinder { - - private final MongoConsistencyRegistry registry; - - private final Map templatesByProfile; - - private final dev.caskeleton.adapter.outbound.mongo.imperative.MongoTemplateSupportContract - support; - - public ReactiveMongoConsistencyBinder( - ReactiveMongoTemplate template, MongoConsistencyRegistry registry) { - this( - template, - registry, - dev.caskeleton.adapter.outbound.mongo.imperative.MongoTemplateSupportContract.defaults()); - } - - /** - * A binder that carries the source template's Spring runtime contract onto the derived ones. - * - *

Derivation used to set read preference and write concern and nothing else, so an entity - * written through the reactive executor skipped auditing and {@code BeforeConvertCallback} while - * the same entity written through an ordinary reactive repository did not — two documents, one - * mapping. The imperative binder was given this contract and the reactive one was not. - * - * @param template the source reactive template - * @param registry the consistency registry - * @param support the runtime contract to carry across - */ - public ReactiveMongoConsistencyBinder( - ReactiveMongoTemplate template, - MongoConsistencyRegistry registry, - dev.caskeleton.adapter.outbound.mongo.imperative.MongoTemplateSupportContract support) { - Objects.requireNonNull(support, "support"); - this.support = support; - Objects.requireNonNull(template, "template"); - this.registry = Objects.requireNonNull(registry, "registry"); - Map derived = - new EnumMap<>(MongoConsistencyProfile.class); - for (MongoConsistencyProfile profile : MongoConsistencyProfile.values()) { - derived.put(profile, derive(template, registry.require(profile))); - } - this.templatesByProfile = Map.copyOf(derived); - } - - private ReactiveMongoTemplate derive( - ReactiveMongoTemplate template, MongoConsistencyDescriptor descriptor) { - ReactiveMongoTemplate bound = - new ReactiveMongoTemplate(template.getMongoDatabaseFactory(), template.getConverter()); - bound.setReadPreference(readPreferenceOf(descriptor)); - bound.setWriteConcern(writeConcernOf(descriptor)); - support.applyTo(bound); - return bound; - } - - /** The reactive template bound to a profile's read preference and write concern. */ - public ReactiveMongoTemplate templateFor(MongoConsistencyProfile profile) { - ReactiveMongoTemplate bound = - templatesByProfile.get(Objects.requireNonNull(profile, "profile")); - if (bound == null) { - throw new IllegalStateException( - "no reactive template bound for consistency profile " + profile); - } - return bound; - } - - /** Applies a profile's read settings to one query. */ - public Query applyReadSettings(Query query, MongoConsistencyProfile profile) { - Objects.requireNonNull(query, "query"); - MongoConsistencyDescriptor descriptor = registry.require(profile); - return query - .withReadPreference(readPreferenceOf(descriptor)) - .withReadConcern(readConcernOf(descriptor)); - } - - private static ReadPreference readPreferenceOf(MongoConsistencyDescriptor descriptor) { - return descriptor.readsFromSecondary() - ? ReadPreference.secondaryPreferred() - : ReadPreference.primary(); - } - - private static ReadConcern readConcernOf(MongoConsistencyDescriptor descriptor) { - return new ReadConcern(ReadConcernLevel.fromString(descriptor.readConcern())); - } - - private static WriteConcern writeConcernOf(MongoConsistencyDescriptor descriptor) { - return "majority".equals(descriptor.writeConcern()) - ? WriteConcern.MAJORITY - : WriteConcern.ACKNOWLEDGED; - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/reactive/ReactiveMongoContextKeys.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/reactive/ReactiveMongoContextKeys.java deleted file mode 100644 index 2f0860eb..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/reactive/ReactiveMongoContextKeys.java +++ /dev/null @@ -1,23 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.reactive; - -/** - * The Reactor Context keys the reactive path propagates operation state under (design §26). - * - *

Reactor Context rather than {@code ThreadLocal}, because a reactive chain changes threads at - * every operator boundary. A {@code ThreadLocal} set at subscription time is simply absent by the - * time the driver callback runs, so operation identity and tracing would silently disappear from - * exactly the signals that need them. - */ -public final class ReactiveMongoContextKeys { - - /** Reactor Context key holding the {@code MongoOperationContext} of the current operation. */ - public static final String OPERATION_CONTEXT = "mongodb.operationContext"; - - /** Reactor Context key holding the observation scope of the current operation. */ - public static final String OBSERVATION = "mongodb.observation"; - - /** Reactor Context key holding the causal session bound to the current chain. */ - public static final String CAUSAL_SESSION = "mongodb.causalSession"; - - private ReactiveMongoContextKeys() {} -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/reactive/ReactiveMongoExecutor.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/reactive/ReactiveMongoExecutor.java deleted file mode 100644 index 0bcb6a5c..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/reactive/ReactiveMongoExecutor.java +++ /dev/null @@ -1,22 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.reactive; - -import dev.caskeleton.adapter.outbound.mongo.api.MongoOperationContext; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; - -/** - * The single reactive execution path (design §26). - * - *

Mirrors the imperative executor's guarantees — registered operation, registered collection, - * consistency, deadline, observation, one translation — and adds the two the reactive model needs: - * cancellation must release resources, and context must travel through Reactor Context rather than - * a thread. - */ -public interface ReactiveMongoExecutor { - - /** Runs an operation that produces at most one element. */ - Mono execute(MongoOperationContext context, ReactiveMongoCallback callback); - - /** Runs an operation that produces a bounded stream of elements. */ - Flux executeMany(MongoOperationContext context, ReactiveMongoCallback callback); -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/reactive/ReactiveScopedMongoOperations.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/reactive/ReactiveScopedMongoOperations.java deleted file mode 100644 index 30011d26..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/reactive/ReactiveScopedMongoOperations.java +++ /dev/null @@ -1,41 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.reactive; - -import org.springframework.data.mongodb.core.aggregation.Aggregation; -import org.springframework.data.mongodb.core.query.Query; -import org.springframework.data.mongodb.core.query.Update; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; - -/** - * The reactive counterpart of {@code ScopedMongoOperations}. - * - *

Same rule, same reason: no method takes a collection, so the scope the operation declared - * cannot be stepped outside by not calling the check. Keeping the two APIs symmetrical is what lets - * a use case move between the blocking and reactive paths without re-deriving its guardrails. - */ -public interface ReactiveScopedMongoOperations { - - /** The physical collection every method here runs against. */ - String collection(); - - /** One document, or an empty {@code Mono}. */ - Mono findOne(Query query, Class documentType); - - /** Every matching document. */ - Flux findMany(Query query, Class documentType); - - /** How many documents match. */ - Mono count(Query query, Class documentType); - - /** Inserts one document. */ - Mono insert(T document); - - /** Updates the first match, emitting the modified count. */ - Mono updateOne(Query query, Update update, Class documentType); - - /** Deletes the first match, emitting the deleted count. */ - Mono deleteOne(Query query, Class documentType); - - /** Runs an aggregation the platform has already validated. */ - Flux aggregate(Aggregation aggregation, Class resultType); -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/reactive/cursor/MongoCursorGuard.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/reactive/cursor/MongoCursorGuard.java deleted file mode 100644 index 969bc616..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/reactive/cursor/MongoCursorGuard.java +++ /dev/null @@ -1,96 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.reactive.cursor; - -import dev.caskeleton.adapter.outbound.mongo.api.error.MongoOperationRejectedException; -import dev.caskeleton.adapter.outbound.mongo.query.budget.MongoOperationBudget; -import java.time.Duration; -import java.util.Objects; -import java.util.concurrent.TimeoutException; -import java.util.function.Consumer; -import java.util.function.Function; -import java.util.function.Supplier; -import reactor.core.publisher.Flux; - -/** - * Bounds a cursor's lifetime and guarantees it is released (design §32). - * - *

{@link Flux#using} is what makes the guarantee hold: the cleanup runs on completion, on error - * and on cancellation, which is the path a plain {@code doFinally} chain is most likely to get - * wrong. The lease's own idempotence means the cleanup can fire more than once without killing a - * cursor twice. - * - *

No transparent retry is offered. Once the first document has been emitted the consumer has - * already acted on a prefix, and silently restarting the cursor would deliver it again. - */ -public final class MongoCursorGuard { - - private final Duration maximumLifetime; - - private final Consumer terminationRecorder; - - public MongoCursorGuard( - Duration maximumLifetime, Consumer terminationRecorder) { - this.maximumLifetime = Objects.requireNonNull(maximumLifetime, "maximumLifetime"); - this.terminationRecorder = Objects.requireNonNull(terminationRecorder, "terminationRecorder"); - if (maximumLifetime.isZero() || maximumLifetime.isNegative()) { - throw new IllegalArgumentException("a cursor lifetime must be positive"); - } - } - - /** A guard that records nothing, for callers without telemetry. */ - public static MongoCursorGuard withLifetime(Duration maximumLifetime) { - return new MongoCursorGuard(maximumLifetime, termination -> {}); - } - - /** - * Wraps a cursor-backed stream so its lease is always released. - * - * @param leaseSupplier opens the cursor at subscription time - * @param streamFactory builds the element stream from the open lease - */ - public Flux guard( - Supplier leaseSupplier, Function> streamFactory) { - Objects.requireNonNull(leaseSupplier, "leaseSupplier"); - Objects.requireNonNull(streamFactory, "streamFactory"); - return Flux.using( - leaseSupplier::get, - lease -> - streamFactory - .apply(lease) - .timeout(maximumLifetime) - .doOnComplete(() -> terminationRecorder.accept(MongoCursorTermination.COMPLETED)) - .doOnCancel(() -> terminationRecorder.accept(MongoCursorTermination.CANCELLED)) - .doOnError( - failure -> - terminationRecorder.accept( - failure instanceof TimeoutException - ? MongoCursorTermination.LIFETIME_EXPIRED - : MongoCursorTermination.FAILED)), - MongoCursorLease::close); - } - - /** - * Checks that a cursor read declares the bounds it needs. - * - * @throws MongoOperationRejectedException when the batch size is unset or above the budget - */ - public void requireBoundedBatch(MongoOperationBudget budget, int requestedBatchSize) { - Objects.requireNonNull(budget, "budget"); - if (requestedBatchSize <= 0) { - throw MongoOperationRejectedException.of( - "cursor.batch", "a cursor read must declare a positive batch size"); - } - if (requestedBatchSize > budget.cursorBatchSize()) { - throw MongoOperationRejectedException.of( - "cursor.batch", - "a batch size of " - + requestedBatchSize - + " is above the registered budget of " - + budget.cursorBatchSize()); - } - } - - /** The maximum time a cursor may stay open. */ - public Duration maximumLifetime() { - return maximumLifetime; - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/reactive/cursor/MongoCursorLease.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/reactive/cursor/MongoCursorLease.java deleted file mode 100644 index ed74a65d..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/reactive/cursor/MongoCursorLease.java +++ /dev/null @@ -1,22 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.reactive.cursor; - -/** - * A borrowed server-side cursor (design §19.1, §32). - * - *

A cursor is server state, not client state: it holds a connection, a snapshot and memory on - * the server until it is exhausted, killed or times out. A stream that ends early — cancelled, - * failed, or simply not fully consumed — leaves that state behind, and enough of them exhaust the - * pool. - * - *

{@link #close()} is idempotent by contract so the guard can call it from every termination - * path without having to work out which one ran first. - */ -public interface MongoCursorLease extends AutoCloseable { - - /** True once the cursor has been released. */ - boolean closed(); - - /** Releases the cursor. Calling it more than once has no further effect. */ - @Override - void close(); -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/reactive/cursor/MongoCursorTermination.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/reactive/cursor/MongoCursorTermination.java deleted file mode 100644 index 4a5a5cb0..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/reactive/cursor/MongoCursorTermination.java +++ /dev/null @@ -1,33 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.reactive.cursor; - -/** - * How a cursor stream ended (design §32). - * - *

Recorded separately from the operation's outcome because the distinctions matter operationally - * and are invisible from the caller's side. Cancellation is normal for a disconnected client; - * lifetime expiry means the consumer is slower than the cursor's budget allows; a query timeout - * means the server gave up. Collapsing all three into "error" hides the only one that is a capacity - * problem. - */ -public enum MongoCursorTermination { - - /** The stream was fully consumed. */ - COMPLETED, - - /** The subscriber cancelled; usually a disconnected client. */ - CANCELLED, - - /** The stream failed. */ - FAILED, - - /** The cursor outlived its configured maximum lifetime. */ - LIFETIME_EXPIRED, - - /** The operation's own deadline fired. */ - OPERATION_TIMEOUT; - - /** True when the termination indicates the consumer could not keep up. */ - public boolean indicatesBackpressureProblem() { - return this == LIFETIME_EXPIRED; - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/reactive/cursor/MongoReactiveCursorPublisher.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/reactive/cursor/MongoReactiveCursorPublisher.java deleted file mode 100644 index 044d3c12..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/reactive/cursor/MongoReactiveCursorPublisher.java +++ /dev/null @@ -1,105 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.reactive.cursor; - -import dev.caskeleton.adapter.outbound.mongo.api.MongoOperationContext; -import dev.caskeleton.adapter.outbound.mongo.query.budget.MongoOperationBudget; -import java.util.Objects; -import java.util.concurrent.atomic.AtomicBoolean; -import org.bson.Document; -import org.springframework.data.mongodb.core.ReactiveMongoOperations; -import org.springframework.data.mongodb.core.convert.MongoConverter; -import org.springframework.data.mongodb.core.query.Query; -import reactor.core.publisher.Flux; - -/** - * A bounded, always-released reactive cursor read (design §32). - * - *

The platform never collects a cursor into a list. A streaming read exists precisely because - * the result does not fit comfortably in memory, and buffering it inside the platform would - * reintroduce the problem the caller was avoiding — with the added twist that the caller cannot see - * it happening. - */ -public final class MongoReactiveCursorPublisher { - - private final MongoCursorGuard guard; - - public MongoReactiveCursorPublisher(MongoCursorGuard guard) { - this.guard = Objects.requireNonNull(guard, "guard"); - } - - /** - * Streams a query's results under the operation's budget. - * - * @param batchSize how many documents the server sends per round trip - */ - public Flux stream( - MongoOperationContext context, - ReactiveMongoOperations operations, - Query query, - Class documentType, - String collection, - MongoOperationBudget budget, - int batchSize) { - Objects.requireNonNull(context, "context"); - Objects.requireNonNull(operations, "operations"); - Objects.requireNonNull(query, "query"); - Objects.requireNonNull(documentType, "documentType"); - Objects.requireNonNull(collection, "collection"); - guard.requireBoundedBatch(budget, batchSize); - - // The server-side limit is applied too, not just the batch size and the time bound. A batch - // size decides how results arrive; it does not decide how many there are. Without a limit a - // query matching far more than the declared budget streamed all of it to the caller, one - // well-behaved batch at a time, and the budget's maxResults was never compared to anything. - // Defensive copy. Spring Data's Query is mutable and these setters return the same instance, - // so this used to reconfigure the caller's object: a Query held as a field and streamed twice - // carried the first call's batch size and deadline into the second, and two concurrent - // subscriptions to the same Query overwrote each other's budget. - int probeLimit = - budget.maxResults() == Integer.MAX_VALUE ? Integer.MAX_VALUE : budget.maxResults() + 1; - Query bounded = - Query.of(query) - .cursorBatchSize(batchSize) - .maxTimeMsec(budget.maxTimeMillis()) - .limit(probeLimit); - MongoConverter converter = operations.getConverter(); - MongoResultBudgetTracker tracker = - new MongoResultBudgetTracker(budget, converter.getCodecRegistry()); - return guard.guard( - TrackingLease::new, - lease -> - Flux.from(operations.find(bounded, documentType, collection)) - // Fetch one probe row beyond maxResults so the client-side guard can distinguish - // "exactly at the bound" from "the query had more". The same conversion used by - // Spring - // Data produces a BSON document for the byte budget. - .doOnNext( - result -> { - Document encoded = new Document(); - converter.write(result, encoded); - tracker.record( - encoded.toBsonDocument(Document.class, converter.getCodecRegistry())); - })); - } - - /** - * The lease for a Spring Data reactive find. - * - *

Spring Data closes the underlying driver cursor when its publisher terminates, so this lease - * records the release rather than performing it. Keeping it in the lease shape means the guard's - * termination handling is identical whether the cursor is driver-managed or platform-managed. - */ - private static final class TrackingLease implements MongoCursorLease { - - private final AtomicBoolean closed = new AtomicBoolean(); - - @Override - public boolean closed() { - return closed.get(); - } - - @Override - public void close() { - closed.set(true); - } - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/reactive/cursor/MongoResultBudgetTracker.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/reactive/cursor/MongoResultBudgetTracker.java deleted file mode 100644 index 758d2bb7..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/reactive/cursor/MongoResultBudgetTracker.java +++ /dev/null @@ -1,88 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.reactive.cursor; - -import dev.caskeleton.adapter.outbound.mongo.api.error.MongoOperationRejectedException; -import dev.caskeleton.adapter.outbound.mongo.query.budget.MongoOperationBudget; -import java.util.Objects; -import java.util.concurrent.atomic.AtomicLong; -import org.bson.BsonDocument; -import org.bson.codecs.EncoderContext; -import org.bson.codecs.configuration.CodecRegistry; -import org.bson.io.BasicOutputBuffer; - -/** - * Counts what a result stream has actually produced, against the budget that declared a bound. - * - *

{@code maxResults} and {@code maxResultBytes} were compared between budgets and intersected - * when two were combined, and never measured against a stream. The cursor publisher applied a batch - * size and a server-side time limit — both of which bound how the results arrive, not how many - * there are — so a query matching far more than the declared bound streamed all of it into the - * caller, one well-behaved batch at a time. - * - *

Byte size is measured by encoding, not estimated. An estimate that is wrong in the cheap - * direction is a bound that does not hold, and the whole point of a byte budget is the case where - * the documents are much larger than anyone expected. - */ -public final class MongoResultBudgetTracker { - - private final MongoOperationBudget budget; - private final CodecRegistry codecs; - private final AtomicLong results = new AtomicLong(); - private final AtomicLong bytes = new AtomicLong(); - - /** - * Creates the tracker. - * - * @param budget the declared result bounds - * @param codecs the registry used to measure encoded size; {@code null} counts results only - */ - public MongoResultBudgetTracker(MongoOperationBudget budget, CodecRegistry codecs) { - this.budget = Objects.requireNonNull(budget, "budget"); - this.codecs = codecs; - } - - /** - * Records one result. - * - * @param document the result as BSON, or {@code null} when only the count is being tracked - * @throws MongoOperationRejectedException when the stream has exceeded its declared bound - */ - public void record(BsonDocument document) { - long seen = results.incrementAndGet(); - if (seen > budget.maxResults()) { - throw MongoOperationRejectedException.of( - "query.result-budget", - "the result stream produced more than the declared " + budget.maxResults() + " results"); - } - if (document == null || codecs == null) { - return; - } - long total = bytes.addAndGet(encodedSizeOf(document)); - if (total > budget.maxResultBytes()) { - throw MongoOperationRejectedException.of( - "query.result-budget", - "the result stream produced more than the declared " - + budget.maxResultBytes() - + " bytes"); - } - } - - /** Results recorded so far. */ - public long results() { - return results.get(); - } - - /** Encoded bytes recorded so far. */ - public long bytes() { - return bytes.get(); - } - - private long encodedSizeOf(BsonDocument document) { - BasicOutputBuffer buffer = new BasicOutputBuffer(); - try (org.bson.BsonBinaryWriter writer = new org.bson.BsonBinaryWriter(buffer)) { - codecs.get(BsonDocument.class).encode(writer, document, EncoderContext.builder().build()); - return buffer.getSize(); - } finally { - buffer.close(); - } - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/transaction/MongoTransactionScope.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/transaction/MongoTransactionScope.java index 9ae3e814..03a996e0 100644 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/transaction/MongoTransactionScope.java +++ b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/transaction/MongoTransactionScope.java @@ -12,8 +12,7 @@ import org.springframework.data.mongodb.core.MongoOperations; * both: the body asks for operations, gets a template already bound to the session, and never sees * the session. * - *

Thread-bound because the imperative path is thread-bound. The reactive path uses Reactor - * Context for the same purpose, since a reactive chain has no stable thread to bind to. + *

Thread-bound because the imperative path is thread-bound. */ public final class MongoTransactionScope { diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/transaction/ReactiveMongoTransactionExecutor.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/transaction/ReactiveMongoTransactionExecutor.java deleted file mode 100644 index bef7501e..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/transaction/ReactiveMongoTransactionExecutor.java +++ /dev/null @@ -1,31 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.transaction; - -import java.util.function.Function; -import org.reactivestreams.Publisher; -import org.springframework.data.mongodb.core.ReactiveMongoOperations; - -/** - * The reactive counterpart of {@link MongoTransactionExecutor} (design §14.2). - * - *

Carries identical retry metadata to the blocking executor. A team that moves a use case from - * one to the other must not have to rediscover that an unknown commit may not be replayed. - * - *

The body receives the session-bound operations. It used to be a {@link - * java.util.function.Supplier}, which gave the caller no way to obtain them: a body that captured - * an ordinary {@code ReactiveMongoTemplate} in its closure — the only template most callers have — - * wrote outside the session entirely, and the executor then committed an empty transaction. The - * writes landed, none of them were atomic, and the method that promised atomicity returned - * successfully. - */ -public interface ReactiveMongoTransactionExecutor { - - /** - * Runs the body in a transaction, retrying and committing according to the profile. - * - * @param work receives the session-bound operations; writes issued through anything else do not - * join the transaction - */ - Publisher execute( - MongoTransactionProfile profile, - Function> work); -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/transaction/ReactiveMongoTransactionSession.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/transaction/ReactiveMongoTransactionSession.java deleted file mode 100644 index ffe70abd..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/transaction/ReactiveMongoTransactionSession.java +++ /dev/null @@ -1,38 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.transaction; - -import java.util.function.Function; -import org.reactivestreams.Publisher; -import org.springframework.data.mongodb.core.ReactiveMongoOperations; -import reactor.core.publisher.Mono; - -/** - * The reactive counterpart of {@link MongoTransactionSession} (design §14.2, §14.3). - * - *

Body and commit stay separate here for the same reason as in the blocking path, and the - * session still never reaches application code: the body is handed session-bound operations - * instead. - */ -public interface ReactiveMongoTransactionSession { - - /** Runs the business body inside this transaction, without committing. */ - /** - * Runs the body against this session's own operations. - * - *

The session supplies the argument; the caller cannot substitute another template. The - * previous signature took a {@code Supplier} and an unused {@code bound} parameter, so the - * binding existed in the signature and nowhere in the behaviour. - */ - Publisher runBody(Function> body); - - /** Session-bound operations the body must use so its writes join the transaction. */ - ReactiveMongoOperations operations(); - - /** Commits this transaction. May be subscribed again after an unknown commit result. */ - Mono commit(); - - /** Aborts this transaction. */ - Mono abort(); - - /** Releases the session. */ - Mono release(); -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/transaction/ReactiveMongoTransactionSessionFactory.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/transaction/ReactiveMongoTransactionSessionFactory.java deleted file mode 100644 index 7cb91360..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/transaction/ReactiveMongoTransactionSessionFactory.java +++ /dev/null @@ -1,16 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.transaction; - -import reactor.core.publisher.Mono; - -/** - * Opens a reactive session with a started transaction (design §14.3). - * - *

Returns a {@link Mono} so the session is opened at subscription time. Opening it eagerly would - * leak a server-side session whenever the resulting chain is assembled but never subscribed — which - * happens routinely in a reactive codebase. - */ -public interface ReactiveMongoTransactionSessionFactory { - - /** Opens a session and starts a transaction under the profile's consistency and timeout. */ - Mono open(MongoTransactionProfile profile); -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/transaction/SpringReactiveMongoTransactionExecutor.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/transaction/SpringReactiveMongoTransactionExecutor.java deleted file mode 100644 index 6d96b51e..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/transaction/SpringReactiveMongoTransactionExecutor.java +++ /dev/null @@ -1,175 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.transaction; - -import dev.caskeleton.adapter.outbound.mongo.api.MongoOperationName; -import dev.caskeleton.adapter.outbound.mongo.api.error.MongoTransactionCommitUnknownException; -import dev.caskeleton.adapter.outbound.mongo.api.error.MongoTransactionTransientException; -import dev.caskeleton.adapter.outbound.mongo.transaction.retry.MongoCommitReconciler; -import dev.caskeleton.adapter.outbound.mongo.transaction.retry.MongoRetryBudget; -import dev.caskeleton.adapter.outbound.mongo.transaction.retry.MongoRetryDecision; -import java.time.Duration; -import java.util.Objects; -import java.util.function.Consumer; -import java.util.random.RandomGenerator; -import org.reactivestreams.Publisher; -import org.springframework.data.mongodb.core.ReactiveMongoOperations; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; - -/** - * The reactive transaction entry point, with the same retry rule as the blocking one (design - * §14.3). - * - *

Body retry re-subscribes the caller's publisher from a fresh session. Commit retry - * re-subscribes only {@code commit()} — the body's publisher is never touched again, because - * re-subscribing a publisher is exactly how a reactive codebase replays work that may already have - * been committed. - * - *

The session is released on every path, including cancellation, through {@link Flux#usingWhen}. - */ -public final class SpringReactiveMongoTransactionExecutor - implements ReactiveMongoTransactionExecutor { - - private final ReactiveMongoTransactionSessionFactory sessions; - - private final MongoRetryBudget budget; - - private final MongoCommitReconciler reconciler; - - private final RandomGenerator random; - - private final Consumer decisionRecorder; - - private final MongoOperationName operationName; - - /** - * Where elapsed time comes from. - * - *

Every budget check passed {@code Duration.ZERO.plusNanos(1)} as the elapsed time, so {@code - * maxElapsed} was compared against one nanosecond on every attempt and could never be reached. - * The caller's deadline was a number the budget held and never used. - */ - private final java.util.function.LongSupplier nanoTime; - - public SpringReactiveMongoTransactionExecutor( - ReactiveMongoTransactionSessionFactory sessions, - MongoRetryBudget budget, - MongoCommitReconciler reconciler, - RandomGenerator random, - Consumer decisionRecorder, - MongoOperationName operationName) { - this(sessions, budget, reconciler, random, decisionRecorder, operationName, System::nanoTime); - } - - /** - * Creates the executor. - * - * @param nanoTime the monotonic clock the deadline is measured against; a test supplies a virtual - * one so a budget can be exhausted without waiting for it - */ - public SpringReactiveMongoTransactionExecutor( - ReactiveMongoTransactionSessionFactory sessions, - MongoRetryBudget budget, - MongoCommitReconciler reconciler, - RandomGenerator random, - Consumer decisionRecorder, - MongoOperationName operationName, - java.util.function.LongSupplier nanoTime) { - this.sessions = Objects.requireNonNull(sessions, "sessions"); - this.budget = Objects.requireNonNull(budget, "budget"); - this.reconciler = Objects.requireNonNull(reconciler, "reconciler"); - this.random = Objects.requireNonNull(random, "random"); - this.decisionRecorder = Objects.requireNonNull(decisionRecorder, "decisionRecorder"); - this.operationName = Objects.requireNonNull(operationName, "operationName"); - this.nanoTime = Objects.requireNonNull(nanoTime, "nanoTime"); - } - - /** An executor over the platform's standard retry budget and reconciler. */ - public static SpringReactiveMongoTransactionExecutor standard( - ReactiveMongoTransactionSessionFactory sessions, String operationName) { - return new SpringReactiveMongoTransactionExecutor( - sessions, - MongoRetryBudget.standard(), - MongoCommitReconciler.standard(), - RandomGenerator.getDefault(), - decision -> {}, - new MongoOperationName(operationName)); - } - - @Override - public Publisher execute( - MongoTransactionProfile profile, - java.util.function.Function> work) { - Objects.requireNonNull(profile, "profile"); - Objects.requireNonNull(work, "work"); - // The deadline starts at subscription, not at assembly: a publisher assembled and subscribed - // much later would otherwise begin with its budget already spent. - return Flux.defer(() -> attempt(profile, work, 1, nanoTime.getAsLong())); - } - - private Flux attempt( - MongoTransactionProfile profile, - java.util.function.Function> work, - int attempt, - long startedAtNanos) { - - return Flux.usingWhen( - sessions.open(profile), - session -> - Flux.from(session.runBody(work)) - .collectList() - .flatMapMany( - values -> - commitWithRetry(session, 1, startedAtNanos) - .thenMany(Flux.fromIterable(values))), - ReactiveMongoTransactionSession::release, - // Cleanup is phase-aware. A commit whose outcome is unknown must not be aborted: - // aborting a transaction that may have committed either fails against a session the - // server has already closed, or replaces the one error the caller needs to reconcile - // with a different one. - (session, failure) -> - failure instanceof MongoTransactionCommitUnknownException - ? session.release() - : session.abort().then(session.release()), - session -> session.abort().then(session.release())) - .onErrorResume( - MongoTransactionTransientException.class, - transientFailure -> { - Duration elapsed = elapsedSince(startedAtNanos); - if (!budget.allowsAttempt(attempt + 1, elapsed)) { - return Flux.error(transientFailure); - } - // Computed once. Calling delayBefore twice produced two different jittered values, - // so the delay a metric recorded was never the delay that was actually waited. - Duration delay = budget.delayBefore(attempt + 1, random); - decisionRecorder.accept(MongoRetryDecision.retryBody(delay)); - return Mono.delay(delay) - .thenMany(attempt(profile, work, attempt + 1, startedAtNanos)); - }); - } - - private Mono commitWithRetry( - ReactiveMongoTransactionSession session, int commitAttempt, long startedAtNanos) { - return session - .commit() - .onErrorResume( - MongoTransactionCommitUnknownException.class, - unknown -> { - if (!budget.allowsAttempt(commitAttempt + 1, elapsedSince(startedAtNanos))) { - decisionRecorder.accept(MongoRetryDecision.reconcile("commit remained unknown")); - return Mono.error( - new MongoTransactionCommitUnknownException( - unknown.failureContext(), - reconciler.reconciliationHintFor(operationName.value()))); - } - Duration delay = budget.delayBefore(commitAttempt + 1, random); - decisionRecorder.accept(MongoRetryDecision.retryCommit(delay)); - return Mono.delay(delay) - .then(commitWithRetry(session, commitAttempt + 1, startedAtNanos)); - }); - } - - private Duration elapsedSince(long startedAtNanos) { - long elapsed = nanoTime.getAsLong() - startedAtNanos; - return elapsed <= 0L ? Duration.ZERO : Duration.ofNanos(elapsed); - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/transaction/SpringReactiveMongoTransactionSessionFactory.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/transaction/SpringReactiveMongoTransactionSessionFactory.java deleted file mode 100644 index b6ef0091..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/transaction/SpringReactiveMongoTransactionSessionFactory.java +++ /dev/null @@ -1,214 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.transaction; - -import com.mongodb.ClientSessionOptions; -import com.mongodb.ReadConcern; -import com.mongodb.ReadConcernLevel; -import com.mongodb.ReadPreference; -import com.mongodb.TransactionOptions; -import com.mongodb.WriteConcern; -import com.mongodb.reactivestreams.client.ClientSession; -import dev.caskeleton.adapter.outbound.mongo.api.MongoOperationName; -import dev.caskeleton.adapter.outbound.mongo.api.MongoOperationType; -import dev.caskeleton.adapter.outbound.mongo.api.consistency.MongoConsistencyDescriptor; -import dev.caskeleton.adapter.outbound.mongo.api.consistency.MongoConsistencyRegistry; -import dev.caskeleton.adapter.outbound.mongo.api.error.MongoFailureContext; -import dev.caskeleton.adapter.outbound.mongo.api.error.MongoRetryScope; -import dev.caskeleton.adapter.outbound.mongo.api.error.MongoTransactionCommitUnknownException; -import dev.caskeleton.adapter.outbound.mongo.api.error.MongoTransactionTransientException; -import dev.caskeleton.adapter.outbound.mongo.failure.DefaultMongoFailureClassifier; -import dev.caskeleton.adapter.outbound.mongo.failure.MongoDriverFailureView; -import dev.caskeleton.adapter.outbound.mongo.failure.MongoFailureClassifier; -import dev.caskeleton.adapter.outbound.mongo.failure.MongoFailureExtractor; -import dev.caskeleton.adapter.outbound.mongo.failure.MongoFailurePhase; -import java.time.Duration; -import java.util.Objects; -import java.util.concurrent.TimeUnit; -import java.util.function.Function; -import org.reactivestreams.Publisher; -import org.springframework.data.mongodb.core.ReactiveMongoOperations; -import org.springframework.data.mongodb.core.ReactiveMongoTemplate; -import reactor.core.publisher.Mono; - -/** - * Opens reactive driver sessions, keeping body and commit separate (design §14.2, §14.3). - * - *

Built on the driver's reactive session rather than on {@code - * ReactiveMongoTemplate.inTransaction}, which commits implicitly. The design's retry rule needs the - * commit to be a step the platform can repeat on its own, without the body coming with it. - */ -public final class SpringReactiveMongoTransactionSessionFactory - implements ReactiveMongoTransactionSessionFactory { - - private static final MongoOperationName SESSION_OPERATION = - new MongoOperationName("transaction.reactive-session"); - - private final ReactiveMongoTemplate template; - - private final MongoConsistencyRegistry consistency; - - private final MongoFailureClassifier classifier; - - public SpringReactiveMongoTransactionSessionFactory( - ReactiveMongoTemplate template, MongoConsistencyRegistry consistency) { - this(template, consistency, new DefaultMongoFailureClassifier()); - } - - public SpringReactiveMongoTransactionSessionFactory( - ReactiveMongoTemplate template, - MongoConsistencyRegistry consistency, - MongoFailureClassifier classifier) { - this.template = Objects.requireNonNull(template, "template"); - this.consistency = Objects.requireNonNull(consistency, "consistency"); - this.classifier = Objects.requireNonNull(classifier, "classifier"); - } - - @Override - public Mono open(MongoTransactionProfile profile) { - Objects.requireNonNull(profile, "profile"); - MongoConsistencyDescriptor descriptor = consistency.require(profile.consistency()); - return Mono.from( - template - .getMongoDatabaseFactory() - .getSession( - ClientSessionOptions.builder() - .causallyConsistent(descriptor.requiresCausalSession()) - .defaultTransactionOptions( - transactionOptions(descriptor, profile.timeout())) - .build())) - .flatMap( - session -> { - // Same acquisition leak as the imperative factory, with one extra way in: a - // subscriber that cancels between the session arriving and startTransaction running - // leaves the session open and unreferenced. `Mono.fromCallable` puts the start inside - // the reactive contract, and the error path closes what the success path would have - // owned. - return Mono.fromCallable( - () -> { - session.startTransaction(); - return (ReactiveMongoTransactionSession) - new DriverBackedReactiveSession( - session, template.withSession(session), classifier); - }) - .onErrorResume( - startFailed -> - Mono.from(session.abortTransaction()) - .onErrorResume(ignored -> Mono.empty()) - .then(Mono.fromRunnable(session::close)) - .then(Mono.error(startFailed))) - .doOnCancel(session::close); - }); - } - - private static TransactionOptions transactionOptions( - MongoConsistencyDescriptor descriptor, Duration timeout) { - return TransactionOptions.builder() - .readPreference(ReadPreference.primary()) - .readConcern(new ReadConcern(ReadConcernLevel.fromString(descriptor.readConcern()))) - .writeConcern( - "majority".equals(descriptor.writeConcern()) - ? WriteConcern.MAJORITY - : WriteConcern.ACKNOWLEDGED) - .maxCommitTime(timeout.toMillis(), TimeUnit.MILLISECONDS) - .build(); - } - - /** One reactive driver session. */ - private static final class DriverBackedReactiveSession - implements ReactiveMongoTransactionSession { - - private final ClientSession session; - - private final ReactiveMongoOperations bound; - - private final MongoFailureClassifier classifier; - - private DriverBackedReactiveSession( - ClientSession session, ReactiveMongoOperations bound, MongoFailureClassifier classifier) { - this.session = session; - this.bound = bound; - this.classifier = classifier; - } - - @Override - public Publisher runBody( - Function> body) { - // `bound` is this session's operations, and it is what the body is handed. The previous - // implementation accepted an operations argument and ignored it, calling `Supplier::get` — - // so a body that captured an ordinary template wrote outside the session and the executor - // committed a transaction containing nothing. - return Mono.defer(() -> Mono.from(body.apply(bound))) - .onErrorMap( - Throwable.class, failure -> translate(failure, MongoFailurePhase.TRANSACTION_BODY)); - } - - @Override - public ReactiveMongoOperations operations() { - return bound; - } - - @Override - public Mono commit() { - return Mono.from(session.commitTransaction()) - .onErrorMap( - Throwable.class, failure -> translate(failure, MongoFailurePhase.TRANSACTION_COMMIT)) - .then(); - } - - @Override - public Mono abort() { - return Mono.from(session.abortTransaction()).onErrorResume(failure -> Mono.empty()).then(); - } - - @Override - public Mono release() { - return Mono.fromRunnable(session::close); - } - - /** - * Classifies whatever the driver or Spring Data handed back. - * - *

Takes a {@code Throwable}, not a {@code MongoException}. Spring Data wraps driver failures - * in its own hierarchy on most paths, and a wrapped failure carries the same error labels and - * server code — but arriving as another type it skipped classification entirely, so a transient - * transaction error Spring had wrapped was treated as terminal and never retried. - */ - private RuntimeException translate(Throwable failure, MongoFailurePhase phase) { - MongoDriverFailureView view = MongoFailureExtractor.viewOf(failure).orElse(null); - if (view == null) { - // Not a Mongo failure, or a cause chain that cannot be walked. Terminal is the fail-closed - // verdict when the alternative is replaying work. - return failure instanceof RuntimeException runtime - ? runtime - : new IllegalStateException("unclassifiable Mongo failure", failure); - } - // Phase-aware, like the imperative session: the same failure is a body replay before the - // commit and a commit-unknown during it. - MongoRetryScope scope = - classifier - .classify( - phase == MongoFailurePhase.TRANSACTION_COMMIT - ? MongoOperationType.TRANSACTION_COMMIT - : MongoOperationType.UPDATE, - phase, - view) - .retryScope(); - String serverCode = view.hasServerCode() ? Integer.toString(view.serverCode()) : ""; - // The context is derived from the scope, not built first and then labelled. Building a - // commit-unknown context and wrapping it in whichever exception the classifier chose is how - // a "replay the body" exception came to carry "unknown commit, not retryable, ambiguous". - if (scope == MongoRetryScope.COMMIT_ONLY) { - return new MongoTransactionCommitUnknownException( - MongoFailureContext.commitUnknown(SESSION_OPERATION, serverCode, Duration.ZERO), - "read the transaction record, version or idempotency key"); - } - if (scope == MongoRetryScope.WHOLE_TRANSACTION) { - return new MongoTransactionTransientException( - MongoFailureContext.transientTransaction(SESSION_OPERATION, serverCode, Duration.ZERO)); - } - // Classified as neither commit-only nor whole-transaction: propagate what arrived. - return failure instanceof RuntimeException runtime - ? runtime - : new IllegalStateException("unretryable Mongo failure", failure); - } - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/transaction/session/ReactiveMongoCausalSessionExecutor.java b/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/transaction/session/ReactiveMongoCausalSessionExecutor.java deleted file mode 100644 index 795c67ae..00000000 --- a/src/adapter/outbound/persistence-mongo/src/main/java/dev/caskeleton/adapter/outbound/mongo/transaction/session/ReactiveMongoCausalSessionExecutor.java +++ /dev/null @@ -1,69 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.transaction.session; - -import com.mongodb.ClientSessionOptions; -import com.mongodb.reactivestreams.client.ClientSession; -import dev.caskeleton.adapter.outbound.mongo.api.consistency.MongoConsistencyProfile; -import dev.caskeleton.adapter.outbound.mongo.reactive.ReactiveMongoContextKeys; -import java.util.Objects; -import java.util.function.Function; -import org.reactivestreams.Publisher; -import org.springframework.data.mongodb.core.ReactiveMongoOperations; -import org.springframework.data.mongodb.core.ReactiveMongoTemplate; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; - -/** - * The reactive causal session scope (design §14, §26). - * - *

The session travels in Reactor Context rather than a thread-local, because a reactive chain - * has no stable thread. {@link Flux#usingWhen} releases it on completion, error and cancellation — - * and cancellation is not the exceptional case here, it is what happens whenever a client - * disconnects. - */ -public final class ReactiveMongoCausalSessionExecutor { - - private final ReactiveMongoTemplate template; - - private final MongoCausalSessionContext context; - - public ReactiveMongoCausalSessionExecutor(ReactiveMongoTemplate template) { - this(template, MongoCausalSessionContext.forProfile(MongoConsistencyProfile.CAUSAL_MAJORITY)); - } - - public ReactiveMongoCausalSessionExecutor( - ReactiveMongoTemplate template, MongoCausalSessionContext context) { - this.template = Objects.requireNonNull(template, "template"); - this.context = Objects.requireNonNull(context, "context"); - } - - /** - * Runs the body inside a causal session, handing it session-bound operations. - * - * @param body receives operations already bound to the session - */ - public Flux execute(Function> body) { - Objects.requireNonNull(body, "body"); - return Flux.usingWhen( - Mono.from( - template - .getMongoDatabaseFactory() - .getSession(ClientSessionOptions.builder().causallyConsistent(true).build())), - session -> - Flux.from(body.apply(template.withSession(session))) - .contextWrite( - reactorContext -> - reactorContext.put(ReactiveMongoContextKeys.CAUSAL_SESSION, session)), - ReactiveMongoCausalSessionExecutor::release, - (session, failure) -> release(session), - ReactiveMongoCausalSessionExecutor::release); - } - - private static Mono release(ClientSession session) { - return Mono.fromRunnable(session::close); - } - - /** The consistency contract this executor enforces. */ - public MongoCausalSessionContext context() { - return context; - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/main/resources/META-INF/spring.factories b/src/adapter/outbound/persistence-mongo/src/main/resources/META-INF/spring.factories index f841a589..6c117720 100644 --- a/src/adapter/outbound/persistence-mongo/src/main/resources/META-INF/spring.factories +++ b/src/adapter/outbound/persistence-mongo/src/main/resources/META-INF/spring.factories @@ -1,2 +1,2 @@ -org.springframework.boot.autoconfigure.AutoConfigurationImportFilter=\ -dev.caskeleton.adapter.outbound.mongo.MongoOptInAutoConfigurationImportFilter +org.springframework.boot.EnvironmentPostProcessor=\ +dev.caskeleton.adapter.outbound.mongo.MongoDefaultsEnvironmentPostProcessor diff --git a/src/adapter/outbound/persistence-mongo/src/main/resources/config/mongo.yml b/src/adapter/outbound/persistence-mongo/src/main/resources/config/mongo.yml new file mode 100644 index 00000000..4e5f3870 --- /dev/null +++ b/src/adapter/outbound/persistence-mongo/src/main/resources/config/mongo.yml @@ -0,0 +1,36 @@ +# MongoDB capability 설정 기본값. +# +# 이 모듈이 직접 읽는다(MongoDefaultsEnvironmentPostProcessor). 우선순위는 가장 낮아서 +# application*.yml, 환경 변수, 시스템 속성이 항상 이긴다. 이 모듈을 빌드에서 빼면 이 파일도 함께 +# 빠진다. Registry SSOT: docs/registries/env-keys.yaml. +ca-skeleton: + persistence-mongo: + # true | false — 모듈이 있으면 켜진다. false 로 끄면 Spring Boot 의 Mongo 자동 설정도 함께 빠진다. + enabled: ${APP_PERSISTENCE_MONGO_ENABLED:true} + # 켠 상태에서 비어 있으면 안 된다. profile 은 정확히 하나: client 하나와 pool 하나만 만들고, + # 고르지 않은 profile 의 secret 은 해석하지 않는다. + active-profile: ${APP_PERSISTENCE_MONGO_ACTIVE_PROFILE:} + # 연결 source 도 명시해야 한다. 표준 배포는 SPRING_MONGODB_URI(Boot 4 -> spring.mongodb.uri)를 + # 준다. typed-profile 배포는 대신 + # ca-skeleton.persistence-mongo.platform.profiles..uri-secret 을 주고 + # MongoCredentialResolver bean 을 제공한다. 둘 다 없으면 driver 의 localhost 기본값을 쓰지 않고 + # 기동을 거절한다. + # + # production profile 전체 예시(MongoProfileProperties 14개 항목): + # platform: + # profiles: + # production: + # uri-secret: secret://mongo/production + # topology: REPLICA_SET + # production: true + # stable-api-strict: true + # server-selection-timeout: 3s + # connect-timeout: 2s + # socket-read-timeout: 5s + # operation-timeout: 3s + # pool-min-size: 2 + # pool-max-size: 40 + # pool-max-wait-time: 500ms + # uuid-representation: STANDARD + # tls-required: true + # authentication-required: true diff --git a/src/adapter/outbound/persistence-mongo/src/mongoProviderTestkit/java/dev/caskeleton/adapter/outbound/mongo/testkit/atlas/MongoAtlasLocalContainer.java b/src/adapter/outbound/persistence-mongo/src/mongoProviderTestkit/java/dev/caskeleton/adapter/outbound/mongo/testkit/atlas/MongoAtlasLocalContainer.java deleted file mode 100644 index 3c600c75..00000000 --- a/src/adapter/outbound/persistence-mongo/src/mongoProviderTestkit/java/dev/caskeleton/adapter/outbound/mongo/testkit/atlas/MongoAtlasLocalContainer.java +++ /dev/null @@ -1,55 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.testkit.atlas; - -import java.util.Objects; -import org.testcontainers.mongodb.MongoDBAtlasLocalContainer; -import org.testcontainers.utility.DockerImageName; - -/** - * Atlas Local, for fast search and vector contracts (advanced plan Task 14). - * - *

Useful for pull-request feedback and explicitly not sufficient for release. Analyzer - * behaviour, index build timing and KMS integration are all provider-side, and Atlas Local - * reproduces none of them faithfully enough to certify against. - */ -public final class MongoAtlasLocalContainer implements AutoCloseable { - - /** System property carrying the pinned Atlas Local image. */ - public static final String IMAGE_PROPERTY = "mongodb.atlas.local.image"; - - private final MongoDBAtlasLocalContainer container; - - private MongoAtlasLocalContainer(String image) { - this.container = new MongoDBAtlasLocalContainer(DockerImageName.parse(image)); - } - - /** An Atlas Local container on the pinned image. */ - public static MongoAtlasLocalContainer pinned() { - return new MongoAtlasLocalContainer( - System.getProperty(IMAGE_PROPERTY, "mongodb/mongodb-atlas-local:8.0.0")); - } - - /** An explicitly pinned image. */ - public static MongoAtlasLocalContainer image(String pinnedImage) { - return new MongoAtlasLocalContainer(Objects.requireNonNull(pinnedImage, "pinnedImage")); - } - - /** Starts the container. */ - public void start() { - container.start(); - } - - /** The connection string. */ - public String connectionString() { - return container.getConnectionString(); - } - - /** Which environment a report from this container should record. */ - public MongoAtlasCapabilityContractSuite.Environment environment() { - return MongoAtlasCapabilityContractSuite.Environment.ATLAS_LOCAL; - } - - @Override - public void close() { - container.stop(); - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/MongoCapabilityActivationTest.java b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/MongoCapabilityActivationTest.java new file mode 100644 index 00000000..429c2236 --- /dev/null +++ b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/MongoCapabilityActivationTest.java @@ -0,0 +1,93 @@ +package dev.caskeleton.adapter.outbound.mongo; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import com.mongodb.client.MongoClient; +import java.util.Arrays; +import org.junit.jupiter.api.Test; +import org.springframework.boot.WebApplicationType; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.mongodb.core.MongoTemplate; +import org.springframework.util.ClassUtils; + +/** + * The capability as an application gets it: this module on the classpath, auto-configuration on. + * + *

A real {@code SpringApplication}, because the module's settings and its explicit-off exclusion + * arrive through its environment post-processor, which a context runner never calls. Creating the + * client does not connect, so no server is needed. + */ +class MongoCapabilityActivationTest { + + @Test + void presentModuleIsOn() { + try (ConfigurableApplicationContext context = + start( + "--APP_PERSISTENCE_MONGO_ACTIVE_PROFILE=standard-uri", + "--spring.mongodb.uri=mongodb://localhost:1/portfolio")) { + assertThat(context.getBean(MongoPersistenceSettings.class).isEnabled()).isTrue(); + assertThat(context.getBeanNamesForType(MongoClient.class)).hasSize(1); + assertThat(context.getBeanNamesForType(MongoTemplate.class)).hasSize(1); + } + } + + @Test + void switchedOffHoldsNoClientTemplateOrPlatformBean() { + try (ConfigurableApplicationContext context = + start( + "--APP_PERSISTENCE_MONGO_ENABLED=false", + "--spring.mongodb.uri=mongodb://localhost:1/portfolio")) { + assertThat(context.getBeanNamesForType(MongoClient.class)).isEmpty(); + assertThat(context.getBeanNamesForType(MongoTemplate.class)).isEmpty(); + assertThat( + Arrays.stream(context.getBeanDefinitionNames()) + .map(name -> context.getBeanFactory().getType(name, false)) + .filter(type -> type != null && type != Application.class) + .map(ClassUtils::getUserClass) + .map(Class::getName) + .filter( + name -> + name.startsWith("dev.caskeleton.adapter.outbound.mongo.") + || name.startsWith("org.springframework.boot.mongodb.") + || name.startsWith("org.springframework.boot.data.mongodb."))) + .isEmpty(); + } + } + + @Test + void anExplicitOffKeepsTheDeploymentsOwnExclusions() { + try (ConfigurableApplicationContext context = + start( + "--APP_PERSISTENCE_MONGO_ENABLED=false", + "--spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.task.TaskSchedulingAutoConfiguration")) { + assertThat(context.getEnvironment().getProperty("spring.autoconfigure.exclude")) + .contains("org.springframework.boot.autoconfigure.task.TaskSchedulingAutoConfiguration") + .contains("org.springframework.boot.mongodb.autoconfigure.MongoAutoConfiguration"); + } + } + + @Test + void anOnModuleWithNoConnectionSourceDoesNotStart() { + Throwable failure = + catchThrowable(() -> start("--APP_PERSISTENCE_MONGO_ACTIVE_PROFILE=primary")); + + assertThat(failure) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("spring.mongodb.uri"); + } + + private static ConfigurableApplicationContext start(String... arguments) { + return new SpringApplicationBuilder(Application.class) + .web(WebApplicationType.NONE) + .logStartupInfo(false) + .run(arguments); + } + + @Configuration(proxyBeanMethods = false) + @EnableAutoConfiguration + static class Application {} +} diff --git a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/MongoConnectionSourceRuleTest.java b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/MongoConnectionSourceRuleTest.java new file mode 100644 index 00000000..4fbbcd25 --- /dev/null +++ b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/MongoConnectionSourceRuleTest.java @@ -0,0 +1,69 @@ +package dev.caskeleton.adapter.outbound.mongo; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.mock.env.MockEnvironment; + +/** An on Mongo module names one profile and an explicit connection source, or it does not start. */ +class MongoConnectionSourceRuleTest { + + @Test + void anOnModuleWithoutAProfileIsRefusedNamingTheProperty() { + Throwable failure = catchThrowable(() -> postProcess(Map.of())); + + assertThat(failure) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ca-skeleton.persistence-mongo.active-profile"); + } + + @Test + void anOnModuleWithoutAConnectionSourceIsRefusedNamingBothSources() { + Throwable failure = + catchThrowable( + () -> postProcess(Map.of("ca-skeleton.persistence-mongo.active-profile", "primary"))); + + assertThat(failure) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("spring.mongodb.uri") + .hasMessageContaining("ca-skeleton.persistence-mongo.platform.profiles.primary.uri-secret"); + } + + @ParameterizedTest + @ValueSource( + strings = { + "spring.mongodb.uri", + "ca-skeleton.persistence-mongo.platform.profiles.primary.uri-secret" + }) + void eitherConnectionSourceSatisfiesTheRule(String source) { + Throwable failure = + catchThrowable( + () -> + postProcess( + Map.of( + "ca-skeleton.persistence-mongo.active-profile", + "primary", + source, + "mongodb://db.example:27017/app"))); + + assertThat(failure).isNull(); + } + + @Test + void anExplicitlyOffModuleIsNotAskedForAConnection() { + Throwable failure = + catchThrowable(() -> postProcess(Map.of("ca-skeleton.persistence-mongo.enabled", "false"))); + + assertThat(failure).isNull(); + } + + private static void postProcess(Map properties) { + MockEnvironment environment = new MockEnvironment(); + properties.forEach(environment::setProperty); + new MongoDefaultsEnvironmentPostProcessor().postProcessEnvironment(environment, null); + } +} diff --git a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/MongoPersistenceConfigTest.java b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/MongoPersistenceConfigTest.java index c4e9384a..9db28254 100644 --- a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/MongoPersistenceConfigTest.java +++ b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/MongoPersistenceConfigTest.java @@ -20,25 +20,12 @@ class MongoPersistenceConfigTest { .withPropertyValues("spring.mongodb.database=portfolio"); @Test - void disabledByDefaultCreatesNoMongoInfrastructure() { - runner.run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context).doesNotHaveBean(MongoClient.class); - assertThat(context).doesNotHaveBean(MongoTemplate.class); - }); - } - - @Test - void explicitlyDisabledCreatesNoMongoInfrastructure() { - runner - .withPropertyValues("ca-skeleton.persistence-mongo.enabled=false") + void theSwitchDefaultsToOn() { + new ApplicationContextRunner() + .withUserConfiguration(PropertiesOnly.class) .run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context).doesNotHaveBean(MongoClient.class); - assertThat(context).doesNotHaveBean(MongoTemplate.class); - }); + context -> + assertThat(context.getBean(MongoPersistenceSettings.class).isEnabled()).isTrue()); } @Test diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/MongoShippedCompositionContractTest.java b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/MongoReactiveDriverAbsenceTest.java similarity index 62% rename from src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/MongoShippedCompositionContractTest.java rename to src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/MongoReactiveDriverAbsenceTest.java index 65751a06..97eacbd0 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/MongoShippedCompositionContractTest.java +++ b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/MongoReactiveDriverAbsenceTest.java @@ -1,14 +1,15 @@ -package dev.caskeleton.bootstrap.contract; +package dev.caskeleton.adapter.outbound.mongo; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; import org.springframework.util.ClassUtils; -class MongoShippedCompositionContractTest { +/** The module brings one Mongo client and pool: the imperative one. */ +class MongoReactiveDriverAbsenceTest { @Test - void shippedCompositionCarriesTheReactiveApiButNotTheReactiveDriver() { + void theModuleCarriesTheReactiveApiButNotTheReactiveDriver() { ClassLoader classLoader = getClass().getClassLoader(); // Spring Data MongoDB packages imperative and reactive templates in the same artifact, so the @@ -18,8 +19,8 @@ class MongoShippedCompositionContractTest { "org.springframework.data.mongodb.core.ReactiveMongoTemplate", classLoader)) .isTrue(); - // The default app-bootstrap explicitly excludes the reactive-streams Mongo driver. Without it, - // Boot cannot construct the ReactiveMongoTemplate bean required by ReactiveExecution. + // No reactive starter and no reactive-streams driver, so Boot's reactive auto-configuration + // cannot build a second client and pool beside the imperative one. assertThat(ClassUtils.isPresent("com.mongodb.reactivestreams.client.MongoClient", classLoader)) .isFalse(); } diff --git a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/advanced/MongoAdvancedCapabilityGuardTest.java b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/advanced/MongoAdvancedCapabilityGuardTest.java new file mode 100644 index 00000000..4841d233 --- /dev/null +++ b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/advanced/MongoAdvancedCapabilityGuardTest.java @@ -0,0 +1,43 @@ +package dev.caskeleton.adapter.outbound.mongo.advanced; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.adapter.outbound.mongo.advanced.tenancy.database.MongoTenantClientRegistry; +import dev.caskeleton.adapter.outbound.mongo.api.capability.MongoCapability; +import dev.caskeleton.adapter.outbound.mongo.api.error.MongoOperationRejectedException; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +@Tag("mongodb-contract") +class MongoAdvancedCapabilityGuardTest { + + @Test + void anEntryPointIsRefusedWhileItsCapabilityIsDisabled() { + // given + MongoAdvancedCapabilityGuard guard = MongoAdvancedCapabilityGuard.allDisabled(); + + // when + Throwable refused = catchThrowable(() -> new MongoTenantClientRegistry(guard, 1)); + + // then + assertThat(refused) + .isInstanceOf(MongoOperationRejectedException.class) + .hasMessageContaining("DATABASE_PER_TENANT is an opt-in Advanced module"); + } + + @Test + void anEntryPointIsBuiltOnceItsCapabilityIsEnabled() { + // given + MongoAdvancedCapabilityGuard guard = + new MongoAdvancedCapabilityGuard( + MongoAdvancedCapabilityFlags.allDisabled() + .withEnabled(MongoCapability.DATABASE_PER_TENANT)); + + // when + MongoTenantClientRegistry registry = new MongoTenantClientRegistry(guard, 1); + + // then + assertThat(registry.activeCount()).isZero(); + } +} diff --git a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/advanced/MongoAdvancedPromotionGateTest.java b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/advanced/MongoAdvancedPromotionGateTest.java deleted file mode 100644 index cce5a22c..00000000 --- a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/advanced/MongoAdvancedPromotionGateTest.java +++ /dev/null @@ -1,97 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.advanced; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.outbound.mongo.api.capability.MongoCapability; -import dev.caskeleton.adapter.outbound.mongo.api.error.MongoOperationRejectedException; -import dev.caskeleton.adapter.outbound.mongo.testkit.atlas.MongoAtlasCapabilityContractSuite; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -/** Advanced plan Tasks 1, 14, 15 — promotion needs real-environment evidence, and stays opt-in. */ -@Tag("mongodb-contract") -class MongoAdvancedPromotionGateTest { - - private final MongoAdvancedPromotionGate gate = new MongoAdvancedPromotionGate(); - - @Test - void everyPromotionRequiresActualEnvironmentEvidence() { - MongoAdvancedPromotionEvidence evidence = MongoAdvancedPromotionEvidence.fixture(); - - assertThat(evidence.requiredCategories()) - .contains("actual-topology", "security", "migration", "failure", "runbook"); - } - - @Test - void anIncompleteEvidencePackageStopsPromotion() { - MongoAdvancedPromotionEvidence evidence = - MongoAdvancedPromotionEvidence.fixture() - .with("stable-platform") - .with("security") - .with("failure") - .with("runbook"); - - assertThatThrownBy(() -> gate.verify(evidence)) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("actual-topology"); - assertThat(gate.passes(evidence)).isFalse(); - } - - @Test - void aCompleteEvidencePackagePasses() { - MongoAdvancedPromotionEvidence evidence = - MongoAdvancedPromotionEvidence.fixture() - .with("stable-platform") - .with("actual-topology") - .with("security") - .with("migration") - .with("failure") - .with("runbook"); - - assertThatCode(() -> gate.verify(evidence)).doesNotThrowAnyException(); - assertThat(gate.passes(evidence)).isTrue(); - } - - @Test - void promotionDoesNotAddTheCapabilityToTheStableStarter() { - assertThat(gate.addsStarterDependency()).isFalse(); - } - - @Test - void everyAdvancedCapabilityIsOffUntilExplicitlyEnabled() { - MongoAdvancedCapabilityFlags flags = MongoAdvancedCapabilityFlags.allDisabled(); - - assertThat(flags.isEnabled(MongoCapability.SHARDING)).isFalse(); - assertThatThrownBy(() -> flags.require(MongoCapability.SHARDING)) - .isInstanceOf(MongoOperationRejectedException.class) - .hasMessageContaining("ca-skeleton.persistence-mongo.advanced.sharding.enabled"); - assertThatCode( - () -> flags.withEnabled(MongoCapability.SHARDING).require(MongoCapability.SHARDING)) - .doesNotThrowAnyException(); - } - - @Test - void atlasLocalIsNotReleaseEvidence() { - MongoAtlasCapabilityContractSuite.MongoAtlasCapabilityReport local = - MongoAtlasCapabilityContractSuite.vectorReadiness( - false, MongoAtlasCapabilityContractSuite.Environment.ATLAS_LOCAL); - MongoAtlasCapabilityContractSuite.MongoAtlasCapabilityReport target = - MongoAtlasCapabilityContractSuite.vectorReadiness( - false, MongoAtlasCapabilityContractSuite.Environment.ACTUAL_TARGET); - - assertThat(local.certifies()).isFalse(); - assertThat(target.certifies()).isTrue(); - } - - @Test - void aQueryAgainstANotReadyIndexFailsTheReadinessContract() { - MongoAtlasCapabilityContractSuite.MongoAtlasCapabilityReport report = - MongoAtlasCapabilityContractSuite.vectorReadiness( - true, MongoAtlasCapabilityContractSuite.Environment.ACTUAL_TARGET); - - assertThat(report.queriedBeforeReady()).isTrue(); - assertThat(report.certifies()).isFalse(); - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/advanced/autoconfigure/MongoAdvancedConfigurationTest.java b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/advanced/autoconfigure/MongoAdvancedConfigurationTest.java deleted file mode 100644 index 360f6746..00000000 --- a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/advanced/autoconfigure/MongoAdvancedConfigurationTest.java +++ /dev/null @@ -1,109 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.advanced.autoconfigure; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.outbound.mongo.advanced.MongoAdvancedCapabilityFlags; -import dev.caskeleton.adapter.outbound.mongo.advanced.MongoAdvancedCapabilityGuard; -import dev.caskeleton.adapter.outbound.mongo.advanced.bridge.MongoChangeMessagingBridge; -import dev.caskeleton.adapter.outbound.mongo.advanced.tenancy.database.MongoTenantClientRegistry; -import dev.caskeleton.adapter.outbound.mongo.api.capability.MongoCapability; -import dev.caskeleton.adapter.outbound.mongo.api.error.MongoOperationRejectedException; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; -import org.springframework.boot.autoconfigure.AutoConfigurations; -import org.springframework.boot.test.context.runner.ApplicationContextRunner; - -/** - * The Advanced flags, bound from configuration and applied to construction. - * - *

Nothing read the flag properties before this. {@code MongoAdvancedCapabilityFlags} could name - * the property that would enable a capability, and setting that property enabled nothing — the flag - * sets that existed at runtime were the ones test code built by hand. - */ -@Tag("mongodb-contract") -class MongoAdvancedConfigurationTest { - - private final ApplicationContextRunner runner = - new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of()) - .withUserConfiguration(MongoAdvancedConfiguration.class) - .withPropertyValues("ca-skeleton.persistence-mongo.enabled=true"); - - @Test - @DisplayName("the property path the refusal names is the path binding reads") - void thePropertyPathIsOneFact() { - assertThat(MongoAdvancedCapabilityFlags.propertyFor(MongoCapability.DATABASE_PER_TENANT)) - .as("a message naming a property nothing binds is worse than no message") - .isEqualTo(MongoAdvancedSettings.PREFIX + ".advanced.database-per-tenant.enabled"); - } - - @Test - @DisplayName("without the module switch there is no guard at all") - void theModuleSwitchGatesTheGuard() { - new ApplicationContextRunner() - .withUserConfiguration(MongoAdvancedConfiguration.class) - .run(context -> assertThat(context).doesNotHaveBean(MongoAdvancedCapabilityGuard.class)); - } - - @Test - @DisplayName("with nothing enabled an entry point refuses construction") - void nothingEnabledRefusesConstruction() { - runner.run( - context -> { - MongoAdvancedCapabilityGuard guard = context.getBean(MongoAdvancedCapabilityGuard.class); - - assertThat(guard.allows(MongoChangeMessagingBridge.class)).isFalse(); - assertThatThrownBy(() -> guard.require(MongoChangeMessagingBridge.class)) - .isInstanceOf(MongoOperationRejectedException.class) - .hasMessageContaining("advanced.change-stream.enabled"); - }); - } - - @Test - @DisplayName("an enabled capability admits its own entry point and no other") - void anEnabledCapabilityIsScopedToItself() { - runner - .withPropertyValues("ca-skeleton.persistence-mongo.advanced.change-stream.enabled=true") - .run( - context -> { - MongoAdvancedCapabilityGuard guard = - context.getBean(MongoAdvancedCapabilityGuard.class); - - assertThat(guard.allows(MongoChangeMessagingBridge.class)).isTrue(); - assertThat(guard.allows(MongoTenantClientRegistry.class)) - .as("enabling one capability must not enable the rest of the package") - .isFalse(); - assertThatThrownBy(() -> new MongoTenantClientRegistry(guard, 2)) - .isInstanceOf(MongoOperationRejectedException.class); - }); - } - - @Test - @DisplayName("a capability explicitly set to false is still off") - void anExplicitFalseIsOff() { - runner - .withPropertyValues("ca-skeleton.persistence-mongo.advanced.sharding.enabled=false") - .run( - context -> - assertThat( - context - .getBean(MongoAdvancedSettings.class) - .toFlags() - .isEnabled(MongoCapability.SHARDING)) - .isFalse()); - } - - @Test - @DisplayName("an unknown capability name fails startup rather than binding to nothing") - void anUnknownCapabilityFailsStartup() { - runner - .withPropertyValues("ca-skeleton.persistence-mongo.advanced.shrading.enabled=true") - .run( - context -> - assertThat(context) - .as("a misspelt flag that binds to nothing leaves the capability off silently") - .hasFailed()); - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/advanced/bridge/MongoChangeMessagingBridgeTest.java b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/advanced/bridge/MongoChangeMessagingBridgeTest.java deleted file mode 100644 index efd2c30c..00000000 --- a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/advanced/bridge/MongoChangeMessagingBridgeTest.java +++ /dev/null @@ -1,159 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.advanced.bridge; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.outbound.mongo.advanced.MongoAdvancedCapabilityFlags; -import dev.caskeleton.adapter.outbound.mongo.advanced.MongoAdvancedCapabilityGuard; -import dev.caskeleton.adapter.outbound.mongo.api.capability.MongoCapability; -import dev.caskeleton.adapter.outbound.mongo.changestream.MongoChangeEventIdentity; -import dev.caskeleton.adapter.outbound.mongo.changestream.MongoResumeCheckpoint; -import dev.caskeleton.adapter.outbound.mongo.changestream.MongoResumeCheckpointStore; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.atomic.AtomicInteger; -import org.bson.BsonDocument; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; -import reactor.core.publisher.Mono; - -/** Advanced plan Task 12 — a failed publish never advances the MongoDB checkpoint. */ -@Tag("mongodb-contract") -class MongoChangeMessagingBridgeTest { - - private static final MongoChangeEventIdentity IDENTITY = - MongoChangeEventIdentity.of("1700000000.1", "shop.orders", "{\"_id\":\"o-1\"}", "insert"); - - private static final MongoResumeCheckpoint CHECKPOINT = - MongoResumeCheckpoint.encrypted("orders", new byte[] {1, 2, 3}); - - private static final MongoAdvancedCapabilityGuard ENABLED = - new MongoAdvancedCapabilityGuard( - MongoAdvancedCapabilityFlags.allDisabled().withEnabled(MongoCapability.CHANGE_STREAM)); - - @Test - void failedPublishDoesNotAdvanceMongoCheckpoint() { - CountingCheckpointStore checkpoints = new CountingCheckpointStore(); - MongoChangeMessagingBridge bridge = - new MongoChangeMessagingBridge( - ENABLED, - (identity, change) -> envelope(), - envelope -> Mono.error(new IllegalStateException("broker unavailable")), - checkpoints, - MongoBridgeCheckpointPolicy.AFTER_PUBLISH_CONFIRMED); - - bridge - .handle(IDENTITY, new BsonDocument(), CHECKPOINT) - .onErrorResume(failure -> Mono.empty()) - .block(); - - assertThat(checkpoints.writes()).isZero(); - } - - @Test - void aConfirmedPublishAdvancesTheCheckpoint() { - CountingCheckpointStore checkpoints = new CountingCheckpointStore(); - MongoChangeMessagingBridge bridge = - new MongoChangeMessagingBridge( - ENABLED, - (identity, change) -> envelope(), - envelope -> Mono.just(MongoPublishResult.confirmed()), - checkpoints, - MongoBridgeCheckpointPolicy.AFTER_PUBLISH_CONFIRMED); - - bridge.handle(IDENTITY, new BsonDocument(), CHECKPOINT).block(); - - assertThat(checkpoints.writes()).isEqualTo(1); - } - - @Test - void anUninterestingChangeStillAdvancesTheCheckpoint() { - CountingCheckpointStore checkpoints = new CountingCheckpointStore(); - MongoChangeMessagingBridge bridge = - new MongoChangeMessagingBridge( - ENABLED, - (identity, change) -> null, - envelope -> Mono.just(MongoPublishResult.confirmed()), - checkpoints, - MongoBridgeCheckpointPolicy.AFTER_PUBLISH_CONFIRMED); - - bridge.handle(IDENTITY, new BsonDocument(), CHECKPOINT).block(); - - assertThat(checkpoints.writes()).isEqualTo(1); - } - - @Test - void anIntegrationEventNeedsADeterministicMessageId() { - assertThatThrownBy(() -> new MongoIntegrationEventEnvelope("order.paid", 1, "", Map.of())) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("deterministic"); - } - - @Test - void theCheckpointPolicyDecidesWhatAnAmbiguousPublishMeans() { - assertThat(MongoBridgeCheckpointPolicy.AFTER_PUBLISH_CONFIRMED.mayAdvance(false, true)) - .isFalse(); - assertThat( - MongoBridgeCheckpointPolicy.AFTER_PUBLISH_AMBIGUOUS_WITH_DEDUPLICATION.mayAdvance( - false, true)) - .isTrue(); - } - - @Test - void anAtomicIntegrationNeedsAnOutboxRatherThanTheBridge() { - assertThat(MongoBridgeOutboxPolicy.forRequirement(true)) - .isEqualTo(MongoBridgeOutboxPolicy.OUTBOX_REQUIRED); - assertThat(MongoBridgeOutboxPolicy.forRequirement(false).bridgeSufficient()).isTrue(); - } - - private static MongoIntegrationEventEnvelope envelope() { - return new MongoIntegrationEventEnvelope( - "order.paid", 1, IDENTITY.value(), Map.of("orderId", "o-1")); - } - - /** Counts checkpoint writes. */ - private static final class CountingCheckpointStore implements MongoResumeCheckpointStore { - - private final AtomicInteger writes = new AtomicInteger(); - - @Override - public Mono> load(String subscriptionProfile) { - return Mono.just(Optional.empty()); - } - - @Override - public Mono save(MongoResumeCheckpoint checkpoint) { - writes.incrementAndGet(); - return Mono.empty(); - } - - @Override - public Mono clear(String subscriptionProfile) { - return Mono.empty(); - } - - private int writes() { - return writes.get(); - } - } - - @Test - void anAmbiguousPublishDoesNotAdvanceTheCheckpoint() { - CountingCheckpointStore checkpoints = new CountingCheckpointStore(); - MongoChangeMessagingBridge bridge = - new MongoChangeMessagingBridge( - ENABLED, - (identity, change) -> envelope(), - envelope -> Mono.just(MongoPublishResult.unknown()), - checkpoints, - MongoBridgeCheckpointPolicy.AFTER_PUBLISH_CONFIRMED); - - bridge.handle(IDENTITY, new BsonDocument(), CHECKPOINT).block(); - - assertThat(checkpoints.writes()) - .as( - "the bridge passed the constants published=true, ambiguous=false, so this branch of the" - + " policy was unreachable and an unacknowledged publish advanced the checkpoint") - .isZero(); - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/advanced/gridfs/MongoGridFsMigrationJobTest.java b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/advanced/gridfs/MongoGridFsMigrationJobTest.java deleted file mode 100644 index 6689b007..00000000 --- a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/advanced/gridfs/MongoGridFsMigrationJobTest.java +++ /dev/null @@ -1,197 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.advanced.gridfs; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.outbound.mongo.advanced.MongoAdvancedCapabilityFlags; -import dev.caskeleton.adapter.outbound.mongo.advanced.MongoAdvancedCapabilityGuard; -import dev.caskeleton.adapter.outbound.mongo.api.capability.MongoCapability; -import java.io.ByteArrayInputStream; -import java.nio.charset.StandardCharsets; -import java.time.Clock; -import java.time.Instant; -import java.time.ZoneOffset; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -/** - * Advanced plan Task 13 — the source stays until the copy verifies, and nothing is deleted here. - */ -@Tag("mongodb-contract") -class MongoGridFsMigrationJobTest { - - private static final Clock FIXED = - Clock.fixed(Instant.parse("2026-08-13T00:00:00Z"), ZoneOffset.UTC); - - private static final MongoAdvancedCapabilityGuard ENABLED = - new MongoAdvancedCapabilityGuard( - MongoAdvancedCapabilityFlags.allDisabled() - .withEnabled(MongoCapability.GRIDFS_COMPATIBILITY)); - - @Test - void sourceIsRetainedUntilTargetChecksumIsVerified() { - List writtenReferences = new ArrayList<>(); - MongoGridFsMigrationJob job = - new MongoGridFsMigrationJob( - legacyId -> legacyContent("sha256:source"), - (legacyId, source) -> - new MongoGridFsObjectReference(legacyId, "content/" + legacyId, 5, "sha256:other"), - writtenReferences::add, - ENABLED, - FIXED); - - Optional migrated = job.migrate("legacy-1"); - - assertThat(migrated).isEmpty(); - assertThat(writtenReferences).isEmpty(); - } - - @Test - void aVerifiedCopySwitchesTheReference() { - List writtenReferences = new ArrayList<>(); - MongoGridFsMigrationJob job = - new MongoGridFsMigrationJob( - legacyId -> legacyContent("sha256:source"), - (legacyId, source) -> - new MongoGridFsObjectReference( - legacyId, "content/" + legacyId, source.sizeBytes(), source.checksum()), - writtenReferences::add, - ENABLED, - FIXED); - - assertThat(job.migrate("legacy-1")).isPresent(); - assertThat(writtenReferences).hasSize(1); - assertThat(writtenReferences.get(0).contentKey()).isEqualTo("content/legacy-1"); - } - - @Test - void theCapabilityMustBeEnabledBeforeTheJobExists() { - assertThatThrownBy( - () -> - new MongoGridFsMigrationJob( - legacyId -> legacyContent("sha256:source"), - (legacyId, source) -> null, - reference -> {}, - MongoAdvancedCapabilityGuard.allDisabled(), - FIXED)) - .hasMessageContaining("opt-in Advanced module"); - } - - @Test - void aReferenceWithoutAChecksumCannotBeVerified() { - assertThatThrownBy(() -> new MongoGridFsObjectReference("legacy-1", "content/legacy-1", 5, "")) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void theCheckpointSeparatesMigratedFromFailed() { - MongoGridFsMigrationCheckpoint checkpoint = - MongoGridFsMigrationCheckpoint.start(FIXED.instant()) - .migrated("legacy-1", FIXED.instant()) - .failed("legacy-2", FIXED.instant()); - - assertThat(checkpoint.migratedCount()).isEqualTo(1); - assertThat(checkpoint.failedCount()).isEqualTo(1); - assertThat(checkpoint.clean()).isFalse(); - assertThat(checkpoint.lastSuccessfullyProcessedLegacyId()) - .as("the failure path used to write the failed id here, so a restart skipped it forever") - .isEqualTo("legacy-1"); - assertThat(checkpoint.failedObjects()).containsExactly("legacy-2"); - } - - @Test - @org.junit.jupiter.api.DisplayName("a resolved failure leaves the retry queue") - void aResolvedFailureLeavesTheRetryQueue() { - MongoGridFsMigrationCheckpoint checkpoint = - MongoGridFsMigrationCheckpoint.start(FIXED.instant()) - .failed("legacy-2", FIXED.instant()) - .resolved("legacy-2", FIXED.instant()); - - assertThat(checkpoint.failedObjects()).isEmpty(); - assertThat(checkpoint.clean()).isTrue(); - assertThat(checkpoint.lastSuccessfullyProcessedLegacyId()).isEqualTo("legacy-2"); - } - - @Test - @org.junit.jupiter.api.DisplayName("the same failure recorded twice is one entry") - void theSameFailureIsOneEntry() { - MongoGridFsMigrationCheckpoint checkpoint = - MongoGridFsMigrationCheckpoint.start(FIXED.instant()) - .failed("legacy-2", FIXED.instant()) - .failed("legacy-2", FIXED.instant()); - - assertThat(checkpoint.failedObjects()).containsExactly("legacy-2"); - } - - @Test - @org.junit.jupiter.api.DisplayName("the retry queue is bounded and stops rather than dropping") - void theRetryQueueIsBounded() { - MongoGridFsMigrationCheckpoint checkpoint = - MongoGridFsMigrationCheckpoint.start(FIXED.instant()); - for (int index = 0; index < MongoGridFsMigrationCheckpoint.MAXIMUM_TRACKED_FAILURES; index++) { - checkpoint = checkpoint.failed("legacy-" + index, FIXED.instant()); - } - - MongoGridFsMigrationCheckpoint full = checkpoint; - assertThatThrownBy(() -> full.failed("one-too-many", FIXED.instant())) - .as("a dropped failed id is a file nobody will look for again") - .isInstanceOf(IllegalStateException.class); - } - - @Test - @org.junit.jupiter.api.DisplayName("the legacy stream is closed on success, failure and error") - void theLegacyStreamIsAlwaysClosed() { - CountingStream stream = new CountingStream(); - MongoGridFsMigrationJob job = - new MongoGridFsMigrationJob( - legacyId -> - new MongoGridFsCompatibilityReader.GridFsLegacyContent( - legacyId, "invoice.pdf", 5, "sha256:abc", stream), - (legacyId, source) -> - new MongoGridFsObjectReference(legacyId, "content/" + legacyId, 5, "sha256:abc"), - reference -> {}, - ENABLED, - FIXED); - - job.migrate("legacy-1"); - - assertThat(stream.closes()) - .as("the job handed the stream to a writer and returned, leaking one cursor per file") - .isEqualTo(1); - } - - /** A stream that counts how often it was closed. */ - private static final class CountingStream extends java.io.InputStream { - - private int closes; - - @Override - public int read() { - return -1; - } - - @Override - public void close() { - closes++; - } - - private int closes() { - return closes; - } - } - - @Test - void theCapabilityFlagNamesThePropertyThatEnablesIt() { - assertThat(MongoAdvancedCapabilityFlags.propertyFor(MongoCapability.GRIDFS_COMPATIBILITY)) - .isEqualTo("ca-skeleton.persistence-mongo.advanced.gridfs-compatibility.enabled"); - } - - private static MongoGridFsCompatibilityReader.GridFsLegacyContent legacyContent(String checksum) { - byte[] bytes = "hello".getBytes(StandardCharsets.UTF_8); - return new MongoGridFsCompatibilityReader.GridFsLegacyContent( - "legacy-1", "invoice.pdf", bytes.length, checksum, new ByteArrayInputStream(bytes)); - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/advanced/search/MongoSearchReadinessGateTest.java b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/advanced/search/MongoSearchReadinessGateTest.java deleted file mode 100644 index 862fe567..00000000 --- a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/advanced/search/MongoSearchReadinessGateTest.java +++ /dev/null @@ -1,110 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.advanced.search; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.outbound.mongo.advanced.vector.MongoEmbedding; -import dev.caskeleton.adapter.outbound.mongo.advanced.vector.MongoVectorIndexDescriptor; -import dev.caskeleton.adapter.outbound.mongo.advanced.vector.MongoVectorQuery; -import dev.caskeleton.adapter.outbound.mongo.advanced.vector.MongoVectorSearchBenchmarkGate; -import dev.caskeleton.adapter.outbound.mongo.api.error.MongoOperationRejectedException; -import dev.caskeleton.adapter.outbound.mongo.schema.manifest.MongoMetadataOwnership; -import java.util.List; -import java.util.Set; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -/** Advanced plan Tasks 8-9 — created is not ready, and an embedding is bound to its index. */ -@Tag("mongodb-contract") -class MongoSearchReadinessGateTest { - - private final MongoSearchReadinessGate gate = new MongoSearchReadinessGate(); - - @Test - void buildingIndexCannotServeTraffic() { - assertThatThrownBy(() -> gate.requireReady(MongoSearchIndexState.BUILDING)) - .isInstanceOf(MongoOperationRejectedException.class); - } - - @Test - void onlyAReadyIndexIsQueryable() { - assertThat(gate.queryable(MongoSearchIndexState.READY)).isTrue(); - assertThat(gate.queryable(MongoSearchIndexState.CREATED)).isFalse(); - assertThat(gate.queryable(MongoSearchIndexState.FAILED)).isFalse(); - assertThatCode(() -> gate.requireReady(MongoSearchIndexState.READY)).doesNotThrowAnyException(); - } - - @Test - void aSearchIndexIsOwnedBySearchRatherThanTheApplication() { - MongoSearchIndexDescriptor descriptor = - MongoSearchIndexDescriptor.standard("ix_search_orders", "orders", List.of("customerName")); - - assertThat(descriptor.metadataOwnership()).isEqualTo(MongoMetadataOwnership.SEARCH_MANAGED); - assertThat(descriptor.metadataOwnership().droppableByApplicationDrift()).isFalse(); - } - - @Test - void searchPathsAreAllowlisted() { - MongoSearchQuery query = - new MongoSearchQuery("ix_search_orders", List.of("customerName"), "alice", 20); - - assertThatCode(() -> query.requireAllowedPaths(Set.of("customerName"))) - .doesNotThrowAnyException(); - assertThatThrownBy(() -> query.requireAllowedPaths(Set.of("orderNumber"))) - .isInstanceOf(MongoOperationRejectedException.class); - } - - @Test - void aSearchQueryIsBoundedInTextLengthAndResults() { - assertThatThrownBy( - () -> new MongoSearchQuery("ix", List.of("customerName"), "a".repeat(1000), 20)) - .isInstanceOf(MongoOperationRejectedException.class); - assertThatThrownBy(() -> new MongoSearchQuery("ix", List.of("customerName"), "a", 10_000)) - .isInstanceOf(MongoOperationRejectedException.class); - } - - @Test - void rejectsDimensionMismatch() { - MongoVectorIndexDescriptor index = MongoVectorIndexDescriptor.cosine("embedding", 3); - - assertThatThrownBy(() -> MongoEmbedding.forIndex(index, new float[] {1f, 2f})) - .isInstanceOf(IllegalArgumentException.class); - assertThat(MongoEmbedding.forIndex(index, new float[] {1f, 2f, 3f}).dimensions()).isEqualTo(3); - } - - @Test - void anEmbeddingDoesNotLeakItsBackingArray() { - MongoVectorIndexDescriptor index = MongoVectorIndexDescriptor.cosine("embedding", 3); - float[] source = {1f, 2f, 3f}; - MongoEmbedding embedding = MongoEmbedding.forIndex(index, source); - - source[0] = 99f; - embedding.values()[1] = 99f; - - assertThat(embedding.values()).containsExactly(1f, 2f, 3f); - } - - @Test - void aVectorQueryNeedsMoreCandidatesThanResults() { - MongoEmbedding embedding = - MongoEmbedding.forIndex( - MongoVectorIndexDescriptor.cosine("embedding", 3), new float[] {1f, 2f, 3f}); - - assertThatThrownBy( - () -> - new MongoVectorQuery(embedding, 10, 10, Set.of(), java.time.Duration.ofSeconds(1))) - .isInstanceOf(MongoOperationRejectedException.class) - .hasMessageContaining("nearest"); - assertThat(MongoVectorQuery.nearest(embedding, 10).numCandidates()).isEqualTo(200); - } - - @Test - void vectorPromotionNeedsRecallNotJustFunctionalSuccess() { - MongoVectorSearchBenchmarkGate benchmark = MongoVectorSearchBenchmarkGate.standard(); - - assertThat(benchmark.passes(0.95, 100, 1024)).isTrue(); - assertThat(benchmark.failures(0.5, 100, 1024)).anyMatch(entry -> entry.startsWith("recall")); - assertThat(MongoVectorSearchBenchmarkGate.requiredEvidence()).contains("recall"); - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/advanced/timeseries/MongoTimeSeriesCapabilityValidatorTest.java b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/advanced/timeseries/MongoTimeSeriesCapabilityValidatorTest.java deleted file mode 100644 index 66c0f6a2..00000000 --- a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/advanced/timeseries/MongoTimeSeriesCapabilityValidatorTest.java +++ /dev/null @@ -1,75 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.advanced.timeseries; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.time.Duration; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.EnumSource; - -/** - * A question with an answer, instead of four methods that always throw. - * - *

Every one of the previous methods had {@code throw new UnsupportedOperationException} as its - * entire body. An API like that cannot be used correctly: every call site is either dead code or a - * bug, and nothing distinguishes them. A caller who genuinely needed change streams found out at - * runtime, from an exception describing a storage-engine limitation rather than a design mistake. - */ -class MongoTimeSeriesCapabilityValidatorTest { - - private static final MongoTimeSeriesDescriptor DESCRIPTOR = - new MongoTimeSeriesDescriptor( - "recordedAt", "sensorId", MongoTimeSeriesGranularity.SECONDS, Duration.ofDays(30)); - - private final MongoTimeSeriesCapabilityValidator validator = - new MongoTimeSeriesCapabilityValidator(); - - @ParameterizedTest - @EnumSource(MongoTimeSeriesCapability.class) - @DisplayName("every capability has a verdict and, when unsupported, a reason") - void everyCapabilityHasAVerdictAndAReason(MongoTimeSeriesCapability capability) { - MongoTimeSeriesSupport support = validator.supportFor(capability); - - assertThat(support.capability()).isEqualTo(capability); - if (support.supported()) { - assertThat(support.explanation()).isEmpty(); - } else { - assertThat(support.explanation()) - .as("an unsupported capability is only actionable if it says why") - .isPresent(); - } - } - - @Test - @DisplayName("change streams report the bucketing reason rather than throwing on call") - void changeStreamsReportTheBucketingReason() { - MongoTimeSeriesSupport support = validator.supportFor(MongoTimeSeriesCapability.CHANGE_STREAM); - - assertThat(support.supported()).isFalse(); - assertThat(support.reason()).contains("buckets"); - } - - @Test - @DisplayName("a descriptor that requires an unsupported capability is rejected at validation") - void aDescriptorRequiringAnUnsupportedCapabilityIsRejected() { - assertThatThrownBy( - () -> - validator.requireSupported( - DESCRIPTOR, MongoTimeSeriesCapability.TRANSACTIONAL_WRITE)) - .as("before the collection exists is when the choice can still be changed") - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("TRANSACTIONAL_WRITE"); - } - - @Test - @DisplayName("a support verdict cannot claim both a yes and a reason it is no") - void aVerdictCannotClaimBothAYesAndAReason() { - assertThatThrownBy( - () -> - new MongoTimeSeriesSupport( - MongoTimeSeriesCapability.CHANGE_STREAM, true, "but actually no")) - .isInstanceOf(IllegalArgumentException.class); - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/architecture/MongoModuleBoundaryTest.java b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/architecture/MongoModuleBoundaryTest.java index a69aa4f3..f3ebe3b3 100644 --- a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/architecture/MongoModuleBoundaryTest.java +++ b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/architecture/MongoModuleBoundaryTest.java @@ -28,8 +28,7 @@ class MongoModuleBoundaryTest { *

Closed, and compared against the tree for exact equality. The previous rules forbade a * handful of reverse dependencies and said nothing about the rest, while the build file and * {@code docs/mongodb/repository-adaptation.md} both claimed this test enforced the design's full - * package DAG. Four edges outside that DAG existed and passed: {@code reactive → imperative}, - * {@code reactive → query}, {@code transaction → reactive} and {@code geo → imperative}. + * package DAG. Edges outside that DAG existed and passed, among them {@code geo → imperative}. * *

They are recorded here rather than removed. Each is a real coupling the code relies on, and * pretending otherwise is what the previous rules did; recording them makes the next one a @@ -46,52 +45,23 @@ class MongoModuleBoundaryTest { java.util.Map.entry("schema", java.util.Set.of("api")), java.util.Map.entry("security", java.util.Set.of("api")), java.util.Map.entry("nativecap", java.util.Set.of("api")), - // The driver-facing half of a subscription resolves its collection through the imperative - // profile registry rather than naming a physical collection, which is the same seam the - // reactive executor reuses and the only thing keeping the physical name a deployment - // decision. - java.util.Map.entry("changestream", java.util.Set.of("api", "failure", "imperative")), java.util.Map.entry("imperative", java.util.Set.of("api", "failure")), java.util.Map.entry("migration", java.util.Set.of("api", "security")), java.util.Map.entry("aggregation", java.util.Set.of("api", "query")), java.util.Map.entry("geo", java.util.Set.of("api", "imperative", "schema")), - // The reactive executor reuses the imperative collection/consistency seam and the query - // budget rather than duplicating either. + java.util.Map.entry("transaction", java.util.Set.of("api", "failure")), java.util.Map.entry( - "reactive", java.util.Set.of("api", "failure", "imperative", "query")), - java.util.Map.entry("transaction", java.util.Set.of("api", "failure", "reactive")), - java.util.Map.entry( - "advanced", - java.util.Set.of( - "api", "changestream", "imperative", "migration", "schema", "security")), + "advanced", java.util.Set.of("api", "imperative", "migration", "schema", "security")), // The one place the typed profile becomes the driver's MongoClientSettings (MNG-INT-002). // It names the settings that describe the client, the security types that resolve its // credential, and the mapping manifest that pins the UUID representation — and nothing // that executes a query, because building a client is not running one. java.util.Map.entry( "client", java.util.Set.of("api", "autoconfigure", "mapping", "security")), - // `reactive` joined the list when the reactive execution path was finally wired. It had - // been the one half of the platform no configuration constructed: the classes shipped, - // their - // unit tests passed, and a deployment could not reach them. Declaring the edge is what - // makes - // the wiring visible here rather than only in a Spring configuration. java.util.Map.entry( "autoconfigure", java.util.Set.of( - "api", - "failure", - "imperative", - "mapping", - "observation", - "query", - "reactive", - "security", - // `changestream` joined for the same reason `reactive` did: no configuration - // opened a change stream at all, so the consumer, its checkpoint store, its - // recovery policy and its ordered pipeline were classes a deployment had no way - // to run. - "changestream")), + "api", "failure", "imperative", "mapping", "observation", "query", "security")), // The leaf root holds the opt-in filter and the Spring configuration entry points. // The testkit is its own source set and depends on production, never the reverse. The // direction that matters — a runtime package importing the testkit — is forbidden by @@ -142,12 +112,10 @@ class MongoModuleBoundaryTest { "..outbound.mongo.mapping..", "..outbound.mongo.failure..", "..outbound.mongo.imperative..", - "..outbound.mongo.reactive..", "..outbound.mongo.query..", "..outbound.mongo.aggregation..", "..outbound.mongo.transaction..", "..outbound.mongo.schema..", - "..outbound.mongo.changestream..", "..outbound.mongo.geo..", "..outbound.mongo.migration..", "..outbound.mongo.observation..", @@ -184,18 +152,6 @@ class MongoModuleBoundaryTest { .check(PLATFORM); } - @Test - void theImperativePathDoesNotDependOnTheReactiveOne() { - ArchRuleDefinition.noClasses() - .that() - .resideInAPackage("..outbound.mongo.imperative..") - .should() - .dependOnClassesThat() - .resideInAPackage("..outbound.mongo.reactive..") - .as("mongodb-imperative depends on core-api and spring-data only (design §6.3)") - .check(PLATFORM); - } - @Test void theAggregationModuleDependsOnQueryRatherThanTheOtherWayRound() { ArchRuleDefinition.noClasses() @@ -227,7 +183,7 @@ class MongoModuleBoundaryTest { .resideInAPackage("..outbound.mongo.schema..") .should() .dependOnClassesThat() - .resideInAnyPackage("..outbound.mongo.imperative..", "..outbound.mongo.reactive..") + .resideInAPackage("..outbound.mongo.imperative..") .as("mongodb-index-schema depends on core-api and spring-data only (design §6.3)") .check(PLATFORM); } @@ -241,7 +197,6 @@ class MongoModuleBoundaryTest { .dependOnClassesThat() .resideInAnyPackage( "..outbound.mongo.imperative..", - "..outbound.mongo.reactive..", "..outbound.mongo.transaction..", "..outbound.mongo.query..") .as("mongodb-observability depends on core-api (design §6.3)") diff --git a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/architecture/MongoRepositoryArchitectureRulesTest.java b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/architecture/MongoRepositoryArchitectureRulesTest.java index 4dff114b..78afbb12 100644 --- a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/architecture/MongoRepositoryArchitectureRulesTest.java +++ b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/architecture/MongoRepositoryArchitectureRulesTest.java @@ -20,9 +20,7 @@ class MongoRepositoryArchitectureRulesTest { @Test void domainRepositoriesMayExtendSpringDataDirectly() { assertThat(rules.allowedRepositorySuperTypes()) - .contains( - "org.springframework.data.mongodb.repository.MongoRepository", - "org.springframework.data.mongodb.repository.ReactiveMongoRepository"); + .contains("org.springframework.data.mongodb.repository.MongoRepository"); } @Test diff --git a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/architecture/MongoTestLaneContractTest.java b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/architecture/MongoTestLaneContractTest.java new file mode 100644 index 00000000..7f7801d1 --- /dev/null +++ b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/architecture/MongoTestLaneContractTest.java @@ -0,0 +1,122 @@ +package dev.caskeleton.adapter.outbound.mongo.architecture; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.IOException; +import java.lang.reflect.AnnotatedElement; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Stream; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.platform.commons.annotation.Testable; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * The Mongo lanes are defined by tags, so a tag mistake moves a test between lanes without any + * build failure. These two rules read the files the lanes are built from; the build declares both + * as inputs of this leaf's {@code test} task. + */ +class MongoTestLaneContractTest { + + private static final Path INTEGRATION_SOURCES = Path.of("src/mongoIntegrationTest/java"); + private static final Path RELEASE_CONTRACTS = + Path.of("../../../config/mongodb/release-contracts.json"); + private static final Set DOCKER_LANE_TAGS = + Set.of( + "mongodb-replicaset", + "mongodb-failover", + "mongodb-migration", + "mongodb-compatibility", + "mongodb-security-integration"); + private static final Pattern TAG = Pattern.compile("@Tag\\(\\s*\"([^\"]+)\"\\s*\\)"); + + @Test + void integrationTestBelongsToAtMostOneDockerLane() throws IOException { + // given + List sources; + try (Stream files = Files.walk(INTEGRATION_SOURCES)) { + sources = files.filter(file -> file.toString().endsWith(".java")).toList(); + } + + // when + List inSeveralLanes = new ArrayList<>(); + for (Path source : sources) { + Set laneTags = new LinkedHashSet<>(); + Matcher matcher = TAG.matcher(Files.readString(source)); + while (matcher.find()) { + if (DOCKER_LANE_TAGS.contains(matcher.group(1))) { + laneTags.add(matcher.group(1)); + } + } + if (laneTags.size() > 1) { + inSeveralLanes.add(source + " " + laneTags); + } + } + + // then + assertThat(inSeveralLanes).isEmpty(); + } + + /** + * A blocking release contract names a class and the stable lane: the class must carry that lane's + * tag, must not be disabled, and must declare at least the number of tests the contract counts + * on. The lane itself rejects skips, so a class that passes here runs there. + */ + @Test + void blockingReleaseContractRunsInTheStableContractLane() throws Exception { + // given + JsonNode contracts = JsonMapper.builder().build().readTree(RELEASE_CONTRACTS.toFile()); + + // when + List broken = new ArrayList<>(); + for (JsonNode contract : contracts.get("contracts")) { + String id = contract.get("id").asString(); + Class type = Class.forName(contract.get("className").asString()); + if (!contract.get("task").asString().equals("mongoStableContractTest")) { + broken.add( + id + + " names lane " + + contract.get("task") + + "; only mongoStableContractTest is blocking"); + } + if (!hasTag(type, "mongodb-contract")) { + broken.add(id + " " + type.getName() + " is not tagged mongodb-contract"); + } + if (type.isAnnotationPresent(Disabled.class)) { + broken.add(id + " " + type.getName() + " is disabled"); + } + long tests = testCount(type); + if (tests < contract.get("minimumExecuted").asInt()) { + broken.add(id + " " + type.getName() + " declares " + tests + " test(s)"); + } + } + + // then + assertThat(broken).isEmpty(); + } + + private static boolean hasTag(Class type, String tag) { + return Arrays.stream(type.getAnnotationsByType(Tag.class)).anyMatch(t -> t.value().equals(tag)); + } + + private static long testCount(Class type) { + return Stream.concat( + Arrays.stream(type.getDeclaredMethods()), Arrays.stream(type.getDeclaredFields())) + .map(AnnotatedElement.class::cast) + .filter( + member -> + Arrays.stream(member.getAnnotations()) + .anyMatch(a -> a.annotationType().isAnnotationPresent(Testable.class))) + .count(); + } +} diff --git a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/autoconfigure/MongoPlatformHealthMeasuresTheClusterTest.java b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/autoconfigure/MongoPlatformHealthMeasuresTheClusterTest.java index f49a2dd5..f392cb3b 100644 --- a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/autoconfigure/MongoPlatformHealthMeasuresTheClusterTest.java +++ b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/autoconfigure/MongoPlatformHealthMeasuresTheClusterTest.java @@ -92,7 +92,7 @@ class MongoPlatformHealthMeasuresTheClusterTest { @Test @DisplayName("a negative requirement is refused rather than read as no requirement") void aNegativeRequirementIsRefused() { - assertThatThrownBy(() -> new MongoPlatformSettings(Map.of(), false, false, -1)) + assertThatThrownBy(() -> new MongoPlatformSettings(Map.of(), false, -1)) .isInstanceOf(MongoOperationRejectedException.class) .hasMessageContaining("secondary"); } @@ -108,7 +108,6 @@ class MongoPlatformHealthMeasuresTheClusterTest { return new MongoPlatformSettings( Map.of("default", MongoProfileProperties.production("secret://mongodb/uri")), false, - false, requiredSecondaries); } } diff --git a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/autoconfigure/MongoPlatformPropertiesTest.java b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/autoconfigure/MongoPlatformPropertiesTest.java index 0e1d3992..ae228099 100644 --- a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/autoconfigure/MongoPlatformPropertiesTest.java +++ b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/autoconfigure/MongoPlatformPropertiesTest.java @@ -4,9 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import dev.caskeleton.adapter.outbound.mongo.api.consistency.MongoConsistencyProfile; import dev.caskeleton.adapter.outbound.mongo.api.error.MongoOperationRejectedException; -import dev.caskeleton.adapter.outbound.mongo.api.mapping.MongoDecimalRepresentation; import dev.caskeleton.adapter.outbound.mongo.api.mapping.MongoUuidRepresentation; import dev.caskeleton.adapter.outbound.mongo.api.profile.MongoTopology; import dev.caskeleton.adapter.outbound.mongo.security.MongoCredentialReference; @@ -39,7 +37,7 @@ class MongoPlatformSettingsTest { } @Test - void productionRejectsStandaloneRuntimeAutoIndexAndRelaxedStableApi() { + void productionRejectsAStandaloneTopology() { MongoProfileProperties standalone = withTopology( MongoProfileProperties.production("secret://mongodb/uri"), MongoTopology.STANDALONE); @@ -49,33 +47,6 @@ class MongoPlatformSettingsTest { .hasMessageContaining("STANDALONE"); } - @Test - void productionRefusesRuntimeIndexCreation() { - MongoProfileProperties autoIndex = - new MongoProfileProperties( - "secret://mongodb/uri", - MongoTopology.REPLICA_SET, - true, - true, - MongoConsistencyProfile.PRIMARY_MAJORITY, - Duration.ofSeconds(3), - Duration.ofSeconds(2), - Duration.ofSeconds(5), - Duration.ofSeconds(3), - 2, - 40, - Duration.ofMillis(500), - MongoUuidRepresentation.STANDARD, - MongoDecimalRepresentation.DECIMAL128, - true, - true, - true); - - assertThatThrownBy(autoIndex::validate) - .isInstanceOf(MongoOperationRejectedException.class) - .hasMessageContaining("auto index creation"); - } - @Test void anOperationDeadlineLongerThanTheSocketReadIsARedundantDeadline() { MongoProfileProperties inconsistent = @@ -84,7 +55,6 @@ class MongoPlatformSettingsTest { MongoTopology.REPLICA_SET, true, true, - MongoConsistencyProfile.PRIMARY_MAJORITY, Duration.ofSeconds(3), Duration.ofSeconds(2), Duration.ofSeconds(1), @@ -93,8 +63,6 @@ class MongoPlatformSettingsTest { 40, Duration.ofMillis(500), MongoUuidRepresentation.STANDARD, - MongoDecimalRepresentation.DECIMAL128, - false, true, true); @@ -107,10 +75,7 @@ class MongoPlatformSettingsTest { void anInvalidProfileNameIsRejectedWithTheProfileNamed() { MongoPlatformSettings properties = new MongoPlatformSettings( - Map.of("Tenant_A", MongoProfileProperties.local("secret://mongodb/uri")), - false, - false, - null); + Map.of("Tenant_A", MongoProfileProperties.local("secret://mongodb/uri")), false, null); assertThatThrownBy(properties::validate) .isInstanceOf(MongoOperationRejectedException.class) @@ -119,7 +84,7 @@ class MongoPlatformSettingsTest { @Test void anAbsentProfileMapBindsToAnEmptyConfiguration() { - assertThat(new MongoPlatformSettings(null, false, false, null).profiles()).isEmpty(); + assertThat(new MongoPlatformSettings(null, false, null).profiles()).isEmpty(); assertThat(MongoPlatformSettings.empty().profiles()).isEmpty(); } @@ -172,7 +137,6 @@ class MongoPlatformSettingsTest { topology, profile.production(), profile.stableApiStrict(), - profile.consistencyDefault(), profile.serverSelectionTimeout(), profile.connectTimeout(), profile.socketReadTimeout(), @@ -181,8 +145,6 @@ class MongoPlatformSettingsTest { profile.poolMaxSize(), profile.poolMaxWaitTime(), profile.uuidRepresentation(), - profile.decimalRepresentation(), - profile.runtimeAutoCreateIndexes(), profile.tlsRequired(), profile.authenticationRequired()); } diff --git a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/autoconfigure/MongoReactiveWiringTest.java b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/autoconfigure/MongoReactiveWiringTest.java deleted file mode 100644 index 00cd5310..00000000 --- a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/autoconfigure/MongoReactiveWiringTest.java +++ /dev/null @@ -1,153 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.autoconfigure; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; - -import dev.caskeleton.adapter.outbound.mongo.reactive.DefaultReactiveMongoExecutor; -import dev.caskeleton.adapter.outbound.mongo.reactive.ReactiveMongoConsistencyBinder; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; -import org.springframework.boot.autoconfigure.AutoConfigurations; -import org.springframework.boot.test.context.runner.ApplicationContextRunner; -import org.springframework.data.mongodb.core.ReactiveMongoTemplate; - -/** - * The reactive half is assembled when a deployment has a reactive template, and only then. - * - *

Every reactive class in this leaf — the executor, the consistency binder, the session factory, - * the cursor guard and its result budget — was declared by no configuration. They shipped in the - * jar and no configuration could construct them, so a deployment that switched the platform on got - * the blocking path and a set of classes with passing unit tests that nothing could reach. - * - *

The negative case matters as much: {@code ReactiveMongoTemplate} is on this leaf's compile - * classpath unconditionally, so a class condition alone would have tried to build the reactive path - * in a servlet-only deployment and failed its startup for a capability nobody asked for. - */ -@Tag("mongodb-contract") -class MongoReactiveWiringTest { - - private final ApplicationContextRunner runner = - new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(MongoPlatformAutoConfiguration.ReactiveExecution.class)) - .withBean( - dev.caskeleton.adapter.outbound.mongo.api.consistency.MongoConsistencyRegistry.class, - dev.caskeleton.adapter.outbound.mongo.api.consistency.MongoConsistencyRegistry - ::standard) - .withBean( - dev.caskeleton.adapter.outbound.mongo.imperative.MongoCollectionProfileRegistry.class, - () -> - dev.caskeleton.adapter.outbound.mongo.imperative.MongoCollectionProfileRegistry - .builder() - .build()) - .withBean( - dev.caskeleton.adapter.outbound.mongo.failure.MongoFailureTranslator.class, - () -> - mock(dev.caskeleton.adapter.outbound.mongo.failure.MongoFailureTranslator.class)) - .withBean( - dev.caskeleton.adapter.outbound.mongo.api.observation.MongoOperationObserver.class, - () -> - mock( - dev.caskeleton.adapter.outbound.mongo.api.observation.MongoOperationObserver - .class)); - - private static ReactiveMongoTemplate template() { - return new ReactiveMongoTemplate( - new org.springframework.data.mongodb.core.SimpleReactiveMongoDatabaseFactory( - mock(com.mongodb.reactivestreams.client.MongoClient.class), "wiring-test")); - } - - @Test - @DisplayName("a reactive template brings the reactive execution path with it") - void aReactiveTemplateAssemblesTheReactivePath() { - runner - // A real template over a real factory, not a mock. The binder derives one template per - // consistency profile by constructing `new ReactiveMongoTemplate(factory, converter)`. - // Only the driver client is mocked so the hermetic wiring test creates no cluster-monitor - // threads. - .withBean(ReactiveMongoTemplate.class, MongoReactiveWiringTest::template) - .run( - context -> - assertThat(context) - .hasSingleBean(ReactiveMongoConsistencyBinder.class) - .hasSingleBean(DefaultReactiveMongoExecutor.class)); - } - - @Test - @DisplayName( - "a subscription with nothing to project builds no consumer, rather than a stalled one") - void aSubscriptionWithoutAProjectorBuildsNoConsumer() { - runner - .withBean(ReactiveMongoTemplate.class, MongoReactiveWiringTest::template) - .withBean( - dev.caskeleton.adapter.outbound.mongo.changestream.MongoChangeStreamSubscription.class, - () -> - dev.caskeleton.adapter.outbound.mongo.changestream.MongoChangeStreamSubscription.of( - "orders-projection", "orders")) - .run( - context -> - assertThat(context) - .as( - "the platform cannot invent a projector, and a consumer without one reads" - + " a stream into nothing") - .hasSingleBean( - dev.caskeleton.adapter.outbound.mongo.changestream.consumer - .MongoChangeStreamSource.class) - .doesNotHaveBean( - dev.caskeleton.adapter.outbound.mongo.changestream.consumer - .ReactiveMongoChangeStreamConsumer.class)); - } - - @Test - @DisplayName("a deployment that supplies the projection pieces gets a running subscription") - void theProjectionPiecesAssembleAConsumer() { - runner - .withBean(ReactiveMongoTemplate.class, MongoReactiveWiringTest::template) - .withBean( - dev.caskeleton.adapter.outbound.mongo.changestream.MongoChangeStreamSubscription.class, - () -> - dev.caskeleton.adapter.outbound.mongo.changestream.MongoChangeStreamSubscription.of( - "orders-projection", "orders")) - .withBean( - dev.caskeleton.adapter.outbound.mongo.changestream.MongoResumeCheckpointStore.class, - () -> - mock( - dev.caskeleton.adapter.outbound.mongo.changestream.MongoResumeCheckpointStore - .class)) - .withBean( - dev.caskeleton.adapter.outbound.mongo.changestream.MongoResumeTokenCodec.class, - () -> - mock( - dev.caskeleton.adapter.outbound.mongo.changestream.MongoResumeTokenCodec.class)) - .withBean( - dev.caskeleton.adapter.outbound.mongo.changestream.projector.MongoChangeProjector.class, - () -> - mock( - dev.caskeleton.adapter.outbound.mongo.changestream.projector - .MongoChangeProjector.class)) - .withBean( - dev.caskeleton.adapter.outbound.mongo.changestream.projector - .MongoChangeDeduplicationStore.class, - () -> - mock( - dev.caskeleton.adapter.outbound.mongo.changestream.projector - .MongoChangeDeduplicationStore.class)) - .run( - context -> - assertThat(context) - .hasSingleBean( - dev.caskeleton.adapter.outbound.mongo.changestream.consumer - .ReactiveMongoChangeStreamConsumer.class)); - } - - @Test - @DisplayName("no reactive template means no reactive beans, rather than a failed startup") - void withoutAReactiveTemplateNothingReactiveIsBuilt() { - runner.run( - context -> - assertThat(context) - .doesNotHaveBean(ReactiveMongoConsistencyBinder.class) - .doesNotHaveBean(DefaultReactiveMongoExecutor.class)); - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/autoconfigure/MongoStartupValidationTest.java b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/autoconfigure/MongoStartupValidationTest.java index fc7fe824..c9031e7a 100644 --- a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/autoconfigure/MongoStartupValidationTest.java +++ b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/autoconfigure/MongoStartupValidationTest.java @@ -1,7 +1,6 @@ package dev.caskeleton.adapter.outbound.mongo.autoconfigure; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.lang.reflect.Method; import java.util.Arrays; @@ -29,12 +28,7 @@ import org.springframework.context.annotation.Bean; * refuse the module's own opt-in contract, and the {@code local-mongo} lane with it — which is what * the first attempt at this did, and how the scope got settled. * - *

The capability flags were literals — {@code true, true} passed straight into {@code - * MongoStartupValidator} — which told the validator that transactions and change streams were both - * wanted regardless of what the deployment asked for. They come from settings now: {@code - * transactions} is a subordinate switch defaulting {@code false}, and {@code change-streams} is - * experimental and always {@code false}, because a replica-set qualification observing that the - * server *can* do something is not evidence that this platform ships it. + *

{@code transactions} comes from settings and is a subordinate switch defaulting {@code false}. */ class MongoStartupValidationTest { @@ -56,25 +50,8 @@ class MongoStartupValidationTest { } @Test - @DisplayName("the capability flags come from settings, not from literals") - void theCapabilityFlagsComeFromSettings() { - assertThat(MongoPlatformSettings.empty().transactions()) - .as("a subordinate switch, off until a deployment asks for it") - .isFalse(); - assertThat(MongoPlatformSettings.empty().changeStreams()) - .as( - "experimental: zero beans and zero threads. A server that supports change streams is" - + " not a platform that ships them.") - .isFalse(); - } - - @Test - @DisplayName("change streams cannot be switched on by configuration") - void changeStreamsCannotBeSwitchedOn() { - assertThatThrownBy(() -> new MongoPlatformSettings(java.util.Map.of(), true, true, null)) - .isInstanceOf( - dev.caskeleton.adapter.outbound.mongo.api.error.MongoOperationRejectedException.class) - .hasMessageContaining("change streams"); + void transactionsAreOffUntilADeploymentAsksForThem() { + assertThat(MongoPlatformSettings.empty().transactions()).isFalse(); } private static java.util.Optional beanMethod(String name) { diff --git a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/autoconfigure/MongoStartupValidatorTest.java b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/autoconfigure/MongoStartupValidatorTest.java index 6729a1cc..bb480f27 100644 --- a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/autoconfigure/MongoStartupValidatorTest.java +++ b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/autoconfigure/MongoStartupValidatorTest.java @@ -32,7 +32,6 @@ class MongoStartupValidatorTest { validator( MongoProfileProperties.production("secret://mongodb/uri"), new MongoTopologyProbe(MongoTopology.STANDALONE, "8.0", 0), - true, true); assertThatThrownBy(validator::validate) @@ -46,7 +45,6 @@ class MongoStartupValidatorTest { validator( MongoProfileProperties.production("secret://mongodb/uri"), new MongoTopologyProbe(MongoTopology.SHARDED, "8.0", 2), - false, false); assertThatThrownBy(validator::validate) @@ -60,8 +58,7 @@ class MongoStartupValidatorTest { validator( MongoProfileProperties.local("secret://mongodb/uri"), new MongoTopologyProbe(MongoTopology.REPLICA_SET, "8.0", 2), - true, - false); + true); assertThatCode(validator::validate).doesNotThrowAnyException(); } @@ -72,7 +69,6 @@ class MongoStartupValidatorTest { validator( MongoProfileProperties.production("secret://mongodb/uri"), new MongoTopologyProbe(MongoTopology.REPLICA_SET, "8.0", 2), - true, true); assertThatCode(validator::validate).doesNotThrowAnyException(); @@ -112,7 +108,6 @@ class MongoStartupValidatorTest { new MongoPlatformSettings( Map.of("default", MongoProfileProperties.production("secret://mongodb/uri")), false, - false, 2)); assertThat(health.live()).isTrue(); @@ -128,7 +123,6 @@ class MongoStartupValidatorTest { new MongoPlatformSettings( Map.of("default", MongoProfileProperties.production("secret://mongodb/uri")), false, - false, 2)); assertThat(health.ready()).isTrue(); @@ -136,17 +130,13 @@ class MongoStartupValidatorTest { } private static MongoStartupValidator validator( - MongoProfileProperties profile, - MongoTopologyProbe probe, - boolean transactionsEnabled, - boolean changeStreamsEnabled) { + MongoProfileProperties profile, MongoTopologyProbe probe, boolean transactionsEnabled) { return new MongoStartupValidator( - new MongoPlatformSettings(Map.of("default", profile), false, false, null), + new MongoPlatformSettings(Map.of("default", profile), false, null), probe, MongoSecurityProfile.production(RUNTIME_CREDENTIAL, Set.of()), ADMIN_CREDENTIAL, transactionsEnabled, - changeStreamsEnabled, MongoSchemaVersionRange.of(1, 3)); } } diff --git a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/autoconfigure/ReactiveWiringCarriesTheContextTest.java b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/autoconfigure/ReactiveWiringCarriesTheContextTest.java deleted file mode 100644 index 831bf5f7..00000000 --- a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/autoconfigure/ReactiveWiringCarriesTheContextTest.java +++ /dev/null @@ -1,71 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.autoconfigure; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; - -import dev.caskeleton.adapter.outbound.mongo.api.consistency.MongoConsistencyProfile; -import dev.caskeleton.adapter.outbound.mongo.reactive.ReactiveMongoConsistencyBinder; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; -import org.springframework.boot.autoconfigure.AutoConfigurations; -import org.springframework.boot.test.context.runner.ApplicationContextRunner; -import org.springframework.data.mongodb.core.ReactiveMongoTemplate; -import org.springframework.test.util.ReflectionTestUtils; - -/** - * The reactive binder bean is built with the running context, not with the context-free defaults. - * - *

Separate from {@code MongoReactiveWiringTest}, which asserts that the reactive beans exist at - * all. Existing is not enough: a binder assembled from {@code MongoTemplateSupportContract - * .defaults()} produces per-profile templates that publish no lifecycle events and run no entity - * callbacks, so auditing silently stops applying to everything written through the reactive - * executor. This test fails if the auto-configuration is reverted to the two-argument constructor. - */ -@Tag("mongodb-contract") -class ReactiveWiringCarriesTheContextTest { - - @Test - @DisplayName("the auto-configured binder's templates carry the application context") - void theAutoConfiguredBinderCarriesTheContext() { - new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(MongoPlatformAutoConfiguration.ReactiveExecution.class)) - .withBean( - dev.caskeleton.adapter.outbound.mongo.api.consistency.MongoConsistencyRegistry.class, - dev.caskeleton.adapter.outbound.mongo.api.consistency.MongoConsistencyRegistry - ::standard) - .withBean( - dev.caskeleton.adapter.outbound.mongo.imperative.MongoCollectionProfileRegistry.class, - () -> - dev.caskeleton.adapter.outbound.mongo.imperative.MongoCollectionProfileRegistry - .builder() - .build()) - .withBean( - dev.caskeleton.adapter.outbound.mongo.failure.MongoFailureTranslator.class, - () -> mock(dev.caskeleton.adapter.outbound.mongo.failure.MongoFailureTranslator.class)) - .withBean( - dev.caskeleton.adapter.outbound.mongo.api.observation.MongoOperationObserver.class, - () -> - mock( - dev.caskeleton.adapter.outbound.mongo.api.observation.MongoOperationObserver - .class)) - .withBean( - ReactiveMongoTemplate.class, - () -> - new ReactiveMongoTemplate( - new org.springframework.data.mongodb.core.SimpleReactiveMongoDatabaseFactory( - mock(com.mongodb.reactivestreams.client.MongoClient.class), - "wiring-context-test"))) - .run( - context -> { - ReactiveMongoTemplate derived = - context - .getBean(ReactiveMongoConsistencyBinder.class) - .templateFor(MongoConsistencyProfile.PRIMARY_MAJORITY); - - assertThat(ReflectionTestUtils.getField(derived, "entityCallbacks")).isNotNull(); - assertThat(ReflectionTestUtils.getField(derived, "eventPublisher")).isNotNull(); - }); - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/changestream/MongoChangeStreamPipelineTest.java b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/changestream/MongoChangeStreamPipelineTest.java deleted file mode 100644 index c51cc246..00000000 --- a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/changestream/MongoChangeStreamPipelineTest.java +++ /dev/null @@ -1,153 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.changestream; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.adapter.outbound.mongo.changestream.projector.MongoChangeClaim; -import dev.caskeleton.adapter.outbound.mongo.changestream.projector.MongoChangeDeduplicationStore; -import dev.caskeleton.adapter.outbound.mongo.changestream.projector.MongoChangeProjectionResult; -import dev.caskeleton.adapter.outbound.mongo.changestream.projector.MongoChangeStreamRunner; -import java.time.Duration; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import org.bson.BsonDocument; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; - -/** - * Ordering, as a property of the pipeline rather than of every caller. - * - *

The runner exposed one event at a time and nothing owned the sequence. A caller using {@code - * flatMap} — the ordinary way to run reactive work — had B and C projecting while A was still in - * flight, and each advanced the checkpoint on completion. A crash after B's checkpoint and before A - * finished left the resume position past A, and a change stream never replays what the checkpoint - * has passed. - */ -@Tag("mongodb-contract") -class MongoChangeStreamPipelineTest { - - private static final MongoResumeCheckpoint CHECKPOINT = - MongoResumeCheckpoint.encrypted("orders", new byte[] {1}); - - @Test - @DisplayName("events are projected strictly in order") - void eventsAreProjectedStrictlyInOrder() { - List projected = new ArrayList<>(); - MongoChangeStreamPipeline pipeline = - new MongoChangeStreamPipeline( - new MongoChangeStreamRunner( - (identity, change) -> - Mono.fromCallable( - () -> { - projected.add(change.getString("id").getValue()); - return MongoChangeProjectionResult.applied(); - }) - // A later event completes faster; concatMap must still keep the order. - .delayElement(Duration.ofMillis(projected.isEmpty() ? 40 : 1)), - new AlwaysClaims(), - new NoOpCheckpoints())); - - pipeline.process(Flux.just(event("a", 1), event("b", 2), event("c", 3))).collectList().block(); - - assertThat(projected) - .as("with flatMap the fast events finish first and checkpoint past the slow one") - .containsExactly("a", "b", "c"); - } - - @Test - @DisplayName("an event behind the high-water mark is not reprocessed") - void anEventBehindTheHighWaterMarkIsDropped() { - List projected = new ArrayList<>(); - MongoChangeStreamPipeline pipeline = - new MongoChangeStreamPipeline( - new MongoChangeStreamRunner( - (identity, change) -> { - projected.add(change.getString("id").getValue()); - return Mono.just(MongoChangeProjectionResult.applied()); - }, - new AlwaysClaims(), - new NoOpCheckpoints())); - - pipeline - .process(Flux.just(event("a", 5), event("late", 2), event("b", 6))) - .collectList() - .block(); - - assertThat(projected) - .as("running it would move the resume checkpoint backwards over applied work") - .containsExactly("a", "b"); - assertThat(pipeline.highWaterMark()).isEqualTo(new MongoClusterTime(1_700_000_000L, 6)); - } - - @Test - @DisplayName("cluster time compares numerically, not as text") - void clusterTimeComparesNumerically() { - assertThat( - MongoClusterTime.parse("1700000000.10").isAfter(MongoClusterTime.parse("1700000000.9"))) - .as("text ordering puts .10 before .9, which a busy second produces constantly") - .isTrue(); - } - - @Test - @DisplayName("two events differing only by transaction position are distinct") - void twoEventsInOneTransactionAreDistinct() { - MongoChangeEventIdentity first = - MongoChangeEventIdentity.of("1700000000.1", "shop.orders", "{\"_id\":1}", "update", "0"); - MongoChangeEventIdentity second = - MongoChangeEventIdentity.of("1700000000.1", "shop.orders", "{\"_id\":1}", "update", "1"); - - assertThat(first) - .as("without the discriminator the second update is dropped as a redelivery of the first") - .isNotEqualTo(second); - } - - private static MongoChangeStreamPipeline.MongoChangeEvent event(String id, int increment) { - return new MongoChangeStreamPipeline.MongoChangeEvent( - MongoChangeEventIdentity.of( - "1700000000." + increment, "shop.orders", "{\"_id\":\"" + id + "\"}", "insert"), - new BsonDocument("id", new org.bson.BsonString(id)), - CHECKPOINT, - new MongoClusterTime(1_700_000_000L, increment)); - } - - /** A store that always grants the claim, so the pipeline's ordering is what is under test. */ - private static final class AlwaysClaims implements MongoChangeDeduplicationStore { - - @Override - public Mono tryClaim(MongoChangeEventIdentity identity, Duration lease) { - return Mono.just(MongoChangeClaim.CLAIMED); - } - - @Override - public Mono complete(MongoChangeEventIdentity identity) { - return Mono.empty(); - } - - @Override - public Mono releaseOrExpire(MongoChangeEventIdentity identity) { - return Mono.empty(); - } - } - - /** A checkpoint store that records nothing; ordering, not persistence, is under test. */ - private static final class NoOpCheckpoints implements MongoResumeCheckpointStore { - - @Override - public Mono> load(String subscriptionProfile) { - return Mono.just(Optional.empty()); - } - - @Override - public Mono save(MongoResumeCheckpoint checkpoint) { - return Mono.empty(); - } - - @Override - public Mono clear(String subscriptionProfile) { - return Mono.empty(); - } - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/changestream/MongoResumeCheckpointStoreTest.java b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/changestream/MongoResumeCheckpointStoreTest.java deleted file mode 100644 index 60a0312b..00000000 --- a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/changestream/MongoResumeCheckpointStoreTest.java +++ /dev/null @@ -1,85 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.changestream; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.outbound.mongo.api.CollectionProfileName; -import java.time.Duration; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -/** Design §20.2, §20.3 — a resume token is opaque, never logged, and knows how to be replayed. */ -@Tag("mongodb-contract") -class MongoResumeCheckpointStoreTest { - - @Test - void checkpointNeverExposesRawTokenInToString() { - MongoResumeCheckpoint checkpoint = - MongoResumeCheckpoint.encrypted("orders", new byte[] {1, 2, 3}); - - assertThat(checkpoint.toString()).doesNotContain("1, 2, 3"); - assertThat(checkpoint.toString()).contains("subscription=orders").contains("tokenChars="); - } - - @Test - void anInvalidateCheckpointRemembersItNeedsStartAfter() { - MongoResumeCheckpoint ordinary = - MongoResumeCheckpoint.encrypted("orders", new byte[] {1, 2, 3}); - MongoResumeCheckpoint afterInvalidate = - MongoResumeCheckpoint.afterInvalidate("orders", new byte[] {1, 2, 3}); - - assertThat(ordinary.position()).isEqualTo(MongoResumePosition.RESUME_AFTER); - assertThat(afterInvalidate.position()).isEqualTo(MongoResumePosition.START_AFTER); - } - - @Test - void aCheckpointFromAnotherClusterIsDetectable() { - MongoResumeCheckpoint checkpoint = - MongoResumeCheckpoint.encrypted("orders", new byte[] {1, 2, 3}) - .withClusterIdentity("cluster-a"); - - assertThat(checkpoint.belongsTo("cluster-a")).isTrue(); - assertThat(checkpoint.belongsTo("cluster-b")).isFalse(); - } - - @Test - void anEmptyTokenIsNotACheckpoint() { - assertThatThrownBy(() -> MongoResumeCheckpoint.encrypted("orders", new byte[0])) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void theStoredCiphertextRoundTrips() { - byte[] ciphertext = {9, 8, 7, 6}; - - assertThat(MongoResumeCheckpoint.encrypted("orders", ciphertext).ciphertext()) - .containsExactly(ciphertext); - } - - @Test - void aSubscriptionBoundsItsBatchAndAwaitTime() { - assertThatThrownBy( - () -> - new MongoChangeStreamSubscription( - "orders", - new CollectionProfileName("orders"), - 5_000, - Duration.ofSeconds(1), - false)) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void eventIdentityIsStableAcrossRedeliveryAndHidesTheDocumentKey() { - MongoChangeEventIdentity first = - MongoChangeEventIdentity.of("1700000000.1", "shop.orders", "{\"_id\":\"o-1\"}", "insert"); - MongoChangeEventIdentity second = - MongoChangeEventIdentity.of("1700000000.1", "shop.orders", "{\"_id\":\"o-1\"}", "insert"); - MongoChangeEventIdentity other = - MongoChangeEventIdentity.of("1700000000.2", "shop.orders", "{\"_id\":\"o-1\"}", "insert"); - - assertThat(first).isEqualTo(second); - assertThat(first).isNotEqualTo(other); - assertThat(first.value()).doesNotContain("o-1"); - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/changestream/consumer/ChangeStreamConsumerLifecycleTest.java b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/changestream/consumer/ChangeStreamConsumerLifecycleTest.java deleted file mode 100644 index a9c7b484..00000000 --- a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/changestream/consumer/ChangeStreamConsumerLifecycleTest.java +++ /dev/null @@ -1,332 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.changestream.consumer; - -import static org.assertj.core.api.Assertions.assertThat; - -import com.mongodb.MongoQueryException; -import com.mongodb.ServerAddress; -import com.mongodb.client.model.changestream.ChangeStreamDocument; -import com.mongodb.client.model.changestream.OperationType; -import dev.caskeleton.adapter.outbound.mongo.changestream.MongoChangeEventIdentity; -import dev.caskeleton.adapter.outbound.mongo.changestream.MongoChangeStreamPipeline; -import dev.caskeleton.adapter.outbound.mongo.changestream.MongoChangeStreamState; -import dev.caskeleton.adapter.outbound.mongo.changestream.MongoChangeStreamSubscription; -import dev.caskeleton.adapter.outbound.mongo.changestream.MongoResumeCheckpoint; -import dev.caskeleton.adapter.outbound.mongo.changestream.MongoResumeCheckpointStore; -import dev.caskeleton.adapter.outbound.mongo.changestream.MongoResumePosition; -import dev.caskeleton.adapter.outbound.mongo.changestream.MongoResumeTokenCodec; -import dev.caskeleton.adapter.outbound.mongo.changestream.projector.MongoChangeClaim; -import dev.caskeleton.adapter.outbound.mongo.changestream.projector.MongoChangeDeduplicationStore; -import dev.caskeleton.adapter.outbound.mongo.changestream.projector.MongoChangeProjectionResult; -import dev.caskeleton.adapter.outbound.mongo.changestream.projector.MongoChangeProjector; -import dev.caskeleton.adapter.outbound.mongo.changestream.projector.MongoChangeStreamRunner; -import dev.caskeleton.adapter.outbound.mongo.changestream.recovery.MongoChangeStreamRecoveryPolicy; -import dev.caskeleton.adapter.outbound.mongo.changestream.recovery.MongoInvalidateRecovery; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.atomic.AtomicInteger; -import org.bson.BsonDocument; -import org.bson.BsonString; -import org.bson.BsonTimestamp; -import org.bson.Document; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; -import org.springframework.data.mongodb.core.ChangeStreamEvent; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; -import reactor.test.StepVerifier; - -/** - * The change stream lifecycle, as a lifecycle. - * - *

Every part of it existed and nothing joined them: no production code opened a change stream at - * all, so the checkpoint store, the resume position, the recovery policy, the invalidate conversion - * and the ordered pipeline were components a deployment had no way to run. These cases are about - * the order and the transitions between them, which is exactly what no unit test of an individual - * piece could see. - */ -@Tag("mongodb-contract") -class ChangeStreamConsumerLifecycleTest { - - private static final MongoChangeStreamSubscription SUBSCRIPTION = - MongoChangeStreamSubscription.of("orders-projection", "orders"); - - private final RecordingCheckpointStore checkpoints = new RecordingCheckpointStore(); - - private final CountingProjector projector = new CountingProjector(); - - @Test - @DisplayName( - "a stored position is what the stream is opened at, with the option it was stored under") - void theStoredPositionIsWhereTheStreamOpens() { - checkpoints.stored = Optional.of(checkpoint("token-7", MongoResumePosition.RESUME_AFTER)); - RecordingSource source = - new RecordingSource(Flux.just(event("token-8", 8, OperationType.UPDATE))); - - StepVerifier.create(consumer(source).run()).expectNextCount(1).verifyComplete(); - - assertThat(source.openedAt).isPresent(); - assertThat(source.openedAt.orElseThrow().position()) - .isEqualTo(MongoResumePosition.RESUME_AFTER); - assertThat(source.openedAt.orElseThrow().token().getString("_data").getValue()) - .isEqualTo("token-7"); - } - - @Test - @DisplayName("an invalidate is stored as a startAfter position, while the event says so") - void anInvalidateIsStoredAsStartAfter() { - RecordingSource source = - new RecordingSource(Flux.just(event("token-9", 9, OperationType.INVALIDATE))); - - StepVerifier.create(consumer(source).run()).expectNextCount(1).verifyComplete(); - - assertThat(checkpoints.saved) - .singleElement() - .satisfies( - saved -> assertThat(saved.position()).isEqualTo(MongoResumePosition.START_AFTER)); - } - - @Test - @DisplayName("a resumable failure reopens from the stored checkpoint rather than from now") - void aResumableFailureReopensFromTheCheckpoint() { - checkpoints.stored = Optional.of(checkpoint("token-1", MongoResumePosition.RESUME_AFTER)); - MongoQueryException resumable = queryFailure(133, "ResumableChangeStreamError"); - RecordingSource source = - new RecordingSource( - Flux.error(resumable), Flux.just(event("token-2", 2, OperationType.INSERT))); - - ReactiveMongoChangeStreamConsumer consumer = consumer(source); - StepVerifier.create(consumer.run()).expectNextCount(1).verifyComplete(); - - assertThat(source.opens).isEqualTo(2); - assertThat(source.reopenedAt.orElseThrow().token().getString("_data").getValue()) - .as("the last written position is the last event a projection completed for") - .isEqualTo("token-1"); - } - - @Test - @DisplayName("a lost history stops the subscription and names the runbook") - void aLostHistoryStopsTheSubscription() { - RecordingSource source = new RecordingSource(Flux.error(queryFailure(286, ""))); - ReactiveMongoChangeStreamConsumer consumer = consumer(source); - - StepVerifier.create(consumer.run()).verifyError(MongoQueryException.class); - - assertThat(consumer.state()).isEqualTo(MongoChangeStreamState.HISTORY_LOST); - assertThat(consumer.requiredRunbook()) - .isEqualTo(MongoChangeStreamRecoveryPolicy.HISTORY_LOST_RUNBOOK); - assertThat(source.opens) - .as("restarting from now would hide the gap, not close it") - .isEqualTo(1); - assertThat(checkpoints.saved).isEmpty(); - } - - @Test - @DisplayName("a projection failure stops the subscription rather than resuming the stream") - void aProjectionFailureStopsTheSubscription() { - projector.failing = true; - RecordingSource source = - new RecordingSource(Flux.just(event("token-3", 3, OperationType.UPDATE))); - ReactiveMongoChangeStreamConsumer consumer = consumer(source); - - StepVerifier.create(consumer.run()).verifyError(IllegalStateException.class); - - assertThat(consumer.state()).isEqualTo(MongoChangeStreamState.FAILED); - assertThat(source.opens).as("reopening a stream does not fix a projector").isEqualTo(1); - assertThat(checkpoints.saved).isEmpty(); - } - - @Test - @DisplayName("the checkpoint is written after the projection, never before") - void theCheckpointFollowsTheProjection() { - RecordingSource source = - new RecordingSource( - Flux.just( - event("token-4", 4, OperationType.INSERT), - event("token-5", 5, OperationType.INSERT))); - - StepVerifier.create(consumer(source).run()).expectNextCount(2).verifyComplete(); - - assertThat(projector.projected).hasValue(2); - assertThat(checkpoints.order) - .containsExactly("project:token-4", "save:token-4", "project:token-5", "save:token-5"); - } - - private ReactiveMongoChangeStreamConsumer consumer(MongoChangeStreamSource source) { - return new ReactiveMongoChangeStreamConsumer( - SUBSCRIPTION, - source, - checkpoints, - new PlainTextCodec(), - new MongoChangeStreamPipeline( - new MongoChangeStreamRunner(projector, new AlwaysClaims(), checkpoints)), - new MongoChangeStreamRecoveryPolicy(), - new MongoInvalidateRecovery()); - } - - private static MongoQueryException queryFailure(int code, String label) { - BsonDocument response = - new BsonDocument("ok", new org.bson.BsonInt32(0)) - .append("code", new org.bson.BsonInt32(code)) - .append("errmsg", new BsonString("change stream failure")); - if (!label.isBlank()) { - response.append("errorLabels", new org.bson.BsonArray(List.of(new BsonString(label)))); - } - return new MongoQueryException(response, new ServerAddress()); - } - - private MongoResumeCheckpoint checkpoint(String token, MongoResumePosition position) { - return new PlainTextCodec() - .encode( - SUBSCRIPTION.subscriptionProfile(), - new BsonDocument("_data", new BsonString(token)), - position); - } - - private static ChangeStreamEvent event( - String token, int clusterSeconds, OperationType operation) { - ChangeStreamDocument raw = - new ChangeStreamDocument<>( - operation.getValue(), - new BsonDocument("_data", new BsonString(token)), - new BsonDocument("db", new BsonString("app")).append("coll", new BsonString("orders")), - null, - null, - new Document("_id", token), - null, - new BsonDocument("_id", new BsonString(token)), - new BsonTimestamp(clusterSeconds, 1), - null, - null, - null, - null, - null, - null); - return new ChangeStreamEvent<>(raw, Document.class, null); - } - - /** A codec that does not protect anything, so the test can read what was stored. */ - private static final class PlainTextCodec implements MongoResumeTokenCodec { - - @Override - public MongoResumeCheckpoint encode( - String subscriptionProfile, BsonDocument token, MongoResumePosition position) { - byte[] bytes = token.toJson().getBytes(StandardCharsets.UTF_8); - MongoResumeCheckpoint base = - position == MongoResumePosition.START_AFTER - ? MongoResumeCheckpoint.afterInvalidate(subscriptionProfile, bytes) - : MongoResumeCheckpoint.encrypted(subscriptionProfile, bytes); - return base; - } - - @Override - public BsonDocument decode(MongoResumeCheckpoint checkpoint) { - return BsonDocument.parse(new String(checkpoint.ciphertext(), StandardCharsets.UTF_8)); - } - } - - /** Hands out prepared streams and records what each open was asked to resume from. */ - private static final class RecordingSource implements MongoChangeStreamSource { - - private final List>> streams = new ArrayList<>(); - - private int opens; - - private Optional openedAt = Optional.empty(); - - private Optional reopenedAt = Optional.empty(); - - @SafeVarargs - private RecordingSource(Flux>... prepared) { - this.streams.addAll(List.of(prepared)); - } - - @Override - public Flux> open( - MongoChangeStreamSubscription subscription, Optional resumeFrom) { - if (opens == 0) { - openedAt = resumeFrom; - } else { - reopenedAt = resumeFrom; - } - Flux> stream = streams.get(Math.min(opens, streams.size() - 1)); - opens++; - return stream; - } - } - - /** Records the interleaving of projections and checkpoint writes. */ - private static final class RecordingCheckpointStore implements MongoResumeCheckpointStore { - - private Optional stored = Optional.empty(); - - private final List saved = new ArrayList<>(); - - private final List order = new ArrayList<>(); - - @Override - public Mono> load(String subscriptionProfile) { - return Mono.just(stored); - } - - @Override - public Mono save(MongoResumeCheckpoint checkpoint) { - return Mono.fromRunnable( - () -> { - saved.add(checkpoint); - order.add( - "save:" - + BsonDocument.parse( - new String(checkpoint.ciphertext(), StandardCharsets.UTF_8)) - .getString("_data") - .getValue()); - }); - } - - @Override - public Mono clear(String subscriptionProfile) { - return Mono.fromRunnable(() -> stored = Optional.empty()); - } - } - - /** A projector that records what it was given, and can be told to fail. */ - private final class CountingProjector implements MongoChangeProjector { - - private final AtomicInteger projected = new AtomicInteger(); - - private boolean failing; - - @Override - public Mono project( - MongoChangeEventIdentity identity, BsonDocument change) { - if (failing) { - return Mono.error(new IllegalStateException("the projector refused this change")); - } - projected.incrementAndGet(); - checkpoints.order.add("project:" + change.getString("_id").getValue()); - return Mono.just(MongoChangeProjectionResult.applied()); - } - } - - /** Deduplication that always grants the claim, so these cases are about the lifecycle. */ - private static final class AlwaysClaims implements MongoChangeDeduplicationStore { - - @Override - public Mono tryClaim( - MongoChangeEventIdentity identity, java.time.Duration lease) { - return Mono.just(MongoChangeClaim.CLAIMED); - } - - @Override - public Mono complete(MongoChangeEventIdentity identity) { - return Mono.empty(); - } - - @Override - public Mono releaseOrExpire(MongoChangeEventIdentity identity) { - return Mono.empty(); - } - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/changestream/projector/MongoChangeStreamRunnerTest.java b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/changestream/projector/MongoChangeStreamRunnerTest.java deleted file mode 100644 index 39c83409..00000000 --- a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/changestream/projector/MongoChangeStreamRunnerTest.java +++ /dev/null @@ -1,357 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.changestream.projector; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.adapter.outbound.mongo.changestream.MongoChangeEventIdentity; -import dev.caskeleton.adapter.outbound.mongo.changestream.MongoResumeCheckpoint; -import dev.caskeleton.adapter.outbound.mongo.changestream.MongoResumeCheckpointStore; -import java.util.HashSet; -import java.util.Optional; -import java.util.Set; -import java.util.concurrent.atomic.AtomicInteger; -import org.bson.BsonDocument; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; -import reactor.core.publisher.Mono; - -/** Design §20.2 — project first, checkpoint second, and never repeat a side effect. */ -@Tag("mongodb-contract") -class MongoChangeStreamRunnerTest { - - private static final MongoChangeEventIdentity IDENTITY = - MongoChangeEventIdentity.of("1700000000.1", "shop.orders", "{\"_id\":\"o-1\"}", "insert"); - - private static final MongoResumeCheckpoint CHECKPOINT = - MongoResumeCheckpoint.encrypted("orders", new byte[] {1, 2, 3}); - - @Test - void failedProjectionDoesNotAdvanceCheckpoint() { - RecordingCheckpointStore checkpoints = new RecordingCheckpointStore(); - MongoChangeStreamRunner runner = - new MongoChangeStreamRunner( - (identity, change) -> Mono.error(new IllegalStateException("projector failed")), - new ClaimingDeduplicationStore(), - checkpoints); - - runner - .runOne(IDENTITY, new BsonDocument(), CHECKPOINT) - .onErrorResume(failure -> Mono.empty()) - .block(); - - assertThat(checkpoints.saveCount()).isZero(); - } - - @Test - void aSuccessfulProjectionAdvancesTheCheckpointAfterwards() { - RecordingCheckpointStore checkpoints = new RecordingCheckpointStore(); - AtomicInteger projections = new AtomicInteger(); - MongoChangeStreamRunner runner = - new MongoChangeStreamRunner( - (identity, change) -> { - projections.incrementAndGet(); - return Mono.just(MongoChangeProjectionResult.applied()); - }, - new ClaimingDeduplicationStore(), - checkpoints); - - runner.runOne(IDENTITY, new BsonDocument(), CHECKPOINT).block(); - - assertThat(projections).hasValue(1); - assertThat(checkpoints.saveCount()).isEqualTo(1); - } - - @Test - void aRedeliveredEventDoesNotRepeatTheSideEffect() { - RecordingCheckpointStore checkpoints = new RecordingCheckpointStore(); - AtomicInteger projections = new AtomicInteger(); - ClaimingDeduplicationStore deduplication = new ClaimingDeduplicationStore(); - MongoChangeStreamRunner runner = - new MongoChangeStreamRunner( - (identity, change) -> { - projections.incrementAndGet(); - return Mono.just(MongoChangeProjectionResult.applied()); - }, - deduplication, - checkpoints); - - runner.runOne(IDENTITY, new BsonDocument(), CHECKPOINT).block(); - MongoChangeProjectionResult second = - runner.runOne(IDENTITY, new BsonDocument(), CHECKPOINT).block(); - - assertThat(projections).hasValue(1); - assertThat(second.outcome()).isEqualTo(MongoChangeProjectionResult.Outcome.SKIPPED_DUPLICATE); - assertThat(checkpoints.saveCount()).isEqualTo(2); - } - - @Test - void aParkedEventDoesNotAdvanceTheCheckpoint() { - RecordingCheckpointStore checkpoints = new RecordingCheckpointStore(); - MongoChangeStreamRunner runner = - new MongoChangeStreamRunner( - (identity, change) -> Mono.just(MongoChangeProjectionResult.parked("malformed")), - new ClaimingDeduplicationStore(), - checkpoints); - - runner.runOne(IDENTITY, new BsonDocument(), CHECKPOINT).block(); - - assertThat(checkpoints.saveCount()).isZero(); - } - - /** Counts checkpoint saves. */ - private static final class RecordingCheckpointStore implements MongoResumeCheckpointStore { - - private final AtomicInteger saves = new AtomicInteger(); - - @Override - public Mono> load(String subscriptionProfile) { - return Mono.just(Optional.empty()); - } - - @Override - public Mono save(MongoResumeCheckpoint checkpoint) { - saves.incrementAndGet(); - return Mono.empty(); - } - - @Override - public Mono clear(String subscriptionProfile) { - return Mono.empty(); - } - - private int saveCount() { - return saves.get(); - } - } - - @Test - @org.junit.jupiter.api.DisplayName("two concurrent runners project exactly once") - void twoConcurrentRunnersProjectExactlyOnce() throws Exception { - RecordingCheckpointStore checkpoints = new RecordingCheckpointStore(); - AtomicInteger projections = new AtomicInteger(); - java.util.concurrent.CountDownLatch bothInside = new java.util.concurrent.CountDownLatch(2); - ClaimingDeduplicationStore deduplication = new ClaimingDeduplicationStore(); - MongoChangeStreamRunner runner = - new MongoChangeStreamRunner( - (identity, change) -> - Mono.fromCallable( - () -> { - projections.incrementAndGet(); - // Hold inside the projection so the two attempts overlap. The old store - // answered alreadyProjected=false to both, and both projected. - bothInside.countDown(); - bothInside.await(200, java.util.concurrent.TimeUnit.MILLISECONDS); - return MongoChangeProjectionResult.applied(); - }), - deduplication, - checkpoints); - - java.util.concurrent.ExecutorService pool = - java.util.concurrent.Executors.newFixedThreadPool(2); - try { - java.util.List> both = - pool.invokeAll( - java.util.List.of( - () -> runner.runOne(IDENTITY, new BsonDocument(), CHECKPOINT).block(), - () -> runner.runOne(IDENTITY, new BsonDocument(), CHECKPOINT).block())); - java.util.List outcomes = new java.util.ArrayList<>(); - for (java.util.concurrent.Future future : both) { - outcomes.add(future.get().outcome()); - } - - assertThat(projections) - .as("the second runner must be told BUSY or ALREADY_COMPLETED, never allowed to project") - .hasValue(1); - assertThat(outcomes).contains(MongoChangeProjectionResult.Outcome.APPLIED); - } finally { - pool.shutdownNow(); - bothInside.countDown(); - } - } - - @Test - @org.junit.jupiter.api.DisplayName("a busy claim never advances the checkpoint") - void aBusyClaimNeverAdvancesTheCheckpoint() { - RecordingCheckpointStore checkpoints = new RecordingCheckpointStore(); - ClaimingDeduplicationStore deduplication = new ClaimingDeduplicationStore(); - deduplication.claimFor(IDENTITY); - - MongoChangeStreamRunner runner = - new MongoChangeStreamRunner( - (identity, change) -> Mono.just(MongoChangeProjectionResult.applied()), - deduplication, - checkpoints); - - MongoChangeProjectionResult result = - runner.runOne(IDENTITY, new BsonDocument(), CHECKPOINT).block(); - - assertThat(result.outcome()).isEqualTo(MongoChangeProjectionResult.Outcome.CLAIMED_ELSEWHERE); - assertThat(checkpoints.saveCount()) - .as("the holder may still fail, and the stream never replays what the checkpoint passed") - .isZero(); - } - - @Test - @org.junit.jupiter.api.DisplayName("a crash after claiming leaves the event retryable") - void aCrashAfterClaimingLeavesTheEventRetryable() { - RecordingCheckpointStore checkpoints = new RecordingCheckpointStore(); - ClaimingDeduplicationStore deduplication = new ClaimingDeduplicationStore(); - AtomicInteger attempts = new AtomicInteger(); - MongoChangeStreamRunner runner = - new MongoChangeStreamRunner( - (identity, change) -> - attempts.incrementAndGet() == 1 - ? Mono.error(new IllegalStateException("worker died mid-projection")) - : Mono.just(MongoChangeProjectionResult.applied()), - deduplication, - checkpoints); - - runner - .runOne(IDENTITY, new BsonDocument(), CHECKPOINT) - .onErrorResume(failure -> Mono.empty()) - .block(); - MongoChangeProjectionResult retry = - runner.runOne(IDENTITY, new BsonDocument(), CHECKPOINT).block(); - - assertThat(retry.outcome()).isEqualTo(MongoChangeProjectionResult.Outcome.APPLIED); - assertThat(checkpoints.saveCount()).isEqualTo(1); - } - - @Test - @org.junit.jupiter.api.DisplayName("a parked event releases its claim instead of holding it") - void aParkedEventReleasesItsClaim() { - ClaimingDeduplicationStore deduplication = new ClaimingDeduplicationStore(); - MongoChangeStreamRunner runner = - new MongoChangeStreamRunner( - (identity, change) -> Mono.just(MongoChangeProjectionResult.parked("malformed")), - deduplication, - new RecordingCheckpointStore()); - - runner.runOne(IDENTITY, new BsonDocument(), CHECKPOINT).block(); - - assertThat(deduplication.isHeld(IDENTITY)) - .as("a parked event that keeps its claim reports BUSY for the whole lease") - .isFalse(); - } - - @Test - @org.junit.jupiter.api.DisplayName("an empty store answer is a protocol violation, not a no") - void anEmptyStoreAnswerIsAProtocolViolation() { - MongoChangeStreamRunner runner = - new MongoChangeStreamRunner( - (identity, change) -> Mono.just(MongoChangeProjectionResult.applied()), - new EmptyDeduplicationStore(), - new RecordingCheckpointStore()); - - org.assertj.core.api.Assertions.assertThatThrownBy( - () -> runner.runOne(IDENTITY, new BsonDocument(), CHECKPOINT).block()) - .as("an empty Mono used to flow through flatMap: no projection, no checkpoint, no error") - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("tryClaim"); - } - - @Test - @org.junit.jupiter.api.DisplayName("an empty projector answer is a protocol violation too") - void anEmptyProjectorAnswerIsAProtocolViolation() { - MongoChangeStreamRunner runner = - new MongoChangeStreamRunner( - (identity, change) -> Mono.empty(), - new ClaimingDeduplicationStore(), - new RecordingCheckpointStore()); - - org.assertj.core.api.Assertions.assertThatThrownBy( - () -> runner.runOne(IDENTITY, new BsonDocument(), CHECKPOINT).block()) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("project"); - } - - @Test - @org.junit.jupiter.api.DisplayName("an expired lease lets another worker take the event") - void anExpiredLeaseLetsAnotherWorkerTakeTheEvent() { - ClaimingDeduplicationStore deduplication = new ClaimingDeduplicationStore(); - deduplication.claimFor(IDENTITY); - deduplication.expireEverything(); - - MongoChangeStreamRunner runner = - new MongoChangeStreamRunner( - (identity, change) -> Mono.just(MongoChangeProjectionResult.applied()), - deduplication, - new RecordingCheckpointStore()); - - assertThat(runner.runOne(IDENTITY, new BsonDocument(), CHECKPOINT).block().outcome()) - .isEqualTo(MongoChangeProjectionResult.Outcome.APPLIED); - } - - /** - * An in-memory claim store with the atomicity a real one must have. - * - *

The claim transition is one synchronized step, which is the whole point: the fixture cannot - * express the check-then-act shape the production store used to have. - */ - private static final class ClaimingDeduplicationStore implements MongoChangeDeduplicationStore { - - private final Set completed = new HashSet<>(); - - private final Set held = new HashSet<>(); - - private boolean leasesExpired; - - @Override - public synchronized Mono tryClaim( - MongoChangeEventIdentity identity, java.time.Duration lease) { - if (completed.contains(identity)) { - return Mono.just(MongoChangeClaim.ALREADY_COMPLETED); - } - if (held.contains(identity) && !leasesExpired) { - return Mono.just(MongoChangeClaim.BUSY); - } - held.add(identity); - leasesExpired = false; - return Mono.just(MongoChangeClaim.CLAIMED); - } - - @Override - public synchronized Mono complete(MongoChangeEventIdentity identity) { - held.remove(identity); - completed.add(identity); - return Mono.empty(); - } - - @Override - public synchronized Mono releaseOrExpire(MongoChangeEventIdentity identity) { - held.remove(identity); - return Mono.empty(); - } - - private synchronized void claimFor(MongoChangeEventIdentity identity) { - held.add(identity); - } - - private synchronized void expireEverything() { - leasesExpired = true; - } - - private synchronized boolean isHeld(MongoChangeEventIdentity identity) { - return held.contains(identity); - } - } - - /** A store that completes without answering, which used to read as "not projected". */ - private static final class EmptyDeduplicationStore implements MongoChangeDeduplicationStore { - - @Override - public Mono tryClaim( - MongoChangeEventIdentity identity, java.time.Duration lease) { - return Mono.empty(); - } - - @Override - public Mono complete(MongoChangeEventIdentity identity) { - return Mono.empty(); - } - - @Override - public Mono releaseOrExpire(MongoChangeEventIdentity identity) { - return Mono.empty(); - } - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/changestream/recovery/MongoChangeStreamRecoveryPolicyTest.java b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/changestream/recovery/MongoChangeStreamRecoveryPolicyTest.java deleted file mode 100644 index d20e9e47..00000000 --- a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/changestream/recovery/MongoChangeStreamRecoveryPolicyTest.java +++ /dev/null @@ -1,69 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.changestream.recovery; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.outbound.mongo.changestream.MongoChangeStreamState; -import dev.caskeleton.adapter.outbound.mongo.changestream.MongoResumeCheckpoint; -import dev.caskeleton.adapter.outbound.mongo.changestream.MongoResumePosition; -import dev.caskeleton.adapter.outbound.mongo.failure.MongoDriverFailureView; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -/** Design §20.3 — a lost oplog history stops consumption instead of silently skipping a gap. */ -@Tag("mongodb-contract") -class MongoChangeStreamRecoveryPolicyTest { - - private final MongoChangeStreamRecoveryPolicy policy = new MongoChangeStreamRecoveryPolicy(); - - @Test - void historyLostNeverStartsFromNowAutomatically() { - MongoChangeStreamRecoveryDecision decision = policy.onHistoryLost("orders"); - - assertThat(decision.state()).isEqualTo(MongoChangeStreamState.HISTORY_LOST); - assertThat(decision.autoResume()).isFalse(); - assertThat(decision.requiredRunbook()) - .isEqualTo(MongoChangeStreamRecoveryPolicy.HISTORY_LOST_RUNBOOK); - } - - @Test - void aResumableFailureResumesWithoutAnOperator() { - assertThat(policy.onResumableFailure().autoResume()).isTrue(); - } - - @Test - void theHistoryLostServerCodesAreRecognised() { - assertThat(policy.onFailure(MongoDriverFailureView.withServerCode(286)).state()) - .isEqualTo(MongoChangeStreamState.HISTORY_LOST); - assertThat(policy.onFailure(MongoDriverFailureView.withServerCode(280)).state()) - .isEqualTo(MongoChangeStreamState.HISTORY_LOST); - } - - @Test - void anUnclassifiedFailureStopsAndNamesARunbook() { - MongoChangeStreamRecoveryDecision decision = - policy.onFailure(MongoDriverFailureView.withServerCode(1)); - - assertThat(decision.state()).isEqualTo(MongoChangeStreamState.FAILED); - assertThat(decision.autoResume()).isFalse(); - assertThat(decision.requiredRunbook()).isNotBlank(); - } - - @Test - void anInvalidateCheckpointMustBeReplayedWithStartAfter() { - MongoInvalidateRecovery recovery = new MongoInvalidateRecovery(); - MongoResumeCheckpoint checkpoint = recovery.checkpointFor("orders", new byte[] {1, 2, 3}); - - assertThat(checkpoint.position()).isEqualTo(MongoResumePosition.START_AFTER); - assertThatThrownBy( - () -> recovery.requireCorrectResumeOption(checkpoint, MongoResumePosition.RESUME_AFTER)) - .isInstanceOf(IllegalStateException.class); - } - - @Test - void onlyTheRunningStatesResumeOnTheirOwn() { - assertThat(MongoChangeStreamState.RUNNING.autoResumable()).isTrue(); - assertThat(MongoChangeStreamState.HISTORY_LOST.autoResumable()).isFalse(); - assertThat(MongoChangeStreamState.FAILED.autoResumable()).isFalse(); - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/client/MongoClientSettingsFactoryTest.java b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/client/MongoClientSettingsFactoryTest.java index 4194ff39..4c329668 100644 --- a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/client/MongoClientSettingsFactoryTest.java +++ b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/client/MongoClientSettingsFactoryTest.java @@ -116,7 +116,6 @@ class MongoClientSettingsFactoryTest { new MongoPlatformSettings( Map.of(ACTIVE, profile(), "unused", profileWith("secret://mongodb/never-read")), false, - false, null); new MongoClientSettingsFactory(settings, ACTIVE, resolver(resolved)).create(); @@ -156,7 +155,7 @@ class MongoClientSettingsFactoryTest { } private static MongoPlatformSettings settingsWith(MongoProfileProperties profile) { - return new MongoPlatformSettings(Map.of(ACTIVE, profile), false, false, null); + return new MongoPlatformSettings(Map.of(ACTIVE, profile), false, null); } private static MongoProfileProperties profile() { diff --git a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/client/MongoProfileClientSettingsAutoConfigurationTest.java b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/client/MongoProfileClientSettingsAutoConfigurationTest.java index 3c9efd37..4c345890 100644 --- a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/client/MongoProfileClientSettingsAutoConfigurationTest.java +++ b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/client/MongoProfileClientSettingsAutoConfigurationTest.java @@ -30,7 +30,7 @@ class MongoProfileClientSettingsAutoConfigurationTest { .withUserConfiguration(MongoProfileClientSettingsAutoConfiguration.class) .withBean( MongoPlatformSettings.class, - () -> new MongoPlatformSettings(Map.of(ACTIVE, profile), false, false, null)) + () -> new MongoPlatformSettings(Map.of(ACTIVE, profile), false, null)) .withBean(MongoCredentialResolver.class, () -> resolver(URI)) .withPropertyValues( "ca-skeleton.persistence-mongo.enabled=true", @@ -66,7 +66,7 @@ class MongoProfileClientSettingsAutoConfigurationTest { .withUserConfiguration(MongoProfileClientSettingsAutoConfiguration.class) .withBean( MongoPlatformSettings.class, - () -> new MongoPlatformSettings(Map.of(ACTIVE, profile), false, false, null)) + () -> new MongoPlatformSettings(Map.of(ACTIVE, profile), false, null)) .withBean(MongoCredentialResolver.class, () -> resolver(URI)) .withPropertyValues( "ca-skeleton.persistence-mongo.enabled=true", @@ -139,7 +139,7 @@ class MongoProfileClientSettingsAutoConfigurationTest { .withUserConfiguration(MongoProfileClientSettingsAutoConfiguration.class) .withBean( MongoPlatformSettings.class, - () -> new MongoPlatformSettings(Map.of(ACTIVE, profile), false, false, null)) + () -> new MongoPlatformSettings(Map.of(ACTIVE, profile), false, null)) .withPropertyValues( "ca-skeleton.persistence-mongo.enabled=true", "ca-skeleton.persistence-mongo.active-profile=" + ACTIVE) diff --git a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/imperative/ScopedAccessSurfaceTest.java b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/imperative/ScopedAccessSurfaceTest.java index 5316416f..a1ee85a9 100644 --- a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/imperative/ScopedAccessSurfaceTest.java +++ b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/imperative/ScopedAccessSurfaceTest.java @@ -2,15 +2,12 @@ package dev.caskeleton.adapter.outbound.mongo.imperative; import static org.assertj.core.api.Assertions.assertThat; -import dev.caskeleton.adapter.outbound.mongo.reactive.ReactiveMongoCollectionAccess; -import dev.caskeleton.adapter.outbound.mongo.reactive.ReactiveScopedMongoOperations; import java.lang.reflect.Method; import java.util.Arrays; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.springframework.data.mongodb.core.MongoOperations; -import org.springframework.data.mongodb.core.ReactiveMongoOperations; /** * What a callback can reach, as a property of the API rather than of the caller's discipline. @@ -29,8 +26,6 @@ class ScopedAccessSurfaceTest { assertThat(returnTypesOf(MongoCollectionAccess.class)) .as("a scoped API with an escape hatch is an escape hatch") .doesNotContain(MongoOperations.class); - assertThat(returnTypesOf(ReactiveMongoCollectionAccess.class)) - .doesNotContain(ReactiveMongoOperations.class); } @Test @@ -39,7 +34,6 @@ class ScopedAccessSurfaceTest { assertThat(methodsTakingAString(ScopedMongoOperations.class)) .as("wrong collection must not be a mistake a caller can make") .isEmpty(); - assertThat(methodsTakingAString(ReactiveScopedMongoOperations.class)).isEmpty(); } @Test @@ -51,14 +45,6 @@ class ScopedAccessSurfaceTest { .isTrue(); } - @Test - @DisplayName("the two scoped APIs offer the same operations") - void theTwoScopedApisAreSymmetrical() { - assertThat(methodNamesOf(ScopedMongoOperations.class)) - .as("a use case moving between blocking and reactive must not re-derive its guardrails") - .isEqualTo(methodNamesOf(ReactiveScopedMongoOperations.class)); - } - private static java.util.Set> returnTypesOf(Class type) { return Arrays.stream(type.getDeclaredMethods()) .map(Method::getReturnType) @@ -71,10 +57,4 @@ class ScopedAccessSurfaceTest { .map(Method::getName) .toList(); } - - private static java.util.Set methodNamesOf(Class type) { - return Arrays.stream(type.getDeclaredMethods()) - .map(Method::getName) - .collect(java.util.stream.Collectors.toCollection(java.util.TreeSet::new)); - } } diff --git a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/reactive/ReactiveBinderCarriesRuntimeContractTest.java b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/reactive/ReactiveBinderCarriesRuntimeContractTest.java deleted file mode 100644 index 4137ab8f..00000000 --- a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/reactive/ReactiveBinderCarriesRuntimeContractTest.java +++ /dev/null @@ -1,80 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.reactive; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.adapter.outbound.mongo.api.consistency.MongoConsistencyProfile; -import dev.caskeleton.adapter.outbound.mongo.api.consistency.MongoConsistencyRegistry; -import dev.caskeleton.adapter.outbound.mongo.imperative.MongoTemplateSupportContract; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.EnumSource; -import org.springframework.context.ApplicationContext; -import org.springframework.context.support.StaticApplicationContext; -import org.springframework.data.mongodb.core.ReactiveMongoTemplate; -import org.springframework.data.mongodb.core.SimpleReactiveMongoDatabaseFactory; -import org.springframework.test.util.ReflectionTestUtils; - -/** - * What a profile-bound reactive template keeps from the template it was derived from. - * - *

The imperative binder was given a support contract; the reactive one derived its per-profile - * templates with a read preference and a write concern and nothing else. So a document written - * through the reactive executor skipped auditing and {@code BeforeConvertCallback} while the same - * document written through an ordinary reactive repository did not — two documents, one mapping. - * That was unreachable while no configuration built the reactive path, and became reachable the - * moment {@code MongoPlatformAutoConfiguration.ReactiveExecution} started declaring it. - * - *

Asserted on {@code entityCallbacks} and {@code eventPublisher} because Spring Data exposes - * setters for both and getters for neither: those two fields are populated only by {@code - * setApplicationContext}, which is exactly the step that used to be missing. - */ -@Tag("mongodb-contract") -class ReactiveBinderCarriesRuntimeContractTest { - - private static ReactiveMongoTemplate sourceTemplate() { - // A real template over a real factory: the binder derives by constructing - // `new ReactiveMongoTemplate(factory, converter)`, so mocking the template would lose the - // contract under test. The client itself is mocked so this hermetic test creates no driver - // monitor threads. - return new ReactiveMongoTemplate( - new SimpleReactiveMongoDatabaseFactory( - org.mockito.Mockito.mock(com.mongodb.reactivestreams.client.MongoClient.class), - "reactive-contract-test")); - } - - @ParameterizedTest - @EnumSource(MongoConsistencyProfile.class) - @DisplayName("every profile's derived template carries the context it was configured with") - void everyProfileCarriesTheContext(MongoConsistencyProfile profile) { - ApplicationContext context = new StaticApplicationContext(); - - ReactiveMongoConsistencyBinder binder = - new ReactiveMongoConsistencyBinder( - sourceTemplate(), - MongoConsistencyRegistry.standard(), - MongoTemplateSupportContract.inContext(context)); - - ReactiveMongoTemplate derived = binder.templateFor(profile); - - assertThat(ReflectionTestUtils.getField(derived, "entityCallbacks")) - .as("entity callbacks are what auditing and BeforeConvertCallback run through") - .isNotNull(); - assertThat(ReflectionTestUtils.getField(derived, "eventPublisher")).isNotNull(); - } - - @Test - @DisplayName("the contract-free constructor derives a template with no context, and says so") - void theContractFreeConstructorDerivesAContextFreeTemplate() { - ReactiveMongoConsistencyBinder binder = - new ReactiveMongoConsistencyBinder(sourceTemplate(), MongoConsistencyRegistry.standard()); - - ReactiveMongoTemplate derived = binder.templateFor(MongoConsistencyProfile.PRIMARY_MAJORITY); - - // This is the shipped behaviour of a binder built without a contract, not an aspiration: the - // two-argument constructor exists for callers that have no context to give, and it must not - // pretend otherwise. Production wiring uses the three-argument one. - assertThat(ReflectionTestUtils.getField(derived, "entityCallbacks")).isNull(); - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/reactive/cursor/MongoCursorGuardTest.java b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/reactive/cursor/MongoCursorGuardTest.java deleted file mode 100644 index f5ae5750..00000000 --- a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/reactive/cursor/MongoCursorGuardTest.java +++ /dev/null @@ -1,107 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.reactive.cursor; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.outbound.mongo.api.error.MongoOperationRejectedException; -import dev.caskeleton.adapter.outbound.mongo.query.budget.MongoOperationBudget; -import java.time.Duration; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.atomic.AtomicInteger; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; -import reactor.core.publisher.Flux; -import reactor.test.StepVerifier; - -/** Design §32 — a cursor is released on every termination path, cancellation included. */ -@Tag("mongodb-contract") -class MongoCursorGuardTest { - - @Test - void cancelClosesCursorExactlyOnce() { - CountingLease lease = new CountingLease(); - MongoCursorGuard guard = MongoCursorGuard.withLifetime(Duration.ofSeconds(5)); - - StepVerifier.create(guard.guard(() -> lease, ignored -> Flux.never())).thenCancel().verify(); - - assertThat(lease.closeCount()).isEqualTo(1); - } - - @Test - void completionAlsoClosesTheCursor() { - CountingLease lease = new CountingLease(); - MongoCursorGuard guard = MongoCursorGuard.withLifetime(Duration.ofSeconds(5)); - - StepVerifier.create(guard.guard(() -> lease, ignored -> Flux.just("a", "b"))) - .expectNext("a", "b") - .verifyComplete(); - - assertThat(lease.closeCount()).isEqualTo(1); - assertThat(lease.closed()).isTrue(); - } - - @Test - void anErrorAlsoClosesTheCursor() { - CountingLease lease = new CountingLease(); - MongoCursorGuard guard = MongoCursorGuard.withLifetime(Duration.ofSeconds(5)); - - StepVerifier.create( - guard.guard(() -> lease, ignored -> Flux.error(new IllegalStateException()))) - .verifyError(IllegalStateException.class); - - assertThat(lease.closeCount()).isEqualTo(1); - } - - @Test - void terminationKindIsRecordedSeparatelyFromTheOperationOutcome() { - List recorded = new ArrayList<>(); - MongoCursorGuard guard = new MongoCursorGuard(Duration.ofSeconds(5), recorded::add); - - StepVerifier.create(guard.guard(CountingLease::new, ignored -> Flux.just("a"))) - .expectNext("a") - .verifyComplete(); - StepVerifier.create(guard.guard(CountingLease::new, ignored -> Flux.never())) - .thenCancel() - .verify(); - - assertThat(recorded) - .containsExactly(MongoCursorTermination.COMPLETED, MongoCursorTermination.CANCELLED); - } - - @Test - void aStreamWithoutABatchSizeIsRefused() { - MongoCursorGuard guard = MongoCursorGuard.withLifetime(Duration.ofSeconds(5)); - - assertThatThrownBy(() -> guard.requireBoundedBatch(MongoOperationBudget.standard(), 0)) - .isInstanceOf(MongoOperationRejectedException.class); - assertThatThrownBy(() -> guard.requireBoundedBatch(MongoOperationBudget.standard(), 10_000)) - .isInstanceOf(MongoOperationRejectedException.class); - } - - @Test - void aLifetimeExpiryIsDistinguishableFromAnOrdinaryFailure() { - assertThat(MongoCursorTermination.LIFETIME_EXPIRED.indicatesBackpressureProblem()).isTrue(); - assertThat(MongoCursorTermination.FAILED.indicatesBackpressureProblem()).isFalse(); - } - - /** A lease that records how often it was released. */ - private static final class CountingLease implements MongoCursorLease { - - private final AtomicInteger closeCount = new AtomicInteger(); - - @Override - public boolean closed() { - return closeCount.get() > 0; - } - - @Override - public void close() { - closeCount.incrementAndGet(); - } - - private int closeCount() { - return closeCount.get(); - } - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/reactive/cursor/MongoCursorQueryIsolationTest.java b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/reactive/cursor/MongoCursorQueryIsolationTest.java deleted file mode 100644 index 9bbcceca..00000000 --- a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/reactive/cursor/MongoCursorQueryIsolationTest.java +++ /dev/null @@ -1,114 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.reactive.cursor; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import com.mongodb.MongoClientSettings; -import dev.caskeleton.adapter.outbound.mongo.api.MongoOperationContext; -import dev.caskeleton.adapter.outbound.mongo.api.consistency.MongoConsistencyProfile; -import dev.caskeleton.adapter.outbound.mongo.query.budget.MongoOperationBudget; -import java.time.Duration; -import org.bson.Document; -import org.bson.conversions.Bson; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; -import org.mockito.ArgumentCaptor; -import org.springframework.data.mongodb.core.ReactiveMongoOperations; -import org.springframework.data.mongodb.core.convert.MongoConverter; -import org.springframework.data.mongodb.core.query.Query; -import reactor.core.publisher.Flux; - -/** - * The caller's {@code Query} after a stream has used it. - * - *

Spring Data's {@code Query} is mutable and its setters return {@code this}, so applying the - * budget reconfigured the object the caller passed in. A {@code Query} held as a field and streamed - * twice carried the first call's batch size and deadline into the second, and two concurrent - * subscriptions overwrote each other's. - */ -@Tag("mongodb-contract") -class MongoCursorQueryIsolationTest { - - private final ReactiveMongoOperations operations = mock(ReactiveMongoOperations.class); - private final MongoConverter converter = mock(MongoConverter.class); - - @BeforeEach - void converterWritesBoundedBson() { - when(operations.getConverter()).thenReturn(converter); - when(converter.getCodecRegistry()).thenReturn(MongoClientSettings.getDefaultCodecRegistry()); - doAnswer( - invocation -> { - Object value = invocation.getArgument(0); - Document target = (Document) invocation.getArgument(1, Bson.class); - target.put("value", String.valueOf(value)); - return null; - }) - .when(converter) - .write(any(), any(Bson.class)); - } - - @Test - @DisplayName("streaming does not reconfigure the caller's query") - void streamingDoesNotReconfigureTheCallersQuery() { - when(operations.find(any(Query.class), eq(String.class), eq("orders"))) - .thenReturn(Flux.just("a")); - Query shared = new Query(); - MongoReactiveCursorPublisher publisher = - new MongoReactiveCursorPublisher( - new MongoCursorGuard(Duration.ofMinutes(1), termination -> {})); - - publisher.stream(context(), operations, shared, String.class, "orders", budget(), 10) - .collectList() - .block(); - - assertThat(shared.getMeta().getCursorBatchSize()) - .as("the caller's object must come back as it went in") - .isNull(); - assertThat(shared.getLimit()).isZero(); - } - - @Test - @DisplayName("two streams over one query get independent budgets") - void twoStreamsGetIndependentBudgets() { - when(operations.find(any(Query.class), eq(String.class), eq("orders"))) - .thenReturn(Flux.just("a")); - Query shared = new Query(); - MongoReactiveCursorPublisher publisher = - new MongoReactiveCursorPublisher( - new MongoCursorGuard(Duration.ofMinutes(1), termination -> {})); - - publisher.stream(context(), operations, shared, String.class, "orders", budget(), 10) - .collectList() - .block(); - publisher.stream(context(), operations, shared, String.class, "orders", budget(), 5) - .collectList() - .block(); - - ArgumentCaptor executed = ArgumentCaptor.forClass(Query.class); - org.mockito.Mockito.verify(operations, org.mockito.Mockito.times(2)) - .find(executed.capture(), eq(String.class), eq("orders")); - assertThat(executed.getAllValues()) - .extracting(query -> query.getMeta().getCursorBatchSize()) - .containsExactly(10, 5); - assertThat(executed.getAllValues()).extracting(Query::getLimit).containsExactly(101, 101); - } - - private static MongoOperationContext context() { - return MongoOperationContext.of( - "orders.stream", - "primary", - "orders", - MongoConsistencyProfile.PRIMARY_MAJORITY, - Duration.ofSeconds(5)); - } - - private static MongoOperationBudget budget() { - return new MongoOperationBudget(100, 1_000_000L, 5_000L, 10); - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/reactive/cursor/MongoResultBudgetTrackerTest.java b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/reactive/cursor/MongoResultBudgetTrackerTest.java deleted file mode 100644 index 9fb7148e..00000000 --- a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/reactive/cursor/MongoResultBudgetTrackerTest.java +++ /dev/null @@ -1,83 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.reactive.cursor; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.outbound.mongo.api.error.MongoOperationRejectedException; -import dev.caskeleton.adapter.outbound.mongo.query.budget.MongoOperationBudget; -import org.bson.BsonDocument; -import org.bson.BsonString; -import org.bson.codecs.configuration.CodecRegistries; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * A declared result bound that nothing measured. - * - *

{@code maxResults} and {@code maxResultBytes} were compared between budgets and intersected - * when two were combined, and never compared to a stream. The cursor applied a batch size and a - * server-side time limit — both of which bound how results arrive, not how many there are — so a - * query matching far more than the declared bound streamed all of it, one well-behaved batch at a - * time. - */ -class MongoResultBudgetTrackerTest { - - private static final MongoOperationBudget BUDGET = new MongoOperationBudget(3, 512, 1_000, 10); - - @Test - @DisplayName("results up to the bound are accepted") - void resultsUpToTheBoundAreAccepted() { - MongoResultBudgetTracker tracker = new MongoResultBudgetTracker(BUDGET, null); - - assertThatCode( - () -> { - tracker.record(null); - tracker.record(null); - tracker.record(null); - }) - .doesNotThrowAnyException(); - assertThat(tracker.results()).isEqualTo(3); - } - - @Test - @DisplayName("one result past the bound is refused") - void oneResultPastTheBoundIsRefused() { - MongoResultBudgetTracker tracker = new MongoResultBudgetTracker(BUDGET, null); - tracker.record(null); - tracker.record(null); - tracker.record(null); - - assertThatThrownBy(() -> tracker.record(null)) - .as("a batch size bounds how results arrive, not how many there are") - .isInstanceOf(MongoOperationRejectedException.class); - } - - @Test - @DisplayName("bytes are measured by encoding, not estimated") - void bytesAreMeasuredByEncoding() { - MongoOperationBudget tightBytes = new MongoOperationBudget(100, 40, 1_000, 10); - MongoResultBudgetTracker tracker = - new MongoResultBudgetTracker( - tightBytes, - CodecRegistries.fromProviders(new org.bson.codecs.BsonValueCodecProvider())); - BsonDocument document = - new BsonDocument("note", new BsonString("a reasonably long value for the byte budget")); - - assertThatThrownBy(() -> tracker.record(document)) - .as("an estimate that is wrong in the cheap direction is a bound that does not hold") - .isInstanceOf(MongoOperationRejectedException.class); - } - - @Test - @DisplayName("a small document stays inside the byte budget") - void aSmallDocumentStaysInsideTheByteBudget() { - MongoResultBudgetTracker tracker = - new MongoResultBudgetTracker( - BUDGET, CodecRegistries.fromProviders(new org.bson.codecs.BsonValueCodecProvider())); - - assertThatCode(() -> tracker.record(new BsonDocument("k", new BsonString("v")))) - .doesNotThrowAnyException(); - assertThat(tracker.bytes()).isPositive(); - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/security/MongoProductionSecurityContractTest.java b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/security/MongoProductionSecurityContractTest.java index 64f8ff90..b3be6448 100644 --- a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/security/MongoProductionSecurityContractTest.java +++ b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/security/MongoProductionSecurityContractTest.java @@ -109,7 +109,6 @@ class MongoProductionSecurityContractTest { base.topology(), true, base.stableApiStrict(), - base.consistencyDefault(), base.serverSelectionTimeout(), base.connectTimeout(), base.socketReadTimeout(), @@ -118,8 +117,6 @@ class MongoProductionSecurityContractTest { base.poolMaxSize(), base.poolMaxWaitTime(), base.uuidRepresentation(), - base.decimalRepresentation(), - base.runtimeAutoCreateIndexes(), tls, base.authenticationRequired()); } @@ -131,7 +128,6 @@ class MongoProductionSecurityContractTest { base.topology(), true, base.stableApiStrict(), - base.consistencyDefault(), base.serverSelectionTimeout(), base.connectTimeout(), base.socketReadTimeout(), @@ -140,8 +136,6 @@ class MongoProductionSecurityContractTest { base.poolMaxSize(), base.poolMaxWaitTime(), base.uuidRepresentation(), - base.decimalRepresentation(), - base.runtimeAutoCreateIndexes(), base.tlsRequired(), authentication); } @@ -153,7 +147,6 @@ class MongoProductionSecurityContractTest { base.topology(), true, base.stableApiStrict(), - base.consistencyDefault(), base.serverSelectionTimeout(), connectTimeout, base.socketReadTimeout(), @@ -162,8 +155,6 @@ class MongoProductionSecurityContractTest { base.poolMaxSize(), base.poolMaxWaitTime(), base.uuidRepresentation(), - base.decimalRepresentation(), - base.runtimeAutoCreateIndexes(), base.tlsRequired(), base.authenticationRequired()); } diff --git a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/transaction/MongoSessionAcquisitionTest.java b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/transaction/MongoSessionAcquisitionTest.java index 0e1323f4..e793a89e 100644 --- a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/transaction/MongoSessionAcquisitionTest.java +++ b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/transaction/MongoSessionAcquisitionTest.java @@ -13,16 +13,12 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.springframework.data.mongodb.MongoDatabaseFactory; -import org.springframework.data.mongodb.ReactiveMongoDatabaseFactory; import org.springframework.data.mongodb.core.MongoTemplate; -import org.springframework.data.mongodb.core.ReactiveMongoTemplate; -import reactor.core.publisher.Mono; -import reactor.test.StepVerifier; /** * What happens to a session when starting its transaction fails. * - *

Both factories opened a session and then called {@code startTransaction} with nothing between + *

The factory opened a session and then called {@code startTransaction} with nothing between * them. {@code startTransaction} fails on a standalone deployment, on a session the server has * already ended, and on a driver-level refusal — and when it did, the session object was dropped * with its server-side session still open. Under the retry loop that is one leaked session per @@ -50,28 +46,4 @@ class MongoSessionAcquisitionTest { .isInstanceOf(MongoClientException.class); verify(session, times(1)).close(); } - - @Test - @DisplayName("a failed startTransaction closes the reactive session exactly once") - void aFailedStartClosesTheReactiveSession() { - com.mongodb.reactivestreams.client.ClientSession session = - mock(com.mongodb.reactivestreams.client.ClientSession.class); - org.mockito.Mockito.doThrow(new MongoClientException("no transactions on a standalone")) - .when(session) - .startTransaction(); - when(session.abortTransaction()).thenReturn(Mono.empty()); - ReactiveMongoDatabaseFactory factory = mock(ReactiveMongoDatabaseFactory.class); - when(factory.getSession(any())).thenReturn(Mono.just(session)); - ReactiveMongoTemplate template = mock(ReactiveMongoTemplate.class); - when(template.getMongoDatabaseFactory()).thenReturn(factory); - - SpringReactiveMongoTransactionSessionFactory sessions = - new SpringReactiveMongoTransactionSessionFactory( - template, MongoConsistencyRegistry.standard()); - - StepVerifier.create(sessions.open(MongoTransactionProfile.majority())) - .expectError(MongoClientException.class) - .verify(); - verify(session, times(1)).close(); - } } diff --git a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/transaction/SpringReactiveMongoTransactionExecutorTest.java b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/transaction/SpringReactiveMongoTransactionExecutorTest.java deleted file mode 100644 index 344c75f5..00000000 --- a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/transaction/SpringReactiveMongoTransactionExecutorTest.java +++ /dev/null @@ -1,236 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.transaction; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.adapter.outbound.mongo.api.MongoOperationName; -import dev.caskeleton.adapter.outbound.mongo.api.error.MongoFailureContext; -import dev.caskeleton.adapter.outbound.mongo.api.error.MongoTransactionTransientException; -import dev.caskeleton.adapter.outbound.mongo.transaction.retry.MongoCommitReconciler; -import dev.caskeleton.adapter.outbound.mongo.transaction.retry.MongoRetryBudget; -import dev.caskeleton.adapter.outbound.mongo.transaction.retry.MongoRetryDecision; -import java.time.Duration; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicLong; -import java.util.function.Function; -import java.util.random.RandomGenerator; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.reactivestreams.Publisher; -import org.springframework.data.mongodb.core.ReactiveMongoOperations; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; -import reactor.test.StepVerifier; - -/** - * The reactive transaction's three broken promises. - * - *

The body was a {@link java.util.function.Supplier}, so a caller had no way to obtain the - * session-bound operations and the writes it issued through its own template did not join the - * transaction. Every budget check passed one nanosecond as the elapsed time, so a caller's deadline - * was a number nobody compared anything to. And the jittered delay was computed twice — once for - * the metric and once for the wait — so the recorded delay was never the delay. - */ -class SpringReactiveMongoTransactionExecutorTest { - - private static final MongoOperationName OPERATION = new MongoOperationName("order.write"); - - @Test - @DisplayName("the body receives the session's own operations") - void theBodyReceivesTheSessionsOwnOperations() { - RecordingSessionFactory sessions = new RecordingSessionFactory(); - var executor = executor(sessions, MongoRetryBudget.none(), new AtomicLong(0)::get, delays()); - List seen = new ArrayList<>(); - - StepVerifier.create( - Flux.from( - executor.execute( - MongoTransactionProfile.majority(), - operations -> { - seen.add(operations); - return Mono.just("ok"); - }))) - .expectNext("ok") - .verifyComplete(); - - assertThat(seen).hasSize(1); - assertThat(seen.get(0) == sessions.lastSession.bound) - .as("a Supplier body could only capture a template of its own, outside the session") - .isTrue(); - } - - @Test - @DisplayName("a no-retry budget still runs the body exactly once") - void aNoRetryBudgetStillRunsTheBodyOnce() { - RecordingSessionFactory sessions = new RecordingSessionFactory(); - AtomicInteger bodyRuns = new AtomicInteger(); - var executor = executor(sessions, MongoRetryBudget.none(), new AtomicLong(0)::get, delays()); - - StepVerifier.create( - Flux.from( - executor.execute( - MongoTransactionProfile.majority(), - operations -> { - bodyRuns.incrementAndGet(); - return Mono.just("ok"); - }))) - .expectNext("ok") - .verifyComplete(); - - assertThat(bodyRuns) - .as("maxElapsed=ZERO with a strict `<` comparison refused the first attempt too") - .hasValue(1); - } - - @Test - @DisplayName("a caller's deadline actually stops the retries") - void aCallersDeadlineStopsTheRetries() { - RecordingSessionFactory sessions = new RecordingSessionFactory(); - AtomicInteger bodyRuns = new AtomicInteger(); - // A clock that jumps past the budget's 10-second window on the first check. - AtomicLong now = new AtomicLong(); - var executor = - executor( - sessions, - MongoRetryBudget.standard(), - () -> now.getAndAdd(Duration.ofSeconds(30).toNanos()), - delays()); - - StepVerifier.create( - Flux.from( - executor.execute( - MongoTransactionProfile.majority(), - operations -> { - bodyRuns.incrementAndGet(); - return Mono.error( - new MongoTransactionTransientException( - MongoFailureContext.rejected(OPERATION))); - }))) - .verifyError(MongoTransactionTransientException.class); - - assertThat(bodyRuns) - .as("elapsed was hard-coded to one nanosecond, so maxElapsed could never be reached") - .hasValue(1); - } - - @Test - @DisplayName("the recorded delay is the delay that is waited") - void theRecordedDelayIsTheDelayThatIsWaited() { - RecordingSessionFactory sessions = new RecordingSessionFactory(); - List decisions = new ArrayList<>(); - AtomicInteger bodyRuns = new AtomicInteger(); - var executor = - new SpringReactiveMongoTransactionExecutor( - sessions, - MongoRetryBudget.standard(), - MongoCommitReconciler.standard(), - // Jitter comes from here; two calls used to produce two different delays. - RandomGenerator.getDefault(), - decisions::add, - OPERATION, - new AtomicLong(0)::get); - - StepVerifier.withVirtualTime( - () -> - Flux.from( - executor.execute( - MongoTransactionProfile.majority(), - operations -> { - if (bodyRuns.incrementAndGet() == 1) { - return Mono.error( - new MongoTransactionTransientException( - MongoFailureContext.rejected(OPERATION))); - } - return Mono.just("ok"); - }))) - .thenAwait(Duration.ofSeconds(5)) - .expectNext("ok") - .verifyComplete(); - - assertThat(decisions).hasSize(1); - assertThat(bodyRuns) - .as("the retry ran, so the delay the metric recorded is the one the scheduler used") - .hasValue(2); - } - - private static SpringReactiveMongoTransactionExecutor executor( - ReactiveMongoTransactionSessionFactory sessions, - MongoRetryBudget budget, - java.util.function.LongSupplier nanoTime, - List decisions) { - return new SpringReactiveMongoTransactionExecutor( - sessions, - budget, - MongoCommitReconciler.standard(), - RandomGenerator.getDefault(), - decisions::add, - OPERATION, - nanoTime); - } - - private static List delays() { - return new ArrayList<>(); - } - - /** A session factory that records what the body was handed. */ - private static final class RecordingSessionFactory - implements ReactiveMongoTransactionSessionFactory { - - private RecordingSession lastSession; - - @Override - public Mono open(MongoTransactionProfile profile) { - return Mono.fromSupplier( - () -> { - lastSession = new RecordingSession(); - return lastSession; - }); - } - } - - private static final class RecordingSession implements ReactiveMongoTransactionSession { - - private final ReactiveMongoOperations bound = - (ReactiveMongoOperations) - java.lang.reflect.Proxy.newProxyInstance( - RecordingSession.class.getClassLoader(), - new Class[] {ReactiveMongoOperations.class}, - // equals/hashCode must answer; the assertion compares by identity. - (proxy, method, args) -> { - if ("equals".equals(method.getName())) { - return proxy == args[0]; - } - if ("hashCode".equals(method.getName())) { - return System.identityHashCode(proxy); - } - return null; - }); - - @Override - public Publisher runBody( - Function> body) { - return body.apply(bound); - } - - @Override - public ReactiveMongoOperations operations() { - return bound; - } - - @Override - public Mono commit() { - return Mono.empty(); - } - - @Override - public Mono abort() { - return Mono.empty(); - } - - @Override - public Mono release() { - return Mono.empty(); - } - } -} diff --git a/src/adapter/outbound/persistence-mongo/src/testFixtures/java/dev/caskeleton/adapter/outbound/mongo/architecture/MongoRepositoryArchitectureRules.java b/src/adapter/outbound/persistence-mongo/src/testFixtures/java/dev/caskeleton/adapter/outbound/mongo/architecture/MongoRepositoryArchitectureRules.java index 952aacfc..a95127cb 100644 --- a/src/adapter/outbound/persistence-mongo/src/testFixtures/java/dev/caskeleton/adapter/outbound/mongo/architecture/MongoRepositoryArchitectureRules.java +++ b/src/adapter/outbound/persistence-mongo/src/testFixtures/java/dev/caskeleton/adapter/outbound/mongo/architecture/MongoRepositoryArchitectureRules.java @@ -57,10 +57,8 @@ public final class MongoRepositoryArchitectureRules { public Set allowedRepositorySuperTypes() { return Set.of( "org.springframework.data.mongodb.repository.MongoRepository", - "org.springframework.data.mongodb.repository.ReactiveMongoRepository", "org.springframework.data.repository.Repository", - "org.springframework.data.repository.CrudRepository", - "org.springframework.data.repository.reactive.ReactiveCrudRepository"); + "org.springframework.data.repository.CrudRepository"); } /** True when a type name is one of the forbidden platform CRUD bases. */ diff --git a/src/adapter/outbound/persistence-mongo/src/testFixtures/java/dev/caskeleton/adapter/outbound/mongo/testkit/atlas/MongoAtlasCapabilityContractSuite.java b/src/adapter/outbound/persistence-mongo/src/testFixtures/java/dev/caskeleton/adapter/outbound/mongo/testkit/atlas/MongoAtlasCapabilityContractSuite.java deleted file mode 100644 index 9334ecc2..00000000 --- a/src/adapter/outbound/persistence-mongo/src/testFixtures/java/dev/caskeleton/adapter/outbound/mongo/testkit/atlas/MongoAtlasCapabilityContractSuite.java +++ /dev/null @@ -1,85 +0,0 @@ -package dev.caskeleton.adapter.outbound.mongo.testkit.atlas; - -import java.util.List; -import java.util.Objects; - -/** - * Search, vector and encryption contracts against a provider environment (advanced plan Task 14). - * - *

Atlas Local is fast enough for pull requests and is explicitly not the release evidence: it - * does not exercise the provider's analyzers, its index build behaviour or its KMS. Recording which - * environment a report came from is what keeps a quick local pass from being mistaken for - * certification. - */ -public final class MongoAtlasCapabilityContractSuite { - - private MongoAtlasCapabilityContractSuite() {} - - /** - * The vector readiness contract. - * - * @param queriedBeforeReady whether any query ran against a non-READY index - * @param environment where the run happened - */ - public static MongoAtlasCapabilityReport vectorReadiness( - boolean queriedBeforeReady, Environment environment) { - return new MongoAtlasCapabilityReport( - queriedBeforeReady, true, environment, List.of("vector-readiness")); - } - - /** The KMS contract: wrong key, missing permission and rotation all fail closed. */ - public static MongoAtlasCapabilityReport kmsFailureModes( - boolean allFailedClosed, Environment environment) { - return new MongoAtlasCapabilityReport( - false, - allFailedClosed, - environment, - List.of("kms-wrong-key", "kms-permission", "kms-rotation")); - } - - /** Where a capability run happened. */ - public enum Environment { - - /** Atlas Local in a container: fast, and not release evidence. */ - ATLAS_LOCAL(false), - - /** The actual target deployment, behind credentials. */ - ACTUAL_TARGET(true); - - private final boolean releaseEvidence; - - Environment(boolean releaseEvidence) { - this.releaseEvidence = releaseEvidence; - } - - /** True when a run here counts towards promotion. */ - public boolean countsAsReleaseEvidence() { - return releaseEvidence; - } - } - - /** - * What one capability run produced. - * - * @param queriedBeforeReady whether a query ran against a non-READY index - * @param failedClosed whether every negative case failed closed - * @param environment where the run happened - * @param contracts which contracts ran - */ - public record MongoAtlasCapabilityReport( - boolean queriedBeforeReady, - boolean failedClosed, - Environment environment, - List contracts) { - - public MongoAtlasCapabilityReport { - Objects.requireNonNull(environment, "environment"); - contracts = List.copyOf(Objects.requireNonNull(contracts, "contracts")); - } - - /** True when the run passed and counts towards promotion. */ - public boolean certifies() { - return !queriedBeforeReady && failedClosed && environment.countsAsReleaseEvidence(); - } - } -} diff --git a/src/adapter/outbound/redis-runtime/build.gradle b/src/adapter/outbound/redis-runtime/build.gradle index 6e09bfd9..ab55a982 100644 --- a/src/adapter/outbound/redis-runtime/build.gradle +++ b/src/adapter/outbound/redis-runtime/build.gradle @@ -1,6 +1,8 @@ plugins { id 'ca.spring-library' id 'ca.spring-config' + id 'java-test-fixtures' + id 'ca.redis-topology-lane' } description = 'Redis runtime substrate: topology client, connection lifecycle, gateway and opt-in runtime configuration' @@ -12,4 +14,15 @@ dependencies { implementation 'io.lettuce:lettuce-core' implementation 'io.projectreactor:reactor-core' implementation 'org.slf4j:slf4j-api' + + // Test fixtures only: the in-memory gateway and the real-topology endpoint that both redis-sdk's + // and cache-redis's tests drive. One fake of RedisCommandGateway, owned by the leaf that owns it. + testFixturesImplementation 'io.lettuce:lettuce-core' +} + +redisTopologyLane { + requiredClasses 'standalone', 'LiveRedisCompositionTest' + requiredClasses 'sentinel', 'LiveRedisCompositionTest' + requiredClasses 'cluster', 'LiveRedisCompositionTest' + requiredClasses 'tls', 'LiveRedisTlsTest' } diff --git a/src/adapter/outbound/redis-runtime/gradle.lockfile b/src/adapter/outbound/redis-runtime/gradle.lockfile index 062d16a3..a83112f9 100644 --- a/src/adapter/outbound/redis-runtime/gradle.lockfile +++ b/src/adapter/outbound/redis-runtime/gradle.lockfile @@ -5,30 +5,30 @@ biz.aQute.bnd:biz.aQute.bnd.annotation:7.1.0=testCompileClasspath ch.qos.logback:logback-classic:1.5.38=testCompileClasspath,testRuntimeClasspath ch.qos.logback:logback-core:1.5.38=testCompileClasspath,testRuntimeClasspath com.fasterxml.jackson.core:jackson-annotations:2.21=compileClasspath,testCompileClasspath,testRuntimeClasspath -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.38.0=testCompileClasspath com.google.errorprone:error_prone_annotations:2.41.0=spotbugs com.google.errorprone:error_prone_annotations:2.47.0=checkstyle -com.google.errorprone:error_prone_annotations:2.49.0=annotationProcessor,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.5.0-jre=annotationProcessor,testAnnotationProcessor +com.google.errorprone:error_prone_annotations:2.49.0=annotationProcessor,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.5.0-jre=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor com.google.guava:guava:33.6.0-jre=checkstyle -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.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.jayway.jsonpath:json-path:2.10.0=testCompileClasspath,testRuntimeClasspath com.puppycrawl.tools:checkstyle:13.5.0=checkstyle @@ -36,27 +36,27 @@ com.vaadin.external.google:android-json:0.0.20131108.vaadin1=testCompileClasspat commons-beanutils:commons-beanutils:1.11.0=checkstyle commons-collections:commons-collections:3.2.2=checkstyle commons-io:commons-io:2.21.0=spotbugs -commons-logging:commons-logging:1.3.6=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +commons-logging:commons-logging:1.3.6=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath 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 -io.lettuce:lettuce-core:6.8.2.RELEASE=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.micrometer:micrometer-commons:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.micrometer:micrometer-observation:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.netty:netty-buffer:4.2.17.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.netty:netty-codec-base:4.2.17.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.netty:netty-codec-dns:4.2.17.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.netty:netty-common:4.2.17.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.netty:netty-handler:4.2.17.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.netty:netty-resolver-dns:4.2.17.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.netty:netty-resolver:4.2.17.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.netty:netty-transport-native-unix-common:4.2.17.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.netty:netty-transport:4.2.17.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.projectreactor:reactor-core:3.8.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +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 +io.lettuce:lettuce-core:6.8.2.RELEASE=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +io.micrometer:micrometer-commons:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +io.micrometer:micrometer-observation:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +io.netty:netty-buffer:4.2.17.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +io.netty:netty-codec-base:4.2.17.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +io.netty:netty-codec-dns:4.2.17.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +io.netty:netty-common:4.2.17.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +io.netty:netty-handler:4.2.17.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +io.netty:netty-resolver-dns:4.2.17.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +io.netty:netty-resolver:4.2.17.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +io.netty:netty-transport-native-unix-common:4.2.17.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +io.netty:netty-transport:4.2.17.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +io.projectreactor:reactor-core:3.8.7=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath jakarta.activation:jakarta.activation-api:2.1.4=testCompileClasspath,testRuntimeClasspath jakarta.annotation:jakarta.annotation-api:3.0.0=testCompileClasspath,testRuntimeClasspath jakarta.xml.bind:jakarta.xml.bind-api:4.0.5=testCompileClasspath,testRuntimeClasspath -javax.inject:javax.inject:1=annotationProcessor,testAnnotationProcessor +javax.inject:javax.inject:1=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor jaxen:jaxen:2.0.6=spotbugs net.bytebuddy:byte-buddy-agent:1.17.8=testCompileClasspath,testRuntimeClasspath net.bytebuddy:byte-buddy:1.17.8=testCompileClasspath,testRuntimeClasspath @@ -91,7 +91,7 @@ org.codehaus.plexus:plexus-utils:3.3.0=checkstyle org.dom4j:dom4j:2.2.0=spotbugs org.hamcrest:hamcrest:3.0=testCompileClasspath,testRuntimeClasspath org.javassist:javassist:3.28.0-GA=checkstyle -org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,compileClasspath,runtimeClasspath,testAnnotationProcessor,testCompileClasspath,testRuntimeClasspath +org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,compileClasspath,runtimeClasspath,testAnnotationProcessor,testCompileClasspath,testFixturesAnnotationProcessor,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.junit.jupiter:junit-jupiter-api:6.0.3=testCompileClasspath,testRuntimeClasspath org.junit.jupiter:junit-jupiter-engine:6.0.3=testRuntimeClasspath org.junit.jupiter:junit-jupiter-params:6.0.3=testCompileClasspath,testRuntimeClasspath @@ -115,17 +115,17 @@ 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.ow2.asm:asm:9.7.1=testCompileClasspath,testRuntimeClasspath -org.pcollections:pcollections:4.0.1=annotationProcessor,testAnnotationProcessor -org.reactivestreams:reactive-streams:1.0.4=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.pcollections:pcollections:4.0.1=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +org.reactivestreams:reactive-streams:1.0.4=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.reflections:reflections:0.10.2=checkstyle org.skyscreamer:jsonassert:1.5.3=testCompileClasspath,testRuntimeClasspath org.slf4j:jul-to-slf4j:2.0.18=testCompileClasspath,testRuntimeClasspath -org.slf4j:slf4j-api:2.0.18=compileClasspath,runtimeClasspath,spotbugs,spotbugsSlf4j,testCompileClasspath,testRuntimeClasspath +org.slf4j:slf4j-api:2.0.18=compileClasspath,runtimeClasspath,spotbugs,spotbugsSlf4j,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j org.slf4j:slf4j-simple:2.0.18=checkstyle -org.springframework.boot:spring-boot-autoconfigure:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-autoconfigure:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-configuration-processor:4.0.8=annotationProcessor -org.springframework.boot:spring-boot-health:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-health:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-http-converter:4.0.8=testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-jackson:4.0.8=testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-resttestclient:4.0.8=testCompileClasspath,testRuntimeClasspath @@ -145,19 +145,19 @@ org.springframework.boot:spring-boot-tomcat:4.0.8=testCompileClasspath,testRunti org.springframework.boot:spring-boot-web-server:4.0.8=testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-webmvc-test:4.0.8=testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-webmvc:4.0.8=testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-aop:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-beans:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-context:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-core:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-expression:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework:spring-aop:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework:spring-beans:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework:spring-context:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework:spring-core:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.springframework:spring-expression:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.springframework:spring-test:7.0.9=testCompileClasspath,testRuntimeClasspath org.springframework:spring-web:7.0.9=testCompileClasspath,testRuntimeClasspath org.springframework:spring-webmvc:7.0.9=testCompileClasspath,testRuntimeClasspath org.xmlresolver:xmlresolver:5.3.3=checkstyle,spotbugs org.xmlunit:xmlunit-core:2.10.4=testCompileClasspath,testRuntimeClasspath org.yaml:snakeyaml:2.5=testCompileClasspath,testRuntimeClasspath -redis.clients.authentication:redis-authx-core:0.1.1-beta2=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +redis.clients.authentication:redis-authx-core:0.1.1-beta2=compileClasspath,runtimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath tools.jackson.core:jackson-core:3.1.5=testCompileClasspath,testRuntimeClasspath tools.jackson.core:jackson-databind:3.1.5=testCompileClasspath,testRuntimeClasspath tools.jackson:jackson-bom:3.1.5=testCompileClasspath,testRuntimeClasspath diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisSdkAutoConfiguration.java b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisSdkAutoConfiguration.java index 7a8c2177..199cd05a 100644 --- a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisSdkAutoConfiguration.java +++ b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisSdkAutoConfiguration.java @@ -5,8 +5,6 @@ import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisC import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeClient; import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeOwner; import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisTopologyClientFactory; -import java.io.IOException; -import java.io.InputStream; import java.util.EnumMap; import java.util.List; import java.util.Map; @@ -46,9 +44,8 @@ import org.springframework.core.type.AnnotatedTypeMetadata; * existed the method had no production caller at all. * *

Roles — cache, session, idempotency, rate limiting, leases — select which Redis - * capabilities compose on top of this. None of them is a second master switch; {@code - * RedisActivationValidator} in the bootstrap refuses the contradiction of a role that selects Redis - * while this switch is off. + * capabilities compose on top of this. None of them is a second switch: while this one is off, a + * role that selects Redis composes nothing. */ @AutoConfiguration @ConditionalOnProperty(prefix = "app.redis", name = "enabled", havingValue = "true") @@ -99,48 +96,12 @@ public class RedisSdkAutoConfiguration { * @return the validation outcome, kept as a bean so warnings are inspectable in tests */ @Bean - public RedisSdkSettingsValidation redisSdkSettingsValidation( - RedisSdkSettings settings, ResourceLoader resourceLoader) { + public RedisSdkSettingsValidation redisSdkSettingsValidation(RedisSdkSettings settings) { List warnings = settings.validate(); - requireRawPolicyResource(settings, resourceLoader); warnings.forEach(warning -> LOG.warn("Redis SDK configuration warning: {}", warning)); return new RedisSdkSettingsValidation(warnings); } - /** - * Proves the raw command allowlist exists before anything can reach Redis. - * - *

{@code validate()} only checks that the setting is non-blank, and the default points at - * {@code classpath:redis-sdk/raw-command-allowlist.yml} — a resource this module does not ship. - * So enabling the raw gateway passed configuration validation and then failed at the first raw - * command, from inside a request, against a live connection. The allowlist is the entire - * authorisation model for that gateway; not being able to read it is a startup failure. - */ - private static void requireRawPolicyResource( - RedisSdkSettings settings, ResourceLoader resourceLoader) { - if (!settings.getRaw().isEnabled()) { - return; - } - String location = settings.getRaw().getPolicyResource(); - Resource resource = resourceLoader.getResource(location); - if (!resource.exists() || !resource.isReadable()) { - throw new IllegalStateException( - "the raw gateway is enabled but its allowlist resource '" - + location - + "' does not exist or cannot be read. The allowlist is the only thing that decides" - + " which raw commands are reachable, so an unreadable one is a startup failure" - + " rather than a per-command surprise. Point" - + " app.redis.raw.policy-resource at a readable resource, or set" - + " app.redis.raw.enabled=false."); - } - try (InputStream ignored = resource.getInputStream()) { - LOG.info("Redis raw command allowlist loaded from {}", location); - } catch (IOException failure) { - throw new IllegalStateException( - "the raw gateway allowlist resource '" + location + "' could not be opened", failure); - } - } - /** * Resolves every credential reference the selected configuration actually needs. * @@ -185,12 +146,6 @@ public class RedisSdkAutoConfiguration { RedisCredentialRole.ADMIN, resolver.resolve("admin", settings.getAdmin().getCredentialReference())); } - if (settings.getRaw().isEnabled()) { - put( - accounts, - RedisCredentialRole.RAW, - resolver.resolve("raw gateway", settings.getRaw().getCredentialReference())); - } Optional sentinel = settings.getMode() == dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisDeploymentMode.SENTINEL @@ -280,7 +235,11 @@ public class RedisSdkAutoConfiguration { limits.put( RedisConnectionKind.PUBSUB, Math.max(1, settings.getPubsub().getBufferCapacity() / 64)); limits.put(RedisConnectionKind.ADMIN, settings.getAdmin().isEnabled() ? 2 : 1); - return new RedisRuntimeOwner(client, limits, settings.getLifecycle().getDrainTimeout()); + return new RedisRuntimeOwner( + client, + limits, + settings.getLifecycle().getAcquireTimeout(), + settings.getLifecycle().getDrainTimeout()); } /** diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisSdkSettings.java b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisSdkSettings.java index 72555553..4b704ce9 100644 --- a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisSdkSettings.java +++ b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisSdkSettings.java @@ -11,8 +11,8 @@ import java.util.List; * *

Defaults are the skeleton guardrails from the design. Validation is fail-closed and runs at * startup: a setting that would make a guardrail meaningless — a non-zero database on Cluster, an - * unbounded block, a raw gateway without an allowlist — stops the context rather than degrading - * quietly at the first request. + * unbounded lane, a Sentinel deployment without a primary name — stops the context rather than + * degrading quietly at the first request. * *

This class carries no {@code @ConfigurationProperties} annotation on purpose. It is registered * and bound only by {@link RedisSdkAutoConfiguration}, which exists only while {@code @@ -34,10 +34,8 @@ public class RedisSdkSettings { private int database; private final Namespace namespace = new Namespace(); private final Timeouts timeout = new Timeouts(); - private final Limits limits = new Limits(); private final Blocking blocking = new Blocking(); private final Transaction transaction = new Transaction(); - private final Advanced advanced = new Advanced(); private final Authentication authentication = new Authentication(); private final Sentinel sentinel = new Sentinel(); private final Tls tls = new Tls(); @@ -45,7 +43,6 @@ public class RedisSdkSettings { private final Cluster cluster = new Cluster(); private final Capacity capacity = new Capacity(); private final PubSub pubsub = new PubSub(); - private final Raw raw = new Raw(); private final Admin admin = new Admin(); /** @@ -66,15 +63,9 @@ public class RedisSdkSettings { throw new IllegalStateException("at least one Redis node must be configured"); } namespace.validate(); - limits.validate(); validateTimeout("fast", timeout.getFast(), warnings); - validateTimeout("collection", timeout.getCollection(), warnings); validateTimeout("script", timeout.getScript(), warnings); validateTimeout("batch", timeout.getBatch(), warnings); - validateTimeout("admin", timeout.getAdmin(), warnings); - if (blocking.getMaxBlock().isZero() || blocking.getMaxBlock().isNegative()) { - throw new IllegalStateException("blocking commands must not be unbounded"); - } if (blocking.getMaxConnections() < 1 || transaction.getMaxConnections() < 1) { throw new IllegalStateException("dedicated connection lanes need a positive ceiling"); } @@ -105,25 +96,12 @@ public class RedisSdkSettings { capacity.validate(); cluster.validate(); pubsub.validate(); - if (raw.isEnabled() && (raw.getPolicyResource() == null || raw.getPolicyResource().isBlank())) { - throw new IllegalStateException("the raw gateway requires an allowlist resource"); - } - if (raw.isEnabled() - && (raw.getCredentialReference() == null || raw.getCredentialReference().isBlank())) { - throw new IllegalStateException( - "app.redis.raw.credential-reference is required when app.redis.raw.enabled=true: the raw" - + " gateway authenticates as its own account"); - } if (admin.isEnabled() && (admin.getCredentialReference() == null || admin.getCredentialReference().isBlank())) { throw new IllegalStateException( "app.redis.admin.credential-reference is required when app.redis.admin.enabled=true: the" + " admin plane authenticates as its own account"); } - if (!advanced.isEnabled() && !advanced.getPolicies().isEmpty()) { - throw new IllegalStateException( - "advanced permit policies are configured while advanced operations are disabled"); - } // Last, deliberately. A deployment with both a structural mistake and a missing credential // should be told about the structural one first: it is the cheaper thing to be wrong about, // and reporting "no credential" for a configuration that could never have connected anyway @@ -188,10 +166,8 @@ public class RedisSdkSettings { public static class Timeouts { private Duration fast = Duration.ofMillis(500); - private Duration collection = Duration.ofSeconds(2); private Duration script = Duration.ofSeconds(1); private Duration batch = Duration.ofSeconds(2); - private Duration admin = Duration.ofSeconds(3); public Duration getFast() { return fast; @@ -201,14 +177,6 @@ public class RedisSdkSettings { this.fast = fast; } - public Duration getCollection() { - return collection; - } - - public void setCollection(Duration collection) { - this.collection = collection; - } - public Duration getScript() { return script; } @@ -224,144 +192,12 @@ public class RedisSdkSettings { public void setBatch(Duration batch) { this.batch = batch; } - - public Duration getAdmin() { - return admin; - } - - public void setAdmin(Duration admin) { - this.admin = admin; - } - } - - /** Size and count ceilings enforced before Redis is called. */ - public static class Limits { - - private int maxKeyBytes = 512; - private long maxValueBytes = 1_048_576L; - private long maxStreamPayloadBytes = 262_144L; - private long maxHashFieldValueBytes = 524_288L; - private int maxCollectionElements = 1_000; - private int maxScanCount = 500; - private int maxBatchCommands = 500; - private long maxBatchRequestBytes = 4L * 1024 * 1024; - private long maxBatchReplyBytes = 16L * 1024 * 1024; - private int offlineQueueCommands = 1_000; - private long maxBitmapOffset = 10_000_000L; - - void validate() { - if (maxKeyBytes < 1 || maxKeyBytes > RedisKeyRules.MAX_KEY_BYTES) { - throw new IllegalStateException( - "max-key-bytes must be in 1.." + RedisKeyRules.MAX_KEY_BYTES); - } - if (maxValueBytes < 1 - || maxStreamPayloadBytes < 1 - || maxHashFieldValueBytes < 1 - || maxCollectionElements < 1 - || maxScanCount < 1 - || maxBatchCommands < 1 - || maxBatchRequestBytes < 1 - || maxBatchReplyBytes < 1 - || offlineQueueCommands < 1 - || maxBitmapOffset < 1) { - throw new IllegalStateException("every Redis SDK limit must be positive"); - } - } - - public int getMaxKeyBytes() { - return maxKeyBytes; - } - - public void setMaxKeyBytes(int maxKeyBytes) { - this.maxKeyBytes = maxKeyBytes; - } - - public long getMaxValueBytes() { - return maxValueBytes; - } - - public void setMaxValueBytes(long maxValueBytes) { - this.maxValueBytes = maxValueBytes; - } - - public long getMaxStreamPayloadBytes() { - return maxStreamPayloadBytes; - } - - public void setMaxStreamPayloadBytes(long maxStreamPayloadBytes) { - this.maxStreamPayloadBytes = maxStreamPayloadBytes; - } - - public long getMaxHashFieldValueBytes() { - return maxHashFieldValueBytes; - } - - public void setMaxHashFieldValueBytes(long maxHashFieldValueBytes) { - this.maxHashFieldValueBytes = maxHashFieldValueBytes; - } - - public int getMaxCollectionElements() { - return maxCollectionElements; - } - - public void setMaxCollectionElements(int maxCollectionElements) { - this.maxCollectionElements = maxCollectionElements; - } - - public int getMaxScanCount() { - return maxScanCount; - } - - public void setMaxScanCount(int maxScanCount) { - this.maxScanCount = maxScanCount; - } - - public int getMaxBatchCommands() { - return maxBatchCommands; - } - - public void setMaxBatchCommands(int maxBatchCommands) { - this.maxBatchCommands = maxBatchCommands; - } - - public long getMaxBatchRequestBytes() { - return maxBatchRequestBytes; - } - - public void setMaxBatchRequestBytes(long maxBatchRequestBytes) { - this.maxBatchRequestBytes = maxBatchRequestBytes; - } - - public long getMaxBatchReplyBytes() { - return maxBatchReplyBytes; - } - - public void setMaxBatchReplyBytes(long maxBatchReplyBytes) { - this.maxBatchReplyBytes = maxBatchReplyBytes; - } - - public int getOfflineQueueCommands() { - return offlineQueueCommands; - } - - public void setOfflineQueueCommands(int offlineQueueCommands) { - this.offlineQueueCommands = offlineQueueCommands; - } - - public long getMaxBitmapOffset() { - return maxBitmapOffset; - } - - public void setMaxBitmapOffset(long maxBitmapOffset) { - this.maxBitmapOffset = maxBitmapOffset; - } } /** Blocking lane ceilings. */ public static class Blocking { private int maxConnections = 32; - private Duration maxBlock = Duration.ofSeconds(30); public int getMaxConnections() { return maxConnections; @@ -370,14 +206,6 @@ public class RedisSdkSettings { public void setMaxConnections(int maxConnections) { this.maxConnections = maxConnections; } - - public Duration getMaxBlock() { - return maxBlock; - } - - public void setMaxBlock(Duration maxBlock) { - this.maxBlock = maxBlock; - } } /** Transaction lane ceilings. */ @@ -558,7 +386,6 @@ public class RedisSdkSettings { private String clientName = "ca-skeleton"; private Duration connectTimeout = Duration.ofSeconds(2); - private Duration tlsHandshakeTimeout = Duration.ofSeconds(3); private Duration acquireTimeout = Duration.ofSeconds(2); private Duration shutdownQuietPeriod = Duration.ofMillis(100); private Duration shutdownTimeout = Duration.ofSeconds(3); @@ -569,7 +396,6 @@ public class RedisSdkSettings { throw new IllegalStateException("the client name must not be blank"); } requirePositive("connect", connectTimeout); - requirePositive("tls-handshake", tlsHandshakeTimeout); requirePositive("acquire", acquireTimeout); requirePositive("shutdown", shutdownTimeout); requirePositive("drain", drainTimeout); @@ -605,14 +431,6 @@ public class RedisSdkSettings { this.connectTimeout = connectTimeout; } - public Duration getTlsHandshakeTimeout() { - return tlsHandshakeTimeout; - } - - public void setTlsHandshakeTimeout(Duration tlsHandshakeTimeout) { - this.tlsHandshakeTimeout = tlsHandshakeTimeout; - } - public Duration getAcquireTimeout() { return acquireTimeout; } @@ -685,15 +503,10 @@ public class RedisSdkSettings { private int maximumInFlightCommands = 64; private int maximumScriptConnections = 8; - private long maximumInFlightBytes = 4L * 1024 * 1024; - private long maximumReplyBytes = 16L * 1024 * 1024; private boolean rejectWhenDisconnected = true; void validate() { - if (maximumInFlightCommands < 1 - || maximumScriptConnections < 1 - || maximumInFlightBytes < 1 - || maximumReplyBytes < 1) { + if (maximumInFlightCommands < 1 || maximumScriptConnections < 1) { throw new IllegalStateException("every Redis capacity ceiling must be positive"); } } @@ -714,22 +527,6 @@ public class RedisSdkSettings { this.maximumScriptConnections = maximumScriptConnections; } - public long getMaximumInFlightBytes() { - return maximumInFlightBytes; - } - - public void setMaximumInFlightBytes(long maximumInFlightBytes) { - this.maximumInFlightBytes = maximumInFlightBytes; - } - - public long getMaximumReplyBytes() { - return maximumReplyBytes; - } - - public void setMaximumReplyBytes(long maximumReplyBytes) { - this.maximumReplyBytes = maximumReplyBytes; - } - /** * Reports whether a command issued while the connection is down is refused rather than queued. * @@ -752,16 +549,11 @@ public class RedisSdkSettings { public static class PubSub { private int bufferCapacity = 1_024; - private String overflowPolicy = "error"; void validate() { if (bufferCapacity < 1) { throw new IllegalStateException("the pub/sub buffer capacity must be positive"); } - if (!List.of("error", "drop-oldest", "drop-latest").contains(overflowPolicy)) { - throw new IllegalStateException( - "the pub/sub overflow policy must be error, drop-oldest, or drop-latest"); - } } public int getBufferCapacity() { @@ -771,69 +563,6 @@ public class RedisSdkSettings { public void setBufferCapacity(int bufferCapacity) { this.bufferCapacity = bufferCapacity; } - - public String getOverflowPolicy() { - return overflowPolicy; - } - - public void setOverflowPolicy(String overflowPolicy) { - this.overflowPolicy = overflowPolicy; - } - } - - /** Advanced R2 exposure. */ - public static class Advanced { - - private boolean enabled; - private List policies = new ArrayList<>(); - - public boolean isEnabled() { - return enabled; - } - - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } - - public List getPolicies() { - return policies; - } - - public void setPolicies(List policies) { - this.policies = policies; - } - } - - /** Approved raw gateway exposure. */ - public static class Raw { - - private boolean enabled; - private String policyResource = "classpath:redis-sdk/raw-command-allowlist.yml"; - private String credentialReference; - - public boolean isEnabled() { - return enabled; - } - - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } - - public String getPolicyResource() { - return policyResource; - } - - public void setPolicyResource(String policyResource) { - this.policyResource = policyResource; - } - - public String getCredentialReference() { - return credentialReference; - } - - public void setCredentialReference(String credentialReference) { - this.credentialReference = credentialReference; - } } /** Isolated admin plane exposure. */ @@ -899,10 +628,6 @@ public class RedisSdkSettings { return timeout; } - public Limits getLimits() { - return limits; - } - public Blocking getBlocking() { return blocking; } @@ -911,14 +636,6 @@ public class RedisSdkSettings { return transaction; } - public Advanced getAdvanced() { - return advanced; - } - - public Raw getRaw() { - return raw; - } - public Admin getAdmin() { return admin; } diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/RedisCredentialRole.java b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/RedisCredentialRole.java index ff404b80..dabef402 100644 --- a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/RedisCredentialRole.java +++ b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/RedisCredentialRole.java @@ -26,7 +26,5 @@ public enum RedisCredentialRole { /** Subscription traffic, whose channel patterns are granted separately from keys. */ PUBSUB, /** Read-only diagnostics, on its own connection so its grants never reach request paths. */ - ADMIN, - /** The approved raw command gateway, whose allowlist is mirrored by the account's grants. */ - RAW + ADMIN } diff --git a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/RedisRuntimeOwner.java b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/RedisRuntimeOwner.java index bbb465c6..42010b28 100644 --- a/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/RedisRuntimeOwner.java +++ b/src/adapter/outbound/redis-runtime/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/RedisRuntimeOwner.java @@ -14,6 +14,8 @@ import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -53,6 +55,8 @@ public final class RedisRuntimeOwner implements AutoCloseable { private final Map limits; private final Map> idle; private final Map outstanding; + private final Map permits; + private final Duration acquireTimeout; private final Duration drainTimeout; private final AtomicReference state = new AtomicReference<>(State.OPEN); private final Object monitor = new Object(); @@ -61,18 +65,25 @@ public final class RedisRuntimeOwner implements AutoCloseable { * Creates the owner. * * @param client the topology client whose connections this owns - * @param limits per-lane maximum concurrent leases + * @param limits per-lane maximum connections, each held by at most one lease at a time + * @param acquireTimeout how long a borrow waits for a returned connection when its lane is full * @param drainTimeout how long shutdown waits for outstanding leases */ public RedisRuntimeOwner( - RedisRuntimeClient client, Map limits, Duration drainTimeout) { + RedisRuntimeClient client, + Map limits, + Duration acquireTimeout, + Duration drainTimeout) { this.client = Objects.requireNonNull(client, "client must be non-null"); + this.acquireTimeout = + Objects.requireNonNull(acquireTimeout, "acquire timeout must be non-null"); this.drainTimeout = Objects.requireNonNull(drainTimeout, "drain timeout must be non-null"); Objects.requireNonNull(limits, "limits must be non-null"); Map configured = new EnumMap<>(RedisConnectionKind.class); Map> pools = new EnumMap<>(RedisConnectionKind.class); Map counters = new EnumMap<>(RedisConnectionKind.class); + Map lanes = new EnumMap<>(RedisConnectionKind.class); for (RedisConnectionKind kind : RedisConnectionKind.values()) { Integer limit = limits.get(kind); if (limit == null || limit < 1) { @@ -81,10 +92,13 @@ public final class RedisRuntimeOwner implements AutoCloseable { configured.put(kind, limit); pools.put(kind, new ArrayDeque<>()); counters.put(kind, 0); + // Fair, so a burst is served in arrival order rather than starving the earliest waiter. + lanes.put(kind, new Semaphore(limit, true)); } this.limits = Map.copyOf(configured); this.idle = pools; this.outstanding = counters; + this.permits = Map.copyOf(lanes); } /** @@ -101,7 +115,8 @@ public final class RedisRuntimeOwner implements AutoCloseable { * * @param kind the lane * @return the lease, which must be closed - * @throws RedisCommandRejectedException when the lane is at its ceiling or the owner is closing + * @throws RedisCommandRejectedException when the lane stayed full for the acquire timeout or the + * owner is closing */ public RedisLease borrow(RedisConnectionKind kind) { return borrow(kind, Optional.empty()); @@ -118,26 +133,43 @@ public final class RedisRuntimeOwner implements AutoCloseable { * @param kind the lane * @param routingKey a key whose slot decides the node, on topologies that have more than one * @return the lease, which must be closed - * @throws RedisCommandRejectedException when the lane is at its ceiling or the owner is closing + * @throws RedisCommandRejectedException when the lane stayed full for the acquire timeout or the + * owner is closing */ public RedisLease borrow(RedisConnectionKind kind, Optional routingKey) { Objects.requireNonNull(kind, "connection kind must be non-null"); Objects.requireNonNull(routingKey, "routing key must be non-null"); + if (state.get() != State.OPEN) { + throw notAccepting(); + } + // The limit is the lane's connection count: a lease holds one connection for one round trip, + // so a burst above it waits for a returned connection instead of being refused against a + // healthy Redis. The wait is bounded, because an unbounded one turns one slow dependency into + // every caller of this process waiting on it. A Semaphore, not a monitor wait, so a virtual + // thread waiting here does not pin its carrier. + Semaphore lane = permits.get(kind); + boolean admitted; + try { + admitted = lane.tryAcquire(acquireTimeout.toNanos(), TimeUnit.NANOSECONDS); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw reject("interrupted while waiting for a connection on lane " + kind); + } + if (!admitted) { + throw reject( + "connection lane " + + kind + + " reached its limit of " + + limits.get(kind) + + " and no connection was returned within " + + acquireTimeout); + } synchronized (monitor) { if (state.get() != State.OPEN) { - throw reject( - "the Redis runtime is " - + state.get() - + " and is not accepting new work; a lease taken during shutdown would either be" - + " aborted mid-command or hold the drain open past its budget"); + lane.release(); + throw notAccepting(); } - int current = outstanding.get(kind); - if (current >= limits.get(kind)) { - // Refused, never queued. An unbounded wait on a saturated lane converts one slow - // dependency into every caller of this process waiting on it. - throw reject("connection lane " + kind + " reached its limit of " + limits.get(kind)); - } - outstanding.put(kind, current + 1); + outstanding.put(kind, outstanding.get(kind) + 1); } RedisRuntimeClient.RedisLaneConnection connection = null; try { @@ -188,6 +220,8 @@ public final class RedisRuntimeOwner implements AutoCloseable { monitor.notifyAll(); } } + // After the counter, so a waiter admitted by this permit never sees the lane over its limit. + permits.get(kind).release(); } private int totalOutstanding() { @@ -239,6 +273,16 @@ public final class RedisRuntimeOwner implements AutoCloseable { } } + private RedisCommandRejectedException notAccepting() { + return reject( + "the Redis runtime is " + + state.get() + + " and is not accepting new work; a lease taken during shutdown would either be" + + " aborted mid-command or hold the drain open past its budget"); + } + + // Every refusal here happens before a command exists, so it is always "not sent": a caller may + // treat it as unavailable rather than as a write that might have landed. private RedisCommandRejectedException reject(String reason) { return new RedisCommandRejectedException( reason, diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/RedisVersionTest.java b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/RedisVersionTest.java similarity index 100% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/RedisVersionTest.java rename to src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/RedisVersionTest.java diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/LiveRedisCompositionTest.java b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/LiveRedisCompositionTest.java similarity index 100% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/LiveRedisCompositionTest.java rename to src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/LiveRedisCompositionTest.java diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/LiveRedisTlsTest.java b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/LiveRedisTlsTest.java similarity index 83% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/LiveRedisTlsTest.java rename to src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/LiveRedisTlsTest.java index 10a77ad0..da591766 100644 --- a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/LiveRedisTlsTest.java +++ b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/LiveRedisTlsTest.java @@ -7,6 +7,8 @@ import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisC import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisLease; import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeOwner; import java.io.IOException; +import java.net.URL; +import java.net.URLClassLoader; import java.nio.file.Files; import java.nio.file.Path; import java.util.Optional; @@ -14,6 +16,7 @@ import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; @@ -73,28 +76,30 @@ class LiveRedisTlsTest { @Test @DisplayName("a classpath CA reference works too, rather than being read as a file name") - void aClasspathTrustReferenceWorks() throws IOException { + void aClasspathTrustReferenceWorks(@TempDir Path classpathRoot) throws IOException { // The defect this covers: the trust material was resolved with `new File(...)`, so a // `classpath:` reference — a CA bundled with the application, which is an ordinary deployment // — failed at the handshake complaining about a file that was never meant to exist. - Path onClasspath = - Path.of("build", "resources", "test", "redis-tls-lane-ca.pem").toAbsolutePath(); - Files.createDirectories(onClasspath.getParent()); + // The CA goes on a classpath root of its own: writing it under build/resources/test only works + // when that directory existed before the test JVM started, since Gradle drops absent entries. Files.copy( - Path.of(endpoint.requireTrustMaterial()), - onClasspath, - java.nio.file.StandardCopyOption.REPLACE_EXISTING); + Path.of(endpoint.requireTrustMaterial()), classpathRoot.resolve("redis-tls-lane-ca.pem")); - runner("classpath:redis-tls-lane-ca.pem") - .run( - context -> { - assertThat(context).hasNotFailed(); - try (RedisLease lease = - context.getBean(RedisRuntimeOwner.class).borrow(RedisConnectionKind.REGULAR)) { - assertThat(lease.gateway().ping().toCompletableFuture().get(5, TimeUnit.SECONDS)) - .isEqualTo("PONG"); - } - }); + try (URLClassLoader withCa = + new URLClassLoader( + new URL[] {classpathRoot.toUri().toURL()}, getClass().getClassLoader())) { + runner("classpath:redis-tls-lane-ca.pem") + .withClassLoader(withCa) + .run( + context -> { + assertThat(context).hasNotFailed(); + try (RedisLease lease = + context.getBean(RedisRuntimeOwner.class).borrow(RedisConnectionKind.REGULAR)) { + assertThat(lease.gateway().ping().toCompletableFuture().get(5, TimeUnit.SECONDS)) + .isEqualTo("PONG"); + } + }); + } } @Test diff --git a/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisScriptLaneAdmissionTest.java b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisScriptLaneAdmissionTest.java new file mode 100644 index 00000000..464cc7de --- /dev/null +++ b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisScriptLaneAdmissionTest.java @@ -0,0 +1,157 @@ +package dev.caskeleton.adapter.outbound.cache.redis.sdk.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.InstanceOfAssertFactories.type; + +import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisDeploymentMode; +import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.error.RedisCommandRejectedException; +import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisConnectionKind; +import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisLease; +import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeClient; +import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeOwner; +import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations.RedisCommandGateway; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import java.util.Queue; +import java.util.concurrent.BrokenBarrierException; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.CyclicBarrier; +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.Test; + +/** + * The SCRIPT lane limit is a connection bound, not a concurrency cap on callers. + * + *

Each lease holds one pooled connection for one script round trip, so a burst above the limit + * has to queue for a returned connection. Refusing it immediately rejected the ninth concurrent + * rate-limit call against a perfectly healthy Redis. + */ +class RedisScriptLaneAdmissionTest { + + private static final String SERVED = "served"; + + @Test + void callersBeyondTheScriptLaneLimitWaitForAReturnedConnectionInsteadOfBeingRefused() + throws Exception { + int limit = 2; + int callers = limit + 3; + try (RedisRuntimeOwner owner = owner(limit, Duration.ofSeconds(10))) { + // given + CyclicBarrier start = new CyclicBarrier(callers); + CountDownLatch scriptsComplete = new CountDownLatch(1); + Queue outcomes = new ConcurrentLinkedQueue<>(); + List threads = new ArrayList<>(); + for (int i = 0; i < callers; i++) { + threads.add( + Thread.ofPlatform() + .start(() -> outcomes.add(runScript(owner, start, scriptsComplete)))); + } + awaitParkedOrFinished(threads, callers - limit); + + // when + scriptsComplete.countDown(); + for (Thread thread : threads) { + thread.join(TimeUnit.SECONDS.toMillis(10)); + } + + // then + assertThat(outcomes).containsExactlyElementsOf(Collections.nCopies(callers, SERVED)); + } + } + + @Test + void aCallerStillWaitingWhenTheAcquireTimeoutRunsOutIsRefusedAsNotSent() { + try (RedisRuntimeOwner owner = owner(1, Duration.ofMillis(50)); + RedisLease held = owner.borrow(RedisConnectionKind.SCRIPT)) { + // when + Throwable refused = catchThrowable(() -> owner.borrow(RedisConnectionKind.SCRIPT)); + + // then + assertThat(refused) + .asInstanceOf(type(RedisCommandRejectedException.class)) + .extracting(Throwable::getMessage, rejection -> rejection.metadata().ambiguousExecution()) + .containsExactly( + "connection lane SCRIPT reached its limit of 1 and no connection was returned" + + " within PT0.05S [command=CONNECTION, mode=STANDALONE, ambiguous=false]", + false); + } + } + + private static RedisRuntimeOwner owner(int scriptConnections, Duration acquireTimeout) { + RedisSdkSettings settings = new RedisSdkSettings(); + settings.getCapacity().setMaximumScriptConnections(scriptConnections); + settings.getLifecycle().setAcquireTimeout(acquireTimeout); + return new RedisSdkAutoConfiguration().redisRuntimeOwner(new NoopClient(), settings); + } + + /** One semantic script call: the lease is held until the test lets the script complete. */ + private static String runScript( + RedisRuntimeOwner owner, CyclicBarrier start, CountDownLatch scriptsComplete) { + try { + start.await(); + try (RedisLease lease = owner.borrow(RedisConnectionKind.SCRIPT)) { + scriptsComplete.await(); + return SERVED; + } + } catch (RedisCommandRejectedException refused) { + return refused.getMessage(); + } catch (InterruptedException | BrokenBarrierException interrupted) { + Thread.currentThread().interrupt(); + return interrupted.toString(); + } + } + + /** + * Waits until the callers that found the lane full have either parked in a timed wait for a + * connection or already finished (refused). Holders park untimed on the latch, so they are not + * counted; either way nothing is released before every caller has tried to borrow. + */ + private static void awaitParkedOrFinished(List threads, int expected) { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (threads.stream() + .map(Thread::getState) + .filter(s -> s == Thread.State.TIMED_WAITING || s == Thread.State.TERMINATED) + .count() + < expected) { + if (System.nanoTime() > deadline) { + fail("callers beyond the limit neither queued nor finished"); + } + Thread.onSpinWait(); + } + } + + private static final class NoopClient implements RedisRuntimeClient { + + @Override + public RedisDeploymentMode mode() { + return RedisDeploymentMode.STANDALONE; + } + + @Override + public RedisLaneConnection openLane(RedisConnectionKind kind, Optional routingKey) { + return new RedisLaneConnection() { + @Override + public RedisCommandGateway gateway() { + return null; + } + + @Override + public boolean open() { + return true; + } + + @Override + public void close() {} + }; + } + + @Override + public void close() {} + } +} diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisScriptLaneCapacityTest.java b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisScriptLaneCapacityTest.java similarity index 95% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisScriptLaneCapacityTest.java rename to src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisScriptLaneCapacityTest.java index 75322efa..5f4f7cf9 100644 --- a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisScriptLaneCapacityTest.java +++ b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisScriptLaneCapacityTest.java @@ -9,6 +9,7 @@ import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisL import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeClient; import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeOwner; import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations.RedisCommandGateway; +import java.time.Duration; import java.util.Optional; import org.junit.jupiter.api.Test; @@ -19,6 +20,7 @@ class RedisScriptLaneCapacityTest { RedisSdkSettings settings = new RedisSdkSettings(); settings.getCapacity().setMaximumInFlightCommands(64); settings.getCapacity().setMaximumScriptConnections(2); + settings.getLifecycle().setAcquireTimeout(Duration.ofMillis(50)); RedisRuntimeOwner owner = new RedisSdkAutoConfiguration().redisRuntimeOwner(new NoopClient(), settings); diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisSdkAutoConfigurationTest.java b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisSdkAutoConfigurationTest.java similarity index 84% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisSdkAutoConfigurationTest.java rename to src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisSdkAutoConfigurationTest.java index 6e970867..0d23c412 100644 --- a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisSdkAutoConfigurationTest.java +++ b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisSdkAutoConfigurationTest.java @@ -79,7 +79,7 @@ class RedisSdkAutoConfigurationTest { "app.redis.database=7", "app.redis.nodes=", "app.redis.timeout.fast=0s", - "app.redis.blocking.max-block=0s") + "app.redis.blocking.max-connections=0") .run( context -> { assertThat(context).hasNotFailed(); @@ -105,9 +105,7 @@ class RedisSdkAutoConfigurationTest { "app.redis.nodes=node-a:7000,node-b:7001", "app.redis.authentication.credential-reference=secret://environment/APP_REDIS_PASSWORD", "app.redis.admin.enabled=true", - "app.redis.admin.credential-reference=secret://environment/APP_REDIS_ADMIN", - "app.redis.raw.enabled=true", - "app.redis.raw.credential-reference=secret://environment/APP_REDIS_RAW") + "app.redis.admin.credential-reference=secret://environment/APP_REDIS_ADMIN") .withBean( RedisSdkAutoConfiguration.RedisSecretSource.class, () -> @@ -195,70 +193,6 @@ class RedisSdkAutoConfigurationTest { }); } - @Test - @DisplayName("the switch on fails the context when a blocking command would be unbounded") - void enabledRejectsAnUnboundedBlock() { - runner - .withPropertyValues("app.redis.enabled=true", "app.redis.blocking.max-block=0s") - .run( - context -> { - assertThat(context).hasFailed(); - assertThat(context.getStartupFailure()) - .hasStackTraceContaining("blocking commands must not be unbounded"); - }); - } - - @Test - @DisplayName("the switch on fails the context when the raw gateway has no allowlist") - void enabledRejectsARawGatewayWithoutAnAllowlist() { - runner - .withPropertyValues( - "app.redis.enabled=true", - "app.redis.raw.enabled=true", - "app.redis.raw.policy-resource=") - .run( - context -> { - assertThat(context).hasFailed(); - assertThat(context.getStartupFailure()) - .hasStackTraceContaining("the raw gateway requires an allowlist resource"); - }); - } - - @Test - @DisplayName("the switch on fails the context when the raw allowlist resource does not exist") - void enabledRejectsAMissingRawAllowlistResource() { - // The default location points at a resource this module does not ship, and validate() only - // checks that the setting is non-blank. Enabling the raw gateway therefore started cleanly and - // failed at the first raw command, against a live connection, from inside a request. - authenticated - .withPropertyValues( - "app.redis.enabled=true", - "app.redis.raw.enabled=true", - "app.redis.raw.credential-reference=secret://environment/APP_REDIS_RAW_CREDENTIAL", - "app.redis.raw.policy-resource=classpath:redis-sdk/raw-command-allowlist.yml") - .run( - context -> { - assertThat(context).hasFailed(); - assertThat(context.getStartupFailure()) - .hasStackTraceContaining("raw-command-allowlist.yml") - .hasStackTraceContaining("does not exist or cannot be read"); - }); - } - - @Test - @DisplayName("the switch on accepts a raw allowlist resource that is actually present") - void enabledAcceptsAReadableRawAllowlistResource() { - authenticated - .withPropertyValues( - "app.redis.enabled=true", - "app.redis.raw.enabled=true", - "app.redis.raw.credential-reference=secret://environment/APP_REDIS_RAW_CREDENTIAL", - // Any readable classpath resource proves the check reads rather than guesses; the - // command policy is the one resource this module is guaranteed to ship. - "app.redis.raw.policy-resource=classpath:redis-sdk/redis-command-policy.yml") - .run(context -> assertThat(context).hasNotFailed()); - } - @Test @DisplayName("a standalone deployment with several nodes is refused rather than picking one") void standaloneWithSeveralNodesIsRefused() { diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisSdkSettingsTest.java b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisSdkSettingsTest.java similarity index 75% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisSdkSettingsTest.java rename to src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisSdkSettingsTest.java index 6b576bbf..0a0babb0 100644 --- a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisSdkSettingsTest.java +++ b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisSdkSettingsTest.java @@ -52,31 +52,6 @@ class RedisSdkSettingsTest { assertThatThrownBy(failure::validate).hasMessageContaining("must not exceed 30s"); } - @Test - void blockingMustNeverBeUnbounded() { - RedisSdkSettings properties = validProperties(); - properties.getBlocking().setMaxBlock(Duration.ZERO); - - assertThatThrownBy(properties::validate).hasMessageContaining("must not be unbounded"); - } - - @Test - void theRawGatewayRequiresAnAllowlistAndItsOwnCredential() { - RedisSdkSettings missingAllowlist = validProperties(); - missingAllowlist.getRaw().setEnabled(true); - missingAllowlist.getRaw().setPolicyResource(" "); - - assertThatThrownBy(missingAllowlist::validate).hasMessageContaining("allowlist resource"); - - RedisSdkSettings missingCredential = validProperties(); - missingCredential.getRaw().setEnabled(true); - - // The setting by name. An operator reading "requires its own credential reference" has to work - // out which of the five credential references the registry declares is the missing one. - assertThatThrownBy(missingCredential::validate) - .hasMessageContaining("app.redis.raw.credential-reference"); - } - @Test void theAdminPlaneRequiresItsOwnCredential() { RedisSdkSettings properties = validProperties(); @@ -115,15 +90,6 @@ class RedisSdkSettingsTest { assertThatCode(properties::validate).doesNotThrowAnyException(); } - @Test - void advancedPoliciesCannotBeConfiguredWhileAdvancedOperationsAreDisabled() { - RedisSdkSettings properties = validProperties(); - properties.getAdvanced().getPolicies().add("collection-full-read"); - - assertThatThrownBy(properties::validate) - .hasMessageContaining("advanced operations are disabled"); - } - @Test void defaultsMatchTheDesignGuardrails() { RedisSdkSettings properties = new RedisSdkSettings(); @@ -132,19 +98,10 @@ class RedisSdkSettingsTest { assertThat(properties.getMode()).isEqualTo(RedisDeploymentMode.STANDALONE); assertThat(properties.getDatabase()).isZero(); assertThat(properties.getTimeout().getFast()).isEqualTo(Duration.ofMillis(500)); - assertThat(properties.getTimeout().getCollection()).isEqualTo(Duration.ofSeconds(2)); assertThat(properties.getTimeout().getScript()).isEqualTo(Duration.ofSeconds(1)); assertThat(properties.getTimeout().getBatch()).isEqualTo(Duration.ofSeconds(2)); - assertThat(properties.getTimeout().getAdmin()).isEqualTo(Duration.ofSeconds(3)); - assertThat(properties.getLimits().getMaxKeyBytes()).isEqualTo(512); - assertThat(properties.getLimits().getMaxValueBytes()).isEqualTo(1_048_576L); - assertThat(properties.getLimits().getMaxBatchCommands()).isEqualTo(500); - assertThat(properties.getLimits().getOfflineQueueCommands()).isEqualTo(1_000); assertThat(properties.getBlocking().getMaxConnections()).isEqualTo(32); - assertThat(properties.getBlocking().getMaxBlock()).isEqualTo(Duration.ofSeconds(30)); assertThat(properties.getTransaction().getMaxConnections()).isEqualTo(16); - assertThat(properties.getAdvanced().isEnabled()).isFalse(); - assertThat(properties.getRaw().isEnabled()).isFalse(); assertThat(properties.getAdmin().isEnabled()).isFalse(); } diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RequiredWhenIsEnforcedTest.java b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RequiredWhenIsEnforcedTest.java similarity index 96% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RequiredWhenIsEnforcedTest.java rename to src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RequiredWhenIsEnforcedTest.java index ebb0ed7a..65ca0cce 100644 --- a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RequiredWhenIsEnforcedTest.java +++ b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RequiredWhenIsEnforcedTest.java @@ -126,10 +126,6 @@ class RequiredWhenIsEnforcedTest { extra.put( "app.redis.sentinel.credential-reference", "secret://s@environment/APP_REDIS_SENTINEL"); } - if ("app.redis.raw.enabled".equals(condition.property())) { - extra.put("app.redis.raw.credential-reference", "secret://r@environment/APP_REDIS_RAW"); - extra.put("app.redis.raw.policy-resource", "classpath:redis-sdk/redis-command-policy.yml"); - } if ("app.redis.admin.enabled".equals(condition.property())) { extra.put("app.redis.admin.credential-reference", "secret://a@environment/APP_REDIS_ADMIN"); } diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/RedisRuntimeOwnerTest.java b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/RedisRuntimeOwnerTest.java similarity index 97% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/RedisRuntimeOwnerTest.java rename to src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/RedisRuntimeOwnerTest.java index cd5253c6..054301ec 100644 --- a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/RedisRuntimeOwnerTest.java +++ b/src/adapter/outbound/redis-runtime/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/RedisRuntimeOwnerTest.java @@ -38,7 +38,7 @@ class RedisRuntimeOwnerTest { private final FakeClient client = new FakeClient(); private RedisRuntimeOwner owner(int perLane, Duration drain) { - return new RedisRuntimeOwner(client, limits(perLane), drain); + return new RedisRuntimeOwner(client, limits(perLane), Duration.ofMillis(50), drain); } @Test @@ -90,8 +90,8 @@ class RedisRuntimeOwnerTest { } @Test - @DisplayName("a lane at its ceiling refuses rather than queues") - void anExhaustedLaneRefuses() { + @DisplayName("a lane still at its ceiling when the acquire wait runs out refuses") + void anExhaustedLaneRefusesOnceTheAcquireWaitRunsOut() { try (RedisRuntimeOwner owner = owner(1, Duration.ofSeconds(1))) { RedisLease held = owner.borrow(RedisConnectionKind.BLOCKING); diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/RedisTopologyEndpoint.java b/src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/RedisTopologyEndpoint.java similarity index 100% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/RedisTopologyEndpoint.java rename to src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/RedisTopologyEndpoint.java diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/InMemoryGatewayAccess.java b/src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/InMemoryGatewayAccess.java similarity index 100% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/InMemoryGatewayAccess.java rename to src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/InMemoryGatewayAccess.java diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/InMemoryRedisCommandGateway.java b/src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/InMemoryRedisCommandGateway.java similarity index 100% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/InMemoryRedisCommandGateway.java rename to src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/InMemoryRedisCommandGateway.java diff --git a/src/adapter/outbound/redis-sdk/README.md b/src/adapter/outbound/redis-sdk/README.md new file mode 100644 index 00000000..1ccb848b --- /dev/null +++ b/src/adapter/outbound/redis-sdk/README.md @@ -0,0 +1,83 @@ +# adapter:outbound:redis-sdk — typed Redis SDK (library) + +A guarded, typed Redis API for service code that needs Redis data structures directly, beyond the +semantic ports `cache-redis` implements (cache, rate limit, lease, idempotency). + +It is a **library, not a capability**. Nothing turns on because this leaf is on the classpath: it +has no `AutoConfiguration.imports`, creates no beans, and has no `enabled` switch of its own. Service +code calls its types directly, so it cannot be taken as `runtimeOnly` (AGENTS.md, library-type +exception to the capability rules). + +## Adding it + +In the service's own outbound adapter leaf — never in `domain-core` or `application-core`: + +```groovy +implementation project(':adapter:outbound:redis-sdk') +implementation project(':adapter:outbound:redis-runtime') // RedisRuntimeOwner, RedisSdkSettings +``` + +and register both edges in that leaf's `allowed_dependencies` in +`src/config/architecture/modules.json` (HARD-STOP 5). Put the adapter behind an application-core +port, as for any other outbound capability. + +The connections come from `redis-runtime`: its `RedisSdkAutoConfiguration` exists only while +`APP_REDIS_ENABLED=true` and provides `RedisSdkSettings` and `RedisRuntimeOwner` (one bounded lane +per `RedisConnectionKind`, each authenticated as its role's account). The service's adapter +composes the SDK objects it uses on top of that; `LiveRedisOperationsFixture` in this leaf's tests +is a complete worked composition (catalog, permit verifier, guard, executor, operations). + +## What it provides + +| Package (`dev.caskeleton.adapter.outbound.cache.redis.sdk.*`) | Contents | +| --- | --- | +| `api.key` | typed keys (`ValueKey`, `HashKey`, `ListKey`, `SetKey`, `SortedSetKey`, `StreamKey`, `BitmapKey`, `GeoKey`, `HyperLogLogKey`), `TypedRedisKeys`, `RedisKeyRenderer`, `RedisSlotTag` | +| `api.operations` / `api.reactive` | per-structure operation interfaces, synchronous and Reactor: value, hash, hash-field expiration, list, blocking list, set, sorted set, bitmap, bitfield, HyperLogLog, geo, stream, blocking stream, stream deletion, key, batch, pub/sub, sharded pub/sub | +| `api.command`, `api.codec`, `api.error` | `OperationBudget`, permits (`MultiKeyPermit`, `AdvancedOperationPermit`), `RedisPolicyAuthority`; `RedisCodec`/`RedisPayloadCodec`; the typed exception family | +| `lettuce.operations` | the `Lettuce*Operations` implementations, `RedisOperationContext`, `RedisOperationLimits` | +| `lettuce.command` | `RedisCommandCatalog` (loaded from `redis-sdk/redis-command-policy.yml`), `CommandPolicyGuard` (every command is admitted here before it runs), exception translation, executors | +| `lettuce.codec` | UTF-8/long/double/bytes codecs, `VersionedJsonCodec`, `RedisCodecRegistry` | +| `lettuce.observability`, `lettuce.connection` | `RedisObservation` through a no-throw sink; `SentinelFailoverObserver` | +| `cluster` | `SameSlotValidator`, `ClusterScanCursor`, `ClusterTopologyObserver` | +| `config` | `ConfiguredRedisPolicyAuthority`, `ConfiguredRedisPermitVerifier`, `RedisCapabilityProbe`, `RedisStartupProbe` | +| `programmability` | `WATCH`/`MULTI`/`EXEC` transactions (never roll back), registered scripts (`EVALSHA` only), deployed functions | +| `raw` | `LettuceRedisRawGateway`: only commands the catalog marks `RAW_ONLY` **and** the service approves in `RawCommandApprovals` | +| `admin` | `LettuceRedisAdminOperations`: read-only diagnostics on the `ADMIN` lane, projected replies | +| `extensions.*` | Redis 8 modules: JSON, Search, Time Series, Probabilistic; each gated by the capability probe | + +Configuration that is **code, not settings** — there is no `app.redis.*` key for any of these: +operation ceilings and timeouts (`RedisOperationLimits`), the enabled advanced policies +(`ConfiguredRedisPolicyAuthority`), raw command approvals (`RawCommandApprovals`) and registered +scripts (`RedisScriptRegistry`). The service passes them where it composes the SDK. + +Package rules (driver containment, no string command surface, the transaction and raw-gateway +invariants) are in `src/adapter/outbound/cache-redis/CLAUDE.md` under "Redis runtime and optional +typed SDK"; `RedisSdkModuleBoundaryTest` enforces them. + +## Env keys + +The SDK reads none itself. It runs on `redis-runtime`, whose rows in +`docs/registries/env-keys.yaml` (owner `adapter-outbound-redis-runtime`) are the contract: + +- Required: `APP_REDIS_ENABLED` left at its default `true`, `APP_REDIS_NODES`, `APP_REDIS_MODE`, + `APP_REDIS_NAMESPACE_ENVIRONMENT`, `APP_REDIS_NAMESPACE_SERVICE`, `APP_REDIS_NAMESPACE_DOMAIN`, + and `APP_REDIS_AUTHENTICATION_CREDENTIAL_REFERENCE` (or + `APP_REDIS_AUTHENTICATION_ANONYMOUS_ACCESS_ACCEPTED=true`). +- Per SDK surface used: `APP_REDIS_AUTHENTICATION_ADVANCED_CREDENTIAL_REFERENCE` (scripts, + functions; falls back to the application account with a startup warning), + `APP_REDIS_AUTHENTICATION_PUBSUB_CREDENTIAL_REFERENCE` (pub/sub), `APP_REDIS_ADMIN_ENABLED` + + `APP_REDIS_ADMIN_CREDENTIAL_REFERENCE` (admin plane), lane ceilings + `APP_REDIS_BLOCKING_MAX_CONNECTIONS`, `APP_REDIS_TRANSACTION_MAX_CONNECTIONS`, + `APP_REDIS_CAPACITY_MAXIMUM_SCRIPT_CONNECTIONS`. +- Topology: `APP_REDIS_SENTINEL_*` when `APP_REDIS_MODE=sentinel`, `APP_REDIS_TLS_*` for TLS. + +## Tests + +```bash +./gradlew :adapter:outbound:redis-sdk:test --console=plain +``` + +Contract tests run the operations against the in-memory gateway from +`testFixtures(project(':adapter:outbound:redis-runtime'))`. The real-server lane is +`redisTopologyTest` (see `infra/redis-sdk/README.md`); this leaf declares `standalone`, `sentinel` +and `cluster` in `build.gradle`. `tls` is qualified by `redis-runtime`. diff --git a/src/adapter/outbound/redis-sdk/build.gradle b/src/adapter/outbound/redis-sdk/build.gradle index cf30b8c8..d13ae0e2 100644 --- a/src/adapter/outbound/redis-sdk/build.gradle +++ b/src/adapter/outbound/redis-sdk/build.gradle @@ -1,8 +1,9 @@ plugins { id 'ca.spring-library' + id 'ca.redis-topology-lane' } -description = 'Optional typed Redis SDK: guarded typed operations, admin/raw surfaces and extensions' +description = 'Optional typed Redis SDK library: guarded typed operations, admin/raw surfaces and extensions' dependencies { implementation project(':adapter:outbound:redis-runtime') @@ -10,4 +11,13 @@ dependencies { implementation 'io.lettuce:lettuce-core' implementation 'io.projectreactor:reactor-core' implementation 'org.slf4j:slf4j-api' + + testImplementation testFixtures(project(':adapter:outbound:redis-runtime')) +} + +// No tls lane: TLS is a transport property of redis-runtime's client, qualified there. +redisTopologyLane { + requiredClasses 'standalone', 'RedisTopologyContractTest', 'LiveRedisGuardrailTest' + requiredClasses 'sentinel', 'RedisTopologyContractTest', 'LiveRedisSentinelPromotionTest' + requiredClasses 'cluster', 'LiveRedisClusterTest', 'LiveRedisClusterTransactionTest' } diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/ReactiveRedisOperations.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/ReactiveRedisOperations.java deleted file mode 100644 index 23471ca9..00000000 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/ReactiveRedisOperations.java +++ /dev/null @@ -1,108 +0,0 @@ -package dev.caskeleton.adapter.outbound.cache.redis.sdk.api; - -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.reactive.ReactiveRedisBatchOperations; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.reactive.ReactiveRedisBitFieldOperations; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.reactive.ReactiveRedisBitmapOperations; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.reactive.ReactiveRedisGeoOperations; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.reactive.ReactiveRedisHashOperations; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.reactive.ReactiveRedisHyperLogLogOperations; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.reactive.ReactiveRedisKeyOperations; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.reactive.ReactiveRedisListOperations; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.reactive.ReactiveRedisSetOperations; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.reactive.ReactiveRedisSortedSetOperations; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.reactive.ReactiveRedisStreamOperations; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.reactive.ReactiveRedisValueOperations; - -/** - * Reactive entry point to the typed Redis API. - * - *

Mirrors {@link RedisOperations} method for method. The two are separate types on purpose: a - * single generic asynchronous abstraction would push {@code CompletionStage} into every call site - * and make the blocking cost of a synchronous caller invisible. - */ -public interface ReactiveRedisOperations { - - /** - * Returns reactive string operations. - * - * @return the string operations - */ - ReactiveRedisValueOperations values(); - - /** - * Returns reactive hash operations. - * - * @return the hash operations - */ - ReactiveRedisHashOperations hashes(); - - /** - * Returns reactive list operations. - * - * @return the list operations - */ - ReactiveRedisListOperations lists(); - - /** - * Returns reactive set operations. - * - * @return the set operations - */ - ReactiveRedisSetOperations sets(); - - /** - * Returns reactive sorted set operations. - * - * @return the sorted set operations - */ - ReactiveRedisSortedSetOperations sortedSets(); - - /** - * Returns reactive bitmap operations. - * - * @return the bitmap operations - */ - ReactiveRedisBitmapOperations bitmaps(); - - /** - * Returns reactive bitfield operations. - * - * @return the bitfield operations - */ - ReactiveRedisBitFieldOperations bitFields(); - - /** - * Returns reactive HyperLogLog operations. - * - * @return the HyperLogLog operations - */ - ReactiveRedisHyperLogLogOperations hyperLogLogs(); - - /** - * Returns reactive geospatial operations. - * - * @return the geospatial operations - */ - ReactiveRedisGeoOperations geo(); - - /** - * Returns reactive stream operations. - * - * @return the stream operations - */ - ReactiveRedisStreamOperations streams(); - - /** - * Returns reactive key and expiry operations. - * - * @return the key operations - */ - ReactiveRedisKeyOperations keys(); - - /** - * Returns reactive batch operations. - * - * @return the batch operations - */ - ReactiveRedisBatchOperations batches(); -} diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/RedisOperations.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/RedisOperations.java deleted file mode 100644 index 4674a18c..00000000 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/RedisOperations.java +++ /dev/null @@ -1,109 +0,0 @@ -package dev.caskeleton.adapter.outbound.cache.redis.sdk.api; - -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.RedisBatchOperations; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.RedisBitFieldOperations; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.RedisBitmapOperations; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.RedisGeoOperations; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.RedisHashOperations; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.RedisHyperLogLogOperations; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.RedisKeyOperations; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.RedisListOperations; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.RedisSetOperations; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.RedisSortedSetOperations; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.RedisStreamOperations; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations.RedisValueOperations; - -/** - * Synchronous entry point to the typed Redis API. - * - *

Blocking, transactional, Pub/Sub, admin, raw, and extension surfaces are deliberately not - * reachable from here. Each of those needs a different connection, a different ACL account, or a - * different deployment decision, and folding them into one facade is how those separations get - * lost. - */ -public interface RedisOperations { - - /** - * Returns string operations. - * - * @return the string operations - */ - RedisValueOperations values(); - - /** - * Returns hash operations. - * - * @return the hash operations - */ - RedisHashOperations hashes(); - - /** - * Returns list operations. - * - * @return the list operations - */ - RedisListOperations lists(); - - /** - * Returns set operations. - * - * @return the set operations - */ - RedisSetOperations sets(); - - /** - * Returns sorted set operations. - * - * @return the sorted set operations - */ - RedisSortedSetOperations sortedSets(); - - /** - * Returns bitmap operations. - * - * @return the bitmap operations - */ - RedisBitmapOperations bitmaps(); - - /** - * Returns bitfield operations. - * - * @return the bitfield operations - */ - RedisBitFieldOperations bitFields(); - - /** - * Returns HyperLogLog operations. - * - * @return the HyperLogLog operations - */ - RedisHyperLogLogOperations hyperLogLogs(); - - /** - * Returns geospatial operations. - * - * @return the geospatial operations - */ - RedisGeoOperations geo(); - - /** - * Returns stream operations. - * - * @return the stream operations - */ - RedisStreamOperations streams(); - - /** - * Returns key and expiry operations. - * - * @return the key operations - */ - RedisKeyOperations keys(); - - /** - * Returns batch operations. - * - * @return the batch operations - */ - RedisBatchOperations batches(); -} diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/ExpirationUpdatePolicy.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/ExpirationUpdatePolicy.java deleted file mode 100644 index c498a640..00000000 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/operations/ExpirationUpdatePolicy.java +++ /dev/null @@ -1,13 +0,0 @@ -package dev.caskeleton.adapter.outbound.cache.redis.sdk.api.operations; - -/** How a write interacts with an expiry that already exists. */ -public enum ExpirationUpdatePolicy { - /** Leave the current expiry untouched. */ - KEEP_EXISTING, - /** Replace whatever expiry the key has. */ - REPLACE, - /** Apply only when the key currently has no expiry. */ - ONLY_IF_NO_EXPIRY, - /** Apply only when the key currently has an expiry. */ - ONLY_IF_HAS_EXPIRY -} diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/RedisCommandMetadataDiff.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/RedisCommandMetadataDiff.java deleted file mode 100644 index a5e60cab..00000000 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/RedisCommandMetadataDiff.java +++ /dev/null @@ -1,145 +0,0 @@ -package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.command; - -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.CommandId; -import java.util.Collection; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.stream.Collectors; - -/** - * Difference between the shipped command policy and what a target server reports. - * - *

The build gate is not "did anything change" for its own sake. Each bucket is a way the policy - * could silently stop describing reality: a new command nobody classified, a command that vanished, - * a key specification that moved so key extraction now points at the wrong argument, an ACL - * category change that quietly widens an account, or a deprecation the typed API still exposes. - * - * @param added commands the server has and the policy does not - * @param removed commands the policy has and the server does not - * @param changedKeySpecs commands whose positional key specification moved - * @param changedAclCategories commands whose ACL categories changed - * @param deprecatedChanges commands the server newly reports as deprecated - */ -public record RedisCommandMetadataDiff( - Set added, - Set removed, - Set changedKeySpecs, - Set changedAclCategories, - Set deprecatedChanges) { - - public RedisCommandMetadataDiff { - added = Set.copyOf(Objects.requireNonNull(added, "added must be non-null")); - removed = Set.copyOf(Objects.requireNonNull(removed, "removed must be non-null")); - changedKeySpecs = - Set.copyOf(Objects.requireNonNull(changedKeySpecs, "changedKeySpecs must be non-null")); - changedAclCategories = - Set.copyOf( - Objects.requireNonNull(changedAclCategories, "changedAclCategories must be non-null")); - deprecatedChanges = - Set.copyOf(Objects.requireNonNull(deprecatedChanges, "deprecatedChanges must be non-null")); - } - - /** - * Compares the catalog against server metadata. - * - * @param catalog the shipped policy catalog - * @param serverMetadata what the target server reports - * @param recordedAclCategories the ACL categories previously reviewed, keyed by command - * @return the difference - */ - public static RedisCommandMetadataDiff compare( - RedisCommandCatalog catalog, - Collection serverMetadata, - Map> recordedAclCategories) { - Objects.requireNonNull(catalog, "catalog must be non-null"); - Objects.requireNonNull(serverMetadata, "server metadata must be non-null"); - Objects.requireNonNull(recordedAclCategories, "recorded ACL categories must be non-null"); - - Map reported = new LinkedHashMap<>(); - for (RedisServerCommandMetadata metadata : serverMetadata) { - reported.put(metadata.commandId(), metadata); - } - - Set added = - reported.keySet().stream() - .filter(commandId -> !catalog.contains(commandId)) - .collect(Collectors.toSet()); - - Set removed = - catalog.commandIds().stream() - .filter(commandId -> !reported.containsKey(commandId)) - .collect(Collectors.toSet()); - - Set changedKeySpecs = - reported.values().stream() - .filter(metadata -> catalog.contains(metadata.commandId())) - .filter( - metadata -> - !catalog.require(metadata.commandId()).keySpec().equals(metadata.keySpec())) - .map(RedisServerCommandMetadata::commandId) - .collect(Collectors.toSet()); - - Set changedAclCategories = - reported.values().stream() - .filter(metadata -> recordedAclCategories.containsKey(metadata.commandId())) - .filter( - metadata -> - !recordedAclCategories - .get(metadata.commandId()) - .equals(metadata.aclCategories())) - .map(RedisServerCommandMetadata::commandId) - .collect(Collectors.toSet()); - - Set deprecatedChanges = - reported.values().stream() - .filter(RedisServerCommandMetadata::deprecated) - .filter(metadata -> catalog.contains(metadata.commandId())) - .filter( - metadata -> - catalog.require(metadata.commandId()).descriptor().applicationReachable()) - .map(RedisServerCommandMetadata::commandId) - .collect(Collectors.toSet()); - - return new RedisCommandMetadataDiff( - added, removed, changedKeySpecs, changedAclCategories, deprecatedChanges); - } - - /** - * Reports whether a human has to look at this difference before release. - * - * @return {@code true} when any bucket is non-empty - */ - public boolean requiresReview() { - return !(added.isEmpty() - && removed.isEmpty() - && changedKeySpecs.isEmpty() - && changedAclCategories.isEmpty() - && deprecatedChanges.isEmpty()); - } - - /** - * Renders the difference as a stable Markdown block for a build failure message. - * - * @return the rendered difference - */ - public String toMarkdown() { - StringBuilder markdown = new StringBuilder("### Redis command metadata drift\n"); - appendSection(markdown, "Added on the server, absent from policy", added); - appendSection(markdown, "Present in policy, absent on the server", removed); - appendSection(markdown, "Key specification changed", changedKeySpecs); - appendSection(markdown, "ACL categories changed", changedAclCategories); - appendSection(markdown, "Deprecated but still application reachable", deprecatedChanges); - return markdown.toString(); - } - - private static void appendSection(StringBuilder markdown, String title, Set members) { - if (members.isEmpty()) { - return; - } - markdown.append("\n- ").append(title).append(": "); - markdown.append( - members.stream().map(CommandId::toString).sorted().collect(Collectors.joining(", "))); - } -} diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/RedisServerCommandMetadata.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/RedisServerCommandMetadata.java deleted file mode 100644 index e54187b7..00000000 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/RedisServerCommandMetadata.java +++ /dev/null @@ -1,29 +0,0 @@ -package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.command; - -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.CommandId; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.KeySpec; -import java.util.Objects; -import java.util.Set; - -/** - * What the server itself reports about a command. - * - *

Populated from {@code COMMAND DOCS}, {@code COMMAND INFO}, and {@code COMMAND - * GETKEYSANDFLAGS}. This is evidence, not policy: it is the side of the drift comparison that the - * organization does not control. - * - * @param commandId the reported command identity - * @param keySpec the reported positional key specification - * @param aclCategories the reported ACL categories, without the leading {@code @} - * @param deprecated whether the server marks the command deprecated - */ -public record RedisServerCommandMetadata( - CommandId commandId, KeySpec keySpec, Set aclCategories, boolean deprecated) { - - public RedisServerCommandMetadata { - Objects.requireNonNull(commandId, "command id must be non-null"); - Objects.requireNonNull(keySpec, "key specification must be non-null"); - Objects.requireNonNull(aclCategories, "ACL categories must be non-null"); - aclCategories = Set.copyOf(aclCategories); - } -} diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/RedisConnectionLease.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/RedisConnectionLease.java deleted file mode 100644 index 6fc28d3e..00000000 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/RedisConnectionLease.java +++ /dev/null @@ -1,28 +0,0 @@ -package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection; - -/** - * A borrowed connection that must be returned. - * - *

Returning is not optional and not best effort. A lease that is never closed removes one - * connection from a bounded pool permanently, which is why the type is {@link AutoCloseable} and - * the registry counts outstanding leases. - */ -public interface RedisConnectionLease extends AutoCloseable { - - /** - * Returns the lane this lease was taken from. - * - * @return the connection lane - */ - RedisConnectionKind kind(); - - /** - * Returns the driver connection handle. - * - * @return the underlying connection - */ - Object connection(); - - @Override - void close(); -} diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/RedisConnectionRegistry.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/RedisConnectionRegistry.java deleted file mode 100644 index 6d74f61b..00000000 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/RedisConnectionRegistry.java +++ /dev/null @@ -1,142 +0,0 @@ -package dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection; - -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisDeploymentMode; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.command.CommandAccess; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.error.RedisCommandRejectedException; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.error.RedisFailureMetadata; -import java.util.EnumMap; -import java.util.Map; -import java.util.Objects; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.Function; - -/** - * Bounded registry of the five connection lanes. - * - *

Every lane has its own hard ceiling. When a lane is exhausted the caller is rejected - * immediately rather than queued, because an unbounded wait converts a saturated pool into a - * cascading latency failure across every caller of the process. - */ -public final class RedisConnectionRegistry implements AutoCloseable { - - private final Map limits; - private final Map borrowed; - private final Function connectionFactory; - private final RedisDeploymentMode deploymentMode; - - /** - * Creates a registry. - * - * @param limits per-lane maximum concurrent leases - * @param connectionFactory supplies a driver connection for a lane - * @param deploymentMode the bound deployment mode, used for failure metadata - */ - public RedisConnectionRegistry( - Map limits, - Function connectionFactory, - RedisDeploymentMode deploymentMode) { - Objects.requireNonNull(limits, "limits must be non-null"); - this.connectionFactory = - Objects.requireNonNull(connectionFactory, "connection factory must be non-null"); - this.deploymentMode = - Objects.requireNonNull(deploymentMode, "deployment mode must be non-null"); - Map configured = new EnumMap<>(RedisConnectionKind.class); - Map counters = new EnumMap<>(RedisConnectionKind.class); - for (RedisConnectionKind kind : RedisConnectionKind.values()) { - Integer limit = limits.get(kind); - if (limit == null || limit < 1) { - throw new IllegalArgumentException("connection lane " + kind + " needs a positive limit"); - } - configured.put(kind, limit); - counters.put(kind, new AtomicInteger()); - } - this.limits = Map.copyOf(configured); - this.borrowed = Map.copyOf(counters); - } - - /** - * Borrows a connection from a lane. - * - * @param kind the lane - * @return the lease - * @throws RedisCommandRejectedException when the lane is at its ceiling - */ - public RedisConnectionLease borrow(RedisConnectionKind kind) { - Objects.requireNonNull(kind, "connection kind must be non-null"); - AtomicInteger counter = borrowed.get(kind); - int limit = limits.get(kind); - int current = counter.incrementAndGet(); - if (current > limit) { - counter.decrementAndGet(); - throw new RedisCommandRejectedException( - "connection lane " + kind + " reached its limit of " + limit, - RedisFailureMetadata.notSent("CONNECTION", CommandAccess.NONE, false, deploymentMode)); - } - Object connection; - try { - connection = connectionFactory.apply(kind); - } catch (RuntimeException failure) { - counter.decrementAndGet(); - throw failure; - } - return new Lease(kind, connection, counter); - } - - /** - * Returns how many leases of a lane are currently outstanding. - * - * @param kind the lane - * @return the outstanding lease count - */ - public int borrowedCount(RedisConnectionKind kind) { - return borrowed.get(Objects.requireNonNull(kind, "connection kind must be non-null")).get(); - } - - /** - * Returns the configured ceiling of a lane. - * - * @param kind the lane - * @return the maximum concurrent leases - */ - public int limit(RedisConnectionKind kind) { - return limits.get(Objects.requireNonNull(kind, "connection kind must be non-null")); - } - - @Override - public void close() { - borrowed.values().forEach(counter -> counter.set(0)); - } - - private static final class Lease implements RedisConnectionLease { - - private final RedisConnectionKind kind; - private final Object connection; - private final AtomicInteger counter; - private boolean closed; - - private Lease(RedisConnectionKind kind, Object connection, AtomicInteger counter) { - this.kind = kind; - this.connection = connection; - this.counter = counter; - } - - @Override - public RedisConnectionKind kind() { - return kind; - } - - @Override - public Object connection() { - return connection; - } - - @Override - public synchronized void close() { - if (closed) { - return; - } - closed = true; - counter.decrementAndGet(); - } - } -} diff --git a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisOperationLimits.java b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisOperationLimits.java index 0e94f868..b2676d7c 100644 --- a/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisOperationLimits.java +++ b/src/adapter/outbound/redis-sdk/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisOperationLimits.java @@ -49,7 +49,10 @@ public record RedisOperationLimits( } /** - * The limits that match the shipped {@code RedisSdkSettings} defaults. + * Conservative defaults for a template deployment. + * + *

These are code, not configuration: there is no {@code app.redis.*} key for them. A service + * that needs other ceilings constructs its own instance where it composes the operations. * * @return conservative limits suitable for a template deployment */ diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/RedisSdkModuleBoundaryTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/RedisSdkModuleBoundaryTest.java similarity index 100% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/RedisSdkModuleBoundaryTest.java rename to src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/RedisSdkModuleBoundaryTest.java diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/RedisSupportMatrixTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/RedisSupportMatrixTest.java similarity index 100% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/RedisSupportMatrixTest.java rename to src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/RedisSupportMatrixTest.java diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/RedisTopologyContractTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/RedisTopologyContractTest.java similarity index 100% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/RedisTopologyContractTest.java rename to src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/RedisTopologyContractTest.java diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/ApiParityInspector.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/ApiParityInspector.java similarity index 100% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/ApiParityInspector.java rename to src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/ApiParityInspector.java diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/ApiParityReport.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/ApiParityReport.java similarity index 100% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/ApiParityReport.java rename to src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/ApiParityReport.java diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/ApiParityTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/ApiParityTest.java similarity index 88% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/ApiParityTest.java rename to src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/ApiParityTest.java index ea4317af..e308ac80 100644 --- a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/ApiParityTest.java +++ b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/ApiParityTest.java @@ -32,9 +32,7 @@ import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.reactive.ReactiveRedi import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.reactive.ReactiveRedisSortedSetOperations; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.reactive.ReactiveRedisStreamOperations; import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.reactive.ReactiveRedisValueOperations; -import java.lang.reflect.Method; import java.util.Arrays; -import java.util.List; import java.util.Map; import org.junit.jupiter.api.Test; @@ -92,28 +90,6 @@ class ApiParityTest { }); } - @Test - void theTwoEntryPointsExposeTheSameStructureAccessors() { - List syncAccessors = accessorNames(RedisOperations.class); - List reactiveAccessors = accessorNames(ReactiveRedisOperations.class); - - assertThat(reactiveAccessors).containsExactlyElementsOf(syncAccessors); - assertThat(syncAccessors) - .containsExactly( - "batches", - "bitFields", - "bitmaps", - "geo", - "hashes", - "hyperLogLogs", - "keys", - "lists", - "sets", - "sortedSets", - "streams", - "values"); - } - @Test void everyReactiveMethodReturnsAPublisher() { PAIRS @@ -135,8 +111,4 @@ class ApiParityTest { assertThat(report.differences()).isNotEmpty(); } - - private static List accessorNames(Class type) { - return Arrays.stream(type.getMethods()).map(Method::getName).sorted().toList(); - } } diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/RedisCapabilitiesTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/RedisCapabilitiesTest.java similarity index 100% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/RedisCapabilitiesTest.java rename to src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/RedisCapabilitiesTest.java diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/command/OperationBudgetTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/command/OperationBudgetTest.java similarity index 100% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/command/OperationBudgetTest.java rename to src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/command/OperationBudgetTest.java diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/key/RedisKeyRendererTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/key/RedisKeyRendererTest.java similarity index 100% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/key/RedisKeyRendererTest.java rename to src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/key/RedisKeyRendererTest.java diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/key/RedisKeyRulesTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/key/RedisKeyRulesTest.java similarity index 100% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/key/RedisKeyRulesTest.java rename to src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/api/key/RedisKeyRulesTest.java diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/cluster/ClusterObservationTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/cluster/ClusterObservationTest.java similarity index 100% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/cluster/ClusterObservationTest.java rename to src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/cluster/ClusterObservationTest.java diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/cluster/RedisSlotCalculatorTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/cluster/RedisSlotCalculatorTest.java similarity index 100% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/cluster/RedisSlotCalculatorTest.java rename to src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/cluster/RedisSlotCalculatorTest.java diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisCapabilityProbeTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisCapabilityProbeTest.java similarity index 100% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisCapabilityProbeTest.java rename to src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisCapabilityProbeTest.java diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisPermitProvenanceTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisPermitProvenanceTest.java similarity index 100% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisPermitProvenanceTest.java rename to src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisPermitProvenanceTest.java diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisStartupProbeTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisStartupProbeTest.java similarity index 100% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisStartupProbeTest.java rename to src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/config/RedisStartupProbeTest.java diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/codec/RedisCodecRegistryTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/codec/RedisCodecRegistryTest.java similarity index 100% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/codec/RedisCodecRegistryTest.java rename to src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/codec/RedisCodecRegistryTest.java diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/codec/VersionedJsonCodecTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/codec/VersionedJsonCodecTest.java similarity index 100% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/codec/VersionedJsonCodecTest.java rename to src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/codec/VersionedJsonCodecTest.java diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/CommandPolicyGuardTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/CommandPolicyGuardTest.java similarity index 100% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/CommandPolicyGuardTest.java rename to src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/CommandPolicyGuardTest.java diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/LettuceExceptionTranslatorTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/LettuceExceptionTranslatorTest.java similarity index 100% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/LettuceExceptionTranslatorTest.java rename to src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/LettuceExceptionTranslatorTest.java diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/ObservationIsolationTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/ObservationIsolationTest.java similarity index 100% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/ObservationIsolationTest.java rename to src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/ObservationIsolationTest.java diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/RedisCommandPolicyLoaderTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/RedisCommandPolicyLoaderTest.java similarity index 100% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/RedisCommandPolicyLoaderTest.java rename to src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/command/RedisCommandPolicyLoaderTest.java diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/SentinelFailoverObserverTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/SentinelFailoverObserverTest.java similarity index 100% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/SentinelFailoverObserverTest.java rename to src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/connection/SentinelFailoverObserverTest.java diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/observability/RedisObservationTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/observability/RedisObservationTest.java similarity index 100% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/observability/RedisObservationTest.java rename to src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/observability/RedisObservationTest.java diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/DeferringRedisCommandGateway.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/DeferringRedisCommandGateway.java similarity index 100% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/DeferringRedisCommandGateway.java rename to src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/DeferringRedisCommandGateway.java diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/InMemoryRedisPubSubGateway.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/InMemoryRedisPubSubGateway.java similarity index 100% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/InMemoryRedisPubSubGateway.java rename to src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/InMemoryRedisPubSubGateway.java diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LiveRedisClusterTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LiveRedisClusterTest.java similarity index 100% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LiveRedisClusterTest.java rename to src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LiveRedisClusterTest.java diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LiveRedisGuardrailTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LiveRedisGuardrailTest.java similarity index 100% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LiveRedisGuardrailTest.java rename to src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LiveRedisGuardrailTest.java diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LiveRedisOperationsFixture.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LiveRedisOperationsFixture.java similarity index 100% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LiveRedisOperationsFixture.java rename to src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LiveRedisOperationsFixture.java diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LiveRedisSentinelPromotionTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LiveRedisSentinelPromotionTest.java similarity index 100% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LiveRedisSentinelPromotionTest.java rename to src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/LiveRedisSentinelPromotionTest.java diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisAdminPlaneContractTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisAdminPlaneContractTest.java similarity index 100% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisAdminPlaneContractTest.java rename to src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisAdminPlaneContractTest.java diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisBatchOperationsContractTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisBatchOperationsContractTest.java similarity index 100% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisBatchOperationsContractTest.java rename to src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisBatchOperationsContractTest.java diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisBitmapGeoOperationsContractTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisBitmapGeoOperationsContractTest.java similarity index 100% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisBitmapGeoOperationsContractTest.java rename to src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisBitmapGeoOperationsContractTest.java diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisExtensionModulesContractTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisExtensionModulesContractTest.java similarity index 100% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisExtensionModulesContractTest.java rename to src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisExtensionModulesContractTest.java diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisFunctionOperationsContractTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisFunctionOperationsContractTest.java similarity index 100% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisFunctionOperationsContractTest.java rename to src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisFunctionOperationsContractTest.java diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisHashFieldExpirationContractTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisHashFieldExpirationContractTest.java similarity index 100% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisHashFieldExpirationContractTest.java rename to src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisHashFieldExpirationContractTest.java diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisHashOperationsContractTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisHashOperationsContractTest.java similarity index 100% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisHashOperationsContractTest.java rename to src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisHashOperationsContractTest.java diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisKeyOperationsContractTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisKeyOperationsContractTest.java similarity index 100% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisKeyOperationsContractTest.java rename to src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisKeyOperationsContractTest.java diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisListOperationsContractTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisListOperationsContractTest.java similarity index 100% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisListOperationsContractTest.java rename to src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisListOperationsContractTest.java diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisOperationsFixture.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisOperationsFixture.java similarity index 100% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisOperationsFixture.java rename to src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisOperationsFixture.java diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisPubSubOperationsContractTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisPubSubOperationsContractTest.java similarity index 100% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisPubSubOperationsContractTest.java rename to src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisPubSubOperationsContractTest.java diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisRawGatewayContractTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisRawGatewayContractTest.java similarity index 100% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisRawGatewayContractTest.java rename to src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisRawGatewayContractTest.java diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisScriptOperationsContractTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisScriptOperationsContractTest.java similarity index 100% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisScriptOperationsContractTest.java rename to src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisScriptOperationsContractTest.java diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisSetOperationsContractTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisSetOperationsContractTest.java similarity index 100% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisSetOperationsContractTest.java rename to src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisSetOperationsContractTest.java diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisSortedSetOperationsContractTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisSortedSetOperationsContractTest.java similarity index 100% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisSortedSetOperationsContractTest.java rename to src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisSortedSetOperationsContractTest.java diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisStreamDeletionCapabilityTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisStreamDeletionCapabilityTest.java similarity index 100% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisStreamDeletionCapabilityTest.java rename to src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisStreamDeletionCapabilityTest.java diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisStreamOperationsContractTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisStreamOperationsContractTest.java similarity index 100% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisStreamOperationsContractTest.java rename to src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisStreamOperationsContractTest.java diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisTransactionContractTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisTransactionContractTest.java similarity index 100% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisTransactionContractTest.java rename to src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisTransactionContractTest.java diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisTransactionSlotContractTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisTransactionSlotContractTest.java similarity index 100% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisTransactionSlotContractTest.java rename to src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisTransactionSlotContractTest.java diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisValueOperationsContractTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisValueOperationsContractTest.java similarity index 100% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisValueOperationsContractTest.java rename to src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/lettuce/operations/RedisValueOperationsContractTest.java diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/programmability/LiveRedisClusterTransactionTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/programmability/LiveRedisClusterTransactionTest.java similarity index 99% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/programmability/LiveRedisClusterTransactionTest.java rename to src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/programmability/LiveRedisClusterTransactionTest.java index 2ee57123..93a40acd 100644 --- a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/programmability/LiveRedisClusterTransactionTest.java +++ b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/programmability/LiveRedisClusterTransactionTest.java @@ -105,6 +105,7 @@ class LiveRedisClusterTransactionTest { }) .create(), limits, + Duration.ofSeconds(2), Duration.ofSeconds(2)); ConfiguredRedisPolicyAuthority authority = diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/raw/RawMovableKeysTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/raw/RawMovableKeysTest.java similarity index 100% rename from src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/raw/RawMovableKeysTest.java rename to src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/raw/RawMovableKeysTest.java diff --git a/src/adapter/outbound/cache-redis/src/test/resources/redis-sdk/golden/order-summary-v1.json b/src/adapter/outbound/redis-sdk/src/test/resources/redis-sdk/golden/order-summary-v1.json similarity index 100% rename from src/adapter/outbound/cache-redis/src/test/resources/redis-sdk/golden/order-summary-v1.json rename to src/adapter/outbound/redis-sdk/src/test/resources/redis-sdk/golden/order-summary-v1.json diff --git a/src/adapter/outbound/support/README.md b/src/adapter/outbound/support/README.md index 4ec68146..0045c871 100644 --- a/src/adapter/outbound/support/README.md +++ b/src/adapter/outbound/support/README.md @@ -29,10 +29,67 @@ fail-open 이라 의존성 실패가 나도 use case 는 성공한 것이다 — MDC 에 correlation id 가 없으면 `null` 이 아니라 `"unknown"` 문자열을 반환해 로그 라인에 필드가 비지 않게 한다. MDC 키는 SSOT(`mdc-keys.yaml`)를 따른다. -## OutboundSupportConfig — 공유 `@Configuration` seam +## OutboundSupportConfig — 공유 auto-configuration seam `FailOpenDependencyLogger` 빈을 `@ConditionalOnMissingBean` 으로 무조건 등록하는 단일 -`@Configuration` 이다. 네 기술 모듈이 각자 로거 빈을 중복 등록하지 않고 이 모듈에만 의존하면 +`@AutoConfiguration` 이다(`META-INF/spring/...AutoConfiguration.imports`에 등록 — 합성 루트의 +component scan 없이 이 모듈이 있으면 등록된다). 네 기술 모듈이 각자 로거 빈을 중복 등록하지 않고 이 모듈에만 의존하면 와이어링되며, 포크는 같은 타입의 빈을 직접 등록해 오버라이드할 수 있다. 이 모듈 자체는 어떤 `@ConditionalOnProperty` 게이팅도 갖지 않는다 — 게이팅은 각 기술 모듈이 자신의 연동 client 단위로 소유한다. + +## startup — 시작 실패 계약과 모듈 기본 설정 (app-bootstrap에서 이동) + +capability 모듈이 합성 루트에 의존하지 않고 같은 방식으로 실패하고, 자기 설정을 가져오게 하려고 +`support.startup` 패키지로 옮겼다. 로거 이름(`dev.caskeleton.bootstrap.runtime.startup`, +`dev.caskeleton.bootstrap.runtime`)과 로그 필드는 그대로 둬서 운영 필터가 바뀌지 않는다. +logstash encoder·Logback은 `compileOnly`다: 애플리케이션의 로깅 스택(app-bootstrap이 둘 다 싣는다)이 +제공하고, 시작 실패를 던지는 모듈(persistence-jpa, cache-redis)은 encoder를 직접 선언한다. + +- `StartupOrder` — 모든 `EnvironmentPostProcessor`의 순서표. 모듈 기본 설정(`MODULE_DEFAULTS`)이 + config data 바로 뒤, 그다음 Redis·DB readiness 기여, 맨 끝에 검증기들이다. +- `ReadinessGroup` — readiness 그룹에 contributor를 붙이는 유일한 방법. +- `RuntimeWarnings` — 경고 두 종류(meter 기록 실패, 설정 대체)의 구조화 필드. +- `ModuleDefaultsEnvironmentPostProcessor` — 모듈이 `config/module-defaults/<모듈>.yml`에 둔 기본 + 설정을 가장 낮은 우선순위로 읽는다. 모듈을 고르면 설정이 따라오고 지우면 같이 사라진다. 이 모듈의 + `spring.factories`에 등록돼 있다. 규칙: 의존성 closure(`modules.json`)에 support가 있는 모듈은 + 전부 이 로더를 쓴다(yml만 두면 되고 코드 의존은 필요 없다). support에 닿지 않는 모듈 + (persistence-mongo, graphql)만 자기 activation EPP가 `config/<이름>.yml`을 읽는다. + +### 시작 실패 타입(StartupErrorCode / StartupPhase / StartupFailures / *Exception) +- **`StartupErrorCode` — 네 가지 시작 실패 원인을 (레지스트리 error code, 표준 프로세스 exit 코드, + `StartupPhase`)로 묶는다.** exit 78(env 누락/오류)과 70(마이그레이션 실패)은 sysexits 표준 + (`EX_CONFIG`, `EX_SOFTWARE`)과 정렬돼 외부적으로 방어 가능하다. 반면 exit 71(프로파일 불일치)과 + 72(필수 어댑터 비활성)는 ca-tmpl 내부 규약이다 — sysexits 의 `EX_OSERR`/`EX_OSFILE`이 이 의미와 + 맞지 않아, 외부 표준이 아니라 내부 룩업 테이블 값으로 정했다. exit 코드는 carrying 예외가 + `ExitCodeGenerator`를 구현하기 때문에만 JVM 종료 상태가 된다. +- **`StartupPhase` — 실패 원인을 운영자가 로그에서 구분할 수 있게 하는 `startup.phase` 필드다.** + 시작 실패는 요청이 아직 없으므로 HTTP 에러 응답에 절대 실리지 않는다. 따라서 구조화 로그의 + `startup.phase`가 `kubectl logs`/`describe`에서 네 가지 원인을 가려내는 유일한 계약이다. wire + 이름은 dash-case(`env-validation | migration | adapter-enablement | profile-check`)이며, MDC 키가 + 아니라 Logstash structured argument 로 방출되므로 snake_case MDC 키 레지스트리 규칙은 적용되지 + 않는다. +- **`StartupFailures` — 시작 실패를 던지는 단일 출처로, 예외 생성 *전에* 구조화 로그를 먼저 + 방출한다.** "throw 직전 각 validator 가 직접 logger 를 호출"하는 패턴을 중앙화해, 어떤 시작 가드도 + 원인/구분자 없는 실패를 던지지 못하게 한다. 로그는 `startup.phase` / `error.code` / + `error.category` 세 필드를 Logstash structured argument 로 싣고, cause 가 있으면 + `error.root_cause.class` / `error.root_cause.message` 요약 필드만 추가한다. 원본 cause 는 반환되는 + `StartupFailureException`에 보존하지만 SLF4J throwable 인자로 넘기지 않는다. 따라서 canonical + startup-failure 로그는 운영자가 분류할 수 있는 요약만 남기고 프레임워크/드라이버 stacktrace 를 + 출력하지 않는다. +- **`StartupFailureException` — 네 실패 원인의 베이스 타입이며 `ExitCodeGenerator`로 exit 코드를 JVM + 종료 상태로 만든다.** context refresh 가 실패하면 `SpringApplication`의 `SpringBootExceptionHandler` + (부팅 스레드의 uncaught-exception handler 로 설치됨)가 실패 예외에서 `getExitCode()`를 읽어 + `System.exit(code)`를 호출한다 — `main()` 수정이 필요 없다. `IllegalStateException`을 상속하는 + 이유는 과거 `StartupSafetyValidator`가 `IllegalStateException`을 던졌기 때문으로, 타입드 예외로 + 업그레이드한 뒤에도 소스/동작 호환을 유지하기 위함이다. +- **`StartupFailureExceptionReporter` / `StartupFailureSpringBootLogFilter` — Spring Boot 의 중복 + startup stacktrace 를 억제한다.** reporter 는 failure cause chain 에 `StartupFailureException`이 + 있을 때만 `true`를 반환해 Boot 의 generic `Application run failed` 출력을 "이미 보고됨"으로 + 처리한다. 이후 Boot 가 반쯤 초기화된 context 를 닫다가 `Unable to close ApplicationContext`를 다시 + 남길 수 있으므로, canonical startup-failure 로그가 이미 찍힌 프로세스에서는 해당 + `org.springframework.boot.SpringApplication` 중복 메시지만 logback turbo filter 가 차단한다. 일반 + startup failure 가 아닌 예외와 다른 logger/message 는 기존 Spring Boot 로그 경로를 유지한다. +- **`RequiredAdapterDisabledException`은 런타임-라이프사이클의 `ADAPTER_DISABLED`와 의도적으로 + 구분된다.** 이쪽은 *시작* 검증(필수 어댑터/조정 빈이 꺼져 있음)이고, 후자는 비활성 옵션 어댑터에 + 대한 *런타임* 호출이다. diff --git a/src/adapter/outbound/support/build.gradle b/src/adapter/outbound/support/build.gradle index 2e446250..a6eae57b 100644 --- a/src/adapter/outbound/support/build.gradle +++ b/src/adapter/outbound/support/build.gradle @@ -4,9 +4,28 @@ plugins { // Shared base for outbound integration adapters: correlation, fail-open dependency // logging, and the @Configuration seam. Depended on by messaging/cache/notification/httpclient. +// +// Also the startup contract every capability module fails through (`support.startup`): typed +// startup failures with their sysexits exit codes and structured log, the EnvironmentPostProcessor +// order, the readiness-group merge, and the loader for module-owned default settings. They moved +// here from app-bootstrap so a capability can own its startup checks without depending on the +// composition root. dependencies { implementation project(":application-core") implementation project(":shared-contract") implementation 'org.springframework.boot:spring-boot-autoconfigure' implementation 'org.slf4j:slf4j-api' + // StartupFailures and RuntimeWarnings write their fields with StructuredArguments, and + // StartupFailureLogState marks the Logback context the startup log filter reads. compileOnly, + // like Boot's optional dependencies: the application's logging stack is Logback plus the + // logstash encoder (app-bootstrap ships both), and a module that raises startup failures + // declares the encoder itself (persistence-jpa, cache-redis). Declaring them here would put them + // on the runtime graph of every outbound adapter that only wants the correlation helpers. + // ModuleDefaultsEnvironmentPostProcessor needs SnakeYAML, which spring-boot-starter provides. + compileOnly libs.logstash.logback.encoder + compileOnly 'ch.qos.logback:logback-core' + + testImplementation libs.logstash.logback.encoder + testImplementation 'ch.qos.logback:logback-classic' + testRuntimeOnly 'org.yaml:snakeyaml' } diff --git a/src/adapter/outbound/support/gradle.lockfile b/src/adapter/outbound/support/gradle.lockfile index 77fd02a7..af5daea7 100644 --- a/src/adapter/outbound/support/gradle.lockfile +++ b/src/adapter/outbound/support/gradle.lockfile @@ -3,8 +3,11 @@ # This file is expected to be part of source control. biz.aQute.bnd:biz.aQute.bnd.annotation:7.1.0=testCompileClasspath ch.qos.logback:logback-classic:1.5.38=testCompileClasspath,testRuntimeClasspath -ch.qos.logback:logback-core:1.5.38=testCompileClasspath,testRuntimeClasspath -com.fasterxml.jackson.core:jackson-annotations:2.21=testCompileClasspath,testRuntimeClasspath +ch.qos.logback:logback-core:1.5.38=compileClasspath,testCompileClasspath,testRuntimeClasspath +com.fasterxml.jackson.core:jackson-annotations:2.21=compileClasspath,testCompileClasspath,testRuntimeClasspath +com.fasterxml.jackson.core:jackson-core:2.21.5=compileClasspath,testCompileClasspath,testRuntimeClasspath +com.fasterxml.jackson.core:jackson-databind:2.21.5=compileClasspath,testCompileClasspath,testRuntimeClasspath +com.fasterxml.jackson:jackson-bom:2.21.5=compileClasspath,testCompileClasspath,testRuntimeClasspath com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,testAnnotationProcessor com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,testAnnotationProcessor com.github.spotbugs:spotbugs-annotations:4.10.2=spotbugs @@ -49,6 +52,7 @@ javax.inject:javax.inject:1=annotationProcessor,testAnnotationProcessor jaxen:jaxen:2.0.6=spotbugs net.bytebuddy:byte-buddy-agent:1.17.8=testCompileClasspath,testRuntimeClasspath net.bytebuddy:byte-buddy:1.17.8=testCompileClasspath,testRuntimeClasspath +net.logstash.logback:logstash-logback-encoder:8.0=compileClasspath,testCompileClasspath,testRuntimeClasspath net.minidev:accessors-smart:2.6.0=testCompileClasspath,testRuntimeClasspath net.minidev:json-smart:2.6.0=testCompileClasspath,testRuntimeClasspath net.sf.saxon:Saxon-HE:12.9=checkstyle,spotbugs diff --git a/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/OutboundSupportConfig.java b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/OutboundSupportConfig.java index 39da8d15..3a46a3cf 100644 --- a/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/OutboundSupportConfig.java +++ b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/OutboundSupportConfig.java @@ -1,15 +1,18 @@ package dev.caskeleton.adapter.outbound.support; +import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; /** * Unconditionally registers the shared log/error contract bean ({@link FailOpenDependencyLogger}) * used by every optional adapter — required regardless of which adapter is enabled. * {@code @ConditionalOnMissingBean} lets a fork override it. + * + *

An auto-configuration, so the bean arrives with this module rather than with a composition + * root's component scan. */ -@Configuration +@AutoConfiguration public class OutboundSupportConfig { @Bean diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/startup/MigrationFailedException.java b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/MigrationFailedException.java similarity index 89% rename from src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/startup/MigrationFailedException.java rename to src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/MigrationFailedException.java index f9c29111..4464f8fb 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/startup/MigrationFailedException.java +++ b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/MigrationFailedException.java @@ -1,4 +1,4 @@ -package dev.caskeleton.bootstrap.runtime.startup; +package dev.caskeleton.adapter.outbound.support.startup; /** * A Flyway forward-only migration failed during startup (MIGRATION_FAILED, exit 70 — sysexits diff --git a/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/ModuleDefaultsEnvironmentPostProcessor.java b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/ModuleDefaultsEnvironmentPostProcessor.java new file mode 100644 index 00000000..302842c0 --- /dev/null +++ b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/ModuleDefaultsEnvironmentPostProcessor.java @@ -0,0 +1,60 @@ +package dev.caskeleton.adapter.outbound.support.startup; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.util.Arrays; +import java.util.Comparator; +import org.springframework.boot.EnvironmentPostProcessor; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.env.YamlPropertySourceLoader; +import org.springframework.core.Ordered; +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.core.io.Resource; +import org.springframework.core.io.support.PathMatchingResourcePatternResolver; + +/** + * Loads the settings every capability module ships, so selecting a module brings its settings and + * removing it removes them. + * + *

A module puts one file under {@value #LOCATION}. The file used to sit in app-bootstrap behind + * a {@code spring.config.import} line, so an application that dropped the capability still carried + * its settings and a line naming it. + * + *

Added last, below every configuration file, profile and environment variable: these are + * defaults, and a deployment's own value always wins. The files map {@code APP_*} variables onto + * hyphenated property trees an environment variable cannot reach directly. Runs straight after + * config data ({@link StartupOrder#MODULE_DEFAULTS}) so the readiness contributions and startup + * validators that read a module's switch see the value the module ships. + */ +public final class ModuleDefaultsEnvironmentPostProcessor + implements EnvironmentPostProcessor, Ordered { + + /** Where a capability module puts the defaults it ships. */ + public static final String LOCATION = "classpath*:config/module-defaults/*.yml"; + + @Override + public void postProcessEnvironment( + ConfigurableEnvironment environment, SpringApplication application) { + try { + Resource[] defaults = + new PathMatchingResourcePatternResolver(application.getClassLoader()) + .getResources(LOCATION); + // Sorted so two modules that ever disagreed would disagree the same way on every host. + Arrays.sort(defaults, Comparator.comparing(Resource::getFilename)); + YamlPropertySourceLoader loader = new YamlPropertySourceLoader(); + for (Resource resource : defaults) { + loader + .load( + "module-defaults (config/module-defaults/" + resource.getFilename() + ")", resource) + .forEach(environment.getPropertySources()::addLast); + } + } catch (IOException failure) { + throw new UncheckedIOException("failed to read " + LOCATION, failure); + } + } + + @Override + public int getOrder() { + return StartupOrder.MODULE_DEFAULTS; + } +} diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/startup/ProfileMismatchException.java b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/ProfileMismatchException.java similarity index 90% rename from src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/startup/ProfileMismatchException.java rename to src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/ProfileMismatchException.java index 3ddf1902..a15eeaf4 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/startup/ProfileMismatchException.java +++ b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/ProfileMismatchException.java @@ -1,4 +1,4 @@ -package dev.caskeleton.bootstrap.runtime.startup; +package dev.caskeleton.adapter.outbound.support.startup; /** * An active profile conflicts with an enabled prod-forbidden setting — e.g. a prod-unsafe toggle or diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/ReadinessGroup.java b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/ReadinessGroup.java similarity index 94% rename from src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/ReadinessGroup.java rename to src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/ReadinessGroup.java index 08f81472..fd596afa 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/ReadinessGroup.java +++ b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/ReadinessGroup.java @@ -1,4 +1,4 @@ -package dev.caskeleton.bootstrap.runtime; +package dev.caskeleton.adapter.outbound.support.startup; import java.util.Arrays; import java.util.LinkedHashSet; @@ -38,8 +38,7 @@ public final class ReadinessGroup { * themselves. * *

Contributions chain rather than race because the callers declare distinct orders in {@link - * dev.caskeleton.bootstrap.runtime.startup.StartupOrder}; each one reads what the previous - * contributed. + * StartupOrder}; each one reads what the previous contributed. * * @param environment the environment to contribute to * @param propertySourceName a name unique to the contributing capability, so the source is diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/startup/RequiredAdapterDisabledException.java b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/RequiredAdapterDisabledException.java similarity index 92% rename from src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/startup/RequiredAdapterDisabledException.java rename to src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/RequiredAdapterDisabledException.java index 8e9872a8..52eee7f2 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/startup/RequiredAdapterDisabledException.java +++ b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/RequiredAdapterDisabledException.java @@ -1,4 +1,4 @@ -package dev.caskeleton.bootstrap.runtime.startup; +package dev.caskeleton.adapter.outbound.support.startup; /** * A required capability adapter / coordination bean is disabled or absent at startup diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/RuntimeWarnings.java b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/RuntimeWarnings.java similarity index 98% rename from src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/RuntimeWarnings.java rename to src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/RuntimeWarnings.java index b02de0ea..9ad905fb 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/RuntimeWarnings.java +++ b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/RuntimeWarnings.java @@ -1,4 +1,4 @@ -package dev.caskeleton.bootstrap.runtime; +package dev.caskeleton.adapter.outbound.support.startup; import static net.logstash.logback.argument.StructuredArguments.kv; import static net.logstash.logback.argument.StructuredArguments.v; diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/startup/StartupErrorCode.java b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupErrorCode.java similarity index 95% rename from src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/startup/StartupErrorCode.java rename to src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupErrorCode.java index a21974ed..3a98e3bb 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/startup/StartupErrorCode.java +++ b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupErrorCode.java @@ -1,4 +1,4 @@ -package dev.caskeleton.bootstrap.runtime.startup; +package dev.caskeleton.adapter.outbound.support.startup; /** * The four startup-failure causes. Each exit code becomes the JVM exit status only because the diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/startup/StartupFailureException.java b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupFailureException.java similarity index 94% rename from src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/startup/StartupFailureException.java rename to src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupFailureException.java index 59659e67..50cd9640 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/startup/StartupFailureException.java +++ b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupFailureException.java @@ -1,4 +1,4 @@ -package dev.caskeleton.bootstrap.runtime.startup; +package dev.caskeleton.adapter.outbound.support.startup; import org.springframework.boot.ExitCodeGenerator; diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/startup/StartupFailureLogState.java b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupFailureLogState.java similarity index 95% rename from src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/startup/StartupFailureLogState.java rename to src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupFailureLogState.java index b1104141..3f142ca0 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/startup/StartupFailureLogState.java +++ b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupFailureLogState.java @@ -1,4 +1,4 @@ -package dev.caskeleton.bootstrap.runtime.startup; +package dev.caskeleton.adapter.outbound.support.startup; import ch.qos.logback.core.Context; import java.util.Objects; diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/startup/StartupFailures.java b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupFailures.java similarity index 95% rename from src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/startup/StartupFailures.java rename to src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupFailures.java index d9869e89..cf4e1a69 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/startup/StartupFailures.java +++ b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupFailures.java @@ -1,4 +1,4 @@ -package dev.caskeleton.bootstrap.runtime.startup; +package dev.caskeleton.adapter.outbound.support.startup; import static net.logstash.logback.argument.StructuredArguments.kv; @@ -49,7 +49,7 @@ public final class StartupFailures { } /** Emits the structured startup-failure log. {@code cause} may be {@code null}. */ - static void emit(StartupErrorCode code, String detail, Throwable cause) { + public static void emit(StartupErrorCode code, String detail, Throwable cause) { StartupFailureLogState.markStartupFailureReported(); if (cause == null) { log.error( diff --git a/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupOrder.java b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupOrder.java new file mode 100644 index 00000000..2babe663 --- /dev/null +++ b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupOrder.java @@ -0,0 +1,57 @@ +package dev.caskeleton.adapter.outbound.support.startup; + +import org.springframework.boot.context.config.ConfigDataEnvironmentPostProcessor; +import org.springframework.core.Ordered; + +/** + * The order every {@code EnvironmentPostProcessor} of this application runs in, in one place. + * + *

It lives in the support leaf rather than in the composition root because capability modules + * register post-processors of their own — the module defaults loader and the Redis and database + * readiness contributions — and they have to take a position in the same sequence without depending + * on the composition root. + * + *

The relative order of the registered post-processors is part of how they work, and several of + * them once returned the same value or declared none at all (BOOT-005). The sequence then held only + * because Spring sorts stably and {@code spring.factories} happened to list them in the intended + * order: reordering lines in a text file would have silently changed behaviour, and nothing would + * have failed. + * + *

Two bands, and why

+ * + *

The readiness post-processors contribute property sources and run immediately after config + * data, so they are expressed relative to {@link ConfigDataEnvironmentPostProcessor#ORDER}. The + * validators must observe the environment the application will actually run with — every + * contributed source included — so they stay at the {@code LOWEST_PRECEDENCE} end and are separated + * from each other by single steps. Keeping the last of them at exactly {@code LOWEST_PRECEDENCE} + * preserves this repository's existing position relative to any third-party post-processor at that + * value, so this change makes an undefined order deterministic without moving the whole band. + */ +public final class StartupOrder { + + private StartupOrder() {} + + /** + * Module-owned defaults ({@link ModuleDefaultsEnvironmentPostProcessor}) — a property source, + * immediately after config data, so every rule after it reads the switches a module ships. + */ + public static final int MODULE_DEFAULTS = ConfigDataEnvironmentPostProcessor.ORDER + 1; + + /** Redis readiness group contribution — a property source, after the module defaults. */ + public static final int READINESS_REDIS = ConfigDataEnvironmentPostProcessor.ORDER + 2; + + /** Database readiness group contribution — a property source, after the module defaults. */ + public static final int READINESS_DATABASE = ConfigDataEnvironmentPostProcessor.ORDER + 3; + + /** + * Runtime environment profile rule. The fail-closed validator: which environment this is decides + * which configuration is even legal, so it runs before anything defaults a value. + */ + public static final int RUNTIME_ENVIRONMENT_PROFILE = Ordered.LOWEST_PRECEDENCE - 1; + + /** + * Tracing sample-rate defaulting. Runs after every rule that can refuse the boot outright — there + * is no value in defaulting a sample rate for a process that is about to exit. + */ + public static final int TRACING_SAMPLING = Ordered.LOWEST_PRECEDENCE; +} diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/startup/StartupPhase.java b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupPhase.java similarity index 94% rename from src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/startup/StartupPhase.java rename to src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupPhase.java index fd9fa9d1..8bd2a724 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/startup/StartupPhase.java +++ b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupPhase.java @@ -1,4 +1,4 @@ -package dev.caskeleton.bootstrap.runtime.startup; +package dev.caskeleton.adapter.outbound.support.startup; /** * The startup lifecycle phase a fail-fast guard belongs to, written to the {@code startup.phase} diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/startup/StartupValidationContext.java b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupValidationContext.java similarity index 99% rename from src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/startup/StartupValidationContext.java rename to src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupValidationContext.java index db917fab..277953c9 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/startup/StartupValidationContext.java +++ b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupValidationContext.java @@ -1,4 +1,4 @@ -package dev.caskeleton.bootstrap.runtime.startup; +package dev.caskeleton.adapter.outbound.support.startup; import java.util.ArrayList; import java.util.List; diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/startup/StartupValidationException.java b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupValidationException.java similarity index 95% rename from src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/startup/StartupValidationException.java rename to src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupValidationException.java index 91bad398..f6433609 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/startup/StartupValidationException.java +++ b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupValidationException.java @@ -1,4 +1,4 @@ -package dev.caskeleton.bootstrap.runtime.startup; +package dev.caskeleton.adapter.outbound.support.startup; /** * A required environment / configuration value is missing or malformed (STARTUP_VALIDATION_FAILED, diff --git a/src/adapter/outbound/support/src/main/resources/META-INF/spring.factories b/src/adapter/outbound/support/src/main/resources/META-INF/spring.factories new file mode 100644 index 00000000..3d4136a8 --- /dev/null +++ b/src/adapter/outbound/support/src/main/resources/META-INF/spring.factories @@ -0,0 +1,2 @@ +org.springframework.boot.EnvironmentPostProcessor=\ +dev.caskeleton.adapter.outbound.support.startup.ModuleDefaultsEnvironmentPostProcessor diff --git a/src/adapter/outbound/support/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/src/adapter/outbound/support/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports new file mode 100644 index 00000000..5c1c7343 --- /dev/null +++ b/src/adapter/outbound/support/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports @@ -0,0 +1 @@ +dev.caskeleton.adapter.outbound.support.OutboundSupportConfig diff --git a/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/OutboundSupportConfigTest.java b/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/OutboundSupportConfigTest.java new file mode 100644 index 00000000..c696940f --- /dev/null +++ b/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/OutboundSupportConfigTest.java @@ -0,0 +1,26 @@ +package dev.caskeleton.adapter.outbound.support; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.autoconfigure.AutoConfiguration; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.context.annotation.ImportCandidates; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; + +/** The shared logger arrives with this module, not with a composition root's component scan. */ +class OutboundSupportConfigTest { + + @Test + void theModuleRegistersItsAutoConfiguration() { + assertThat(ImportCandidates.load(AutoConfiguration.class, getClass().getClassLoader())) + .contains(OutboundSupportConfig.class.getName()); + } + + @Test + void theAutoConfigurationProvidesTheFailOpenDependencyLogger() { + new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(OutboundSupportConfig.class)) + .run(context -> assertThat(context).hasSingleBean(FailOpenDependencyLogger.class)); + } +} diff --git a/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/startup/ModuleDefaultsEnvironmentPostProcessorTest.java b/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/startup/ModuleDefaultsEnvironmentPostProcessorTest.java new file mode 100644 index 00000000..543ef4c5 --- /dev/null +++ b/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/startup/ModuleDefaultsEnvironmentPostProcessorTest.java @@ -0,0 +1,44 @@ +package dev.caskeleton.adapter.outbound.support.startup; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.springframework.boot.SpringApplication; +import org.springframework.core.env.MapPropertySource; +import org.springframework.core.env.StandardEnvironment; + +/** A module's shipped file is found by location, and a deployment's value always beats it. */ +class ModuleDefaultsEnvironmentPostProcessorTest { + + @Test + void aModuleFileUnderTheLocationIsLoaded() { + StandardEnvironment environment = processed(Map.of()); + + assertThat(environment.getProperty("support-test.shipped")).isEqualTo("shipped-default"); + } + + @Test + void theShippedPlaceholderStillResolvesAgainstTheDeployment() { + StandardEnvironment environment = processed(Map.of("SUPPORT_TEST_SHIPPED", "from-env")); + + assertThat(environment.getProperty("support-test.shipped")).isEqualTo("from-env"); + } + + @Test + void aDeploymentValueOutranksTheShippedDefault() { + StandardEnvironment environment = processed(Map.of("support-test.overridden", "deployment")); + + assertThat(environment.getProperty("support-test.overridden")).isEqualTo("deployment"); + assertThat(environment.getPropertySources().stream().toList().getLast().getName()) + .startsWith("module-defaults"); + } + + private static StandardEnvironment processed(Map deployment) { + StandardEnvironment environment = new StandardEnvironment(); + environment.getPropertySources().addFirst(new MapPropertySource("deployment", deployment)); + new ModuleDefaultsEnvironmentPostProcessor() + .postProcessEnvironment(environment, new SpringApplication()); + return environment; + } +} diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/startup/StartupErrorCodeTest.java b/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/startup/StartupErrorCodeTest.java similarity index 97% rename from src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/startup/StartupErrorCodeTest.java rename to src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/startup/StartupErrorCodeTest.java index f1cdbf61..5d012c77 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/startup/StartupErrorCodeTest.java +++ b/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/startup/StartupErrorCodeTest.java @@ -1,4 +1,4 @@ -package dev.caskeleton.bootstrap.runtime.startup; +package dev.caskeleton.adapter.outbound.support.startup; import static org.assertj.core.api.Assertions.assertThat; diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/startup/StartupFailureExceptionTest.java b/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/startup/StartupFailureExceptionTest.java similarity index 97% rename from src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/startup/StartupFailureExceptionTest.java rename to src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/startup/StartupFailureExceptionTest.java index f2934043..e7af1f9c 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/startup/StartupFailureExceptionTest.java +++ b/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/startup/StartupFailureExceptionTest.java @@ -1,4 +1,4 @@ -package dev.caskeleton.bootstrap.runtime.startup; +package dev.caskeleton.adapter.outbound.support.startup; import static org.assertj.core.api.Assertions.assertThat; diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/startup/StartupFailuresTest.java b/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/startup/StartupFailuresTest.java similarity index 98% rename from src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/startup/StartupFailuresTest.java rename to src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/startup/StartupFailuresTest.java index d503e436..ff862999 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/startup/StartupFailuresTest.java +++ b/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/startup/StartupFailuresTest.java @@ -1,4 +1,4 @@ -package dev.caskeleton.bootstrap.runtime.startup; +package dev.caskeleton.adapter.outbound.support.startup; import static org.assertj.core.api.Assertions.assertThat; diff --git a/src/adapter/outbound/support/src/test/resources/config/module-defaults/support-test.yml b/src/adapter/outbound/support/src/test/resources/config/module-defaults/support-test.yml new file mode 100644 index 00000000..cd868eb1 --- /dev/null +++ b/src/adapter/outbound/support/src/test/resources/config/module-defaults/support-test.yml @@ -0,0 +1,3 @@ +support-test: + shipped: ${SUPPORT_TEST_SHIPPED:shipped-default} + overridden: shipped-default diff --git a/src/app-bootstrap/CLAUDE.md b/src/app-bootstrap/CLAUDE.md index 14912f03..b48d3d08 100644 --- a/src/app-bootstrap/CLAUDE.md +++ b/src/app-bootstrap/CLAUDE.md @@ -32,10 +32,10 @@ Package root: `dev.caskeleton.bootstrap`. - Settings classes that implement business logic. - Implementing an `application-core` or `domain-core` port. A class that implements one is an outbound adapter and belongs in an `adapter/outbound/*` leaf, however its dependencies are - configured — `CompositionRootBoundaryArchitectureTest` enforces this and holds the one documented - exception. + configured — `CompositionRootBoundaryArchitectureTest` enforces this, with no exceptions. - Raising a startup failure with `throw new IllegalStateException(...)`. Use `StartupFailures` - (`envValidation` / `profileMismatch` / `requiredAdapterDisabled` / `migrationFailed`), so the + (`adapter:outbound:support`, package `support.startup`: `envValidation` / `profileMismatch` / + `requiredAdapterDisabled` / `migrationFailed`), so the failure carries its sysexits exit code and structured log fields — `StartupFailureContractArchitectureTest` enforces this. - Answering "is this production?" locally. `dev.caskeleton.shared.runtime.RuntimeEnvironment` owns @@ -52,19 +52,31 @@ between a `settings/` package and their feature packages with no stated rule; an decomposition problem was solved two different ways in the same leaf — Notification as nine focused configurations, Redis as one 376-line class. -- **A capability's assembly lives in `autoconfigure//`.** Everything a deployment can - switch on is a capability: `fileserver`, `httpclient`, `jpa`, `redis`, `notification`, `mongo`, - `outbox`, `tracing`, `idempotency`, `lock`, `messaging`. +- **A capability's assembly lives in the capability's own module**, registered by that module's + `AutoConfiguration.imports`, with its settings in the module's `config/module-defaults/*.yml`. + JPA (startup guards, Flyway strategy, lock decorator, readiness and full-off handling in + `JpaActivationEnvironmentPostProcessor`) is `adapter:outbound:persistence-jpa`; Redis (readiness) is + `adapter:outbound:cache-redis`; notification is `composition:notification-platform`. Every + capability is a commented `runtimeOnly` line in `build.gradle`; the default composition is web, + observability, the cores, support and identifier. This leaf keeps no list of capabilities: no + switch registry, no cross-capability dependency validator, no activation endpoint. Component scan + covers `dev.caskeleton.bootstrap` only; web (`WebAdapterAutoConfiguration`) and support + (`OutboundSupportConfig`) arrive through their own `AutoConfiguration.imports`. What stays in `autoconfigure//` is application + composition over application-core ports that names no module type: `outbox` (the relay use case + and its scheduler, on only when the store and publisher ports exist), `idempotency` (the one + executor over whichever store is selected), `tracing`, `common`. - **`Settings` lives beside its capability**, not in `settings/`. The `settings/` package holds only settings that belong to no capability — `BootstrapSettings`, `LoggingSettings`, `PrivacySettings`, `RuntimeSafetySettings`. -- **`runtime/` holds guards that run whatever is switched on.** Subject matter does not decide - ownership: `JpaSchemaSafetyValidator` reads JPA properties but runs when JPA is off, which is the - whole point of it, so it is a runtime guard and not part of the JPA capability. Moving guards like - it into `autoconfigure/jpa/` made `FiveAdapterOffInventoryTest` fail — correctly, because that test - asserts a switched-off capability owns no beans, and the package is how it classifies them. -- **`runtime/startup/` holds the startup failure vocabulary** — phases, error codes, exceptions, the - `StartupFailures` factory, `StartupValidationContext`, and `StartupOrder`. +- **`runtime/` holds guards about the application itself** — secrets, numeric bounds, error-detail + exposure, multi-instance coordination, the runtime-profile check (`RuntimeEnvironmentProfileValidator`). + A guard about a capability's settings (the JPA OSIV/DDL/pool/TLS/vendor guards, the Mongo + connection-source rule, the GraphQL deployment-mode rule) ships with that capability's module, so + it exists exactly when the capability does. +- **The startup failure vocabulary lives in `adapter:outbound:support`** (`support.startup`: phases, + error codes, exceptions, `StartupFailures`, `StartupValidationContext`, `StartupOrder`, + `ReadinessGroup`, `RuntimeWarnings`), so capability modules fail the same way without depending on + this leaf. `runtime/startup/` keeps only `StartupFailureExceptionReporter`. ## Decomposition threshold @@ -74,19 +86,20 @@ different answers for the same question. - One `@Configuration` holds one assembly concern. Split when it passes roughly **eight `@Bean` methods**, or as soon as it assembles two unrelated port families — whichever comes first. - One `@ConfigurationProperties` class owns one capability namespace. -- A capability that needs more than one configuration gets a root class holding the master switch, - `@EnableConfigurationProperties`, and an `@Import` of the per-concern classes. Scan nothing: - `@Import` from a gated root is what keeps the master switch load-bearing rather than advisory. - `autoconfigure/redis/RedisCapabilityConfig` is the bootstrap-owned example. Optional adapter +- A capability that needs more than one configuration gets a root class holding its `enabled` + condition, `@EnableConfigurationProperties`, and an `@Import` of the per-concern classes. Scan + nothing: `@Import` from a gated root is what keeps `enabled=false` load-bearing rather than advisory. + `cache-redis`'s `capability/RedisCapabilityConfig` is the reference example. Optional adapter capabilities that own reusable Spring composition publish their own root instead. Notification - uses `adapter:outbound:notification`'s `NotificationPlatformAutoConfiguration`; JPA uses the - package-private `PersistenceJpaAutoConfiguration` plus `PersistenceJpaRuntimeConfig` from - `adapter:outbound:persistence-jpa`. `autoconfigure/jpa/` therefore contains only application - startup/deployment policy layered over that leaf runtime — migration sequencing, resolved - datasource validation, OSIV/DDL safety, and the management view. + uses `adapter:outbound:notification`'s `NotificationPlatformAutoConfiguration` plus + `composition:notification-platform`'s `NotificationApplicationCompositionAutoConfiguration`; JPA uses the + package-private `PersistenceJpaAutoConfiguration`, `PersistenceJpaRuntimeConfig` and + `startup.JpaStartupAutoConfiguration` from `adapter:outbound:persistence-jpa`, which is not in the + default composition (`// runtimeOnly project(':adapter:outbound:persistence-jpa')` in + `build.gradle`). Mongo follows the same rule: the persistence-mongo leaf owns MongoRootAutoConfiguration and its internal health bridge; bootstrap owns no Mongo-specific production health configuration. - Shared helpers of a split capability get their own type named for what they are, not a `*Util` - bucket — `autoconfigure/redis/RedisKeys` is the reference. + bucket — `cache-redis`'s `capability/RedisKeys` is the reference. ## Test diff --git a/src/app-bootstrap/README.md b/src/app-bootstrap/README.md index 5f40e57d..cb6bd1cd 100644 --- a/src/app-bootstrap/README.md +++ b/src/app-bootstrap/README.md @@ -4,19 +4,33 @@ 이 모듈은 비즈니스 로직을 담지 않는다. Spring Boot 기동, 런타임 설정 바인딩, 기본 runtime 모듈 간 최종 와이어링, 그리고 composition classpath를 대상으로 한 중앙 아키텍처 테스트만 둔다. -19개 leaf 전체의 프로젝트 edge와 두 composition root의 실제 runtime membership은 JSON registry를 -읽는 Gradle gate가 별도로 검사한다. 허용/금지 의존, 책임 범위, 테스트 명령 같은 **모듈 규칙**의 +모든 leaf의 프로젝트 edge는 JSON registry를 읽는 Gradle 방향 게이트가 별도로 검사한다. 허용/금지 의존, 책임 범위, 테스트 명령 같은 **모듈 규칙**의 SSOT 는 [CLAUDE.md](CLAUDE.md) 다. -기본 composition의 SSOT는 `build.gradle`의 실제 project dependency graph다. architecture registry는 -같은 runtime membership 목록을 다시 저장하지 않는다. `verifyRuntimeModuleRegistry`가 resolved -`runtimeClasspath`에 registry 밖 project가 침투하지 않았는지만 검증한다. +기본 composition의 SSOT는 `build.gradle`의 실제 project dependency graph다. registry는 runtime +membership 목록을 두지 않는다. `allowed_dependencies` 밖의 project는 방향 게이트가 막는다. `conditionalTransportBuildContractTest`는 GraphQL/gRPC/WebSocket 세 leaf를 test-only classpath에서 함께 resolve하는 -qualification composition이다. 현재 GraphQL은 app-bootstrap의 실제 dependency이고 master switch로 -활성화되며, gRPC/WebSocket은 production dependency가 아니다. optional leaf를 실제 app에 채택하려면 -`app-bootstrap/build.gradle`의 dependency, architecture의 `allowed_dependencies`, typed settings/보안 -경계/검증을 같은 변경에서 갱신한다. +qualification composition이다. 세 leaf 모두 기본 조립에는 없다. + +### 기능 추가 = 한 줄 + env + +기본 조립(`bootJar`)은 web, 관측, `domain-core`·`application-core`·`shared-contract`, support, +identifier뿐이다. 나머지 capability(JPA, Redis, Kafka, Mongo, GraphQL, HTTP client, object storage, +WebSocket, gRPC, 파일 서버, 알림)는 `build.gradle`에 주석 처리된 `runtimeOnly project(...)` 한 줄씩으로 +있다. 주석을 풀면 그 모듈이 자기 `AutoConfiguration.imports`와 설정 기본값으로 켜지고, 줄을 지우면 함께 +사라진다. 있는 모듈은 자기 `enabled` 키(기본 `true`)를 `false`로 줄 때만 꺼진다. 합성 루트는 capability +목록을 따로 들고 있지 않다(스위치 목록, scan 제외 정규식, 의존 검사기 없음). component scan은 +`dev.caskeleton.bootstrap`만 보고, web(`WebAdapterAutoConfiguration`)과 support(`OutboundSupportConfig`)도 +자기 auto-configuration으로 들어온다. + +- 줄마다 필요한 env와 끄는 키: [src/README.md](../README.md)의 "기능 추가 = 한 줄 + env" 표. +- 줄을 바꾼 뒤: `./gradlew :app-bootstrap:resolveAndLockAll --write-locks`로 strict lock을 갱신한다. +- `./gradlew :app-bootstrap:qualificationBootJar`는 main runtime에 모든 capability를 더한 jar를 만든다. + compose 레인과 CI용이고, 배포 artifact는 `bootJar`다. +- `build.gradle`의 `capabilityProjects` 목록이 capability 전체를 한 번 적는다. 전체 저장소 ArchUnit + import(`architectureTest`)와 qualification jar가 이 목록을 읽고, 운영 runtimeClasspath에는 고른 줄만 + 들어간다. 새 capability leaf는 이 목록과 주석 한 줄, 두 곳에 추가한다. 이 문서는 코드 주석에서 덜어낸 **설계 결정의 근거**를 모아둔 참조용 기록이다 — 코드를 읽다 "왜 이렇게 했나"가 궁금할 때 본다. 본문은 한국어로 쓰고, 클래스·Spring API·메트릭 이름처럼 @@ -29,8 +43,7 @@ qualification composition이다. 현재 GraphQL은 app-bootstrap의 실제 depen - [runtime — 시크릿 소스 선택과 런타임 안전 가드](#runtime--시크릿-소스-선택과-런타임-안전-가드) - [concurrency — 도메인 컨텍스트 전파](#concurrency--도메인-컨텍스트-전파-전략-조립) - [async — 비동기 executor 컨텍스트 전파와 포화 처리](#async--비동기-executor-컨텍스트-전파와-포화-처리) -- [idempotency — 멱등성 런타임 조립과 TTL 상한](#idempotency--멱등성-런타임-조립과-ttl-상한) -- [lock — 분산 락 메트릭 데코레이터](#lock--분산-락-메트릭-데코레이터-배선) +- [idempotency — 멱등성 provider 선택과 executor 조립](#idempotency--멱등성-provider-선택과-executor-조립) - [outbox — 트랜잭셔널 아웃박스 릴레이](#outbox--트랜잭셔널-아웃박스-릴레이-와이어링) - [logging — 로그 시크릿 마스킹·샘플링·가명화](#logging--로그-시크릿-마스킹샘플링가명화) - [metrics — 메트릭 계약 MeterFilter](#metrics--메트릭-계약-meterfilter-설치) @@ -55,97 +68,15 @@ Redis session mode는 반대로 `jwtDecoder`를 거부하고 `redisVersionedSess Spring Session/Redis 구현 타입을 직접 의존하지 않으며, composition 누락과 이중 활성화를 context refresh 완료 전에 실패시킨다. -### FlywayProdSafetyValidator -- **`prod` 프로파일에서 Flyway 안전장치가 꺼지지 못하도록 런타임에서 강제한다.** Flyway 옵션은 - `application.yml`에 안전값으로 고정돼 있지만(`baseline-on-migrate=false`, `out-of-order=false`, - `clean-disabled=true`), 환경별 override 가 프로덕션에서 이 값을 조용히 되돌릴 수 있다. 이 검증기는 - 그런 override 를 시작 시점에 잡아 `PROFILE_MISMATCH`(exit 71)로 부팅을 막는다. -- **금지하는 옵션은 각각 "복구 불가능한 위험" 때문이다.** `baseline-on-migrate=true`는 누락된 - 마이그레이션을 감지하는 안전망을 없애고, `out-of-order=true`는 개발자 간 마이그레이션 적용 순서 - 일관성을 깨며, `clean-disabled=false`는 스키마 전체를 드롭하는 파괴적 `clean` 명령을 다시 - 활성화한다. -- **프로파일 비교는 대소문자를 무시한다.** `SPRING_PROFILES_ACTIVE=PROD`처럼 대문자 오타가 나도 - 가드가 우회되지 않게 하기 위함이다. -- **Flyway repair 는 가드 대상이 아니다.** repair 는 property 가 아니라 Flyway 명령이고 스켈레톤은 - repair 호출 경로 자체를 배선하지 않으므로, "prod 에서 repair 금지"는 런타임 트리거가 없는 - 문서화된 정책으로 남는다. 부분 스키마 복구는 in-prod Flyway repair 가 아니라 - runbook(`runbook://migration/manual-recovery`)을 통한 수동 복구로 가도록 실패 메시지에 명시한다. - (프로젝트가 repair 경로를 추가한다면 동일하게 prod 게이트 + non-prod 감사 로그를 걸어야 한다.) - -### RequiredEnvironmentValidator -- **datasource 연결 환경변수를 마이그레이션 실행 전에 검증해 부팅을 빨리 실패시킨다.** Flyway - forward-only 마이그레이션은 context refresh 동안 애플리케이션 datasource 에 대해 실행된다. 연결 - 환경변수가 빠져 있으면 마이그레이션은 시작 단계 구분자 없이 불투명한 driver/connection 에러로 - 한참 뒤에야 실패한다. 이 검증기는 그것을 명시적인 env 검증 실패(`STARTUP_VALIDATION_FAILED`, - exit 78)로 바꿔, 누락된 운영자용 env 키를 전부 이름으로 짚어준다. -- **검증 범위를 datasource 3종(url/username/driver)으로 의도적으로 좁혔다.** 이것들이 이 브랜치가 - 소유하는 마이그레이션 전제조건이기 때문이다. app-name(`BootstrapSettings`), issuer-uri(security - settings) 등 다른 필수값은 각 모듈의 가드가 책임지므로 여기서 중복 검증하지 않는다. -- **값이 없거나(blank) 공백이면 모두 "누락"으로 본다.** spring-dotenv 에서 미설정 placeholder - `${...}`가 빈 문자열로 해석되기 때문에, null 뿐 아니라 blank 도 누락으로 처리해야 빈틈이 없다. -- **메시지는 env 키 이름순으로 정렬해 출력한다.** Map 순회 순서와 무관하게 결정적이고 안정적인 실패 - 메시지를 보장하기 위함이다. - -### MigrationStartupConfig -- **시작 마이그레이션 가드와 Flyway 마이그레이션 전략을 한곳에 모아 소유권을 명확히 한다.** prod - 토글 / 멀티 인스턴스 가드는 env-driven `RuntimeSafetyConfig`가 소유하고, 이 config 는 마이그레이션 - 관련 가드만 배선한다. -- **`migrationStartupRunner` 빈 이름은 반드시 유지해야 한다.** 멀티 인스턴스 모드 - (`APP_MULTI_INSTANCE_ENABLED=true`)에서 `StartupSafetyValidator`가 이 정확한 이름의 빈 존재를 - 단언하기 때문이다. 동시에 이 빈은 `FlywayMigrationStrategy`로서 Spring Boot Flyway - 오토컨피규레이션이 `migrate()`를 위임하는 전략이 된다. - -### MigrationStartupRunner -- **`FlywayMigrationStrategy`로 등록해 context refresh 중에 마이그레이션을 직접 실행한다(오토컨피그 - 기본값을 그대로 두지 않는다).** refresh 안에서 실행한다는 것은 마이그레이션이 완료되거나 부팅을 - 실패시키는 일이 애플리케이션이 readiness 를 보고하기 *전에* 일어난다는 뜻이다. 따라서 절반만 - 마이그레이션된 스키마가 트래픽을 받는 일이 구조적으로 없다(actuator readiness probe 의 형태 - 자체는 health-lifecycle 브랜치가 소유하고, 여기서는 "마이그레이션 → ready" 순서만 책임진다). -- **`FlywayException`을 `MigrationFailedException`(exit 70)으로 번역한다.** 일반적이고 구분 안 되는 - 스택트레이스 대신 구조화된 `MIGRATION_FAILED` 로그와 표준 exit 코드를 남기기 위함이다. -- **멀티 인스턴스에서는 in-app 마이그레이션 + Flyway 자체 schema-history 락에 의존하는 것이 기본 - 전략이다.** 여러 레플리카의 동시 `migrate()`를 Flyway 의 락이 직렬화한다. 대안인 "in-app - 마이그레이션을 끄고 플랫폼 one-shot Job 으로 돌리기"는 "migration=Job"을 강제하는 공개 표준이 - 없는 배포 선택이라 스켈레톤 기본값이 아니다. Job 으로 돌리는 프로젝트는 이 빈의 `migrate()`를 - no-op 으로 만들면 된다. +관계형 기동 가드(`FlywayProdSafetyValidator`, `RequiredEnvironmentValidator`, 마이그레이션 전략 +`MigrationStartupRunner`)는 `adapter:outbound:persistence-jpa`로 옮겼다. 설계 근거는 그 모듈 +README의 "startup" 절에 있다. ### 시작 실패 타입(StartupErrorCode / StartupPhase / StartupFailures / *Exception) -- **`StartupErrorCode` — 네 가지 시작 실패 원인을 (레지스트리 error code, 표준 프로세스 exit 코드, - `StartupPhase`)로 묶는다.** exit 78(env 누락/오류)과 70(마이그레이션 실패)은 sysexits 표준 - (`EX_CONFIG`, `EX_SOFTWARE`)과 정렬돼 외부적으로 방어 가능하다. 반면 exit 71(프로파일 불일치)과 - 72(필수 어댑터 비활성)는 ca-tmpl 내부 규약이다 — sysexits 의 `EX_OSERR`/`EX_OSFILE`이 이 의미와 - 맞지 않아, 외부 표준이 아니라 내부 룩업 테이블 값으로 정했다. exit 코드는 carrying 예외가 - `ExitCodeGenerator`를 구현하기 때문에만 JVM 종료 상태가 된다. -- **`StartupPhase` — 실패 원인을 운영자가 로그에서 구분할 수 있게 하는 `startup.phase` 필드다.** - 시작 실패는 요청이 아직 없으므로 HTTP 에러 응답에 절대 실리지 않는다. 따라서 구조화 로그의 - `startup.phase`가 `kubectl logs`/`describe`에서 네 가지 원인을 가려내는 유일한 계약이다. wire - 이름은 dash-case(`env-validation | migration | adapter-enablement | profile-check`)이며, MDC 키가 - 아니라 Logstash structured argument 로 방출되므로 snake_case MDC 키 레지스트리 규칙은 적용되지 - 않는다. -- **`StartupFailures` — 시작 실패를 던지는 단일 출처로, 예외 생성 *전에* 구조화 로그를 먼저 - 방출한다.** "throw 직전 각 validator 가 직접 logger 를 호출"하는 패턴을 중앙화해, 어떤 시작 가드도 - 원인/구분자 없는 실패를 던지지 못하게 한다. 로그는 `startup.phase` / `error.code` / - `error.category` 세 필드를 Logstash structured argument 로 싣고, cause 가 있으면 - `error.root_cause.class` / `error.root_cause.message` 요약 필드만 추가한다. 원본 cause 는 반환되는 - `StartupFailureException`에 보존하지만 SLF4J throwable 인자로 넘기지 않는다. 따라서 canonical - startup-failure 로그는 운영자가 분류할 수 있는 요약만 남기고 프레임워크/드라이버 stacktrace 를 - 출력하지 않는다. -- **`StartupFailureException` — 네 실패 원인의 베이스 타입이며 `ExitCodeGenerator`로 exit 코드를 JVM - 종료 상태로 만든다.** context refresh 가 실패하면 `SpringApplication`의 `SpringBootExceptionHandler` - (부팅 스레드의 uncaught-exception handler 로 설치됨)가 실패 예외에서 `getExitCode()`를 읽어 - `System.exit(code)`를 호출한다 — `main()` 수정이 필요 없다. `IllegalStateException`을 상속하는 - 이유는 과거 `StartupSafetyValidator`가 `IllegalStateException`을 던졌기 때문으로, 타입드 예외로 - 업그레이드한 뒤에도 소스/동작 호환을 유지하기 위함이다. -- **`StartupFailureExceptionReporter` / `StartupFailureSpringBootLogFilter` — Spring Boot 의 중복 - startup stacktrace 를 억제한다.** reporter 는 failure cause chain 에 `StartupFailureException`이 - 있을 때만 `true`를 반환해 Boot 의 generic `Application run failed` 출력을 "이미 보고됨"으로 - 처리한다. 이후 Boot 가 반쯤 초기화된 context 를 닫다가 `Unable to close ApplicationContext`를 다시 - 남길 수 있으므로, canonical startup-failure 로그가 이미 찍힌 프로세스에서는 해당 - `org.springframework.boot.SpringApplication` 중복 메시지만 logback turbo filter 가 차단한다. 일반 - startup failure 가 아닌 예외와 다른 logger/message 는 기존 Spring Boot 로그 경로를 유지한다. -- **`RequiredAdapterDisabledException`은 런타임-라이프사이클의 `ADAPTER_DISABLED`와 의도적으로 - 구분된다.** 이쪽은 *시작* 검증(필수 어댑터/조정 빈이 꺼져 있음)이고, 후자는 비활성 옵션 어댑터에 - 대한 *런타임* 호출이다. +- 실패 분류와 구조화 로그 계약은 `adapter:outbound:support`의 `support.startup` 패키지로 옮겼다 + (capability 모듈이 합성 루트에 의존하지 않고 같은 exit 코드로 실패하게 하려고). 설계 근거는 그 + 모듈 README에 있다. 합성 루트에는 `StartupFailureExceptionReporter`(Spring Boot 보고 억제)와 + `StartupFailureSpringBootLogFilter`만 남는다. --- @@ -219,45 +150,11 @@ refresh 완료 전에 실패시킨다. 발동시켜야 하므로 `equalsIgnoreCase`로 비교한다(`Environment#matchesProfiles`는 대소문자를 구분해 "PROD"를 통과시킨다). -### HikariPoolConstraintValidator -- **HikariCP 노브 사이의 상호 제약을 부팅 실패로 바꾼다.** Hikari/Tomcat 은 잘못된 값을 결국 - 거부하지만 pool/connector 초기화 시점에 난해한 메시지로만 거부한다. 이 검증기는 계약을 일찍·명확 - 하게 만든다: resolved Spring property 를 읽고, 위반을 모두 모아 운영자가 실제로 설정한 `APP_*` - 환경 키를 메시지에 담아 `IllegalStateException`을 던진다. 속성이 *없으면* 건너뛰고(placeholder/ - 프레임워크 기본값이 소유), *있을 때만* 검사한다. -- **강제하는 제약과 그 숫자의 근거.** `connection-timeout >= 250ms`(너무 짧으면 정상 연결도 타임 - 아웃). `validation-timeout < connection-timeout`(둘 다 있을 때; validation-timeout 기본 5000ms 가 - 흔한 connection-timeout 5s/5000ms 와 같아지는 충돌을 해소). `keepalive-time < max-lifetime`(둘 다 - 있을 때; keepalive 가 lifetime 보다 길면 의미 없음). `leak-detection-threshold`는 0(비활성)이 - 아니라면 `>= 2000ms`(너무 작으면 정상 사용을 누수로 오탐). -- **Spring Boot와 같은 Duration 문법을 검증한다.** `env-keys.yaml`의 `connection-timeout` - 기본값은 `5s`인데 `src/.env`는 `30000`(ms)을 준다. resolved 값을 `String`으로 읽은 뒤 - `DurationStyle`로 plain milliseconds, simple duration(`5s`)과 ISO-8601(`PT5S`)을 같은 - milliseconds 계약으로 변환한다. present-but-invalid 값은 부재로 조용히 취급하지 않고 property - 이름을 포함한 startup validation failure로 거절한다. -- **env 키가 아직 없는 노브는 "env key pending" 문구를 쓴다.** `connection-timeout` / - `max-lifetime`만 `env-keys.yaml`에 등록돼 있고, greenfield 노브(validation-timeout, keepalive-time, - leak-detection-threshold)는 env 키가 없다. 없는 키 이름을 지어내는 대신 pending 문구를 메시지에 넣는다. - -### OpenInViewSafetyValidator -- **OSIV(Open Session In View) OFF 를 hard stop 으로 강제한다.** OSIV 가 켜져 있으면 Hibernate - 세션이 view 렌더링까지 열려 있어, presentation 레이어에서 lazy 연관을 건드리면 거기서 조용히 DB - 쿼리가 나간다 — 이것이 정확히 금지된 레이어 경계 위반이다. Spring Boot 는 - `spring.jpa.open-in-view`가 암묵 기본값일 때 WARN 만 찍을 뿐 명시적으로 `true`로 설정한 배포는 - 막지 못한다. WARN 은 놓치기 쉬우므로, resolved 값이 `true`면 운영자가 실제 설정한 - `APP_DATASOURCE_OPEN_IN_VIEW` 키를 메시지에 담아 부팅을 실패시킨다. -- **읽기만 하고 re-bind 하지 않으며, 부재 값은 Spring 기본에 맡긴다.** `SmartInitializingSingleton` - 으로 한 번만 검사하고, 값이 *없으면* Spring Boot 기본(이 스켈레톤은 `application.yml`에서 OSIV off - 가 기본)에 맡기며 *있는 `true`*만 거부한다. - -### JpaSchemaSafetyValidator -- **Flyway를 production physical schema의 유일한 writer로 유지한다.** `prod` profile에서는 - `spring.jpa.hibernate.ddl-auto`가 `none` 또는 `validate`일 때만 허용한다. `update`, `create`, - `create-drop` 또는 그 밖의 값이면 `APP_DATASOURCE_DDL_AUTO`를 이름으로 포함한 - `PROFILE_MISMATCH`로 부팅을 중단한다. -- **local 개발 편의와 production 권위를 분리한다.** non-prod profile의 `update`/`create`는 이 - validator가 막지 않는다. prod profile 비교와 mode 비교는 대소문자를 무시해 `PROD`/`UPDATE` - 같은 변형도 guard를 우회하지 못한다. +관계형 설정 가드(`HikariPoolConstraintValidator`, `OpenInViewSafetyValidator`, +`JpaSchemaSafetyValidator`, `PostgreSqlTransportSecurityValidator`, +`PersistenceVendorProdSafetyValidator`)는 `adapter:outbound:persistence-jpa`로 옮겼다. 풀 크기 +하한(`APP_DATASOURCE_POOL_MAX_SIZE >= 1`, `APP_DATASOURCE_POOL_MIN_IDLE >= 0`)도 이제 그쪽 +`HikariPoolConstraintValidator`가 검사한다. ### RuntimeNumericBoundsValidator - **고위험 숫자 노브(pool/thread 사이징)만 일부러 좁게 검증한다.** pool/connector 사이징 키는 @@ -277,8 +174,10 @@ refresh 완료 전에 실패시킨다. *존재 여부*(multi-instance 검사에 필요)를 검사할 수 없고, `ApplicationReadyEvent` 리스너는 트래픽 직전에야 발동해 잘못된 부팅을 거부하기엔 너무 늦다. 그래서 이 중간 타이밍을 택했고, 위반 시 throw 하여 context 가 시작을 거부한다. -- **prod 안전 토글은 잘못 켜져 있으면 PROFILE_MISMATCH(exit 71)로 죽인다.** prod 프로파일에서 내부 - 상세 노출/요청 본문 캡처 토글이 켜져 있으면 구조화된 startup-failure 로그와 함께 부팅을 중단한다. +- **prod 에러 상세 노출은 `ErrorDetailExposureSafetyValidator`가 막는다(이 클래스가 아니다).** prod에서 + `spring.web.error.include-stacktrace`·`include-message`·`include-binding-errors`가 `never`가 아니거나 + `include-exception=true`면 PROFILE_MISMATCH(exit 71)로 부팅을 중단한다. env override로 들어온 값도 + 같다. 요청 본문 캡처는 `RequestLoggingFilter`가 body를 읽지 않는 계약으로 막는다. - **multi-instance 가 켜지면 실제 cross-instance lock provider가 조립되어 있어야 한다.** `APP_MULTI_INSTANCE_ENABLED=true`일 때 `distributedLockProvider`가 없거나 `DistributedLockPort` 타입이 아니면 REQUIRED_ADAPTER_DISABLED(exit 72)로 실패시킨다. cache refresh @@ -386,68 +285,48 @@ refresh 완료 전에 실패시킨다. --- -## idempotency — 멱등성 런타임 조립과 TTL 상한 +## idempotency — 멱등성 provider 선택과 executor 조립 -### IdempotencyConfig -- **공유 `Clock` 빈과 `IdempotencyExecutor`를 composition root 에서 조립하고, `@EnableScheduling`으로 - 만료 레코드 reaper 의 스케줄 purge 를 켠다.** `Clock`을 빈으로 한 번만 정의해 executor·persistence - store 어댑터·reaper·rate-limit 인터셉터가 같은 시계를 쓰게 만들어 테스트에서 시간 고정이 쉽고 - 분기마다 시간 해석이 어긋나지 않는다. executor 를 여기서 만드는 이유는 TTL 같은 설정을 - `application-core`가 직접 읽으면 안 되기 때문이다. `@Scheduled` purge 는 `@EnableScheduling` 없이는 - 동작하지 않으므로 이 설정 클래스에서 명시적으로 활성화한다. +### IdempotencyProviderSelectionConfig +- **`IdempotencyExecutor`를 여기서 한 번만 만든다.** provider 모듈은 `IdempotencyStorePort`만 + 내놓는다 — `redis`는 `cache-redis`의 `RedisIdempotencyConfig`, `postgresql`은 `persistence-jpa`의 + `PostgreSqlIdempotencyStoreConfig`. lease·replay TTL·retention·codec id·policy revision 은 어느 + store 든 같은 정책이라 `IdempotencySettings` 하나에서 읽는다. executor 를 application-core 밖에서 + 만드는 이유는 이 설정을 `application-core`가 직접 읽으면 안 되기 때문이다. +- **store 가 정확히 하나가 아니면 기동을 거부한다.** 0개는 provider 모듈이 runtime classpath 에 + 없거나 스위치가 꺼진 경우, 2개는 다른 무언가가 store 를 등록한 경우다. 둘 다 빈 누락 오류나 엉뚱한 + store 로 요청을 처리하는 대신 개수를 담은 startup 실패로 드러난다. +- `provider=disabled`(기본)면 executor 빈 자체가 없다. `jdbc` 값과 V1 조립(`IdempotencyConfig`, + `config/idempotency.yml`)은 삭제됐다. +- `postgresql` provider 는 PostgreSQL data source 가 아니면 기동을 거부한다. `bootRunH2` 에서는 + `disabled` 나 `redis` 를 쓴다. ### IdempotencySettings -- **TTL 기본값은 24h 이고 상한은 72h 이며, 이 상한 검사는 컴팩트 생성자에서 fail-fast 로 던진다.** - `Duration`의 상한은 JSR-303(`@Valid`) 애너테이션으로 표현할 수 없는 교차 필드 불변식이라 생성자에서 - 직접 검증한다. 검증을 느슨하게 두고 넘어가면 과도하게 긴 TTL 이 저장소를 조용히 부풀리고 멱등성 키 - 추측 공격의 유효 시간 창을 넓히기 때문에, 부팅 시점에 즉시 실패시키는 쪽을 택했다. -- **`MAX_TTL`(72h) / 기본 TTL(24h)을 바꿀 때는 보안 베이스라인의 JWT 키 회전 겹침(overlap) 윈도와 - 반드시 함께 검토해야 한다.** 멱등성 레코드의 수명이 키 회전 겹침 윈도(현재 24h)보다 길면, 가명화 - (pseudonym) 기준이 회전된 principal 에 대해 레코드가 재생(replay)될 수 있다. 이 불변식을 강제하는 - CI 게이트는 security-operational-baseline 쪽에 위임돼 있다. -- **`reaperInterval`은 전용 환경변수가 없고 기본 10분이다.** reaper 실행 주기는 비밀이나 배포별 값이 - 아니라 순수 운영 튜닝 값이라 env key 를 따로 두지 않고, 비어 있거나 0/음수면 10분으로 채운다. +- `ca-skeleton.capabilities.idempotency` 에 바인딩되는 유일한 설정 record 다(값은 + `config/capabilities.yml`). ---- + | 키 | env | 기본값 | 상한 | + | --- | --- | --- | --- | + | `provider` | `APP_IDEMPOTENCY_PROVIDER` | `disabled` | `disabled` \| `redis` \| `postgresql` | + | `processing-lease` | `APP_IDEMPOTENCY_PROCESSING_LEASE` | 30s | 1h | + | `replay-ttl` | `APP_IDEMPOTENCY_TTL` | 24h | 72h | + | `failure-retention` | `APP_IDEMPOTENCY_FAILURE_RETENTION` | 24h | 30d | + | `response-codec-id` | — | `json-v2` | 1–64자 | + | `policy-revision` | — | 2 | 양수 | + | `reaper-interval` | — | 10m | 양수 | -## lock — 분산 락 메트릭 데코레이터 배선 - -### DistributedLockConfig -- **`distributedLockProvider` 빈은 `ca-skeleton.runtime.multi-instance-enabled=true`일 때만 - `@ConditionalOnProperty`로 등록되고 `@Primary`로 우선 적용된다.** 다중 인스턴스 환경에서만 - `adapter-persistence`의 원시 `jdbcDistributedLock`(JdbcLockRegistry, Flyway 가 프로비저닝한 - `INT_LOCK` 기반) 어댑터를 `MeteredDistributedLockPort`로 감싸 `lock.acquisition` 카운터를 기록한다. -- **단일 인스턴스에서는 이 조건부 빈이 아예 없으므로 `adapter-persistence`가 등록한 `@Primary - inProcessDistributedLock`(in-process `DefaultLockRegistry`)이 그대로 선택된다.** 이 경로는 의도적 - 으로 계측하지 않는다 — `lock.acquisition` 카운터는 인스턴스 간 분산 조율을 관측할 때만 의미가 - 있고, JVM 안의 단순 뮤텍스에는 무의미하기 때문이다. -- **빈 이름 `"distributedLockProvider"`는 `StartupSafetyValidator`가 이름과 - `DistributedLockPort` 타입을 함께 검증하는 계약이다.** `APP_MULTI_INSTANCE_ENABLED=true`는 이 - cross-instance lock provider를 선택한다. cache refresh / rate-limit / outbox 같은 다른 capability의 - 분산 보장은 각 capability가 켜졌을 때 자기 계약으로 검증하며, 이 스위치가 존재하지 않는 sibling - capability까지 암묵적으로 켜지는 것으로 해석하지 않는다. - -### MeteredDistributedLockPort -- **`DistributedLockPort`를 감싸는 얇은 Micrometer 데코레이터다.** `tryAcquire` 호출마다 - `lock.acquisition` 카운터를 `outcome` 태그와 함께 1 증가시킨다. 태그 값은 세 가지: `acquired`(락 - 획득 성공, 위임 핸들 반환), `timeout`(`LockAcquisitionTimeoutException` 발생), `error`(그 외 모든 - `RuntimeException` 발생). 메트릭 이름과 태그 값은 `docs/registries/metrics.yaml`의 `lock.acquisition` - 행과 일치해야 한다. -- **리스 만료(lease-expiry) CME 흡수.** 보유자가 `close()`를 호출하기 전에 리스(저장소 TTL)가 - 만료되면 그 락 행은 이미 다른 인스턴스가 회수해 갔을 수 있고, 그 시점에 내부 `JdbcLock.unlock()`은 - `ConcurrentModificationException`(CME)을 던진다. 이 예외를 호출자의 `finally { lock.close(); }` - 블록 밖으로 그대로 전파하면 보호 구간(critical section)에서 발생한 본래 예외를 가려버린다 - (masking). 그래서 CME 만 잡아 WARN 로그를 남기고 태그 없는 `lock.lease.expired` 카운터를 1 - 증가시킨 뒤 `close()`는 정상 복귀시킨다. 이렇게 해야 신호(로그+메트릭)는 남기면서도 호출자의 정상 - 흐름과 예외 전파를 방해하지 않는다. 오직 `ConcurrentModificationException`만 흡수하며, DB 장애 같은 - 다른 예외(예: `DataAccessResourceFailureException`)는 리스 만료 신호가 아니므로 손대지 않고 그대로 - 전파한다. -- **MeterRegistry 부재 시 no-op.** 레지스트리를 `ObjectProvider.getIfAvailable()`로 해석하므로 - 클래스패스에 `MeterRegistry` 빈이 없으면(Actuator 미탑재) 모든 메트릭 연산이 조용히 no-op 이 - 된다. `BackgroundJobMetrics` 선례와 동일한 패턴이다. -- **메트릭 실패가 락 경로를 절대 깨뜨리지 않음.** 카운터 등록·증가는 모두 try/catch 로 감싸 예외를 - 로깅 후 삼킨다(log-and-swallow). Micrometer 쪽 실패가 락 획득·보유·실패 보고를 막는 일은 없어야 - 하기 때문이다. + Redis store 튜닝값 `key-version`, `command-timeout`(`APP_IDEMPOTENCY_REDIS_COMMAND_TIMEOUT`)도 + 같은 prefix 아래 있지만 lifecycle 정책이 아니라서 이 record 에 두지 않고 `cache-redis`가 읽는다. +- **상한 검사는 컴팩트 생성자에서 fail-fast 로 던진다.** `Duration`의 상한은 JSR-303(`@Valid`) + 애너테이션으로 표현할 수 없어 생성자에서 직접 검증한다. 검증을 느슨하게 두면 과도하게 긴 TTL 이 + 저장소를 조용히 부풀리고 멱등성 키 추측 공격의 유효 시간 창을 넓히기 때문에, 부팅 시점에 즉시 + 실패시키는 쪽을 택했다. +- **replay TTL 상한(72h) / 기본값(24h)을 바꿀 때는 보안 베이스라인의 JWT 키 회전 겹침(overlap) + 윈도와 반드시 함께 검토해야 한다.** 멱등성 레코드의 수명이 키 회전 겹침 윈도(현재 24h)보다 길면, + 가명화(pseudonym) 기준이 회전된 principal 에 대해 레코드가 재생(replay)될 수 있다. 이 불변식을 + 강제하는 CI 게이트는 security-operational-baseline 쪽에 위임돼 있다. +- **`reaper-interval`은 전용 환경변수가 없다.** reaper 실행 주기는 비밀이나 배포별 값이 아니라 순수 + 운영 튜닝 값이다. reaper 는 provider 가 `postgresql` 일 때만 돈다. --- @@ -470,6 +349,18 @@ refresh 완료 전에 실패시킨다. - **`outboxRelayScheduler` 빈은 `ca-skeleton.outbox.relay-enabled`로 게이팅한다(기본 true, `matchIfMissing=true`).** 릴레이를 끄고 싶을 때 빈 자체가 만들어지지 않게 하기 위함. 키가 없으면 켜진 것으로 본다. +- **store와 publisher가 있을 때만 켜진다.** 설정 전체는 `OutboxStorePort` 빈(persistence-jpa를 고르고 + outbox를 켰을 때만 존재)을, 스케줄러는 추가로 `OutboxMessagePublishPort` 빈(messaging bridge가 + 제공)을 조건으로 건다. 두 auto-configuration 뒤에 오도록 `afterName`으로 순서를 명시한다. 발행할 + 곳이 없으면 스케줄러가 없으므로 PENDING 행이 그대로 남는다 — 예전에는 + `DisabledMessagingSentinelAutoConfiguration`의 대역 publisher가 모든 claim을 실패시켜 DEAD로 + 소진했고, 그걸 막으려고 `OutboxRelayBrokerRequirementValidator`가 있었다. 둘 다 삭제했다. + messaging bridge의 `MessagingConfig`도 outbox 대역 publisher를 만들지 않는다. bridge가 있고 + 켜져 있는데 broker가 비었고 canonical transport도 없으면 기동을 거부한다. +- **왜 persistence-jpa가 아니라 여기인가.** 릴레이는 use case를 조립해 타이머로 구동하는 합성 + 코드다. driven adapter인 persistence-jpa가 use case를 만들거나 호출하면 + `PERSISTENCE_DOES_NOT_DEPEND_ON_APPLICATION_SERVICES` 규칙 위반이다. 모듈 타입은 하나도 이름으로 + 부르지 않고 포트만 쓰므로, persistence-jpa 한 줄을 지우면 릴레이도 함께 꺼진다. - **`outboxLeaderElection` 토큰 빈은 outbox capability 안에서 조건 없이 등록한다.** SKIP LOCKED 는 멀티 인스턴스 전역 스위치와 무관하게 outbox relay 자체의 리더십/claim 메커니즘이라, outbox가 켜진 상태에서 별도 하위 토글로 끌 수 있게 만들지 않는다. 이 토큰은 outbox 조립의 자기 설명용 marker이지 @@ -505,9 +396,9 @@ refresh 완료 전에 실패시킨다. (FAILED/DEAD 전이)는 relay가 persisted transition 성공 뒤 typed reporter로 canonical ERROR를 요청하고 결과에 반영하므로 이 catch 블록까지 오지 않는다 — 여기서 삼키는 것은 어디까지나 "예상치 못한" 예외다. -- **`@EnableScheduling`을 직접 켜지 않고 fixed-delay 를 쓴다.** 스케줄링은 이미 `IdempotencyConfig`를 - 통해 활성화돼 있어 중복으로 켤 필요가 없고, fixed-delay 는 릴레이 실행 시간과 무관하게 사이클이 - 겹치지 않도록(non-overlapping) 보장한다. +- **스케줄링은 `OutboxConfig`가 직접 켜고(`@EnableScheduling`) fixed-delay 를 쓴다.** 예전에는 JDBC + idempotency 설정만 스케줄링을 켰기 때문에 다른 provider 를 고르면 릴레이가 조립만 되고 돌지 + 않았다. fixed-delay 는 릴레이 실행 시간과 무관하게 사이클이 겹치지 않도록(non-overlapping) 보장한다. ### OutboxSettings - **여섯 개 설정값 모두 코드 리터럴 기본값을 쓰고 env placeholder 를 두지 않는다.** 신규 env key 를 @@ -515,7 +406,8 @@ refresh 완료 전에 실패시킨다. `PT5M`, `PT10M`, `P7D`)을 채운다. - **`reaper-interval`과 `published-retention`은 `adapter-persistence`의 `OutboxReaper`도 property 문자열로 읽는다.** 두 모듈이 같은 키를 공유하지만, 이 properties record 가 여섯 값 전체를 문서화 - 하는 단일 지점(single place) 역할을 한다. + 하는 단일 지점(single place) 역할을 한다. 기본값 yml(`ca-skeleton.outbox.*`)은 store를 가진 + persistence-jpa 모듈이 `config/module-defaults/persistence-jpa.yml`로 가져온다. --- @@ -785,8 +677,9 @@ refresh 완료 전에 실패시킨다. - **시작 시 `StartupSafetyValidator`가 강제하는 운영 안전 설정이다.** 현재 구현된 runtime contract는 `APP_MULTI_INSTANCE_ENABLED`이며, 활성화 시 cross-instance `DistributedLockPort`가 실제로 조립됐는지 검증한다. -- 내부 error detail 노출과 request/response body logging은 shipped 구현이 없으므로 예약 토글도 - 두지 않는다. body 로그 안전성은 `RequestLoggingFilter`가 body를 읽지 않는 계약으로 검증한다. +- 내부 error detail 노출은 이 설정의 토글이 아니다. prod에서 `spring.web.error.include-*`가 켜지면 + `ErrorDetailExposureSafetyValidator`가 기동을 막는다. body 로그 안전성은 `RequestLoggingFilter`가 + body를 읽지 않는 계약으로 검증한다. - **`multiInstanceEnabled`가 `true`면 shipped cross-instance `DistributedLockPort`가 실제로 조립됐는지 단언하고, 없거나 이름만 맞춘 잘못된 타입이면 시작을 실패시킨다.** 이 스위치는 JPA-backed distributed lock 선택자다. cache refresh coordination은 optional efficiency이고, rate-limit/outbox는 @@ -803,16 +696,19 @@ app-bootstrap 은 합성 루트라 "왜 이 의존성이, 왜 이 scope 로" 결 필요하면 여기서 **명시적으로** 다시 선언한다. ### 런타임(production) 의존성 -- **`flyway-core`를 직접 의존하는 이유.** PostgreSQL vendor 모듈이 `flyway-database-postgresql`와 - 마이그레이션 스크립트를 소유하지만, 합성 루트는 Flyway API 자체가 필요하다. `MigrationStartupConfig`의 - `migrationStartupRunner`(FlywayMigrationStrategy)가 `migrate()`를 직접 구동하고 `FlywayException`을 - exit-70 `MigrationFailedException`으로 번역하기 때문이다. +- **capability는 main 의존이 아니다.** 알림(`composition:notification-platform`)을 포함한 모든 + capability가 주석 처리된 `runtimeOnly` 한 줄이다(위 "기능 추가 = 한 줄 + env"). +- **persistence-jpa는 main 의존이 아니다.** 기본 조립은 관계형 저장소를 싣지 않는다 + (`// runtimeOnly project(':adapter:outbound:persistence-jpa')` 한 줄을 풀면 켜진다). Flyway + 마이그레이션 전략과 관계형 기동 가드는 그 모듈이 가져온다. 테스트는 JPA rule pack과 계약 테스트 + 때문에 모듈을 `testImplementation`으로 보지만, `systemTest`는 `bootJar`와 같은 런타임 그래프 + (main runtime + 테스트 프레임워크)로 돌도록 test 의존을 물려받지 않는다. - **`spring-boot-starter-security`를 compile classpath 에 두는 이유.** adapter-web 이 security 를 `implementation`(not `api`)으로 선언해서 Spring Security 타입이 app-bootstrap 컴파일 경로로 새지 않는다. 그런데 `ManagementSecurityConfig`가 `HttpSecurity`/`SecurityFilterChain`/`EndpointRequest`를 쓴다. cross-cutting 보안 와이어링은 합성 루트가 소유한다는 원칙(AGENTS.md)에 따라 여기서 직접 의존한다. -- **`micrometer-core`** — `OutboxMetrics` 카운터/게이지용. `ObjectProvider`라 registry +- **`micrometer-core`** — `OutboxMetrics`·`BackgroundJobMetrics` 카운터/게이지용. `ObjectProvider`라 registry 가 없으면 no-op 이다(registry 는 Actuator 가 제공). - **tracing(`micrometer-tracing-bridge-otel` + `opentelemetry-exporter-otlp`)** — OTel/Micrometer tracer 런타임. exporter 는 `OTEL_EXPORTER_OTLP_ENDPOINT`가 비면 켜진 채로 대기만 하고 export 는 @@ -850,12 +746,10 @@ app-bootstrap 은 합성 루트라 "왜 이 의존성이, 왜 이 scope 로" 결 `config/messaging/`은 first polling-producer tuple의 machine-readable 계획 truth만 보관한다. 현재 card 11개는 모두 `maturity: not-implemented`, `evidenceFingerprint: ""`이고 consumer, -CDC, EOS, schema-registry 확장 row는 없다. Task 6의 `verifyMessagingJsonSchemaV1`과 -`verifyMessagingContracts`는 exact qualification test와 test/build 전용 Draft 2020-12 manifest -validator를 실행한다. combined task는 JSON-only task/validator에 명시적으로 의존하므로 CLI 순서와 -무관하게 shared `contracts-schema/manifest.json`의 최종 소유자가 된다. 나머지 `verifyMessaging*` -root task는 후속 owner test와 payload-free evidence validator가 구현되기 전까지 공통 fail-closed -guard에서 반드시 non-zero로 종료한다. 파일 존재, SKIP, 오래된 evidence, 다른 source digest 또는 +CDC, EOS, schema-registry 확장 row는 없다. `verifyMessagingContracts`는 application-core· +shared-contract의 exact qualification test를 실행하고 `contracts-schema/manifest.json`을 쓴 뒤 그 +바이트를 Draft 2020-12 common schema로 검증한다(`verifyMessagingJsonSchemaV1`은 R1 encoder와 함께 +2026-09-25에 삭제). 나머지 `verifyMessaging*` 이름은 등록되지 않은 계획이다. 파일 존재, SKIP, 오래된 evidence, 다른 source digest 또는 다른 profile hash를 PASS로 취급하지 않는다. 이 scaffold는 broker client, scheduler, thread, network 또는 다른 런타임 resource를 생성하지 않는다. diff --git a/src/app-bootstrap/build.gradle b/src/app-bootstrap/build.gradle index 4069fd87..f0dd66bd 100644 --- a/src/app-bootstrap/build.gradle +++ b/src/app-bootstrap/build.gradle @@ -5,13 +5,8 @@ plugins { id 'ca.config-contract' id 'ca.auxiliary-source-set' id 'ca.bootrun-dotenv' - id 'ca.strict-qualification' - id 'ca.dependency-policy' } -def contractRegistriesDirectory = rootProject.projectDir.parentFile.toPath() - .resolve('docs/registries').toFile() - // Application entry point. Wires the default runtime module set and runs Spring Boot. // Optional leaves require an explicit registry allowance plus a composition-root dependency. // The infrastructure lane. Testcontainers-backed tests boot a real PostgreSQL, so they belong to a @@ -30,10 +25,11 @@ auxiliarySourceSets { inherits 'implementation', 'compileOnly', 'runtimeOnly', 'annotationProcessor' runtimeFrom 'test' } + // No `runtimeFrom 'test'` and no inherited test dependencies: the full-boot lane runs on the + // composition bootJar packages (see the configurations block below). sourceSet('systemTest') { compilesAgainst 'main', 'test' - inherits 'implementation', 'compileOnly', 'runtimeOnly', 'annotationProcessor' - runtimeFrom 'test' + inherits 'annotationProcessor' } } @@ -44,6 +40,7 @@ strictTestLanes { sourceSet = 'integrationTest' requires 'dev.caskeleton.bootstrap.integration.fileserver.FileserverCompositionIntegrationTest' requires 'dev.caskeleton.bootstrap.integration.objectstorage.ObjectStorageCompositionIntegrationTest' + requires 'dev.caskeleton.bootstrap.integration.idempotency.PostgreSqlIdempotencyProviderIntegrationTest' } lane('architectureTest') { architecture() @@ -52,7 +49,6 @@ strictTestLanes { maxHeapSize = '2g' jvmArgs '-Duser.timezone=UTC' shouldRunAfter 'test' - inputDirectory contractRegistriesDirectory } lane('systemTest') { system() @@ -62,15 +58,45 @@ strictTestLanes { jvmArgs '-Duser.timezone=UTC' shouldRunAfter 'test' } + lane('conditionalTransportBuildContractTest') { + description = 'Proves the explicit test-only GraphQL/gRPC/WebSocket opt-in classpath.' + sourceSet = 'conditionalTransportBuildContractTest' + requires 'dev.caskeleton.bootstrap.transport.ConditionalTransportBuildContractTest' + rejectSkipped = true + jvmArgs '-Duser.timezone=UTC' + shouldRunAfter 'test' + } } tasks.named('check') { dependsOn tasks.named('systemTestLaneCheck') } -// architectureTest and systemTest compile against test fixtures but intentionally mirror -// the ordinary test runtime rather than their compile classpath. `runtimeFrom 'test'` above keeps -// testCompileOnly analysis dependencies out of these behavioral lanes. +// architectureTest runs on the `test` runtime (runtimeFrom above) plus its own configuration, so +// the capability leaves declared `architectureTestRuntimeOnly` reach the whole-repository ArchUnit +// import without reaching the default composition that `test` and `systemTest` boot. +sourceSets.architectureTest.runtimeClasspath += configurations.architectureTestRuntimeClasspath + +// The full-boot lane boots the composition bootJar packages. It compiles against everything the +// test lane sees, but it runs on the main runtime graph plus the test frameworks — not on the test +// lane's extra modules (persistence-jpa, the slice-test starters). +// A module on the classpath is on, and the shipped artifact contains none of those, so running the +// full boot on the test classpath would open a pool the artifact cannot open. +configurations { + systemTestCompileOnly.extendsFrom testImplementation, testCompileOnly + systemTestImplementation.extendsFrom implementation + systemTestRuntimeOnly.extendsFrom runtimeOnly +} +dependencies { + systemTestImplementation 'org.junit.jupiter:junit-jupiter' + systemTestImplementation 'org.assertj:assertj-core' + systemTestImplementation 'org.springframework.boot:spring-boot-starter-test' + systemTestRuntimeOnly 'org.junit.platform:junit-platform-launcher' +} + +// architectureTest compiles against test fixtures but intentionally mirrors the ordinary test +// runtime rather than its compile classpath. `runtimeFrom 'test'` above keeps testCompileOnly +// analysis dependencies out of that lane. sourceSets { conditionalTransportBuildContractTest { @@ -81,95 +107,75 @@ sourceSets { } } +// Every capability a service can select — the commented runtimeOnly lines below — listed once. +// Two consumers read it: the whole-repository ArchUnit import (spec §7: the architecture suite sees +// every module, the shipped runtime only the selected ones) and the qualification artifact the +// Compose lanes boot (qualificationBootJar, below). Neither reaches `bootJar`, `test` or +// `systemTest`, because a capability on a classpath is switched on there by its mere presence. +// A new capability leaf is added here and as a commented line below; nowhere else. +def capabilityProjects = [ + ':adapter:outbound:persistence-jpa', + ':adapter:outbound:cache-redis', + ':adapter:outbound:messaging-kafka', + ':adapter:outbound:persistence-mongo', + ':adapter:inbound:graphql', + ':adapter:outbound:httpclient', + ':adapter:outbound:objectstorage', + ':adapter:inbound:websocket', + ':adapter:inbound:grpc', + ':composition:fileserver-platform', + ':composition:notification-platform', +] + dependencies { implementation project(':domain-core') implementation project(':application-core') - implementation project(':application-notification') - implementation project(':adapter:outbound:persistence-jpa') + // Test sources name the JPA capability types (the JPA rule pack, the persistence failure + // contract). Test scope only: systemTest runs on the main runtime graph, so the full-boot lane + // still boots the composition this build ships. + testImplementation project(':adapter:outbound:persistence-jpa') + integrationTestImplementation project(':adapter:outbound:persistence-jpa') - // The JPA rule pack, for the production architecture suite. Test scope only: the rules are - // ArchUnit assertions, and the composition root is the one place that can see every runtime - // leaf at once — which is what makes it the right consumer and the wrong shipper. - // Fileserver is not selected by the minimal composition (see the dependencyPolicy block at the - // end of this file). These lanes select it, because they are what proves the capability still - // assembles and still stays off — a contract that cannot be verified from an artifact that does - // not contain it. Object storage already works exactly this way. - testImplementation project(':composition:fileserver-platform') - // The leaf as well as the composition: a handful of bootstrap tests name the adapter's own - // types — the off-state gating inventory and the entity-scan registration among them — and a - // composition that re-exported them would be an `api` edge this module does not want. - testImplementation project(':adapter:outbound:fileserver') - testImplementation project(':application-fileserver') + // 이 서비스가 쓰는 부가 기능 — 필요한 줄의 주석을 푼다. + // 각 모듈은 있으면 켜지고(자기 AutoConfiguration.imports와 설정 기본값을 가진다), 줄을 지우면 + // 기능·설정·의존성이 함께 빠진다. 켠 뒤 필요한 env 키는 각 모듈 README에 있다. + // 줄을 바꾼 뒤 strict lock을 갱신한다: ./gradlew :app-bootstrap:resolveAndLockAll --write-locks + // runtimeOnly project(':adapter:outbound:persistence-jpa') // JPA·Flyway·outbox·lock + // runtimeOnly project(':adapter:outbound:cache-redis') // Redis (캐시·rate limit·idempotency) + // runtimeOnly project(':adapter:outbound:messaging-kafka') // Kafka 발행 + // runtimeOnly project(':adapter:outbound:persistence-mongo') // Mongo + // runtimeOnly project(':adapter:inbound:graphql') // GraphQL + // runtimeOnly project(':adapter:outbound:httpclient') // 외부 HTTP 호출 + // runtimeOnly project(':adapter:outbound:objectstorage') // 객체 저장소 (S3/로컬) + // runtimeOnly project(':adapter:inbound:websocket') // WebSocket (STOMP push) + // runtimeOnly project(':adapter:inbound:grpc') // gRPC 서버 + // runtimeOnly project(':composition:fileserver-platform') // 파일 서버 + // runtimeOnly project(':composition:notification-platform') // 알림 (persistence-jpa 줄도 함께 푼다) + + capabilityProjects.each { architectureTestRuntimeOnly project(it) } + + // The capability integration lane selects Fileserver and object storage together, as a service + // would, and turns off whichever one a test is not about. integrationTestImplementation project(':composition:fileserver-platform') integrationTestImplementation project(':adapter:inbound:web-fileserver') testImplementation(testFixtures(project(':adapter:outbound:persistence-jpa'))) testImplementation(testFixtures(project(':adapter:inbound:web'))) - // The three capabilities above are runtimeOnly for main, and these tests name their types — - // the import filters, the deployment-mode enum, the settings records. Declared here rather than - // widened back to `implementation`, so the composition root's own sources still cannot reach - // them. The Mongo exclusions are repeated because MongoShippedCompositionContractTest asserts - // the shape of the classpath it runs on, not only the shape of the shipped one. - testImplementation(project(':adapter:outbound:persistence-mongo')) { - exclude group: 'org.springframework.boot', module: 'spring-boot-starter-data-mongodb-reactive' - exclude group: 'org.mongodb', module: 'mongodb-driver-reactivestreams' - } - testImplementation project(':adapter:outbound:httpclient') - testImplementation project(':adapter:inbound:graphql') - // Shipped so an operator can enable it with one environment variable. An adapter that is - // absent is not the same contract as one that is off: absence cannot be reversed at deploy time, - // and it hides every gating defect, because code that is not there holds no beans whatever its - // conditions say. - // - // runtimeOnly, not implementation: no source under src/main names a type from this leaf, so the - // composition root has no compile-time business with it, and saying so in the build makes that - // a rule the compiler keeps rather than a habit. It also states which capabilities a fork can - // drop from its artifact by deleting one line — the step the composition-ownership work has to - // reach for the capabilities bootstrap still imports. - runtimeOnly(project(':adapter:outbound:persistence-mongo')) { - // Reactive Mongo is not in the shipped Stable scope: there is no reactive port, no resource - // budget for a second client, and no qualification. Leaving the starter on the runtime - // classpath would let Boot's reactive auto-configuration build a second client and pool from - // the same URI the moment the master switch went on — a duplicate connection nobody asked - // for and nothing tests. Removed here rather than in the leaf, which still needs it to - // compile the reactive code paths it keeps for a future promotion. - exclude group: 'org.springframework.boot', module: 'spring-boot-starter-data-mongodb-reactive' - exclude group: 'org.mongodb', module: 'mongodb-driver-reactivestreams' - } + // The idempotency composition tests drive the executor over the port owner's shared fake store. + testImplementation(testFixtures(project(':application-core'))) + // The opt-in web library is in no shipped composition. Runtime-only for the tests so the + // whole-repository ArchUnit import (architectureTest runs on the test runtime classpath) still + // reads its classes; no test source may name one of its types. It cannot reach a shipped + // composition: no module in modules.json may depend on it, so the direction gate refuses the edge. + testRuntimeOnly project(':adapter:inbound:web-advanced') implementation project(':adapter:outbound:support') - implementation project(':adapter:outbound:messaging') - // The messaging platform facade, so all five adapters are in one artifact and "off" is a switch - // rather than an omission (ShippedRuntimeFacadePresenceTest). It resolves seventeen further - // leaves onto the runtime classpath, which is intended and is why the qualification state is - // recorded rather than implied: MessagingLiveRoundTripQualificationTest qualifies the Kafka - // publish path against a real broker, and the Rabbit transport, the JDBC inbox and outbox - // adapters and the admin plane ship inactive and unqualified behind the same master switch. - // MessagingMembershipQualificationTest holds that distinction so it cannot be forgotten. - implementation project(':messaging:messaging-spring-boot-starter') - implementation project(':adapter:outbound:cache-redis') - implementation project(':adapter:outbound:redis-runtime') - implementation project(':adapter:outbound:notification') - // runtimeOnly for the same reason as persistence-mongo: no main source names an HTTP client type. - runtimeOnly project(':adapter:outbound:httpclient') implementation project(':adapter:outbound:identifier') - // Shipped so an operator can enable the transport with one environment variable. The platform - // configuration carried no master condition at all, so this edge is only safe now that - // GraphQlRootAutoConfiguration owns the switch and the import filter holds Spring GraphQL's own - // auto-configurations back — without both, adding the jar would publish /graphql. - // runtimeOnly: the switch and the import filter are the leaf's, and no main source names either. - runtimeOnly project(':adapter:inbound:graphql') implementation project(':adapter:inbound:web') implementation project(':shared-contract') implementation 'org.springframework.boot:spring-boot-starter' implementation 'org.springframework.boot:spring-boot-starter-validation' implementation libs.spring.dotenv - // Boot 4 Flyway API/autoconfiguration: the composition root drives startup migration - // (MigrationStartupConfig). See README. - implementation 'org.springframework.boot:spring-boot-flyway' - // Flyway API: MigrationStartupRunner directly invokes Flyway. Kept explicit for readability. - implementation 'org.flywaydb:flyway-core' - - // Micrometer core for OutboxMetrics meters (no-op without a MeterRegistry). See README. + // Micrometer core for the bootstrap meters (no-op without a MeterRegistry). See README. implementation 'io.micrometer:micrometer-core' // OTel/Micrometer tracer runtime (exporter stays off until an OTLP endpoint is set). See README. @@ -178,15 +184,11 @@ dependencies { // Actuator + Prometheus registry (health/info/prometheus/loggers endpoints). implementation 'org.springframework.boot:spring-boot-starter-actuator' - // The composition root wires the OAuth2 credential provider for the HTTP Client Platform, - // so it must see OAuth2AuthorizedClientManager. The adapter keeps the dependency internal. - implementation 'org.springframework.security:spring-security-oauth2-client' implementation 'io.micrometer:micrometer-registry-prometheus' // Security types for ManagementSecurityConfig (not reachable via adapter-web's implementation dep). See README. implementation 'org.springframework.boot:spring-boot-starter-security' // test-only: ArchUnit needs actuator types to verify the health-shape guardrail. See README. - testImplementation project(':adapter:outbound:messaging-kafka') testImplementation 'org.springframework.boot:spring-boot-starter-actuator' // test-only: @WithMockUser for the actuator security authorization tests. See README. testImplementation 'org.springframework.security:spring-security-test' @@ -213,8 +215,12 @@ dependencies { testImplementation 'org.springframework.boot:spring-boot-data-jpa-test' // test-only: PG JDBC driver (the vendor module's runtimeOnly does not leak here). See README. testRuntimeOnly 'org.postgresql:postgresql' - // test-only: JPA/Hikari for the outbox tests' minimal context (not leaked from rdbms). See README. + // test-only: Boot's relational auto-configuration types, which a few context tests exclude by name. testImplementation 'org.springframework.boot:spring-boot-starter-data-jpa' + testImplementation 'org.springframework.boot:spring-boot-flyway' + // The integration lane drives Flyway itself and names Boot's Flyway auto-configuration. + integrationTestImplementation 'org.springframework.boot:spring-boot-flyway' + integrationTestImplementation 'org.flywaydb:flyway-core' testImplementation 'com.zaxxer:HikariCP' testImplementation libs.archunit.junit5 @@ -267,9 +273,24 @@ dependencies { conditionalTransportBuildContractTestRuntimeOnly 'org.junit.platform:junit-platform-launcher' } -def repositoryRootForContractTests = rootProject.projectDir.parentFile.absolutePath +// The contract tests here read the repository itself — docs/registries and docs/runbooks, the +// module registry and the rest of src/config, build scripts, Dockerfiles, Compose files, workflows, +// src/.env.example, the root guidance documents. Every one of those is an input, or Gradle calls +// the lane up to date after exactly the edit the test exists to catch. +def repositoryRootForContractTests = rootProject.projectDir.parentFile +def repositoryContractInputs = files( + fileTree(repositoryRootForContractTests) { + include 'docs/**', '.github/**', 'infra/**', 'scripts/**', '*.md', '*.yml', '*.example' + }, + fileTree(rootProject.projectDir) { + include 'config/**', '**/*.gradle', 'gradle/*.toml', 'Dockerfile*', '.env*', '**/*.md' + exclude '**/build/**', '**/.gradle/**' + }) tasks.withType(Test).configureEach { - systemProperty 'ca.repository.root', repositoryRootForContractTests + systemProperty 'ca.repository.root', repositoryRootForContractTests.absolutePath + inputs.files(repositoryContractInputs) + .withPathSensitivity(PathSensitivity.RELATIVE) + .withPropertyName('repositoryContractInputs') } // Fast developer test lane. Whole-repository ArchUnit graphs and full composition-root boot @@ -279,26 +300,12 @@ tasks.named('test', Test) { // Two forks are the measured sweet spot after moving whole-repository ArchUnit and full boot // composition tests out of the fast lane. More forks duplicate Spring contexts for little gain. maxParallelForks = 2 - inputs.dir(contractRegistriesDirectory) - .withPathSensitivity(PathSensitivity.RELATIVE) // Pin UTC for the TEST JVM so timestamp tests are host-locale-independent (production UTC is // owned elsewhere). jvmArgs '-Duser.timezone=UTC' } -def conditionalTransportCompositionQualification = extensions.getByName('strictQualification').register( - 'conditionalTransportBuildContractTest', - sourceSets.conditionalTransportBuildContractTest, - [ - 'dev.caskeleton.bootstrap.transport.ConditionalTransportBuildContractTest' - ], - 'Proves the explicit test-only GraphQL/gRPC/WebSocket opt-in classpath.' -) -conditionalTransportCompositionQualification.configure { - shouldRunAfter tasks.named('test') -} - bootJar { mainClass = 'dev.caskeleton.bootstrap.CaSkeletonApplication' } @@ -310,6 +317,49 @@ tasks.register('stageDockerJar', Sync) { rename { 'application.jar' } } +// A runtime classpath of this composition plus extra leaves, resolved the way Boot resolves +// runtimeClasspath. Used by the H2 convenience below and by the qualification artifact. +def compositionRuntimeClasspath = { String name -> + configurations.create(name) { + canBeConsumed = false + canBeResolved = true + extendsFrom configurations.implementation, configurations.runtimeOnly + attributes { + attribute(Usage.USAGE_ATTRIBUTE, objects.named(Usage, Usage.JAVA_RUNTIME)) + attribute(Category.CATEGORY_ATTRIBUTE, objects.named(Category, Category.LIBRARY)) + attribute(LibraryElements.LIBRARY_ELEMENTS_ATTRIBUTE, objects.named(LibraryElements, LibraryElements.JAR)) + attribute(Bundling.BUNDLING_ATTRIBUTE, objects.named(Bundling, Bundling.EXTERNAL)) + } + } +} + +// The qualification artifact: this composition with every capability on the classpath. It is what +// the Compose lanes (config/runtime/compose-profile-contracts.json) boot, because a lane that turns +// JPA or Kafka on needs the module in the image, and `bootJar` — the default composition a service +// ships — carries none of them. It is never released: `release.yml` builds `stageDockerJar`. +// Each capability is on while present, so a lane switches off what it is not about. +def qualificationClasspath = compositionRuntimeClasspath('qualificationRuntimeClasspath') +dependencies { + capabilityProjects.each { qualificationRuntimeClasspath project(it) } +} +def qualificationBootJar = tasks.register('qualificationBootJar', org.springframework.boot.gradle.tasks.bundling.BootJar) { + group = 'build' + description = 'Assembles the Compose qualification jar: the default composition plus every capability.' + mainClass = 'dev.caskeleton.bootstrap.CaSkeletonApplication' + classpath = sourceSets.main.output + qualificationClasspath + resolvedArtifacts(qualificationClasspath.incoming.artifacts.resolvedArtifacts) + targetJavaVersion = java.targetCompatibility + archiveClassifier = 'qualification' +} +// Same staging path as stageDockerJar, so src/Dockerfile's extract step is one path; its +// COMPOSITION build argument picks which of the two tasks writes it. +tasks.register('stageQualificationDockerJar', Sync) { + dependsOn qualificationBootJar + from(qualificationBootJar.flatMap { it.archiveFile }) + into(layout.buildDirectory.dir('docker')) + rename { 'application.jar' } +} + // `ca.bootrun-dotenv` owns root working-directory and .env injection for bootRun. // Boot 4 initializes profiles/logging before spring-dotenv can reliably contribute these values. @@ -325,14 +375,24 @@ tasks.register('stageDockerJar', Sync) { // separate, named task rather than a property: choosing a datastore whose schema comes from // somewhere else should look like a choice in the command somebody typed. It is not part of `check`, // `build`, or any release lane. +// +// H2 needs relational persistence, which this composition does not ship, so the task adds the +// module to its own classpath. The artifact is unchanged; choosing H2 is still a choice in the +// command somebody typed. +def h2RunClasspath = compositionRuntimeClasspath('bootRunH2Classpath') +dependencies { + bootRunH2Classpath project(':adapter:outbound:persistence-jpa') +} tasks.register('bootRunH2', org.springframework.boot.gradle.tasks.run.BootRun) { group = 'application' description = 'Runs the application on an in-memory H2, for development without a container. ' + 'Not a release lane: H2 has no migration tree and Hibernate owns its schema.' - classpath = sourceSets.main.runtimeClasspath + classpath = sourceSets.main.output + h2RunClasspath mainClass = 'dev.caskeleton.bootstrap.CaSkeletonApplication' workingDir = rootProject.projectDir environment 'SPRING_PROFILES_ACTIVE', 'local' + // A .env copied before the module became opt-in may still say false. + environment 'APP_PERSISTENCE_JPA_ENABLED', 'true' environment 'APP_PERSISTENCE_VENDOR', 'h2' environment 'APP_DATASOURCE_URL', 'jdbc:h2:mem:ca_skeleton;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1' @@ -343,48 +403,6 @@ tasks.register('bootRunH2', org.springframework.boot.gradle.tasks.run.BootRun) { // and DB_CLOSE_DELAY=-1 above is what keeps the in-memory schema alive when the pool goes idle. environment 'APP_FLYWAY_ENABLED', 'false' environment 'APP_DATASOURCE_DDL_AUTO', 'create-drop' -} - -// Runtime project membership is derived directly by verifyRuntimeModuleRegistry from the -// resolved runtimeClasspath. No generated snapshot is maintained here. - -// The environment configuration contract. Owned here because the question it answers — what must a -// deployment of this application be given — is the composition root's, and reached through -// `configContractCheck` rather than through every leaf's `check`. - -// The Build Composition contract. -// -// Three questions the repository kept answering with one answer: -// -// Does this repository support Fileserver? -> the capability catalog, modules.json -// Does this build ship Fileserver? -> here -// Is the shipped Fileserver switched on? -> app.fileserver-platform.enabled -// -// Only the second one is a dependency question, and until now nothing asked it. Lowering a -// capability to `runtimeOnly` answered a different question — it left the compile classpath and -// stayed in the jar — so "we do not ship it" and "we ship it switched off" were the same build. -// They are not the same artifact, and they are not the same risk: code that is absent holds no -// beans, opens no ports and carries no CVE, whatever its conditions say. -// -// Declared as an absence on `runtimeClasspath` rather than as a test, because `runtimeClasspath` is -// what `bootJar` packages. `ca.dependency-policy` already resolves a named configuration and fails -// on a forbidden coordinate, so this needs no verifier of its own — which is the point: a build -// composition rule that required new build tooling would be trading one coupling for another. -// -// A fork that wants the capability adds the project dependency back and deletes the matching line -// here, the same two-line act that object storage already documents in docs/capability-status.md. -dependencyPolicy { - absent 'dev.caskeleton:fileserver', - 'Fileserver is an optional capability. The minimal composition does not ship it; a deployment that wants it selects :composition:fileserver-platform.' - absent 'dev.caskeleton:application-fileserver', - 'Fileserver use cases ship with the capability that drives them, not with every application.' - // The capability is four modules, so the contract names four. Listing only the ones that were - // easy to remove would have left the rule true and the artifact unchanged: `application-fileserver` - // stayed on the classpath through `adapter:inbound:web`, `adapter:outbound:persistence-jpa` and - // `adapter:outbound:identifier` long after the composition root stopped naming Fileserver, because - // the capability's code was inside those three leaves rather than merely wired by bootstrap. - absent 'dev.caskeleton:web-fileserver', - 'The Fileserver HTTP surface ships with the capability, not with every application that has an HTTP API.' - absent 'dev.caskeleton:persistence-fileserver', - 'The Fileserver schema and stores ship with the capability, not with every application that has a database.' + // The PostgreSQL idempotency store refuses H2, and a .env copied from .env.example may select it. + environment 'APP_IDEMPOTENCY_PROVIDER', 'disabled' } diff --git a/src/app-bootstrap/gradle.lockfile b/src/app-bootstrap/gradle.lockfile index a0a2df18..493ff1f3 100644 --- a/src/app-bootstrap/gradle.lockfile +++ b/src/app-bootstrap/gradle.lockfile @@ -1,250 +1,248 @@ # 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. -aopalliance:aopalliance:1.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -at.yawk.lz4:lz4-java:1.10.1=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath +aopalliance:aopalliance:1.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +at.yawk.lz4:lz4-java:1.10.1=architectureTestRuntimeClasspath,qualificationRuntimeClasspath biz.aQute.bnd:biz.aQute.bnd.annotation:7.1.0=architectureTestCompileClasspath,compileClasspath,integrationTestCompileClasspath,systemTestCompileClasspath,testCompileClasspath -ch.qos.logback:logback-classic:1.5.38=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -ch.qos.logback:logback-core:1.5.38=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -com.approvaltests:approvaltests-util:31.0.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -com.approvaltests:approvaltests:31.0.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -com.ethlo.time:itu:1.14.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -com.fasterxml.jackson.core:jackson-annotations:2.21=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -com.fasterxml.jackson.core:jackson-core:2.21.5=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -com.fasterxml.jackson.core:jackson-databind:2.21.5=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:2.21.5=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.21.5=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -com.fasterxml.jackson:jackson-bom:2.21.5=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -com.fasterxml:classmate:1.7.3=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +ch.qos.logback:logback-classic:1.5.38=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +ch.qos.logback:logback-core:1.5.38=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +com.approvaltests:approvaltests-util:31.0.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath +com.approvaltests:approvaltests:31.0.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath +com.ethlo.time:itu:1.14.0=architectureTestRuntimeClasspath,qualificationRuntimeClasspath +com.fasterxml.jackson.core:jackson-annotations:2.21=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +com.fasterxml.jackson.core:jackson-core:2.21.5=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +com.fasterxml.jackson.core:jackson-databind:2.21.5=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:2.21.5=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath +com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.21.5=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath +com.fasterxml.jackson:jackson-bom:2.21.5=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +com.fasterxml:classmate:1.7.3=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,architectureTestAnnotationProcessor,conditionalTransportBuildContractTestAnnotationProcessor,integrationTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor -com.github.docker-java:docker-java-api:3.7.1=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -com.github.docker-java:docker-java-transport-zerodep:3.7.1=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -com.github.docker-java:docker-java-transport:3.7.1=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +com.github.docker-java:docker-java-api:3.7.1=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath +com.github.docker-java:docker-java-transport-zerodep:3.7.1=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath +com.github.docker-java:docker-java-transport:3.7.1=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,architectureTestAnnotationProcessor,conditionalTransportBuildContractTestAnnotationProcessor,integrationTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor -com.github.luben:zstd-jni:1.5.6-10=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath +com.github.luben:zstd-jni:1.5.6-10=architectureTestRuntimeClasspath,qualificationRuntimeClasspath 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=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,spotbugs,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -com.google.android:annotations:4.1.1.4=conditionalTransportBuildContractTestRuntimeClasspath -com.google.api.grpc:proto-google-common-protos:2.41.0=conditionalTransportBuildContractTestRuntimeClasspath +com.github.stephenc.jcip:jcip-annotations:1.0-1=architectureTestRuntimeClasspath,qualificationRuntimeClasspath,spotbugs +com.google.android:annotations:4.1.1.4=architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,qualificationRuntimeClasspath +com.google.api.grpc:proto-google-common-protos:2.41.0=architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,qualificationRuntimeClasspath com.google.auto.service:auto-service-annotations:1.0.1=annotationProcessor,architectureTestAnnotationProcessor,conditionalTransportBuildContractTestAnnotationProcessor,integrationTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor com.google.auto.value:auto-value-annotations:1.9=annotationProcessor,architectureTestAnnotationProcessor,conditionalTransportBuildContractTestAnnotationProcessor,integrationTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor com.google.auto:auto-common:1.2.2=annotationProcessor,architectureTestAnnotationProcessor,conditionalTransportBuildContractTestAnnotationProcessor,integrationTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor -com.google.code.findbugs:jsr305:3.0.2=checkstyle,conditionalTransportBuildContractTestRuntimeClasspath,spotbugs -com.google.code.gson:gson:2.13.2=architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestRuntimeClasspath,spotbugs,systemTestRuntimeClasspath,testRuntimeClasspath +com.google.code.findbugs:jsr305:3.0.2=architectureTestRuntimeClasspath,checkstyle,conditionalTransportBuildContractTestRuntimeClasspath,qualificationRuntimeClasspath,spotbugs +com.google.code.gson:gson:2.13.2=architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,spotbugs,testRuntimeClasspath com.google.errorprone:error_prone_annotation:2.49.0=annotationProcessor,architectureTestAnnotationProcessor,conditionalTransportBuildContractTestAnnotationProcessor,integrationTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor com.google.errorprone:error_prone_annotations:2.38.0=architectureTestCompileClasspath,compileClasspath,integrationTestCompileClasspath,systemTestCompileClasspath,testCompileClasspath -com.google.errorprone:error_prone_annotations:2.41.0=architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestRuntimeClasspath,spotbugs,systemTestRuntimeClasspath,testRuntimeClasspath +com.google.errorprone:error_prone_annotations:2.41.0=architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,spotbugs,testRuntimeClasspath com.google.errorprone:error_prone_annotations:2.47.0=checkstyle com.google.errorprone:error_prone_annotations:2.49.0=annotationProcessor,architectureTestAnnotationProcessor,conditionalTransportBuildContractTestAnnotationProcessor,integrationTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor com.google.errorprone:error_prone_check_api:2.49.0=annotationProcessor,architectureTestAnnotationProcessor,conditionalTransportBuildContractTestAnnotationProcessor,integrationTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor com.google.errorprone:error_prone_core:2.49.0=annotationProcessor,architectureTestAnnotationProcessor,conditionalTransportBuildContractTestAnnotationProcessor,integrationTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor com.google.googlejavaformat:google-java-format:1.35.0=annotationProcessor,architectureTestAnnotationProcessor,conditionalTransportBuildContractTestAnnotationProcessor,integrationTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor -com.google.guava:failureaccess:1.0.2=conditionalTransportBuildContractTestRuntimeClasspath +com.google.guava:failureaccess:1.0.2=architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,qualificationRuntimeClasspath com.google.guava:failureaccess:1.0.3=annotationProcessor,architectureTestAnnotationProcessor,checkstyle,conditionalTransportBuildContractTestAnnotationProcessor,integrationTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor -com.google.guava:guava:33.2.1-jre=conditionalTransportBuildContractTestRuntimeClasspath +com.google.guava:guava:33.2.1-jre=architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,qualificationRuntimeClasspath com.google.guava:guava:33.5.0-jre=annotationProcessor,architectureTestAnnotationProcessor,conditionalTransportBuildContractTestAnnotationProcessor,integrationTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor com.google.guava:guava:33.6.0-jre=checkstyle -com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,architectureTestAnnotationProcessor,checkstyle,conditionalTransportBuildContractTestAnnotationProcessor,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor -com.google.j2objc:j2objc-annotations:2.8=conditionalTransportBuildContractTestRuntimeClasspath +com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,architectureTestAnnotationProcessor,architectureTestRuntimeClasspath,checkstyle,conditionalTransportBuildContractTestAnnotationProcessor,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestAnnotationProcessor,qualificationRuntimeClasspath,systemTestAnnotationProcessor,testAnnotationProcessor +com.google.j2objc:j2objc-annotations:2.8=architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,qualificationRuntimeClasspath com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,architectureTestAnnotationProcessor,checkstyle,conditionalTransportBuildContractTestAnnotationProcessor,integrationTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor -com.google.protobuf:protobuf-java-util:3.25.5=conditionalTransportBuildContractTestRuntimeClasspath -com.google.protobuf:protobuf-java:3.25.5=conditionalTransportBuildContractTestRuntimeClasspath +com.google.protobuf:protobuf-java-util:3.25.5=architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,qualificationRuntimeClasspath +com.google.protobuf:protobuf-java:3.25.5=architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,qualificationRuntimeClasspath com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,architectureTestAnnotationProcessor,conditionalTransportBuildContractTestAnnotationProcessor,integrationTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor -com.graphql-java:graphql-java:25.0=architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -com.graphql-java:java-dataloader:6.0.0=architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -com.h2database:h2:2.4.240=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath +com.graphql-java:graphql-java:25.0=architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,qualificationRuntimeClasspath +com.graphql-java:java-dataloader:6.0.0=architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,qualificationRuntimeClasspath +com.h2database:h2:2.4.240=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,testRuntimeClasspath com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins com.jayway.jsonpath:json-path:2.10.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -com.networknt:json-schema-validator:3.0.2=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -com.nimbusds:content-type:2.3=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -com.nimbusds:lang-tag:1.7=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -com.nimbusds:nimbus-jose-jwt:10.4=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -com.nimbusds:oauth2-oidc-sdk:11.26.1=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +com.networknt:json-schema-validator:3.0.2=architectureTestRuntimeClasspath,qualificationRuntimeClasspath +com.nimbusds:content-type:2.3=architectureTestRuntimeClasspath,qualificationRuntimeClasspath +com.nimbusds:lang-tag:1.7=architectureTestRuntimeClasspath,qualificationRuntimeClasspath +com.nimbusds:nimbus-jose-jwt:10.4=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath +com.nimbusds:oauth2-oidc-sdk:11.26.1=architectureTestRuntimeClasspath,qualificationRuntimeClasspath com.puppycrawl.tools:checkstyle:13.5.0=checkstyle -com.squareup.okhttp3:okhttp-jvm:5.2.1=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -com.squareup.okhttp3:okhttp:5.2.1=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -com.squareup.okio:okio-jvm:3.16.1=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -com.squareup.okio:okio:3.16.1=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -com.sun.istack:istack-commons-runtime:4.1.2=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -com.tngtech.archunit:archunit-junit5-api:1.3.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -com.tngtech.archunit:archunit-junit5-engine-api:1.3.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -com.tngtech.archunit:archunit-junit5-engine:1.3.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -com.tngtech.archunit:archunit-junit5:1.3.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -com.tngtech.archunit:archunit:1.3.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +com.squareup.okhttp3:okhttp-jvm:5.2.1=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath +com.squareup.okhttp3:okhttp:5.2.1=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath +com.squareup.okio:okio-jvm:3.16.1=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath +com.squareup.okio:okio:3.16.1=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath +com.sun.istack:istack-commons-runtime:4.1.2=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,testRuntimeClasspath +com.tngtech.archunit:archunit-junit5-api:1.3.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath +com.tngtech.archunit:archunit-junit5-engine-api:1.3.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,testRuntimeClasspath +com.tngtech.archunit:archunit-junit5-engine:1.3.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,testRuntimeClasspath +com.tngtech.archunit:archunit-junit5:1.3.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath +com.tngtech.archunit:archunit:1.3.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath com.vaadin.external.google:android-json:0.0.20131108.vaadin1=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -com.zaxxer:HikariCP:7.0.2=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +com.zaxxer:HikariCP:7.0.2=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath commons-beanutils:commons-beanutils:1.11.0=checkstyle -commons-codec:commons-codec:1.19.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +commons-codec:commons-codec:1.19.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath commons-collections:commons-collections:3.2.2=checkstyle -commons-io:commons-io:2.20.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +commons-io:commons-io:2.20.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath commons-io:commons-io:2.21.0=spotbugs -commons-logging:commons-logging:1.3.6=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -eu.rekawek.toxiproxy:toxiproxy-java:2.1.11=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath +commons-logging:commons-logging:1.3.6=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +eu.rekawek.toxiproxy:toxiproxy-java:2.1.11=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,testRuntimeClasspath info.picocli:picocli:4.7.7=checkstyle -io.cloudevents:cloudevents-api:4.0.1=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -io.cloudevents:cloudevents-core:4.0.1=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -io.github.cdimascio:dotenv-java:3.0.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath +io.github.cdimascio:dotenv-java:3.0.0=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,architectureTestAnnotationProcessor,conditionalTransportBuildContractTestAnnotationProcessor,integrationTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,architectureTestAnnotationProcessor,conditionalTransportBuildContractTestAnnotationProcessor,integrationTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor -io.github.resilience4j:resilience4j-bulkhead:2.2.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -io.github.resilience4j:resilience4j-circuitbreaker:2.2.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -io.github.resilience4j:resilience4j-core:2.2.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -io.github.resilience4j:resilience4j-micrometer:2.2.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -io.github.resilience4j:resilience4j-ratelimiter:2.2.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -io.github.resilience4j:resilience4j-retry:2.2.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -io.github.resilience4j:resilience4j-timelimiter:2.2.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -io.grpc:grpc-api:1.68.1=conditionalTransportBuildContractTestRuntimeClasspath -io.grpc:grpc-context:1.68.1=conditionalTransportBuildContractTestRuntimeClasspath -io.grpc:grpc-core:1.68.1=conditionalTransportBuildContractTestRuntimeClasspath -io.grpc:grpc-netty-shaded:1.68.1=conditionalTransportBuildContractTestRuntimeClasspath -io.grpc:grpc-protobuf-lite:1.68.1=conditionalTransportBuildContractTestRuntimeClasspath -io.grpc:grpc-protobuf:1.68.1=conditionalTransportBuildContractTestRuntimeClasspath -io.grpc:grpc-services:1.68.1=conditionalTransportBuildContractTestRuntimeClasspath -io.grpc:grpc-stub:1.68.1=conditionalTransportBuildContractTestRuntimeClasspath -io.grpc:grpc-util:1.68.1=conditionalTransportBuildContractTestRuntimeClasspath -io.lettuce:lettuce-core:6.8.2.RELEASE=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -io.micrometer:context-propagation:1.2.1=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -io.micrometer:micrometer-commons:1.16.7=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -io.micrometer:micrometer-core:1.16.7=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -io.micrometer:micrometer-jakarta9:1.16.7=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -io.micrometer:micrometer-observation:1.16.7=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -io.micrometer:micrometer-registry-prometheus:1.16.7=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -io.micrometer:micrometer-tracing-bridge-otel:1.6.7=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -io.micrometer:micrometer-tracing:1.6.7=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -io.netty:netty-buffer:4.2.17.Final=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -io.netty:netty-codec-base:4.2.17.Final=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -io.netty:netty-codec-classes-quic:4.2.17.Final=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -io.netty:netty-codec-compression:4.2.17.Final=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -io.netty:netty-codec-dns:4.2.17.Final=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -io.netty:netty-codec-http2:4.2.17.Final=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -io.netty:netty-codec-http3:4.2.17.Final=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -io.netty:netty-codec-http:4.2.17.Final=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -io.netty:netty-codec-marshalling:4.2.17.Final=integrationTestRuntimeClasspath -io.netty:netty-codec-native-quic:4.2.17.Final=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -io.netty:netty-codec-protobuf:4.2.17.Final=integrationTestRuntimeClasspath -io.netty:netty-codec-socks:4.2.17.Final=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -io.netty:netty-codec:4.2.17.Final=integrationTestRuntimeClasspath -io.netty:netty-common:4.2.17.Final=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -io.netty:netty-handler-proxy:4.2.17.Final=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -io.netty:netty-handler:4.2.17.Final=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -io.netty:netty-resolver-dns-classes-macos:4.2.17.Final=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -io.netty:netty-resolver-dns-native-macos:4.2.17.Final=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -io.netty:netty-resolver-dns:4.2.17.Final=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -io.netty:netty-resolver:4.2.17.Final=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -io.netty:netty-transport-classes-epoll:4.2.17.Final=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -io.netty:netty-transport-native-epoll:4.2.17.Final=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -io.netty:netty-transport-native-unix-common:4.2.17.Final=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -io.netty:netty-transport:4.2.17.Final=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -io.opentelemetry.semconv:opentelemetry-semconv:1.37.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -io.opentelemetry:opentelemetry-api:1.55.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -io.opentelemetry:opentelemetry-common:1.55.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -io.opentelemetry:opentelemetry-context:1.55.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -io.opentelemetry:opentelemetry-exporter-common:1.55.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -io.opentelemetry:opentelemetry-exporter-otlp-common:1.55.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -io.opentelemetry:opentelemetry-exporter-otlp:1.55.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -io.opentelemetry:opentelemetry-exporter-sender-okhttp:1.55.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -io.opentelemetry:opentelemetry-extension-trace-propagators:1.55.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -io.opentelemetry:opentelemetry-sdk-common:1.55.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -io.opentelemetry:opentelemetry-sdk-extension-autoconfigure-spi:1.55.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -io.opentelemetry:opentelemetry-sdk-logs:1.55.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -io.opentelemetry:opentelemetry-sdk-metrics:1.55.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -io.opentelemetry:opentelemetry-sdk-trace:1.55.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -io.opentelemetry:opentelemetry-sdk:1.55.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -io.perfmark:perfmark-api:0.27.0=conditionalTransportBuildContractTestRuntimeClasspath -io.projectreactor.netty:reactor-netty-core:1.3.7=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -io.projectreactor.netty:reactor-netty-http:1.3.7=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -io.projectreactor:reactor-core:3.8.7=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -io.prometheus:prometheus-metrics-config:1.4.3=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -io.prometheus:prometheus-metrics-core:1.4.3=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -io.prometheus:prometheus-metrics-exposition-formats:1.4.3=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -io.prometheus:prometheus-metrics-exposition-textformats:1.4.3=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -io.prometheus:prometheus-metrics-model:1.4.3=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -io.prometheus:prometheus-metrics-tracer-common:1.4.3=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -io.smallrye:jandex:3.3.2=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -io.swagger.core.v3:swagger-annotations-jakarta:2.2.38=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -io.swagger.core.v3:swagger-core-jakarta:2.2.38=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -io.swagger.core.v3:swagger-models-jakarta:2.2.38=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -jakarta.activation:jakarta.activation-api:2.1.4=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -jakarta.annotation:jakarta.annotation-api:3.0.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -jakarta.inject:jakarta.inject-api:2.0.1=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -jakarta.mail:jakarta.mail-api:2.1.5=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -jakarta.persistence:jakarta.persistence-api:3.2.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -jakarta.servlet:jakarta.servlet-api:6.1.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -jakarta.transaction:jakarta.transaction-api:2.0.1=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -jakarta.validation:jakarta.validation-api:3.1.1=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +io.github.resilience4j:resilience4j-bulkhead:2.2.0=architectureTestRuntimeClasspath,qualificationRuntimeClasspath +io.github.resilience4j:resilience4j-circuitbreaker:2.2.0=architectureTestRuntimeClasspath,qualificationRuntimeClasspath +io.github.resilience4j:resilience4j-core:2.2.0=architectureTestRuntimeClasspath,qualificationRuntimeClasspath +io.github.resilience4j:resilience4j-micrometer:2.2.0=architectureTestRuntimeClasspath,qualificationRuntimeClasspath +io.github.resilience4j:resilience4j-ratelimiter:2.2.0=architectureTestRuntimeClasspath,qualificationRuntimeClasspath +io.github.resilience4j:resilience4j-retry:2.2.0=architectureTestRuntimeClasspath,qualificationRuntimeClasspath +io.github.resilience4j:resilience4j-timelimiter:2.2.0=architectureTestRuntimeClasspath,qualificationRuntimeClasspath +io.grpc:grpc-api:1.68.1=architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,qualificationRuntimeClasspath +io.grpc:grpc-context:1.68.1=architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,qualificationRuntimeClasspath +io.grpc:grpc-core:1.68.1=architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,qualificationRuntimeClasspath +io.grpc:grpc-netty-shaded:1.68.1=architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,qualificationRuntimeClasspath +io.grpc:grpc-protobuf-lite:1.68.1=architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,qualificationRuntimeClasspath +io.grpc:grpc-protobuf:1.68.1=architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,qualificationRuntimeClasspath +io.grpc:grpc-services:1.68.1=architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,qualificationRuntimeClasspath +io.grpc:grpc-stub:1.68.1=architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,qualificationRuntimeClasspath +io.grpc:grpc-util:1.68.1=architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,qualificationRuntimeClasspath +io.lettuce:lettuce-core:6.8.2.RELEASE=architectureTestRuntimeClasspath,qualificationRuntimeClasspath +io.micrometer:context-propagation:1.2.1=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +io.micrometer:micrometer-commons:1.16.7=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +io.micrometer:micrometer-core:1.16.7=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +io.micrometer:micrometer-jakarta9:1.16.7=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +io.micrometer:micrometer-observation:1.16.7=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +io.micrometer:micrometer-registry-prometheus:1.16.7=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +io.micrometer:micrometer-tracing-bridge-otel:1.6.7=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +io.micrometer:micrometer-tracing:1.6.7=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +io.netty:netty-buffer:4.2.17.Final=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath +io.netty:netty-codec-base:4.2.17.Final=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath +io.netty:netty-codec-classes-quic:4.2.17.Final=architectureTestRuntimeClasspath,qualificationRuntimeClasspath +io.netty:netty-codec-compression:4.2.17.Final=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath +io.netty:netty-codec-dns:4.2.17.Final=architectureTestRuntimeClasspath,qualificationRuntimeClasspath +io.netty:netty-codec-http2:4.2.17.Final=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath +io.netty:netty-codec-http3:4.2.17.Final=architectureTestRuntimeClasspath,qualificationRuntimeClasspath +io.netty:netty-codec-http:4.2.17.Final=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath +io.netty:netty-codec-marshalling:4.2.17.Final=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath +io.netty:netty-codec-native-quic:4.2.17.Final=architectureTestRuntimeClasspath,qualificationRuntimeClasspath +io.netty:netty-codec-protobuf:4.2.17.Final=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath +io.netty:netty-codec-socks:4.2.17.Final=architectureTestRuntimeClasspath,qualificationRuntimeClasspath +io.netty:netty-codec:4.2.17.Final=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath +io.netty:netty-common:4.2.17.Final=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath +io.netty:netty-handler-proxy:4.2.17.Final=architectureTestRuntimeClasspath,qualificationRuntimeClasspath +io.netty:netty-handler:4.2.17.Final=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath +io.netty:netty-resolver-dns-classes-macos:4.2.17.Final=architectureTestRuntimeClasspath,qualificationRuntimeClasspath +io.netty:netty-resolver-dns-native-macos:4.2.17.Final=architectureTestRuntimeClasspath,qualificationRuntimeClasspath +io.netty:netty-resolver-dns:4.2.17.Final=architectureTestRuntimeClasspath,qualificationRuntimeClasspath +io.netty:netty-resolver:4.2.17.Final=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath +io.netty:netty-transport-classes-epoll:4.2.17.Final=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath +io.netty:netty-transport-native-epoll:4.2.17.Final=architectureTestRuntimeClasspath,qualificationRuntimeClasspath +io.netty:netty-transport-native-unix-common:4.2.17.Final=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath +io.netty:netty-transport:4.2.17.Final=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath +io.opentelemetry.semconv:opentelemetry-semconv:1.37.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +io.opentelemetry:opentelemetry-api:1.55.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +io.opentelemetry:opentelemetry-common:1.55.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +io.opentelemetry:opentelemetry-context:1.55.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +io.opentelemetry:opentelemetry-exporter-common:1.55.0=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath +io.opentelemetry:opentelemetry-exporter-otlp-common:1.55.0=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath +io.opentelemetry:opentelemetry-exporter-otlp:1.55.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +io.opentelemetry:opentelemetry-exporter-sender-okhttp:1.55.0=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath +io.opentelemetry:opentelemetry-extension-trace-propagators:1.55.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +io.opentelemetry:opentelemetry-sdk-common:1.55.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +io.opentelemetry:opentelemetry-sdk-extension-autoconfigure-spi:1.55.0=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath +io.opentelemetry:opentelemetry-sdk-logs:1.55.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +io.opentelemetry:opentelemetry-sdk-metrics:1.55.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +io.opentelemetry:opentelemetry-sdk-trace:1.55.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +io.opentelemetry:opentelemetry-sdk:1.55.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +io.perfmark:perfmark-api:0.27.0=architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,qualificationRuntimeClasspath +io.projectreactor.netty:reactor-netty-core:1.3.7=architectureTestRuntimeClasspath,qualificationRuntimeClasspath +io.projectreactor.netty:reactor-netty-http:1.3.7=architectureTestRuntimeClasspath,qualificationRuntimeClasspath +io.projectreactor:reactor-core:3.8.7=architectureTestRuntimeClasspath,bootRunH2Classpath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,testRuntimeClasspath +io.prometheus:prometheus-metrics-config:1.4.3=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +io.prometheus:prometheus-metrics-core:1.4.3=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +io.prometheus:prometheus-metrics-exposition-formats:1.4.3=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath +io.prometheus:prometheus-metrics-exposition-textformats:1.4.3=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath +io.prometheus:prometheus-metrics-model:1.4.3=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +io.prometheus:prometheus-metrics-tracer-common:1.4.3=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +io.smallrye:jandex:3.3.2=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,testRuntimeClasspath +io.swagger.core.v3:swagger-annotations-jakarta:2.2.38=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath +io.swagger.core.v3:swagger-core-jakarta:2.2.38=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath +io.swagger.core.v3:swagger-models-jakarta:2.2.38=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath +jakarta.activation:jakarta.activation-api:2.1.4=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +jakarta.annotation:jakarta.annotation-api:3.0.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +jakarta.inject:jakarta.inject-api:2.0.1=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,testRuntimeClasspath +jakarta.mail:jakarta.mail-api:2.1.5=architectureTestRuntimeClasspath,qualificationRuntimeClasspath +jakarta.persistence:jakarta.persistence-api:3.2.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath +jakarta.servlet:jakarta.servlet-api:6.1.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,testRuntimeClasspath +jakarta.transaction:jakarta.transaction-api:2.0.1=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath +jakarta.validation:jakarta.validation-api:3.1.1=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath jakarta.websocket:jakarta.websocket-api:2.2.0=architectureTestCompileClasspath,integrationTestCompileClasspath,systemTestCompileClasspath,testCompileClasspath jakarta.ws.rs:jakarta.ws.rs-api:4.0.0=architectureTestCompileClasspath,integrationTestCompileClasspath,systemTestCompileClasspath,testCompileClasspath -jakarta.xml.bind:jakarta.xml.bind-api:4.0.5=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +jakarta.xml.bind:jakarta.xml.bind-api:4.0.5=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath javax.inject:javax.inject:1=annotationProcessor,architectureTestAnnotationProcessor,conditionalTransportBuildContractTestAnnotationProcessor,integrationTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor jaxen:jaxen:2.0.6=spotbugs -me.paulschwarz:spring-dotenv:4.0.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +me.paulschwarz:spring-dotenv:4.0.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath net.bytebuddy:byte-buddy-agent:1.17.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -net.bytebuddy:byte-buddy:1.17.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,conditionalTransportBuildContractTestCompileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -net.java.dev.jna:jna:5.18.1=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -net.logstash.logback:logstash-logback-encoder:8.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -net.minidev:accessors-smart:2.6.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -net.minidev:json-smart:2.6.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +net.bytebuddy:byte-buddy:1.17.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,conditionalTransportBuildContractTestCompileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +net.java.dev.jna:jna:5.18.1=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath +net.logstash.logback:logstash-logback-encoder:8.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +net.minidev:accessors-smart:2.6.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +net.minidev:json-smart:2.6.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath net.sf.saxon:Saxon-HE:12.9=checkstyle,spotbugs -ognl:ognl:3.3.4=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -org.antlr:antlr4-runtime:4.13.2=architectureTestCompileClasspath,architectureTestRuntimeClasspath,checkstyle,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +ognl:ognl:3.3.4=architectureTestRuntimeClasspath,qualificationRuntimeClasspath +org.antlr:antlr4-runtime:4.13.2=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,checkstyle,integrationTestCompileClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath org.apache.bcel:bcel:6.12.0=spotbugs -org.apache.commons:commons-compress:1.28.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.apache.commons:commons-lang3:3.20.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,checkstyle,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,spotbugs,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.apache.commons:commons-compress:1.28.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath +org.apache.commons:commons-lang3:3.20.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,checkstyle,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,spotbugs,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.apache.commons:commons-text:1.15.0=spotbugs org.apache.commons:commons-text:1.3=checkstyle org.apache.groovy:groovy-bom:5.0.8=architectureTestCompileClasspath,integrationTestCompileClasspath,systemTestCompileClasspath,testCompileClasspath org.apache.groovy:groovy:5.0.8=architectureTestCompileClasspath,integrationTestCompileClasspath,systemTestCompileClasspath,testCompileClasspath -org.apache.httpcomponents.client5:httpclient5:5.5.2=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -org.apache.httpcomponents.core5:httpcore5-h2:5.3.6=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -org.apache.httpcomponents.core5:httpcore5:5.3.6=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -org.apache.httpcomponents:httpclient:4.5.13=checkstyle,integrationTestRuntimeClasspath -org.apache.httpcomponents:httpcore:4.4.16=checkstyle,integrationTestRuntimeClasspath -org.apache.kafka:kafka-clients:4.1.2=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -org.apache.logging.log4j:log4j-api:2.25.5=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,spotbugs,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.apache.httpcomponents.client5:httpclient5:5.5.2=architectureTestRuntimeClasspath,qualificationRuntimeClasspath +org.apache.httpcomponents.core5:httpcore5-h2:5.3.6=architectureTestRuntimeClasspath,qualificationRuntimeClasspath +org.apache.httpcomponents.core5:httpcore5:5.3.6=architectureTestRuntimeClasspath,qualificationRuntimeClasspath +org.apache.httpcomponents:httpclient:4.5.13=architectureTestRuntimeClasspath,checkstyle,integrationTestRuntimeClasspath,qualificationRuntimeClasspath +org.apache.httpcomponents:httpcore:4.4.16=architectureTestRuntimeClasspath,checkstyle,integrationTestRuntimeClasspath,qualificationRuntimeClasspath +org.apache.kafka:kafka-clients:4.1.2=architectureTestCompileClasspath,architectureTestRuntimeClasspath,qualificationRuntimeClasspath +org.apache.logging.log4j:log4j-api:2.25.5=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,spotbugs,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.apache.logging.log4j:log4j-core:2.25.5=spotbugs -org.apache.logging.log4j:log4j-to-slf4j:2.25.5=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.apache.logging.log4j:log4j-to-slf4j:2.25.5=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.apache.maven.doxia:doxia-core:1.12.0=checkstyle 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.tomcat.embed:tomcat-embed-core:11.0.24=architectureTestCompileClasspath,architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.apache.tomcat.embed:tomcat-embed-el:11.0.24=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.apache.tomcat.embed:tomcat-embed-websocket:11.0.24=architectureTestCompileClasspath,architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.apache.tomcat.embed:tomcat-embed-core:11.0.24=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.apache.tomcat.embed:tomcat-embed-el:11.0.24=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.apache.tomcat.embed:tomcat-embed-websocket:11.0.24=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.apache.xbean:xbean-reflect:3.7=checkstyle org.apiguardian:apiguardian-api:1.1.2=architectureTestCompileClasspath,conditionalTransportBuildContractTestCompileClasspath,integrationTestCompileClasspath,systemTestCompileClasspath,testCompileClasspath -org.aspectj:aspectjweaver:1.9.25.1=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.aspectj:aspectjweaver:1.9.25.1=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath org.assertj:assertj-core:3.27.7=architectureTestCompileClasspath,architectureTestRuntimeClasspath,conditionalTransportBuildContractTestCompileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.attoparser:attoparser:2.0.7.RELEASE=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath +org.attoparser:attoparser:2.0.7.RELEASE=architectureTestRuntimeClasspath,qualificationRuntimeClasspath org.awaitility:awaitility:4.3.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.checkerframework:checker-qual:3.42.0=conditionalTransportBuildContractTestRuntimeClasspath -org.checkerframework:checker-qual:3.55.1=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -org.codehaus.mojo:animal-sniffer-annotations:1.24=conditionalTransportBuildContractTestRuntimeClasspath +org.checkerframework:checker-qual:3.55.1=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,testRuntimeClasspath +org.codehaus.mojo:animal-sniffer-annotations:1.24=architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,qualificationRuntimeClasspath 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.3.0=checkstyle org.dom4j:dom4j:2.2.0=spotbugs -org.eclipse.angus:angus-activation:2.0.3=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -org.eclipse.angus:angus-mail:2.0.5=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -org.flywaydb:flyway-core:11.14.1=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.flywaydb:flyway-database-postgresql:11.14.1=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -org.glassfish.jaxb:jaxb-core:4.0.9=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -org.glassfish.jaxb:jaxb-runtime:4.0.9=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -org.glassfish.jaxb:txw2:4.0.9=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath +org.eclipse.angus:angus-activation:2.0.3=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,testRuntimeClasspath +org.eclipse.angus:angus-mail:2.0.5=architectureTestRuntimeClasspath,qualificationRuntimeClasspath +org.flywaydb:flyway-core:11.14.1=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath +org.flywaydb:flyway-database-postgresql:11.14.1=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,testRuntimeClasspath +org.glassfish.jaxb:jaxb-core:4.0.9=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,testRuntimeClasspath +org.glassfish.jaxb:jaxb-runtime:4.0.9=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,testRuntimeClasspath +org.glassfish.jaxb:txw2:4.0.9=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,testRuntimeClasspath org.hamcrest:hamcrest:3.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.hdrhistogram:HdrHistogram:2.2.2=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -org.hibernate.models:hibernate-models:1.0.1=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -org.hibernate.orm:hibernate-core:7.2.24.Final=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.hibernate.orm:hibernate-envers:7.2.24.Final=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -org.hibernate.validator:hibernate-validator:9.0.1.Final=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.hdrhistogram:HdrHistogram:2.2.2=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath +org.hibernate.models:hibernate-models:1.0.1=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,testRuntimeClasspath +org.hibernate.orm:hibernate-core:7.2.24.Final=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath +org.hibernate.orm:hibernate-envers:7.2.24.Final=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,testRuntimeClasspath +org.hibernate.validator:hibernate-validator:9.0.1.Final=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.javassist:javassist:3.28.0-GA=checkstyle -org.javassist:javassist:3.29.0-GA=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -org.jboss.logging:jboss-logging:3.6.3.Final=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.jetbrains.kotlin:kotlin-stdlib:2.2.21=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -org.jetbrains:annotations:13.0=productionRuntimeClasspath,runtimeClasspath -org.jetbrains:annotations:17.0.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.jspecify:jspecify:1.0.1=annotationProcessor,architectureTestAnnotationProcessor,architectureTestCompileClasspath,architectureTestRuntimeClasspath,checkstyle,compileClasspath,conditionalTransportBuildContractTestAnnotationProcessor,conditionalTransportBuildContractTestCompileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestAnnotationProcessor,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestAnnotationProcessor,systemTestCompileClasspath,systemTestRuntimeClasspath,testAnnotationProcessor,testCompileClasspath,testRuntimeClasspath +org.javassist:javassist:3.29.0-GA=architectureTestRuntimeClasspath,qualificationRuntimeClasspath +org.jboss.logging:jboss-logging:3.6.3.Final=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.jetbrains.kotlin:kotlin-stdlib:2.2.21=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath +org.jetbrains:annotations:13.0=bootRunH2Classpath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath +org.jetbrains:annotations:17.0.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath +org.jspecify:jspecify:1.0.1=annotationProcessor,architectureTestAnnotationProcessor,architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,checkstyle,compileClasspath,conditionalTransportBuildContractTestAnnotationProcessor,conditionalTransportBuildContractTestCompileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestAnnotationProcessor,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestAnnotationProcessor,systemTestCompileClasspath,systemTestRuntimeClasspath,testAnnotationProcessor,testCompileClasspath,testRuntimeClasspath org.junit.jupiter:junit-jupiter-api:6.0.3=architectureTestCompileClasspath,architectureTestRuntimeClasspath,conditionalTransportBuildContractTestCompileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.junit.jupiter:junit-jupiter-engine:6.0.3=architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestRuntimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath org.junit.jupiter:junit-jupiter-params:6.0.3=architectureTestCompileClasspath,architectureTestRuntimeClasspath,conditionalTransportBuildContractTestCompileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath @@ -252,18 +250,18 @@ org.junit.jupiter:junit-jupiter:6.0.3=architectureTestCompileClasspath,architect org.junit.platform:junit-platform-commons:6.0.3=architectureTestCompileClasspath,architectureTestRuntimeClasspath,conditionalTransportBuildContractTestCompileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.junit.platform:junit-platform-engine:6.0.3=architectureTestCompileClasspath,architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.junit.platform:junit-platform-launcher:6.0.3=architectureTestCompileClasspath,architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.junit.platform:junit-platform-testkit:6.0.3=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.junit.platform:junit-platform-testkit:6.0.3=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath org.junit:junit-bom:6.0.3=architectureTestCompileClasspath,architectureTestRuntimeClasspath,conditionalTransportBuildContractTestCompileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.junit:junit-bom:6.1.0=spotbugs -org.latencyutils:LatencyUtils:2.0.3=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath +org.latencyutils:LatencyUtils:2.0.3=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath org.mockito:mockito-core:5.20.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,mockitoAgent,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.mockito:mockito-junit-jupiter:5.20.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.mongodb:bson-record-codec:5.6.5=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -org.mongodb:bson:5.6.5=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -org.mongodb:mongodb-driver-core:5.6.5=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -org.mongodb:mongodb-driver-sync:5.6.5=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath +org.mongodb:bson-record-codec:5.6.5=architectureTestRuntimeClasspath,qualificationRuntimeClasspath +org.mongodb:bson:5.6.5=architectureTestRuntimeClasspath,qualificationRuntimeClasspath +org.mongodb:mongodb-driver-core:5.6.5=architectureTestRuntimeClasspath,qualificationRuntimeClasspath +org.mongodb:mongodb-driver-sync:5.6.5=architectureTestRuntimeClasspath,qualificationRuntimeClasspath org.objenesis:objenesis:3.3=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -org.openapitools:jackson-databind-nullable:0.2.6=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath +org.openapitools:jackson-databind-nullable:0.2.6=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath org.opentest4j:opentest4j:1.3.0=architectureTestCompileClasspath,architectureTestRuntimeClasspath,conditionalTransportBuildContractTestCompileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.osgi:org.osgi.annotation.bundle:2.0.0=architectureTestCompileClasspath,compileClasspath,integrationTestCompileClasspath,systemTestCompileClasspath,testCompileClasspath org.osgi:org.osgi.annotation.versioning:1.1.2=architectureTestCompileClasspath,compileClasspath,integrationTestCompileClasspath,systemTestCompileClasspath,testCompileClasspath @@ -274,160 +272,160 @@ 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.ow2.asm:asm:9.7.1=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.ow2.asm:asm:9.7.1=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.pcollections:pcollections:4.0.1=annotationProcessor,architectureTestAnnotationProcessor,conditionalTransportBuildContractTestAnnotationProcessor,integrationTestAnnotationProcessor,systemTestAnnotationProcessor,testAnnotationProcessor -org.postgresql:postgresql:42.7.13=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -org.reactivestreams:reactive-streams:1.0.4=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.postgresql:postgresql:42.7.13=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,testRuntimeClasspath +org.reactivestreams:reactive-streams:1.0.4=architectureTestRuntimeClasspath,bootRunH2Classpath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,testRuntimeClasspath org.reflections:reflections:0.10.2=checkstyle -org.rnorth.duct-tape:duct-tape:1.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.rnorth.duct-tape:duct-tape:1.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath org.skyscreamer:jsonassert:1.5.3=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.slf4j:jul-to-slf4j:2.0.18=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.slf4j:slf4j-api:2.0.18=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,spotbugs,spotbugsSlf4j,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.slf4j:jul-to-slf4j:2.0.18=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.slf4j:slf4j-api:2.0.18=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,spotbugs,spotbugsSlf4j,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j org.slf4j:slf4j-simple:2.0.18=checkstyle -org.springdoc:springdoc-openapi-starter-common:3.0.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -org.springdoc:springdoc-openapi-starter-webmvc-api:3.0.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-actuator-autoconfigure:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-actuator:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-autoconfigure:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springdoc:springdoc-openapi-starter-common:3.0.0=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath +org.springdoc:springdoc-openapi-starter-webmvc-api:3.0.0=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-actuator-autoconfigure:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-actuator:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-autoconfigure:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-configuration-processor:4.0.8=annotationProcessor -org.springframework.boot:spring-boot-data-commons:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-data-jpa-test:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-data-jpa:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-data-mongodb:4.0.8=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-flyway:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-graphql:4.0.8=architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-health:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-hibernate:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-http-converter:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-jackson:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-jdbc-test:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-jdbc:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-jpa-test:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-jpa:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-mail:4.0.8=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-micrometer-metrics:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-micrometer-observation:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-mongodb:4.0.8=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-persistence:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-reactor:4.0.8=architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-resttestclient:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-security-oauth2-resource-server:4.0.8=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-security:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-servlet:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-sql:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-starter-actuator:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-starter-data-jpa:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-starter-data-mongodb:4.0.8=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-starter-flyway:4.0.8=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-starter-graphql:4.0.8=architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-starter-jackson-test:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-starter-jackson:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-starter-jdbc:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-starter-json:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-starter-logging:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-starter-mail:4.0.8=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-starter-micrometer-metrics:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-starter-mongodb:4.0.8=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-starter-oauth2-resource-server:4.0.8=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-starter-security:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-data-commons:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-data-jpa-test:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-data-jpa:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-data-mongodb:4.0.8=architectureTestRuntimeClasspath,qualificationRuntimeClasspath +org.springframework.boot:spring-boot-flyway:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-graphql:4.0.8=architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,qualificationRuntimeClasspath +org.springframework.boot:spring-boot-health:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-hibernate:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-http-converter:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-jackson:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-jdbc-test:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-jdbc:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-jpa-test:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-jpa:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-mail:4.0.8=architectureTestRuntimeClasspath,qualificationRuntimeClasspath +org.springframework.boot:spring-boot-micrometer-metrics:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-micrometer-observation:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-mongodb:4.0.8=architectureTestRuntimeClasspath,qualificationRuntimeClasspath +org.springframework.boot:spring-boot-persistence:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-reactor:4.0.8=architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,qualificationRuntimeClasspath +org.springframework.boot:spring-boot-resttestclient:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-security-oauth2-resource-server:4.0.8=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-security:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-servlet:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-sql:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-actuator:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-data-jpa:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-data-mongodb:4.0.8=architectureTestRuntimeClasspath,qualificationRuntimeClasspath +org.springframework.boot:spring-boot-starter-flyway:4.0.8=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-graphql:4.0.8=architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,qualificationRuntimeClasspath +org.springframework.boot:spring-boot-starter-jackson-test:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-jackson:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-jdbc:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-json:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-logging:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-mail:4.0.8=architectureTestRuntimeClasspath,qualificationRuntimeClasspath +org.springframework.boot:spring-boot-starter-micrometer-metrics:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-mongodb:4.0.8=architectureTestRuntimeClasspath,qualificationRuntimeClasspath +org.springframework.boot:spring-boot-starter-oauth2-resource-server:4.0.8=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-security:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-starter-test:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-starter-tomcat-runtime:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-starter-tomcat:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-starter-validation:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-starter-web:4.0.8=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-starter-webmvc-test:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-starter-webmvc:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-starter-websocket:4.0.8=conditionalTransportBuildContractTestRuntimeClasspath -org.springframework.boot:spring-boot-starter:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-tomcat-runtime:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-tomcat:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-validation:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-web:4.0.8=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-webmvc-test:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-webmvc:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-websocket:4.0.8=architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,qualificationRuntimeClasspath +org.springframework.boot:spring-boot-starter:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-test-autoconfigure:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-test:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-tomcat:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-transaction:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-validation:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-web-server:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-webmvc-test:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-webmvc:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-websocket:4.0.8=conditionalTransportBuildContractTestRuntimeClasspath -org.springframework.boot:spring-boot:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-tomcat:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-transaction:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-validation:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-web-server:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-webmvc-test:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-webmvc:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-websocket:4.0.8=architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,qualificationRuntimeClasspath +org.springframework.boot:spring-boot:4.0.8=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework.cloud:spring-cloud-context:4.1.4=architectureTestCompileClasspath,integrationTestCompileClasspath,systemTestCompileClasspath,testCompileClasspath -org.springframework.data:spring-data-commons:4.0.7=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.data:spring-data-jpa:4.0.7=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.data:spring-data-mongodb:5.0.7=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -org.springframework.graphql:spring-graphql:2.0.5=architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -org.springframework.integration:spring-integration-core:7.0.6=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -org.springframework.integration:spring-integration-jdbc:7.0.6=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -org.springframework.security:spring-security-config:7.0.7=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.security:spring-security-core:7.0.7=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.security:spring-security-crypto:7.0.7=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.security:spring-security-oauth2-client:7.0.7=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.security:spring-security-oauth2-core:7.0.7=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.security:spring-security-oauth2-jose:7.0.7=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -org.springframework.security:spring-security-oauth2-resource-server:7.0.7=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -org.springframework.security:spring-security-test:7.0.7=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.security:spring-security-web:7.0.7=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.session:spring-session-core:4.0.5=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -org.springframework:spring-aop:7.0.9=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-aspects:7.0.9=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-beans:7.0.9=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-context-support:7.0.9=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -org.springframework:spring-context:7.0.9=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-core:7.0.9=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-expression:7.0.9=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-jdbc:7.0.9=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-messaging:7.0.9=architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -org.springframework:spring-orm:7.0.9=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.data:spring-data-commons:4.0.7=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.data:spring-data-jpa:4.0.7=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.data:spring-data-mongodb:5.0.7=architectureTestRuntimeClasspath,qualificationRuntimeClasspath +org.springframework.graphql:spring-graphql:2.0.5=architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,qualificationRuntimeClasspath +org.springframework.integration:spring-integration-core:7.0.6=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,testRuntimeClasspath +org.springframework.integration:spring-integration-jdbc:7.0.6=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,testRuntimeClasspath +org.springframework.security:spring-security-config:7.0.7=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.security:spring-security-core:7.0.7=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.security:spring-security-crypto:7.0.7=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.security:spring-security-oauth2-client:7.0.7=architectureTestRuntimeClasspath,qualificationRuntimeClasspath +org.springframework.security:spring-security-oauth2-core:7.0.7=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath +org.springframework.security:spring-security-oauth2-jose:7.0.7=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath +org.springframework.security:spring-security-oauth2-resource-server:7.0.7=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath +org.springframework.security:spring-security-test:7.0.7=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.security:spring-security-web:7.0.7=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.session:spring-session-core:4.0.5=architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath +org.springframework:spring-aop:7.0.9=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-aspects:7.0.9=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-beans:7.0.9=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-context-support:7.0.9=architectureTestRuntimeClasspath,qualificationRuntimeClasspath +org.springframework:spring-context:7.0.9=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-core:7.0.9=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-expression:7.0.9=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-jdbc:7.0.9=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-messaging:7.0.9=architectureTestRuntimeClasspath,bootRunH2Classpath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,testRuntimeClasspath +org.springframework:spring-orm:7.0.9=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath org.springframework:spring-test:7.0.9=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-tx:7.0.9=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-web:7.0.9=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-webflux:7.0.9=architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -org.springframework:spring-webmvc:7.0.9=architectureTestCompileClasspath,architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-websocket:7.0.9=architectureTestCompileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,systemTestCompileClasspath,testCompileClasspath -org.testcontainers:testcontainers-database-commons:2.0.5=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.testcontainers:testcontainers-jdbc:2.0.5=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.testcontainers:testcontainers-junit-jupiter:2.0.5=architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -org.testcontainers:testcontainers-postgresql:2.0.5=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.testcontainers:testcontainers-toxiproxy:2.0.5=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -org.testcontainers:testcontainers:2.0.5=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.thymeleaf:thymeleaf:3.1.5.RELEASE=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -org.unbescape:unbescape:1.1.6.RELEASE=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -org.xerial.snappy:snappy-java:1.1.10.7=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath +org.springframework:spring-tx:7.0.9=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-web:7.0.9=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-webflux:7.0.9=architectureTestRuntimeClasspath,qualificationRuntimeClasspath +org.springframework:spring-webmvc:7.0.9=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-websocket:7.0.9=architectureTestCompileClasspath,architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,qualificationRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath +org.testcontainers:testcontainers-database-commons:2.0.5=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath +org.testcontainers:testcontainers-jdbc:2.0.5=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath +org.testcontainers:testcontainers-junit-jupiter:2.0.5=architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,testRuntimeClasspath +org.testcontainers:testcontainers-postgresql:2.0.5=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath +org.testcontainers:testcontainers-toxiproxy:2.0.5=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,testRuntimeClasspath +org.testcontainers:testcontainers:2.0.5=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath +org.thymeleaf:thymeleaf:3.1.5.RELEASE=architectureTestRuntimeClasspath,qualificationRuntimeClasspath +org.unbescape:unbescape:1.1.6.RELEASE=architectureTestRuntimeClasspath,qualificationRuntimeClasspath +org.xerial.snappy:snappy-java:1.1.10.7=architectureTestRuntimeClasspath,qualificationRuntimeClasspath org.xmlresolver:xmlresolver:5.3.3=checkstyle,spotbugs org.xmlunit:xmlunit-core:2.10.4=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.yaml:snakeyaml:2.5=architectureTestCompileClasspath,architectureTestRuntimeClasspath,compileClasspath,conditionalTransportBuildContractTestCompileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -redis.clients.authentication:redis-authx-core:0.1.1-beta2=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath -software.amazon.awssdk:annotations:2.30.0=integrationTestRuntimeClasspath -software.amazon.awssdk:apache-client:2.30.0=integrationTestRuntimeClasspath -software.amazon.awssdk:arns:2.30.0=integrationTestRuntimeClasspath -software.amazon.awssdk:auth:2.30.0=integrationTestRuntimeClasspath -software.amazon.awssdk:aws-core:2.30.0=integrationTestRuntimeClasspath -software.amazon.awssdk:aws-query-protocol:2.30.0=integrationTestRuntimeClasspath -software.amazon.awssdk:aws-xml-protocol:2.30.0=integrationTestRuntimeClasspath +org.yaml:snakeyaml:2.5=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,conditionalTransportBuildContractTestCompileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +redis.clients.authentication:redis-authx-core:0.1.1-beta2=architectureTestRuntimeClasspath,qualificationRuntimeClasspath +software.amazon.awssdk:annotations:2.30.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath +software.amazon.awssdk:apache-client:2.30.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath +software.amazon.awssdk:arns:2.30.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath +software.amazon.awssdk:auth:2.30.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath +software.amazon.awssdk:aws-core:2.30.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath +software.amazon.awssdk:aws-query-protocol:2.30.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath +software.amazon.awssdk:aws-xml-protocol:2.30.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath software.amazon.awssdk:bom:2.30.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath -software.amazon.awssdk:checksums-spi:2.30.0=integrationTestRuntimeClasspath -software.amazon.awssdk:checksums:2.30.0=integrationTestRuntimeClasspath -software.amazon.awssdk:crt-core:2.30.0=integrationTestRuntimeClasspath -software.amazon.awssdk:endpoints-spi:2.30.0=integrationTestRuntimeClasspath -software.amazon.awssdk:http-auth-aws-eventstream:2.30.0=integrationTestRuntimeClasspath -software.amazon.awssdk:http-auth-aws:2.30.0=integrationTestRuntimeClasspath -software.amazon.awssdk:http-auth-spi:2.30.0=integrationTestRuntimeClasspath -software.amazon.awssdk:http-auth:2.30.0=integrationTestRuntimeClasspath -software.amazon.awssdk:http-client-spi:2.30.0=integrationTestRuntimeClasspath -software.amazon.awssdk:identity-spi:2.30.0=integrationTestRuntimeClasspath -software.amazon.awssdk:json-utils:2.30.0=integrationTestRuntimeClasspath -software.amazon.awssdk:metrics-spi:2.30.0=integrationTestRuntimeClasspath -software.amazon.awssdk:netty-nio-client:2.30.0=integrationTestRuntimeClasspath -software.amazon.awssdk:profiles:2.30.0=integrationTestRuntimeClasspath -software.amazon.awssdk:protocol-core:2.30.0=integrationTestRuntimeClasspath -software.amazon.awssdk:regions:2.30.0=integrationTestRuntimeClasspath -software.amazon.awssdk:retries-spi:2.30.0=integrationTestRuntimeClasspath -software.amazon.awssdk:retries:2.30.0=integrationTestRuntimeClasspath -software.amazon.awssdk:s3:2.30.0=integrationTestRuntimeClasspath -software.amazon.awssdk:sdk-core:2.30.0=integrationTestRuntimeClasspath -software.amazon.awssdk:third-party-jackson-core:2.30.0=integrationTestRuntimeClasspath -software.amazon.awssdk:utils:2.30.0=integrationTestRuntimeClasspath -software.amazon.eventstream:eventstream:1.0.1=integrationTestRuntimeClasspath -tools.jackson.core:jackson-core:3.1.5=architectureTestCompileClasspath,architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -tools.jackson.core:jackson-databind:3.1.5=architectureTestCompileClasspath,architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -tools.jackson:jackson-bom:3.1.5=architectureTestCompileClasspath,architectureTestRuntimeClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +software.amazon.awssdk:checksums-spi:2.30.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath +software.amazon.awssdk:checksums:2.30.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath +software.amazon.awssdk:crt-core:2.30.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath +software.amazon.awssdk:endpoints-spi:2.30.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath +software.amazon.awssdk:http-auth-aws-eventstream:2.30.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath +software.amazon.awssdk:http-auth-aws:2.30.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath +software.amazon.awssdk:http-auth-spi:2.30.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath +software.amazon.awssdk:http-auth:2.30.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath +software.amazon.awssdk:http-client-spi:2.30.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath +software.amazon.awssdk:identity-spi:2.30.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath +software.amazon.awssdk:json-utils:2.30.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath +software.amazon.awssdk:metrics-spi:2.30.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath +software.amazon.awssdk:netty-nio-client:2.30.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath +software.amazon.awssdk:profiles:2.30.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath +software.amazon.awssdk:protocol-core:2.30.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath +software.amazon.awssdk:regions:2.30.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath +software.amazon.awssdk:retries-spi:2.30.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath +software.amazon.awssdk:retries:2.30.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath +software.amazon.awssdk:s3:2.30.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath +software.amazon.awssdk:sdk-core:2.30.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath +software.amazon.awssdk:third-party-jackson-core:2.30.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath +software.amazon.awssdk:utils:2.30.0=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath +software.amazon.eventstream:eventstream:1.0.1=architectureTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath +tools.jackson.core:jackson-core:3.1.5=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +tools.jackson.core:jackson-databind:3.1.5=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +tools.jackson:jackson-bom:3.1.5=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath empty=developmentOnly,testAndDevelopmentOnly diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/AdapterBoundaryArchitectureTest.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/AdapterBoundaryArchitectureTest.java index 7949b51e..149dc310 100644 --- a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/AdapterBoundaryArchitectureTest.java +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/AdapterBoundaryArchitectureTest.java @@ -104,12 +104,14 @@ class AdapterBoundaryArchitectureTest { .or( JavaClass.Predicates.resideInAPackage("..adapter.outbound..") .and( - JavaClass.Predicates.resideOutsideOfPackage( - "..adapter.outbound.persistence..")))) + JavaClass.Predicates.resideOutsideOfPackages( + "..adapter.outbound.persistence..", + "..adapter.outbound.support..")))) .as( "persistence-jpa is an internal (driven) outbound adapter — it must not reach into " + "the web adapter, sibling outbound adapters, or the composition root " - + "(intra-persistence references are allowed).") + + "(intra-persistence references and the registered adapter:outbound:support " + + "base — typed startup failures, the module-defaults loader — are allowed).") .allowEmptyShould(true); // ---- persistence-rdbms/no-sql-extensibility (RDBMS base vendor-neutrality) ---- @@ -478,20 +480,15 @@ class AdapterBoundaryArchitectureTest { "observation", "policy", "provider", - "push", "security", "template")), Map.entry("contact", Set.of("api")), - Map.entry("email", Set.of("api")), Map.entry("inbox", Set.of("api")), Map.entry("observation", Set.of("api")), Map.entry("policy", Set.of("api", "contact", "provider")), Map.entry("provider", Set.of("api", "callback", "security", "template")), - Map.entry("push", Set.of("api")), Map.entry("security", Set.of("api", "contact")), - Map.entry("sms", Set.of("api", "contact")), - Map.entry("template", Set.of("api")), - Map.entry("webpush", Set.of("api"))); + Map.entry("template", Set.of("api"))); private static final String NOTIFICATION_PLATFORM_ROOT = "dev.caskeleton.application.notification.platform"; diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ApplicationBoundaryArchitectureTest.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ApplicationBoundaryArchitectureTest.java index c968fc01..04627d67 100644 --- a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ApplicationBoundaryArchitectureTest.java +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ApplicationBoundaryArchitectureTest.java @@ -1,6 +1,5 @@ package dev.caskeleton.bootstrap.architecture; -import static com.tngtech.archunit.core.domain.properties.HasName.Predicates.name; import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes; import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.methods; import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses; @@ -93,41 +92,6 @@ class ApplicationBoundaryArchitectureTest { + "outbox status models mean opposite things under the same names") .allowEmptyShould(true); - /** - * The two notification models must not learn about each other. - * - *

NOTIF-ADR-005 makes the platform canonical and keeps R1's hundred public types in place - * without new consumers. Nothing enforced that: {@code Channel}, plan, dispatch and - * receipt/evidence exist in both namespaces with the same simple names, so a new consumer picks - * one by import order and the two models drift apart while both claim to be current. - * - *

The exception is a single compatibility package. If a bridge is ever needed it goes there, - * and only there — an exception in several places is not an exception, it is the second canonical - * model the ADR exists to prevent. - */ - @ArchTest - static final ArchRule NOTIFICATION_R1_AND_PLATFORM_DO_NOT_DEPEND_ON_EACH_OTHER = - noClasses() - .that() - .resideInAPackage("dev.caskeleton.application.notification.platform..") - .and() - .resideOutsideOfPackage("dev.caskeleton.application.notification.compatibility.r1..") - .should() - .dependOnClassesThat( - new com.tngtech.archunit.base.DescribedPredicate<>( - "reside in the R1 notification namespace") { - @Override - public boolean test(com.tngtech.archunit.core.domain.JavaClass candidate) { - String name = candidate.getPackageName(); - return name.equals("dev.caskeleton.application.notification"); - } - }) - .because( - "NOTIFICATION_R1_AND_PLATFORM_DO_NOT_DEPEND_ON_EACH_OTHER: NOTIF-ADR-005 makes the " - + "platform canonical; a bridge belongs in " - + "dev.caskeleton.application.notification.compatibility.r1 and nowhere else") - .allowEmptyShould(true); - /** * An orchestration entrypoint, recognised by what it does rather than by what it implements. * diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ArchRuleDiscoveryContractTest.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ArchRuleDiscoveryContractTest.java index 496720a5..8569a0f3 100644 --- a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ArchRuleDiscoveryContractTest.java +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ArchRuleDiscoveryContractTest.java @@ -126,7 +126,6 @@ class ArchRuleDiscoveryContractTest { "NOTIFICATION_CONTRACT_HAS_NO_DIAGNOSTIC_FRAMEWORK", "NOTIFICATION_PLATFORM_PACKAGES_ARE_ACYCLIC", "NOTIFICATION_PLATFORM_PACKAGE_EDGES_ARE_REGISTERED", - "NOTIFICATION_R1_AND_PLATFORM_DO_NOT_DEPEND_ON_EACH_OTHER", "NO_BIGDECIMAL_DOUBLE_CONSTRUCTOR", "NO_INHERITABLE_THREAD_LOCAL", "NO_JACKSON_ENABLE_DEFAULT_TYPING_CALL", diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/CompositionRootBoundaryArchitectureTest.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/CompositionRootBoundaryArchitectureTest.java index a4ac3204..9d0b2ab3 100644 --- a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/CompositionRootBoundaryArchitectureTest.java +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/CompositionRootBoundaryArchitectureTest.java @@ -2,7 +2,6 @@ package dev.caskeleton.bootstrap.architecture; import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses; -import com.tngtech.archunit.base.DescribedPredicate; import com.tngtech.archunit.core.domain.JavaClass; import com.tngtech.archunit.junit.AnalyzeClasses; import com.tngtech.archunit.junit.ArchTest; @@ -33,43 +32,22 @@ import com.tngtech.archunit.lang.ArchRule; * *

Secret resolution now follows the same boundary. {@code SecretSourcePort} is application-owned * and the Spring Environment implementation lives in {@code adapter:outbound:support}; bootstrap - * selects that implementation but does not implement the port. The explicit decorator allowlist - * below is therefore the only production exception to this rule. + * selects that implementation but does not implement the port. + * + *

The rule has no exceptions any more. Its one allowlisted class, the metering decorator {@code + * MeteredDistributedLockPort}, moved to {@code adapter:outbound:persistence-jpa} with the JDBC lock + * it decorates. */ @AnalyzeClasses( packages = "dev.caskeleton.bootstrap", importOptions = ProductionClassImportOption.class) class CompositionRootBoundaryArchitectureTest { - /** - * {@code MeteredDistributedLockPort} — a decorator, not an adapter. - * - *

It implements {@code DistributedLockPort} in order to wrap another implementation of it with - * metering, and "which ports are metered" is an assembly decision, which is this leaf's job. The - * argument on the other side is real — metering is a cross-cutting concern like retry or caching, - * and those collecting here is how a composition root becomes large again — so the threshold is - * stated rather than left to taste: at the second such decorator, they move to {@code - * adapter:outbound:support} together. One is a special case; two is a category. - */ - private static final String METERED_DISTRIBUTED_LOCK_PORT = - "dev.caskeleton.bootstrap.autoconfigure.lock.MeteredDistributedLockPort"; - - private static final DescribedPredicate ALLOWLISTED = - new DescribedPredicate<>("allowlisted from the composition-root boundary") { - @Override - public boolean test(JavaClass candidate) { - String name = candidate.getFullName(); - return name.equals(METERED_DISTRIBUTED_LOCK_PORT) - || name.startsWith(METERED_DISTRIBUTED_LOCK_PORT + "$"); - } - }; - @ArchTest static final ArchRule COMPOSITION_ROOT_DOES_NOT_IMPLEMENT_APPLICATION_OR_DOMAIN_PORTS = noClasses() .that() .resideInAPackage("dev.caskeleton.bootstrap..") - .and(DescribedPredicate.not(ALLOWLISTED)) .should() .implement( JavaClass.Predicates.resideInAnyPackage( diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ForbiddenApiArchitectureTest.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ForbiddenApiArchitectureTest.java index a0ba4d69..dd043c55 100644 --- a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ForbiddenApiArchitectureTest.java +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ForbiddenApiArchitectureTest.java @@ -67,12 +67,6 @@ class ForbiddenApiArchitectureTest { // tenancy.shared package of its own and only began tripping this rule when that leaf // joined the composition root's analysis scope. "dev.caskeleton.adapter.outbound.mongo.advanced.tenancy.shared", - // The registered master switches and their strict parse. Operational rather than - // domain: - // it names environment keys and rejects unreadable values, and it lives here because - // the environment post-processor needs it before a Spring context exists, so it must - // not depend on Spring. - "dev.caskeleton.shared.activation", // feature-authentication-authorization-contract: the Permission // (resource:action) value object is a Java-only operational // authorization contract consumed by AuthorizationPort. @@ -566,16 +560,21 @@ class ForbiddenApiArchitectureTest { noClasses() .that() .resideInAPackage("dev.caskeleton..") + // The WebSocket capability leaf is the one module whose job this is. It entered this + // import when the suite started seeing every module rather than the default composition. + .and() + .resideOutsideOfPackage("dev.caskeleton.adapter.inbound.websocket..") .should() .dependOnClassesThat() .resideInAnyPackage("org.springframework.web.socket..", "jakarta.websocket..") .as( - "D3 NO_WEBSOCKET_HANDLER: production code must not depend on " + "D3 NO_WEBSOCKET_HANDLER: production code outside the WebSocket capability leaf " + + "(adapter.inbound.websocket) must not depend on " + "org.springframework.web.socket.. or jakarta.websocket.. — " + "these cover the spring-websocket handler/STOMP surfaces and " + "Jakarta @ServerEndpoint (RFC 6455 full-duplex WebSocket model). " - + "Full-duplex streaming is not supported in ca-skeleton " - + "(feature-streaming-response-contract D3). Production code is " + + "Full-duplex streaming belongs to that selectable capability, not to the web " + + "platform (feature-streaming-response-contract D3). Production code is " + "scanned only under ImportOption.DoNotIncludeTests.") .allowEmptyShould(true); diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/GraphQlInboundOwnershipBoundaryTest.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/GraphQlInboundOwnershipBoundaryTest.java index fdefbc4d..fe6a59a5 100644 --- a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/GraphQlInboundOwnershipBoundaryTest.java +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/GraphQlInboundOwnershipBoundaryTest.java @@ -35,15 +35,15 @@ import org.junit.jupiter.api.Test; class GraphQlInboundOwnershipBoundaryTest { /** Inbound-owned types that no other leaf may name. */ - private static final List INBOUND_OWNED = - List.of("GraphQlPersistedOperationRegistry", "GraphQlRequestContext"); + // GraphQlPersistedOperationRegistry left this list when advanced/persisted was deleted + // (2026-09-25): an SPI with no implementation anywhere is not a boundary worth guarding. + private static final List INBOUND_OWNED = List.of("GraphQlRequestContext"); /** The one place they belong: the GraphQL adapter's own production sources. */ private static final String GRAPHQL_SOURCE = "/src/adapter/inbound/graphql/src/main/java/"; @Test - @DisplayName( - "no leaf outside the GraphQL adapter names its context or its persisted-operation SPI") + @DisplayName("no leaf outside the GraphQL adapter names its request context") void inboundOwnedTypesStayInsideTheLeaf() { List violations = new ArrayList<>(); diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/StartupFailureContractArchitectureTest.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/StartupFailureContractArchitectureTest.java index 5658228c..9d70fd14 100644 --- a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/StartupFailureContractArchitectureTest.java +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/StartupFailureContractArchitectureTest.java @@ -12,6 +12,11 @@ import java.util.List; /** * The composition root's startup failures must carry an exit code (BOOT-003). * + *

The failure machinery ({@code StartupFailures}, {@code StartupErrorCode}) lives in {@code + * adapter:outbound:support} now, so capability modules can raise it without depending on the + * composition root; the rule covers the composition root and the startup guards that moved with + * their capability. + * *

{@code StartupErrorCode} classifies a failed start into four causes and gives each one a * sysexits exit status — 78 for a configuration error, 70 for a failed migration, 71 for a profile * conflict, 72 for a required adapter that is off. That status only reaches the JVM because {@code @@ -43,7 +48,13 @@ import java.util.List; * with a reviewer attached. */ @AnalyzeClasses( - packages = "dev.caskeleton.bootstrap", + packages = { + "dev.caskeleton.bootstrap", + // The startup guards that moved out of the composition root keep the same contract: the + // relational ones live with persistence-jpa, the failure machinery with the support leaf. + "dev.caskeleton.adapter.outbound.persistence.startup", + "dev.caskeleton.adapter.outbound.support.startup" + }, importOptions = ProductionClassImportOption.class) class StartupFailureContractArchitectureTest { @@ -77,7 +88,7 @@ class StartupFailureContractArchitectureTest { * require. */ private static final String STARTUP_FAILURES = - "dev.caskeleton.bootstrap.runtime.startup.StartupFailures"; + "dev.caskeleton.adapter.outbound.support.startup.StartupFailures"; /** * {@code StartupFailureException} — the typed base class. Its constructor delegates to {@code @@ -87,7 +98,7 @@ class StartupFailureContractArchitectureTest { * passing across this migration. */ private static final String STARTUP_FAILURE_EXCEPTION = - "dev.caskeleton.bootstrap.runtime.startup.StartupFailureException"; + "dev.caskeleton.adapter.outbound.support.startup.StartupFailureException"; /** * Matched by prefix rather than exact name, so a nested type is covered by its outer class's @@ -116,7 +127,10 @@ class StartupFailureContractArchitectureTest { static final ArchRule STARTUP_FAILURES_ARE_RAISED_THROUGH_THE_TYPED_FACTORY = noClasses() .that() - .resideInAPackage("dev.caskeleton.bootstrap..") + .resideInAnyPackage( + "dev.caskeleton.bootstrap..", + "dev.caskeleton.adapter.outbound.persistence.startup..", + "dev.caskeleton.adapter.outbound.support.startup..") .and(DescribedPredicate.not(ALLOWLISTED)) .should() .callConstructor(IllegalStateException.class, String.class) diff --git a/src/app-bootstrap/src/conditionalTransportBuildContractTest/java/dev/caskeleton/bootstrap/transport/ConditionalTransportBuildContractTest.java b/src/app-bootstrap/src/conditionalTransportBuildContractTest/java/dev/caskeleton/bootstrap/transport/ConditionalTransportBuildContractTest.java index 6b3b8d5f..09ef449a 100644 --- a/src/app-bootstrap/src/conditionalTransportBuildContractTest/java/dev/caskeleton/bootstrap/transport/ConditionalTransportBuildContractTest.java +++ b/src/app-bootstrap/src/conditionalTransportBuildContractTest/java/dev/caskeleton/bootstrap/transport/ConditionalTransportBuildContractTest.java @@ -3,107 +3,104 @@ package dev.caskeleton.bootstrap.transport; import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.List; import java.util.Map; import java.util.regex.Pattern; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; /** - * Conditional transports are verified against the real composition root, not a duplicate registry - * membership list. Build-only transports must be absent from app-bootstrap dependencies; GraphQL is - * shipped deliberately and is controlled by its master switch. Runtime behavior is proven by the - * named compose qualification lanes. + * The optional inbound transports are capabilities a service selects with one line. + * + *

Each one is absent from the default composition, offered in {@code app-bootstrap/build.gradle} + * as one commented {@code runtimeOnly} line, and — on this qualification classpath, which selects + * all three — registered by its own {@code AutoConfiguration.imports}, so uncommenting the line is + * the whole act of turning it on. */ class ConditionalTransportBuildContractTest { - /** Transports that must not reach any runtime: no membership, and no composition-root edge. */ - private static final Map BUILD_ONLY_TRANSPORTS = + private static final String IMPORTS = + "META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports"; + + /** Gradle path to the auto-configuration the module registers for itself. */ + private static final Map TRANSPORTS = Map.of( - "adapter-inbound-grpc", + ":adapter:inbound:graphql", + "dev.caskeleton.adapter.inbound.graphql.autoconfigure.GraphQlRootAutoConfiguration", + ":adapter:inbound:grpc", "dev.caskeleton.adapter.inbound.grpc.GrpcServerConfig", - "adapter-inbound-websocket", + ":adapter:inbound:websocket", "dev.caskeleton.adapter.inbound.websocket.stomp.WebSocketConfig"); - /** Transports that ship on the one bootJar and are decided by a master switch. */ - private static final Map SWITCH_GATED_TRANSPORTS = - Map.of( - "adapter-inbound-graphql", - "dev.caskeleton.adapter.inbound.graphql.HealthGraphqlController"); - @Test - @DisplayName("build-only transports are absent from the production composition") - void buildOnlyTransportsAreAbsentFromProductionComposition() throws IOException { - String bootstrapBuild = - Files.readString(repositoryRoot().resolve("src/app-bootstrap/build.gradle")); - BUILD_ONLY_TRANSPORTS.forEach( - (moduleId, typeName) -> { - String gradlePath = - switch (moduleId) { - case "adapter-inbound-grpc" -> ":adapter:inbound:grpc"; - case "adapter-inbound-websocket" -> ":adapter:inbound:websocket"; - default -> throw new IllegalArgumentException(moduleId); - }; - assertThat(productionProjectDependency(bootstrapBuild, gradlePath)) - .as("%s is qualification-only and must not ship in app-bootstrap", moduleId) - .isFalse(); - assertThatCodeLoads(typeName); - }); + @DisplayName("no optional transport ships in the default composition") + void noOptionalTransportShipsInTheDefaultComposition() throws IOException { + String bootstrapBuild = bootstrapBuild(); + + TRANSPORTS + .keySet() + .forEach( + gradlePath -> + assertThat(productionProjectDependency(bootstrapBuild, gradlePath)) + .as( + "%s is a capability a service selects; it must not ship by default", + gradlePath) + .isFalse()); } @Test - @DisplayName("GraphQL is a real composition dependency and its master switch decides activation") - void switchGatedTransportIsARealDependencyWithASwitch() throws IOException { - String bootstrapBuild = - Files.readString(repositoryRoot().resolve("src/app-bootstrap/build.gradle")); - assertThat(bootstrapBuild).contains("project(':adapter:inbound:graphql')"); - SWITCH_GATED_TRANSPORTS - .values() - .forEach(ConditionalTransportBuildContractTest::assertThatCodeLoads); - assertThat(shippedApplicationYaml()).contains("classpath:config/graphql.yml"); - assertThat(shippedGraphQlYaml()) - .contains("${APP_GRAPHQL_ENABLED:false}") - .contains("${APP_GRAPHQL_DEPLOYMENT_MODE:}") - .contains("${APP_GRAPHQL_EXECUTION_PROFILE:BLOCKING_MVC}") - .contains("${APP_GRAPHQL_VALIDATION_POLICY_VERSION:v1}") - .contains("${APP_GRAPHQL_OBSERVED_OPERATION_NAMES:}") - .contains("${APP_GRAPHQL_GRAPHIQL_ENABLED:false}") - .contains("${APP_GRAPHQL_INTROSPECTION_ENABLED:false}") - .contains("${APP_GRAPHQL_MAXIMUM_PAGE_SIZE:100}") - .contains("${APP_GRAPHQL_MAXIMUM_COMPLEXITY:10000}") - .contains("${APP_GRAPHQL_PREPARSED_CACHE_ENTRIES:1000}") - .contains("${APP_GRAPHQL_PREPARSED_CACHE_WEIGHT:10000000}") - .contains("${APP_GRAPHQL_PREPARSED_CACHE_EXPIRE_AFTER_ACCESS:30m}") - .doesNotContain("APP_GRAPHQL_CURSOR_KEY_IDS"); + @DisplayName("each transport is offered as one commented runtimeOnly line") + void eachTransportIsOfferedAsOneLine() throws IOException { + String bootstrapBuild = bootstrapBuild(); + + TRANSPORTS + .keySet() + .forEach( + gradlePath -> + assertThat(bootstrapBuild) + .as("uncommenting one line is how a service selects %s", gradlePath) + .contains("// runtimeOnly project('" + gradlePath + "')")); } @Test - @DisplayName("the off-state evidence this contract relies on is named, not assumed") - void theOffStateEvidenceIsNamed() throws IOException { - String lanes = - Files.readString( - repositoryRoot().resolve("src/config/runtime/compose-profile-contracts.json")); + @DisplayName("each transport registers itself, so the one line is enough") + void eachTransportRegistersItsOwnAutoConfiguration() throws IOException { + List registered = registeredAutoConfigurations(); - assertThat(lanes) - .as( - "a switch-gated transport's real proof is a running application with the switch off and" - + " the route absent; this file is where those lanes are declared, and they are " - + "blocking") - .contains("\"off-local\"") - .contains("\"off-dev\"") - .contains("\"off-prod\"") - .contains("\"local-graphql\""); + assertThat(registered).containsAll(TRANSPORTS.values()); + for (String root : TRANSPORTS.values()) { + try { + assertThat(Class.forName(root)).isNotNull(); + } catch (ClassNotFoundException missing) { + throw new AssertionError("missing opt-in transport type " + root, missing); + } + } } - private static String shippedApplicationYaml() throws IOException { - return Files.readString( - repositoryRoot().resolve("src/app-bootstrap/src/main/resources/application.yml")); + private static List registeredAutoConfigurations() throws IOException { + List names = new ArrayList<>(); + Enumeration files = + ConditionalTransportBuildContractTest.class.getClassLoader().getResources(IMPORTS); + while (files.hasMoreElements()) { + try (InputStream in = files.nextElement().openStream()) { + new String(in.readAllBytes(), StandardCharsets.UTF_8) + .lines() + .map(String::trim) + .filter(line -> !line.isEmpty() && !line.startsWith("#")) + .forEach(names::add); + } + } + return names; } - private static String shippedGraphQlYaml() throws IOException { - return Files.readString( - repositoryRoot().resolve("src/app-bootstrap/src/main/resources/config/graphql.yml")); + private static String bootstrapBuild() throws IOException { + return Files.readString(repositoryRoot().resolve("src/app-bootstrap/build.gradle")); } private static boolean productionProjectDependency(String buildScript, String gradlePath) { @@ -116,14 +113,6 @@ class ConditionalTransportBuildContractTest { return productionDependency.matcher(buildScript).find(); } - private static void assertThatCodeLoads(String typeName) { - try { - assertThat(Class.forName(typeName)).isNotNull(); - } catch (ClassNotFoundException exception) { - throw new AssertionError("missing opt-in qualification type " + typeName, exception); - } - } - private static Path repositoryRoot() { Path candidate = Path.of("").toAbsolutePath(); while (candidate != null diff --git a/src/app-bootstrap/src/integrationTest/java/dev/caskeleton/bootstrap/integration/fileserver/FileserverCompositionIntegrationTest.java b/src/app-bootstrap/src/integrationTest/java/dev/caskeleton/bootstrap/integration/fileserver/FileserverCompositionIntegrationTest.java index 1b9aaf58..f30da0cf 100644 --- a/src/app-bootstrap/src/integrationTest/java/dev/caskeleton/bootstrap/integration/fileserver/FileserverCompositionIntegrationTest.java +++ b/src/app-bootstrap/src/integrationTest/java/dev/caskeleton/bootstrap/integration/fileserver/FileserverCompositionIntegrationTest.java @@ -99,6 +99,8 @@ import tools.jackson.databind.ObjectMapper; "spring.jpa.open-in-view=false", "spring.jpa.hibernate.ddl-auto=none", "app.fileserver-platform.enabled=true", + // The lane also selects object storage, which is on when present; this test is not about it. + "app.object-storage.enabled=false", "app.fileserver-platform.instance-id=round-trip-node", "app.fileserver-platform.security.access-policy=role-based", // Metrics are a separate concern with their own tests; leaving them off keeps a MeterRegistry @@ -406,7 +408,11 @@ class FileserverCompositionIntegrationTest { * Fileserver failure. */ @SpringBootConfiguration - @EnableAutoConfiguration + // The web adapter publishes its own auto-configuration (security, envelope, principal + // pseudonymization); the Fileserver routes under test are reached through MockMvc without it. + @EnableAutoConfiguration( + excludeName = + "dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebAdapterAutoConfiguration") @ComponentScan( basePackages = { "dev.caskeleton.adapter.inbound.web.fileserver", diff --git a/src/app-bootstrap/src/integrationTest/java/dev/caskeleton/bootstrap/integration/idempotency/PostgreSqlIdempotencyProviderIntegrationTest.java b/src/app-bootstrap/src/integrationTest/java/dev/caskeleton/bootstrap/integration/idempotency/PostgreSqlIdempotencyProviderIntegrationTest.java new file mode 100644 index 00000000..1bf2dab4 --- /dev/null +++ b/src/app-bootstrap/src/integrationTest/java/dev/caskeleton/bootstrap/integration/idempotency/PostgreSqlIdempotencyProviderIntegrationTest.java @@ -0,0 +1,120 @@ +package dev.caskeleton.bootstrap.integration.idempotency; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.application.idempotency.IdempotencyExecutor; +import dev.caskeleton.application.idempotency.IdempotencyScopeDigest; +import dev.caskeleton.application.idempotency.IdempotentAction; +import dev.caskeleton.application.idempotency.IdempotentResponseCodec; +import dev.caskeleton.application.idempotency.RequestFingerprint; +import dev.caskeleton.application.transaction.OperationId; +import dev.caskeleton.bootstrap.autoconfigure.idempotency.IdempotencyProviderSelectionConfig; +import dev.caskeleton.bootstrap.integration.PostgreSqlTestContainer; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.UnaryOperator; +import org.junit.jupiter.api.Test; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.flyway.autoconfigure.FlywayAutoConfiguration; +import org.springframework.boot.jdbc.autoconfigure.DataSourceAutoConfiguration; +import org.springframework.boot.jdbc.autoconfigure.DataSourceTransactionManagerAutoConfiguration; +import org.springframework.boot.jdbc.autoconfigure.JdbcTemplateAutoConfiguration; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import org.testcontainers.postgresql.PostgreSQLContainer; + +/** + * {@code provider=postgresql} on a fresh PostgreSQL works with no operator step. + * + *

The primary Flyway applies {@code db/migration/postgresql} only, as the shipped composition + * configures it. The owner-safe columns and the capability registry row live in the {@code + * jpa/core} and {@code jpa/idempotency} streams, which only the provider itself applies. Without + * that, the store fails closed on the first request and the capability is "selected" but unusable. + */ +@Testcontainers +class PostgreSqlIdempotencyProviderIntegrationTest { + + private static final String POSTGRESQL_STORE_CONFIG = + "dev.caskeleton.adapter.outbound.persistence.autoconfigure.PostgreSqlIdempotencyStoreConfig"; + + private static final IdempotencyScopeDigest SCOPE = + new IdempotencyScopeDigest("b".repeat(64), 1, "CREATE_WORK_LOG"); + private static final RequestFingerprint FINGERPRINT = + RequestFingerprint.ofSha256("request".getBytes(StandardCharsets.UTF_8)); + private static final IdempotentResponseCodec CODEC = + new IdempotentResponseCodec<>() { + @Override + public String serialize(String result) { + return result; + } + + @Override + public String deserialize(String payload) { + return payload; + } + }; + + @Container static final PostgreSQLContainer PG = PostgreSqlTestContainer.create(); + + @Test + void secondCallWithTheSameKeyReplaysTheStoredResponseOnAFreshDatabase() throws Exception { + // given + AtomicInteger executions = new AtomicInteger(); + + // when + List responses = runTwiceWithOneKey(executions); + + // then + assertThat(List.of(responses.get(0), responses.get(1), executions.get())) + .containsExactly("work-log-1", "work-log-1", 1); + } + + private List runTwiceWithOneKey(AtomicInteger executions) throws Exception { + String[] responses = new String[2]; + runner() + .run( + context -> { + assertThat(context).hasNotFailed(); + IdempotencyExecutor executor = context.getBean(IdempotencyExecutor.class); + TransactionTemplate transactions = + new TransactionTemplate(context.getBean(PlatformTransactionManager.class)); + UnaryOperator call = + operation -> + transactions.execute( + status -> + executor.execute( + SCOPE, + FINGERPRINT, + executor.newAttempt(new OperationId(operation)), + () -> + new IdempotentAction.Outcome.Success<>( + "work-log-" + executions.incrementAndGet()), + CODEC)); + responses[0] = call.apply("first-request"); + responses[1] = call.apply("second-request"); + }); + return List.of(responses); + } + + private static ApplicationContextRunner runner() throws ClassNotFoundException { + return new ApplicationContextRunner() + .withConfiguration( + AutoConfigurations.of( + DataSourceAutoConfiguration.class, + JdbcTemplateAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class, + FlywayAutoConfiguration.class, + IdempotencyProviderSelectionConfig.class)) + .withUserConfiguration(Class.forName(POSTGRESQL_STORE_CONFIG)) + .withPropertyValues( + "ca-skeleton.capabilities.idempotency.provider=postgresql", + "spring.datasource.url=" + PG.getJdbcUrl(), + "spring.datasource.username=" + PG.getUsername(), + "spring.datasource.password=" + PG.getPassword(), + "spring.flyway.locations=classpath:db/migration/postgresql"); + } +} diff --git a/src/app-bootstrap/src/integrationTest/java/dev/caskeleton/bootstrap/integration/objectstorage/ObjectStorageCompositionIntegrationTest.java b/src/app-bootstrap/src/integrationTest/java/dev/caskeleton/bootstrap/integration/objectstorage/ObjectStorageCompositionIntegrationTest.java index db61e106..186fc604 100644 --- a/src/app-bootstrap/src/integrationTest/java/dev/caskeleton/bootstrap/integration/objectstorage/ObjectStorageCompositionIntegrationTest.java +++ b/src/app-bootstrap/src/integrationTest/java/dev/caskeleton/bootstrap/integration/objectstorage/ObjectStorageCompositionIntegrationTest.java @@ -30,7 +30,10 @@ import org.testcontainers.utility.DockerImageName; classes = ObjectStorageCompositionIntegrationTest.ObjectStorageRuntime.class, properties = { "spring.config.name=object-storage-composition", + "ca-skeleton.persistence-jpa.enabled=false", "spring.main.banner-mode=off", + // The lane also selects Fileserver, which is on when present; this test is not about it. + "app.fileserver-platform.enabled=false", "app.object-storage.enabled=false", "app.object-storage.legacy.enabled=true", "app.object-storage.legacy.backend=s3", @@ -84,7 +87,18 @@ class ObjectStorageCompositionIntegrationTest { } @SpringBootConfiguration - @EnableAutoConfiguration + // Data-less: this lane's classpath carries persistence-jpa for the relational lanes beside it, + // and a module on the classpath is on, so the relational stack is excluded here. + @EnableAutoConfiguration( + excludeName = { + "org.springframework.boot.jdbc.autoconfigure.DataSourceAutoConfiguration", + "org.springframework.boot.jdbc.autoconfigure.DataSourceTransactionManagerAutoConfiguration", + "org.springframework.boot.hibernate.autoconfigure.HibernateJpaAutoConfiguration", + "org.springframework.boot.data.jpa.autoconfigure.DataJpaRepositoriesAutoConfiguration", + "org.springframework.boot.flyway.autoconfigure.FlywayAutoConfiguration", + // Web publishes its own auto-configuration; this test drives the port, not HTTP. + "dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebAdapterAutoConfiguration" + }) @Import(ObjectStorageCapabilityConfig.class) static class ObjectStorageRuntime {} } diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/CaSkeletonApplication.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/CaSkeletonApplication.java index 07e26c0e..41a3e140 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/CaSkeletonApplication.java +++ b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/CaSkeletonApplication.java @@ -1,121 +1,32 @@ package dev.caskeleton.bootstrap; import org.springframework.boot.SpringApplication; -import org.springframework.boot.SpringBootConfiguration; -import org.springframework.boot.autoconfigure.AutoConfigurationExcludeFilter; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.context.TypeExcludeFilter; +import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.ConfigurationPropertiesScan; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.FilterType; /** * Composition root. * - *

Spelled out as {@code @SpringBootConfiguration} + {@code @EnableAutoConfiguration} + - * {@code @ComponentScan} rather than {@code @SpringBootApplication}, because the scan needs an - * exclusion the composed annotation cannot express. The two custom filters below are the ones - * {@code @SpringBootApplication} contributes and must stay. + *

The component scan covers this package only. Every module on the classpath registers its own + * beans and settings through its {@code AutoConfiguration.imports}, so adding a capability is one + * build line and removing it is deleting that line — nothing here names a module. * - *

Both scans stop at the same boundary, by different means. The component scan excludes the - * auto-configured packages with a regex filter; {@code @ConfigurationPropertiesScan} has no {@code - * excludeFilters} attribute, so it names the packages it does scan instead. The asymmetry that - * existed before — beans gated, settings not — is why a notification settings object bound itself - * in a deployment whose notification master was off. A capability whose beans are gated but whose - * settings still bind is gated only where somebody remembered to gate it. - * - *

The five optional adapters are absent from the list below on purpose. Each one\'s settings are - * registered by its capability root through {@code @EnableConfigurationProperties}, which is what - * ties binding to the master switch. Adding a package back here would restore the binding and - * silently undo the gate. - * - *

The third exclusion is what makes an optional capability optional. Configuration classes under - * {@code bootstrap.autoconfigure} are reachable only through their own auto-configuration entry, - * which carries the capability's master switch; leaving them inside the broad scan would let the - * component scanner discover each child configuration on its own and assemble the capability - * whatever that switch said. Registering them as auto-configuration instead makes "off" a - * structural fact rather than a condition every future bean has to remember to repeat. + *

{@code @ConfigurationPropertiesScan} names the bootstrap packages whose settings are always + * bound. {@code bootstrap.autoconfigure} is left out on purpose: each auto-configuration there + * binds its own settings with {@code @EnableConfigurationProperties}, so a root whose condition is + * off binds nothing. */ -@SpringBootConfiguration -@EnableAutoConfiguration -@ComponentScan( - basePackages = { - "dev.caskeleton.bootstrap", - "dev.caskeleton.adapter", - "dev.caskeleton.application", - "dev.caskeleton.domain", - "dev.caskeleton.shared" - }, - excludeFilters = { - @ComponentScan.Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class), - @ComponentScan.Filter( - type = FilterType.CUSTOM, - classes = AutoConfigurationExcludeFilter.class), - @ComponentScan.Filter( - type = FilterType.REGEX, - pattern = CaSkeletonApplication.AUTO_CONFIGURED_PACKAGES) - }) +@SpringBootApplication @ConfigurationPropertiesScan( basePackages = { "dev.caskeleton.bootstrap.async", "dev.caskeleton.bootstrap.concurrency", "dev.caskeleton.bootstrap.runtime", "dev.caskeleton.bootstrap.security", - "dev.caskeleton.bootstrap.settings", - "dev.caskeleton.adapter.inbound.web", - // Not the whole redis tree. `...cache.redis.capability` holds RedisCapabilitySettings, which - // the capability's own gated root binds with @EnableConfigurationProperties; scanning it here - // bound the settings while every switch was off, which is the one thing the off-state - // contract forbids — and the shipped-composition test caught it by name the moment the - // capability moved into this package. - "dev.caskeleton.adapter.outbound.cache.redis.sdk", - "dev.caskeleton.adapter.outbound.objectstorage", - "dev.caskeleton.application", - "dev.caskeleton.domain", - "dev.caskeleton.shared" + "dev.caskeleton.bootstrap.settings" }) public class CaSkeletonApplication { - /** - * Packages owned by an auto-configuration entry rather than by the component scan. - * - *

A package prefix rather than a class list: a new configuration added to an optional - * capability must not become active merely because nobody remembered to exclude it. - * - *

The Fileserver admin package is here for a different reason: those routes belong to the - * management context, and a component scan that also found them would publish the management - * plane on the public connector — the exposure the separate context exists to remove. - * - *

The web platform's error, budget and operation packages are here for a third reason. Their - * advices and controllers need beans that only exist when the corresponding platform - * auto-configuration is active, and a component scan finds them regardless — so an all-off or - * partially configured deployment failed to start on an unsatisfied dependency rather than simply - * not installing the control. Ownership by auto-configuration is what ties a control's presence - * to its dependency's. - */ - static final String AUTO_CONFIGURED_PACKAGES = - "dev\\.caskeleton\\.bootstrap\\.autoconfigure\\..*" - + "|dev\\.caskeleton\\.bootstrap\\.notification\\..*" - + "|dev\\.caskeleton\\.adapter\\.inbound\\.web\\.fileserver\\.admin\\..*" - + "|dev\\.caskeleton\\.adapter\\.outbound\\.fileserver\\.platform\\.autoconfigure\\..*" - // Capability composition modules. They are never in `basePackages`, so the scan - // cannot reach them anyway — named here because the parity test asks the regex, - // not the scan, whether an imported child could ever be found twice. - + "|dev\\.caskeleton\\.composition\\..*" - + "|dev\\.caskeleton\\.adapter\\.outbound\\.cache\\.redis\\.capability\\..*" - + "|dev\\.caskeleton\\.adapter\\.outbound\\.httpclient\\.autoconfigure\\..*" - + "|dev\\.caskeleton\\.adapter\\.outbound\\.mongo\\..*" - + "|dev\\.caskeleton\\.adapter\\.outbound\\.messaging\\..*" - + "|dev\\.caskeleton\\.adapter\\.outbound\\.notification\\..*" - + "|dev\\.caskeleton\\.adapter\\.outbound\\.persistence\\..*" - + "|dev\\.caskeleton\\.adapter\\.inbound\\.graphql\\..*" - + "|dev\\.caskeleton\\.adapter\\.inbound\\.web\\.mvc\\.error\\..*" - + "|dev\\.caskeleton\\.adapter\\.inbound\\.web\\.mvc\\.budget\\..*" - + "|dev\\.caskeleton\\.adapter\\.inbound\\.web\\.mvc\\.operation\\..*" - + "|dev\\.caskeleton\\.adapter\\.inbound\\.web\\.webflux\\.error\\..*" - + "|dev\\.caskeleton\\.adapter\\.inbound\\.web\\.webflux\\.operation\\..*" - + "|dev\\.caskeleton\\.messaging\\..*"; - public static void main(String[] args) { SpringApplication.run(CaSkeletonApplication.class, args); } diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/activation/AdapterActivationAutoConfiguration.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/activation/AdapterActivationAutoConfiguration.java deleted file mode 100644 index bf2d4200..00000000 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/activation/AdapterActivationAutoConfiguration.java +++ /dev/null @@ -1,42 +0,0 @@ -package dev.caskeleton.bootstrap.activation; - -import org.springframework.boot.autoconfigure.AutoConfiguration; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.context.annotation.Bean; -import org.springframework.core.env.Environment; - -/** - * Registers the activation checks the composition root owns. - * - *

Unconditional on purpose. The dependency check is most needed precisely when a capability was - * left off — that is the combination it exists to catch — so gating it behind any switch would - * remove it from the deployments it protects. - */ -@AutoConfiguration -public class AdapterActivationAutoConfiguration { - - /** - * The startup check for the active capability graph. - * - * @param environment the resolved environment - * @return the check, which refuses refresh when a dependency is missing - */ - @Bean - @ConditionalOnMissingBean - public CapabilityDependencyStartupCheck capabilityDependencyStartupCheck( - Environment environment) { - return new CapabilityDependencyStartupCheck(environment); - } - - /** - * The endpoint a smoke lane reads to check the application rather than its own input. - * - * @param environment the resolved environment - * @return the read-only activation endpoint - */ - @Bean - @ConditionalOnMissingBean - public AdapterActivationEndpoint adapterActivationEndpoint(Environment environment) { - return new AdapterActivationEndpoint(environment); - } -} diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/activation/AdapterActivationEndpoint.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/activation/AdapterActivationEndpoint.java deleted file mode 100644 index 744e377a..00000000 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/activation/AdapterActivationEndpoint.java +++ /dev/null @@ -1,75 +0,0 @@ -package dev.caskeleton.bootstrap.activation; - -import dev.caskeleton.adapter.outbound.support.runtime.RuntimeProfileSnapshot; -import dev.caskeleton.bootstrap.autoconfigure.jpa.DataSourceRequirement; -import dev.caskeleton.shared.activation.MasterSwitch; -import java.util.LinkedHashMap; -import java.util.Map; -import org.springframework.boot.actuate.endpoint.annotation.Endpoint; -import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; -import org.springframework.core.env.Environment; - -/** - * Serves the resolved activation state so a smoke lane can check the application rather than - * itself. - * - *

Read-only and cheap: it reports what the environment resolved to, and creates nothing. It is - * registered unconditionally because the state it reports is most interesting when everything is - * off — an endpoint that appeared only once a capability was enabled could never confirm that none - * of them were. - */ -@Endpoint(id = "adapteractivation") -public class AdapterActivationEndpoint { - - private final Environment environment; - - /** - * @param environment the resolved environment to report on - */ - public AdapterActivationEndpoint(Environment environment) { - this.environment = environment; - } - - /** - * Returns the resolved activation state. - * - * @return the report - */ - @ReadOperation - public AdapterActivationReport activation() { - Map switches = new LinkedHashMap<>(); - for (MasterSwitch masterSwitch : MasterSwitch.values()) { - switches.put( - masterSwitch.property(), - "true".equalsIgnoreCase(environment.getProperty(masterSwitch.property(), "false"))); - } - var profiles = RuntimeProfileSnapshot.from(environment).activeProfiles(); - return new AdapterActivationReport( - profiles.isEmpty() ? "" : profiles.get(0), - switches, - DataSourceRequirement.reasons(environment), - resolvedVendor()); - } - - /** - * Names the relational vendor this deployment resolved, without naming the database. - * - *

Derived from the JDBC URL's scheme rather than from the vendor selector, because the two can - * disagree and it is the URL that decides where the queries go. This is the value that separates - * "JPA is on" from "JPA is on against the database this deployment started" — a smoke lane that - * starts PostgreSQL while the active profile pins H2 satisfies every other field here. - * - * @return the vendor, or {@code "none"} when nothing requires a connection - */ - private String resolvedVendor() { - if (!DataSourceRequirement.isRequired(environment)) { - return "none"; - } - String url = environment.getProperty("spring.datasource.url", ""); - if (!url.startsWith("jdbc:")) { - return "unknown"; - } - int schemeEnd = url.indexOf(':', "jdbc:".length()); - return schemeEnd > 0 ? url.substring("jdbc:".length(), schemeEnd) : "unknown"; - } -} diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/activation/AdapterActivationReport.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/activation/AdapterActivationReport.java deleted file mode 100644 index 6f35140f..00000000 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/activation/AdapterActivationReport.java +++ /dev/null @@ -1,34 +0,0 @@ -package dev.caskeleton.bootstrap.activation; - -import java.util.List; -import java.util.Map; - -/** - * What this deployment actually turned on, as it resolved rather than as it was configured. - * - *

A smoke lane that asserts on the environment it passed in is asserting on its own input. This - * is the application's answer: the profile it settled on, the state each master switch parsed to, - * and which capabilities are asking for a relational connection. A lane claiming "all five off" is - * checked against this, not against the flags it set. - * - * @param activeProfile the single resolved runtime environment - * @param switches each master switch's canonical property to its resolved state - * @param dataSourceRequiredBy capabilities that need a relational connection; empty when none does - * @param persistenceVendor the resolved relational vendor, or {@code "none"} when none is required. - * A vendor name rather than a URL, so the report still carries no address — and it is the value - * that separates "JPA is on" from "JPA is on against the database this deployment started". A - * lane that starts PostgreSQL while the profile pins H2 passes every other check in this - * report. - */ -public record AdapterActivationReport( - String activeProfile, - Map switches, - List dataSourceRequiredBy, - String persistenceVendor) { - - /** Defensive copies: this is served over HTTP and read by evidence collectors. */ - public AdapterActivationReport { - switches = Map.copyOf(switches); - dataSourceRequiredBy = List.copyOf(dataSourceRequiredBy); - } -} diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/activation/CapabilityDependencyEnvironmentValidator.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/activation/CapabilityDependencyEnvironmentValidator.java deleted file mode 100644 index 6942e7c6..00000000 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/activation/CapabilityDependencyEnvironmentValidator.java +++ /dev/null @@ -1,50 +0,0 @@ -package dev.caskeleton.bootstrap.activation; - -import dev.caskeleton.bootstrap.runtime.startup.StartupOrder; -import org.springframework.boot.EnvironmentPostProcessor; -import org.springframework.boot.SpringApplication; -import org.springframework.core.Ordered; -import org.springframework.core.env.ConfigurableEnvironment; - -/** - * Refuses an inconsistent capability graph before the context exists. - * - *

{@link CapabilityDependencyStartupCheck} already ran this rule, as an {@code - * InitializingBean}, on the stated grounds that refreshing beans is early enough — "before a - * scheduler has claimed a row or a pool has opened a connection". It is not, and the case that - * shows it is the one the rule cares most about. - * - *

Turning the outbox on without the JPA switch is a dependency error this repository names - * explicitly. But the outbox is also a registered relational consumer, so {@link - * DataSourceRequirement} reports that a pool is required, {@code - * JpaOffAutoConfigurationImportFilter} therefore keeps Boot's relational auto-configurations in the - * candidate set, and Hibernate and Flyway are instantiated during refresh — ahead of any {@code - * InitializingBean} of ours. What the operator saw was: - * - *

- *   Unable to obtain connection from database: Connection to localhost:5433 refused.
- * 
- * - *

That is the "go and read the logs" failure the named-switch message exists to replace, and it - * arrived first every time. The two components are each right on their own — a pool does have - * consumers besides JPA, and the outbox does need the JPA switch — and the disagreement was only - * visible in which one spoke first. - * - *

So the check moves to the environment stage, where every property source is resolved and - * nothing has been instantiated. The bean stays as well: a context assembled without {@code - * spring.factories} — an {@code ApplicationContextRunner}, a slice test — never reaches this class, - * and the rule should not be optional there. - */ -public class CapabilityDependencyEnvironmentValidator implements EnvironmentPostProcessor, Ordered { - - @Override - public void postProcessEnvironment( - ConfigurableEnvironment environment, SpringApplication application) { - CapabilityDependencyValidator.requireSatisfied(environment); - } - - @Override - public int getOrder() { - return StartupOrder.CAPABILITY_DEPENDENCY; - } -} diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/activation/CapabilityDependencyStartupCheck.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/activation/CapabilityDependencyStartupCheck.java deleted file mode 100644 index 198bbcf2..00000000 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/activation/CapabilityDependencyStartupCheck.java +++ /dev/null @@ -1,27 +0,0 @@ -package dev.caskeleton.bootstrap.activation; - -import org.springframework.beans.factory.InitializingBean; -import org.springframework.core.env.Environment; - -/** - * Runs {@link CapabilityDependencyValidator} at context refresh and stops a startup that fails it. - * - *

An {@code InitializingBean} rather than a listener, so the refusal happens while the context - * is still assembling — before a scheduler has claimed a row or a pool has opened a connection. - */ -public class CapabilityDependencyStartupCheck implements InitializingBean { - - private final Environment environment; - - /** - * @param environment the resolved environment to validate - */ - public CapabilityDependencyStartupCheck(Environment environment) { - this.environment = environment; - } - - @Override - public void afterPropertiesSet() { - CapabilityDependencyValidator.requireSatisfied(environment); - } -} diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/activation/CapabilityDependencyValidator.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/activation/CapabilityDependencyValidator.java deleted file mode 100644 index 44a317a6..00000000 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/activation/CapabilityDependencyValidator.java +++ /dev/null @@ -1,199 +0,0 @@ -package dev.caskeleton.bootstrap.activation; - -import dev.caskeleton.adapter.outbound.support.runtime.RuntimeProfileSnapshot; -import dev.caskeleton.bootstrap.runtime.startup.StartupPhase; -import dev.caskeleton.bootstrap.runtime.startup.StartupValidationContext; -import dev.caskeleton.shared.activation.MasterSwitch; -import dev.caskeleton.shared.runtime.RuntimeEnvironment; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import org.springframework.core.env.Environment; - -/** - * Refuses a startup whose capabilities ask for something no switch turned on. - * - *

Every rule here replaces a failure that used to arrive later and read worse. A relay with no - * broker exhausted outbox rows to DEAD one retry budget at a time; a JDBC idempotency store with no - * database failed at the first request that needed a claim; a GraphQL deployment mode that - * disagreed with the runtime environment served production traffic under local safety rules. A - * dependency that is checked at startup is a deployment that does not start; a dependency that is - * checked at first use is an incident. - * - *

Each message names the exact switch or value that is missing. "Misconfiguration" tells an - * operator to go reading; a property name tells them what to set. - */ -public final class CapabilityDependencyValidator { - - /** Which GraphQL deployment modes each runtime environment permits. */ - private static final Map> PERMITTED_GRAPHQL_MODES = - Map.of( - RuntimeEnvironment.LOCAL, Set.of("LOCAL"), - RuntimeEnvironment.DEV, Set.of("DEV"), - RuntimeEnvironment.PROD, Set.of("PRODUCTION_INTERNAL", "PRODUCTION_PUBLIC")); - - private CapabilityDependencyValidator() {} - - /** - * Returns one message per unsatisfied dependency, in declaration order. - * - * @param environment the resolved environment - * @return the violations; empty when the active capability graph is consistent - */ - public static List violations(Environment environment) { - StartupValidationContext violations = - StartupValidationContext.forPhase(StartupPhase.ADAPTER_ENABLEMENT); - - boolean jpa = isOn(environment, MasterSwitch.PERSISTENCE_JPA.property()); - boolean mongo = isOn(environment, MasterSwitch.PERSISTENCE_MONGO.property()); - boolean messaging = isOn(environment, MasterSwitch.MESSAGING.property()); - boolean notification = isOn(environment, MasterSwitch.NOTIFICATION_PLATFORM.property()); - boolean graphQl = isOn(environment, MasterSwitch.GRAPHQL.property()); - boolean outbox = isOn(environment, "ca-skeleton.outbox.enabled"); - boolean relay = isOn(environment, "ca-skeleton.outbox.relay-enabled"); - String broker = environment.getProperty("app.messaging.broker", "").trim(); - - if (outbox && !jpa) { - violations.reject( - "ca-skeleton.outbox.enabled=true needs relational persistence to store rows; set " - + MasterSwitch.PERSISTENCE_JPA.property() - + "=true or turn the outbox off."); - } - // Only a *relaying* outbox needs somewhere to publish. An outbox with the relay off writes rows - // inside the application's own transactions and publishes nothing, which is the configuration - // an - // operator uses to park events until a transport exists — the very state - // OutboxRelayBrokerRequirementValidator documents as one of the two coherent ones. Requiring - // messaging for the capability rather than for the relay contradicted that, and in a - // broker-neutral artifact it made the outbox unreachable: messaging on demands a broker, and a - // broker demands a starter the default composition deliberately does not ship. - if (outbox && relay && !messaging) { - violations.reject( - "ca-skeleton.outbox.relay-enabled=true needs somewhere to publish; set " - + MasterSwitch.MESSAGING.property() - + "=true, or set ca-skeleton.outbox.relay-enabled=false to keep writing rows without" - + " a transport."); - } - if (relay && !outbox) { - violations.reject( - "ca-skeleton.outbox.relay-enabled=true only starts the scheduler for a capability that is " - + "off; set ca-skeleton.outbox.enabled=true or turn the relay off."); - } - if (messaging && broker.isEmpty()) { - violations.reject( - "app.messaging.enabled=true needs a transport; set app.messaging.broker to a registered " - + "broker id."); - } - String idempotencyProvider = - environment.getProperty("ca-skeleton.capabilities.idempotency.provider", "disabled").trim(); - if (("jdbc".equalsIgnoreCase(idempotencyProvider) - || "postgresql".equalsIgnoreCase(idempotencyProvider)) - && !jpa) { - violations.reject( - "ca-skeleton.capabilities.idempotency.provider=" - + idempotencyProvider - + " needs relational persistence; set " - + MasterSwitch.PERSISTENCE_JPA.property() - + "=true or choose another provider."); - } - if (isOn(environment, "ca-skeleton.runtime.multi-instance-enabled") && !jpa) { - violations.reject( - "ca-skeleton.runtime.multi-instance-enabled=true needs a database for the lock registry; set " - + MasterSwitch.PERSISTENCE_JPA.property() - + "=true or turn multi-instance locking off."); - } - if (notification - && !"none" - .equalsIgnoreCase( - environment.getProperty("ca-skeleton.notification.platform.persistence", "jpa")) - && !jpa) { - violations.reject( - MasterSwitch.NOTIFICATION_PLATFORM.property() - + "=true stores requests relationally, and no other store is implemented; set " - + MasterSwitch.PERSISTENCE_JPA.property() - + "=true."); - } - if (mongo) { - String activeMongoProfile = - environment - .getProperty( - MasterSwitch.PERSISTENCE_MONGO.property().replace(".enabled", ".active-profile"), - "") - .trim(); - if (activeMongoProfile.isBlank()) { - violations.reject( - MasterSwitch.PERSISTENCE_MONGO.property() - + "=true needs exactly one profile; set " - + "ca-skeleton.persistence-mongo.active-profile."); - } else { - String standardUri = environment.getProperty("spring.mongodb.uri", "").trim(); - String profileSecretProperty = - "ca-skeleton.persistence-mongo.platform.profiles." + activeMongoProfile + ".uri-secret"; - String profileSecret = environment.getProperty(profileSecretProperty, "").trim(); - if (standardUri.isBlank() && profileSecret.isBlank()) { - violations.reject( - MasterSwitch.PERSISTENCE_MONGO.property() - + "=true has no explicit MongoDB connection source; set spring.mongodb.uri " - + "(SPRING_MONGODB_URI) or " - + profileSecretProperty - + "."); - } - } - } - if (graphQl) { - violations.rejectAll(graphQlModeViolations(environment)); - } - return violations.violations(); - } - - /** - * Rejects the deployment when any capability dependency is unsatisfied. - * - *

Both the EnvironmentPostProcessor path and the bean fallback delegate here, so phase, - * aggregation and operator-facing failure formatting cannot drift between startup entry points. - */ - public static void requireSatisfied(Environment environment) { - StartupValidationContext violations = - StartupValidationContext.forPhase(StartupPhase.ADAPTER_ENABLEMENT) - .rejectAll(violations(environment)); - violations.failIfViolated("This deployment enables capabilities whose dependencies are off"); - } - - private static List graphQlModeViolations(Environment environment) { - String mode = environment.getProperty("backend.graphql.deployment-mode", "").trim(); - if (mode.isEmpty()) { - return List.of( - MasterSwitch.GRAPHQL.property() - + "=true needs an explicit safety posture; set backend.graphql.deployment-mode to one " - + "of LOCAL, DEV, PRODUCTION_INTERNAL, PRODUCTION_PUBLIC."); - } - RuntimeProfileSnapshot profiles = RuntimeProfileSnapshot.from(environment); - List activeProfiles = profiles.activeProfiles(); - RuntimeEnvironment runtime = profiles.resolve().orElse(null); - if (runtime == null) { - return List.of( - "backend.graphql.deployment-mode cannot be checked because the runtime environment '" - + String.join(",", activeProfiles) - + "' is not one of " - + RuntimeEnvironment.deployableProfileNames() - + "."); - } - Set permitted = PERMITTED_GRAPHQL_MODES.get(runtime); - if (!permitted.contains(mode.toUpperCase(Locale.ROOT))) { - return List.of( - "backend.graphql.deployment-mode=" - + mode - + " is not permitted in the " - + runtime.profileName() - + " runtime; permitted here: " - + permitted.stream().sorted().toList() - + "."); - } - return List.of(); - } - - private static boolean isOn(Environment environment, String property) { - return "true".equalsIgnoreCase(environment.getProperty(property, "false")); - } -} diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/activation/MasterSwitchEnvironmentPostProcessor.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/activation/MasterSwitchEnvironmentPostProcessor.java deleted file mode 100644 index 8f59918f..00000000 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/activation/MasterSwitchEnvironmentPostProcessor.java +++ /dev/null @@ -1,73 +0,0 @@ -package dev.caskeleton.bootstrap.activation; - -import dev.caskeleton.bootstrap.runtime.startup.StartupFailures; -import dev.caskeleton.bootstrap.runtime.startup.StartupOrder; -import dev.caskeleton.shared.activation.MasterSwitch; -import dev.caskeleton.shared.activation.MasterSwitchParseResult; -import dev.caskeleton.shared.activation.MasterSwitchParser; -import java.util.LinkedHashMap; -import java.util.Map; -import org.springframework.boot.EnvironmentPostProcessor; -import org.springframework.boot.SpringApplication; -import org.springframework.core.Ordered; -import org.springframework.core.env.ConfigurableEnvironment; - -/** - * Rejects an unreadable master switch before anything binds a detail namespace. - * - *

Reads raw property values rather than binding, deliberately. An adapter that is off has to be - * able to start next to an environment full of its own malformed configuration — a validator that - * bound the namespace to check the switch would fail exactly the deployments the switch exists to - * protect. - * - *

Runs at lowest precedence so profile-specific configuration data has already been contributed; - * a check that ran before it would read {@code application-prod.yml}'s switches as unset. - */ -public class MasterSwitchEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered { - - @Override - public void postProcessEnvironment( - ConfigurableEnvironment environment, SpringApplication application) { - for (MasterSwitch masterSwitch : MasterSwitch.values()) { - Map legacy = new LinkedHashMap<>(); - for (String legacyProperty : masterSwitch.legacyProperties()) { - String value = environment.getProperty(legacyProperty); - if (value != null) { - legacy.put(legacyProperty, value); - } - } - reject( - MasterSwitchParser.parse( - masterSwitch, environment.getProperty(masterSwitch.property()), legacy)); - } - } - - private static void reject(MasterSwitchParseResult result) { - if (result instanceof MasterSwitchParseResult.Invalid invalid) { - throw StartupFailures.envValidation( - ("%s must be exactly true or false, but was \"%s\". A value this close to a boolean is a " - + "deployment that believes it set the switch; it is rejected rather than read as " - + "off.") - .formatted(invalid.owner().property(), invalid.raw())); - } - if (result instanceof MasterSwitchParseResult.Ambiguous ambiguous) { - throw StartupFailures.envValidation( - ("%s and %s are both set. They agree today and diverge the first time somebody edits one " - + "of them; remove %s.") - .formatted( - ambiguous.owner().property(), - ambiguous.legacyProperty(), - ambiguous.legacyProperty())); - } - if (result instanceof MasterSwitchParseResult.LegacyOnly legacy) { - throw StartupFailures.envValidation( - "%s has been replaced by %s. Set the replacement; the old key is no longer read." - .formatted(legacy.legacyProperty(), legacy.replacementProperty())); - } - } - - @Override - public int getOrder() { - return StartupOrder.MASTER_SWITCH_NORMALISATION; - } -} diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/async/AsyncExecutorSettings.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/async/AsyncExecutorSettings.java index 4cf2675b..7375072c 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/async/AsyncExecutorSettings.java +++ b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/async/AsyncExecutorSettings.java @@ -1,6 +1,6 @@ package dev.caskeleton.bootstrap.async; -import dev.caskeleton.bootstrap.runtime.startup.StartupFailures; +import dev.caskeleton.adapter.outbound.support.startup.StartupFailures; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.validation.annotation.Validated; diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/async/BackgroundJobMetrics.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/async/BackgroundJobMetrics.java index bd47d3d2..c8eee3dc 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/async/BackgroundJobMetrics.java +++ b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/async/BackgroundJobMetrics.java @@ -1,6 +1,6 @@ package dev.caskeleton.bootstrap.async; -import dev.caskeleton.bootstrap.runtime.RuntimeWarnings; +import dev.caskeleton.adapter.outbound.support.startup.RuntimeWarnings; import io.micrometer.core.instrument.Counter; import io.micrometer.core.instrument.Gauge; import io.micrometer.core.instrument.MeterRegistry; diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencyComposition.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencyComposition.java deleted file mode 100644 index 3e94322b..00000000 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencyComposition.java +++ /dev/null @@ -1,39 +0,0 @@ -package dev.caskeleton.bootstrap.autoconfigure.idempotency; - -/** - * The bean shape a selected idempotency provider requires the composition root to hold. - * - *

This used to be a {@code switch} in {@code IdempotencyProviderSelectionConfig} — so adding a - * provider meant editing two places, the enum and the switch, and forgetting the second still - * compiled (BOOT-010). Now the requirement is a constructor argument of the enum constant, which - * means it cannot be added without being stated. - * - *

It stays here rather than being contributed by the provider modules. A count of beans in the - * composition root is assembly knowledge: the Redis adapter has no view of how many stores this - * deployment ended up holding, and asking it to declare one would give an adapter an opinion about - * a graph it is only a part of. - * - * @param jdbcStores V1 {@code IdempotencyStorePort} beans expected - * @param jdbcExecutors V1 {@code IdempotencyExecutor} beans expected - * @param ownerSafeStores V2 {@code IdempotencyStorePortV2} beans expected - * @param ownerSafeExecutors V2 {@code IdempotencyExecutorV2} beans expected - */ -record IdempotencyComposition( - int jdbcStores, int jdbcExecutors, int ownerSafeStores, int ownerSafeExecutors) { - - /** - * Redis and PostgreSQL declare the same shape because they satisfy one contract: the count is by - * type, so the guard cannot tell them apart and does not need to. What it refuses is a deployment - * holding two stores, or a store with nothing to drive it, whichever provider produced them. - */ - String describe() { - return jdbcStores - + " JDBC V1 store(s), " - + jdbcExecutors - + " JDBC V1 executor(s), " - + ownerSafeStores - + " owner-safe V2 store(s) and " - + ownerSafeExecutors - + " owner-safe V2 executor(s)"; - } -} diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencyConfig.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencyConfig.java deleted file mode 100644 index c11b647d..00000000 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencyConfig.java +++ /dev/null @@ -1,27 +0,0 @@ -package dev.caskeleton.bootstrap.autoconfigure.idempotency; - -import dev.caskeleton.application.idempotency.IdempotencyExecutor; -import dev.caskeleton.application.idempotency.IdempotencyStorePort; -import java.time.Clock; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.scheduling.annotation.EnableScheduling; - -/** - * Wires idempotency execution. {@code @EnableScheduling} activates the {@code IdempotencyReaper}'s - * scheduled purge. See README for the design rationale. - */ -@Configuration(proxyBeanMethods = false) -@EnableScheduling -@EnableConfigurationProperties(IdempotencySettings.class) -@ConditionalOnProperty(name = "ca-skeleton.capabilities.idempotency.provider", havingValue = "jdbc") -public class IdempotencyConfig { - - @Bean - public IdempotencyExecutor idempotencyExecutor( - IdempotencyStorePort store, Clock clock, IdempotencySettings properties) { - return new IdempotencyExecutor(store, clock, properties.ttl()); - } -} diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencyProviderSelectionConfig.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencyProviderSelectionConfig.java index 1d6b4642..8ef7a06f 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencyProviderSelectionConfig.java +++ b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencyProviderSelectionConfig.java @@ -1,73 +1,56 @@ package dev.caskeleton.bootstrap.autoconfigure.idempotency; +import dev.caskeleton.adapter.outbound.support.startup.StartupFailures; import dev.caskeleton.application.idempotency.IdempotencyExecutor; import dev.caskeleton.application.idempotency.IdempotencyStorePort; -import dev.caskeleton.application.idempotency.v2.IdempotencyExecutorV2; -import dev.caskeleton.application.idempotency.v2.IdempotencyStorePortV2; -import dev.caskeleton.bootstrap.runtime.startup.StartupFailures; +import java.util.List; import org.springframework.beans.factory.ObjectProvider; -import org.springframework.beans.factory.SmartInitializingSingleton; import org.springframework.boot.autoconfigure.AutoConfiguration; +import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Import; /** - * Fail-fast exclusivity guard for the JDBC V1 provider and the two owner-safe V2 providers. + * Assembles the request-idempotency executor, once, for whichever provider is selected. * - *

Redis and PostgreSQL share one expectation because they satisfy one contract: exactly one - * owner-safe store and exactly one executor. The count is by type, so the guard cannot tell them - * apart and does not need to — what it refuses is a deployment holding two stores, or a store with - * nothing to drive it, whichever provider produced them. + *

Providers contribute only an {@link IdempotencyStorePort}: Redis from {@code + * adapter:outbound:cache-redis}, PostgreSQL from {@code adapter:outbound:persistence-jpa}, each + * conditional on {@code ca-skeleton.capabilities.idempotency.provider}. The lifecycle policy — + * lease, replay TTL, retention, codec id, policy revision — is the same whichever store holds the + * records, so it lives in one {@link IdempotencySettings} record and the executor is built here + * from it. * - *

The V2 side counts {@link IdempotencyStorePortV2} from {@code application.idempotency.v2} — - * the contract both owner-safe stores, PostgreSQL and Redis, actually implement. It used to count - * the same-named interface in the parent package, which nothing implements: selecting {@code redis} - * therefore required a bean no provider could supply, and the deployment failed with "ambiguous or - * incomplete" while every configured provider was present and correct. - * - *

It requires a V2 executor alongside the V2 store. A store with nothing to drive it is a - * selection that cannot serve a request, and the executor is the only thing that turns the store's - * claim/start/complete transitions into a request-replay lifecycle. The requirement was dropped - * once, while the only {@code IdempotencyExecutorV2} was written against the unimplemented - * parent-package contract and so could never be composed; that executor now exists in {@code - * application.idempotency.v2} over the contract the stores implement, so the requirement is real - * again rather than a demand nothing could satisfy. + *

A selected provider must yield exactly one store. None means the provider's module is not on + * the runtime classpath or its switch is off; two means something else registered one (a scan-found + * stereotype, a hand-written bean). Either is refused at startup with the count, rather than + * surfacing as an unsatisfied dependency or as requests served by the wrong store. */ @AutoConfiguration -@EnableConfigurationProperties(IdempotencyProviderSettings.class) -@Import({IdempotencyConfig.class, PostgreSqlIdempotencyProviderConfig.class}) +@EnableConfigurationProperties(IdempotencySettings.class) public class IdempotencyProviderSelectionConfig { @Bean - SmartInitializingSingleton idempotencyProviderExclusivity( - IdempotencyProviderSettings settings, - ObjectProvider jdbcStores, - ObjectProvider jdbcExecutors, - ObjectProvider ownerSafeStores, - ObjectProvider ownerSafeExecutors) { - return () -> { - IdempotencyComposition found = - new IdempotencyComposition( - count(jdbcStores), - count(jdbcExecutors), - count(ownerSafeStores), - count(ownerSafeExecutors)); - require(found, settings.provider().composition()); - }; - } - - private static int count(ObjectProvider beans) { - return Math.toIntExact(beans.stream().count()); - } - - private static void require(IdempotencyComposition found, IdempotencyComposition expected) { - if (!found.equals(expected)) { + @ConditionalOnExpression( + "!'${ca-skeleton.capabilities.idempotency.provider:disabled}'.trim()" + + ".equalsIgnoreCase('disabled')") + IdempotencyExecutor idempotencyExecutor( + ObjectProvider stores, IdempotencySettings settings) { + List found = stores.orderedStream().toList(); + if (found.size() != 1) { throw StartupFailures.requiredAdapterDisabled( - "Idempotency provider selection is ambiguous or incomplete: expected " - + expected.describe() - + ", but found " - + found.describe()); + "ca-skeleton.capabilities.idempotency.provider=" + + settings.provider().name().toLowerCase(java.util.Locale.ROOT) + + " needs exactly one IdempotencyStorePort, but found " + + found.size() + + ". Add the provider's module to the runtime classpath and enable it, and make sure" + + " nothing else registers a store."); } + return new IdempotencyExecutor( + found.get(0), + settings.processingLease(), + settings.replayTtl(), + settings.failureRetention(), + settings.responseCodecId(), + settings.policyRevision()); } } diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencyProviderSettings.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencyProviderSettings.java deleted file mode 100644 index fa2b7da5..00000000 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencyProviderSettings.java +++ /dev/null @@ -1,67 +0,0 @@ -package dev.caskeleton.bootstrap.autoconfigure.idempotency; - -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.boot.context.properties.bind.ConstructorBinding; - -/** Exact provider selector; provider precedence is never inferred from the classpath. */ -@ConfigurationProperties(prefix = "ca-skeleton.capabilities.idempotency") -public record IdempotencyProviderSettings(Provider provider) { - - @ConstructorBinding - public IdempotencyProviderSettings { - provider = provider == null ? Provider.DISABLED : provider; - } - - /** - * The stores a deployment may select. - * - *

{@code POSTGRESQL} selects the owner-safe V2 store in the JPA leaf. It had no value here for - * as long as it existed, so the only way to reach it was to construct it in a test: a capability - * with an implementation, a schema stream and an integration suite that no deployment could turn - * on. A store nobody can select is not a feature, and leaving the selector out did not make the - * code any less present in the artifact. - */ - public enum Provider { - - /** Nothing composed — the capability is off. */ - DISABLED(0, 0, 0, 0), - - /** The JDBC V1 store and its executor. */ - JDBC(1, 1, 0, 0), - - /** The owner-safe V2 store and its executor. */ - REDIS(0, 0, 1, 1), - - /** The owner-safe V2 store and its executor — the same contract Redis satisfies. */ - POSTGRESQL(0, 0, 1, 1); - - private final int jdbcStores; - private final int jdbcExecutors; - private final int ownerSafeStores; - private final int ownerSafeExecutors; - - Provider(int jdbcStores, int jdbcExecutors, int ownerSafeStores, int ownerSafeExecutors) { - this.jdbcStores = jdbcStores; - this.jdbcExecutors = jdbcExecutors; - this.ownerSafeStores = ownerSafeStores; - this.ownerSafeExecutors = ownerSafeExecutors; - } - - /** - * The bean shape this provider requires the composition root to hold. - * - *

Carried by the constant rather than decided by a {@code switch} elsewhere, so a fifth - * provider cannot be added without saying what it needs — the compiler asks for the four - * arguments (BOOT-010). - * - *

Held as four ints rather than as a shared {@link IdempotencyComposition} constant because - * Error Prone's {@code ImmutableEnumChecker} refuses a reference field in an enum unless its - * type carries {@code @Immutable}, and that annotation is not a dependency of this build. - * Adding one to satisfy a checker would be a worse trade than four primitives. - */ - IdempotencyComposition composition() { - return new IdempotencyComposition( - jdbcStores, jdbcExecutors, ownerSafeStores, ownerSafeExecutors); - } - } -} diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencySettings.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencySettings.java index fcc771d7..42c58498 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencySettings.java +++ b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencySettings.java @@ -1,37 +1,93 @@ package dev.caskeleton.bootstrap.autoconfigure.idempotency; -import dev.caskeleton.bootstrap.runtime.startup.StartupFailures; +import dev.caskeleton.adapter.outbound.support.startup.StartupFailures; import java.time.Duration; import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.validation.annotation.Validated; /** - * Idempotency runtime knobs. The {@code <= 72h} TTL cap is enforced fail-fast in the compact - * constructor. See README for the design rationale. + * The one settings record for request idempotency, bound at {@code + * ca-skeleton.capabilities.idempotency}. The executor is built from it once, whichever provider + * supplies the store. Every value is checked here, so a bad value fails startup rather than the + * first request. * - * @param ttl default idempotency record TTL (≤ 72h) - * @param reaperInterval how often the expired-record reaper runs + *

The Redis store reads its own two knobs ({@code key-version}, {@code command-timeout}) under + * the same prefix; they are store tuning, not lifecycle policy, so they are not repeated here. + * + * @param provider which store is composed: {@code disabled}, {@code redis} or {@code postgresql} + * @param processingLease how long one attempt holds a claim before another may take it over + * @param replayTtl how long a completed response is replayable (at most 72h, D6) + * @param failureRetention how long a failed attempt's evidence is kept + * @param responseCodecId identifier of the codec the stored payload is written with + * @param policyRevision replay policy revision written into and compared on each record + * @param reaperInterval how often the PostgreSQL provider purges expired rows */ -@Validated -@ConfigurationProperties(prefix = "ca-skeleton.idempotency") -public record IdempotencySettings(Duration ttl, Duration reaperInterval) { +@ConfigurationProperties(prefix = IdempotencySettings.PREFIX) +public record IdempotencySettings( + Provider provider, + Duration processingLease, + Duration replayTtl, + Duration failureRetention, + String responseCodecId, + Integer policyRevision, + Duration reaperInterval) { - private static final Duration MAX_TTL = Duration.ofDays(3); + static final String PREFIX = "ca-skeleton.capabilities.idempotency"; + private static final Duration MAX_PROCESSING_LEASE = Duration.ofHours(1); + private static final Duration MAX_REPLAY_TTL = Duration.ofDays(3); + private static final Duration MAX_FAILURE_RETENTION = Duration.ofDays(30); public IdempotencySettings { - if (ttl == null) { - ttl = Duration.ofHours(24); - } - if (ttl.isZero() || ttl.isNegative()) { + provider = provider == null ? Provider.DISABLED : provider; + processingLease = + bounded( + "processing-lease", + orDefault(processingLease, Duration.ofSeconds(30)), + MAX_PROCESSING_LEASE); + replayTtl = bounded("replay-ttl", orDefault(replayTtl, Duration.ofHours(24)), MAX_REPLAY_TTL); + failureRetention = + bounded( + "failure-retention", + orDefault(failureRetention, Duration.ofHours(24)), + MAX_FAILURE_RETENTION); + reaperInterval = + bounded("reaper-interval", orDefault(reaperInterval, Duration.ofMinutes(10)), null); + responseCodecId = responseCodecId == null ? "json-v2" : responseCodecId; + if (responseCodecId.isBlank() || responseCodecId.length() > 64) { throw StartupFailures.envValidation( - "APP_IDEMPOTENCY_TTL (ca-skeleton.idempotency.ttl) must be positive, was " + ttl); + PREFIX + + ".response-codec-id must contain 1-64 characters, was '" + + responseCodecId + + "'"); } - if (ttl.compareTo(MAX_TTL) > 0) { + policyRevision = policyRevision == null ? 2 : policyRevision; + if (policyRevision < 1) { throw StartupFailures.envValidation( - "APP_IDEMPOTENCY_TTL (ca-skeleton.idempotency.ttl) must be <= 72h (D6), was " + ttl); - } - if (reaperInterval == null || reaperInterval.isZero() || reaperInterval.isNegative()) { - reaperInterval = Duration.ofMinutes(10); + PREFIX + ".policy-revision must be positive, was " + policyRevision); } } + + private static Duration orDefault(Duration value, Duration fallback) { + return value == null ? fallback : value; + } + + private static Duration bounded(String key, Duration value, Duration maximum) { + if (value.isZero() || value.isNegative()) { + throw StartupFailures.envValidation(PREFIX + "." + key + " must be positive, was " + value); + } + if (maximum != null && value.compareTo(maximum) > 0) { + throw StartupFailures.envValidation( + PREFIX + "." + key + " must be at most " + maximum + ", was " + value); + } + return value; + } + + /** The stores a deployment may select; never inferred from the classpath. */ + public enum Provider { + /** No store and no executor: the capability is off. */ + DISABLED, + /** The Redis owner-safe store (adapter:outbound:cache-redis). */ + REDIS, + /** The PostgreSQL owner-safe store (adapter:outbound:persistence-jpa). */ + POSTGRESQL + } } diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/PostgreSqlIdempotencyProviderConfig.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/PostgreSqlIdempotencyProviderConfig.java deleted file mode 100644 index 528740ca..00000000 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/PostgreSqlIdempotencyProviderConfig.java +++ /dev/null @@ -1,61 +0,0 @@ -package dev.caskeleton.bootstrap.autoconfigure.idempotency; - -import dev.caskeleton.application.idempotency.v2.IdempotencyExecutorV2; -import dev.caskeleton.application.idempotency.v2.IdempotencyStorePortV2; -import java.time.Duration; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -/** - * Composes the application-owned V2 request-replay lifecycle over the selected PostgreSQL store. - * - *

The concrete store is assembled by the JPA leaf under the same provider selector and exposed - * only as {@code IdempotencyStorePortV2}. This application configuration owns the lifecycle policy - * layered over that port; it does not construct or import the PostgreSQL implementation. - * - *

The lifecycle bounds come from the single registered idempotency TTL rather than from five new - * keys. The processing lease is deliberately not derived from it: a lease is how long one attempt - * may hold a record before another may take over, which is a property of how long the work takes, - * not of how long its result stays replayable. - */ -@Configuration(proxyBeanMethods = false) -@EnableConfigurationProperties(IdempotencySettings.class) -@ConditionalOnProperty( - name = "ca-skeleton.capabilities.idempotency.provider", - havingValue = "postgresql") -public class PostgreSqlIdempotencyProviderConfig { - - /** - * How long one attempt holds a claim before another caller may take it over. - * - *

The store refuses anything above one hour, and a lease longer than the work it covers turns - * a crashed worker into an outage for that key. - */ - private static final Duration PROCESSING_LEASE = Duration.ofMinutes(2); - - /** The codec identity the stored payload is written with, matching the V2 schema's column. */ - private static final String RESPONSE_CODEC_ID = "json.v1"; - - /** The replay policy revision this schema stream enforces. */ - private static final int POLICY_REVISION = 2; - - /** - * The request-replay lifecycle driven over the store. - * - *

Provider-neutral by type. A selection that produced the store and no executor produced a - * store nothing could drive, which is what {@link IdempotencyProviderSelectionConfig} refuses. - */ - @Bean - IdempotencyExecutorV2 postgreSqlIdempotencyExecutorV2( - IdempotencyStorePortV2 store, IdempotencySettings settings) { - return new IdempotencyExecutorV2( - store, - PROCESSING_LEASE, - settings.ttl(), - settings.ttl(), - RESPONSE_CODEC_ID, - POLICY_REVISION); - } -} diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/jpa/DataSourceRequirement.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/jpa/DataSourceRequirement.java deleted file mode 100644 index 592ab04a..00000000 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/jpa/DataSourceRequirement.java +++ /dev/null @@ -1,77 +0,0 @@ -package dev.caskeleton.bootstrap.autoconfigure.jpa; - -import dev.caskeleton.shared.activation.MasterSwitch; -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; -import org.springframework.core.env.Environment; - -/** - * Which active capabilities need a relational connection. - * - *

A pool is not JPA's private property. The outbox, the JDBC idempotency store, the - * multi-instance lock, the notification store, and the Fileserver transaction path all need one, - * and asking only "is JPA off?" would either open a pool nobody uses or silently break a capability - * that was legitimately using it. Naming the consumers here turns that into a dependency error an - * operator can read. - */ -public final class DataSourceRequirement { - - private DataSourceRequirement() {} - - /** - * Names every active capability that requires a relational connection. - * - * @param environment the resolved environment - * @return one human-readable reason per requiring capability; empty when none does - */ - public static List reasons(Environment environment) { - List reasons = new ArrayList<>(); - if (isOn(environment, MasterSwitch.PERSISTENCE_JPA.property())) { - reasons.add(MasterSwitch.PERSISTENCE_JPA.property() + "=true"); - } - if (isOn(environment, "ca-skeleton.outbox.enabled")) { - reasons.add("ca-skeleton.outbox.enabled=true"); - } - String idempotencyProvider = - environment.getProperty("ca-skeleton.capabilities.idempotency.provider", "disabled").trim(); - if ("jdbc".equalsIgnoreCase(idempotencyProvider) - || "postgresql".equalsIgnoreCase(idempotencyProvider)) { - reasons.add("ca-skeleton.capabilities.idempotency.provider=" + idempotencyProvider); - } - if (isOn(environment, "ca-skeleton.runtime.multi-instance-enabled")) { - reasons.add("ca-skeleton.runtime.multi-instance-enabled=true"); - } - if (isOn(environment, MasterSwitch.NOTIFICATION_PLATFORM.property()) - && !"none" - .equalsIgnoreCase( - environment.getProperty("ca-skeleton.notification.platform.persistence", "jpa"))) { - reasons.add("ca-skeleton.notification.platform.persistence requires a relational store"); - } - // Fileserver's TransactionPort path is a relational consumer too. Named rather than redesigned: - // an all-off deployment that quietly opened a pool for it would break the invariant this class - // exists to state. - if (isOn(environment, "app.fileserver-platform.enabled") - && !"none" - .equalsIgnoreCase( - environment.getProperty("app.fileserver-platform.transaction-provider", "jpa"))) { - reasons.add("app.fileserver-platform.enabled=true with a relational transaction provider"); - } - return List.copyOf(reasons); - } - - /** - * Reports whether any active capability requires a relational connection. - * - * @param environment the resolved environment - * @return true when at least one capability requires one - */ - public static boolean isRequired(Environment environment) { - return !reasons(environment).isEmpty(); - } - - private static boolean isOn(Environment environment, String property) { - return "true" - .equalsIgnoreCase(environment.getProperty(property, "false").toLowerCase(Locale.ROOT)); - } -} diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/jpa/DatabaseReadinessGroupPostProcessor.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/jpa/DatabaseReadinessGroupPostProcessor.java deleted file mode 100644 index 977e972b..00000000 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/jpa/DatabaseReadinessGroupPostProcessor.java +++ /dev/null @@ -1,47 +0,0 @@ -package dev.caskeleton.bootstrap.autoconfigure.jpa; - -import dev.caskeleton.bootstrap.runtime.ReadinessGroup; -import dev.caskeleton.bootstrap.runtime.startup.StartupOrder; -import org.springframework.boot.EnvironmentPostProcessor; -import org.springframework.boot.SpringApplication; -import org.springframework.core.Ordered; -import org.springframework.core.env.ConfigurableEnvironment; - -/** - * Adds the database readiness contributor to the readiness group, and only when it will exist. - * - *

The same problem {@link RedisReadinessGroupPostProcessor} solves, arriving at {@code db} once - * relational persistence became optional. {@code validate-group-membership} is on, so a static - * {@code readiness.include: readinessState,db} is not "a database group that is ignored when there - * is no database" — it is a deployment that cannot boot without one, which is the opposite of what - * the JPA master switch exists to provide. - * - *

Dropping the validation is not the answer either: without it a misspelled contributor is - * ignored and readiness reports UP while proving nothing. So membership becomes a function of the - * same question that decides whether a {@code DataSource} exists at all — {@link - * DataSourceRequirement} — which is asked about capabilities rather than about JPA, because outbox, - * idempotency, the distributed lock, the notification store and Fileserver are all legitimate - * consumers of the pool. - */ -public class DatabaseReadinessGroupPostProcessor implements EnvironmentPostProcessor, Ordered { - - static final String DB_CONTRIBUTOR = "db"; - - private static final String PROPERTY_SOURCE = "databaseReadinessGroup"; - - @Override - public void postProcessEnvironment( - ConfigurableEnvironment environment, SpringApplication application) { - if (!DataSourceRequirement.isRequired(environment)) { - return; - } - ReadinessGroup.include(environment, PROPERTY_SOURCE, DB_CONTRIBUTOR); - } - - @Override - public int getOrder() { - // After config data, for the same reason the Redis one does; and after the Redis processor, so - // the two appends chain deterministically instead of racing for the same property. - return StartupOrder.READINESS_DATABASE; - } -} diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/jpa/JpaOffAutoConfigurationImportFilter.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/jpa/JpaOffAutoConfigurationImportFilter.java deleted file mode 100644 index 3df03cd5..00000000 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/jpa/JpaOffAutoConfigurationImportFilter.java +++ /dev/null @@ -1,55 +0,0 @@ -package dev.caskeleton.bootstrap.autoconfigure.jpa; - -import java.util.Set; -import org.springframework.boot.autoconfigure.AutoConfigurationImportFilter; -import org.springframework.boot.autoconfigure.AutoConfigurationMetadata; -import org.springframework.context.EnvironmentAware; -import org.springframework.core.env.Environment; - -/** - * Keeps Boot's relational auto-configurations out of the candidate set while nothing needs them. - * - *

Conditioning only this repository's own configurations is not enough: the JPA and Flyway - * starters contribute theirs through Boot's import metadata, so an ordinary - * {@code @EnableAutoConfiguration} application opens a pool and runs a migration regardless of what - * any project condition says. The requirement is asked as a question about capabilities rather than - * about JPA, because the pool has several legitimate consumers. - * - *

A misspelled entry below fails open silently — the filter simply never matches — so the tests - * that protect this assert on bean absence rather than on what this method returns. - */ -public final class JpaOffAutoConfigurationImportFilter - implements AutoConfigurationImportFilter, EnvironmentAware { - - private static final Set RELATIONAL_AUTO_CONFIGURATIONS = - Set.of( - "org.springframework.boot.jdbc.autoconfigure.DataSourceAutoConfiguration", - "org.springframework.boot.jdbc.autoconfigure.JdbcTemplateAutoConfiguration", - "org.springframework.boot.jdbc.autoconfigure.JdbcClientAutoConfiguration", - "org.springframework.boot.jdbc.autoconfigure.DataSourceTransactionManagerAutoConfiguration", - "org.springframework.boot.jdbc.autoconfigure.health.DataSourceHealthContributorAutoConfiguration", - "org.springframework.boot.jdbc.autoconfigure.metrics.DataSourcePoolMetricsAutoConfiguration", - "org.springframework.boot.hibernate.autoconfigure.HibernateJpaAutoConfiguration", - "org.springframework.boot.data.jpa.autoconfigure.DataJpaRepositoriesAutoConfiguration", - "org.springframework.boot.flyway.autoconfigure.FlywayAutoConfiguration"); - - private Environment environment; - - @Override - public boolean[] match(String[] candidates, AutoConfigurationMetadata metadata) { - boolean required = environment != null && DataSourceRequirement.isRequired(environment); - boolean[] matches = new boolean[candidates.length]; - for (int index = 0; index < candidates.length; index++) { - matches[index] = - required - || candidates[index] == null - || !RELATIONAL_AUTO_CONFIGURATIONS.contains(candidates[index]); - } - return matches; - } - - @Override - public void setEnvironment(Environment environment) { - this.environment = environment; - } -} diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/jpa/JpaPlatformAutoConfiguration.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/jpa/JpaPlatformAutoConfiguration.java deleted file mode 100644 index c1ff1f08..00000000 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/jpa/JpaPlatformAutoConfiguration.java +++ /dev/null @@ -1,123 +0,0 @@ -package dev.caskeleton.bootstrap.autoconfigure.jpa; - -import dev.caskeleton.adapter.outbound.persistence.api.capability.CapabilitySupport; -import dev.caskeleton.adapter.outbound.persistence.api.capability.JpaCapability; -import dev.caskeleton.adapter.outbound.persistence.hibernate.HibernateProviderPolicy; -import dev.caskeleton.adapter.outbound.persistence.migration.FlywaySchemaPolicy; -import dev.caskeleton.adapter.outbound.persistence.security.DatabasePrivilegeReport; -import dev.caskeleton.adapter.outbound.persistence.security.PostgreSqlRuntimeRoleVerifier; -import java.sql.Connection; -import java.sql.SQLException; -import java.util.List; -import java.util.Objects; -import javax.sql.DataSource; -import org.springframework.core.env.Environment; - -/** - * Composes the Stable JPA platform for this application (design §7.1). - * - *

Plain construction rather than Spring auto-configuration. This repository's rule is that - * {@code app-bootstrap} owns composition, and an adapter leaf that auto-configured itself would - * build beans in any application that merely has it on the classpath — which is how the fileserver - * capability once produced beans for a composition root that had no use for them. - * - *

Only Stable modules are composed here. Querydsl, Envers, the second-level cache, and COPY are - * Advanced or admin capabilities that require their own dependency and their own explicit opt-in - * (design §4.2, §8.4). - */ -public final class JpaPlatformAutoConfiguration { - - private final Environment environment; - private final HibernateProviderPolicy providerPolicy; - private final PostgreSqlRuntimeRoleVerifier roleVerifier; - - public JpaPlatformAutoConfiguration( - Environment environment, - HibernateProviderPolicy providerPolicy, - PostgreSqlRuntimeRoleVerifier roleVerifier) { - this.environment = Objects.requireNonNull(environment, "environment"); - this.providerPolicy = Objects.requireNonNull(providerPolicy, "providerPolicy"); - this.roleVerifier = Objects.requireNonNull(roleVerifier, "roleVerifier"); - } - - /** The startup guard for the two settings that quietly break production. */ - public JpaDangerousConfigurationGuard dangerousConfigurationGuard(JpaSafetySettings safety) { - return new JpaDangerousConfigurationGuard(safety, FlywaySchemaPolicy.standard()); - } - - /** The datasource product, version, and pool validator. */ - public JpaDataSourceProfileValidator dataSourceProfileValidator() { - return new JpaDataSourceProfileValidator(new PostgreSqlVersionPolicy()); - } - - /** The capabilities this composition actually provides. */ - public List capabilities() { - return List.of( - CapabilitySupport.stable(JpaCapability.TRANSACTION_RETRY), - CapabilitySupport.advanced( - JpaCapability.COMPLETION_EVIDENCE, - "requires an application-owned completion-evidence/reconciliation composition"), - CapabilitySupport.stable(JpaCapability.KEYSET_PAGINATION), - CapabilitySupport.advanced( - JpaCapability.BATCH, - "requires hibernate.jdbc.batch_size > 0, ordering settings, statistics and JDBC batch instrumentation"), - CapabilitySupport.stable(JpaCapability.SCHEMA_GATE), - CapabilitySupport.stable(JpaCapability.RUNTIME_ROLE_VERIFICATION), - CapabilitySupport.advanced( - JpaCapability.OBSERVABILITY, - "requires explicit metrics/statistics collector composition"), - CapabilitySupport.advanced( - JpaCapability.POSTGRESQL_NATIVE_WRITE, "requires a registered statement"), - CapabilitySupport.advanced(JpaCapability.POSTGRESQL_WORK_CLAIM, "requires a named queue"), - CapabilitySupport.advanced(JpaCapability.POSTGRESQL_JSONB, "requires a registered path"), - CapabilitySupport.advanced(JpaCapability.POSTGRESQL_ARRAY_RANGE, "requires a JDBC type"), - CapabilitySupport.advanced(JpaCapability.BULK_DML, "requires a registered operation"), - CapabilitySupport.advanced( - JpaCapability.STATELESS_SESSION, "requires registered work and a row cap"), - CapabilitySupport.advanced( - JpaCapability.POSTGRESQL_COPY, "requires the admin credential and a registered COPY"), - CapabilitySupport.advanced(JpaCapability.L2_CACHE, "requires an enrolled region catalog"), - CapabilitySupport.advanced( - JpaCapability.ENVERS, "requires the Envers dependency and a retention policy")); - } - - /** - * Builds the sanitized report the actuator endpoint serves. - * - *

A failure to read the runtime role is reported as "not verified" rather than propagated: an - * unreachable database must not turn the diagnostic endpoint into a second outage. - */ - public JpaPlatformReport report(DataSource dataSource, String schemaVersion) { - Objects.requireNonNull(dataSource, "dataSource"); - String product = "unknown"; - int majorVersion = 0; - try (Connection connection = dataSource.getConnection()) { - product = connection.getMetaData().getDatabaseProductName(); - majorVersion = connection.getMetaData().getDatabaseMajorVersion(); - } catch (SQLException unreachable) { - // Reported as unknown below; the endpoint must not fail because the database is down. - product = "unavailable"; - } - DatabasePrivilegeReport privileges = readPrivileges(dataSource); - boolean openInViewDisabled = - !Boolean.TRUE.equals( - environment.getProperty( - JpaDangerousConfigurationGuard.OPEN_IN_VIEW_KEY, Boolean.class)); - return JpaPlatformReport.sanitized( - product, - majorVersion, - providerPolicy.runtimeVersion(), - schemaVersion, - openInViewDisabled, - privileges, - capabilities()); - } - - private DatabasePrivilegeReport readPrivileges(DataSource dataSource) { - try { - return roleVerifier.verify(dataSource); - } catch (IllegalStateException unverified) { - return null; - } - } -} diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/jpa/JpaPlatformReport.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/jpa/JpaPlatformReport.java deleted file mode 100644 index 4e5f19e0..00000000 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/jpa/JpaPlatformReport.java +++ /dev/null @@ -1,64 +0,0 @@ -package dev.caskeleton.bootstrap.autoconfigure.jpa; - -import dev.caskeleton.adapter.outbound.persistence.api.capability.CapabilitySupport; -import dev.caskeleton.adapter.outbound.persistence.security.DatabasePrivilegeReport; -import java.util.List; -import java.util.Objects; - -/** - * What the JPA platform is willing to say about itself over HTTP (design §37). - * - *

The interesting part of this type is what it cannot hold. There is no JDBC URL, no username, - * no password, no SQL, and no entity catalog — an actuator endpoint is reachable by anyone who - * reaches the management port, and every one of those would be a free reconnaissance answer. - * - *

What it does report is what an operator actually needs during an incident: which database - * major version is behind this instance, which provider, which schema version, and whether the - * safety properties this platform depends on are holding. - */ -public record JpaPlatformReport( - String databaseProduct, - int databaseMajorVersion, - String providerVersion, - String schemaVersion, - boolean openInViewDisabled, - boolean runtimeRoleVerified, - List capabilities) { - - public JpaPlatformReport { - Objects.requireNonNull(databaseProduct, "databaseProduct"); - Objects.requireNonNull(providerVersion, "providerVersion"); - schemaVersion = schemaVersion == null ? "unknown" : schemaVersion; - capabilities = List.copyOf(Objects.requireNonNull(capabilities, "capabilities")); - } - - /** - * Builds the report, deriving only bounded values from the privilege report. - * - *

The privilege report's {@code currentUser} and {@code searchPath} are deliberately reduced - * to a single boolean here: an operator needs to know the runtime role passed verification, not - * which role it is. - */ - public static JpaPlatformReport sanitized( - String databaseProduct, - int databaseMajorVersion, - String providerVersion, - String schemaVersion, - boolean openInViewDisabled, - DatabasePrivilegeReport privileges, - List capabilities) { - return new JpaPlatformReport( - databaseProduct, - databaseMajorVersion, - providerVersion, - schemaVersion, - openInViewDisabled, - privileges != null && !privileges.holdsCreatePrivilege(), - capabilities); - } - - /** Whether every safety property this platform depends on is currently holding. */ - public boolean safe() { - return openInViewDisabled && runtimeRoleVerified; - } -} diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/jpa/JpaPlatformRuntimeAutoConfiguration.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/jpa/JpaPlatformRuntimeAutoConfiguration.java deleted file mode 100644 index f6b60cee..00000000 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/jpa/JpaPlatformRuntimeAutoConfiguration.java +++ /dev/null @@ -1,107 +0,0 @@ -package dev.caskeleton.bootstrap.autoconfigure.jpa; - -import dev.caskeleton.adapter.outbound.persistence.hibernate.HibernateProviderPolicy; -import dev.caskeleton.adapter.outbound.persistence.security.PostgreSqlRuntimeRoleVerifier; -import java.util.function.Supplier; -import javax.sql.DataSource; -import org.springframework.beans.factory.InitializingBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.core.env.Environment; - -/** - * Application-owned JPA startup safety and management composition. - * - *

The persistence leaf owns provider selection, vendor beans, transaction execution and retry. - * This configuration consumes those collaborators only to apply application deployment policy: - * unsafe JPA settings fail startup, the resolved datasource is reported through a sanitized - * actuator view, and application-owned safety settings stay in the composition root. - * - *

The add-on switch remains for these application-level diagnostics and guards. It does not - * control whether relational persistence exists; the capability master switch is {@code - * ca-skeleton.persistence-jpa.enabled} and is owned by the persistence leaf. - */ -@org.springframework.context.annotation.Configuration(proxyBeanMethods = false) -@ConditionalOnClass(DataSource.class) -@ConditionalOnProperty(prefix = "app.jpa-platform", name = "addons-enabled", matchIfMissing = true) -@EnableConfigurationProperties(JpaSafetySettings.class) -public class JpaPlatformRuntimeAutoConfiguration { - - /** The composition factory, exposed so an application can reuse its decisions. */ - @Bean - @ConditionalOnMissingBean - public JpaPlatformAutoConfiguration jpaPlatformComposition( - Environment environment, - HibernateProviderPolicy providerPolicy, - PostgreSqlRuntimeRoleVerifier roleVerifier) { - return new JpaPlatformAutoConfiguration(environment, providerPolicy, roleVerifier); - } - - /** - * The startup guard for the two settings that quietly break production. - * - *

An {@code InitializingBean} wrapper is deliberately not used here: the guard is a bean an - * application can also invoke itself, and the refresh-time check belongs to whoever decides - * when a misconfiguration should stop a boot. - */ - @Bean - @ConditionalOnMissingBean - public JpaDangerousConfigurationGuard jpaDangerousConfigurationGuard( - JpaPlatformAutoConfiguration composition, JpaSafetySettings safety) { - return composition.dangerousConfigurationGuard(safety); - } - - /** The datasource product, version and pool validator. */ - @Bean - @ConditionalOnMissingBean - public JpaDataSourceProfileValidator jpaDataSourceProfileValidator( - JpaPlatformAutoConfiguration composition) { - return composition.dataSourceProfileValidator(); - } - - /** The platform report the actuator endpoint serves. */ - @Bean - @ConditionalOnMissingBean - public Supplier jpaPlatformReportSupplier( - JpaPlatformAutoConfiguration composition, DataSource dataSource) { - // Computed per request rather than at startup: the report names the live schema version, and a - // value captured at boot would keep reporting the version the application started with. - return () -> composition.report(dataSource, schemaVersion(dataSource)); - } - - /** - * The actuator endpoint. - * - *

{@code @Endpoint} alone registers nothing; exposure is still governed by the application's - * existing {@code management.endpoints} policy, which this deliberately does not widen. - */ - @Bean - @ConditionalOnMissingBean - @ConditionalOnBean(name = "jpaPlatformReportSupplier") - public JpaPlatformEndpoint jpaPlatformEndpoint(Supplier reportSupplier) { - return new JpaPlatformEndpoint(reportSupplier); - } - - /** Runs the dangerous-configuration guard during refresh. */ - @Bean - public InitializingBean jpaPlatformStartupCheck( - JpaDangerousConfigurationGuard guard, Environment environment) { - // A refresh-time failure beats a runtime one: OSIV left on, or a schema-mutating ddl-auto in a - // profile that forbids it, is a deployment mistake and not a request-time condition. - return () -> guard.validate(environment); - } - - private static String schemaVersion(DataSource dataSource) { - try (var connection = dataSource.getConnection()) { - return connection.getMetaData().getDatabaseProductVersion(); - } catch (java.sql.SQLException unavailable) { - // Reporting "unknown" is honest; failing the endpoint over a transient connection problem - // would turn a diagnostic into an outage. - return "unknown"; - } - } -} diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/jpa/MigrationStartupConfig.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/jpa/MigrationStartupConfig.java deleted file mode 100644 index 26c7fed1..00000000 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/jpa/MigrationStartupConfig.java +++ /dev/null @@ -1,48 +0,0 @@ -package dev.caskeleton.bootstrap.autoconfigure.jpa; - -import dev.caskeleton.bootstrap.runtime.startup.FlywayProdSafetyValidator; -import dev.caskeleton.bootstrap.runtime.startup.MigrationStartupRunner; -import dev.caskeleton.bootstrap.runtime.startup.RequiredEnvironmentValidator; -import dev.caskeleton.bootstrap.settings.RuntimeSafetySettings; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.boot.flyway.autoconfigure.FlywayMigrationStrategy; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.Environment; - -/** - * Composition-root wiring for the startup migration guards and the Flyway migration strategy. See - * README for the design rationale. - * - *

Gated on the JPA master, and imported by {@code PersistenceJpaRootAutoConfiguration}. Before - * that, a Flyway migration strategy, a datasource environment validator, and a prod Flyway - * validator were created on every startup — including deployments with no database, where migration - * is not a thing that can be safe or unsafe, only absent. - */ -@Configuration -@ConditionalOnProperty( - prefix = "ca-skeleton.persistence-jpa", - name = "enabled", - havingValue = "true") -public class MigrationStartupConfig { - - /** - * Bean name must stay {@code migrationStartupRunner} (Flyway autoconfiguration delegates to it). - */ - @Bean - FlywayMigrationStrategy migrationStartupRunner(RuntimeSafetySettings settings) { - return new MigrationStartupRunner(settings); - } - - /** Env-validation (exit 78): datasource connection env present before migration runs. */ - @Bean - RequiredEnvironmentValidator requiredEnvironmentValidator(Environment environment) { - return new RequiredEnvironmentValidator(environment); - } - - /** Profile check (exit 71): forbidden Flyway options stay off under the prod profile. */ - @Bean - FlywayProdSafetyValidator flywayProdSafetyValidator(Environment environment) { - return new FlywayProdSafetyValidator(environment); - } -} diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/jpa/PersistenceJpaRootAutoConfiguration.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/jpa/PersistenceJpaRootAutoConfiguration.java deleted file mode 100644 index 09790d80..00000000 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/jpa/PersistenceJpaRootAutoConfiguration.java +++ /dev/null @@ -1,49 +0,0 @@ -package dev.caskeleton.bootstrap.autoconfigure.jpa; - -import dev.caskeleton.adapter.outbound.persistence.config.PersistenceVendorSettings; -import javax.sql.DataSource; -import org.springframework.beans.factory.InitializingBean; -import org.springframework.boot.autoconfigure.AutoConfiguration; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Import; -import org.springframework.core.env.Environment; - -/** - * Application startup policy layered over the leaf-owned relational persistence capability. - * - *

The persistence leaf owns entity/repository discovery, vendor selection, optional capability - * persistence registrations, and reusable transaction/retry runtime. This root deliberately does - * not reconstruct those implementation details. - * - *

What remains application-owned is startup/deployment policy: migration startup sequencing, - * resolved datasource validation, OSIV/DDL safety, and the sanitized management view. The root - * carries the same master switch so those checks never bind or run while JPA is disabled; bean - * dependencies, not a reference to leaf-internal auto-configuration classes, provide runtime - * ordering. - */ -@AutoConfiguration -@ConditionalOnProperty( - prefix = "ca-skeleton.persistence-jpa", - name = "enabled", - havingValue = "true") -@Import({MigrationStartupConfig.class, JpaPlatformRuntimeAutoConfiguration.class}) -public class PersistenceJpaRootAutoConfiguration { - - /** - * Validates the datasource the application actually resolved. - * - *

The vendor selector is read from the environment because the persistence settings tree is - * intentionally bound only by the enabled leaf. PostgreSQL validation opens the resolved - * datasource during startup; H2 local-development selection skips the PostgreSQL product check. - */ - @Bean - public InitializingBean jpaResolvedDataSourceCheck( - DataSource dataSource, Environment environment) { - JpaDataSourceProfileValidator validator = - new JpaDataSourceProfileValidator(new PostgreSqlVersionPolicy()); - String vendor = - environment.getProperty(PersistenceVendorSettings.VENDOR_PROPERTY, "postgresql").trim(); - return () -> validator.validateResolved(dataSource, "postgresql".equalsIgnoreCase(vendor)); - } -} diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/lock/DistributedLockConfig.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/lock/DistributedLockConfig.java deleted file mode 100644 index 86fdabe4..00000000 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/lock/DistributedLockConfig.java +++ /dev/null @@ -1,34 +0,0 @@ -package dev.caskeleton.bootstrap.autoconfigure.lock; - -import dev.caskeleton.application.lock.DistributedLockPort; -import io.micrometer.core.instrument.MeterRegistry; -import org.springframework.beans.factory.ObjectProvider; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.boot.autoconfigure.AutoConfiguration; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Primary; - -/** - * Composition-root wiring for the distributed-lock metrics decorator. See README for the design - * rationale. - */ -@AutoConfiguration -public class DistributedLockConfig { - - /** - * The bean name {@code "distributedLockProvider"} is the contract with {@code - * StartupSafetyValidator} — do not rename. See README for the design rationale. - */ - @Bean(name = "distributedLockProvider") - @Primary - @ConditionalOnProperty( - prefix = "ca-skeleton.runtime", - name = "multi-instance-enabled", - havingValue = "true") - DistributedLockPort distributedLockProvider( - @Qualifier("jdbcDistributedLock") DistributedLockPort jdbcDistributedLock, - ObjectProvider meterRegistry) { - return new MeteredDistributedLockPort(jdbcDistributedLock, meterRegistry); - } -} diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/messaging/DisabledMessagingSentinelAutoConfiguration.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/messaging/DisabledMessagingSentinelAutoConfiguration.java deleted file mode 100644 index 607dabd1..00000000 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/messaging/DisabledMessagingSentinelAutoConfiguration.java +++ /dev/null @@ -1,47 +0,0 @@ -package dev.caskeleton.bootstrap.autoconfigure.messaging; - -import dev.caskeleton.adapter.outbound.messaging.core.DisabledMessagePublisher; -import dev.caskeleton.adapter.outbound.messaging.core.MessagePublisher; -import dev.caskeleton.adapter.outbound.messaging.outbox.DisabledOutboxMessagePublisher; -import dev.caskeleton.application.outbox.OutboxMessagePublishPort; -import org.springframework.boot.autoconfigure.AutoConfiguration; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.context.annotation.Bean; - -/** - * Supplies the fail-fast stand-ins for a messaging capability nobody enabled. - * - *

The adapter used to register these itself, which meant an application with messaging switched - * off still held two messaging beans — and the off invariant says an adapter that is off owns - * nothing. The stand-ins still have to exist for any consumer that requires a publisher - * unconditionally, so the composition root provides them: it is the layer that knows what the rest - * of the application demands, and it is not the adapter. - * - *

{@code @ConditionalOnMissingBean} rather than a switch condition, so turning messaging on - * replaces these without either side naming the other. - */ -@AutoConfiguration -public class DisabledMessagingSentinelAutoConfiguration { - - /** - * The generic publisher stand-in. - * - * @return a publisher that throws {@code AdapterDisabledException} on first use - */ - @Bean - @ConditionalOnMissingBean(MessagePublisher.class) - public MessagePublisher disabledMessagePublisher() { - return new DisabledMessagePublisher(); - } - - /** - * The outbox publish-port stand-in. - * - * @return a port that throws {@code AdapterDisabledException} on first use - */ - @Bean - @ConditionalOnMissingBean(OutboxMessagePublishPort.class) - public OutboxMessagePublishPort disabledOutboxMessagePublishPort() { - return new DisabledOutboxMessagePublisher(); - } -} diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/notification/NotificationApplicationCompositionAutoConfiguration.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/notification/NotificationApplicationCompositionAutoConfiguration.java deleted file mode 100644 index 210c77f5..00000000 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/notification/NotificationApplicationCompositionAutoConfiguration.java +++ /dev/null @@ -1,329 +0,0 @@ -package dev.caskeleton.bootstrap.autoconfigure.notification; - -import dev.caskeleton.adapter.inbound.web.notification.platform.callback.ProviderCallbackIngress; -import dev.caskeleton.adapter.outbound.notification.platform.callback.ProviderCallbackAdapterRegistry; -import dev.caskeleton.adapter.outbound.notification.platform.dispatch.NotificationDispatchProperties; -import dev.caskeleton.application.notification.platform.callback.CallbackPayloadProtectionPort; -import dev.caskeleton.application.notification.platform.callback.DeliveryAttemptResolverPort; -import dev.caskeleton.application.notification.platform.callback.DeliveryProjectionStorePort; -import dev.caskeleton.application.notification.platform.callback.IngestProviderCallbackApplicationUseCase; -import dev.caskeleton.application.notification.platform.callback.NotificationSideEffectPort; -import dev.caskeleton.application.notification.platform.callback.ProviderEventLedger; -import dev.caskeleton.application.notification.platform.callback.ProviderEventProjectionService; -import dev.caskeleton.application.notification.platform.callback.ProviderEventProjectorRegistry; -import dev.caskeleton.application.notification.platform.dispatch.CanonicalNotificationPlanWriter; -import dev.caskeleton.application.notification.platform.dispatch.ContactPointStorePort; -import dev.caskeleton.application.notification.platform.dispatch.DeliveryAttemptFactory; -import dev.caskeleton.application.notification.platform.dispatch.DeliveryAttemptStorePort; -import dev.caskeleton.application.notification.platform.dispatch.DispatchOutcomeRecorder; -import dev.caskeleton.application.notification.platform.dispatch.DispatchPipeline; -import dev.caskeleton.application.notification.platform.dispatch.NotificationDispatchService; -import dev.caskeleton.application.notification.platform.dispatch.NotificationIdGeneratorPort; -import dev.caskeleton.application.notification.platform.dispatch.NotificationRequestStorePort; -import dev.caskeleton.application.notification.platform.dispatch.NotificationSubmissionService; -import dev.caskeleton.application.notification.platform.dispatch.ProviderDispatchGatewayPort; -import dev.caskeleton.application.notification.platform.dispatch.RecipientDeliveryStorePort; -import dev.caskeleton.application.notification.platform.dispatch.RecipientLeaseStorePort; -import dev.caskeleton.application.notification.platform.dispatch.ReconciliationService; -import dev.caskeleton.application.notification.platform.dispatch.RequestFingerprint; -import dev.caskeleton.application.notification.platform.dispatch.TemplateRendererRegistry; -import dev.caskeleton.application.notification.platform.dispatch.TenantContextPort; -import dev.caskeleton.application.notification.platform.observation.NotificationMetricsPort; -import dev.caskeleton.application.notification.platform.observation.NotificationSecurityAuditPort; -import dev.caskeleton.application.notification.platform.policy.NotificationRetryPolicy; -import dev.caskeleton.application.notification.platform.policy.RoutingDecisionEngine; -import dev.caskeleton.application.notification.platform.port.in.IngestProviderCallbackUseCase; -import dev.caskeleton.application.notification.platform.template.TemplateRegistry; -import dev.caskeleton.application.transaction.TransactionPort; -import java.time.Clock; -import org.springframework.boot.autoconfigure.AutoConfiguration; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.context.annotation.Bean; - -/** Application-owned Notification orchestration and transaction-bound use-case assembly. */ -@AutoConfiguration( - afterName = - "dev.caskeleton.adapter.outbound.notification.platform.autoconfigure.NotificationPlatformAutoConfiguration") -@ConditionalOnProperty( - prefix = "ca-skeleton.notification.platform", - name = "enabled", - havingValue = "true") -public class NotificationApplicationCompositionAutoConfiguration { - /** N2 orchestration. */ - @Bean - public NotificationSubmissionService notificationOrchestrator( - NotificationRequestStorePort requests, - RecipientDeliveryStorePort recipients, - DeliveryAttemptStorePort attempts, - TemplateRegistry templates, - RequestFingerprint fingerprints, - CanonicalNotificationPlanWriter writer, - TransactionPort transactions, - TenantContextPort tenants, - dev.caskeleton.application.notification.platform.policy.DeduplicationService deduplication, - NotificationMetricsPort metrics, - Clock clock) { - return new NotificationSubmissionService( - requests, - recipients, - attempts, - templates, - fingerprints, - writer, - transactions, - tenants, - deduplication, - metrics, - clock); - } - - /** - * The split inbound use cases. - * - *

Four beans rather than one orchestrator, because four capabilities cannot be declared on one - * class — and a caller depending on the whole orchestrator depends on three operations it does - * not use. - * - * @param service the shared submission service - * @param transactions the transaction boundary each use case opens for itself - * @return the use case - */ - /** - * The transport-facing entry point: accept by address (NTF-INT-008). - * - *

Separate from {@code submitNotificationUseCase}, which it delegates to. That one takes a - * plan whose recipients reference contact points already in the directory; this one takes an - * address, registers or reuses the contact point, and builds the plan. Without it the platform is - * reachable only by a caller that already holds contact point ids — and the platform ships no way - * to obtain one, so it was reachable by nobody. - * - * @param submit the plan-shaped submission it delegates to - * @param contactPoints the contact point directory - * @param protector the encryption and keyed-lookup boundary - * @param tenants the ambient tenant - * @param ids the identifier source for the contact point and correlation ids - * @param fingerprints canonical SHA-256 fingerprinting used when the caller supplies no key - * @param transactions the write boundary for registration - * @param clock the registration time source - * @return the use case - */ - @Bean - public dev.caskeleton.application.notification.platform.port.in.AcceptNotificationUseCase - acceptNotificationUseCase( - dev.caskeleton.application.notification.platform.port.in.SubmitNotificationUseCase submit, - ContactPointStorePort contactPoints, - dev.caskeleton.application.notification.platform.security.ContactPointProtector protector, - TenantContextPort tenants, - NotificationIdGeneratorPort ids, - RequestFingerprint fingerprints, - TransactionPort transactions, - Clock clock) { - return new dev.caskeleton.application.notification.platform.dispatch - .AcceptNotificationApplicationUseCase( - submit, contactPoints, protector, tenants, ids, fingerprints, transactions, clock); - } - - /** - * Publishing a template version. - * - *

A submission pins a template id and version and the platform refuses one it cannot resolve, - * so a deployment with no published template can accept nothing. {@code TemplateRegistry.publish} - * existed throughout and was called by no application code and no transport. - * - * @param templates the registry - * @param digests the hashing boundary used for the content digest - * @param transactions the write boundary - * @return the use case - */ - @Bean - public dev.caskeleton.application.notification.platform.port.in.PublishNotificationTemplateUseCase - publishNotificationTemplateUseCase( - TemplateRegistry templates, - dev.caskeleton.application.notification.platform.dispatch.MessageDigestPort digests, - TransactionPort transactions) { - return new dev.caskeleton.application.notification.platform.dispatch - .PublishNotificationTemplateApplicationUseCase(templates, digests, transactions); - } - - @Bean - public dev.caskeleton.application.notification.platform.port.in.SubmitNotificationUseCase - submitNotificationUseCase( - NotificationSubmissionService service, TransactionPort transactions) { - return new dev.caskeleton.application.notification.platform.dispatch - .SubmitNotificationApplicationUseCase(service, transactions); - } - - /** - * Scheduling a notification for later. - * - * @param service the shared submission service - * @param transactions the transaction boundary - * @return the use case - */ - @Bean - public dev.caskeleton.application.notification.platform.port.in.ScheduleNotificationUseCase - scheduleNotificationUseCase( - NotificationSubmissionService service, TransactionPort transactions) { - return new dev.caskeleton.application.notification.platform.dispatch - .ScheduleNotificationApplicationUseCase(service, transactions); - } - - /** - * Cancelling a notification. - * - * @param service the shared submission service - * @param transactions the transaction boundary - * @return the use case - */ - @Bean - public dev.caskeleton.application.notification.platform.port.in.CancelNotificationUseCase - cancelNotificationUseCase( - NotificationSubmissionService service, TransactionPort transactions) { - return new dev.caskeleton.application.notification.platform.dispatch - .CancelNotificationApplicationUseCase(service, transactions); - } - - /** - * Reading a notification. - * - * @param service the shared submission service - * @param transactions the transaction boundary - * @return the use case - */ - @Bean - public dev.caskeleton.application.notification.platform.port.in.GetNotificationUseCase - getNotificationUseCase(NotificationSubmissionService service, TransactionPort transactions) { - return new dev.caskeleton.application.notification.platform.dispatch - .GetNotificationApplicationUseCase(service, transactions); - } - - /** - * The N4 operator plane. - * - * @param authorization operator authority and tenant scope - * @param duplicateRiskGuard ambiguous-redrive approval - * @param attempts the attempt store - * @param recipients the delivery store - * @param reconciliation the reconciliation service - * @param suppressions the suppression store - * @param runtimes the narrow runtime control port - * @param operations the admin operation claims - * @param audit the audit sink - * @param transactions the transaction boundary - * @param ids the identifier generator the suppression rows use - * @param digests stable SHA-256 used to bind an operation id to its command - * @param clock the clock - * @return the admin service - */ - @Bean - public dev.caskeleton.application.notification.platform.admin.NotificationAdminService - notificationAdminService( - dev.caskeleton.application.notification.platform.admin.AdminAuthorizationGuard - authorization, - dev.caskeleton.application.notification.platform.admin.DuplicateRiskGuard - duplicateRiskGuard, - DeliveryAttemptStorePort attempts, - RecipientDeliveryStorePort recipients, - ReconciliationService reconciliation, - dev.caskeleton.application.notification.platform.policy.SuppressionStorePort suppressions, - dev.caskeleton.application.notification.platform.admin.ProviderRuntimeControlPort - runtimes, - dev.caskeleton.application.notification.platform.admin.AdminOperationStorePort operations, - dev.caskeleton.application.notification.platform.observation.NotificationAuditPort audit, - TransactionPort transactions, - NotificationIdGeneratorPort ids, - dev.caskeleton.application.notification.platform.dispatch.MessageDigestPort digests, - Clock clock) { - return new dev.caskeleton.application.notification.platform.admin - .NotificationAdminApplicationService( - authorization, - duplicateRiskGuard, - attempts, - recipients, - reconciliation, - suppressions, - runtimes, - operations, - audit, - transactions, - ids, - digests, - clock); - } - - /** Dispatch orchestration. */ - @Bean - public NotificationDispatchService notificationDispatchService( - NotificationRequestStorePort requests, - RecipientDeliveryStorePort recipients, - DeliveryAttemptStorePort attempts, - DispatchPipeline pipeline, - RoutingDecisionEngine routing, - NotificationRetryPolicy retryPolicy, - DeliveryAttemptFactory attemptFactory, - DispatchOutcomeRecorder recorder, - ProviderDispatchGatewayPort gateway, - TemplateRendererRegistry renderers, - RecipientLeaseStorePort leases, - TransactionPort transactions, - Clock clock, - NotificationDispatchProperties properties) { - return new NotificationDispatchService( - requests, - recipients, - attempts, - pipeline, - routing, - retryPolicy, - attemptFactory, - recorder, - gateway, - renderers, - leases, - transactions, - clock, - properties.maxAdditionalAttempts(), - properties.estimatedDispatchDuration()); - } - - /** Ledger projection. */ - @Bean - public ProviderEventProjectionService providerEventProjectionService( - ProviderEventLedger ledger, - ProviderEventProjectorRegistry projectors, - DeliveryAttemptResolverPort resolver, - DeliveryProjectionStorePort projections, - NotificationSideEffectPort sideEffects, - TransactionPort transactions, - NotificationMetricsPort metrics) { - return new ProviderEventProjectionService( - ledger, projectors, resolver, projections, sideEffects, transactions, metrics); - } - - /** Semantic callback ingestion after provider verification has completed. */ - @Bean - public IngestProviderCallbackApplicationUseCase providerCallbackIngestionService( - ProviderEventLedger ledger, - dev.caskeleton.application.transaction.TransactionPort transactions, - CallbackPayloadProtectionPort payloadProtection, - NotificationMetricsPort metrics, - Clock clock) { - return new IngestProviderCallbackApplicationUseCase( - ledger, transactions, payloadProtection, metrics, clock); - } - - /** - * The adapter-to-adapter callback bridge owned by the composition root. - * - *

Raw HTTP remains in the inbound adapter, provider signature verification remains in the - * outbound provider integration, and only the verified semantic callback crosses the application - * port. - */ - @Bean - public ProviderCallbackIngress providerCallbackIngress( - ProviderCallbackAdapterRegistry adapters, - IngestProviderCallbackUseCase ingestion, - NotificationSecurityAuditPort securityAudit) { - return new ProviderCallbackIngressBridge(adapters, ingestion, securityAudit); - } -} diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxCanonicalTransportRequirementValidator.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxCanonicalTransportRequirementValidator.java index 48db55a3..ea29a724 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxCanonicalTransportRequirementValidator.java +++ b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxCanonicalTransportRequirementValidator.java @@ -1,8 +1,8 @@ package dev.caskeleton.bootstrap.autoconfigure.outbox; +import dev.caskeleton.adapter.outbound.support.startup.StartupFailures; import dev.caskeleton.application.messaging.event.IntegrationEventEncoderPort; import dev.caskeleton.application.messaging.event.IntegrationEventPublishPort; -import dev.caskeleton.bootstrap.runtime.startup.StartupFailures; import java.util.Objects; import org.springframework.beans.factory.InitializingBean; @@ -51,10 +51,9 @@ public final class OutboxCanonicalTransportRequirementValidator implements Initi if (encoder == null) { throw StartupFailures.requiredAdapterDisabled( CANONICAL_KEY - + "=true also requires an IntegrationEventEncoderPort. The repository ships a " - + "JsonSchemaIntegrationEventEncoder implementation, but the Stable composition does " - + "not compile an application contract catalog or schema registry automatically. " - + "Provide the encoder as part of the application messaging composition or set " + + "=true also requires an IntegrationEventEncoderPort bean. The template ships no " + + "implementation: the adopter owns its event contracts and must provide the " + + "encoder as part of the application messaging composition, or set " + CANONICAL_KEY + "=false."); } diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxConfig.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxConfig.java index 7f545908..3023c8ea 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxConfig.java +++ b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxConfig.java @@ -11,40 +11,49 @@ import dev.caskeleton.application.transaction.TransactionPort; import io.micrometer.core.instrument.MeterRegistry; import java.time.Clock; import java.util.SplittableRandom; +import java.util.UUID; import java.util.random.RandomGenerator; import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.autoconfigure.AutoConfiguration; +import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; +import org.springframework.scheduling.annotation.EnableScheduling; /** - * Composition-root wiring for the transactional outbox relay: assembles the relay use case manually - * and registers the leader-election token, metrics, and scheduler. See README for the design - * rationale. + * The transactional outbox relay: assembles the relay use case manually and registers the leader + * election token, metrics, and scheduler. See README for the design rationale. + * + *

Application composition, like the idempotency executor: it wires application-core ports into a + * use case and drives it on a timer, which is why it stays in the composition root rather than in + * the persistence module — a driven adapter must not construct or call use cases. It names no + * module type, only ports, and it turns itself on from what the selected modules provide. * *

{@code ca-skeleton.outbox.enabled} is the capability switch; {@code relay-enabled} only - * decides whether the scheduler runs. The two were conflated before, so a deployment with the relay - * off still assembled settings, a validator, an RNG, a leader token, and outbox metrics over a - * store port that a database-less deployment does not have. + * decides whether the scheduler runs. The store port exists only while the persistence-jpa module + * is selected and its outbox is on, so this configuration waits for it: removing that module's + * build line removes the relay with it. + * + *

The scheduler additionally needs somewhere to publish. It is created only when an {@link + * OutboxMessagePublishPort} bean exists — the messaging bridge contributes one — so a deployment + * that selected no publishing capability keeps its PENDING rows instead of failing every claim + * against a stand-in and exhausting them to DEAD. Ordered after both contributing + * auto-configurations by name, because a bean condition only sees what was registered before it. */ -@AutoConfiguration +@AutoConfiguration( + afterName = { + "dev.caskeleton.adapter.outbound.persistence.autoconfigure.PersistenceJpaAutoConfiguration", + "dev.caskeleton.adapter.outbound.messaging.autoconfigure.MessagingBridgeRootAutoConfiguration" + }) @ConditionalOnProperty(prefix = "ca-skeleton.outbox", name = "enabled", havingValue = "true") +@ConditionalOnBean(OutboxStorePort.class) @EnableConfigurationProperties(OutboxSettings.class) +// The relay is @Scheduled. It must switch scheduling on itself rather than rely on another +// capability (the PostgreSQL idempotency provider also does), or the relay runs only by accident. +@EnableScheduling public class OutboxConfig { - /** - * Refuses a relay that has nowhere to publish. - * - * @param environment the Spring environment - * @return the startup validator - */ - @Bean - public OutboxRelayBrokerRequirementValidator outboxRelayBrokerRequirementValidator( - org.springframework.core.env.Environment environment) { - return new OutboxRelayBrokerRequirementValidator(environment); - } - /** Requires the canonical messaging bridge whenever canonical outbox transport is enabled. */ @Bean public OutboxCanonicalTransportRequirementValidator outboxCanonicalTransportRequirementValidator( @@ -55,15 +64,13 @@ public class OutboxConfig { settings, canonicalPublisherProvider.getIfAvailable(), encoderProvider.getIfAvailable()); } - /** - * Relay use case is assembled manually here (not a bean) from {@link OutboxSettings} values. See - * README for the design rationale. - */ + /** Relay use case is assembled manually here (not a bean) from {@link OutboxSettings} values. */ @Bean @ConditionalOnProperty( name = "ca-skeleton.outbox.relay-enabled", havingValue = "true", matchIfMissing = true) + @ConditionalOnBean(OutboxMessagePublishPort.class) public OutboxRelayScheduler outboxRelayScheduler( OutboxStorePort store, OutboxMessagePublishPort publishPort, @@ -73,6 +80,8 @@ public class OutboxConfig { RandomGenerator outboxRandomGenerator, OutboxSettings properties, OutboxMetrics metrics) { + // One lease owner per relay instance. Its claims record it, and a completion applies only while + // this owner's lease still holds the row (V17 fencing). PublishPendingOutboxEventsUseCase relayUseCase = new PublishPendingOutboxEventsUseCase( store, @@ -82,7 +91,8 @@ public class OutboxConfig { new OutboxBackoffPolicy(outboxRandomGenerator), clock, properties.batchSize(), - properties.inFlightTimeout()); + properties.inFlightTimeout(), + UUID.randomUUID().toString()); return new OutboxRelayScheduler(relayUseCase, metrics, clock); } diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxMetrics.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxMetrics.java index 08bc1e8b..6b2c0f89 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxMetrics.java +++ b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxMetrics.java @@ -1,9 +1,9 @@ package dev.caskeleton.bootstrap.autoconfigure.outbox; +import dev.caskeleton.adapter.outbound.support.startup.RuntimeWarnings; import dev.caskeleton.application.outbox.OutboxEventStatus; import dev.caskeleton.application.outbox.OutboxRelayResult; import dev.caskeleton.application.outbox.OutboxStorePort; -import dev.caskeleton.bootstrap.runtime.RuntimeWarnings; import io.micrometer.core.instrument.Counter; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.MultiGauge; @@ -49,7 +49,7 @@ public final class OutboxMetrics { } } - /** Counts each terminal outcome (PUBLISHED, FAILED, DEAD; not IN_FLIGHT). */ + /** Counts each per-event outcome (PUBLISHED, FAILED, DEAD, STALE; never IN_FLIGHT). */ public void recordRelayResult(OutboxRelayResult result) { if (registry == null || result == null) { return; diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxRelayBrokerRequirementValidator.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxRelayBrokerRequirementValidator.java deleted file mode 100644 index e2227b31..00000000 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxRelayBrokerRequirementValidator.java +++ /dev/null @@ -1,64 +0,0 @@ -package dev.caskeleton.bootstrap.autoconfigure.outbox; - -import dev.caskeleton.bootstrap.runtime.startup.StartupFailures; -import java.util.Objects; -import org.springframework.beans.factory.InitializingBean; -import org.springframework.core.env.Environment; - -/** - * Refuses to start a relay that has nowhere to publish. - * - *

{@code ca-skeleton.outbox.relay-enabled} defaults to true and {@code app.messaging.broker} - * defaults to blank, so the shipped configuration starts a relay wired to {@code - * DisabledOutboxMessagePublisher}. That publisher throws on every call, and the relay treats a - * throw as a publish failure: it claims a batch of PENDING rows, marks them IN_FLIGHT, fails them - * with backoff, and eventually exhausts them to DEAD. An environment that is deliberately - * messaging-off therefore does not park its outbox — it destroys it, one retry budget at a time, - * and the rows that mattered are terminal by the time anyone notices. - * - *

Two configurations are coherent: a relay with a broker, or no relay. This makes the third one - * a startup failure that names both keys, rather than a slow data-loss bug. - */ -public final class OutboxRelayBrokerRequirementValidator implements InitializingBean { - - private static final String RELAY_KEY = "ca-skeleton.outbox.relay-enabled"; - private static final String BROKER_KEY = "app.messaging.broker"; - - private final Environment environment; - - /** - * Creates the validator. - * - * @param environment the Spring environment, read for both keys - */ - public OutboxRelayBrokerRequirementValidator(Environment environment) { - this.environment = Objects.requireNonNull(environment, "environment must not be null"); - } - - @Override - public void afterPropertiesSet() { - validate(); - } - - /** - * Refuses an enabled relay with no broker configured. - * - * @throws IllegalStateException naming both keys and both coherent configurations - */ - public void validate() { - // The relay bean's own condition uses matchIfMissing = true, so absent means enabled here too. - boolean relayEnabled = environment.getProperty(RELAY_KEY, Boolean.class, Boolean.TRUE); - String broker = environment.getProperty(BROKER_KEY, ""); - if (!relayEnabled || !broker.isBlank()) { - return; - } - throw StartupFailures.requiredAdapterDisabled( - RELAY_KEY - + " is enabled but " - + BROKER_KEY - + " is blank, so every claimed outbox row would fail to publish and be exhausted to" - + " DEAD. Either configure a broker, or set " - + RELAY_KEY - + "=false so PENDING rows are preserved until one exists."); - } -} diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxSettings.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxSettings.java index bf1a049d..13540da2 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxSettings.java +++ b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxSettings.java @@ -1,6 +1,6 @@ package dev.caskeleton.bootstrap.autoconfigure.outbox; -import dev.caskeleton.bootstrap.runtime.startup.StartupFailures; +import dev.caskeleton.adapter.outbound.support.startup.StartupFailures; import java.time.Duration; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.validation.annotation.Validated; diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/redis/RedisActivationValidator.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/redis/RedisActivationValidator.java deleted file mode 100644 index b6d073a5..00000000 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/redis/RedisActivationValidator.java +++ /dev/null @@ -1,91 +0,0 @@ -package dev.caskeleton.bootstrap.autoconfigure.redis; - -import dev.caskeleton.bootstrap.runtime.SecretSourceValidator; -import dev.caskeleton.bootstrap.runtime.startup.StartupPhase; -import dev.caskeleton.bootstrap.runtime.startup.StartupValidationContext; -import java.util.Map; -import java.util.Objects; -import org.springframework.beans.factory.SmartInitializingSingleton; -import org.springframework.core.env.ConfigurableEnvironment; - -/** - * Refuses a deployment that selects Redis for a role while Redis itself is switched off. - * - *

{@code app.redis.enabled} is the only global activation authority. A role selector says which - * Redis capability should compose, never whether Redis exists, so "off plus a Redis role" is not a - * defaulting question with a sensible answer — it is two settings that contradict each other. - * - *

Without this check the contradiction surfaces much later and much worse: composition proceeds, - * the conditional Redis configuration creates nothing, and startup dies on whichever provider - * selector notices a missing bean first. That failure names a bean the operator never configured - * and stays silent about the one line that caused it. Every offending role is listed together so a - * misconfigured deployment is fixed in one pass rather than one restart per role. - */ -public class RedisActivationValidator implements SmartInitializingSingleton { - - /** Role selector property to the value that selects Redis for it. */ - private static final Map REDIS_SELECTING_VALUES = - Map.of( - "ca-skeleton.capabilities.cache.bindings.default", "redis", - "ca-skeleton.capabilities.rate-limit.provider", "redis", - "ca-skeleton.capabilities.idempotency.provider", "redis", - "ca-skeleton.capabilities.lease.provider", "redis", - "ca-skeleton.security.auth-mode", "redis-session"); - - private final ConfigurableEnvironment environment; - - public RedisActivationValidator(ConfigurableEnvironment environment) { - this.environment = Objects.requireNonNull(environment, "environment must be non-null"); - } - - @Override - public void afterSingletonsInstantiated() { - if (isRedisGloballyEnabled()) { - validateIdempotencyKeyVersion(); - return; - } - StartupValidationContext contradictions = - StartupValidationContext.forPhase(StartupPhase.ADAPTER_ENABLEMENT); - REDIS_SELECTING_VALUES.forEach( - (property, selectingValue) -> { - String configured = environment.getProperty(property); - if (selectingValue.equalsIgnoreCase(configured)) { - contradictions.reject(property + "=" + configured); - } - }); - contradictions - .sorted() - .failIfViolated( - "Redis is disabled (" - + SecretSourceValidator.REDIS_ENABLED_PROPERTY - + "=false, env APP_REDIS_ENABLED) but these roles select it", - "set APP_REDIS_ENABLED=true to compose Redis, or point each role at a non-Redis " - + "provider. A role selector never activates Redis on its own."); - } - - private void validateIdempotencyKeyVersion() { - if (!"redis" - .equalsIgnoreCase( - environment.getProperty("ca-skeleton.capabilities.idempotency.provider", "disabled"))) { - return; - } - int keyVersion = - environment.getProperty( - "ca-skeleton.capabilities.idempotency.key-version", Integer.class, 1); - if (keyVersion == 1) { - return; - } - - StartupValidationContext.forPhase(StartupPhase.ADAPTER_ENABLEMENT) - .reject("ca-skeleton.capabilities.idempotency.key-version=" + keyVersion) - .failIfViolated( - "Redis idempotency key-version rotation is unsupported without dual-read", - "keep ca-skeleton.capabilities.idempotency.key-version=1 until a migration can read " - + "the previous keyspace during the replay-retention window."); - } - - private boolean isRedisGloballyEnabled() { - return Boolean.parseBoolean( - environment.getProperty(SecretSourceValidator.REDIS_ENABLED_PROPERTY, "false")); - } -} diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/tracing/TracingSamplingEnvironmentPostProcessor.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/tracing/TracingSamplingEnvironmentPostProcessor.java index 8c12f23e..8eb1c33a 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/tracing/TracingSamplingEnvironmentPostProcessor.java +++ b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/tracing/TracingSamplingEnvironmentPostProcessor.java @@ -1,7 +1,7 @@ package dev.caskeleton.bootstrap.autoconfigure.tracing; import dev.caskeleton.adapter.outbound.support.runtime.RuntimeProfileSnapshot; -import dev.caskeleton.bootstrap.runtime.startup.StartupOrder; +import dev.caskeleton.adapter.outbound.support.startup.StartupOrder; import java.util.List; import java.util.Map; import org.springframework.boot.EnvironmentPostProcessor; diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/tracing/TracingSamplingRateGauge.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/tracing/TracingSamplingRateGauge.java index d66bd7a8..f83206be 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/tracing/TracingSamplingRateGauge.java +++ b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/tracing/TracingSamplingRateGauge.java @@ -1,6 +1,6 @@ package dev.caskeleton.bootstrap.autoconfigure.tracing; -import dev.caskeleton.bootstrap.runtime.RuntimeWarnings; +import dev.caskeleton.adapter.outbound.support.startup.RuntimeWarnings; import io.micrometer.core.instrument.Gauge; import io.micrometer.core.instrument.MeterRegistry; import org.springframework.beans.factory.ObjectProvider; diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/tracing/TracingSettings.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/tracing/TracingSettings.java index 39f8fb6f..e196720c 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/tracing/TracingSettings.java +++ b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/tracing/TracingSettings.java @@ -1,6 +1,6 @@ package dev.caskeleton.bootstrap.autoconfigure.tracing; -import dev.caskeleton.bootstrap.runtime.startup.StartupFailures; +import dev.caskeleton.adapter.outbound.support.startup.StartupFailures; import java.net.URI; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.validation.annotation.Validated; diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/logging/StartupFailureSpringBootLogFilter.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/logging/StartupFailureSpringBootLogFilter.java index d7275b9a..e0e9a1f7 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/logging/StartupFailureSpringBootLogFilter.java +++ b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/logging/StartupFailureSpringBootLogFilter.java @@ -4,7 +4,7 @@ import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.turbo.TurboFilter; import ch.qos.logback.core.spi.FilterReply; -import dev.caskeleton.bootstrap.runtime.startup.StartupFailureLogState; +import dev.caskeleton.adapter.outbound.support.startup.StartupFailureLogState; import java.util.Set; import org.slf4j.Marker; diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/management/security/ManagementSecurityConfig.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/management/security/ManagementSecurityConfig.java index 967cbc55..a5ade0c1 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/management/security/ManagementSecurityConfig.java +++ b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/management/security/ManagementSecurityConfig.java @@ -32,19 +32,7 @@ public class ManagementSecurityConfig { auth -> auth // permit-all for probes and Prometheus scrape. - // - // adapteractivation joins them deliberately. It reports which master switches - // resolved on, and nothing else: property names, booleans, and the reasons a - // relational connection is required. No address, no credential, no schema — and - // AdapterActivationReportShapeTest is what keeps it that way rather than a - // promise in this comment. - // - // The alternative was worse. Authentication here is JWT, so a smoke lane could - // only read the report where an identity provider was already running, which - // excludes every lane that starts no infrastructure — the all-off lanes, which - // are exactly the ones whose claim is hardest to check any other way. - .requestMatchers( - EndpointRequest.to("health", "info", "prometheus", "adapteractivation")) + .requestMatchers(EndpointRequest.to("health", "info", "prometheus")) .permitAll() .requestMatchers(HttpMethod.POST, "/actuator/loggers/**") .denyAll() diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/ErrorDetailExposureSafetyValidator.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/ErrorDetailExposureSafetyValidator.java new file mode 100644 index 00000000..93126679 --- /dev/null +++ b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/ErrorDetailExposureSafetyValidator.java @@ -0,0 +1,67 @@ +package dev.caskeleton.bootstrap.runtime; + +import dev.caskeleton.adapter.outbound.support.runtime.RuntimeProfileSnapshot; +import dev.caskeleton.adapter.outbound.support.startup.StartupFailures; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import org.springframework.beans.factory.SmartInitializingSingleton; +import org.springframework.core.env.Environment; + +/** + * Keeps error internals out of production responses. Boot's {@code /error} body can carry the stack + * trace, the exception message, binding errors (with the rejected input) and the exception class; + * each is an environment override away in {@code application.yml}, so a YAML default alone does not + * hold them off in prod. + */ +public class ErrorDetailExposureSafetyValidator implements SmartInitializingSingleton { + + /** Each key that must stay {@code never}, with the name an operator would have set. */ + private static final Map MUST_BE_NEVER = new LinkedHashMap<>(); + + static { + MUST_BE_NEVER.put("spring.web.error.include-stacktrace", "APP_SERVER_ERROR_INCLUDE_STACKTRACE"); + MUST_BE_NEVER.put("spring.web.error.include-message", "APP_SERVER_ERROR_INCLUDE_MESSAGE"); + MUST_BE_NEVER.put( + "spring.web.error.include-binding-errors", "spring.web.error.include-binding-errors"); + } + + private static final String INCLUDE_EXCEPTION = "spring.web.error.include-exception"; + + private final Environment environment; + + public ErrorDetailExposureSafetyValidator(Environment environment) { + this.environment = environment; + } + + @Override + public void afterSingletonsInstantiated() { + if (!RuntimeProfileSnapshot.from(environment).isProduction()) { + return; + } + List violations = new ArrayList<>(); + MUST_BE_NEVER.forEach( + (key, shownAs) -> { + String value = environment.getProperty(key); + if (value != null && !"never".equals(normalized(value))) { + violations.add(shownAs + "=" + value.trim()); + } + }); + String includeException = environment.getProperty(INCLUDE_EXCEPTION); + if (includeException != null && "true".equals(normalized(includeException))) { + violations.add(INCLUDE_EXCEPTION + "=true"); + } + if (!violations.isEmpty()) { + throw StartupFailures.profileMismatch( + "prod profile requires error details to stay out of responses (include-* = never, " + + "include-exception = false), but found " + + String.join(", ", violations)); + } + } + + private static String normalized(String value) { + return value.trim().toLowerCase(Locale.ROOT); + } +} diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/activation/RuntimeEnvironmentProfileValidator.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/RuntimeEnvironmentProfileValidator.java similarity index 88% rename from src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/activation/RuntimeEnvironmentProfileValidator.java rename to src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/RuntimeEnvironmentProfileValidator.java index 6d5ef5af..b379649d 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/activation/RuntimeEnvironmentProfileValidator.java +++ b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/RuntimeEnvironmentProfileValidator.java @@ -1,8 +1,8 @@ -package dev.caskeleton.bootstrap.activation; +package dev.caskeleton.bootstrap.runtime; import dev.caskeleton.adapter.outbound.support.runtime.RuntimeProfileSnapshot; -import dev.caskeleton.bootstrap.runtime.startup.StartupFailures; -import dev.caskeleton.bootstrap.runtime.startup.StartupOrder; +import dev.caskeleton.adapter.outbound.support.startup.StartupFailures; +import dev.caskeleton.adapter.outbound.support.startup.StartupOrder; import dev.caskeleton.shared.runtime.RuntimeEnvironment; import java.util.List; import org.springframework.boot.EnvironmentPostProcessor; @@ -18,9 +18,9 @@ import org.springframework.core.env.ConfigurableEnvironment; * meant an in-memory database that loses every write on restart. The failure had no symptom until * the data was already gone. * - *

Feature selection is not expressed here. That is what the registered master switches are for, - * and a supplementary profile used as a feature flag is how a profile list stops being a statement - * about where the application is running. + *

Feature selection is not expressed here. A capability is selected by adding its module to the + * build, and a supplementary profile used as a feature flag is how a profile list stops being a + * statement about where the application is running. * *

Scoped to the deployable artifact, which means contexts whose main class is {@link * dev.caskeleton.bootstrap.CaSkeletonApplication}. Slice tests boot minimal applications with no @@ -70,7 +70,7 @@ public class RuntimeEnvironmentProfileValidator implements EnvironmentPostProces + String.join(",", active) + " names no runtime environment. Set exactly one of " + RuntimeEnvironment.deployableProfileNames() - + "; a capability is selected with its master switch, never with a profile."); + + "; a capability is selected by adding its module, never with a profile."); } } diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/RuntimeNumericBoundsValidator.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/RuntimeNumericBoundsValidator.java index e0ac185e..8b3dd6bc 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/RuntimeNumericBoundsValidator.java +++ b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/RuntimeNumericBoundsValidator.java @@ -1,7 +1,7 @@ package dev.caskeleton.bootstrap.runtime; -import dev.caskeleton.bootstrap.runtime.startup.StartupPhase; -import dev.caskeleton.bootstrap.runtime.startup.StartupValidationContext; +import dev.caskeleton.adapter.outbound.support.startup.StartupPhase; +import dev.caskeleton.adapter.outbound.support.startup.StartupValidationContext; import java.util.List; import org.springframework.beans.factory.SmartInitializingSingleton; import org.springframework.core.env.Environment; @@ -17,13 +17,11 @@ public class RuntimeNumericBoundsValidator implements SmartInitializingSingleton static final List BOUNDS = List.of( - // positive (>= 1) - new Bound( - "spring.datasource.hikari.maximum-pool-size", "APP_DATASOURCE_POOL_MAX_SIZE", 1), + // positive (>= 1). Pool sizing is checked by the persistence-jpa module that owns the + // pool. new Bound("server.tomcat.threads.max", "APP_SERVER_TOMCAT_MAX_THREADS", 1), new Bound("server.tomcat.max-connections", "APP_SERVER_TOMCAT_MAX_CONNECTIONS", 1), // non-negative (>= 0) - new Bound("spring.datasource.hikari.minimum-idle", "APP_DATASOURCE_POOL_MIN_IDLE", 0), new Bound("server.tomcat.threads.min-spare", "APP_SERVER_TOMCAT_MIN_SPARE_THREADS", 0), new Bound("server.tomcat.accept-count", "APP_SERVER_TOMCAT_ACCEPT_COUNT", 0)); diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/RuntimeSafetyConfig.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/RuntimeSafetyConfig.java index 72fe9857..f8cac611 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/RuntimeSafetyConfig.java +++ b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/RuntimeSafetyConfig.java @@ -8,7 +8,8 @@ import org.springframework.core.env.Environment; /** * Wires the runtime-safety startup fail-fast validators into the running application. See README - * for the design rationale. + * for the design rationale. The relational guards (OSIV, DDL, pool, TLS, vendor) belong to the + * persistence-jpa module and arrive with it. */ @Configuration public class RuntimeSafetyConfig { @@ -25,29 +26,7 @@ public class RuntimeSafetyConfig { } @Bean - OpenInViewSafetyValidator openInViewSafetyValidator(Environment environment) { - return new OpenInViewSafetyValidator(environment); - } - - @Bean - JpaSchemaSafetyValidator jpaSchemaSafetyValidator(Environment environment) { - return new JpaSchemaSafetyValidator(environment); - } - - @Bean - PostgreSqlTransportSecurityValidator postgreSqlTransportSecurityValidator( - Environment environment) { - return new PostgreSqlTransportSecurityValidator(environment); - } - - @Bean - PersistenceVendorProdSafetyValidator persistenceVendorProdSafetyValidator( - Environment environment) { - return new PersistenceVendorProdSafetyValidator(environment); - } - - @Bean - HikariPoolConstraintValidator hikariPoolConstraintValidator(Environment environment) { - return new HikariPoolConstraintValidator(environment); + ErrorDetailExposureSafetyValidator errorDetailExposureSafetyValidator(Environment environment) { + return new ErrorDetailExposureSafetyValidator(environment); } } diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceConfig.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceConfig.java index 70b661fd..ddde9f4a 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceConfig.java +++ b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceConfig.java @@ -1,7 +1,6 @@ package dev.caskeleton.bootstrap.runtime; import dev.caskeleton.application.outbound.SecretSourcePort; -import dev.caskeleton.bootstrap.autoconfigure.redis.RedisActivationValidator; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -26,19 +25,4 @@ public class SecretSourceConfig { ConfigurableEnvironment environment, SecretSourcePort secretSource) { return new SecretSourceValidator(environment, secretSource); } - - /** - * Guards the Redis activation contract. - * - *

It lives beside the secret validator because they read the same two inputs — the global - * switch and the role selectors — and disagreeing about them is exactly the failure both exist to - * prevent. - * - * @param environment the bound environment - * @return the validator - */ - @Bean - RedisActivationValidator redisActivationValidator(ConfigurableEnvironment environment) { - return new RedisActivationValidator(environment); - } } diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceValidator.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceValidator.java index c0322e4a..105024d9 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceValidator.java +++ b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceValidator.java @@ -1,9 +1,9 @@ package dev.caskeleton.bootstrap.runtime; import dev.caskeleton.adapter.outbound.support.runtime.RuntimeProfileSnapshot; +import dev.caskeleton.adapter.outbound.support.startup.StartupPhase; +import dev.caskeleton.adapter.outbound.support.startup.StartupValidationContext; import dev.caskeleton.application.outbound.SecretSourcePort; -import dev.caskeleton.bootstrap.runtime.startup.StartupPhase; -import dev.caskeleton.bootstrap.runtime.startup.StartupValidationContext; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; @@ -24,8 +24,8 @@ public class SecretSourceValidator implements SmartInitializingSingleton { /** * The one global Redis switch, bound from {@code APP_REDIS_ENABLED}. * - *

There is deliberately no second master switch. {@code APP_CACHE_REDIS_ENABLED} used to read - * like one, which is how a deployment with no Redis at all still had to supply cache Redis + *

There is deliberately no second capability switch. {@code APP_CACHE_REDIS_ENABLED} used to + * read like one, which is how a deployment with no Redis at all still had to supply cache Redis * credentials to reach a running state. */ public static final String REDIS_ENABLED_PROPERTY = "app.redis.enabled"; @@ -48,6 +48,17 @@ public class SecretSourceValidator implements SmartInitializingSingleton { "APP_LEASE_REDIS_KEY_HMAC_SECRET", "APP_PRIVACY_PSEUDONYMIZATION_SALT"); + /** + * The relational credential, required only while relational persistence is on. The switch is set + * by the persistence-jpa module's shipped defaults, so a composition without the module — the + * default one — owes no database password, the same way a deployment without Redis owes no Redis + * credential. + */ + private static final String DATASOURCE_PASSWORD = "APP_DATASOURCE_PASSWORD"; + + private static final String RELATIONAL_PERSISTENCE_PROPERTY = + "ca-skeleton.persistence-jpa.enabled"; + private final ConfigurableEnvironment environment; private final SecretSourcePort secretSource; @@ -95,6 +106,9 @@ public class SecretSourceValidator implements SmartInitializingSingleton { if (isRedisMaterial(key) && !isRedisRoleSelected(key)) { continue; } + if (DATASOURCE_PASSWORD.equals(key) && !isRelationalPersistenceOn()) { + continue; + } if (secretSource.resolve(key).isEmpty()) { validation.reject(key + " is missing/blank"); } @@ -134,7 +148,7 @@ public class SecretSourceValidator implements SmartInitializingSingleton { return isSelected("ca-skeleton.security.auth-mode", "jwt", "redis-session"); } if (key.startsWith("APP_IDEMPOTENCY_REDIS_")) { - return isSelected("ca-skeleton.capabilities.idempotency.provider", "jdbc", "redis"); + return isSelected("ca-skeleton.capabilities.idempotency.provider", "disabled", "redis"); } if (key.startsWith("APP_LEASE_REDIS_")) { return isSelected("ca-skeleton.capabilities.lease.provider", "disabled", "redis"); @@ -161,4 +175,9 @@ public class SecretSourceValidator implements SmartInitializingSingleton { private boolean isProdActive() { return RuntimeProfileSnapshot.from(environment).isProduction(); } + + private boolean isRelationalPersistenceOn() { + return Boolean.parseBoolean( + environment.getProperty(RELATIONAL_PERSISTENCE_PROPERTY, "false").trim()); + } } diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/StartupSafetyValidator.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/StartupSafetyValidator.java index d05f6e87..207caf80 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/StartupSafetyValidator.java +++ b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/StartupSafetyValidator.java @@ -1,8 +1,8 @@ package dev.caskeleton.bootstrap.runtime; +import dev.caskeleton.adapter.outbound.support.startup.StartupPhase; +import dev.caskeleton.adapter.outbound.support.startup.StartupValidationContext; import dev.caskeleton.application.lock.DistributedLockPort; -import dev.caskeleton.bootstrap.runtime.startup.StartupPhase; -import dev.caskeleton.bootstrap.runtime.startup.StartupValidationContext; import dev.caskeleton.bootstrap.settings.RuntimeSafetySettings; import org.springframework.beans.factory.ListableBeanFactory; import org.springframework.beans.factory.SmartInitializingSingleton; diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/startup/StartupFailureExceptionReporter.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/startup/StartupFailureExceptionReporter.java index f15b93e2..c52bbacc 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/startup/StartupFailureExceptionReporter.java +++ b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/startup/StartupFailureExceptionReporter.java @@ -1,6 +1,9 @@ package dev.caskeleton.bootstrap.runtime.startup; import dev.caskeleton.adapter.outbound.support.CapabilityStartupValidationException; +import dev.caskeleton.adapter.outbound.support.startup.StartupErrorCode; +import dev.caskeleton.adapter.outbound.support.startup.StartupFailureException; +import dev.caskeleton.adapter.outbound.support.startup.StartupFailures; import org.springframework.boot.SpringBootExceptionReporter; /** diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/startup/StartupOrder.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/startup/StartupOrder.java deleted file mode 100644 index 19afd86a..00000000 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/startup/StartupOrder.java +++ /dev/null @@ -1,66 +0,0 @@ -package dev.caskeleton.bootstrap.runtime.startup; - -import org.springframework.boot.context.config.ConfigDataEnvironmentPostProcessor; -import org.springframework.core.Ordered; - -/** - * The order every {@code EnvironmentPostProcessor} in this composition root runs in, in one place. - * - *

Six post-processors are registered in {@code META-INF/spring.factories} and their relative - * order is part of how they work — a capability violation reported against a key the master switch - * was about to rewrite sends an operator somewhere useless. Three of them nonetheless returned the - * same value, {@code Ordered.LOWEST_PRECEDENCE}, and a fourth declared no order at all (BOOT-005). - * The sequence held only because Spring sorts stably and {@code spring.factories} happened to list - * them in the intended order: reordering four lines in a text file would have silently changed - * behaviour, and nothing would have failed. - * - *

{@link dev.caskeleton.bootstrap.activation.CapabilityDependencyEnvironmentValidator} even - * documented the constraint in its {@code getOrder()} Javadoc — "after {@code - * MasterSwitchEnvironmentPostProcessor} has rejected legacy switch spellings" — while returning a - * value that could not express it. A comment stating an ordering its return value does not enforce - * is the shape this class exists to remove. - * - *

Two bands, and why

- * - *

The readiness post-processors contribute property sources and run immediately after config - * data, so they are expressed relative to {@link ConfigDataEnvironmentPostProcessor#ORDER}. The - * validators must observe the environment the application will actually run with — every - * contributed source included — so they stay at the {@code LOWEST_PRECEDENCE} end and are separated - * from each other by single steps. Keeping the last of them at exactly {@code LOWEST_PRECEDENCE} - * preserves this repository's existing position relative to any third-party post-processor at that - * value, so this change makes an undefined order deterministic without moving the whole band. - */ -public final class StartupOrder { - - private StartupOrder() {} - - /** Redis readiness group contribution — a property source, immediately after config data. */ - public static final int READINESS_REDIS = ConfigDataEnvironmentPostProcessor.ORDER + 1; - - /** Database readiness group contribution — a property source, immediately after config data. */ - public static final int READINESS_DATABASE = ConfigDataEnvironmentPostProcessor.ORDER + 2; - - /** - * Master-switch normalisation. First of the validators, because it rewrites and rejects legacy - * switch spellings; every rule after it reads the keys an operator will actually be told about. - */ - public static final int MASTER_SWITCH_NORMALISATION = Ordered.LOWEST_PRECEDENCE - 3; - - /** - * Runtime environment profile rule. After master-switch normalisation and before capability - * checks: which environment this is decides which capability combinations are even legal. - */ - public static final int RUNTIME_ENVIRONMENT_PROFILE = Ordered.LOWEST_PRECEDENCE - 2; - - /** - * Capability dependency graph. Last of the fail-closed rules, so its message names post-migration - * keys under a runtime environment that has already been established as valid. - */ - public static final int CAPABILITY_DEPENDENCY = Ordered.LOWEST_PRECEDENCE - 1; - - /** - * Tracing sample-rate defaulting. Runs after every rule that can refuse the boot outright — there - * is no value in defaulting a sample rate for a process that is about to exit. - */ - public static final int TRACING_SAMPLING = Ordered.LOWEST_PRECEDENCE; -} diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/security/AuthenticationModeCompositionConfig.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/security/AuthenticationModeCompositionConfig.java index c3c6bd60..9e35b47d 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/security/AuthenticationModeCompositionConfig.java +++ b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/security/AuthenticationModeCompositionConfig.java @@ -1,7 +1,7 @@ package dev.caskeleton.bootstrap.security; -import dev.caskeleton.bootstrap.runtime.startup.StartupPhase; -import dev.caskeleton.bootstrap.runtime.startup.StartupValidationContext; +import dev.caskeleton.adapter.outbound.support.startup.StartupPhase; +import dev.caskeleton.adapter.outbound.support.startup.StartupValidationContext; import org.springframework.beans.factory.ListableBeanFactory; import org.springframework.beans.factory.SmartInitializingSingleton; import org.springframework.boot.context.properties.EnableConfigurationProperties; diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/settings/LoggingSettings.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/settings/LoggingSettings.java index 3af317a2..28428963 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/settings/LoggingSettings.java +++ b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/settings/LoggingSettings.java @@ -1,6 +1,6 @@ package dev.caskeleton.bootstrap.settings; -import dev.caskeleton.bootstrap.runtime.RuntimeWarnings; +import dev.caskeleton.adapter.outbound.support.startup.RuntimeWarnings; import java.time.ZoneId; import org.springframework.boot.context.properties.ConfigurationProperties; diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/settings/PrivacySettings.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/settings/PrivacySettings.java index 4e4de4d8..73612d76 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/settings/PrivacySettings.java +++ b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/settings/PrivacySettings.java @@ -1,6 +1,6 @@ package dev.caskeleton.bootstrap.settings; -import dev.caskeleton.bootstrap.runtime.RuntimeWarnings; +import dev.caskeleton.adapter.outbound.support.startup.RuntimeWarnings; import java.nio.charset.StandardCharsets; import org.springframework.boot.context.properties.ConfigurationProperties; diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/settings/RuntimeSafetySettings.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/settings/RuntimeSafetySettings.java index dc685283..1116837a 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/settings/RuntimeSafetySettings.java +++ b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/settings/RuntimeSafetySettings.java @@ -1,14 +1,13 @@ package dev.caskeleton.bootstrap.settings; import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.boot.context.properties.bind.DefaultValue; /** * Operational runtime settings bound from {@code ca-skeleton.runtime.*}. * *

Only implemented controls belong here. Internal error-detail exposure and HTTP body logging - * have no runtime implementation and therefore no reserved configuration switch. + * have no runtime implementation and therefore no reserved configuration switch. {@code + * migration-on-startup} is read by the JPA module that runs the migration, not here. */ @ConfigurationProperties(prefix = "ca-skeleton.runtime") -public record RuntimeSafetySettings( - boolean multiInstanceEnabled, @DefaultValue("true") boolean migrationOnStartup) {} +public record RuntimeSafetySettings(boolean multiInstanceEnabled) {} diff --git a/src/app-bootstrap/src/main/resources/META-INF/spring.factories b/src/app-bootstrap/src/main/resources/META-INF/spring.factories index 40f0c7bf..6d8b085a 100644 --- a/src/app-bootstrap/src/main/resources/META-INF/spring.factories +++ b/src/app-bootstrap/src/main/resources/META-INF/spring.factories @@ -1,17 +1,10 @@ org.springframework.boot.EnvironmentPostProcessor=\ -dev.caskeleton.bootstrap.activation.MasterSwitchEnvironmentPostProcessor,\ -dev.caskeleton.bootstrap.activation.RuntimeEnvironmentProfileValidator,\ -dev.caskeleton.bootstrap.activation.CapabilityDependencyEnvironmentValidator,\ -dev.caskeleton.bootstrap.autoconfigure.tracing.TracingSamplingEnvironmentPostProcessor,\ -dev.caskeleton.bootstrap.autoconfigure.redis.RedisReadinessGroupPostProcessor,\ -dev.caskeleton.bootstrap.autoconfigure.jpa.DatabaseReadinessGroupPostProcessor +dev.caskeleton.bootstrap.runtime.RuntimeEnvironmentProfileValidator,\ +dev.caskeleton.bootstrap.autoconfigure.tracing.TracingSamplingEnvironmentPostProcessor org.springframework.boot.SpringBootExceptionReporter=\ dev.caskeleton.bootstrap.runtime.startup.StartupFailureExceptionReporter -org.springframework.boot.autoconfigure.AutoConfigurationImportFilter=\ -dev.caskeleton.bootstrap.autoconfigure.jpa.JpaOffAutoConfigurationImportFilter - # Corrects the structured log's profile field once the environment has resolved. An # ApplicationListener, not a bean: this event fires before there is a context to hold one. org.springframework.context.ApplicationListener=\ diff --git a/src/app-bootstrap/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/src/app-bootstrap/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports index 818ac665..1e3c2e8a 100644 --- a/src/app-bootstrap/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports +++ b/src/app-bootstrap/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports @@ -1,9 +1,4 @@ dev.caskeleton.bootstrap.autoconfigure.common.BootstrapClockAutoConfiguration -dev.caskeleton.bootstrap.autoconfigure.jpa.PersistenceJpaRootAutoConfiguration -dev.caskeleton.bootstrap.autoconfigure.messaging.DisabledMessagingSentinelAutoConfiguration -dev.caskeleton.bootstrap.activation.AdapterActivationAutoConfiguration -dev.caskeleton.bootstrap.autoconfigure.notification.NotificationApplicationCompositionAutoConfiguration dev.caskeleton.bootstrap.autoconfigure.outbox.OutboxConfig -dev.caskeleton.bootstrap.autoconfigure.lock.DistributedLockConfig dev.caskeleton.bootstrap.autoconfigure.idempotency.IdempotencyProviderSelectionConfig dev.caskeleton.bootstrap.autoconfigure.tracing.TracingConfig diff --git a/src/app-bootstrap/src/main/resources/application-local.yml b/src/app-bootstrap/src/main/resources/application-local.yml index 6e1629c8..effcd09e 100644 --- a/src/app-bootstrap/src/main/resources/application-local.yml +++ b/src/app-bootstrap/src/main/resources/application-local.yml @@ -167,8 +167,6 @@ ca-skeleton: # keeps the local pseudonymization stable across runs and keeps the warning for deployments # that really did forget to supply one. pseudonymization-salt: __LOCAL_DEV_pseudonymization_salt - idempotency: - ttl: 24h security: # Placeholders for the reason above: the two blocks must agree, and a literal in either one is # a value a deployment cannot correct. @@ -203,16 +201,3 @@ ca-skeleton: logger-name-length: 0 # Keep every log line locally; prod samples <=INFO down to 10%. sampling-rate: 1.0 - -app: - messaging: - # Blank selects no transport, which is right for a default local run — but as a literal it also - # outranked every environment a caller supplied, so a lane that started Kafka and set - # APP_MESSAGING_BROKER was refused by the dependency validator for a value it had actually - # provided. The switch decides whether there is a broker; this decides which one. - broker: ${APP_MESSAGING_BROKER:} - notification: - slack-webhook: - enabled: ${APP_NOTIFICATION_SLACK_WEBHOOK_ENABLED:false} - google-email: - enabled: ${APP_NOTIFICATION_GOOGLE_EMAIL_ENABLED:false} diff --git a/src/app-bootstrap/src/main/resources/application-prod.yml b/src/app-bootstrap/src/main/resources/application-prod.yml index 2f53a960..abc999e5 100644 --- a/src/app-bootstrap/src/main/resources/application-prod.yml +++ b/src/app-bootstrap/src/main/resources/application-prod.yml @@ -10,7 +10,7 @@ # # JpaSchemaSafetyValidator ddl-auto must be none|validate (exit 71) # FlywayProdSafetyValidator baseline-on-migrate / out-of-order / clean stay disarmed -# StartupSafetyValidator error-detail exposure and body-capture logging stay off +# ErrorDetailExposureSafetyValidator spring.web.error.include-* stay never/false (exit 71) # PostgreSqlTransportSecurityValidator pgJDBC sslmode=verify-full # PersistenceVendorProdSafetyValidator neither the vendor selector nor the URL may be H2 # diff --git a/src/app-bootstrap/src/main/resources/application.yml b/src/app-bootstrap/src/main/resources/application.yml index 26e7ddb2..951673bc 100644 --- a/src/app-bootstrap/src/main/resources/application.yml +++ b/src/app-bootstrap/src/main/resources/application.yml @@ -35,141 +35,6 @@ spring: # with a message about a missing value, and what an operator needs to read is # RuntimeEnvironmentProfileValidator saying which three profiles are permitted. active: ${SPRING_PROFILES_ACTIVE:} - datasource: - # jdbc URL: jdbc:postgresql://host:5432/db - url: ${APP_DATASOURCE_URL} - username: ${APP_DATASOURCE_USERNAME} - password: ${APP_DATASOURCE_PASSWORD} - driver-class-name: ${APP_DATASOURCE_DRIVER:org.postgresql.Driver} - hikari: - # D1 (feature-database-connection-pool-contract): small-pool axiom + PostgreSQL formula - # starting point (maximumPoolSize = cores * 2 + effective_spindle_count, adjust via load - # test). Fixed-size pool recommended (minimumIdle = maximumPoolSize). Must satisfy - # application-port D12 REQUIRES_NEW lower bound: - # maxPoolSize >= concurrent_threads * (1 + max_inNew_depth) + 1 - # Value owner: feature-env-driven-runtime-configuration (APP_DATASOURCE_POOL_MAX_SIZE). - # integer >= 1 - maximum-pool-size: ${APP_DATASOURCE_POOL_MAX_SIZE:10} - # D1: fixed-size pool recommended (minimumIdle = maximumPoolSize per HikariCP #HIKARI-CFG-C8). - # Current registry value min-idle=2 is a MIN_IDLE_POLICY_DRIFT vs the fixed-size - # recommendation; value alignment is delegated to feature-env-driven-runtime-configuration. - # integer >= 0 - minimum-idle: ${APP_DATASOURCE_POOL_MIN_IDLE:2} - # D2 (HIKARI-CFG-C1): fail-fast pin — reject pool-starved threads quickly rather than - # holding them for 30 s (HikariCP default). Must be >= 250 ms (enforced at startup by - # HikariPoolConstraintValidator). Typical synchronous HTTP path value: a few seconds. - # PLAIN MILLISECONDS ONLY. This key binds onto HikariConfig#setConnectionTimeout, which takes - # a long, so the binder rejects "5s" outright: `failed to convert java.lang.String to long`. - # It shipped as "5s" and every prod and dev deployment failed to start on it, while local - # passed because application-local.yml overrides the value — so only a prod lane could find - # it. HikariPoolConstraintValidator reads this key with DurationStyle and therefore accepts - # "5s" happily; that tolerance is what made the wrong default look supported, and it is - # recorded as an open Section A finding rather than quietly changed here. - connection-timeout: ${APP_DATASOURCE_CONNECTION_TIMEOUT:5000} - # milliseconds - idle-timeout: ${APP_DATASOURCE_POOL_IDLE_TIMEOUT:600000} - # D3 (HIKARI-CFG-C2): must be several seconds shorter than the DB/infrastructure idle - # timeout (DB wait_timeout, PgBouncer idle_transaction_timeout, firewall NAT timeout). - # Current default (30 min) is a placeholder until the actual DB wait_timeout is confirmed - # (see §Claims "DB wait_timeout 미확인" — needs-confirmation). Recommended: DB_idle_limit - # minus at least 60 s as a conservative margin. Value owner: feature-env-driven. - # milliseconds - max-lifetime: ${APP_DATASOURCE_POOL_MAX_LIFETIME:1800000} - # D4 (HIKARI-CFG-C4): greenfield — ping idle connections to prevent NAT/firewall/DB - # idle-kill from silently dropping them. Constraint: keepalive-time < max-lifetime - # (enforced by HikariPoolConstraintValidator). Provisional literal 120 000 ms (2 min); - # adjust once actual DB/firewall idle timeout is confirmed (§Claims). - # UNSUPPORTED_IMPL_DECISION: literal value is a provisional policy default. - # New env key APP_DATASOURCE_KEEPALIVE_TIME registration delegated to - # feature-env-driven-runtime-configuration. - keepalive-time: 120000 - # D5 (HIKARI-CFG-C5): greenfield — enable connection leak early warning. Value must be - # >= 2000 ms to activate (enforced by HikariPoolConstraintValidator; 0 = disabled). - # Provisional literal 30 000 ms (30 s) — chosen well above the estimated longest normal - # transaction (~5 s) to avoid false positives on legitimate slow operations. - # UNSUPPORTED_IMPL_DECISION: literal value is a provisional policy default. - # New env key APP_DATASOURCE_LEAK_DETECTION_THRESHOLD delegated to - # feature-env-driven-runtime-configuration. - leak-detection-threshold: 30000 - # D7 (HIKARI-CFG-C6): greenfield — must be < connection-timeout (HIKARI-CFG-C6), - # enforced by HikariPoolConstraintValidator. Resolves VALIDATION_TIMEOUT_CONFLICT: - # HikariCP default 5000 ms equals connection-timeout 5 s / 5000 ms → constraint - # violation. Provisional literal 3000 ms satisfies the constraint for connection-timeout - # values >= 3001 ms. - # UNSUPPORTED_IMPL_DECISION: literal value is a provisional policy default. - # New env key APP_DATASOURCE_VALIDATION_TIMEOUT delegated to - # feature-env-driven-runtime-configuration. - validation-timeout: 3000 - # D6 (HIKARI-CFG-C7): greenfield — keep positive (default = 1 ms) to fail fast when DB - # is unavailable at startup. Aligns with runtime-health startup validation and project-note - # §9 "잘못된 env 값 startup fail-fast" policy. Negative value disables fail-fast (allowed - # only in orchestration environments where DB may start after the app — coordinate with - # runtime-health-lifecycle branch). - # UNSUPPORTED_IMPL_DECISION: literal value is a provisional policy default. - # New env key APP_DATASOURCE_INIT_FAIL_TIMEOUT delegated to - # feature-env-driven-runtime-configuration. - initialization-fail-timeout: 1 - # --------------------------------------------------------------------------- - # D8 (feature-database-connection-pool-contract) — SLOW QUERY DETECTION - # POLICY ONLY — no library dependency added here. Implementation is DEFERRED - # pending local verification (TODO #3: confirm ParameterTransformer masking - # applies to slow-query listener output). - # - # Baseline (app layer, param-safe): - # datasource-proxy SlowQueryListener + ParameterTransformer ([REDACTED] masking). - # Requires the datasource-proxy / spring-boot-data-source-decorator dependency - # and a @Bean ParameterTransformer; deferred until masking behavior on slow-query - # output is locally verified. - # - # Production augment (DBA-owned): - # DB-side log_min_duration_statement — parameters included in extended-protocol - # output (PostgreSQL official security warning). DBA controls and redacts. - # - # Dev only (PROD-FORBIDDEN): - # Hibernate SQL_SLOW (LOG_QUERIES_SLOWER_THAN_MS) logs materialized SQL with - # substituted parameters — violates the "SQL/param 로그 금지" hard rule from - # feature-persistence-failure-baseline. NEVER enable in prod. - # - # Rejected: - # P6Spy — no built-in masking API; effective SQL exposes parameters by default - # with no safe override. Rejected per D8 (#C3/#C4). - # --------------------------------------------------------------------------- - # --------------------------------------------------------------------------- - # Flyway forward-only migration (feature-migration-startup-contract D1/D2/D4). - # Flyway runs during context refresh (Spring Boot autoconfig + the - # migrationStartupRunner FlywayMigrationStrategy), BEFORE the app reports - # readiness — so migration is inherently readiness-gated (D5): a failed or - # in-progress migration can never serve traffic. - # - # The three options below are PINNED, not env-driven: they are forbidden under - # prod (D2/D4) and a static pin means a future Flyway/Spring Boot default flip - # cannot silently re-enable them (same reasoning as spring.mvc.problemdetails. - # enabled above). FlywayProdSafetyValidator fails the boot (exit 71) if any - # per-environment override re-enables them under the prod profile. - # --------------------------------------------------------------------------- - flyway: - # false: never auto-baseline an existing schema — keep the missing-migration - # safety net (FLYWAY-C6). Enabling under prod is forbidden (D4). - baseline-on-migrate: false - # false: reject out-of-order migrations — preserve cross-developer ordering - # consistency (FLYWAY-C5). Enabling under prod is forbidden (D4). - out-of-order: false - # true: keep Flyway `clean` (drops the whole schema) disarmed. Disabling this - # under prod is forbidden — clean is destructive. - clean-disabled: true - jpa: - hibernate: - # none | validate | update | create | create-drop - # prod accepts only none|validate; JpaSchemaSafetyValidator rejects schema-writing modes. - ddl-auto: ${APP_DATASOURCE_DDL_AUTO:validate} - # true | false - show-sql: ${APP_DATASOURCE_SHOW_SQL:false} - # true | false (don't enable in prod) - open-in-view: ${APP_DATASOURCE_OPEN_IN_VIEW:false} - properties: - hibernate: - # true | false (paired with show-sql) - format_sql: ${APP_DATASOURCE_FORMAT_SQL:false} security: oauth2: resourceserver: @@ -190,19 +55,9 @@ spring: virtual: # true | false (Java 21 virtual threads for Tomcat request handlers) enabled: ${SPRING_THREADS_VIRTUAL_ENABLED:true} - servlet: - multipart: - # feature-api-contract-baseline D8: bound request body size so an oversized - # upload classifies as 413 PAYLOAD_TOO_LARGE inside the envelope (via - # GlobalExceptionHandler#handleMaxUploadSizeExceededException), never a raw 500. - # Multipart-specific upload limits (UPLOAD_SIZE_EXCEEDED) are refined by - # feature-file-resource-handling-contract. - # Same placeholders as app.fileserver-platform.upload.*, deliberately. Two independent - # ceilings meant the servlet container rejected at 10MB whatever the Fileserver policy said, - # so a 100MB upload failed before any Fileserver code — including its error mapping — ran, - # and the configured limit described a policy nobody could reach. - max-file-size: ${APP_FILESERVER_PLATFORM_UPLOAD_MAX_FILE_SIZE:100MB} - max-request-size: ${APP_FILESERVER_PLATFORM_UPLOAD_MAX_REQUEST_SIZE:110MB} + # spring.servlet.multipart: Spring's bounded defaults apply (an oversized upload is still a 413 + # inside the envelope via GlobalExceptionHandler). The Fileserver capability ships its own ceiling + # in its module settings, tied to app.fileserver-platform.upload.*, when a service selects it. # Jackson deserialization policy and the single runtime JsonMapper SSOT (feature-boundary-validation-mapping-contract B1). # Every request DTO crosses this boundary; the switches make malformed payloads # fail at the edge rather than silently coercing or dropping fields. @@ -233,16 +88,6 @@ spring: import: - classpath:config/server.yml - classpath:config/observability.yml - - classpath:config/persistence.yml - classpath:config/capabilities.yml - classpath:config/runtime.yml - - classpath:config/notification.yml - - classpath:config/idempotency.yml - - classpath:config/outbox.yml - classpath:config/security.yml - - classpath:config/redis.yml - - classpath:config/fileserver.yml - - classpath:config/httpclient.yml - - classpath:config/ratelimit.yml - - classpath:config/messaging.yml - - classpath:config/graphql.yml diff --git a/src/app-bootstrap/src/main/resources/config/capabilities.yml b/src/app-bootstrap/src/main/resources/config/capabilities.yml index 52461818..78c505c0 100644 --- a/src/app-bootstrap/src/main/resources/config/capabilities.yml +++ b/src/app-bootstrap/src/main/resources/config/capabilities.yml @@ -1,75 +1,18 @@ -# 능력별 제공자 선택(cache/rate-limit/lease/idempotency). +# 멱등성 제공자 선택과 수명 정책. Redis 역할(cache/rate-limit/lease)과 Redis 저장소 튜닝은 +# cache-redis 모듈이 config/module-defaults/cache-redis.yml 로 가져온다. # # application.yml 이 spring.config.import 로 취합한다. 이 파일의 값은 application.yml 보다 # 낮고 application-{profile}.yml 보다도 낮으므로, 배포별 오버라이드는 그대로 우선한다. ca-skeleton: capabilities: - # Every capability below renders its keys under one namespace — app.redis.namespace, which is - # {environment}:{service}:{domain}. The per-capability namespace-application / - # namespace-environment pairs that used to live here are gone: four capabilities each joining - # two free-form tokens in their own order produced four different key prefixes, and the ACL - # pattern meant to fence the deployment in matched none of them. - cache: - # Canonical semantic cache activation. Disabled by default; "redis" composes - # RedisCacheRegionAdapter for the region named below and resolves HMAC material by reference. - bindings: - default: ${APP_CACHE_CANONICAL_DEFAULT_PROVIDER:disabled} - semantic-region: ${APP_CACHE_REDIS_SEMANTIC_REGION:default} - key-version: 1 - key-hmac-secret-reference: secret://environment/APP_CACHE_REDIS_KEY_HMAC_SECRET - command-timeout: ${APP_CACHE_REDIS_COMMAND_TIMEOUT:200ms} - positive-soft-ttl: ${APP_CACHE_REDIS_POSITIVE_SOFT_TTL:30s} - positive-hard-ttl: ${APP_CACHE_REDIS_POSITIVE_HARD_TTL:5m} - negative-ttl: ${APP_CACHE_REDIS_NEGATIVE_TTL:10s} - # Floor on the hard TTL. Below it, entries expire faster than the round trip that wrote them: - # every read misses and every miss writes. - minimum-hard-ttl: ${APP_CACHE_REDIS_MINIMUM_HARD_TTL:1s} idempotency: - # disabled | jdbc | redis | postgresql. JDBC is the existing V1 provider; Redis and - # PostgreSQL are owner-safe V2 providers. They are mutually exclusive. + # disabled | redis | postgresql. Exactly one store; the executor is built once over it from + # the lifecycle keys below, whichever provider is selected. provider: ${APP_IDEMPOTENCY_PROVIDER:disabled} - key-version: 1 - command-timeout: ${APP_IDEMPOTENCY_REDIS_COMMAND_TIMEOUT:200ms} + # Lifecycle policy (IdempotencySettings), the same whichever provider holds the records. processing-lease: ${APP_IDEMPOTENCY_PROCESSING_LEASE:30s} replay-ttl: ${APP_IDEMPOTENCY_TTL:24h} failure-retention: ${APP_IDEMPOTENCY_FAILURE_RETENTION:24h} - # Redis V2 codec identity. PostgreSQL V2 currently owns its json.v1 codec in its provider - # composition and does not consume this Redis-specific setting. response-codec-id: json-v2 # Numeric: the owner-safe claim writes this into the record and compares it there. policy-revision: 2 - lease: - # disabled | redis. This is EFFICIENCY_ONLY and never supplies fencing. - provider: ${APP_LEASE_PROVIDER:disabled} - key-version: 1 - command-timeout: ${APP_LEASE_REDIS_COMMAND_TIMEOUT:200ms} - contention-retry-after: ${APP_LEASE_REDIS_CONTENTION_RETRY_AFTER:50ms} - # How much shorter than the server's TTL this holder considers its lease valid. The two - # clocks are not the same clock, and a holder that measured the full TTL locally would still - # believe it held a lease the server had already handed to somebody else. - drift-budget: ${APP_LEASE_REDIS_DRIFT_BUDGET:10ms} - rate-limit: - # disabled | redis. This is the sole outbound provider activation selector. - provider: ${APP_RATE_LIMIT_PROVIDER:disabled} - failure-policy: ${APP_RATE_LIMIT_FAILURE_POLICY:fail-closed} - default-policy-id: ${APP_RATE_LIMIT_DEFAULT_POLICY_ID:api-default} - failure-retry-after: ${APP_RATE_LIMIT_FAILURE_RETRY_AFTER:100ms} - key-version: ${APP_RATE_LIMIT_KEY_VERSION:1} - command-timeout: ${APP_RATE_LIMIT_REDIS_COMMAND_TIMEOUT:200ms} - policies: - api-default: - revision: ${APP_RATE_LIMIT_POLICY_REVISION:v1} - algorithm: ${APP_RATE_LIMIT_ALGORITHM:sliding-counter} - limit: ${APP_RATE_LIMIT_LIMIT:100} - window: ${APP_RATE_LIMIT_WINDOW:1s} - capacity: ${APP_RATE_LIMIT_CAPACITY:100} - refill-tokens: ${APP_RATE_LIMIT_REFILL_TOKENS:100} - refill-period: ${APP_RATE_LIMIT_REFILL_PERIOD:1s} - maximum-cost: ${APP_RATE_LIMIT_MAXIMUM_COST:10} - cleanup-grace: ${APP_RATE_LIMIT_CLEANUP_GRACE:5s} - realtime: - replay: - # PostgreSQL-backed retained event history. Disabled unless a composition actually publishes - # events into the store and exposes replay/resume semantics. - enabled: ${APP_REALTIME_REPLAY_ENABLED:false} - retention: ${APP_REALTIME_REPLAY_RETENTION:1h} diff --git a/src/app-bootstrap/src/main/resources/config/httpclient.yml b/src/app-bootstrap/src/main/resources/config/httpclient.yml deleted file mode 100644 index 440d7549..00000000 --- a/src/app-bootstrap/src/main/resources/config/httpclient.yml +++ /dev/null @@ -1,15 +0,0 @@ -# 아웃바운드 HTTP 클라이언트 플랫폼 스위치. 나머지 키는 환경변수에서 직접 바인딩된다. -# -# application.yml 이 spring.config.import 로 취합한다. 이 파일의 값은 application.yml 보다 -# 낮고 application-{profile}.yml 보다도 낮으므로, 배포별 오버라이드는 그대로 우선한다. -# -# Only the master switch is templated here. Per-client settings are indexed and bind directly from -# APP_HTTPCLIENT_CLIENTS_N_* according to docs/httpclient/env-fields.yaml; materialising a nameless -# list element in YAML would make an otherwise-disabled deployment invalid. When the master switch -# is false the platform settings are not bound. -app: - httpclient: - enabled: ${APP_HTTPCLIENT_ENABLED:false} - # Platform-level, not per-client: how long a retired runtime generation keeps draining after a - # certificate rotation before its pool is closed under whatever is still in flight. - rotation-drain-timeout: ${APP_HTTPCLIENT_ROTATION_DRAIN_TIMEOUT:30s} diff --git a/src/app-bootstrap/src/main/resources/config/idempotency.yml b/src/app-bootstrap/src/main/resources/config/idempotency.yml deleted file mode 100644 index 7d3209b5..00000000 --- a/src/app-bootstrap/src/main/resources/config/idempotency.yml +++ /dev/null @@ -1,10 +0,0 @@ -# 멱등성 TTL 상한. -# -# application.yml 이 spring.config.import 로 취합한다. 이 파일의 값은 application.yml 보다 -# 낮고 application-{profile}.yml 보다도 낮으므로, 배포별 오버라이드는 그대로 우선한다. -ca-skeleton: - idempotency: - # feature-rate-limit-idempotency-contract D6/§E. ttl is env-driven (<=72h, - # validated in IdempotencyProperties); reaper-interval is literal operational tuning. - ttl: ${APP_IDEMPOTENCY_TTL:24h} - reaper-interval: 10m diff --git a/src/app-bootstrap/src/main/resources/config/messaging.yml b/src/app-bootstrap/src/main/resources/config/messaging.yml deleted file mode 100644 index 9cfc3fb6..00000000 --- a/src/app-bootstrap/src/main/resources/config/messaging.yml +++ /dev/null @@ -1,19 +0,0 @@ -# 벤더드 메시징 플랫폼 스위치. -# -# application.yml 이 spring.config.import 로 취합한다. 이 파일의 값은 application.yml 보다 -# 낮고 application-{profile}.yml 보다도 낮으므로, 배포별 오버라이드는 그대로 우선한다. -app: - messaging: - # true | false — whether there is a broker at all. `broker` below selects which one; a - # blank broker used to be the de-facto switch, which is a selector doing a switch's job. - enabled: ${APP_MESSAGING_ENABLED:false} - # Active message broker id (e.g. kafka). Blank = messaging disabled (fail-fast on use). - # Selects the single MessageBroker; adding a broker is new files only (MessagingConfig). - broker: ${APP_MESSAGING_BROKER:} - # Stable logical producer identity for the canonical IntegrationEventPublishPort bridge. - # Blank keeps the canonical bridge absent; identity is never inferred from host/pod/process. - producer-id: ${APP_MESSAGING_PRODUCER_ID:} - kafka: - # CSV of host:port; required (non-empty) only when broker=kafka. Bound + - # validated by KafkaAdapterSettings (format) + KafkaAdapterConfig (required-when-active). - brokers: ${APP_MESSAGING_KAFKA_BROKERS:} diff --git a/src/app-bootstrap/src/main/resources/config/observability.yml b/src/app-bootstrap/src/main/resources/config/observability.yml index 6b2076ef..520d3b9e 100644 --- a/src/app-bootstrap/src/main/resources/config/observability.yml +++ b/src/app-bootstrap/src/main/resources/config/observability.yml @@ -31,11 +31,7 @@ management: web: # D2: production allowlist — only safe, scrape-friendly endpoints are exposed. exposure: - # adapteractivation reports which master switches resolved on and what that makes required. - # It reads the environment and creates nothing, so it leaks no secret and opens no resource — - # and it is exposed precisely so a smoke lane can check the application's own answer rather - # than the flags the lane itself passed in, which is a test of the test. - include: health,prometheus,info,loggers,adapteractivation + include: health,prometheus,info,loggers # D2/D4/D5: explicitly excluded dangerous endpoints (env leaks secrets, # heapdump/threaddump = memory forensics, shutdown = remote kill, configprops = secret leak). exclude: env,configprops,heapdump,threaddump,shutdown diff --git a/src/app-bootstrap/src/main/resources/config/outbox.yml b/src/app-bootstrap/src/main/resources/config/outbox.yml deleted file mode 100644 index 4141ff6e..00000000 --- a/src/app-bootstrap/src/main/resources/config/outbox.yml +++ /dev/null @@ -1,33 +0,0 @@ -# 트랜잭셔널 아웃박스 릴레이. -# -# application.yml 이 spring.config.import 로 취합한다. 이 파일의 값은 application.yml 보다 -# 낮고 application-{profile}.yml 보다도 낮으므로, 배포별 오버라이드는 그대로 우선한다. -ca-skeleton: - outbox: - # feature-domain-event-outbox-contract I11 — all six values are literal defaults; - # NO env placeholders (spec: 신규 env key 없음). Bound into OutboxProperties. - # true | false — enable/disable the relay scheduler (OutboxRelayScheduler). - # MSG-024: an enabled relay with a blank app.messaging.broker fails startup - # (OutboxRelayBrokerRequirementValidator). The relay would otherwise claim PENDING rows, fail - # every publish against the disabled publisher, and exhaust them to DEAD — a messaging-off - # environment must preserve its outbox, not destroy it one retry budget at a time. - # true | false — the capability switch. Off means no outbox settings, validator, leader token, - # metrics, or store binding at all; relay-enabled below only decides whether the scheduler runs. - # Conflating the two meant a relay-off deployment still assembled an OutboxMetrics over a store - # port that a database-less deployment does not have. - enabled: ${APP_OUTBOX_ENABLED:false} - relay-enabled: ${APP_OUTBOX_RELAY_ENABLED:false} - # Transport-only MSG-015 cutover gate. It does not activate POLLING_V2 or a second relay. - # When true, startup also requires the canonical IntegrationEventPublishPort. - canonical-transport-enabled: ${APP_OUTBOX_CANONICAL_TRANSPORT_ENABLED:false} - # ISO-8601 duration — how often the relay polls for pending rows - poll-interval: PT5S - # integer >= 1 — maximum rows claimed per relay cycle - batch-size: 20 - # ISO-8601 duration — IN_FLIGHT orphan visibility window (I6: next_attempt_at reuse) - in-flight-timeout: PT5M - # ISO-8601 duration — read also by adapter-persistence OutboxReaper @Scheduled - reaper-interval: PT10M - # ISO-8601 duration — PUBLISHED row retention before reaper deletes them (I3) - # read also by adapter-persistence OutboxReaper via ${ca-skeleton.outbox.published-retention:P7D} - published-retention: P7D diff --git a/src/app-bootstrap/src/main/resources/config/persistence.yml b/src/app-bootstrap/src/main/resources/config/persistence.yml deleted file mode 100644 index 96611165..00000000 --- a/src/app-bootstrap/src/main/resources/config/persistence.yml +++ /dev/null @@ -1,78 +0,0 @@ -# 관계형/문서 저장소 활성화와 JPA·persistence 정책. -# -# application.yml 이 spring.config.import 로 취합한다. 이 파일의 값은 application.yml 보다 -# 낮고 application-{profile}.yml 보다도 낮으므로, 배포별 오버라이드는 그대로 우선한다. -spring: - jpa: - properties: - hibernate: - # Advanced JPA batch/fetch/measurement knobs. Defaults preserve Hibernate's off state. - # JpaBatchExecutor requires batch_size > 0 and generate_statistics=true so it can prove - # batching happened instead of trusting a configuration value. - jdbc: - batch_size: ${APP_JPA_HIBERNATE_BATCH_SIZE:0} - order_inserts: ${APP_JPA_HIBERNATE_ORDER_INSERTS:false} - order_updates: ${APP_JPA_HIBERNATE_ORDER_UPDATES:false} - default_batch_fetch_size: ${APP_JPA_HIBERNATE_DEFAULT_BATCH_FETCH_SIZE:0} - generate_statistics: ${APP_JPA_HIBERNATE_GENERATE_STATISTICS:false} - -ca-skeleton: - # The five optional adapters ship in this artifact and are off unless a deployment says otherwise, - # so one jar serves every environment and an operator turns a capability on with one variable. Off - # is structural: no settings bind, no bean is created, no socket, pool or thread exists, and a - # malformed detail setting for a capability nobody enabled does not block startup. - # Registry SSOT: docs/registries/env-keys.yaml. - persistence-jpa: - # true | false — relational persistence: DataSource, entity scan, repositories, Flyway. - enabled: ${APP_PERSISTENCE_JPA_ENABLED:false} - persistence-mongo: - # true | false - enabled: ${APP_PERSISTENCE_MONGO_ENABLED:false} - # Required non-blank when the switch above is true. Exactly one profile: the runtime builds one - # sync client and one pool, and never resolves a non-selected profile's secret. - active-profile: ${APP_PERSISTENCE_MONGO_ACTIVE_PROFILE:} - # Connection source must also be explicit. Standard deployments set the Spring-native - # SPRING_MONGODB_URI (Boot 4 -> spring.mongodb.uri); typed-profile deployments instead set - # ca-skeleton.persistence-mongo.platform.profiles..uri-secret and supply a - # MongoCredentialResolver. Startup refuses the driver localhost/test fallback when neither exists. - # - # Complete production profile example (17 MongoProfileProperties components): - # platform: - # profiles: - # production: - # uri-secret: secret://mongo/production - # topology: REPLICA_SET - # production: true - # stable-api-strict: true - # consistency-default: PRIMARY_MAJORITY - # server-selection-timeout: 3s - # connect-timeout: 2s - # socket-read-timeout: 5s - # operation-timeout: 3s - # pool-min-size: 2 - # pool-max-size: 40 - # pool-max-wait-time: 500ms - # uuid-representation: STANDARD - # decimal-representation: DECIMAL128 - # runtime-auto-create-indexes: false - # tls-required: true - # authentication-required: true - persistence: - vendor: ${APP_PERSISTENCE_VENDOR:postgresql} - # JPA named-policy deadline envelope. JpaTransactionSettings validates the hierarchy; - # SpringPolicyTransactionPort intersects these limits with the caller's absolute CallBudget - # and the actual Hikari connection timeout before acquiring a transaction. - jpa: - transaction: - transaction-timeout: 30s - begin-budget: 250ms - minimum-action-window: 1s - completion-margin: 500ms - statement-timeout: 10s - lock-timeout: 2s - idle-guard-timeout: 15s - transaction-margin: 250ms - lock-margin: 100ms - retry-base-delay: 10ms - retry-maximum-delay: 50ms - retry-maximum-attempts: 2 diff --git a/src/app-bootstrap/src/main/resources/config/ratelimit.yml b/src/app-bootstrap/src/main/resources/config/ratelimit.yml deleted file mode 100644 index 448ffc24..00000000 --- a/src/app-bootstrap/src/main/resources/config/ratelimit.yml +++ /dev/null @@ -1,14 +0,0 @@ -# 엣지 레이트 리밋 정책. -# -# application.yml 이 spring.config.import 로 취합한다. 이 파일의 값은 application.yml 보다 -# 낮고 application-{profile}.yml 보다도 낮으므로, 배포별 오버라이드는 그대로 우선한다. -app: - rate-limit: - # Inbound HTTP enforcement is a separate axis from outbound provider activation. - # enabled=true with no exact EdgeRateLimitPort fails fast; it never installs a local fallback. - enabled: ${APP_RATE_LIMIT_ENABLED:false} - default-policy-id: ${APP_RATE_LIMIT_DEFAULT_POLICY_ID:api-default} - hash-key-version: ${APP_RATE_LIMIT_HASH_KEY_VERSION:1} - caller-deadline-budget: 2s - # remote-addr-only | forwarded-headers-trusted (trusted ingress only) - client-ip-mode: ${APP_RATE_LIMIT_CLIENT_IP_MODE:remote-addr-only} diff --git a/src/app-bootstrap/src/main/resources/config/redis.yml b/src/app-bootstrap/src/main/resources/config/redis.yml deleted file mode 100644 index a29166e2..00000000 --- a/src/app-bootstrap/src/main/resources/config/redis.yml +++ /dev/null @@ -1,11 +0,0 @@ -# Redis 전역 스위치와 SDK 네임스페이스. -# -# application.yml 이 spring.config.import 로 취합한다. 이 파일의 값은 application.yml 보다 -# 낮고 application-{profile}.yml 보다도 낮으므로, 배포별 오버라이드는 그대로 우선한다. -app: - # The one global Redis switch. False (the default) means no Redis settings are bound, no Redis - # credential is required, no client, connection, thread or health contributor is created, and no - # Redis-specific resource is read. There is deliberately no second master switch: a role such as - # cache or session selects *which* Redis capabilities compose, never *whether* Redis exists. - redis: - enabled: ${APP_REDIS_ENABLED:false} diff --git a/src/app-bootstrap/src/main/resources/config/runtime.yml b/src/app-bootstrap/src/main/resources/config/runtime.yml index 6ec46cdf..5f8e3718 100644 --- a/src/app-bootstrap/src/main/resources/config/runtime.yml +++ b/src/app-bootstrap/src/main/resources/config/runtime.yml @@ -1,4 +1,5 @@ -# 부트스트랩 신원, 런타임 안전 토글, 분산 락, 표현 계층, 비동기 실행기. +# 부트스트랩 신원, 런타임 안전 토글, 표현 계층, 비동기 실행기. +# (마이그레이션·분산 락 설정은 persistence-jpa 모듈이 가져온다.) # # application.yml 이 spring.config.import 로 취합한다. 이 파일의 값은 application.yml 보다 # 낮고 application-{profile}.yml 보다도 낮으므로, 배포별 오버라이드는 그대로 우선한다. @@ -11,15 +12,6 @@ ca-skeleton: # the prod profile; multi-instance fails startup if its coordination beans are absent. # true | false (requires the 5 instance-coordination beans when true) multi-instance-enabled: ${APP_MULTI_INSTANCE_ENABLED:false} - # true | false (whether to run Flyway migrations automatically at startup) - migration-on-startup: ${APP_MIGRATION_ON_STARTUP:true} - # feature-distributed-lock-contract D5 — distributed lock acquisition contract (try-lock + - # finite wait + lease TTL). Bound to LockSettings (adapter-persistence). Plain values, NOT - # APP_* env keys — new env-key registration is feature-env-driven-runtime-configuration's - # domain (out of scope for this branch); code defaults in LockSettings mirror these. - lock: - wait-time: 3s - lease-ttl: 30s presentation: # feature-api-contract-baseline D2: API version prefix. Default is the URI # prefix "/v1" (major-version path, AIP-185); override via env, or set "" for diff --git a/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/activation/AdapterActivationInventory.java b/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/activation/AdapterActivationInventory.java deleted file mode 100644 index 8304834a..00000000 --- a/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/activation/AdapterActivationInventory.java +++ /dev/null @@ -1,242 +0,0 @@ -package dev.caskeleton.bootstrap.activation; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Comparator; -import java.util.EnumMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import org.springframework.context.ApplicationContext; - -/** - * The one answer to "which beans, and which threads, belong to this adapter?". - * - *

Ownership is a package question rather than a bean-name question. Bean names are generated, - * and a rule written against them silently stops covering the bean somebody adds next week; a - * package prefix keeps covering it. The vendor sets exist for the same reason from the other - * direction: JPA being off has to mean no {@code HikariDataSource} and no {@code Flyway}, and - * neither of those lives under a project package, so a project-only rule would report a clean - * inventory for a deployment that had opened a connection pool. - * - *

The ownership data sits in a static map rather than in enum fields because Error Prone's - * {@code ImmutableEnumChecker} rejects collection-typed instance fields on an enum, and this module - * compiles with {@code -Werror}. The indirection buys nothing else, and costs nothing either. - */ -public final class AdapterActivationInventory { - - /** The five optional adapters this repository ships behind a master switch. */ - public enum Adapter { - JPA, - MONGO, - MESSAGING, - NOTIFICATION, - GRAPHQL - } - - /** - * What one adapter owns: its own packages, the vendor packages Boot contributes on its behalf, - * and the pattern its threads are named with. - * - * @param projectPackages package prefixes this repository owns for the adapter - * @param vendorPackages package prefixes a starter contributes on the adapter's behalf - * @param threadNamePattern a regex alternation matched against lower-cased thread names - */ - private record Ownership( - Set projectPackages, Set vendorPackages, String threadNamePattern) { - - /** - * Types the container registers itself whenever an API is on the classpath, regardless of what - * any capability decided. - * - *

{@code AnnotationConfigUtils} adds {@code PersistenceAnnotationBeanPostProcessor} to every - * context that can see the JPA API, which a single-artifact build always can. It holds no - * connection, opens no pool, and starts no thread — counting it as JPA\'s would make the off - * invariant unsatisfiable by construction, and an assertion that cannot pass teaches the reader - * to ignore it. - */ - private static final Set CONTAINER_INFRASTRUCTURE = - Set.of("org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"); - - /** - * Fail-fast stand-ins the composition root provides for a capability nobody enabled. - * - *

The off invariant asks for these explicitly: where the application requires a port bean - * unconditionally, the disabled sentinel is supplied by the composition root and throws {@code - * ADAPTER_DISABLED} when called. They live in the adapter's package because that is where the - * type is declared, and counting them as the adapter's would make the invariant contradict - * itself — the same list cannot both require a bean and forbid it. They hold no client, no - * socket and no thread, which is the property that actually matters here. - */ - private static final Set COMPOSITION_ROOT_STANDINS = - Set.of( - "dev.caskeleton.adapter.outbound.messaging.core.DisabledMessagePublisher", - "dev.caskeleton.adapter.outbound.messaging.outbox.DisabledOutboxMessagePublisher"); - - boolean owns(String typeName) { - if (CONTAINER_INFRASTRUCTURE.contains(typeName) - || COMPOSITION_ROOT_STANDINS.contains(typeName)) { - return false; - } - return projectPackages.stream().anyMatch(prefix -> typeName.startsWith(prefix + ".")) - || vendorPackages.stream().anyMatch(prefix -> typeName.startsWith(prefix + ".")); - } - } - - private static final Map OWNERSHIP = ownership(); - - private AdapterActivationInventory() {} - - private static Map ownership() { - Map byAdapter = new EnumMap<>(Adapter.class); - byAdapter.put( - Adapter.JPA, - new Ownership( - Set.of( - "dev.caskeleton.adapter.outbound.persistence", - "dev.caskeleton.bootstrap.autoconfigure.jpa", - "dev.caskeleton.bootstrap.migration"), - Set.of( - "com.zaxxer.hikari", - "org.flywaydb", - "org.hibernate", - "jakarta.persistence", - "org.springframework.orm.jpa", - "org.springframework.jdbc.datasource", - "org.springframework.boot.jdbc", - "org.springframework.boot.jpa", - "org.springframework.boot.hibernate", - "org.springframework.boot.flyway", - "org.springframework.boot.data.jpa"), - "hikari|flyway|jpa|hibernate")); - byAdapter.put( - Adapter.MONGO, - new Ownership( - Set.of("dev.caskeleton.adapter.outbound.mongo"), - Set.of( - "com.mongodb", - "org.springframework.data.mongodb", - "org.springframework.boot.mongodb", - "org.springframework.boot.data.mongodb"), - "mongo|cluster-|maintenance-")); - byAdapter.put( - Adapter.MESSAGING, - new Ownership( - Set.of("dev.caskeleton.adapter.outbound.messaging", "dev.caskeleton.messaging"), - Set.of( - "org.apache.kafka", - "com.rabbitmq", - "org.springframework.kafka", - "org.springframework.amqp", - "org.springframework.boot.kafka", - "org.springframework.boot.amqp"), - "kafka|rabbit|messaging-|outbox-relay")); - byAdapter.put( - Adapter.NOTIFICATION, - new Ownership( - Set.of( - "dev.caskeleton.adapter.outbound.notification", - "dev.caskeleton.bootstrap.autoconfigure.notification"), - Set.of(), - "notification-")); - byAdapter.put( - Adapter.GRAPHQL, - new Ownership( - Set.of("dev.caskeleton.adapter.inbound.graphql"), - Set.of("graphql", "org.springframework.graphql", "org.springframework.boot.graphql"), - "graphql-")); - return Map.copyOf(byAdapter); - } - - /** - * Returns the names of every bean in the context whose type the adapter owns. - * - * @param context the context to inspect - * @param adapter the adapter whose ownership decides membership - * @return sorted bean names; empty when the adapter is structurally off - */ - public static List beanNamesOwnedBy(ApplicationContext context, Adapter adapter) { - Ownership ownership = OWNERSHIP.get(adapter); - List owned = new ArrayList<>(); - for (String name : context.getBeanDefinitionNames()) { - Class type = safeType(context, name); - if (type != null && ownership.owns(type.getName())) { - owned.add(name); - } - } - owned.sort(Comparator.naturalOrder()); - return List.copyOf(owned); - } - - /** - * Returns the distinct type names behind {@link #beanNamesOwnedBy}, which read better in a - * failure message than generated bean names do. - * - * @param context the context to inspect - * @param adapter the adapter whose ownership decides membership - * @return sorted, distinct fully-qualified type names - */ - public static List ownedBeanTypeNames(ApplicationContext context, Adapter adapter) { - return beanNamesOwnedBy(context, adapter).stream() - .map(name -> safeType(context, name)) - .filter(Objects::nonNull) - .map(Class::getName) - .distinct() - .sorted() - .toList(); - } - - /** - * Returns live thread names that match the adapter's thread-naming pattern. - * - *

A connection pool or a consumer loop that survives an "off" deployment shows up here and - * nowhere in the bean inventory, because the thread outlives the factory that made it. - * - * @param adapter the adapter whose naming pattern decides membership - * @return sorted matching thread names - */ - public static List liveThreadNamesMatching(Adapter adapter) { - String pattern = ".*(" + OWNERSHIP.get(adapter).threadNamePattern() + ").*"; - return Thread.getAllStackTraces().keySet().stream() - .map(Thread::getName) - .filter(name -> name.toLowerCase(Locale.ROOT).matches(pattern)) - .distinct() - .sorted() - .toList(); - } - - /** - * Renders a stable report of everything the adapter currently owns. - * - * @param context the context to inspect - * @param adapter the adapter to report on - * @return a multi-line report suitable for an assertion message or an evidence artifact - */ - public static String describe(ApplicationContext context, Adapter adapter) { - return String.join( - System.lineSeparator(), - Arrays.asList( - adapter.name() + " beans: " + ownedBeanTypeNames(context, adapter), - adapter.name() + " threads: " + liveThreadNamesMatching(adapter))); - } - - /** - * Resolves a bean's type without letting an unresolvable definition abort the whole inventory. - * - *

An inventory that throws on the first lazy or abstract definition reports nothing at all, - * which reads as "the adapter is off" — the exact conclusion this class exists to make honest. - * - * @param context the context to inspect - * @param name the bean definition name - * @return the resolved type, or null when it cannot be determined - */ - private static Class safeType(ApplicationContext context, String name) { - try { - return context.getType(name); - } catch (RuntimeException unresolvable) { - return null; - } - } -} diff --git a/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/activation/BootstrapCapabilityReachabilitySystemTest.java b/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/activation/BootstrapCapabilityReachabilitySystemTest.java deleted file mode 100644 index 84b869ef..00000000 --- a/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/activation/BootstrapCapabilityReachabilitySystemTest.java +++ /dev/null @@ -1,159 +0,0 @@ -package dev.caskeleton.bootstrap.activation; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.outbound.cache.redis.capability.RedisCapabilitySettings; -import dev.caskeleton.adapter.outbound.cache.redis.sdk.config.RedisSdkSettings; -import dev.caskeleton.adapter.outbound.httpclient.autoconfigure.HttpClientPlatformSettings; -import dev.caskeleton.adapter.outbound.httpclient.service.HttpServiceRegistry; -import dev.caskeleton.application.idempotency.IdempotencyExecutor; -import dev.caskeleton.application.idempotency.v2.IdempotencyExecutorV2; -import dev.caskeleton.bootstrap.autoconfigure.lock.MeteredDistributedLockPort; -import dev.caskeleton.bootstrap.autoconfigure.outbox.OutboxMetrics; -import dev.caskeleton.bootstrap.autoconfigure.outbox.OutboxRelayScheduler; -import io.micrometer.tracing.Tracer; -import org.junit.jupiter.api.Test; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.scheduling.config.TaskManagementConfigUtils; - -/** - * Shipped-root proof for bootstrap-owned capability auto-configurations. - * - *

The unit tests exercise each configuration in isolation. This test boots the real application - * scan plus Boot auto-configuration discovery and proves that making the roots reachable did not - * turn their disabled state into runtime work. - */ -class BootstrapCapabilityReachabilitySystemTest { - - @Test - void allOffDeploymentDiscoversRootsWithoutCreatingOptionalRuntimeWork() { - try (ConfigurableApplicationContext context = - ShippedCompositionHarness.shippedComposition("local") - .run(ShippedCompositionHarness.allOffArguments())) { - assertThat(context.getBeansOfType(RedisCapabilitySettings.class)).isEmpty(); - assertThat(context.getBeansOfType(HttpClientPlatformSettings.class)).isEmpty(); - assertThat(context.getBeansOfType(OutboxRelayScheduler.class)).isEmpty(); - assertThat(context.getBeansOfType(MeteredDistributedLockPort.class)).isEmpty(); - assertThat(context.getBeansOfType(IdempotencyExecutor.class)).isEmpty(); - assertThat(context.getBeansOfType(IdempotencyExecutorV2.class)).isEmpty(); - assertThat( - context.containsBean( - TaskManagementConfigUtils.SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME)) - .isFalse(); - assertThat(context.getBeansOfType(Tracer.class)).isEmpty(); - } - } - - @Test - void redisRootIsReachableFromTheShippedCompositionWhenEnabled() { - try (ConfigurableApplicationContext context = - ShippedCompositionHarness.shippedComposition("local") - .run( - ShippedCompositionHarness.allOffExcept( - "--app.redis.enabled=true", - "--app.redis.authentication.anonymous-access-accepted=true"))) { - assertThat(context.getBeansOfType(RedisSdkSettings.class)).hasSize(1); - assertThat(context.getBeansOfType(RedisCapabilitySettings.class)).hasSize(1); - } - } - - @Test - void tracingRootIsReachableFromTheShippedCompositionWhenEnabled() { - try (ConfigurableApplicationContext context = - ShippedCompositionHarness.shippedComposition("local") - .run(ShippedCompositionHarness.allOffExcept("--ca-skeleton.tracing.enabled=true"))) { - assertThat(context.getBeansOfType(Tracer.class)).hasSize(1); - } - } - - @Test - void httpClientRootIsReachableFromTheShippedCompositionWhenEnabled() { - try (ConfigurableApplicationContext context = - ShippedCompositionHarness.shippedComposition("local") - .run( - ShippedCompositionHarness.allOffExcept( - "--app.httpclient.enabled=true", - "--app.httpclient.clients[0].name=payment", - "--app.httpclient.clients[0].base-url=https://payment.test", - "--app.httpclient.clients[0].allowed-hosts[0]=payment.test", - "--app.httpclient.clients[0].allowed-ports[0]=443", - "--app.httpclient.clients[0].request.max-body-bytes=1024", - "--app.httpclient.clients[0].tls.profile-id=payment"))) { - assertThat(context.getBeansOfType(HttpClientPlatformSettings.class)).hasSize(1); - assertThat(context.getBeansOfType(HttpServiceRegistry.class)).hasSize(1); - } - } - - @Test - void distributedLockRootIsReachableFromTheShippedCompositionWhenEnabled() { - try (ConfigurableApplicationContext context = - ShippedCompositionHarness.shippedComposition("local") - .run( - ShippedCompositionHarness.allOffWithH2( - "reachability_lock", "--ca-skeleton.runtime.multi-instance-enabled=true"))) { - assertThat(context.containsBean("jdbcDistributedLock")).isTrue(); - assertThat(context.containsBean("distributedLockProvider")).isTrue(); - assertThat(context.getBean("distributedLockProvider")) - .isInstanceOf(MeteredDistributedLockPort.class); - } - } - - @Test - void jdbcIdempotencyRootIsReachableFromTheShippedCompositionWhenEnabled() { - try (ConfigurableApplicationContext context = - ShippedCompositionHarness.shippedComposition("local") - .run( - ShippedCompositionHarness.allOffWithH2( - "reachability_idempotency", - "--ca-skeleton.capabilities.idempotency.provider=jdbc"))) { - assertThat(context.getBeansOfType(IdempotencyExecutor.class)).hasSize(1); - assertThat( - context.containsBean( - TaskManagementConfigUtils.SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME)) - .isTrue(); - } - } - - @Test - void outboxRootIsReachableFromTheShippedCompositionWhenEnabled() { - // No broker, and none needed: `relay-enabled=false` is one of the two coherent outbox - // configurations, and it is the one a broker-neutral artifact can run. This test used to select - // Kafka and hand-register no-op Kafka seams, which only worked while the shipped composition - // still carried the Kafka provider configuration. It does not — the broker starter is a build - // decision the deployment makes — so selecting one here was asserting a composition this - // artifact cannot produce. - try (ConfigurableApplicationContext context = - ShippedCompositionHarness.shippedComposition("local") - .run( - ShippedCompositionHarness.allOffWithH2( - "reachability_outbox", - "--ca-skeleton.outbox.enabled=true", - "--ca-skeleton.outbox.relay-enabled=false"))) { - assertThat(context.containsBean("outboxLeaderElection")).isTrue(); - assertThat(context.getBeansOfType(OutboxMetrics.class)).hasSize(1); - assertThat(context.getBeansOfType(OutboxRelayScheduler.class)).isEmpty(); - } - } - - @Test - void shippedCompositionRefusesABrokerItDidNotCompose() { - // The build composition question, asked of the artifact rather than of a build file. The core - // messaging starter is broker-neutral and neither broker starter ships, so selecting one is a - // deployment asking for a transport it did not compose. Before the selector checked for the - // provider configuration it checked only for the client library — which a deployment can hold - // transitively — and the refusal arrived as Spring reporting a missing .class file. - assertThatThrownBy( - () -> - ShippedCompositionHarness.shippedComposition("local") - .run( - ShippedCompositionHarness.allOffWithH2( - "refuses_uncomposed_broker", - "--app.messaging.enabled=true", - "--app.messaging.broker=kafka"))) - .rootCause() - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("messaging-spring-boot-starter-kafka") - .hasMessageContaining("broker-neutral"); - } -} diff --git a/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/activation/DefaultProfileBootCharacterizationTest.java b/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/activation/DefaultProfileBootCharacterizationTest.java deleted file mode 100644 index 0103107b..00000000 --- a/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/activation/DefaultProfileBootCharacterizationTest.java +++ /dev/null @@ -1,80 +0,0 @@ -package dev.caskeleton.bootstrap.activation; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.catchThrowable; - -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.springframework.context.ConfigurableApplicationContext; - -/** - * The shipped defaults do not start. - * - *

Both failures were the same class of mistake: a capability that consumes an adapter defaulted - * to on while the adapter it consumes defaulted to off. The relay was enabled with no broker; the - * schema was Flyway-owned with {@code ddl-auto=update}. Neither validator was wrong to refuse — the - * defaults they were refusing were, and they are what changed. - * - *

The second one stayed hidden until the first was fixed, because the relay validator ran first - * and both profiles reported its message. A characterization that stops at the first cause is a - * characterization that finds one bug. - * - *

Asserted on the cause chain rather than on a message, because a validator whose wording - * changes must not quietly turn this green. - */ -class DefaultProfileBootCharacterizationTest { - - @Test - @DisplayName("the local profile starts with shipped defaults") - void localProfileStartsWithShippedDefaults() { - assertProfileStarts("local"); - } - - /** - * Starts with its required operator inputs and nothing else. - * - *

The original cause — an enabled relay with no broker — was hiding a structural one: {@code - * application.yml} carried 62 placeholders with no inline default, so every value had to arrive - * from {@code src/.env}, and {@code application-local.yml} pinned enough of them that only local - * appeared to work. 55 now carry a default derived from the env registry rather than guessed; the - * remaining seven are the address, the credential, the application name, the allowed origin, and - * the token issuer and audience, which stay undefaulted because a default for any of them is a - * deployment running against something nobody chose. - */ - @Test - @DisplayName("the dev profile starts with its required inputs and shipped defaults") - void devProfileStartsWithShippedDefaults() { - assertProfileStarts("dev"); - } - - @Test - @DisplayName("the prod profile refuses a JDBC URL without verify-full TLS") - void prodProfileRefusesPlaintextJdbc() { - Throwable thrown = catchThrowable(() -> startAndClose("prod")); - assertThat(thrown) - .as( - "a production datasource without sslmode=verify-full must be refused at startup; " - + "this case documents a validator working, and the missing piece is a TLS-capable " - + "prod smoke environment rather than a code fix") - .isNotNull(); - } - - private static void assertProfileStarts(String profile) { - Throwable thrown = catchThrowable(() -> startAndClose(profile)); - assertThat(thrown) - .as( - "the %s profile must start with the values this repository ships, with no operator " - + "override; it currently fails because a capability that consumes an adapter " - + "defaults to on while the adapter defaults to off", - profile) - .isNull(); - } - - private static void startAndClose(String profile) { - try (ConfigurableApplicationContext context = - ShippedCompositionHarness.shippedComposition(profile) - .run(ShippedCompositionHarness.requiredOperatorInputs())) { - assertThat(context.isRunning()).isTrue(); - } - } -} diff --git a/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/activation/DependencyErrorStartupContractTest.java b/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/activation/DependencyErrorStartupContractTest.java deleted file mode 100644 index 97a90f4f..00000000 --- a/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/activation/DependencyErrorStartupContractTest.java +++ /dev/null @@ -1,151 +0,0 @@ -package dev.caskeleton.bootstrap.activation; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.catchThrowable; - -import java.util.ArrayList; -import java.util.List; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.springframework.context.ConfigurableApplicationContext; - -/** - * Row 8 of the activation matrix: a capability switched on without its dependency must refuse the - * startup, and the refusal must name the switch. - * - *

There was already a test for this and it proved something weaker than it looked. {@code - * CapabilityDependencyValidatorTest} calls the validator's static method against a {@code - * MockEnvironment}, so it establishes that the rule computes the right sentence — not that anything - * runs the rule, and not that a deployment which breaks it fails to start. Those are exactly the - * two claims Row 8 makes, and the difference between them is the difference between a validator - * that is wired in and a validator that merely exists. This repository has found five classes that - * were green in their own tests and present in no running application; a validator is a poor - * candidate to become the sixth. - * - *

So this boots the real composition root and asserts the refusal, which covers the wiring - * (`AdapterActivationAutoConfiguration` registering the check), the timing (an {@code - * InitializingBean}, so the context dies while still assembling rather than after a scheduler has - * claimed a row), and the message. - * - *

The plan is explicit that a failure is not enough: the message must name the exact switch. A - * generic "misconfiguration" tells an operator to go reading; a property name tells them what to - * set. Each case below therefore asserts the property string, and — because "contains a property - * name" is easy to satisfy by accident once the message lists several — that the named property is - * the one whose absence caused this particular refusal. - */ -class DependencyErrorStartupContractTest { - - @Test - @DisplayName("the outbox without relational persistence is refused, naming the JPA switch") - void outboxWithoutPersistenceNamesTheJpaSwitch() { - assertRefusedNaming( - List.of("--ca-skeleton.outbox.enabled=true"), "ca-skeleton.persistence-jpa.enabled"); - } - - @Test - @DisplayName("the relay without a broker is refused, naming the messaging switch") - void relayingOutboxWithoutMessagingNamesTheMessagingSwitch() { - // The relay, not the capability. An outbox with the relay off writes rows and publishes - // nothing, which is how an operator parks events until a transport exists; demanding messaging - // for the capability refused that configuration and, in a broker-neutral artifact, left the - // outbox with no reachable configuration at all. - assertRefusedNaming( - List.of( - "--ca-skeleton.outbox.enabled=true", - "--ca-skeleton.outbox.relay-enabled=true", - "--ca-skeleton.persistence-jpa.enabled=true"), - "app.messaging.enabled"); - } - - @Test - @DisplayName("the relay without the capability it relays is refused, naming the outbox switch") - void relayWithoutTheOutboxNamesTheOutboxSwitch() { - // The relay is a scheduler for a capability, not a capability. Switched on alone it used to - // start, find nothing to publish, and look healthy. - assertRefusedNaming( - List.of("--ca-skeleton.outbox.relay-enabled=true"), "ca-skeleton.outbox.enabled"); - } - - @Test - @DisplayName("the refusal names a property rather than reporting a misconfiguration") - void theRefusalIsNotGeneric() { - Throwable failure = refuse(List.of("--ca-skeleton.outbox.relay-enabled=true")); - - String message = messageChain(failure); - assertThat(message) - .as("an operator reading this has to learn which value to change, from this text alone") - .contains("=true or turn the relay off"); - assertThat(message) - .as("the sentence must carry a settable property, not a category of problem") - .containsPattern("ca-skeleton\\.[a-z.\\-]+"); - } - - /** Boots the all-off composition with the given overrides and returns the refusal. */ - private static Throwable refuse(List overrides) { - // Replaced, not appended, and the difference is not stylistic. Spring's command-line property - // source collects *every* occurrence of an option name into a list, so passing - // `--x=false --x=true` yields the string "false,true" — which binds as neither. The first - // version of this test appended, watched an inconsistent deployment start cleanly, and was one - // assertion away from reporting a runtime defect that did not exist. - List arguments = new ArrayList<>(); - for (String argument : ShippedCompositionHarness.allOffArguments()) { - String key = argument.substring(0, argument.indexOf('=')); - if (overrides.stream().noneMatch(override -> override.startsWith(key + "="))) { - arguments.add(argument); - } - } - arguments.addAll(overrides); - - ConfigurableApplicationContext[] leaked = new ConfigurableApplicationContext[1]; - try { - Throwable thrown = - catchThrowable( - () -> - leaked[0] = - ShippedCompositionHarness.shippedComposition("local") - .run(arguments.toArray(String[]::new))); - assertThat(thrown) - .as("a deployment whose capability graph is inconsistent must not reach a running state") - .isNotNull(); - return thrown; - } finally { - if (leaked[0] != null) { - leaked[0].close(); - } - } - } - - private static void assertRefusedNaming(List overrides, String expectedProperty) { - assertThat(messageChain(refuse(overrides))) - .as( - "the refusal must name %s, which is the value an operator has to change", - expectedProperty) - .contains(expectedProperty); - } - - /** - * The whole message chain. - * - *

Spring wraps a refusal thrown from {@code afterPropertiesSet} more than once, and which - * wrapper carries the text is a framework detail this contract should not depend on. - */ - private static String messageChain(Throwable failure) { - StringBuilder text = new StringBuilder(); - for (Throwable current = failure; current != null; current = current.getCause()) { - text.append(current.getMessage()).append(System.lineSeparator()); - } - return text.toString(); - } - - @Test - @DisplayName( - "a consistent all-off deployment still starts, so the check is not refusing everything") - void allOffStillStarts() { - // Without this, every assertion above is satisfied by a validator that rejects unconditionally. - try (ConfigurableApplicationContext context = - ShippedCompositionHarness.shippedComposition("local") - .run(ShippedCompositionHarness.allOffArguments())) { - assertThat(context.isRunning()).isTrue(); - } - } -} diff --git a/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/activation/FiveAdapterOffInventoryTest.java b/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/activation/FiveAdapterOffInventoryTest.java deleted file mode 100644 index 9e8574c8..00000000 --- a/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/activation/FiveAdapterOffInventoryTest.java +++ /dev/null @@ -1,104 +0,0 @@ -package dev.caskeleton.bootstrap.activation; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.bootstrap.activation.AdapterActivationInventory.Adapter; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.springframework.context.ConfigurableApplicationContext; - -/** - * With all registered master switches off, the application must hold nothing that belongs to any of - * them. - * - *

This boots the real composition root rather than an {@code ApplicationContextRunner}, because - * the two things most likely to defeat a master switch are exactly the two a runner does not have: - * the broad component scan, and the vendor auto-configuration a starter drags in from the - * classpath. A green runner and a red application is the outcome this test exists to prevent. - * - *

Four of the five cases are expected to be red at Wave 0, and two of the greens are green for - * the wrong reason — Mongo and GraphQL hold nothing because their code is not shipped at all. - * {@link ShippedRuntimeFacadePresenceTest} is the test that refuses to accept absence as off. - */ -class FiveAdapterOffInventoryTest { - - private static ConfigurableApplicationContext context; - - /** - * Threads already running before this context started. - * - *

Thread names are JVM-wide, and this suite shares a JVM with tests that legitimately open a - * connection pool. A Hikari housekeeper left behind by one of those made this class fail for - * something it did not do — so what is asserted is the threads this context added, which is the - * claim anyway: an adapter that is off starts no thread. - */ - private static Set threadsBeforeStartup; - - @BeforeAll - static void startAllOff() { - threadsBeforeStartup = - Thread.getAllStackTraces().keySet().stream() - .map(Thread::getName) - .collect(Collectors.toSet()); - context = - ShippedCompositionHarness.shippedComposition("local") - .run(ShippedCompositionHarness.allOffArguments()); - } - - @AfterAll - static void stop() { - if (context != null) { - context.close(); - } - } - - @Test - @DisplayName("JPA off holds no entity manager, no pool, and no migration") - void jpaOffHoldsNothing() { - assertOffInventoryIsEmpty(Adapter.JPA); - } - - @Test - @DisplayName("Mongo off holds nothing") - void mongoOffHoldsNothing() { - assertOffInventoryIsEmpty(Adapter.MONGO); - } - - @Test - @DisplayName("messaging off holds no publisher, sender, or relay") - void messagingOffHoldsNothing() { - assertOffInventoryIsEmpty(Adapter.MESSAGING); - } - - @Test - @DisplayName("notification off binds no settings and holds no worker") - void notificationOffHoldsNothing() { - assertOffInventoryIsEmpty(Adapter.NOTIFICATION); - } - - @Test - @DisplayName("GraphQL off exposes no schema and no endpoint") - void graphQlOffHoldsNothing() { - assertOffInventoryIsEmpty(Adapter.GRAPHQL); - } - - private static void assertOffInventoryIsEmpty(Adapter adapter) { - assertThat(AdapterActivationInventory.ownedBeanTypeNames(context, adapter)) - .as( - "%s is off, so it must own no bean; the composition root still assembled:%n%s", - adapter, AdapterActivationInventory.describe(context, adapter)) - .isEmpty(); - List startedHere = - AdapterActivationInventory.liveThreadNamesMatching(adapter).stream() - .filter(name -> !threadsBeforeStartup.contains(name)) - .toList(); - assertThat(startedHere) - .as("%s is off, so starting this context must have started no thread of its own", adapter) - .isEmpty(); - } -} diff --git a/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/activation/GraphQlShippedAndGatedTest.java b/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/activation/GraphQlShippedAndGatedTest.java deleted file mode 100644 index 78041382..00000000 --- a/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/activation/GraphQlShippedAndGatedTest.java +++ /dev/null @@ -1,115 +0,0 @@ -package dev.caskeleton.bootstrap.activation; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.bootstrap.activation.AdapterActivationInventory.Adapter; -import java.io.IOException; -import java.net.URI; -import java.net.http.HttpClient; -import java.net.http.HttpRequest; -import java.net.http.HttpResponse; -import java.time.Duration; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.springframework.boot.WebApplicationType; -import org.springframework.boot.web.server.context.WebServerApplicationContext; -import org.springframework.context.ConfigurableApplicationContext; - -/** - * GraphQL ships in the jar and exposes nothing until it is switched on. - * - *

Asserted through a real port rather than through the bean registry, because the failure this - * guards against is precisely the one a bean assertion cannot see: Spring GraphQL publishing {@code - * /graphql} from its own auto-configuration, with no project bean involved. An inventory check - * would report a clean context while the endpoint answered. - */ -class GraphQlShippedAndGatedTest { - - private static ConfigurableApplicationContext context; - private static int port; - - @BeforeAll - static void startAllOff() { - context = - ShippedCompositionHarness.shippedComposition("local") - .web(WebApplicationType.SERVLET) - .run(withRandomPort(ShippedCompositionHarness.allOffArguments())); - port = ((WebServerApplicationContext) context).getWebServer().getPort(); - } - - @AfterAll - static void stop() { - if (context != null) { - context.close(); - } - } - - @Test - @DisplayName("the GraphQL facade is on the shipped classpath") - void facadeIsShipped() throws ClassNotFoundException { - assertThat( - Class.forName( - "dev.caskeleton.adapter.inbound.graphql.autoconfigure.GraphQlRootAutoConfiguration")) - .as("an adapter an operator cannot enable with one environment variable is not off, absent") - .isNotNull(); - } - - /** - * The endpoint is absent, judged against a path that is certainly absent. - * - *

Asserting a literal 404 would have been wrong: the security filter chain runs before - * dispatch and answers 401 for any non-public path, mapped or not. So the question "is /graphql - * published?" is answered by comparing it with a route nobody has ever defined — if the two are - * indistinguishable from outside, the transport is not being served. A literal status assertion - * would also have passed for a published endpoint that merely required authentication, which is - * exactly the false green this test exists to prevent. - */ - @Test - @DisplayName("GraphQL off publishes no endpoint") - void graphQlOffPublishesNoEndpoint() throws IOException, InterruptedException { - HttpResponse graphQl = post("/graphql", "{\"query\":\"{__typename}\"}"); - HttpResponse neverMapped = post("/no-such-route-exists", "{}"); - - assertThat(graphQl.statusCode()) - .as( - "an unswitched transport must be indistinguishable from a route that was never defined; " - + "Spring GraphQL publishes this path from its own auto-configuration, which is why " - + "the off contract needs an import filter and why a bean assertion could not have " - + "caught it") - .isEqualTo(neverMapped.statusCode()); - assertThat(graphQl.statusCode()) - .as("whatever that shared status is, it must never be a success") - .isGreaterThanOrEqualTo(400); - } - - @Test - @DisplayName("GraphQL off holds no schema and no execution bean") - void graphQlOffHoldsNothing() { - assertThat(AdapterActivationInventory.ownedBeanTypeNames(context, Adapter.GRAPHQL)) - .as("%s", AdapterActivationInventory.describe(context, Adapter.GRAPHQL)) - .isEmpty(); - } - - private static HttpResponse post(String path, String body) - throws IOException, InterruptedException { - try (HttpClient client = - HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build()) { - return client.send( - HttpRequest.newBuilder(URI.create("http://localhost:" + port + path)) - .header("Content-Type", "application/json") - .POST(HttpRequest.BodyPublishers.ofString(body)) - .build(), - HttpResponse.BodyHandlers.ofString()); - } - } - - private static String[] withRandomPort(String[] arguments) { - String[] extended = new String[arguments.length + 2]; - System.arraycopy(arguments, 0, extended, 0, arguments.length); - extended[arguments.length] = "--server.port=0"; - extended[arguments.length + 1] = "--management.server.port=0"; - return extended; - } -} diff --git a/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/activation/MasterSwitchEnvironmentPostProcessorTest.java b/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/activation/MasterSwitchEnvironmentPostProcessorTest.java deleted file mode 100644 index ed4bc92b..00000000 --- a/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/activation/MasterSwitchEnvironmentPostProcessorTest.java +++ /dev/null @@ -1,85 +0,0 @@ -package dev.caskeleton.bootstrap.activation; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.util.ArrayList; -import java.util.List; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.springframework.context.ConfigurableApplicationContext; - -/** - * The switch is checked before anything reads a detail setting. - * - *

Checking it later would require binding the namespace it guards, and an adapter that is off - * must be able to start beside an environment full of its own malformed configuration — otherwise - * "off" is only off for deployments that got the off-path settings right. - */ -class MasterSwitchEnvironmentPostProcessorTest { - - @Test - @DisplayName("a typo in a master switch fails startup by name") - void aTypoFailsByName() { - assertThatThrownBy(() -> start("--ca-skeleton.persistence-mongo.enabled=ture").close()) - .hasMessageContaining("ca-skeleton.persistence-mongo.enabled") - .hasMessageContaining("ture") - .hasMessageContaining("rejected rather than read as off"); - } - - /** - * A superseded key fails, and the failure names the key that replaced it. - * - *

Which of the two migration errors fires depends on the shipped configuration. Now that - * {@code application.yml} binds every canonical switch to its environment variable, the canonical - * key is always present, so a legacy key is always the ambiguous case rather than the alone case. - * That is the better outcome and it is not worth arranging around: what an operator needs is the - * replacement name, and both messages carry it. - */ - @Test - @DisplayName("a legacy key fails and names its replacement") - void aLegacyKeyNamesItsReplacement() { - assertThatThrownBy(() -> startWithoutJpaSwitch("--app.jpa-platform.enabled=true").close()) - .hasMessageContaining("app.jpa-platform.enabled") - .hasMessageContaining("ca-skeleton.persistence-jpa.enabled"); - } - - @Test - @DisplayName("an off adapter starts beside its own malformed detail settings") - void offSurvivesMalformedDetail() { - try (ConfigurableApplicationContext context = - start( - "--ca-skeleton.persistence-mongo.active-profile=", - "--ca-skeleton.persistence-mongo.profiles.primary.uri=not a uri")) { - assertThat(context.isRunning()) - .as("a malformed detail setting for an adapter nobody enabled must not block startup") - .isTrue(); - } - } - - /** - * Starts with the all-off baseline minus the JPA switch, so a legacy key is alone rather than - * duplicated. A run that set both would be rejected as ambiguous first, which is a different - * rule. - * - * @param extraArguments arguments appended to the reduced baseline - * @return the started context - */ - private static ConfigurableApplicationContext startWithoutJpaSwitch(String... extraArguments) { - List arguments = - new ArrayList<>( - List.of(ShippedCompositionHarness.allOffArguments()).stream() - .filter(argument -> !argument.startsWith("--ca-skeleton.persistence-jpa.enabled")) - .toList()); - arguments.addAll(List.of(extraArguments)); - return ShippedCompositionHarness.shippedComposition("local") - .run(arguments.toArray(String[]::new)); - } - - private static ConfigurableApplicationContext start(String... extraArguments) { - List arguments = new ArrayList<>(List.of(ShippedCompositionHarness.allOffArguments())); - arguments.addAll(List.of(extraArguments)); - return ShippedCompositionHarness.shippedComposition("local") - .run(arguments.toArray(String[]::new)); - } -} diff --git a/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/composition/BootstrapCapabilityReachabilitySystemTest.java b/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/composition/BootstrapCapabilityReachabilitySystemTest.java new file mode 100644 index 00000000..bdd10bde --- /dev/null +++ b/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/composition/BootstrapCapabilityReachabilitySystemTest.java @@ -0,0 +1,53 @@ +package dev.caskeleton.bootstrap.composition; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.application.idempotency.IdempotencyExecutor; +import io.micrometer.tracing.Tracer; +import org.junit.jupiter.api.Test; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.scheduling.config.TaskManagementConfigUtils; + +/** + * Shipped-root proof for bootstrap-owned capability auto-configurations. + * + *

The unit tests exercise each configuration in isolation. This test boots the real application + * scan plus Boot auto-configuration discovery and proves that making the roots reachable did not + * turn their disabled state into runtime work. + * + *

The lock, outbox, PostgreSQL idempotency and Redis roots are no longer here: they belong to + * persistence-jpa and cache-redis, which this composition does not ship, and {@code + * PersistenceJpaCapabilityAssemblyTest} and {@code RedisCapabilityCompositionTest} prove them where + * the modules are. + */ +class BootstrapCapabilityReachabilitySystemTest { + + @Test + void allOffDeploymentDiscoversRootsWithoutCreatingOptionalRuntimeWork() { + try (ConfigurableApplicationContext context = + ShippedCompositionHarness.shippedComposition("local") + .run(ShippedCompositionHarness.allOffArguments())) { + assertThat(context.containsBean("outboxLeaderElection")).isFalse(); + assertThat(context.containsBean("distributedLockProvider")).isFalse(); + assertThat(context.getBeansOfType(IdempotencyExecutor.class)).isEmpty(); + assertThat( + context.containsBean( + TaskManagementConfigUtils.SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME)) + .isFalse(); + assertThat(context.getBeansOfType(Tracer.class)).isEmpty(); + } + } + + @Test + void tracingRootIsReachableFromTheShippedCompositionWhenEnabled() { + try (ConfigurableApplicationContext context = + ShippedCompositionHarness.shippedComposition("local") + .run(ShippedCompositionHarness.allOffExcept("--ca-skeleton.tracing.enabled=true"))) { + assertThat(context.getBeansOfType(Tracer.class)).hasSize(1); + } + } + + // HTTP client and messaging left this class on 2026-09-25: each is a capability a service selects + // with one runtimeOnly line, and each proves present = on and enabled=false = off in its own + // leaf (HttpClientPlatformActivationTest, KafkaCapabilityActivationTest). +} diff --git a/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/composition/DefaultCompositionBootTest.java b/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/composition/DefaultCompositionBootTest.java new file mode 100644 index 00000000..7b7893ba --- /dev/null +++ b/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/composition/DefaultCompositionBootTest.java @@ -0,0 +1,123 @@ +package dev.caskeleton.bootstrap.composition; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.boot.WebApplicationType; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.util.ClassUtils; + +/** + * The default composition — web, observability, the cores, support and identifier — starts in every + * shipped profile with no database, Redis or broker, and holds nothing a capability brings. + * + *

This is the other half of "one line turns a capability on": each capability leaf proves that + * its module present means its beans exist and {@code enabled=false} means none do ({@code + * PersistenceJpaCapabilityAssemblyTest}, {@code RedisCapabilityActivationTest}, {@code + * KafkaCapabilityActivationTest}). This proves that with every line commented out, nothing of any + * of them is left behind. + * + *

Types are matched by name so the test compiles without a capability on its classpath; a type + * whose class is absent cannot have a bean. + */ +class DefaultCompositionBootTest { + + /** Packages only a capability module contributes. */ + private static final List CAPABILITY_PACKAGES = + List.of( + "dev.caskeleton.adapter.outbound.persistence", + "dev.caskeleton.adapter.outbound.mongo", + "dev.caskeleton.adapter.outbound.cache.redis", + "dev.caskeleton.adapter.outbound.redis", + "dev.caskeleton.adapter.outbound.messaging", + "dev.caskeleton.messaging", + "dev.caskeleton.adapter.outbound.httpclient", + "dev.caskeleton.adapter.outbound.objectstorage", + "dev.caskeleton.adapter.outbound.notification", + "dev.caskeleton.adapter.outbound.fileserver", + "dev.caskeleton.adapter.inbound.graphql", + "dev.caskeleton.adapter.inbound.websocket", + "dev.caskeleton.adapter.inbound.grpc", + "dev.caskeleton.composition"); + + /** Infrastructure a capability connects to; a bean of any of these would open a connection. */ + private static final List INFRASTRUCTURE_TYPES = + List.of( + "javax.sql.DataSource", + "jakarta.persistence.EntityManagerFactory", + "org.flywaydb.core.Flyway", + "com.mongodb.client.MongoClient", + "com.mongodb.reactivestreams.client.MongoClient", + "org.apache.kafka.clients.producer.Producer", + "org.springframework.data.redis.connection.RedisConnectionFactory", + "io.lettuce.core.AbstractRedisClient"); + + /** A production secret the prod profile demands; a dummy is enough to start. */ + private static final String PRODUCTION_SALT = + "--APP_PRIVACY_PSEUDONYMIZATION_SALT=default-composition-boot-test-salt"; + + @ParameterizedTest + @ValueSource(strings = {"local", "dev", "prod"}) + void defaultCompositionStartsWithoutAnyCapability(String profile) { + // when + try (ConfigurableApplicationContext context = start(profile, PRODUCTION_SALT)) { + + // then + assertThat(Stream.concat(capabilityBeans(context), infrastructureBeans(context))) + .as("the %s profile of the default composition carries no capability", profile) + .isEmpty(); + } + } + + @Test + void prodRefusesToStartWithoutItsProductionSecret() { + // when + Throwable thrown = catchThrowable(() -> start("prod").close()); + + // then + assertThat(thrown) + .hasStackTraceContaining("prod secret/config-source contract") + .hasStackTraceContaining("APP_PRIVACY_PSEUDONYMIZATION_SALT"); + } + + private static ConfigurableApplicationContext start(String profile, String... extra) { + String[] arguments = + Stream.of( + ShippedCompositionHarness.requiredOperatorInputs(), + new String[] {"--server.port=0", "--management.server.port=0"}, + extra) + .flatMap(Arrays::stream) + .toArray(String[]::new); + return ShippedCompositionHarness.shippedComposition(profile) + .web(WebApplicationType.SERVLET) + .run(arguments); + } + + private static Stream capabilityBeans(ConfigurableApplicationContext context) { + return Arrays.stream(context.getBeanDefinitionNames()) + .filter( + name -> { + Class type = context.getBeanFactory().getType(name, false); + return type != null + && CAPABILITY_PACKAGES.stream() + .anyMatch(prefix -> type.getName().startsWith(prefix + ".")); + }); + } + + private static Stream infrastructureBeans(ConfigurableApplicationContext context) { + ClassLoader loader = context.getClassLoader(); + return INFRASTRUCTURE_TYPES.stream() + .filter(type -> ClassUtils.isPresent(type, loader)) + .flatMap( + type -> + Arrays.stream( + context.getBeanNamesForType(ClassUtils.resolveClassName(type, loader))) + .map(name -> type + " " + name)); + } +} diff --git a/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/activation/ShippedCompositionHarness.java b/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/composition/ShippedCompositionHarness.java similarity index 52% rename from src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/activation/ShippedCompositionHarness.java rename to src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/composition/ShippedCompositionHarness.java index eb4ffd94..0c72f679 100644 --- a/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/activation/ShippedCompositionHarness.java +++ b/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/composition/ShippedCompositionHarness.java @@ -1,4 +1,4 @@ -package dev.caskeleton.bootstrap.activation; +package dev.caskeleton.bootstrap.composition; import dev.caskeleton.bootstrap.CaSkeletonApplication; import java.io.IOException; @@ -14,23 +14,16 @@ import org.springframework.core.type.classreading.MetadataReaderFactory; /** * Boots the composition root as a deployment would, from inside a test JVM that is not one. * - *

The test classpath is not the shipped classpath, and the difference is not cosmetic. {@code - * CaSkeletonApplication} component-scans {@code dev.caskeleton.bootstrap}; this module's own test - * sources live in that package; so an in-JVM boot discovers test configurations the jar has never - * contained. At the time of writing that is not hypothetical — {@code - * OutboxContainerTestSupport.OutboxRepositoryConfig} declares a second - * {@code @EnableJpaRepositories} and the context dies with a {@code - * BeanDefinitionOverrideException} on {@code outboxEventJpaRepository} before any adapter has been - * examined. - * - *

Left alone, that failure would sit in front of every activation characterization and report - * the same cause for all of them, hiding the defects those tests exist to name. So this harness - * excludes types whose class file was loaded from a test output directory, which is a rule about - * where code came from rather than a list of class names somebody has to maintain. + *

The systemTest runtime is the default composition's runtime graph — the modules {@code + * bootJar} ships, no capability — plus this module's compiled test sources. {@code + * CaSkeletonApplication} component-scans {@code dev.caskeleton.bootstrap}, and the test sources + * live in that package and declare {@code @Configuration} fixtures the jar has never contained. So + * this harness excludes types whose class file was loaded from a test output directory, which is a + * rule about where code came from rather than a list of class names somebody has to maintain. * *

This is a workaround for measuring, not a fix. The real answer is to run the produced jar as a - * child process, which is what the GraphQL runtime qualification does; until the activation work - * needs that machinery, excluding test output is the smaller honest instrument. + * child process; until a test needs that machinery, excluding test output is the smaller honest + * instrument. */ public final class ShippedCompositionHarness { @@ -41,26 +34,22 @@ public final class ShippedCompositionHarness { /** * The inputs a deployment must supply, whatever else it leaves at defaults. * - *

Seven values have no inline default on purpose: an address, a credential, an application - * name, an allowed origin, and a token issuer and audience are decisions only an operator can - * make, and a default for any of them is a deployment running against something nobody chose. - * Everything else in {@code application.yml} now carries a default derived from the env registry, - * so this list is the whole of what an operator has to know. + *

These values have no inline default on purpose: the application name and the token issuer + * and audience are decisions only an operator can make, and a default for any of them is a + * deployment running against something nobody chose. The datasource address and credential used + * to be here too; they arrive with the persistence-jpa module now, which this composition does + * not ship. Everything else in {@code application.yml} now carries a default derived from the env + * registry, so this list is the whole of what an operator has to know. * * @return arguments in {@code --key=value} form */ public static String[] requiredOperatorInputs() { - // The seven values application.yml deliberately leaves undefaulted, supplied at every Spring - // path each one feeds. A default for any of these is a deployment running against something - // nobody chose: an address, a credential, the application's own name, and the issuer and - // audience its tokens are + // The values application.yml deliberately leaves undefaulted, supplied at every Spring path + // each one feeds: the application's own name, and the issuer and audience its tokens are // checked against. return new String[] { "--spring.application.name=ca-skeleton-test", "--ca-skeleton.bootstrap.app-name=ca-skeleton-test", - "--spring.datasource.url=jdbc:postgresql://localhost:5432/ca_skeleton", - "--spring.datasource.username=ca_skeleton", - "--spring.datasource.password=ca_skeleton", "--spring.security.oauth2.resourceserver.jwt.issuer-uri=http://localhost:8081/realms/ca-skeleton", "--ca-skeleton.security.issuer-uri=http://localhost:8081/realms/ca-skeleton", "--spring.security.oauth2.resourceserver.jwt.audiences=ca-skeleton-api", @@ -86,30 +75,24 @@ public final class ShippedCompositionHarness { } /** - * The argument set that turns every optional adapter, and every consumer of one, off. + * The argument set that turns every bootstrap-owned option off. + * + *

Capabilities are not listed: the default composition does not ship them, so their absence + * from the classpath is already the off state. What is left are the composition root's own + * opt-ins. * *

Command-line arguments rather than {@code SpringApplicationBuilder#properties}, which - * contributes to {@code defaultProperties} — the lowest-precedence source there is. Passing the - * all-off set that way left {@code application.yml}'s {@code relay-enabled: true} in charge, and - * the context died on the relay validator while claiming to be an all-off deployment. + * contributes to {@code defaultProperties} — the lowest-precedence source there is, below every + * shipped YAML value it is meant to override. * * @return arguments in {@code --key=value} form, ready for {@link * SpringApplicationBuilder#run(String...)} */ public static String[] allOffArguments() { return new String[] { - "--ca-skeleton.persistence-jpa.enabled=false", - "--ca-skeleton.persistence-mongo.enabled=false", - "--app.messaging.enabled=false", - "--ca-skeleton.notification.platform.enabled=false", - "--backend.graphql.enabled=false", - "--ca-skeleton.outbox.enabled=false", - "--ca-skeleton.outbox.relay-enabled=false", - "--app.redis.enabled=false", "--ca-skeleton.runtime.multi-instance-enabled=false", "--ca-skeleton.capabilities.idempotency.provider=disabled", - "--ca-skeleton.tracing.enabled=false", - "--management.endpoint.health.group.readiness.include=readinessState" + "--ca-skeleton.tracing.enabled=false" }; } @@ -141,38 +124,6 @@ public final class ShippedCompositionHarness { return argument.substring(2, argument.indexOf('=')); } - /** - * Starts from the all-off deployment with the repository's explicit local H2 opt-out enabled. - * - *

This mirrors {@code bootRunH2}: H2 is a wiring/behaviour lane only, Flyway stays off and - * Hibernate owns the ephemeral schema. A unique database name keeps independently runnable system - * tests from sharing an in-memory schema. - * - * @param databaseName unique in-memory database name - * @param overrides additional command-line overrides - * @return one argument per key - */ - public static String[] allOffWithH2(String databaseName, String... overrides) { - String[] h2 = - new String[] { - "--ca-skeleton.persistence-jpa.enabled=true", - "--ca-skeleton.persistence.vendor=h2", - "--spring.datasource.url=jdbc:h2:mem:" - + databaseName - + ";MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1", - "--spring.datasource.username=sa", - "--spring.datasource.password=", - "--spring.datasource.driver-class-name=org.h2.Driver", - "--spring.flyway.enabled=false", - "--spring.jpa.hibernate.ddl-auto=create-drop", - "--ca-skeleton.runtime.migration-on-startup=false" - }; - String[] combined = new String[h2.length + overrides.length]; - System.arraycopy(h2, 0, combined, 0, h2.length); - System.arraycopy(overrides, 0, combined, h2.length, overrides.length); - return allOffExcept(combined); - } - /** * Excludes any candidate whose class file lives in a test output directory. * diff --git a/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/activation/StartupWarningZeroTest.java b/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/composition/StartupWarningZeroTest.java similarity index 97% rename from src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/activation/StartupWarningZeroTest.java rename to src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/composition/StartupWarningZeroTest.java index cd90a36b..0c124a6c 100644 --- a/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/activation/StartupWarningZeroTest.java +++ b/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/composition/StartupWarningZeroTest.java @@ -1,4 +1,4 @@ -package dev.caskeleton.bootstrap.activation; +package dev.caskeleton.bootstrap.composition; import static org.assertj.core.api.Assertions.assertThat; diff --git a/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/logging/LogProfileDriftCharacterizationTest.java b/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/logging/LogProfileDriftCharacterizationTest.java index f742d7d8..0c41d051 100644 --- a/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/logging/LogProfileDriftCharacterizationTest.java +++ b/src/app-bootstrap/src/systemTest/java/dev/caskeleton/bootstrap/logging/LogProfileDriftCharacterizationTest.java @@ -3,7 +3,7 @@ package dev.caskeleton.bootstrap.logging; import static org.assertj.core.api.Assertions.assertThat; import ch.qos.logback.classic.LoggerContext; -import dev.caskeleton.bootstrap.activation.ShippedCompositionHarness; +import dev.caskeleton.bootstrap.composition.ShippedCompositionHarness; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/adapter/outbound/DisabledAdapterSentinelTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/adapter/outbound/DisabledAdapterSentinelTest.java deleted file mode 100644 index 01441488..00000000 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/adapter/outbound/DisabledAdapterSentinelTest.java +++ /dev/null @@ -1,60 +0,0 @@ -package dev.caskeleton.adapter.outbound; - -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.outbound.messaging.core.DisabledMessagePublisher; -import dev.caskeleton.adapter.outbound.messaging.core.OutboundMessage; -import dev.caskeleton.adapter.outbound.notification.core.RoutingNotifier; -import dev.caskeleton.application.notification.Notification; -import dev.caskeleton.application.notification.NotificationChannel; -import dev.caskeleton.shared.error.AdapterDisabledException; -import java.util.List; -import java.util.Map; -import org.junit.jupiter.api.Test; - -/** - * Layer 3 (D4) — a disabled optional adapter that is nonetheless invoked must fail fast with {@link - * AdapterDisabledException}, never a silent no-op or timeout wait (required_test {@code - * adapter-contract:adapter-disabled-runtime-call}). - * - *

Notification uses the router-fail-fast shape (no per-channel {@code Disabled*Notifier} - * sentinel): an unbound route on a {@link RoutingNotifier} with no providers/routes throws {@link - * AdapterDisabledException}. - */ -class DisabledAdapterSentinelTest { - - private static final Notification STUB_NOTIFICATION = - new Notification("test@example.com", "s", "b"); - - @Test - void disabledMessagingFailsFast() { - assertThatThrownBy( - () -> new DisabledMessagePublisher().publish(new OutboundMessage("t", "k", "p"))) - .isInstanceOf(AdapterDisabledException.class) - .extracting("adapterName") - .isEqualTo("messaging"); - } - - @Test - void unwiredNotificationEmailFailsFast() { - // router-fail-fast: no providers, no routes → AdapterDisabledException on first call - assertThatThrownBy( - () -> - new RoutingNotifier(List.of(), Map.of()) - .notify(NotificationChannel.EMAIL, STUB_NOTIFICATION)) - .isInstanceOf(AdapterDisabledException.class) - .extracting("adapterName") - .isEqualTo("notification"); - } - - @Test - void unwiredNotificationSlackFailsFast() { - assertThatThrownBy( - () -> - new RoutingNotifier(List.of(), Map.of()) - .notify(NotificationChannel.SLACK, "alerts", STUB_NOTIFICATION)) - .isInstanceOf(AdapterDisabledException.class) - .extracting("adapterName") - .isEqualTo("notification"); - } -} diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/adapter/outbound/OptionalAdapterBeanGatingTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/adapter/outbound/OptionalAdapterBeanGatingTest.java deleted file mode 100644 index 1d3feece..00000000 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/adapter/outbound/OptionalAdapterBeanGatingTest.java +++ /dev/null @@ -1,197 +0,0 @@ -package dev.caskeleton.adapter.outbound; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.outbound.fileserver.FileExportConfig; -import dev.caskeleton.adapter.outbound.fileserver.FileserverR2Config; -import dev.caskeleton.adapter.outbound.httpclient.autoconfigure.HttpClientPlatformAutoConfiguration; -import dev.caskeleton.adapter.outbound.httpclient.profile.ClientRuntimeRegistry; -import dev.caskeleton.adapter.outbound.messaging.MessagingConfig; -import dev.caskeleton.adapter.outbound.messaging.core.DisabledMessagePublisher; -import dev.caskeleton.adapter.outbound.messaging.core.MessageBroker; -import dev.caskeleton.adapter.outbound.messaging.core.MessagePublisher; -import dev.caskeleton.adapter.outbound.messaging.core.OutboundMessagePublisher; -import dev.caskeleton.adapter.outbound.messaging.kafka.KafkaAdapterConfig; -import dev.caskeleton.adapter.outbound.messaging.kafka.KafkaSender; -import dev.caskeleton.adapter.outbound.messaging.outbox.DisabledOutboxMessagePublisher; -import dev.caskeleton.adapter.outbound.messaging.outbox.OutboxMessagePublishAdapter; -import dev.caskeleton.adapter.outbound.messaging.outbox.Slf4jOutboxRelayFailureReportAdapter; -import dev.caskeleton.adapter.outbound.notification.NotificationConfig; -import dev.caskeleton.adapter.outbound.notification.core.NotificationProvider; -import dev.caskeleton.adapter.outbound.notification.core.RoutingNotifier; -import dev.caskeleton.adapter.outbound.notification.email.google.GoogleEmailClient; -import dev.caskeleton.adapter.outbound.notification.email.google.GoogleEmailNotificationAdapterConfig; -import dev.caskeleton.adapter.outbound.notification.slack.webhook.SlackClient; -import dev.caskeleton.adapter.outbound.notification.slack.webhook.SlackNotificationAdapterConfig; -import dev.caskeleton.adapter.outbound.support.OutboundSupportConfig; -import dev.caskeleton.application.filepublication.FilePublicationPort; -import dev.caskeleton.application.notification.Notification; -import dev.caskeleton.application.notification.NotificationChannel; -import dev.caskeleton.application.notification.NotificationPort; -import dev.caskeleton.application.outbox.OutboxMessagePublishPort; -import dev.caskeleton.application.outbox.OutboxRelayFailureReportPort; -import dev.caskeleton.shared.error.AdapterDisabledException; -import dev.caskeleton.shared.ratelimit.EdgeRateLimitPort; -import org.junit.jupiter.api.Test; -import org.springframework.boot.autoconfigure.AutoConfigurations; -import org.springframework.boot.test.context.runner.ApplicationContextRunner; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -/** - * Layer 1 (D2) — {@code @ConditionalOnProperty} bean-gating contract (required_test {@code - * adapter-contract:{kafka,slack-webhook,google-email}-disabled-default}). - * - *

Asserts that with the default (env absent → disabled) the real adapter bean count is 0 and the - * router fails fast on unbound access; and that flipping the enable flag (with the integration - * client supplied) registers the real adapter and routes correctly. - * - *

Notification: uses the router-fail-fast shape. No per-channel {@code Disabled*Notifier} - * sentinel — unbound route → {@link AdapterDisabledException} from {@link RoutingNotifier}. - */ -class OptionalAdapterBeanGatingTest { - - private static final Notification STUB_NOTIFICATION = - new Notification("test@example.com", "test", "body"); - - private final ApplicationContextRunner runner = - new ApplicationContextRunner() - // Registered as a real auto-configuration entry, which is how the composition root - // reaches it: the HTTP Client platform's off state is a property of that entry, not of a - // hand-assembled subset of its children. - .withConfiguration(AutoConfigurations.of(HttpClientPlatformAutoConfiguration.class)) - .withUserConfiguration( - OutboundSupportConfig.class, - MessagingConfig.class, - KafkaAdapterConfig.class, - NotificationConfig.class, - SlackNotificationAdapterConfig.class, - GoogleEmailNotificationAdapterConfig.class, - FileExportConfig.class, - FileserverR2Config.class, - StubClientsConfig.class); - - @Test - void allOptionalAdaptersAreDisabledByDefaultAndTheAppStillStarts() { - // L262: an optional adapter must NOT become a required startup dependency. - runner.run( - context -> { - assertThat(context).hasNotFailed(); - - // real provider beans absent (Layer 1 — disabled, contributes nothing) - assertThat(context.getBeansOfType(MessageBroker.class)).isEmpty(); - assertThat(context.getBeansOfType(EdgeRateLimitPort.class)).isEmpty(); - assertThat(context.getBeansOfType(NotificationProvider.class)).isEmpty(); - assertThat(context.getBeansOfType(FilePublicationPort.class)).isEmpty(); - // Not "an empty registry". With app.httpclient.enabled unset there is no registry, no - // transport provider and no gateway at all. The previous assertion — a registry bean - // holding no profiles — was what made the capability mandatory-with-a-switch rather than - // optional: the pool, TLS and credential machinery was still assembled around it. - assertThat(context.getBeansOfType(ClientRuntimeRegistry.class)).isEmpty(); - - // messaging: fail-fast sentinels satisfy the ports (Layer 3 fallback) - assertThat(context.getBean(MessagePublisher.class)) - .isInstanceOf(DisabledMessagePublisher.class); - assertThat(context.getBean(OutboxMessagePublishPort.class)) - .isInstanceOf(DisabledOutboxMessagePublisher.class); - assertThat(context.getBeansOfType(OutboxRelayFailureReportPort.class)).hasSize(1); - assertThat(context.getBean(OutboxRelayFailureReportPort.class)) - .isInstanceOf(Slf4jOutboxRelayFailureReportAdapter.class); - - // notification D4: zero providers boot fine, unbound route fails fast in RoutingNotifier - NotificationPort notificationPort = context.getBean(NotificationPort.class); - assertThat(notificationPort).isInstanceOf(RoutingNotifier.class); - assertThatThrownBy( - () -> notificationPort.notify(NotificationChannel.EMAIL, STUB_NOTIFICATION)) - .isInstanceOf(AdapterDisabledException.class) - .extracting("adapterName") - .isEqualTo("notification"); - }); - } - - @Test - void kafkaSelectedRegistersTheBrokerAndBindsTheRealPublishers() { - runner - .withPropertyValues( - "app.messaging.broker=kafka", "app.messaging.kafka.brokers=broker-1:9092") - .run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context.getBeansOfType(MessageBroker.class)).hasSize(1); - assertThat(context.getBean(MessagePublisher.class)) - .isInstanceOf(OutboundMessagePublisher.class); - assertThat(context.getBeansOfType(DisabledMessagePublisher.class)).isEmpty(); - assertThat(context.getBeansOfType(DisabledOutboxMessagePublisher.class)).isEmpty(); - assertThat(context.getBean(OutboxMessagePublishPort.class)) - .isInstanceOf(OutboxMessagePublishAdapter.class); - assertThat(context.getBeansOfType(OutboxRelayFailureReportPort.class)).hasSize(1); - assertThat(context.getBean(OutboxRelayFailureReportPort.class)) - .isInstanceOf(Slf4jOutboxRelayFailureReportAdapter.class); - }); - } - - @Test - void slackWebhookEnabledContributesTheProviderAndRoutesBoundNotifications() { - runner - .withPropertyValues( - "app.notification.slack-webhook.enabled=true", - "app.notification.routes.slack.default=slack-webhook") - .run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context.getBeansOfType(NotificationProvider.class)).hasSize(1); - NotificationPort port = context.getBean(NotificationPort.class); - assertThat(port).isInstanceOf(RoutingNotifier.class); - // stub SlackClient is a no-op — call succeeds without exception - assertThatCode(() -> port.notify(NotificationChannel.SLACK, STUB_NOTIFICATION)) - .doesNotThrowAnyException(); - }); - } - - @Test - void googleEmailEnabledContributesTheProviderAndRoutesBoundNotifications() { - runner - .withPropertyValues( - "app.notification.google-email.enabled=true", - "app.notification.routes.email.default=google-email") - .run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context.getBeansOfType(NotificationProvider.class)).hasSize(1); - NotificationPort port = context.getBean(NotificationPort.class); - assertThat(port).isInstanceOf(RoutingNotifier.class); - assertThatCode(() -> port.notify(NotificationChannel.EMAIL, STUB_NOTIFICATION)) - .doesNotThrowAnyException(); - }); - } - - @Test - void aRouteBindingToADisabledProviderFailsStartup() { - // configuration contradiction: route references a provider that contributed no bean - runner - .withPropertyValues("app.notification.routes.email.default=google-email") - .run(context -> assertThat(context).hasFailed()); - } - - /** Supplies the integration-seam client beans an enabled adapter requires. */ - @Configuration - static class StubClientsConfig { - - @Bean - KafkaSender kafkaSender() { - return message -> {}; - } - - @Bean - SlackClient slackClient() { - return notification -> {}; - } - - @Bean - GoogleEmailClient googleEmailClient() { - return notification -> {}; - } - } -} diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/activation/AdapterActivationEndpointTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/activation/AdapterActivationEndpointTest.java deleted file mode 100644 index e715f27f..00000000 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/activation/AdapterActivationEndpointTest.java +++ /dev/null @@ -1,57 +0,0 @@ -package dev.caskeleton.bootstrap.activation; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.shared.activation.MasterSwitch; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.springframework.mock.env.MockEnvironment; - -/** - * The report answers for the application, not for the flags a lane passed in. - * - *

A smoke lane that asserted on its own environment would pass whenever it set the variables - * correctly, which is not the claim. What it needs to know is what the application resolved — and - * the two differ exactly when something is wrong. - */ -class AdapterActivationEndpointTest { - - @Test - @DisplayName("all off reports five false switches and no relational consumer") - void allOffReportsEverythingOff() { - AdapterActivationReport report = new AdapterActivationEndpoint(allOff()).activation(); - - assertThat(report.switches()) - .as("every master switch is reported, so a lane cannot check four and assume the fifth") - .hasSize(MasterSwitch.values().length) - .containsValues(false); - assertThat(report.dataSourceRequiredBy()) - .as("nothing needs a connection, which is what makes an infrastructure-free boot possible") - .isEmpty(); - assertThat(report.activeProfile()).isEqualTo("local"); - } - - @Test - @DisplayName("an enabled capability is reported by name, with what it makes required") - void anEnabledCapabilityIsReported() { - MockEnvironment environment = allOff(); - environment.setProperty(MasterSwitch.PERSISTENCE_JPA.property(), "true"); - - AdapterActivationReport report = new AdapterActivationEndpoint(environment).activation(); - - assertThat(report.switches()).containsEntry(MasterSwitch.PERSISTENCE_JPA.property(), true); - assertThat(report.dataSourceRequiredBy()) - .as("the report names why a connection is needed, not merely that one is") - .anySatisfy(reason -> assertThat(reason).contains(MasterSwitch.PERSISTENCE_JPA.property())); - } - - private static MockEnvironment allOff() { - MockEnvironment environment = new MockEnvironment(); - environment.setActiveProfiles("local"); - for (MasterSwitch masterSwitch : MasterSwitch.values()) { - environment.setProperty(masterSwitch.property(), "false"); - } - environment.setProperty("ca-skeleton.capabilities.idempotency.provider", "disabled"); - return environment; - } -} diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/activation/AdapterActivationReportShapeTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/activation/AdapterActivationReportShapeTest.java deleted file mode 100644 index eec86179..00000000 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/activation/AdapterActivationReportShapeTest.java +++ /dev/null @@ -1,73 +0,0 @@ -package dev.caskeleton.bootstrap.activation; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.shared.activation.MasterSwitch; -import java.util.List; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.springframework.mock.env.MockEnvironment; - -/** - * The activation report stays safe to serve without authentication. - * - *

It is permit-all on the management connector, which is a decision rather than an oversight: a - * lane that starts no infrastructure has no identity provider to authenticate against, and those - * are the lanes whose claim — that nothing is on — is hardest to check any other way. - * - *

What makes that safe is the shape, so the shape is asserted rather than assumed. Every key is - * a master switch's own property name; every value is a boolean; and the required-connection - * reasons name properties, never the address or credential of anything. - */ -class AdapterActivationReportShapeTest { - - /** Values that would turn a capability summary into reconnaissance if they ever leaked in. */ - private static final List MUST_NOT_APPEAR = - List.of("password", "secret", "credential", "token", "jdbc:", "mongodb://", "://", "@"); - - @Test - @DisplayName("keys are master-switch properties and values are booleans") - void theReportIsPropertyNamesAndBooleans() { - AdapterActivationReport report = new AdapterActivationEndpoint(populated()).activation(); - - List canonical = - java.util.Arrays.stream(MasterSwitch.values()).map(MasterSwitch::property).toList(); - assertThat(report.switches().keySet()) - .as("a key that is not a master switch property is a field nobody reviewed") - .containsExactlyInAnyOrderElementsOf(canonical); - } - - @Test - @DisplayName("nothing in the report can carry an address or a credential") - void theReportCarriesNoSensitiveShape() { - AdapterActivationReport report = new AdapterActivationEndpoint(populated()).activation(); - - String rendered = - report.activeProfile() + report.switches().keySet() + report.dataSourceRequiredBy(); - - for (String forbidden : MUST_NOT_APPEAR) { - assertThat(rendered) - .as( - "the report is permit-all, so %s appearing in it would publish something the " - + "management connector authenticates for everywhere else", - forbidden) - .doesNotContain(forbidden); - } - } - - /** Every switch on and every relational consumer active — the report's widest possible shape. */ - private static MockEnvironment populated() { - MockEnvironment environment = new MockEnvironment(); - environment.setActiveProfiles("prod"); - for (MasterSwitch masterSwitch : MasterSwitch.values()) { - environment.setProperty(masterSwitch.property(), "true"); - } - environment.setProperty("ca-skeleton.outbox.enabled", "true"); - environment.setProperty("ca-skeleton.capabilities.idempotency.provider", "jdbc"); - environment.setProperty("ca-skeleton.runtime.multi-instance-enabled", "true"); - environment.setProperty("app.fileserver-platform.enabled", "true"); - environment.setProperty("spring.datasource.url", "jdbc:postgresql://secret-host:5432/db"); - environment.setProperty("spring.datasource.password", "hunter2"); - return environment; - } -} diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/activation/CapabilityDependencyValidatorTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/activation/CapabilityDependencyValidatorTest.java deleted file mode 100644 index 07a9b568..00000000 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/activation/CapabilityDependencyValidatorTest.java +++ /dev/null @@ -1,274 +0,0 @@ -package dev.caskeleton.bootstrap.activation; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.bootstrap.runtime.startup.RequiredAdapterDisabledException; -import dev.caskeleton.bootstrap.runtime.startup.StartupErrorCode; -import java.util.List; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.springframework.mock.env.MockEnvironment; - -/** - * A capability that needs something switched off must say which switch, by name. - * - *

Each case pairs the combination with the property an operator has to set. That pairing is the - * whole point: a validator that rejects a deployment without naming the value has moved the - * incident from runtime to startup without making it any easier to fix. - */ -class CapabilityDependencyValidatorTest { - - @Test - @DisplayName("all off is consistent") - void allOffIsConsistent() { - assertThat(CapabilityDependencyValidator.violations(allOff())).isEmpty(); - } - - @Test - @DisplayName("the outbox needs a database, and a relaying outbox also needs a broker") - void outboxNeedsPersistenceAndARelayingOutboxNeedsMessaging() { - MockEnvironment environment = - allOff() - .withProperty("ca-skeleton.outbox.enabled", "true") - .withProperty("ca-skeleton.outbox.relay-enabled", "true"); - - List violations = CapabilityDependencyValidator.violations(environment); - - assertThat(violations) - .as("a relay that cannot store rows exhausts them to DEAD one retry budget at a time") - .anySatisfy(v -> assertThat(v).contains("ca-skeleton.persistence-jpa.enabled")) - .anySatisfy(v -> assertThat(v).contains("app.messaging.enabled")); - } - - @Test - @DisplayName("an outbox with the relay off stores rows and demands no transport") - void outboxWithoutARelayDoesNotDemandMessaging() { - // The two coherent configurations OutboxRelayBrokerRequirementValidator names are "a relay with - // a broker" and "no relay". Requiring messaging for the capability rather than for the relay - // refused the second one, and in a broker-neutral artifact — which is what the default build - // composition produces — it left the outbox with no reachable configuration at all. - MockEnvironment environment = - allOff() - .withProperty("ca-skeleton.outbox.enabled", "true") - .withProperty("ca-skeleton.outbox.relay-enabled", "false") - .withProperty("ca-skeleton.persistence-jpa.enabled", "true"); - - assertThat(CapabilityDependencyValidator.violations(environment)).isEmpty(); - } - - @Test - @DisplayName("the relay is not a capability switch") - void relayWithoutTheCapabilityIsRejected() { - MockEnvironment environment = allOff().withProperty("ca-skeleton.outbox.relay-enabled", "true"); - - assertThat(CapabilityDependencyValidator.violations(environment)) - .anySatisfy(v -> assertThat(v).contains("ca-skeleton.outbox.enabled")); - } - - @Test - @DisplayName("messaging on with a blank broker names the broker property") - void messagingNeedsABroker() { - MockEnvironment environment = allOff().withProperty("app.messaging.enabled", "true"); - - assertThat(CapabilityDependencyValidator.violations(environment)) - .as("a blank broker used to be read as off, which is a selector doing a switch's job") - .anySatisfy(v -> assertThat(v).contains("app.messaging.broker")); - } - - @Test - @DisplayName("a JDBC idempotency store needs a database") - void jdbcIdempotencyNeedsPersistence() { - MockEnvironment environment = - allOff().withProperty("ca-skeleton.capabilities.idempotency.provider", "jdbc"); - - assertThat(CapabilityDependencyValidator.violations(environment)) - .anySatisfy(v -> assertThat(v).contains("ca-skeleton.persistence-jpa.enabled")); - } - - @Test - @DisplayName("the PostgreSQL owner-safe idempotency provider needs JPA") - void postgresqlIdempotencyNeedsPersistence() { - MockEnvironment environment = - allOff().withProperty("ca-skeleton.capabilities.idempotency.provider", "postgresql"); - - assertThat(CapabilityDependencyValidator.violations(environment)) - .anySatisfy( - violation -> - assertThat(violation) - .contains("provider=postgresql") - .contains("ca-skeleton.persistence-jpa.enabled")); - } - - @Test - @DisplayName("the canonical multi-instance runtime switch needs JPA") - void multiInstanceLockNeedsPersistence() { - MockEnvironment environment = - allOff().withProperty("ca-skeleton.runtime.multi-instance-enabled", "true"); - - assertThat(CapabilityDependencyValidator.violations(environment)) - .anySatisfy( - violation -> - assertThat(violation) - .contains("ca-skeleton.runtime.multi-instance-enabled") - .contains("ca-skeleton.persistence-jpa.enabled")); - } - - @Test - @DisplayName("notification stores requests relationally, and no other store exists yet") - void notificationNeedsPersistence() { - MockEnvironment environment = - allOff().withProperty("ca-skeleton.notification.platform.enabled", "true"); - - assertThat(CapabilityDependencyValidator.violations(environment)) - .anySatisfy(v -> assertThat(v).contains("ca-skeleton.persistence-jpa.enabled")); - } - - @Test - @DisplayName("Mongo on needs exactly one active profile") - void mongoNeedsAnActiveProfile() { - MockEnvironment environment = - allOff().withProperty("ca-skeleton.persistence-mongo.enabled", "true"); - - assertThat(CapabilityDependencyValidator.violations(environment)) - .as("a profiles map with nothing selected builds no client, or silently builds several") - .anySatisfy(v -> assertThat(v).contains("ca-skeleton.persistence-mongo.active-profile")); - } - - @Test - @DisplayName( - "Mongo on refuses the driver localhost/test fallback when no connection source exists") - void mongoNeedsAnExplicitConnectionSource() { - MockEnvironment environment = - allOff() - .withProperty("ca-skeleton.persistence-mongo.enabled", "true") - .withProperty("ca-skeleton.persistence-mongo.active-profile", "primary"); - - assertThat(CapabilityDependencyValidator.violations(environment)) - .anySatisfy( - violation -> - assertThat(violation) - .contains("spring.mongodb.uri") - .contains("platform.profiles.primary.uri-secret")); - } - - @Test - @DisplayName("Mongo standard URI is an explicit connection source") - void mongoAcceptsTheStandardSpringUriConnectionSource() { - MockEnvironment environment = - allOff() - .withProperty("ca-skeleton.persistence-mongo.enabled", "true") - .withProperty("ca-skeleton.persistence-mongo.active-profile", "primary") - .withProperty("spring.mongodb.uri", "mongodb://mongo:27017/app"); - - assertThat(CapabilityDependencyValidator.violations(environment)) - .noneSatisfy(violation -> assertThat(violation).contains("connection source")); - } - - @Test - @DisplayName("Mongo active profile URI secret is an explicit connection source") - void mongoAcceptsTheTypedProfileSecretConnectionSource() { - MockEnvironment environment = - allOff() - .withProperty("ca-skeleton.persistence-mongo.enabled", "true") - .withProperty("ca-skeleton.persistence-mongo.active-profile", "primary") - .withProperty( - "ca-skeleton.persistence-mongo.platform.profiles.primary.uri-secret", - "secret://mongodb/primary-uri"); - - assertThat(CapabilityDependencyValidator.violations(environment)) - .noneSatisfy(violation -> assertThat(violation).contains("connection source")); - } - - @Test - @DisplayName("GraphQL on needs a deployment mode") - void graphQlNeedsADeploymentMode() { - MockEnvironment environment = allOff().withProperty("backend.graphql.enabled", "true"); - environment.setActiveProfiles("local"); - - assertThat(CapabilityDependencyValidator.violations(environment)) - .anySatisfy(v -> assertThat(v).contains("backend.graphql.deployment-mode")); - } - - @Test - @DisplayName("a production GraphQL mode is refused in the local runtime") - void graphQlModeMustMatchTheRuntime() { - MockEnvironment environment = - allOff() - .withProperty("backend.graphql.enabled", "true") - .withProperty("backend.graphql.deployment-mode", "PRODUCTION_PUBLIC"); - environment.setActiveProfiles("local"); - - assertThat(CapabilityDependencyValidator.violations(environment)) - .as( - "the two old axes could disagree, so anonymous access and allow-by-default authorization " - + "followed one while the other claimed production") - .anySatisfy(v -> assertThat(v).contains("not permitted in the local runtime")); - } - - @Test - @DisplayName("a matching GraphQL mode is accepted") - void graphQlLocalModeIsAccepted() { - MockEnvironment environment = - allOff() - .withProperty("backend.graphql.enabled", "true") - .withProperty("backend.graphql.deployment-mode", "LOCAL"); - environment.setActiveProfiles("local"); - - assertThat(CapabilityDependencyValidator.violations(environment)).isEmpty(); - } - - @Test - @DisplayName( - "requireSatisfied raises one typed adapter-enablement failure containing every dependency") - void requireSatisfiedAggregatesThroughTheTypedStartupContext() { - MockEnvironment environment = - allOff() - .withProperty("ca-skeleton.outbox.enabled", "true") - .withProperty("ca-skeleton.outbox.relay-enabled", "true"); - - assertThatThrownBy(() -> CapabilityDependencyValidator.requireSatisfied(environment)) - .isInstanceOfSatisfying( - RequiredAdapterDisabledException.class, - failure -> { - assertThat(failure.errorCode()).isEqualTo(StartupErrorCode.REQUIRED_ADAPTER_DISABLED); - assertThat(failure.getMessage()) - .contains("dependencies are off") - .contains("ca-skeleton.persistence-jpa.enabled") - .contains("app.messaging.enabled"); - }); - } - - @Test - @DisplayName("requireSatisfied returns quietly when the dependency graph is consistent") - void requireSatisfiedAcceptsAConsistentGraph() { - CapabilityDependencyValidator.requireSatisfied(allOff()); - } - - @Test - @DisplayName("a satisfied outbox graph is accepted") - void aSatisfiedOutboxGraphIsAccepted() { - MockEnvironment environment = - allOff() - .withProperty("ca-skeleton.outbox.enabled", "true") - .withProperty("ca-skeleton.outbox.relay-enabled", "true") - .withProperty("ca-skeleton.persistence-jpa.enabled", "true") - .withProperty("app.messaging.enabled", "true") - .withProperty("app.messaging.broker", "kafka"); - - assertThat(CapabilityDependencyValidator.violations(environment)).isEmpty(); - } - - private static MockEnvironment allOff() { - MockEnvironment environment = new MockEnvironment(); - environment.setProperty("ca-skeleton.persistence-jpa.enabled", "false"); - environment.setProperty("ca-skeleton.persistence-mongo.enabled", "false"); - environment.setProperty("app.messaging.enabled", "false"); - environment.setProperty("ca-skeleton.notification.platform.enabled", "false"); - environment.setProperty("backend.graphql.enabled", "false"); - environment.setProperty("ca-skeleton.outbox.enabled", "false"); - environment.setProperty("ca-skeleton.outbox.relay-enabled", "false"); - environment.setProperty("ca-skeleton.capabilities.idempotency.provider", "disabled"); - return environment; - } -} diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/activation/GraphQlDeploymentModeRegistryParityTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/activation/GraphQlDeploymentModeRegistryParityTest.java deleted file mode 100644 index 370b1ff7..00000000 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/activation/GraphQlDeploymentModeRegistryParityTest.java +++ /dev/null @@ -1,110 +0,0 @@ -package dev.caskeleton.bootstrap.activation; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.adapter.inbound.graphql.autoconfigure.GraphQlDeploymentMode; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.Arrays; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.EnumSource; -import org.springframework.mock.env.MockEnvironment; - -/** - * The deployment mode means the same thing in the enum, the registry, and the startup validator. - * - *

Three places have to agree, and every one of them is somebody's source of truth: the enum is - * what the platform switches on, {@code docs/registries/env-keys.yaml} is what an operator reads, - * and {@link CapabilityDependencyValidator} is what refuses the deployment. Drift between them is - * quiet in the worst way — a mode the registry documents but the enum cannot bind fails at startup - * with a type-conversion error, and a mode the enum has but no runtime permits is a posture nobody - * can deploy and nobody notices is dead. - * - *

Derived from {@link GraphQlDeploymentMode#values()} rather than from a list written here, so a - * fifth mode cannot be added without this test demanding its registry row and its runtime. - */ -class GraphQlDeploymentModeRegistryParityTest { - - private static final Pattern ALLOWED_VALUES = - Pattern.compile( - "name: APP_GRAPHQL_DEPLOYMENT_MODE.*?allowed_values: \\[([^\\]]*)\\]", Pattern.DOTALL); - - @Test - @DisplayName("the registry lists exactly the modes the enum has") - void theRegistryListsExactlyTheModesTheEnumHas() throws IOException { - Set registered = registeredModes(); - - assertThat(registered) - .as("the registry is what an operator sets APP_GRAPHQL_DEPLOYMENT_MODE from") - .containsExactlyInAnyOrderElementsOf( - Arrays.stream(GraphQlDeploymentMode.values()).map(Enum::name).toList()); - } - - @ParameterizedTest - @EnumSource(GraphQlDeploymentMode.class) - @DisplayName("every mode is permitted by exactly one runtime") - void everyModeIsReachableFromOneRuntime(GraphQlDeploymentMode mode) { - Set accepting = new LinkedHashSet<>(); - for (String runtime : List.of("local", "dev", "prod")) { - if (violationsFor(runtime, mode.name()).isEmpty()) { - accepting.add(runtime); - } - } - - assertThat(accepting) - .as( - "%s must be selectable somewhere and refused everywhere else; a mode no runtime accepts " - + "is dead configuration, and one that several accept is the ambiguity the collapse " - + "removed", - mode) - .hasSize(1); - } - - @Test - @DisplayName("a mode the enum does not have is refused rather than guessed") - void anUnknownModeIsRefused() { - assertThat(violationsFor("prod", "PRODUCTION")) - .as("the retired enum resolved an unknown name to PRODUCTION_PUBLIC, which is a guess") - .isNotEmpty(); - } - - private static List violationsFor(String runtime, String mode) { - MockEnvironment environment = new MockEnvironment(); - environment.setProperty("backend.graphql.enabled", "true"); - environment.setProperty("backend.graphql.deployment-mode", mode); - environment.setActiveProfiles(runtime); - return CapabilityDependencyValidator.violations(environment); - } - - private static Set registeredModes() throws IOException { - String registry = Files.readString(repositoryRoot().resolve("docs/registries/env-keys.yaml")); - Matcher matcher = ALLOWED_VALUES.matcher(registry); - assertThat(matcher.find()) - .as("APP_GRAPHQL_DEPLOYMENT_MODE must carry an allowed_values list") - .isTrue(); - return Arrays.stream(matcher.group(1).split(",")) - .map(String::trim) - .filter(value -> !value.isEmpty()) - .collect(java.util.stream.Collectors.toCollection(LinkedHashSet::new)); - } - - private static Path repositoryRoot() { - Path candidate = Path.of("").toAbsolutePath(); - while (candidate != null - && !Files.isRegularFile(candidate.resolve("src/config/architecture/modules.json"))) { - candidate = candidate.getParent(); - } - if (candidate == null) { - throw new IllegalStateException("could not locate the repository root from the test cwd"); - } - return candidate; - } -} diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/activation/MasterSwitchRegistryContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/activation/MasterSwitchRegistryContractTest.java deleted file mode 100644 index d918475a..00000000 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/activation/MasterSwitchRegistryContractTest.java +++ /dev/null @@ -1,102 +0,0 @@ -package dev.caskeleton.bootstrap.activation; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.bootstrap.contract.support.ShippedConfiguration; -import dev.caskeleton.shared.activation.MasterSwitch; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.EnumSource; - -/** - * The five switches say the same thing in the enum, the registry, and the shipped YAML. - * - *

Three places have to agree for a switch to mean anything: the code that reads it, the registry - * an operator consults, and the file that supplies the default. When they drift the failure is - * quiet — an operator sets the documented variable and nothing happens, or a default flips - * somewhere nobody was looking. Deriving every case from {@link MasterSwitch} means a sixth adapter - * cannot be added without this test demanding its row. - */ -class MasterSwitchRegistryContractTest { - - @ParameterizedTest - @EnumSource(MasterSwitch.class) - @DisplayName("every switch is registered, defaults to false, and is bound by the shipped YAML") - void everySwitchAgreesAcrossItsThreeHomes(MasterSwitch masterSwitch) throws IOException { - String registry = read("docs/registries/env-keys.yaml"); - // Every shipped resource, not application.yml alone: the capability blocks these - // switches bind moved to config/*.yml when the 974-line file was split (BOOT-008). - String applicationYaml = ShippedConfiguration.text(); - - assertThat(registry) - .as( - "%s must have an env registry row; the registry is the operator-facing SSOT", - masterSwitch) - .contains("name: " + masterSwitch.environmentVariable()); - - String row = rowFor(registry, masterSwitch.environmentVariable()); - assertThat(row) - .as( - "%s must default to false: shipping a capability on by default is the state this whole " - + "contract exists to remove", - masterSwitch) - .contains("default: false"); - - assertThat(applicationYaml) - .as( - "%s must be bound by application.yml with a false inline default, or the registry " - + "documents a variable the application never reads", - masterSwitch) - .contains("${" + masterSwitch.environmentVariable() + ":false}"); - } - - @Test - @DisplayName("no demoted selector is documented as an activation switch") - void demotedSelectorsAreNotActivationSwitches() throws IOException { - String registry = read("docs/registries/env-keys.yaml"); - - for (String demoted : - new String[] { - "APP_MESSAGING_BROKER", - "APP_NOTIFICATION_SLACK_WEBHOOK_ENABLED", - "APP_NOTIFICATION_GOOGLE_EMAIL_ENABLED" - }) { - if (!registry.contains("name: " + demoted)) { - continue; - } - assertThat(rowFor(registry, demoted)) - .as( - "%s selects which provider or transport, not whether the capability exists; a blank " - + "value used to be the de-facto switch and that is what the master switches " - + "replaced", - demoted) - .doesNotContain("master switch"); - } - } - - private static String rowFor(String registry, String variable) { - int start = registry.indexOf("name: " + variable); - int next = registry.indexOf("\n - name:", start); - return next < 0 ? registry.substring(start) : registry.substring(start, next); - } - - private static String read(String relativePath) throws IOException { - return Files.readString(repositoryRoot().resolve(relativePath)); - } - - private static Path repositoryRoot() { - Path candidate = Path.of("").toAbsolutePath(); - while (candidate != null - && !Files.isRegularFile(candidate.resolve("src/config/architecture/modules.json"))) { - candidate = candidate.getParent(); - } - if (candidate == null) { - throw new IllegalStateException("could not locate the repository root from the test cwd"); - } - return candidate; - } -} diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/activation/ShippedRuntimeFacadePresenceTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/activation/ShippedRuntimeFacadePresenceTest.java deleted file mode 100644 index 196e343f..00000000 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/activation/ShippedRuntimeFacadePresenceTest.java +++ /dev/null @@ -1,66 +0,0 @@ -package dev.caskeleton.bootstrap.activation; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.catchThrowable; - -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * All master-gated runtime capabilities ship in one artifact, and are off because a switch says so. - * - *

An adapter whose classes are absent also holds no beans, which makes it indistinguishable from - * a correctly gated one in any bean-inventory test — and it is not the same thing at all. An - * operator can turn a gated adapter on by setting one environment variable; they cannot turn on - * code that was never built into the jar. This test is the one that tells the two apart, so that - * "off by default" cannot be delivered by leaving something out of the build. - */ -class ShippedRuntimeFacadePresenceTest { - - @Test - @DisplayName("the JPA runtime facade is on the shipped classpath") - void jpaFacadeIsShipped() { - assertFacadeIsShipped( - "dev.caskeleton.bootstrap.autoconfigure.jpa.JpaPlatformRuntimeAutoConfiguration"); - } - - @Test - @DisplayName("the notification runtime facade is on the shipped classpath") - void notificationFacadeIsShipped() { - assertFacadeIsShipped("dev.caskeleton.adapter.outbound.notification.core.RoutingNotifier"); - } - - @Test - @DisplayName("the Mongo runtime facade is on the shipped classpath") - void mongoFacadeIsShipped() { - assertFacadeIsShipped("dev.caskeleton.adapter.outbound.mongo.MongoRootAutoConfiguration"); - } - - @Test - @DisplayName("the GraphQL runtime facade is on the shipped classpath") - void graphQlFacadeIsShipped() { - assertFacadeIsShipped( - "dev.caskeleton.adapter.inbound.graphql.autoconfigure.GraphQlRootAutoConfiguration"); - } - - @Test - @DisplayName("the messaging platform runtime facade is on the shipped classpath") - void messagingPlatformFacadeIsShipped() { - assertFacadeIsShipped("dev.caskeleton.messaging.autoconfigure.MessagingCoreAutoConfiguration"); - } - - private static void assertFacadeIsShipped(String className) { - Throwable thrown = - catchThrowable( - () -> - Class.forName( - className, false, ShippedRuntimeFacadePresenceTest.class.getClassLoader())); - assertThat(thrown) - .as( - "%s must be on the composition root's runtime classpath; an adapter that is absent " - + "cannot be enabled by an operator setting one environment variable, so absence " - + "is not the same contract as off", - className) - .isNull(); - } -} diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/async/AsyncExecutorSettingsTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/async/AsyncExecutorSettingsTest.java index 360f7c05..2dcc6cd8 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/async/AsyncExecutorSettingsTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/async/AsyncExecutorSettingsTest.java @@ -3,7 +3,7 @@ package dev.caskeleton.bootstrap.async; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import dev.caskeleton.bootstrap.runtime.startup.StartupValidationException; +import dev.caskeleton.adapter.outbound.support.startup.StartupValidationException; import java.util.Map; import org.junit.jupiter.api.Test; import org.springframework.boot.context.properties.bind.Binder; diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/common/BootstrapClockAutoConfigurationTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/common/BootstrapClockAutoConfigurationTest.java index 61218454..15d3c1fa 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/common/BootstrapClockAutoConfigurationTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/common/BootstrapClockAutoConfigurationTest.java @@ -2,7 +2,7 @@ package dev.caskeleton.bootstrap.autoconfigure.common; import static org.assertj.core.api.Assertions.assertThat; -import dev.caskeleton.bootstrap.autoconfigure.idempotency.IdempotencyConfig; +import dev.caskeleton.bootstrap.autoconfigure.idempotency.IdempotencyProviderSelectionConfig; import java.time.Clock; import java.time.Instant; import java.time.ZoneOffset; @@ -40,7 +40,7 @@ class BootstrapClockAutoConfigurationTest { @Test void idempotencyCompositionDoesNotOwnTheApplicationClock() { - assertThat(Arrays.stream(IdempotencyConfig.class.getDeclaredMethods())) + assertThat(Arrays.stream(IdempotencyProviderSelectionConfig.class.getDeclaredMethods())) .noneMatch( method -> method.getReturnType() == Clock.class && method.isAnnotationPresent(Bean.class)); diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencyProviderCompositionTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencyProviderCompositionTest.java index d5669d45..ca678deb 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencyProviderCompositionTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencyProviderCompositionTest.java @@ -2,167 +2,115 @@ package dev.caskeleton.bootstrap.autoconfigure.idempotency; import static org.assertj.core.api.Assertions.assertThat; +import dev.caskeleton.application.idempotency.IdempotencyExecutor; import dev.caskeleton.application.idempotency.IdempotencyStorePort; -import dev.caskeleton.application.idempotency.v2.IdempotencyExecutorV2; -import dev.caskeleton.application.idempotency.v2.IdempotencyStorePortV2; +import dev.caskeleton.application.idempotency.testkit.InMemoryIdempotencyStore; import java.time.Clock; -import java.time.Duration; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.jdbc.core.JdbcOperations; /** - * What each provider selection actually composes, counted. + * What each provider selection composes, counted: one executor over exactly one store, or nothing. * - *

The owner-safe PostgreSQL store had an implementation, a schema stream and a Docker-backed - * integration suite, and no value of the provider property selected it — so the only thing that - * ever built it was a test that constructed it directly. A capability nothing can compose is not a - * capability, and no bean-count assertion existed that would have said so. - * - *

Counting all four selections in one place is what makes that visible: the store's own tests - * pass whether or not a deployment can reach it, and only the composition tells them apart. + *

The PostgreSQL case uses the real persistence-jpa provider configuration, so a selection that + * stops reaching it shows up here. The Redis store needs a live runtime owner, so a stand-in store + * plays it; what is under test is that the composition root builds the executor once, not the + * store. The component scan of the PostgreSQL store package is included in every case, pinning the + * old regression where a stereotype on the store registered it under every selection. */ class IdempotencyProviderCompositionTest { + private static final String POSTGRESQL_STORE_CONFIG = + "dev.caskeleton.adapter.outbound.persistence.autoconfigure.PostgreSqlIdempotencyStoreConfig"; + private final ApplicationContextRunner runner = new ApplicationContextRunner() - .withConfiguration( - org.springframework.boot.autoconfigure.AutoConfigurations.of( - IdempotencyProviderSelectionConfig.class)) - .withBean(Clock.class, Clock::systemUTC); + .withConfiguration(AutoConfigurations.of(IdempotencyProviderSelectionConfig.class)) + .withUserConfiguration(ScannedPersistence.class, postgreSqlStoreConfig()) + .withBean(JdbcOperations.class, () -> org.mockito.Mockito.mock(JdbcOperations.class)) + .withBean(Clock.class, Clock::systemUTC) + // The schema stream talks to a real database; its own integration test covers it. + .withPropertyValues("ca-skeleton.runtime.migration-on-startup=false"); @Test - @DisplayName("disabled composes no idempotency store at all") - void disabledComposesNothing() { + void disabledComposesNoExecutorEvenWithAStorePresent() { runner .withPropertyValues("ca-skeleton.capabilities.idempotency.provider=disabled") + .withBean(IdempotencyStorePort.class, InMemoryIdempotencyStore::new) .run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context.getBeansOfType(IdempotencyStorePortV2.class)).isEmpty(); - assertThat(context.getBeansOfType(IdempotencyExecutorV2.class)).isEmpty(); - }); + context -> + assertThat(context).hasNotFailed().doesNotHaveBean(IdempotencyExecutor.class)); } @Test - @DisplayName("jdbc composes its own V1 pair and no owner-safe store") - void jdbcComposesOnlyItsOwnPair() { - runner - .withPropertyValues("ca-skeleton.capabilities.idempotency.provider=jdbc") - .withBean( - IdempotencyStorePort.class, () -> org.mockito.Mockito.mock(IdempotencyStorePort.class)) - .run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context.getBeansOfType(IdempotencyStorePortV2.class)).isEmpty(); - assertThat(context.getBeansOfType(IdempotencyExecutorV2.class)).isEmpty(); - }); - } - - @Test - @DisplayName( - "redis composes exactly one owner-safe store and its executor, and no PostgreSQL one") - void redisComposesExactlyItsOwnPair() { + void redisComposesOneExecutorOverTheRedisStoreAlone() { runner .withPropertyValues("ca-skeleton.capabilities.idempotency.provider=redis") - .withBean(IdempotencyStorePortV2.class, RedisLikeStore::new) - .withBean(IdempotencyExecutorV2.class, () -> executorOver(new RedisLikeStore())) + .withBean(IdempotencyStorePort.class, InMemoryIdempotencyStore::new) .run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context.getBeansOfType(IdempotencyStorePortV2.class)).hasSize(1); - assertThat(context.getBean(IdempotencyStorePortV2.class)) - .as("the PostgreSQL configuration must stay inert under another selection") - .isInstanceOf(RedisLikeStore.class); - }); + context -> + assertThat(context) + .hasNotFailed() + .hasSingleBean(IdempotencyExecutor.class) + .getBean(IdempotencyStorePort.class) + .isInstanceOf(InMemoryIdempotencyStore.class)); } @Test - @DisplayName("postgresql composes exactly one owner-safe store and its executor") - void postgresqlComposesExactlyOnePair() { + void postgresqlComposesOneExecutorOverThePersistenceJpaStore() { runner .withPropertyValues("ca-skeleton.capabilities.idempotency.provider=postgresql") - .withBean(IdempotencyStorePortV2.class, RedisLikeStore::new) .run( - context -> { - assertThat(context) - .as("the selector is what makes the owner-safe store reachable at all") - .hasNotFailed(); - assertThat(context.getBeansOfType(IdempotencyStorePortV2.class)).hasSize(1); - assertThat(context.getBeansOfType(IdempotencyExecutorV2.class)).hasSize(1); - assertThat(context.getBeansOfType(IdempotencyExecutorV2.class)).hasSize(1); - }); + context -> + assertThat(context) + .hasNotFailed() + .hasSingleBean(IdempotencyExecutor.class) + .getBean(IdempotencyStorePort.class) + .extracting(store -> store.getClass().getSimpleName()) + .isEqualTo("PostgreSqlOwnerSafeIdempotencyStore")); } - private static IdempotencyExecutorV2 executorOver(IdempotencyStorePortV2 store) { - return new IdempotencyExecutorV2( - store, Duration.ofSeconds(30), Duration.ofHours(1), Duration.ofHours(1), "json-v2", 1); + @Test + @DisplayName("a selected provider whose module contributed no store fails startup with the count") + void selectedProviderWithoutAStoreFailsStartup() { + runner + .withPropertyValues("ca-skeleton.capabilities.idempotency.provider=redis") + .run( + context -> + assertThat(context) + .hasFailed() + .getFailure() + .hasStackTraceContaining( + "provider=redis needs exactly one IdempotencyStorePort") + .hasStackTraceContaining("found 0")); } - /** Stands in for the Redis V2 store, whose own composition is covered elsewhere. */ - private static final class RedisLikeStore implements IdempotencyStorePortV2 { + @Test + @DisplayName("a second store beside the selected one fails startup with the count") + void secondStoreBesideTheSelectedOneFailsStartup() { + runner + .withPropertyValues("ca-skeleton.capabilities.idempotency.provider=postgresql") + .withBean("strayStore", IdempotencyStorePort.class, InMemoryIdempotencyStore::new) + .run( + context -> + assertThat(context).hasFailed().getFailure().hasStackTraceContaining("found 2")); + } - @Override - public dev.caskeleton.application.idempotency.v2.IdempotencyClaimAttempt newClaimAttempt( - dev.caskeleton.application.transaction.OperationId operationId) { - throw new UnsupportedOperationException(); - } - - @Override - public dev.caskeleton.application.idempotency.v2.IdempotencyClaimOutcome claim( - dev.caskeleton.application.idempotency.v2.IdempotencyClaimRequest request) { - throw new UnsupportedOperationException(); - } - - @Override - public dev.caskeleton.application.idempotency.v2.IdempotencyMutationResult< - dev.caskeleton.application.idempotency.v2.IdempotencyStartOutcome> - markExecutionStarted( - dev.caskeleton.application.idempotency.v2.IdempotencyOwner owner, - dev.caskeleton.application.transaction.OperationId operationId) { - throw new UnsupportedOperationException(); - } - - @Override - public dev.caskeleton.application.idempotency.v2.IdempotencyMutationResult< - dev.caskeleton.application.idempotency.v2.IdempotencyRenewOutcome> - renew( - dev.caskeleton.application.idempotency.v2.IdempotencyOwner owner, - Duration processingLeaseTtl, - dev.caskeleton.application.transaction.OperationId operationId) { - throw new UnsupportedOperationException(); - } - - @Override - public dev.caskeleton.application.idempotency.v2.IdempotencyCompleteOutcome complete( - dev.caskeleton.application.idempotency.v2.IdempotencyOwner owner, - dev.caskeleton.application.idempotency.StoredResponse response, - Duration replayTtl, - dev.caskeleton.application.transaction.OperationId operationId) { - throw new UnsupportedOperationException(); - } - - @Override - public dev.caskeleton.application.idempotency.v2.IdempotencyFailOutcome markFailed( - dev.caskeleton.application.idempotency.v2.IdempotencyOwner owner, - dev.caskeleton.application.idempotency.v2.IdempotencyFailureDisposition disposition, - Duration retention, - dev.caskeleton.application.transaction.OperationId operationId) { - throw new UnsupportedOperationException(); - } - - @Override - public dev.caskeleton.application.idempotency.v2.IdempotencyReleaseOutcome - releaseBeforeExecution( - dev.caskeleton.application.idempotency.v2.IdempotencyOwner owner, - dev.caskeleton.application.transaction.OperationId operationId) { - throw new UnsupportedOperationException(); - } - - @Override - public dev.caskeleton.application.idempotency.v2.IdempotencyInspection inspect( - dev.caskeleton.application.idempotency.v2.IdempotencyInspectionRequest request) { - throw new UnsupportedOperationException(); + private static Class postgreSqlStoreConfig() { + try { + return Class.forName(POSTGRESQL_STORE_CONFIG); + } catch (ClassNotFoundException missing) { + throw new IllegalStateException(missing); } } + + /** What the composition root once scanned, narrowed to the store package. */ + @Configuration(proxyBeanMethods = false) + @ComponentScan("dev.caskeleton.adapter.outbound.persistence.postgresql.idempotency") + static class ScannedPersistence {} } diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencyProviderScanCollisionTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencyProviderScanCollisionTest.java deleted file mode 100644 index d90396ba..00000000 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencyProviderScanCollisionTest.java +++ /dev/null @@ -1,165 +0,0 @@ -package dev.caskeleton.bootstrap.autoconfigure.idempotency; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.application.idempotency.IdempotencyExecutor; -import dev.caskeleton.application.idempotency.IdempotencyStorePort; -import dev.caskeleton.application.idempotency.v2.IdempotencyStorePortV2; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.runner.ApplicationContextRunner; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.jdbc.core.JdbcOperations; - -/** - * The provider guard, against the beans the component scan actually produces. - * - *

Every other test of this guard hands it the beans it expects. That is precisely the shape of - * test that cannot see the defect it is guarding against, because the question is not "does the - * guard count correctly" but "what is in the context to count". {@code CaSkeletonApplication} scans - * {@code dev.caskeleton.adapter}. Historically the PostgreSQL owner-safe store carried a repository - * stereotype, so it was registered in every deployment regardless of provider choice. The store is - * now stereotype-free and composed only by the JPA leaf under {@code provider=postgresql}; this - * test keeps the original scan-collision regression pinned. - * - *

Both JDBC and Redis selections are asserted so a future stereotype or scan-visible factory - * cannot silently reintroduce an owner-safe V2 store into a provider that did not select it. - */ -class IdempotencyProviderScanCollisionTest { - - private final ApplicationContextRunner runner = - new ApplicationContextRunner() - .withUserConfiguration(ScannedPersistence.class, IdempotencyProviderSelectionConfig.class) - .withBean(JdbcOperations.class, () -> org.mockito.Mockito.mock(JdbcOperations.class)) - .withBean(java.time.Clock.class, java.time.Clock::systemUTC); - - @Test - @DisplayName("the default JDBC provider composes exactly its own V1 pair and no V2 store") - void theJdbcProviderComposesOnlyV1() { - runner - .withPropertyValues("ca-skeleton.capabilities.idempotency.provider=jdbc") - .withBean( - IdempotencyStorePort.class, () -> org.mockito.Mockito.mock(IdempotencyStorePort.class)) - .run( - context -> { - assertThat(context) - .as("the default provider must not acquire an owner-safe V2 store by scan") - .hasNotFailed(); - assertThat(context).hasSingleBean(IdempotencyStorePort.class); - assertThat(context).hasSingleBean(IdempotencyExecutor.class); - assertThat(context.getBeansOfType(IdempotencyStorePortV2.class)).isEmpty(); - }); - } - - @Test - @DisplayName("the Redis provider composes exactly one owner-safe V2 store and its executor") - void theRedisProviderComposesOneV2StoreAndItsExecutor() { - runner - .withPropertyValues("ca-skeleton.capabilities.idempotency.provider=redis") - .withBean(IdempotencyStorePortV2.class, RedisLikeStore::new) - .withBean( - dev.caskeleton.application.idempotency.v2.IdempotencyExecutorV2.class, - () -> - new dev.caskeleton.application.idempotency.v2.IdempotencyExecutorV2( - new RedisLikeStore(), - java.time.Duration.ofSeconds(30), - java.time.Duration.ofHours(1), - java.time.Duration.ofHours(1), - "json-v2", - 1)) - .run( - context -> { - assertThat(context) - .as("a second V2 store from the scan makes the selection ambiguous") - .hasNotFailed(); - assertThat(context.getBeansOfType(IdempotencyStorePortV2.class)).hasSize(1); - }); - } - - @Test - @DisplayName("a V2 store with no executor is refused: nothing could drive it") - void aStoreWithoutAnExecutorIsRefused() { - runner - .withPropertyValues("ca-skeleton.capabilities.idempotency.provider=redis") - .withBean(IdempotencyStorePortV2.class, RedisLikeStore::new) - .run( - context -> { - assertThat(context).hasFailed(); - assertThat(context.getStartupFailure()) - .hasStackTraceContaining("owner-safe V2 executor"); - }); - } - - /** Exactly what the composition root scans, narrowed to the package under test. */ - @Configuration(proxyBeanMethods = false) - @ComponentScan("dev.caskeleton.adapter.outbound.persistence.postgresql.idempotency") - static class ScannedPersistence {} - - /** Stands in for the Redis V2 store, whose own composition is covered elsewhere. */ - private static final class RedisLikeStore implements IdempotencyStorePortV2 { - - @Override - public dev.caskeleton.application.idempotency.v2.IdempotencyClaimAttempt newClaimAttempt( - dev.caskeleton.application.transaction.OperationId operationId) { - throw new UnsupportedOperationException(); - } - - @Override - public dev.caskeleton.application.idempotency.v2.IdempotencyClaimOutcome claim( - dev.caskeleton.application.idempotency.v2.IdempotencyClaimRequest request) { - throw new UnsupportedOperationException(); - } - - @Override - public dev.caskeleton.application.idempotency.v2.IdempotencyMutationResult< - dev.caskeleton.application.idempotency.v2.IdempotencyStartOutcome> - markExecutionStarted( - dev.caskeleton.application.idempotency.v2.IdempotencyOwner owner, - dev.caskeleton.application.transaction.OperationId operationId) { - throw new UnsupportedOperationException(); - } - - @Override - public dev.caskeleton.application.idempotency.v2.IdempotencyMutationResult< - dev.caskeleton.application.idempotency.v2.IdempotencyRenewOutcome> - renew( - dev.caskeleton.application.idempotency.v2.IdempotencyOwner owner, - java.time.Duration processingLeaseTtl, - dev.caskeleton.application.transaction.OperationId operationId) { - throw new UnsupportedOperationException(); - } - - @Override - public dev.caskeleton.application.idempotency.v2.IdempotencyCompleteOutcome complete( - dev.caskeleton.application.idempotency.v2.IdempotencyOwner owner, - dev.caskeleton.application.idempotency.StoredResponse response, - java.time.Duration replayTtl, - dev.caskeleton.application.transaction.OperationId operationId) { - throw new UnsupportedOperationException(); - } - - @Override - public dev.caskeleton.application.idempotency.v2.IdempotencyFailOutcome markFailed( - dev.caskeleton.application.idempotency.v2.IdempotencyOwner owner, - dev.caskeleton.application.idempotency.v2.IdempotencyFailureDisposition disposition, - java.time.Duration retention, - dev.caskeleton.application.transaction.OperationId operationId) { - throw new UnsupportedOperationException(); - } - - @Override - public dev.caskeleton.application.idempotency.v2.IdempotencyReleaseOutcome - releaseBeforeExecution( - dev.caskeleton.application.idempotency.v2.IdempotencyOwner owner, - dev.caskeleton.application.transaction.OperationId operationId) { - throw new UnsupportedOperationException(); - } - - @Override - public dev.caskeleton.application.idempotency.v2.IdempotencyInspection inspect( - dev.caskeleton.application.idempotency.v2.IdempotencyInspectionRequest request) { - throw new UnsupportedOperationException(); - } - } -} diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencyProviderSettingsTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencyProviderSettingsTest.java deleted file mode 100644 index 413c2740..00000000 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencyProviderSettingsTest.java +++ /dev/null @@ -1,15 +0,0 @@ -package dev.caskeleton.bootstrap.autoconfigure.idempotency; - -import static org.assertj.core.api.Assertions.assertThat; - -import org.junit.jupiter.api.Test; - -class IdempotencyProviderSettingsTest { - - @Test - void absentProviderDefaultsToDisabledLikeTheShippedConfiguration() { - IdempotencyProviderSettings settings = new IdempotencyProviderSettings(null); - - assertThat(settings.provider()).isEqualTo(IdempotencyProviderSettings.Provider.DISABLED); - } -} diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencySettingsTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencySettingsTest.java index ab9e5160..e0f99a40 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencySettingsTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencySettingsTest.java @@ -1,45 +1,140 @@ package dev.caskeleton.bootstrap.autoconfigure.idempotency; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; -import dev.caskeleton.bootstrap.runtime.startup.StartupValidationException; +import dev.caskeleton.adapter.outbound.support.startup.StartupValidationException; import java.time.Duration; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; class IdempotencySettingsTest { + private final ApplicationContextRunner runner = + new ApplicationContextRunner().withUserConfiguration(Binding.class); + @Test - void bindsAValidTtlAndReaperInterval() { - IdempotencySettings props = - new IdempotencySettings(Duration.ofHours(24), Duration.ofMinutes(5)); - assertThat(props.ttl()).isEqualTo(Duration.ofHours(24)); - assertThat(props.reaperInterval()).isEqualTo(Duration.ofMinutes(5)); + void absentKeysBindToTheDocumentedDefaults() { + runner.run( + context -> + assertThat(context.getBean(IdempotencySettings.class)) + .usingRecursiveComparison() + .isEqualTo( + new IdempotencySettings( + IdempotencySettings.Provider.DISABLED, + Duration.ofSeconds(30), + Duration.ofHours(24), + Duration.ofHours(24), + "json-v2", + 2, + Duration.ofMinutes(10)))); } @Test - void allowsOverrideUpToThe72hCap() { - assertThat(new IdempotencySettings(Duration.ofDays(3), null).ttl()) - .isEqualTo(Duration.ofDays(3)); + void kebabCaseKeysBindEveryField() { + runner + .withPropertyValues( + "ca-skeleton.capabilities.idempotency.provider=postgresql", + "ca-skeleton.capabilities.idempotency.processing-lease=45s", + "ca-skeleton.capabilities.idempotency.replay-ttl=72h", + "ca-skeleton.capabilities.idempotency.failure-retention=2h", + "ca-skeleton.capabilities.idempotency.response-codec-id=json-v3", + "ca-skeleton.capabilities.idempotency.policy-revision=3", + "ca-skeleton.capabilities.idempotency.reaper-interval=1m") + .run( + context -> + assertThat(context.getBean(IdempotencySettings.class)) + .usingRecursiveComparison() + .isEqualTo( + new IdempotencySettings( + IdempotencySettings.Provider.POSTGRESQL, + Duration.ofSeconds(45), + Duration.ofHours(72), + Duration.ofHours(2), + "json-v3", + 3, + Duration.ofMinutes(1)))); } @Test - void rejectsATtlAbove72h() { - assertThatThrownBy(() -> new IdempotencySettings(Duration.ofHours(73), null)) + void anUnknownProviderFailsBinding() { + runner + .withPropertyValues("ca-skeleton.capabilities.idempotency.provider=jdbc") + .run( + context -> + assertThat(context) + .hasFailed() + .getFailure() + .hasStackTraceContaining("ca-skeleton.capabilities.idempotency.provider")); + } + + @ParameterizedTest + @DisplayName("an out-of-range duration is refused with its key and bound") + @CsvSource({ + "PT0S, PT24H, PT24H, PT10M, processing-lease must be positive", + "PT61M, PT24H, PT24H, PT10M, processing-lease must be at most PT1H", + "PT30S, PT73H, PT24H, PT10M, replay-ttl must be at most PT72H", + "PT30S, -PT1H, PT24H, PT10M, replay-ttl must be positive", + "PT30S, PT24H, P31D, PT10M, failure-retention must be at most PT720H", + "PT30S, PT24H, PT24H, PT0S, reaper-interval must be positive" + }) + void outOfRangeDurationIsRefused( + Duration lease, Duration replay, Duration retention, Duration reaper, String message) { + // when + Throwable thrown = + catchThrowable( + () -> + new IdempotencySettings( + IdempotencySettings.Provider.REDIS, + lease, + replay, + retention, + null, + null, + reaper)); + + // then + assertThat(thrown) .isInstanceOf(StartupValidationException.class) - .hasMessageContaining("72h"); + .hasMessageContaining("ca-skeleton.capabilities.idempotency." + message); + } + + @ParameterizedTest + @CsvSource({"'', response-codec-id must contain 1-64 characters", "' ', response-codec-id"}) + void blankCodecIdIsRefused(String codecId, String message) { + // when + Throwable thrown = + catchThrowable( + () -> + new IdempotencySettings( + IdempotencySettings.Provider.REDIS, null, null, null, codecId, null, null)); + + // then + assertThat(thrown) + .isInstanceOf(StartupValidationException.class) + .hasMessageContaining("ca-skeleton.capabilities.idempotency." + message); } @Test - void rejectsANonPositiveTtl() { - assertThatThrownBy(() -> new IdempotencySettings(Duration.ZERO, null)) - .isInstanceOf(StartupValidationException.class); + void nonPositivePolicyRevisionIsRefused() { + // when + Throwable thrown = + catchThrowable( + () -> + new IdempotencySettings( + IdempotencySettings.Provider.REDIS, null, null, null, null, 0, null)); + + // then + assertThat(thrown) + .isInstanceOf(StartupValidationException.class) + .hasMessageContaining( + "ca-skeleton.capabilities.idempotency.policy-revision must be positive"); } - @Test - void defaultsAbsentValues() { - IdempotencySettings props = new IdempotencySettings(null, null); - assertThat(props.ttl()).isEqualTo(Duration.ofHours(24)); - assertThat(props.reaperInterval()).isEqualTo(Duration.ofMinutes(10)); - } + @EnableConfigurationProperties(IdempotencySettings.class) + static class Binding {} } diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencyShippedAutoConfigurationTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencyShippedAutoConfigurationTest.java deleted file mode 100644 index 5a34ea9f..00000000 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencyShippedAutoConfigurationTest.java +++ /dev/null @@ -1,48 +0,0 @@ -package dev.caskeleton.bootstrap.autoconfigure.idempotency; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.application.idempotency.IdempotencyExecutor; -import dev.caskeleton.application.idempotency.IdempotencyStorePort; -import java.time.Clock; -import org.junit.jupiter.api.Test; -import org.springframework.boot.autoconfigure.AutoConfigurations; -import org.springframework.boot.test.context.runner.ApplicationContextRunner; -import org.springframework.scheduling.config.TaskManagementConfigUtils; - -class IdempotencyShippedAutoConfigurationTest { - - private final ApplicationContextRunner runner = - new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(IdempotencyProviderSelectionConfig.class)); - - @Test - void disabledProviderDoesNotEnableSchedulingOrCreateAnExecutor() { - runner - .withPropertyValues("ca-skeleton.capabilities.idempotency.provider=disabled") - .run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context).doesNotHaveBean(IdempotencyExecutor.class); - assertThat(context) - .doesNotHaveBean( - TaskManagementConfigUtils.SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME); - }); - } - - @Test - void jdbcProviderImportsItsExecutorAndEnablesScheduling() { - runner - .withPropertyValues("ca-skeleton.capabilities.idempotency.provider=jdbc") - .withBean( - IdempotencyStorePort.class, () -> org.mockito.Mockito.mock(IdempotencyStorePort.class)) - .withBean(Clock.class, Clock::systemUTC) - .run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context).hasSingleBean(IdempotencyExecutor.class); - assertThat(context) - .hasBean(TaskManagementConfigUtils.SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME); - }); - } -} diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/jpa/CapabilityEntityScanRegistrationTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/jpa/CapabilityEntityScanRegistrationTest.java index 7e561f9e..8e631b4c 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/jpa/CapabilityEntityScanRegistrationTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/jpa/CapabilityEntityScanRegistrationTest.java @@ -3,30 +3,26 @@ package dev.caskeleton.bootstrap.autoconfigure.jpa; import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.bootstrap.CaSkeletonApplication; -import java.util.regex.Pattern; +import java.util.List; import org.junit.jupiter.api.Test; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.FilterType; +import org.springframework.boot.autoconfigure.SpringBootApplication; /** Application scan must not bypass capability-owned persistence auto-configuration. */ class CapabilityEntityScanRegistrationTest { @Test - void persistencePackageRemainsOutsideTheBroadComponentScan() { - boolean excluded = - java.util.Arrays.stream( - CaSkeletonApplication.class.getAnnotation(ComponentScan.class).excludeFilters()) - .filter(filter -> filter.type() == FilterType.REGEX) - .flatMap(filter -> java.util.Arrays.stream(filter.pattern())) - .anyMatch( - pattern -> - Pattern.compile(pattern) - .matcher("dev.caskeleton.adapter.outbound.persistence.fileserver") - .matches()); + void theComponentScanStopsAtTheBootstrapPackage() { + SpringBootApplication application = + CaSkeletonApplication.class.getAnnotation(SpringBootApplication.class); - assertThat(excluded) + assertThat( + List.of( + List.of(application.scanBasePackages()), + List.of(application.scanBasePackageClasses()), + CaSkeletonApplication.class.getPackageName())) .as( - "persistence must be reached through the leaf auto-configuration, not broad classpath scan") - .isTrue(); + "persistence and every other capability are reached through their own " + + "auto-configuration, never through the composition root's scan") + .containsExactly(List.of(), List.of(), "dev.caskeleton.bootstrap"); } } diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/jpa/DataSourceRequirementTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/jpa/DataSourceRequirementTest.java deleted file mode 100644 index c9923998..00000000 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/jpa/DataSourceRequirementTest.java +++ /dev/null @@ -1,28 +0,0 @@ -package dev.caskeleton.bootstrap.autoconfigure.jpa; - -import static org.assertj.core.api.Assertions.assertThat; - -import org.junit.jupiter.api.Test; -import org.springframework.mock.env.MockEnvironment; - -class DataSourceRequirementTest { - - @Test - void canonicalMultiInstanceRuntimeSwitchRequiresADataSource() { - MockEnvironment environment = - new MockEnvironment().withProperty("ca-skeleton.runtime.multi-instance-enabled", "true"); - - assertThat(DataSourceRequirement.reasons(environment)) - .contains("ca-skeleton.runtime.multi-instance-enabled=true"); - } - - @Test - void postgresqlIdempotencyIsADataSourceConsumer() { - MockEnvironment environment = - new MockEnvironment() - .withProperty("ca-skeleton.capabilities.idempotency.provider", "postgresql"); - - assertThat(DataSourceRequirement.reasons(environment)) - .contains("ca-skeleton.capabilities.idempotency.provider=postgresql"); - } -} diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/jpa/JpaPlatformAddonAssemblyTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/jpa/JpaPlatformAddonAssemblyTest.java deleted file mode 100644 index 191c515a..00000000 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/jpa/JpaPlatformAddonAssemblyTest.java +++ /dev/null @@ -1,69 +0,0 @@ -package dev.caskeleton.bootstrap.autoconfigure.jpa; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.Arrays; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; - -/** - * The JPA add-on layer assembles when JPA is on (JPA-INT-002, found while wiring A1). - * - *

It did not. {@code JpaPlatformRuntimeAutoConfiguration} carried - * {@code @ConditionalOnBean(DataSource.class)} while being a plain {@code @Configuration} imported - * by {@code PersistenceJpaRootAutoConfiguration}. {@code @ConditionalOnBean} is evaluated when the - * class is parsed, and at that point the datasource bean definition is not registered yet — so the - * condition was false in the real application and the class dropped out silently, taking with it - * the Hibernate provider policy, the runtime role verifier, the platform composition, the - * dangerous- configuration guard, the datasource validator, the platform report and the startup - * check. - * - *

Eight beans absent from every deployment, and nothing noticed, because nothing depended on any - * of them. It surfaced only when A1 tried to inject the validator and the Compose lane answered "No - * qualifying bean of type JpaDataSourceProfileValidator". - * - *

The condition is gone rather than reordered. The class is reached only through the JPA root, - * which already carries the master switch, so "is there a datasource" is a question that has - * already been answered yes by the time this is parsed. A bean here that needs one takes it as a - * parameter, and a missing datasource is then a loud failure with the switch on — which is what - * should happen, rather than the whole layer disappearing. - * - *

{@code @ConditionalOnBean} on a configuration that is imported rather than auto-configured is - * the general trap; Spring Boot's own documentation limits the annotation to auto-configuration - * classes for exactly this reason. - */ -class JpaPlatformAddonAssemblyTest { - - @Test - @DisplayName("the add-on layer carries no bean-presence condition it cannot evaluate") - void theAddonLayerCarriesNoUnorderedBeanCondition() { - assertThat(JpaPlatformRuntimeAutoConfiguration.class.getAnnotation(ConditionalOnBean.class)) - .as( - "@ConditionalOnBean is evaluated at parse time on an imported @Configuration, so it " - + "answers about a bean definition that does not exist yet; the whole class then " - + "drops out and nothing reports it") - .isNull(); - } - - @Test - @DisplayName("the layer still declares the beans whose absence went unnoticed") - void theLayerStillDeclaresItsBeans() { - var beanMethods = - Arrays.stream(JpaPlatformRuntimeAutoConfiguration.class.getDeclaredMethods()) - .filter( - method -> - method.isAnnotationPresent(org.springframework.context.annotation.Bean.class)) - .map(java.lang.reflect.Method::getName) - .sorted() - .toList(); - - assertThat(beanMethods) - .as("named so a future removal is a decision rather than a silent regression") - .contains( - "jpaDataSourceProfileValidator", - "jpaDangerousConfigurationGuard", - "jpaPlatformComposition", - "jpaPlatformStartupCheck"); - } -} diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/jpa/LocalJpaVendorParityTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/jpa/LocalJpaVendorParityTest.java index 16a173d0..b63f2240 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/jpa/LocalJpaVendorParityTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/jpa/LocalJpaVendorParityTest.java @@ -107,12 +107,26 @@ class LocalJpaVendorParityTest { .contains("'APP_DATASOURCE_DDL_AUTO', 'create-drop'"); } - /** The properties a profile resolves, with the base file underneath it as Spring layers them. */ + /** + * The properties a profile resolves with JPA selected: the persistence-jpa module's shipped + * defaults at the bottom, the base file above them, and the profile on top, as Spring layers + * them. + */ private static MockEnvironment profile(String resource) throws IOException { MockEnvironment environment = new MockEnvironment(); for (PropertySource source : load("application.yml")) { environment.getPropertySources().addLast(source); } + Path moduleDefaults = + repositoryRoot() + .resolve( + "src/adapter/outbound/persistence-jpa/src/main/resources/config/module-defaults/" + + "persistence-jpa.yml"); + for (PropertySource source : + new YamlPropertySourceLoader() + .load("persistence-jpa module defaults", new FileSystemResource(moduleDefaults))) { + environment.getPropertySources().addLast(source); + } for (PropertySource source : load(resource)) { environment.getPropertySources().addFirst(source); } diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/jpa/PersistenceJpaRootAutoConfigurationOrderingTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/jpa/PersistenceJpaRootAutoConfigurationOrderingTest.java deleted file mode 100644 index 6bfd47ad..00000000 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/jpa/PersistenceJpaRootAutoConfigurationOrderingTest.java +++ /dev/null @@ -1,21 +0,0 @@ -package dev.caskeleton.bootstrap.autoconfigure.jpa; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.Arrays; -import org.junit.jupiter.api.Test; -import org.springframework.boot.autoconfigure.AutoConfiguration; - -class PersistenceJpaRootAutoConfigurationOrderingTest { - - @Test - void bootstrapDoesNotOrderAgainstLeafInternalAutoConfigurationClasses() { - AutoConfiguration root = - PersistenceJpaRootAutoConfiguration.class.getAnnotation(AutoConfiguration.class); - - assertThat(Arrays.asList(root.after())).isEmpty(); - assertThat(root.afterName()) - .noneMatch( - name -> name.startsWith("dev.caskeleton.adapter.outbound.persistence.autoconfigure.")); - } -} diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/lock/DistributedLockConfigTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/lock/DistributedLockConfigTest.java deleted file mode 100644 index 5c49f3e4..00000000 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/lock/DistributedLockConfigTest.java +++ /dev/null @@ -1,46 +0,0 @@ -package dev.caskeleton.bootstrap.autoconfigure.lock; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.application.lock.DistributedLockPort; -import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.runner.ApplicationContextRunner; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -class DistributedLockConfigTest { - - private final ApplicationContextRunner contextRunner = - new ApplicationContextRunner() - .withUserConfiguration(DistributedLockConfig.class, JdbcProviderFixture.class); - - @Test - void multiInstanceWrapsTheJdbcProviderAsThePrimaryDistributedProvider() { - contextRunner - .withPropertyValues("ca-skeleton.runtime.multi-instance-enabled=true") - .run( - context -> { - assertThat(context).hasBean("jdbcDistributedLock"); - assertThat(context).hasBean("distributedLockProvider"); - assertThat(context.getBean("distributedLockProvider")) - .isInstanceOf(MeteredDistributedLockPort.class); - assertThat(context.getBean(DistributedLockPort.class)) - .isSameAs(context.getBean("distributedLockProvider")); - }); - } - - @Test - void singleInstanceDoesNotCreateTheBootstrapDistributedProvider() { - contextRunner - .withPropertyValues("ca-skeleton.runtime.multi-instance-enabled=false") - .run(context -> assertThat(context).doesNotHaveBean("distributedLockProvider")); - } - - @Configuration(proxyBeanMethods = false) - static class JdbcProviderFixture { - @Bean("jdbcDistributedLock") - DistributedLockPort jdbcDistributedLock() { - return (key, waitTime, leaseTtl) -> () -> {}; - } - } -} diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/notification/NotificationAutoConfigurationTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/notification/NotificationAutoConfigurationTest.java deleted file mode 100644 index 9097c2f3..00000000 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/notification/NotificationAutoConfigurationTest.java +++ /dev/null @@ -1,36 +0,0 @@ -package dev.caskeleton.bootstrap.autoconfigure.notification; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.adapter.inbound.web.notification.platform.callback.NotificationCallbackMvcController; -import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.runner.ReactiveWebApplicationContextRunner; -import org.springframework.boot.test.context.runner.WebApplicationContextRunner; -import org.springframework.context.annotation.Configuration; - -/** Cross-layer callback activation evidence kept at the application composition boundary. */ -class NotificationAutoConfigurationTest { - - @Test - void theServletCallbackControllerIsAbsentWhileCallbacksAreDisabled() { - new WebApplicationContextRunner() - .withUserConfiguration(MvcCallbackConfiguration.class) - .run( - context -> - assertThat(context).doesNotHaveBean(NotificationCallbackMvcController.class)); - } - - @Test - void theServletControllerNeverRegistersInAReactiveApplication() { - new ReactiveWebApplicationContextRunner() - .withUserConfiguration(MvcCallbackConfiguration.class) - .withPropertyValues("ca-skeleton.notification.platform.callbacks.enabled=true") - .run( - context -> - assertThat(context).doesNotHaveBean(NotificationCallbackMvcController.class)); - } - - @Configuration(proxyBeanMethods = false) - @org.springframework.context.annotation.Import(NotificationCallbackMvcController.class) - static class MvcCallbackConfiguration {} -} diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxConfigTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxConfigTest.java index c6637f8d..374762a5 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxConfigTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxConfigTest.java @@ -1,9 +1,19 @@ package dev.caskeleton.bootstrap.autoconfigure.outbox; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import dev.caskeleton.application.outbox.OutboxMessagePublishPort; +import dev.caskeleton.application.outbox.OutboxRelayFailureReportPort; +import dev.caskeleton.application.outbox.OutboxStorePort; +import dev.caskeleton.application.transaction.TransactionPort; +import java.lang.reflect.Proxy; +import java.time.Clock; import java.util.random.RandomGenerator; import org.junit.jupiter.api.Test; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.scheduling.config.TaskManagementConfigUtils; class OutboxConfigTest { @@ -13,4 +23,67 @@ class OutboxConfigTest { assertThat(random.getClass().getModule().getName()).isEqualTo("java.base"); } + + @Test + void outboxCapabilityEnablesSchedulingWithIdempotencyDisabled() { + // given + ApplicationContextRunner runner = + new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(OutboxConfig.class)) + .withBean(OutboxStorePort.class, OutboxConfigTest::unusedStore) + .withPropertyValues( + "ca-skeleton.outbox.enabled=true", + "ca-skeleton.outbox.relay-enabled=false", + "ca-skeleton.capabilities.idempotency.provider=disabled"); + + // when & then + runner.run( + context -> + assertThat(context) + .hasBean(TaskManagementConfigUtils.SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME)); + } + + @Test + void theRelayRunsOnlyWhenSomethingCanPublishWhatItClaims() { + ApplicationContextRunner relayOn = + new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(OutboxConfig.class)) + .withBean(OutboxStorePort.class, OutboxConfigTest::unusedStore) + .withBean(OutboxRelayFailureReportPort.class, () -> report -> {}) + .withBean(TransactionPort.class, () -> mock(TransactionPort.class)) + .withBean(Clock.class, Clock::systemUTC) + .withPropertyValues( + "ca-skeleton.outbox.enabled=true", "ca-skeleton.outbox.relay-enabled=true"); + + // No publish port: PENDING rows stay PENDING rather than being failed to DEAD. + relayOn.run(context -> assertThat(context).doesNotHaveBean(OutboxRelayScheduler.class)); + relayOn + .withBean(OutboxMessagePublishPort.class, () -> mock(OutboxMessagePublishPort.class)) + .run(context -> assertThat(context).hasSingleBean(OutboxRelayScheduler.class)); + } + + @Test + void withoutTheRelationalStoreTheOutboxAssemblesNothing() { + new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(OutboxConfig.class)) + .withPropertyValues("ca-skeleton.outbox.enabled=true") + .run(context -> assertThat(context).doesNotHaveBean(OutboxMetrics.class)); + } + + private static OutboxStorePort unusedStore() { + return (OutboxStorePort) + Proxy.newProxyInstance( + OutboxStorePort.class.getClassLoader(), + new Class[] {OutboxStorePort.class}, + (proxy, method, arguments) -> { + if (method.getDeclaringClass() == Object.class) { + return switch (method.getName()) { + case "equals" -> proxy == arguments[0]; + case "hashCode" -> System.identityHashCode(proxy); + default -> "unusedOutboxStore"; + }; + } + throw new AssertionError("store is not used while wiring: " + method.getName()); + }); + } } diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxRelayBrokerRequirementValidatorTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxRelayBrokerRequirementValidatorTest.java deleted file mode 100644 index 20740eec..00000000 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxRelayBrokerRequirementValidatorTest.java +++ /dev/null @@ -1,79 +0,0 @@ -package dev.caskeleton.bootstrap.autoconfigure.outbox; - -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.springframework.mock.env.MockEnvironment; - -/** - * The configuration that quietly destroys an outbox. - * - *

{@code relay-enabled} defaults to true and {@code app.messaging.broker} defaults to blank, so - * the shipped configuration starts a relay wired to a publisher that throws on every call. The - * relay reads that throw as a publish failure: it claims PENDING rows, marks them IN_FLIGHT, fails - * them with backoff, and exhausts them to DEAD. An environment that is deliberately messaging-off - * does not park its outbox under that configuration — it consumes it. - */ -class OutboxRelayBrokerRequirementValidatorTest { - - @Test - @DisplayName("an enabled relay with no broker fails startup") - void anEnabledRelayWithNoBrokerFailsStartup() { - MockEnvironment environment = new MockEnvironment(); - environment.setProperty("ca-skeleton.outbox.relay-enabled", "true"); - environment.setProperty("app.messaging.broker", ""); - - assertThatThrownBy(() -> new OutboxRelayBrokerRequirementValidator(environment).validate()) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("ca-skeleton.outbox.relay-enabled") - .hasMessageContaining("app.messaging.broker") - .hasMessageContaining("DEAD"); - } - - @Test - @DisplayName("the default, with both keys absent, is the failing combination") - void theDefaultWithBothKeysAbsentIsTheFailingCombination() { - // relay-enabled uses matchIfMissing = true on its bean condition, so absent means enabled. - assertThatThrownBy( - () -> new OutboxRelayBrokerRequirementValidator(new MockEnvironment()).validate()) - .isInstanceOf(IllegalStateException.class); - } - - @Test - @DisplayName("a relay with a broker starts") - void aRelayWithABrokerStarts() { - MockEnvironment environment = new MockEnvironment(); - environment.setProperty("ca-skeleton.outbox.relay-enabled", "true"); - environment.setProperty("app.messaging.broker", "kafka"); - - assertThatCode(() -> new OutboxRelayBrokerRequirementValidator(environment).validate()) - .doesNotThrowAnyException(); - } - - @Test - @DisplayName("canonical transport does not waive the legacy broker during the mixed-row window") - void canonicalTransportStillRequiresLegacyBrokerDuringCompatibilityWindow() { - MockEnvironment environment = new MockEnvironment(); - environment.setProperty("ca-skeleton.outbox.relay-enabled", "true"); - environment.setProperty("ca-skeleton.outbox.canonical-transport-enabled", "true"); - environment.setProperty("app.messaging.broker", ""); - - assertThatThrownBy(() -> new OutboxRelayBrokerRequirementValidator(environment).validate()) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("app.messaging.broker"); - } - - @Test - @DisplayName("a disabled relay with no broker starts, and its PENDING rows are preserved") - void aDisabledRelayWithNoBrokerStarts() { - MockEnvironment environment = new MockEnvironment(); - environment.setProperty("ca-skeleton.outbox.relay-enabled", "false"); - environment.setProperty("app.messaging.broker", ""); - - assertThatCode(() -> new OutboxRelayBrokerRequirementValidator(environment).validate()) - .as("the coherent messaging-off configuration: nothing claims the rows") - .doesNotThrowAnyException(); - } -} diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxRelaySchedulerLoggingTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxRelaySchedulerLoggingTest.java new file mode 100644 index 00000000..fa682a0e --- /dev/null +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxRelaySchedulerLoggingTest.java @@ -0,0 +1,76 @@ +package dev.caskeleton.bootstrap.autoconfigure.outbox; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.LoggerContext; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; +import dev.caskeleton.application.outbox.PublishPendingOutboxEventsCommand; +import dev.caskeleton.application.outbox.PublishPendingOutboxEventsUseCase; +import java.time.Clock; +import java.util.Arrays; +import java.util.stream.Collectors; +import org.junit.jupiter.api.Test; +import org.slf4j.LoggerFactory; + +/** The relay's failure log carries bounded structured fields and no invented error code. */ +class OutboxRelaySchedulerLoggingTest { + + @Test + void outboxRelayUnexpectedFailureCarriesNextTickDispositionWithoutInventedErrorCode() { + PublishPendingOutboxEventsUseCase relay = mock(PublishPendingOutboxEventsUseCase.class); + OutboxMetrics metrics = mock(OutboxMetrics.class); + when(relay.handle(PublishPendingOutboxEventsCommand.INSTANCE)) + .thenThrow(new IllegalStateException("unexpected")); + + try (CapturedLogger captured = capture(OutboxRelayScheduler.class)) { + new OutboxRelayScheduler(relay, metrics, Clock.systemUTC()).relay(); + + ILoggingEvent event = captured.singleEvent(); + assertThat(event.getLevel()).isEqualTo(Level.ERROR); + String arguments = renderedArguments(event); + assertThat(arguments) + .contains("capability=outbox") + .contains("operation=relay") + .contains("retry.disposition=next-tick") + .doesNotContain("error.code="); + assertThat(event.getThrowableProxy()).isNotNull(); + } + } + + private static CapturedLogger capture(Class owner) { + Logger logger = (Logger) LoggerFactory.getLogger(owner); + ListAppender appender = new ListAppender<>(); + appender.setContext((LoggerContext) LoggerFactory.getILoggerFactory()); + appender.start(); + logger.addAppender(appender); + return new CapturedLogger(logger, appender); + } + + private static String renderedArguments(ILoggingEvent event) { + Object[] arguments = event.getArgumentArray(); + if (arguments == null) { + return ""; + } + return Arrays.stream(arguments).map(String::valueOf).collect(Collectors.joining(" | ")); + } + + private record CapturedLogger(Logger logger, ListAppender appender) + implements AutoCloseable { + + ILoggingEvent singleEvent() { + assertThat(appender.list).hasSize(1); + return appender.list.get(0); + } + + @Override + public void close() { + logger.detachAppender(appender); + appender.stop(); + } + } +} diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxSettingsTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxSettingsTest.java index 24f1c649..5a008dba 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxSettingsTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxSettingsTest.java @@ -3,7 +3,7 @@ package dev.caskeleton.bootstrap.autoconfigure.outbox; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import dev.caskeleton.bootstrap.runtime.startup.StartupValidationException; +import dev.caskeleton.adapter.outbound.support.startup.StartupValidationException; import java.time.Duration; import org.junit.jupiter.api.Test; diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/redis/RedisActivationValidatorTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/redis/RedisActivationValidatorTest.java deleted file mode 100644 index 29e5ae23..00000000 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/redis/RedisActivationValidatorTest.java +++ /dev/null @@ -1,158 +0,0 @@ -package dev.caskeleton.bootstrap.autoconfigure.redis; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.bootstrap.runtime.startup.RequiredAdapterDisabledException; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.runner.ApplicationContextRunner; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.ConfigurableEnvironment; - -/** - * Selecting Redis for a role while Redis is globally off is a contradiction, not a default. - * - *

Without this guard the deployment reaches the composition root and fails on whichever bean - * happens to be missing first — a message about an absent {@code IdempotencyStorePortV2} that says - * nothing about the switch that caused it. The operator's actual mistake is one line of - * configuration, so that is what the failure has to name. - */ -class RedisActivationValidatorTest { - - private final ApplicationContextRunner runner = - new ApplicationContextRunner().withUserConfiguration(ValidatorConfig.class); - - @Test - @DisplayName("Redis off and no role selected starts cleanly") - void redisOffWithNoRoleSelectedStartsCleanly() { - runner.run(context -> assertThat(context).hasNotFailed()); - } - - @Test - @DisplayName("Redis off with the cache role bound to redis fails with both names") - void cacheRoleWithoutTheGlobalSwitchFails() { - runner - .withPropertyValues("ca-skeleton.capabilities.cache.bindings.default=redis") - .run( - context -> { - assertThat(context).hasFailed(); - assertThat(context.getStartupFailure()) - .isInstanceOf(RequiredAdapterDisabledException.class) - .hasStackTraceContaining("APP_REDIS_ENABLED") - .hasStackTraceContaining("ca-skeleton.capabilities.cache.bindings.default"); - }); - } - - @Test - @DisplayName("Redis off with the rate-limit provider set to redis fails") - void rateLimitProviderWithoutTheGlobalSwitchFails() { - runner - .withPropertyValues("ca-skeleton.capabilities.rate-limit.provider=redis") - .run( - context -> { - assertThat(context).hasFailed(); - assertThat(context.getStartupFailure()) - .isInstanceOf(RequiredAdapterDisabledException.class) - .hasStackTraceContaining("ca-skeleton.capabilities.rate-limit.provider"); - }); - } - - @Test - @DisplayName("Redis off with the idempotency provider set to redis fails") - void idempotencyProviderWithoutTheGlobalSwitchFails() { - runner - .withPropertyValues("ca-skeleton.capabilities.idempotency.provider=redis") - .run( - context -> { - assertThat(context).hasFailed(); - assertThat(context.getStartupFailure()) - .isInstanceOf(RequiredAdapterDisabledException.class) - .hasStackTraceContaining("ca-skeleton.capabilities.idempotency.provider"); - }); - } - - @Test - @DisplayName("Redis off with the lease provider set to redis fails") - void leaseProviderWithoutTheGlobalSwitchFails() { - runner - .withPropertyValues("ca-skeleton.capabilities.lease.provider=redis") - .run( - context -> { - assertThat(context).hasFailed(); - assertThat(context.getStartupFailure()) - .isInstanceOf(RequiredAdapterDisabledException.class) - .hasStackTraceContaining("ca-skeleton.capabilities.lease.provider"); - }); - } - - @Test - @DisplayName("Redis off with redis-session authentication fails") - void redisSessionWithoutTheGlobalSwitchFails() { - runner - .withPropertyValues("ca-skeleton.security.auth-mode=redis-session") - .run( - context -> { - assertThat(context).hasFailed(); - assertThat(context.getStartupFailure()) - .isInstanceOf(RequiredAdapterDisabledException.class) - .hasStackTraceContaining("ca-skeleton.security.auth-mode"); - }); - } - - @Test - @DisplayName("every contradicting role is reported at once, not one per restart") - void allContradictingRolesAreReportedTogether() { - runner - .withPropertyValues( - "ca-skeleton.capabilities.cache.bindings.default=redis", - "ca-skeleton.capabilities.lease.provider=redis") - .run( - context -> { - assertThat(context).hasFailed(); - assertThat(context.getStartupFailure()) - .hasStackTraceContaining("ca-skeleton.capabilities.cache.bindings.default") - .hasStackTraceContaining("ca-skeleton.capabilities.lease.provider"); - }); - } - - @Test - @DisplayName("the same roles start cleanly once the global switch is on") - void rolesAreAllowedOnceRedisIsEnabled() { - runner - .withPropertyValues( - "app.redis.enabled=true", - "ca-skeleton.capabilities.cache.bindings.default=redis", - "ca-skeleton.capabilities.rate-limit.provider=redis", - "ca-skeleton.capabilities.idempotency.provider=redis", - "ca-skeleton.capabilities.lease.provider=redis", - "ca-skeleton.security.auth-mode=redis-session") - .run(context -> assertThat(context).hasNotFailed()); - } - - @Test - @DisplayName("Redis idempotency refuses a key-version rotation until dual-read exists") - void idempotencyKeyVersionRotationFailsClosed() { - runner - .withPropertyValues( - "app.redis.enabled=true", - "ca-skeleton.capabilities.idempotency.provider=redis", - "ca-skeleton.capabilities.idempotency.key-version=2") - .run( - context -> { - assertThat(context).hasFailed(); - assertThat(context.getStartupFailure()) - .isInstanceOf(RequiredAdapterDisabledException.class) - .hasStackTraceContaining("ca-skeleton.capabilities.idempotency.key-version=2") - .hasStackTraceContaining("unsupported without dual-read"); - }); - } - - @Configuration - static class ValidatorConfig { - @Bean - RedisActivationValidator redisActivationValidator(ConfigurableEnvironment environment) { - return new RedisActivationValidator(environment); - } - } -} diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/tracing/TracingActivationContextTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/tracing/TracingActivationContextTest.java index f07070ba..36affa62 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/tracing/TracingActivationContextTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/tracing/TracingActivationContextTest.java @@ -2,6 +2,7 @@ package dev.caskeleton.bootstrap.autoconfigure.tracing; import static org.assertj.core.api.Assertions.assertThat; +import dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebAdapterAutoConfiguration; import dev.caskeleton.shared.tracing.SpanErrorRecorder; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.tracing.Tracer; @@ -32,6 +33,9 @@ import org.springframework.context.annotation.Import; // placeholders (resolved only when src/.env is on the working dir at bootRun time). // Same pattern as ActuatorSecurityHttpTest. "spring.config.location=optional:classpath:tracing-activation-test-no-config.yml", + // The test classpath carries persistence-jpa, which is on while present; this slice excludes + // the data layer, so it switches the module off too. + "ca-skeleton.persistence-jpa.enabled=false", // blank exporter endpoint = export off (무해) "ca-skeleton.tracing.enabled=true", "ca-skeleton.tracing.sample-rate=", @@ -89,7 +93,9 @@ class TracingActivationContextTest { DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class, DataJpaRepositoriesAutoConfiguration.class, - FlywayAutoConfiguration.class + FlywayAutoConfiguration.class, + // The web adapter's own root (security, filters, settings) is not what this slice is about. + WebAdapterAutoConfiguration.class }) @Import(TracingConfig.class) static class MinimalTracingApp {} diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/tracing/TracingSettingsTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/tracing/TracingSettingsTest.java index 77b89de5..48d343ea 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/tracing/TracingSettingsTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/tracing/TracingSettingsTest.java @@ -4,7 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatNoException; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import dev.caskeleton.bootstrap.runtime.startup.StartupValidationException; +import dev.caskeleton.adapter.outbound.support.startup.StartupValidationException; import org.junit.jupiter.api.Test; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.test.context.runner.ApplicationContextRunner; diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/activation/PortResolutionContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/composition/PortResolutionContractTest.java similarity index 99% rename from src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/activation/PortResolutionContractTest.java rename to src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/composition/PortResolutionContractTest.java index 9e49f856..9e4e1ee8 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/activation/PortResolutionContractTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/composition/PortResolutionContractTest.java @@ -1,4 +1,4 @@ -package dev.caskeleton.bootstrap.activation; +package dev.caskeleton.bootstrap.composition; import static org.assertj.core.api.Assertions.assertThat; diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/activation/StartupWarningRecorder.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/composition/StartupWarningRecorder.java similarity index 98% rename from src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/activation/StartupWarningRecorder.java rename to src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/composition/StartupWarningRecorder.java index d6d2fbaa..3ab62719 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/activation/StartupWarningRecorder.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/composition/StartupWarningRecorder.java @@ -1,4 +1,4 @@ -package dev.caskeleton.bootstrap.activation; +package dev.caskeleton.bootstrap.composition; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Logger; diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/activation/StartupWarningRecorderTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/composition/StartupWarningRecorderTest.java similarity index 96% rename from src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/activation/StartupWarningRecorderTest.java rename to src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/composition/StartupWarningRecorderTest.java index b1711977..146b6e2b 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/activation/StartupWarningRecorderTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/composition/StartupWarningRecorderTest.java @@ -1,4 +1,4 @@ -package dev.caskeleton.bootstrap.activation; +package dev.caskeleton.bootstrap.composition; import static org.assertj.core.api.Assertions.assertThat; diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ActuatorSecurityHttpTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ActuatorSecurityHttpTest.java index 7c27ba7b..576ba3ce 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ActuatorSecurityHttpTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ActuatorSecurityHttpTest.java @@ -6,6 +6,7 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebAdapterAutoConfiguration; import dev.caskeleton.bootstrap.management.security.ManagementSecurityConfig; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -45,6 +46,9 @@ import org.springframework.test.web.servlet.MockMvc; // ${APP_*}/${SPRING_PROFILES_ACTIVE} placeholders resolved only at deploy time). // All config this slice needs is supplied inline below. "spring.config.location=optional:classpath:actuator-security-slice-no-config.yml", + // The test classpath carries persistence-jpa, which is on while present; this slice excludes + // the data layer, so it switches the module off too. + "ca-skeleton.persistence-jpa.enabled=false", "management.endpoints.web.exposure.include=health,prometheus,info,loggers", "management.endpoints.web.exposure.exclude=env,configprops,heapdump,threaddump,shutdown", "management.endpoint.health.show-details=when-authorized", @@ -123,7 +127,9 @@ class ActuatorSecurityHttpTest { DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class, DataJpaRepositoriesAutoConfiguration.class, - FlywayAutoConfiguration.class + FlywayAutoConfiguration.class, + // The web adapter's own root (security, filters, settings) is not what this slice is about. + WebAdapterAutoConfiguration.class }) @Import(ManagementSecurityConfig.class) static class MinimalActuatorApp {} diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/AutoConfigurationReachabilityParityTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/AutoConfigurationReachabilityParityTest.java deleted file mode 100644 index 2f44f2ed..00000000 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/AutoConfigurationReachabilityParityTest.java +++ /dev/null @@ -1,193 +0,0 @@ -package dev.caskeleton.bootstrap.contract; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.adapter.inbound.graphql.autoconfigure.GraphQlOffAutoConfigurationImportFilter; -import dev.caskeleton.adapter.outbound.mongo.MongoOptInAutoConfigurationImportFilter; -import dev.caskeleton.bootstrap.CaSkeletonApplication; -import dev.caskeleton.bootstrap.autoconfigure.jpa.JpaOffAutoConfigurationImportFilter; -import java.lang.reflect.Field; -import java.lang.reflect.Modifier; -import java.util.Arrays; -import java.util.LinkedHashSet; -import java.util.Set; -import java.util.function.Predicate; -import java.util.regex.Pattern; -import java.util.stream.Collectors; -import org.junit.jupiter.api.Test; -import org.springframework.boot.autoconfigure.AutoConfiguration; -import org.springframework.boot.context.annotation.ImportCandidates; -import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.FilterType; -import org.springframework.context.annotation.Import; -import org.springframework.core.annotation.AnnotatedElementUtils; -import org.springframework.core.type.filter.AnnotationTypeFilter; -import org.springframework.stereotype.Component; - -/** - * Generic deployment-reachability parity for project auto-configuration. - * - *

A configuration can be perfectly green when supplied directly to {@code - * ApplicationContextRunner} and still be absent from every shipped application. These checks bind - * source-level ownership to Boot discovery and to the composition root's structural scan exclusion. - */ -class AutoConfigurationReachabilityParityTest { - - private static final String GRAPHQL_PREFIX = "org.springframework.boot.graphql.autoconfigure."; - private static final String MONGO_PREFIX = "org.springframework.boot.mongodb.autoconfigure."; - private static final String DATA_MONGO_PREFIX = - "org.springframework.boot.data.mongodb.autoconfigure."; - - @Test - void everyProjectAutoConfigurationOnTheShippedClasspathIsABootImportCandidate() { - Set annotated = projectAutoConfigurations(); - Set candidates = bootCandidates(); - - requireRegistered(annotated, candidates); - - assertThat(annotated).isNotEmpty(); - } - - @Test - void componentScannableChildrenImportedByProjectRootsStayBehindTheStructuralExclusion() { - Set importedChildren = componentScannableImportedChildren(); - Predicate excluded = compositionRootScanExclusion(); - - requireExcluded(importedChildren, excluded); - - assertThat(importedChildren).isNotEmpty(); - } - - @Test - void offImportFiltersReferenceCurrentBootCandidates() { - Set candidates = bootCandidates(); - - requireTargetsExist(targets(JpaOffAutoConfigurationImportFilter.class), candidates); - assertThat(targets(GraphQlOffAutoConfigurationImportFilter.class)) - .isEqualTo(candidatesWithPrefix(candidates, GRAPHQL_PREFIX)); - assertThat(targets(MongoOptInAutoConfigurationImportFilter.class)) - .isEqualTo( - candidates.stream() - .filter(name -> name.startsWith(MONGO_PREFIX) || name.startsWith(DATA_MONGO_PREFIX)) - .collect(Collectors.toCollection(LinkedHashSet::new))); - } - - @Test - void parityAssertionsFailClosedForMissingImportScannedChildAndStaleFilterTarget() { - assertThatThrownBy(() -> requireRegistered(Set.of("example.MissingRoot"), Set.of())) - .isInstanceOf(AssertionError.class) - .hasMessageContaining("MissingRoot"); - assertThatThrownBy(() -> requireExcluded(Set.of("example.ScannedChild"), name -> false)) - .isInstanceOf(AssertionError.class) - .hasMessageContaining("ScannedChild"); - assertThatThrownBy(() -> requireTargetsExist(Set.of("example.StaleBootTarget"), Set.of())) - .isInstanceOf(AssertionError.class) - .hasMessageContaining("StaleBootTarget"); - } - - private static Set projectAutoConfigurations() { - ClassPathScanningCandidateComponentProvider scanner = - new ClassPathScanningCandidateComponentProvider(false); - scanner.addIncludeFilter(new AnnotationTypeFilter(AutoConfiguration.class)); - return scanner.findCandidateComponents("dev.caskeleton").stream() - .map(definition -> definition.getBeanClassName()) - .collect(Collectors.toCollection(LinkedHashSet::new)); - } - - private static Set bootCandidates() { - return new LinkedHashSet<>( - ImportCandidates.load( - AutoConfiguration.class, - AutoConfigurationReachabilityParityTest.class.getClassLoader()) - .getCandidates()); - } - - private static Set componentScannableImportedChildren() { - Set children = new LinkedHashSet<>(); - for (String rootName : bootCandidates()) { - if (!rootName.startsWith("dev.caskeleton.")) { - continue; - } - Class root = load(rootName); - Import directImport = root.getAnnotation(Import.class); - if (directImport == null) { - continue; - } - for (Class imported : directImport.value()) { - if (AnnotatedElementUtils.hasAnnotation(imported, Component.class)) { - children.add(imported.getName()); - } - } - } - return children; - } - - private static Predicate compositionRootScanExclusion() { - ComponentScan scan = CaSkeletonApplication.class.getAnnotation(ComponentScan.class); - Set exclusions = - Arrays.stream(scan.excludeFilters()) - .filter(filter -> filter.type() == FilterType.REGEX) - .flatMap(filter -> Arrays.stream(filter.pattern())) - .map(Pattern::compile) - .collect(Collectors.toCollection(LinkedHashSet::new)); - return className -> - exclusions.stream().anyMatch(pattern -> pattern.matcher(className).matches()); - } - - private static Set candidatesWithPrefix(Set candidates, String prefix) { - return candidates.stream() - .filter(name -> name.startsWith(prefix)) - .collect(Collectors.toCollection(LinkedHashSet::new)); - } - - @SuppressWarnings("unchecked") - private static Set targets(Class filterType) { - for (Field field : filterType.getDeclaredFields()) { - if (Modifier.isStatic(field.getModifiers()) && Set.class.equals(field.getType())) { - try { - field.setAccessible(true); - return new LinkedHashSet<>((Set) field.get(null)); - } catch (ReflectiveOperationException exception) { - throw new LinkageError("cannot read target set from " + filterType.getName(), exception); - } - } - } - throw new AssertionError("no static target Set found in " + filterType.getName()); - } - - private static Class load(String className) { - try { - return Class.forName(className); - } catch (ClassNotFoundException exception) { - throw new AssertionError("Boot candidate is not loadable: " + className, exception); - } - } - - private static void requireRegistered(Set roots, Set candidates) { - Set missing = new LinkedHashSet<>(roots); - missing.removeAll(candidates); - if (!missing.isEmpty()) { - throw new AssertionError("AutoConfiguration.imports is missing project roots: " + missing); - } - } - - private static void requireExcluded(Set children, Predicate excluded) { - Set leaking = - children.stream() - .filter(excluded.negate()) - .collect(Collectors.toCollection(LinkedHashSet::new)); - if (!leaking.isEmpty()) { - throw new AssertionError("imported children can leak through component scan: " + leaking); - } - } - - private static void requireTargetsExist(Set targets, Set candidates) { - Set stale = new LinkedHashSet<>(targets); - stale.removeAll(candidates); - if (!stale.isEmpty()) { - throw new AssertionError("off-import filter contains stale Boot targets: " + stale); - } - } -} diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/BootstrapCapabilityAutoConfigurationReachabilityTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/BootstrapCapabilityAutoConfigurationReachabilityTest.java index 10297a20..23f8f510 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/BootstrapCapabilityAutoConfigurationReachabilityTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/BootstrapCapabilityAutoConfigurationReachabilityTest.java @@ -11,22 +11,21 @@ import org.springframework.boot.context.annotation.ImportCandidates; * Deployment reachability contract for bootstrap-owned capability roots. * *

Supplying a configuration class manually to ApplicationContextRunner proves its bean methods, - * not that the shipped application can ever discover it. Every root below lives under a package - * excluded from component scan, so Boot's AutoConfiguration.imports resource is its only production - * entry point. + * not that the shipped application can ever discover it. The composition root's component scan + * skips auto-configuration classes (Boot's {@code AutoConfigurationExcludeFilter}), so Boot's + * AutoConfiguration.imports resource is each root's only production entry point. */ class BootstrapCapabilityAutoConfigurationReachabilityTest { private static final List REQUIRED_ROOTS = List.of( - // Redis is no longer here. Its semantic wiring — the cache, rate-limit, lease and - // idempotency ports and the key policy they share — moved into - // `adapter:outbound:cache-redis`, which now ships its own registration and its own - // reachability test. What stayed in the composition root is the part that is genuinely - // cross-capability: the readiness-group append and the activation validator that reads - // the bootstrap-owned secret policy. + // Redis and the distributed lock are no longer here. Each moved into the module that + // implements it — `adapter:outbound:cache-redis` (with its readiness append and + // activation guard) and `adapter:outbound:persistence-jpa` — which ships its own + // registration and its own reachability test. The outbox relay stays: it assembles a use + // case over ports, which is composition, and it turns on from the store port the + // persistence module contributes. "dev.caskeleton.bootstrap.autoconfigure.outbox.OutboxConfig", - "dev.caskeleton.bootstrap.autoconfigure.lock.DistributedLockConfig", "dev.caskeleton.bootstrap.autoconfigure.idempotency.IdempotencyProviderSelectionConfig", "dev.caskeleton.bootstrap.autoconfigure.tracing.TracingConfig"); diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/CapabilityStatusDocumentTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/CapabilityStatusDocumentTest.java index 9e191a94..da666ed0 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/CapabilityStatusDocumentTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/CapabilityStatusDocumentTest.java @@ -2,7 +2,6 @@ package dev.caskeleton.bootstrap.contract; import static org.assertj.core.api.Assertions.assertThat; -import dev.caskeleton.shared.activation.MasterSwitch; import java.io.IOException; import java.io.UncheckedIOException; import java.nio.file.Files; @@ -11,13 +10,11 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; /** - * Every master switch has a row in the capability status document. + * The capability status document states what decides each of its columns. * *

The document separates three questions the review found conflated everywhere — is the * capability implemented, does the shipped artifact assemble it, has it been proven against a real - * provider. Those are judgements about evidence, so the document is written rather than generated; - * what a test can hold is that a capability cannot be added without stating them. A switch with no - * row is a capability whose deployment status nobody has answered. + * provider. Those are judgements about evidence, so the document is written rather than generated. * *

Deliberately the only automated check on that file. Re-deriving its cells would make a parser * the source of truth for a judgement, which is the shape of verification this repository's own @@ -27,20 +24,6 @@ class CapabilityStatusDocumentTest { private static final String DOCUMENT = "docs/capability-status.md"; - @Test - @DisplayName("every master switch is accounted for in the capability status document") - void everyMasterSwitchHasARow() { - String document = read(); - - for (MasterSwitch masterSwitch : MasterSwitch.values()) { - assertThat(document) - .as( - "%s names %s but %s does not say whether it is implemented, wired and qualified", - MasterSwitch.class.getSimpleName(), masterSwitch.environmentVariable(), DOCUMENT) - .contains(masterSwitch.environmentVariable()); - } - } - @Test @DisplayName("the document states what decides each column") void theDocumentNamesItsOwnSources() { diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ConditionalTransportQualificationContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ConditionalTransportQualificationContractTest.java deleted file mode 100644 index f1f458a2..00000000 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ConditionalTransportQualificationContractTest.java +++ /dev/null @@ -1,100 +0,0 @@ -package dev.caskeleton.bootstrap.contract; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.bootstrap.CaSkeletonApplication; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import org.junit.jupiter.api.Test; -import org.springframework.boot.context.properties.ConfigurationPropertiesScan; - -/** - * The opt-in inbound transports qualify without skips, and the root only aggregates. - * - *

This class used to be 860 lines, of which about 800 tested {@code - * .github/scripts/verify-gate-matrix.sh}: eighteen tests that wrote mutated copies of {@code - * .github/ci-gate-matrix.yml} into a {@code @TempDir} — a duplicate gate id, a row naming a job - * that does not exist, a {@code ref} containing a regex metacharacter, a release-blocking row no - * release gate required — and ran the shell script against them to check that it refused each one. - * - *

That is an application's test suite testing a YAML register of CI controls, through a bash - * validator, in a fixture repository. The register itself duplicated what the Gradle task graph and - * the GitHub Actions job graph already said, so the whole structure existed to keep three - * descriptions of one fact equal to each other. All three layers are gone. - * - *

What survives is the part that was about this repository's transports rather than about its CI - * register: each inbound transport leaf owns its qualification lane and names the wire classes that - * lane must execute, and the root task only aggregates them. - */ -class ConditionalTransportQualificationContractTest { - - @Test - void ownerQualificationsNameEveryRequiredWireClassAndRootOnlyAggregates() throws IOException { - Path root = repositoryRoot(); - String rootBuild = Files.readString(root.resolve("src/build.gradle")); - String graphql = Files.readString(root.resolve("src/adapter/inbound/graphql/build.gradle")); - String grpc = Files.readString(root.resolve("src/adapter/inbound/grpc/build.gradle")); - String websocket = Files.readString(root.resolve("src/adapter/inbound/websocket/build.gradle")); - - assertThat(graphql) - .contains("extensions.getByName('strictQualification').register(") - .contains("dev.caskeleton.adapter.inbound.graphql.GraphqlHttpBoundaryQualificationTest"); - assertThat(grpc) - .contains("extensions.getByName('strictQualification').register(") - .contains("dev.caskeleton.adapter.inbound.grpc.GrpcSafeActivationTest") - .contains("dev.caskeleton.adapter.inbound.grpc.GrpcP1BoundaryWireTest"); - assertThat(websocket) - .contains("extensions.getByName('strictQualification').register(") - .contains( - "dev.caskeleton.adapter.inbound.websocket.stomp.WebSocketBoundaryQualificationTest"); - - // The root delegates aggregation to the Java convention and knows no wire-test class name. - // The convention's TestKit contract owns the concrete aggregate task graph; this repository - // contract only prevents the root script from growing a second implementation of it. - assertThat(rootBuild) - .contains("id 'ca.conditional-transport-qualification'") - .doesNotContain("tasks.register('conditionalTransportQualification')") - .doesNotContain("registerConditionalTransportQualificationTest") - .doesNotContain("GraphqlHttpBoundaryQualificationTest") - .doesNotContain("GrpcP1BoundaryWireTest") - .doesNotContain("WebSocketBoundaryQualificationTest"); - } - - @Test - void optionalTransportsAreNotSettingsScannedByTheShippedComposition() { - ConfigurationPropertiesScan scan = - CaSkeletonApplication.class.getAnnotation(ConfigurationPropertiesScan.class); - - assertThat(scan).isNotNull(); - assertThat(scan.basePackages()) - .doesNotContain( - "dev.caskeleton.adapter.inbound.grpc", "dev.caskeleton.adapter.inbound.websocket"); - } - - @Test - void theReleaseBlockingQualityJobInvokesTheAggregate() throws IOException { - String workflow = - Files.readString(repositoryRoot().resolve(".github/workflows/ci-quality-gates.yml")); - - assertThat(workflow) - .contains("./gradlew :conditionalTransportQualification") - // `--continue` would let a failing transport lane be reported alongside a green overall - // step, which is the one thing a no-skip qualification may not do. - .doesNotContain("conditionalTransportQualification --continue"); - // The job that runs it has to be one the release gate waits on. - assertThat(workflow).contains("\n quality-gates:\n").contains("\n - quality-gates\n"); - } - - private static Path repositoryRoot() { - for (Path path = Paths.get("").toAbsolutePath(); path != null; path = path.getParent()) { - if (Files.isRegularFile(path.resolve("AGENTS.md")) - && Files.isRegularFile(path.resolve("src/settings.gradle"))) { - return path; - } - } - throw new IllegalStateException( - "repository root not found from " + Paths.get("").toAbsolutePath()); - } -} diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ConfigurationNamespaceContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ConfigurationNamespaceContractTest.java index ecd63b0d..76a7fb2c 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ConfigurationNamespaceContractTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ConfigurationNamespaceContractTest.java @@ -44,6 +44,12 @@ import org.junit.jupiter.api.Test; * *

So the roots stay, and what changes is that they can no longer grow quietly. A fourth root, or * a new prefix under an existing one, fails here and has to be argued for. + * + *

Since capabilities became modules a service selects (2026-09-25), the default composition + * declares only {@code ca-skeleton} of the three. {@code app} and {@code backend} arrive with the + * capability modules that own them — {@code app.redis}, {@code app.messaging}, {@code + * app.httpclient}, {@code app.fileserver-platform}, {@code backend.graphql} — so they stay allowed + * here: uncommenting one capability line must not turn this contract red. */ class ConfigurationNamespaceContractTest { @@ -73,17 +79,11 @@ class ConfigurationNamespaceContractTest { private static final Set DECLARED_PREFIXES = new TreeSet<>( List.of( - "app.fileserver-platform", - "app.httpclient", - "app.jpa-platform", "ca-skeleton.async.executor", "ca-skeleton.bootstrap", - "ca-skeleton.capabilities", "ca-skeleton.capabilities.idempotency", "ca-skeleton.domain-context", - "ca-skeleton.idempotency", "ca-skeleton.logging", - "ca-skeleton.notification.platform.secrets", "ca-skeleton.outbox", "ca-skeleton.privacy", "ca-skeleton.runtime", @@ -116,7 +116,7 @@ class ConfigurationNamespaceContractTest { .isSubsetOf(ALLOWED_ROOTS); assertThat(roots) .as("the scan must actually reach the shipped roots, or this check passes vacuously") - .contains("ca-skeleton", "app", "spring"); + .contains("ca-skeleton", "spring"); } @Test @@ -147,37 +147,6 @@ class ConfigurationNamespaceContractTest { .isSubsetOf(DECLARED_PREFIXES); } - @Test - @DisplayName("each capability's configuration lives in exactly one shipped file") - void eachCapabilityHasOneHome() { - // The operator-facing half of BOOT-001, and the half the split actually fixed: notification was - // registered under both roots, in one 974-line file, 470 lines apart. The two trees are still - // two - // trees — one is the delivery platform, the other the R0 legacy seam — but they are now in - // config/notification.yml together, so looking up "notification" reaches both. - assertThat(ShippedConfiguration.resources()) - .as("the split must be in place for this contract to mean anything") - .contains("config/notification.yml"); - - String notification = fileText("config/notification.yml"); - assertThat(notification) - .as("the delivery platform tree must be in the notification file") - .contains("ca-skeleton:") - .contains("platform:"); - assertThat(notification) - .as("the legacy provider-selection tree must be in the same file, not a root away") - .contains("app:"); - } - - private static String fileText(String resource) { - String marker = "# --- " + resource + " ---"; - String all = ShippedConfiguration.text(); - int start = all.indexOf(marker); - assertThat(start).as("%s must be among the shipped resources", resource).isNotNegative(); - int next = all.indexOf("# --- ", start + marker.length()); - return next < 0 ? all.substring(start) : all.substring(start, next); - } - private static Path repositoryRoot() { Path candidate = Path.of("").toAbsolutePath(); while (candidate != null diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/HeaderRegistryRuntimeAlignmentTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/HeaderRegistryRuntimeAlignmentTest.java index 01c71604..6d87719b 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/HeaderRegistryRuntimeAlignmentTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/HeaderRegistryRuntimeAlignmentTest.java @@ -1,11 +1,8 @@ package dev.caskeleton.bootstrap.contract; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; import dev.caskeleton.adapter.inbound.web.ratelimit.RateLimitWebConfig; -import dev.caskeleton.adapter.inbound.web.security.UntrustedTenantInputException; -import dev.caskeleton.adapter.inbound.web.security.WebTenantContextResolver; import dev.caskeleton.bootstrap.contract.support.RepositoryContractResources; import java.io.InputStream; import java.nio.file.Files; @@ -38,10 +35,6 @@ class HeaderRegistryRuntimeAlignmentTest { @Test void unsupportedTenantAndApiVersionHeadersAreNotAdvertisedAsSupportedSurface() { assertThat(names()).doesNotContain("X-Tenant-Id", "X-Api-Version"); - - WebTenantContextResolver resolver = new WebTenantContextResolver(); - assertThatThrownBy(() -> resolver.rejectTenantInput(Map.of("X-Tenant-Id", "tenant-attacker"))) - .isInstanceOf(UntrustedTenantInputException.class); } @Test diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ManagementActuatorSecurityContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ManagementActuatorSecurityContractTest.java index 4038d62d..8dd68d79 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ManagementActuatorSecurityContractTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ManagementActuatorSecurityContractTest.java @@ -187,15 +187,9 @@ class ManagementActuatorSecurityContractTest { Set includeSet = csvToSet(include); // Exactly the safe, scrape/probe-friendly endpoints — no more. - // - // adapteractivation is on the list and is the one addition since D2. It reports which master - // switches resolved on and what that makes required: property names and booleans, no address, - // credential or schema. AdapterActivationReportShapeTest is what holds it to that, which is why - // adding it here is a decision rather than a widening — the allowlist stays exact, and a - // sixth entry still has to argue for itself. assertThat(includeSet) .as("application.yml management.endpoints.web.exposure.include (D2 allowlist)") - .containsExactlyInAnyOrder("health", "prometheus", "info", "loggers", "adapteractivation"); + .containsExactlyInAnyOrder("health", "prometheus", "info", "loggers"); // Dangerous endpoints must never appear in the include allowlist. assertThat(includeSet) .as("D2/D4/D5: dangerous endpoints must not be in application.yml include") diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ProfileSeparationContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ProfileSeparationContractTest.java index 1e8de49e..3be9a777 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ProfileSeparationContractTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ProfileSeparationContractTest.java @@ -25,15 +25,17 @@ import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.SafeConstructor; /** - * Pins the environment split: local runs on an in-memory database, every deployed profile runs on - * PostgreSQL with Flyway owning the schema. + * Pins the environment split: every profile that runs relational persistence runs PostgreSQL with + * Flyway owning the schema, and local needs nothing from {@code src/.env}. * - *

These are file assertions rather than a booted context on purpose. Booting the real - * composition root inside this source set is not currently possible — the component scan that makes - * {@code CaSkeletonApplication} the composition root also finds the nested {@code @Configuration} - * classes that dozens of tests here declare, and they collide. The behaviour behind these files is - * covered where it can be: {@code H2ClaimSqlTest} runs the H2 statements against a real H2, {@code - * PersistenceVendorSelectionTest} covers the selector, and {@code + *

The default composition ships no database. The profile files still carry the relational values + * a service gets the moment it selects {@code persistence-jpa} with one build line; until then they + * bind to nothing. So the datasource assertions below are about those files, not about a connection + * the default composition opens — {@code DefaultCompositionBootTest} proves it opens none. + * + *

These are file assertions rather than a booted context on purpose. The behaviour behind these + * files is covered in the persistence-jpa module: {@code H2ClaimSqlTest} runs the H2 statements + * against a real H2, {@code PersistenceVendorSelectionTest} covers the selector, and {@code * PersistenceVendorProdSafetyValidatorTest} covers the prod refusal. What is left, and what this * test guards, is the wiring between them drifting — a profile quietly changing vendor, or local * regaining a migration expectation it cannot satisfy. @@ -108,8 +110,8 @@ class ProfileSeparationContractTest { @Test void theProfilelessDefaultIsPostgreSqlRatherThanTheInMemoryDatabase() throws IOException { - // The merged shipped configuration; the datasource block moved to config/persistence.yml - // when the base file was split (BOOT-008). + // The merged shipped configuration; the datasource block ships with the persistence-jpa module + // (config/module-defaults/persistence-jpa.yml). Map base = ShippedConfiguration.tree(); assertThat(vendorOf(base)) diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/RedisOptionalityContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/RedisOptionalityContractTest.java deleted file mode 100644 index e26c81a6..00000000 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/RedisOptionalityContractTest.java +++ /dev/null @@ -1,84 +0,0 @@ -package dev.caskeleton.bootstrap.contract; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.adapter.outbound.cache.redis.sdk.config.RedisSdkSettings; -import dev.caskeleton.bootstrap.CaSkeletonApplication; -import java.util.List; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.springframework.boot.SpringBootConfiguration; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.boot.context.properties.ConfigurationPropertiesScan; - -/** - * Redis optionality, guarded where it is actually decided: the composition root. - * - *

{@link CaSkeletonApplication} scans {@code dev.caskeleton.adapter} for - * {@code @ConfigurationProperties}. That scan is not selective and cannot be made selective per - * deployment, so any annotated settings class under an adapter package is registered in every - * deployment — including one that runs no Redis at all. Redis settings must therefore not carry the - * annotation; they are registered by the conditional {@code RedisSdkAutoConfiguration} and by - * nothing else. - * - *

This is a structural test on purpose. The runtime version of the same claim needs a full - * context per case, and the property it protects is a single annotation that is very easy to re-add - * "for consistency" with every other settings class in the repository. - */ -class RedisOptionalityContractTest { - - /** The settings classes Redis owns, all of which must stay outside the application-wide scan. */ - private static final List> REDIS_SETTINGS_TYPES = List.of(RedisSdkSettings.class); - - @Test - @DisplayName("the application-wide properties scan still covers the adapter package") - void theScanThisTestProtectsAgainstIsStillInPlace() { - ConfigurationPropertiesScan scan = - CaSkeletonApplication.class.getAnnotation(ConfigurationPropertiesScan.class); - - assertThat(scan) - .as("CaSkeletonApplication must keep declaring @ConfigurationPropertiesScan") - .isNotNull(); - assertThat(scan.basePackages()) - .as( - "the scan that would make an annotated Redis SDK settings class unconditional; this " - + "asserts the hazard still exists, so the assertion below is about something") - .contains("dev.caskeleton.adapter.outbound.cache.redis.sdk"); - assertThat(scan.basePackages()) - .as( - "the capability package must stay outside the scan. RedisCapabilitySettings is " - + "annotated @ConfigurationProperties and is bound by the gated " - + "RedisCapabilityConfig; when the capability moved into the leaf under the wider " - + "`...cache.redis` prefix the scan bound it with every switch off, which is the " - + "one thing the off-state contract forbids") - .doesNotContain("dev.caskeleton.adapter.outbound.cache.redis") - .noneMatch( - basePackage -> - "dev.caskeleton.adapter.outbound.cache.redis.capability" - .startsWith(basePackage + ".")); - assertThat(CaSkeletonApplication.class.getAnnotation(SpringBootConfiguration.class)) - .as( - "the composition root is spelled out as @SpringBootConfiguration + " - + "@EnableAutoConfiguration + @ComponentScan so the scan can carry an exclusion; " - + "the properties scan this test protects against is unaffected") - .isNotNull(); - assertThat(CaSkeletonApplication.class.getAnnotation(EnableAutoConfiguration.class)) - .isNotNull(); - } - - @Test - @DisplayName("no Redis settings class is annotated @ConfigurationProperties") - void redisSettingsAreNotPickedUpByTheApplicationWideScan() { - for (Class settings : REDIS_SETTINGS_TYPES) { - assertThat(settings.getAnnotation(ConfigurationProperties.class)) - .as( - "%s must not be annotated @ConfigurationProperties: the application-wide scan would " - + "register it in every deployment, so a service that runs no Redis would bind " - + "Redis configuration and a malformed Redis block it never enabled would still " - + "be read. RedisSdkAutoConfiguration binds it behind app.redis.enabled instead.", - settings.getName()) - .isNull(); - } - } -} diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/SecretsClassificationRegistryTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/SecretsClassificationRegistryTest.java index bdbc7450..c4e13c94 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/SecretsClassificationRegistryTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/SecretsClassificationRegistryTest.java @@ -54,13 +54,11 @@ class SecretsClassificationRegistryTest { for (Map row : registryRows) { boolean isSecret = "secret".equals(row.get("classification")); boolean prodDefaultNull = row.containsKey("prod_default") && row.get("prod_default") == null; - // `required_when` marks a secret that a prod deployment needs only if it switched the owning - // capability on. The validator demands its constant unconditionally at startup, so listing - // one - // there would make every prod deployment supply key material for a capability that is off by - // default — the exact coupling the master switches exist to remove. The eight notification - // platform keys are the first of these; the platform validates them itself, at startup, and - // only once enabled. + // `required_when` marks a secret that a prod deployment needs only if it selected the owning + // capability. The validator demands its constant unconditionally at startup, so listing one + // there would make every prod deployment supply key material for a capability it did not + // select. The eight notification platform keys are the first of these; the platform + // validates them itself, at startup, and only once enabled. boolean conditional = row.get("required_when") != null; if (isSecret && prodDefaultNull && !conditional) { registryRequired.add((String) row.get("name")); diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/graphql/GraphQlResolverReachabilityTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/graphql/GraphQlResolverReachabilityTest.java index f610dc07..3208e755 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/graphql/GraphQlResolverReachabilityTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/graphql/GraphQlResolverReachabilityTest.java @@ -14,10 +14,10 @@ import org.junit.jupiter.api.Test; * *

{@code skeleton.graphqls} declares one field, {@code _health: String!}, and {@code * HealthGraphqlController} resolves it. The controller is a {@code @Controller} in a package the - * composition root's {@code @ComponentScan} excludes by regex — the same exclusion that makes the - * capability optional — and no auto-configuration imported it. So a deployment with GraphQL enabled - * served a schema whose only field had nothing behind it, and every query came back {@code - * NullValueInNonNullableField}. + * composition root's {@code @ComponentScan} does not reach — it covers {@code + * dev.caskeleton.bootstrap} only — and no auto-configuration imported it. So a deployment with + * GraphQL enabled served a schema whose only field had nothing behind it, and every query came back + * {@code NullValueInNonNullableField}. * *

Two unit tests covered that controller and both passed: one registers the class in an {@code * ApplicationContextRunner}, the other lists it among a fixed set of classes for a boundary diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/messaging/MessagingAuthorityContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/messaging/MessagingAuthorityContractTest.java index fe41f9f2..4bda0988 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/messaging/MessagingAuthorityContractTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/messaging/MessagingAuthorityContractTest.java @@ -79,10 +79,10 @@ class MessagingAuthorityContractTest { assertThat(implementations) .as( - "the fail-closed sentinel and the real adapter are one path with two states, not two " - + "paths; a second real implementation would publish every event twice and look " - + "like it was working") - .containsExactly("DisabledOutboxMessagePublisher", "OutboxMessagePublishAdapter"); + "one publication path and no stand-in: a second real implementation would publish " + + "every event twice, and a throwing stand-in would let the relay drain every " + + "PENDING row to DEAD") + .containsExactly("OutboxMessagePublishAdapter"); } @Test diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/messaging/MessagingCapabilityRegistryContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/messaging/MessagingCapabilityRegistryContractTest.java index 6eee2645..d36b4035 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/messaging/MessagingCapabilityRegistryContractTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/messaging/MessagingCapabilityRegistryContractTest.java @@ -43,7 +43,7 @@ class MessagingCapabilityRegistryContractTest { /** Qualification tasks that exist and can pass. */ private static final Set IMPLEMENTED_VERIFICATION_TASKS = - Set.of("verifyMessagingContracts", "verifyMessagingJsonSchemaV1"); + Set.of("verifyMessagingContracts"); /** * Task names a not-implemented card names as the evidence it will need. @@ -68,12 +68,12 @@ class MessagingCapabilityRegistryContractTest { "verifyMessagingFinalR2Profile"); /** - * Every producer name the registry files enumerate: the two that exist plus the nine planned. + * Every producer name the registry files enumerate: the one that exists plus the nine planned. * *

Used for the release profiles and the evidence manifest schema, which describe the complete - * R2 shape rather than the current build. A schema saying "producerTask must be one of these - * eleven" is a statement about the evidence format; it is not a claim that eleven tasks exist, - * which is exactly the claim the deleted Gradle registrations were making. + * R2 shape rather than the current build. A schema saying "producerTask must be one of these ten" + * is a statement about the evidence format; it is not a claim that ten tasks exist, which is + * exactly the claim the deleted Gradle registrations were making. */ private static final Set ALL_VERIFICATION_TASKS = Stream.concat(IMPLEMENTED_VERIFICATION_TASKS.stream(), PLANNED_VERIFICATION_TASKS.stream()) @@ -135,33 +135,22 @@ class MessagingCapabilityRegistryContractTest { } @Test - void onlyTheQualifiedJsonSchemaCardIsAnImplementedCandidate() throws Exception { + void noCardIsAnImplementedCandidateWhileNoCardHasAnImplementation() throws Exception { List> cards = rows(readYaml(requiredConfig("readiness-cards.yaml")), "cards"); for (Map card : cards) { assertThat(card.get("maturity")).isIn(LEGAL_MATURITY); assertThat(card.get("evidenceFingerprint")).isEqualTo(""); - if ("json-schema-envelope.v1".equals(card.get("cardId"))) { - assertThat(card.get("maturity")).isEqualTo("implemented-candidate"); - assertThat(card.get("schemaSetHash")) - .isEqualTo("sha256:42040504d5c204f9ee0e01bfa17fd9a03182db13f8f99e31b63ec79d5ecc40d0"); - assertThat(card.get("settingsDigest")) - .isEqualTo("sha256:fcd849322d43a8d88c926a43160296339cbc6e945db81e46c513ab45d185b924"); - } else { - assertThat(card.get("maturity")).isEqualTo("not-implemented"); - assertThat(card.get("schemaSetHash")).isEqualTo(""); - assertThat(card.get("settingsDigest")).isEqualTo(""); - } + // json-schema-envelope.v1 was the one implemented candidate; its encoder was removed on + // 2026-09-25, so every card is back to not-implemented with no pinned hashes. + assertThat(card.get("maturity")).isEqualTo("not-implemented"); + assertThat(card.get("schemaSetHash")).isEqualTo(""); + assertThat(card.get("settingsDigest")).isEqualTo(""); assertNonEmptyStringList(card, "evidenceTasks"); - boolean implementedCandidate = "implemented-candidate".equals(card.get("maturity")); assertThat(stringList(card, "evidenceTasks")) .as("evidenceTasks on %s must name a known qualification task", card.get("cardId")) - .allMatch( - task -> - IMPLEMENTED_VERIFICATION_TASKS.contains(task) - || (!implementedCandidate && PLANNED_VERIFICATION_TASKS.contains(task)), - "an implemented-candidate card may only name a task that exists"); + .allMatch(ALL_VERIFICATION_TASKS::contains); assertNonEmptyStringList(card, "requiredScenarios"); assertNonEmptyStringList(card, "runbookIds"); } diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/messaging/MessagingMembershipQualificationTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/messaging/MessagingMembershipQualificationTest.java deleted file mode 100644 index ed1fcec6..00000000 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/messaging/MessagingMembershipQualificationTest.java +++ /dev/null @@ -1,103 +0,0 @@ -package dev.caskeleton.bootstrap.contract.messaging; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.io.IOException; -import java.io.UncheckedIOException; -import java.nio.file.Files; -import java.nio.file.Path; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** Build-time membership contract for the messaging core and broker capabilities (MSG-INT-003). */ -class MessagingMembershipQualificationTest { - - @Test - @DisplayName("the Kafka capability is qualified by a live broker round trip") - void theKafkaCapabilityIsQualifiedByALiveRoundTrip() { - Path qualification = - repositoryRoot() - .resolve( - "src/messaging/messaging-spring-boot-starter/src/integrationTest/java/dev/caskeleton/messaging/" - + "autoconfigure/MessagingLiveRoundTripQualificationTest.java"); - - assertThat(Files.exists(qualification)) - .as("Kafka capability promotion must not rest on unit fakes") - .isTrue(); - assertThat(read(qualification)).contains("brokerAccepted()"); - assertThat( - read( - repositoryRoot() - .resolve("src/messaging/messaging-spring-boot-starter/build.gradle"))) - .contains( - "integrationTestImplementation project(':messaging:messaging-spring-boot-starter-kafka')"); - } - - @Test - @DisplayName( - "the default composition ships the broker-neutral core, not either broker capability") - void defaultCompositionShipsOnlyTheBrokerNeutralCore() { - String bootstrap = read(repositoryRoot().resolve("src/app-bootstrap/build.gradle")); - - assertThat(bootstrap) - .contains("implementation project(':messaging:messaging-spring-boot-starter')") - .doesNotContain( - "implementation project(':messaging:messaging-spring-boot-starter-kafka')", - "implementation project(':messaging:messaging-spring-boot-starter-rabbit')", - "implementation project(':adapter:outbound:messaging-kafka')"); - } - - @Test - @DisplayName("the core starter has no production edge to either broker leaf") - void coreStarterIsBrokerNeutral() { - String starter = - read(repositoryRoot().resolve("src/messaging/messaging-spring-boot-starter/build.gradle")); - - assertThat(starter) - .doesNotContain( - "implementation project(':messaging:messaging-kafka')", - "implementation project(':messaging:messaging-rabbit')"); - } - - @Test - @DisplayName("Kafka and Rabbit capability leaves are registered as separate build-time modules") - void brokerCapabilitiesAreRegisteredSeparately() { - String registry = read(repositoryRoot().resolve("src/config/architecture/modules.json")); - - assertThat(registry) - .contains("\"messaging-spring-boot-starter-kafka\"") - .contains("\"messaging-spring-boot-starter-rabbit\"") - .contains("\"adapter-outbound-messaging-kafka\""); - } - - @Test - @DisplayName("Rabbit remains explicitly unselectable until a production transport exists") - void rabbitQualificationStateIsExplicit() { - String matrix = read(repositoryRoot().resolve("docs/messaging/support-matrix.md")); - - assertThat(matrix) - .contains("RabbitMQ") - .contains("현재 starter에서 선택 불가") - .contains("RabbitChannelPublisher"); - } - - private static String read(Path path) { - try { - return Files.readString(path); - } catch (IOException unreadable) { - throw new UncheckedIOException(unreadable); - } - } - - private static Path repositoryRoot() { - Path candidate = Path.of("").toAbsolutePath(); - while (candidate != null - && !Files.isRegularFile(candidate.resolve("src/config/architecture/modules.json"))) { - candidate = candidate.getParent(); - } - if (candidate == null) { - throw new IllegalStateException("could not locate the repository root from the test cwd"); - } - return candidate; - } -} diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/support/ShippedConfiguration.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/support/ShippedConfiguration.java index f08b9cf9..bbfe85a2 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/support/ShippedConfiguration.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/support/ShippedConfiguration.java @@ -5,6 +5,7 @@ import java.io.InputStream; import java.io.UncheckedIOException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; +import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -13,6 +14,8 @@ import java.util.regex.Pattern; import org.springframework.boot.env.YamlPropertySourceLoader; import org.springframework.core.env.PropertySource; import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.yaml.snakeyaml.Yaml; /** @@ -50,7 +53,15 @@ public final class ShippedConfiguration { /** * Every shipped configuration resource, in the order Spring reads them. * - * @return {@code application.yml} first, then each imported file + *

A capability module ships a {@code config/module-defaults/*.yml} the support leaf's loader + * reads instead of appearing in the import list, or — {@code persistence-mongo} and {@code + * graphql}, which cannot reach the support leaf — its own {@code config/*.yml} that it loads + * itself. Such a file ships whenever the module is on the classpath, so it is read here too, + * after the imported ones. The default composition selects no capability; on this test classpath + * the one such file is {@code persistence-jpa}'s, which the test lane carries for its JPA + * contracts, plus any capability line a service has uncommented. + * + * @return {@code application.yml} first, then each imported file, then module-owned files */ public static List resources() { List resources = new ArrayList<>(); @@ -72,9 +83,29 @@ public final class ShippedConfiguration { + " parser stopped matching the import block — in which case every test using this" + " class would silently narrow to the framework settings alone."); } + resources.addAll(moduleOwnedResources(resources)); return List.copyOf(resources); } + private static List moduleOwnedResources(List imported) { + try { + PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); + List owned = new ArrayList<>(); + for (String location : List.of("config", "config/module-defaults")) { + Arrays.stream(resolver.getResources("classpath*:" + location + "/*.yml")) + .map(Resource::getFilename) + .map(name -> location + "/" + name) + .filter(name -> !imported.contains(name)) + .distinct() + .sorted() + .forEach(owned::add); + } + return owned; + } catch (IOException failure) { + throw new UncheckedIOException("failed to list classpath config/*.yml", failure); + } + } + /** * The shipped configuration as property sources, ready for a {@code * PropertySourcesPropertyResolver}. @@ -97,9 +128,9 @@ public final class ShippedConfiguration { /** * The shipped configuration as one merged tree. * - *

Merged one level deep, which is all that is needed and all that is safe: the split gave each - * root key's subtrees to different files ({@code ca-skeleton.notification} here, {@code - * ca-skeleton.outbox} there), and no two files define the same second-level key. + *

Merged recursively: module-owned files share second-level keys with the application's own + * ({@code ca-skeleton.capabilities.idempotency} holds the provider here and the Redis store's + * tuning in {@code cache-redis}), and a later file only adds or replaces leaves. * * @return root key to its merged subtree */ @@ -111,22 +142,26 @@ public final class ShippedConfiguration { if (document == null) { continue; } - document.forEach( - (root, subtree) -> { - Object existing = merged.get(root); - if (existing instanceof Map left && subtree instanceof Map right) { - Map combined = new LinkedHashMap<>(); - left.forEach((k, v) -> combined.put(String.valueOf(k), v)); - right.forEach((k, v) -> combined.put(String.valueOf(k), v)); - merged.put(root, combined); - } else { - merged.put(root, subtree); - } - }); + mergeInto(merged, document); } return merged; } + private static void mergeInto(Map target, Map source) { + source.forEach( + (key, value) -> { + String name = String.valueOf(key); + if (target.get(name) instanceof Map left && value instanceof Map right) { + Map combined = new LinkedHashMap<>(); + left.forEach((k, v) -> combined.put(String.valueOf(k), v)); + mergeInto(combined, right); + target.put(name, combined); + } else { + target.put(name, value); + } + }); + } + /** * The shipped configuration as text, for assertions about how a value is written. * diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/logging/StartupFailureSpringBootLogFilterTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/logging/StartupFailureSpringBootLogFilterTest.java index c93685e4..3de1d3eb 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/logging/StartupFailureSpringBootLogFilterTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/logging/StartupFailureSpringBootLogFilterTest.java @@ -6,7 +6,7 @@ import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.core.spi.FilterReply; -import dev.caskeleton.bootstrap.runtime.startup.StartupFailureLogState; +import dev.caskeleton.adapter.outbound.support.startup.StartupFailureLogState; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/registry/MongoRegistryPermissionParityTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/registry/MongoRegistryPermissionParityTest.java index b5fa61cf..89b6c3b2 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/registry/MongoRegistryPermissionParityTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/registry/MongoRegistryPermissionParityTest.java @@ -58,13 +58,13 @@ class MongoRegistryPermissionParityTest { } @Test - @DisplayName("the composition root actually declares the Mongo leaf") - void theCompositionRootDeclaresTheMongoLeaf() throws IOException { + @DisplayName("the composition root offers the Mongo leaf as one line a service uncomments") + void theCompositionRootOffersTheMongoLeafAsOneLine() throws IOException { assertThat( Files.readString( repositoryRoot().resolve(Path.of("src", "app-bootstrap", "build.gradle")))) - .as("property-only activation requires the Mongo module to be on the application classpath") - .contains("project(':adapter:outbound:persistence-mongo')"); + .as("Mongo is selected by one runtimeOnly line; the default composition leaves it out") + .contains("// runtimeOnly project(':adapter:outbound:persistence-mongo')"); } private static List declaredProjectDependencies() throws IOException { diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/ErrorDetailExposureSafetyValidatorTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/ErrorDetailExposureSafetyValidatorTest.java new file mode 100644 index 00000000..351150a3 --- /dev/null +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/ErrorDetailExposureSafetyValidatorTest.java @@ -0,0 +1,70 @@ +package dev.caskeleton.bootstrap.runtime; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.adapter.outbound.support.startup.ProfileMismatchException; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; + +class ErrorDetailExposureSafetyValidatorTest { + + private final ApplicationContextRunner runner = + new ApplicationContextRunner().withUserConfiguration(ValidatorConfig.class); + + @ParameterizedTest + @CsvSource({ + "spring.web.error.include-stacktrace, always, APP_SERVER_ERROR_INCLUDE_STACKTRACE", + "spring.web.error.include-stacktrace, ON_PARAM, APP_SERVER_ERROR_INCLUDE_STACKTRACE", + "spring.web.error.include-message, always, APP_SERVER_ERROR_INCLUDE_MESSAGE", + "spring.web.error.include-binding-errors, always, spring.web.error.include-binding-errors", + "spring.web.error.include-exception, true, spring.web.error.include-exception" + }) + void prodRefusesToStartWhenErrorDetailsWouldReachClients( + String key, String value, String namedInFailure) { + runner + .withInitializer(context -> context.getEnvironment().setActiveProfiles("Prod")) + .withPropertyValues(key + "=" + value) + .run( + context -> { + assertThat(context).hasFailed(); + assertThat(context.getStartupFailure()) + .isInstanceOf(ProfileMismatchException.class) + .hasStackTraceContaining(namedInFailure); + }); + } + + @Test + void prodStartsWhenEveryErrorDetailStaysHidden() { + runner + .withInitializer(context -> context.getEnvironment().setActiveProfiles("prod")) + .withPropertyValues( + "spring.web.error.include-stacktrace=never", + "spring.web.error.include-message=NEVER", + "spring.web.error.include-binding-errors=never", + "spring.web.error.include-exception=false") + .run(context -> assertThat(context).hasNotFailed()); + } + + @Test + void nonProdMayExposeErrorDetailsForDebugging() { + runner + .withInitializer(context -> context.getEnvironment().setActiveProfiles("local")) + .withPropertyValues( + "spring.web.error.include-stacktrace=always", "spring.web.error.include-exception=true") + .run(context -> assertThat(context).hasNotFailed()); + } + + @Configuration(proxyBeanMethods = false) + static class ValidatorConfig { + + @Bean + ErrorDetailExposureSafetyValidator errorDetailExposureSafetyValidator(Environment environment) { + return new ErrorDetailExposureSafetyValidator(environment); + } + } +} diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/OperationalContractRuntimeTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/OperationalContractRuntimeTest.java index f0b05583..aba03c71 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/OperationalContractRuntimeTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/OperationalContractRuntimeTest.java @@ -10,9 +10,8 @@ import dev.caskeleton.adapter.inbound.web.envelope.EnvelopeBodyAdvice; import dev.caskeleton.adapter.inbound.web.error.GlobalExceptionHandler; import dev.caskeleton.adapter.inbound.web.filter.CacheControlFilter; import dev.caskeleton.adapter.inbound.web.filter.RequestLoggingFilter; +import dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebAdapterAutoConfiguration; import dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebMvcPlatformAutoConfiguration; -import dev.caskeleton.adapter.inbound.web.mvc.error.WebMvcProblemExceptionHandler; -import dev.caskeleton.adapter.inbound.web.mvc.filter.WebMvcEvidenceFilter; import dev.caskeleton.adapter.inbound.web.mvc.filter.WebMvcRequestIdFilter; import dev.caskeleton.adapter.inbound.web.settings.PresentationSettings; import dev.caskeleton.bootstrap.CaSkeletonApplication; @@ -38,20 +37,20 @@ import org.springframework.web.bind.annotation.RestController; /** * Regression guard for the skeleton's operational envelope/error contract. * - *

This test pins that {@link CaSkeletonApplication}'s component scan ({@code scanBasePackages = - * "dev.caskeleton"}) wires the production envelope/error contract into the running application. A - * {@code @WebMvcTest} slice is used instead of a full {@code @SpringBootTest} because the latter - * requires the complete external runtime configuration and infrastructure. + *

This test pins that the web leaf's own auto-configuration ({@link + * WebAdapterAutoConfiguration}, which the running {@link CaSkeletonApplication} gets from the + * classpath) wires the production envelope/error contract. A {@code @WebMvcTest} slice is used + * instead of a full {@code @SpringBootTest} because the latter requires the complete external + * runtime configuration and infrastructure. * - *

The slice scans {@code CaSkeletonApplication}'s package for {@code @ControllerAdvice} beans, - * so it picks up the advices via the same component-scan path the running app uses. The raw-{@code - * Map} probe controller proves the {@link EnvelopeBodyAdvice} actually wraps a non-envelope body - * (the production {@code HealthcheckController} returns {@code Envelope.ok} by hand, so it cannot - * prove wrapping). + *

The slice imports that auto-configuration, so it picks up the advices and filters via the same + * path the running app uses. The raw-{@code Map} probe controller proves the {@link + * EnvelopeBodyAdvice} actually wraps a non-envelope body (the production {@code + * HealthcheckController} returns {@code Envelope.ok} by hand, so it cannot prove wrapping). */ @WebMvcTest(CaSkeletonApplication.class) @AutoConfigureMockMvc(addFilters = false) -@ImportAutoConfiguration(WebMvcPlatformAutoConfiguration.class) +@ImportAutoConfiguration({WebAdapterAutoConfiguration.class, WebMvcPlatformAutoConfiguration.class}) // RequestLoggingFilter (a @Component filter the broad CaSkeletonApplication slice scan // instantiates) now requires a UserPrincipalPseudonymizerPort; PseudonymizationConfig supplies it // (and binds PrivacySettings from the test salt) so the slice context can be built. @@ -88,29 +87,21 @@ class OperationalContractRuntimeTest { @Test void operationalContractBeansAreWiredIntoTheApplicationContext() { assertThat(ctx.getBeansOfType(EnvelopeBodyAdvice.class)) - .as("EnvelopeBodyAdvice must be component-scanned into the CaSkeletonApplication context") + .as("EnvelopeBodyAdvice must be registered in the CaSkeletonApplication context") .isNotEmpty(); assertThat(ctx.getBeansOfType(GlobalExceptionHandler.class)) - .as( - "GlobalExceptionHandler must be component-scanned into the CaSkeletonApplication" - + " context") + .as("GlobalExceptionHandler must be registered in the CaSkeletonApplication" + " context") .isNotEmpty(); assertThat(environment.getProperty("spring.mvc.problemdetails.enabled", Boolean.class)) .as("the shipped servlet contract pins Spring problem details off") .isFalse(); - assertThat(ctx.getBeansOfType(WebMvcProblemExceptionHandler.class)) - .as("the shipped envelope contract must not activate the optional problem-document advice") - .isEmpty(); } @Test void productionServletFiltersHaveTheDeclaredRelativeOrder() { java.util.Set> expected = java.util.Set.of( - WebMvcRequestIdFilter.class, - WebMvcEvidenceFilter.class, - CacheControlFilter.class, - RequestLoggingFilter.class); + WebMvcRequestIdFilter.class, CacheControlFilter.class, RequestLoggingFilter.class); Map, Integer> registrationOrders = new java.util.LinkedHashMap<>(); for (var initializer : new ServletContextInitializerBeans(ctx)) { @@ -123,14 +114,10 @@ class OperationalContractRuntimeTest { } assertThat(registrationOrders.keySet()) - .as("Boot must adapt all four production Filter beans into servlet registrations") + .as("Boot must adapt all three production Filter beans into servlet registrations") .containsExactlyInAnyOrderElementsOf(expected); - assertThat(registrationOrders.get(WebMvcRequestIdFilter.class)) - .isLessThan(registrationOrders.get(WebMvcEvidenceFilter.class)); assertThat(registrationOrders.get(WebMvcRequestIdFilter.class)) .isLessThan(registrationOrders.get(CacheControlFilter.class)); - assertThat(registrationOrders.get(WebMvcEvidenceFilter.class)) - .isLessThan(registrationOrders.get(RequestLoggingFilter.class)); assertThat(registrationOrders.get(CacheControlFilter.class)) .isLessThan(registrationOrders.get(RequestLoggingFilter.class)); } diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/activation/RuntimeEnvironmentProfileValidatorTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/RuntimeEnvironmentProfileValidatorTest.java similarity index 97% rename from src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/activation/RuntimeEnvironmentProfileValidatorTest.java rename to src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/RuntimeEnvironmentProfileValidatorTest.java index 25bc5495..a0da123c 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/activation/RuntimeEnvironmentProfileValidatorTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/RuntimeEnvironmentProfileValidatorTest.java @@ -1,4 +1,4 @@ -package dev.caskeleton.bootstrap.activation; +package dev.caskeleton.bootstrap.runtime; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -40,7 +40,7 @@ class RuntimeEnvironmentProfileValidatorTest { void anUnknownProfileIsRefused() { assertThatThrownBy(() -> validate("stage")) .hasMessageContaining("names no runtime environment") - .hasMessageContaining("master switch"); + .hasMessageContaining("never with a profile"); } @Test diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/RuntimeHealthLifecycleContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/RuntimeHealthLifecycleContractTest.java index 9d4ae061..2ecb743a 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/RuntimeHealthLifecycleContractTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/RuntimeHealthLifecycleContractTest.java @@ -95,10 +95,10 @@ class RuntimeHealthLifecycleContractTest { // The shipped file names only contributors that always exist. Both `redisRequired` and `db` are // conditional, and membership validation does NOT tolerate a conditional member being absent — // naming either statically made a deployment without it fail at startup. `db` joined that list - // once relational persistence became optional: a deployment with no database has no `db` - // contributor to gate on. RedisReadinessGroupPostProcessor and - // DatabaseReadinessGroupPostProcessor - // each append their own from the same predicate that creates the contributor. + // once relational persistence became optional: the default composition has no database and so + // no `db` contributor to gate on. The module that creates each contributor appends it — + // cache-redis's RedisReadinessGroupPostProcessor and persistence-jpa's + // JpaActivationEnvironmentPostProcessor. assertThat(properties.getProperty("management.endpoint.health.group.readiness.include")) .isEqualTo("readinessState"); assertThat(properties.getProperty("management.endpoint.health.validate-group-membership")) @@ -165,11 +165,11 @@ class RuntimeHealthLifecycleContractTest { /** * The taxonomy claim, asserted against an explicit include rather than the shipped one. * - *

{@code db} is appended at runtime by {@code DatabaseReadinessGroupPostProcessor} when a - * capability actually needs a connection, and an {@code ApplicationContextRunner} does not run - * environment post-processors. So this states the rule the appended member has to satisfy — a - * DOWN database makes a pod unready — while {@code DatabaseReadinessGroupPostProcessorTest} - * proves the appending itself. + *

{@code db} is appended at runtime by persistence-jpa's {@code + * JpaActivationEnvironmentPostProcessor} when that module is selected, and an {@code + * ApplicationContextRunner} does not run environment post-processors. So this states the rule the + * appended member has to satisfy — a DOWN database makes a pod unready — while {@code + * JpaActivationEnvironmentPostProcessorTest} proves the appending itself. */ @Test @DisplayName("readiness group includes db (REQUIRED dependency taxonomy)") diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/RuntimeNumericBoundsValidatorTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/RuntimeNumericBoundsValidatorTest.java index b22b50a0..d613b4c9 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/RuntimeNumericBoundsValidatorTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/RuntimeNumericBoundsValidatorTest.java @@ -2,7 +2,7 @@ package dev.caskeleton.bootstrap.runtime; import static org.assertj.core.api.Assertions.assertThat; -import dev.caskeleton.bootstrap.runtime.startup.StartupValidationException; +import dev.caskeleton.adapter.outbound.support.startup.StartupValidationException; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; @@ -21,15 +21,15 @@ class RuntimeNumericBoundsValidatorTest { new ApplicationContextRunner().withUserConfiguration(ValidatorConfig.class); @Test - void nonPositivePoolSizeFailsStartupNamingTheAppKey() { + void nonPositiveMaxThreadsFailsStartupNamingTheAppKey() { runner - .withPropertyValues("spring.datasource.hikari.maximum-pool-size=0") + .withPropertyValues("server.tomcat.threads.max=0") .run( context -> { assertThat(context).hasFailed(); assertThat(context.getStartupFailure()) .isInstanceOf(StartupValidationException.class) - .hasStackTraceContaining("APP_DATASOURCE_POOL_MAX_SIZE") + .hasStackTraceContaining("APP_SERVER_TOMCAT_MAX_THREADS") .hasStackTraceContaining(">= 1"); }); } @@ -51,8 +51,6 @@ class RuntimeNumericBoundsValidatorTest { void validValuesStartCleanly() { runner .withPropertyValues( - "spring.datasource.hikari.maximum-pool-size=20", - "spring.datasource.hikari.minimum-idle=2", "server.tomcat.threads.max=200", "server.tomcat.threads.min-spare=10", "server.tomcat.max-connections=8192", diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/SecretSourceValidatorTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/SecretSourceValidatorTest.java index 37cbe4f6..edd7fbdc 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/SecretSourceValidatorTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/SecretSourceValidatorTest.java @@ -2,7 +2,7 @@ package dev.caskeleton.bootstrap.runtime; import static org.assertj.core.api.Assertions.assertThat; -import dev.caskeleton.bootstrap.runtime.startup.StartupValidationException; +import dev.caskeleton.adapter.outbound.support.startup.StartupValidationException; import java.util.Arrays; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.runner.ApplicationContextRunner; @@ -98,6 +98,7 @@ class SecretSourceValidatorTest { void prodProfileWithMissingRequiredSecretFailsStartup() { runner .withInitializer(ctx -> ctx.getEnvironment().setActiveProfiles("prod")) + .withPropertyValues("ca-skeleton.persistence-jpa.enabled=true") .run( context -> { assertThat(context).hasFailed(); @@ -112,7 +113,7 @@ class SecretSourceValidatorTest { runner .withInitializer(ctx -> ctx.getEnvironment().setActiveProfiles("prod")) .withPropertyValues(allRequiredSecretsPresent()) - .withPropertyValues("APP_DATASOURCE_PASSWORD=") + .withPropertyValues("APP_DATASOURCE_PASSWORD=", "ca-skeleton.persistence-jpa.enabled=true") .run( context -> { assertThat(context).hasFailed(); @@ -122,6 +123,18 @@ class SecretSourceValidatorTest { }); } + @Test + void prodProfileWithoutRelationalPersistenceDoesNotRequireADatabasePassword() { + // The switch is set by the persistence-jpa module's shipped defaults; absent means the module + // is + // not in this composition, and a composition with no database owes no database password. + runner + .withInitializer(ctx -> ctx.getEnvironment().setActiveProfiles("prod")) + .withPropertyValues(allRequiredSecretsPresent()) + .withPropertyValues("APP_DATASOURCE_PASSWORD=") + .run(context -> assertThat(context).hasNotFailed()); + } + // ---- Redis is optional: no switch, no secret requirement ----------------- @Test diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/ShippedDefaultBindabilityTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/ShippedDefaultBindabilityTest.java index 5895e57e..2c647861 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/ShippedDefaultBindabilityTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/ShippedDefaultBindabilityTest.java @@ -3,8 +3,6 @@ package dev.caskeleton.bootstrap.runtime; import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; @@ -13,7 +11,7 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.boot.env.YamlPropertySourceLoader; import org.springframework.core.env.PropertySource; -import org.springframework.core.io.FileSystemResource; +import org.springframework.core.io.ClassPathResource; /** * A shipped inline default must be a value its property can actually bind. @@ -32,6 +30,11 @@ import org.springframework.core.io.FileSystemResource; *

This is the cheap half of that check: a scan, not a boot. It cannot know every property's * type, so it holds the list below — the millisecond-typed knobs where a duration shorthand is the * easy and wrong thing to write. Adding a row is how a future long-typed key joins. + * + *

The pool defaults ship with the persistence-jpa module ({@code + * config/module-defaults/persistence-jpa.yml}), not with the default composition; the profile files + * here override them for a service that selects it. Both are scanned from the test classpath, which + * carries the module. */ class ShippedDefaultBindabilityTest { @@ -57,7 +60,10 @@ class ShippedDefaultBindabilityTest { for (String resource : new String[] { - "application.yml", "application-local.yml", "application-dev.yml", "application-prod.yml" + "config/module-defaults/persistence-jpa.yml", + "application-local.yml", + "application-dev.yml", + "application-prod.yml" }) { for (PropertySource source : load(resource)) { for (String key : PLAIN_MILLISECOND_KEYS) { @@ -109,19 +115,6 @@ class ShippedDefaultBindabilityTest { * every property that happens to end in the same word. */ private static List> load(String resource) throws IOException { - Path path = repositoryRoot().resolve("src/app-bootstrap/src/main/resources").resolve(resource); - return new YamlPropertySourceLoader().load(resource, new FileSystemResource(path)); - } - - private static Path repositoryRoot() { - Path candidate = Path.of("").toAbsolutePath(); - while (candidate != null - && !Files.isRegularFile(candidate.resolve("src/config/architecture/modules.json"))) { - candidate = candidate.getParent(); - } - if (candidate == null) { - throw new IllegalStateException("could not locate the repository root from the test cwd"); - } - return candidate; + return new YamlPropertySourceLoader().load(resource, new ClassPathResource(resource)); } } diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/StartupSafetyValidatorTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/StartupSafetyValidatorTest.java index 94178a4f..65692d0b 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/StartupSafetyValidatorTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/StartupSafetyValidatorTest.java @@ -2,9 +2,9 @@ package dev.caskeleton.bootstrap.runtime; import static org.assertj.core.api.Assertions.assertThat; +import dev.caskeleton.adapter.outbound.support.startup.RequiredAdapterDisabledException; +import dev.caskeleton.adapter.outbound.support.startup.StartupFailureException; import dev.caskeleton.application.lock.DistributedLockPort; -import dev.caskeleton.bootstrap.runtime.startup.RequiredAdapterDisabledException; -import dev.caskeleton.bootstrap.runtime.startup.StartupFailureException; import dev.caskeleton.bootstrap.settings.RuntimeSafetySettings; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.ListableBeanFactory; diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/startup/StartupFailureExceptionReporterTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/startup/StartupFailureExceptionReporterTest.java index a557c495..d823f8db 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/startup/StartupFailureExceptionReporterTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/startup/StartupFailureExceptionReporterTest.java @@ -3,6 +3,7 @@ package dev.caskeleton.bootstrap.runtime.startup; import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.adapter.outbound.support.CapabilityStartupValidationException; +import dev.caskeleton.adapter.outbound.support.startup.MigrationFailedException; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.BeanCreationException; diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/startup/StartupOrderContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/startup/StartupOrderContractTest.java index aa3e878e..bc2e6411 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/startup/StartupOrderContractTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/startup/StartupOrderContractTest.java @@ -2,12 +2,9 @@ package dev.caskeleton.bootstrap.runtime.startup; import static org.assertj.core.api.Assertions.assertThat; -import dev.caskeleton.bootstrap.activation.CapabilityDependencyEnvironmentValidator; -import dev.caskeleton.bootstrap.activation.MasterSwitchEnvironmentPostProcessor; -import dev.caskeleton.bootstrap.activation.RuntimeEnvironmentProfileValidator; -import dev.caskeleton.bootstrap.autoconfigure.jpa.DatabaseReadinessGroupPostProcessor; -import dev.caskeleton.bootstrap.autoconfigure.redis.RedisReadinessGroupPostProcessor; +import dev.caskeleton.adapter.outbound.support.startup.StartupOrder; import dev.caskeleton.bootstrap.autoconfigure.tracing.TracingSamplingEnvironmentPostProcessor; +import dev.caskeleton.bootstrap.runtime.RuntimeEnvironmentProfileValidator; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; @@ -25,14 +22,8 @@ class StartupOrderContractTest { void everyRegisteredEnvironmentPostProcessorHasTheExpectedCentralOrder() throws Exception { Map expected = Map.of( - RedisReadinessGroupPostProcessor.class.getName(), StartupOrder.READINESS_REDIS, - DatabaseReadinessGroupPostProcessor.class.getName(), StartupOrder.READINESS_DATABASE, - MasterSwitchEnvironmentPostProcessor.class.getName(), - StartupOrder.MASTER_SWITCH_NORMALISATION, RuntimeEnvironmentProfileValidator.class.getName(), StartupOrder.RUNTIME_ENVIRONMENT_PROFILE, - CapabilityDependencyEnvironmentValidator.class.getName(), - StartupOrder.CAPABILITY_DEPENDENCY, TracingSamplingEnvironmentPostProcessor.class.getName(), StartupOrder.TRACING_SAMPLING); Map actual = registeredEnvironmentPostProcessorOrders(); @@ -45,21 +36,20 @@ class StartupOrderContractTest { } @Test - void readinessBandRunsImmediatelyAfterConfigDataInDeterministicOrder() { - assertThat(StartupOrder.READINESS_REDIS) + void propertySourceBandRunsImmediatelyAfterConfigDataInDeterministicOrder() { + // Module defaults first: the Redis and database readiness contributions (registered by the + // cache-redis and persistence-jpa modules) read switches those defaults carry. + assertThat(StartupOrder.MODULE_DEFAULTS) .isEqualTo(ConfigDataEnvironmentPostProcessor.ORDER + 1); - assertThat(StartupOrder.READINESS_DATABASE) + assertThat(StartupOrder.READINESS_REDIS) .isEqualTo(ConfigDataEnvironmentPostProcessor.ORDER + 2); - assertThat(StartupOrder.READINESS_REDIS).isLessThan(StartupOrder.READINESS_DATABASE); + assertThat(StartupOrder.READINESS_DATABASE) + .isEqualTo(ConfigDataEnvironmentPostProcessor.ORDER + 3); } @Test void validationAndDefaultingBandIsStrictlyOrdered() { - assertThat(StartupOrder.MASTER_SWITCH_NORMALISATION) - .isLessThan(StartupOrder.RUNTIME_ENVIRONMENT_PROFILE); - assertThat(StartupOrder.RUNTIME_ENVIRONMENT_PROFILE) - .isLessThan(StartupOrder.CAPABILITY_DEPENDENCY); - assertThat(StartupOrder.CAPABILITY_DEPENDENCY).isLessThan(StartupOrder.TRACING_SAMPLING); + assertThat(StartupOrder.RUNTIME_ENVIRONMENT_PROFILE).isLessThan(StartupOrder.TRACING_SAMPLING); assertThat(StartupOrder.TRACING_SAMPLING).isEqualTo(Ordered.LOWEST_PRECEDENCE); } diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/settings/WebJsonMapperCompositionTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/settings/WebJsonMapperCompositionTest.java index 317fccce..6c1a950a 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/settings/WebJsonMapperCompositionTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/settings/WebJsonMapperCompositionTest.java @@ -3,15 +3,13 @@ package dev.caskeleton.bootstrap.settings; import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebMvcPlatformAutoConfiguration; -import dev.caskeleton.adapter.inbound.web.webflux.autoconfigure.WebFluxPlatformAutoConfiguration; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.jackson.autoconfigure.JacksonAutoConfiguration; -import org.springframework.boot.test.context.runner.ReactiveWebApplicationContextRunner; import org.springframework.boot.test.context.runner.WebApplicationContextRunner; import tools.jackson.databind.json.JsonMapper; -/** Pins one Jackson runtime owner for both servlet and reactive web compositions. */ +/** Pins one Jackson runtime owner for the servlet web composition. */ class WebJsonMapperCompositionTest { @Test @@ -26,17 +24,4 @@ class WebJsonMapperCompositionTest { assertThat(context).doesNotHaveBean("webStrictObjectMapper"); }); } - - @Test - void reactiveCompositionHasExactlyOneJsonMapper() { - new ReactiveWebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of( - JacksonAutoConfiguration.class, WebFluxPlatformAutoConfiguration.class)) - .run( - context -> { - assertThat(context).hasNotFailed().hasSingleBean(JsonMapper.class); - assertThat(context).doesNotHaveBean("webStrictObjectMapper"); - }); - } } diff --git a/src/app-bootstrap/src/test/resources/application-test.yml b/src/app-bootstrap/src/test/resources/application-test.yml index 8d829bbf..827bb807 100644 --- a/src/app-bootstrap/src/test/resources/application-test.yml +++ b/src/app-bootstrap/src/test/resources/application-test.yml @@ -115,9 +115,6 @@ ca-skeleton: limit: 100 window: 1s algorithm: fixed-window - idempotency: - ttl: 24h - reaper-interval: 10m security: issuer-uri: http://localhost:8081/realms/ca-skeleton-test audience: ca-skeleton-test diff --git a/src/application-core/CLAUDE.md b/src/application-core/CLAUDE.md index 043d7517..081cd289 100644 --- a/src/application-core/CLAUDE.md +++ b/src/application-core/CLAUDE.md @@ -73,37 +73,11 @@ Package root: `dev.caskeleton.application`. | `messaging.event.ValidatedIntegrationEvent` | Stable semantic identities plus immutable exact encoded bytes and hashes, ready for a later durable append boundary. | | `messaging.event.IntegrationEventEncoderPort` | Framework-free local draft-to-validated-event boundary implemented by an outbound adapter. | -## Notification canonical namespace (NOTIF-ADR-005) +## Notification (NOTIF-ADR-005) -`..notification.platform..` is canonical. The R1 types directly under -`dev.caskeleton.application.notification` remain and accept no new production consumers; their -per-type disposition is in `docs/notification/module-mapping.md`. Production dependencies between -the two namespaces are zero, enforced by -`NOTIFICATION_R1_AND_PLATFORM_DO_NOT_DEPEND_ON_EACH_OTHER`; the only permitted exception is -`dev.caskeleton.application.notification.compatibility.r1`. - -## Notification R1 application boundary - -- `dev.caskeleton.application.notification` owns only framework-free semantic values, code-owned - kind policy, narrow outbound ports, dispatch/receipt/admission/reconciliation orchestration and - writer-cutover command contracts. -- Feature/application code creates a typed `NotificationIntentDraft`; `NotificationPlanPort` - returns the application-owned immutable `NotificationFrozenPlan`, which is the only planning - handoff consumed by append or inline attempt ports. Provider SDK, transport DTO, persistence - entity, compiled adapter binding and raw recipient/template payload types are forbidden here. -- Provider calls run outside database transactions. Dispatch and reconciliation use bounded - claim/authorize/finalize transactions with opaque claim/version/execution tokens; an - `INDETERMINATE` submission is terminal and must not be blindly retried. -- Receipt reduction is order-independent and keeps delivery acceptance monotonic. Only hard bounce - and complaint facts may request technical suppression; consent/unsubscribe policy is outside this - capability. -- Writer-cutover operations that must prove a physical commit use `inRootWrite`. Route/profile - registries are application-owned exact inputs; signed inventory/quiescence verification is - delegated to narrow verifier ports and the persistence operation must enforce locked durable - state/journal invariants. -- This is the R1 application contract proven with fakes. It does not claim PostgreSQL schema/locking, - provider protocol, cryptographic verifier, or runtime wiring qualification; those belong to the - notification/persistence/bootstrap adapters. +`..notification.platform..` (leaf `application-notification`) is canonical. The R1 types directly +under `dev.caskeleton.application.notification` were removed on 2026-09-25; only the simple +`NotificationPort`, `Notification` and `NotificationChannel` remain there. ## Naming convention @@ -177,18 +151,24 @@ loop outside the transaction boundary. ## Idempotency (KEYED) — feature-rate-limit-idempotency-contract -`@UseCaseCapability(idempotency = Idempotency.KEYED)` is now **supported** (the D14 -freeze is lifted). A KEYED use case wraps its work with the `idempotency`-package -`IdempotencyExecutor`: +`@UseCaseCapability(idempotency = Idempotency.KEYED)` is **supported**. A KEYED use case wraps +its work with `dev.caskeleton.application.idempotency.IdempotencyExecutor` — the one owner-safe +generation; the V1 `IdempotencyScope`/`tryBegin` API is gone. -- **Key source**: the `Idempotency-Key` HTTP header, assembled by `adapter:inbound:web`'s - `IdempotencyKeySupport` into an `IdempotencyScope` of - `(authenticatedPrincipal, idempotencyKey, useCaseName)` (tenant 4-tuple when active). -- **Storage**: a DB table (`IdempotencyStore` port → `adapter-persistence` - `IdempotencyStoreAdapter` over `idempotency_record`); in-memory prod storage is forbidden. -- **TTL**: `APP_IDEMPOTENCY_TTL` (default 24h, ≤72h override). -- Concurrency (200ms in-flight wait → 409) and fingerprint mismatch (SHA-256 → 422) - are enforced by the executor; the codes live in `OperationalError`. +- **Scope**: the caller passes an `IdempotencyScopeDigest` — a versioned HMAC of + principal + client key + operation code, computed before the executor sees it. The raw + `Idempotency-Key` never reaches this layer or the store. +- **Store**: `IdempotencyStorePort`, contributed by exactly one provider selected with + `ca-skeleton.capabilities.idempotency.provider` (`redis` → `cache-redis`, `postgresql` → + `persistence-jpa`; default `disabled`). In-memory prod storage is forbidden. +- **Executor**: built once by app-bootstrap `IdempotencyProviderSelectionConfig` from + `IdempotencySettings` (processing lease 30s, replay TTL `APP_IDEMPOTENCY_TTL` 24h ≤72h, + failure retention 24h). Do not construct it in a use case or a sample config. +- The action returns `IdempotentAction.Outcome` (`Success` / `RetryableNoEffect` / + `EffectUnknown`); a thrown exception counts as effect-unknown. In progress → 409 + `IDEMPOTENT_IN_FLIGHT`, fingerprint mismatch (SHA-256) → 422 `IDEMPOTENT_REQUEST_MISMATCH`; + `IdempotencyUnavailableException` and `IdempotencyRecoveryRequiredException` mean the store + could not prove the outcome, so do not blindly retry. The former ArchUnit freeze rule `inbound_port_implementations_do_not_declare_keyed_idempotency` and its fixture were removed when this branch merged. diff --git a/src/application-core/README.md b/src/application-core/README.md index eca1bcb8..ff429b89 100644 --- a/src/application-core/README.md +++ b/src/application-core/README.md @@ -14,11 +14,8 @@ `verifyApplicationCoreDependencyPurity`와 ArchUnit `APPLICATION_HAS_NO_DIAGNOSTIC_FRAMEWORK`가 이 계약을 자동 검증한다. -Cache 진단도 같은 원칙을 따른다. `CacheObservationEvent`는 code-owned bounded cache name, -local/Redis tier, enum outcome과 finite duration/count만 표현하며 semantic key, user/tenant ID, -endpoint를 담지 않는다. `CacheObservationPort`는 이 event를 전달하는 framework-free 경계이고, -Micrometer meter/tag 렌더링은 Redis adapter가 소유한다. 관측 실패는 cache lookup/invalidation -결과를 바꾸지 않는다. +Cache도 같은 원칙을 따른다. `cache` 패키지에는 cache-redis가 구현하는 `CacheRegionPort`와 그 +값 타입만 있다. Redis key, codec, Micrometer 렌더링은 adapter가 소유한다. --- @@ -138,31 +135,6 @@ application/domain 을 프레임워크-free 로 유지하는 핵심 장치. `@Transactional` 직접 사용, `inRootWrite` 의 ambient transaction 진입, `inNew` 의 per-record 루프 호출. ---- - -## Notification R1 오케스트레이션 경계 - -`dev.caskeleton.application.notification`은 알림 vendor 구현이 아니라 알림 capability의 순수 -애플리케이션 계약이다. - -- 입력은 typed recipient/template value와 코드 소유 `NotificationKindPolicy`로 제한한다. feature가 - 만든 `NotificationIntentDraft`는 `NotificationPlanPort`에서 immutable - `NotificationFrozenPlan`으로 고정되고, append/inline 포트는 이 plan만 소비한다. -- dispatch는 claim → reserve/authorize → provider call → terminal-once finalize 순서다. 짧은 DB - transaction 사이에서 provider를 호출하며, opaque claim/version/execution token으로 stale 결과를 - 거부한다. submission certainty가 `INDETERMINATE`면 blind retry나 fallback을 하지 않는다. -- receipt reducer는 fact 순서와 무관한 monotonic projection을 만든다. hard bounce/complaint만 - technical suppression 후보이고, business consent/unsubscribe는 다른 capability가 소유한다. -- admission/reconciliation/maintenance는 bounded batch와 주입된 `Clock`을 사용한다. scheduler는 - 이 유스케이스만 호출하며 store/provider 포트를 직접 조율하지 않는다. -- legacy→canonical writer cutover는 exact route/generation/profile registry, root-only commit, - 서명된 inventory/quiescence evidence와 closed transition action으로 표현한다. 애플리케이션은 - verifier/operation 포트의 입력 계약을 강제하고, 실제 서명 검증·행 잠금·불변 journal·provider - egress 차단은 후속 adapter 구현이 증명해야 한다. - -현재 증거 등급은 **R1 application contract with fakes**다. PostgreSQL DDL/locking, provider -protocol, receipt ingress, runtime wiring을 포함한 R2/R3 완료 주장이 아니다. - ### TransactionMode - `WRITE` / `READ_ONLY` / `REQUIRES_NEW`. TransactionPort API 와 UseCaseCapability 양쪽에서 쓰여, @@ -236,52 +208,52 @@ protocol, receipt ingress, runtime wiring을 포함한 R2/R3 완료 주장이 ## 멱등성 (idempotency) -application 계층이 in-flight 대기·replay **정책** 을 소유하고, 저장은 -`IdempotencyStorePort` 로 위임한다. +application 계층이 claim·replay·복구 **정책** 을 소유하고, 저장은 `IdempotencyStorePort` 로 +위임한다. 패키지는 `dev.caskeleton.application.idempotency` 하나다. 예전 V1(`IdempotencyScope`, +`tryBegin/complete/discard`)은 삭제됐고, owner-safe 계약이 유일한 세대다. ### IdempotencyExecutor -- application 유스케이스 경계에서 멱등 실행을 조율한다. 하나의 `IdempotencyScope` 에 대해 순서대로: - 1. **claim** — store 유니크 제약 위의 atomic insert-or-read(D7). 이긴 caller 가 action 을 - 정확히 한 번 실행한다. - 2. **fingerprint mismatch** — 같은 key, 다른 body(다른 fingerprint)인 live record 는 - `IdempotencyRequestMismatchException` → 422(D8). - 3. **replay** — `COMPLETED` record 는 저장된 응답을 codec 으로 재생(§B). - 4. **in-flight wait** — 동시 `IN_FLIGHT` record 는 최대 `IN_FLIGHT_WAIT`(200ms) 동안 폴링하고, - 여전히 미해결이면 `IdempotencyInFlightException` → 409(D7). -- claim 한 action 이 예외를 던지면 in-flight record 를 `discard` 한다 — 그래야 재시도가 TTL - 만료까지 409 에 갇히지 않는다. -- **200ms 대기 창의 출처(표준이 강제한 값 아님 — 스켈레톤 기본 선택)**: 이 200ms 대기 창은 - 인용 가능한 표준이 강제하는 값이 아니다(IETF/Toss 는 즉시 409 를 권장). 표준의 운영 친화적 - 변형이다 — "표준 기반 + 운영 변형" 으로 설명해야지 "표준을 따른다" 고 말하면 안 된다. 블로킹 - 폴링이 요청 스레드를 점유하므로, 중복 도착이 몰리면 스레드 점유 vs 클라이언트 재시도 친화성의 - 트레이드오프가 있다(임계치는 부하 테스트로 검증 필요). -- 상수: `IN_FLIGHT_WAIT = 200ms`(D7), `MAX_TTL = 72h`(D6 하드 캡), `POLL_INTERVAL = 20ms`. -- package-private 한 `Sleeper` 주입 생성자가 따로 있는 이유: 테스트 `Sleeper` 가 mutable clock 을 - 전진시켜 실제 시간 블로킹 없이 in-flight wait 를 결정적으로 검증하기 위함. +- application 유스케이스 경계에서 멱등 실행을 조율한다. 입력은 `IdempotencyScopeDigest`, + `RequestFingerprint`, caller 가 응답 유실 뒤에도 보관하는 `IdempotencyClaimAttempt` + (`newAttempt(operationId)` 로 만든다), `IdempotentAction`, `IdempotentResponseCodec` 이다. +- 흐름: **claim → markExecutionStarted → action 실행 → complete(또는 markFailed)**. + - `COMPLETED` record 는 저장된 응답을 codec 으로 재생한다. + - 같은 scope 에 다른 fingerprint → `IdempotencyRequestMismatchException` → 422. + - 다른 owner 가 진행 중 → 기다리지 않고 바로 `IdempotencyInFlightException` → 409. + - store 응답이 유실(`INDETERMINATE`)되면 `inspect` 로 실제 상태를 읽어 이어가거나 멈춘다. +- 모든 상태 전이는 owner 핸들(owner token + attempt + operation ID + state revision)을 + compare-and-set 으로 검증한다. 전이가 성공하면 revision 이 올라간 새 핸들을 다음 호출에 쓴다. +- action 결과는 `IdempotentAction.Outcome` 으로 분류한다. `RetryableNoEffect` 만 재시도 가능한 + 실패로 기록하고, `EffectUnknown` 이나 그냥 던진 예외는 "효과 불명"(`ABANDONED`)으로 남긴다. + 한 번 실행됐을지 모르는 작업을 재시도로 두 번 돌리지 않기 위해서다. +- processing lease 와 replay TTL 은 따로 간다. 만료된 `CLAIMED` 만 다른 caller 가 가져갈 수 있고, + 만료된 `EXECUTING` 은 `RECOVERY_REQUIRED` 로 닫는다. +- 생성은 app-bootstrap `IdempotencyProviderSelectionConfig` 가 한 번 한다(`IdempotencySettings`: + processing lease 30s, replay TTL 24h(최대 72h), failure retention 24h, codec id `json-v2`, + policy revision 2). 유스케이스나 샘플 설정이 직접 만들지 않는다. +- 이 계약은 요청 재생(replay) 근거를 남길 뿐이다. store 와 비즈니스 DB 사이의 exactly-once 를 + 보장하지 않는다. ### IdempotencyStorePort -- 멱등 record 저장 outbound 포트(D3). `adapter-persistence` 가 유니크 제약 - `(tenant, principal, idempotency_key, use_case_name)` 위에 구현한다. 포트는 저장 primitive - (tryBegin/find/complete/discard)만 노출하고, 정책은 executor 가 가진다. -- **in-memory 프로덕션 구현 금지**: 계약상 내구성 있고 유일성을 강제하는 백킹 스토어가 필요하다. - Redis 는 내구 스토어 앞단의 선택적 캐시로만 허용된다. -- **만료 record 는 reclaimable**: `expiresAt <= now` 인 record 는 없는 것처럼 취급해야 한다. - `tryBegin` 은 만료된 죽은 행을 purge/replace 해서 새 claim 이 이기게 하고, `find` 는 만료된 - record 를 absent 로 보아 만료 replay 를 거부한다(§E / TTL 경계). +- provider 중립 owner-safe 상태 기계 포트. 메서드: `newClaimAttempt`, `claim`, + `markExecutionStarted`, `renew`, `complete`, `markFailed`, `releaseBeforeExecution`, `inspect`. +- 상태: `CLAIMED` / `EXECUTING` / `COMPLETED` / `FAILED_RETRYABLE` / `ABANDONED`(`IdempotencyState`). +- 구현은 provider 하나만 붙는다: `redis`(`adapter:outbound:cache-redis` + `RedisIdempotencyStoreAdapter`) 또는 `postgresql`(`adapter:outbound:persistence-jpa` + `PostgreSqlOwnerSafeIdempotencyStore`). `ca-skeleton.capabilities.idempotency.provider` 로 고르고 + 기본값은 `disabled` 다. store 가 정확히 하나가 아니면 기동을 거부한다. +- **in-memory 프로덕션 구현 금지**. 테스트용 `InMemoryIdempotencyStore` 는 testFixtures 에만 있다. -### IdempotencyScope +### IdempotencyScopeDigest -- 멱등 요청의 정체성이자 계약의 SSOT scope 모양(D2). 기본은 triple - `(authenticatedPrincipal, idempotencyKey, useCaseName)`. 테넌트 격리가 활성이면 `tenant` 차원을 - 앞에 붙인 4-tuple 이 되고, single-tenant 모드에선 `tenant = null`. -- **여기서 막는 실패 모드**: `principal`/`useCaseName` 이 빠진 key 는 전역적으로 충돌해 다른 - caller 의 응답을 재생할 수 있다. `of` 팩토리가 blank 필수 차원을 `IdempotencyScopeMissingException` - 으로 거부해, scope 없는 key 가 store 에 닿지 못하게 막는다. 막으려는 실패 모드는 "scope 누락으로 - 인한 silent 전역 충돌"이다. -- `storageKey()` 는 진단/단일 컬럼 조회용으로 사람이 읽는 join 문자열일 뿐이다. 유일성은 차원 - 컬럼에 강제되지 이 문자열에 강제되지 않는다. +- 멱등 요청의 정체성. principal·클라이언트 key·operation code 를 **caller 가 먼저 versioned + HMAC-SHA-256 으로 digest** 한 값이다(`digest`, `keyDigestVersion`, `operationCode`). +- raw 클라이언트 key 와 principal 은 executor·store·로그·메트릭 어디에도 닿지 않는다. 예외 + 메시지의 진단 문자열도 이 digest 로만 만든다. +- digest 를 만드는 쪽(키 링, 버전 교체)은 adapter 나 유스케이스 소유다. 예: sample 의 + `HmacPosterImageIdempotencyScopeDigester`. ### RequestFingerprint @@ -296,48 +268,31 @@ application 계층이 in-flight 대기·replay **정책** 을 소유하고, 저 - `NoSuchAlgorithmException` catch 는 도달 불가다(SHA-256 은 모든 JDK 에 필수). 그래서 `IllegalStateException` 으로 감싼다. -### 멱등성 값/계약 타입 (Context · Record · StoredResponse · Codec · Status · Sleeper) +### 멱등성 값/계약 타입 (StoredResponse · Codec · Action) -- `IdempotencyContext` — executor 입력. scope + fingerprint + 선택적 per-use-case TTL - override(D6). 결제/송금 같은 장기 유스케이스가 72h 캡까지 override 가능하고, 캡 초과는 executor 가 - 거부한다. -- `IdempotencyRecord` — application 이 보는 영속 record. `COMPLETED` 면 반드시 response 를 - 동반해야 한다(생성자가 강제). adapter 가 테이블 행과 매핑한다. - `StoredResponse` — 완료된 응답의 불투명 직렬화 표현으로, 중복 caller 에게 그대로 재생된다(§B). - **어디에** 물리 저장되는지(작으면 행 인라인 ≤8KB, 크면 object store + 행엔 ref 만 — §F/D9)는 - 전적으로 persistence adapter 관심사라 여기선 보이지 않는다 → application 계층을 transport·저장 - 중립으로 유지. + 어디에 어떻게 저장되는지는 provider 관심사다. PostgreSQL store 는 8 KiB 이하 응답만 행에 + inline 으로 저장하고, 넘으면 거부한다(별도 object store 경로는 없다). - `IdempotentResponseCodec` — 유스케이스 결과를 `StoredResponse` payload 로 직렬화/역직렬화. - application 은 wire-format 중립이다 — 구체 JSON 인코딩은 `R` 의 응답 모양을 아는 `adapter-web` - caller 가 소유하고, executor 는 그 문자열을 store 로 왕복시키기만 한다. -- `IdempotencyStatus` — `IN_FLIGHT` / `COMPLETED` 두 값. -- `Sleeper` — `Thread.sleep` 우회 인터페이스. executor 의 in-flight 폴링 대기를 결정적으로 - 테스트하기 위함(테스트 Sleeper 가 실제 시간 블로킹 대신 mutable clock 전진). + application 은 wire-format 중립이다 — 구체 JSON 인코딩은 `R` 의 응답 모양을 아는 adapter 가 + 소유하고(예: web-advanced `JsonIdempotentResponseCodec`), executor 는 그 문자열을 store 로 + 왕복시키기만 한다. +- `IdempotentAction` — 실행할 작업. 결과를 `Outcome.Success` / `RetryableNoEffect` / + `EffectUnknown` 으로 돌려준다. +- complete/fail/release 재호출은 operation ID 와 result digest 가 같을 때만 이전 결과로 재생한다. -### 멱등성 예외 3종 (공통 패턴) +### 멱등성 예외 (공통 패턴) -- `IdempotencyRequestMismatchException`(422), `IdempotencyInFlightException`(409), - `IdempotencyScopeMissingException`(400, `VALIDATION_FAILED`). -- 셋 다 **프레임워크-free, application 소유**(`AuthorizationDeniedException` 선례). web adapter 가 - 경계에서 각각의 HTTP 코드로 매핑한다. 진단 메시지는 scope storage key / 누락 차원을 **로그용으로만** - 담고, 클라이언트에는 핸들러가 고정 client-safe 메시지로 대체한다(fingerprint 자체는 노출 안 함). +- `IdempotencyRequestMismatchException`(422 `IDEMPOTENT_REQUEST_MISMATCH`), + `IdempotencyInFlightException`(409 `IDEMPOTENT_IN_FLIGHT`), + `IdempotencyUnavailableException`(store 에 닿지 못함), + `IdempotencyRecoveryRequiredException`(첫 시도가 효과를 냈는지 증명하지 못함). +- 모두 **프레임워크-free, application 소유**(`AuthorizationDeniedException` 선례). web adapter 가 + 경계에서 HTTP 코드로 매핑한다. 진단 메시지는 scope digest 만 **로그용으로** 담고, 클라이언트에는 + 핸들러가 고정 client-safe 메시지로 대체한다(fingerprint 자체는 노출 안 함). - retryable: mismatch / in-flight 모두 `false`. 클라이언트는 body 를 고치거나 결과를 polling 해야지 - 단순 재시도를 하면 안 된다. - -### Owner-safe idempotency V2 - -`idempotency.v2`는 V1의 scope-only `tryBegin/complete/discard`를 대체하는 additive contract다. -provider가 JPA인지 Redis인지와 무관하게 claim에는 secure owner token과 stable operation ID가 -필요하고, 모든 mutation은 owner/attempt/claim-operation/state-revision을 검증한다. - -- processing lease와 completed replay TTL을 분리한다. -- expired `CLAIMED`만 takeover하고 expired `EXECUTING`은 `RECOVERY_REQUIRED`로 닫는다. -- complete/fail/release는 operation ID와 result digest가 같은 재호출만 prior result로 replay한다. -- `SAME_STORE_TRANSACTIONAL` JPA profile의 response는 8 KiB 이하 inline 값만 지원한다. -- raw principal/client key는 versioned HMAC scope digest로 바꾼 뒤 adapter에 전달한다. - -V1은 rolling migration compatibility를 위해 유지된다. 새 reliability profile이 V2 claim과 V1 -scope-only mutation을 섞는 것은 금지한다. + 단순 재시도를 하면 안 된다. recovery-required 는 재생도 재실행도 안전하지 않다 — 비즈니스 + 데이터로만 판단할 수 있다. --- @@ -367,12 +322,20 @@ claim → 트랜잭션 밖에서 발행 → at-least-once 보장. 아니면 그 aggregate 의 뒤 행들은 skip 한다. `DEAD` 행도 그 aggregate 큐를 막는다(strict FIFO — 해제하려면 runbook 개입 필요). - claim 후: `status = IN_FLIGHT`, `attempt_count += 1`, - `next_attempt_at = now + inFlightTimeout`. + `next_attempt_at = now + inFlightTimeout`, `lease_owner = owner`, `lease_token += 1`. + claim 결과는 행마다 `OutboxLease(event, owner, token)`이다. - 순서: adapter 는 claim 쿼리에 `ORDER BY occurred_at ASC` 를 쓰는 게 좋고, relay 도 받은 배치를 방어적으로 재정렬한다. - **in-flight timeout 재사용(I6)**: `next_attempt_at` 컬럼을 in-flight 고아 timeout 으로 재사용한다. relay 인스턴스가 죽어 `IN_FLIGHT` 로 남은 행이 `next_attempt_at` 을 지나면 다음 폴링에서 다시 claim 가능해진다. 별도 `claimed_at` 컬럼 없이 at-least-once 전달을 보장하는 트릭. +- **lease fencing**: in-flight timeout 뒤 다른 relay 가 행을 다시 claim 할 수 있으므로 완료 + (`markPublished`/`markFailed`/`markDead`)는 lease 를 받아, 행이 아직 `IN_FLIGHT` 이고 owner·token + 이 같을 때만 적용된다. 결과는 `OutboxCompletion.APPLIED`/`STALE` 이고 `STALE` 이면 아무것도 쓰지 + 않는다. 그래서 timeout 을 넘겨 멈췄던 relay 가 행을 넘겨받은 relay 의 결과를 덮지 못한다. + relay 는 `STALE` 을 `Outcome.STALE` 로 남기고 `reportStaleCompletion` 으로 알린 뒤 넘어간다. + owner 는 relay 인스턴스마다 한 번 만든 UUID 다. fake 는 testFixtures `InMemoryOutboxStore`, + 계약은 `OutboxLeaseFencingContract`(fake 와 PostgreSQL adapter 가 같은 계약을 통과). - `countByStatus` / `oldestUnpublishedAgeSecondsByEventType` 는 메트릭 게이지 (`outbox.pending.size`, `outbox.publisher.lag`)의 데이터 소스다. 트랜잭션 밖 read-only (metric-scrape 경로)로 호출된다. @@ -455,7 +418,8 @@ claim → 트랜잭션 밖에서 발행 → at-least-once 보장. 공급한다(I12 — outbox core 는 ID 생성에 비의존). 권장 기본값은 `idempotencyKey = eventId` (per-event dedup, CloudEvents-C2). - `OutboxRelayResult` — relay 한 사이클의 결과. `claimedCount` + per-event outcome 목록. 내부 - `Outcome` enum 이 `OutboxEventStatus` 의 5값을 재사용하지 않고 3값(PUBLISHED/FAILED/DEAD)을 + `Outcome` enum 이 `OutboxEventStatus` 의 5값을 재사용하지 않고 4값(PUBLISHED/FAILED/DEAD/ + STALE — 마지막은 lease 를 잃어 결과를 쓰지 못한 경우)을 따로 두는 이유: relay 관점은 "이번 실행에서 무슨 일이 있었나" 이지 "행의 현재 영속 상태" 가 아니다(후자는 store 가 5값으로 추적). 별도 enum 이 메트릭·스케줄러 로깅 consumer 에게 relay API 를 깔끔하게 유지해 준다. @@ -466,25 +430,11 @@ claim → 트랜잭션 밖에서 발행 → at-least-once 보장. adapter에 전달하는 framework-free outbound contract. 구조화 ERROR 필드와 runbook 렌더링은 messaging adapter가 소유한다. -### Immutable outbox/polling delivery V2 +### outbox V2 (삭제됨) -`outbox.v2`는 domain event intent와 delivery state를 분리한다. - -- `NewOutboxEventV2`의 aggregate version과 deterministic ordinal이 ordering authority다. -- `OutboxAppendPortV2`는 caller의 primary write transaction에 참여하고 publication epoch와 - authority를 DB control row에서 얻는다. -- immutable event ID 충돌과 aggregate ordering tuple 충돌은 서로 다른 outcome이다. -- `OutboxPollingDeliveryPortV2`는 publish 밖의 짧은 claim/completion transaction만 소유하고 - owner/token/attempt/version/epoch CAS로 stale relay를 거절한다. -- broker publish와 DB completion 사이 ACK 유실은 stable event ID의 duplicate publish를 만들 수 - 있으므로 exactly-once delivery로 표현하지 않는다. - -### Same-store inbox - -`inbox.InboxStorePort`는 broker redelivery를 DB business mutation과 같은 transaction에서 -deduplicate한다. `RECEIVED -> PROCESSING -> COMPLETED`가 기본이며 expired `PROCESSING`은 blind -takeover하지 않는다. broker ACK는 transaction commit 이후 adapter 바깥에서만 수행하고 remote -side effect는 outbox/workflow로 옮긴다. +`outbox.v2`(immutable storage + polling delivery 포트·유스케이스)는 어떤 composition 도 조립하지 +않은 세대라 2026-09-25 에 삭제했다(`docs/capability-status.md` "제거된 코드"). 그 설계에서 가져온 +owner/token CAS 는 위 `OutboxStorePort` 의 lease fencing 이다. --- @@ -542,6 +492,12 @@ application 계층은 락 획득/해제 계약만 알고, 실제 구현은 adapt --- +## Notification R1 + +R1 오케스트레이션 타입(`dev.caskeleton.application.notification` 직속, production consumer 0건)은 +2026-09-25에 삭제했다. canonical은 `..notification.platform..`이다(NOTIF-ADR-005). 직속 패키지에는 +단순 알림 포트 `NotificationPort`·`Notification`·`NotificationChannel`만 남았다. + ## 알림 포트 (notification) ### NotificationPort diff --git a/src/application-core/build.gradle b/src/application-core/build.gradle index fda8205e..f3e94f85 100644 --- a/src/application-core/build.gradle +++ b/src/application-core/build.gradle @@ -1,7 +1,6 @@ plugins { id 'ca.java-library' id 'java-test-fixtures' - id 'ca.strict-qualification' } // Framework-free application use-case contract. Runtime dependencies are project-only; @@ -10,22 +9,19 @@ plugins { dependencies { implementation project(':shared-contract') + // Port contracts (`*Contract`) are abstract JUnit classes that fakes and adapters both extend. + testFixturesImplementation 'org.junit.jupiter:junit-jupiter-api' + testFixturesImplementation 'org.assertj:assertj-core' } -def messagingApplicationContractQualification = extensions.getByName('strictQualification').register( - 'messagingApplicationContractQualificationTest', - sourceSets.test, - [ - 'dev.caskeleton.application.messaging.contract.IntegrationEventContractContributionTest', +// Half of the root `verifyMessagingContracts`: the integration-event contract, run by name, no skips. +strictTestLanes { + lane('messagingApplicationContractQualificationTest') { + description = 'Runs exact Messaging application contract qualification tests.' + requires 'dev.caskeleton.application.messaging.contract.IntegrationEventContractContributionTest', 'dev.caskeleton.application.messaging.event.IntegrationEventDraftTest', 'dev.caskeleton.application.messaging.event.ValidatedIntegrationEventTest' - ], - rootProject.layout.buildDirectory.dir( - 'test-results/messaging-evidence/application'), - rootProject.layout.buildDirectory.dir( - 'test-results/messaging-evidence-binary/application'), - 'Runs exact Messaging application contract qualification tests.' -) -messagingApplicationContractQualification.configure { - dependsOn ':prepareMessagingContractEvidence' + rejectSkipped = true + jvmArgs '-Duser.timezone=UTC' + } } diff --git a/src/application-core/gradle.lockfile b/src/application-core/gradle.lockfile index d651dd99..4c5fc01b 100644 --- a/src/application-core/gradle.lockfile +++ b/src/application-core/gradle.lockfile @@ -35,7 +35,7 @@ io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,redisPolic io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,redisPolicyContractTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor javax.inject:javax.inject:1=annotationProcessor,redisPolicyContractTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor jaxen:jaxen:2.0.6=spotbugs -net.bytebuddy:byte-buddy:1.17.8=redisPolicyContractTestCompileClasspath,redisPolicyContractTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +net.bytebuddy:byte-buddy:1.17.8=redisPolicyContractTestCompileClasspath,redisPolicyContractTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath net.jqwik:jqwik-api:1.9.1=redisPolicyContractTestCompileClasspath,redisPolicyContractTestRuntimeClasspath net.jqwik:jqwik-engine:1.9.1=redisPolicyContractTestRuntimeClasspath net.jqwik:jqwik-time:1.9.1=redisPolicyContractTestCompileClasspath,redisPolicyContractTestRuntimeClasspath @@ -56,9 +56,9 @@ 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=redisPolicyContractTestCompileClasspath,redisPolicyContractTestRuntimeClasspath,testCompileClasspath +org.apiguardian:apiguardian-api:1.1.2=redisPolicyContractTestCompileClasspath,redisPolicyContractTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath org.assertj:assertj-core:3.27.6=redisPolicyContractTestCompileClasspath,redisPolicyContractTestRuntimeClasspath -org.assertj:assertj-core:3.27.7=testCompileClasspath,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 @@ -66,9 +66,9 @@ org.codehaus.plexus:plexus-utils:3.3.0=checkstyle org.dom4j:dom4j:2.2.0=spotbugs org.javassist:javassist:3.28.0-GA=checkstyle org.jspecify:jspecify:1.0.0=redisPolicyContractTestAnnotationProcessor,redisPolicyContractTestCompileClasspath -org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,testAnnotationProcessor,testCompileClasspath,testFixturesAnnotationProcessor +org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,testAnnotationProcessor,testCompileClasspath,testFixturesAnnotationProcessor,testFixturesCompileClasspath org.junit.jupiter:junit-jupiter-api:6.0.1=redisPolicyContractTestCompileClasspath,redisPolicyContractTestRuntimeClasspath -org.junit.jupiter:junit-jupiter-api:6.0.3=testCompileClasspath,testRuntimeClasspath +org.junit.jupiter:junit-jupiter-api:6.0.3=testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.junit.jupiter:junit-jupiter-engine:6.0.1=redisPolicyContractTestRuntimeClasspath org.junit.jupiter:junit-jupiter-engine:6.0.3=testRuntimeClasspath org.junit.jupiter:junit-jupiter-params:6.0.1=redisPolicyContractTestCompileClasspath,redisPolicyContractTestRuntimeClasspath @@ -76,16 +76,16 @@ org.junit.jupiter:junit-jupiter-params:6.0.3=testCompileClasspath,testRuntimeCla org.junit.jupiter:junit-jupiter:6.0.1=redisPolicyContractTestCompileClasspath,redisPolicyContractTestRuntimeClasspath org.junit.jupiter:junit-jupiter:6.0.3=testCompileClasspath,testRuntimeClasspath org.junit.platform:junit-platform-commons:6.0.1=redisPolicyContractTestCompileClasspath,redisPolicyContractTestRuntimeClasspath -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.1=redisPolicyContractTestRuntimeClasspath org.junit.platform:junit-platform-engine:6.0.3=testRuntimeClasspath org.junit.platform:junit-platform-launcher:6.0.1=redisPolicyContractTestRuntimeClasspath org.junit.platform:junit-platform-launcher:6.0.3=testRuntimeClasspath org.junit:junit-bom:6.0.1=redisPolicyContractTestCompileClasspath,redisPolicyContractTestRuntimeClasspath -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=redisPolicyContractTestCompileClasspath,redisPolicyContractTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath +org.opentest4j:opentest4j:1.3.0=redisPolicyContractTestCompileClasspath,redisPolicyContractTestRuntimeClasspath,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 @@ -97,4 +97,4 @@ org.slf4j:slf4j-api:2.0.18=spotbugs,spotbugsSlf4j org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j org.slf4j:slf4j-simple:2.0.18=checkstyle org.xmlresolver:xmlresolver:5.3.3=checkstyle,spotbugs -empty=compileClasspath,runtimeClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath +empty=compileClasspath,runtimeClasspath diff --git a/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheAsideExecutor.java b/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheAsideExecutor.java deleted file mode 100644 index 9b8c9712..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheAsideExecutor.java +++ /dev/null @@ -1,457 +0,0 @@ -package dev.caskeleton.application.cache; - -import java.time.Clock; -import java.time.DateTimeException; -import java.time.Instant; -import java.util.Objects; - -/** - * Framework-free cache-aside orchestration with bounded local coalescing and source concurrency. - * Construct one instance per semantic cache region so its policy and protection bounds are shared. - * - *

When optional refresh coordination is enabled, the soft-lease owner refreshes synchronously. - * This executor does not schedule an asynchronous stale-while-revalidate task. A valid stale - * contender or a valid stale request facing coordination failure returns immediately instead. - * - * @deprecated the shipped runtime does not compose this executor. The algorithm remains available - * as a verified reference, but callers must not assume template-level production support. - */ -@Deprecated -public final class CacheAsideExecutor { - - private final CacheAsidePolicy policy; - private final Clock clock; - private final CacheSingleFlight> singleFlight; - private final CacheSourceBulkhead sourceBulkhead; - private final CacheRefreshCoordinationPort refreshCoordinator; - private final CacheRefreshCoordinationPolicy refreshCoordinationPolicy; - - public CacheAsideExecutor(CacheAsidePolicy policy, Clock clock) { - this(policy, clock, null, null); - } - - public CacheAsideExecutor( - CacheAsidePolicy policy, - Clock clock, - CacheRefreshCoordinationPort refreshCoordinator, - CacheRefreshCoordinationPolicy refreshCoordinationPolicy) { - this.policy = Objects.requireNonNull(policy, "policy must be non-null"); - this.clock = Objects.requireNonNull(clock, "clock must be non-null"); - this.refreshCoordinator = refreshCoordinator; - if (refreshCoordinator == null) { - if (refreshCoordinationPolicy != null) { - throw new IllegalArgumentException("refresh coordination policy requires a coordinator"); - } - this.refreshCoordinationPolicy = null; - } else { - this.refreshCoordinationPolicy = - Objects.requireNonNull( - refreshCoordinationPolicy, "refreshCoordinationPolicy must be non-null") - .validateAgainst(policy); - } - singleFlight = - new CacheSingleFlight<>(policy.maximumInFlightSourceKeys(), policy.maximumWaitersPerKey()); - sourceBulkhead = new CacheSourceBulkhead(policy.maximumConcurrentSourceLoads()); - } - - public CacheResult getOrLoad( - K key, CacheRegionPort region, CacheSourceLoader sourceLoader) { - Objects.requireNonNull(key, "key must be non-null"); - Objects.requireNonNull(region, "region must be non-null"); - Objects.requireNonNull(sourceLoader, "sourceLoader must be non-null"); - - CacheLookup lookup = - Objects.requireNonNull(region.lookup(key), "cache lookup must be non-null"); - StaleCandidate stale = null; - boolean hardMiss = false; - RefillCondition refillCondition = RefillCondition.absent(CacheWriteCondition.unavailable()); - if (lookup instanceof CacheLookup.Hit hit) { - if (hit.freshness() == CacheLookup.Freshness.FRESH) { - return new CacheResult.FreshHit<>(hit.value(), hit.sourceRevision()); - } - if (!hit.observationToken().usable()) { - return new CacheResult.IncompatibleSchema<>( - CacheLookup.SchemaCategory.UNKNOWN_ENVELOPE, CacheLookup.SchemaPolicy.FAIL_FAST); - } - stale = - new StaleCandidate<>( - hit.value(), hit.sourceRevision(), hit.hardExpiresAt(), hit.observationToken()); - refillCondition = RefillCondition.observed(hit.observationToken(), hit.writeCondition()); - } else if (lookup instanceof CacheLookup.NegativeHit negative) { - return new CacheResult.NegativeHit<>(negative.reason()); - } else if (lookup instanceof CacheLookup.Miss miss) { - refillCondition = RefillCondition.absent(miss.writeCondition()); - hardMiss = true; - } else if (lookup instanceof CacheLookup.IncompatibleSchema incompatible) { - if (incompatible.policy() == CacheLookup.SchemaPolicy.FAIL_FAST) { - return new CacheResult.IncompatibleSchema<>(incompatible.category(), incompatible.policy()); - } - if (!incompatible.observationToken().usable()) { - return new CacheResult.IncompatibleSchema<>( - incompatible.category(), CacheLookup.SchemaPolicy.FAIL_FAST); - } - refillCondition = - RefillCondition.observed(incompatible.observationToken(), incompatible.writeCondition()); - } else if (lookup instanceof CacheLookup.Unavailable unavailable) { - refillCondition = RefillCondition.absent(unavailable.writeCondition()); - } - - RefillCondition selectedCondition = refillCondition; - StaleCandidate selectedStale = stale; - boolean selectedHardMiss = hardMiss; - CacheSingleFlight.Outcome> flight = - singleFlight.execute( - key, - policy.maximumWaitDuration(), - () -> - loadFromSource( - key, region, sourceLoader, selectedCondition, selectedStale, selectedHardMiss)); - if (flight instanceof CacheSingleFlight.Rejected> rejected) { - return new CacheResult.Rejected<>( - switch (rejected.reason()) { - case MAXIMUM_IN_FLIGHT_KEYS -> CacheResult.RejectionReason.MAXIMUM_IN_FLIGHT_KEYS; - case MAXIMUM_WAITERS -> CacheResult.RejectionReason.MAXIMUM_WAITERS; - case WAIT_TIMEOUT -> CacheResult.RejectionReason.WAIT_TIMEOUT; - }); - } - if (flight instanceof CacheSingleFlight.Interrupted>) { - return new CacheResult.Cancelled<>(); - } - SourceAttempt attempt = ((CacheSingleFlight.Completed>) flight).value(); - return toResult(attempt, stale); - } - - int inFlightWaiterCount(K key) { - return singleFlight.waiterCount(key); - } - - private SourceAttempt loadFromSource( - K key, - CacheRegionPort region, - CacheSourceLoader sourceLoader, - RefillCondition refillCondition, - StaleCandidate stale, - boolean hardMiss) { - CacheSourceBulkhead.Outcome> admitted = - sourceBulkhead.execute( - policy.sourceAdmissionWait(), - () -> invokeSource(key, region, sourceLoader, refillCondition, stale, hardMiss)); - if (admitted instanceof CacheSourceBulkhead.Rejected>) { - return new SourceRejected<>(); - } - if (admitted instanceof CacheSourceBulkhead.Interrupted>) { - return new SourceInterrupted<>(); - } - return ((CacheSourceBulkhead.Completed>) admitted).value(); - } - - private SourceAttempt invokeSource( - K key, - CacheRegionPort region, - CacheSourceLoader sourceLoader, - RefillCondition refillCondition, - StaleCandidate stale, - boolean hardMiss) { - CacheRefreshClaimAttempt ownedAttempt = null; - RefillCondition selectedCondition = refillCondition; - try { - if (shouldCoordinate(stale, hardMiss)) { - CacheRefreshClaimAttempt attempt = - Objects.requireNonNull( - refreshCoordinator.newAttempt(), "cache refresh claim attempt must be non-null"); - CacheRefreshClaimOutcome claim = claimWithOneUncertainRetry(key, attempt); - if (claim instanceof CacheRefreshClaimOutcome.Contended) { - SourceAttempt deferred = staleDeferral(stale, claim); - if (deferred != null) { - return deferred; - } - if (hardMiss - && refreshCoordinationPolicy.hardMissPolicy() - == CacheRefreshCoordinationPolicy.HardMissPolicy.BOUNDED_WAIT_THEN_SOURCE_LOAD) { - if (!boundedWait(refreshCoordinationPolicy.hardMissWait())) { - return new SourceInterrupted<>(); - } - Recheck recheck = recheck(region, key); - if (recheck.immediateResult() != null) { - return new ImmediateResult<>(recheck.immediateResult()); - } - selectedCondition = recheck.refillCondition(); - } - } else if (claim instanceof CacheRefreshClaimOutcome.Unavailable - || claim instanceof CacheRefreshClaimOutcome.Indeterminate) { - SourceAttempt deferred = staleDeferral(stale, claim); - if (deferred != null) { - return deferred; - } - } else if (claim instanceof CacheRefreshClaimOutcome.Claimed - || claim instanceof CacheRefreshClaimOutcome.AlreadyOwned) { - ownedAttempt = attempt; - Recheck recheck = recheck(region, key); - if (recheck.immediateResult() != null) { - return new ImmediateResult<>(recheck.immediateResult()); - } - selectedCondition = recheck.refillCondition(); - } - } - return invokeSourceDirect(key, region, sourceLoader, selectedCondition); - } finally { - if (ownedAttempt != null) { - Objects.requireNonNull( - refreshCoordinator.release(key, ownedAttempt), - "cache refresh release outcome must be non-null"); - } - } - } - - private SourceAttempt invokeSourceDirect( - K key, - CacheRegionPort region, - CacheSourceLoader sourceLoader, - RefillCondition refillCondition) { - Instant deadline; - try { - deadline = clock.instant().plus(policy.sourceLoadDeadline()); - } catch (DateTimeException exception) { - throw new IllegalStateException("cache source deadline cannot be represented", exception); - } - CacheCancellationToken cancellation = new CacheCancellationToken(deadline, clock); - if (cancellation.isInterrupted()) { - return new SourceInterrupted<>(); - } - - SourceLoadOutcome outcome = - Objects.requireNonNull( - sourceLoader.load(key, cancellation), "source loader outcome must be non-null"); - if (cancellation.isInterrupted() || outcome instanceof SourceLoadOutcome.Cancelled) { - return new SourceInterrupted<>(); - } - if (cancellation.isDeadlineExceeded()) { - return new SourceTimedOut<>(); - } - if (outcome instanceof SourceLoadOutcome.Loaded loaded) { - CacheRecordOutcome recorded = - Objects.requireNonNull( - region.record( - key, - loaded.value(), - new CacheRecordMetadata( - loaded.sourceRevision(), - refillCondition.intent(), - refillCondition.observationToken(), - refillCondition.writeCondition())), - "cache record outcome must be non-null"); - return new SourceResolved<>(outcome, recorded); - } - if (outcome instanceof SourceLoadOutcome.AuthoritativeAbsent absent) { - CacheRecordOutcome recorded = - Objects.requireNonNull( - region.recordAbsent( - key, - absent.reason(), - new CacheRecordMetadata( - absent.sourceRevision(), - refillCondition.intent(), - refillCondition.observationToken(), - refillCondition.writeCondition())), - "negative cache record outcome must be non-null"); - return new SourceResolved<>(outcome, recorded); - } - return new SourceResolved<>(outcome, null); - } - - private boolean shouldCoordinate(StaleCandidate stale, boolean hardMiss) { - if (refreshCoordinator == null) { - return false; - } - return stale != null - || (hardMiss - && refreshCoordinationPolicy.hardMissPolicy() - == CacheRefreshCoordinationPolicy.HardMissPolicy.BOUNDED_WAIT_THEN_SOURCE_LOAD); - } - - private CacheRefreshClaimOutcome claimWithOneUncertainRetry( - K key, CacheRefreshClaimAttempt attempt) { - CacheRefreshClaimOutcome first = - Objects.requireNonNull( - refreshCoordinator.claim(key, attempt, refreshCoordinationPolicy.leaseTimeToLive()), - "cache refresh claim outcome must be non-null"); - if (first instanceof CacheRefreshClaimOutcome.Indeterminate) { - return Objects.requireNonNull( - refreshCoordinator.claim(key, attempt, refreshCoordinationPolicy.leaseTimeToLive()), - "cache refresh claim retry outcome must be non-null"); - } - return first; - } - - private SourceAttempt staleDeferral(StaleCandidate stale, CacheRefreshClaimOutcome claim) { - if (stale != null && clock.instant().isBefore(stale.hardExpiresAt())) { - CacheResult.RefreshDeferralReason reason = - claim instanceof CacheRefreshClaimOutcome.Contended - ? CacheResult.RefreshDeferralReason.CONTENDED - : claim instanceof CacheRefreshClaimOutcome.Unavailable - ? CacheResult.RefreshDeferralReason.COORDINATION_UNAVAILABLE - : CacheResult.RefreshDeferralReason.COORDINATION_INDETERMINATE; - return new ImmediateResult<>( - new CacheResult.StaleRefreshDeferred<>(stale.value(), stale.sourceRevision(), reason)); - } - return null; - } - - private boolean boundedWait(java.time.Duration duration) { - try { - long milliseconds = duration.toMillis(); - int nanoseconds = (int) duration.minusMillis(milliseconds).toNanos(); - Thread.sleep(milliseconds, nanoseconds); - return true; - } catch (InterruptedException exception) { - Thread.currentThread().interrupt(); - return false; - } - } - - private Recheck recheck(CacheRegionPort region, K key) { - CacheLookup lookup = - Objects.requireNonNull(region.lookup(key), "cache recheck must be non-null"); - if (lookup instanceof CacheLookup.Hit hit) { - if (hit.freshness() == CacheLookup.Freshness.FRESH) { - return Recheck.immediate(new CacheResult.FreshHit<>(hit.value(), hit.sourceRevision())); - } - if (!hit.observationToken().usable()) { - return Recheck.immediate( - new CacheResult.IncompatibleSchema<>( - CacheLookup.SchemaCategory.UNKNOWN_ENVELOPE, CacheLookup.SchemaPolicy.FAIL_FAST)); - } - return Recheck.refill(RefillCondition.observed(hit.observationToken(), hit.writeCondition())); - } - if (lookup instanceof CacheLookup.NegativeHit negative) { - return Recheck.immediate(new CacheResult.NegativeHit<>(negative.reason())); - } - if (lookup instanceof CacheLookup.Miss miss) { - return Recheck.refill(RefillCondition.absent(miss.writeCondition())); - } - if (lookup instanceof CacheLookup.IncompatibleSchema incompatible) { - if (incompatible.policy() == CacheLookup.SchemaPolicy.FAIL_FAST - || !incompatible.observationToken().usable()) { - return Recheck.immediate( - new CacheResult.IncompatibleSchema<>( - incompatible.category(), CacheLookup.SchemaPolicy.FAIL_FAST)); - } - return Recheck.refill( - RefillCondition.observed(incompatible.observationToken(), incompatible.writeCondition())); - } - CacheLookup.Unavailable unavailable = (CacheLookup.Unavailable) lookup; - return Recheck.refill(RefillCondition.absent(unavailable.writeCondition())); - } - - private CacheResult toResult(SourceAttempt attempt, StaleCandidate stale) { - if (attempt instanceof ImmediateResult immediate) { - return immediate.result(); - } - if (attempt instanceof SourceRejected) { - return new CacheResult.Rejected<>(CacheResult.RejectionReason.SOURCE_OVERLOADED); - } - if (attempt instanceof SourceTimedOut) { - return new CacheResult.Rejected<>(CacheResult.RejectionReason.LOAD_TIMEOUT); - } - if (attempt instanceof SourceInterrupted) { - return new CacheResult.Cancelled<>(); - } - SourceResolved resolved = (SourceResolved) attempt; - SourceLoadOutcome outcome = resolved.outcome(); - if (outcome instanceof SourceLoadOutcome.Loaded loaded) { - return new CacheResult.LoadedFromSource<>( - loaded.value(), loaded.sourceRevision(), resolved.recordOutcome()); - } - if (outcome instanceof SourceLoadOutcome.AuthoritativeAbsent absent) { - return new CacheResult.AuthoritativeAbsent<>( - absent.reason(), absent.sourceRevision(), resolved.recordOutcome()); - } - if (outcome instanceof SourceLoadOutcome.TransientFailure transientFailure) { - if (stale != null - && policy.serveStaleOnTransientFailure() - && clock.instant().isBefore(stale.hardExpiresAt())) { - return new CacheResult.StaleFallbackAfterTransientFailure<>( - stale.value(), stale.sourceRevision(), transientFailure.failure()); - } - return new CacheResult.SourceFailed<>( - transientFailure.failure(), CacheResult.SourceFailureKind.TRANSIENT); - } - if (outcome instanceof SourceLoadOutcome.PermanentFailure permanentFailure) { - return new CacheResult.SourceFailed<>( - permanentFailure.failure(), CacheResult.SourceFailureKind.PERMANENT); - } - return new CacheResult.Cancelled<>(); - } - - private sealed interface SourceAttempt - permits SourceResolved, SourceRejected, SourceInterrupted, SourceTimedOut, ImmediateResult {} - - private record SourceResolved(SourceLoadOutcome outcome, CacheRecordOutcome recordOutcome) - implements SourceAttempt { - - private SourceResolved { - Objects.requireNonNull(outcome, "outcome must be non-null"); - } - } - - private record SourceRejected() implements SourceAttempt {} - - private record SourceInterrupted() implements SourceAttempt {} - - private record SourceTimedOut() implements SourceAttempt {} - - private record ImmediateResult(CacheResult result) implements SourceAttempt { - - private ImmediateResult { - Objects.requireNonNull(result, "result must be non-null"); - } - } - - private record StaleCandidate( - T value, - String sourceRevision, - Instant hardExpiresAt, - CacheObservationToken observationToken) { - - private StaleCandidate { - Objects.requireNonNull(value, "value must be non-null"); - Objects.requireNonNull(sourceRevision, "sourceRevision must be non-null"); - Objects.requireNonNull(hardExpiresAt, "hardExpiresAt must be non-null"); - Objects.requireNonNull(observationToken, "observationToken must be non-null"); - } - } - - private record RefillCondition( - CacheRecordIntent intent, - CacheObservationToken observationToken, - CacheWriteCondition writeCondition) { - - private RefillCondition { - Objects.requireNonNull(intent, "intent must be non-null"); - Objects.requireNonNull(observationToken, "observationToken must be non-null"); - Objects.requireNonNull(writeCondition, "writeCondition must be non-null"); - } - - private static RefillCondition absent(CacheWriteCondition writeCondition) { - return new RefillCondition( - CacheRecordIntent.ONLY_IF_ABSENT, CacheObservationToken.unavailable(), writeCondition); - } - - private static RefillCondition observed( - CacheObservationToken token, CacheWriteCondition writeCondition) { - return new RefillCondition(CacheRecordIntent.ONLY_IF_OBSERVED, token, writeCondition); - } - } - - private record Recheck(RefillCondition refillCondition, CacheResult immediateResult) { - - private static Recheck refill(RefillCondition refillCondition) { - return new Recheck<>( - Objects.requireNonNull(refillCondition, "refillCondition must be non-null"), null); - } - - private static Recheck immediate(CacheResult result) { - return new Recheck<>(null, Objects.requireNonNull(result, "result must be non-null")); - } - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheAsidePolicy.java b/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheAsidePolicy.java deleted file mode 100644 index 0890b861..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheAsidePolicy.java +++ /dev/null @@ -1,54 +0,0 @@ -package dev.caskeleton.application.cache; - -import java.time.Duration; -import java.util.Objects; - -/** Immutable per-region bounds for cache-aside fallback and local coalescing. */ -public record CacheAsidePolicy( - int maximumInFlightSourceKeys, - int maximumWaitersPerKey, - int maximumConcurrentSourceLoads, - Duration sourceAdmissionWait, - Duration sourceLoadDeadline, - boolean serveStaleOnTransientFailure) { - - private static final int MAXIMUM_COUNT_BOUND = 4096; - private static final Duration MAXIMUM_DURATION_BOUND = Duration.ofDays(30); - - public CacheAsidePolicy { - requirePositiveBound( - maximumInFlightSourceKeys, "maximumInFlightSourceKeys", MAXIMUM_COUNT_BOUND); - if (maximumWaitersPerKey < 0 || maximumWaitersPerKey > MAXIMUM_COUNT_BOUND) { - throw new IllegalArgumentException( - "maximumWaitersPerKey must be in 0.." + MAXIMUM_COUNT_BOUND); - } - requirePositiveBound( - maximumConcurrentSourceLoads, "maximumConcurrentSourceLoads", MAXIMUM_COUNT_BOUND); - requireDuration(sourceAdmissionWait, "sourceAdmissionWait", true); - requireDuration(sourceLoadDeadline, "sourceLoadDeadline", false); - } - - Duration maximumWaitDuration() { - return sourceAdmissionWait.plus(sourceLoadDeadline); - } - - private static void requirePositiveBound(int value, String field, int maximum) { - if (value < 1 || value > maximum) { - throw new IllegalArgumentException(field + " must be in 1.." + maximum); - } - } - - private static void requireDuration(Duration value, String field, boolean zeroAllowed) { - Objects.requireNonNull(value, field + " must be non-null"); - if (value.isNegative() - || (!zeroAllowed && value.isZero()) - || value.compareTo(MAXIMUM_DURATION_BOUND) > 0) { - throw new IllegalArgumentException( - field - + " must be " - + (zeroAllowed ? "non-negative" : "positive") - + " and at most " - + MAXIMUM_DURATION_BOUND); - } - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheCancellationToken.java b/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheCancellationToken.java deleted file mode 100644 index 39a461f7..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheCancellationToken.java +++ /dev/null @@ -1,36 +0,0 @@ -package dev.caskeleton.application.cache; - -import java.time.Clock; -import java.time.Instant; -import java.util.Objects; - -/** - * Cooperative source-load cancellation signal. It observes the executing thread's interrupt flag - * and an immutable deadline; it cannot forcibly stop arbitrary source code. - */ -public final class CacheCancellationToken { - - private final Instant deadline; - private final Clock clock; - - CacheCancellationToken(Instant deadline, Clock clock) { - this.deadline = Objects.requireNonNull(deadline, "deadline must be non-null"); - this.clock = Objects.requireNonNull(clock, "clock must be non-null"); - } - - public Instant deadline() { - return deadline; - } - - public boolean isDeadlineExceeded() { - return !clock.instant().isBefore(deadline); - } - - public boolean isInterrupted() { - return Thread.currentThread().isInterrupted(); - } - - public boolean isCancellationRequested() { - return isInterrupted() || isDeadlineExceeded(); - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheObservationEvent.java b/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheObservationEvent.java deleted file mode 100644 index 4412731c..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheObservationEvent.java +++ /dev/null @@ -1,97 +0,0 @@ -package dev.caskeleton.application.cache; - -import java.time.Duration; -import java.util.Objects; - -/** - * Framework-free, cache-only diagnostic events. - * - *

Events intentionally omit semantic keys, tenant/user identifiers and provider endpoints. - * {@code cacheName} is a bounded code-owned name suitable for a low-cardinality metric tag. - */ -public sealed interface CacheObservationEvent { - - String cacheName(); - - /** One lookup at a concrete cache tier. */ - record Lookup(String cacheName, Tier tier, LookupResult result, Duration entryAge) - implements CacheObservationEvent { - - public Lookup { - cacheName = boundedCacheName(cacheName); - Objects.requireNonNull(tier, "tier must be non-null"); - Objects.requireNonNull(result, "result must be non-null"); - Objects.requireNonNull(entryAge, "entryAge must be non-null"); - if (entryAge.isNegative() || entryAge.compareTo(Duration.ofDays(30)) > 0) { - throw new IllegalArgumentException("entryAge must be between zero and 30 days"); - } - } - } - - /** A bounded local-tier eviction, flush, subscriber or generation reconciliation action. */ - record LocalMaintenance( - String cacheName, - MaintenanceAction action, - MaintenanceResult result, - MaintenanceCause cause, - int affectedEntries) - implements CacheObservationEvent { - - public LocalMaintenance { - cacheName = boundedCacheName(cacheName); - Objects.requireNonNull(action, "action must be non-null"); - Objects.requireNonNull(result, "result must be non-null"); - Objects.requireNonNull(cause, "cause must be non-null"); - if (affectedEntries < 0 || affectedEntries > 1_000_000) { - throw new IllegalArgumentException("affectedEntries must be in 0..1000000"); - } - } - } - - enum Tier { - LOCAL_L1, - REDIS_L2 - } - - enum LookupResult { - HIT, - MISS, - ERROR, - BYPASS - } - - enum MaintenanceAction { - EVICT, - FLUSH, - RECONCILE, - SUBSCRIBER_EVENT - } - - enum MaintenanceResult { - SUCCESS, - FLUSHED, - DROPPED, - ERROR, - UNCHANGED - } - - enum MaintenanceCause { - CARDINALITY, - WEIGHT, - TTL, - INVALIDATION, - GENERATION_CHANGED, - SUBSCRIBER_DISCONNECTED, - SUBSCRIBER_OVERFLOW, - MALFORMED_MESSAGE, - RECONCILIATION_FAILURE - } - - private static String boundedCacheName(String value) { - if (value == null || !value.matches("[a-z][a-z0-9-]{0,62}")) { - throw new IllegalArgumentException( - "cacheName must be a code-owned lower-case slug with 1..63 characters"); - } - return value; - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheObservationPort.java b/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheObservationPort.java deleted file mode 100644 index 17d82281..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheObservationPort.java +++ /dev/null @@ -1,8 +0,0 @@ -package dev.caskeleton.application.cache; - -/** Framework-free output boundary for low-cardinality cache diagnostics. */ -@FunctionalInterface -public interface CacheObservationPort { - - void observe(CacheObservationEvent event); -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheRefreshClaimAttempt.java b/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheRefreshClaimAttempt.java deleted file mode 100644 index a8dcf7de..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheRefreshClaimAttempt.java +++ /dev/null @@ -1,35 +0,0 @@ -package dev.caskeleton.application.cache; - -import java.util.Objects; - -/** Owner plus operation identities that must be reused for an uncertain claim retry. */ -public record CacheRefreshClaimAttempt( - CacheRefreshOwnerToken ownerToken, CacheRefreshOperationToken operationToken) { - - private static final CacheRefreshClaimAttempt UNAVAILABLE = - new CacheRefreshClaimAttempt( - CacheRefreshOwnerToken.unavailable(), CacheRefreshOperationToken.unavailable()); - - public CacheRefreshClaimAttempt { - Objects.requireNonNull(ownerToken, "ownerToken must be non-null"); - Objects.requireNonNull(operationToken, "operationToken must be non-null"); - if (ownerToken.usable() != operationToken.usable()) { - throw new IllegalArgumentException("refresh claim attempt tokens must have equal usability"); - } - } - - public static CacheRefreshClaimAttempt unavailable() { - return UNAVAILABLE; - } - - public boolean usable() { - return ownerToken.usable(); - } - - @Override - public String toString() { - return usable() - ? "CacheRefreshClaimAttempt[redacted]" - : "CacheRefreshClaimAttempt[unavailable]"; - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheRefreshClaimOutcome.java b/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheRefreshClaimOutcome.java deleted file mode 100644 index f38602ea..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheRefreshClaimOutcome.java +++ /dev/null @@ -1,42 +0,0 @@ -package dev.caskeleton.application.cache; - -import java.util.Objects; - -/** Provider-neutral result of attempting to own a cache-refresh soft lease. */ -public sealed interface CacheRefreshClaimOutcome - permits CacheRefreshClaimOutcome.Claimed, - CacheRefreshClaimOutcome.AlreadyOwned, - CacheRefreshClaimOutcome.Contended, - CacheRefreshClaimOutcome.Disabled, - CacheRefreshClaimOutcome.Unavailable, - CacheRefreshClaimOutcome.Indeterminate { - - record Claimed(CacheRefreshClaimAttempt attempt) implements CacheRefreshClaimOutcome { - - public Claimed { - requireUsable(attempt); - } - } - - record AlreadyOwned(CacheRefreshClaimAttempt attempt) implements CacheRefreshClaimOutcome { - - public AlreadyOwned { - requireUsable(attempt); - } - } - - record Contended() implements CacheRefreshClaimOutcome {} - - record Disabled() implements CacheRefreshClaimOutcome {} - - record Unavailable() implements CacheRefreshClaimOutcome {} - - record Indeterminate() implements CacheRefreshClaimOutcome {} - - private static void requireUsable(CacheRefreshClaimAttempt attempt) { - Objects.requireNonNull(attempt, "attempt must be non-null"); - if (!attempt.usable()) { - throw new IllegalArgumentException("owned refresh claim requires a usable attempt"); - } - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheRefreshCoordinationPolicy.java b/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheRefreshCoordinationPolicy.java deleted file mode 100644 index 33e40f85..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheRefreshCoordinationPolicy.java +++ /dev/null @@ -1,47 +0,0 @@ -package dev.caskeleton.application.cache; - -import java.time.Duration; -import java.util.Objects; - -/** Finite soft-lease and hard-miss behavior for optional distributed refresh coordination. */ -public record CacheRefreshCoordinationPolicy( - Duration leaseTimeToLive, HardMissPolicy hardMissPolicy, Duration hardMissWait) { - - private static final Duration MAXIMUM_LEASE = Duration.ofMinutes(5); - private static final Duration MAXIMUM_HARD_MISS_WAIT = Duration.ofSeconds(5); - - public CacheRefreshCoordinationPolicy { - Objects.requireNonNull(leaseTimeToLive, "leaseTimeToLive must be non-null"); - Objects.requireNonNull(hardMissPolicy, "hardMissPolicy must be non-null"); - Objects.requireNonNull(hardMissWait, "hardMissWait must be non-null"); - if (leaseTimeToLive.isZero() - || leaseTimeToLive.isNegative() - || leaseTimeToLive.compareTo(MAXIMUM_LEASE) > 0) { - throw new IllegalArgumentException( - "refresh lease TTL must be positive and at most 5 minutes"); - } - if (hardMissWait.isNegative() || hardMissWait.compareTo(MAXIMUM_HARD_MISS_WAIT) > 0) { - throw new IllegalArgumentException("hard miss wait must be between zero and 5 seconds"); - } - if (hardMissPolicy == HardMissPolicy.NORMAL_SOURCE_LOAD && !hardMissWait.isZero()) { - throw new IllegalArgumentException("normal hard miss source load requires zero wait"); - } - if (hardMissPolicy == HardMissPolicy.BOUNDED_WAIT_THEN_SOURCE_LOAD && hardMissWait.isZero()) { - throw new IllegalArgumentException("bounded hard miss wait must be positive"); - } - } - - public CacheRefreshCoordinationPolicy validateAgainst(CacheAsidePolicy cacheAsidePolicy) { - Objects.requireNonNull(cacheAsidePolicy, "cacheAsidePolicy must be non-null"); - if (leaseTimeToLive.compareTo(cacheAsidePolicy.sourceLoadDeadline()) <= 0) { - throw new IllegalArgumentException( - "refresh lease TTL must be longer than the source load deadline"); - } - return this; - } - - public enum HardMissPolicy { - NORMAL_SOURCE_LOAD, - BOUNDED_WAIT_THEN_SOURCE_LOAD - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheRefreshCoordinationPort.java b/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheRefreshCoordinationPort.java deleted file mode 100644 index 22f3443e..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheRefreshCoordinationPort.java +++ /dev/null @@ -1,20 +0,0 @@ -package dev.caskeleton.application.cache; - -import java.time.Duration; - -/** - * Optional soft-lease coordination for cache refresh admission. - * - *

This port reduces duplicate refresh work. It is not a correctness lock and must not protect - * domain invariants. The claim owner performs its source refresh synchronously; only a stale - * contender or a stale request facing coordination failure returns immediately with a deferral - * result. - */ -public interface CacheRefreshCoordinationPort { - - CacheRefreshClaimAttempt newAttempt(); - - CacheRefreshClaimOutcome claim(K key, CacheRefreshClaimAttempt attempt, Duration leaseTimeToLive); - - CacheRefreshReleaseOutcome release(K key, CacheRefreshClaimAttempt attempt); -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheRefreshOperationToken.java b/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheRefreshOperationToken.java deleted file mode 100644 index 970f0d04..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheRefreshOperationToken.java +++ /dev/null @@ -1,62 +0,0 @@ -package dev.caskeleton.application.cache; - -import java.util.Objects; - -/** Opaque idempotency identity reused when a refresh-claim response is uncertain. */ -public final class CacheRefreshOperationToken { - - private static final CacheRefreshOperationToken UNAVAILABLE = new CacheRefreshOperationToken(); - - private final String value; - - public CacheRefreshOperationToken(String value) { - this.value = validate(value); - } - - private CacheRefreshOperationToken() { - value = null; - } - - public static CacheRefreshOperationToken unavailable() { - return UNAVAILABLE; - } - - public boolean usable() { - return value != null; - } - - public String value() { - if (!usable()) { - throw new IllegalStateException("cache refresh operation token is unavailable"); - } - return value; - } - - @Override - public boolean equals(Object candidate) { - return candidate instanceof CacheRefreshOperationToken other - && Objects.equals(value, other.value); - } - - @Override - public int hashCode() { - return Objects.hashCode(value); - } - - @Override - public String toString() { - return usable() - ? "CacheRefreshOperationToken[redacted]" - : "CacheRefreshOperationToken[unavailable]"; - } - - private static String validate(String value) { - if (value == null - || !value.matches("[A-Za-z0-9_-]{16,128}") - || value.codePoints().anyMatch(Character::isISOControl)) { - throw new IllegalArgumentException( - "operation token must contain 16..128 URL-safe non-control characters"); - } - return value; - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheRefreshOwnerToken.java b/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheRefreshOwnerToken.java deleted file mode 100644 index da41c75c..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheRefreshOwnerToken.java +++ /dev/null @@ -1,59 +0,0 @@ -package dev.caskeleton.application.cache; - -import java.util.Objects; - -/** Opaque owner identity for one bounded cache-refresh soft lease. */ -public final class CacheRefreshOwnerToken { - - private static final CacheRefreshOwnerToken UNAVAILABLE = new CacheRefreshOwnerToken(); - - private final String value; - - public CacheRefreshOwnerToken(String value) { - this.value = validate(value, "owner token"); - } - - private CacheRefreshOwnerToken() { - value = null; - } - - public static CacheRefreshOwnerToken unavailable() { - return UNAVAILABLE; - } - - public boolean usable() { - return value != null; - } - - public String value() { - if (!usable()) { - throw new IllegalStateException("cache refresh owner token is unavailable"); - } - return value; - } - - @Override - public boolean equals(Object candidate) { - return candidate instanceof CacheRefreshOwnerToken other && Objects.equals(value, other.value); - } - - @Override - public int hashCode() { - return Objects.hashCode(value); - } - - @Override - public String toString() { - return usable() ? "CacheRefreshOwnerToken[redacted]" : "CacheRefreshOwnerToken[unavailable]"; - } - - private static String validate(String value, String field) { - if (value == null - || !value.matches("[A-Za-z0-9_-]{16,128}") - || value.codePoints().anyMatch(Character::isISOControl)) { - throw new IllegalArgumentException( - field + " must contain 16..128 URL-safe non-control characters"); - } - return value; - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheRefreshReleaseOutcome.java b/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheRefreshReleaseOutcome.java deleted file mode 100644 index 6f02ae6e..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheRefreshReleaseOutcome.java +++ /dev/null @@ -1,23 +0,0 @@ -package dev.caskeleton.application.cache; - -/** Provider-neutral owner-safe release result for a cache-refresh soft lease. */ -public sealed interface CacheRefreshReleaseOutcome - permits CacheRefreshReleaseOutcome.Released, - CacheRefreshReleaseOutcome.AlreadyReleased, - CacheRefreshReleaseOutcome.NotOwner, - CacheRefreshReleaseOutcome.Disabled, - CacheRefreshReleaseOutcome.Unavailable, - CacheRefreshReleaseOutcome.Indeterminate { - - record Released() implements CacheRefreshReleaseOutcome {} - - record AlreadyReleased() implements CacheRefreshReleaseOutcome {} - - record NotOwner() implements CacheRefreshReleaseOutcome {} - - record Disabled() implements CacheRefreshReleaseOutcome {} - - record Unavailable() implements CacheRefreshReleaseOutcome {} - - record Indeterminate() implements CacheRefreshReleaseOutcome {} -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheResult.java b/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheResult.java deleted file mode 100644 index 5258a7c5..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheResult.java +++ /dev/null @@ -1,131 +0,0 @@ -package dev.caskeleton.application.cache; - -import java.util.Objects; - -/** End-to-end cache-aside result without provider or transport types. */ -public sealed interface CacheResult - permits CacheResult.FreshHit, - CacheResult.NegativeHit, - CacheResult.LoadedFromSource, - CacheResult.AuthoritativeAbsent, - CacheResult.StaleFallbackAfterTransientFailure, - CacheResult.StaleRefreshDeferred, - CacheResult.SourceFailed, - CacheResult.Rejected, - CacheResult.Cancelled, - CacheResult.IncompatibleSchema { - - record FreshHit(V value, String sourceRevision) implements CacheResult { - - public FreshHit { - Objects.requireNonNull(value, "value must be non-null"); - requireSourceRevision(sourceRevision); - } - } - - record NegativeHit(dev.caskeleton.application.cache.AuthoritativeAbsence reason) - implements CacheResult { - - public NegativeHit { - Objects.requireNonNull(reason, "reason must be non-null"); - } - } - - record LoadedFromSource(V value, String sourceRevision, CacheRecordOutcome recordOutcome) - implements CacheResult { - - public LoadedFromSource { - Objects.requireNonNull(value, "value must be non-null"); - requireSourceRevision(sourceRevision); - Objects.requireNonNull(recordOutcome, "recordOutcome must be non-null"); - } - } - - record AuthoritativeAbsent( - dev.caskeleton.application.cache.AuthoritativeAbsence reason, - String sourceRevision, - CacheRecordOutcome recordOutcome) - implements CacheResult { - - public AuthoritativeAbsent { - Objects.requireNonNull(reason, "reason must be non-null"); - requireSourceRevision(sourceRevision); - Objects.requireNonNull(recordOutcome, "recordOutcome must be non-null"); - } - } - - record StaleFallbackAfterTransientFailure( - V value, String sourceRevision, SourceFailure failure) implements CacheResult { - - public StaleFallbackAfterTransientFailure { - Objects.requireNonNull(value, "value must be non-null"); - requireSourceRevision(sourceRevision); - Objects.requireNonNull(failure, "failure must be non-null"); - } - } - - record StaleRefreshDeferred(V value, String sourceRevision, RefreshDeferralReason reason) - implements CacheResult { - - public StaleRefreshDeferred { - Objects.requireNonNull(value, "value must be non-null"); - requireSourceRevision(sourceRevision); - Objects.requireNonNull(reason, "reason must be non-null"); - } - } - - record SourceFailed(SourceFailure failure, SourceFailureKind kind) implements CacheResult { - - public SourceFailed { - Objects.requireNonNull(failure, "failure must be non-null"); - Objects.requireNonNull(kind, "kind must be non-null"); - } - } - - record Rejected(RejectionReason reason) implements CacheResult { - - public Rejected { - Objects.requireNonNull(reason, "reason must be non-null"); - } - } - - record Cancelled() implements CacheResult {} - - record IncompatibleSchema(CacheLookup.SchemaCategory category, CacheLookup.SchemaPolicy policy) - implements CacheResult { - - public IncompatibleSchema { - Objects.requireNonNull(category, "category must be non-null"); - Objects.requireNonNull(policy, "policy must be non-null"); - } - } - - enum SourceFailureKind { - TRANSIENT, - PERMANENT - } - - enum RejectionReason { - MAXIMUM_IN_FLIGHT_KEYS, - MAXIMUM_WAITERS, - SOURCE_OVERLOADED, - WAIT_TIMEOUT, - LOAD_TIMEOUT - } - - enum RefreshDeferralReason { - CONTENDED, - COORDINATION_UNAVAILABLE, - COORDINATION_INDETERMINATE - } - - private static void requireSourceRevision(String sourceRevision) { - if (sourceRevision == null - || sourceRevision.isBlank() - || sourceRevision.length() > 128 - || sourceRevision.codePoints().anyMatch(Character::isISOControl)) { - throw new IllegalArgumentException( - "sourceRevision must contain 1..128 non-control characters"); - } - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheSingleFlight.java b/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheSingleFlight.java deleted file mode 100644 index 18b34b90..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheSingleFlight.java +++ /dev/null @@ -1,210 +0,0 @@ -package dev.caskeleton.application.cache; - -import java.time.Duration; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.LongSupplier; -import java.util.function.Supplier; - -/** Bounded, synchronous local coalescing for one semantic cache region. */ -public final class CacheSingleFlight { - - private static final int MAXIMUM_BOUND = 4096; - - private final int maximumInFlightKeys; - private final int maximumWaitersPerKey; - private final LongSupplier monotonicTicker; - private final Map> flights = new HashMap<>(); - - public CacheSingleFlight(int maximumInFlightKeys, int maximumWaitersPerKey) { - this(maximumInFlightKeys, maximumWaitersPerKey, System::nanoTime); - } - - CacheSingleFlight( - int maximumInFlightKeys, int maximumWaitersPerKey, LongSupplier monotonicTicker) { - if (maximumInFlightKeys < 1 || maximumInFlightKeys > MAXIMUM_BOUND) { - throw new IllegalArgumentException("maximumInFlightKeys must be in 1.." + MAXIMUM_BOUND); - } - if (maximumWaitersPerKey < 0 || maximumWaitersPerKey > MAXIMUM_BOUND) { - throw new IllegalArgumentException("maximumWaitersPerKey must be in 0.." + MAXIMUM_BOUND); - } - this.maximumInFlightKeys = maximumInFlightKeys; - this.maximumWaitersPerKey = maximumWaitersPerKey; - this.monotonicTicker = - Objects.requireNonNull(monotonicTicker, "monotonicTicker must be non-null"); - } - - public Outcome execute(K key, Duration waiterTimeout, Supplier leaderAction) { - Objects.requireNonNull(key, "key must be non-null"); - Objects.requireNonNull(waiterTimeout, "waiterTimeout must be non-null"); - Objects.requireNonNull(leaderAction, "leaderAction must be non-null"); - if (waiterTimeout.isNegative()) { - throw new IllegalArgumentException("waiterTimeout must be non-negative"); - } - - Flight flight; - boolean leader; - synchronized (flights) { - long monotonicNow = monotonicTicker.getAsLong(); - flight = flights.get(key); - if (flight != null && flight.isAbandonedAt(monotonicNow)) { - flights.remove(key, flight); - flight = null; - } - if (flight == null) { - if (flights.size() >= maximumInFlightKeys) { - flights.values().removeIf(candidate -> candidate.isAbandonedAt(monotonicNow)); - if (flights.size() >= maximumInFlightKeys) { - return new Rejected<>(RejectionReason.MAXIMUM_IN_FLIGHT_KEYS); - } - } - flight = new Flight<>(deadlineFrom(monotonicNow, waiterTimeout)); - flights.put(key, flight); - leader = true; - } else { - leader = false; - } - } - if (!leader) { - return await(flight, waiterTimeout); - } - - try { - V value = Objects.requireNonNull(leaderAction.get(), "leader result must be non-null"); - flight.result.complete(value); - return new Completed<>(value); - } catch (RuntimeException | Error failure) { - flight.result.completeExceptionally(failure); - throw failure; - } finally { - synchronized (flights) { - flights.remove(key, flight); - } - } - } - - int inFlightCount() { - synchronized (flights) { - return flights.size(); - } - } - - int waiterCount(K key) { - synchronized (flights) { - Flight flight = flights.get(key); - return flight == null ? 0 : flight.waiters.get(); - } - } - - private Outcome await(Flight flight, Duration waiterTimeout) { - if (Thread.currentThread().isInterrupted()) { - return new Interrupted<>(); - } - if (!acquireWaiter(flight)) { - return new Rejected<>(RejectionReason.MAXIMUM_WAITERS); - } - try { - return new Completed<>( - flight.result.get(toNanosSaturated(waiterTimeout), TimeUnit.NANOSECONDS)); - } catch (TimeoutException timeout) { - return new Rejected<>(RejectionReason.WAIT_TIMEOUT); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - return new Interrupted<>(); - } catch (ExecutionException execution) { - return rethrow(execution.getCause()); - } finally { - flight.waiters.decrementAndGet(); - } - } - - private boolean acquireWaiter(Flight flight) { - while (true) { - int current = flight.waiters.get(); - if (current >= maximumWaitersPerKey) { - return false; - } - if (flight.waiters.compareAndSet(current, current + 1)) { - return true; - } - } - } - - private static long toNanosSaturated(Duration duration) { - try { - return duration.toNanos(); - } catch (ArithmeticException overflow) { - return Long.MAX_VALUE; - } - } - - private static long deadlineFrom(long monotonicNow, Duration timeout) { - long timeoutNanos = toNanosSaturated(timeout); - if (timeoutNanos == Long.MAX_VALUE) { - return Long.MAX_VALUE; - } - try { - return Math.addExact(monotonicNow, timeoutNanos); - } catch (ArithmeticException overflow) { - return Long.MAX_VALUE; - } - } - - private static Outcome rethrow(Throwable cause) { - if (cause instanceof RuntimeException runtime) { - throw runtime; - } - if (cause instanceof Error error) { - throw error; - } - throw new IllegalStateException( - "single-flight completed with an unexpected checked failure", cause); - } - - public sealed interface Outcome permits Completed, Rejected, Interrupted {} - - public record Completed(T value) implements Outcome { - - public Completed { - Objects.requireNonNull(value, "value must be non-null"); - } - } - - public record Rejected(RejectionReason reason) implements Outcome { - - public Rejected { - Objects.requireNonNull(reason, "reason must be non-null"); - } - } - - public record Interrupted() implements Outcome {} - - public enum RejectionReason { - MAXIMUM_IN_FLIGHT_KEYS, - MAXIMUM_WAITERS, - WAIT_TIMEOUT - } - - private static final class Flight { - - private final CompletableFuture result = new CompletableFuture<>(); - private final AtomicInteger waiters = new AtomicInteger(); - private final long abandonAtNanos; - - private Flight(long abandonAtNanos) { - this.abandonAtNanos = abandonAtNanos; - } - - private boolean isAbandonedAt(long monotonicNow) { - return abandonAtNanos != Long.MAX_VALUE - && monotonicNow - abandonAtNanos >= 0 - && !result.isDone(); - } - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheSourceBulkhead.java b/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheSourceBulkhead.java deleted file mode 100644 index 39454db3..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheSourceBulkhead.java +++ /dev/null @@ -1,69 +0,0 @@ -package dev.caskeleton.application.cache; - -import java.time.Duration; -import java.util.Objects; -import java.util.concurrent.Semaphore; -import java.util.concurrent.TimeUnit; -import java.util.function.Supplier; - -/** Bounded source concurrency admission shared by every key in one semantic cache region. */ -public final class CacheSourceBulkhead { - - private final Semaphore permits; - - public CacheSourceBulkhead(int maximumConcurrentLoads) { - if (maximumConcurrentLoads < 1) { - throw new IllegalArgumentException("maximumConcurrentLoads must be positive"); - } - permits = new Semaphore(maximumConcurrentLoads, true); - } - - public Outcome execute(Duration admissionWait, Supplier action) { - Objects.requireNonNull(admissionWait, "admissionWait must be non-null"); - Objects.requireNonNull(action, "action must be non-null"); - if (admissionWait.isNegative()) { - throw new IllegalArgumentException("admissionWait must be non-negative"); - } - if (Thread.currentThread().isInterrupted()) { - return new Interrupted<>(); - } - - boolean acquired; - try { - acquired = permits.tryAcquire(toNanosSaturated(admissionWait), TimeUnit.NANOSECONDS); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - return new Interrupted<>(); - } - if (!acquired) { - return new Rejected<>(); - } - try { - return new Completed<>( - Objects.requireNonNull(action.get(), "source action result must be non-null")); - } finally { - permits.release(); - } - } - - private static long toNanosSaturated(Duration duration) { - try { - return duration.toNanos(); - } catch (ArithmeticException overflow) { - return Long.MAX_VALUE; - } - } - - public sealed interface Outcome permits Completed, Rejected, Interrupted {} - - public record Completed(T value) implements Outcome { - - public Completed { - Objects.requireNonNull(value, "value must be non-null"); - } - } - - public record Rejected() implements Outcome {} - - public record Interrupted() implements Outcome {} -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheSourceLoader.java b/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheSourceLoader.java deleted file mode 100644 index 75824cd0..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/cache/CacheSourceLoader.java +++ /dev/null @@ -1,8 +0,0 @@ -package dev.caskeleton.application.cache; - -/** Loads one semantic cache key from its authoritative source. */ -@FunctionalInterface -public interface CacheSourceLoader { - - SourceLoadOutcome load(K key, CacheCancellationToken cancellation); -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/cache/DisabledCacheObservationPort.java b/src/application-core/src/main/java/dev/caskeleton/application/cache/DisabledCacheObservationPort.java deleted file mode 100644 index a3a2acc0..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/cache/DisabledCacheObservationPort.java +++ /dev/null @@ -1,18 +0,0 @@ -package dev.caskeleton.application.cache; - -/** Explicit no-op cache diagnostics adapter used when no metrics backend is installed. */ -public final class DisabledCacheObservationPort implements CacheObservationPort { - - private static final DisabledCacheObservationPort INSTANCE = new DisabledCacheObservationPort(); - - private DisabledCacheObservationPort() {} - - public static DisabledCacheObservationPort instance() { - return INSTANCE; - } - - @Override - public void observe(CacheObservationEvent event) { - // Diagnostics must never change cache semantics. - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/cache/DisabledCacheRefreshCoordinationPort.java b/src/application-core/src/main/java/dev/caskeleton/application/cache/DisabledCacheRefreshCoordinationPort.java deleted file mode 100644 index 2cd1c2a5..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/cache/DisabledCacheRefreshCoordinationPort.java +++ /dev/null @@ -1,34 +0,0 @@ -package dev.caskeleton.application.cache; - -import java.time.Duration; - -/** Explicit no-op refresh coordinator for deployments that disable distributed soft leases. */ -public final class DisabledCacheRefreshCoordinationPort - implements CacheRefreshCoordinationPort { - - private static final DisabledCacheRefreshCoordinationPort INSTANCE = - new DisabledCacheRefreshCoordinationPort<>(); - - private DisabledCacheRefreshCoordinationPort() {} - - @SuppressWarnings("unchecked") - public static DisabledCacheRefreshCoordinationPort instance() { - return (DisabledCacheRefreshCoordinationPort) INSTANCE; - } - - @Override - public CacheRefreshClaimAttempt newAttempt() { - return CacheRefreshClaimAttempt.unavailable(); - } - - @Override - public CacheRefreshClaimOutcome claim( - K key, CacheRefreshClaimAttempt attempt, Duration leaseTimeToLive) { - return new CacheRefreshClaimOutcome.Disabled(); - } - - @Override - public CacheRefreshReleaseOutcome release(K key, CacheRefreshClaimAttempt attempt) { - return new CacheRefreshReleaseOutcome.Disabled(); - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/cache/SourceFailure.java b/src/application-core/src/main/java/dev/caskeleton/application/cache/SourceFailure.java deleted file mode 100644 index 5dbee339..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/cache/SourceFailure.java +++ /dev/null @@ -1,22 +0,0 @@ -package dev.caskeleton.application.cache; - -import java.util.Objects; - -/** - * Bounded source failure classification with its original cause preserved for the application - * boundary. The cause message must not be copied into cache state, metrics, or tags. - */ -public record SourceFailure(String code, Throwable cause) { - - public SourceFailure { - if (code == null || !code.matches("[A-Z][A-Z0-9_]{0,63}")) { - throw new IllegalArgumentException("code must be a bounded uppercase failure code"); - } - Objects.requireNonNull(cause, "cause must be non-null"); - } - - @Override - public String toString() { - return "SourceFailure[code=" + code + ']'; - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/cache/SourceLoadOutcome.java b/src/application-core/src/main/java/dev/caskeleton/application/cache/SourceLoadOutcome.java deleted file mode 100644 index 82f27a1d..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/cache/SourceLoadOutcome.java +++ /dev/null @@ -1,56 +0,0 @@ -package dev.caskeleton.application.cache; - -import java.util.Objects; - -/** Business-classified result of consulting a cache region's authoritative source. */ -public sealed interface SourceLoadOutcome - permits SourceLoadOutcome.Loaded, - SourceLoadOutcome.AuthoritativeAbsent, - SourceLoadOutcome.TransientFailure, - SourceLoadOutcome.PermanentFailure, - SourceLoadOutcome.Cancelled { - - record Loaded(V value, String sourceRevision) implements SourceLoadOutcome { - - public Loaded { - Objects.requireNonNull(value, "value must be non-null"); - requireSourceRevision(sourceRevision); - } - } - - record AuthoritativeAbsent( - dev.caskeleton.application.cache.AuthoritativeAbsence reason, String sourceRevision) - implements SourceLoadOutcome { - - public AuthoritativeAbsent { - Objects.requireNonNull(reason, "reason must be non-null"); - requireSourceRevision(sourceRevision); - } - } - - record TransientFailure(SourceFailure failure) implements SourceLoadOutcome { - - public TransientFailure { - Objects.requireNonNull(failure, "failure must be non-null"); - } - } - - record PermanentFailure(SourceFailure failure) implements SourceLoadOutcome { - - public PermanentFailure { - Objects.requireNonNull(failure, "failure must be non-null"); - } - } - - record Cancelled() implements SourceLoadOutcome {} - - private static void requireSourceRevision(String sourceRevision) { - if (sourceRevision == null - || sourceRevision.isBlank() - || sourceRevision.length() > 128 - || sourceRevision.codePoints().anyMatch(Character::isISOControl)) { - throw new IllegalArgumentException( - "sourceRevision must contain 1..128 non-control characters"); - } - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/fileexport/ExportedFile.java b/src/application-core/src/main/java/dev/caskeleton/application/fileexport/ExportedFile.java deleted file mode 100644 index 6a7e7972..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/fileexport/ExportedFile.java +++ /dev/null @@ -1,39 +0,0 @@ -package dev.caskeleton.application.fileexport; - -import dev.caskeleton.application.filepublication.PublishedFileReference; -import java.util.Objects; - -/** - * Legacy receipt for a file written through {@link FileExportPort}. - * - *

The original contract exposed the server's absolute filesystem path. That made the application - * boundary depend on deployment topology and produced a value that is meaningless for SFTP, NFS - * aliases or clustered storage. The compatibility receipt now carries only an opaque publication - * reference. - * - * @param fileName the logical name the file was written under (never null/blank) - * @param reference an opaque reference that never exposes a filesystem path or provider location - * @param byteSize the written file size in bytes (never negative) - * @param rowCount the number of data rows written, excluding the header (never negative) - * @deprecated use the streaming {@link - * dev.caskeleton.application.filepublication.FilePublicationPort} contract instead - */ -@Deprecated(forRemoval = true) -public record ExportedFile( - String fileName, PublishedFileReference reference, long byteSize, long rowCount) { - - public ExportedFile { - if (fileName == null || fileName.isBlank()) { - throw new IllegalArgumentException("ExportedFile.fileName must be non-null and non-blank"); - } - Objects.requireNonNull(reference, "reference"); - if (byteSize < 0) { - throw new IllegalArgumentException( - "ExportedFile.byteSize must be non-negative, was " + byteSize); - } - if (rowCount < 0) { - throw new IllegalArgumentException( - "ExportedFile.rowCount must be non-negative, was " + rowCount); - } - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/fileexport/FileExportPort.java b/src/application-core/src/main/java/dev/caskeleton/application/fileexport/FileExportPort.java deleted file mode 100644 index 44b5be76..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/fileexport/FileExportPort.java +++ /dev/null @@ -1,33 +0,0 @@ -package dev.caskeleton.application.fileexport; - -import java.util.List; - -/** - * Legacy outbound port for exporting already-materialized tabular data as CSV. - * - *

This contract requires the caller to materialize every row in memory before the adapter is - * invoked. The replacement {@link dev.caskeleton.application.filepublication.FilePublicationPort} - * streams rows through a {@link dev.caskeleton.application.filepublication.TabularRowProducer} and - * returns an opaque publication reference. - * - * @deprecated use {@link dev.caskeleton.application.filepublication.FilePublicationPort}; this - * compatibility port retains whole-result materialization and will be removed - */ -@Deprecated(forRemoval = true) -@SuppressWarnings("removal") -public interface FileExportPort { - - /** - * Writes {@code header} + {@code rows} as a CSV file named {@code fileName} under the adapter's - * configured base directory. - * - *

Every field is escaped per RFC-4180. A {@code null} field is written as an empty field. The - * file is UTF-8 encoded. - * - * @param fileName the target logical file name; must be non-null and non-blank - * @param header the column names written as the first line; must be non-null - * @param rows the already-materialized data rows; must be non-null - * @return a legacy receipt containing an opaque reference, byte size and row count - */ - ExportedFile exportCsv(String fileName, List header, List> rows); -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/filepublication/ExportSchema.java b/src/application-core/src/main/java/dev/caskeleton/application/filepublication/ExportSchema.java deleted file mode 100644 index 2f9b4976..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/filepublication/ExportSchema.java +++ /dev/null @@ -1,65 +0,0 @@ -package dev.caskeleton.application.filepublication; - -import java.util.HashSet; -import java.util.List; -import java.util.Objects; -import java.util.Set; - -/** Ordered, versioned schema for tabular publication. */ -public record ExportSchema(String schemaId, int version, List columns) { - - public ExportSchema { - schemaId = FilePublicationValues.requireOpaque("schemaId", schemaId, 128); - if (version < 1) { - throw new IllegalArgumentException("schema version must be >= 1"); - } - if (columns == null || columns.isEmpty()) { - throw new IllegalArgumentException("schema columns must be non-empty"); - } - columns = List.copyOf(columns); - Set names = new HashSet<>(); - for (Column column : columns) { - Objects.requireNonNull(column, "schema column must be non-null"); - if (!names.add(column.name())) { - throw new IllegalArgumentException("duplicate schema column: " + column.name()); - } - } - } - - public record Column( - String name, - CellType cellType, - boolean nullable, - FormulaPolicy formulaPolicy, - int maximumUtf8Bytes) { - - public Column { - name = FilePublicationValues.requireOpaque("column name", name, 128); - // The formula policy governs cell values; the header row had no policy at all, so a column - // named "=cmd|'/c calc'!A1" was written verbatim and executed by the spreadsheet that opened - // the export. Rejecting rather than mitigating is deliberate: prefixing a header with a quote - // would silently rename the column and break whatever parses it downstream. - FilePublicationValues.requireNotFormulaShaped("column name", name); - Objects.requireNonNull(cellType, "cellType must be non-null"); - Objects.requireNonNull(formulaPolicy, "formulaPolicy must be non-null"); - if (maximumUtf8Bytes < 1) { - throw new IllegalArgumentException("maximumUtf8Bytes must be >= 1"); - } - } - } - - public enum CellType { - TEXT, - INTEGER, - DECIMAL, - BOOLEAN, - DATE, - INSTANT - } - - public enum FormulaPolicy { - ALLOW, - MITIGATE, - REJECT - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/filepublication/FileDestinationId.java b/src/application-core/src/main/java/dev/caskeleton/application/filepublication/FileDestinationId.java deleted file mode 100644 index 441b0916..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/filepublication/FileDestinationId.java +++ /dev/null @@ -1,11 +0,0 @@ -package dev.caskeleton.application.filepublication; - -/** Registered logical file destination; never a path, URI, host, or provider identifier. */ -public record FileDestinationId(String value) { - - public FileDestinationId { - if (value == null || !value.matches("[a-z][a-z0-9-]{0,62}")) { - throw new IllegalArgumentException("destinationId must match [a-z][a-z0-9-]{0,62}"); - } - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/filepublication/FilePublicationException.java b/src/application-core/src/main/java/dev/caskeleton/application/filepublication/FilePublicationException.java deleted file mode 100644 index 6b64414a..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/filepublication/FilePublicationException.java +++ /dev/null @@ -1,35 +0,0 @@ -package dev.caskeleton.application.filepublication; - -/** - * Provider-neutral publication failure. The reason is stable application-facing vocabulary; paths, - * credentials, and provider exception messages must not be embedded in it. - */ -public final class FilePublicationException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - private final Reason reason; - - public FilePublicationException(Reason reason, String message) { - super(message); - this.reason = reason; - } - - public FilePublicationException(Reason reason, String message, Throwable cause) { - super(message, cause); - this.reason = reason; - } - - public Reason reason() { - return reason; - } - - public enum Reason { - INVALID_REQUEST, - CONFLICT, - CAPACITY_EXCEEDED, - UNAVAILABLE, - CANCELLED, - PUBLISH_INDETERMINATE - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/filepublication/FilePublicationPort.java b/src/application-core/src/main/java/dev/caskeleton/application/filepublication/FilePublicationPort.java deleted file mode 100644 index b70cfb0d..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/filepublication/FilePublicationPort.java +++ /dev/null @@ -1,10 +0,0 @@ -package dev.caskeleton.application.filepublication; - -/** - * Outbound application port for publishing a bounded tabular artifact to a registered logical - * destination. - */ -public interface FilePublicationPort { - - FilePublishReceipt publish(FilePublishRequest request, TabularRowProducer producer); -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/filepublication/FilePublicationValues.java b/src/application-core/src/main/java/dev/caskeleton/application/filepublication/FilePublicationValues.java deleted file mode 100644 index aed1e973..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/filepublication/FilePublicationValues.java +++ /dev/null @@ -1,45 +0,0 @@ -package dev.caskeleton.application.filepublication; - -final class FilePublicationValues { - - private FilePublicationValues() {} - - static String requireOpaque(String field, String value, int maximumLength) { - if (value == null || value.isBlank()) { - throw new IllegalArgumentException(field + " must be non-null and non-blank"); - } - String normalized = value.trim(); - if (normalized.length() > maximumLength) { - throw new IllegalArgumentException(field + " exceeds " + maximumLength + " characters"); - } - if (normalized.chars().anyMatch(Character::isISOControl)) { - throw new IllegalArgumentException(field + " must not contain control characters"); - } - return normalized; - } - - /** - * Refuses a value a spreadsheet would evaluate as a formula. - * - *

A CSV is data to the producer and a program to Excel, LibreOffice and Sheets: a field - * starting with {@code =}, {@code +}, {@code -}, {@code @}, a tab or a carriage return is - * evaluated on open, and {@code =cmd|'/c calc'!A1} is a remote-code-execution vector against - * whoever opens the report. Escaping belongs to cell values, where a leading quote is invisible; - * for identifiers such as a column name there is nothing to escape into, so it is refused. - */ - static void requireNotFormulaShaped(String field, String value) { - if (value.isEmpty()) { - return; - } - char first = value.charAt(0); - if (first == '=' - || first == '+' - || first == '-' - || first == '@' - || first == '\t' - || first == '\r') { - throw new IllegalArgumentException( - field + " must not start with a spreadsheet formula character (= + - @ tab CR)"); - } - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/filepublication/FilePublishOperationId.java b/src/application-core/src/main/java/dev/caskeleton/application/filepublication/FilePublishOperationId.java deleted file mode 100644 index 47c55493..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/filepublication/FilePublishOperationId.java +++ /dev/null @@ -1,9 +0,0 @@ -package dev.caskeleton.application.filepublication; - -/** Stable opaque operation identity retained across resolution and retry. */ -public record FilePublishOperationId(String value) { - - public FilePublishOperationId { - value = FilePublicationValues.requireOpaque("operationId", value, 128); - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/filepublication/FilePublishReceipt.java b/src/application-core/src/main/java/dev/caskeleton/application/filepublication/FilePublishReceipt.java deleted file mode 100644 index d9f63f64..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/filepublication/FilePublishReceipt.java +++ /dev/null @@ -1,53 +0,0 @@ -package dev.caskeleton.application.filepublication; - -import java.time.Instant; -import java.util.Objects; - -/** Sanitized publication receipt. It intentionally contains no local/remote path or credential. */ -public record FilePublishReceipt( - FilePublishOperationId operationId, - PublishedFileReference reference, - FileDestinationId destinationId, - String publishedFileName, - FileVersion version, - String formatProfileId, - String mediaType, - String charset, - long byteSize, - long dataRowCount, - int columnCount, - String sha256, - Instant publishedAt, - PublicationGuarantee publicationGuarantee, - DurabilityGuarantee durabilityGuarantee, - long formulaMitigatedCount) { - - public FilePublishReceipt { - Objects.requireNonNull(operationId, "operationId must be non-null"); - Objects.requireNonNull(reference, "reference must be non-null"); - Objects.requireNonNull(destinationId, "destinationId must be non-null"); - publishedFileName = - FilePublicationValues.requireOpaque("publishedFileName", publishedFileName, 256); - Objects.requireNonNull(version, "version must be non-null"); - formatProfileId = FilePublicationValues.requireOpaque("formatProfileId", formatProfileId, 128); - mediaType = FilePublicationValues.requireOpaque("mediaType", mediaType, 128); - charset = FilePublicationValues.requireOpaque("charset", charset, 64); - sha256 = FilePublicationValues.requireOpaque("sha256", sha256, 64); - Objects.requireNonNull(publishedAt, "publishedAt must be non-null"); - Objects.requireNonNull(publicationGuarantee, "publicationGuarantee must be non-null"); - Objects.requireNonNull(durabilityGuarantee, "durabilityGuarantee must be non-null"); - if (byteSize < 0 || dataRowCount < 0 || columnCount < 1 || formulaMitigatedCount < 0) { - throw new IllegalArgumentException("receipt counts and sizes are out of range"); - } - } - - public enum PublicationGuarantee { - UNIQUE_ATOMIC_CREATE - } - - public enum DurabilityGuarantee { - PROCESS_LOCAL_SYNC, - FILE_AND_DIRECTORY_SYNC, - PROVIDER_ACK_ONLY - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/filepublication/FilePublishRequest.java b/src/application-core/src/main/java/dev/caskeleton/application/filepublication/FilePublishRequest.java deleted file mode 100644 index 47be9cae..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/filepublication/FilePublishRequest.java +++ /dev/null @@ -1,22 +0,0 @@ -package dev.caskeleton.application.filepublication; - -import java.util.Objects; - -/** Provider-neutral publication intent. */ -public record FilePublishRequest( - FilePublishOperationId operationId, - FileDestinationId destinationId, - LogicalFileName logicalFileName, - SourceRevision sourceRevision, - ExportSchema schema, - String formatProfileId) { - - public FilePublishRequest { - Objects.requireNonNull(operationId, "operationId must be non-null"); - Objects.requireNonNull(destinationId, "destinationId must be non-null"); - Objects.requireNonNull(logicalFileName, "logicalFileName must be non-null"); - Objects.requireNonNull(sourceRevision, "sourceRevision must be non-null"); - Objects.requireNonNull(schema, "schema must be non-null"); - formatProfileId = FilePublicationValues.requireOpaque("formatProfileId", formatProfileId, 128); - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/filepublication/FileVersion.java b/src/application-core/src/main/java/dev/caskeleton/application/filepublication/FileVersion.java deleted file mode 100644 index 8ba687f5..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/filepublication/FileVersion.java +++ /dev/null @@ -1,9 +0,0 @@ -package dev.caskeleton.application.filepublication; - -/** Opaque immutable version of a published artifact. */ -public record FileVersion(String value) { - - public FileVersion { - value = FilePublicationValues.requireOpaque("fileVersion", value, 128); - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/filepublication/LogicalFileName.java b/src/application-core/src/main/java/dev/caskeleton/application/filepublication/LogicalFileName.java deleted file mode 100644 index f0ed08c0..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/filepublication/LogicalFileName.java +++ /dev/null @@ -1,12 +0,0 @@ -package dev.caskeleton.application.filepublication; - -/** Display/naming input that cannot carry filesystem path syntax. */ -public record LogicalFileName(String value) { - - public LogicalFileName { - value = FilePublicationValues.requireOpaque("logicalFileName", value, 128); - if (value.contains("/") || value.contains("\\") || value.equals(".") || value.equals("..")) { - throw new IllegalArgumentException("logicalFileName must not contain path syntax"); - } - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/filepublication/PublishedFileReference.java b/src/application-core/src/main/java/dev/caskeleton/application/filepublication/PublishedFileReference.java deleted file mode 100644 index f27f5364..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/filepublication/PublishedFileReference.java +++ /dev/null @@ -1,9 +0,0 @@ -package dev.caskeleton.application.filepublication; - -/** Opaque reference that never exposes a filesystem path, host, or provider location. */ -public record PublishedFileReference(String value) { - - public PublishedFileReference { - value = FilePublicationValues.requireOpaque("publishedFileReference", value, 256); - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/filepublication/SourceRevision.java b/src/application-core/src/main/java/dev/caskeleton/application/filepublication/SourceRevision.java deleted file mode 100644 index 6993cd7c..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/filepublication/SourceRevision.java +++ /dev/null @@ -1,9 +0,0 @@ -package dev.caskeleton.application.filepublication; - -/** Stable source snapshot or source fingerprint selected by the application. */ -public record SourceRevision(String value) { - - public SourceRevision { - value = FilePublicationValues.requireOpaque("sourceRevision", value, 256); - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/filepublication/TabularCell.java b/src/application-core/src/main/java/dev/caskeleton/application/filepublication/TabularCell.java deleted file mode 100644 index 5dd025fa..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/filepublication/TabularCell.java +++ /dev/null @@ -1,77 +0,0 @@ -package dev.caskeleton.application.filepublication; - -import java.math.BigDecimal; -import java.time.Instant; -import java.time.LocalDate; -import java.util.Objects; - -/** Closed framework-free set of cells supported by the baseline tabular publisher. */ -public sealed interface TabularCell { - - ExportSchema.CellType cellType(); - - record TextCell(String value) implements TabularCell { - public TextCell { - Objects.requireNonNull(value, "text value must be non-null"); - } - - @Override - public ExportSchema.CellType cellType() { - return ExportSchema.CellType.TEXT; - } - } - - record IntegerCell(long value) implements TabularCell { - @Override - public ExportSchema.CellType cellType() { - return ExportSchema.CellType.INTEGER; - } - } - - record DecimalCell(BigDecimal value) implements TabularCell { - public DecimalCell { - Objects.requireNonNull(value, "decimal value must be non-null"); - } - - @Override - public ExportSchema.CellType cellType() { - return ExportSchema.CellType.DECIMAL; - } - } - - record BooleanCell(boolean value) implements TabularCell { - @Override - public ExportSchema.CellType cellType() { - return ExportSchema.CellType.BOOLEAN; - } - } - - record DateCell(LocalDate value) implements TabularCell { - public DateCell { - Objects.requireNonNull(value, "date value must be non-null"); - } - - @Override - public ExportSchema.CellType cellType() { - return ExportSchema.CellType.DATE; - } - } - - record InstantCell(Instant value) implements TabularCell { - public InstantCell { - Objects.requireNonNull(value, "instant value must be non-null"); - } - - @Override - public ExportSchema.CellType cellType() { - return ExportSchema.CellType.INSTANT; - } - } - - record NullCell() implements TabularCell { - @Override - public ExportSchema.CellType cellType() { - throw new IllegalStateException("null cells do not have a concrete cell type"); - } - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/filepublication/TabularRow.java b/src/application-core/src/main/java/dev/caskeleton/application/filepublication/TabularRow.java deleted file mode 100644 index f0ded279..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/filepublication/TabularRow.java +++ /dev/null @@ -1,16 +0,0 @@ -package dev.caskeleton.application.filepublication; - -import java.util.List; -import java.util.Objects; - -/** Immutable ordered row. */ -public record TabularRow(List cells) { - - public TabularRow { - Objects.requireNonNull(cells, "cells must be non-null"); - cells = List.copyOf(cells); - if (cells.stream().anyMatch(Objects::isNull)) { - throw new IllegalArgumentException("cells must not contain null; use NullCell"); - } - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/filepublication/TabularRowProducer.java b/src/application-core/src/main/java/dev/caskeleton/application/filepublication/TabularRowProducer.java deleted file mode 100644 index d4dd2d17..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/filepublication/TabularRowProducer.java +++ /dev/null @@ -1,8 +0,0 @@ -package dev.caskeleton.application.filepublication; - -/** Synchronous single-attempt producer for bounded row-by-row publication. */ -@FunctionalInterface -public interface TabularRowProducer { - - void produce(TabularRowSink sink); -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/filepublication/TabularRowSink.java b/src/application-core/src/main/java/dev/caskeleton/application/filepublication/TabularRowSink.java deleted file mode 100644 index f5b15c6d..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/filepublication/TabularRowSink.java +++ /dev/null @@ -1,9 +0,0 @@ -package dev.caskeleton.application.filepublication; - -/** Attempt-scoped non-thread-safe sink owned by the file publication adapter. */ -public interface TabularRowSink { - - void write(TabularRow row); - - void checkpoint(); -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/v2/IdempotencyClaimAttempt.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyClaimAttempt.java similarity index 93% rename from src/application-core/src/main/java/dev/caskeleton/application/idempotency/v2/IdempotencyClaimAttempt.java rename to src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyClaimAttempt.java index 7546d4cd..1bb1542a 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/v2/IdempotencyClaimAttempt.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyClaimAttempt.java @@ -1,4 +1,4 @@ -package dev.caskeleton.application.idempotency.v2; +package dev.caskeleton.application.idempotency; import dev.caskeleton.application.transaction.OperationId; import java.util.Objects; diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/v2/IdempotencyClaimOutcome.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyClaimOutcome.java similarity index 95% rename from src/application-core/src/main/java/dev/caskeleton/application/idempotency/v2/IdempotencyClaimOutcome.java rename to src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyClaimOutcome.java index a94373dd..a23fc9d2 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/v2/IdempotencyClaimOutcome.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyClaimOutcome.java @@ -1,6 +1,5 @@ -package dev.caskeleton.application.idempotency.v2; +package dev.caskeleton.application.idempotency; -import dev.caskeleton.application.idempotency.StoredResponse; import dev.caskeleton.application.transaction.OperationId; import java.time.Duration; import java.time.Instant; diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/v2/IdempotencyClaimRequest.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyClaimRequest.java similarity index 93% rename from src/application-core/src/main/java/dev/caskeleton/application/idempotency/v2/IdempotencyClaimRequest.java rename to src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyClaimRequest.java index 93d1bc88..0b270635 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/v2/IdempotencyClaimRequest.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyClaimRequest.java @@ -1,6 +1,5 @@ -package dev.caskeleton.application.idempotency.v2; +package dev.caskeleton.application.idempotency; -import dev.caskeleton.application.idempotency.RequestFingerprint; import java.time.Duration; import java.util.Objects; diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/v2/IdempotencyCompleteOutcome.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyCompleteOutcome.java similarity index 84% rename from src/application-core/src/main/java/dev/caskeleton/application/idempotency/v2/IdempotencyCompleteOutcome.java rename to src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyCompleteOutcome.java index 2bc615e9..c325e0eb 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/v2/IdempotencyCompleteOutcome.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyCompleteOutcome.java @@ -1,4 +1,4 @@ -package dev.caskeleton.application.idempotency.v2; +package dev.caskeleton.application.idempotency; /** Outcomes of an owner-safe EXECUTING to COMPLETED transition. */ public enum IdempotencyCompleteOutcome { diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyContext.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyContext.java deleted file mode 100644 index 6b10f556..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyContext.java +++ /dev/null @@ -1,33 +0,0 @@ -package dev.caskeleton.application.idempotency; - -import java.time.Duration; -import java.util.Objects; - -/** - * The per-request inputs to {@link IdempotencyExecutor#execute}: the request {@link - * IdempotencyScope identity}, its body {@link RequestFingerprint}, and an optional per-use-case TTL - * override (≤ 72h, enforced by the executor — see {@link #withTtl}). - * - * @param scope request identity (triple or tenant 4-tuple) - * @param fingerprint SHA-256 of the request body - * @param ttlOverride per-use-case TTL, or {@code null} to use the configured default - */ -public record IdempotencyContext( - IdempotencyScope scope, RequestFingerprint fingerprint, Duration ttlOverride) { - - public IdempotencyContext { - Objects.requireNonNull(scope, "scope"); - Objects.requireNonNull(fingerprint, "fingerprint"); - } - - /** Context using the executor's configured default TTL. */ - public static IdempotencyContext of(IdempotencyScope scope, RequestFingerprint fingerprint) { - return new IdempotencyContext(scope, fingerprint, null); - } - - /** Context with a per-use-case TTL override (must be ≤ 72h, enforced by the executor). */ - public static IdempotencyContext withTtl( - IdempotencyScope scope, RequestFingerprint fingerprint, Duration ttl) { - return new IdempotencyContext(scope, fingerprint, Objects.requireNonNull(ttl, "ttl")); - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyExecutor.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyExecutor.java index 25fe1aed..5800e070 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyExecutor.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyExecutor.java @@ -1,123 +1,315 @@ package dev.caskeleton.application.idempotency; -import java.time.Clock; +import dev.caskeleton.application.transaction.OperationId; import java.time.Duration; -import java.time.Instant; import java.util.Objects; import java.util.Optional; -import java.util.function.Supplier; /** - * Orchestrates idempotent execution at the application use case boundary. For a single {@link - * IdempotencyScope} it runs, in order: claim (atomic {@link IdempotencyStorePort#tryBegin - * insert-or-read}, winner runs the action once) → fingerprint mismatch ({@link - * IdempotencyRequestMismatchException}, 422) → replay of a {@link IdempotencyStatus#COMPLETED} - * record → in-flight wait up to {@link #IN_FLIGHT_WAIT} then {@link IdempotencyInFlightException} - * (409). A throwing action is {@link IdempotencyStorePort#discard discarded} so the request can be - * retried. See README for the policy details and the rationale behind the 200ms wait window. + * Owner-safe request-replay lifecycle over {@link IdempotencyStorePort}. + * + *

This contract threads the owner handle through every mutation: a confirmed transition returns + * the owner with its state revision advanced, and the next call must present that handle. + * Re-using the claim's original owner would present a stale revision, which the store is built to + * refuse — that refusal is the whole point of the compare-and-set, so a caller that defeats it has + * an owner-safe store and no owner safety. + * + *

The action runs only after a confirmed start. This preserves request-replay evidence; it does + * not create a cross-store exactly-once boundary, and nothing here should be read as claiming one. */ public final class IdempotencyExecutor { - /** In-flight wait window before a concurrent duplicate gets 409. */ - public static final Duration IN_FLIGHT_WAIT = Duration.ofMillis(200); - - /** Hard cap: a per-use-case TTL override may not exceed 72h. */ - public static final Duration MAX_TTL = Duration.ofDays(3); - - private static final Duration POLL_INTERVAL = Duration.ofMillis(20); - private final IdempotencyStorePort store; - private final Clock clock; - private final Duration defaultTtl; - private final Sleeper sleeper; + private final Duration processingLeaseTtl; + private final Duration replayTtl; + private final Duration failureRetention; + private final String responseCodecId; + private final int policyRevision; - public IdempotencyExecutor(IdempotencyStorePort store, Clock clock, Duration defaultTtl) { - this(store, clock, defaultTtl, Sleeper.realtime()); - } - - // Visible for testing: a test Sleeper advances a mutable clock so the in-flight - // wait is deterministic without blocking real time. - IdempotencyExecutor( - IdempotencyStorePort store, Clock clock, Duration defaultTtl, Sleeper sleeper) { - this.store = Objects.requireNonNull(store, "store"); - this.clock = Objects.requireNonNull(clock, "clock"); - this.defaultTtl = requireSaneTtl(defaultTtl); - this.sleeper = Objects.requireNonNull(sleeper, "sleeper"); + /** + * Creates the executor. + * + * @param store the owner-safe store + * @param processingLeaseTtl how long a claim holds the record before another caller may take over + * @param replayTtl how long a completed response is replayable + * @param failureRetention how long a failed attempt's evidence is kept + * @param responseCodecId the identifier of the codec the stored payload was written with + * @param policyRevision the replay policy revision this deployment enforces + */ + public IdempotencyExecutor( + IdempotencyStorePort store, + Duration processingLeaseTtl, + Duration replayTtl, + Duration failureRetention, + String responseCodecId, + int policyRevision) { + this.store = Objects.requireNonNull(store, "store must be non-null"); + this.processingLeaseTtl = + Objects.requireNonNull(processingLeaseTtl, "processing lease TTL must be non-null"); + this.replayTtl = Objects.requireNonNull(replayTtl, "replay TTL must be non-null"); + this.failureRetention = + Objects.requireNonNull(failureRetention, "failure retention must be non-null"); + this.responseCodecId = + Objects.requireNonNull(responseCodecId, "response codec identifier must be non-null"); + this.policyRevision = policyRevision; + if (failureRetention.isZero() || failureRetention.isNegative()) { + throw new IllegalArgumentException("the failure retention must be positive"); + } } /** - * Execute {@code action} idempotently under {@code context}, replaying a prior response when the - * scope has already been seen. + * Mints the attempt a caller retains across a lost response. * - * @throws IdempotencyRequestMismatchException same key, different body (422) - * @throws IdempotencyInFlightException a duplicate is still in flight (409) + * @param operationId the caller's operation identifier + * @return the claim attempt + */ + public IdempotencyClaimAttempt newAttempt(OperationId operationId) { + return store.newClaimAttempt(operationId); + } + + /** + * Claims the scope, runs the action once, and stores its response for replay. + * + * @param scope the digested scope; the raw client key never reaches this class + * @param fingerprint the request fingerprint a replay is checked against + * @param attempt the retained claim attempt + * @param action the action to run at most once + * @param codec serialises and deserialises the action's result + * @param the action's result type + * @return the action's result, or the replayed one */ public R execute( - IdempotencyContext context, Supplier action, IdempotentResponseCodec codec) { - Objects.requireNonNull(context, "context"); - Objects.requireNonNull(action, "action"); - Objects.requireNonNull(codec, "codec"); + IdempotencyScopeDigest scope, + RequestFingerprint fingerprint, + IdempotencyClaimAttempt attempt, + IdempotentAction action, + IdempotentResponseCodec codec) { + Objects.requireNonNull(action, "action must be non-null"); + Objects.requireNonNull(codec, "codec must be non-null"); + IdempotencyClaimRequest request = + new IdempotencyClaimRequest( + scope, + fingerprint, + attempt, + processingLeaseTtl, + replayTtl, + responseCodecId, + policyRevision); - Duration ttl = - requireSaneTtl(context.ttlOverride() != null ? context.ttlOverride() : defaultTtl); - IdempotencyScope scope = context.scope(); - RequestFingerprint fingerprint = context.fingerprint(); - Instant deadline = clock.instant().plus(IN_FLIGHT_WAIT); - - while (true) { - Instant now = clock.instant(); - Optional existing = store.find(scope, now); - - if (existing.isEmpty()) { - // No live record — try to claim the scope and own the execution. - if (store.tryBegin(scope, fingerprint, now.plus(ttl))) { - return runAndComplete(scope, action, codec); - } - // Lost the claim race (another caller inserted concurrently); loop to - // read their record. Bounded by the in-flight deadline below. - if (!now.isBefore(deadline)) { - throw new IdempotencyInFlightException(scope); - } - sleeper.sleep(POLL_INTERVAL); - continue; - } - - IdempotencyRecord record = existing.get(); - // Mismatch is terminal regardless of status: same key, different body. - if (!record.fingerprint().equals(fingerprint)) { - throw new IdempotencyRequestMismatchException(scope); - } - if (record.status() == IdempotencyStatus.COMPLETED) { - return codec.deserialize(record.response().payload()); - } - // IN_FLIGHT by another caller — wait out the window then surface 409. - if (!now.isBefore(deadline)) { - throw new IdempotencyInFlightException(scope); - } - sleeper.sleep(POLL_INTERVAL); - } + return switch (store.claim(request)) { + case IdempotencyClaimOutcome.CompletedReplay replay -> + codec.deserialize(replay.response().payload()); + case IdempotencyClaimOutcome.FingerprintMismatch ignored -> + throw IdempotencyRequestMismatchException.forScopeDigest(diagnostic(scope)); + case IdempotencyClaimOutcome.InProgress ignored -> + throw IdempotencyInFlightException.forScopeDigest(diagnostic(scope)); + case IdempotencyClaimOutcome.RecoveryRequired ignored -> + throw recovery("claim requires reconciliation"); + case IdempotencyClaimOutcome.OwnerOperationConflict ignored -> + throw recovery("claim requires reconciliation"); + case IdempotencyClaimOutcome.Unavailable ignored -> + throw new IdempotencyUnavailableException(); + // The response was lost, not the attempt. The retained attempt is what makes the record + // findable, so the only safe move is to ask the store what actually happened. + case IdempotencyClaimOutcome.Indeterminate ignored -> reconcile(request, action, codec); + case IdempotencyClaimOutcome.Acquired acquired -> + startAndRun(request, acquired.owner(), action, codec, false); + case IdempotencyClaimOutcome.ReplayedAcquire replayed -> + startAndRun(request, replayed.owner(), action, codec, false); + case IdempotencyClaimOutcome.TakenOverClaimed takenOver -> + startAndRun(request, takenOver.owner(), action, codec, false); + }; } - private R runAndComplete( - IdempotencyScope scope, Supplier action, IdempotentResponseCodec codec) { + private R reconcile( + IdempotencyClaimRequest request, + IdempotentAction action, + IdempotentResponseCodec codec) { + IdempotencyInspection inspection = inspect(request); + return switch (inspection.outcome()) { + case CLAIMED_SAME_OPERATION -> + startAndRun(request, requireOwner(inspection), action, codec, false); + case EXECUTING_SAME_OPERATION -> runStarted(request, requireOwner(inspection), action, codec); + case COMPLETED_REPLAY -> codec.deserialize(requireResponse(inspection).payload()); + case FINGERPRINT_MISMATCH -> + throw IdempotencyRequestMismatchException.forScopeDigest(diagnostic(request.scope())); + case IN_PROGRESS_OTHER -> + throw IdempotencyInFlightException.forScopeDigest(diagnostic(request.scope())); + case UNAVAILABLE -> throw new IdempotencyUnavailableException(); + // ABSENT, FAILED_RETRYABLE, ABANDONED and OPERATION_CONFLICT all mean the same thing here: + // this caller cannot prove what happened to its own attempt, and guessing is the one thing an + // owner-safe store exists to prevent. + default -> throw recovery("an indeterminate claim could not be resumed safely"); + }; + } + + private R startAndRun( + IdempotencyClaimRequest request, + IdempotencyOwner owner, + IdempotentAction action, + IdempotentResponseCodec codec, + boolean alreadyRetried) { + IdempotencyMutationResult started = + store.markExecutionStarted(owner, request.claimAttempt().operationId()); + return switch (started.outcome()) { + // The owner handle from the transition, not the one from the claim: the state revision has + // advanced and the next compare-and-set is against the new one. + case STARTED, ALREADY_STARTED_SAME_OPERATION -> + runStarted(request, advanced(started, owner), action, codec); + case UNAVAILABLE -> throw new IdempotencyUnavailableException(); + case INDETERMINATE -> { + if (alreadyRetried) { + throw recovery("execution start stayed indeterminate after reconciliation"); + } + yield resumeAfterIndeterminateStart(request, action, codec); + } + default -> throw recovery("execution start was not confirmed for this exact operation"); + }; + } + + private R resumeAfterIndeterminateStart( + IdempotencyClaimRequest request, + IdempotentAction action, + IdempotentResponseCodec codec) { + IdempotencyInspection inspection = inspect(request); + return switch (inspection.outcome()) { + case CLAIMED_SAME_OPERATION -> + startAndRun(request, requireOwner(inspection), action, codec, true); + case EXECUTING_SAME_OPERATION -> runStarted(request, requireOwner(inspection), action, codec); + case COMPLETED_REPLAY -> codec.deserialize(requireResponse(inspection).payload()); + case UNAVAILABLE -> throw new IdempotencyUnavailableException(); + default -> throw recovery("execution start is indeterminate"); + }; + } + + private R runStarted( + IdempotencyClaimRequest request, + IdempotencyOwner owner, + IdempotentAction action, + IdempotentResponseCodec codec) { + OperationId operationId = request.claimAttempt().operationId(); + IdempotentAction.Outcome outcome; try { - R result = action.get(); - store.complete(scope, new StoredResponse(codec.serialize(result))); - return result; - } catch (RuntimeException e) { - store.discard(scope); - throw e; + outcome = Objects.requireNonNull(action.run(), "action outcome must be non-null"); + } catch (RuntimeException failure) { + // The action threw without saying whether it had an effect, so the record must not say + // "retryable": that would invite a second execution of something that may already have run. + preserveUnknown(owner, operationId); + throw failure; } + return switch (outcome) { + case IdempotentAction.Outcome.Success success -> + complete(request, owner, success.result(), codec, false); + case IdempotentAction.Outcome.RetryableNoEffect retryable -> { + store.markFailed( + owner, + IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE, + failureRetention, + operationId); + throw retryable.failure(); + } + case IdempotentAction.Outcome.EffectUnknown unknown -> { + preserveUnknown(owner, operationId); + throw unknown.failure(); + } + }; } - private static Duration requireSaneTtl(Duration ttl) { - Objects.requireNonNull(ttl, "ttl"); - if (ttl.isZero() || ttl.isNegative()) { - throw new IllegalArgumentException("idempotency TTL must be positive, was " + ttl); - } - if (ttl.compareTo(MAX_TTL) > 0) { - throw new IllegalArgumentException("idempotency TTL exceeds the 72h cap (D6), was " + ttl); - } - return ttl; + private R complete( + IdempotencyClaimRequest request, + IdempotencyOwner owner, + R result, + IdempotentResponseCodec codec, + boolean alreadyRetried) { + StoredResponse response = new StoredResponse(codec.serialize(result)); + return switch (store.complete( + owner, response, replayTtl, request.claimAttempt().operationId())) { + case COMPLETED, ALREADY_COMPLETED_SAME_RESULT -> result; + case UNAVAILABLE -> throw new IdempotencyUnavailableException(); + case INDETERMINATE -> reconcileCompletion(request, result, codec, alreadyRetried); + default -> throw recovery("completion was not confirmed"); + }; + } + + /** + * Resolves a completion whose response was lost. + * + *

Deliberately does not carry the caller's owner handle forward: after an indeterminate + * completion the caller's handle may already be stale, and the only handle worth presenting is + * the one the store reports now. + */ + private R reconcileCompletion( + IdempotencyClaimRequest request, + R result, + IdempotentResponseCodec codec, + boolean alreadyRetried) { + IdempotencyInspection inspection = inspect(request); + return switch (inspection.outcome()) { + case COMPLETED_REPLAY -> { + StoredResponse stored = requireResponse(inspection); + if (stored.payload().equals(codec.serialize(result))) { + yield result; + } + // The stored response is somebody else's answer to this scope. Returning either one would + // be asserting a fact this caller cannot establish. + throw recovery("the completed response conflicts with the one this caller produced"); + } + case EXECUTING_SAME_OPERATION -> { + if (alreadyRetried) { + throw recovery("completion stayed indeterminate after reconciliation"); + } + yield complete(request, requireOwner(inspection), result, codec, true); + } + case UNAVAILABLE -> throw new IdempotencyUnavailableException(); + default -> throw recovery("the completion response is indeterminate and was not reconciled"); + }; + } + + private void preserveUnknown(IdempotencyOwner owner, OperationId operationId) { + store.markFailed( + owner, + IdempotencyFailureDisposition.EFFECT_UNKNOWN_ABANDONED, + failureRetention, + operationId); + } + + private IdempotencyInspection inspect(IdempotencyClaimRequest request) { + return store.inspect( + new IdempotencyInspectionRequest( + request.scope(), request.requestFingerprint(), request.claimAttempt())); + } + + private static IdempotencyOwner advanced( + IdempotencyMutationResult transition, IdempotencyOwner fallback) { + return transition.owner().orElse(fallback); + } + + private static IdempotencyOwner requireOwner(IdempotencyInspection inspection) { + Optional owner = inspection.owner(); + return owner.orElseThrow( + () -> + recovery( + "the store reported " + + inspection.outcome() + + " without the owner handle it needs")); + } + + private static StoredResponse requireResponse(IdempotencyInspection inspection) { + return inspection + .response() + .orElseThrow(() -> recovery("the store reported a completed replay with no response")); + } + + /** + * Renders the scope for a diagnostic. Every component is already opaque — the raw client key and + * principal were digested before the scope was constructed — so this is safe to log, and it is + * the only scope identity this lifecycle ever holds. + */ + private static String diagnostic(IdempotencyScopeDigest scope) { + return scope.operationCode() + "::v" + scope.keyDigestVersion() + "::" + scope.digest(); + } + + private static IdempotencyRecoveryRequiredException recovery(String message) { + return new IdempotencyRecoveryRequiredException(message); } } diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/v2/IdempotencyFailOutcome.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyFailOutcome.java similarity index 83% rename from src/application-core/src/main/java/dev/caskeleton/application/idempotency/v2/IdempotencyFailOutcome.java rename to src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyFailOutcome.java index b0e911dd..efee562e 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/v2/IdempotencyFailOutcome.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyFailOutcome.java @@ -1,4 +1,4 @@ -package dev.caskeleton.application.idempotency.v2; +package dev.caskeleton.application.idempotency; /** Outcomes of an owner-safe failure transition. */ public enum IdempotencyFailOutcome { diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/v2/IdempotencyFailureDisposition.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyFailureDisposition.java similarity index 79% rename from src/application-core/src/main/java/dev/caskeleton/application/idempotency/v2/IdempotencyFailureDisposition.java rename to src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyFailureDisposition.java index d1037e41..c7424b15 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/v2/IdempotencyFailureDisposition.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyFailureDisposition.java @@ -1,4 +1,4 @@ -package dev.caskeleton.application.idempotency.v2; +package dev.caskeleton.application.idempotency; /** Whether a failed action is proven retryable or requires explicit effect reconciliation. */ public enum IdempotencyFailureDisposition { diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyInFlightException.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyInFlightException.java index 041738d2..2f0c0dc1 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyInFlightException.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyInFlightException.java @@ -1,40 +1,27 @@ package dev.caskeleton.application.idempotency; /** - * Raised when a concurrent request for the same {@link IdempotencyScope} is still processing after - * the in-flight wait window elapses. Framework-free, application-owned; the web adapter maps it to - * a {@code IDEMPOTENT_IN_FLIGHT} 409 (retryable=false — the client polls). The diagnostic carries - * the scope storage key for logs only. See README. + * Raised when another attempt still holds the same {@link IdempotencyScopeDigest}. Framework-free, + * application-owned; the web adapter maps it to a {@code IDEMPOTENT_IN_FLIGHT} 409 (retryable=false + * — the client polls). The message carries only the opaque scope digest, for logs. */ public class IdempotencyInFlightException extends RuntimeException { private static final long serialVersionUID = 1L; - private final transient IdempotencyScope scope; - - public IdempotencyInFlightException(IdempotencyScope scope) { - this(scope == null ? "" : scope.storageKey(), scope); - } - /** - * Creates the exception for the owner-safe lifecycle, which never holds the raw scope: the - * principal and the client key are digested before they reach the store, so the opaque digest - * diagnostic is the only identity available. {@link #scope()} is {@code null} on this path, as it - * already is for any deserialized instance — the field is {@code transient}. + * Creates the exception from the opaque digest diagnostic — the only scope identity the + * owner-safe lifecycle holds, since the principal and client key are digested before they reach + * the store. * * @param scopeDigestDiagnostic opaque scope-digest diagnostic, for logs only * @return the exception */ public static IdempotencyInFlightException forScopeDigest(String scopeDigestDiagnostic) { - return new IdempotencyInFlightException(scopeDigestDiagnostic, null); + return new IdempotencyInFlightException(scopeDigestDiagnostic); } - private IdempotencyInFlightException(String scopeDiagnostic, IdempotencyScope scope) { + private IdempotencyInFlightException(String scopeDiagnostic) { super("idempotent request still in flight: " + scopeDiagnostic); - this.scope = scope; - } - - public IdempotencyScope scope() { - return scope; } } diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/v2/IdempotencyInspection.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyInspection.java similarity index 89% rename from src/application-core/src/main/java/dev/caskeleton/application/idempotency/v2/IdempotencyInspection.java rename to src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyInspection.java index 1e8f2ea6..00ee2523 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/v2/IdempotencyInspection.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyInspection.java @@ -1,6 +1,5 @@ -package dev.caskeleton.application.idempotency.v2; +package dev.caskeleton.application.idempotency; -import dev.caskeleton.application.idempotency.StoredResponse; import java.time.Instant; import java.util.Objects; import java.util.Optional; diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/v2/IdempotencyInspectionOutcome.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyInspectionOutcome.java similarity index 80% rename from src/application-core/src/main/java/dev/caskeleton/application/idempotency/v2/IdempotencyInspectionOutcome.java rename to src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyInspectionOutcome.java index 99a07513..7b23f7e0 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/v2/IdempotencyInspectionOutcome.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyInspectionOutcome.java @@ -1,6 +1,6 @@ -package dev.caskeleton.application.idempotency.v2; +package dev.caskeleton.application.idempotency; -/** Recovery-safe classifications returned by {@link IdempotencyStorePortV2#inspect}. */ +/** Recovery-safe classifications returned by {@link IdempotencyStorePort#inspect}. */ public enum IdempotencyInspectionOutcome { ABSENT, CLAIMED_SAME_OPERATION, diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/v2/IdempotencyInspectionRequest.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyInspectionRequest.java similarity index 80% rename from src/application-core/src/main/java/dev/caskeleton/application/idempotency/v2/IdempotencyInspectionRequest.java rename to src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyInspectionRequest.java index 1eadb5ba..a3b3f5d8 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/v2/IdempotencyInspectionRequest.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyInspectionRequest.java @@ -1,6 +1,5 @@ -package dev.caskeleton.application.idempotency.v2; +package dev.caskeleton.application.idempotency; -import dev.caskeleton.application.idempotency.RequestFingerprint; import java.util.Objects; /** Read-only recovery request after a claim or transition response was lost. */ diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/v2/IdempotencyMutationResult.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyMutationResult.java similarity index 95% rename from src/application-core/src/main/java/dev/caskeleton/application/idempotency/v2/IdempotencyMutationResult.java rename to src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyMutationResult.java index 082993af..5c8fca26 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/v2/IdempotencyMutationResult.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyMutationResult.java @@ -1,4 +1,4 @@ -package dev.caskeleton.application.idempotency.v2; +package dev.caskeleton.application.idempotency; import java.util.Objects; import java.util.Optional; diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/v2/IdempotencyOwner.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyOwner.java similarity index 95% rename from src/application-core/src/main/java/dev/caskeleton/application/idempotency/v2/IdempotencyOwner.java rename to src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyOwner.java index 5ae6bc37..2a05a334 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/v2/IdempotencyOwner.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyOwner.java @@ -1,4 +1,4 @@ -package dev.caskeleton.application.idempotency.v2; +package dev.caskeleton.application.idempotency; import dev.caskeleton.application.transaction.OperationId; import java.util.Objects; diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyRecord.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyRecord.java deleted file mode 100644 index 58748a93..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyRecord.java +++ /dev/null @@ -1,39 +0,0 @@ -package dev.caskeleton.application.idempotency; - -import java.time.Instant; -import java.util.Objects; - -/** - * A persisted idempotency record as seen by the application layer; the persistence adapter maps it - * to and from table rows. - * - * @param scope the request identity (triple or tenant 4-tuple) - * @param fingerprint SHA-256 of the original request body - * @param status lifecycle state - * @param response the stored response — present only when {@code status == COMPLETED} - * @param createdAt when the record was first claimed - * @param expiresAt TTL boundary; a record at/after this instant is treated as absent - */ -public record IdempotencyRecord( - IdempotencyScope scope, - RequestFingerprint fingerprint, - IdempotencyStatus status, - StoredResponse response, - Instant createdAt, - Instant expiresAt) { - - public IdempotencyRecord { - Objects.requireNonNull(scope, "scope"); - Objects.requireNonNull(fingerprint, "fingerprint"); - Objects.requireNonNull(status, "status"); - Objects.requireNonNull(createdAt, "createdAt"); - Objects.requireNonNull(expiresAt, "expiresAt"); - if (status == IdempotencyStatus.COMPLETED && response == null) { - throw new IllegalArgumentException("a COMPLETED record must carry a stored response"); - } - } - - public boolean isExpiredAt(Instant now) { - return !now.isBefore(expiresAt); - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/v2/IdempotencyReleaseOutcome.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyReleaseOutcome.java similarity index 85% rename from src/application-core/src/main/java/dev/caskeleton/application/idempotency/v2/IdempotencyReleaseOutcome.java rename to src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyReleaseOutcome.java index fb49dd60..952f8012 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/v2/IdempotencyReleaseOutcome.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyReleaseOutcome.java @@ -1,4 +1,4 @@ -package dev.caskeleton.application.idempotency.v2; +package dev.caskeleton.application.idempotency; /** Outcomes of releasing a claim only while business execution has not started. */ public enum IdempotencyReleaseOutcome { diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/v2/IdempotencyRenewOutcome.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyRenewOutcome.java similarity index 90% rename from src/application-core/src/main/java/dev/caskeleton/application/idempotency/v2/IdempotencyRenewOutcome.java rename to src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyRenewOutcome.java index 29d1b8b7..a48dc47c 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/v2/IdempotencyRenewOutcome.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyRenewOutcome.java @@ -1,4 +1,4 @@ -package dev.caskeleton.application.idempotency.v2; +package dev.caskeleton.application.idempotency; /** Outcomes of an owner-safe processing lease renewal. */ public enum IdempotencyRenewOutcome { diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyRequestMismatchException.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyRequestMismatchException.java index 4b9d9ab8..6edf135b 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyRequestMismatchException.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyRequestMismatchException.java @@ -2,39 +2,27 @@ package dev.caskeleton.application.idempotency; /** * Raised when an {@code Idempotency-Key} is reused with a different request body (same {@link - * IdempotencyScope}, different {@link RequestFingerprint}). Framework-free, application-owned; the - * web adapter maps it to a {@code IDEMPOTENT_REQUEST_MISMATCH} 422 (retryable=false). The - * diagnostic carries the scope storage key for logs only. See README. + * IdempotencyScopeDigest}, different {@link RequestFingerprint}). Framework-free, + * application-owned; the web adapter maps it to a {@code IDEMPOTENT_REQUEST_MISMATCH} 422 + * (retryable=false). The message carries only the opaque scope digest, for logs. */ public class IdempotencyRequestMismatchException extends RuntimeException { private static final long serialVersionUID = 1L; - private final transient IdempotencyScope scope; - - public IdempotencyRequestMismatchException(IdempotencyScope scope) { - this(scope == null ? "" : scope.storageKey(), scope); - } - /** - * Creates the exception for the owner-safe lifecycle, which never holds the raw scope: the - * principal and the client key are digested before they reach the store, so the opaque digest - * diagnostic is the only identity available. {@link #scope()} is {@code null} on this path, as it - * already is for any deserialized instance — the field is {@code transient}. + * Creates the exception from the opaque digest diagnostic — the only scope identity the + * owner-safe lifecycle holds, since the principal and client key are digested before they reach + * the store. * * @param scopeDigestDiagnostic opaque scope-digest diagnostic, for logs only * @return the exception */ public static IdempotencyRequestMismatchException forScopeDigest(String scopeDigestDiagnostic) { - return new IdempotencyRequestMismatchException(scopeDigestDiagnostic, null); + return new IdempotencyRequestMismatchException(scopeDigestDiagnostic); } - private IdempotencyRequestMismatchException(String scopeDiagnostic, IdempotencyScope scope) { + private IdempotencyRequestMismatchException(String scopeDiagnostic) { super("idempotency key reused with a different request body: " + scopeDiagnostic); - this.scope = scope; - } - - public IdempotencyScope scope() { - return scope; } } diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyScope.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyScope.java deleted file mode 100644 index 89f32dd0..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyScope.java +++ /dev/null @@ -1,54 +0,0 @@ -package dev.caskeleton.application.idempotency; - -/** - * Identity of an idempotent request: the triple {@code (principal, idempotencyKey, useCaseName)}, - * or a 4-tuple with a leading {@code tenant} when tenant isolation is active ({@code null} - * otherwise). The {@link #of} factory rejects blank required dimensions with {@link - * IdempotencyScopeMissingException}. See README for the global-collision failure mode. - * - * @param tenant tenant id, or {@code null} in single-tenant mode - * @param principal authenticated principal (pseudonymized) - * @param idempotencyKey the client-supplied {@code Idempotency-Key} value - * @param useCaseName the {@code application-core} use case identifier - */ -public record IdempotencyScope( - String tenant, String principal, String idempotencyKey, String useCaseName) { - - /** Single-tenant triple scope. */ - public static IdempotencyScope of(String principal, String idempotencyKey, String useCaseName) { - return of(null, principal, idempotencyKey, useCaseName); - } - - /** - * Tenant-aware scope. {@code tenant} may be {@code null} (single-tenant); the other three - * dimensions are mandatory and rejected when blank. - */ - public static IdempotencyScope of( - String tenant, String principal, String idempotencyKey, String useCaseName) { - requirePresent("principal", principal); - requirePresent("idempotencyKey", idempotencyKey); - requirePresent("useCaseName", useCaseName); - String normalizedTenant = (tenant == null || tenant.isBlank()) ? null : tenant; - return new IdempotencyScope(normalizedTenant, principal, idempotencyKey, useCaseName); - } - - private static void requirePresent(String dimension, String value) { - if (value == null || value.isBlank()) { - throw new IdempotencyScopeMissingException(dimension); - } - } - - /** True when this scope carries a tenant dimension (4-tuple form). */ - public boolean isTenantScoped() { - return tenant != null; - } - - /** - * Stable storage key for diagnostics / single-column lookups. The persistence adapter enforces - * uniqueness on the dimension columns, not on this string; this is a human-readable join only. - */ - public String storageKey() { - String prefix = tenant == null ? "" : tenant + "::"; - return prefix + principal + "::" + idempotencyKey + "::" + useCaseName; - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/v2/IdempotencyScopeDigest.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyScopeDigest.java similarity index 96% rename from src/application-core/src/main/java/dev/caskeleton/application/idempotency/v2/IdempotencyScopeDigest.java rename to src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyScopeDigest.java index 123f9e1a..e0ae6c52 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/v2/IdempotencyScopeDigest.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyScopeDigest.java @@ -1,4 +1,4 @@ -package dev.caskeleton.application.idempotency.v2; +package dev.caskeleton.application.idempotency; import java.util.Objects; import java.util.regex.Pattern; diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyScopeMissingException.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyScopeMissingException.java deleted file mode 100644 index 72dbbbbd..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyScopeMissingException.java +++ /dev/null @@ -1,22 +0,0 @@ -package dev.caskeleton.application.idempotency; - -/** - * Raised when an idempotency request omits a required scope dimension. Framework-free, - * application-owned; the web adapter maps it to a {@code VALIDATION_FAILED} 400. The diagnostic - * names the missing dimension for logs only. See README. - */ -public class IdempotencyScopeMissingException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - private final String missingDimension; - - public IdempotencyScopeMissingException(String missingDimension) { - super("idempotency scope is incomplete: '" + missingDimension + "' is blank"); - this.missingDimension = missingDimension; - } - - public String missingDimension() { - return missingDimension; - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/v2/IdempotencyStartOutcome.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyStartOutcome.java similarity index 90% rename from src/application-core/src/main/java/dev/caskeleton/application/idempotency/v2/IdempotencyStartOutcome.java rename to src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyStartOutcome.java index 21b1b5fa..c7a1eaed 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/v2/IdempotencyStartOutcome.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyStartOutcome.java @@ -1,4 +1,4 @@ -package dev.caskeleton.application.idempotency.v2; +package dev.caskeleton.application.idempotency; /** Outcomes of the CLAIMED to EXECUTING owner-safe transition. */ public enum IdempotencyStartOutcome { diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/v2/IdempotencyState.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyState.java similarity index 50% rename from src/application-core/src/main/java/dev/caskeleton/application/idempotency/v2/IdempotencyState.java rename to src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyState.java index 52c27dfb..e6a21775 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/v2/IdempotencyState.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyState.java @@ -1,6 +1,6 @@ -package dev.caskeleton.application.idempotency.v2; +package dev.caskeleton.application.idempotency; -/** Owner-safe idempotency V2 state machine. */ +/** Owner-safe idempotency state machine. */ public enum IdempotencyState { CLAIMED, EXECUTING, diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyStatus.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyStatus.java deleted file mode 100644 index d9249b8f..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyStatus.java +++ /dev/null @@ -1,15 +0,0 @@ -package dev.caskeleton.application.idempotency; - -/** - * Lifecycle of an idempotency record. - * - *

    - *
  • {@link #IN_FLIGHT} — a caller has claimed the scope and is executing the action; concurrent - * arrivals wait then receive 409. - *
  • {@link #COMPLETED} — the action finished and the response is stored for replay. - *
- */ -public enum IdempotencyStatus { - IN_FLIGHT, - COMPLETED -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyStorePort.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyStorePort.java index a9292a6e..0f2be4bf 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyStorePort.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyStorePort.java @@ -1,43 +1,36 @@ package dev.caskeleton.application.idempotency; -import java.time.Instant; -import java.util.Optional; +import dev.caskeleton.application.transaction.OperationId; +import java.time.Duration; /** - * Outbound port for idempotency record storage, implemented by {@code adapter-persistence} over a - * DB table unique on {@code (tenant, principal, idempotency_key, use_case_name)}. The {@link - * IdempotencyExecutor} owns the wait/replay policy; this port exposes only storage primitives. See - * README (in-memory production impls forbidden; Redis cache-only). + * Provider-neutral owner-safe idempotency state machine. + * + *

Providers (Redis, PostgreSQL) contribute only this store; the {@link IdempotencyExecutor} that + * drives it is assembled once by the composition root. */ public interface IdempotencyStorePort { - /** - * Atomically claim the scope by inserting an {@link IdempotencyStatus#IN_FLIGHT} record. Returns - * {@code true} when this caller won the claim, {@code false} when a live record already exists - * (the unique constraint is the arbiter — race-safe). An expired record must be treated as - * reclaimable. See README. - * - * @param scope the request identity - * @param fingerprint SHA-256 of the request body - * @param expiresAt TTL boundary for the new record - */ - boolean tryBegin(IdempotencyScope scope, RequestFingerprint fingerprint, Instant expiresAt); + IdempotencyClaimAttempt newClaimAttempt(OperationId operationId); - /** - * Read the current live record for a scope. A record at/after its {@code expiresAt} must be - * treated as absent (expired replay is refused). - */ - Optional find(IdempotencyScope scope, Instant now); + IdempotencyClaimOutcome claim(IdempotencyClaimRequest request); - /** - * Transition the in-flight record for {@code scope} to {@link IdempotencyStatus#COMPLETED}, - * persisting the response for replay. - */ - void complete(IdempotencyScope scope, StoredResponse response); + IdempotencyMutationResult markExecutionStarted( + IdempotencyOwner owner, OperationId operationId); - /** - * Remove the in-flight record for {@code scope} so the original request can be retried. Called - * when the claimed action throws (a stuck IN_FLIGHT row would 409 every retry). - */ - void discard(IdempotencyScope scope); + IdempotencyMutationResult renew( + IdempotencyOwner owner, Duration processingLeaseTtl, OperationId operationId); + + IdempotencyCompleteOutcome complete( + IdempotencyOwner owner, StoredResponse response, Duration replayTtl, OperationId operationId); + + IdempotencyFailOutcome markFailed( + IdempotencyOwner owner, + IdempotencyFailureDisposition disposition, + Duration retention, + OperationId operationId); + + IdempotencyReleaseOutcome releaseBeforeExecution(IdempotencyOwner owner, OperationId operationId); + + IdempotencyInspection inspect(IdempotencyInspectionRequest request); } diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotentAction.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotentAction.java index 3b685b10..5982b20c 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotentAction.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotentAction.java @@ -5,8 +5,8 @@ import java.util.Objects; /** * Explicitly classifies action effects after execution has started. * - *

An ordinary thrown exception is intentionally not classified as no-effect; the v2 executor - * treats it as effect-unknown and preserves recovery evidence. + *

An ordinary thrown exception is intentionally not classified as no-effect; the executor treats + * it as effect-unknown and preserves recovery evidence. */ @FunctionalInterface public interface IdempotentAction { diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/RequestFingerprint.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/RequestFingerprint.java index bb0aa391..d640de46 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/RequestFingerprint.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/RequestFingerprint.java @@ -6,7 +6,7 @@ import java.util.HexFormat; import java.util.Objects; /** - * SHA-256 fingerprint of a request body. Same {@link IdempotencyScope} but a different body + * SHA-256 fingerprint of a request body. Same {@link IdempotencyScopeDigest} but a different body * (different fingerprint) is a client bug, rejected by the executor with {@link * IdempotencyRequestMismatchException} (422); a null/empty body hashes as a zero-length payload. * The raw transmitted bytes are hashed — no canonicalization. See README for the SHA-256 choice and diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/Sleeper.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/Sleeper.java deleted file mode 100644 index 7566a4db..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/Sleeper.java +++ /dev/null @@ -1,25 +0,0 @@ -package dev.caskeleton.application.idempotency; - -import java.time.Duration; - -/** - * Indirection over {@code Thread.sleep} so the {@link IdempotencyExecutor}'s in-flight poll wait is - * deterministically testable (a test {@code Sleeper} can advance a mutable clock instead of - * blocking real time). - */ -@FunctionalInterface -public interface Sleeper { - - void sleep(Duration duration); - - /** Real-time sleeper that restores the interrupt flag and stops waiting on interruption. */ - static Sleeper realtime() { - return duration -> { - try { - Thread.sleep(Math.max(0L, duration.toMillis())); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } - }; - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/v2/IdempotencyExecutorV2.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/v2/IdempotencyExecutorV2.java deleted file mode 100644 index 35255fe8..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/v2/IdempotencyExecutorV2.java +++ /dev/null @@ -1,328 +0,0 @@ -package dev.caskeleton.application.idempotency.v2; - -import dev.caskeleton.application.idempotency.IdempotencyInFlightException; -import dev.caskeleton.application.idempotency.IdempotencyRecoveryRequiredException; -import dev.caskeleton.application.idempotency.IdempotencyRequestMismatchException; -import dev.caskeleton.application.idempotency.IdempotencyUnavailableException; -import dev.caskeleton.application.idempotency.IdempotentAction; -import dev.caskeleton.application.idempotency.IdempotentResponseCodec; -import dev.caskeleton.application.idempotency.RequestFingerprint; -import dev.caskeleton.application.idempotency.StoredResponse; -import dev.caskeleton.application.transaction.OperationId; -import java.time.Duration; -import java.util.Objects; -import java.util.Optional; - -/** - * Owner-safe request-replay lifecycle, over the contract the providers actually implement. - * - *

There were two V2 store contracts with the same name in neighbouring packages, and this - * orchestration was written against the one nothing implements. Both owner-safe stores — PostgreSQL - * and Redis — implement {@link IdempotencyStorePortV2} here, so selecting a V2 provider required a - * bean that could not exist and the executor could never be composed at all. - * - *

Porting it was not a rename. This contract threads the owner handle through every mutation: a - * confirmed transition returns the owner with its state revision advanced, and the next call must - * present that handle. Re-using the claim's original owner would present a stale revision, - * which the store is built to refuse — that refusal is the whole point of the compare-and-set, so a - * caller that defeats it has an owner-safe store and no owner safety. - * - *

The action runs only after a confirmed start. This preserves request-replay evidence; it does - * not create a cross-store exactly-once boundary, and nothing here should be read as claiming one. - */ -public final class IdempotencyExecutorV2 { - - private final IdempotencyStorePortV2 store; - private final Duration processingLeaseTtl; - private final Duration replayTtl; - private final Duration failureRetention; - private final String responseCodecId; - private final int policyRevision; - - /** - * Creates the executor. - * - * @param store the owner-safe store - * @param processingLeaseTtl how long a claim holds the record before another caller may take over - * @param replayTtl how long a completed response is replayable - * @param failureRetention how long a failed attempt's evidence is kept - * @param responseCodecId the identifier of the codec the stored payload was written with - * @param policyRevision the replay policy revision this deployment enforces - */ - public IdempotencyExecutorV2( - IdempotencyStorePortV2 store, - Duration processingLeaseTtl, - Duration replayTtl, - Duration failureRetention, - String responseCodecId, - int policyRevision) { - this.store = Objects.requireNonNull(store, "store must be non-null"); - this.processingLeaseTtl = - Objects.requireNonNull(processingLeaseTtl, "processing lease TTL must be non-null"); - this.replayTtl = Objects.requireNonNull(replayTtl, "replay TTL must be non-null"); - this.failureRetention = - Objects.requireNonNull(failureRetention, "failure retention must be non-null"); - this.responseCodecId = - Objects.requireNonNull(responseCodecId, "response codec identifier must be non-null"); - this.policyRevision = policyRevision; - if (failureRetention.isZero() || failureRetention.isNegative()) { - throw new IllegalArgumentException("the failure retention must be positive"); - } - } - - /** - * Mints the attempt a caller retains across a lost response. - * - * @param operationId the caller's operation identifier - * @return the claim attempt - */ - public IdempotencyClaimAttempt newAttempt(OperationId operationId) { - return store.newClaimAttempt(operationId); - } - - /** - * Claims the scope, runs the action once, and stores its response for replay. - * - * @param scope the digested scope; the raw client key never reaches this class - * @param fingerprint the request fingerprint a replay is checked against - * @param attempt the retained claim attempt - * @param action the action to run at most once - * @param codec serialises and deserialises the action's result - * @param the action's result type - * @return the action's result, or the replayed one - */ - public R execute( - IdempotencyScopeDigest scope, - RequestFingerprint fingerprint, - IdempotencyClaimAttempt attempt, - IdempotentAction action, - IdempotentResponseCodec codec) { - Objects.requireNonNull(action, "action must be non-null"); - Objects.requireNonNull(codec, "codec must be non-null"); - IdempotencyClaimRequest request = - new IdempotencyClaimRequest( - scope, - fingerprint, - attempt, - processingLeaseTtl, - replayTtl, - responseCodecId, - policyRevision); - - return switch (store.claim(request)) { - case IdempotencyClaimOutcome.CompletedReplay replay -> - codec.deserialize(replay.response().payload()); - case IdempotencyClaimOutcome.FingerprintMismatch ignored -> - throw IdempotencyRequestMismatchException.forScopeDigest(diagnostic(scope)); - case IdempotencyClaimOutcome.InProgress ignored -> - throw IdempotencyInFlightException.forScopeDigest(diagnostic(scope)); - case IdempotencyClaimOutcome.RecoveryRequired ignored -> - throw recovery("claim requires reconciliation"); - case IdempotencyClaimOutcome.OwnerOperationConflict ignored -> - throw recovery("claim requires reconciliation"); - case IdempotencyClaimOutcome.Unavailable ignored -> - throw new IdempotencyUnavailableException(); - // The response was lost, not the attempt. The retained attempt is what makes the record - // findable, so the only safe move is to ask the store what actually happened. - case IdempotencyClaimOutcome.Indeterminate ignored -> reconcile(request, action, codec); - case IdempotencyClaimOutcome.Acquired acquired -> - startAndRun(request, acquired.owner(), action, codec, false); - case IdempotencyClaimOutcome.ReplayedAcquire replayed -> - startAndRun(request, replayed.owner(), action, codec, false); - case IdempotencyClaimOutcome.TakenOverClaimed takenOver -> - startAndRun(request, takenOver.owner(), action, codec, false); - }; - } - - private R reconcile( - IdempotencyClaimRequest request, - IdempotentAction action, - IdempotentResponseCodec codec) { - IdempotencyInspection inspection = inspect(request); - return switch (inspection.outcome()) { - case CLAIMED_SAME_OPERATION -> - startAndRun(request, requireOwner(inspection), action, codec, false); - case EXECUTING_SAME_OPERATION -> runStarted(request, requireOwner(inspection), action, codec); - case COMPLETED_REPLAY -> codec.deserialize(requireResponse(inspection).payload()); - case FINGERPRINT_MISMATCH -> - throw IdempotencyRequestMismatchException.forScopeDigest(diagnostic(request.scope())); - case IN_PROGRESS_OTHER -> - throw IdempotencyInFlightException.forScopeDigest(diagnostic(request.scope())); - case UNAVAILABLE -> throw new IdempotencyUnavailableException(); - // ABSENT, FAILED_RETRYABLE, ABANDONED and OPERATION_CONFLICT all mean the same thing here: - // this caller cannot prove what happened to its own attempt, and guessing is the one thing an - // owner-safe store exists to prevent. - default -> throw recovery("an indeterminate claim could not be resumed safely"); - }; - } - - private R startAndRun( - IdempotencyClaimRequest request, - IdempotencyOwner owner, - IdempotentAction action, - IdempotentResponseCodec codec, - boolean alreadyRetried) { - IdempotencyMutationResult started = - store.markExecutionStarted(owner, request.claimAttempt().operationId()); - return switch (started.outcome()) { - // The owner handle from the transition, not the one from the claim: the state revision has - // advanced and the next compare-and-set is against the new one. - case STARTED, ALREADY_STARTED_SAME_OPERATION -> - runStarted(request, advanced(started, owner), action, codec); - case UNAVAILABLE -> throw new IdempotencyUnavailableException(); - case INDETERMINATE -> { - if (alreadyRetried) { - throw recovery("execution start stayed indeterminate after reconciliation"); - } - yield resumeAfterIndeterminateStart(request, action, codec); - } - default -> throw recovery("execution start was not confirmed for this exact operation"); - }; - } - - private R resumeAfterIndeterminateStart( - IdempotencyClaimRequest request, - IdempotentAction action, - IdempotentResponseCodec codec) { - IdempotencyInspection inspection = inspect(request); - return switch (inspection.outcome()) { - case CLAIMED_SAME_OPERATION -> - startAndRun(request, requireOwner(inspection), action, codec, true); - case EXECUTING_SAME_OPERATION -> runStarted(request, requireOwner(inspection), action, codec); - case COMPLETED_REPLAY -> codec.deserialize(requireResponse(inspection).payload()); - case UNAVAILABLE -> throw new IdempotencyUnavailableException(); - default -> throw recovery("execution start is indeterminate"); - }; - } - - private R runStarted( - IdempotencyClaimRequest request, - IdempotencyOwner owner, - IdempotentAction action, - IdempotentResponseCodec codec) { - OperationId operationId = request.claimAttempt().operationId(); - IdempotentAction.Outcome outcome; - try { - outcome = Objects.requireNonNull(action.run(), "action outcome must be non-null"); - } catch (RuntimeException failure) { - // The action threw without saying whether it had an effect, so the record must not say - // "retryable": that would invite a second execution of something that may already have run. - preserveUnknown(owner, operationId); - throw failure; - } - return switch (outcome) { - case IdempotentAction.Outcome.Success success -> - complete(request, owner, success.result(), codec, false); - case IdempotentAction.Outcome.RetryableNoEffect retryable -> { - store.markFailed( - owner, - IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE, - failureRetention, - operationId); - throw retryable.failure(); - } - case IdempotentAction.Outcome.EffectUnknown unknown -> { - preserveUnknown(owner, operationId); - throw unknown.failure(); - } - }; - } - - private R complete( - IdempotencyClaimRequest request, - IdempotencyOwner owner, - R result, - IdempotentResponseCodec codec, - boolean alreadyRetried) { - StoredResponse response = new StoredResponse(codec.serialize(result)); - return switch (store.complete( - owner, response, replayTtl, request.claimAttempt().operationId())) { - case COMPLETED, ALREADY_COMPLETED_SAME_RESULT -> result; - case UNAVAILABLE -> throw new IdempotencyUnavailableException(); - case INDETERMINATE -> reconcileCompletion(request, result, codec, alreadyRetried); - default -> throw recovery("completion was not confirmed"); - }; - } - - /** - * Resolves a completion whose response was lost. - * - *

Deliberately does not carry the caller's owner handle forward: after an indeterminate - * completion the caller's handle may already be stale, and the only handle worth presenting is - * the one the store reports now. - */ - private R reconcileCompletion( - IdempotencyClaimRequest request, - R result, - IdempotentResponseCodec codec, - boolean alreadyRetried) { - IdempotencyInspection inspection = inspect(request); - return switch (inspection.outcome()) { - case COMPLETED_REPLAY -> { - StoredResponse stored = requireResponse(inspection); - if (stored.payload().equals(codec.serialize(result))) { - yield result; - } - // The stored response is somebody else's answer to this scope. Returning either one would - // be asserting a fact this caller cannot establish. - throw recovery("the completed response conflicts with the one this caller produced"); - } - case EXECUTING_SAME_OPERATION -> { - if (alreadyRetried) { - throw recovery("completion stayed indeterminate after reconciliation"); - } - yield complete(request, requireOwner(inspection), result, codec, true); - } - case UNAVAILABLE -> throw new IdempotencyUnavailableException(); - default -> throw recovery("the completion response is indeterminate and was not reconciled"); - }; - } - - private void preserveUnknown(IdempotencyOwner owner, OperationId operationId) { - store.markFailed( - owner, - IdempotencyFailureDisposition.EFFECT_UNKNOWN_ABANDONED, - failureRetention, - operationId); - } - - private IdempotencyInspection inspect(IdempotencyClaimRequest request) { - return store.inspect( - new IdempotencyInspectionRequest( - request.scope(), request.requestFingerprint(), request.claimAttempt())); - } - - private static IdempotencyOwner advanced( - IdempotencyMutationResult transition, IdempotencyOwner fallback) { - return transition.owner().orElse(fallback); - } - - private static IdempotencyOwner requireOwner(IdempotencyInspection inspection) { - Optional owner = inspection.owner(); - return owner.orElseThrow( - () -> - recovery( - "the store reported " - + inspection.outcome() - + " without the owner handle it needs")); - } - - private static StoredResponse requireResponse(IdempotencyInspection inspection) { - return inspection - .response() - .orElseThrow(() -> recovery("the store reported a completed replay with no response")); - } - - /** - * Renders the scope for a diagnostic. Every component is already opaque — the raw client key and - * principal were digested before the scope was constructed — so this is safe to log, and it is - * the only scope identity this lifecycle ever holds. - */ - private static String diagnostic(IdempotencyScopeDigest scope) { - return scope.operationCode() + "::v" + scope.keyDigestVersion() + "::" + scope.digest(); - } - - private static IdempotencyRecoveryRequiredException recovery(String message) { - return new IdempotencyRecoveryRequiredException(message); - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/v2/IdempotencyStorePortV2.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/v2/IdempotencyStorePortV2.java deleted file mode 100644 index 762312d3..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/v2/IdempotencyStorePortV2.java +++ /dev/null @@ -1,37 +0,0 @@ -package dev.caskeleton.application.idempotency.v2; - -import dev.caskeleton.application.idempotency.StoredResponse; -import dev.caskeleton.application.transaction.OperationId; -import java.time.Duration; - -/** - * Provider-neutral owner-safe idempotency state machine. - * - *

V1 remains source-compatible during migration, but new reliability profiles must use this - * complete contract rather than combining V2 claim with scope-only V1 mutations. - */ -public interface IdempotencyStorePortV2 { - - IdempotencyClaimAttempt newClaimAttempt(OperationId operationId); - - IdempotencyClaimOutcome claim(IdempotencyClaimRequest request); - - IdempotencyMutationResult markExecutionStarted( - IdempotencyOwner owner, OperationId operationId); - - IdempotencyMutationResult renew( - IdempotencyOwner owner, Duration processingLeaseTtl, OperationId operationId); - - IdempotencyCompleteOutcome complete( - IdempotencyOwner owner, StoredResponse response, Duration replayTtl, OperationId operationId); - - IdempotencyFailOutcome markFailed( - IdempotencyOwner owner, - IdempotencyFailureDisposition disposition, - Duration retention, - OperationId operationId); - - IdempotencyReleaseOutcome releaseBeforeExecution(IdempotencyOwner owner, OperationId operationId); - - IdempotencyInspection inspect(IdempotencyInspectionRequest request); -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/inbox/InboxClaimAttempt.java b/src/application-core/src/main/java/dev/caskeleton/application/inbox/InboxClaimAttempt.java deleted file mode 100644 index 93b8d503..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/inbox/InboxClaimAttempt.java +++ /dev/null @@ -1,20 +0,0 @@ -package dev.caskeleton.application.inbox; - -import dev.caskeleton.application.transaction.OperationId; -import java.util.Objects; -import java.util.regex.Pattern; - -/** Caller-retained inbox claim identity used to replay a lost claim response. */ -public record InboxClaimAttempt(String ownerToken, OperationId operationId) { - - private static final Pattern TOKEN = Pattern.compile("[0-9a-f]{64}"); - - public InboxClaimAttempt { - Objects.requireNonNull(ownerToken, "ownerToken"); - Objects.requireNonNull(operationId, "operationId"); - if (!TOKEN.matcher(ownerToken).matches()) { - throw new IllegalArgumentException( - "owner token must be a 64-character lowercase hexadecimal value"); - } - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/inbox/InboxClaimOutcome.java b/src/application-core/src/main/java/dev/caskeleton/application/inbox/InboxClaimOutcome.java deleted file mode 100644 index 0c5c4909..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/inbox/InboxClaimOutcome.java +++ /dev/null @@ -1,40 +0,0 @@ -package dev.caskeleton.application.inbox; - -import java.time.Duration; -import java.time.Instant; -import java.util.Objects; - -/** Exhaustive atomic inbox claim classification. */ -public sealed interface InboxClaimOutcome { - - record Acquired(InboxOwner owner, Instant leaseUntil) implements InboxClaimOutcome { - public Acquired { - Objects.requireNonNull(owner, "owner"); - Objects.requireNonNull(leaseUntil, "leaseUntil"); - } - } - - record ReplayedAcquire(InboxOwner owner, Instant leaseUntil) implements InboxClaimOutcome { - public ReplayedAcquire { - Objects.requireNonNull(owner, "owner"); - Objects.requireNonNull(leaseUntil, "leaseUntil"); - } - } - - record TakenOver(InboxOwner owner, Instant leaseUntil) implements InboxClaimOutcome { - public TakenOver { - Objects.requireNonNull(owner, "owner"); - Objects.requireNonNull(leaseUntil, "leaseUntil"); - } - } - - record Completed() implements InboxClaimOutcome {} - - record InProgress(Duration retryAfter, long attempt) implements InboxClaimOutcome {} - - record RecoveryRequired(long attempt) implements InboxClaimOutcome {} - - record IntentMismatch() implements InboxClaimOutcome {} - - record OwnerOperationConflict() implements InboxClaimOutcome {} -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/inbox/InboxClaimRequest.java b/src/application-core/src/main/java/dev/caskeleton/application/inbox/InboxClaimRequest.java deleted file mode 100644 index 09304bf1..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/inbox/InboxClaimRequest.java +++ /dev/null @@ -1,35 +0,0 @@ -package dev.caskeleton.application.inbox; - -import java.time.Duration; -import java.util.Objects; -import java.util.regex.Pattern; - -/** Atomic inbox claim request with separate processing and terminal retention windows. */ -public record InboxClaimRequest( - InboxScopeDigest scope, - String messageIntentDigest, - InboxClaimAttempt claimAttempt, - Duration processingLease, - Duration terminalRetention) { - - private static final Pattern DIGEST = Pattern.compile("[0-9a-f]{64}"); - - public InboxClaimRequest { - Objects.requireNonNull(scope, "scope"); - Objects.requireNonNull(messageIntentDigest, "messageIntentDigest"); - Objects.requireNonNull(claimAttempt, "claimAttempt"); - if (!DIGEST.matcher(messageIntentDigest).matches()) { - throw new IllegalArgumentException( - "message intent digest must be a 64-character lowercase hexadecimal value"); - } - requirePositiveBounded("processing lease", processingLease, Duration.ofHours(1)); - requirePositiveBounded("terminal retention", terminalRetention, Duration.ofDays(30)); - } - - private static void requirePositiveBounded(String name, Duration value, Duration maximum) { - Objects.requireNonNull(value, name); - if (value.isZero() || value.isNegative() || value.compareTo(maximum) > 0) { - throw new IllegalArgumentException(name + " must be positive and at most " + maximum); - } - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/inbox/InboxOwner.java b/src/application-core/src/main/java/dev/caskeleton/application/inbox/InboxOwner.java deleted file mode 100644 index cabdf16f..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/inbox/InboxOwner.java +++ /dev/null @@ -1,32 +0,0 @@ -package dev.caskeleton.application.inbox; - -import dev.caskeleton.application.transaction.OperationId; -import java.util.Objects; - -/** Full owner/attempt/claim-operation/state-revision CAS tuple for one inbox message. */ -public record InboxOwner( - InboxScopeDigest scope, - String ownerToken, - long attempt, - long stateRevision, - OperationId claimOperationId) { - - public InboxOwner { - Objects.requireNonNull(scope, "scope"); - Objects.requireNonNull(ownerToken, "ownerToken"); - Objects.requireNonNull(claimOperationId, "claimOperationId"); - if (ownerToken.isBlank() || ownerToken.length() > 128) { - throw new IllegalArgumentException("owner token must contain 1-128 characters"); - } - if (attempt < 1) { - throw new IllegalArgumentException("attempt must be positive"); - } - if (stateRevision < 0) { - throw new IllegalArgumentException("state revision must be non-negative"); - } - } - - public InboxOwner withStateRevision(long revision) { - return new InboxOwner(scope, ownerToken, attempt, revision, claimOperationId); - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/inbox/InboxOwnerTransition.java b/src/application-core/src/main/java/dev/caskeleton/application/inbox/InboxOwnerTransition.java deleted file mode 100644 index ce4119b9..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/inbox/InboxOwnerTransition.java +++ /dev/null @@ -1,20 +0,0 @@ -package dev.caskeleton.application.inbox; - -import java.util.Objects; -import java.util.Optional; - -/** Transition outcome and updated owner handle while ownership remains live. */ -public record InboxOwnerTransition(InboxTransitionOutcome outcome, Optional owner) { - - public InboxOwnerTransition { - Objects.requireNonNull(outcome, "outcome"); - Objects.requireNonNull(owner, "owner"); - boolean mustCarryOwner = outcome == InboxTransitionOutcome.PROCESSING_STARTED; - if (mustCarryOwner != owner.isPresent()) { - throw new IllegalArgumentException( - mustCarryOwner - ? "PROCESSING_STARTED must carry an updated owner" - : outcome + " must not carry an owner"); - } - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/inbox/InboxScopeDigest.java b/src/application-core/src/main/java/dev/caskeleton/application/inbox/InboxScopeDigest.java deleted file mode 100644 index 59500218..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/inbox/InboxScopeDigest.java +++ /dev/null @@ -1,18 +0,0 @@ -package dev.caskeleton.application.inbox; - -import java.util.Objects; -import java.util.regex.Pattern; - -/** Versioned canonical digest of consumer-group, handler, tenant, and message ID scope. */ -public record InboxScopeDigest(String value) { - - private static final Pattern LOWERCASE_SHA_256 = Pattern.compile("[0-9a-f]{64}"); - - public InboxScopeDigest { - Objects.requireNonNull(value, "value"); - if (!LOWERCASE_SHA_256.matcher(value).matches()) { - throw new IllegalArgumentException( - "inbox scope must be a 64-character lowercase hexadecimal digest"); - } - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/inbox/InboxState.java b/src/application-core/src/main/java/dev/caskeleton/application/inbox/InboxState.java deleted file mode 100644 index a58f993b..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/inbox/InboxState.java +++ /dev/null @@ -1,10 +0,0 @@ -package dev.caskeleton.application.inbox; - -/** Same-store inbox lifecycle. */ -public enum InboxState { - RECEIVED, - PROCESSING, - COMPLETED, - RETRYABLE, - DEAD -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/inbox/InboxStorePort.java b/src/application-core/src/main/java/dev/caskeleton/application/inbox/InboxStorePort.java deleted file mode 100644 index 3df5294b..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/inbox/InboxStorePort.java +++ /dev/null @@ -1,23 +0,0 @@ -package dev.caskeleton.application.inbox; - -import dev.caskeleton.application.transaction.OperationId; -import java.time.Duration; - -/** - * Owner-safe same-store inbox state machine. Broker ACK must happen only after transaction commit. - */ -public interface InboxStorePort { - - InboxClaimAttempt newClaimAttempt(OperationId operationId); - - InboxClaimOutcome claim(InboxClaimRequest request); - - InboxOwnerTransition markProcessing(InboxOwner owner, OperationId operationId); - - InboxTransitionOutcome complete(InboxOwner owner, OperationId operationId); - - InboxTransitionOutcome markRetryable( - InboxOwner owner, Duration retention, OperationId operationId); - - InboxTransitionOutcome markDead(InboxOwner owner, Duration retention, OperationId operationId); -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/inbox/InboxTransitionOutcome.java b/src/application-core/src/main/java/dev/caskeleton/application/inbox/InboxTransitionOutcome.java deleted file mode 100644 index 4009a624..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/inbox/InboxTransitionOutcome.java +++ /dev/null @@ -1,15 +0,0 @@ -package dev.caskeleton.application.inbox; - -/** Owner-safe inbox transition classification. */ -public enum InboxTransitionOutcome { - PROCESSING_STARTED, - COMPLETED, - RETRYABLE, - DEAD, - ALREADY_APPLIED_SAME_OPERATION, - RESULT_CONFLICT, - ABSENT, - NOT_OWNER, - INVALID_STATE, - STALE_REVISION -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/lease/LeaseWatchdog.java b/src/application-core/src/main/java/dev/caskeleton/application/lease/LeaseWatchdog.java deleted file mode 100644 index 83eca45b..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/lease/LeaseWatchdog.java +++ /dev/null @@ -1,228 +0,0 @@ -package dev.caskeleton.application.lease; - -import java.time.Clock; -import java.time.Duration; -import java.time.Instant; -import java.util.List; -import java.util.Objects; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.RejectedExecutionException; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.Consumer; - -/** - * Bounded renewal scheduler for efficiency leases. - * - *

A watchdog reduces duplicate work only. It does not remove process pauses, Redis failover, or - * the requirement for a correctness authority at the protected resource. - * - * @deprecated the shipped runtime does not compose this scheduler. Keep it as a verified reference - * only unless an application explicitly owns its lifecycle and integration. - */ -@Deprecated -public final class LeaseWatchdog implements AutoCloseable { - - private static final int MAXIMUM_WORKERS = 32; - private static final int MAXIMUM_REGISTRATIONS = 100_000; - - private final ScheduledThreadPoolExecutor scheduler; - private final int maximumRegistrations; - private final Clock clock; - private final AtomicInteger registrations = new AtomicInteger(); - private final AtomicBoolean closed = new AtomicBoolean(); - private final Set active = ConcurrentHashMap.newKeySet(); - - public LeaseWatchdog(int workerThreads, int maximumRegistrations, Clock clock) { - if (workerThreads < 1 || workerThreads > MAXIMUM_WORKERS) { - throw new IllegalArgumentException("workerThreads must be in 1..32"); - } - if (maximumRegistrations < 1 || maximumRegistrations > MAXIMUM_REGISTRATIONS) { - throw new IllegalArgumentException("maximumRegistrations must be in 1..100000"); - } - this.maximumRegistrations = maximumRegistrations; - this.clock = Objects.requireNonNull(clock, "clock must be non-null"); - this.scheduler = - new ScheduledThreadPoolExecutor( - workerThreads, - daemonThreadFactory(), - new java.util.concurrent.ThreadPoolExecutor.AbortPolicy()); - this.scheduler.setRemoveOnCancelPolicy(true); - this.scheduler.setExecuteExistingDelayedTasksAfterShutdownPolicy(false); - this.scheduler.setContinueExistingPeriodicTasksAfterShutdownPolicy(false); - } - - public Registration watch( - LeaseHandle handle, - Duration leaseTtl, - Duration cadence, - Instant applicationDeadline, - Runnable cancelWork, - Consumer lostListener) { - Objects.requireNonNull(handle, "handle must be non-null"); - Duration boundedLeaseTtl = - LeaseValidation.positiveBounded(leaseTtl, LeaseValidation.MAXIMUM_LEASE, "leaseTtl"); - Duration boundedCadence = LeaseValidation.positiveBounded(cadence, boundedLeaseTtl, "cadence"); - if (boundedCadence.compareTo(boundedLeaseTtl.dividedBy(2)) > 0) { - throw new IllegalArgumentException("cadence must not exceed half of leaseTtl"); - } - Objects.requireNonNull(applicationDeadline, "applicationDeadline must be non-null"); - if (!applicationDeadline.isAfter(clock.instant())) { - throw new IllegalArgumentException("applicationDeadline must be in the future"); - } - Objects.requireNonNull(cancelWork, "cancelWork must be non-null"); - Objects.requireNonNull(lostListener, "lostListener must be non-null"); - reserve(); - Registration registration = - new Registration(handle, boundedLeaseTtl, applicationDeadline, cancelWork, lostListener); - active.add(registration); - try { - registration.future = - scheduler.scheduleWithFixedDelay( - registration::runOnce, - boundedCadence.toMillis(), - boundedCadence.toMillis(), - TimeUnit.MILLISECONDS); - return registration; - } catch (RuntimeException failure) { - registration.close(); - throw failure; - } - } - - private void reserve() { - while (true) { - if (closed.get()) { - throw new RejectedExecutionException("lease watchdog is closed"); - } - int current = registrations.get(); - if (current >= maximumRegistrations) { - throw new RejectedExecutionException("lease watchdog registration bound reached"); - } - if (registrations.compareAndSet(current, current + 1)) { - if (closed.get()) { - registrations.decrementAndGet(); - throw new RejectedExecutionException("lease watchdog is closed"); - } - return; - } - } - } - - int activeRegistrations() { - return registrations.get(); - } - - @Override - public void close() { - if (closed.compareAndSet(false, true)) { - for (Registration registration : active.toArray(Registration[]::new)) { - registration.close(); - } - // shutdownNow() returns the tasks it cancelled before they ran. Nothing here can act on - // them, but the value has to be read rather than discarded, or the ignored-return-value - // check reads this as a call made purely for its side effect. - List cancelled = scheduler.shutdownNow(); - cancelled.clear(); - } - } - - public final class Registration implements AutoCloseable { - - private final LeaseHandle handle; - private final Duration leaseTtl; - private final Instant applicationDeadline; - private final Runnable cancelWork; - private final Consumer lostListener; - private final AtomicBoolean registrationClosed = new AtomicBoolean(); - private final AtomicBoolean lossReported = new AtomicBoolean(); - private volatile ScheduledFuture future; - - private Registration( - LeaseHandle handle, - Duration leaseTtl, - Instant applicationDeadline, - Runnable cancelWork, - Consumer lostListener) { - this.handle = handle; - this.leaseTtl = leaseTtl; - this.applicationDeadline = applicationDeadline; - this.cancelWork = cancelWork; - this.lostListener = lostListener; - } - - private void runOnce() { - if (registrationClosed.get()) { - return; - } - if (!applicationDeadline.isAfter(clock.instant())) { - terminateLost(LeaseState.LOST); - return; - } - LeaseState before = handle.state(); - if (before != LeaseState.ACTIVE || handle.remainingValidity().isZero()) { - terminateLost(before == LeaseState.ACTIVE ? LeaseState.LOST : before); - return; - } - LeaseRenewOutcome outcome; - try { - outcome = Objects.requireNonNull(handle.renew(leaseTtl), "renew outcome must be non-null"); - } catch (RuntimeException failure) { - terminateLost(LeaseState.UNKNOWN); - return; - } - if (!(outcome instanceof LeaseRenewOutcome.Renewed) || handle.state() != LeaseState.ACTIVE) { - LeaseState state = handle.state(); - terminateLost(state == LeaseState.ACTIVE ? LeaseState.LOST : state); - } - } - - void runOnceForTest() { - runOnce(); - } - - public boolean closed() { - return registrationClosed.get(); - } - - private void terminateLost(LeaseState state) { - if (lossReported.compareAndSet(false, true)) { - try { - cancelWork.run(); - } finally { - try { - lostListener.accept(state); - } finally { - close(); - } - } - } - } - - @Override - public void close() { - if (registrationClosed.compareAndSet(false, true)) { - ScheduledFuture scheduled = future; - if (scheduled != null) { - scheduled.cancel(false); - } - active.remove(this); - registrations.decrementAndGet(); - } - } - } - - private static ThreadFactory daemonThreadFactory() { - AtomicInteger sequence = new AtomicInteger(); - return runnable -> { - Thread thread = new Thread(runnable, "ca-lease-watchdog-" + sequence.incrementAndGet()); - thread.setDaemon(true); - return thread; - }; - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/operation/CancelDurableOperationCommand.java b/src/application-core/src/main/java/dev/caskeleton/application/operation/CancelDurableOperationCommand.java new file mode 100644 index 00000000..aa9fc88e --- /dev/null +++ b/src/application-core/src/main/java/dev/caskeleton/application/operation/CancelDurableOperationCommand.java @@ -0,0 +1,19 @@ +package dev.caskeleton.application.operation; + +import dev.caskeleton.application.command.Command; +import java.util.Objects; + +/** + * A caller asking to cancel one operation. + * + * @param operationId the identity to cancel + * @param principal the authenticated caller, or null when the caller is not authenticated + * @param tenantId the caller's tenant, or null when the request is not tenant scoped + */ +public record CancelDurableOperationCommand( + DurableOperationId operationId, String principal, String tenantId) implements Command { + + public CancelDurableOperationCommand { + Objects.requireNonNull(operationId, "operationId"); + } +} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/operation/CancelDurableOperationUseCase.java b/src/application-core/src/main/java/dev/caskeleton/application/operation/CancelDurableOperationUseCase.java new file mode 100644 index 00000000..6c3c2449 --- /dev/null +++ b/src/application-core/src/main/java/dev/caskeleton/application/operation/CancelDurableOperationUseCase.java @@ -0,0 +1,70 @@ +package dev.caskeleton.application.operation; + +import dev.caskeleton.application.capability.Idempotency; +import dev.caskeleton.application.capability.RepositoryAccess; +import dev.caskeleton.application.capability.UseCaseCapability; +import dev.caskeleton.application.security.RequiresPermission; +import dev.caskeleton.application.transaction.TransactionMode; +import dev.caskeleton.application.transaction.TransactionPort; +import dev.caskeleton.application.usecase.CommandUseCase; +import java.time.Clock; +import java.time.Instant; +import java.util.Objects; +import java.util.Optional; + +/** + * Cancels one operation for the caller that submitted it. + * + *

The result is empty when the caller may not see the operation, which is the same answer as for + * one that does not exist; otherwise it says whether this call moved it to CANCELED. A repeat, or a + * cancel of work that already finished, is {@code false}, never an error. + */ +@RequiresPermission("operation:cancel") +@UseCaseCapability( + transactionMode = TransactionMode.WRITE, + idempotency = Idempotency.IDEMPOTENT, + repositoryAccess = RepositoryAccess.WRITE_REPOSITORY) +// Not final: @RequiresPermission is applied through a CGLIB proxy +// (RequiresPermissionProxyabilityTest). +public class CancelDurableOperationUseCase + implements CommandUseCase> { + + private final DurableOperationStorePort operations; + private final TransactionPort transactions; + private final Clock clock; + + /** + * A use case over the operation store. + * + * @param operations where operations are recorded + * @param transactions opens the write transaction + * @param clock the cancellation clock + */ + public CancelDurableOperationUseCase( + DurableOperationStorePort operations, TransactionPort transactions, Clock clock) { + this.operations = Objects.requireNonNull(operations, "operations"); + this.transactions = Objects.requireNonNull(transactions, "transactions"); + this.clock = Objects.requireNonNull(clock, "clock"); + } + + @Override + public Optional handle(CancelDurableOperationCommand command) { + Objects.requireNonNull(command, "command"); + if (command.principal() == null) { + return Optional.empty(); + } + return transactions.inWrite( + () -> { + Instant now = clock.instant(); + // The store's own state predicate decides whether the cancel lands: the operation can + // finish between this read and the cancel, and only the store can refuse that race. + return operations + .find(command.operationId(), command.principal(), now) + .filter( + operation -> + DurableOperationAccessPolicy.mayAccess( + operation, command.principal(), command.tenantId())) + .map(visible -> operations.cancel(command.operationId(), command.principal(), now)); + }); + } +} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/operation/DurableOperationAccessPolicy.java b/src/application-core/src/main/java/dev/caskeleton/application/operation/DurableOperationAccessPolicy.java new file mode 100644 index 00000000..6674f707 --- /dev/null +++ b/src/application-core/src/main/java/dev/caskeleton/application/operation/DurableOperationAccessPolicy.java @@ -0,0 +1,29 @@ +package dev.caskeleton.application.operation; + +import java.util.Objects; + +/** + * Who may read or cancel an operation: the principal that submitted it, in the tenant it was + * submitted in. + * + *

Object-level, not route-level. Being allowed to call the operation route says nothing about + * being allowed to see this operation, and a failed one carries its problem detail. A caller that + * fails this check is answered exactly as if the operation did not exist, so a guessed id is not an + * oracle for what other callers or tenants are running. + */ +final class DurableOperationAccessPolicy { + + private DurableOperationAccessPolicy() {} + + /** + * Whether this caller may see this operation. + * + * @param operation the stored operation + * @param principal the authenticated caller, or null when the caller is not authenticated + * @param tenantId the caller's tenant, or null when the request is not tenant scoped + */ + static boolean mayAccess(DurableOperation operation, String principal, String tenantId) { + return operation.principal().equals(principal) + && Objects.equals(operation.tenantId(), tenantId); + } +} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/operation/GetDurableOperationQuery.java b/src/application-core/src/main/java/dev/caskeleton/application/operation/GetDurableOperationQuery.java new file mode 100644 index 00000000..e6ce2ae6 --- /dev/null +++ b/src/application-core/src/main/java/dev/caskeleton/application/operation/GetDurableOperationQuery.java @@ -0,0 +1,19 @@ +package dev.caskeleton.application.operation; + +import dev.caskeleton.application.query.Query; +import java.util.Objects; + +/** + * A caller asking to read one operation. + * + * @param operationId the identity being polled + * @param principal the authenticated caller, or null when the caller is not authenticated + * @param tenantId the caller's tenant, or null when the request is not tenant scoped + */ +public record GetDurableOperationQuery( + DurableOperationId operationId, String principal, String tenantId) implements Query { + + public GetDurableOperationQuery { + Objects.requireNonNull(operationId, "operationId"); + } +} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/operation/GetDurableOperationUseCase.java b/src/application-core/src/main/java/dev/caskeleton/application/operation/GetDurableOperationUseCase.java new file mode 100644 index 00000000..3fb1bfed --- /dev/null +++ b/src/application-core/src/main/java/dev/caskeleton/application/operation/GetDurableOperationUseCase.java @@ -0,0 +1,52 @@ +package dev.caskeleton.application.operation; + +import dev.caskeleton.application.capability.Idempotency; +import dev.caskeleton.application.capability.RepositoryAccess; +import dev.caskeleton.application.capability.UseCaseCapability; +import dev.caskeleton.application.transaction.TransactionMode; +import dev.caskeleton.application.transaction.TransactionPort; +import dev.caskeleton.application.usecase.QueryUseCase; +import java.time.Clock; +import java.util.Objects; +import java.util.Optional; + +/** Reads one operation for the caller that submitted it; anyone else is told it does not exist. */ +@UseCaseCapability( + transactionMode = TransactionMode.READ_ONLY, + idempotency = Idempotency.IDEMPOTENT, + repositoryAccess = RepositoryAccess.READ_REPOSITORY) +public final class GetDurableOperationUseCase + implements QueryUseCase> { + + private final DurableOperationStorePort operations; + private final TransactionPort transactions; + private final Clock clock; + + /** + * A use case over the operation store. + * + * @param operations where operations are recorded + * @param transactions opens the read transaction + * @param clock the clock expiry is judged against + */ + public GetDurableOperationUseCase( + DurableOperationStorePort operations, TransactionPort transactions, Clock clock) { + this.operations = Objects.requireNonNull(operations, "operations"); + this.transactions = Objects.requireNonNull(transactions, "transactions"); + this.clock = Objects.requireNonNull(clock, "clock"); + } + + @Override + public Optional handle(GetDurableOperationQuery query) { + Objects.requireNonNull(query, "query"); + if (query.principal() == null) { + return Optional.empty(); + } + return transactions + .inRead(() -> operations.find(query.operationId(), query.principal(), clock.instant())) + .filter( + operation -> + DurableOperationAccessPolicy.mayAccess( + operation, query.principal(), query.tenantId())); + } +} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxCompletion.java b/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxCompletion.java new file mode 100644 index 00000000..ef987d47 --- /dev/null +++ b/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxCompletion.java @@ -0,0 +1,14 @@ +package dev.caskeleton.application.outbox; + +/** What a completion ({@code markPublished} / {@code markFailed} / {@code markDead}) achieved. */ +public enum OutboxCompletion { + + /** The lease still held the row; the row took the new state. */ + APPLIED, + + /** + * The lease no longer held the row — it expired and another relay claimed the row, or the row was + * already completed. Nothing was written. + */ + STALE +} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxLease.java b/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxLease.java new file mode 100644 index 00000000..eed397ab --- /dev/null +++ b/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxLease.java @@ -0,0 +1,35 @@ +package dev.caskeleton.application.outbox; + +import java.util.Objects; + +/** + * One relay's claim on one outbox row, as returned by {@link OutboxStorePort#claimBatch}. + * + *

A claim expires after the in-flight timeout and another relay may then take the row. The + * {@code token} is the fence: every claim increments it and a completion names the token it holds, + * so the relay that stalled past its claim finds nothing left to complete instead of overwriting + * the result of the relay that took over. + * + *

Kept apart from {@link ClaimedOutboxEvent} on purpose: the broker adapter receives the event, + * and the claim is store bookkeeping it has no use for. + * + * @param event the claimed row + * @param owner the relay instance that holds the claim + * @param token the fencing token this claim was granted + */ +public record OutboxLease(ClaimedOutboxEvent event, String owner, long token) { + + public OutboxLease { + Objects.requireNonNull(event, "event must not be null"); + if (owner == null || owner.isBlank()) { + throw new IllegalArgumentException("owner must not be blank"); + } + if (token < 1) { + throw new IllegalArgumentException("token must be >= 1, was " + token); + } + } + + public String eventId() { + return event.eventId(); + } +} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxRelayFailureReportPort.java b/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxRelayFailureReportPort.java index 3967dc97..e92ff073 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxRelayFailureReportPort.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxRelayFailureReportPort.java @@ -10,4 +10,17 @@ package dev.caskeleton.application.outbox; public interface OutboxRelayFailureReportPort { void report(OutboxRelayFailureReport report); + + /** + * Reports a completion this relay could not write because its claim had been superseded: the + * claim outlived the in-flight timeout and another relay took the row. Nothing was persisted, so + * this is not a FAILED/DEAD transition; it says the timeout is shorter than a relay stall and the + * broker may have seen the event twice. + * + * @param eventId the event whose completion was refused + * @param eventType the logical event type + * @param attempted the outcome this relay tried to write + */ + default void reportStaleCompletion( + String eventId, String eventType, OutboxRelayResult.Outcome attempted) {} } diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxRelayResult.java b/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxRelayResult.java index 615c2a5c..2edc90f8 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxRelayResult.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxRelayResult.java @@ -41,7 +41,8 @@ public record OutboxRelayResult(int claimedCount, List outcomes) { * *

Three values mirror the three terminal states reachable in a single relay cycle: broker ack * ({@link #PUBLISHED}), transient failure below the retry cap ({@link #FAILED}), or retry cap - * exhausted ({@link #DEAD}). + * exhausted ({@link #DEAD}). The fourth, {@link #STALE}, records a result this relay was no + * longer allowed to write. */ public enum Outcome { @@ -52,6 +53,13 @@ public record OutboxRelayResult(int claimedCount, List outcomes) { FAILED, /** All retry attempts exhausted; row transitions to DEAD. */ - DEAD + DEAD, + + /** + * This relay's claim expired and another relay took the row over before the result could be + * written, so nothing was written. The other relay owns the row's outcome; the broker may have + * seen this relay's attempt as well. + */ + STALE } } diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxStorePort.java b/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxStorePort.java index 9de958f6..df892933 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxStorePort.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxStorePort.java @@ -9,49 +9,56 @@ import java.util.Map; * Outbound port for relay-side access to the outbox store. All mutating operations ({@link * #claimBatch}, {@link #markPublished}, {@link #markFailed}, {@link #markDead}) must be called * inside a {@code TransactionPort.inWrite(...)} boundary owned by the relay; implementations must - * not open their own transaction. See README for the claim/FIFO/in-flight-timeout semantics. + * not open their own transaction. A completion applies only while the relay's {@link OutboxLease} + * still holds the row, so a relay that stalled past its claim cannot overwrite the relay that took + * the row over. See README for the claim/FIFO/in-flight-timeout/lease semantics. */ public interface OutboxStorePort { /** - * Atomically claims up to {@code batchSize} eligible rows and transitions them to {@link - * OutboxEventStatus#IN_FLIGHT}. Must be called inside {@code TransactionPort.inWrite(...)}. See - * README for eligibility and the FIFO gate. + * Atomically claims up to {@code batchSize} eligible rows for {@code owner} and transitions them + * to {@link OutboxEventStatus#IN_FLIGHT}. While the row lock is held each claimed row records + * {@code owner} and increments its fencing token. Must be called inside {@code + * TransactionPort.inWrite(...)}. See README for eligibility and the FIFO gate. * + * @param owner the claiming relay instance; stable for the relay's lifetime * @param batchSize maximum number of events to claim * @param now current wall-clock time used for eligibility checks * @param inFlightTimeout duration after which an IN_FLIGHT orphan becomes re-claimable - * @return claimed events ({@code status = IN_FLIGHT}, incremented {@code attemptCount}); empty if - * none + * @return one lease per claimed event ({@code status = IN_FLIGHT}, incremented {@code + * attemptCount}); empty if none */ - List claimBatch(int batchSize, Instant now, Duration inFlightTimeout); + List claimBatch(String owner, int batchSize, Instant now, Duration inFlightTimeout); /** - * Marks the event as successfully published. Must be called inside {@code + * Marks the leased event as successfully published. Must be called inside {@code * TransactionPort.inWrite(...)} after a successful publish. * - * @param eventId the identifier of the event to mark published + * @param lease the claim this relay holds + * @return {@link OutboxCompletion#STALE}, writing nothing, when the lease no longer holds the row */ - void markPublished(String eventId); + OutboxCompletion markPublished(OutboxLease lease); /** - * Marks the event as failed and schedules the next retry attempt. Must be called inside {@code - * TransactionPort.inWrite(...)} when a publish fails transiently and {@code attemptCount < + * Marks the leased event as failed and schedules the next retry attempt. Must be called inside + * {@code TransactionPort.inWrite(...)} when a publish fails transiently and {@code attemptCount < * maxAttempts}. * - * @param eventId the identifier of the event to mark failed + * @param lease the claim this relay holds * @param nextAttemptAt the earliest instant at which the event may be re-claimed + * @return {@link OutboxCompletion#STALE}, writing nothing, when the lease no longer holds the row */ - void markFailed(String eventId, Instant nextAttemptAt); + OutboxCompletion markFailed(OutboxLease lease, Instant nextAttemptAt); /** - * Marks the event as dead-lettered after all retry attempts are exhausted. Must be called inside - * {@code TransactionPort.inWrite(...)}. A DEAD row blocks its aggregate's FIFO queue until + * Marks the leased event as dead-lettered after all retry attempts are exhausted. Must be called + * inside {@code TransactionPort.inWrite(...)}. A DEAD row blocks its aggregate's FIFO queue until * manually resolved (see README). * - * @param eventId the identifier of the event to dead-letter + * @param lease the claim this relay holds + * @return {@link OutboxCompletion#STALE}, writing nothing, when the lease no longer holds the row */ - void markDead(String eventId); + OutboxCompletion markDead(OutboxLease lease); /** * Returns a count of rows grouped by {@link OutboxEventStatus} — gauge source for the {@code diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbox/PublishPendingOutboxEventsUseCase.java b/src/application-core/src/main/java/dev/caskeleton/application/outbox/PublishPendingOutboxEventsUseCase.java index b420b4f4..6115ea33 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/outbox/PublishPendingOutboxEventsUseCase.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/outbox/PublishPendingOutboxEventsUseCase.java @@ -22,9 +22,11 @@ import java.util.function.Supplier; * outside any transaction and drive the PUBLISHED / FAILED / DEAD state machine per * result. Confirmed failure transitions are reported through a typed outbound port and publish * failures are never rethrown; a status-update failure after a successful publish propagates and - * the row is recovered via the in-flight timeout. Wired manually by {@code app-bootstrap} (not a - * Spring bean). See README for the full algorithm, failure semantics, manual-wiring rationale, and - * the {@code "outbox:relay"} permission. + * the row is recovered via the in-flight timeout. A completion runs only under the claim's {@link + * OutboxLease}; when that claim has been superseded the result is recorded as {@code STALE} and + * reported, never written. Wired manually by {@code app-bootstrap} (not a Spring bean). See README + * for the full algorithm, failure semantics, manual-wiring rationale, and the {@code + * "outbox:relay"} permission. */ @RequiresPermission("outbox:relay") @UseCaseCapability( @@ -44,6 +46,9 @@ public class PublishPendingOutboxEventsUseCase private final int batchSize; private final Duration inFlightTimeout; + /** The lease owner this relay instance claims under: one per instance, fixed for its lifetime. */ + private final String relayOwner; + /** * Constructs the relay use case with all required collaborators (wired manually by {@code * app-bootstrap}; see README). @@ -56,6 +61,8 @@ public class PublishPendingOutboxEventsUseCase * @param clock wall-clock source (injected for testability) * @param batchSize maximum events to claim per relay cycle * @param inFlightTimeout how long a claimed row stays IN_FLIGHT before re-claim + * @param relayOwner lease owner id, unique per relay instance (the composition root generates it; + * identifier generation stays out of the application layer) */ public PublishPendingOutboxEventsUseCase( OutboxStorePort store, @@ -65,7 +72,8 @@ public class PublishPendingOutboxEventsUseCase OutboxBackoffPolicy backoffPolicy, Clock clock, int batchSize, - Duration inFlightTimeout) { + Duration inFlightTimeout, + String relayOwner) { this.store = Objects.requireNonNull(store, "store must not be null"); this.publishPort = Objects.requireNonNull(publishPort, "publishPort must not be null"); this.failureReporter = @@ -79,6 +87,10 @@ public class PublishPendingOutboxEventsUseCase this.batchSize = batchSize; this.inFlightTimeout = Objects.requireNonNull(inFlightTimeout, "inFlightTimeout must not be null"); + if (relayOwner == null || relayOwner.isBlank()) { + throw new IllegalArgumentException("relayOwner must not be blank"); + } + this.relayOwner = relayOwner; } @Override @@ -87,8 +99,8 @@ public class PublishPendingOutboxEventsUseCase Instant now = clock.instant(); // Step 1: Claim a batch inside a short write transaction. - List claimed = - tx.inWrite(() -> store.claimBatch(batchSize, now, inFlightTimeout)); + List claimed = + tx.inWrite(() -> store.claimBatch(relayOwner, batchSize, now, inFlightTimeout)); if (claimed.isEmpty()) { return new OutboxRelayResult(0, List.of()); @@ -96,14 +108,15 @@ public class PublishPendingOutboxEventsUseCase // Step 2: Defensive sort by occurredAt ascending (relay enforces FIFO even if the adapter does // not). - List sorted = new ArrayList<>(claimed); - sorted.sort(Comparator.comparing(ClaimedOutboxEvent::occurredAt)); + List sorted = new ArrayList<>(claimed); + sorted.sort(Comparator.comparing(lease -> lease.event().occurredAt())); // Step 3: Publish each event outside any transaction; drive status machine per result. List outcomes = new ArrayList<>(sorted.size()); - for (ClaimedOutboxEvent event : sorted) { - OutboxRelayResult.Outcome outcome = publishOne(event, now); - outcomes.add(new OutboxRelayResult.EventOutcome(event.eventId(), event.eventType(), outcome)); + for (OutboxLease lease : sorted) { + OutboxRelayResult.Outcome outcome = publishOne(lease, now); + outcomes.add( + new OutboxRelayResult.EventOutcome(lease.eventId(), lease.event().eventType(), outcome)); } return new OutboxRelayResult(claimed.size(), outcomes); @@ -115,7 +128,8 @@ public class PublishPendingOutboxEventsUseCase * successful publish is NOT caught — it propagates so the row is recovered via the in-flight * timeout. See README for both failure modes. */ - private OutboxRelayResult.Outcome publishOne(ClaimedOutboxEvent event, Instant now) { + private OutboxRelayResult.Outcome publishOne(OutboxLease lease, Instant now) { + ClaimedOutboxEvent event = lease.event(); OutboxPublishOutcome achieved; try { // The four-valued call, not the throwing one. An adapter that cannot tell an ambiguous @@ -124,22 +138,24 @@ public class PublishPendingOutboxEventsUseCase achieved = publishPort.publishForOutcome(event); } catch (RuntimeException publishEx) { // Publish failure: drive FAILED/DEAD state machine + typed report; do NOT rethrow. - return handlePublishFailure(event, now, publishEx); + return handlePublishFailure(lease, now, publishEx); } if (achieved == OutboxPublishOutcome.AMBIGUOUS) { // The message left this process and no acknowledgement arrived, so it may be stored. Treated // as retryable and reported as such: the duplicate risk is the caller's to bound with an // idempotency key, and the alternative — parking it — loses a message that was delivered. - return handlePublishFailure(event, now, new OutboxPublishAmbiguousException()); + return handlePublishFailure(lease, now, new OutboxPublishAmbiguousException()); } if (achieved != OutboxPublishOutcome.CONFIRMED) { // Definite refusal. Retrying the same payload fails the same way, so the attempt budget is // not spent on it; the row is dead-lettered now rather than after the timer runs out. - return deadLetter(event, new OutboxPublishRefusedException(achieved)); + return deadLetter(lease, new OutboxPublishRefusedException(achieved)); } // markPublished failure (if any) propagates: the row stays IN_FLIGHT and is // recovered via the orphan visibility-timeout reclaim path. - tx.inWrite(() -> store.markPublished(event.eventId())); + if (tx.inWrite(() -> store.markPublished(lease)) == OutboxCompletion.STALE) { + return stale(lease, OutboxRelayResult.Outcome.PUBLISHED); + } return OutboxRelayResult.Outcome.PUBLISHED; } @@ -149,15 +165,18 @@ public class PublishPendingOutboxEventsUseCase * failure is contained and cannot change the persisted outcome. See README. */ private OutboxRelayResult.Outcome handlePublishFailure( - ClaimedOutboxEvent event, Instant now, RuntimeException cause) { + OutboxLease lease, Instant now, RuntimeException cause) { + ClaimedOutboxEvent event = lease.event(); if (event.attemptCount() >= backoffPolicy.maxAttempts()) { // All attempts exhausted — DEAD-letter the event. - return deadLetter(event, cause); + return deadLetter(lease, cause); } else { // Transient failure — schedule retry with exponential backoff. Instant nextAttemptAt = backoffPolicy.nextAttemptAt(event.attemptCount(), now); - tx.inWrite(() -> store.markFailed(event.eventId(), nextAttemptAt)); + if (tx.inWrite(() -> store.markFailed(lease, nextAttemptAt)) == OutboxCompletion.STALE) { + return stale(lease, OutboxRelayResult.Outcome.FAILED); + } reportFailure( () -> OutboxRelayFailureReport.retryableFailure( @@ -172,8 +191,11 @@ public class PublishPendingOutboxEventsUseCase } } - private OutboxRelayResult.Outcome deadLetter(ClaimedOutboxEvent event, RuntimeException cause) { - tx.inWrite(() -> store.markDead(event.eventId())); + private OutboxRelayResult.Outcome deadLetter(OutboxLease lease, RuntimeException cause) { + ClaimedOutboxEvent event = lease.event(); + if (tx.inWrite(() -> store.markDead(lease)) == OutboxCompletion.STALE) { + return stale(lease, OutboxRelayResult.Outcome.DEAD); + } reportFailure( () -> OutboxRelayFailureReport.deadLetter( @@ -186,6 +208,19 @@ public class PublishPendingOutboxEventsUseCase return OutboxRelayResult.Outcome.DEAD; } + /** + * The claim expired and another relay took the row, so this relay's result was not written and + * must not be reported as a transition. The row belongs to the relay that holds it now. + */ + private OutboxRelayResult.Outcome stale(OutboxLease lease, OutboxRelayResult.Outcome attempted) { + try { + failureReporter.reportStaleCompletion(lease.eventId(), lease.event().eventType(), attempted); + } catch (RuntimeException ignored) { + // Diagnostics are non-authoritative, as for reportFailure. + } + return OutboxRelayResult.Outcome.STALE; + } + private void reportFailure(Supplier reportFactory) { try { failureReporter.report(reportFactory.get()); diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbox/v2/ClaimedOutboxDelivery.java b/src/application-core/src/main/java/dev/caskeleton/application/outbox/v2/ClaimedOutboxDelivery.java deleted file mode 100644 index d6819972..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/outbox/v2/ClaimedOutboxDelivery.java +++ /dev/null @@ -1,20 +0,0 @@ -package dev.caskeleton.application.outbox.v2; - -import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent; -import java.time.Instant; -import java.util.Objects; - -/** Exact canonical event plus mutable delivery ownership and immutable DB creation facts. */ -public record ClaimedOutboxDelivery( - OutboxDeliveryOwner owner, - ValidatedIntegrationEvent event, - Instant eventCreatedAt, - Instant deliveryCreatedAt) { - - public ClaimedOutboxDelivery { - Objects.requireNonNull(owner, "owner"); - Objects.requireNonNull(event, "event"); - Objects.requireNonNull(eventCreatedAt, "eventCreatedAt"); - Objects.requireNonNull(deliveryCreatedAt, "deliveryCreatedAt"); - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbox/v2/NewOutboxEventV2.java b/src/application-core/src/main/java/dev/caskeleton/application/outbox/v2/NewOutboxEventV2.java deleted file mode 100644 index aa6b5989..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/outbox/v2/NewOutboxEventV2.java +++ /dev/null @@ -1,70 +0,0 @@ -package dev.caskeleton.application.outbox.v2; - -import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent; -import java.util.Objects; - -/** - * Owner-safe V2 append intent. - * - *

The canonical integration event is the semantic and wire authority. This wrapper exists only - * because the V2 append port returns an owner-safe append receipt; it must not grow a second raw - * event model. - */ -public record NewOutboxEventV2(ValidatedIntegrationEvent event) { - - public NewOutboxEventV2 { - Objects.requireNonNull(event, "event"); - } - - public String eventId() { - return event.eventId().value(); - } - - public String aggregateType() { - return event.aggregate().aggregateType(); - } - - public String aggregateId() { - return event.aggregate().aggregateId(); - } - - public long aggregateVersion() { - return event.order().sequence(); - } - - public int eventOrdinal() { - return event.order().eventIndex(); - } - - public String eventType() { - return event.contractId().value(); - } - - public int eventSchema() { - return event.payloadVersion(); - } - - public String logicalDestination() { - return event.logicalDestinationId().value(); - } - - public String partitionKey() { - return event.partitionKeyText(); - } - - public String contentType() { - return event.contentType(); - } - - public String correlationId() { - return event.correlationId(); - } - - public String causationId() { - return event.causationId().orElse(null); - } - - public java.time.Instant occurredAt() { - return event.occurredAt(); - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbox/v2/OutboxAppendOutcome.java b/src/application-core/src/main/java/dev/caskeleton/application/outbox/v2/OutboxAppendOutcome.java deleted file mode 100644 index 1c7d8e35..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/outbox/v2/OutboxAppendOutcome.java +++ /dev/null @@ -1,9 +0,0 @@ -package dev.caskeleton.application.outbox.v2; - -/** Conflict-safe result of immutable identity plus event-envelope append. */ -public enum OutboxAppendOutcome { - APPENDED, - ALREADY_APPENDED_SAME_EVENT, - EVENT_ID_CONFLICT, - AGGREGATE_ORDER_CONFLICT -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbox/v2/OutboxAppendPortV2.java b/src/application-core/src/main/java/dev/caskeleton/application/outbox/v2/OutboxAppendPortV2.java deleted file mode 100644 index 26a980a2..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/outbox/v2/OutboxAppendPortV2.java +++ /dev/null @@ -1,12 +0,0 @@ -package dev.caskeleton.application.outbox.v2; - -/** - * Same-store immutable outbox append. - * - *

The implementation must participate in the caller's active primary read-write transaction; it - * must never open a repository-local transaction. - */ -public interface OutboxAppendPortV2 { - - OutboxAppendReceipt append(NewOutboxEventV2 event); -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbox/v2/OutboxAppendReceipt.java b/src/application-core/src/main/java/dev/caskeleton/application/outbox/v2/OutboxAppendReceipt.java deleted file mode 100644 index 5590584d..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/outbox/v2/OutboxAppendReceipt.java +++ /dev/null @@ -1,23 +0,0 @@ -package dev.caskeleton.application.outbox.v2; - -import java.time.LocalDate; -import java.util.Objects; - -/** Database-authoritative routing receipt for one immutable event append. */ -public record OutboxAppendReceipt( - OutboxAppendOutcome outcome, - String eventId, - LocalDate retentionBucket, - long publicationEpoch, - OutboxDispatchAuthority dispatchAuthority) { - - public OutboxAppendReceipt { - Objects.requireNonNull(outcome, "outcome"); - Objects.requireNonNull(eventId, "eventId"); - Objects.requireNonNull(retentionBucket, "retentionBucket"); - Objects.requireNonNull(dispatchAuthority, "dispatchAuthority"); - if (publicationEpoch < 1) { - throw new IllegalArgumentException("publication epoch must be positive"); - } - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbox/v2/OutboxDeliveryClaimRequest.java b/src/application-core/src/main/java/dev/caskeleton/application/outbox/v2/OutboxDeliveryClaimRequest.java deleted file mode 100644 index 4abc745b..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/outbox/v2/OutboxDeliveryClaimRequest.java +++ /dev/null @@ -1,26 +0,0 @@ -package dev.caskeleton.application.outbox.v2; - -import java.time.Duration; - -/** Bounded strict-order polling claim request. */ -public record OutboxDeliveryClaimRequest( - String destination, String claimOwner, int batchSize, Duration claimLease) { - - public OutboxDeliveryClaimRequest { - if (destination == null || destination.isBlank()) { - throw new IllegalArgumentException("destination must be present"); - } - if (claimOwner == null || claimOwner.isBlank() || claimOwner.length() > 128) { - throw new IllegalArgumentException("claim owner must contain 1-128 characters"); - } - if (batchSize < 1 || batchSize > 100) { - throw new IllegalArgumentException("batch size must be between 1 and 100"); - } - if (claimLease == null - || claimLease.isZero() - || claimLease.isNegative() - || claimLease.compareTo(Duration.ofMinutes(5)) > 0) { - throw new IllegalArgumentException("claim lease must be positive and at most PT5M"); - } - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbox/v2/OutboxDeliveryOwner.java b/src/application-core/src/main/java/dev/caskeleton/application/outbox/v2/OutboxDeliveryOwner.java deleted file mode 100644 index 11b9c3d8..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/outbox/v2/OutboxDeliveryOwner.java +++ /dev/null @@ -1,45 +0,0 @@ -package dev.caskeleton.application.outbox.v2; - -import java.time.LocalDate; -import java.util.Objects; -import java.util.regex.Pattern; - -/** Full owner/token/status-version CAS handle for one destination delivery. */ -public record OutboxDeliveryOwner( - LocalDate retentionBucket, - String eventId, - String destination, - String claimOwner, - String claimToken, - int attempt, - long version, - long publicationEpoch) { - - private static final Pattern CLAIM_TOKEN = Pattern.compile("[0-9a-f]{64}"); - - public OutboxDeliveryOwner { - Objects.requireNonNull(retentionBucket, "retentionBucket"); - requirePresent(eventId, "event ID"); - requirePresent(destination, "destination"); - requirePresent(claimOwner, "claim owner"); - if (claimToken == null || !CLAIM_TOKEN.matcher(claimToken).matches()) { - throw new IllegalArgumentException( - "claim token must be a 64-character lowercase hexadecimal value"); - } - if (attempt < 1) { - throw new IllegalArgumentException("attempt must be positive"); - } - if (version < 1) { - throw new IllegalArgumentException("version must be positive"); - } - if (publicationEpoch < 1) { - throw new IllegalArgumentException("publication epoch must be positive"); - } - } - - private static void requirePresent(String value, String name) { - if (value == null || value.isBlank()) { - throw new IllegalArgumentException(name + " must be present"); - } - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbox/v2/OutboxDeliveryTransition.java b/src/application-core/src/main/java/dev/caskeleton/application/outbox/v2/OutboxDeliveryTransition.java deleted file mode 100644 index 2962cb8f..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/outbox/v2/OutboxDeliveryTransition.java +++ /dev/null @@ -1,13 +0,0 @@ -package dev.caskeleton.application.outbox.v2; - -import dev.caskeleton.application.transaction.OperationId; -import java.util.Objects; - -/** Idempotent transition request for a claimed delivery. */ -public record OutboxDeliveryTransition(OutboxDeliveryOwner owner, OperationId operationId) { - - public OutboxDeliveryTransition { - Objects.requireNonNull(owner, "owner"); - Objects.requireNonNull(operationId, "operationId"); - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbox/v2/OutboxDeliveryTransitionOutcome.java b/src/application-core/src/main/java/dev/caskeleton/application/outbox/v2/OutboxDeliveryTransitionOutcome.java deleted file mode 100644 index 023e1618..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/outbox/v2/OutboxDeliveryTransitionOutcome.java +++ /dev/null @@ -1,15 +0,0 @@ -package dev.caskeleton.application.outbox.v2; - -/** Owner-safe polling completion/failure result. */ -public enum OutboxDeliveryTransitionOutcome { - PUBLISHED, - RETRY_SCHEDULED, - DEAD, - ALREADY_APPLIED_SAME_OPERATION, - RESULT_CONFLICT, - ABSENT, - NOT_OWNER, - NOT_CLAIMED, - STALE_VERSION, - AUTHORITY_MISMATCH -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbox/v2/OutboxDispatchAuthority.java b/src/application-core/src/main/java/dev/caskeleton/application/outbox/v2/OutboxDispatchAuthority.java deleted file mode 100644 index e6ad2527..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/outbox/v2/OutboxDispatchAuthority.java +++ /dev/null @@ -1,8 +0,0 @@ -package dev.caskeleton.application.outbox.v2; - -/** Per-row dispatch authority derived from the locked publication control row. */ -public enum OutboxDispatchAuthority { - LEGACY_SHADOW, - POLLING_V2, - CDC -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbox/v2/OutboxPollingDeliveryPortV2.java b/src/application-core/src/main/java/dev/caskeleton/application/outbox/v2/OutboxPollingDeliveryPortV2.java deleted file mode 100644 index 7e5005c6..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/outbox/v2/OutboxPollingDeliveryPortV2.java +++ /dev/null @@ -1,17 +0,0 @@ -package dev.caskeleton.application.outbox.v2; - -import java.time.Instant; -import java.util.List; - -/** Owner-safe polling delivery state machine; broker publish occurs outside its transactions. */ -public interface OutboxPollingDeliveryPortV2 { - - List claimBatch(OutboxDeliveryClaimRequest request); - - OutboxDeliveryTransitionOutcome markPublished(OutboxDeliveryTransition transition); - - OutboxDeliveryTransitionOutcome markRetryable( - OutboxDeliveryTransition transition, Instant nextAttemptAt, String errorCode); - - OutboxDeliveryTransitionOutcome markDead(OutboxDeliveryTransition transition, String errorCode); -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbox/v2/OutboxPublicationAdmissionPort.java b/src/application-core/src/main/java/dev/caskeleton/application/outbox/v2/OutboxPublicationAdmissionPort.java deleted file mode 100644 index 8013f6ad..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/outbox/v2/OutboxPublicationAdmissionPort.java +++ /dev/null @@ -1,15 +0,0 @@ -package dev.caskeleton.application.outbox.v2; - -import java.util.Optional; - -/** Bounded worker admission boundary used before a polling worker claims any database row. */ -public interface OutboxPublicationAdmissionPort { - - Optional tryAcquire(String destination); - - /** One acquired admission slot. Implementations must release the same slot exactly once. */ - @FunctionalInterface - interface Permit { - void release(); - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbox/v2/OutboxPublicationAuthority.java b/src/application-core/src/main/java/dev/caskeleton/application/outbox/v2/OutboxPublicationAuthority.java deleted file mode 100644 index 6d580abe..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/outbox/v2/OutboxPublicationAuthority.java +++ /dev/null @@ -1,8 +0,0 @@ -package dev.caskeleton.application.outbox.v2; - -/** The single database-controlled publisher authority for the primary outbox scope. */ -public enum OutboxPublicationAuthority { - LEGACY_POLLING, - POLLING_V2, - CDC -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbox/v2/OutboxV2RetryPolicy.java b/src/application-core/src/main/java/dev/caskeleton/application/outbox/v2/OutboxV2RetryPolicy.java deleted file mode 100644 index 8898a6bc..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/outbox/v2/OutboxV2RetryPolicy.java +++ /dev/null @@ -1,134 +0,0 @@ -package dev.caskeleton.application.outbox.v2; - -import java.time.DateTimeException; -import java.time.Duration; -import java.time.Instant; -import java.util.Objects; -import java.util.Optional; -import java.util.random.RandomGenerator; - -/** - * Finite automatic-publication budget for the owner-safe V2 polling candidate. - * - *

Age is anchored to immutable database timestamps, never to the first attempt. Retry scheduling - * is therefore stable across worker restarts and claim churn. - */ -public final class OutboxV2RetryPolicy { - - private static final Duration MAXIMUM_POLICY_DURATION = Duration.ofDays(30); - - private final int maximumAttempts; - private final Duration baseDelay; - private final Duration maximumDelay; - private final Duration maximumAutomaticPublicationAge; - private final Duration sameEventHorizon; - private final Duration publishTimeout; - private final Duration transitionSafetyMargin; - private final RandomGenerator random; - - public OutboxV2RetryPolicy( - int maximumAttempts, - Duration baseDelay, - Duration maximumDelay, - Duration maximumAutomaticPublicationAge, - Duration sameEventHorizon, - Duration publishTimeout, - Duration transitionSafetyMargin, - RandomGenerator random) { - if (maximumAttempts < 1 || maximumAttempts > 100) { - throw new IllegalArgumentException("maximumAttempts must be between 1 and 100"); - } - this.maximumAttempts = maximumAttempts; - this.baseDelay = positiveBounded(baseDelay, "baseDelay"); - this.maximumDelay = positiveBounded(maximumDelay, "maximumDelay"); - if (this.maximumDelay.compareTo(this.baseDelay) < 0) { - throw new IllegalArgumentException("maximumDelay must be greater than or equal to baseDelay"); - } - this.maximumAutomaticPublicationAge = - positiveBounded(maximumAutomaticPublicationAge, "maximumAutomaticPublicationAge"); - this.sameEventHorizon = positiveBounded(sameEventHorizon, "sameEventHorizon"); - this.publishTimeout = positiveBounded(publishTimeout, "publishTimeout"); - this.transitionSafetyMargin = positiveBounded(transitionSafetyMargin, "transitionSafetyMargin"); - this.random = Objects.requireNonNull(random, "random"); - } - - public int maximumAttempts() { - return maximumAttempts; - } - - public Duration publishTimeout() { - return publishTimeout; - } - - public Duration requiredClaimLease() { - try { - return publishTimeout.plus(transitionSafetyMargin); - } catch (ArithmeticException exception) { - throw new IllegalStateException("publication lease budget cannot be represented", exception); - } - } - - public Instant automaticDeadline(ClaimedOutboxDelivery delivery) { - Objects.requireNonNull(delivery, "delivery"); - try { - Instant deliveryDeadline = delivery.deliveryCreatedAt().plus(maximumAutomaticPublicationAge); - Instant sameEventDeadline = delivery.eventCreatedAt().plus(sameEventHorizon); - return deliveryDeadline.isBefore(sameEventDeadline) ? deliveryDeadline : sameEventDeadline; - } catch (DateTimeException | ArithmeticException exception) { - throw new IllegalStateException("outbox automatic deadline cannot be represented", exception); - } - } - - public boolean mayAttempt(ClaimedOutboxDelivery delivery, Instant now) { - Objects.requireNonNull(now, "now"); - return delivery.owner().attempt() <= maximumAttempts - && now.isBefore(automaticDeadline(delivery)); - } - - public Optional nextRetryAt(ClaimedOutboxDelivery delivery, Instant now) { - Objects.requireNonNull(delivery, "delivery"); - Objects.requireNonNull(now, "now"); - if (delivery.owner().attempt() >= maximumAttempts) { - return Optional.empty(); - } - - Instant deadline = automaticDeadline(delivery); - if (!now.isBefore(deadline)) { - return Optional.empty(); - } - - long baseMillis = baseDelay.toMillis(); - long maximumMillis = maximumDelay.toMillis(); - int exponent = Math.min(delivery.owner().attempt() - 1, 30); - long exponentialMillis; - try { - exponentialMillis = Math.multiplyExact(baseMillis, 1L << exponent); - } catch (ArithmeticException overflow) { - exponentialMillis = maximumMillis; - } - exponentialMillis = Math.min(exponentialMillis, maximumMillis); - long jitterMillis = random.nextLong(baseMillis + 1L); - long delayMillis; - try { - delayMillis = Math.min(maximumMillis, Math.addExact(exponentialMillis, jitterMillis)); - } catch (ArithmeticException overflow) { - delayMillis = maximumMillis; - } - - final Instant candidate; - try { - candidate = now.plusMillis(delayMillis); - } catch (DateTimeException | ArithmeticException exception) { - return Optional.empty(); - } - return candidate.isBefore(deadline) ? Optional.of(candidate) : Optional.empty(); - } - - private static Duration positiveBounded(Duration value, String name) { - Objects.requireNonNull(value, name); - if (value.isZero() || value.isNegative() || value.compareTo(MAXIMUM_POLICY_DURATION) > 0) { - throw new IllegalArgumentException(name + " must be positive and at most PT720H"); - } - return value; - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbox/v2/PublishNextOutboxDeliveryCommand.java b/src/application-core/src/main/java/dev/caskeleton/application/outbox/v2/PublishNextOutboxDeliveryCommand.java deleted file mode 100644 index a6164a02..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/outbox/v2/PublishNextOutboxDeliveryCommand.java +++ /dev/null @@ -1,17 +0,0 @@ -package dev.caskeleton.application.outbox.v2; - -import dev.caskeleton.application.command.Command; -import java.time.Duration; - -/** Scheduler command for one bounded owner-safe V2 publication attempt. */ -public record PublishNextOutboxDeliveryCommand( - String destination, String claimOwner, Duration claimLease) implements Command { - - public PublishNextOutboxDeliveryCommand { - new OutboxDeliveryClaimRequest(destination, claimOwner, 1, claimLease); - } - - OutboxDeliveryClaimRequest claimRequest() { - return new OutboxDeliveryClaimRequest(destination, claimOwner, 1, claimLease); - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbox/v2/PublishNextOutboxDeliveryResult.java b/src/application-core/src/main/java/dev/caskeleton/application/outbox/v2/PublishNextOutboxDeliveryResult.java deleted file mode 100644 index 14a4abfb..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/outbox/v2/PublishNextOutboxDeliveryResult.java +++ /dev/null @@ -1,58 +0,0 @@ -package dev.caskeleton.application.outbox.v2; - -import dev.caskeleton.application.outbox.OutboxPublishOutcome; -import java.time.Instant; -import java.util.Objects; -import java.util.Optional; - -/** One-record relay result. Empty event/outcome fields are used only before a row is claimed. */ -public record PublishNextOutboxDeliveryResult( - Status status, - Optional eventId, - Optional publishOutcome, - Optional transitionOutcome, - Optional nextAttemptAt) { - - public PublishNextOutboxDeliveryResult { - Objects.requireNonNull(status, "status"); - Objects.requireNonNull(eventId, "eventId"); - Objects.requireNonNull(publishOutcome, "publishOutcome"); - Objects.requireNonNull(transitionOutcome, "transitionOutcome"); - Objects.requireNonNull(nextAttemptAt, "nextAttemptAt"); - } - - public static PublishNextOutboxDeliveryResult notAdmitted() { - return empty(Status.NOT_ADMITTED); - } - - public static PublishNextOutboxDeliveryResult noDelivery() { - return empty(Status.NO_DELIVERY); - } - - static PublishNextOutboxDeliveryResult transitioned( - Status status, - ClaimedOutboxDelivery delivery, - OutboxPublishOutcome publishOutcome, - OutboxDeliveryTransitionOutcome transitionOutcome, - Optional nextAttemptAt) { - return new PublishNextOutboxDeliveryResult( - status, - Optional.of(delivery.owner().eventId()), - Optional.of(publishOutcome), - Optional.of(transitionOutcome), - nextAttemptAt); - } - - private static PublishNextOutboxDeliveryResult empty(Status status) { - return new PublishNextOutboxDeliveryResult( - status, Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty()); - } - - public enum Status { - NOT_ADMITTED, - NO_DELIVERY, - PUBLISHED, - RETRY_SCHEDULED, - DEAD - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/outbox/v2/PublishNextOutboxDeliveryUseCase.java b/src/application-core/src/main/java/dev/caskeleton/application/outbox/v2/PublishNextOutboxDeliveryUseCase.java deleted file mode 100644 index aaaba58f..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/outbox/v2/PublishNextOutboxDeliveryUseCase.java +++ /dev/null @@ -1,242 +0,0 @@ -package dev.caskeleton.application.outbox.v2; - -import dev.caskeleton.application.capability.Idempotency; -import dev.caskeleton.application.capability.RepositoryAccess; -import dev.caskeleton.application.capability.UseCaseCapability; -import dev.caskeleton.application.messaging.event.IntegrationEventPublishPort; -import dev.caskeleton.application.outbox.OutboxPublishOutcome; -import dev.caskeleton.application.security.RequiresPermission; -import dev.caskeleton.application.transaction.OperationId; -import dev.caskeleton.application.transaction.TransactionMode; -import dev.caskeleton.application.transaction.TransactionPort; -import dev.caskeleton.application.usecase.CommandUseCase; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.time.Clock; -import java.time.Instant; -import java.util.HexFormat; -import java.util.List; -import java.util.Objects; -import java.util.Optional; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - -/** - * Unwired owner-safe V2 polling publication policy. One invocation processes at most one record. - */ -@RequiresPermission("outbox:relay") -@UseCaseCapability( - transactionMode = TransactionMode.REQUIRES_NEW, - idempotency = Idempotency.NOT_IDEMPOTENT, - repositoryAccess = RepositoryAccess.WRITE_REPOSITORY, - externalOutboundAllowed = true) -public class PublishNextOutboxDeliveryUseCase - implements CommandUseCase { - - static final String AMBIGUOUS_ERROR = "OUTBOX_PUBLISH_AMBIGUOUS"; - static final String AMBIGUOUS_BUDGET_ERROR = "OUTBOX_AMBIGUOUS_BUDGET_EXHAUSTED"; - static final String BEFORE_SEND_REJECTION = "OUTBOX_REJECTED_BEFORE_SEND"; - static final String AFTER_BROKER_REJECTION = "OUTBOX_REJECTED_AFTER_BROKER"; - static final String DEADLINE_ERROR = "OUTBOX_AUTOMATIC_DEADLINE_EXHAUSTED"; - - private final OutboxPublicationAdmissionPort admission; - private final OutboxPollingDeliveryPortV2 deliveries; - private final IntegrationEventPublishPort publisher; - private final TransactionPort transactions; - private final OutboxV2RetryPolicy retryPolicy; - private final Clock clock; - - public PublishNextOutboxDeliveryUseCase( - OutboxPublicationAdmissionPort admission, - OutboxPollingDeliveryPortV2 deliveries, - IntegrationEventPublishPort publisher, - TransactionPort transactions, - OutboxV2RetryPolicy retryPolicy, - Clock clock) { - this.admission = Objects.requireNonNull(admission, "admission"); - this.deliveries = Objects.requireNonNull(deliveries, "deliveries"); - this.publisher = Objects.requireNonNull(publisher, "publisher"); - this.transactions = Objects.requireNonNull(transactions, "transactions"); - this.retryPolicy = Objects.requireNonNull(retryPolicy, "retryPolicy"); - this.clock = Objects.requireNonNull(clock, "clock"); - } - - @Override - public PublishNextOutboxDeliveryResult handle(PublishNextOutboxDeliveryCommand command) { - Objects.requireNonNull(command, "command"); - if (command.claimLease().compareTo(retryPolicy.requiredClaimLease()) <= 0) { - throw new IllegalArgumentException( - "claimLease must exceed publishTimeout + transitionSafetyMargin"); - } - - Optional admitted = - admission.tryAcquire(command.destination()); - if (admitted.isEmpty()) { - return PublishNextOutboxDeliveryResult.notAdmitted(); - } - - OutboxPublicationAdmissionPort.Permit permit = admitted.orElseThrow(); - try { - List claimed = - transactions.inNew(() -> deliveries.claimBatch(command.claimRequest())); - if (claimed.size() > 1) { - throw new IllegalStateException( - "one-record outbox relay claimed " + claimed.size() + " records"); - } - if (claimed.isEmpty()) { - return PublishNextOutboxDeliveryResult.noDelivery(); - } - - ClaimedOutboxDelivery delivery = claimed.getFirst(); - Instant beforePublish = clock.instant(); - if (!retryPolicy.mayAttempt(delivery, beforePublish)) { - return markDead( - delivery, - OutboxPublishOutcome.AMBIGUOUS, - DEADLINE_ERROR, - PublishNextOutboxDeliveryResult.Status.DEAD); - } - - OutboxPublishOutcome outcome = publish(delivery); - return applyOutcome(delivery, outcome); - } finally { - permit.release(); - } - } - - private OutboxPublishOutcome publish(ClaimedOutboxDelivery delivery) { - try { - return Objects.requireNonNull( - publisher - .publish(delivery.event()) - .toCompletableFuture() - .get(retryPolicy.publishTimeout().toMillis(), TimeUnit.MILLISECONDS), - "publish outcome"); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - return OutboxPublishOutcome.AMBIGUOUS; - } catch (ExecutionException | TimeoutException | RuntimeException uncertain) { - return OutboxPublishOutcome.AMBIGUOUS; - } - } - - private PublishNextOutboxDeliveryResult applyOutcome( - ClaimedOutboxDelivery delivery, OutboxPublishOutcome outcome) { - return switch (outcome) { - case CONFIRMED -> markPublished(delivery, outcome); - case AMBIGUOUS -> retryOrDead(delivery, outcome); - case REJECTED_BEFORE_SEND -> - markDead( - delivery, - outcome, - BEFORE_SEND_REJECTION, - PublishNextOutboxDeliveryResult.Status.DEAD); - case REJECTED_AFTER_BROKER -> - markDead( - delivery, - outcome, - AFTER_BROKER_REJECTION, - PublishNextOutboxDeliveryResult.Status.DEAD); - }; - } - - private PublishNextOutboxDeliveryResult retryOrDead( - ClaimedOutboxDelivery delivery, OutboxPublishOutcome outcome) { - Instant now = clock.instant(); - Optional nextAttemptAt = retryPolicy.nextRetryAt(delivery, now); - if (nextAttemptAt.isEmpty()) { - return markDead( - delivery, outcome, AMBIGUOUS_BUDGET_ERROR, PublishNextOutboxDeliveryResult.Status.DEAD); - } - - OutboxDeliveryTransition transition = transition(delivery, "RETRY_WAIT", AMBIGUOUS_ERROR); - OutboxDeliveryTransitionOutcome transitioned = - transactions.inNew( - () -> - deliveries.markRetryable(transition, nextAttemptAt.orElseThrow(), AMBIGUOUS_ERROR)); - requireTransition( - transitioned, OutboxDeliveryTransitionOutcome.RETRY_SCHEDULED, transition.operationId()); - return PublishNextOutboxDeliveryResult.transitioned( - PublishNextOutboxDeliveryResult.Status.RETRY_SCHEDULED, - delivery, - outcome, - transitioned, - nextAttemptAt); - } - - private PublishNextOutboxDeliveryResult markPublished( - ClaimedOutboxDelivery delivery, OutboxPublishOutcome outcome) { - OutboxDeliveryTransition transition = transition(delivery, "PUBLISHED", null); - OutboxDeliveryTransitionOutcome transitioned = - transactions.inNew(() -> deliveries.markPublished(transition)); - requireTransition( - transitioned, OutboxDeliveryTransitionOutcome.PUBLISHED, transition.operationId()); - return PublishNextOutboxDeliveryResult.transitioned( - PublishNextOutboxDeliveryResult.Status.PUBLISHED, - delivery, - outcome, - transitioned, - Optional.empty()); - } - - private PublishNextOutboxDeliveryResult markDead( - ClaimedOutboxDelivery delivery, - OutboxPublishOutcome outcome, - String errorCode, - PublishNextOutboxDeliveryResult.Status status) { - OutboxDeliveryTransition transition = transition(delivery, "DEAD", errorCode); - OutboxDeliveryTransitionOutcome transitioned = - transactions.inNew(() -> deliveries.markDead(transition, errorCode)); - requireTransition(transitioned, OutboxDeliveryTransitionOutcome.DEAD, transition.operationId()); - return PublishNextOutboxDeliveryResult.transitioned( - status, delivery, outcome, transitioned, Optional.empty()); - } - - private static void requireTransition( - OutboxDeliveryTransitionOutcome actual, - OutboxDeliveryTransitionOutcome expected, - OperationId operationId) { - if (actual != expected - && actual != OutboxDeliveryTransitionOutcome.ALREADY_APPLIED_SAME_OPERATION) { - throw new IllegalStateException( - "outbox V2 transition " - + operationId.value() - + " expected " - + expected - + " but was " - + actual); - } - } - - private static OutboxDeliveryTransition transition( - ClaimedOutboxDelivery delivery, String target, String errorCode) { - return new OutboxDeliveryTransition( - delivery.owner(), - operationId(delivery.owner(), target, errorCode == null ? "-" : errorCode)); - } - - static OperationId operationId(OutboxDeliveryOwner owner, String target, String errorCode) { - String material = - owner.eventId() - + "|" - + owner.publicationEpoch() - + "|" - + owner.attempt() - + "|" - + target - + "|" - + errorCode; - try { - String digest = - HexFormat.of() - .formatHex( - MessageDigest.getInstance("SHA-256") - .digest(material.getBytes(StandardCharsets.UTF_8))); - return new OperationId("outbox-v2-" + digest); - } catch (NoSuchAlgorithmException impossible) { - throw new IllegalStateException("SHA-256 unavailable", impossible); - } - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/realtime/ActorFingerprint.java b/src/application-core/src/main/java/dev/caskeleton/application/realtime/ActorFingerprint.java deleted file mode 100644 index 24925855..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/realtime/ActorFingerprint.java +++ /dev/null @@ -1,36 +0,0 @@ -package dev.caskeleton.application.realtime; - -import java.util.Objects; -import java.util.regex.Pattern; - -/** - * A pseudonymous handle for whoever is connected. - * - *

A fingerprint and never an identity, and the type exists to make that non-optional. Everything - * downstream of this port writes the value into a datastore key, a broker partition key or a metric - * tag — places with none of the access controls the application has, and places whose contents end - * up in backups, slow logs and incident screenshots. A raw user id or tenant name there is a - * disclosure that no later code change can take back. - * - *

The grammar is enforced rather than documented for the same reason: a caller that passes an - * email address gets a failure at the boundary instead of a Redis key containing an email address. - * - * @param value the fingerprint - */ -public record ActorFingerprint(String value) { - - private static final Pattern GRAMMAR = Pattern.compile("[a-zA-Z0-9][a-zA-Z0-9._:-]{7,127}"); - - public ActorFingerprint { - Objects.requireNonNull(value, "value"); - if (!GRAMMAR.matcher(value).matches()) { - throw new IllegalArgumentException( - "an actor fingerprint is 8..128 characters of [a-zA-Z0-9._:-] starting alphanumeric; a" - + " value outside that is usually a raw identifier, and this one reaches datastore" - + " keys and metric tags"); - } - if (value.indexOf('@') >= 0) { - throw new IllegalArgumentException("an address is not a fingerprint"); - } - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/realtime/ConnectionRegistration.java b/src/application-core/src/main/java/dev/caskeleton/application/realtime/ConnectionRegistration.java deleted file mode 100644 index 16352aa4..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/realtime/ConnectionRegistration.java +++ /dev/null @@ -1,42 +0,0 @@ -package dev.caskeleton.application.realtime; - -import java.time.Instant; -import java.util.Objects; - -/** - * One node's report that it is holding connections for an actor. - * - *

A report, not a fact. The node that wrote it is the only thing that knows whether the - * connections still exist, and by the time anybody reads this the node may be gone. Everything the - * registry returns therefore carries {@code observedAt}, and every reader is expected to judge it. - * - * @param actor whose connections - * @param nodeId which process is holding them - * @param channel which feed - * @param connectionCount how many the node had at that moment - * @param observedAt when it looked - */ -public record ConnectionRegistration( - ActorFingerprint actor, - RealtimeNodeId nodeId, - RealtimeChannel channel, - int connectionCount, - Instant observedAt) { - - public ConnectionRegistration { - Objects.requireNonNull(actor, "actor"); - Objects.requireNonNull(nodeId, "nodeId"); - Objects.requireNonNull(channel, "channel"); - Objects.requireNonNull(observedAt, "observedAt"); - if (connectionCount < 0) { - throw new IllegalArgumentException("a connection count cannot be negative"); - } - } - - /** Whether this report is older than the caller is willing to act on. */ - public boolean staleAt(java.time.Duration maximumAge, Instant now) { - Objects.requireNonNull(maximumAge, "maximumAge"); - Objects.requireNonNull(now, "now"); - return !now.isBefore(observedAt.plus(maximumAge)); - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/realtime/ConnectionRegistryPort.java b/src/application-core/src/main/java/dev/caskeleton/application/realtime/ConnectionRegistryPort.java deleted file mode 100644 index 9fb5a4c6..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/realtime/ConnectionRegistryPort.java +++ /dev/null @@ -1,57 +0,0 @@ -package dev.caskeleton.application.realtime; - -import java.time.Duration; -import java.time.Instant; -import java.util.List; - -/** - * Where an actor is currently connected, across every node. - * - *

A cache of state owned by other processes, and the port says so rather than leaving each - * caller to discover it. Two expiry mechanisms exist because neither covers the other's case: a TTL - * per entry removes what a node forgot to clean up, and a node heartbeat removes everything a node - * was holding when it died. A TTL alone leaves a dead node's entries live until each one - * individually expires; a heartbeat alone leaves a live node's stale entries for ever. - * - *

Nothing here is authoritative and nothing security-relevant may depend on it. An attacker who - * can stop a node reporting can move this registry's answer, so "is this actor connected" is a - * question for showing a green dot and for deciding where to route a message that will be dropped - * if it is wrong — not for deciding whether a request is legitimate. - * - *

Every implementation is expected to degrade rather than throw. A registry that is unreachable - * should report nothing found, because the caller's fallback — broadcast to the cluster and let the - * holder claim it — is correct and an exception is not. - */ -public interface ConnectionRegistryPort { - - /** - * Record that a node holds connections for an actor. - * - * @param registration what the node observed - * @param timeToLive how long the entry survives without being refreshed - */ - void announce(ConnectionRegistration registration, Duration timeToLive); - - /** Remove one node's entry for an actor. */ - void withdraw(ActorFingerprint actor, RealtimeChannel channel, RealtimeNodeId nodeId); - - /** - * Where an actor is reported connected. - * - * @param now the instant staleness is judged against; entries older than their TTL are omitted - * @return one entry per node, newest first; empty when nothing is known - */ - List locate(ActorFingerprint actor, RealtimeChannel channel, Instant now); - - /** Record that a node is alive. */ - void heartbeat(RealtimeNodeId nodeId, Instant now); - - /** - * Remove everything held by nodes that have stopped reporting. - * - * @param heartbeatTimeout how long a node may be silent before it is treated as gone - * @param now the current instant - * @return the nodes whose entries were removed - */ - List evictSilentNodes(Duration heartbeatTimeout, Instant now); -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/realtime/DurableFanoutPort.java b/src/application-core/src/main/java/dev/caskeleton/application/realtime/DurableFanoutPort.java deleted file mode 100644 index dc3f460c..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/realtime/DurableFanoutPort.java +++ /dev/null @@ -1,23 +0,0 @@ -package dev.caskeleton.application.realtime; - -/** - * At-least-once delivery to whichever node holds the recipient. - * - *

At-least-once is the contract, and saying so is the point of the name. A redeploy, a slow - * consumer or a broker rebalance all redeliver, so a receiver that assumes exactly-once will show a - * user the same thing twice on a perfectly ordinary Tuesday. Deduplication belongs at the receiver, - * keyed on the record's stream and position. - * - *

Publication is not delivery. A successful call means the transport accepted the record, which - * is a statement about the transport and not about any recipient. - */ -public interface DurableFanoutPort { - - /** - * Publish a record. - * - * @param record what to publish - * @throws DurableFanoutUnavailableException when the transport would not accept it - */ - void publish(DurableFanoutRecord record); -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/realtime/DurableFanoutRecord.java b/src/application-core/src/main/java/dev/caskeleton/application/realtime/DurableFanoutRecord.java deleted file mode 100644 index 24053a8d..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/realtime/DurableFanoutRecord.java +++ /dev/null @@ -1,67 +0,0 @@ -package dev.caskeleton.application.realtime; - -import java.time.Instant; -import java.util.Objects; -import java.util.Optional; - -/** - * One message published for delivery to whichever node holds its recipient. - * - *

{@code expiresAt} is carried on the record and checked by the receiver, not only by the - * publisher. A durable transport is exactly the one that can hold a message through an outage and - * deliver it afterwards, and for the traffic this carries — a notification, a live update — late is - * indistinguishable from wrong. The receiving node is the only place that knows what time it is - * when the message finally arrives. - * - *

The ordering pair is present or absent together. A stream id without a position cannot be - * deduplicated and a position without a stream cannot be interpreted, so half of one is a caller - * error rather than a partial ordering. - * - * @param channel which feed - * @param partitionKey what the transport should order and route by, usually the recipient - * @param payload the encoded message, as a document rather than raw bytes — a byte array cannot be - * a record component without breaking equality, and every producer here is already serialising - * through the message catalog - * @param streamId the ordering stream, when the message is ordered - * @param position the position within that stream - * @param publishedAt when it was published - * @param expiresAt after which a receiver must drop it - */ -public record DurableFanoutRecord( - RealtimeChannel channel, - String partitionKey, - String payload, - Optional streamId, - Optional position, - Instant publishedAt, - Instant expiresAt) { - - public DurableFanoutRecord { - Objects.requireNonNull(channel, "channel"); - Objects.requireNonNull(partitionKey, "partitionKey"); - Objects.requireNonNull(payload, "payload"); - Objects.requireNonNull(streamId, "streamId"); - Objects.requireNonNull(position, "position"); - Objects.requireNonNull(publishedAt, "publishedAt"); - Objects.requireNonNull(expiresAt, "expiresAt"); - if (partitionKey.isBlank()) { - throw new IllegalArgumentException( - "a blank partition key sends every message to one partition, which serialises the whole" - + " feed behind its slowest recipient"); - } - if (streamId.isPresent() != position.isPresent()) { - throw new IllegalArgumentException( - "a stream id and a position are meaningless apart: one cannot be deduplicated and the" - + " other cannot be interpreted"); - } - if (!expiresAt.isAfter(publishedAt)) { - throw new IllegalArgumentException("a record that expires before it is published is dropped"); - } - } - - /** Whether a receiver must drop this rather than deliver it. */ - public boolean expiredAt(Instant now) { - Objects.requireNonNull(now, "now"); - return !now.isBefore(expiresAt); - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/realtime/DurableFanoutUnavailableException.java b/src/application-core/src/main/java/dev/caskeleton/application/realtime/DurableFanoutUnavailableException.java deleted file mode 100644 index ca6b1e14..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/realtime/DurableFanoutUnavailableException.java +++ /dev/null @@ -1,30 +0,0 @@ -package dev.caskeleton.application.realtime; - -import java.util.Objects; - -/** - * The durable transport would not accept a record. - * - *

Distinct from a delivery failure, which this port cannot observe. It means the message was not - * published, so the caller still owns it — retrying, dropping it, or falling back to a best-effort - * publish are all defensible and the caller is the only one that knows which. - * - *

The channel is named and the payload is not: the payload is the user's data and this exception - * reaches logs. - */ -public final class DurableFanoutUnavailableException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - private final transient RealtimeChannel channel; - - public DurableFanoutUnavailableException(RealtimeChannel channel, Throwable cause) { - super("the durable transport did not accept a record for channel " + channel.value(), cause); - this.channel = Objects.requireNonNull(channel, "channel"); - } - - /** Which channel. */ - public RealtimeChannel channel() { - return channel; - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/realtime/EphemeralFanoutPort.java b/src/application-core/src/main/java/dev/caskeleton/application/realtime/EphemeralFanoutPort.java deleted file mode 100644 index a640d8ea..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/realtime/EphemeralFanoutPort.java +++ /dev/null @@ -1,39 +0,0 @@ -package dev.caskeleton.application.realtime; - -import java.util.function.BiConsumer; - -/** - * Best-effort delivery to every node listening on a channel. - * - *

Ephemeral is the whole contract and it is stated in the name because the alternative is that - * somebody assumes otherwise. A message published here reaches the nodes that are subscribed at - * that instant and nobody else: a node that is restarting misses it, a subscriber that reconnects a - * second later misses it, and nothing is retained, retried or acknowledged. There is no replay. - * - *

That is the right shape for presence updates, typing indicators and cache invalidations — - * things whose next update supersedes the one that was lost. It is the wrong shape for anything a - * user is told happened, and {@link DurableFanoutPort} exists for those. - */ -public interface EphemeralFanoutPort { - - /** - * Publish to everyone currently listening. - * - * @param channel where to publish - * @param payload the encoded message - * @return how many subscribers the transport reported, which is a diagnostic and not a delivery - * guarantee — the count is what the broker saw, not what any node processed - */ - long publish(RealtimeChannel channel, byte[] payload); - - /** - * Listen on a channel. - * - * @param channel what to listen to - * @param listener receives the channel name and the payload; must not block, because it runs on - * the transport's delivery thread and a slow listener stalls every other subscription sharing - * it - */ - FanoutSubscription subscribe( - RealtimeChannel channel, BiConsumer listener); -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/realtime/FanoutSubscription.java b/src/application-core/src/main/java/dev/caskeleton/application/realtime/FanoutSubscription.java deleted file mode 100644 index d75b244e..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/realtime/FanoutSubscription.java +++ /dev/null @@ -1,19 +0,0 @@ -package dev.caskeleton.application.realtime; - -/** - * A live subscription to a channel. - * - *

{@link AutoCloseable} because the subscription holds a connection, and one that is never - * closed is a connection that is never returned. A node that opens one per stream and closes none - * runs out of Redis connections at whatever its stream churn happens to be, which looks like Redis - * being unavailable and is not. - */ -public interface FanoutSubscription extends AutoCloseable { - - /** Whether the subscription is still delivering. */ - boolean active(); - - /** Stop delivering and release the connection. Idempotent. */ - @Override - void close(); -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/realtime/RealtimeChannel.java b/src/application-core/src/main/java/dev/caskeleton/application/realtime/RealtimeChannel.java deleted file mode 100644 index 8401ddfb..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/realtime/RealtimeChannel.java +++ /dev/null @@ -1,26 +0,0 @@ -package dev.caskeleton.application.realtime; - -import java.util.Objects; -import java.util.regex.Pattern; - -/** - * A logical channel: which feed a registration, a fan-out or a replay belongs to. - * - *

Kept separate from the transport's own endpoint or destination names so that a change to a URL - * is not a change to a Redis key or a broker topic. The two drift on purpose — a path can be - * renamed for a client's benefit without invalidating every entry a cluster is holding. - * - * @param value the channel name - */ -public record RealtimeChannel(String value) { - - private static final Pattern GRAMMAR = Pattern.compile("[a-z0-9][a-z0-9._-]{0,63}"); - - public RealtimeChannel { - Objects.requireNonNull(value, "value"); - if (!GRAMMAR.matcher(value).matches()) { - throw new IllegalArgumentException( - "a channel is 1..64 lowercase characters of [a-z0-9._-] starting alphanumeric: " + value); - } - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/realtime/RealtimeNodeId.java b/src/application-core/src/main/java/dev/caskeleton/application/realtime/RealtimeNodeId.java deleted file mode 100644 index 13b1e959..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/realtime/RealtimeNodeId.java +++ /dev/null @@ -1,26 +0,0 @@ -package dev.caskeleton.application.realtime; - -import java.util.Objects; -import java.util.regex.Pattern; - -/** - * Which process reported something. - * - *

Constrained because it is both a datastore key component and a metric tag. An unconstrained - * node id is an unbounded-cardinality tag on every metric that carries it, and in a deployment that - * names nodes after pods that is one new tag value per restart. - * - * @param value the node identity - */ -public record RealtimeNodeId(String value) { - - private static final Pattern GRAMMAR = Pattern.compile("[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}"); - - public RealtimeNodeId { - Objects.requireNonNull(value, "value"); - if (!GRAMMAR.matcher(value).matches()) { - throw new IllegalArgumentException( - "a node id is 1..64 characters of [a-zA-Z0-9._-] starting alphanumeric: " + value); - } - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/transaction/CompletionResolution.java b/src/application-core/src/main/java/dev/caskeleton/application/transaction/CompletionResolution.java deleted file mode 100644 index f64f1502..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/transaction/CompletionResolution.java +++ /dev/null @@ -1,21 +0,0 @@ -package dev.caskeleton.application.transaction; - -/** - * What reconciliation concluded about a transaction whose commit outcome was unknown (design - * §17.4). - * - *

{@link #STILL_UNKNOWN} is a legitimate answer, and keeping it is the point. Forcing a binary - * result would push the resolver into guessing, and a wrong guess either duplicates a payment or - * loses one. - */ -public enum CompletionResolution { - - /** Evidence shows the transaction committed; the use case must not be re-run. */ - COMMITTED, - - /** Evidence shows the transaction did not commit; the use case may be re-run. */ - NOT_COMMITTED, - - /** No conclusive evidence; the record stays in the reconciliation queue. */ - STILL_UNKNOWN -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/transaction/PolicyTransactionPort.java b/src/application-core/src/main/java/dev/caskeleton/application/transaction/PolicyTransactionPort.java deleted file mode 100644 index 4029558a..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/transaction/PolicyTransactionPort.java +++ /dev/null @@ -1,13 +0,0 @@ -package dev.caskeleton.application.transaction; - -import java.util.function.Supplier; - -/** - * Additive transaction port for named policies and explicit outcomes. - * - *

{@link TransactionPort} remains source-compatible for existing callers and fakes. - */ -public interface PolicyTransactionPort extends TransactionPort { - - TransactionResult inTransaction(TransactionRequest request, Supplier action); -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/transaction/ReconciliationReference.java b/src/application-core/src/main/java/dev/caskeleton/application/transaction/ReconciliationReference.java deleted file mode 100644 index b0b09730..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/transaction/ReconciliationReference.java +++ /dev/null @@ -1,24 +0,0 @@ -package dev.caskeleton.application.transaction; - -import java.util.Objects; - -/** - * Sanitized, bounded reference that an operator or application workflow can use to reconcile an - * uncertain transaction outcome. - */ -public record ReconciliationReference(String value) { - - private static final int MAXIMUM_LENGTH = 256; - - public ReconciliationReference { - Objects.requireNonNull(value, "value must be non-null"); - if (value.isBlank() || value.length() > MAXIMUM_LENGTH || !isPrintableAscii(value)) { - throw new IllegalArgumentException( - "reconciliation reference must contain 1-256 printable non-whitespace ASCII characters"); - } - } - - private static boolean isPrintableAscii(String value) { - return value.chars().allMatch(character -> character >= 0x21 && character <= 0x7e); - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/transaction/TransactionAdmissionException.java b/src/application-core/src/main/java/dev/caskeleton/application/transaction/TransactionAdmissionException.java deleted file mode 100644 index dbd4373d..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/transaction/TransactionAdmissionException.java +++ /dev/null @@ -1,18 +0,0 @@ -package dev.caskeleton.application.transaction; - -/** - * A transaction was rejected before application work started because its policy, route, or - * remaining deadline could not be honored. - */ -public final class TransactionAdmissionException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - public TransactionAdmissionException(String message) { - super(message); - } - - public TransactionAdmissionException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/transaction/TransactionCompletionResolver.java b/src/application-core/src/main/java/dev/caskeleton/application/transaction/TransactionCompletionResolver.java deleted file mode 100644 index e3b21f87..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/transaction/TransactionCompletionResolver.java +++ /dev/null @@ -1,29 +0,0 @@ -package dev.caskeleton.application.transaction; - -/** - * The domain-specific SPI that decides whether an unknown transaction actually committed (design - * §17.4). - * - *

An outbound SPI in application-core, not in the persistence adapter. It used to live beside - * the JPA transaction engine while its own documentation said the domain implements it — which the - * domain cannot do without importing an outbound adapter, inverting the dependency. Declaring it - * here means the adapter depends on the contract and the domain implements it, both pointing the - * same way. - * - *

The core cannot implement this. Only the domain knows which unique constraint, idempotency - * record, business row, or outbox entry proves the write happened, so the platform provides the - * question and the domain provides the evidence. - * - * @param the application's transaction key type - */ -@FunctionalInterface -public interface TransactionCompletionResolver { - - /** - * Resolves one unknown transaction against domain evidence. - * - *

Implementations must read evidence only. Re-running the original use case from a resolver is - * the exact duplicate-write this design forbids. - */ - CompletionResolution resolve(K transactionKey); -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/transaction/TransactionOutcome.java b/src/application-core/src/main/java/dev/caskeleton/application/transaction/TransactionOutcome.java deleted file mode 100644 index 9a3be547..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/transaction/TransactionOutcome.java +++ /dev/null @@ -1,10 +0,0 @@ -package dev.caskeleton.application.transaction; - -/** Framework-neutral outcome of an application transaction boundary. */ -public enum TransactionOutcome { - COMMITTED, - PARTICIPATING_PENDING_OUTER, - DETERMINATE_ROLLBACK, - INDETERMINATE, - COMMITTED_WITH_POST_COMMIT_FAILURE -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/transaction/TransactionPhase.java b/src/application-core/src/main/java/dev/caskeleton/application/transaction/TransactionPhase.java deleted file mode 100644 index 080b68d4..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/transaction/TransactionPhase.java +++ /dev/null @@ -1,12 +0,0 @@ -package dev.caskeleton.application.transaction; - -/** Last safely observed phase of a physical transaction. */ -public enum TransactionPhase { - ROUTE_ADMISSION, - CONNECTION_ACQUIRED, - ACTIVE, - FLUSHED, - COMMIT_REQUESTED, - COMMIT_ACKED, - SYNCHRONIZATION_CLEANUP -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/transaction/TransactionPolicyId.java b/src/application-core/src/main/java/dev/caskeleton/application/transaction/TransactionPolicyId.java deleted file mode 100644 index 25763e3b..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/transaction/TransactionPolicyId.java +++ /dev/null @@ -1,45 +0,0 @@ -package dev.caskeleton.application.transaction; - -/** - * Allowlisted application transaction policies. - * - *

Callers select semantic policy IDs rather than framework propagation, isolation, route, or - * timeout numbers. Legacy facade policies remain adapter-internal and are intentionally absent. - */ -public enum TransactionPolicyId { - COMMAND_DEFAULT(false, true), - COMMAND_SERIALIZABLE_REPLAY_SAFE(false, true), - QUERY_PRIMARY(true, false), - QUERY_REPLICA_ELIGIBLE(true, false), - OUTBOX_APPEND(false, false), - INBOX_AND_HANDLER(false, true), - MAINTENANCE_NEW(false, true); - - private final boolean readPolicy; - private final boolean operationIdRequired; - - TransactionPolicyId(boolean readPolicy, boolean operationIdRequired) { - this.readPolicy = readPolicy; - this.operationIdRequired = operationIdRequired; - } - - public boolean isReadPolicy() { - return readPolicy; - } - - public boolean requiresOperationId() { - return operationIdRequired; - } - - public boolean supports(ReadConsistency consistency) { - if (this == QUERY_PRIMARY) { - return consistency == ReadConsistency.STRONG - || consistency == ReadConsistency.READ_YOUR_WRITES; - } - if (this == QUERY_REPLICA_ELIGIBLE) { - return consistency == ReadConsistency.EVENTUAL - || consistency == ReadConsistency.BOUNDED_STALENESS; - } - return false; - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/transaction/TransactionRequest.java b/src/application-core/src/main/java/dev/caskeleton/application/transaction/TransactionRequest.java deleted file mode 100644 index 3029aacd..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/transaction/TransactionRequest.java +++ /dev/null @@ -1,38 +0,0 @@ -package dev.caskeleton.application.transaction; - -import dev.caskeleton.application.outbound.CallBudget; -import java.util.Objects; -import java.util.Optional; - -/** One framework-neutral request to execute an allowlisted transaction policy. */ -public record TransactionRequest( - TransactionPolicyId policyId, - CallBudget callBudget, - Optional readConsistency, - Optional operationId) { - - public TransactionRequest { - Objects.requireNonNull(policyId, "policyId must be non-null"); - Objects.requireNonNull(callBudget, "callBudget must be non-null"); - Objects.requireNonNull(readConsistency, "readConsistency must be non-null"); - Objects.requireNonNull(operationId, "operationId must be non-null"); - - if (policyId.isReadPolicy()) { - ReadConsistency selected = - readConsistency.orElseThrow( - () -> - new IllegalArgumentException( - "readConsistency is required for " + policyId.name())); - if (!policyId.supports(selected)) { - throw new IllegalArgumentException( - "readConsistency " + selected + " is not allowed for " + policyId.name()); - } - } else if (readConsistency.isPresent()) { - throw new IllegalArgumentException("readConsistency is forbidden for " + policyId.name()); - } - - if (policyId.requiresOperationId() && operationId.isEmpty()) { - throw new IllegalArgumentException("operationId is required for " + policyId.name()); - } - } -} diff --git a/src/application-core/src/main/java/dev/caskeleton/application/transaction/TransactionResult.java b/src/application-core/src/main/java/dev/caskeleton/application/transaction/TransactionResult.java deleted file mode 100644 index 55286e86..00000000 --- a/src/application-core/src/main/java/dev/caskeleton/application/transaction/TransactionResult.java +++ /dev/null @@ -1,83 +0,0 @@ -package dev.caskeleton.application.transaction; - -import java.util.Objects; -import java.util.Optional; - -/** - * Outcome algebra for policy-based transactions. - * - *

A participant result never claims commit. An indeterminate result never grants replay - * authority. - */ -public sealed interface TransactionResult { - - TransactionOutcome outcome(); - - record Committed(T value, Optional operationId) implements TransactionResult { - - public Committed { - Objects.requireNonNull(operationId, "operationId must be non-null"); - } - - @Override - public TransactionOutcome outcome() { - return TransactionOutcome.COMMITTED; - } - } - - record Participating(T value) implements TransactionResult { - - @Override - public TransactionOutcome outcome() { - return TransactionOutcome.PARTICIPATING_PENDING_OUTER; - } - } - - record DeterminateRollback(RuntimeException failure) implements TransactionResult { - - public DeterminateRollback { - Objects.requireNonNull(failure, "failure must be non-null"); - } - - @Override - public TransactionOutcome outcome() { - return TransactionOutcome.DETERMINATE_ROLLBACK; - } - } - - record Indeterminate( - Optional operationId, - TransactionPhase lastObservedPhase, - Optional reconciliationReference) - implements TransactionResult { - - public Indeterminate { - Objects.requireNonNull(operationId, "operationId must be non-null"); - Objects.requireNonNull(lastObservedPhase, "lastObservedPhase must be non-null"); - Objects.requireNonNull(reconciliationReference, "reconciliationReference must be non-null"); - if (operationId.isEmpty() && reconciliationReference.isPresent()) { - throw new IllegalArgumentException("reconciliationReference requires a stable operationId"); - } - } - - @Override - public TransactionOutcome outcome() { - return TransactionOutcome.INDETERMINATE; - } - } - - record CommittedWithPostCommitFailure( - T value, Optional operationId, RuntimeException operationalFailure) - implements TransactionResult { - - public CommittedWithPostCommitFailure { - Objects.requireNonNull(operationId, "operationId must be non-null"); - Objects.requireNonNull(operationalFailure, "operationalFailure must be non-null"); - } - - @Override - public TransactionOutcome outcome() { - return TransactionOutcome.COMMITTED_WITH_POST_COMMIT_FAILURE; - } - } -} diff --git a/src/application-core/src/test/java/dev/caskeleton/application/cache/CacheAsideExecutorTest.java b/src/application-core/src/test/java/dev/caskeleton/application/cache/CacheAsideExecutorTest.java deleted file mode 100644 index 0e41eefb..00000000 --- a/src/application-core/src/test/java/dev/caskeleton/application/cache/CacheAsideExecutorTest.java +++ /dev/null @@ -1,889 +0,0 @@ -package dev.caskeleton.application.cache; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.time.Clock; -import java.time.Duration; -import java.time.Instant; -import java.time.ZoneOffset; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicReference; -import org.junit.jupiter.api.Test; - -@SuppressWarnings("deprecation") -class CacheAsideExecutorTest { - - private static final Instant NOW = Instant.parse("2026-07-28T00:00:00Z"); - private static final Instant SOFT_EXPIRES_AT = NOW.plusSeconds(30); - private static final Instant HARD_EXPIRES_AT = NOW.plusSeconds(60); - private static final CacheObservationToken OBSERVATION = - new CacheObservationToken("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"); - - @Test - void freshAndNegativeHitsNeverInvokeTheSource() { - AtomicInteger loads = new AtomicInteger(); - CacheAsideExecutor executor = - executor(policy(), Clock.fixed(NOW, ZoneOffset.UTC)); - FakeRegion fresh = - new FakeRegion( - new CacheLookup.Hit<>( - "cached", CacheLookup.Freshness.FRESH, "rev-1", SOFT_EXPIRES_AT, HARD_EXPIRES_AT)); - FakeRegion negative = - new FakeRegion( - new CacheLookup.NegativeHit<>(AuthoritativeAbsence.NOT_FOUND, HARD_EXPIRES_AT)); - - CacheResult freshResult = - executor.getOrLoad( - "key", fresh, loader(loads, new SourceLoadOutcome.Loaded<>("source", "rev-2"))); - CacheResult negativeResult = - executor.getOrLoad( - "key", negative, loader(loads, new SourceLoadOutcome.Loaded<>("source", "rev-2"))); - - assertThat(freshResult).isEqualTo(new CacheResult.FreshHit<>("cached", "rev-1")); - assertThat(negativeResult) - .isEqualTo(new CacheResult.NegativeHit<>(AuthoritativeAbsence.NOT_FOUND)); - assertThat(loads).hasValue(0); - } - - @Test - void recordsLoadedValuesAndOnlyClassifiedAuthoritativeAbsenceAsNegative() { - CacheAsideExecutor executor = - executor(policy(), Clock.fixed(NOW, ZoneOffset.UTC)); - FakeRegion loadedRegion = new FakeRegion(new CacheLookup.Miss<>(CacheLookup.MissReason.ABSENT)); - FakeRegion absentRegion = new FakeRegion(new CacheLookup.Miss<>(CacheLookup.MissReason.ABSENT)); - FakeRegion failedRegion = new FakeRegion(new CacheLookup.Miss<>(CacheLookup.MissReason.ABSENT)); - SourceFailure transientFailure = - new SourceFailure("SOURCE_TIMEOUT", new IllegalStateException()); - - CacheResult loaded = - executor.getOrLoad( - "loaded", - loadedRegion, - (key, cancellation) -> new SourceLoadOutcome.Loaded<>("value", "rev-2")); - CacheResult absent = - executor.getOrLoad( - "absent", - absentRegion, - (key, cancellation) -> - new SourceLoadOutcome.AuthoritativeAbsent<>( - AuthoritativeAbsence.NOT_FOUND, "rev-3")); - CacheResult failed = - executor.getOrLoad( - "failed", - failedRegion, - (key, cancellation) -> new SourceLoadOutcome.TransientFailure<>(transientFailure)); - - assertThat(loaded) - .isEqualTo( - new CacheResult.LoadedFromSource<>("value", "rev-2", CacheRecordOutcome.RECORDED)); - assertThat(loadedRegion.positiveRecords).containsExactly("loaded"); - assertThat(loadedRegion.recordIntents).containsExactly(CacheRecordIntent.ONLY_IF_ABSENT); - assertThat(absent) - .isEqualTo( - new CacheResult.AuthoritativeAbsent<>( - AuthoritativeAbsence.NOT_FOUND, "rev-3", CacheRecordOutcome.RECORDED)); - assertThat(absentRegion.negativeRecords).containsExactly("absent"); - assertThat(absentRegion.recordIntents).containsExactly(CacheRecordIntent.ONLY_IF_ABSENT); - assertThat(failed) - .isEqualTo( - new CacheResult.SourceFailed<>( - transientFailure, CacheResult.SourceFailureKind.TRANSIENT)); - assertThat(failedRegion.negativeRecords).isEmpty(); - } - - @Test - void servesStaleOnlyAfterAClassifiedTransientFailure() { - SourceFailure transientFailure = - new SourceFailure("SOURCE_TIMEOUT", new IllegalStateException()); - SourceFailure permanentFailure = - new SourceFailure("SOURCE_REJECTED", new IllegalArgumentException()); - FakeRegion region = - new FakeRegion( - new CacheLookup.Hit<>( - "stale", - CacheLookup.Freshness.STALE, - "rev-1", - NOW.minusSeconds(1), - HARD_EXPIRES_AT, - OBSERVATION)); - - CacheResult transientResult = - executor(policy(), Clock.fixed(NOW, ZoneOffset.UTC)) - .getOrLoad( - "key", - region, - (key, cancellation) -> new SourceLoadOutcome.TransientFailure<>(transientFailure)); - CacheResult permanentResult = - executor(policy(), Clock.fixed(NOW, ZoneOffset.UTC)) - .getOrLoad( - "key", - region, - (key, cancellation) -> new SourceLoadOutcome.PermanentFailure<>(permanentFailure)); - - assertThat(transientResult) - .isEqualTo( - new CacheResult.StaleFallbackAfterTransientFailure<>( - "stale", "rev-1", transientFailure)); - assertThat(permanentResult) - .isEqualTo( - new CacheResult.SourceFailed<>( - permanentFailure, CacheResult.SourceFailureKind.PERMANENT)); - } - - @Test - void neverServesAStaleCandidateAfterItsHardExpiry() { - MutableClock clock = new MutableClock(NOW); - SourceFailure transientFailure = - new SourceFailure("SOURCE_TIMEOUT", new IllegalStateException()); - FakeRegion region = - new FakeRegion( - new CacheLookup.Hit<>( - "stale", - CacheLookup.Freshness.STALE, - "rev-1", - NOW.minusSeconds(1), - NOW.plusSeconds(1), - OBSERVATION)); - - CacheResult result = - executor(policy(), clock) - .getOrLoad( - "key", - region, - (key, cancellation) -> { - clock.advance(Duration.ofSeconds(2)); - return new SourceLoadOutcome.TransientFailure<>(transientFailure); - }); - - assertThat(result) - .isEqualTo( - new CacheResult.SourceFailed<>( - transientFailure, CacheResult.SourceFailureKind.TRANSIENT)); - } - - @Test - void conditionallyReplacesApprovedSchemaAndRefusesAnUnobservableEntry() { - AtomicInteger loads = new AtomicInteger(); - FakeRegion reloadable = - new FakeRegion( - new CacheLookup.IncompatibleSchema<>( - CacheLookup.SchemaCategory.RETIRED_VERSION, - CacheLookup.SchemaPolicy.QUARANTINE_AND_RELOAD, - OBSERVATION)); - - CacheResult reloaded = - executor(policy(), Clock.fixed(NOW, ZoneOffset.UTC)) - .getOrLoad( - "key", reloadable, loader(loads, new SourceLoadOutcome.Loaded<>("value", "rev-2"))); - - assertThat(reloaded) - .isEqualTo( - new CacheResult.LoadedFromSource<>("value", "rev-2", CacheRecordOutcome.RECORDED)); - assertThat(reloadable.recordIntents).containsExactly(CacheRecordIntent.ONLY_IF_OBSERVED); - assertThat(reloadable.observedTokens).containsExactly(OBSERVATION); - assertThat(loads).hasValue(1); - - FakeRegion unobservable = - new FakeRegion( - new CacheLookup.IncompatibleSchema<>( - CacheLookup.SchemaCategory.RETIRED_VERSION, - CacheLookup.SchemaPolicy.QUARANTINE_AND_RELOAD)); - - CacheResult refused = - executor(policy(), Clock.fixed(NOW, ZoneOffset.UTC)) - .getOrLoad( - "key", - unobservable, - loader(loads, new SourceLoadOutcome.Loaded<>("must-not-load", "rev-3"))); - - assertThat(refused) - .isEqualTo( - new CacheResult.IncompatibleSchema<>( - CacheLookup.SchemaCategory.RETIRED_VERSION, CacheLookup.SchemaPolicy.FAIL_FAST)); - assertThat(loads).hasValue(1); - } - - @Test - void propagatesAnUnclassifiedExceptionAsTheSameInstanceAndCleansTheFlight() { - CacheAsideExecutor executor = - executor(policy(), Clock.fixed(NOW, ZoneOffset.UTC)); - FakeRegion region = new FakeRegion(new CacheLookup.Miss<>(CacheLookup.MissReason.ABSENT)); - IllegalStateException original = new IllegalStateException("do not translate"); - - assertThatThrownBy( - () -> - executor.getOrLoad( - "key", - region, - (key, cancellation) -> { - throw original; - })) - .isSameAs(original); - - assertThat( - executor.getOrLoad( - "key", - region, - (key, cancellation) -> new SourceLoadOutcome.Loaded<>("recovered", "rev-2"))) - .isEqualTo( - new CacheResult.LoadedFromSource<>("recovered", "rev-2", CacheRecordOutcome.RECORDED)); - } - - @Test - void concurrentSameKeyMissesInvokeTheLoaderOnce() throws Exception { - CacheAsideExecutor executor = executor(policy(), Clock.systemUTC()); - FakeRegion region = new FakeRegion(new CacheLookup.Miss<>(CacheLookup.MissReason.ABSENT)); - AtomicInteger loads = new AtomicInteger(); - CountDownLatch entered = new CountDownLatch(1); - CountDownLatch release = new CountDownLatch(1); - ExecutorService pool = Executors.newFixedThreadPool(4); - try { - List>> futures = new ArrayList<>(); - for (int index = 0; index < 4; index++) { - futures.add( - pool.submit( - () -> - executor.getOrLoad( - "same-key", - region, - (key, cancellation) -> { - loads.incrementAndGet(); - entered.countDown(); - await(release); - return new SourceLoadOutcome.Loaded<>("value", "rev-1"); - }))); - } - assertThat(entered.await(5, TimeUnit.SECONDS)).isTrue(); - awaitWaiterCount(executor, "same-key", 3); - release.countDown(); - - for (Future> future : futures) { - assertThat(future.get(5, TimeUnit.SECONDS)) - .isEqualTo( - new CacheResult.LoadedFromSource<>("value", "rev-1", CacheRecordOutcome.RECORDED)); - } - assertThat(loads).hasValue(1); - assertThat(region.positiveRecords).containsExactly("same-key"); - } finally { - pool.shutdownNow(); - assertThat(pool.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); - } - } - - @Test - void loadDeadlineRejectsLateResultsWithoutRecordingThem() { - MutableClock clock = new MutableClock(NOW); - CacheAsideExecutor executor = executor(policy(), clock); - FakeRegion region = new FakeRegion(new CacheLookup.Miss<>(CacheLookup.MissReason.ABSENT)); - - CacheResult result = - executor.getOrLoad( - "key", - region, - (key, cancellation) -> { - assertThat(cancellation.deadline()).isEqualTo(NOW.plusSeconds(5)); - clock.advance(Duration.ofSeconds(6)); - return new SourceLoadOutcome.Loaded<>("late", "rev-1"); - }); - - assertThat(result) - .isEqualTo(new CacheResult.Rejected<>(CacheResult.RejectionReason.LOAD_TIMEOUT)); - assertThat(region.positiveRecords).isEmpty(); - } - - @Test - void invalidationDuringLoadRejectsTheOldCapturedWriteCondition() throws Exception { - CacheWriteCondition initiallyCaptured = new CacheWriteCondition("generation-a.revision-a"); - CacheWriteCondition afterInvalidation = new CacheWriteCondition("generation-a.revision-b"); - GenerationGuardedFakeRegion region = - new GenerationGuardedFakeRegion(initiallyCaptured, afterInvalidation); - CountDownLatch sourceEntered = new CountDownLatch(1); - CountDownLatch releaseSource = new CountDownLatch(1); - ExecutorService pool = Executors.newSingleThreadExecutor(); - try { - Future> result = - pool.submit( - () -> - executor(policy(), Clock.fixed(NOW, ZoneOffset.UTC)) - .getOrLoad( - "key", - region, - (key, cancellation) -> { - sourceEntered.countDown(); - await(releaseSource); - return new SourceLoadOutcome.Loaded<>("old-source-value", "opaque-rev"); - })); - - assertThat(sourceEntered.await(5, TimeUnit.SECONDS)).isTrue(); - assertThat(region.invalidate("key")).isEqualTo(CacheInvalidationOutcome.INVALIDATED); - releaseSource.countDown(); - - assertThat(result.get(5, TimeUnit.SECONDS)) - .isEqualTo( - new CacheResult.LoadedFromSource<>( - "old-source-value", "opaque-rev", CacheRecordOutcome.NOT_RECORDED_CONDITION)); - assertThat(region.recordedConditions).containsExactly(initiallyCaptured); - assertThat(region.visibleValue).isNull(); - assertThat(region.currentCondition).isEqualTo(afterInvalidation); - } finally { - pool.shutdownNow(); - assertThat(pool.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); - } - } - - @Test - void distributedSoftLeaseLetsOnePodRefreshWhileAContenderReturnsStale() throws Exception { - SharedCoordinator coordinator = new SharedCoordinator(); - CacheRefreshCoordinationPolicy refreshPolicy = refreshPolicy(); - CacheAsideExecutor first = - new CacheAsideExecutor<>(policy(), Clock.systemUTC(), coordinator, refreshPolicy); - CacheAsideExecutor second = - new CacheAsideExecutor<>(policy(), Clock.systemUTC(), coordinator, refreshPolicy); - Instant now = Instant.now(); - FakeRegion stale = - new FakeRegion( - new CacheLookup.Hit<>( - "stale", - CacheLookup.Freshness.STALE, - "rev-1", - now.minusSeconds(1), - now.plusSeconds(30), - OBSERVATION)); - CountDownLatch ownerEntered = new CountDownLatch(1); - CountDownLatch releaseOwner = new CountDownLatch(1); - AtomicInteger loads = new AtomicInteger(); - ExecutorService pool = Executors.newSingleThreadExecutor(); - try { - Future> owner = - pool.submit( - () -> - first.getOrLoad( - "key", - stale, - (key, cancellation) -> { - loads.incrementAndGet(); - ownerEntered.countDown(); - await(releaseOwner); - return new SourceLoadOutcome.Loaded<>("refreshed", "rev-2"); - })); - assertThat(ownerEntered.await(5, TimeUnit.SECONDS)).isTrue(); - - assertThat( - second.getOrLoad( - "key", - stale, - loader(loads, new SourceLoadOutcome.Loaded<>("must-not-load", "rev-contender")))) - .isEqualTo( - new CacheResult.StaleRefreshDeferred<>( - "stale", "rev-1", CacheResult.RefreshDeferralReason.CONTENDED)); - - releaseOwner.countDown(); - assertThat(owner.get(5, TimeUnit.SECONDS)) - .isEqualTo( - new CacheResult.LoadedFromSource<>( - "refreshed", "rev-2", CacheRecordOutcome.RECORDED)); - assertThat(loads).hasValue(1); - assertThat(coordinator.maximumOwners).hasValue(1); - } finally { - releaseOwner.countDown(); - pool.shutdownNow(); - assertThat(pool.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); - } - } - - @Test - void localSingleFlightBoundsRefreshClaimsAndSourceLoadsToOnePerKey() throws Exception { - SharedCoordinator coordinator = new SharedCoordinator(); - CacheAsideExecutor executor = - new CacheAsideExecutor<>(policy(), Clock.systemUTC(), coordinator, refreshPolicy()); - Instant now = Instant.now(); - FakeRegion stale = - new FakeRegion( - new CacheLookup.Hit<>( - "stale", - CacheLookup.Freshness.STALE, - "rev-1", - now.minusSeconds(1), - now.plusSeconds(30), - OBSERVATION)); - AtomicInteger loads = new AtomicInteger(); - CountDownLatch ownerEntered = new CountDownLatch(1); - CountDownLatch releaseOwner = new CountDownLatch(1); - ExecutorService pool = Executors.newFixedThreadPool(4); - try { - List>> results = new ArrayList<>(); - for (int index = 0; index < 4; index++) { - results.add( - pool.submit( - () -> - executor.getOrLoad( - "key", - stale, - (key, cancellation) -> { - loads.incrementAndGet(); - ownerEntered.countDown(); - await(releaseOwner); - return new SourceLoadOutcome.Loaded<>("refreshed", "rev-2"); - }))); - } - assertThat(ownerEntered.await(5, TimeUnit.SECONDS)).isTrue(); - awaitWaiterCount(executor, "key", 3); - releaseOwner.countDown(); - - for (Future> result : results) { - assertThat(result.get(5, TimeUnit.SECONDS)) - .isEqualTo( - new CacheResult.LoadedFromSource<>( - "refreshed", "rev-2", CacheRecordOutcome.RECORDED)); - } - assertThat(loads).hasValue(1); - assertThat(coordinator.sequences).hasValue(1); - assertThat(coordinator.maximumOwners).hasValue(1); - } finally { - releaseOwner.countDown(); - pool.shutdownNow(); - assertThat(pool.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); - } - } - - @Test - void ownerDoubleChecksAndSkipsTheSourceWhenAnotherPodAlreadyRefreshed() { - SequencedRegion region = - new SequencedRegion( - new CacheLookup.Hit<>( - "stale", - CacheLookup.Freshness.STALE, - "rev-1", - NOW.minusSeconds(1), - HARD_EXPIRES_AT, - OBSERVATION), - new CacheLookup.Hit<>( - "fresh", - CacheLookup.Freshness.FRESH, - "rev-2", - NOW.plusSeconds(30), - NOW.plusSeconds(60))); - SharedCoordinator coordinator = new SharedCoordinator(); - AtomicInteger loads = new AtomicInteger(); - - CacheResult result = - new CacheAsideExecutor( - policy(), Clock.fixed(NOW, ZoneOffset.UTC), coordinator, refreshPolicy()) - .getOrLoad( - "key", - region, - loader(loads, new SourceLoadOutcome.Loaded<>("must-not-load", "rev-3"))); - - assertThat(result).isEqualTo(new CacheResult.FreshHit<>("fresh", "rev-2")); - assertThat(loads).hasValue(0); - assertThat(coordinator.releases).hasValue(1); - } - - @Test - void hardMissNormalLoadDoesNotUseTheSoftLease() { - CountingCoordinator coordinator = new CountingCoordinator(); - CacheResult result = - new CacheAsideExecutor( - policy(), Clock.fixed(NOW, ZoneOffset.UTC), coordinator, refreshPolicy()) - .getOrLoad( - "key", - new FakeRegion(new CacheLookup.Miss<>(CacheLookup.MissReason.ABSENT)), - (key, cancellation) -> new SourceLoadOutcome.Loaded<>("source", "rev-1")); - - assertThat(result) - .isEqualTo( - new CacheResult.LoadedFromSource<>("source", "rev-1", CacheRecordOutcome.RECORDED)); - assertThat(coordinator.calls).hasValue(0); - } - - @Test - void hardMissBoundedWaitObservesAnotherPodsFillBeforeFallingBackToSource() { - ContendedCoordinator coordinator = new ContendedCoordinator(); - SequencedRegion region = - new SequencedRegion( - new CacheLookup.Miss<>(CacheLookup.MissReason.ABSENT), - new CacheLookup.Hit<>( - "filled-by-owner", - CacheLookup.Freshness.FRESH, - "rev-2", - NOW.plusSeconds(30), - NOW.plusSeconds(60))); - AtomicInteger loads = new AtomicInteger(); - CacheRefreshCoordinationPolicy boundedWait = - new CacheRefreshCoordinationPolicy( - Duration.ofSeconds(10), - CacheRefreshCoordinationPolicy.HardMissPolicy.BOUNDED_WAIT_THEN_SOURCE_LOAD, - Duration.ofMillis(1)); - - CacheResult result = - new CacheAsideExecutor( - policy(), Clock.fixed(NOW, ZoneOffset.UTC), coordinator, boundedWait) - .getOrLoad( - "key", - region, - loader(loads, new SourceLoadOutcome.Loaded<>("must-not-load", "rev-3"))); - - assertThat(result).isEqualTo(new CacheResult.FreshHit<>("filled-by-owner", "rev-2")); - assertThat(loads).hasValue(0); - assertThat(coordinator.claims).hasValue(1); - } - - @Test - void indeterminateClaimIsRetriedOnceWithTheSameOperation() { - IndeterminateThenOwnedCoordinator coordinator = new IndeterminateThenOwnedCoordinator(); - FakeRegion stale = - new FakeRegion( - new CacheLookup.Hit<>( - "stale", - CacheLookup.Freshness.STALE, - "rev-1", - NOW.minusSeconds(1), - HARD_EXPIRES_AT, - OBSERVATION)); - - CacheResult result = - new CacheAsideExecutor( - policy(), Clock.fixed(NOW, ZoneOffset.UTC), coordinator, refreshPolicy()) - .getOrLoad( - "key", - stale, - (key, cancellation) -> new SourceLoadOutcome.Loaded<>("refreshed", "rev-2")); - - assertThat(result) - .isEqualTo( - new CacheResult.LoadedFromSource<>("refreshed", "rev-2", CacheRecordOutcome.RECORDED)); - assertThat(coordinator.attempts).hasSize(2); - assertThat(coordinator.attempts.get(0)).isSameAs(coordinator.attempts.get(1)); - } - - private static CacheRefreshCoordinationPolicy refreshPolicy() { - return new CacheRefreshCoordinationPolicy( - Duration.ofSeconds(10), - CacheRefreshCoordinationPolicy.HardMissPolicy.NORMAL_SOURCE_LOAD, - Duration.ZERO); - } - - private static CacheAsidePolicy policy() { - return new CacheAsidePolicy(16, 8, 4, Duration.ofMillis(100), Duration.ofSeconds(5), true); - } - - private static CacheAsideExecutor executor(CacheAsidePolicy policy, Clock clock) { - return new CacheAsideExecutor<>(policy, clock); - } - - private static CacheSourceLoader loader( - AtomicInteger loads, SourceLoadOutcome outcome) { - return (key, cancellation) -> { - loads.incrementAndGet(); - return outcome; - }; - } - - private static void await(CountDownLatch latch) { - try { - latch.await(); - } catch (InterruptedException exception) { - Thread.currentThread().interrupt(); - throw new AssertionError(exception); - } - } - - private static void awaitWaiterCount( - CacheAsideExecutor executor, String key, int expected) { - long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); - while (executor.inFlightWaiterCount(key) != expected && System.nanoTime() < deadline) { - Thread.onSpinWait(); - } - assertThat(executor.inFlightWaiterCount(key)).isEqualTo(expected); - } - - private static final class FakeRegion implements CacheRegionPort { - - private final CacheLookup lookup; - private final List positiveRecords = new ArrayList<>(); - private final List negativeRecords = new ArrayList<>(); - private final List recordIntents = new ArrayList<>(); - private final List observedTokens = new ArrayList<>(); - private CacheInvalidationOutcome invalidationOutcome = CacheInvalidationOutcome.INVALIDATED; - - private FakeRegion(CacheLookup lookup) { - this.lookup = lookup; - } - - @Override - public CacheLookup lookup(String key) { - return lookup; - } - - @Override - public synchronized CacheRecordOutcome record( - String key, String value, CacheRecordMetadata metadata) { - positiveRecords.add(key); - recordIntents.add(metadata.intent()); - observedTokens.add(metadata.observedToken()); - return CacheRecordOutcome.RECORDED; - } - - @Override - public synchronized CacheRecordOutcome recordAbsent( - String key, AuthoritativeAbsence reason, CacheRecordMetadata metadata) { - negativeRecords.add(key); - recordIntents.add(metadata.intent()); - observedTokens.add(metadata.observedToken()); - return CacheRecordOutcome.RECORDED; - } - - @Override - public synchronized CacheInvalidationOutcome invalidate(String key) { - return invalidationOutcome; - } - - @Override - public CacheInvalidationOutcome invalidateRegion() { - return invalidationOutcome; - } - } - - private static final class GenerationGuardedFakeRegion - implements CacheRegionPort { - - private final CacheWriteCondition invalidatedCondition; - private final List recordedConditions = new ArrayList<>(); - private volatile CacheWriteCondition currentCondition; - private volatile String visibleValue; - - private GenerationGuardedFakeRegion( - CacheWriteCondition initiallyCaptured, CacheWriteCondition invalidatedCondition) { - this.currentCondition = initiallyCaptured; - this.invalidatedCondition = invalidatedCondition; - } - - @Override - public CacheLookup lookup(String key) { - return new CacheLookup.Miss<>(CacheLookup.MissReason.ABSENT, currentCondition); - } - - @Override - public synchronized CacheRecordOutcome record( - String key, String value, CacheRecordMetadata metadata) { - recordedConditions.add(metadata.writeCondition()); - if (!metadata.writeCondition().equals(currentCondition)) { - return CacheRecordOutcome.NOT_RECORDED_CONDITION; - } - visibleValue = value; - return CacheRecordOutcome.RECORDED; - } - - @Override - public CacheRecordOutcome recordAbsent( - String key, AuthoritativeAbsence reason, CacheRecordMetadata metadata) { - return record(key, reason.name(), metadata); - } - - @Override - public synchronized CacheInvalidationOutcome invalidate(String key) { - currentCondition = invalidatedCondition; - visibleValue = null; - return CacheInvalidationOutcome.INVALIDATED; - } - - @Override - public CacheInvalidationOutcome invalidateRegion() { - return invalidate("*"); - } - } - - private static final class SequencedRegion implements CacheRegionPort { - - private final CacheLookup first; - private final CacheLookup subsequent; - private final AtomicInteger lookups = new AtomicInteger(); - - private SequencedRegion(CacheLookup first, CacheLookup subsequent) { - this.first = first; - this.subsequent = subsequent; - } - - @Override - public CacheLookup lookup(String key) { - return lookups.getAndIncrement() == 0 ? first : subsequent; - } - - @Override - public CacheRecordOutcome record(String key, String value, CacheRecordMetadata metadata) { - return CacheRecordOutcome.RECORDED; - } - - @Override - public CacheRecordOutcome recordAbsent( - String key, AuthoritativeAbsence reason, CacheRecordMetadata metadata) { - return CacheRecordOutcome.RECORDED; - } - - @Override - public CacheInvalidationOutcome invalidate(String key) { - return CacheInvalidationOutcome.INVALIDATED; - } - - @Override - public CacheInvalidationOutcome invalidateRegion() { - return CacheInvalidationOutcome.INVALIDATED; - } - } - - private static final class SharedCoordinator implements CacheRefreshCoordinationPort { - - private final AtomicInteger sequences = new AtomicInteger(); - private final AtomicReference owner = new AtomicReference<>(); - private final AtomicInteger owners = new AtomicInteger(); - private final AtomicInteger maximumOwners = new AtomicInteger(); - private final AtomicInteger releases = new AtomicInteger(); - - @Override - public CacheRefreshClaimAttempt newAttempt() { - int sequence = sequences.incrementAndGet(); - return new CacheRefreshClaimAttempt( - new CacheRefreshOwnerToken("owner-token-%011d".formatted(sequence)), - new CacheRefreshOperationToken("operation-%012d".formatted(sequence))); - } - - @Override - public CacheRefreshClaimOutcome claim( - String key, CacheRefreshClaimAttempt attempt, Duration leaseTimeToLive) { - CacheRefreshClaimAttempt current = owner.get(); - if (current != null) { - return current.equals(attempt) - ? new CacheRefreshClaimOutcome.AlreadyOwned(attempt) - : new CacheRefreshClaimOutcome.Contended(); - } - if (owner.compareAndSet(null, attempt)) { - int active = owners.incrementAndGet(); - maximumOwners.accumulateAndGet(active, Math::max); - return new CacheRefreshClaimOutcome.Claimed(attempt); - } - return new CacheRefreshClaimOutcome.Contended(); - } - - @Override - public CacheRefreshReleaseOutcome release(String key, CacheRefreshClaimAttempt attempt) { - if (!owner.compareAndSet(attempt, null)) { - return new CacheRefreshReleaseOutcome.NotOwner(); - } - owners.decrementAndGet(); - releases.incrementAndGet(); - return new CacheRefreshReleaseOutcome.Released(); - } - } - - private static final class CountingCoordinator implements CacheRefreshCoordinationPort { - - private final AtomicInteger calls = new AtomicInteger(); - - @Override - public CacheRefreshClaimAttempt newAttempt() { - calls.incrementAndGet(); - return CacheRefreshClaimAttempt.unavailable(); - } - - @Override - public CacheRefreshClaimOutcome claim( - String key, CacheRefreshClaimAttempt attempt, Duration leaseTimeToLive) { - calls.incrementAndGet(); - return new CacheRefreshClaimOutcome.Disabled(); - } - - @Override - public CacheRefreshReleaseOutcome release(String key, CacheRefreshClaimAttempt attempt) { - calls.incrementAndGet(); - return new CacheRefreshReleaseOutcome.Disabled(); - } - } - - private static final class IndeterminateThenOwnedCoordinator - implements CacheRefreshCoordinationPort { - - private final List attempts = new ArrayList<>(); - private final AtomicInteger claims = new AtomicInteger(); - - @Override - public CacheRefreshClaimAttempt newAttempt() { - return new CacheRefreshClaimAttempt( - new CacheRefreshOwnerToken("AAAAAAAAAAAAAAAAAAAAAA"), - new CacheRefreshOperationToken("BBBBBBBBBBBBBBBBBBBBBB")); - } - - @Override - public CacheRefreshClaimOutcome claim( - String key, CacheRefreshClaimAttempt attempt, Duration leaseTimeToLive) { - attempts.add(attempt); - return claims.getAndIncrement() == 0 - ? new CacheRefreshClaimOutcome.Indeterminate() - : new CacheRefreshClaimOutcome.AlreadyOwned(attempt); - } - - @Override - public CacheRefreshReleaseOutcome release(String key, CacheRefreshClaimAttempt attempt) { - return new CacheRefreshReleaseOutcome.Released(); - } - } - - private static final class ContendedCoordinator implements CacheRefreshCoordinationPort { - - private final AtomicInteger claims = new AtomicInteger(); - - @Override - public CacheRefreshClaimAttempt newAttempt() { - return new CacheRefreshClaimAttempt( - new CacheRefreshOwnerToken("CCCCCCCCCCCCCCCCCCCCCC"), - new CacheRefreshOperationToken("DDDDDDDDDDDDDDDDDDDDDD")); - } - - @Override - public CacheRefreshClaimOutcome claim( - String key, CacheRefreshClaimAttempt attempt, Duration leaseTimeToLive) { - claims.incrementAndGet(); - return new CacheRefreshClaimOutcome.Contended(); - } - - @Override - public CacheRefreshReleaseOutcome release(String key, CacheRefreshClaimAttempt attempt) { - return new CacheRefreshReleaseOutcome.NotOwner(); - } - } - - private static final class MutableClock extends Clock { - - private Instant now; - - private MutableClock(Instant now) { - this.now = now; - } - - private void advance(Duration duration) { - now = now.plus(duration); - } - - @Override - public java.time.ZoneId getZone() { - return ZoneOffset.UTC; - } - - @Override - public Clock withZone(java.time.ZoneId zone) { - return this; - } - - @Override - public Instant instant() { - return now; - } - } -} diff --git a/src/application-core/src/test/java/dev/caskeleton/application/cache/CacheObservationContractTest.java b/src/application-core/src/test/java/dev/caskeleton/application/cache/CacheObservationContractTest.java deleted file mode 100644 index 5f70b4fc..00000000 --- a/src/application-core/src/test/java/dev/caskeleton/application/cache/CacheObservationContractTest.java +++ /dev/null @@ -1,71 +0,0 @@ -package dev.caskeleton.application.cache; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.time.Duration; -import org.junit.jupiter.api.Test; - -class CacheObservationContractTest { - - @Test - void observationEventsCarryOnlyBoundedLowCardinalityDimensions() { - CacheObservationEvent.Lookup lookup = - new CacheObservationEvent.Lookup( - "worklog-summary", - CacheObservationEvent.Tier.LOCAL_L1, - CacheObservationEvent.LookupResult.HIT, - Duration.ofSeconds(2)); - CacheObservationEvent.LocalMaintenance maintenance = - new CacheObservationEvent.LocalMaintenance( - "worklog-summary", - CacheObservationEvent.MaintenanceAction.RECONCILE, - CacheObservationEvent.MaintenanceResult.FLUSHED, - CacheObservationEvent.MaintenanceCause.GENERATION_CHANGED, - 7); - - assertThat(lookup.cacheName()).isEqualTo("worklog-summary"); - assertThat(lookup.entryAge()).isEqualTo(Duration.ofSeconds(2)); - assertThat(maintenance.affectedEntries()).isEqualTo(7); - assertThat(lookup.toString()).doesNotContain("semantic-key"); - } - - @Test - void observationEventsRejectHighCardinalityOrUnboundedValues() { - assertThatThrownBy( - () -> - new CacheObservationEvent.Lookup( - "WorkLog/42", - CacheObservationEvent.Tier.LOCAL_L1, - CacheObservationEvent.LookupResult.HIT, - Duration.ZERO)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("cacheName"); - - assertThatThrownBy( - () -> - new CacheObservationEvent.LocalMaintenance( - "worklog", - CacheObservationEvent.MaintenanceAction.EVICT, - CacheObservationEvent.MaintenanceResult.SUCCESS, - CacheObservationEvent.MaintenanceCause.TTL, - -1)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("affectedEntries"); - } - - @Test - void disabledObservationPortIsReusableAndHasNoFrameworkDependency() { - CacheObservationPort first = DisabledCacheObservationPort.instance(); - CacheObservationPort second = DisabledCacheObservationPort.instance(); - - first.observe( - new CacheObservationEvent.Lookup( - "worklog", - CacheObservationEvent.Tier.REDIS_L2, - CacheObservationEvent.LookupResult.MISS, - Duration.ZERO)); - - assertThat(first).isSameAs(second); - } -} diff --git a/src/application-core/src/test/java/dev/caskeleton/application/cache/CacheRefreshCoordinationContractTest.java b/src/application-core/src/test/java/dev/caskeleton/application/cache/CacheRefreshCoordinationContractTest.java deleted file mode 100644 index e7f2ef61..00000000 --- a/src/application-core/src/test/java/dev/caskeleton/application/cache/CacheRefreshCoordinationContractTest.java +++ /dev/null @@ -1,74 +0,0 @@ -package dev.caskeleton.application.cache; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.time.Duration; -import org.junit.jupiter.api.Test; - -class CacheRefreshCoordinationContractTest { - - @Test - void opaqueAttemptTokensAreBoundedAndRedacted() { - CacheRefreshOwnerToken owner = new CacheRefreshOwnerToken("AAAAAAAAAAAAAAAAAAAAAA"); - CacheRefreshOperationToken operation = new CacheRefreshOperationToken("BBBBBBBBBBBBBBBBBBBBBB"); - CacheRefreshClaimAttempt attempt = new CacheRefreshClaimAttempt(owner, operation); - - assertThat(attempt.usable()).isTrue(); - assertThat(attempt.toString()).doesNotContain(owner.value()).doesNotContain(operation.value()); - assertThatThrownBy(() -> new CacheRefreshOwnerToken("short")) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> new CacheRefreshOperationToken("contains spaces here")) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void disabledCoordinatorIsExplicitAndHasNoOwnershipSideEffects() { - CacheRefreshCoordinationPort disabled = DisabledCacheRefreshCoordinationPort.instance(); - CacheRefreshClaimAttempt attempt = disabled.newAttempt(); - - assertThat(attempt.usable()).isFalse(); - assertThat(disabled.claim("key", attempt, Duration.ofSeconds(10))) - .isEqualTo(new CacheRefreshClaimOutcome.Disabled()); - assertThat(disabled.release("key", attempt)) - .isEqualTo(new CacheRefreshReleaseOutcome.Disabled()); - } - - @Test - void policyRequiresAFiniteLeaseBeyondTheSourceDeadlineAndMakesHardMissBehaviorExplicit() { - CacheAsidePolicy cacheAside = - new CacheAsidePolicy(16, 8, 4, Duration.ofMillis(100), Duration.ofSeconds(5), true); - - assertThatThrownBy( - () -> - new CacheRefreshCoordinationPolicy( - Duration.ofSeconds(5), - CacheRefreshCoordinationPolicy.HardMissPolicy.NORMAL_SOURCE_LOAD, - Duration.ZERO) - .validateAgainst(cacheAside)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("source load deadline"); - assertThatThrownBy( - () -> - new CacheRefreshCoordinationPolicy( - Duration.ofMinutes(5).plusMillis(1), - CacheRefreshCoordinationPolicy.HardMissPolicy.NORMAL_SOURCE_LOAD, - Duration.ZERO)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("5 minutes"); - - CacheRefreshCoordinationPolicy normal = - new CacheRefreshCoordinationPolicy( - Duration.ofSeconds(10), - CacheRefreshCoordinationPolicy.HardMissPolicy.NORMAL_SOURCE_LOAD, - Duration.ZERO); - CacheRefreshCoordinationPolicy boundedWait = - new CacheRefreshCoordinationPolicy( - Duration.ofSeconds(10), - CacheRefreshCoordinationPolicy.HardMissPolicy.BOUNDED_WAIT_THEN_SOURCE_LOAD, - Duration.ofMillis(25)); - - assertThat(normal.validateAgainst(cacheAside)).isSameAs(normal); - assertThat(boundedWait.validateAgainst(cacheAside)).isSameAs(boundedWait); - } -} diff --git a/src/application-core/src/test/java/dev/caskeleton/application/cache/CacheRegionContractTest.java b/src/application-core/src/test/java/dev/caskeleton/application/cache/CacheRegionContractTest.java index 1b73a79d..bcb9f93f 100644 --- a/src/application-core/src/test/java/dev/caskeleton/application/cache/CacheRegionContractTest.java +++ b/src/application-core/src/test/java/dev/caskeleton/application/cache/CacheRegionContractTest.java @@ -95,12 +95,4 @@ class CacheRegionContractTest { () -> new CacheRecordMetadata(" ", CacheRecordIntent.ONLY_IF_SOURCE_REVISION_NEWER)) .isInstanceOf(IllegalArgumentException.class); } - - @Test - void sourceFailureRenderingNeverLeaksTheOriginalCauseMessage() { - SourceFailure failure = - new SourceFailure("SOURCE_TIMEOUT", new IllegalStateException("sensitive upstream detail")); - - assertThat(failure.toString()).contains("SOURCE_TIMEOUT").doesNotContain("sensitive"); - } } diff --git a/src/application-core/src/test/java/dev/caskeleton/application/cache/CacheResilienceConcurrencyTest.java b/src/application-core/src/test/java/dev/caskeleton/application/cache/CacheResilienceConcurrencyTest.java deleted file mode 100644 index 1d6ea2f0..00000000 --- a/src/application-core/src/test/java/dev/caskeleton/application/cache/CacheResilienceConcurrencyTest.java +++ /dev/null @@ -1,200 +0,0 @@ -package dev.caskeleton.application.cache; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.time.Duration; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicLong; -import org.junit.jupiter.api.Test; - -class CacheResilienceConcurrencyTest { - - @Test - void singleFlightBoundsInFlightKeysAndWaitersAndCleansCompletedFlights() throws Exception { - CacheSingleFlight flights = new CacheSingleFlight<>(1, 1); - CountDownLatch leaderEntered = new CountDownLatch(1); - CountDownLatch releaseLeader = new CountDownLatch(1); - ExecutorService pool = Executors.newFixedThreadPool(2); - try { - Future> leader = - pool.submit( - () -> - flights.execute( - "first", - Duration.ofSeconds(5), - () -> { - leaderEntered.countDown(); - await(releaseLeader); - return "value"; - })); - assertThat(leaderEntered.await(5, TimeUnit.SECONDS)).isTrue(); - - Future> waiter = - pool.submit( - () -> flights.execute("first", Duration.ofSeconds(5), () -> "must-not-be-called")); - awaitWaiterCount(flights, "first", 1); - - assertThat(flights.execute("first", Duration.ZERO, () -> "must-not-be-called")) - .isEqualTo( - new CacheSingleFlight.Rejected<>(CacheSingleFlight.RejectionReason.MAXIMUM_WAITERS)); - assertThat(flights.execute("second", Duration.ZERO, () -> "must-not-be-called")) - .isEqualTo( - new CacheSingleFlight.Rejected<>( - CacheSingleFlight.RejectionReason.MAXIMUM_IN_FLIGHT_KEYS)); - - releaseLeader.countDown(); - assertThat(leader.get(5, TimeUnit.SECONDS)) - .isEqualTo(new CacheSingleFlight.Completed<>("value")); - assertThat(waiter.get(5, TimeUnit.SECONDS)) - .isEqualTo(new CacheSingleFlight.Completed<>("value")); - assertThat(flights.inFlightCount()).isZero(); - - assertThat(flights.execute("second", Duration.ZERO, () -> "next")) - .isEqualTo(new CacheSingleFlight.Completed<>("next")); - } finally { - pool.shutdownNow(); - assertThat(pool.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); - } - } - - @Test - void waiterTimeoutAndInterruptionAreFiniteAndPreserveTheInterruptFlag() throws Exception { - CacheSingleFlight flights = new CacheSingleFlight<>(1, 2); - CountDownLatch leaderEntered = new CountDownLatch(1); - CountDownLatch releaseLeader = new CountDownLatch(1); - ExecutorService pool = Executors.newFixedThreadPool(2); - try { - Future leader = - pool.submit( - () -> - flights.execute( - "key", - Duration.ofSeconds(5), - () -> { - leaderEntered.countDown(); - await(releaseLeader); - return "value"; - })); - assertThat(leaderEntered.await(5, TimeUnit.SECONDS)).isTrue(); - - assertThat(flights.execute("key", Duration.ZERO, () -> "must-not-run")) - .isEqualTo( - new CacheSingleFlight.Rejected<>(CacheSingleFlight.RejectionReason.WAIT_TIMEOUT)); - - Future interrupted = - pool.submit( - () -> { - Thread.currentThread().interrupt(); - CacheSingleFlight.Outcome result = - flights.execute("key", Duration.ofSeconds(1), () -> "must-not-run"); - return result instanceof CacheSingleFlight.Interrupted - && Thread.currentThread().isInterrupted(); - }); - assertThat(interrupted.get(5, TimeUnit.SECONDS)).isTrue(); - releaseLeader.countDown(); - leader.get(5, TimeUnit.SECONDS); - } finally { - releaseLeader.countDown(); - pool.shutdownNow(); - assertThat(pool.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); - } - } - - @Test - void sourceBulkheadBoundsConcurrencyAndPreservesAdmissionInterruption() throws Exception { - CacheSourceBulkhead bulkhead = new CacheSourceBulkhead(1); - CountDownLatch entered = new CountDownLatch(1); - CountDownLatch release = new CountDownLatch(1); - ExecutorService pool = Executors.newFixedThreadPool(2); - try { - Future> first = - pool.submit( - () -> - bulkhead.execute( - Duration.ZERO, - () -> { - entered.countDown(); - await(release); - return "value"; - })); - assertThat(entered.await(5, TimeUnit.SECONDS)).isTrue(); - assertThat(bulkhead.execute(Duration.ZERO, () -> "must-not-run")) - .isEqualTo(new CacheSourceBulkhead.Rejected<>()); - - Future interrupted = - pool.submit( - () -> { - Thread.currentThread().interrupt(); - CacheSourceBulkhead.Outcome outcome = - bulkhead.execute(Duration.ofSeconds(1), () -> "must-not-run"); - return outcome instanceof CacheSourceBulkhead.Interrupted - && Thread.currentThread().isInterrupted(); - }); - assertThat(interrupted.get(5, TimeUnit.SECONDS)).isTrue(); - release.countDown(); - assertThat(first.get(5, TimeUnit.SECONDS)) - .isEqualTo(new CacheSourceBulkhead.Completed<>("value")); - } finally { - release.countDown(); - pool.shutdownNow(); - assertThat(pool.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); - } - } - - @Test - void opportunisticallyReapsAnAbandonedFlightSoTheKeyBoundCannotLeakForever() throws Exception { - AtomicLong ticker = new AtomicLong(1_000L); - CacheSingleFlight flights = new CacheSingleFlight<>(1, 1, ticker::get); - CountDownLatch leaderEntered = new CountDownLatch(1); - CountDownLatch releaseLeader = new CountDownLatch(1); - ExecutorService pool = Executors.newSingleThreadExecutor(); - try { - Future abandoned = - pool.submit( - () -> - flights.execute( - "abandoned", - Duration.ofNanos(10), - () -> { - leaderEntered.countDown(); - await(releaseLeader); - return "late"; - })); - assertThat(leaderEntered.await(5, TimeUnit.SECONDS)).isTrue(); - ticker.addAndGet(11L); - - assertThat(flights.execute("next", Duration.ofSeconds(1), () -> "accepted")) - .isEqualTo(new CacheSingleFlight.Completed<>("accepted")); - - releaseLeader.countDown(); - abandoned.get(5, TimeUnit.SECONDS); - assertThat(flights.inFlightCount()).isZero(); - } finally { - releaseLeader.countDown(); - pool.shutdownNow(); - assertThat(pool.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); - } - } - - private static void awaitWaiterCount( - CacheSingleFlight flights, String key, int expected) { - long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); - while (flights.waiterCount(key) != expected && System.nanoTime() < deadline) { - Thread.onSpinWait(); - } - assertThat(flights.waiterCount(key)).isEqualTo(expected); - } - - private static void await(CountDownLatch latch) { - try { - latch.await(); - } catch (InterruptedException exception) { - Thread.currentThread().interrupt(); - throw new AssertionError(exception); - } - } -} diff --git a/src/application-core/src/test/java/dev/caskeleton/application/filepublication/FilePublicationContractTest.java b/src/application-core/src/test/java/dev/caskeleton/application/filepublication/FilePublicationContractTest.java deleted file mode 100644 index ee75c305..00000000 --- a/src/application-core/src/test/java/dev/caskeleton/application/filepublication/FilePublicationContractTest.java +++ /dev/null @@ -1,136 +0,0 @@ -package dev.caskeleton.application.filepublication; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.time.Instant; -import java.util.Arrays; -import java.util.List; -import java.util.Locale; -import org.junit.jupiter.api.Test; - -class FilePublicationContractTest { - - @Test - void logicalFileNameRejectsPathSyntax() { - assertThatThrownBy(() -> new LogicalFileName("../report.csv")) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> new LogicalFileName("nested/report.csv")) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> new LogicalFileName("nested\\report.csv")) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void schemaRejectsDuplicateColumnNames() { - assertThatThrownBy( - () -> - new ExportSchema( - "worklog-v1", - 1, - List.of( - new ExportSchema.Column( - "id", - ExportSchema.CellType.INTEGER, - false, - ExportSchema.FormulaPolicy.REJECT, - 64), - new ExportSchema.Column( - "id", - ExportSchema.CellType.TEXT, - false, - ExportSchema.FormulaPolicy.MITIGATE, - 128)))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("duplicate"); - } - - @Test - void schemaDefensivelyCopiesColumns() { - ExportSchema schema = - new ExportSchema( - "worklog-v1", - 1, - List.of( - new ExportSchema.Column( - "id", - ExportSchema.CellType.INTEGER, - false, - ExportSchema.FormulaPolicy.REJECT, - 64))); - - assertThat(schema.columns()).hasSize(1); - assertThatThrownBy( - () -> - schema - .columns() - .add( - new ExportSchema.Column( - "other", - ExportSchema.CellType.TEXT, - true, - ExportSchema.FormulaPolicy.MITIGATE, - 128))) - .isInstanceOf(UnsupportedOperationException.class); - } - - @Test - void requestRequiresRegisteredIdentifiersAndFormatProfile() { - ExportSchema schema = - new ExportSchema( - "worklog-v1", - 1, - List.of( - new ExportSchema.Column( - "id", - ExportSchema.CellType.INTEGER, - false, - ExportSchema.FormulaPolicy.REJECT, - 64))); - - FilePublishRequest request = - new FilePublishRequest( - new FilePublishOperationId("01J1234567890ABCDEFGHJKMNP"), - new FileDestinationId("local-export"), - new LogicalFileName("worklogs"), - new SourceRevision("snapshot-42"), - schema, - "csv-rfc4180-v1"); - - assertThat(request.formatProfileId()).isEqualTo("csv-rfc4180-v1"); - } - - @Test - void receiptReportsFileAndDirectorySyncWithoutProviderTypes() { - FilePublishReceipt receipt = - new FilePublishReceipt( - new FilePublishOperationId("01J1234567890ABCDEFGHJKMNP"), - new PublishedFileReference("publication-42"), - new FileDestinationId("local-export"), - "worklogs.csv", - new FileVersion("version-42"), - "csv-rfc4180-v1", - "text/csv", - "UTF-8", - 128, - 4, - 3, - "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", - Instant.parse("2026-07-28T00:00:00Z"), - FilePublishReceipt.PublicationGuarantee.UNIQUE_ATOMIC_CREATE, - FilePublishReceipt.DurabilityGuarantee.FILE_AND_DIRECTORY_SYNC, - 0); - - assertThat(receipt.durabilityGuarantee()) - .isEqualTo(FilePublishReceipt.DurabilityGuarantee.FILE_AND_DIRECTORY_SYNC); - assertThat( - Arrays.stream(FilePublishReceipt.class.getRecordComponents()) - .map(component -> component.getGenericType().getTypeName()) - .map(typeName -> typeName.toLowerCase(Locale.ROOT))) - .noneMatch( - typeName -> - typeName.startsWith("java.nio.file.") - || typeName.contains("fileserver") - || typeName.contains("sftp")); - } -} diff --git a/src/application-core/src/test/java/dev/caskeleton/application/idempotency/v2/IdempotencyV2ContractTest.java b/src/application-core/src/test/java/dev/caskeleton/application/idempotency/IdempotencyContractTest.java similarity index 95% rename from src/application-core/src/test/java/dev/caskeleton/application/idempotency/v2/IdempotencyV2ContractTest.java rename to src/application-core/src/test/java/dev/caskeleton/application/idempotency/IdempotencyContractTest.java index 2cab6e45..8bf1f463 100644 --- a/src/application-core/src/test/java/dev/caskeleton/application/idempotency/v2/IdempotencyV2ContractTest.java +++ b/src/application-core/src/test/java/dev/caskeleton/application/idempotency/IdempotencyContractTest.java @@ -1,15 +1,14 @@ -package dev.caskeleton.application.idempotency.v2; +package dev.caskeleton.application.idempotency; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import dev.caskeleton.application.idempotency.RequestFingerprint; import dev.caskeleton.application.transaction.OperationId; import java.nio.charset.StandardCharsets; import java.time.Duration; import org.junit.jupiter.api.Test; -class IdempotencyV2ContractTest { +class IdempotencyContractTest { private static final IdempotencyScopeDigest SCOPE = new IdempotencyScopeDigest("a".repeat(64), 3, "CREATE_WORK_LOG"); diff --git a/src/application-core/src/test/java/dev/caskeleton/application/idempotency/IdempotencyExecutorTest.java b/src/application-core/src/test/java/dev/caskeleton/application/idempotency/IdempotencyExecutorTest.java index d4e67da5..3b712843 100644 --- a/src/application-core/src/test/java/dev/caskeleton/application/idempotency/IdempotencyExecutorTest.java +++ b/src/application-core/src/test/java/dev/caskeleton/application/idempotency/IdempotencyExecutorTest.java @@ -3,292 +3,337 @@ package dev.caskeleton.application.idempotency; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import java.nio.charset.StandardCharsets; -import java.time.Clock; +import dev.caskeleton.application.transaction.OperationId; import java.time.Duration; import java.time.Instant; -import java.time.ZoneId; -import java.time.ZoneOffset; -import java.util.Map; import java.util.Optional; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicBoolean; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +/** + * The request-replay lifecycle, over the contract the stores implement. + * + *

Carried over from a test of the same name that exercised the duplicate V2 contract in the + * parent package — the one nothing implements. The behaviours below are the ones worth keeping: the + * action runs at most once, a lost response is reconciled rather than re-run, and an outcome the + * caller cannot classify is never recorded as "no effect". + * + *

One behaviour is new, because the contract is: every confirmed transition hands back the owner + * with its state revision advanced, and the next call must present that handle rather than the one + * the claim returned. + */ class IdempotencyExecutorTest { - private static final Instant T0 = Instant.parse("2026-06-09T00:00:00Z"); - private static final Duration DEFAULT_TTL = Duration.ofHours(24); + private static final String OWNER_TOKEN = "b".repeat(64); + private static final OperationId OPERATION = new OperationId("operation-aaaaaaaaaa"); + private static final IdempotencyScopeDigest SCOPE = + new IdempotencyScopeDigest("a".repeat(64), 1, "CREATE_WORKLOG"); + private static final RequestFingerprint FINGERPRINT = new RequestFingerprint("c".repeat(64)); + private static final IdempotencyClaimAttempt ATTEMPT = + new IdempotencyClaimAttempt(OWNER_TOKEN, OPERATION); + private static final Instant LEASE_UNTIL = Instant.parse("2026-07-29T12:00:30Z"); - private static final IdempotencyScope SCOPE = - IdempotencyScope.of("user-42", "key-abc", "CreateWorkLogUseCase"); - private static final RequestFingerprint FP_A = - RequestFingerprint.ofSha256("body-A".getBytes(StandardCharsets.UTF_8)); - private static final RequestFingerprint FP_B = - RequestFingerprint.ofSha256("body-B".getBytes(StandardCharsets.UTF_8)); - - private static final IdempotentResponseCodec STRING_CODEC = - new IdempotentResponseCodec<>() { - @Override - public String serialize(String result) { - return result; - } - - @Override - public String deserialize(String payload) { - return payload; - } - }; + private static IdempotencyOwner owner(long stateRevision) { + return new IdempotencyOwner(SCOPE, OWNER_TOKEN, 1, stateRevision, OPERATION); + } @Test - void firstCallerRunsActionOnceAndStoresResponse() { + @DisplayName("the action runs only after a confirmed start, and then completes") + void actionRunsOnlyAfterAConfirmedStart() { FakeStore store = new FakeStore(); - MutableClock clock = new MutableClock(T0); - AtomicInteger runs = new AtomicInteger(); - IdempotencyExecutor executor = - new IdempotencyExecutor(store, clock, DEFAULT_TTL, clock.sleeper()); + store.claim = new IdempotencyClaimOutcome.Acquired(owner(0), LEASE_UNTIL); + store.start = IdempotencyStartOutcome.STARTED; + AtomicBoolean ran = new AtomicBoolean(); String result = - executor.execute( - IdempotencyContext.of(SCOPE, FP_A), - () -> { - runs.incrementAndGet(); - return "created"; - }, - STRING_CODEC); + executor(store) + .execute( + SCOPE, + FINGERPRINT, + ATTEMPT, + () -> { + ran.set(true); + return new IdempotentAction.Outcome.Success<>("created"); + }, + codec()); assertThat(result).isEqualTo("created"); - assertThat(runs.get()).isEqualTo(1); - assertThat(store.find(SCOPE, T0)) - .hasValueSatisfying(r -> assertThat(r.status()).isEqualTo(IdempotencyStatus.COMPLETED)); + assertThat(ran).isTrue(); + assertThat(store.completeCalls).isEqualTo(1); + assertThat(store.failedCalls).isZero(); } @Test - void duplicateWithSameBodyReplaysWithoutRerunningAction() { + @DisplayName("each mutation presents the owner handle the previous one returned") + void theAdvancedOwnerHandleIsCarriedForward() { + // The contract's whole point. The store advances the state revision on a confirmed transition + // and refuses a stale one; a caller that kept presenting the claim's original handle would be + // refused by its own store, so an owner-safe store would buy nothing. FakeStore store = new FakeStore(); - MutableClock clock = new MutableClock(T0); - AtomicInteger runs = new AtomicInteger(); - IdempotencyExecutor executor = - new IdempotencyExecutor(store, clock, DEFAULT_TTL, clock.sleeper()); + store.claim = new IdempotencyClaimOutcome.Acquired(owner(0), LEASE_UNTIL); + store.start = IdempotencyStartOutcome.STARTED; + store.startOwner = owner(1); - executor.execute( - IdempotencyContext.of(SCOPE, FP_A), - () -> { - runs.incrementAndGet(); - return "created"; - }, - STRING_CODEC); - String replay = - executor.execute( - IdempotencyContext.of(SCOPE, FP_A), - () -> { - runs.incrementAndGet(); - return "SHOULD-NOT-RUN"; - }, - STRING_CODEC); + executor(store) + .execute( + SCOPE, + FINGERPRINT, + ATTEMPT, + () -> new IdempotentAction.Outcome.Success<>("created"), + codec()); - assertThat(replay).isEqualTo("created"); - assertThat(runs.get()).as("action runs exactly once across the duplicate").isEqualTo(1); + assertThat(store.completeOwner.stateRevision()) + .as("complete must present the revision the start returned, not the claim's") + .isEqualTo(1); } @Test - void sameKeyDifferentBodyIsRejectedAsMismatch() { + @DisplayName("an indeterminate claim is reconciled rather than re-run") + void anIndeterminateClaimIsReconciled() { FakeStore store = new FakeStore(); - MutableClock clock = new MutableClock(T0); - IdempotencyExecutor executor = - new IdempotencyExecutor(store, clock, DEFAULT_TTL, clock.sleeper()); - executor.execute(IdempotencyContext.of(SCOPE, FP_A), () -> "created", STRING_CODEC); + store.claim = new IdempotencyClaimOutcome.Indeterminate(OPERATION); + store.inspection = + new IdempotencyInspection( + IdempotencyInspectionOutcome.EXECUTING_SAME_OPERATION, + Optional.of(owner(1)), + Optional.of(LEASE_UNTIL), + Optional.empty(), + Optional.empty()); + AtomicBoolean ran = new AtomicBoolean(); - assertThatThrownBy( - () -> executor.execute(IdempotencyContext.of(SCOPE, FP_B), () -> "other", STRING_CODEC)) - .isInstanceOf(IdempotencyRequestMismatchException.class); - } - - @Test - void concurrentInFlightArrivalWaitsThenSurfaces409() { - FakeStore store = new FakeStore(); - MutableClock clock = new MutableClock(T0); - // Another caller has already claimed the scope and is still running. - store.tryBegin(SCOPE, FP_A, T0.plus(Duration.ofHours(1))); - IdempotencyExecutor executor = - new IdempotencyExecutor(store, clock, DEFAULT_TTL, clock.sleeper()); - - assertThatThrownBy( - () -> executor.execute(IdempotencyContext.of(SCOPE, FP_A), () -> "x", STRING_CODEC)) - .isInstanceOf(IdempotencyInFlightException.class); - // The poll loop advanced the clock by at least the 200ms in-flight window. - assertThat(Duration.between(T0, clock.instant())) - .isGreaterThanOrEqualTo(IdempotencyExecutor.IN_FLIGHT_WAIT); - } - - @Test - void inFlightThatCompletesDuringWaitReplaysTheResult() { - // The in-flight record flips to COMPLETED after the first poll sleep. - MutableClock clock = new MutableClock(T0); - FakeStore store = new FakeStore(); - store.tryBegin(SCOPE, FP_A, T0.plus(Duration.ofHours(1))); - store.completeAfterFirstFind = "winner-result"; - IdempotencyExecutor executor = - new IdempotencyExecutor(store, clock, DEFAULT_TTL, clock.sleeper()); - - String result = executor.execute(IdempotencyContext.of(SCOPE, FP_A), () -> "x", STRING_CODEC); - - assertThat(result).isEqualTo("winner-result"); - } - - @Test - void actionFailureDiscardsTheRecordSoARetryCanWin() { - FakeStore store = new FakeStore(); - MutableClock clock = new MutableClock(T0); - IdempotencyExecutor executor = - new IdempotencyExecutor(store, clock, DEFAULT_TTL, clock.sleeper()); - - assertThatThrownBy( - () -> - executor.execute( - IdempotencyContext.of(SCOPE, FP_A), + assertThat( + executor(store) + .execute( + SCOPE, + FINGERPRINT, + ATTEMPT, () -> { - throw new IllegalStateException("boom"); + ran.set(true); + return new IdempotentAction.Outcome.Success<>("created"); }, - STRING_CODEC)) - .isInstanceOf(IllegalStateException.class); - - assertThat(store.find(SCOPE, T0)).as("failed claim is discarded").isEmpty(); - String retry = - executor.execute(IdempotencyContext.of(SCOPE, FP_A), () -> "recovered", STRING_CODEC); - assertThat(retry).isEqualTo("recovered"); + codec())) + .isEqualTo("created"); + assertThat(ran).isTrue(); + assertThat(store.startCalls) + .as("the record already says EXECUTING; starting it again would be a second transition") + .isZero(); } @Test - void ttlOverrideAbove72hCapIsRejected() { - FakeStore store = new FakeStore(); - MutableClock clock = new MutableClock(T0); - IdempotencyExecutor executor = - new IdempotencyExecutor(store, clock, DEFAULT_TTL, clock.sleeper()); + @DisplayName("a lost completion is inspected without running the action a second time") + void aLostCompletionIsInspectedNotRepeated() { + FakeStore store = startedStore(); + store.complete = IdempotencyCompleteOutcome.INDETERMINATE; + store.inspectionAfterComplete = + new IdempotencyInspection( + IdempotencyInspectionOutcome.COMPLETED_REPLAY, + Optional.empty(), + Optional.empty(), + Optional.of(new StoredResponse("created")), + Optional.of(Instant.parse("2026-07-29T13:00:00Z"))); + int[] actionCalls = {0}; + + assertThat( + executor(store) + .execute( + SCOPE, + FINGERPRINT, + ATTEMPT, + () -> { + actionCalls[0]++; + return new IdempotentAction.Outcome.Success<>("created"); + }, + codec())) + .isEqualTo("created"); + assertThat(actionCalls[0]).isEqualTo(1); + assertThat(store.completeCalls).isEqualTo(1); + } + + @Test + @DisplayName("a replayed response that disagrees with this caller's is a recovery, not a result") + void aConflictingReplayIsNotReturned() { + FakeStore store = startedStore(); + store.complete = IdempotencyCompleteOutcome.INDETERMINATE; + store.inspectionAfterComplete = + new IdempotencyInspection( + IdempotencyInspectionOutcome.COMPLETED_REPLAY, + Optional.empty(), + Optional.empty(), + Optional.of(new StoredResponse("somebody-elses-answer")), + Optional.of(Instant.parse("2026-07-29T13:00:00Z"))); assertThatThrownBy( () -> - executor.execute( - IdempotencyContext.withTtl(SCOPE, FP_A, Duration.ofHours(73)), - () -> "x", - STRING_CODEC)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("72h"); + executor(store) + .execute( + SCOPE, + FINGERPRINT, + ATTEMPT, + () -> new IdempotentAction.Outcome.Success<>("created"), + codec())) + .hasMessageContaining("conflicts"); } @Test - void defaultTtlAbove72hCapIsRejectedAtConstruction() { + @DisplayName("an unclassified throw and an unknown effect are never recorded as no-effect") + void unknownEffectsAreNeverDiscarded() { + FakeStore thrown = startedStore(); + RuntimeException unclassified = new IllegalStateException("unknown effect"); + assertThatThrownBy( () -> - new IdempotencyExecutor( - new FakeStore(), new MutableClock(T0), Duration.ofHours(73))) - .isInstanceOf(IllegalArgumentException.class); + executor(thrown) + .execute( + SCOPE, + FINGERPRINT, + ATTEMPT, + () -> { + throw unclassified; + }, + codec())) + .isSameAs(unclassified); + assertThat(thrown.lastDisposition) + .isEqualTo(IdempotencyFailureDisposition.EFFECT_UNKNOWN_ABANDONED); + + FakeStore declared = startedStore(); + RuntimeException classified = new IllegalArgumentException("provider response unknown"); + assertThatThrownBy( + () -> + executor(declared) + .execute( + SCOPE, + FINGERPRINT, + ATTEMPT, + () -> new IdempotentAction.Outcome.EffectUnknown<>(classified), + codec())) + .isSameAs(classified); + assertThat(declared.lastDisposition) + .isEqualTo(IdempotencyFailureDisposition.EFFECT_UNKNOWN_ABANDONED); } @Test - void expiredRecordIsTreatedAsAbsentAndReclaimed() { + @DisplayName("only an explicitly effect-free failure is recorded as retryable") + void onlyDeclaredNoEffectIsRetryable() { + FakeStore store = startedStore(); + RuntimeException failure = new IllegalArgumentException("validation"); + + assertThatThrownBy( + () -> + executor(store) + .execute( + SCOPE, + FINGERPRINT, + ATTEMPT, + () -> new IdempotentAction.Outcome.RetryableNoEffect<>(failure), + codec())) + .isSameAs(failure); + assertThat(store.lastDisposition).isEqualTo(IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE); + } + + private static FakeStore startedStore() { FakeStore store = new FakeStore(); - store.tryBegin(SCOPE, FP_A, T0.plus(Duration.ofHours(1))); - store.complete(SCOPE, new StoredResponse("stale")); - // Clock is now past the record's expiry → replay must be refused, new run wins. - MutableClock clock = new MutableClock(T0.plus(Duration.ofHours(2))); - IdempotencyExecutor executor = - new IdempotencyExecutor(store, clock, DEFAULT_TTL, clock.sleeper()); - - String result = - executor.execute(IdempotencyContext.of(SCOPE, FP_A), () -> "fresh", STRING_CODEC); - assertThat(result).isEqualTo("fresh"); + store.claim = new IdempotencyClaimOutcome.Acquired(owner(0), LEASE_UNTIL); + store.start = IdempotencyStartOutcome.STARTED; + return store; } - // ---- test doubles ---- - - /** In-memory store keyed by storage key; honours TTL expiry in {@link #find}. */ - static final class FakeStore implements IdempotencyStorePort { - final Map rows = new ConcurrentHashMap<>(); - String completeAfterFirstFind; - private boolean firstFindSeen; - - @Override - public boolean tryBegin( - IdempotencyScope scope, RequestFingerprint fingerprint, Instant expiresAt) { - IdempotencyRecord claim = - new IdempotencyRecord( - scope, - fingerprint, - IdempotencyStatus.IN_FLIGHT, - null, - expiresAt.minusSeconds(1), - expiresAt); - return rows.putIfAbsent(scope.storageKey(), claim) == null; - } - - @Override - public Optional find(IdempotencyScope scope, Instant now) { - IdempotencyRecord record = rows.get(scope.storageKey()); - if (record == null) { - return Optional.empty(); - } - if (record.isExpiredAt(now)) { - // Lazy expiry: an expired row is reclaimable, so purge it on read. - rows.remove(scope.storageKey(), record); - return Optional.empty(); - } - // Simulate the concurrent winner completing mid-wait. - if (completeAfterFirstFind != null - && firstFindSeen - && record.status() == IdempotencyStatus.IN_FLIGHT) { - complete(scope, new StoredResponse(completeAfterFirstFind)); - record = rows.get(scope.storageKey()); - } - firstFindSeen = true; - return Optional.of(record); - } - - @Override - public void complete(IdempotencyScope scope, StoredResponse response) { - rows.compute( - scope.storageKey(), - (k, cur) -> - new IdempotencyRecord( - cur.scope(), - cur.fingerprint(), - IdempotencyStatus.COMPLETED, - response, - cur.createdAt(), - cur.expiresAt())); - } - - @Override - public void discard(IdempotencyScope scope) { - rows.remove(scope.storageKey()); - } + private static IdempotencyExecutor executor(FakeStore store) { + return new IdempotencyExecutor( + store, Duration.ofSeconds(30), Duration.ofHours(1), Duration.ofHours(1), "json-v2", 1); } - /** A clock whose {@code instant()} is advanced explicitly by the test sleeper. */ - static final class MutableClock extends Clock { - private Instant instant; + private static IdempotentResponseCodec codec() { + return new IdempotentResponseCodec<>() { + @Override + public String serialize(String result) { + return result; + } - MutableClock(Instant start) { - this.instant = start; - } + @Override + public String deserialize(String payload) { + return payload; + } + }; + } - Sleeper sleeper() { - return duration -> instant = instant.plus(duration); + private static final class FakeStore implements IdempotencyStorePort { + + private IdempotencyClaimOutcome claim; + private IdempotencyStartOutcome start; + private IdempotencyOwner startOwner; + private IdempotencyCompleteOutcome complete = IdempotencyCompleteOutcome.COMPLETED; + private IdempotencyInspection inspection = + IdempotencyInspection.outcome(IdempotencyInspectionOutcome.UNAVAILABLE); + private IdempotencyInspection inspectionAfterComplete; + private int startCalls; + private int completeCalls; + private int failedCalls; + private IdempotencyOwner completeOwner; + private IdempotencyFailureDisposition lastDisposition; + + @Override + public IdempotencyClaimAttempt newClaimAttempt(OperationId operationId) { + return new IdempotencyClaimAttempt(OWNER_TOKEN, operationId); } @Override - public Instant instant() { - return instant; + public IdempotencyClaimOutcome claim(IdempotencyClaimRequest request) { + return claim; } @Override - public ZoneId getZone() { - return ZoneOffset.UTC; + public IdempotencyMutationResult markExecutionStarted( + IdempotencyOwner owner, OperationId operationId) { + startCalls++; + IdempotencyOwner advanced = + start.carriesOwner() ? (startOwner == null ? owner : startOwner) : null; + return new IdempotencyMutationResult<>( + start, advanced, IdempotencyStartOutcome::carriesOwner); } @Override - public Clock withZone(ZoneId zone) { - return this; + public IdempotencyMutationResult renew( + IdempotencyOwner owner, Duration processingLeaseTtl, OperationId operationId) { + throw new UnsupportedOperationException("the executor does not renew"); + } + + @Override + public IdempotencyCompleteOutcome complete( + IdempotencyOwner owner, + StoredResponse response, + Duration replayTtl, + OperationId operationId) { + completeCalls++; + completeOwner = owner; + if (inspectionAfterComplete != null) { + inspection = inspectionAfterComplete; + } + return complete; + } + + @Override + public IdempotencyFailOutcome markFailed( + IdempotencyOwner owner, + IdempotencyFailureDisposition disposition, + Duration retention, + OperationId operationId) { + failedCalls++; + lastDisposition = disposition; + return disposition == IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE + ? IdempotencyFailOutcome.MARKED_RETRYABLE + : IdempotencyFailOutcome.MARKED_ABANDONED; + } + + @Override + public IdempotencyReleaseOutcome releaseBeforeExecution( + IdempotencyOwner owner, OperationId operationId) { + throw new UnsupportedOperationException("the executor never releases before execution"); + } + + @Override + public IdempotencyInspection inspect(IdempotencyInspectionRequest request) { + return inspection; } } } diff --git a/src/application-core/src/test/java/dev/caskeleton/application/idempotency/IdempotencyScopeTest.java b/src/application-core/src/test/java/dev/caskeleton/application/idempotency/IdempotencyScopeTest.java deleted file mode 100644 index 0f321f83..00000000 --- a/src/application-core/src/test/java/dev/caskeleton/application/idempotency/IdempotencyScopeTest.java +++ /dev/null @@ -1,53 +0,0 @@ -package dev.caskeleton.application.idempotency; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import org.junit.jupiter.api.Test; - -class IdempotencyScopeTest { - - @Test - void tripleScopeHasNoTenantDimension() { - IdempotencyScope scope = IdempotencyScope.of("user-1", "key-1", "RegisterUserUseCase"); - assertThat(scope.isTenantScoped()).isFalse(); - assertThat(scope.tenant()).isNull(); - assertThat(scope.storageKey()).isEqualTo("user-1::key-1::RegisterUserUseCase"); - } - - @Test - void tenantScopePrependsTheTenantDimension() { - IdempotencyScope scope = IdempotencyScope.of("acme", "user-1", "key-1", "RegisterUserUseCase"); - assertThat(scope.isTenantScoped()).isTrue(); - assertThat(scope.storageKey()).isEqualTo("acme::user-1::key-1::RegisterUserUseCase"); - } - - @Test - void blankTenantCollapsesToSingleTenantTriple() { - IdempotencyScope scope = IdempotencyScope.of(" ", "user-1", "key-1", "RegisterUserUseCase"); - assertThat(scope.isTenantScoped()).isFalse(); - } - - @Test - void missingPrincipalIsRejectedToPreventGlobalCollision() { - // design record §실패 모드: a scope-less key would replay another caller's response. - assertThatThrownBy(() -> IdempotencyScope.of(" ", "key-1", "UseCase")) - .isInstanceOf(IdempotencyScopeMissingException.class) - .satisfies( - e -> - assertThat(((IdempotencyScopeMissingException) e).missingDimension()) - .isEqualTo("principal")); - } - - @Test - void missingIdempotencyKeyIsRejected() { - assertThatThrownBy(() -> IdempotencyScope.of("user-1", null, "UseCase")) - .isInstanceOf(IdempotencyScopeMissingException.class); - } - - @Test - void missingUseCaseNameIsRejected() { - assertThatThrownBy(() -> IdempotencyScope.of("user-1", "key-1", "")) - .isInstanceOf(IdempotencyScopeMissingException.class); - } -} diff --git a/src/application-core/src/test/java/dev/caskeleton/application/idempotency/IdempotencyV2ContractSingularityTest.java b/src/application-core/src/test/java/dev/caskeleton/application/idempotency/IdempotencyV2ContractSingularityTest.java deleted file mode 100644 index c724409f..00000000 --- a/src/application-core/src/test/java/dev/caskeleton/application/idempotency/IdempotencyV2ContractSingularityTest.java +++ /dev/null @@ -1,72 +0,0 @@ -package dev.caskeleton.application.idempotency; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * The owner-safe request-replay contract exists in one package. - * - *

It existed in two. {@code dev.caskeleton.application.idempotency} declared a full {@code - * IdempotencyStorePortV2}, executor and outcome algebra, and {@code - * dev.caskeleton.application.idempotency.v2} declared another set under the same simple names. - * Every store — the Redis adapter and the PostgreSQL owner-safe one — implemented the {@code v2} - * contract, and nothing anywhere implemented the parent-package one. - * - *

That is not a harmless leftover. The composition root counts beans by type to decide whether a - * provider selection is complete, and a count taken against the unimplemented copy is a count that - * can never reach one: selecting a provider then failed with "ambiguous or incomplete" while every - * configured provider was present and correct. A second contract under the same names also means an - * import list decides which algebra a new adapter is written against, and the compiler cannot tell - * the author they picked the one no executor drives. - * - *

So the check is on the name, not on behaviour: the duplicate must stay deleted, because the - * failure it caused was invisible in every test that constructed its own store. - */ -class IdempotencyV2ContractSingularityTest { - - private static final String V2_PACKAGE = "dev.caskeleton.application.idempotency.v2."; - private static final String PARENT_PACKAGE = "dev.caskeleton.application.idempotency."; - - private static final String[] V2_TYPES = { - "IdempotencyStorePortV2", - "IdempotencyExecutorV2", - "IdempotencyClaimAttempt", - "IdempotencyClaimOutcome", - "IdempotencyClaimRequest", - "IdempotencyCompleteOutcome", - "IdempotencyFailOutcome", - "IdempotencyFailureDisposition", - "IdempotencyInspection", - "IdempotencyInspectionRequest", - "IdempotencyOwner", - "IdempotencyReleaseOutcome", - "IdempotencyRenewOutcome", - "IdempotencyStartOutcome" - }; - - @Test - @DisplayName("every owner-safe V2 type resolves in the v2 package") - void everyOwnerSafeTypeResolvesInTheV2Package() throws ClassNotFoundException { - for (String type : V2_TYPES) { - assertThat(Class.forName(V2_PACKAGE + type)) - .as("%s is part of the contract the stores implement", type) - .isNotNull(); - } - } - - @Test - @DisplayName("no owner-safe V2 type has a second declaration in the parent package") - void noOwnerSafeTypeHasASecondDeclarationInTheParentPackage() { - for (String type : V2_TYPES) { - assertThatThrownBy(() -> Class.forName(PARENT_PACKAGE + type)) - .as( - "%s must exist once; a second copy is what made the composition root count a bean" - + " no provider could supply", - type) - .isInstanceOf(ClassNotFoundException.class); - } - } -} diff --git a/src/application-core/src/test/java/dev/caskeleton/application/idempotency/v2/IdempotencyExecutorV2Test.java b/src/application-core/src/test/java/dev/caskeleton/application/idempotency/v2/IdempotencyExecutorV2Test.java deleted file mode 100644 index 4bd71478..00000000 --- a/src/application-core/src/test/java/dev/caskeleton/application/idempotency/v2/IdempotencyExecutorV2Test.java +++ /dev/null @@ -1,343 +0,0 @@ -package dev.caskeleton.application.idempotency.v2; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.application.idempotency.IdempotentAction; -import dev.caskeleton.application.idempotency.IdempotentResponseCodec; -import dev.caskeleton.application.idempotency.RequestFingerprint; -import dev.caskeleton.application.idempotency.StoredResponse; -import dev.caskeleton.application.transaction.OperationId; -import java.time.Duration; -import java.time.Instant; -import java.util.Optional; -import java.util.concurrent.atomic.AtomicBoolean; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * The request-replay lifecycle, over the contract the stores implement. - * - *

Carried over from a test of the same name that exercised the duplicate V2 contract in the - * parent package — the one nothing implements. The behaviours below are the ones worth keeping: the - * action runs at most once, a lost response is reconciled rather than re-run, and an outcome the - * caller cannot classify is never recorded as "no effect". - * - *

One behaviour is new, because the contract is: every confirmed transition hands back the owner - * with its state revision advanced, and the next call must present that handle rather than the one - * the claim returned. - */ -class IdempotencyExecutorV2Test { - - private static final String OWNER_TOKEN = "b".repeat(64); - private static final OperationId OPERATION = new OperationId("operation-aaaaaaaaaa"); - private static final IdempotencyScopeDigest SCOPE = - new IdempotencyScopeDigest("a".repeat(64), 1, "CREATE_WORKLOG"); - private static final RequestFingerprint FINGERPRINT = new RequestFingerprint("c".repeat(64)); - private static final IdempotencyClaimAttempt ATTEMPT = - new IdempotencyClaimAttempt(OWNER_TOKEN, OPERATION); - private static final Instant LEASE_UNTIL = Instant.parse("2026-07-29T12:00:30Z"); - - private static IdempotencyOwner owner(long stateRevision) { - return new IdempotencyOwner(SCOPE, OWNER_TOKEN, 1, stateRevision, OPERATION); - } - - @Test - @DisplayName("the action runs only after a confirmed start, and then completes") - void actionRunsOnlyAfterAConfirmedStart() { - FakeStore store = new FakeStore(); - store.claim = new IdempotencyClaimOutcome.Acquired(owner(0), LEASE_UNTIL); - store.start = IdempotencyStartOutcome.STARTED; - AtomicBoolean ran = new AtomicBoolean(); - - String result = - executor(store) - .execute( - SCOPE, - FINGERPRINT, - ATTEMPT, - () -> { - ran.set(true); - return new IdempotentAction.Outcome.Success<>("created"); - }, - codec()); - - assertThat(result).isEqualTo("created"); - assertThat(ran).isTrue(); - assertThat(store.completeCalls).isEqualTo(1); - assertThat(store.failedCalls).isZero(); - } - - @Test - @DisplayName("each mutation presents the owner handle the previous one returned") - void theAdvancedOwnerHandleIsCarriedForward() { - // The contract's whole point. The store advances the state revision on a confirmed transition - // and refuses a stale one; a caller that kept presenting the claim's original handle would be - // refused by its own store, so an owner-safe store would buy nothing. - FakeStore store = new FakeStore(); - store.claim = new IdempotencyClaimOutcome.Acquired(owner(0), LEASE_UNTIL); - store.start = IdempotencyStartOutcome.STARTED; - store.startOwner = owner(1); - - executor(store) - .execute( - SCOPE, - FINGERPRINT, - ATTEMPT, - () -> new IdempotentAction.Outcome.Success<>("created"), - codec()); - - assertThat(store.completeOwner.stateRevision()) - .as("complete must present the revision the start returned, not the claim's") - .isEqualTo(1); - } - - @Test - @DisplayName("an indeterminate claim is reconciled rather than re-run") - void anIndeterminateClaimIsReconciled() { - FakeStore store = new FakeStore(); - store.claim = new IdempotencyClaimOutcome.Indeterminate(OPERATION); - store.inspection = - new IdempotencyInspection( - IdempotencyInspectionOutcome.EXECUTING_SAME_OPERATION, - Optional.of(owner(1)), - Optional.of(LEASE_UNTIL), - Optional.empty(), - Optional.empty()); - AtomicBoolean ran = new AtomicBoolean(); - - assertThat( - executor(store) - .execute( - SCOPE, - FINGERPRINT, - ATTEMPT, - () -> { - ran.set(true); - return new IdempotentAction.Outcome.Success<>("created"); - }, - codec())) - .isEqualTo("created"); - assertThat(ran).isTrue(); - assertThat(store.startCalls) - .as("the record already says EXECUTING; starting it again would be a second transition") - .isZero(); - } - - @Test - @DisplayName("a lost completion is inspected without running the action a second time") - void aLostCompletionIsInspectedNotRepeated() { - FakeStore store = startedStore(); - store.complete = IdempotencyCompleteOutcome.INDETERMINATE; - store.inspectionAfterComplete = - new IdempotencyInspection( - IdempotencyInspectionOutcome.COMPLETED_REPLAY, - Optional.empty(), - Optional.empty(), - Optional.of(new StoredResponse("created")), - Optional.of(Instant.parse("2026-07-29T13:00:00Z"))); - int[] actionCalls = {0}; - - assertThat( - executor(store) - .execute( - SCOPE, - FINGERPRINT, - ATTEMPT, - () -> { - actionCalls[0]++; - return new IdempotentAction.Outcome.Success<>("created"); - }, - codec())) - .isEqualTo("created"); - assertThat(actionCalls[0]).isEqualTo(1); - assertThat(store.completeCalls).isEqualTo(1); - } - - @Test - @DisplayName("a replayed response that disagrees with this caller's is a recovery, not a result") - void aConflictingReplayIsNotReturned() { - FakeStore store = startedStore(); - store.complete = IdempotencyCompleteOutcome.INDETERMINATE; - store.inspectionAfterComplete = - new IdempotencyInspection( - IdempotencyInspectionOutcome.COMPLETED_REPLAY, - Optional.empty(), - Optional.empty(), - Optional.of(new StoredResponse("somebody-elses-answer")), - Optional.of(Instant.parse("2026-07-29T13:00:00Z"))); - - assertThatThrownBy( - () -> - executor(store) - .execute( - SCOPE, - FINGERPRINT, - ATTEMPT, - () -> new IdempotentAction.Outcome.Success<>("created"), - codec())) - .hasMessageContaining("conflicts"); - } - - @Test - @DisplayName("an unclassified throw and an unknown effect are never recorded as no-effect") - void unknownEffectsAreNeverDiscarded() { - FakeStore thrown = startedStore(); - RuntimeException unclassified = new IllegalStateException("unknown effect"); - - assertThatThrownBy( - () -> - executor(thrown) - .execute( - SCOPE, - FINGERPRINT, - ATTEMPT, - () -> { - throw unclassified; - }, - codec())) - .isSameAs(unclassified); - assertThat(thrown.lastDisposition) - .isEqualTo(IdempotencyFailureDisposition.EFFECT_UNKNOWN_ABANDONED); - - FakeStore declared = startedStore(); - RuntimeException classified = new IllegalArgumentException("provider response unknown"); - assertThatThrownBy( - () -> - executor(declared) - .execute( - SCOPE, - FINGERPRINT, - ATTEMPT, - () -> new IdempotentAction.Outcome.EffectUnknown<>(classified), - codec())) - .isSameAs(classified); - assertThat(declared.lastDisposition) - .isEqualTo(IdempotencyFailureDisposition.EFFECT_UNKNOWN_ABANDONED); - } - - @Test - @DisplayName("only an explicitly effect-free failure is recorded as retryable") - void onlyDeclaredNoEffectIsRetryable() { - FakeStore store = startedStore(); - RuntimeException failure = new IllegalArgumentException("validation"); - - assertThatThrownBy( - () -> - executor(store) - .execute( - SCOPE, - FINGERPRINT, - ATTEMPT, - () -> new IdempotentAction.Outcome.RetryableNoEffect<>(failure), - codec())) - .isSameAs(failure); - assertThat(store.lastDisposition).isEqualTo(IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE); - } - - private static FakeStore startedStore() { - FakeStore store = new FakeStore(); - store.claim = new IdempotencyClaimOutcome.Acquired(owner(0), LEASE_UNTIL); - store.start = IdempotencyStartOutcome.STARTED; - return store; - } - - private static IdempotencyExecutorV2 executor(FakeStore store) { - return new IdempotencyExecutorV2( - store, Duration.ofSeconds(30), Duration.ofHours(1), Duration.ofHours(1), "json-v2", 1); - } - - private static IdempotentResponseCodec codec() { - return new IdempotentResponseCodec<>() { - @Override - public String serialize(String result) { - return result; - } - - @Override - public String deserialize(String payload) { - return payload; - } - }; - } - - private static final class FakeStore implements IdempotencyStorePortV2 { - - private IdempotencyClaimOutcome claim; - private IdempotencyStartOutcome start; - private IdempotencyOwner startOwner; - private IdempotencyCompleteOutcome complete = IdempotencyCompleteOutcome.COMPLETED; - private IdempotencyInspection inspection = - IdempotencyInspection.outcome(IdempotencyInspectionOutcome.UNAVAILABLE); - private IdempotencyInspection inspectionAfterComplete; - private int startCalls; - private int completeCalls; - private int failedCalls; - private IdempotencyOwner completeOwner; - private IdempotencyFailureDisposition lastDisposition; - - @Override - public IdempotencyClaimAttempt newClaimAttempt(OperationId operationId) { - return new IdempotencyClaimAttempt(OWNER_TOKEN, operationId); - } - - @Override - public IdempotencyClaimOutcome claim(IdempotencyClaimRequest request) { - return claim; - } - - @Override - public IdempotencyMutationResult markExecutionStarted( - IdempotencyOwner owner, OperationId operationId) { - startCalls++; - IdempotencyOwner advanced = - start.carriesOwner() ? (startOwner == null ? owner : startOwner) : null; - return new IdempotencyMutationResult<>( - start, advanced, IdempotencyStartOutcome::carriesOwner); - } - - @Override - public IdempotencyMutationResult renew( - IdempotencyOwner owner, Duration processingLeaseTtl, OperationId operationId) { - throw new UnsupportedOperationException("the executor does not renew"); - } - - @Override - public IdempotencyCompleteOutcome complete( - IdempotencyOwner owner, - StoredResponse response, - Duration replayTtl, - OperationId operationId) { - completeCalls++; - completeOwner = owner; - if (inspectionAfterComplete != null) { - inspection = inspectionAfterComplete; - } - return complete; - } - - @Override - public IdempotencyFailOutcome markFailed( - IdempotencyOwner owner, - IdempotencyFailureDisposition disposition, - Duration retention, - OperationId operationId) { - failedCalls++; - lastDisposition = disposition; - return disposition == IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE - ? IdempotencyFailOutcome.MARKED_RETRYABLE - : IdempotencyFailOutcome.MARKED_ABANDONED; - } - - @Override - public IdempotencyReleaseOutcome releaseBeforeExecution( - IdempotencyOwner owner, OperationId operationId) { - throw new UnsupportedOperationException("the executor never releases before execution"); - } - - @Override - public IdempotencyInspection inspect(IdempotencyInspectionRequest request) { - return inspection; - } - } -} diff --git a/src/application-core/src/test/java/dev/caskeleton/application/inbox/InboxContractTest.java b/src/application-core/src/test/java/dev/caskeleton/application/inbox/InboxContractTest.java deleted file mode 100644 index 9caeda58..00000000 --- a/src/application-core/src/test/java/dev/caskeleton/application/inbox/InboxContractTest.java +++ /dev/null @@ -1,39 +0,0 @@ -package dev.caskeleton.application.inbox; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.application.transaction.OperationId; -import java.time.Duration; -import org.junit.jupiter.api.Test; - -class InboxContractTest { - - @Test - void scopeIsAnOpaqueCanonicalDigestAndOwnerCarriesTheFullCasTuple() { - InboxScopeDigest scope = new InboxScopeDigest("a".repeat(64)); - InboxOwner owner = - new InboxOwner(scope, "b".repeat(64), 2, 7, new OperationId("claim-message-1")); - - assertThat(owner.attempt()).isEqualTo(2); - assertThat(owner.stateRevision()).isEqualTo(7); - - assertThatThrownBy(() -> new InboxScopeDigest("A".repeat(64))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("lowercase"); - } - - @Test - void claimRequestSeparatesProcessingLeaseFromTerminalRetention() { - InboxClaimRequest request = - new InboxClaimRequest( - new InboxScopeDigest("a".repeat(64)), - "c".repeat(64), - new InboxClaimAttempt("b".repeat(64), new OperationId("claim-message-1")), - Duration.ofSeconds(30), - Duration.ofDays(7)); - - assertThat(request.processingLease()).isEqualTo(Duration.ofSeconds(30)); - assertThat(request.terminalRetention()).isEqualTo(Duration.ofDays(7)); - } -} diff --git a/src/application-core/src/test/java/dev/caskeleton/application/lease/LeaseWatchdogTest.java b/src/application-core/src/test/java/dev/caskeleton/application/lease/LeaseWatchdogTest.java deleted file mode 100644 index 8b4ae942..00000000 --- a/src/application-core/src/test/java/dev/caskeleton/application/lease/LeaseWatchdogTest.java +++ /dev/null @@ -1,136 +0,0 @@ -package dev.caskeleton.application.lease; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.time.Clock; -import java.time.Duration; -import java.time.Instant; -import java.time.ZoneOffset; -import java.util.concurrent.RejectedExecutionException; -import java.util.concurrent.atomic.AtomicInteger; -import org.junit.jupiter.api.Test; - -@SuppressWarnings("deprecation") -class LeaseWatchdogTest { - - private static final Instant NOW = Instant.parse("2026-07-29T10:00:00Z"); - - // FakeHandle is an inert test double; the watchdog rejects it before taking ownership, so - // there is nothing to close and no resource to release. - @SuppressWarnings("resource") - @Test - void boundsRegistrationsAndCancelsWorkWhenRenewalBecomesUnknown() { - AtomicInteger cancelled = new AtomicInteger(); - AtomicInteger lostSignals = new AtomicInteger(); - FakeHandle handle = new FakeHandle(); - handle.renewOutcome = new LeaseRenewOutcome.Indeterminate("renew_operation_12345"); - - try (LeaseWatchdog watchdog = new LeaseWatchdog(1, 1, Clock.fixed(NOW, ZoneOffset.UTC))) { - LeaseWatchdog.Registration registration = - watchdog.watch( - handle, - Duration.ofSeconds(10), - Duration.ofSeconds(5), - NOW.plusSeconds(30), - cancelled::incrementAndGet, - state -> { - assertThat(state).isEqualTo(LeaseState.UNKNOWN); - lostSignals.incrementAndGet(); - }); - - assertThatThrownBy( - () -> - watchdog.watch( - new FakeHandle(), - Duration.ofSeconds(10), - Duration.ofSeconds(5), - NOW.plusSeconds(30), - () -> {}, - state -> {})) - .isInstanceOf(RejectedExecutionException.class); - - registration.runOnceForTest(); - registration.runOnceForTest(); - - assertThat(cancelled).hasValue(1); - assertThat(lostSignals).hasValue(1); - assertThat(registration.closed()).isTrue(); - assertThat(watchdog.activeRegistrations()).isZero(); - } - } - - @Test - void explicitCancellationRemovesTheScheduledRenewalWithoutReportingLeaseLoss() { - AtomicInteger cancelled = new AtomicInteger(); - AtomicInteger lostSignals = new AtomicInteger(); - - try (LeaseWatchdog watchdog = new LeaseWatchdog(1, 1, Clock.fixed(NOW, ZoneOffset.UTC))) { - LeaseWatchdog.Registration registration = - watchdog.watch( - new FakeHandle(), - Duration.ofSeconds(10), - Duration.ofSeconds(5), - NOW.plusSeconds(30), - cancelled::incrementAndGet, - state -> lostSignals.incrementAndGet()); - - registration.close(); - registration.runOnceForTest(); - - assertThat(cancelled).hasValue(0); - assertThat(lostSignals).hasValue(0); - assertThat(watchdog.activeRegistrations()).isZero(); - } - } - - private static final class FakeHandle implements LeaseHandle { - - private LeaseState state = LeaseState.ACTIVE; - private LeaseRenewOutcome renewOutcome = new LeaseRenewOutcome.Renewed(Duration.ofSeconds(9)); - - @Override - public String ownerToken() { - return "owner_token_1234567890"; - } - - @Override - public String operationId() { - return "operation_token_12345"; - } - - @Override - public Instant acquiredAt() { - return NOW; - } - - @Override - public Duration remainingValidity() { - return state == LeaseState.ACTIVE ? Duration.ofSeconds(9) : Duration.ZERO; - } - - @Override - public Instant observedServerExpiry() { - return NOW.plusSeconds(10); - } - - @Override - public LeaseState state() { - return state; - } - - @Override - public LeaseRenewOutcome renew(Duration leaseTtl) { - if (renewOutcome instanceof LeaseRenewOutcome.Indeterminate) { - state = LeaseState.UNKNOWN; - } - return renewOutcome; - } - - @Override - public LeaseReleaseOutcome release() { - state = LeaseState.RELEASED; - return new LeaseReleaseOutcome.Released(); - } - } -} diff --git a/src/application-core/src/test/java/dev/caskeleton/application/operation/CancelDurableOperationUseCaseTest.java b/src/application-core/src/test/java/dev/caskeleton/application/operation/CancelDurableOperationUseCaseTest.java new file mode 100644 index 00000000..628ee3ef --- /dev/null +++ b/src/application-core/src/test/java/dev/caskeleton/application/operation/CancelDurableOperationUseCaseTest.java @@ -0,0 +1,89 @@ +package dev.caskeleton.application.operation; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.application.idempotency.RequestFingerprint; +import dev.caskeleton.application.operation.testkit.InMemoryDurableOperationStore; +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.Optional; +import org.junit.jupiter.api.Test; + +class CancelDurableOperationUseCaseTest { + + private static final Instant NOW = Instant.parse("2026-08-25T10:00:00Z"); + private static final DurableOperationId ID = new DurableOperationId("op-1"); + + private final InMemoryDurableOperationStore operations = new InMemoryDurableOperationStore(); + private final CancelDurableOperationUseCase useCase = + new CancelDurableOperationUseCase( + operations, new DirectTransactionPort(), Clock.fixed(NOW, ZoneOffset.UTC)); + + @Test + void submitterCancelMovesTheOperationToCanceled() { + // given + operations.submit(submission("t-1")); + + // when + useCase.handle(new CancelDurableOperationCommand(ID, "alice", "t-1")); + + // then + assertThat(operations.find(ID, "alice", NOW).orElseThrow().state()) + .isEqualTo(DurableOperationState.CANCELED); + } + + @Test + void cancelOfAFinishedOperationReportsNoChange() { + // given + operations.submit(submission(null)); + operations.claimNext("worker-a", Duration.ofMinutes(1), NOW); + operations.succeed(ID, "worker-a", "/results/1", NOW); + + // when + Optional canceled = + useCase.handle(new CancelDurableOperationCommand(ID, "alice", null)); + + // then + assertThat(canceled).contains(false); + } + + @Test + void submitterInAnotherTenantIsAnsweredAsIfTheOperationDidNotExist() { + // given + operations.submit(submission("t-1")); + + // when + Optional canceled = + useCase.handle(new CancelDurableOperationCommand(ID, "alice", "t-2")); + + // then + assertThat(canceled).isEmpty(); + } + + @Test + void unauthenticatedCallerIsAnsweredAsIfTheOperationDidNotExist() { + // given + operations.submit(submission(null)); + + // when + Optional canceled = useCase.handle(new CancelDurableOperationCommand(ID, null, null)); + + // then + assertThat(canceled).isEmpty(); + } + + private static DurableOperationSubmission submission(String tenantId) { + return new DurableOperationSubmission( + ID, + "reports.generate", + "alice", + tenantId, + new RequestFingerprint("a".repeat(64)), + "{}", + NOW, + Duration.ofHours(1)); + } +} diff --git a/src/application-core/src/test/java/dev/caskeleton/application/operation/DurableOperationAccessPolicyTest.java b/src/application-core/src/test/java/dev/caskeleton/application/operation/DurableOperationAccessPolicyTest.java new file mode 100644 index 00000000..44c66954 --- /dev/null +++ b/src/application-core/src/test/java/dev/caskeleton/application/operation/DurableOperationAccessPolicyTest.java @@ -0,0 +1,56 @@ +package dev.caskeleton.application.operation; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.time.Instant; +import java.util.Optional; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +/** + * Who can read or cancel somebody else's long-running work. + * + *

A polled operation carries its result location and, when it failed, its problem detail, so a + * permissive rule here leaks more than the fact that the work exists. + */ +class DurableOperationAccessPolicyTest { + + private static final Instant NOW = Instant.parse("2026-08-25T10:00:00Z"); + + @ParameterizedTest(name = "owner={0}/{1}, caller={2}/{3} -> {4}") + @CsvSource( + nullValues = "-", + value = { + "alice, -, alice, -, true", + "alice, t-1, alice, t-1, true", + "alice, -, mallory, -, false", + "alice, t-1, alice, t-2, false", + "alice, t-1, alice, -, false", + "alice, -, alice, t-1, false", + "alice, -, -, -, false" + }) + void onlyTheSubmitterInTheSubmittingTenantMayAccess( + String owner, String ownerTenant, String caller, String callerTenant, boolean expected) { + assertThat( + DurableOperationAccessPolicy.mayAccess( + operation(owner, ownerTenant), caller, callerTenant)) + .isEqualTo(expected); + } + + private static DurableOperation operation(String principal, String tenantId) { + return new DurableOperation( + new DurableOperationId("op-1"), + "reports.generate", + principal, + tenantId, + DurableOperationState.PENDING, + NOW, + Optional.empty(), + Optional.empty(), + Optional.empty(), + Optional.empty(), + Optional.empty(), + Optional.empty(), + NOW.plusSeconds(3600)); + } +} diff --git a/src/application-core/src/test/java/dev/caskeleton/application/operation/GetDurableOperationUseCaseTest.java b/src/application-core/src/test/java/dev/caskeleton/application/operation/GetDurableOperationUseCaseTest.java new file mode 100644 index 00000000..85c7357b --- /dev/null +++ b/src/application-core/src/test/java/dev/caskeleton/application/operation/GetDurableOperationUseCaseTest.java @@ -0,0 +1,74 @@ +package dev.caskeleton.application.operation; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.application.idempotency.RequestFingerprint; +import dev.caskeleton.application.operation.testkit.InMemoryDurableOperationStore; +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.Optional; +import org.junit.jupiter.api.Test; + +class GetDurableOperationUseCaseTest { + + private static final Instant NOW = Instant.parse("2026-08-25T10:00:00Z"); + private static final DurableOperationId ID = new DurableOperationId("op-1"); + + private final InMemoryDurableOperationStore operations = new InMemoryDurableOperationStore(); + private final GetDurableOperationUseCase useCase = + new GetDurableOperationUseCase( + operations, new DirectTransactionPort(), Clock.fixed(NOW, ZoneOffset.UTC)); + + @Test + void submitterReadsTheirOperation() { + // given + DurableOperation submitted = operations.submit(submission("t-1")); + + // when + Optional read = + useCase.handle(new GetDurableOperationQuery(ID, "alice", "t-1")); + + // then + assertThat(read).contains(submitted); + } + + @Test + void submitterInAnotherTenantReadsNothing() { + // given + operations.submit(submission("t-1")); + + // when + Optional read = + useCase.handle(new GetDurableOperationQuery(ID, "alice", "t-2")); + + // then + assertThat(read).isEmpty(); + } + + @Test + void unauthenticatedCallerReadsNothing() { + // given + operations.submit(submission(null)); + + // when + Optional read = useCase.handle(new GetDurableOperationQuery(ID, null, null)); + + // then + assertThat(read).isEmpty(); + } + + private static DurableOperationSubmission submission(String tenantId) { + return new DurableOperationSubmission( + ID, + "reports.generate", + "alice", + tenantId, + new RequestFingerprint("a".repeat(64)), + "{}", + NOW, + Duration.ofHours(1)); + } +} diff --git a/src/application-core/src/test/java/dev/caskeleton/application/operation/SubmitDurableOperationUseCaseTest.java b/src/application-core/src/test/java/dev/caskeleton/application/operation/SubmitDurableOperationUseCaseTest.java index fd3ceb29..3b03ce3d 100644 --- a/src/application-core/src/test/java/dev/caskeleton/application/operation/SubmitDurableOperationUseCaseTest.java +++ b/src/application-core/src/test/java/dev/caskeleton/application/operation/SubmitDurableOperationUseCaseTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import dev.caskeleton.application.idempotency.RequestFingerprint; +import dev.caskeleton.application.operation.testkit.InMemoryDurableOperationStore; import dev.caskeleton.application.outbox.LegacyOutboxAppendPort; import dev.caskeleton.application.outbox.NewOutboxEvent; import dev.caskeleton.application.transaction.TransactionPort; diff --git a/src/application-core/src/test/java/dev/caskeleton/application/operation/testkit/InMemoryDurableOperationStoreContractTest.java b/src/application-core/src/test/java/dev/caskeleton/application/operation/testkit/InMemoryDurableOperationStoreContractTest.java new file mode 100644 index 00000000..5842a6d9 --- /dev/null +++ b/src/application-core/src/test/java/dev/caskeleton/application/operation/testkit/InMemoryDurableOperationStoreContractTest.java @@ -0,0 +1,19 @@ +package dev.caskeleton.application.operation.testkit; + +import dev.caskeleton.application.operation.DurableOperationStorePort; +import java.util.function.Supplier; + +class InMemoryDurableOperationStoreContractTest extends DurableOperationStoreContract { + + private final InMemoryDurableOperationStore store = new InMemoryDurableOperationStore(); + + @Override + protected DurableOperationStorePort store() { + return store; + } + + @Override + protected T inTransaction(Supplier work) { + return work.get(); + } +} diff --git a/src/application-core/src/test/java/dev/caskeleton/application/outbox/OutcomeAwareRelayTest.java b/src/application-core/src/test/java/dev/caskeleton/application/outbox/OutcomeAwareRelayTest.java index 2b34055e..bd699265 100644 --- a/src/application-core/src/test/java/dev/caskeleton/application/outbox/OutcomeAwareRelayTest.java +++ b/src/application-core/src/test/java/dev/caskeleton/application/outbox/OutcomeAwareRelayTest.java @@ -2,6 +2,7 @@ package dev.caskeleton.application.outbox; import static org.assertj.core.api.Assertions.assertThat; +import dev.caskeleton.application.outbox.testkit.InMemoryOutboxStore; import dev.caskeleton.application.transaction.TransactionPort; import java.time.Clock; import java.time.Duration; @@ -30,7 +31,7 @@ class OutcomeAwareRelayTest { private static final Duration IN_FLIGHT_TIMEOUT = Duration.ofMinutes(5); - private OutcomeStore store; + private InMemoryOutboxStore store; private OutcomeReporter reporter; @@ -40,7 +41,7 @@ class OutcomeAwareRelayTest { @BeforeEach void setUp() { - store = new OutcomeStore(); + store = new InMemoryOutboxStore(); reporter = new OutcomeReporter(); publishPort = new OutcomePort(); useCase = @@ -52,13 +53,14 @@ class OutcomeAwareRelayTest { new OutboxBackoffPolicy(new NoJitter()), Clock.fixed(NOW, ZoneOffset.UTC), 10, - IN_FLIGHT_TIMEOUT); + IN_FLIGHT_TIMEOUT, + "relay-under-test"); } @Test @DisplayName("a confirmed publish still marks the row published") void aConfirmedPublishMarksTheRowPublished() { - store.claimable.add(event("evt-1", 1)); + store.addClaimable(event("evt-1", 1)); publishPort.answer = OutboxPublishOutcome.CONFIRMED; OutboxRelayResult result = useCase.handle(PublishPendingOutboxEventsCommand.INSTANCE); @@ -66,13 +68,13 @@ class OutcomeAwareRelayTest { assertThat(result.outcomes()) .extracting(OutboxRelayResult.EventOutcome::outcome) .containsExactly(OutboxRelayResult.Outcome.PUBLISHED); - assertThat(store.published).containsExactly("evt-1"); + assertThat(store.published()).containsExactly("evt-1"); } @Test @DisplayName("an ambiguous publish stays claimable rather than being treated as a definite loss") void anAmbiguousPublishStaysClaimable() { - store.claimable.add(event("evt-2", 1)); + store.addClaimable(event("evt-2", 1)); publishPort.answer = OutboxPublishOutcome.AMBIGUOUS; OutboxRelayResult result = useCase.handle(PublishPendingOutboxEventsCommand.INSTANCE); @@ -80,8 +82,10 @@ class OutcomeAwareRelayTest { assertThat(result.outcomes()) .extracting(OutboxRelayResult.EventOutcome::outcome) .containsExactly(OutboxRelayResult.Outcome.FAILED); - assertThat(store.failed).containsKey("evt-2"); - assertThat(store.dead).as("parking it loses a message that may have been delivered").isEmpty(); + assertThat(store.failed()).containsKey("evt-2"); + assertThat(store.dead()) + .as("parking it loses a message that may have been delivered") + .isEmpty(); assertThat(reporter.reports) .singleElement() .satisfies( @@ -94,7 +98,7 @@ class OutcomeAwareRelayTest { @Test @DisplayName("a refusal before transmission is dead-lettered without spending the retry budget") void aRefusalBeforeTransmissionIsDeadLettered() { - store.claimable.add(event("evt-3", 1)); + store.addClaimable(event("evt-3", 1)); publishPort.answer = OutboxPublishOutcome.REJECTED_BEFORE_SEND; OutboxRelayResult result = useCase.handle(PublishPendingOutboxEventsCommand.INSTANCE); @@ -103,8 +107,8 @@ class OutcomeAwareRelayTest { .extracting(OutboxRelayResult.EventOutcome::outcome) .as("the same payload will be refused the same way on every attempt") .containsExactly(OutboxRelayResult.Outcome.DEAD); - assertThat(store.dead).containsExactly("evt-3"); - assertThat(store.failed).isEmpty(); + assertThat(store.dead()).containsExactly("evt-3"); + assertThat(store.failed()).isEmpty(); assertThat(reporter.reports) .singleElement() .satisfies( @@ -116,12 +120,12 @@ class OutcomeAwareRelayTest { @Test @DisplayName("a broker-side refusal is also definite, and says which side refused") void aBrokerSideRefusalIsAlsoDefinite() { - store.claimable.add(event("evt-4", 1)); + store.addClaimable(event("evt-4", 1)); publishPort.answer = OutboxPublishOutcome.REJECTED_AFTER_BROKER; useCase.handle(PublishPendingOutboxEventsCommand.INSTANCE); - assertThat(store.dead).containsExactly("evt-4"); + assertThat(store.dead()).containsExactly("evt-4"); assertThat(reporter.reports.get(0).causeType()) .isEqualTo(OutboxPublishRefusedException.class.getName()); assertThat(new OutboxPublishRefusedException(OutboxPublishOutcome.REJECTED_AFTER_BROKER)) @@ -133,7 +137,7 @@ class OutcomeAwareRelayTest { @Test @DisplayName("an adapter that only throws keeps the behaviour it always had") void aThrowingAdapterIsUnchanged() { - store.claimable.add(event("evt-5", 1)); + store.addClaimable(event("evt-5", 1)); publishPort.failure = new IllegalStateException("the broker connection dropped"); OutboxRelayResult result = useCase.handle(PublishPendingOutboxEventsCommand.INSTANCE); @@ -141,7 +145,7 @@ class OutcomeAwareRelayTest { assertThat(result.outcomes()) .extracting(OutboxRelayResult.EventOutcome::outcome) .containsExactly(OutboxRelayResult.Outcome.FAILED); - assertThat(store.failed).containsKey("evt-5"); + assertThat(store.failed()).containsKey("evt-5"); } private static OutboxEvent event(String eventId, int attemptCount) { @@ -180,51 +184,6 @@ class OutcomeAwareRelayTest { } } - /** Records the transitions the relay drove. */ - private static final class OutcomeStore implements OutboxStorePort { - - private final List claimable = new ArrayList<>(); - - private final List published = new ArrayList<>(); - - private final java.util.Map failed = new java.util.LinkedHashMap<>(); - - private final List dead = new ArrayList<>(); - - @Override - public List claimBatch( - int batchSize, Instant now, Duration inFlightTimeout) { - List claimed = List.copyOf(claimable); - claimable.clear(); - return claimed; - } - - @Override - public void markPublished(String eventId) { - published.add(eventId); - } - - @Override - public void markFailed(String eventId, Instant nextAttemptAt) { - failed.put(eventId, nextAttemptAt); - } - - @Override - public void markDead(String eventId) { - dead.add(eventId); - } - - @Override - public java.util.Map countByStatus() { - return java.util.Map.of(); - } - - @Override - public java.util.Map oldestUnpublishedAgeSecondsByEventType(Instant now) { - return java.util.Map.of(); - } - } - private static final class OutcomeReporter implements OutboxRelayFailureReportPort { private final List reports = new ArrayList<>(); diff --git a/src/application-core/src/test/java/dev/caskeleton/application/outbox/PublishPendingOutboxEventsUseCaseTest.java b/src/application-core/src/test/java/dev/caskeleton/application/outbox/PublishPendingOutboxEventsUseCaseTest.java index 29a42201..70dcb293 100644 --- a/src/application-core/src/test/java/dev/caskeleton/application/outbox/PublishPendingOutboxEventsUseCaseTest.java +++ b/src/application-core/src/test/java/dev/caskeleton/application/outbox/PublishPendingOutboxEventsUseCaseTest.java @@ -3,6 +3,7 @@ package dev.caskeleton.application.outbox; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import dev.caskeleton.application.outbox.testkit.InMemoryOutboxStore; import dev.caskeleton.application.transaction.TransactionPort; import java.time.Clock; import java.time.Duration; @@ -56,7 +57,15 @@ class PublishPendingOutboxEventsUseCaseTest { backoffPolicy = new OutboxBackoffPolicy(new ZeroRandom()); useCase = new PublishPendingOutboxEventsUseCase( - store, publishPort, reporter, tx, backoffPolicy, clock, BATCH_SIZE, IN_FLIGHT_TIMEOUT); + store, + publishPort, + reporter, + tx, + backoffPolicy, + clock, + BATCH_SIZE, + IN_FLIGHT_TIMEOUT, + "relay-under-test"); } // ---- success path ---- @@ -72,7 +81,7 @@ class PublishPendingOutboxEventsUseCaseTest { assertThat(result.outcomes()).hasSize(1); assertThat(result.outcomes().getFirst().outcome()) .isEqualTo(OutboxRelayResult.Outcome.PUBLISHED); - assertThat(store.publishedEvents).containsExactly("evt-1"); + assertThat(store.published()).containsExactly("evt-1"); assertThat(publishPort.publishedEvents).containsExactly("evt-1"); assertThat(reporter.reports).isEmpty(); } @@ -104,12 +113,12 @@ class PublishPendingOutboxEventsUseCaseTest { assertThat(result.outcomes()).hasSize(1); assertThat(result.outcomes().getFirst().outcome()).isEqualTo(OutboxRelayResult.Outcome.FAILED); // The store must record the FAILED transition with a future nextAttemptAt - assertThat(store.failedEvents).containsKey("evt-fail"); - Instant nextAttemptAt = store.failedEvents.get("evt-fail"); + assertThat(store.failed()).containsKey("evt-fail"); + Instant nextAttemptAt = store.failed().get("evt-fail"); // backoff = now + 30s * 2^(1-1) = now + 30s (jitter=0 with fixed rng) assertThat(nextAttemptAt).isAfter(NOW); // Not yet DEAD (attempt 1 < maxAttempts 3) - assertThat(store.deadEvents).doesNotContain("evt-fail"); + assertThat(store.dead()).doesNotContain("evt-fail"); assertThat(reporter.reports) .containsExactly( OutboxRelayFailureReport.retryableFailure( @@ -132,8 +141,8 @@ class PublishPendingOutboxEventsUseCaseTest { OutboxRelayResult result = useCase.handle(PublishPendingOutboxEventsCommand.INSTANCE); assertThat(result.outcomes().getFirst().outcome()).isEqualTo(OutboxRelayResult.Outcome.DEAD); - assertThat(store.deadEvents).contains("evt-dead"); - assertThat(store.failedEvents).doesNotContainKey("evt-dead"); + assertThat(store.dead()).contains("evt-dead"); + assertThat(store.failed()).doesNotContainKey("evt-dead"); assertThat(reporter.reports) .containsExactly( OutboxRelayFailureReport.deadLetter( @@ -176,7 +185,7 @@ class PublishPendingOutboxEventsUseCaseTest { .orElseThrow(); assertThat(okOutcome.outcome()).isEqualTo(OutboxRelayResult.Outcome.PUBLISHED); // FAILED event must have a status transition (not silently swallowed) - assertThat(store.failedEvents).containsKey("evt-fail"); + assertThat(store.failed()).containsKey("evt-fail"); } @Test @@ -188,8 +197,8 @@ class PublishPendingOutboxEventsUseCaseTest { OutboxRelayResult result = useCase.handle(PublishPendingOutboxEventsCommand.INSTANCE); assertThat(result.outcomes().getFirst().outcome()).isEqualTo(OutboxRelayResult.Outcome.FAILED); - assertThat(store.failedEvents).containsKey("evt-2nd"); - assertThat(store.deadEvents).doesNotContain("evt-2nd"); + assertThat(store.failed()).containsKey("evt-2nd"); + assertThat(store.dead()).doesNotContain("evt-2nd"); } @Test @@ -228,7 +237,7 @@ class PublishPendingOutboxEventsUseCaseTest { MutableClock mutableClock = new MutableClock(NOW, ZoneOffset.UTC); TimeoutAwareThrowingOnMarkPublishedStorePort throwingStore = new TimeoutAwareThrowingOnMarkPublishedStorePort( - event, NOW, new RuntimeException("DB down on markPublished")); + event, new RuntimeException("DB down on markPublished")); PublishPendingOutboxEventsUseCase useCaseWithThrowingStore = new PublishPendingOutboxEventsUseCase( @@ -239,7 +248,8 @@ class PublishPendingOutboxEventsUseCaseTest { backoffPolicy, mutableClock, BATCH_SIZE, - IN_FLIGHT_TIMEOUT); + IN_FLIGHT_TIMEOUT, + "relay-under-test"); // The exception must propagate — handle() must throw. assertThatThrownBy( @@ -307,7 +317,8 @@ class PublishPendingOutboxEventsUseCaseTest { backoffPolicy, clock, BATCH_SIZE, - IN_FLIGHT_TIMEOUT); + IN_FLIGHT_TIMEOUT, + "relay-under-test"); assertThatThrownBy( () -> useCaseWithThrowingStore.handle(PublishPendingOutboxEventsCommand.INSTANCE)) @@ -319,12 +330,12 @@ class PublishPendingOutboxEventsUseCaseTest { assertThat(publishPort.publishedEvents).containsExactly("evt-first"); // No FAILED or DEAD misclassification for the first event. - assertThat(throwingStore.failedEvents).doesNotContainKey("evt-first"); - assertThat(throwingStore.deadEvents).doesNotContain("evt-first"); + assertThat(throwingStore.failed()).doesNotContainKey("evt-first"); + assertThat(throwingStore.dead()).doesNotContain("evt-first"); // No FAILED or DEAD misclassification for the second event either. - assertThat(throwingStore.failedEvents).doesNotContainKey("evt-second"); - assertThat(throwingStore.deadEvents).doesNotContain("evt-second"); + assertThat(throwingStore.failed()).doesNotContainKey("evt-second"); + assertThat(throwingStore.dead()).doesNotContain("evt-second"); assertThat(reporter.reports).isEmpty(); } @@ -344,7 +355,8 @@ class PublishPendingOutboxEventsUseCaseTest { backoffPolicy, clock, BATCH_SIZE, - IN_FLIGHT_TIMEOUT); + IN_FLIGHT_TIMEOUT, + "relay-under-test"); assertThatThrownBy(() -> throwingUseCase.handle(PublishPendingOutboxEventsCommand.INSTANCE)) .hasMessage("markFailed failed"); @@ -367,7 +379,8 @@ class PublishPendingOutboxEventsUseCaseTest { backoffPolicy, clock, BATCH_SIZE, - IN_FLIGHT_TIMEOUT); + IN_FLIGHT_TIMEOUT, + "relay-under-test"); assertThatThrownBy(() -> throwingUseCase.handle(PublishPendingOutboxEventsCommand.INSTANCE)) .hasMessage("markDead failed"); @@ -394,7 +407,8 @@ class PublishPendingOutboxEventsUseCaseTest { backoffPolicy, clock, BATCH_SIZE, - IN_FLIGHT_TIMEOUT); + IN_FLIGHT_TIMEOUT, + "relay-under-test"); OutboxRelayResult result = useCaseWithThrowingReporter.handle(PublishPendingOutboxEventsCommand.INSTANCE); @@ -402,8 +416,8 @@ class PublishPendingOutboxEventsUseCaseTest { assertThat(result.outcomes()) .extracting(OutboxRelayResult.EventOutcome::outcome) .containsExactly(OutboxRelayResult.Outcome.FAILED, OutboxRelayResult.Outcome.PUBLISHED); - assertThat(store.failedEvents).containsKey("evt-fail"); - assertThat(store.publishedEvents).containsExactly("evt-ok"); + assertThat(store.failed()).containsKey("evt-fail"); + assertThat(store.published()).containsExactly("evt-ok"); } @Test @@ -425,9 +439,9 @@ class PublishPendingOutboxEventsUseCaseTest { OutboxRelayResult.Outcome.FAILED, OutboxRelayResult.Outcome.DEAD, OutboxRelayResult.Outcome.PUBLISHED); - assertThat(store.failedEvents).containsKey("evt-fail"); - assertThat(store.deadEvents).containsExactly("evt-dead"); - assertThat(store.publishedEvents).containsExactly("evt-ok"); + assertThat(store.failed()).containsKey("evt-fail"); + assertThat(store.dead()).containsExactly("evt-dead"); + assertThat(store.published()).containsExactly("evt-ok"); assertThat(reporter.reports).isEmpty(); } @@ -449,53 +463,12 @@ class PublishPendingOutboxEventsUseCaseTest { // ---- test doubles ---- - static class FakeOutboxStorePort implements OutboxStorePort { - final List claimable = new ArrayList<>(); - final List publishedEvents = new ArrayList<>(); - final Map failedEvents = new LinkedHashMap<>(); - final List deadEvents = new ArrayList<>(); - - void addClaimable(OutboxEvent event) { - claimable.add(event); - } - - @Override - public List claimBatch( - int batchSize, Instant now, Duration inFlightTimeout) { - return List.copyOf(claimable); - } - - @Override - public void markPublished(String eventId) { - publishedEvents.add(eventId); - } - - @Override - public void markFailed(String eventId, Instant nextAttemptAt) { - failedEvents.put(eventId, nextAttemptAt); - } - - @Override - public void markDead(String eventId) { - deadEvents.add(eventId); - } - - @Override - public Map countByStatus() { - return Map.of(); - } - - @Override - public Map oldestUnpublishedAgeSecondsByEventType(Instant now) { - return Map.of(); - } - } + /** The fencing fake; the name is kept so the throwing variants below read as before. */ + static class FakeOutboxStorePort extends InMemoryOutboxStore {} /** - * Extends {@link FakeOutboxStorePort}, overriding only {@link #markPublished} to throw, - * simulating a DB-down scenario after a successful broker publish. All other operations — - * claimBatch, markFailed, markDead, countByStatus, oldestUnpublishedAgeSecondsByEventType — are - * inherited unchanged. + * Overrides only {@link #markPublished} to throw, simulating a DB-down scenario after a + * successful broker publish. Everything else is the fencing fake unchanged. */ static final class ThrowingOnMarkPublishedStorePort extends FakeOutboxStorePort { private final RuntimeException markPublishedEx; @@ -505,90 +478,52 @@ class PublishPendingOutboxEventsUseCaseTest { } @Override - public void markPublished(String eventId) { + public OutboxCompletion markPublished(OutboxLease lease) { throw markPublishedEx; } } - static final class TimeoutAwareThrowingOnMarkPublishedStorePort implements OutboxStorePort { - private final OutboxEvent event; + /** One row whose PUBLISHED completion always fails; claims keep the timeout semantics. */ + static final class TimeoutAwareThrowingOnMarkPublishedStorePort extends InMemoryOutboxStore { + private final String eventId; private final RuntimeException markPublishedException; - private OutboxEventStatus currentStatus = OutboxEventStatus.PENDING; - private int attemptCount; - private Instant nextAttemptAt; private int markFailedCalls; private int markDeadCalls; TimeoutAwareThrowingOnMarkPublishedStorePort( - OutboxEvent event, Instant firstEligibleAt, RuntimeException markPublishedException) { - this.event = event; - this.nextAttemptAt = firstEligibleAt; + OutboxEvent event, RuntimeException markPublishedException) { + this.eventId = event.eventId(); this.markPublishedException = markPublishedException; + addClaimable(event); } @Override - public List claimBatch( - int batchSize, Instant now, Duration inFlightTimeout) { - if (batchSize == 0 - || currentStatus == OutboxEventStatus.PUBLISHED - || currentStatus == OutboxEventStatus.DEAD - || nextAttemptAt.isAfter(now)) { - return List.of(); - } - currentStatus = OutboxEventStatus.IN_FLIGHT; - attemptCount++; - nextAttemptAt = now.plus(inFlightTimeout); - return List.of( - new OutboxEvent( - event.eventId(), - event.eventType(), - event.aggregateId(), - event.payload(), - event.occurredAt(), - event.correlationId(), - event.idempotencyKey(), - currentStatus, - attemptCount)); - } - - @Override - public void markPublished(String eventId) { + public OutboxCompletion markPublished(OutboxLease lease) { throw markPublishedException; } @Override - public void markFailed(String eventId, Instant retryAt) { + public OutboxCompletion markFailed(OutboxLease lease, Instant retryAt) { markFailedCalls++; - currentStatus = OutboxEventStatus.FAILED; - nextAttemptAt = retryAt; + return super.markFailed(lease, retryAt); } @Override - public void markDead(String eventId) { + public OutboxCompletion markDead(OutboxLease lease) { markDeadCalls++; - currentStatus = OutboxEventStatus.DEAD; - } - - @Override - public Map countByStatus() { - return Map.of(currentStatus, 1L); - } - - @Override - public Map oldestUnpublishedAgeSecondsByEventType(Instant now) { - return Map.of(); + return super.markDead(lease); } OutboxEventStatus currentStatus() { - return currentStatus; + return status(eventId); } int attemptCount() { - return attemptCount; + return attemptCount(eventId); } Instant nextAttemptAt() { - return nextAttemptAt; + return nextAttemptAt(eventId); } int markFailedCalls() { @@ -611,19 +546,19 @@ class PublishPendingOutboxEventsUseCaseTest { } @Override - public void markFailed(String eventId, Instant nextAttemptAt) { + public OutboxCompletion markFailed(OutboxLease lease, Instant nextAttemptAt) { if (markFailedException != null) { throw markFailedException; } - super.markFailed(eventId, nextAttemptAt); + return super.markFailed(lease, nextAttemptAt); } @Override - public void markDead(String eventId) { + public OutboxCompletion markDead(OutboxLease lease) { if (markDeadException != null) { throw markDeadException; } - super.markDead(eventId); + return super.markDead(lease); } } diff --git a/src/application-core/src/test/java/dev/caskeleton/application/outbox/testkit/InMemoryOutboxStoreLeaseFencingContractTest.java b/src/application-core/src/test/java/dev/caskeleton/application/outbox/testkit/InMemoryOutboxStoreLeaseFencingContractTest.java new file mode 100644 index 00000000..d4b4539d --- /dev/null +++ b/src/application-core/src/test/java/dev/caskeleton/application/outbox/testkit/InMemoryOutboxStoreLeaseFencingContractTest.java @@ -0,0 +1,32 @@ +package dev.caskeleton.application.outbox.testkit; + +import dev.caskeleton.application.outbox.LegacyOutboxAppendPort; +import dev.caskeleton.application.outbox.OutboxEventStatus; +import dev.caskeleton.application.outbox.OutboxStorePort; +import dev.caskeleton.application.transaction.TransactionPort; +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; + +class InMemoryOutboxStoreLeaseFencingContractTest extends OutboxLeaseFencingContract { + + private final InMemoryOutboxStore store = new InMemoryOutboxStore(); + + @Override + protected OutboxStorePort store() { + return store; + } + + @Override + protected LegacyOutboxAppendPort append() { + return store; + } + + @Override + protected TransactionPort transactions() { + return new DirectTransactionPort(); + } + + @Override + protected OutboxEventStatus statusOf(String eventId) { + return store.status(eventId); + } +} diff --git a/src/application-core/src/test/java/dev/caskeleton/application/outbox/v2/OutboxDeliveryV2ContractTest.java b/src/application-core/src/test/java/dev/caskeleton/application/outbox/v2/OutboxDeliveryV2ContractTest.java deleted file mode 100644 index d89969aa..00000000 --- a/src/application-core/src/test/java/dev/caskeleton/application/outbox/v2/OutboxDeliveryV2ContractTest.java +++ /dev/null @@ -1,84 +0,0 @@ -package dev.caskeleton.application.outbox.v2; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.application.transaction.OperationId; -import java.time.Instant; -import java.time.LocalDate; -import org.junit.jupiter.api.Test; - -class OutboxDeliveryV2ContractTest { - - @Test - void ownerHandleCarriesTheFullDeliveryCasTuple() { - OutboxDeliveryOwner owner = - new OutboxDeliveryOwner( - LocalDate.parse("2026-07-28"), - "event-1", - "portfolio.events", - "relay-1", - "a".repeat(64), - 2, - 7, - 3); - - assertThat(owner.attempt()).isEqualTo(2); - assertThat(owner.version()).isEqualTo(7); - assertThat(owner.publicationEpoch()).isEqualTo(3); - - assertThatThrownBy( - () -> - new OutboxDeliveryOwner( - LocalDate.parse("2026-07-28"), - "event-1", - "portfolio.events", - "relay-1", - "a".repeat(64), - 0, - 7, - 3)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("attempt"); - } - - @Test - void claimedDeliveryCarriesTheExactCanonicalEvent() { - OutboxDeliveryOwner owner = - new OutboxDeliveryOwner( - LocalDate.parse("2026-07-28"), - "event-1", - "portfolio-events", - "relay-1", - "a".repeat(64), - 1, - 2, - 1); - var canonical = OutboxV2ContractTest.canonicalEvent(); - - Instant createdAt = Instant.parse("2026-07-28T12:00:00Z"); - ClaimedOutboxDelivery claimed = - new ClaimedOutboxDelivery(owner, canonical, createdAt, createdAt); - - assertThat(claimed.owner()).isSameAs(owner); - assertThat(claimed.event()).isSameAs(canonical); - } - - @Test - void completionRequestRequiresStableOperationIdentity() { - OutboxDeliveryTransition transition = - new OutboxDeliveryTransition( - new OutboxDeliveryOwner( - LocalDate.parse("2026-07-28"), - "event-1", - "portfolio.events", - "relay-1", - "a".repeat(64), - 1, - 2, - 1), - new OperationId("publish-complete-1")); - - assertThat(transition.operationId().value()).isEqualTo("publish-complete-1"); - } -} diff --git a/src/application-core/src/test/java/dev/caskeleton/application/outbox/v2/OutboxV2ContractTest.java b/src/application-core/src/test/java/dev/caskeleton/application/outbox/v2/OutboxV2ContractTest.java deleted file mode 100644 index 4ac18a8f..00000000 --- a/src/application-core/src/test/java/dev/caskeleton/application/outbox/v2/OutboxV2ContractTest.java +++ /dev/null @@ -1,67 +0,0 @@ -package dev.caskeleton.application.outbox.v2; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatNullPointerException; - -import dev.caskeleton.application.messaging.contract.ContractId; -import dev.caskeleton.application.messaging.contract.LogicalDestinationId; -import dev.caskeleton.application.messaging.contract.Sha256; -import dev.caskeleton.application.messaging.event.AggregateIdentity; -import dev.caskeleton.application.messaging.event.AggregateOrder; -import dev.caskeleton.application.messaging.event.EventId; -import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent; -import java.nio.charset.StandardCharsets; -import java.time.Instant; -import java.util.Optional; -import org.junit.jupiter.api.Test; - -class OutboxV2ContractTest { - - @Test - void appendIntentWrapsTheCanonicalEventWithoutASecondRawPayloadModel() { - ValidatedIntegrationEvent canonical = canonicalEvent(); - NewOutboxEventV2 event = new NewOutboxEventV2(canonical); - - assertThat(event.event()).isSameAs(canonical); - assertThat(event.eventId()).isEqualTo("event-1"); - assertThat(event.aggregateVersion()).isEqualTo(7); - assertThat(event.eventOrdinal()).isEqualTo(2); - assertThat(event.eventType()).isEqualTo("portfolio.worklog.changed"); - assertThat(event.eventSchema()).isEqualTo(3); - assertThat(event.logicalDestination()).isEqualTo("portfolio-events"); - assertThat(event.partitionKey()).isEqualTo("a".repeat(64)); - } - - @Test - void appendIntentCannotExistWithoutACanonicalEvent() { - assertThatNullPointerException() - .isThrownBy(() -> new NewOutboxEventV2(null)) - .withMessage("event"); - } - - static ValidatedIntegrationEvent canonicalEvent() { - String partition = "a".repeat(64); - Sha256 zero = new Sha256(new byte[32]); - return new ValidatedIntegrationEvent( - new EventId("event-1"), - new ContractId("portfolio.worklog.changed"), - 1, - 3, - new LogicalDestinationId("portfolio-events"), - new AggregateIdentity("tenant-a", "worklog", "work-log-42"), - new AggregateOrder(7, 2), - Instant.parse("2026-07-28T12:00:00Z"), - "correlation-1", - Optional.empty(), - partition, - partition.getBytes(StandardCharsets.US_ASCII), - "{\"wire\":\"exact\"}".getBytes(StandardCharsets.UTF_8), - "application/json", - zero, - zero, - zero, - zero, - "catalog-r1", - "binding-r1"); - } -} diff --git a/src/application-core/src/test/java/dev/caskeleton/application/testsupport/CompiledPackageScanner.java b/src/application-core/src/test/java/dev/caskeleton/application/testsupport/CompiledPackageScanner.java deleted file mode 100644 index 76f57033..00000000 --- a/src/application-core/src/test/java/dev/caskeleton/application/testsupport/CompiledPackageScanner.java +++ /dev/null @@ -1,66 +0,0 @@ -package dev.caskeleton.application.testsupport; - -import java.io.IOException; -import java.io.UncheckedIOException; -import java.net.URISyntaxException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.List; -import java.util.jar.JarFile; -import java.util.stream.Stream; - -/** Scans compiled classes from either a classes directory or the project's packaged JAR. */ -public final class CompiledPackageScanner { - - private CompiledPackageScanner() {} - - public static List classNamesUnder(Class anchor, String packageName) { - try { - Path codeSource = Path.of(anchor.getProtectionDomain().getCodeSource().getLocation().toURI()); - String packagePath = packageName.replace('.', '/'); - if (Files.isDirectory(codeSource)) { - return fromDirectory(codeSource.resolve(packagePath), packageName); - } - if (Files.isRegularFile(codeSource)) { - return fromJar(codeSource, packagePath); - } - throw new IOException("unsupported compiled-code location: " + codeSource); - } catch (URISyntaxException | IOException unreadable) { - throw new UncheckedIOException( - new IOException("cannot scan compiled package " + packageName, unreadable)); - } - } - - private static List fromDirectory(Path packageRoot, String packageName) - throws IOException { - if (!Files.isDirectory(packageRoot)) { - return List.of(); - } - try (Stream files = Files.walk(packageRoot)) { - return files - .filter(path -> path.toString().endsWith(".class")) - .map( - path -> - packageName - + "." - + packageRoot - .relativize(path) - .toString() - .replace(java.io.File.separatorChar, '.') - .replaceAll("\\.class$", "")) - .toList(); - } - } - - private static List fromJar(Path jarPath, String packagePath) throws IOException { - String prefix = packagePath.endsWith("/") ? packagePath : packagePath + "/"; - try (JarFile jar = new JarFile(jarPath.toFile())) { - return jar.stream() - .map(entry -> entry.getName()) - .filter(name -> name.startsWith(prefix)) - .filter(name -> name.endsWith(".class")) - .map(name -> name.substring(0, name.length() - ".class".length()).replace('/', '.')) - .toList(); - } - } -} diff --git a/src/application-core/src/test/java/dev/caskeleton/application/transaction/TransactionRequestTest.java b/src/application-core/src/test/java/dev/caskeleton/application/transaction/TransactionRequestTest.java deleted file mode 100644 index 077e7de8..00000000 --- a/src/application-core/src/test/java/dev/caskeleton/application/transaction/TransactionRequestTest.java +++ /dev/null @@ -1,114 +0,0 @@ -package dev.caskeleton.application.transaction; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.application.outbound.CallBudget; -import java.time.Duration; -import java.util.Optional; -import org.junit.jupiter.api.Test; - -class TransactionRequestTest { - - private static final CallBudget BUDGET = CallBudget.after(1_000, Duration.ofSeconds(5)); - private static final OperationId OPERATION_ID = new OperationId("operation-42"); - - @Test - void commandPoliciesRequireAStableOperationIdAndRejectReadConsistency() { - TransactionRequest request = - new TransactionRequest( - TransactionPolicyId.COMMAND_DEFAULT, - BUDGET, - Optional.empty(), - Optional.of(OPERATION_ID)); - - assertThat(request.operationId()).contains(OPERATION_ID); - assertThatThrownBy( - () -> - new TransactionRequest( - TransactionPolicyId.COMMAND_DEFAULT, - BUDGET, - Optional.empty(), - Optional.empty())) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("operationId"); - assertThatThrownBy( - () -> - new TransactionRequest( - TransactionPolicyId.COMMAND_DEFAULT, - BUDGET, - Optional.of(ReadConsistency.STRONG), - Optional.of(OPERATION_ID))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("readConsistency"); - } - - @Test - void queryPrimaryAcceptsOnlyStrongOrReadYourWrites() { - assertThat( - new TransactionRequest( - TransactionPolicyId.QUERY_PRIMARY, - BUDGET, - Optional.of(ReadConsistency.STRONG), - Optional.empty()) - .readConsistency()) - .contains(ReadConsistency.STRONG); - assertThat( - new TransactionRequest( - TransactionPolicyId.QUERY_PRIMARY, - BUDGET, - Optional.of(ReadConsistency.READ_YOUR_WRITES), - Optional.empty()) - .readConsistency()) - .contains(ReadConsistency.READ_YOUR_WRITES); - assertThatThrownBy( - () -> - new TransactionRequest( - TransactionPolicyId.QUERY_PRIMARY, - BUDGET, - Optional.of(ReadConsistency.EVENTUAL), - Optional.empty())) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("QUERY_PRIMARY"); - } - - @Test - void replicaEligibleQueryAcceptsOnlyEventualOrBoundedStaleness() { - assertThat( - new TransactionRequest( - TransactionPolicyId.QUERY_REPLICA_ELIGIBLE, - BUDGET, - Optional.of(ReadConsistency.BOUNDED_STALENESS), - Optional.empty()) - .readConsistency()) - .contains(ReadConsistency.BOUNDED_STALENESS); - assertThatThrownBy( - () -> - new TransactionRequest( - TransactionPolicyId.QUERY_REPLICA_ELIGIBLE, - BUDGET, - Optional.of(ReadConsistency.STRONG), - Optional.empty())) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("QUERY_REPLICA_ELIGIBLE"); - } - - @Test - void readPoliciesRequireAnExplicitConsistency() { - assertThatThrownBy( - () -> - new TransactionRequest( - TransactionPolicyId.QUERY_PRIMARY, BUDGET, Optional.empty(), Optional.empty())) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("readConsistency"); - } - - @Test - void outboxAppendCanInheritTheOuterOperationIdentity() { - TransactionRequest request = - new TransactionRequest( - TransactionPolicyId.OUTBOX_APPEND, BUDGET, Optional.empty(), Optional.empty()); - - assertThat(request.operationId()).isEmpty(); - } -} diff --git a/src/application-core/src/test/java/dev/caskeleton/application/transaction/TransactionResultTest.java b/src/application-core/src/test/java/dev/caskeleton/application/transaction/TransactionResultTest.java deleted file mode 100644 index 70cef3c2..00000000 --- a/src/application-core/src/test/java/dev/caskeleton/application/transaction/TransactionResultTest.java +++ /dev/null @@ -1,58 +0,0 @@ -package dev.caskeleton.application.transaction; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.util.Optional; -import org.junit.jupiter.api.Test; - -class TransactionResultTest { - - private static final OperationId OPERATION_ID = new OperationId("operation-42"); - - @Test - void representsCommittedAndParticipatingResultsWithoutConflatingThem() { - TransactionResult committed = - new TransactionResult.Committed<>("value", Optional.of(OPERATION_ID)); - TransactionResult participating = new TransactionResult.Participating<>("value"); - - assertThat(committed.outcome()).isEqualTo(TransactionOutcome.COMMITTED); - assertThat(participating.outcome()).isEqualTo(TransactionOutcome.PARTICIPATING_PENDING_OUTER); - } - - @Test - void indeterminateOutcomeCarriesOnlyOptionalSafeReconciliationData() { - ReconciliationReference reference = - new ReconciliationReference("operation-ledger:operation-42"); - TransactionResult result = - new TransactionResult.Indeterminate<>( - Optional.of(OPERATION_ID), TransactionPhase.COMMIT_REQUESTED, Optional.of(reference)); - - assertThat(result.outcome()).isEqualTo(TransactionOutcome.INDETERMINATE); - assertThat(((TransactionResult.Indeterminate) result).reconciliationReference()) - .contains(reference); - } - - @Test - void determinateRollbackAndPostCommitFailureKeepDifferentOutcomes() { - RuntimeException rollback = new IllegalStateException("rolled back"); - RuntimeException cleanup = new IllegalStateException("cleanup failed"); - - TransactionResult rolledBack = new TransactionResult.DeterminateRollback<>(rollback); - TransactionResult committedWithFailure = - new TransactionResult.CommittedWithPostCommitFailure<>( - "value", Optional.of(OPERATION_ID), cleanup); - - assertThat(rolledBack.outcome()).isEqualTo(TransactionOutcome.DETERMINATE_ROLLBACK); - assertThat(committedWithFailure.outcome()) - .isEqualTo(TransactionOutcome.COMMITTED_WITH_POST_COMMIT_FAILURE); - } - - @Test - void reconciliationReferenceRejectsUnsafeOrUnboundedText() { - assertThatThrownBy(() -> new ReconciliationReference("raw\nsql")) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> new ReconciliationReference("a".repeat(257))) - .isInstanceOf(IllegalArgumentException.class); - } -} diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/InMemoryIdempotencyStore.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/InMemoryIdempotencyStore.java new file mode 100644 index 00000000..40da620f --- /dev/null +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/InMemoryIdempotencyStore.java @@ -0,0 +1,256 @@ +package dev.caskeleton.application.idempotency.testkit; + +import dev.caskeleton.application.idempotency.IdempotencyClaimAttempt; +import dev.caskeleton.application.idempotency.IdempotencyClaimOutcome; +import dev.caskeleton.application.idempotency.IdempotencyClaimRequest; +import dev.caskeleton.application.idempotency.IdempotencyCompleteOutcome; +import dev.caskeleton.application.idempotency.IdempotencyFailOutcome; +import dev.caskeleton.application.idempotency.IdempotencyFailureDisposition; +import dev.caskeleton.application.idempotency.IdempotencyInspection; +import dev.caskeleton.application.idempotency.IdempotencyInspectionOutcome; +import dev.caskeleton.application.idempotency.IdempotencyInspectionRequest; +import dev.caskeleton.application.idempotency.IdempotencyMutationResult; +import dev.caskeleton.application.idempotency.IdempotencyOwner; +import dev.caskeleton.application.idempotency.IdempotencyReleaseOutcome; +import dev.caskeleton.application.idempotency.IdempotencyRenewOutcome; +import dev.caskeleton.application.idempotency.IdempotencyStartOutcome; +import dev.caskeleton.application.idempotency.IdempotencyState; +import dev.caskeleton.application.idempotency.IdempotencyStorePort; +import dev.caskeleton.application.idempotency.RequestFingerprint; +import dev.caskeleton.application.idempotency.StoredResponse; +import dev.caskeleton.application.transaction.OperationId; +import java.time.Duration; +import java.time.Instant; +import java.util.HashMap; +import java.util.HexFormat; +import java.util.Map; +import java.util.Optional; +import java.util.Random; + +/** + * In-memory {@link IdempotencyStorePort} for use-case and composition tests. + * + *

Models the owner-safe state machine without time: a claim is never expired, so a second + * attempt against an in-flight record is always {@code InProgress}. Leases and replay windows are + * reported as {@link Instant#MAX}. What it keeps exact is what a test of a caller relies on: one + * claim wins, the owner handle's revision advances on every transition, a completed response + * replays, a different fingerprint is refused, and a retryable failure can be claimed again. + */ +public final class InMemoryIdempotencyStore implements IdempotencyStorePort { + + private final Map rows = new HashMap<>(); + private final Random tokens = new Random(0); + + @Override + public synchronized IdempotencyClaimAttempt newClaimAttempt(OperationId operationId) { + byte[] token = new byte[32]; + tokens.nextBytes(token); + return new IdempotencyClaimAttempt(HexFormat.of().formatHex(token), operationId); + } + + @Override + public synchronized IdempotencyClaimOutcome claim(IdempotencyClaimRequest request) { + Row row = rows.get(request.scope().digest()); + if (row == null || row.state == IdempotencyState.FAILED_RETRYABLE) { + long attempt = row == null ? 1 : row.owner.attempt() + 1; + long revision = row == null ? 0 : row.owner.stateRevision() + 1; + Row claimed = new Row(request.requestFingerprint(), request, attempt, revision); + rows.put(request.scope().digest(), claimed); + return row == null + ? new IdempotencyClaimOutcome.Acquired(claimed.owner, Instant.MAX) + : new IdempotencyClaimOutcome.TakenOverClaimed(claimed.owner, Instant.MAX); + } + if (!row.fingerprint.equals(request.requestFingerprint())) { + return new IdempotencyClaimOutcome.FingerprintMismatch(); + } + if (row.state == IdempotencyState.COMPLETED) { + return new IdempotencyClaimOutcome.CompletedReplay(row.response, Instant.MAX); + } + if (row.owner.ownerToken().equals(request.claimAttempt().ownerToken()) + && row.owner.claimOperationId().equals(request.claimAttempt().operationId())) { + return new IdempotencyClaimOutcome.ReplayedAcquire(row.owner, Instant.MAX); + } + if (row.state == IdempotencyState.ABANDONED) { + return new IdempotencyClaimOutcome.RecoveryRequired(row.owner.attempt()); + } + return new IdempotencyClaimOutcome.InProgress(Duration.ZERO, row.owner.attempt()); + } + + @Override + public synchronized IdempotencyMutationResult markExecutionStarted( + IdempotencyOwner owner, OperationId operationId) { + Row row = rows.get(owner.scope().digest()); + IdempotencyStartOutcome outcome = + row == null + ? IdempotencyStartOutcome.ABSENT + : !row.owner.equals(owner) + ? IdempotencyStartOutcome.NOT_OWNER + : row.state != IdempotencyState.CLAIMED + ? IdempotencyStartOutcome.NOT_CLAIMED + : IdempotencyStartOutcome.STARTED; + if (outcome != IdempotencyStartOutcome.STARTED) { + return new IdempotencyMutationResult<>(outcome, null, IdempotencyStartOutcome::carriesOwner); + } + row.advance(IdempotencyState.EXECUTING); + return new IdempotencyMutationResult<>( + outcome, row.owner, IdempotencyStartOutcome::carriesOwner); + } + + @Override + public synchronized IdempotencyMutationResult renew( + IdempotencyOwner owner, Duration processingLeaseTtl, OperationId operationId) { + Row row = rows.get(owner.scope().digest()); + if (row == null || !row.owner.equals(owner) || !row.inProgress()) { + IdempotencyRenewOutcome refused = + row == null ? IdempotencyRenewOutcome.ABSENT : IdempotencyRenewOutcome.NOT_OWNER; + return new IdempotencyMutationResult<>(refused, null, IdempotencyRenewOutcome::carriesOwner); + } + row.advance(row.state); + return new IdempotencyMutationResult<>( + IdempotencyRenewOutcome.RENEWED, row.owner, IdempotencyRenewOutcome::carriesOwner); + } + + @Override + public synchronized IdempotencyCompleteOutcome complete( + IdempotencyOwner owner, + StoredResponse response, + Duration replayTtl, + OperationId operationId) { + Row row = rows.get(owner.scope().digest()); + if (row == null) { + return IdempotencyCompleteOutcome.ABSENT; + } + if (!row.owner.equals(owner)) { + return IdempotencyCompleteOutcome.NOT_OWNER; + } + if (row.state != IdempotencyState.EXECUTING) { + return IdempotencyCompleteOutcome.NOT_IN_PROGRESS; + } + row.response = response; + row.advance(IdempotencyState.COMPLETED); + return IdempotencyCompleteOutcome.COMPLETED; + } + + @Override + public synchronized IdempotencyFailOutcome markFailed( + IdempotencyOwner owner, + IdempotencyFailureDisposition disposition, + Duration retention, + OperationId operationId) { + Row row = rows.get(owner.scope().digest()); + if (row == null) { + return IdempotencyFailOutcome.ABSENT; + } + if (!row.owner.equals(owner)) { + return IdempotencyFailOutcome.NOT_OWNER; + } + if (row.state != IdempotencyState.EXECUTING) { + return IdempotencyFailOutcome.NOT_IN_PROGRESS; + } + boolean retryable = disposition == IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE; + row.advance(retryable ? IdempotencyState.FAILED_RETRYABLE : IdempotencyState.ABANDONED); + return retryable + ? IdempotencyFailOutcome.MARKED_RETRYABLE + : IdempotencyFailOutcome.MARKED_ABANDONED; + } + + @Override + public synchronized IdempotencyReleaseOutcome releaseBeforeExecution( + IdempotencyOwner owner, OperationId operationId) { + Row row = rows.get(owner.scope().digest()); + if (row == null) { + return IdempotencyReleaseOutcome.ABSENT; + } + if (!row.owner.equals(owner)) { + return IdempotencyReleaseOutcome.NOT_OWNER; + } + if (row.state != IdempotencyState.CLAIMED) { + return IdempotencyReleaseOutcome.EXECUTION_ALREADY_STARTED; + } + rows.remove(owner.scope().digest()); + return IdempotencyReleaseOutcome.RELEASED_BEFORE_EXECUTION; + } + + @Override + public synchronized IdempotencyInspection inspect(IdempotencyInspectionRequest request) { + Row row = rows.get(request.scope().digest()); + if (row == null) { + return IdempotencyInspection.outcome(IdempotencyInspectionOutcome.ABSENT); + } + if (!row.fingerprint.equals(request.requestFingerprint())) { + return IdempotencyInspection.outcome(IdempotencyInspectionOutcome.FINGERPRINT_MISMATCH); + } + if (row.state == IdempotencyState.COMPLETED) { + return new IdempotencyInspection( + IdempotencyInspectionOutcome.COMPLETED_REPLAY, + Optional.empty(), + Optional.empty(), + Optional.of(row.response), + Optional.of(Instant.MAX)); + } + boolean sameAttempt = + row.owner.ownerToken().equals(request.claimAttempt().ownerToken()) + && row.owner.claimOperationId().equals(request.claimAttempt().operationId()); + IdempotencyInspectionOutcome outcome = + switch (row.state) { + case CLAIMED -> + sameAttempt + ? IdempotencyInspectionOutcome.CLAIMED_SAME_OPERATION + : IdempotencyInspectionOutcome.IN_PROGRESS_OTHER; + case EXECUTING -> + sameAttempt + ? IdempotencyInspectionOutcome.EXECUTING_SAME_OPERATION + : IdempotencyInspectionOutcome.IN_PROGRESS_OTHER; + case FAILED_RETRYABLE -> IdempotencyInspectionOutcome.FAILED_RETRYABLE; + default -> IdempotencyInspectionOutcome.ABANDONED; + }; + return outcome == IdempotencyInspectionOutcome.CLAIMED_SAME_OPERATION + || outcome == IdempotencyInspectionOutcome.EXECUTING_SAME_OPERATION + ? new IdempotencyInspection( + outcome, + Optional.of(row.owner), + Optional.of(Instant.MAX), + Optional.empty(), + Optional.empty()) + : IdempotencyInspection.outcome(outcome); + } + + /** + * The state the store holds for a scope digest, for assertions. + * + * @param scopeDigest the scope digest + * @return the state, or empty when no record exists + */ + public synchronized Optional stateOf(String scopeDigest) { + return Optional.ofNullable(rows.get(scopeDigest)).map(row -> row.state); + } + + /** One record. */ + private static final class Row { + + private final RequestFingerprint fingerprint; + private IdempotencyOwner owner; + private IdempotencyState state = IdempotencyState.CLAIMED; + private StoredResponse response; + + Row(RequestFingerprint fingerprint, IdempotencyClaimRequest request, long attempt, long rev) { + this.fingerprint = fingerprint; + this.owner = + new IdempotencyOwner( + request.scope(), + request.claimAttempt().ownerToken(), + attempt, + rev, + request.claimAttempt().operationId()); + } + + boolean inProgress() { + return state == IdempotencyState.CLAIMED || state == IdempotencyState.EXECUTING; + } + + void advance(IdempotencyState next) { + owner = owner.withStateRevision(owner.stateRevision() + 1); + state = next; + } + } +} diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/operation/testkit/DurableOperationStoreContract.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/operation/testkit/DurableOperationStoreContract.java new file mode 100644 index 00000000..17d72dd1 --- /dev/null +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/operation/testkit/DurableOperationStoreContract.java @@ -0,0 +1,436 @@ +package dev.caskeleton.application.operation.testkit; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.application.idempotency.RequestFingerprint; +import dev.caskeleton.application.operation.DurableOperation; +import dev.caskeleton.application.operation.DurableOperationId; +import dev.caskeleton.application.operation.DurableOperationState; +import dev.caskeleton.application.operation.DurableOperationStorePort; +import dev.caskeleton.application.operation.DurableOperationSubmission; +import dev.caskeleton.application.operation.OperationFailure; +import dev.caskeleton.application.operation.OperationLease; +import dev.caskeleton.application.operation.OperationProgressSnapshot; +import java.time.Duration; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.function.Supplier; +import org.junit.jupiter.api.Test; + +/** + * What every {@link DurableOperationStorePort} promises, run against the in-memory fake and the + * PostgreSQL adapter alike. + * + *

Every call goes through {@link #inTransaction}, because the real store refuses writes without + * a caller transaction and because a resubmission must leave that transaction usable. + */ +public abstract class DurableOperationStoreContract { + + private static final Instant NOW = Instant.parse("2026-08-25T09:00:00Z"); + private static final Duration LEASE = Duration.ofMinutes(2); + private static final Duration TTL = Duration.ofDays(1); + private static final String HASH_A = "a".repeat(64); + private static final String HASH_B = "b".repeat(64); + + /** The store under test, empty at the start of each test. */ + protected abstract DurableOperationStorePort store(); + + /** Runs {@code work} in one committed write transaction of the store under test. */ + protected abstract T inTransaction(Supplier work); + + @Test + void submitReturnsAPendingOperation() { + // when + DurableOperation submitted = submit(submission("op-1", null, HASH_A)); + + // then + assertThat(submitted) + .usingRecursiveComparison() + .isEqualTo( + new DurableOperation( + id("op-1"), + "reports.generate", + "alice", + null, + DurableOperationState.PENDING, + NOW, + Optional.empty(), + Optional.empty(), + Optional.empty(), + Optional.empty(), + Optional.empty(), + Optional.empty(), + NOW.plus(TTL))); + } + + @Test + void identicalResubmissionReturnsTheFirstOperation() { + // given + DurableOperation first = submit(submission("op-1", null, HASH_A)); + + // when + DurableOperation again = submit(submission("op-2", null, HASH_A)); + + // then + assertThat(again).isEqualTo(first); + } + + @Test + void identicalResubmissionInsideOneTransactionReturnsTheFirstOperation() { + // when + DurableOperation again = + inTransaction( + () -> { + store().submit(submission("op-1", null, HASH_A)); + return store().submit(submission("op-2", null, HASH_A)); + }); + + // then + assertThat(again.operationId()).isEqualTo(id("op-1")); + } + + @Test + void differentFingerprintIsADifferentOperation() { + // given + submit(submission("op-1", null, HASH_A)); + + // when + DurableOperation second = submit(submission("op-2", null, HASH_B)); + + // then + assertThat(second.operationId()).isEqualTo(id("op-2")); + } + + @Test + void sameRequestInAnotherTenantIsADifferentOperation() { + // given + submit(submission("op-1", null, HASH_A)); + + // when + DurableOperation tenantScoped = submit(submission("op-2", "t-1", HASH_A)); + + // then + assertThat(tenantScoped) + .extracting(DurableOperation::operationId, DurableOperation::tenantId) + .containsExactly(id("op-2"), "t-1"); + } + + @Test + void findReturnsTheOperationToItsPrincipal() { + // given + DurableOperation submitted = submit(submission("op-1", null, HASH_A)); + + // when + Optional found = find("op-1", "alice", NOW); + + // then + assertThat(found).contains(submitted); + } + + @Test + void findHidesTheOperationFromAnotherPrincipal() { + // given + submit(submission("op-1", null, HASH_A)); + + // when + Optional found = find("op-1", "mallory", NOW); + + // then + assertThat(found).isEmpty(); + } + + @Test + void findReportsAnAgedOutOperationAsExpired() { + // given + submit(submission("op-1", null, HASH_A)); + + // when + DurableOperation found = find("op-1", "alice", NOW.plus(TTL)).orElseThrow(); + + // then + assertThat(found) + .extracting(DurableOperation::state, DurableOperation::completedAt) + .containsExactly(DurableOperationState.EXPIRED, Optional.of(NOW.plus(TTL))); + } + + @Test + void claimHandsTheWorkerTheSubmittedWork() { + // given + DurableOperationSubmission submission = submission("op-1", null, HASH_A); + submit(submission); + + // when + Optional claimed = claim("worker-a", NOW); + + // then + assertThat(claimed).contains(submission); + } + + @Test + void liveLeaseIsNotClaimedAgain() { + // given + submit(submission("op-1", null, HASH_A)); + claim("worker-a", NOW); + + // when + Optional claimed = claim("worker-b", NOW.plusSeconds(30)); + + // then + assertThat(claimed).isEmpty(); + } + + @Test + void lapsedLeaseIsClaimedByAnotherWorkerKeepingTheStartTime() { + // given + submit(submission("op-1", null, HASH_A)); + claim("worker-a", NOW); + Instant later = NOW.plus(LEASE).plusSeconds(1); + + // when + claim("worker-b", later); + + // then + assertThat(find("op-1", "alice", later).orElseThrow()) + .extracting(DurableOperation::state, DurableOperation::startedAt, DurableOperation::lease) + .containsExactly( + DurableOperationState.RUNNING, + Optional.of(NOW), + Optional.of(new OperationLease("worker-b", later, later.plus(LEASE)))); + } + + @Test + void heartbeatFromTheLeaseHolderExtendsTheLease() { + // given + submit(submission("op-1", null, HASH_A)); + claim("worker-a", NOW); + Instant beat = NOW.plusSeconds(60); + + // when + inTransaction(() -> store().heartbeat(id("op-1"), "worker-a", LEASE, beat)); + + // then + assertThat(find("op-1", "alice", beat).orElseThrow().lease()) + .contains(new OperationLease("worker-a", NOW, beat.plus(LEASE))); + } + + @Test + void heartbeatFromAWorkerThatLostTheLeaseIsRefused() { + // given + submit(submission("op-1", null, HASH_A)); + claim("worker-a", NOW); + Instant later = NOW.plus(LEASE).plusSeconds(1); + claim("worker-b", later); + + // when + boolean extended = + inTransaction(() -> store().heartbeat(id("op-1"), "worker-a", LEASE, later.plusSeconds(1))); + + // then + assertThat(extended).isFalse(); + } + + @Test + void progressFromTheLeaseHolderIsPublished() { + // given + submit(submission("op-1", null, HASH_A)); + claim("worker-a", NOW); + OperationProgressSnapshot progress = + new OperationProgressSnapshot(3, Optional.of(10L), Optional.of("extracting")); + + // when + inTransaction(() -> store().reportProgress(id("op-1"), "worker-a", progress)); + + // then + assertThat(find("op-1", "alice", NOW).orElseThrow().progress()).contains(progress); + } + + @Test + void progressFromAnotherWorkerIsRefused() { + // given + submit(submission("op-1", null, HASH_A)); + claim("worker-a", NOW); + + // when + boolean published = + inTransaction( + () -> store().reportProgress(id("op-1"), "worker-b", OperationProgressSnapshot.of(1))); + + // then + assertThat(published).isFalse(); + } + + @Test + void successFromTheLeaseHolderIsRecorded() { + // given + submit(submission("op-1", null, HASH_A)); + claim("worker-a", NOW); + Instant done = NOW.plusSeconds(10); + + // when + inTransaction(() -> store().succeed(id("op-1"), "worker-a", "/results/a", done)); + + // then + assertThat(find("op-1", "alice", done).orElseThrow()) + .extracting( + DurableOperation::state, + DurableOperation::resultReference, + DurableOperation::completedAt, + DurableOperation::lease) + .containsExactly( + DurableOperationState.SUCCEEDED, + Optional.of("/results/a"), + Optional.of(done), + Optional.empty()); + } + + @Test + void staleWorkerCannotRecordAResultOverItsSuccessor() { + // given + submit(submission("op-1", null, HASH_A)); + claim("worker-a", NOW); + Instant later = NOW.plus(LEASE).plusSeconds(1); + claim("worker-b", later); + + // when + boolean recorded = + inTransaction( + () -> store().succeed(id("op-1"), "worker-a", "/results/a", later.plusSeconds(1))); + + // then + assertThat(recorded).isFalse(); + } + + @Test + void failureFromTheLeaseHolderIsRecorded() { + // given + submit(submission("op-1", null, HASH_A)); + claim("worker-a", NOW); + OperationFailure failure = new OperationFailure("DEPENDENCY_TIMEOUT", "timed out", true); + + // when + inTransaction(() -> store().fail(id("op-1"), "worker-a", failure, NOW.plusSeconds(10))); + + // then + assertThat(find("op-1", "alice", NOW.plusSeconds(10)).orElseThrow()) + .extracting(DurableOperation::state, DurableOperation::failure) + .containsExactly(DurableOperationState.FAILED, Optional.of(failure)); + } + + @Test + void cancelMovesAnUnfinishedOperationToCanceled() { + // given + submit(submission("op-1", null, HASH_A)); + + // when + cancel("op-1", "alice", NOW.plusSeconds(5)); + + // then + assertThat(find("op-1", "alice", NOW.plusSeconds(5)).orElseThrow()) + .extracting(DurableOperation::state, DurableOperation::completedAt) + .containsExactly(DurableOperationState.CANCELED, Optional.of(NOW.plusSeconds(5))); + } + + @Test + void secondCancelReportsNoChange() { + // given + submit(submission("op-1", null, HASH_A)); + cancel("op-1", "alice", NOW.plusSeconds(5)); + + // when + boolean canceled = cancel("op-1", "alice", NOW.plusSeconds(6)); + + // then + assertThat(canceled).isFalse(); + } + + @Test + void cancelNeverReversesASuccess() { + // given + submit(submission("op-1", null, HASH_A)); + claim("worker-a", NOW); + inTransaction(() -> store().succeed(id("op-1"), "worker-a", "/results/a", NOW.plusSeconds(10))); + + // when + cancel("op-1", "alice", NOW.plusSeconds(20)); + + // then + assertThat(find("op-1", "alice", NOW.plusSeconds(20)).orElseThrow().state()) + .isEqualTo(DurableOperationState.SUCCEEDED); + } + + @Test + void anotherPrincipalCannotCancel() { + // given + submit(submission("op-1", null, HASH_A)); + + // when + boolean canceled = cancel("op-1", "mallory", NOW.plusSeconds(5)); + + // then + assertThat(canceled).isFalse(); + } + + @Test + void reclaimReturnsALapsedLeaseToPending() { + // given + submit(submission("op-1", null, HASH_A)); + claim("worker-a", NOW); + + // when + List reclaimed = + inTransaction(() -> store().reclaimExpiredLeases(NOW.plus(LEASE).plusSeconds(1))); + + // then + assertThat(reclaimed).containsExactly(id("op-1")); + } + + @Test + void expirySweepExpiresAgedOutWorkAndLeavesFinishedWorkAlone() { + // given + submit(submission("op-1", null, HASH_A)); + claim("worker-a", NOW); + inTransaction(() -> store().succeed(id("op-1"), "worker-a", "/results/a", NOW.plusSeconds(10))); + submit(submission("op-2", null, HASH_B)); + + // when + List expired = + inTransaction(() -> store().expireStaleOperations(NOW.plus(TTL).plus(TTL))); + + // then + assertThat(expired).containsExactly(id("op-2")); + } + + private DurableOperation submit(DurableOperationSubmission submission) { + return inTransaction(() -> store().submit(submission)); + } + + private Optional find(String operationId, String principal, Instant now) { + return inTransaction(() -> store().find(id(operationId), principal, now)); + } + + private Optional claim(String workerId, Instant now) { + return inTransaction(() -> store().claimNext(workerId, LEASE, now)); + } + + private boolean cancel(String operationId, String principal, Instant canceledAt) { + return inTransaction(() -> store().cancel(id(operationId), principal, canceledAt)); + } + + private static DurableOperationSubmission submission( + String operationId, String tenantId, String hash) { + return new DurableOperationSubmission( + id(operationId), + "reports.generate", + "alice", + tenantId, + new RequestFingerprint(hash), + "{\"range\":\"2026-08\"}", + NOW, + TTL); + } + + private static DurableOperationId id(String value) { + return new DurableOperationId(value); + } +} diff --git a/src/application-core/src/test/java/dev/caskeleton/application/operation/InMemoryDurableOperationStore.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/operation/testkit/InMemoryDurableOperationStore.java similarity index 84% rename from src/application-core/src/test/java/dev/caskeleton/application/operation/InMemoryDurableOperationStore.java rename to src/application-core/src/testFixtures/java/dev/caskeleton/application/operation/testkit/InMemoryDurableOperationStore.java index 4d60d67c..33de76cc 100644 --- a/src/application-core/src/test/java/dev/caskeleton/application/operation/InMemoryDurableOperationStore.java +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/operation/testkit/InMemoryDurableOperationStore.java @@ -1,5 +1,13 @@ -package dev.caskeleton.application.operation; +package dev.caskeleton.application.operation.testkit; +import dev.caskeleton.application.operation.DurableOperation; +import dev.caskeleton.application.operation.DurableOperationId; +import dev.caskeleton.application.operation.DurableOperationState; +import dev.caskeleton.application.operation.DurableOperationStorePort; +import dev.caskeleton.application.operation.DurableOperationSubmission; +import dev.caskeleton.application.operation.OperationFailure; +import dev.caskeleton.application.operation.OperationLease; +import dev.caskeleton.application.operation.OperationProgressSnapshot; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; @@ -15,15 +23,17 @@ import java.util.concurrent.ConcurrentHashMap; *

Written to the same rules rather than to whatever makes the tests pass: a submission scope * that already exists returns the existing operation, a lease is checked on every write, and a * terminal operation is never reopened. A fake that was laxer than the adapter would let the use - * case tests certify behaviour the real store refuses. + * case tests certify behaviour the real store refuses. {@link DurableOperationStoreContract} holds + * this fake and the adapter to the same cases. */ -final class InMemoryDurableOperationStore implements DurableOperationStorePort { +public final class InMemoryDurableOperationStore implements DurableOperationStorePort { private record Scope(String tenant, String principal, String operationName, String hash) {} private final Map byId = new ConcurrentHashMap<>(); private final Map byScope = new ConcurrentHashMap<>(); - private final Map payloads = new ConcurrentHashMap<>(); + private final Map submissions = + new ConcurrentHashMap<>(); @Override public DurableOperation submit(DurableOperationSubmission submission) { @@ -53,7 +63,7 @@ final class InMemoryDurableOperationStore implements DurableOperationStorePort { Optional.empty(), submission.expiresAt()); byId.put(submission.operationId(), operation); - payloads.put(submission.operationId(), submission.payload()); + submissions.put(submission.operationId(), submission); return operation; } @@ -61,7 +71,8 @@ final class InMemoryDurableOperationStore implements DurableOperationStorePort { public Optional find( DurableOperationId operationId, String principal, Instant now) { return Optional.ofNullable(byId.get(operationId)) - .filter(operation -> operation.principal().equals(principal)); + .filter(operation -> operation.principal().equals(principal)) + .map(operation -> expiredOnRead(operation, now)); } @Override @@ -88,15 +99,7 @@ final class InMemoryDurableOperationStore implements DurableOperationStorePort { Optional.empty(), Optional.of(new OperationLease(workerId, now, now.plus(leaseDuration)))); byId.put(claimed.operationId(), claimed); - return new DurableOperationSubmission( - claimed.operationId(), - claimed.operationName(), - claimed.principal(), - claimed.tenantId(), - new dev.caskeleton.application.idempotency.RequestFingerprint("0".repeat(64)), - payloads.getOrDefault(claimed.operationId(), "{}"), - claimed.submittedAt(), - Duration.between(claimed.submittedAt(), claimed.expiresAt())); + return submissions.get(claimed.operationId()); }); } @@ -259,15 +262,31 @@ final class InMemoryDurableOperationStore implements DurableOperationStorePort { } /** How many operations exist. */ - int size() { + public int size() { return byId.size(); } /** Drops everything, standing in for a rolled-back transaction. */ - void clear() { + public void clear() { byId.clear(); byScope.clear(); - payloads.clear(); + submissions.clear(); + } + + // Same as the adapter: a poll after the TTL sees EXPIRED even before the sweeper runs. + private static DurableOperation expiredOnRead(DurableOperation operation, Instant now) { + if (operation.finished() || now.isBefore(operation.expiresAt())) { + return operation; + } + return replace( + operation, + DurableOperationState.EXPIRED, + operation.startedAt(), + Optional.of(operation.expiresAt()), + operation.progress(), + operation.resultReference(), + Optional.empty(), + Optional.empty()); } private static boolean holdsLease(DurableOperation operation, String workerId, Instant now) { diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/InMemoryOutboxStore.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/InMemoryOutboxStore.java new file mode 100644 index 00000000..fdf174ad --- /dev/null +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/InMemoryOutboxStore.java @@ -0,0 +1,222 @@ +package dev.caskeleton.application.outbox.testkit; + +import dev.caskeleton.application.outbox.LegacyOutboxAppendPort; +import dev.caskeleton.application.outbox.NewOutboxEvent; +import dev.caskeleton.application.outbox.OutboxCompletion; +import dev.caskeleton.application.outbox.OutboxEvent; +import dev.caskeleton.application.outbox.OutboxEventStatus; +import dev.caskeleton.application.outbox.OutboxLease; +import dev.caskeleton.application.outbox.OutboxStorePort; +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * In-memory outbox store with the relay semantics of the SQL one: claim eligibility by status and + * {@code nextAttemptAt}, in-flight reclaim after the timeout, and completions fenced by lease owner + * and token. It does not model the per-aggregate FIFO gate; that lives in the claim SQL and is + * covered against PostgreSQL. + * + *

Not final so a test can override one operation to inject a storage failure. + */ +public class InMemoryOutboxStore implements OutboxStorePort, LegacyOutboxAppendPort { + + private static final Set CLAIMABLE = + Set.of(OutboxEventStatus.PENDING, OutboxEventStatus.FAILED, OutboxEventStatus.IN_FLIGHT); + + private final Map rows = new LinkedHashMap<>(); + private final List published = new ArrayList<>(); + private final Map failed = new LinkedHashMap<>(); + private final List dead = new ArrayList<>(); + + @Override + public void append(NewOutboxEvent event) { + add( + new OutboxEvent( + event.eventId(), + event.eventType(), + event.aggregateId(), + event.payload(), + event.occurredAt(), + event.correlationId(), + event.idempotencyKey(), + OutboxEventStatus.PENDING, + 0), + 0); + } + + /** + * Adds a claimable row that reads as {@code claimedAs} once it is next claimed, so a relay test + * can start at a later attempt. The row is eligible from {@code claimedAs.occurredAt()}. + * + * @param claimedAs the event as the next claim returns it; its attempt count is the count after + * that claim and must be at least 1 + */ + public void addClaimable(OutboxEvent claimedAs) { + if (claimedAs.attemptCount() < 1) { + throw new IllegalArgumentException("a claimed event has made at least one attempt"); + } + add(claimedAs, claimedAs.attemptCount() - 1); + } + + private void add(OutboxEvent event, int attemptsSoFar) { + if (rows.putIfAbsent(event.eventId(), new Row(event, attemptsSoFar)) != null) { + throw new IllegalStateException("duplicate outbox eventId " + event.eventId()); + } + } + + @Override + public List claimBatch( + String owner, int batchSize, Instant now, Duration inFlightTimeout) { + List eligible = + rows.values().stream() + .filter(row -> CLAIMABLE.contains(row.status) && !row.nextAttemptAt.isAfter(now)) + .sorted(Comparator.comparing(row -> row.event.occurredAt())) + .limit(batchSize) + .toList(); + List leases = new ArrayList<>(eligible.size()); + for (Row row : eligible) { + row.status = OutboxEventStatus.IN_FLIGHT; + row.attemptCount++; + row.nextAttemptAt = now.plus(inFlightTimeout); + row.leaseOwner = owner; + row.leaseToken++; + leases.add(new OutboxLease(row.claimed(), owner, row.leaseToken)); + } + return leases; + } + + @Override + public OutboxCompletion markPublished(OutboxLease lease) { + OutboxCompletion completion = complete(lease, OutboxEventStatus.PUBLISHED, null); + if (completion == OutboxCompletion.APPLIED) { + published.add(lease.eventId()); + } + return completion; + } + + @Override + public OutboxCompletion markFailed(OutboxLease lease, Instant nextAttemptAt) { + OutboxCompletion completion = complete(lease, OutboxEventStatus.FAILED, nextAttemptAt); + if (completion == OutboxCompletion.APPLIED) { + failed.put(lease.eventId(), nextAttemptAt); + } + return completion; + } + + @Override + public OutboxCompletion markDead(OutboxLease lease) { + OutboxCompletion completion = complete(lease, OutboxEventStatus.DEAD, null); + if (completion == OutboxCompletion.APPLIED) { + dead.add(lease.eventId()); + } + return completion; + } + + /** The same predicate the SQL completion carries: still IN_FLIGHT, same owner, same token. */ + private OutboxCompletion complete( + OutboxLease lease, OutboxEventStatus status, Instant nextAttemptAt) { + Row row = rows.get(lease.eventId()); + if (row == null + || row.status != OutboxEventStatus.IN_FLIGHT + || !lease.owner().equals(row.leaseOwner) + || lease.token() != row.leaseToken) { + return OutboxCompletion.STALE; + } + row.status = status; + row.leaseOwner = null; + if (nextAttemptAt != null) { + row.nextAttemptAt = nextAttemptAt; + } + return OutboxCompletion.APPLIED; + } + + @Override + public Map countByStatus() { + Map counts = new EnumMap<>(OutboxEventStatus.class); + rows.values().forEach(row -> counts.merge(row.status, 1L, Long::sum)); + return counts; + } + + @Override + public Map oldestUnpublishedAgeSecondsByEventType(Instant now) { + Map ages = new HashMap<>(); + for (Row row : rows.values()) { + if (row.status != OutboxEventStatus.PUBLISHED) { + long age = Duration.between(row.event.occurredAt(), now).toSeconds(); + ages.merge(row.event.eventType(), age, Math::max); + } + } + return ages; + } + + public OutboxEventStatus status(String eventId) { + return row(eventId).status; + } + + public int attemptCount(String eventId) { + return row(eventId).attemptCount; + } + + public Instant nextAttemptAt(String eventId) { + return row(eventId).nextAttemptAt; + } + + /** Event ids whose PUBLISHED completion applied, in order. */ + public List published() { + return List.copyOf(published); + } + + /** Event id to scheduled retry, for every FAILED completion that applied. */ + public Map failed() { + return new LinkedHashMap<>(failed); + } + + /** Event ids whose DEAD completion applied, in order. */ + public List dead() { + return List.copyOf(dead); + } + + private Row row(String eventId) { + Row row = rows.get(eventId); + if (row == null) { + throw new IllegalArgumentException("no outbox row " + eventId); + } + return row; + } + + private static final class Row { + private final OutboxEvent event; + private OutboxEventStatus status = OutboxEventStatus.PENDING; + private int attemptCount; + private Instant nextAttemptAt; + private String leaseOwner; + private long leaseToken; + + private Row(OutboxEvent event, int attemptCount) { + this.event = event; + this.attemptCount = attemptCount; + this.nextAttemptAt = event.occurredAt(); + } + + private OutboxEvent claimed() { + return new OutboxEvent( + event.eventId(), + event.eventType(), + event.aggregateId(), + event.payload(), + event.occurredAt(), + event.correlationId(), + event.idempotencyKey(), + status, + attemptCount); + } + } +} diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/OutboxLeaseFencingContract.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/OutboxLeaseFencingContract.java new file mode 100644 index 00000000..5f5d29bc --- /dev/null +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/OutboxLeaseFencingContract.java @@ -0,0 +1,276 @@ +package dev.caskeleton.application.outbox.testkit; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.application.outbox.LegacyOutboxAppendPort; +import dev.caskeleton.application.outbox.NewOutboxEvent; +import dev.caskeleton.application.outbox.OutboxBackoffPolicy; +import dev.caskeleton.application.outbox.OutboxCompletion; +import dev.caskeleton.application.outbox.OutboxEventStatus; +import dev.caskeleton.application.outbox.OutboxLease; +import dev.caskeleton.application.outbox.OutboxMessagePublishPort; +import dev.caskeleton.application.outbox.OutboxRelayFailureReport; +import dev.caskeleton.application.outbox.OutboxRelayFailureReportPort; +import dev.caskeleton.application.outbox.OutboxRelayResult; +import dev.caskeleton.application.outbox.OutboxRelayResult.Outcome; +import dev.caskeleton.application.outbox.OutboxStorePort; +import dev.caskeleton.application.outbox.PublishPendingOutboxEventsCommand; +import dev.caskeleton.application.outbox.PublishPendingOutboxEventsUseCase; +import dev.caskeleton.application.transaction.TransactionPort; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import org.junit.jupiter.api.Test; + +/** + * What every {@link OutboxStorePort} promises about a claim that outlived its in-flight timeout, + * run through the relay against the in-memory fake and the PostgreSQL adapter alike. + * + *

The interleaving: relay A claims a row and stalls inside the broker call; the claim expires; + * relay B claims the same row and completes it; A finally returns and tries to complete it too. + * Only B's completion may land — otherwise A can mark a published row FAILED (it is published + * again) or hide B's failure behind a late PUBLISHED. + * + *

Every test appends its own row; the subclass supplies an empty store per test. + */ +public abstract class OutboxLeaseFencingContract { + + private static final Instant CLAIMED_AT = Instant.parse("2026-09-25T00:00:00Z"); + private static final Duration IN_FLIGHT_TIMEOUT = Duration.ofSeconds(30); + private static final Instant AFTER_EXPIRY = CLAIMED_AT.plus(IN_FLIGHT_TIMEOUT).plusSeconds(1); + + protected abstract OutboxStorePort store(); + + protected abstract LegacyOutboxAppendPort append(); + + protected abstract TransactionPort transactions(); + + /** Reads the row's persisted status, bypassing anything the store caches. */ + protected abstract OutboxEventStatus statusOf(String eventId); + + @Test + void lateFailureFromASupersededRelayIsStaleAndThePublishedRowStays() { + // given + String eventId = appendEvent("late-failure"); + CountingStore store = new CountingStore(store()); + RecordingReporter reporterA = new RecordingReporter(); + List takeover = new ArrayList<>(); + PublishPendingOutboxEventsUseCase relayB = + relay("relay-b", store, event -> {}, new RecordingReporter(), AFTER_EXPIRY); + PublishPendingOutboxEventsUseCase relayA = + relay( + "relay-a", + store, + event -> { + takeover.add(relayB.handle(PublishPendingOutboxEventsCommand.INSTANCE)); + throw new IllegalStateException("broker call timed out after the claim expired"); + }, + reporterA, + CLAIMED_AT); + + // when + OutboxRelayResult stalled = relayA.handle(PublishPendingOutboxEventsCommand.INSTANCE); + + // then + assertThat( + new Observed( + outcome(stalled, eventId), + outcome(takeover.getFirst(), eventId), + statusOf(eventId), + store.applied.get(), + reporterA.reports)) + .isEqualTo( + new Observed( + Outcome.STALE, + Outcome.PUBLISHED, + OutboxEventStatus.PUBLISHED, + 1, + List.of("stale:" + eventId + ":FAILED"))); + } + + @Test + void lateConfirmationFromASupersededRelayIsStaleAndTheScheduledRetryStays() { + // given + String eventId = appendEvent("late-confirmation"); + CountingStore store = new CountingStore(store()); + RecordingReporter reporterA = new RecordingReporter(); + List takeover = new ArrayList<>(); + PublishPendingOutboxEventsUseCase relayB = + relay( + "relay-b", + store, + event -> { + throw new IllegalStateException("broker unavailable"); + }, + new RecordingReporter(), + AFTER_EXPIRY); + PublishPendingOutboxEventsUseCase relayA = + relay( + "relay-a", + store, + event -> takeover.add(relayB.handle(PublishPendingOutboxEventsCommand.INSTANCE)), + reporterA, + CLAIMED_AT); + + // when + OutboxRelayResult stalled = relayA.handle(PublishPendingOutboxEventsCommand.INSTANCE); + + // then + assertThat( + new Observed( + outcome(stalled, eventId), + outcome(takeover.getFirst(), eventId), + statusOf(eventId), + store.applied.get(), + reporterA.reports)) + .isEqualTo( + new Observed( + Outcome.STALE, + Outcome.FAILED, + OutboxEventStatus.FAILED, + 1, + List.of("stale:" + eventId + ":PUBLISHED"))); + } + + @Test + void aLeaseCompletesItsRowOnlyOnce() { + // given + String eventId = appendEvent("complete-once"); + OutboxLease lease = + transactions() + .inWrite(() -> store().claimBatch("relay-a", 1, CLAIMED_AT, IN_FLIGHT_TIMEOUT)) + .getFirst(); + transactions().inWrite(() -> store().markPublished(lease)); + + // when + OutboxCompletion second = transactions().inWrite(() -> store().markDead(lease)); + + // then + assertThat(Map.entry(second, statusOf(eventId))) + .isEqualTo(Map.entry(OutboxCompletion.STALE, OutboxEventStatus.PUBLISHED)); + } + + private String appendEvent(String scenario) { + String eventId = "lease-fencing-" + scenario + "-" + UUID.randomUUID(); + transactions() + .inWrite( + () -> { + append() + .append( + new NewOutboxEvent( + eventId, + "LeaseFencingContractEvent", + "aggregate-" + eventId, + "{\"scenario\":\"" + scenario + "\"}", + CLAIMED_AT.minusSeconds(1), + "correlation-" + eventId, + eventId)); + return null; + }); + return eventId; + } + + private PublishPendingOutboxEventsUseCase relay( + String owner, + OutboxStorePort store, + OutboxMessagePublishPort publisher, + OutboxRelayFailureReportPort reporter, + Instant now) { + return new PublishPendingOutboxEventsUseCase( + store, + publisher, + reporter, + transactions(), + new OutboxBackoffPolicy(() -> 0L), + Clock.fixed(now, ZoneOffset.UTC), + 10, + IN_FLIGHT_TIMEOUT, + owner); + } + + private static Outcome outcome(OutboxRelayResult result, String eventId) { + return result.outcomes().stream() + .filter(outcome -> outcome.eventId().equals(eventId)) + .map(OutboxRelayResult.EventOutcome::outcome) + .findFirst() + .orElse(null); + } + + private record Observed( + Outcome stalledRelay, + Outcome takeoverRelay, + OutboxEventStatus row, + int appliedCompletions, + List stalledRelayReports) {} + + /** + * Records what the relay reported, as {@code failure:eventId} or {@code stale:eventId:attempt}. + */ + private static final class RecordingReporter implements OutboxRelayFailureReportPort { + private final List reports = new ArrayList<>(); + + @Override + public void report(OutboxRelayFailureReport report) { + reports.add("failure:" + report.eventId()); + } + + @Override + public void reportStaleCompletion(String eventId, String eventType, Outcome attempted) { + reports.add("stale:" + eventId + ":" + attempted); + } + } + + /** Counts the completions the store under test reported as applied. */ + private static final class CountingStore implements OutboxStorePort { + private final OutboxStorePort delegate; + private final AtomicInteger applied = new AtomicInteger(); + + private CountingStore(OutboxStorePort delegate) { + this.delegate = delegate; + } + + @Override + public List claimBatch( + String owner, int batchSize, Instant now, Duration inFlightTimeout) { + return delegate.claimBatch(owner, batchSize, now, inFlightTimeout); + } + + @Override + public OutboxCompletion markPublished(OutboxLease lease) { + return count(delegate.markPublished(lease)); + } + + @Override + public OutboxCompletion markFailed(OutboxLease lease, Instant nextAttemptAt) { + return count(delegate.markFailed(lease, nextAttemptAt)); + } + + @Override + public OutboxCompletion markDead(OutboxLease lease) { + return count(delegate.markDead(lease)); + } + + private OutboxCompletion count(OutboxCompletion completion) { + if (completion == OutboxCompletion.APPLIED) { + applied.incrementAndGet(); + } + return completion; + } + + @Override + public Map countByStatus() { + return delegate.countByStatus(); + } + + @Override + public Map oldestUnpublishedAgeSecondsByEventType(Instant now) { + return delegate.oldestUnpublishedAgeSecondsByEventType(now); + } + } +} diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/transaction/testkit/DirectTransactionPort.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/transaction/testkit/DirectTransactionPort.java new file mode 100644 index 00000000..d83e1eb4 --- /dev/null +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/transaction/testkit/DirectTransactionPort.java @@ -0,0 +1,99 @@ +package dev.caskeleton.application.transaction.testkit; + +import dev.caskeleton.application.transaction.NestedRootTransactionRejectedException; +import dev.caskeleton.application.transaction.TransactionPort; +import java.util.ArrayList; +import java.util.List; +import java.util.function.Supplier; + +/** + * Runs every action in place, for tests over fakes that have no transaction to open, and records + * which boundaries ran so a test can assert them. + * + *

    + *
  • {@link #committed()} lists the boundaries whose action returned, in completion order; an + * action that throws is rolled back and not listed. + *
  • {@link #active()} is true while an action runs, so a fake can record whether it was called + * inside a transaction. + *
  • {@link #inRootWrite} rejects an active transaction, as the real port does. + *
  • {@link #rejectingNesting()} also fails any boundary opened inside another, for use cases + * that must commit each step on its own. + *
+ * + *

Single-threaded: one instance per test. + */ +public final class DirectTransactionPort implements TransactionPort { + + /** The port method a transaction was opened through. */ + public enum Boundary { + WRITE, + ROOT_WRITE, + READ, + NEW + } + + private final boolean rejectNesting; + private final List committed = new ArrayList<>(); + private boolean active; + + public DirectTransactionPort() { + this(false); + } + + private DirectTransactionPort(boolean rejectNesting) { + this.rejectNesting = rejectNesting; + } + + /** A port that fails with {@link IllegalStateException} when a boundary opens inside another. */ + public static DirectTransactionPort rejectingNesting() { + return new DirectTransactionPort(true); + } + + /** Boundaries whose action returned, in completion order. */ + public List committed() { + return List.copyOf(committed); + } + + /** Whether an action is running right now. */ + public boolean active() { + return active; + } + + @Override + public T inWrite(Supplier action) { + return run(Boundary.WRITE, action); + } + + @Override + public T inRootWrite(Supplier action) { + if (active) { + throw new NestedRootTransactionRejectedException(); + } + return run(Boundary.ROOT_WRITE, action); + } + + @Override + public T inRead(Supplier action) { + return run(Boundary.READ, action); + } + + @Override + public T inNew(Supplier action) { + return run(Boundary.NEW, action); + } + + private T run(Boundary boundary, Supplier action) { + if (active && rejectNesting) { + throw new IllegalStateException(boundary + " transaction opened inside another"); + } + boolean outer = active; + active = true; + try { + T result = action.get(); + committed.add(boundary); + return result; + } finally { + active = outer; + } + } +} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/api/error/FileserverErrorCode.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/api/error/FileserverErrorCode.java index 6b304bb2..2c0a9e4f 100644 --- a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/api/error/FileserverErrorCode.java +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/api/error/FileserverErrorCode.java @@ -42,6 +42,9 @@ public enum FileserverErrorCode implements ApiErrorCode { INVALID_PATH(422, Category.VALIDATION, false), PATH_OUTSIDE_NAMESPACE(422, Category.VALIDATION, false), TRANSFER_ADMISSION_REJECTED(429, Category.RATE_LIMIT, true), + // tus checksum extension status: one request's bytes did not match the checksum the client sent + // for them. The chunk is rolled back before its offset commits, so the upload stays resumable. + CHECKSUM_MISMATCH(460, Category.DATA_INTEGRITY, false), PARTIAL_WRITE(500, Category.TRANSIENT_DEPENDENCY, false), // Never retryable by definition: the operation may already have taken effect, and a blind retry // is what turns an ambiguous outcome into a duplicated one. diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/DefaultFinalizeUploadService.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/DefaultFinalizeUploadService.java index 502972af..505d4e37 100644 --- a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/DefaultFinalizeUploadService.java +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/DefaultFinalizeUploadService.java @@ -27,7 +27,7 @@ import dev.caskeleton.application.fileserver.cleanup.CleanupQueue; import dev.caskeleton.application.fileserver.cleanup.CleanupRequest; import dev.caskeleton.application.fileserver.cleanup.CleanupType; import dev.caskeleton.application.fileserver.recovery.RecoveryQueue; -import dev.caskeleton.application.transaction.PolicyTransactionPort; +import dev.caskeleton.application.transaction.TransactionPort; import java.time.Clock; import java.time.Instant; import java.util.Locale; @@ -53,7 +53,7 @@ public final class DefaultFinalizeUploadService implements FinalizeUploadService private final CleanupQueue cleanupQueue; private final RecoveryQueue recoveryQueue; private final PublishMode publishMode; - private final PolicyTransactionPort transactions; + private final TransactionPort transactions; private final Clock clock; public DefaultFinalizeUploadService( @@ -65,7 +65,7 @@ public final class DefaultFinalizeUploadService implements FinalizeUploadService CleanupQueue cleanupQueue, RecoveryQueue recoveryQueue, PublishMode publishMode, - PolicyTransactionPort transactions, + TransactionPort transactions, Clock clock) { this.metadataStore = metadataStore; this.sessionStore = sessionStore; @@ -318,9 +318,7 @@ public final class DefaultFinalizeUploadService implements FinalizeUploadService // The object is on the volume and the record does not say so — the definition of an ambiguous // completion. Enqueued in its own boundary, because the one that failed took nothing with it. try { - FileserverCompensationTransaction.run( - transactions, - "fileserver-ready-recovery-" + verifying.fileId().value(), + transactions.inNew( () -> recoveryQueue.enqueue(verifying.fileId(), "READY_COMMIT_UNCONFIRMED")); } catch (RuntimeException recoveryWriteFailure) { exception.addSuppressed(recoveryWriteFailure); diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/DefaultUploadApplicationService.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/DefaultUploadApplicationService.java index f5f94a71..c5fd19ec 100644 --- a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/DefaultUploadApplicationService.java +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/DefaultUploadApplicationService.java @@ -36,7 +36,7 @@ import dev.caskeleton.application.fileserver.observability.FileserverMetricsPort import dev.caskeleton.application.fileserver.observability.SizeBucket; import dev.caskeleton.application.fileserver.quota.TransferAdmissionController; import dev.caskeleton.application.fileserver.quota.TransferPermit; -import dev.caskeleton.application.transaction.PolicyTransactionPort; +import dev.caskeleton.application.transaction.TransactionPort; import java.nio.channels.ReadableByteChannel; import java.time.Clock; import java.time.Duration; @@ -72,7 +72,7 @@ public final class DefaultUploadApplicationService implements UploadApplicationS private final UploadIdentifierFactory identifierFactory; private final UploadPolicy uploadPolicy; private final FileserverMetricsPort metrics; - private final PolicyTransactionPort transactions; + private final TransactionPort transactions; private final Clock clock; public DefaultUploadApplicationService( @@ -88,7 +88,7 @@ public final class DefaultUploadApplicationService implements UploadApplicationS UploadIdentifierFactory identifierFactory, UploadPolicy uploadPolicy, FileserverMetricsPort metrics, - PolicyTransactionPort transactions, + TransactionPort transactions, Clock clock) { this.transactions = transactions; this.metadataStore = metadataStore; @@ -152,9 +152,7 @@ public final class DefaultUploadApplicationService implements UploadApplicationS // Staging sits outside the boundary above because it has to — it is a filesystem call — so // it is the one failure here that still compensates by hand instead of rolling back. try { - FileserverCompensationTransaction.run( - transactions, - "fileserver-upload-create-compensation-" + uploadId.value(), + transactions.inNew( () -> { failRecord(created.record(), "UPLOAD_CREATE_FAILED"); quotaService.release(created.reservation()); @@ -188,6 +186,7 @@ public final class DefaultUploadApplicationService implements UploadApplicationS long expectedOffset, ReadableByteChannel content, long contentLength, + Optional expectedChunkSha256, RequestContext context) { UploadSession session = requireActiveSession(uploadId); FileRecord record = requireRecord(session.fileId()); @@ -212,8 +211,11 @@ public final class DefaultUploadApplicationService implements UploadApplicationS requireOffsetsAgree(session, handle, expectedOffset); Instant startedAt = clock.instant(); + // The chunk checksum is checked by the store before it returns, so a mismatch never reaches + // the offset commit below. AppendResult appended = - storageGateway.append(handle, expectedOffset, content, contentLength, fence); + storageGateway.append( + handle, expectedOffset, content, contentLength, expectedChunkSha256, fence); UploadSession committed = leaseCoordinator.commitOffset( fence.current(), expectedOffset, appended.committedOffset()); diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/FileserverCompensationTransaction.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/FileserverCompensationTransaction.java deleted file mode 100644 index 2a31487f..00000000 --- a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/FileserverCompensationTransaction.java +++ /dev/null @@ -1,60 +0,0 @@ -package dev.caskeleton.application.fileserver.upload; - -import dev.caskeleton.application.outbound.CallBudget; -import dev.caskeleton.application.transaction.OperationId; -import dev.caskeleton.application.transaction.PolicyTransactionPort; -import dev.caskeleton.application.transaction.TransactionPolicyId; -import dev.caskeleton.application.transaction.TransactionRequest; -import dev.caskeleton.application.transaction.TransactionResult; -import java.time.Duration; -import java.util.Objects; -import java.util.Optional; - -/** Policy-based REQUIRES_NEW boundary for fileserver compensation/recovery writes. */ -final class FileserverCompensationTransaction { - - private static final Duration BUDGET = Duration.ofSeconds(30); - - private FileserverCompensationTransaction() {} - - static void run(PolicyTransactionPort transactions, String operationId, Runnable action) { - Objects.requireNonNull(transactions, "transactions"); - Objects.requireNonNull(operationId, "operationId"); - Objects.requireNonNull(action, "action"); - - TransactionRequest request = - new TransactionRequest( - TransactionPolicyId.MAINTENANCE_NEW, - CallBudget.fromNow(BUDGET), - Optional.empty(), - Optional.of(new OperationId(operationId))); - - TransactionResult result = - transactions.inTransaction( - request, - () -> { - action.run(); - return null; - }); - - if (result instanceof TransactionResult.Committed) { - return; - } - if (result - instanceof TransactionResult.CommittedWithPostCommitFailure committedWithFailure) { - throw committedWithFailure.operationalFailure(); - } - if (result instanceof TransactionResult.DeterminateRollback rollback) { - throw rollback.failure(); - } - if (result instanceof TransactionResult.Indeterminate indeterminate) { - throw new IllegalStateException( - "fileserver compensation transaction outcome is indeterminate at " - + indeterminate.lastObservedPhase() - + " for operationId=" - + operationId); - } - throw new IllegalStateException( - "MAINTENANCE_NEW compensation unexpectedly participated in an outer transaction"); - } -} diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/UploadApplicationService.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/UploadApplicationService.java index 19453fc0..d4cdf99a 100644 --- a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/UploadApplicationService.java +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/UploadApplicationService.java @@ -3,6 +3,7 @@ package dev.caskeleton.application.fileserver.upload; import dev.caskeleton.application.fileserver.api.UploadId; import dev.caskeleton.application.fileserver.api.security.RequestContext; import java.nio.channels.ReadableByteChannel; +import java.util.Optional; /** * The upload half of the public application surface. @@ -14,13 +15,31 @@ public interface UploadApplicationService { UploadSessionView create(CreateUploadRequest request, RequestContext context); + /** + * Appends one request's bytes. + * + * @param expectedChunkSha256 hex SHA-256 the client asserted for this request's bytes only, never + * the whole upload; a mismatch is rejected before the offset commits and leaves no bytes + * behind + */ AppendUploadResult append( UploadId uploadId, long expectedOffset, ReadableByteChannel content, long contentLength, + Optional expectedChunkSha256, RequestContext context); + /** Appends without a client checksum. */ + default AppendUploadResult append( + UploadId uploadId, + long expectedOffset, + ReadableByteChannel content, + long contentLength, + RequestContext context) { + return append(uploadId, expectedOffset, content, contentLength, Optional.empty(), context); + } + UploadSessionView status(UploadId uploadId, RequestContext context); void cancel(UploadId uploadId, RequestContext context); diff --git a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/UploadStorageGateway.java b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/UploadStorageGateway.java index 92da5dd9..215efa14 100644 --- a/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/UploadStorageGateway.java +++ b/src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/upload/UploadStorageGateway.java @@ -6,6 +6,7 @@ import dev.caskeleton.application.fileserver.api.content.AppendResult; import dev.caskeleton.application.fileserver.api.content.UploadHandle; import dev.caskeleton.application.fileserver.api.content.WriteFence; import java.nio.channels.ReadableByteChannel; +import java.util.Optional; /** * Narrow view of the content store used while an upload is in progress. @@ -26,11 +27,27 @@ public interface UploadStorageGateway { * visible mid-transfer: the storage layer stops on the next buffer instead of at the end of a * transfer whose bytes are already on the volume. */ + default AppendResult append( + UploadHandle handle, + long expectedOffset, + ReadableByteChannel source, + long contentLength, + WriteFence fence) { + return append(handle, expectedOffset, source, contentLength, Optional.empty(), fence); + } + + /** + * Appends and, when {@code expectedChunkSha256} is present, compares it with the digest of this + * call's bytes only. A mismatch is rolled back to {@code expectedOffset} and reported as {@link + * dev.caskeleton.application.fileserver.api.error.FileserverErrorCode#CHECKSUM_MISMATCH}, so the + * caller never commits an offset for bytes the client disowned. + */ AppendResult append( UploadHandle handle, long expectedOffset, ReadableByteChannel source, long contentLength, + Optional expectedChunkSha256, WriteFence fence); /** Appends with no ownership to lose; see {@link WriteFence#unfenced()}. */ diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/api/error/FileserverExceptionTest.java b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/api/error/FileserverExceptionTest.java index e05da46d..cb46d27d 100644 --- a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/api/error/FileserverExceptionTest.java +++ b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/api/error/FileserverExceptionTest.java @@ -15,7 +15,8 @@ import org.junit.jupiter.params.provider.EnumSource; class FileserverExceptionTest { private static final Set DESIGN_STATUSES = - Set.of(400, 401, 403, 404, 409, 410, 411, 412, 413, 415, 416, 422, 429, 500, 503, 504, 507); + Set.of( + 400, 401, 403, 404, 409, 410, 411, 412, 413, 415, 416, 422, 429, 460, 500, 503, 504, 507); @Test void ambiguousCompletionCarriesReconciliationFlag() { diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/DirectTransactions.java b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/DirectTransactions.java index fb16782f..7e33d98d 100644 --- a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/DirectTransactions.java +++ b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/DirectTransactions.java @@ -1,8 +1,6 @@ package dev.caskeleton.application.fileserver.testkit; -import dev.caskeleton.application.transaction.PolicyTransactionPort; -import dev.caskeleton.application.transaction.TransactionRequest; -import dev.caskeleton.application.transaction.TransactionResult; +import dev.caskeleton.application.transaction.TransactionPort; import java.util.ArrayList; import java.util.List; import java.util.function.Supplier; @@ -14,11 +12,18 @@ import java.util.function.Supplier; * a failed unit undoes its writes — that is what the real-PostgreSQL readiness suite is for. What * it does prove is the part unit tests can: that a service opens a boundary at all, and how many. * {@link #openedWrites()} lets a test assert that two writes which must commit together were asked - * for inside one boundary rather than two. + * for inside one boundary rather than two. {@link #failNextNew(RuntimeException)} makes the next + * independent boundary fail, which is how a test reaches a compensation that could not be written. */ -public final class DirectTransactions implements PolicyTransactionPort { +public final class DirectTransactions implements TransactionPort { private final List opened = new ArrayList<>(); + private RuntimeException nextNewFailure; + + /** Makes the next {@link #inNew(Supplier)} fail with {@code failure} instead of running. */ + public void failNextNew(RuntimeException failure) { + this.nextNewFailure = failure; + } /** The boundary kinds opened so far, in order. */ public List openedWrites() { @@ -50,12 +55,11 @@ public final class DirectTransactions implements PolicyTransactionPort { @Override public T inNew(Supplier action) { opened.add("new"); + RuntimeException failure = nextNewFailure; + if (failure != null) { + nextNewFailure = null; + throw failure; + } return action.get(); } - - @Override - public TransactionResult inTransaction(TransactionRequest request, Supplier action) { - opened.add("policy:" + request.policyId().name()); - return new TransactionResult.Committed<>(action.get(), request.operationId()); - } } diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/FakeUploadStorageGateway.java b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/FakeUploadStorageGateway.java index ea499638..d7156c21 100644 --- a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/FakeUploadStorageGateway.java +++ b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/testkit/FakeUploadStorageGateway.java @@ -7,6 +7,7 @@ import dev.caskeleton.application.fileserver.api.content.UploadHandle; import dev.caskeleton.application.fileserver.api.content.WriteFence; import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode; import dev.caskeleton.application.fileserver.api.error.FileserverFailureContext; +import dev.caskeleton.application.fileserver.api.error.IntegrityMismatchException; import dev.caskeleton.application.fileserver.api.error.StorageUnavailableException; import dev.caskeleton.application.fileserver.upload.UploadStorageGateway; import java.io.ByteArrayOutputStream; @@ -19,6 +20,7 @@ import java.security.NoSuchAlgorithmException; import java.util.HexFormat; import java.util.LinkedHashMap; import java.util.Map; +import java.util.Optional; /** Hand-rolled staging store that keeps upload bytes in memory. */ public final class FakeUploadStorageGateway implements UploadStorageGateway { @@ -66,10 +68,11 @@ public final class FakeUploadStorageGateway implements UploadStorageGateway { long expectedOffset, ReadableByteChannel source, long contentLength, + Optional expectedChunkSha256, WriteFence fence) { ByteArrayOutputStream sink = staging.get(handle.uploadId()); + ByteArrayOutputStream chunk = new ByteArrayOutputStream(); ByteBuffer buffer = ByteBuffer.allocate(8192); - long appended = 0; try { while (true) { fence.requireStillOwned(); @@ -79,15 +82,25 @@ public final class FakeUploadStorageGateway implements UploadStorageGateway { break; } buffer.flip(); - byte[] chunk = new byte[buffer.remaining()]; - buffer.get(chunk); - sink.write(chunk); - appended += chunk.length; + byte[] bytes = new byte[buffer.remaining()]; + buffer.get(bytes); + chunk.write(bytes); } } catch (IOException exception) { throw new UncheckedIOException(exception); } - return new AppendResult(expectedOffset + appended, appended, sha256Hex(sink.toByteArray())); + byte[] received = chunk.toByteArray(); + // Same rule as the real store: checked against this call's bytes, before anything is kept. + if (expectedChunkSha256.isPresent() + && !sha256Hex(received).equalsIgnoreCase(expectedChunkSha256.get())) { + throw new IntegrityMismatchException( + "chunk checksum mismatch", + FileserverFailureContext.forUpload( + FileserverErrorCode.CHECKSUM_MISMATCH, handle.uploadId(), false, false, false)); + } + sink.writeBytes(received); + return new AppendResult( + expectedOffset + received.length, received.length, sha256Hex(sink.toByteArray())); } @Override diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/DefaultSingleShotUploadServiceTest.java b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/DefaultSingleShotUploadServiceTest.java index b0f7691b..56a85dc1 100644 --- a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/DefaultSingleShotUploadServiceTest.java +++ b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/DefaultSingleShotUploadServiceTest.java @@ -89,6 +89,7 @@ class DefaultSingleShotUploadServiceTest { long expectedOffset, ReadableByteChannel content, long contentLength, + Optional expectedChunkSha256, RequestContext context) { if (appendFailure != null) { throw appendFailure; diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/FileserverCompensationTransactionTest.java b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/FileserverCompensationTransactionTest.java deleted file mode 100644 index 609c460a..00000000 --- a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/FileserverCompensationTransactionTest.java +++ /dev/null @@ -1,122 +0,0 @@ -package dev.caskeleton.application.fileserver.upload; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.application.transaction.PolicyTransactionPort; -import dev.caskeleton.application.transaction.TransactionPhase; -import dev.caskeleton.application.transaction.TransactionRequest; -import dev.caskeleton.application.transaction.TransactionResult; -import java.util.Optional; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.function.Supplier; -import org.junit.jupiter.api.Test; - -class FileserverCompensationTransactionTest { - - @Test - void committedCompensationReturnsNormally() { - AtomicBoolean invoked = new AtomicBoolean(); - - FileserverCompensationTransaction.run( - new StubTransactions(ResultMode.COMMITTED), - "fileserver-compensation-1", - () -> invoked.set(true)); - - assertThat(invoked).isTrue(); - } - - @Test - void determinateRollbackPropagatesTheRollbackFailure() { - IllegalStateException failure = new IllegalStateException("rolled back"); - - assertThatThrownBy( - () -> - FileserverCompensationTransaction.run( - new StubTransactions(ResultMode.ROLLBACK, failure), - "fileserver-compensation-2", - () -> {})) - .isSameAs(failure); - } - - @Test - void indeterminateOutcomeIsNeverReportedAsSuccessfulCompensation() { - assertThatThrownBy( - () -> - FileserverCompensationTransaction.run( - new StubTransactions(ResultMode.INDETERMINATE), - "fileserver-compensation-3", - () -> {})) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("indeterminate") - .hasMessageContaining("fileserver-compensation-3"); - } - - @Test - void postCommitOperationalFailureIsSurfacedWithoutTreatingTheCommitAsRollback() { - IllegalStateException failure = new IllegalStateException("post-commit callback failed"); - - assertThatThrownBy( - () -> - FileserverCompensationTransaction.run( - new StubTransactions(ResultMode.POST_COMMIT_FAILURE, failure), - "fileserver-compensation-4", - () -> {})) - .isSameAs(failure); - } - - private enum ResultMode { - COMMITTED, - POST_COMMIT_FAILURE, - ROLLBACK, - INDETERMINATE - } - - private static final class StubTransactions implements PolicyTransactionPort { - private final ResultMode mode; - private final RuntimeException rollbackFailure; - - private StubTransactions(ResultMode mode) { - this(mode, new IllegalStateException("rollback")); - } - - private StubTransactions(ResultMode mode, RuntimeException rollbackFailure) { - this.mode = mode; - this.rollbackFailure = rollbackFailure; - } - - @Override - public TransactionResult inTransaction(TransactionRequest request, Supplier action) { - return switch (mode) { - case COMMITTED -> new TransactionResult.Committed<>(action.get(), request.operationId()); - case POST_COMMIT_FAILURE -> - new TransactionResult.CommittedWithPostCommitFailure<>( - action.get(), request.operationId(), rollbackFailure); - case ROLLBACK -> new TransactionResult.DeterminateRollback<>(rollbackFailure); - case INDETERMINATE -> - new TransactionResult.Indeterminate<>( - request.operationId(), TransactionPhase.COMMIT_REQUESTED, Optional.empty()); - }; - } - - @Override - public T inWrite(Supplier action) { - return action.get(); - } - - @Override - public T inRootWrite(Supplier action) { - return action.get(); - } - - @Override - public T inRead(Supplier action) { - return action.get(); - } - - @Override - public T inNew(Supplier action) { - return action.get(); - } - } -} diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/FinalizeUploadServiceTest.java b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/FinalizeUploadServiceTest.java index 87e559df..7197405f 100644 --- a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/FinalizeUploadServiceTest.java +++ b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/FinalizeUploadServiceTest.java @@ -211,7 +211,7 @@ class FinalizeUploadServiceTest { assertThat(recovery.reasons()).containsValue("READY_COMMIT_UNCONFIRMED"); assertThat(transactions.openedWrites()) .as("recovery must survive the failed ambient READY transaction") - .endsWith("policy:MAINTENANCE_NEW"); + .endsWith("new"); assertThat(metadata.find(verifyingRecord.fileId()).orElseThrow().state()) .isNotEqualTo(FileState.READY); assertThat(quota.anyCommitted()).isFalse(); diff --git a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/UploadApplicationServiceTest.java b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/UploadApplicationServiceTest.java index ea2e290a..1b07ed96 100644 --- a/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/UploadApplicationServiceTest.java +++ b/src/application-fileserver/src/test/java/dev/caskeleton/application/fileserver/upload/UploadApplicationServiceTest.java @@ -2,12 +2,15 @@ package dev.caskeleton.application.fileserver.upload; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; import dev.caskeleton.application.fileserver.api.FileState; import dev.caskeleton.application.fileserver.api.UploadId; import dev.caskeleton.application.fileserver.api.error.ConcurrentFileModificationException; import dev.caskeleton.application.fileserver.api.error.FileAccessDeniedException; import dev.caskeleton.application.fileserver.api.error.FileTooLargeException; +import dev.caskeleton.application.fileserver.api.error.FileserverErrorCode; +import dev.caskeleton.application.fileserver.api.error.IntegrityMismatchException; import dev.caskeleton.application.fileserver.api.error.StorageUnavailableException; import dev.caskeleton.application.fileserver.api.error.UploadExpiredException; import dev.caskeleton.application.fileserver.api.error.UploadOffsetMismatchException; @@ -32,8 +35,11 @@ import java.io.ByteArrayInputStream; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; import java.time.Clock; import java.time.ZoneOffset; +import java.util.HexFormat; import java.util.Optional; import java.util.OptionalLong; import org.junit.jupiter.api.Test; @@ -145,11 +151,29 @@ class UploadApplicationServiceTest { assertThat(quota.anyReleased()).isTrue(); assertThat(transactions.openedWrites()) .as("filesystem-create compensation must commit independently of an ambient transaction") - .endsWith("policy:MAINTENANCE_NEW"); + .endsWith("new"); assertThat(metadata.findRecoverable(recoveryQuery()).stream().map(record -> record.state())) .containsOnly(FileState.FAILED); } + @Test + void aCompensationThatCannotCommitIsAttachedToTheStagingFailure() { + // given + storage.failNextCreate(); + IllegalStateException compensationFailure = new IllegalStateException("compensation lost"); + transactions.failNextNew(compensationFailure); + + // when + Throwable thrown = + catchThrowable(() -> service.create(createRequest(), FileserverFixtures.context())); + + // then + assertThat(thrown) + .isInstanceOf(StorageUnavailableException.class) + .satisfies( + failure -> assertThat(failure.getSuppressed()).containsExactly(compensationFailure)); + } + @Test void appendsAccumulateMonotonically() { UploadSessionView created = service.create(createRequest(6), FileserverFixtures.context()); @@ -180,6 +204,33 @@ class UploadApplicationServiceTest { .isEqualTo(3); } + @Test + void aChunkWhoseChecksumDoesNotMatchIsRejectedWithoutAdvancingTheOffset() { + // given + UploadSessionView created = service.create(createRequest(6), FileserverFixtures.context()); + service.append(created.uploadId(), 0, channel("abc"), 3, FileserverFixtures.context()); + + // when + Throwable failure = + catchThrowable( + () -> + service.append( + created.uploadId(), + 3, + channel("def"), + 3, + Optional.of(sha256Hex("xyz")), + FileserverFixtures.context())); + + // then + assertThat(failure) + .isInstanceOfSatisfying( + IntegrityMismatchException.class, + mismatch -> + assertThat(mismatch.code()).isEqualTo(FileserverErrorCode.CHECKSUM_MISMATCH)); + assertThat(sessions.find(created.uploadId()).orElseThrow().committedOffset()).isEqualTo(3); + } + @Test void aMetadataOffsetThatDisagreesWithStorageIsNeverSilentlyRepaired() { UploadSessionView created = service.create(createRequest(), FileserverFixtures.context()); @@ -313,4 +364,15 @@ class UploadApplicationServiceTest { private static ReadableByteChannel channel(String payload) { return Channels.newChannel(new ByteArrayInputStream(payload.getBytes(StandardCharsets.UTF_8))); } + + private static String sha256Hex(String payload) { + try { + return HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(payload.getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is required by the platform", impossible); + } + } } diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/ApplyNotificationReceiptCommand.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/ApplyNotificationReceiptCommand.java deleted file mode 100644 index 5b5e21ba..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/ApplyNotificationReceiptCommand.java +++ /dev/null @@ -1,13 +0,0 @@ -package dev.caskeleton.application.notification; - -import dev.caskeleton.application.command.Command; -import java.util.Objects; - -/** Applies one already authenticated and normalized receipt. */ -public record ApplyNotificationReceiptCommand(NormalizedNotificationReceiptCommand receipt) - implements Command { - - public ApplyNotificationReceiptCommand { - Objects.requireNonNull(receipt, "normalized notification receipt must be non-null"); - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/ApplyNotificationReceiptResult.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/ApplyNotificationReceiptResult.java deleted file mode 100644 index 2dc4c007..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/ApplyNotificationReceiptResult.java +++ /dev/null @@ -1,21 +0,0 @@ -package dev.caskeleton.application.notification; - -import java.util.Objects; - -/** Non-sensitive result of reducing one receipt event. */ -public record ApplyNotificationReceiptResult( - Status status, NotificationReceiptProjection projection, boolean suppressionApplied) { - - public ApplyNotificationReceiptResult { - Objects.requireNonNull(status, "notification receipt apply status must be non-null"); - Objects.requireNonNull(projection, "notification receipt projection must be non-null"); - if (status == Status.DUPLICATE && suppressionApplied) { - throw new IllegalArgumentException("duplicate receipt cannot repeat technical suppression"); - } - } - - public enum Status { - APPLIED, - DUPLICATE - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/ApplyNotificationReceiptUseCase.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/ApplyNotificationReceiptUseCase.java deleted file mode 100644 index dd57cde4..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/ApplyNotificationReceiptUseCase.java +++ /dev/null @@ -1,80 +0,0 @@ -package dev.caskeleton.application.notification; - -import dev.caskeleton.application.capability.Idempotency; -import dev.caskeleton.application.capability.RepositoryAccess; -import dev.caskeleton.application.capability.UseCaseCapability; -import dev.caskeleton.application.security.RequiresPermission; -import dev.caskeleton.application.transaction.TransactionMode; -import dev.caskeleton.application.transaction.TransactionPort; -import dev.caskeleton.application.usecase.CommandUseCase; -import java.time.Clock; -import java.util.Objects; - -/** - * Appends one receipt fact and reduces its delivery projection in one physical root transaction. - */ -@RequiresPermission("notification:receipt") -@UseCaseCapability( - transactionMode = TransactionMode.WRITE, - idempotency = Idempotency.IDEMPOTENT, - repositoryAccess = RepositoryAccess.WRITE_REPOSITORY) -public class ApplyNotificationReceiptUseCase - implements CommandUseCase { - - private final NotificationReceiptStorePort store; - private final NotificationTechnicalSuppressionPort suppression; - private final TransactionPort transactions; - private final Clock clock; - - public ApplyNotificationReceiptUseCase( - NotificationReceiptStorePort store, - NotificationTechnicalSuppressionPort suppression, - TransactionPort transactions, - Clock clock) { - this.store = Objects.requireNonNull(store, "notification receipt store must be non-null"); - this.suppression = - Objects.requireNonNull(suppression, "notification suppression port must be non-null"); - this.transactions = Objects.requireNonNull(transactions, "transaction port must be non-null"); - this.clock = Objects.requireNonNull(clock, "clock must be non-null"); - } - - @Override - public ApplyNotificationReceiptResult handle(ApplyNotificationReceiptCommand command) { - Objects.requireNonNull(command, "apply notification receipt command must be non-null"); - return transactions.inRootWrite(() -> applyInsideRoot(command.receipt())); - } - - private ApplyNotificationReceiptResult applyInsideRoot( - NormalizedNotificationReceiptCommand command) { - NotificationReceiptStorePort.AppendResult appendResult = store.appendIfAbsent(command); - if (appendResult instanceof NotificationReceiptStorePort.Duplicate duplicate) { - return new ApplyNotificationReceiptResult( - ApplyNotificationReceiptResult.Status.DUPLICATE, duplicate.projection(), false); - } - - NotificationReceiptStorePort.ReceiptAggregate aggregate = - ((NotificationReceiptStorePort.Appended) appendResult).aggregate(); - if (!aggregate.deliveryId().equals(command.deliveryId())) { - throw new IllegalStateException( - "receipt aggregate delivery does not match normalized command"); - } - NotificationReceiptProjection projection = - NotificationReceiptProjection.reduce(aggregate.facts()); - store.saveProjection(aggregate.deliveryId(), projection); - - boolean suppressionApplied = shouldSuppress(command.fact()); - if (suppressionApplied) { - suppression.suppress( - new NotificationTechnicalSuppressionPort.SuppressionMutation( - aggregate.recipient(), command.fact().reasonCode(), clock.instant())); - } - return new ApplyNotificationReceiptResult( - ApplyNotificationReceiptResult.Status.APPLIED, projection, suppressionApplied); - } - - private static boolean shouldSuppress(NotificationReceiptFact fact) { - return fact.type() == NotificationReceiptFact.Type.COMPLAINT - || (fact.type() == NotificationReceiptFact.Type.BOUNCE - && fact.bounceClass() == NotificationReceiptFact.BounceClass.HARD); - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/ConsentCheckMode.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/ConsentCheckMode.java deleted file mode 100644 index f24e7fc6..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/ConsentCheckMode.java +++ /dev/null @@ -1,7 +0,0 @@ -package dev.caskeleton.application.notification; - -/** Point at which recipient consent or preference must be established. */ -public enum ConsentCheckMode { - SNAPSHOT_AT_APPEND, - RECHECK_BEFORE_EACH_DELIVERY -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/EmailRecipientReference.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/EmailRecipientReference.java deleted file mode 100644 index 2db363f0..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/EmailRecipientReference.java +++ /dev/null @@ -1,19 +0,0 @@ -package dev.caskeleton.application.notification; - -/** Opaque reference resolved to an email recipient only inside a qualified adapter. */ -public record EmailRecipientReference(String reference) implements NotificationRecipientReference { - - public EmailRecipientReference { - reference = NotificationIntentId.requireOpaque("email recipient reference", reference); - } - - @Override - public NotificationChannel channel() { - return NotificationChannel.EMAIL; - } - - @Override - public String toString() { - return "EmailRecipientReference[reference=]"; - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/InitializeNotificationWriterFencesCommand.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/InitializeNotificationWriterFencesCommand.java deleted file mode 100644 index 34e689fb..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/InitializeNotificationWriterFencesCommand.java +++ /dev/null @@ -1,32 +0,0 @@ -package dev.caskeleton.application.notification; - -import dev.caskeleton.application.command.Command; -import java.util.Objects; - -/** Reviewed all-route initialization request; partial route sets are rejected by the use case. */ -public record InitializeNotificationWriterFencesCommand( - String operationToken, - NotificationCanonicalWriterRouteSet reviewedRoutes, - String reviewedRouteSetDigest, - String actorReference, - NotificationReasonCode reasonCode) - implements Command { - - public InitializeNotificationWriterFencesCommand { - operationToken = - NotificationIntentId.requireOpaque("writer initialization operation token", operationToken); - Objects.requireNonNull(reviewedRoutes, "reviewed writer routes must be non-null"); - reviewedRouteSetDigest = requireDigest(reviewedRouteSetDigest); - actorReference = - NotificationIntentId.requireOpaque("writer initialization actor", actorReference); - Objects.requireNonNull(reasonCode, "notification reason code must be non-null"); - } - - static String requireDigest(String digest) { - if (digest == null || !digest.matches("[0-9a-f]{64}")) { - throw new IllegalArgumentException( - "writer evidence digest must be 64 lowercase hex characters"); - } - return digest; - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/InitializeNotificationWriterFencesOperation.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/InitializeNotificationWriterFencesOperation.java deleted file mode 100644 index 809f55b5..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/InitializeNotificationWriterFencesOperation.java +++ /dev/null @@ -1,13 +0,0 @@ -package dev.caskeleton.application.notification; - -import java.time.Instant; - -/** Atomic persistence operation for absent-fence and empty-journal initialization. */ -@FunctionalInterface -public interface InitializeNotificationWriterFencesOperation { - - InitializeNotificationWriterFencesResult initialize( - InitializeNotificationWriterFencesCommand command, - NotificationWriterRouteSet trustedRoutes, - Instant requestedAt); -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/InitializeNotificationWriterFencesResult.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/InitializeNotificationWriterFencesResult.java deleted file mode 100644 index 850b3fe0..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/InitializeNotificationWriterFencesResult.java +++ /dev/null @@ -1,21 +0,0 @@ -package dev.caskeleton.application.notification; - -import java.util.Objects; - -/** Committed all-route fence initialization result. */ -public record InitializeNotificationWriterFencesResult( - Status status, int initializedRouteCount, String routeSetDigest) { - - public InitializeNotificationWriterFencesResult { - Objects.requireNonNull(status, "writer initialization status must be non-null"); - if (initializedRouteCount < 1 || initializedRouteCount > 100) { - throw new IllegalArgumentException("initialized writer route count must be in 1..100"); - } - routeSetDigest = InitializeNotificationWriterFencesCommand.requireDigest(routeSetDigest); - } - - public enum Status { - INITIALIZED, - REPLAYED - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/InitializeNotificationWriterFencesUseCase.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/InitializeNotificationWriterFencesUseCase.java deleted file mode 100644 index fecb18c9..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/InitializeNotificationWriterFencesUseCase.java +++ /dev/null @@ -1,55 +0,0 @@ -package dev.caskeleton.application.notification; - -import dev.caskeleton.application.capability.Idempotency; -import dev.caskeleton.application.capability.RepositoryAccess; -import dev.caskeleton.application.capability.UseCaseCapability; -import dev.caskeleton.application.security.RequiresPermission; -import dev.caskeleton.application.transaction.TransactionMode; -import dev.caskeleton.application.transaction.TransactionPort; -import dev.caskeleton.application.usecase.CommandUseCase; -import java.time.Clock; -import java.util.Objects; - -/** Root-commits the complete trusted writer fence and proof registry initialization batch. */ -@RequiresPermission("notification:cutover") -@UseCaseCapability( - transactionMode = TransactionMode.WRITE, - idempotency = Idempotency.IDEMPOTENT, - repositoryAccess = RepositoryAccess.WRITE_REPOSITORY, - crossTenantAdmin = true) -public class InitializeNotificationWriterFencesUseCase - implements CommandUseCase< - InitializeNotificationWriterFencesCommand, InitializeNotificationWriterFencesResult> { - - private final NotificationWriterRouteSet routes; - private final InitializeNotificationWriterFencesOperation operation; - private final TransactionPort transactions; - private final Clock clock; - - public InitializeNotificationWriterFencesUseCase( - NotificationWriterRouteSet routes, - InitializeNotificationWriterFencesOperation operation, - TransactionPort transactions, - Clock clock) { - this.routes = Objects.requireNonNull(routes, "notification writer route set must be non-null"); - this.operation = - Objects.requireNonNull(operation, "writer initialization operation must be non-null"); - this.transactions = Objects.requireNonNull(transactions, "transaction port must be non-null"); - this.clock = Objects.requireNonNull(clock, "clock must be non-null"); - } - - @Override - public InitializeNotificationWriterFencesResult handle( - InitializeNotificationWriterFencesCommand command) { - Objects.requireNonNull(command, "writer initialization command must be non-null"); - if (!command.reviewedRoutes().equals(routes.canonicalRoutes())) { - throw new IllegalArgumentException( - "reviewed writer routes must exactly equal the trusted all-route set"); - } - if (!command.reviewedRouteSetDigest().equals(routes.digest())) { - throw new IllegalArgumentException( - "reviewed writer route-set digest does not match trusted registry digest"); - } - return transactions.inRootWrite(() -> operation.initialize(command, routes, clock.instant())); - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/InlineNotificationAttemptPort.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/InlineNotificationAttemptPort.java deleted file mode 100644 index 021d0ef3..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/InlineNotificationAttemptPort.java +++ /dev/null @@ -1,11 +0,0 @@ -package dev.caskeleton.application.notification; - -/** - * Executes one bounded, non-durable inline attempt over a frozen application plan. The caller must - * establish the physical root-write sequencing contract before invoking this port. - */ -@FunctionalInterface -public interface InlineNotificationAttemptPort { - - NotificationRequestResult.InlineCompleted attempt(NotificationFrozenPlan plan); -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NormalizedNotificationReceiptCommand.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NormalizedNotificationReceiptCommand.java deleted file mode 100644 index cb7b7169..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NormalizedNotificationReceiptCommand.java +++ /dev/null @@ -1,16 +0,0 @@ -package dev.caskeleton.application.notification; - -import java.util.Objects; - -/** Framework-free receipt normalized by an authenticated inbound adapter. */ -public record NormalizedNotificationReceiptCommand( - NotificationReceiptEventId receiptEventId, - NotificationDeliveryId deliveryId, - NotificationReceiptFact fact) { - - public NormalizedNotificationReceiptCommand { - Objects.requireNonNull(receiptEventId, "notification receipt event ID must be non-null"); - Objects.requireNonNull(deliveryId, "notification delivery ID must be non-null"); - Objects.requireNonNull(fact, "notification receipt fact must be non-null"); - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationAdmissionClass.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationAdmissionClass.java deleted file mode 100644 index d80a25c9..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationAdmissionClass.java +++ /dev/null @@ -1,8 +0,0 @@ -package dev.caskeleton.application.notification; - -/** Code-owned dispatch admission and fairness class. */ -public enum NotificationAdmissionClass { - SECURITY_CRITICAL, - TRANSACTIONAL, - BULK_LOW_VALUE -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationAdmissionGateCommand.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationAdmissionGateCommand.java deleted file mode 100644 index 70072b21..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationAdmissionGateCommand.java +++ /dev/null @@ -1,53 +0,0 @@ -package dev.caskeleton.application.notification; - -import dev.caskeleton.application.command.Command; -import java.util.Objects; - -/** Audited operator request to re-probe and resume one shared notification admission gate. */ -public record NotificationAdmissionGateCommand( - String operationToken, - NotificationRouteId routeId, - int policyRevision, - NotificationFaultScope faultScope, - String scopeReference, - long expectedGeneration, - int maximumParkedLegs, - String actorReference, - NotificationReasonCode reasonCode) - implements Command { - - public NotificationAdmissionGateCommand { - operationToken = - NotificationIntentId.requireOpaque("admission resume operation token", operationToken); - Objects.requireNonNull(routeId, "notification route ID must be non-null"); - if (policyRevision < 1 || expectedGeneration < 0) { - throw new IllegalArgumentException( - "policy revision must be positive and expected generation non-negative"); - } - if (maximumParkedLegs < 1 || maximumParkedLegs > 100) { - throw new IllegalArgumentException("maximum parked legs must be in 1..100"); - } - Objects.requireNonNull(faultScope, "notification fault scope must be non-null"); - if (faultScope == NotificationFaultScope.DELIVERY) { - throw new IllegalArgumentException("operator admission command cannot target DELIVERY scope"); - } - scopeReference = - NotificationIntentId.requireOpaque("admission scope reference", scopeReference); - actorReference = - NotificationIntentId.requireOpaque("admission resume actor reference", actorReference); - Objects.requireNonNull(reasonCode, "notification reason code must be non-null"); - } - - NotificationAdmissionReadinessPort.ResumeRequest toResumeRequest() { - return new NotificationAdmissionReadinessPort.ResumeRequest( - operationToken, - routeId, - policyRevision, - faultScope, - scopeReference, - expectedGeneration, - maximumParkedLegs, - actorReference, - reasonCode); - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationAdmissionGateUseCase.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationAdmissionGateUseCase.java deleted file mode 100644 index 4cd038c2..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationAdmissionGateUseCase.java +++ /dev/null @@ -1,89 +0,0 @@ -package dev.caskeleton.application.notification; - -import dev.caskeleton.application.capability.Idempotency; -import dev.caskeleton.application.capability.RepositoryAccess; -import dev.caskeleton.application.capability.UseCaseCapability; -import dev.caskeleton.application.security.RequiresPermission; -import dev.caskeleton.application.transaction.TransactionMode; -import dev.caskeleton.application.transaction.TransactionPort; -import dev.caskeleton.application.usecase.CommandUseCase; -import java.time.Clock; -import java.util.Objects; - -/** Probes readiness outside a transaction and generation-CAS resumes inside one short write. */ -@RequiresPermission("notification:operate") -@UseCaseCapability( - transactionMode = TransactionMode.WRITE, - idempotency = Idempotency.IDEMPOTENT, - repositoryAccess = RepositoryAccess.WRITE_REPOSITORY, - externalOutboundAllowed = true, - crossTenantAdmin = true) -public class NotificationAdmissionGateUseCase - implements CommandUseCase< - NotificationAdmissionGateCommand, NotificationAdmissionGateUseCase.Result> { - - private final NotificationAdmissionReadinessPort admission; - private final TransactionPort transactions; - private final Clock clock; - - public NotificationAdmissionGateUseCase( - NotificationAdmissionReadinessPort admission, TransactionPort transactions, Clock clock) { - this.admission = - Objects.requireNonNull(admission, "notification admission port must be non-null"); - this.transactions = Objects.requireNonNull(transactions, "transaction port must be non-null"); - this.clock = Objects.requireNonNull(clock, "clock must be non-null"); - } - - @Override - public Result handle(NotificationAdmissionGateCommand command) { - Objects.requireNonNull(command, "notification admission command must be non-null"); - NotificationAdmissionReadinessPort.ResumeRequest request = command.toResumeRequest(); - NotificationAdmissionReadinessPort.ReadinessProbe probe = - Objects.requireNonNull(admission.probe(request), "readiness probe must be non-null"); - if (!probe.ready()) { - return new Result(Result.Status.NOT_READY, probe.reasonCode()); - } - NotificationAdmissionReadinessPort.ResumeResult resumeResult = - Objects.requireNonNull( - transactions.inWrite(() -> admission.resume(request, probe, clock.instant())), - "notification admission resume result must be non-null"); - validateResumeResult(request, resumeResult); - return switch (resumeResult.status()) { - case RESUMED -> new Result(Result.Status.RESUMED, probe.reasonCode()); - case ALREADY_ACTIVE -> new Result(Result.Status.ALREADY_ACTIVE, probe.reasonCode()); - case STALE_GENERATION -> - new Result( - Result.Status.STALE_GENERATION, - new NotificationReasonCode("STALE_ADMISSION_GENERATION")); - }; - } - - private static void validateResumeResult( - NotificationAdmissionReadinessPort.ResumeRequest request, - NotificationAdmissionReadinessPort.ResumeResult result) { - if (result.processedLegCount() > request.maximumParkedLegs()) { - throw new IllegalArgumentException( - "admission resume processed more parked legs than the requested bound"); - } - if (result.status() == NotificationAdmissionReadinessPort.ResumeStatus.RESUMED - && result.resultingGeneration() != request.expectedGeneration() + 1) { - throw new IllegalArgumentException( - "resumed admission gate must advance the exact expected generation"); - } - } - - public record Result(Status status, NotificationReasonCode reasonCode) { - - public Result { - Objects.requireNonNull(status, "notification admission result status must be non-null"); - Objects.requireNonNull(reasonCode, "notification reason code must be non-null"); - } - - public enum Status { - RESUMED, - ALREADY_ACTIVE, - NOT_READY, - STALE_GENERATION - } - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationAdmissionReadinessPort.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationAdmissionReadinessPort.java deleted file mode 100644 index 5e490d5d..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationAdmissionReadinessPort.java +++ /dev/null @@ -1,154 +0,0 @@ -package dev.caskeleton.application.notification; - -import java.time.Instant; -import java.util.Objects; - -/** Persists shared route/provider/account admission readiness with generation-guarded CAS. */ -@FunctionalInterface -public interface NotificationAdmissionReadinessPort { - - ParkResult park(ParkRequest request); - - default ReadinessProbe probe(ResumeRequest request) { - throw new UnsupportedOperationException("notification readiness probe is not implemented"); - } - - default ResumeResult resume(ResumeRequest request, ReadinessProbe probe, Instant resumedAt) { - throw new UnsupportedOperationException("notification admission resume is not implemented"); - } - - record ParkRequest( - NotificationRouteId routeId, - int policyRevision, - NotificationFaultScope faultScope, - String scopeReference, - long expectedGeneration, - NotificationReasonCode reasonCode, - Instant parkedAt) { - - public ParkRequest { - Objects.requireNonNull(routeId, "notification route ID must be non-null"); - if (policyRevision < 1 || expectedGeneration < 0) { - throw new IllegalArgumentException( - "policy revision must be positive and expected generation non-negative"); - } - Objects.requireNonNull(faultScope, "notification fault scope must be non-null"); - if (faultScope == NotificationFaultScope.DELIVERY) { - throw new IllegalArgumentException("shared admission gate cannot use DELIVERY fault scope"); - } - scopeReference = - NotificationIntentId.requireOpaque("admission scope reference", scopeReference); - Objects.requireNonNull(reasonCode, "notification reason code must be non-null"); - Objects.requireNonNull(parkedAt, "admission parked time must be non-null"); - } - } - - enum ParkResult { - NOT_REQUESTED, - PARKED, - ALREADY_PARKED, - STALE_GENERATION - } - - record ResumeRequest( - String operationToken, - NotificationRouteId routeId, - int policyRevision, - NotificationFaultScope faultScope, - String scopeReference, - long expectedGeneration, - int maximumParkedLegs, - String actorReference, - NotificationReasonCode reasonCode) { - - public ResumeRequest { - operationToken = - NotificationIntentId.requireOpaque("admission resume operation token", operationToken); - Objects.requireNonNull(routeId, "notification route ID must be non-null"); - if (policyRevision < 1 || expectedGeneration < 0) { - throw new IllegalArgumentException( - "policy revision must be positive and expected generation non-negative"); - } - if (maximumParkedLegs < 1 || maximumParkedLegs > 100) { - throw new IllegalArgumentException("maximum parked legs must be in 1..100"); - } - Objects.requireNonNull(faultScope, "notification fault scope must be non-null"); - if (faultScope == NotificationFaultScope.DELIVERY) { - throw new IllegalArgumentException("shared admission gate cannot use DELIVERY fault scope"); - } - scopeReference = - NotificationIntentId.requireOpaque("admission scope reference", scopeReference); - actorReference = - NotificationIntentId.requireOpaque("admission resume actor reference", actorReference); - Objects.requireNonNull(reasonCode, "notification reason code must be non-null"); - } - } - - record ReadinessProbe(boolean ready, NotificationReasonCode reasonCode) { - - public ReadinessProbe { - Objects.requireNonNull(reasonCode, "notification readiness reason must be non-null"); - } - } - - enum ResumeStatus { - RESUMED, - ALREADY_ACTIVE, - STALE_GENERATION - } - - /** - * Audited bounded result of rechecking every selected parked leg inside the gate-resume - * transaction. Initial R1 never activates fallback while resuming a binding park. - */ - record ResumeResult( - ResumeStatus status, - long resultingGeneration, - int queuedCount, - int expiredCount, - int cancelledCount, - int technicallySuppressedCount, - int policyRejectedCount, - int activatedFallbackCount) { - - public ResumeResult { - Objects.requireNonNull(status, "notification admission resume status must be non-null"); - if (resultingGeneration < 0 - || queuedCount < 0 - || expiredCount < 0 - || cancelledCount < 0 - || technicallySuppressedCount < 0 - || policyRejectedCount < 0 - || activatedFallbackCount < 0) { - throw new IllegalArgumentException( - "notification admission resume generation/counts must be non-negative"); - } - int processedLegCount = - queuedCount - + expiredCount - + cancelledCount - + technicallySuppressedCount - + policyRejectedCount; - if (processedLegCount > 100) { - throw new IllegalArgumentException( - "notification admission resume leg count must be bounded by 100"); - } - if (activatedFallbackCount != 0) { - throw new IllegalArgumentException( - "binding-park resume must not activate initial fallback legs"); - } - if (status != ResumeStatus.RESUMED && processedLegCount != 0) { - throw new IllegalArgumentException( - "non-mutating admission resume status cannot report processed legs"); - } - } - - public int processedLegCount() { - return queuedCount - + expiredCount - + cancelledCount - + technicallySuppressedCount - + policyRejectedCount; - } - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationAppendResult.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationAppendResult.java deleted file mode 100644 index 81c9e512..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationAppendResult.java +++ /dev/null @@ -1,31 +0,0 @@ -package dev.caskeleton.application.notification; - -import java.util.Objects; - -/** Durable append result; neither appended nor duplicate means provider delivery succeeded. */ -public sealed interface NotificationAppendResult - permits NotificationAppendResult.Appended, - NotificationAppendResult.DuplicateExisting, - NotificationAppendResult.Rejected { - - record Appended(NotificationIntentId intentId) implements NotificationAppendResult { - - public Appended { - Objects.requireNonNull(intentId, "notification intent ID must be non-null"); - } - } - - record DuplicateExisting(NotificationIntentId intentId) implements NotificationAppendResult { - - public DuplicateExisting { - Objects.requireNonNull(intentId, "notification intent ID must be non-null"); - } - } - - record Rejected(NotificationReasonCode reasonCode) implements NotificationAppendResult { - - public Rejected { - Objects.requireNonNull(reasonCode, "notification reason code must be non-null"); - } - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationApplicationException.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationApplicationException.java deleted file mode 100644 index 0b0faeae..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationApplicationException.java +++ /dev/null @@ -1,21 +0,0 @@ -package dev.caskeleton.application.notification; - -import java.util.Objects; - -/** Framework- and provider-neutral application failure carrying only a stable reason code. */ -public final class NotificationApplicationException extends RuntimeException { - - private static final long serialVersionUID = 1L; - private final NotificationReasonCode reasonCode; - - public NotificationApplicationException(NotificationReasonCode reasonCode, Throwable cause) { - super( - Objects.requireNonNull(reasonCode, "notification reason code must be non-null").value(), - cause); - this.reasonCode = reasonCode; - } - - public NotificationReasonCode reasonCode() { - return reasonCode; - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationAttemptId.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationAttemptId.java deleted file mode 100644 index 516be328..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationAttemptId.java +++ /dev/null @@ -1,9 +0,0 @@ -package dev.caskeleton.application.notification; - -/** Opaque identity of one authorized physical provider attempt. */ -public record NotificationAttemptId(String value) { - - public NotificationAttemptId { - value = NotificationIntentId.requireOpaque("attemptId", value); - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationCanonicalWriterFenceGuard.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationCanonicalWriterFenceGuard.java deleted file mode 100644 index 0eafc3aa..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationCanonicalWriterFenceGuard.java +++ /dev/null @@ -1,44 +0,0 @@ -package dev.caskeleton.application.notification; - -import java.util.Objects; - -/** - * Internal application collaborator asserting canonical ownership in an existing write boundary. - */ -public final class NotificationCanonicalWriterFenceGuard { - - private final NotificationCanonicalWriterFencePort fence; - private final NotificationCanonicalWriterRouteSet routes; - - public NotificationCanonicalWriterFenceGuard( - NotificationCanonicalWriterFencePort fence, NotificationCanonicalWriterRouteSet routes) { - this.fence = Objects.requireNonNull(fence, "canonical writer fence port must be non-null"); - this.routes = Objects.requireNonNull(routes, "canonical writer route set must be non-null"); - } - - public void assertCanonical( - NotificationCanonicalWriterRouteSet.RouteRevision route, long expectedGeneration) { - if (!routes.contains(route)) { - throw new IllegalArgumentException( - "route is outside canonical notification writer route set"); - } - NotificationCanonicalWriterFencePort.FenceSnapshot snapshot = - Objects.requireNonNull( - fence.assertCanonicalInCallerTransaction( - new NotificationCanonicalWriterFencePort.FenceRequest(route, expectedGeneration)), - "canonical writer fence snapshot must be non-null"); - if (!snapshot.route().equals(route)) { - throw failure("CANONICAL_WRITER_ROUTE_MISMATCH"); - } - if (snapshot.owner() != NotificationWriterOwnership.CANONICAL) { - throw failure("CANONICAL_WRITER_NOT_OWNER"); - } - if (snapshot.generation() != expectedGeneration) { - throw failure("STALE_CANONICAL_WRITER_GENERATION"); - } - } - - private static NotificationApplicationException failure(String reason) { - return new NotificationApplicationException(new NotificationReasonCode(reason), null); - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationCanonicalWriterFencePort.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationCanonicalWriterFencePort.java deleted file mode 100644 index 420ea9de..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationCanonicalWriterFencePort.java +++ /dev/null @@ -1,38 +0,0 @@ -package dev.caskeleton.application.notification; - -import java.util.Objects; - -/** - * Acquires a transaction-scoped shared fence assertion. The persistence implementation must hold - * the share lock until the caller's physical commit or rollback. - */ -@FunctionalInterface -public interface NotificationCanonicalWriterFencePort { - - FenceSnapshot assertCanonicalInCallerTransaction(FenceRequest request); - - record FenceRequest( - NotificationCanonicalWriterRouteSet.RouteRevision route, long expectedGeneration) { - - public FenceRequest { - Objects.requireNonNull(route, "notification writer route must be non-null"); - if (expectedGeneration < 0) { - throw new IllegalArgumentException("expected writer generation must be non-negative"); - } - } - } - - record FenceSnapshot( - NotificationCanonicalWriterRouteSet.RouteRevision route, - NotificationWriterOwnership owner, - long generation) { - - public FenceSnapshot { - Objects.requireNonNull(route, "notification writer route must be non-null"); - Objects.requireNonNull(owner, "notification writer owner must be non-null"); - if (generation < 0) { - throw new IllegalArgumentException("writer generation must be non-negative"); - } - } - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationCanonicalWriterRouteSet.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationCanonicalWriterRouteSet.java deleted file mode 100644 index 3a9316ec..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationCanonicalWriterRouteSet.java +++ /dev/null @@ -1,79 +0,0 @@ -package dev.caskeleton.application.notification; - -import java.nio.ByteBuffer; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.Comparator; -import java.util.HashSet; -import java.util.List; -import java.util.Objects; - -/** Bounded, ordered canonical route-revision set that production admission is allowed to use. */ -public record NotificationCanonicalWriterRouteSet(List routes) { - - public NotificationCanonicalWriterRouteSet { - Objects.requireNonNull(routes, "canonical notification writer routes must be non-null"); - routes = - routes.stream() - .map(route -> Objects.requireNonNull(route, "canonical route must be non-null")) - .sorted( - Comparator.comparing((RouteRevision route) -> route.routeId().value()) - .thenComparingInt(RouteRevision::routeRevision)) - .toList(); - if (routes.isEmpty() || routes.size() > 100) { - throw new IllegalArgumentException("canonical writer route set must contain 1..100 routes"); - } - if (new HashSet<>(routes).size() != routes.size()) { - throw new IllegalArgumentException("canonical writer route set contains a duplicate route"); - } - long distinctRouteKeys = routes.stream().map(RouteRevision::routeId).distinct().count(); - if (distinctRouteKeys != routes.size()) { - throw new IllegalArgumentException( - "canonical writer route set contains multiple revisions for one route key"); - } - } - - public boolean contains(RouteRevision route) { - return routes.contains(route); - } - - public String digest() { - MessageDigest digest = sha256(); - routes.forEach( - route -> { - update(digest, route.routeId().value()); - digest.update(ByteBuffer.allocate(Integer.BYTES).putInt(route.routeRevision()).array()); - digest.update( - ByteBuffer.allocate(Long.BYTES).putLong(route.predecessorGeneration()).array()); - }); - return java.util.HexFormat.of().formatHex(digest.digest()); - } - - private static MessageDigest sha256() { - try { - return MessageDigest.getInstance("SHA-256"); - } catch (NoSuchAlgorithmException unavailable) { - throw new IllegalStateException( - "SHA-256 must be available on every Java runtime", unavailable); - } - } - - static void update(MessageDigest digest, String value) { - byte[] encoded = value.getBytes(StandardCharsets.UTF_8); - digest.update(ByteBuffer.allocate(Integer.BYTES).putInt(encoded.length).array()); - digest.update(encoded); - } - - public record RouteRevision( - NotificationRouteId routeId, int routeRevision, long predecessorGeneration) { - - public RouteRevision { - Objects.requireNonNull(routeId, "notification route ID must be non-null"); - if (routeRevision < 1 || routeRevision > 1_000_000 || predecessorGeneration < 0) { - throw new IllegalArgumentException( - "route revision must be in 1..1000000 and predecessor generation non-negative"); - } - } - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationCapabilityCompatibilityValidator.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationCapabilityCompatibilityValidator.java deleted file mode 100644 index 088c69f1..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationCapabilityCompatibilityValidator.java +++ /dev/null @@ -1,96 +0,0 @@ -package dev.caskeleton.application.notification; - -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; -import java.util.Optional; - -/** Pure validator over application-owned policy and provider/store/ingress capability facts. */ -public final class NotificationCapabilityCompatibilityValidator { - - public Compatibility validate( - NotificationKindPolicy policy, - NotificationProviderCapabilityDescriptor provider, - NotificationStoreCapabilityDescriptor store, - Optional receiptIngress, - boolean receiptRequired) { - Objects.requireNonNull(policy, "notification kind policy must be non-null"); - Objects.requireNonNull(provider, "notification provider descriptor must be non-null"); - Objects.requireNonNull(store, "notification store descriptor must be non-null"); - Objects.requireNonNull(receiptIngress, "receipt ingress container must be non-null"); - - List reasons = new ArrayList<>(); - addIf(reasons, provider.channel() != policy.channel(), "PROVIDER_CHANNEL_MISMATCH"); - addIf(reasons, !provider.supportedModes().contains(policy.mode()), "PROVIDER_MODE_UNSUPPORTED"); - addIf(reasons, !provider.hiddenRetriesControlled(), "PROVIDER_HIDDEN_RETRY_UNCONTROLLED"); - addIf( - reasons, - provider.maximumTargets() < policy.maxTargetsPerRecipient(), - "PROVIDER_TARGET_BOUND_INSUFFICIENT"); - addIf( - reasons, - policy.maxReconcileCalls() > 0 && !provider.reconciliationSupported(), - "PROVIDER_RECONCILIATION_UNSUPPORTED"); - if (policy.mode() == NotificationMode.DURABLE_ASYNC) { - addIf( - reasons, - !store.durableIntentStore() || !store.attemptJournal(), - "DURABLE_STORE_UNAVAILABLE"); - } - addIf( - reasons, - !store.availablePolicyRevisions().contains(policy.policyRevision()), - "POLICY_REVISION_UNAVAILABLE"); - addIf( - reasons, - !store.availableTemplateRevisions().contains(policy.templateRef()), - "TEMPLATE_REVISION_UNAVAILABLE"); - if (receiptRequired) { - addIf(reasons, !provider.receiptSupported(), "PROVIDER_RECEIPT_UNSUPPORTED"); - addIf(reasons, !store.receiptInbox(), "RECEIPT_STORE_UNAVAILABLE"); - boolean ingressUnavailable = - receiptIngress.isEmpty() - || !receiptIngress.orElseThrow().enabled() - || !receiptIngress.orElseThrow().authenticated() - || receiptIngress.orElseThrow().channel() != policy.channel() - || receiptIngress.orElseThrow().supportedFactTypes().isEmpty(); - addIf(reasons, ingressUnavailable, "RECEIPT_INGRESS_UNAVAILABLE"); - } - return new Compatibility(reasons.isEmpty(), reasons); - } - - public void requireCompatible( - NotificationKindPolicy policy, - NotificationProviderCapabilityDescriptor provider, - NotificationStoreCapabilityDescriptor store, - Optional receiptIngress, - boolean receiptRequired) { - Compatibility compatibility = - validate(policy, provider, store, receiptIngress, receiptRequired); - if (!compatibility.compatible()) { - throw new NotificationApplicationException( - new NotificationReasonCode("NOTIFICATION_CAPABILITY_INCOMPATIBLE"), null); - } - } - - private static void addIf( - List reasons, boolean condition, String reasonCode) { - if (condition) { - reasons.add(new NotificationReasonCode(reasonCode)); - } - } - - public record Compatibility(boolean compatible, List reasonCodes) { - - public Compatibility { - reasonCodes = - List.copyOf( - Objects.requireNonNull( - reasonCodes, "notification compatibility reasons must be non-null")); - if (compatible != reasonCodes.isEmpty()) { - throw new IllegalArgumentException( - "compatible flag must equal an empty incompatibility reason set"); - } - } - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationDeliveryId.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationDeliveryId.java deleted file mode 100644 index 405e0095..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationDeliveryId.java +++ /dev/null @@ -1,9 +0,0 @@ -package dev.caskeleton.application.notification; - -/** Opaque identity of one provider leg for a logical recipient. */ -public record NotificationDeliveryId(String value) { - - public NotificationDeliveryId { - value = NotificationIntentId.requireOpaque("deliveryId", value); - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationDeliveryStorePort.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationDeliveryStorePort.java deleted file mode 100644 index 339337bb..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationDeliveryStorePort.java +++ /dev/null @@ -1,267 +0,0 @@ -package dev.caskeleton.application.notification; - -import java.time.Instant; -import java.util.List; -import java.util.Objects; - -/** Durable delivery-leg state port; provider I/O is deliberately absent from this contract. */ -public interface NotificationDeliveryStorePort { - - List claimEligible(int maximumClaims, Instant now); - - AttemptAuthorization reserveAndAuthorize(ClaimedDelivery claimed, Instant now); - - FinalizationResult finalizeAttempt( - AuthorizedAttempt attempt, AttemptFinalization finalization, Instant now); - - List claimForReconciliation(int maximumClaims, Instant now); - - ReconciliationFinalizationResult finalizeReconciliation( - ReconciliationClaim claim, - NotificationReconciliationPort.ReconciliationOutcome outcome, - Instant now); - - int attachOrphanReceipts(int maximumAttachments, Instant now); - - record ClaimedDelivery( - NotificationDeliveryId deliveryId, - NotificationFrozenPlan plan, - int targetOrdinal, - String claimToken, - long rowVersion, - long admissionGeneration) { - - public ClaimedDelivery { - Objects.requireNonNull(deliveryId, "notification delivery ID must be non-null"); - Objects.requireNonNull(plan, "notification frozen plan must be non-null"); - if (targetOrdinal < 0 || targetOrdinal >= plan.policy().maxTargetsPerRecipient()) { - throw new IllegalArgumentException("target ordinal is outside the frozen plan bound"); - } - claimToken = NotificationIntentId.requireOpaque("claim token", claimToken); - if (rowVersion < 0 || admissionGeneration < 0) { - throw new IllegalArgumentException( - "row version and admission generation must be non-negative"); - } - } - } - - sealed interface AttemptAuthorization permits Authorized, StaleClaim, NotEligible {} - - record Authorized(AuthorizedAttempt attempt) implements AttemptAuthorization { - - public Authorized { - Objects.requireNonNull(attempt, "authorized notification attempt must be non-null"); - } - } - - record StaleClaim(NotificationDeliveryId deliveryId, NotificationReasonCode reasonCode) - implements AttemptAuthorization { - - public StaleClaim { - Objects.requireNonNull(deliveryId, "notification delivery ID must be non-null"); - Objects.requireNonNull(reasonCode, "notification reason code must be non-null"); - } - } - - record NotEligible(NotificationDeliveryId deliveryId, NotificationReasonCode reasonCode) - implements AttemptAuthorization { - - public NotEligible { - Objects.requireNonNull(deliveryId, "notification delivery ID must be non-null"); - Objects.requireNonNull(reasonCode, "notification reason code must be non-null"); - } - } - - record AuthorizedAttempt( - NotificationDeliveryId deliveryId, - NotificationAttemptId attemptId, - NotificationFrozenPlan plan, - int targetOrdinal, - String claimToken, - String executionToken, - long expectedRowVersion, - long admissionGeneration, - String admissionScopeReference, - Instant absoluteDeadline) { - - public AuthorizedAttempt { - Objects.requireNonNull(deliveryId, "notification delivery ID must be non-null"); - Objects.requireNonNull(attemptId, "notification attempt ID must be non-null"); - Objects.requireNonNull(plan, "notification frozen plan must be non-null"); - if (targetOrdinal < 0 || targetOrdinal >= plan.policy().maxTargetsPerRecipient()) { - throw new IllegalArgumentException("target ordinal is outside the frozen plan bound"); - } - claimToken = NotificationIntentId.requireOpaque("claim token", claimToken); - executionToken = - NotificationIntentId.requireOpaque("attempt execution token", executionToken); - if (claimToken.equals(executionToken)) { - throw new IllegalArgumentException( - "attempt execution token must be distinct from the claim token"); - } - if (expectedRowVersion < 0 || admissionGeneration < 0) { - throw new IllegalArgumentException( - "row version and admission generation must be non-negative"); - } - admissionScopeReference = - NotificationIntentId.requireOpaque("admission scope reference", admissionScopeReference); - Objects.requireNonNull(absoluteDeadline, "absolute attempt deadline must be non-null"); - } - - @Override - public String toString() { - return "AuthorizedAttempt[deliveryId=, attemptId=" - + attemptId - + ", plan=, targetOrdinal=" - + targetOrdinal - + ", claimToken=, executionToken=, expectedRowVersion=" - + expectedRowVersion - + ", admissionGeneration=" - + admissionGeneration - + ", admissionScopeReference=, absoluteDeadline=" - + absoluteDeadline - + "]"; - } - } - - record AttemptFinalization( - ProviderAttemptOutcome providerOutcome, - TerminalState terminalState, - boolean fallbackEligible, - NotificationAdmissionReadinessPort.ParkResult parkResult) { - - public AttemptFinalization { - Objects.requireNonNull(providerOutcome, "provider attempt outcome must be non-null"); - Objects.requireNonNull(terminalState, "notification terminal state must be non-null"); - Objects.requireNonNull(parkResult, "admission park result must be non-null"); - if (fallbackEligible - && providerOutcome.submissionCertainty() != SubmissionCertainty.DEFINITELY_NOT_APPLIED) { - throw new IllegalArgumentException("fallback is eligible only for DEFINITELY_NOT_APPLIED"); - } - if (terminalState == TerminalState.TERMINAL_INDETERMINATE - && providerOutcome.submissionCertainty() != SubmissionCertainty.INDETERMINATE) { - throw new IllegalArgumentException( - "TERMINAL_INDETERMINATE requires an indeterminate provider outcome"); - } - if (terminalState == TerminalState.PARKED_BINDING - && providerOutcome.retryDisposition() != RetryDisposition.PARK_BINDING) { - throw new IllegalArgumentException("PARKED_BINDING requires PARK_BINDING disposition"); - } - if (providerOutcome.retryDisposition() == RetryDisposition.PARK_BINDING) { - if (parkResult == NotificationAdmissionReadinessPort.ParkResult.NOT_REQUESTED) { - throw new IllegalArgumentException("PARK_BINDING requires an admission park result"); - } - boolean parked = - parkResult == NotificationAdmissionReadinessPort.ParkResult.PARKED - || parkResult == NotificationAdmissionReadinessPort.ParkResult.ALREADY_PARKED; - TerminalState expected = - parked ? TerminalState.PARKED_BINDING : TerminalState.RETRY_SCHEDULED; - if (terminalState != expected) { - throw new IllegalArgumentException( - "terminal state must reflect the generation-guarded admission park result"); - } - } - } - } - - enum TerminalState { - ACCEPTED, - RETRY_SCHEDULED, - PARKED_BINDING, - TERMINAL_FAILURE, - TERMINAL_INDETERMINATE - } - - enum FinalizationResult { - APPLIED, - LATE_EXACT_APPLIED, - STALE_EXECUTION_TOKEN, - ALREADY_TERMINAL - } - - record ReconciliationClaim( - NotificationDeliveryId deliveryId, - String executionToken, - long expectedRowVersion, - NotificationRouteId routeId, - int routeRevision, - String bindingDigest, - int targetOrdinal, - String targetReference, - String providerCapabilityReference, - String providerBindingRevision, - String credentialGeneration, - String lookupReference, - ReconciliationLookupKind lookupKind, - Instant absoluteDeadline) { - - public ReconciliationClaim { - Objects.requireNonNull(deliveryId, "notification delivery ID must be non-null"); - executionToken = - NotificationIntentId.requireOpaque("reconciliation execution token", executionToken); - if (expectedRowVersion < 0 || routeRevision < 1 || targetOrdinal < 0 || targetOrdinal > 15) { - throw new IllegalArgumentException( - "reconciliation row version, route revision and target ordinal are invalid"); - } - Objects.requireNonNull(routeId, "reconciliation route ID must be non-null"); - if (bindingDigest == null || !bindingDigest.matches("[0-9a-f]{64}")) { - throw new IllegalArgumentException( - "reconciliation binding digest must be a lowercase SHA-256 digest"); - } - targetReference = - NotificationIntentId.requireOpaque("reconciliation target reference", targetReference); - providerCapabilityReference = - NotificationIntentId.requireOpaque( - "reconciliation provider capability reference", providerCapabilityReference); - providerBindingRevision = - NotificationIntentId.requireOpaque( - "reconciliation provider binding revision", providerBindingRevision); - credentialGeneration = - NotificationIntentId.requireSlug( - "reconciliation credential generation", credentialGeneration); - lookupReference = - NotificationIntentId.requireOpaque( - "provider reconciliation lookup reference", lookupReference); - Objects.requireNonNull(lookupKind, "provider reconciliation lookup kind must be non-null"); - Objects.requireNonNull(absoluteDeadline, "reconciliation deadline must be non-null"); - } - - @Override - public String toString() { - return "ReconciliationClaim[deliveryId=, executionToken=, " - + "expectedRowVersion=" - + expectedRowVersion - + ", routeId=" - + routeId - + ", routeRevision=" - + routeRevision - + ", bindingDigest=" - + bindingDigest - + ", targetOrdinal=" - + targetOrdinal - + ", targetReference=, providerCapabilityReference=" - + providerCapabilityReference - + ", providerBindingRevision=" - + providerBindingRevision - + ", credentialGeneration=" - + credentialGeneration - + ", lookupReference=, lookupKind=" - + lookupKind - + ", absoluteDeadline=" - + absoluteDeadline - + "]"; - } - } - - enum ReconciliationLookupKind { - PRE_SEND_CORRELATION, - CLIENT_OPERATION_KEY, - MESSAGE_REFERENCE - } - - enum ReconciliationFinalizationResult { - APPLIED, - LATE_EXACT_APPLIED, - STALE_EXECUTION_TOKEN, - ALREADY_TERMINAL - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationDispatchCommand.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationDispatchCommand.java deleted file mode 100644 index 3689b395..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationDispatchCommand.java +++ /dev/null @@ -1,13 +0,0 @@ -package dev.caskeleton.application.notification; - -import dev.caskeleton.application.command.Command; - -/** Requests one bounded cross-tenant dispatch cycle. */ -public record NotificationDispatchCommand(int maximumClaims) implements Command { - - public NotificationDispatchCommand { - if (maximumClaims < 1 || maximumClaims > 100) { - throw new IllegalArgumentException("maximum notification claims must be in 1..100"); - } - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationDispatchResult.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationDispatchResult.java deleted file mode 100644 index 43502a07..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationDispatchResult.java +++ /dev/null @@ -1,37 +0,0 @@ -package dev.caskeleton.application.notification; - -/** Bounded non-sensitive aggregate outcome of one dispatch cycle. */ -public record NotificationDispatchResult( - int claimedCount, - int authorizedCount, - int providerCallCount, - int finalizedCount, - int staleClaimCount, - int indeterminateCount, - int parkedCount) { - - public NotificationDispatchResult { - int[] counts = { - claimedCount, - authorizedCount, - providerCallCount, - finalizedCount, - staleClaimCount, - indeterminateCount, - parkedCount - }; - for (int count : counts) { - if (count < 0 || count > 100) { - throw new IllegalArgumentException("notification dispatch counts must be in 0..100"); - } - } - if (authorizedCount > claimedCount - || providerCallCount > authorizedCount - || finalizedCount > providerCallCount - || staleClaimCount > claimedCount - || indeterminateCount > providerCallCount - || parkedCount > providerCallCount) { - throw new IllegalArgumentException("notification dispatch counts are inconsistent"); - } - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationDispatchUseCase.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationDispatchUseCase.java deleted file mode 100644 index 3977af2c..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationDispatchUseCase.java +++ /dev/null @@ -1,199 +0,0 @@ -package dev.caskeleton.application.notification; - -import dev.caskeleton.application.capability.Idempotency; -import dev.caskeleton.application.capability.RepositoryAccess; -import dev.caskeleton.application.capability.UseCaseCapability; -import dev.caskeleton.application.security.RequiresPermission; -import dev.caskeleton.application.transaction.TransactionMode; -import dev.caskeleton.application.transaction.TransactionPort; -import dev.caskeleton.application.usecase.CommandUseCase; -import java.time.Clock; -import java.util.List; -import java.util.Objects; - -/** Coordinates short store transactions around provider I/O for a bounded delivery batch. */ -@RequiresPermission("notification:dispatch") -@UseCaseCapability( - transactionMode = TransactionMode.WRITE, - idempotency = Idempotency.IDEMPOTENT, - repositoryAccess = RepositoryAccess.WRITE_REPOSITORY, - externalOutboundAllowed = true, - sensitiveRead = true, - crossTenantAdmin = true) -public class NotificationDispatchUseCase - implements CommandUseCase { - - private final NotificationDeliveryStorePort store; - private final NotificationProviderAttemptPort provider; - private final NotificationAdmissionReadinessPort admission; - private final TransactionPort transactions; - private final Clock clock; - - public NotificationDispatchUseCase( - NotificationDeliveryStorePort store, - NotificationProviderAttemptPort provider, - NotificationAdmissionReadinessPort admission, - TransactionPort transactions, - Clock clock) { - this.store = Objects.requireNonNull(store, "notification delivery store must be non-null"); - this.provider = Objects.requireNonNull(provider, "notification provider port must be non-null"); - this.admission = - Objects.requireNonNull(admission, "notification admission port must be non-null"); - this.transactions = Objects.requireNonNull(transactions, "transaction port must be non-null"); - this.clock = Objects.requireNonNull(clock, "clock must be non-null"); - } - - @Override - public NotificationDispatchResult handle(NotificationDispatchCommand command) { - Objects.requireNonNull(command, "notification dispatch command must be non-null"); - List claimed = - List.copyOf( - transactions.inWrite( - () -> store.claimEligible(command.maximumClaims(), clock.instant()))); - if (claimed.size() > command.maximumClaims()) { - throw new IllegalStateException("notification store returned more claims than requested"); - } - - MutableCounts counts = new MutableCounts(claimed.size()); - for (NotificationDeliveryStorePort.ClaimedDelivery delivery : claimed) { - dispatchOne(delivery, counts); - } - return counts.toResult(); - } - - private void dispatchOne( - NotificationDeliveryStorePort.ClaimedDelivery delivery, MutableCounts counts) { - NotificationDeliveryStorePort.AttemptAuthorization authorization = - transactions.inWrite(() -> store.reserveAndAuthorize(delivery, clock.instant())); - if (authorization instanceof NotificationDeliveryStorePort.StaleClaim) { - counts.staleClaims++; - return; - } - if (authorization instanceof NotificationDeliveryStorePort.NotEligible) { - return; - } - - NotificationDeliveryStorePort.AuthorizedAttempt attempt = - ((NotificationDeliveryStorePort.Authorized) authorization).attempt(); - counts.authorized++; - ProviderAttemptOutcome outcome = invokeProvider(attempt); - counts.providerCalls++; - if (outcome.submissionCertainty() == SubmissionCertainty.INDETERMINATE) { - counts.indeterminate++; - } - - FinalizationExecution execution = - transactions.inWrite(() -> finalizeInsideTransaction(attempt, outcome)); - boolean applied = - execution.result() == NotificationDeliveryStorePort.FinalizationResult.APPLIED - || execution.result() - == NotificationDeliveryStorePort.FinalizationResult.LATE_EXACT_APPLIED; - if (applied) { - counts.finalized++; - } - if (applied - && execution.finalization().terminalState() - == NotificationDeliveryStorePort.TerminalState.PARKED_BINDING) { - counts.parked++; - } - } - - private ProviderAttemptOutcome invokeProvider( - NotificationDeliveryStorePort.AuthorizedAttempt attempt) { - try { - return Objects.requireNonNull( - provider.attempt(attempt), "provider attempt outcome must be non-null"); - } catch (RuntimeException providerFailure) { - return new ProviderAttemptOutcome( - SubmissionCertainty.INDETERMINATE, - RetryDisposition.NOT_APPLICABLE, - NotificationFaultScope.DELIVERY, - new NotificationReasonCode("UNCLASSIFIED_PROVIDER_FAILURE"), - java.util.Optional.empty(), - attempt.executionToken(), - java.util.Optional.empty()); - } - } - - private FinalizationExecution finalizeInsideTransaction( - NotificationDeliveryStorePort.AuthorizedAttempt attempt, ProviderAttemptOutcome outcome) { - NotificationAdmissionReadinessPort.ParkResult parkResult = - NotificationAdmissionReadinessPort.ParkResult.NOT_REQUESTED; - if (outcome.retryDisposition() == RetryDisposition.PARK_BINDING) { - parkResult = - admission.park( - new NotificationAdmissionReadinessPort.ParkRequest( - attempt.plan().routeId(), - attempt.plan().policy().policyRevision(), - outcome.faultScope(), - attempt.admissionScopeReference(), - attempt.admissionGeneration(), - outcome.reasonCode(), - clock.instant())); - } - - NotificationDeliveryStorePort.AttemptFinalization finalization = - new NotificationDeliveryStorePort.AttemptFinalization( - outcome, terminalState(outcome, parkResult), fallbackEligible(outcome), parkResult); - NotificationDeliveryStorePort.FinalizationResult result = - Objects.requireNonNull( - store.finalizeAttempt(attempt, finalization, clock.instant()), - "notification attempt finalization result must be non-null"); - return new FinalizationExecution(finalization, result); - } - - private static NotificationDeliveryStorePort.TerminalState terminalState( - ProviderAttemptOutcome outcome, NotificationAdmissionReadinessPort.ParkResult parkResult) { - if (outcome.submissionCertainty() == SubmissionCertainty.PROVIDER_ACCEPTED) { - return NotificationDeliveryStorePort.TerminalState.ACCEPTED; - } - if (outcome.submissionCertainty() == SubmissionCertainty.INDETERMINATE) { - return NotificationDeliveryStorePort.TerminalState.TERMINAL_INDETERMINATE; - } - return switch (outcome.retryDisposition()) { - case RETRY_AT -> NotificationDeliveryStorePort.TerminalState.RETRY_SCHEDULED; - case PARK_BINDING -> - switch (parkResult) { - case PARKED, ALREADY_PARKED -> - NotificationDeliveryStorePort.TerminalState.PARKED_BINDING; - case STALE_GENERATION -> NotificationDeliveryStorePort.TerminalState.RETRY_SCHEDULED; - case NOT_REQUESTED -> - throw new IllegalStateException( - "PARK_BINDING outcome requires an admission park result"); - }; - case TERMINAL -> NotificationDeliveryStorePort.TerminalState.TERMINAL_FAILURE; - case NOT_APPLICABLE -> - throw new IllegalArgumentException( - "definitely-not-applied outcome requires an explicit disposition"); - }; - } - - private static boolean fallbackEligible(ProviderAttemptOutcome outcome) { - return outcome.submissionCertainty() == SubmissionCertainty.DEFINITELY_NOT_APPLIED - && outcome.retryDisposition() == RetryDisposition.TERMINAL; - } - - private record FinalizationExecution( - NotificationDeliveryStorePort.AttemptFinalization finalization, - NotificationDeliveryStorePort.FinalizationResult result) {} - - private static final class MutableCounts { - - private final int claimed; - private int authorized; - private int providerCalls; - private int finalized; - private int staleClaims; - private int indeterminate; - private int parked; - - private MutableCounts(int claimed) { - this.claimed = claimed; - } - - private NotificationDispatchResult toResult() { - return new NotificationDispatchResult( - claimed, authorized, providerCalls, finalized, staleClaims, indeterminate, parked); - } - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationEvidenceTrustSnapshot.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationEvidenceTrustSnapshot.java deleted file mode 100644 index a94083af..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationEvidenceTrustSnapshot.java +++ /dev/null @@ -1,24 +0,0 @@ -package dev.caskeleton.application.notification; - -import java.util.Objects; - -/** Historical issuer-key decision retained with accepted signed evidence. */ -public record NotificationEvidenceTrustSnapshot( - String catalogRevision, HistoricalKeyStatus historicalKeyStatus, String issuerKeyDigest) { - - public NotificationEvidenceTrustSnapshot { - catalogRevision = - NotificationIntentId.requireSlug("evidence trust catalog revision", catalogRevision); - Objects.requireNonNull(historicalKeyStatus, "historical evidence key status must be non-null"); - issuerKeyDigest = InitializeNotificationWriterFencesCommand.requireDigest(issuerKeyDigest); - if (historicalKeyStatus == HistoricalKeyStatus.REVOKED) { - throw new IllegalArgumentException("revoked evidence issuer key cannot be accepted"); - } - } - - public enum HistoricalKeyStatus { - ALLOWED, - RETIRING, - REVOKED - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationFaultScope.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationFaultScope.java deleted file mode 100644 index 9a3dad4d..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationFaultScope.java +++ /dev/null @@ -1,9 +0,0 @@ -package dev.caskeleton.application.notification; - -/** Smallest durable scope affected by a classified attempt failure. */ -public enum NotificationFaultScope { - DELIVERY, - ROUTE_REVISION, - PROVIDER_BINDING, - ACCOUNT -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationFrozenPlan.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationFrozenPlan.java deleted file mode 100644 index ac263192..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationFrozenPlan.java +++ /dev/null @@ -1,216 +0,0 @@ -package dev.caskeleton.application.notification; - -import java.time.Duration; -import java.time.Instant; -import java.util.Comparator; -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.Objects; -import java.util.Optional; - -/** Immutable provider-neutral plan snapshot returned by the application planning boundary. */ -public record NotificationFrozenPlan( - NotificationIntentId intentId, - NotificationKindPolicy policy, - Locale selectedLocale, - BindingSnapshot binding, - NotificationRecipientReference recipient, - NotificationTemplateParameters parameters, - String idempotencyScope, - String sourceOperationId, - Optional tenantReference, - String correlationReference, - Optional causationReference, - Instant notBefore, - Instant expiresAt) { - - public NotificationFrozenPlan { - Objects.requireNonNull(intentId, "notification intent ID must be non-null"); - Objects.requireNonNull(policy, "notification kind policy must be non-null"); - selectedLocale = NotificationIntentDraft.requireLocale("selected locale", selectedLocale); - Objects.requireNonNull(binding, "notification binding snapshot must be non-null"); - Objects.requireNonNull(recipient, "notification recipient must be non-null"); - Objects.requireNonNull(parameters, "notification template parameters must be non-null"); - idempotencyScope = - NotificationIntentId.requireOpaque("notification idempotency scope", idempotencyScope); - sourceOperationId = - NotificationIntentId.requireOpaque("notification source operation ID", sourceOperationId); - tenantReference = requireOptionalOpaque("tenant reference", tenantReference); - correlationReference = - NotificationIntentId.requireOpaque( - "notification correlation reference", correlationReference); - causationReference = requireOptionalOpaque("causation reference", causationReference); - Objects.requireNonNull(notBefore, "notification not-before time must be non-null"); - Objects.requireNonNull(expiresAt, "notification expiry time must be non-null"); - if (recipient.channel() != policy.channel()) { - throw new IllegalArgumentException("recipient channel must match notification kind channel"); - } - if (binding.targets().size() != policy.maxTargetsPerRecipient()) { - throw new IllegalArgumentException( - "frozen binding target count must match the code-owned policy target bound"); - } - Duration lifetime = Duration.between(notBefore, expiresAt); - if (lifetime.isZero() - || lifetime.isNegative() - || lifetime.compareTo(policy.maxElapsedRetryHorizon()) > 0) { - throw new IllegalArgumentException( - "notification expiry must be after not-before and within the policy retry horizon"); - } - } - - public static NotificationFrozenPlan from( - NotificationIntentDraft draft, Locale selectedLocale, BindingSnapshot binding) { - Objects.requireNonNull(draft, "notification intent draft must be non-null"); - return new NotificationFrozenPlan( - draft.intentId(), - draft.policy(), - selectedLocale, - binding, - draft.recipient(), - draft.parameters(), - draft.idempotencyScope(), - draft.sourceOperationId(), - draft.tenantReference(), - draft.correlationReference(), - draft.causationReference(), - draft.notBefore(), - draft.expiresAt()); - } - - public NotificationMode mode() { - return policy.mode(); - } - - public NotificationRouteId routeId() { - return policy.routeId(); - } - - private static Optional requireOptionalOpaque(String field, Optional reference) { - Objects.requireNonNull(reference, field + " container must be non-null"); - return reference.map(value -> NotificationIntentId.requireOpaque(field, value)); - } - - @Override - public String toString() { - return "NotificationFrozenPlan[intentId=" - + intentId - + ", kindId=" - + policy.kindId() - + ", policyRevision=" - + policy.policyRevision() - + ", selectedLocale=" - + selectedLocale.toLanguageTag() - + ", routeRevision=" - + binding.routeRevision() - + ", bindingDigest=" - + binding.bindingDigest() - + ", rendererRevision=" - + binding.rendererRevision() - + ", targets=" - + ", recipient=, parameters=, context=, notBefore=" - + notBefore - + ", expiresAt=" - + expiresAt - + "]"; - } - - /** Provider-neutral immutable execution graph persisted with the logical intent. */ - public record BindingSnapshot( - int routeRevision, - String bindingDigest, - String templateChecksum, - String rendererRevision, - List targets, - boolean receiptRequired, - Duration perAttemptDeadline) { - - private static final Duration MAXIMUM_ATTEMPT_DEADLINE = Duration.ofMinutes(5); - - public BindingSnapshot { - if (routeRevision < 1 || routeRevision > 1_000_000) { - throw new IllegalArgumentException("frozen route revision must be in 1..1000000"); - } - bindingDigest = requireDigest("notification binding digest", bindingDigest); - templateChecksum = requireDigest("notification template checksum", templateChecksum); - rendererRevision = - NotificationIntentId.requireSlug("notification renderer revision", rendererRevision); - Objects.requireNonNull(targets, "frozen notification targets must be non-null"); - targets = - targets.stream() - .map(target -> Objects.requireNonNull(target, "frozen target must be non-null")) - .sorted(Comparator.comparingInt(FrozenTarget::ordinal)) - .toList(); - if (targets.isEmpty() || targets.size() > 16) { - throw new IllegalArgumentException( - "frozen notification targets must contain 1..16 entries"); - } - if (new HashSet<>(targets.stream().map(FrozenTarget::targetReference).toList()).size() - != targets.size()) { - throw new IllegalArgumentException( - "frozen notification targets contain duplicate references"); - } - for (int index = 0; index < targets.size(); index++) { - if (targets.get(index).ordinal() != index) { - throw new IllegalArgumentException( - "frozen notification target ordinals must be contiguous from zero"); - } - } - Objects.requireNonNull( - perAttemptDeadline, "notification per-attempt deadline must be non-null"); - if (perAttemptDeadline.isZero() - || perAttemptDeadline.isNegative() - || perAttemptDeadline.compareTo(MAXIMUM_ATTEMPT_DEADLINE) > 0) { - throw new IllegalArgumentException( - "notification per-attempt deadline must be positive and at most five minutes"); - } - } - - private static String requireDigest(String field, String digest) { - if (digest == null || !digest.matches("[0-9a-f]{64}")) { - throw new IllegalArgumentException(field + " must be a lowercase SHA-256 digest"); - } - return digest; - } - } - - /** Opaque provider-leg identity; credentials, endpoints and SDK types are deliberately absent. */ - public record FrozenTarget( - int ordinal, - String targetReference, - String providerCapabilityReference, - String providerBindingRevision, - String credentialGeneration) { - - public FrozenTarget { - if (ordinal < 0 || ordinal > 15) { - throw new IllegalArgumentException("frozen notification target ordinal must be in 0..15"); - } - targetReference = - NotificationIntentId.requireOpaque( - "frozen notification target reference", targetReference); - providerCapabilityReference = - NotificationIntentId.requireOpaque( - "frozen provider capability reference", providerCapabilityReference); - providerBindingRevision = - NotificationIntentId.requireOpaque( - "frozen provider binding revision", providerBindingRevision); - credentialGeneration = - NotificationIntentId.requireSlug( - "frozen provider credential generation", credentialGeneration); - } - - @Override - public String toString() { - return "FrozenTarget[ordinal=" - + ordinal - + ", targetReference=, providerCapabilityReference=" - + providerCapabilityReference - + ", providerBindingRevision=" - + providerBindingRevision - + ", credentialGeneration=" - + credentialGeneration - + "]"; - } - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationIntentAppendPort.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationIntentAppendPort.java deleted file mode 100644 index 4346c5f8..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationIntentAppendPort.java +++ /dev/null @@ -1,11 +0,0 @@ -package dev.caskeleton.application.notification; - -/** - * Appends a frozen intent to durable storage in the caller's current transaction. Implementations - * must not open an independent transaction. - */ -@FunctionalInterface -public interface NotificationIntentAppendPort { - - NotificationAppendResult append(NotificationFrozenPlan plan); -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationIntentDraft.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationIntentDraft.java deleted file mode 100644 index 59356cda..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationIntentDraft.java +++ /dev/null @@ -1,84 +0,0 @@ -package dev.caskeleton.application.notification; - -import java.time.Duration; -import java.time.Instant; -import java.util.Locale; -import java.util.Objects; -import java.util.Optional; - -/** Feature-policy output containing one logical recipient and no provider or transport types. */ -public record NotificationIntentDraft( - NotificationIntentId intentId, - NotificationKindPolicy policy, - Locale requestedLocale, - NotificationRecipientReference recipient, - NotificationTemplateParameters parameters, - String idempotencyScope, - String sourceOperationId, - Optional tenantReference, - String correlationReference, - Optional causationReference, - Instant notBefore, - Instant expiresAt) { - - public NotificationIntentDraft { - Objects.requireNonNull(intentId, "notification intent ID must be non-null"); - Objects.requireNonNull(policy, "notification kind policy must be non-null"); - requestedLocale = requireLocale("requested locale", requestedLocale); - Objects.requireNonNull(recipient, "notification recipient must be non-null"); - Objects.requireNonNull(parameters, "notification template parameters must be non-null"); - if (recipient.channel() != policy.channel()) { - throw new IllegalArgumentException("recipient channel must match notification kind channel"); - } - idempotencyScope = - NotificationIntentId.requireOpaque("notification idempotency scope", idempotencyScope); - sourceOperationId = - NotificationIntentId.requireOpaque("notification source operation ID", sourceOperationId); - tenantReference = requireOptionalOpaque("tenant reference", tenantReference); - correlationReference = - NotificationIntentId.requireOpaque( - "notification correlation reference", correlationReference); - causationReference = requireOptionalOpaque("causation reference", causationReference); - Objects.requireNonNull(notBefore, "notification not-before time must be non-null"); - Objects.requireNonNull(expiresAt, "notification expiry time must be non-null"); - Duration lifetime = Duration.between(notBefore, expiresAt); - if (lifetime.isZero() - || lifetime.isNegative() - || lifetime.compareTo(policy.maxElapsedRetryHorizon()) > 0) { - throw new IllegalArgumentException( - "notification expiry must be after not-before and within the policy retry horizon"); - } - } - - static Locale requireLocale(String field, Locale locale) { - Objects.requireNonNull(locale, field + " must be non-null"); - String languageTag = locale.toLanguageTag(); - if (locale.equals(Locale.ROOT) - || languageTag.equals("und") - || languageTag.isBlank() - || languageTag.length() > 35) { - throw new IllegalArgumentException(field + " must be an explicit bounded locale"); - } - return Locale.forLanguageTag(languageTag); - } - - private static Optional requireOptionalOpaque(String field, Optional reference) { - Objects.requireNonNull(reference, field + " container must be non-null"); - return reference.map(value -> NotificationIntentId.requireOpaque(field, value)); - } - - @Override - public String toString() { - return "NotificationIntentDraft[intentId=" - + intentId - + ", kindId=" - + policy.kindId() - + ", requestedLocale=" - + requestedLocale.toLanguageTag() - + ", recipient=, parameters=, context=, notBefore=" - + notBefore - + ", expiresAt=" - + expiresAt - + "]"; - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationIntentId.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationIntentId.java deleted file mode 100644 index 6c1c3c49..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationIntentId.java +++ /dev/null @@ -1,24 +0,0 @@ -package dev.caskeleton.application.notification; - -/** Opaque identity of one logical business notification. */ -public record NotificationIntentId(String value) { - - public NotificationIntentId { - value = requireOpaque("intentId", value); - } - - static String requireOpaque(String field, String value) { - if (value == null || !value.matches("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}")) { - throw new IllegalArgumentException( - field + " must contain 1..128 opaque identifier characters"); - } - return value; - } - - static String requireSlug(String field, String value) { - if (value == null || !value.matches("[a-z][a-z0-9.-]{0,62}")) { - throw new IllegalArgumentException(field + " must match [a-z][a-z0-9.-]{0,62}"); - } - return value; - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationKindId.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationKindId.java deleted file mode 100644 index 3aed1f86..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationKindId.java +++ /dev/null @@ -1,9 +0,0 @@ -package dev.caskeleton.application.notification; - -/** Closed-catalog notification business kind. */ -public record NotificationKindId(String value) { - - public NotificationKindId { - value = NotificationIntentId.requireSlug("kindId", value); - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationKindPolicy.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationKindPolicy.java deleted file mode 100644 index 05429fae..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationKindPolicy.java +++ /dev/null @@ -1,124 +0,0 @@ -package dev.caskeleton.application.notification; - -import java.time.Duration; -import java.util.Objects; - -/** - * Code-owned notification kind catalog row. Runtime configuration may assert these values and lower - * resource concurrency, but cannot replace semantic fields in this record. - */ -public record NotificationKindPolicy( - NotificationKindId kindId, - NotificationChannel channel, - NotificationRouteId routeId, - NotificationTemplateRef templateRef, - NotificationMode mode, - NotificationAdmissionClass admissionClass, - NotificationRouteStrategy routeStrategy, - ConsentCheckMode consentCheckMode, - int policyRevision, - int maxTargetsPerRecipient, - int maxPhysicalAttemptsPerDelivery, - int maxFallbackActivations, - int maxReconcileCalls, - int maxTotalProviderCallsPerIntent, - Duration maxElapsedRetryHorizon) { - - private static final int MAXIMUM_TARGETS = 16; - private static final int MAXIMUM_ATTEMPTS_PER_DELIVERY = 10; - private static final int MAXIMUM_PROVIDER_CALLS = 64; - private static final Duration MAXIMUM_RETRY_HORIZON = Duration.ofDays(30); - - public NotificationKindPolicy { - Objects.requireNonNull(kindId, "notification kind must be non-null"); - Objects.requireNonNull(channel, "notification channel must be non-null"); - Objects.requireNonNull(routeId, "notification route must be non-null"); - Objects.requireNonNull(templateRef, "notification template must be non-null"); - Objects.requireNonNull(mode, "notification mode must be non-null"); - Objects.requireNonNull(admissionClass, "notification admission class must be non-null"); - Objects.requireNonNull(routeStrategy, "notification route strategy must be non-null"); - Objects.requireNonNull(consentCheckMode, "consent check mode must be non-null"); - Objects.requireNonNull(maxElapsedRetryHorizon, "maximum retry horizon must be non-null"); - if (policyRevision < 1 || policyRevision > 1_000_000) { - throw new IllegalArgumentException("policy revision must be in 1..1000000"); - } - if (maxTargetsPerRecipient < 1 || maxTargetsPerRecipient > MAXIMUM_TARGETS) { - throw new IllegalArgumentException("maximum targets per recipient must be in 1..16"); - } - if (maxPhysicalAttemptsPerDelivery < 1 - || maxPhysicalAttemptsPerDelivery > MAXIMUM_ATTEMPTS_PER_DELIVERY) { - throw new IllegalArgumentException("maximum physical attempts per delivery must be in 1..10"); - } - if (maxFallbackActivations < 0 || maxFallbackActivations >= MAXIMUM_TARGETS) { - throw new IllegalArgumentException("maximum fallback activations must be in 0..15"); - } - if (maxReconcileCalls < 0 || maxReconcileCalls > 10) { - throw new IllegalArgumentException("maximum reconcile calls must be in 0..10"); - } - if (maxTotalProviderCallsPerIntent < 1 - || maxTotalProviderCallsPerIntent > MAXIMUM_PROVIDER_CALLS) { - throw new IllegalArgumentException("maximum total provider calls must be in 1..64"); - } - if (maxElapsedRetryHorizon.isZero() - || maxElapsedRetryHorizon.isNegative() - || maxElapsedRetryHorizon.compareTo(MAXIMUM_RETRY_HORIZON) > 0) { - throw new IllegalArgumentException( - "maximum retry horizon must be positive and at most 30 days"); - } - if (admissionClass == NotificationAdmissionClass.SECURITY_CRITICAL - && mode == NotificationMode.BEST_EFFORT_INLINE) { - throw new IllegalArgumentException( - "SECURITY_CRITICAL notification kind cannot use BEST_EFFORT_INLINE"); - } - validateStrategy(routeStrategy, maxTargetsPerRecipient, maxFallbackActivations); - if (mode == NotificationMode.BEST_EFFORT_INLINE - && (maxPhysicalAttemptsPerDelivery != 1 || maxReconcileCalls != 0)) { - throw new IllegalArgumentException( - "BEST_EFFORT_INLINE permits one attempt per target and no reconciliation"); - } - long worstCaseProviderCalls = - Math.addExact( - Math.multiplyExact( - (long) maxTargetsPerRecipient, (long) maxPhysicalAttemptsPerDelivery), - maxReconcileCalls); - if (worstCaseProviderCalls > maxTotalProviderCallsPerIntent) { - throw new IllegalArgumentException( - "worst-case provider calls exceed maximum total provider calls per intent"); - } - } - - public NotificationKindPolicy assertRuntimeExpectation( - NotificationMode expectedMode, NotificationAdmissionClass expectedAdmissionClass) { - Objects.requireNonNull(expectedMode, "expected notification mode must be non-null"); - Objects.requireNonNull( - expectedAdmissionClass, "expected notification admission class must be non-null"); - if (mode != expectedMode) { - throw new IllegalStateException( - "runtime expected mode " + expectedMode + " does not match code-owned mode " + mode); - } - if (admissionClass != expectedAdmissionClass) { - throw new IllegalStateException( - "runtime expected admission " - + expectedAdmissionClass - + " does not match code-owned admission " - + admissionClass); - } - return this; - } - - private static void validateStrategy( - NotificationRouteStrategy strategy, int maximumTargets, int maximumFallbacks) { - if (strategy == NotificationRouteStrategy.SINGLE - && (maximumTargets != 1 || maximumFallbacks != 0)) { - throw new IllegalArgumentException("SINGLE requires one target and zero fallbacks"); - } - if (strategy == NotificationRouteStrategy.FAN_OUT_ALL && maximumFallbacks != 0) { - throw new IllegalArgumentException("FAN_OUT_ALL cannot activate fallback targets"); - } - if (strategy == NotificationRouteStrategy.ORDERED_FALLBACK - && (maximumTargets < 2 || maximumFallbacks < 1 || maximumFallbacks > maximumTargets - 1)) { - throw new IllegalArgumentException( - "ORDERED_FALLBACK requires 2..16 targets and 1..targetCount-1 fallbacks"); - } - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationLegacyWriterPermitCommand.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationLegacyWriterPermitCommand.java deleted file mode 100644 index 6bbb029d..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationLegacyWriterPermitCommand.java +++ /dev/null @@ -1,103 +0,0 @@ -package dev.caskeleton.application.notification; - -import dev.caskeleton.application.command.Command; -import java.time.Duration; -import java.util.Objects; -import java.util.Optional; - -/** Root-committed acquire or release of one bounded legacy writer permit. */ -public record NotificationLegacyWriterPermitCommand( - Action action, - NotificationCanonicalWriterRouteSet.RouteRevision route, - long expectedGeneration, - String transportProfileId, - String permitToken, - String holderReference, - String operationToken, - String actorReference, - NotificationReasonCode reasonCode, - Optional wireBudget) - implements Command { - - private static final Duration MAXIMUM_WIRE_BUDGET = Duration.ofSeconds(30); - - public NotificationLegacyWriterPermitCommand { - Objects.requireNonNull(action, "legacy writer permit action must be non-null"); - Objects.requireNonNull(route, "notification writer route must be non-null"); - if (expectedGeneration < 0) { - throw new IllegalArgumentException("expected writer generation must be non-negative"); - } - transportProfileId = - NotificationIntentId.requireSlug("legacy transport profile ID", transportProfileId); - permitToken = NotificationIntentId.requireOpaque("legacy writer permit token", permitToken); - holderReference = - NotificationIntentId.requireOpaque("legacy writer permit holder", holderReference); - operationToken = - NotificationIntentId.requireOpaque("legacy writer permit operation token", operationToken); - actorReference = - NotificationIntentId.requireOpaque("legacy writer permit actor", actorReference); - Objects.requireNonNull(reasonCode, "notification reason code must be non-null"); - Objects.requireNonNull(wireBudget, "wire budget container must be non-null"); - if (action == Action.ACQUIRE) { - Duration budget = - wireBudget.orElseThrow( - () -> new IllegalArgumentException("legacy permit acquire requires a wire budget")); - if (budget.isZero() || budget.isNegative() || budget.compareTo(MAXIMUM_WIRE_BUDGET) > 0) { - throw new IllegalArgumentException( - "legacy writer wire budget must be positive and at most 30 seconds"); - } - } else if (wireBudget.isPresent()) { - throw new IllegalArgumentException("legacy permit release must not carry a wire budget"); - } - } - - public static NotificationLegacyWriterPermitCommand acquire( - NotificationCanonicalWriterRouteSet.RouteRevision route, - long expectedGeneration, - String transportProfileId, - String permitToken, - String holderReference, - String operationToken, - String actorReference, - NotificationReasonCode reasonCode, - Duration wireBudget) { - return new NotificationLegacyWriterPermitCommand( - Action.ACQUIRE, - route, - expectedGeneration, - transportProfileId, - permitToken, - holderReference, - operationToken, - actorReference, - reasonCode, - Optional.of(wireBudget)); - } - - public static NotificationLegacyWriterPermitCommand release( - NotificationCanonicalWriterRouteSet.RouteRevision route, - long expectedGeneration, - String transportProfileId, - String permitToken, - String holderReference, - String operationToken, - String actorReference, - NotificationReasonCode reasonCode) { - return new NotificationLegacyWriterPermitCommand( - Action.RELEASE, - route, - expectedGeneration, - transportProfileId, - permitToken, - holderReference, - operationToken, - actorReference, - reasonCode, - Optional.empty()); - } - - public enum Action { - ACQUIRE, - RELEASE - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationLegacyWriterPermitResult.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationLegacyWriterPermitResult.java deleted file mode 100644 index 7547674a..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationLegacyWriterPermitResult.java +++ /dev/null @@ -1,45 +0,0 @@ -package dev.caskeleton.application.notification; - -import java.time.Instant; -import java.util.Objects; -import java.util.Optional; - -/** Physically committed permit facts used by the legacy wrapper's monotonic wire deadline guard. */ -public record NotificationLegacyWriterPermitResult( - Status status, - String permitToken, - Optional acquiredAt, - Optional wireDeadline, - Optional expiresAt) { - - public NotificationLegacyWriterPermitResult { - Objects.requireNonNull(status, "legacy writer permit status must be non-null"); - permitToken = NotificationIntentId.requireOpaque("legacy writer permit token", permitToken); - Objects.requireNonNull(acquiredAt, "permit acquired-at container must be non-null"); - Objects.requireNonNull(wireDeadline, "permit wire-deadline container must be non-null"); - Objects.requireNonNull(expiresAt, "permit expiry container must be non-null"); - if (status == Status.ACQUIRED) { - Instant acquired = - acquiredAt.orElseThrow( - () -> new IllegalArgumentException("acquired permit requires DB acquired-at")); - Instant deadline = - wireDeadline.orElseThrow( - () -> new IllegalArgumentException("acquired permit requires wire deadline")); - Instant expiry = - expiresAt.orElseThrow( - () -> new IllegalArgumentException("acquired permit requires expiry")); - if (deadline.isBefore(acquired) || expiry.isBefore(deadline)) { - throw new IllegalArgumentException( - "permit timestamps must satisfy acquiredAt <= wireDeadline <= expiresAt"); - } - } else if (acquiredAt.isPresent() || wireDeadline.isPresent() || expiresAt.isPresent()) { - throw new IllegalArgumentException("non-acquired permit result must not expose wire times"); - } - } - - public enum Status { - ACQUIRED, - RELEASED, - REPLAYED - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationLegacyWriterPermitUseCase.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationLegacyWriterPermitUseCase.java deleted file mode 100644 index f0452dc3..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationLegacyWriterPermitUseCase.java +++ /dev/null @@ -1,59 +0,0 @@ -package dev.caskeleton.application.notification; - -import dev.caskeleton.application.capability.Idempotency; -import dev.caskeleton.application.capability.RepositoryAccess; -import dev.caskeleton.application.capability.UseCaseCapability; -import dev.caskeleton.application.security.RequiresPermission; -import dev.caskeleton.application.transaction.TransactionMode; -import dev.caskeleton.application.transaction.TransactionPort; -import dev.caskeleton.application.usecase.CommandUseCase; -import java.time.Clock; -import java.util.Objects; - -/** Root-commits bounded legacy permit acquire/release before any caller provider I/O. */ -@RequiresPermission("notification:cutover-admit") -@UseCaseCapability( - transactionMode = TransactionMode.WRITE, - idempotency = Idempotency.IDEMPOTENT, - repositoryAccess = RepositoryAccess.WRITE_REPOSITORY, - crossTenantAdmin = true) -public class NotificationLegacyWriterPermitUseCase - implements CommandUseCase< - NotificationLegacyWriterPermitCommand, NotificationLegacyWriterPermitResult> { - - private final NotificationWriterRouteSet routes; - private final NotificationWriterCutoverPort cutover; - private final TransactionPort transactions; - private final Clock clock; - - public NotificationLegacyWriterPermitUseCase( - NotificationWriterRouteSet routes, - NotificationWriterCutoverPort cutover, - TransactionPort transactions, - Clock clock) { - this.routes = Objects.requireNonNull(routes, "notification writer route set must be non-null"); - this.cutover = - Objects.requireNonNull(cutover, "notification writer cutover port must be non-null"); - this.transactions = Objects.requireNonNull(transactions, "transaction port must be non-null"); - this.clock = Objects.requireNonNull(clock, "clock must be non-null"); - } - - @Override - public NotificationLegacyWriterPermitResult handle( - NotificationLegacyWriterPermitCommand command) { - Objects.requireNonNull(command, "legacy writer permit command must be non-null"); - NotificationWriterRouteSet.RouteProfile route = routes.requireRoute(command.route()); - NotificationWriterRouteSet.TransportProfile profile = - route.requireProfile(command.transportProfileId()); - if (command.action() == NotificationLegacyWriterPermitCommand.Action.ACQUIRE - && !profile.activeAdmissionProfile()) { - throw new IllegalArgumentException( - "new legacy permit acquire requires the active admission transport profile"); - } - return transactions.inRootWrite( - () -> - command.action() == NotificationLegacyWriterPermitCommand.Action.ACQUIRE - ? cutover.acquireLegacyPermit(command, route, clock.instant()) - : cutover.releaseLegacyPermit(command, route, clock.instant())); - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationMaintenanceCommand.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationMaintenanceCommand.java deleted file mode 100644 index cc979963..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationMaintenanceCommand.java +++ /dev/null @@ -1,21 +0,0 @@ -package dev.caskeleton.application.notification; - -import dev.caskeleton.application.command.Command; - -/** Bounded retention and redaction mutation request. */ -public record NotificationMaintenanceCommand( - int maximumExpiredIntents, int maximumPayloadRedactions, int maximumExpiredReceipts) - implements Command { - - public NotificationMaintenanceCommand { - long total = (long) maximumExpiredIntents + maximumPayloadRedactions + maximumExpiredReceipts; - if (maximumExpiredIntents < 0 - || maximumPayloadRedactions < 0 - || maximumExpiredReceipts < 0 - || total < 1 - || total > 100) { - throw new IllegalArgumentException( - "notification maintenance total mutation bound must be in 1..100"); - } - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationMaintenanceResult.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationMaintenanceResult.java deleted file mode 100644 index 13edab51..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationMaintenanceResult.java +++ /dev/null @@ -1,16 +0,0 @@ -package dev.caskeleton.application.notification; - -/** Bounded non-sensitive maintenance outcome. */ -public record NotificationMaintenanceResult( - int expiredIntentCount, int redactedPayloadCount, int expiredReceiptCount) { - - public NotificationMaintenanceResult { - long total = (long) expiredIntentCount + redactedPayloadCount + expiredReceiptCount; - if (expiredIntentCount < 0 - || redactedPayloadCount < 0 - || expiredReceiptCount < 0 - || total > 100) { - throw new IllegalArgumentException("notification maintenance result must total 0..100"); - } - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationMaintenanceStorePort.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationMaintenanceStorePort.java deleted file mode 100644 index 5379667b..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationMaintenanceStorePort.java +++ /dev/null @@ -1,23 +0,0 @@ -package dev.caskeleton.application.notification; - -import java.time.Instant; - -/** Performs one bounded local retention/redaction mutation batch. */ -@FunctionalInterface -public interface NotificationMaintenanceStorePort { - - MutationResult maintain(NotificationMaintenanceCommand command, Instant now); - - record MutationResult(int expiredIntentCount, int redactedPayloadCount, int expiredReceiptCount) { - - public MutationResult { - long total = (long) expiredIntentCount + redactedPayloadCount + expiredReceiptCount; - if (expiredIntentCount < 0 - || redactedPayloadCount < 0 - || expiredReceiptCount < 0 - || total > 100) { - throw new IllegalArgumentException("notification maintenance mutations must total 0..100"); - } - } - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationMaintenanceUseCase.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationMaintenanceUseCase.java deleted file mode 100644 index 7772f8ee..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationMaintenanceUseCase.java +++ /dev/null @@ -1,44 +0,0 @@ -package dev.caskeleton.application.notification; - -import dev.caskeleton.application.capability.Idempotency; -import dev.caskeleton.application.capability.RepositoryAccess; -import dev.caskeleton.application.capability.UseCaseCapability; -import dev.caskeleton.application.security.RequiresPermission; -import dev.caskeleton.application.transaction.TransactionMode; -import dev.caskeleton.application.transaction.TransactionPort; -import dev.caskeleton.application.usecase.CommandUseCase; -import java.time.Clock; -import java.util.Objects; - -/** Runs one bounded notification retention/redaction mutation in a short write transaction. */ -@RequiresPermission("notification:maintain") -@UseCaseCapability( - transactionMode = TransactionMode.WRITE, - idempotency = Idempotency.IDEMPOTENT, - repositoryAccess = RepositoryAccess.WRITE_REPOSITORY, - crossTenantAdmin = true) -public class NotificationMaintenanceUseCase - implements CommandUseCase { - - private final NotificationMaintenanceStorePort store; - private final TransactionPort transactions; - private final Clock clock; - - public NotificationMaintenanceUseCase( - NotificationMaintenanceStorePort store, TransactionPort transactions, Clock clock) { - this.store = Objects.requireNonNull(store, "notification maintenance store must be non-null"); - this.transactions = Objects.requireNonNull(transactions, "transaction port must be non-null"); - this.clock = Objects.requireNonNull(clock, "clock must be non-null"); - } - - @Override - public NotificationMaintenanceResult handle(NotificationMaintenanceCommand command) { - Objects.requireNonNull(command, "notification maintenance command must be non-null"); - NotificationMaintenanceStorePort.MutationResult mutation = - transactions.inWrite(() -> store.maintain(command, clock.instant())); - return new NotificationMaintenanceResult( - mutation.expiredIntentCount(), - mutation.redactedPayloadCount(), - mutation.expiredReceiptCount()); - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationMode.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationMode.java deleted file mode 100644 index d9bb2884..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationMode.java +++ /dev/null @@ -1,7 +0,0 @@ -package dev.caskeleton.application.notification; - -/** Code-owned delivery durability contract. */ -public enum NotificationMode { - BEST_EFFORT_INLINE, - DURABLE_ASYNC -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationOperationsSnapshot.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationOperationsSnapshot.java deleted file mode 100644 index df256e39..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationOperationsSnapshot.java +++ /dev/null @@ -1,57 +0,0 @@ -package dev.caskeleton.application.notification; - -import java.time.Instant; -import java.util.List; -import java.util.Objects; - -/** Bounded non-sensitive operational aggregate returned through the application query boundary. */ -public record NotificationOperationsSnapshot( - Instant observedAt, - long pendingIntentCount, - long parkedDeliveryCount, - long orphanReceiptCount, - long activeLegacyPermitCount, - List writerRoutes) { - - private static final long MAXIMUM_COUNT = 1_000_000_000L; - - public NotificationOperationsSnapshot { - Objects.requireNonNull(observedAt, "notification snapshot time must be non-null"); - validateCount(pendingIntentCount); - validateCount(parkedDeliveryCount); - validateCount(orphanReceiptCount); - validateCount(activeLegacyPermitCount); - writerRoutes = - List.copyOf( - Objects.requireNonNull(writerRoutes, "writer route snapshots must be non-null")); - if (writerRoutes.size() > 100) { - throw new IllegalArgumentException("writer route snapshot exceeds 100 entries"); - } - } - - private static void validateCount(long count) { - if (count < 0 || count > MAXIMUM_COUNT) { - throw new IllegalArgumentException("notification operation count is outside 0..1000000000"); - } - } - - public record RouteWriterStatus( - NotificationRouteId routeId, - int routeRevision, - NotificationWriterOwnership owner, - long generation, - boolean draining) { - - public RouteWriterStatus { - Objects.requireNonNull(routeId, "notification route ID must be non-null"); - Objects.requireNonNull(owner, "notification writer owner must be non-null"); - if (routeRevision < 1 || generation < 0) { - throw new IllegalArgumentException( - "writer route revision must be positive and generation non-negative"); - } - if (draining && owner != NotificationWriterOwnership.LEGACY) { - throw new IllegalArgumentException("only LEGACY writer ownership may be draining"); - } - } - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationOperationsSnapshotPort.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationOperationsSnapshotPort.java deleted file mode 100644 index 8c74e79d..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationOperationsSnapshotPort.java +++ /dev/null @@ -1,8 +0,0 @@ -package dev.caskeleton.application.notification; - -/** Loads bounded non-sensitive operational aggregates from the durable store. */ -@FunctionalInterface -public interface NotificationOperationsSnapshotPort { - - NotificationOperationsSnapshot load(NotificationOperationsSnapshotQuery query); -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationOperationsSnapshotQuery.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationOperationsSnapshotQuery.java deleted file mode 100644 index ac11509b..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationOperationsSnapshotQuery.java +++ /dev/null @@ -1,13 +0,0 @@ -package dev.caskeleton.application.notification; - -import dev.caskeleton.application.query.Query; - -/** Requests at most a bounded number of route writer status rows. */ -public record NotificationOperationsSnapshotQuery(int maximumRoutes) implements Query { - - public NotificationOperationsSnapshotQuery { - if (maximumRoutes < 1 || maximumRoutes > 100) { - throw new IllegalArgumentException("maximum notification routes must be in 1..100"); - } - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationOperationsSnapshotUseCase.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationOperationsSnapshotUseCase.java deleted file mode 100644 index 1d82fd46..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationOperationsSnapshotUseCase.java +++ /dev/null @@ -1,37 +0,0 @@ -package dev.caskeleton.application.notification; - -import dev.caskeleton.application.capability.Idempotency; -import dev.caskeleton.application.capability.RepositoryAccess; -import dev.caskeleton.application.capability.UseCaseCapability; -import dev.caskeleton.application.security.RequiresPermission; -import dev.caskeleton.application.transaction.TransactionMode; -import dev.caskeleton.application.transaction.TransactionPort; -import dev.caskeleton.application.usecase.QueryUseCase; -import java.util.Objects; - -/** Application query boundary for bounded notification operations visibility. */ -@RequiresPermission("notification:observe") -@UseCaseCapability( - transactionMode = TransactionMode.READ_ONLY, - idempotency = Idempotency.IDEMPOTENT, - repositoryAccess = RepositoryAccess.READ_REPOSITORY, - crossTenantAdmin = true) -public class NotificationOperationsSnapshotUseCase - implements QueryUseCase { - - private final NotificationOperationsSnapshotPort snapshots; - private final TransactionPort transactions; - - public NotificationOperationsSnapshotUseCase( - NotificationOperationsSnapshotPort snapshots, TransactionPort transactions) { - this.snapshots = - Objects.requireNonNull(snapshots, "notification operations snapshot port must be non-null"); - this.transactions = Objects.requireNonNull(transactions, "transaction port must be non-null"); - } - - @Override - public NotificationOperationsSnapshot handle(NotificationOperationsSnapshotQuery query) { - Objects.requireNonNull(query, "notification operations snapshot query must be non-null"); - return transactions.inRead(() -> snapshots.load(query)); - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationPlanPort.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationPlanPort.java deleted file mode 100644 index 95a6d47c..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationPlanPort.java +++ /dev/null @@ -1,8 +0,0 @@ -package dev.caskeleton.application.notification; - -/** Resolves a feature-owned draft into a provider-neutral immutable application plan. */ -@FunctionalInterface -public interface NotificationPlanPort { - - NotificationPlanningResult plan(NotificationIntentDraft draft); -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationPlanningResult.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationPlanningResult.java deleted file mode 100644 index 28ee6914..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationPlanningResult.java +++ /dev/null @@ -1,32 +0,0 @@ -package dev.caskeleton.application.notification; - -import java.util.Objects; - -/** Closed result of compiling a feature draft without exposing adapter binding types. */ -public sealed interface NotificationPlanningResult - permits NotificationPlanningResult.Planned, - NotificationPlanningResult.Rejected, - NotificationPlanningResult.CapabilityUnavailable { - - record Planned(NotificationFrozenPlan plan) implements NotificationPlanningResult { - - public Planned { - Objects.requireNonNull(plan, "notification frozen plan must be non-null"); - } - } - - record Rejected(NotificationReasonCode reasonCode) implements NotificationPlanningResult { - - public Rejected { - Objects.requireNonNull(reasonCode, "notification reason code must be non-null"); - } - } - - record CapabilityUnavailable(NotificationReasonCode reasonCode) - implements NotificationPlanningResult { - - public CapabilityUnavailable { - Objects.requireNonNull(reasonCode, "notification reason code must be non-null"); - } - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationProviderAttemptPort.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationProviderAttemptPort.java deleted file mode 100644 index 93094979..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationProviderAttemptPort.java +++ /dev/null @@ -1,8 +0,0 @@ -package dev.caskeleton.application.notification; - -/** Performs one previously authorized provider call and returns only a classified outcome. */ -@FunctionalInterface -public interface NotificationProviderAttemptPort { - - ProviderAttemptOutcome attempt(NotificationDeliveryStorePort.AuthorizedAttempt attempt); -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationProviderCapabilityDescriptor.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationProviderCapabilityDescriptor.java deleted file mode 100644 index eedf4d8c..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationProviderCapabilityDescriptor.java +++ /dev/null @@ -1,41 +0,0 @@ -package dev.caskeleton.application.notification; - -import java.util.Collections; -import java.util.EnumSet; -import java.util.Objects; -import java.util.Set; - -/** Provider-neutral capability facts consumed by the pure compatibility validator. */ -public record NotificationProviderCapabilityDescriptor( - String capabilityReference, - NotificationChannel channel, - Set supportedModes, - boolean receiptSupported, - boolean reconciliationSupported, - boolean hiddenRetriesControlled, - int maximumTargets, - int maximumPayloadBytes) { - - public NotificationProviderCapabilityDescriptor { - capabilityReference = - NotificationIntentId.requireOpaque( - "notification provider capability reference", capabilityReference); - Objects.requireNonNull(channel, "notification provider channel must be non-null"); - Objects.requireNonNull(supportedModes, "notification provider modes must be non-null"); - EnumSet modes = - supportedModes.isEmpty() - ? EnumSet.noneOf(NotificationMode.class) - : EnumSet.copyOf(supportedModes); - if (modes.isEmpty()) { - throw new IllegalArgumentException("notification provider must support at least one mode"); - } - supportedModes = Collections.unmodifiableSet(modes); - if (maximumTargets < 1 || maximumTargets > 16) { - throw new IllegalArgumentException("notification provider maximum targets must be in 1..16"); - } - if (maximumPayloadBytes < 1 || maximumPayloadBytes > 10_000_000) { - throw new IllegalArgumentException( - "notification provider maximum payload must be in 1..10000000 bytes"); - } - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationReasonCode.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationReasonCode.java deleted file mode 100644 index 11322bf8..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationReasonCode.java +++ /dev/null @@ -1,12 +0,0 @@ -package dev.caskeleton.application.notification; - -/** Bounded stable operational reason code; never a provider error body or SDK exception message. */ -public record NotificationReasonCode(String value) { - - public NotificationReasonCode { - if (value == null || !value.matches("[A-Z][A-Z0-9_]{0,63}")) { - throw new IllegalArgumentException( - "notification reason code must match [A-Z][A-Z0-9_]{0,63}"); - } - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationReceiptEventId.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationReceiptEventId.java deleted file mode 100644 index dd875177..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationReceiptEventId.java +++ /dev/null @@ -1,9 +0,0 @@ -package dev.caskeleton.application.notification; - -/** Opaque identity used to deduplicate one normalized provider receipt event. */ -public record NotificationReceiptEventId(String value) { - - public NotificationReceiptEventId { - value = NotificationIntentId.requireOpaque("receiptEventId", value); - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationReceiptFact.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationReceiptFact.java deleted file mode 100644 index 7faa18da..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationReceiptFact.java +++ /dev/null @@ -1,34 +0,0 @@ -package dev.caskeleton.application.notification; - -import java.time.Instant; -import java.util.Objects; - -/** One normalized, immutable provider feedback fact. */ -public record NotificationReceiptFact( - Type type, BounceClass bounceClass, NotificationReasonCode reasonCode, Instant occurredAt) { - - public NotificationReceiptFact { - Objects.requireNonNull(type, "notification receipt type must be non-null"); - Objects.requireNonNull(bounceClass, "notification bounce class must be non-null"); - Objects.requireNonNull(reasonCode, "notification reason code must be non-null"); - Objects.requireNonNull(occurredAt, "notification receipt occurrence time must be non-null"); - if ((type == Type.BOUNCE) != (bounceClass != BounceClass.NONE)) { - throw new IllegalArgumentException( - "BOUNCE requires HARD or SOFT classification and other facts require NONE"); - } - } - - public enum Type { - SEND, - DELIVERY, - BOUNCE, - COMPLAINT, - DELIVERY_DELAY - } - - public enum BounceClass { - NONE, - SOFT, - HARD - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationReceiptIngressCapabilityDescriptor.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationReceiptIngressCapabilityDescriptor.java deleted file mode 100644 index bae4f331..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationReceiptIngressCapabilityDescriptor.java +++ /dev/null @@ -1,25 +0,0 @@ -package dev.caskeleton.application.notification; - -import java.util.Collections; -import java.util.EnumSet; -import java.util.Objects; -import java.util.Set; - -/** Authenticated normalized receipt-ingress capabilities for one channel. */ -public record NotificationReceiptIngressCapabilityDescriptor( - NotificationChannel channel, - boolean enabled, - boolean authenticated, - Set supportedFactTypes) { - - public NotificationReceiptIngressCapabilityDescriptor { - Objects.requireNonNull(channel, "notification receipt ingress channel must be non-null"); - Objects.requireNonNull( - supportedFactTypes, "notification receipt ingress fact types must be non-null"); - EnumSet factTypes = - supportedFactTypes.isEmpty() - ? EnumSet.noneOf(NotificationReceiptFact.Type.class) - : EnumSet.copyOf(supportedFactTypes); - supportedFactTypes = Collections.unmodifiableSet(factTypes); - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationReceiptProjection.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationReceiptProjection.java deleted file mode 100644 index 079d337a..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationReceiptProjection.java +++ /dev/null @@ -1,70 +0,0 @@ -package dev.caskeleton.application.notification; - -import java.time.Instant; -import java.util.List; -import java.util.Objects; - -/** Order-independent orthogonal projection derived only from immutable receipt facts. */ -public record NotificationReceiptProjection( - boolean submissionAccepted, - boolean delivered, - boolean softBounced, - boolean hardBounced, - boolean complained, - boolean deliveryDelayed, - Instant latestFactAt, - int factCount) { - - public NotificationReceiptProjection { - Objects.requireNonNull(latestFactAt, "latest receipt fact time must be non-null"); - if (factCount < 1 || factCount > 100) { - throw new IllegalArgumentException("receipt projection fact count must be in 1..100"); - } - if ((delivered || softBounced || hardBounced || complained || deliveryDelayed) - && !submissionAccepted) { - throw new IllegalArgumentException( - "delivery feedback cannot erase or contradict provider acceptance"); - } - } - - public static NotificationReceiptProjection reduce(List facts) { - Objects.requireNonNull(facts, "notification receipt facts must be non-null"); - List immutableFacts = List.copyOf(facts); - if (immutableFacts.isEmpty() || immutableFacts.size() > 100) { - throw new IllegalArgumentException("notification receipt facts must contain 1..100 entries"); - } - - boolean accepted = false; - boolean delivered = false; - boolean softBounced = false; - boolean hardBounced = false; - boolean complained = false; - boolean delayed = false; - Instant latest = Instant.MIN; - for (NotificationReceiptFact fact : immutableFacts) { - Objects.requireNonNull(fact, "notification receipt fact must be non-null"); - accepted = true; - delivered |= fact.type() == NotificationReceiptFact.Type.DELIVERY; - softBounced |= - fact.type() == NotificationReceiptFact.Type.BOUNCE - && fact.bounceClass() == NotificationReceiptFact.BounceClass.SOFT; - hardBounced |= - fact.type() == NotificationReceiptFact.Type.BOUNCE - && fact.bounceClass() == NotificationReceiptFact.BounceClass.HARD; - complained |= fact.type() == NotificationReceiptFact.Type.COMPLAINT; - delayed |= fact.type() == NotificationReceiptFact.Type.DELIVERY_DELAY; - if (fact.occurredAt().isAfter(latest)) { - latest = fact.occurredAt(); - } - } - return new NotificationReceiptProjection( - accepted, - delivered, - softBounced, - hardBounced, - complained, - delayed, - latest, - immutableFacts.size()); - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationReceiptStorePort.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationReceiptStorePort.java deleted file mode 100644 index 18269be6..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationReceiptStorePort.java +++ /dev/null @@ -1,52 +0,0 @@ -package dev.caskeleton.application.notification; - -import java.util.List; -import java.util.Objects; - -/** Durable receipt inbox and delivery projection mutation boundary. */ -public interface NotificationReceiptStorePort { - - AppendResult appendIfAbsent(NormalizedNotificationReceiptCommand command); - - void saveProjection(NotificationDeliveryId deliveryId, NotificationReceiptProjection projection); - - sealed interface AppendResult permits Appended, Duplicate {} - - record Appended(ReceiptAggregate aggregate) implements AppendResult { - - public Appended { - Objects.requireNonNull(aggregate, "notification receipt aggregate must be non-null"); - } - } - - record Duplicate(NotificationReceiptProjection projection) implements AppendResult { - - public Duplicate { - Objects.requireNonNull(projection, "notification receipt projection must be non-null"); - } - } - - record ReceiptAggregate( - NotificationDeliveryId deliveryId, - NotificationRecipientReference recipient, - List facts) { - - public ReceiptAggregate { - Objects.requireNonNull(deliveryId, "notification delivery ID must be non-null"); - Objects.requireNonNull(recipient, "notification recipient reference must be non-null"); - facts = - List.copyOf(Objects.requireNonNull(facts, "notification receipt facts must be non-null")); - if (facts.isEmpty() || facts.size() > 100) { - throw new IllegalArgumentException( - "notification receipt aggregate must contain 1..100 facts"); - } - } - - @Override - public String toString() { - return "ReceiptAggregate[deliveryId=, recipient=, factCount=" - + facts.size() - + "]"; - } - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationRecipientReference.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationRecipientReference.java deleted file mode 100644 index 3b18c233..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationRecipientReference.java +++ /dev/null @@ -1,8 +0,0 @@ -package dev.caskeleton.application.notification; - -/** Channel-typed opaque recipient reference; raw addresses are forbidden at this boundary. */ -public sealed interface NotificationRecipientReference - permits EmailRecipientReference, SlackAudienceReference { - - NotificationChannel channel(); -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationReconciliationPort.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationReconciliationPort.java deleted file mode 100644 index ebd32079..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationReconciliationPort.java +++ /dev/null @@ -1,19 +0,0 @@ -package dev.caskeleton.application.notification; - -import java.util.Objects; - -/** Performs one bounded provider reconciliation outside any database transaction. */ -@FunctionalInterface -public interface NotificationReconciliationPort { - - ReconciliationOutcome reconcile(NotificationDeliveryStorePort.ReconciliationClaim claim); - - record ReconciliationOutcome( - SubmissionCertainty submissionCertainty, NotificationReasonCode reasonCode) { - - public ReconciliationOutcome { - Objects.requireNonNull(submissionCertainty, "submission certainty must be non-null"); - Objects.requireNonNull(reasonCode, "notification reason code must be non-null"); - } - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationRequestResult.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationRequestResult.java deleted file mode 100644 index eff18bd5..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationRequestResult.java +++ /dev/null @@ -1,71 +0,0 @@ -package dev.caskeleton.application.notification; - -import java.util.List; -import java.util.Objects; - -/** Closed result union for a notification request; append is not delivery success. */ -public sealed interface NotificationRequestResult - permits NotificationRequestResult.InlineCompleted, - NotificationRequestResult.AppendedDurably, - NotificationRequestResult.DuplicateExistingIntent, - NotificationRequestResult.RejectedByBusinessPolicy, - NotificationRequestResult.RejectedInvalidRequest, - NotificationRequestResult.CapabilityUnavailable { - - record InlineCompleted(NotificationIntentId intentId, List outcomes) - implements NotificationRequestResult { - - public InlineCompleted { - Objects.requireNonNull(intentId, "notification intent ID must be non-null"); - Objects.requireNonNull(outcomes, "inline outcomes must be non-null"); - outcomes = List.copyOf(outcomes); - if (outcomes.isEmpty() || outcomes.size() > 16) { - throw new IllegalArgumentException("inline outcomes must contain 1..16 targets"); - } - long distinctOrdinals = - outcomes.stream().map(TargetAttemptOutcome::targetOrdinal).distinct().count(); - if (distinctOrdinals != outcomes.size()) { - throw new IllegalArgumentException("inline target ordinals must be unique"); - } - } - } - - record AppendedDurably(NotificationIntentId intentId) implements NotificationRequestResult { - - public AppendedDurably { - Objects.requireNonNull(intentId, "notification intent ID must be non-null"); - } - } - - record DuplicateExistingIntent(NotificationIntentId intentId) - implements NotificationRequestResult { - - public DuplicateExistingIntent { - Objects.requireNonNull(intentId, "notification intent ID must be non-null"); - } - } - - record RejectedByBusinessPolicy(NotificationReasonCode reasonCode) - implements NotificationRequestResult { - - public RejectedByBusinessPolicy { - Objects.requireNonNull(reasonCode, "notification reason code must be non-null"); - } - } - - record RejectedInvalidRequest(NotificationReasonCode reasonCode) - implements NotificationRequestResult { - - public RejectedInvalidRequest { - Objects.requireNonNull(reasonCode, "notification reason code must be non-null"); - } - } - - record CapabilityUnavailable(NotificationReasonCode reasonCode) - implements NotificationRequestResult { - - public CapabilityUnavailable { - Objects.requireNonNull(reasonCode, "notification reason code must be non-null"); - } - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationRouteId.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationRouteId.java deleted file mode 100644 index bd153861..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationRouteId.java +++ /dev/null @@ -1,9 +0,0 @@ -package dev.caskeleton.application.notification; - -/** Closed-catalog logical technical route; never a provider or endpoint identifier. */ -public record NotificationRouteId(String value) { - - public NotificationRouteId { - value = NotificationIntentId.requireSlug("routeId", value); - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationRouteStrategy.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationRouteStrategy.java deleted file mode 100644 index c7be8612..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationRouteStrategy.java +++ /dev/null @@ -1,8 +0,0 @@ -package dev.caskeleton.application.notification; - -/** Closed provider-leg expansion strategy for one logical recipient. */ -public enum NotificationRouteStrategy { - SINGLE, - FAN_OUT_ALL, - ORDERED_FALLBACK -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationSignedEvidenceHeader.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationSignedEvidenceHeader.java deleted file mode 100644 index 969287dd..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationSignedEvidenceHeader.java +++ /dev/null @@ -1,281 +0,0 @@ -package dev.caskeleton.application.notification; - -import java.time.Duration; -import java.time.Instant; -import java.util.Arrays; -import java.util.Objects; - -/** - * Bounded immutable signed-evidence header; cryptographic verification belongs to verifier ports. - */ -public final class NotificationSignedEvidenceHeader { - - private final String canonicalProfile; - private final byte[] canonicalPayload; - private final byte[] signature; - private final String signatureAlgorithm; - private final String issuerKeyId; - private final byte[] issuerPublicKeySpki; - private final String issuerPublicKeyDigest; - private final NotificationEvidenceTrustSnapshot trustSnapshot; - private final Instant issuedAt; - private final Instant expiresAt; - private final Duration allowedClockSkew; - private final Duration acceptanceMargin; - private final String environmentId; - private final String databaseId; - private final String artifactId; - private final String consumerInventoryId; - private final String providerCallLedgerId; - private final String providerCallLedgerSnapshot; - private final int childCount; - private final String childSetDigest; - - public NotificationSignedEvidenceHeader( - String canonicalProfile, - byte[] canonicalPayload, - byte[] signature, - String signatureAlgorithm, - String issuerKeyId, - byte[] issuerPublicKeySpki, - String issuerPublicKeyDigest, - NotificationEvidenceTrustSnapshot trustSnapshot, - Instant issuedAt, - Instant expiresAt, - Duration allowedClockSkew, - Duration acceptanceMargin, - String environmentId, - String databaseId, - String artifactId, - String consumerInventoryId, - String providerCallLedgerId, - String providerCallLedgerSnapshot, - int childCount, - String childSetDigest) { - this.canonicalProfile = - NotificationIntentId.requireSlug("signed evidence canonical profile", canonicalProfile); - this.canonicalPayload = copyBounded("canonical evidence payload", canonicalPayload, 1, 65_536); - this.signature = copyBounded("evidence signature", signature, 64, 128); - if (!"Ed25519".equals(signatureAlgorithm)) { - throw new IllegalArgumentException("signed evidence algorithm must be Ed25519"); - } - this.signatureAlgorithm = signatureAlgorithm; - this.issuerKeyId = NotificationIntentId.requireOpaque("evidence issuer key ID", issuerKeyId); - this.issuerPublicKeySpki = - copyBounded("evidence issuer public-key SPKI", issuerPublicKeySpki, 32, 1_024); - this.issuerPublicKeyDigest = - InitializeNotificationWriterFencesCommand.requireDigest(issuerPublicKeyDigest); - this.trustSnapshot = - Objects.requireNonNull(trustSnapshot, "evidence trust snapshot must be non-null"); - if (!this.issuerPublicKeyDigest.equals(trustSnapshot.issuerKeyDigest())) { - throw new IllegalArgumentException("evidence issuer key digest must match trust snapshot"); - } - this.issuedAt = Objects.requireNonNull(issuedAt, "evidence issued-at must be non-null"); - this.expiresAt = Objects.requireNonNull(expiresAt, "evidence expires-at must be non-null"); - this.allowedClockSkew = - Objects.requireNonNull(allowedClockSkew, "evidence allowed clock skew must be non-null"); - this.acceptanceMargin = - Objects.requireNonNull(acceptanceMargin, "evidence acceptance margin must be non-null"); - if (!expiresAt.isAfter(issuedAt) - || allowedClockSkew.isNegative() - || allowedClockSkew.compareTo(Duration.ofMinutes(5)) > 0 - || acceptanceMargin.isNegative() - || acceptanceMargin.compareTo(Duration.ofMinutes(5)) > 0 - || !expiresAt.minus(acceptanceMargin).isAfter(issuedAt.minus(allowedClockSkew))) { - throw new IllegalArgumentException("signed evidence acceptance window is invalid"); - } - this.environmentId = - NotificationIntentId.requireOpaque("evidence environment identity", environmentId); - this.databaseId = NotificationIntentId.requireOpaque("evidence database identity", databaseId); - this.artifactId = NotificationIntentId.requireOpaque("evidence artifact identity", artifactId); - this.consumerInventoryId = - NotificationIntentId.requireOpaque( - "evidence consumer inventory identity", consumerInventoryId); - this.providerCallLedgerId = - NotificationIntentId.requireOpaque( - "evidence provider-call ledger identity", providerCallLedgerId); - this.providerCallLedgerSnapshot = - NotificationIntentId.requireOpaque( - "evidence provider-call ledger snapshot", providerCallLedgerSnapshot); - if (childCount < 0 || childCount > 1_000) { - throw new IllegalArgumentException("signed evidence child count must be in 0..1000"); - } - this.childCount = childCount; - this.childSetDigest = InitializeNotificationWriterFencesCommand.requireDigest(childSetDigest); - } - - public String canonicalProfile() { - return canonicalProfile; - } - - public byte[] canonicalPayload() { - return Arrays.copyOf(canonicalPayload, canonicalPayload.length); - } - - public byte[] signature() { - return Arrays.copyOf(signature, signature.length); - } - - public String signatureAlgorithm() { - return signatureAlgorithm; - } - - public String issuerKeyId() { - return issuerKeyId; - } - - public byte[] issuerPublicKeySpki() { - return Arrays.copyOf(issuerPublicKeySpki, issuerPublicKeySpki.length); - } - - public String issuerPublicKeyDigest() { - return issuerPublicKeyDigest; - } - - public NotificationEvidenceTrustSnapshot trustSnapshot() { - return trustSnapshot; - } - - public Instant issuedAt() { - return issuedAt; - } - - public Instant expiresAt() { - return expiresAt; - } - - public Duration allowedClockSkew() { - return allowedClockSkew; - } - - public Duration acceptanceMargin() { - return acceptanceMargin; - } - - public String environmentId() { - return environmentId; - } - - public String databaseId() { - return databaseId; - } - - public String artifactId() { - return artifactId; - } - - public String consumerInventoryId() { - return consumerInventoryId; - } - - public String providerCallLedgerId() { - return providerCallLedgerId; - } - - public String providerCallLedgerSnapshot() { - return providerCallLedgerSnapshot; - } - - public int childCount() { - return childCount; - } - - public String childSetDigest() { - return childSetDigest; - } - - @Override - public boolean equals(Object candidate) { - if (this == candidate) { - return true; - } - if (!(candidate instanceof NotificationSignedEvidenceHeader other)) { - return false; - } - return childCount == other.childCount - && canonicalProfile.equals(other.canonicalProfile) - && Arrays.equals(canonicalPayload, other.canonicalPayload) - && Arrays.equals(signature, other.signature) - && signatureAlgorithm.equals(other.signatureAlgorithm) - && issuerKeyId.equals(other.issuerKeyId) - && Arrays.equals(issuerPublicKeySpki, other.issuerPublicKeySpki) - && issuerPublicKeyDigest.equals(other.issuerPublicKeyDigest) - && trustSnapshot.equals(other.trustSnapshot) - && issuedAt.equals(other.issuedAt) - && expiresAt.equals(other.expiresAt) - && allowedClockSkew.equals(other.allowedClockSkew) - && acceptanceMargin.equals(other.acceptanceMargin) - && environmentId.equals(other.environmentId) - && databaseId.equals(other.databaseId) - && artifactId.equals(other.artifactId) - && consumerInventoryId.equals(other.consumerInventoryId) - && providerCallLedgerId.equals(other.providerCallLedgerId) - && providerCallLedgerSnapshot.equals(other.providerCallLedgerSnapshot) - && childSetDigest.equals(other.childSetDigest); - } - - @Override - public int hashCode() { - int result = - Objects.hash( - canonicalProfile, - signatureAlgorithm, - issuerKeyId, - issuerPublicKeyDigest, - trustSnapshot, - issuedAt, - expiresAt, - allowedClockSkew, - acceptanceMargin, - environmentId, - databaseId, - artifactId, - consumerInventoryId, - providerCallLedgerId, - providerCallLedgerSnapshot, - childCount, - childSetDigest); - result = 31 * result + Arrays.hashCode(canonicalPayload); - result = 31 * result + Arrays.hashCode(signature); - result = 31 * result + Arrays.hashCode(issuerPublicKeySpki); - return result; - } - - @Override - public String toString() { - return "NotificationSignedEvidenceHeader[canonicalProfile=" - + canonicalProfile - + ", canonicalPayload=, signature=, signatureAlgorithm=" - + signatureAlgorithm - + ", issuerKeyId=" - + issuerKeyId - + ", issuerPublicKeySpki=, issuerPublicKeyDigest=" - + issuerPublicKeyDigest - + ", trustSnapshot=" - + trustSnapshot - + ", issuedAt=" - + issuedAt - + ", expiresAt=" - + expiresAt - + ", consumerInventoryId=" - + consumerInventoryId - + ", providerCallLedgerId=" - + providerCallLedgerId - + ", providerCallLedgerSnapshot=" - + providerCallLedgerSnapshot - + ", childCount=" - + childCount - + ", childSetDigest=" - + childSetDigest - + "]"; - } - - private static byte[] copyBounded( - String field, byte[] value, int minimumLength, int maximumLength) { - if (value == null || value.length < minimumLength || value.length > maximumLength) { - throw new IllegalArgumentException( - field + " length must be in " + minimumLength + ".." + maximumLength); - } - return Arrays.copyOf(value, value.length); - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationStoreCapabilityDescriptor.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationStoreCapabilityDescriptor.java deleted file mode 100644 index 8f32c71d..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationStoreCapabilityDescriptor.java +++ /dev/null @@ -1,41 +0,0 @@ -package dev.caskeleton.application.notification; - -import java.util.Collections; -import java.util.HashSet; -import java.util.Objects; -import java.util.Set; -import java.util.TreeSet; - -/** Durable store capabilities and retained frozen revisions visible to application validation. */ -public record NotificationStoreCapabilityDescriptor( - boolean durableIntentStore, - boolean attemptJournal, - boolean receiptInbox, - int maximumBatch, - Set availablePolicyRevisions, - Set availableTemplateRevisions) { - - public NotificationStoreCapabilityDescriptor { - if (maximumBatch < 1 || maximumBatch > 100) { - throw new IllegalArgumentException("notification store maximum batch must be in 1..100"); - } - Objects.requireNonNull(availablePolicyRevisions, "available policy revisions must be non-null"); - TreeSet policies = new TreeSet<>(availablePolicyRevisions); - if (policies.isEmpty() - || policies.size() > 100 - || policies.stream().anyMatch(revision -> revision == null || revision < 1)) { - throw new IllegalArgumentException( - "available policy revisions must contain 1..100 positive revisions"); - } - availablePolicyRevisions = Collections.unmodifiableSet(policies); - Objects.requireNonNull( - availableTemplateRevisions, "available template revisions must be non-null"); - HashSet templates = new HashSet<>(availableTemplateRevisions); - if (templates.isEmpty() - || templates.size() > 100 - || templates.stream().anyMatch(Objects::isNull)) { - throw new IllegalArgumentException("available template revisions must contain 1..100 values"); - } - availableTemplateRevisions = Collections.unmodifiableSet(templates); - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationTechnicalSuppressionPort.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationTechnicalSuppressionPort.java deleted file mode 100644 index 10d7b26f..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationTechnicalSuppressionPort.java +++ /dev/null @@ -1,32 +0,0 @@ -package dev.caskeleton.application.notification; - -import java.time.Instant; -import java.util.Objects; - -/** Persists technical suppression caused by hard bounce or complaint, not business consent. */ -@FunctionalInterface -public interface NotificationTechnicalSuppressionPort { - - void suppress(SuppressionMutation mutation); - - record SuppressionMutation( - NotificationRecipientReference recipient, - NotificationReasonCode reasonCode, - Instant suppressedAt) { - - public SuppressionMutation { - Objects.requireNonNull(recipient, "notification recipient reference must be non-null"); - Objects.requireNonNull(reasonCode, "notification reason code must be non-null"); - Objects.requireNonNull(suppressedAt, "notification suppression time must be non-null"); - } - - @Override - public String toString() { - return "SuppressionMutation[recipient=, reasonCode=" - + reasonCode - + ", suppressedAt=" - + suppressedAt - + "]"; - } - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationTemplateParameters.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationTemplateParameters.java deleted file mode 100644 index eeeee958..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationTemplateParameters.java +++ /dev/null @@ -1,36 +0,0 @@ -package dev.caskeleton.application.notification; - -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Objects; - -/** Bounded, immutable and redacted template parameter bag over a closed scalar value set. */ -public record NotificationTemplateParameters(Map values) { - - private static final int MAXIMUM_PARAMETERS = 32; - - public NotificationTemplateParameters { - Objects.requireNonNull(values, "template parameters must be non-null"); - if (values.size() > MAXIMUM_PARAMETERS) { - throw new IllegalArgumentException( - "template parameters exceed " + MAXIMUM_PARAMETERS + " entries"); - } - LinkedHashMap copy = new LinkedHashMap<>(); - values.forEach( - (name, value) -> { - if (name == null || !name.matches("[a-z][A-Za-z0-9]{0,63}")) { - throw new IllegalArgumentException( - "template parameter name must match [a-z][A-Za-z0-9]{0,63}"); - } - copy.put( - name, Objects.requireNonNull(value, "template parameter value must be non-null")); - }); - values = Collections.unmodifiableMap(copy); - } - - @Override - public String toString() { - return "NotificationTemplateParameters[names=" + values.keySet() + ", values=]"; - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationTemplateRef.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationTemplateRef.java deleted file mode 100644 index 775a2c62..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationTemplateRef.java +++ /dev/null @@ -1,12 +0,0 @@ -package dev.caskeleton.application.notification; - -/** Immutable checked-in template identity and version. */ -public record NotificationTemplateRef(String templateId, int version) { - - public NotificationTemplateRef { - templateId = NotificationIntentId.requireSlug("templateId", templateId); - if (version < 1 || version > 1_000_000) { - throw new IllegalArgumentException("template version must be in 1..1000000"); - } - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationTemplateValue.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationTemplateValue.java deleted file mode 100644 index d9da83de..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationTemplateValue.java +++ /dev/null @@ -1,103 +0,0 @@ -package dev.caskeleton.application.notification; - -import java.math.BigDecimal; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.util.Currency; -import java.util.Objects; - -/** - * Closed scalar set accepted by the generic template boundary. Provider objects, raw HTML, JSON, - * collections and arbitrary objects cannot implement this sealed contract. - */ -public sealed interface NotificationTemplateValue - permits NotificationTemplateValue.SafeText, - NotificationTemplateValue.TrustedAbsoluteLinkReference, - NotificationTemplateValue.LocalDateValue, - NotificationTemplateValue.LocalDateTimeValue, - NotificationTemplateValue.IntegerValue, - NotificationTemplateValue.MoneyValue { - - record SafeText(String value) implements NotificationTemplateValue { - - public SafeText { - if (value == null || value.isBlank() || value.length() > 4_096) { - throw new IllegalArgumentException("safe text must contain 1..4096 characters"); - } - if (value.chars().anyMatch(character -> character == 0)) { - throw new IllegalArgumentException("safe text must not contain NUL"); - } - } - - @Override - public String toString() { - return "SafeText[value=]"; - } - } - - record TrustedAbsoluteLinkReference(String value) implements NotificationTemplateValue { - - public TrustedAbsoluteLinkReference { - value = NotificationIntentId.requireOpaque("trusted link reference", value); - } - - @Override - public String toString() { - return "TrustedAbsoluteLinkReference[value=]"; - } - } - - record LocalDateValue(LocalDate value) implements NotificationTemplateValue { - - public LocalDateValue { - Objects.requireNonNull(value, "local date value must be non-null"); - } - - @Override - public String toString() { - return "LocalDateValue[value=]"; - } - } - - record LocalDateTimeValue(LocalDateTime value, ZoneId zone) implements NotificationTemplateValue { - - public LocalDateTimeValue { - Objects.requireNonNull(value, "local date-time value must be non-null"); - Objects.requireNonNull(zone, "business time zone must be non-null"); - if (zone.getId().length() > 64) { - throw new IllegalArgumentException("business time zone exceeds 64 characters"); - } - } - - @Override - public String toString() { - return "LocalDateTimeValue[value=, zone=]"; - } - } - - record IntegerValue(long value) implements NotificationTemplateValue { - - @Override - public String toString() { - return "IntegerValue[value=]"; - } - } - - record MoneyValue(BigDecimal amount, Currency currency) implements NotificationTemplateValue { - - public MoneyValue { - Objects.requireNonNull(amount, "money amount must be non-null"); - Objects.requireNonNull(currency, "money currency must be non-null"); - if (amount.scale() < 0 || amount.scale() > 4 || amount.precision() > 19) { - throw new IllegalArgumentException( - "money amount must have precision at most 19 and scale in 0..4"); - } - } - - @Override - public String toString() { - return "MoneyValue[amount=, currency=]"; - } - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationWriterCutoverPort.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationWriterCutoverPort.java deleted file mode 100644 index 9c8ff08f..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationWriterCutoverPort.java +++ /dev/null @@ -1,17 +0,0 @@ -package dev.caskeleton.application.notification; - -import java.time.Instant; - -/** Durable legacy permit mutation boundary; ownership operations use dedicated operation ports. */ -public interface NotificationWriterCutoverPort { - - NotificationLegacyWriterPermitResult acquireLegacyPermit( - NotificationLegacyWriterPermitCommand command, - NotificationWriterRouteSet.RouteProfile routeProfile, - Instant requestedAt); - - NotificationLegacyWriterPermitResult releaseLegacyPermit( - NotificationLegacyWriterPermitCommand command, - NotificationWriterRouteSet.RouteProfile routeProfile, - Instant requestedAt); -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationWriterInventoryEvidence.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationWriterInventoryEvidence.java deleted file mode 100644 index f5551f0e..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationWriterInventoryEvidence.java +++ /dev/null @@ -1,36 +0,0 @@ -package dev.caskeleton.application.notification; - -import java.time.Instant; -import java.util.Collections; -import java.util.Objects; -import java.util.Set; -import java.util.TreeSet; - -/** - * Verified complete BEGIN inventory evidence; never construct from caller-authored digests alone. - */ -public record NotificationWriterInventoryEvidence( - NotificationCanonicalWriterRouteSet.RouteRevision route, - long generation, - Set nodeIds, - String nodeSetDigest, - Instant verifiedAt) { - - public NotificationWriterInventoryEvidence { - Objects.requireNonNull(route, "verified writer inventory route must be non-null"); - if (generation < 0) { - throw new IllegalArgumentException( - "verified writer inventory generation must be non-negative"); - } - Objects.requireNonNull(nodeIds, "verified writer inventory nodes must be non-null"); - TreeSet nodes = new TreeSet<>(); - nodeIds.forEach( - node -> nodes.add(NotificationIntentId.requireOpaque("writer inventory node ID", node))); - if (nodes.size() > 100) { - throw new IllegalArgumentException("verified writer inventory exceeds 100 nodes"); - } - nodeIds = Collections.unmodifiableSet(nodes); - nodeSetDigest = InitializeNotificationWriterFencesCommand.requireDigest(nodeSetDigest); - Objects.requireNonNull(verifiedAt, "writer inventory verification time must be non-null"); - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationWriterInventoryEvidenceVerifierPort.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationWriterInventoryEvidenceVerifierPort.java deleted file mode 100644 index f94dfb39..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationWriterInventoryEvidenceVerifierPort.java +++ /dev/null @@ -1,14 +0,0 @@ -package dev.caskeleton.application.notification; - -import java.time.Instant; - -/** Verifies signed BEGIN inventory against the closed issuer trust catalog and exact context. */ -@FunctionalInterface -public interface NotificationWriterInventoryEvidenceVerifierPort { - - NotificationWriterInventoryEvidence verify( - SignedNotificationWriterInventoryManifest manifest, - NotificationCanonicalWriterRouteSet.RouteRevision expectedRoute, - long expectedGeneration, - Instant verifiedAt); -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationWriterOwnership.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationWriterOwnership.java deleted file mode 100644 index 39d58ab9..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationWriterOwnership.java +++ /dev/null @@ -1,7 +0,0 @@ -package dev.caskeleton.application.notification; - -/** Exclusive writer owner stored in the route-specific database fence. */ -public enum NotificationWriterOwnership { - LEGACY, - CANONICAL -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationWriterQuiescenceAttestationPort.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationWriterQuiescenceAttestationPort.java deleted file mode 100644 index 2edc22a0..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationWriterQuiescenceAttestationPort.java +++ /dev/null @@ -1,34 +0,0 @@ -package dev.caskeleton.application.notification; - -import java.time.Instant; -import java.util.Objects; - -/** Verifies signed quiescence payload, issuer trust and exact route/registry context. */ -@FunctionalInterface -public interface NotificationWriterQuiescenceAttestationPort { - - VerifiedQuiescenceEvidence verify( - SignedNotificationWriterQuiescenceManifest manifest, - NotificationCanonicalWriterRouteSet.RouteRevision expectedRoute, - long expectedGeneration, - NotificationWriterRouteSet.RouteProfile trustedRoute, - Instant verifiedAt); - - record VerifiedQuiescenceEvidence( - NotificationCanonicalWriterRouteSet.RouteRevision route, - long generation, - String childSetDigest, - int childCount, - Instant verifiedAt) { - - public VerifiedQuiescenceEvidence { - Objects.requireNonNull(route, "verified quiescence route must be non-null"); - if (generation < 0 || childCount < 0 || childCount > 1_000) { - throw new IllegalArgumentException( - "verified quiescence generation/count is outside bounds"); - } - childSetDigest = InitializeNotificationWriterFencesCommand.requireDigest(childSetDigest); - Objects.requireNonNull(verifiedAt, "quiescence verification time must be non-null"); - } - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationWriterRouteSet.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationWriterRouteSet.java deleted file mode 100644 index e2d13bf1..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationWriterRouteSet.java +++ /dev/null @@ -1,157 +0,0 @@ -package dev.caskeleton.application.notification; - -import java.nio.ByteBuffer; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.Comparator; -import java.util.HashSet; -import java.util.List; -import java.util.Objects; -import java.util.Optional; - -/** - * PRE-only route set decorating the canonical route keys with legacy aliases and the complete - * current-plus-retiring transport proof registry. - */ -public record NotificationWriterRouteSet( - NotificationCanonicalWriterRouteSet canonicalRoutes, List routeProfiles) { - - public NotificationWriterRouteSet { - Objects.requireNonNull(canonicalRoutes, "canonical writer route set must be non-null"); - Objects.requireNonNull(routeProfiles, "writer route profiles must be non-null"); - routeProfiles = - routeProfiles.stream() - .map( - profile -> Objects.requireNonNull(profile, "writer route profile must be non-null")) - .sorted( - Comparator.comparing((RouteProfile profile) -> profile.route().routeId().value()) - .thenComparingInt(profile -> profile.route().routeRevision())) - .toList(); - if (routeProfiles.size() != canonicalRoutes.routes().size()) { - throw new IllegalArgumentException( - "writer route profile keys must exactly equal canonical route keys"); - } - if (new HashSet<>(routeProfiles.stream().map(RouteProfile::route).toList()).size() - != routeProfiles.size()) { - throw new IllegalArgumentException("writer route profiles contain duplicate routes"); - } - if (!routeProfiles.stream() - .map(RouteProfile::route) - .toList() - .equals(canonicalRoutes.routes())) { - throw new IllegalArgumentException( - "writer route profile keys must exactly equal canonical route keys"); - } - } - - public RouteProfile requireRoute(NotificationCanonicalWriterRouteSet.RouteRevision route) { - return routeProfiles.stream() - .filter(candidate -> candidate.route().equals(route)) - .findFirst() - .orElseThrow( - () -> new IllegalArgumentException("route is outside trusted writer route set")); - } - - public String digest() { - MessageDigest digest = sha256(); - NotificationCanonicalWriterRouteSet.update(digest, canonicalRoutes.digest()); - routeProfiles.forEach( - route -> { - NotificationCanonicalWriterRouteSet.update(digest, route.route().routeId().value()); - digest.update( - ByteBuffer.allocate(Integer.BYTES).putInt(route.route().routeRevision()).array()); - NotificationCanonicalWriterRouteSet.update(digest, route.legacyAlias().orElse("")); - route - .transportProfiles() - .forEach( - profile -> { - NotificationCanonicalWriterRouteSet.update(digest, profile.profileId()); - NotificationCanonicalWriterRouteSet.update(digest, profile.proofClass().name()); - NotificationCanonicalWriterRouteSet.update(digest, profile.evidenceRevision()); - digest.update((byte) (profile.activeAdmissionProfile() ? 1 : 0)); - }); - }); - return java.util.HexFormat.of().formatHex(digest.digest()); - } - - private static MessageDigest sha256() { - try { - return MessageDigest.getInstance("SHA-256"); - } catch (NoSuchAlgorithmException unavailable) { - throw new IllegalStateException( - "SHA-256 must be available on every Java runtime", unavailable); - } - } - - public record RouteProfile( - NotificationCanonicalWriterRouteSet.RouteRevision route, - Optional legacyAlias, - List transportProfiles) { - - public RouteProfile { - Objects.requireNonNull(route, "notification writer route must be non-null"); - Objects.requireNonNull(legacyAlias, "legacy alias container must be non-null"); - legacyAlias = - legacyAlias.map(alias -> NotificationIntentId.requireSlug("legacy route alias", alias)); - Objects.requireNonNull( - transportProfiles, "legacy transport profile registry must be non-null"); - transportProfiles = - transportProfiles.stream() - .map( - profile -> - Objects.requireNonNull(profile, "legacy transport profile must be non-null")) - .sorted(Comparator.comparing(TransportProfile::profileId)) - .toList(); - if (transportProfiles.isEmpty() || transportProfiles.size() > 8) { - throw new IllegalArgumentException( - "legacy transport profile registry must contain 1..8 profiles"); - } - if (new HashSet<>(transportProfiles.stream().map(TransportProfile::profileId).toList()).size() - != transportProfiles.size()) { - throw new IllegalArgumentException("legacy transport profile registry contains duplicates"); - } - long activeCount = - transportProfiles.stream().filter(TransportProfile::activeAdmissionProfile).count(); - if (activeCount != 1) { - throw new IllegalArgumentException( - "legacy transport registry requires exactly one active admission profile"); - } - } - - public ProofClass proofRequirement() { - return transportProfiles.stream() - .allMatch(profile -> profile.proofClass() == ProofClass.HARD_BOUND_PROVEN) - ? ProofClass.HARD_BOUND_PROVEN - : ProofClass.QUIESCENCE_REQUIRED; - } - - public TransportProfile requireProfile(String profileId) { - return transportProfiles.stream() - .filter(profile -> profile.profileId().equals(profileId)) - .findFirst() - .orElseThrow( - () -> - new IllegalArgumentException( - "transport profile is outside trusted writer registry")); - } - } - - public record TransportProfile( - String profileId, - ProofClass proofClass, - String evidenceRevision, - boolean activeAdmissionProfile) { - - public TransportProfile { - profileId = NotificationIntentId.requireSlug("legacy transport profile ID", profileId); - Objects.requireNonNull(proofClass, "legacy transport proof class must be non-null"); - evidenceRevision = - NotificationIntentId.requireSlug("legacy transport evidence revision", evidenceRevision); - } - } - - public enum ProofClass { - HARD_BOUND_PROVEN, - QUIESCENCE_REQUIRED - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/ProviderAttemptOutcome.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/ProviderAttemptOutcome.java deleted file mode 100644 index 7dac31fe..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/ProviderAttemptOutcome.java +++ /dev/null @@ -1,92 +0,0 @@ -package dev.caskeleton.application.notification; - -import java.time.Instant; -import java.util.Objects; -import java.util.Optional; - -/** - * Provider-neutral attempt fact with submission, coordinator action and failure scope kept as - * separate axes. - */ -public record ProviderAttemptOutcome( - SubmissionCertainty submissionCertainty, - RetryDisposition retryDisposition, - NotificationFaultScope faultScope, - NotificationReasonCode reasonCode, - Optional retryNotBefore, - String attemptCorrelationReference, - Optional providerMessageReference) { - - public ProviderAttemptOutcome { - Objects.requireNonNull(submissionCertainty, "submission certainty must be non-null"); - Objects.requireNonNull(retryDisposition, "retry disposition must be non-null"); - Objects.requireNonNull(faultScope, "fault scope must be non-null"); - Objects.requireNonNull(reasonCode, "notification reason code must be non-null"); - Objects.requireNonNull(retryNotBefore, "retry-not-before container must be non-null"); - attemptCorrelationReference = - NotificationIntentId.requireOpaque( - "attempt correlation reference", attemptCorrelationReference); - Objects.requireNonNull( - providerMessageReference, "provider message reference container must be non-null"); - providerMessageReference = - providerMessageReference.map( - value -> NotificationIntentId.requireOpaque("provider message reference", value)); - validateAxes( - submissionCertainty, - retryDisposition, - faultScope, - retryNotBefore, - providerMessageReference); - } - - private static void validateAxes( - SubmissionCertainty certainty, - RetryDisposition disposition, - NotificationFaultScope scope, - Optional retryAt, - Optional providerReference) { - if ((disposition == RetryDisposition.RETRY_AT) != retryAt.isPresent()) { - throw new IllegalArgumentException( - "retryNotBefore must be present exactly when retry disposition is RETRY_AT"); - } - if (certainty == SubmissionCertainty.PROVIDER_ACCEPTED - && (disposition != RetryDisposition.NOT_APPLICABLE - || scope != NotificationFaultScope.DELIVERY)) { - throw new IllegalArgumentException("PROVIDER_ACCEPTED requires NOT_APPLICABLE and DELIVERY"); - } - if (certainty == SubmissionCertainty.INDETERMINATE - && (disposition != RetryDisposition.NOT_APPLICABLE - || scope != NotificationFaultScope.DELIVERY - || providerReference.isPresent())) { - throw new IllegalArgumentException( - "INDETERMINATE requires NOT_APPLICABLE, DELIVERY and no provider message reference"); - } - if (certainty == SubmissionCertainty.DEFINITELY_NOT_APPLIED - && disposition == RetryDisposition.NOT_APPLICABLE) { - throw new IllegalArgumentException( - "DEFINITELY_NOT_APPLIED requires an explicit retry, park or terminal disposition"); - } - if (certainty != SubmissionCertainty.PROVIDER_ACCEPTED && providerReference.isPresent()) { - throw new IllegalArgumentException( - "provider message reference is only valid for a provider-accepted outcome"); - } - if (disposition == RetryDisposition.PARK_BINDING && scope == NotificationFaultScope.DELIVERY) { - throw new IllegalArgumentException("PARK_BINDING requires a shared non-delivery fault scope"); - } - } - - @Override - public String toString() { - return "ProviderAttemptOutcome[submissionCertainty=" - + submissionCertainty - + ", retryDisposition=" - + retryDisposition - + ", faultScope=" - + faultScope - + ", reasonCode=" - + reasonCode - + ", retryNotBefore=" - + retryNotBefore - + ", attemptCorrelationReference=, providerMessageReference=]"; - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/ReconcileNotificationDeliveriesCommand.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/ReconcileNotificationDeliveriesCommand.java deleted file mode 100644 index d1a64b4a..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/ReconcileNotificationDeliveriesCommand.java +++ /dev/null @@ -1,19 +0,0 @@ -package dev.caskeleton.application.notification; - -import dev.caskeleton.application.command.Command; - -/** Requests bounded provider reconciliation and/or local orphan-receipt attachment. */ -public record ReconcileNotificationDeliveriesCommand( - int maximumClaims, int maximumOrphanAttachments) implements Command { - - public ReconcileNotificationDeliveriesCommand { - if (maximumClaims < 0 - || maximumClaims > 100 - || maximumOrphanAttachments < 0 - || maximumOrphanAttachments > 100 - || maximumClaims + maximumOrphanAttachments == 0) { - throw new IllegalArgumentException( - "reconciliation bounds must each be in 0..100 and at least one must be positive"); - } - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/ReconcileNotificationDeliveriesResult.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/ReconcileNotificationDeliveriesResult.java deleted file mode 100644 index 70601ec0..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/ReconcileNotificationDeliveriesResult.java +++ /dev/null @@ -1,18 +0,0 @@ -package dev.caskeleton.application.notification; - -/** Bounded non-sensitive aggregate outcome of one reconciliation cycle. */ -public record ReconcileNotificationDeliveriesResult( - int claimedCount, int providerCallCount, int finalizedCount, int orphanAttachedCount) { - - public ReconcileNotificationDeliveriesResult { - int[] counts = {claimedCount, providerCallCount, finalizedCount, orphanAttachedCount}; - for (int count : counts) { - if (count < 0 || count > 100) { - throw new IllegalArgumentException("reconciliation counts must be in 0..100"); - } - } - if (providerCallCount > claimedCount || finalizedCount > providerCallCount) { - throw new IllegalArgumentException("reconciliation counts are inconsistent"); - } - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/ReconcileNotificationDeliveriesUseCase.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/ReconcileNotificationDeliveriesUseCase.java deleted file mode 100644 index 84c70f88..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/ReconcileNotificationDeliveriesUseCase.java +++ /dev/null @@ -1,84 +0,0 @@ -package dev.caskeleton.application.notification; - -import dev.caskeleton.application.capability.Idempotency; -import dev.caskeleton.application.capability.RepositoryAccess; -import dev.caskeleton.application.capability.UseCaseCapability; -import dev.caskeleton.application.security.RequiresPermission; -import dev.caskeleton.application.transaction.TransactionMode; -import dev.caskeleton.application.transaction.TransactionPort; -import dev.caskeleton.application.usecase.CommandUseCase; -import java.time.Clock; -import java.util.List; -import java.util.Objects; - -/** - * Coordinates local orphan attach and provider reconciliation with short transaction boundaries. - */ -@RequiresPermission("notification:reconcile") -@UseCaseCapability( - transactionMode = TransactionMode.WRITE, - idempotency = Idempotency.IDEMPOTENT, - repositoryAccess = RepositoryAccess.WRITE_REPOSITORY, - externalOutboundAllowed = true, - sensitiveRead = true, - crossTenantAdmin = true) -public class ReconcileNotificationDeliveriesUseCase - implements CommandUseCase< - ReconcileNotificationDeliveriesCommand, ReconcileNotificationDeliveriesResult> { - - private final NotificationDeliveryStorePort store; - private final NotificationReconciliationPort provider; - private final TransactionPort transactions; - private final Clock clock; - - public ReconcileNotificationDeliveriesUseCase( - NotificationDeliveryStorePort store, - NotificationReconciliationPort provider, - TransactionPort transactions, - Clock clock) { - this.store = Objects.requireNonNull(store, "notification delivery store must be non-null"); - this.provider = - Objects.requireNonNull(provider, "notification reconciliation port must be non-null"); - this.transactions = Objects.requireNonNull(transactions, "transaction port must be non-null"); - this.clock = Objects.requireNonNull(clock, "clock must be non-null"); - } - - @Override - public ReconcileNotificationDeliveriesResult handle( - ReconcileNotificationDeliveriesCommand command) { - Objects.requireNonNull(command, "reconciliation command must be non-null"); - int orphanAttached = - command.maximumOrphanAttachments() == 0 - ? 0 - : transactions.inWrite( - () -> - store.attachOrphanReceipts( - command.maximumOrphanAttachments(), clock.instant())); - List claims = - command.maximumClaims() == 0 - ? List.of() - : List.copyOf( - transactions.inWrite( - () -> store.claimForReconciliation(command.maximumClaims(), clock.instant()))); - if (claims.size() > command.maximumClaims()) { - throw new IllegalStateException("notification store returned too many reconciliation claims"); - } - - int finalized = 0; - for (NotificationDeliveryStorePort.ReconciliationClaim claim : claims) { - NotificationReconciliationPort.ReconciliationOutcome outcome = - Objects.requireNonNull( - provider.reconcile(claim), "reconciliation outcome must be non-null"); - NotificationDeliveryStorePort.ReconciliationFinalizationResult finalization = - transactions.inWrite(() -> store.finalizeReconciliation(claim, outcome, clock.instant())); - if (finalization == NotificationDeliveryStorePort.ReconciliationFinalizationResult.APPLIED - || finalization - == NotificationDeliveryStorePort.ReconciliationFinalizationResult - .LATE_EXACT_APPLIED) { - finalized++; - } - } - return new ReconcileNotificationDeliveriesResult( - claims.size(), claims.size(), finalized, orphanAttached); - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/RecordNotificationWriterQuiescenceAttestationCommand.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/RecordNotificationWriterQuiescenceAttestationCommand.java deleted file mode 100644 index 6163ac47..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/RecordNotificationWriterQuiescenceAttestationCommand.java +++ /dev/null @@ -1,23 +0,0 @@ -package dev.caskeleton.application.notification; - -import dev.caskeleton.application.command.Command; -import java.util.Objects; - -/** Authenticated PRE request to verify and retain one immutable signed quiescence manifest. */ -public record RecordNotificationWriterQuiescenceAttestationCommand( - String operationToken, - SignedNotificationWriterQuiescenceManifest manifest, - String actorReference, - NotificationReasonCode reasonCode) - implements Command { - - public RecordNotificationWriterQuiescenceAttestationCommand { - operationToken = - NotificationIntentId.requireOpaque( - "quiescence attestation operation token", operationToken); - Objects.requireNonNull(manifest, "signed quiescence manifest must be non-null"); - actorReference = - NotificationIntentId.requireOpaque("quiescence attestation actor", actorReference); - Objects.requireNonNull(reasonCode, "notification reason code must be non-null"); - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/RecordNotificationWriterQuiescenceAttestationOperation.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/RecordNotificationWriterQuiescenceAttestationOperation.java deleted file mode 100644 index 1655b68d..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/RecordNotificationWriterQuiescenceAttestationOperation.java +++ /dev/null @@ -1,14 +0,0 @@ -package dev.caskeleton.application.notification; - -import java.time.Instant; - -/** Atomically re-derives current blocking sets and retains verified signed quiescence evidence. */ -@FunctionalInterface -public interface RecordNotificationWriterQuiescenceAttestationOperation { - - RecordNotificationWriterQuiescenceAttestationResult record( - RecordNotificationWriterQuiescenceAttestationCommand command, - NotificationWriterQuiescenceAttestationPort.VerifiedQuiescenceEvidence verifiedEvidence, - NotificationWriterRouteSet.RouteProfile trustedRoute, - Instant requestedAt); -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/RecordNotificationWriterQuiescenceAttestationResult.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/RecordNotificationWriterQuiescenceAttestationResult.java deleted file mode 100644 index d1284fd6..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/RecordNotificationWriterQuiescenceAttestationResult.java +++ /dev/null @@ -1,29 +0,0 @@ -package dev.caskeleton.application.notification; - -import java.util.Objects; - -/** Committed retained quiescence evidence identity. */ -public record RecordNotificationWriterQuiescenceAttestationResult( - Status status, - String operationToken, - NotificationCanonicalWriterRouteSet.RouteRevision route, - long generation, - String childSetDigest) { - - public RecordNotificationWriterQuiescenceAttestationResult { - Objects.requireNonNull(status, "quiescence attestation status must be non-null"); - operationToken = - NotificationIntentId.requireOpaque( - "quiescence attestation operation token", operationToken); - Objects.requireNonNull(route, "quiescence attestation route must be non-null"); - if (generation < 0) { - throw new IllegalArgumentException("quiescence generation must be non-negative"); - } - childSetDigest = InitializeNotificationWriterFencesCommand.requireDigest(childSetDigest); - } - - public enum Status { - RECORDED, - REPLAYED - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/RecordNotificationWriterQuiescenceAttestationUseCase.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/RecordNotificationWriterQuiescenceAttestationUseCase.java deleted file mode 100644 index f93ab151..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/RecordNotificationWriterQuiescenceAttestationUseCase.java +++ /dev/null @@ -1,80 +0,0 @@ -package dev.caskeleton.application.notification; - -import dev.caskeleton.application.capability.Idempotency; -import dev.caskeleton.application.capability.RepositoryAccess; -import dev.caskeleton.application.capability.UseCaseCapability; -import dev.caskeleton.application.security.RequiresPermission; -import dev.caskeleton.application.transaction.TransactionMode; -import dev.caskeleton.application.transaction.TransactionPort; -import dev.caskeleton.application.usecase.CommandUseCase; -import java.time.Clock; -import java.util.Objects; -import java.util.Set; - -/** - * Verifies signed quiescence outside a transaction, then root-commits its exact retained evidence. - */ -@RequiresPermission("notification:cutover-attest") -@UseCaseCapability( - transactionMode = TransactionMode.WRITE, - idempotency = Idempotency.IDEMPOTENT, - repositoryAccess = RepositoryAccess.WRITE_REPOSITORY, - crossTenantAdmin = true) -public class RecordNotificationWriterQuiescenceAttestationUseCase - implements CommandUseCase< - RecordNotificationWriterQuiescenceAttestationCommand, - RecordNotificationWriterQuiescenceAttestationResult> { - - private final NotificationWriterRouteSet routes; - private final NotificationWriterQuiescenceAttestationPort verifier; - private final RecordNotificationWriterQuiescenceAttestationOperation operation; - private final TransactionPort transactions; - private final Clock clock; - - public RecordNotificationWriterQuiescenceAttestationUseCase( - NotificationWriterRouteSet routes, - NotificationWriterQuiescenceAttestationPort verifier, - RecordNotificationWriterQuiescenceAttestationOperation operation, - TransactionPort transactions, - Clock clock) { - this.routes = Objects.requireNonNull(routes, "notification writer route set must be non-null"); - this.verifier = - Objects.requireNonNull(verifier, "quiescence evidence verifier must be non-null"); - this.operation = - Objects.requireNonNull(operation, "quiescence attestation operation must be non-null"); - this.transactions = Objects.requireNonNull(transactions, "transaction port must be non-null"); - this.clock = Objects.requireNonNull(clock, "clock must be non-null"); - } - - @Override - public RecordNotificationWriterQuiescenceAttestationResult handle( - RecordNotificationWriterQuiescenceAttestationCommand command) { - Objects.requireNonNull(command, "quiescence attestation command must be non-null"); - SignedNotificationWriterQuiescenceManifest manifest = command.manifest(); - NotificationWriterRouteSet.RouteProfile route = routes.requireRoute(manifest.route()); - if (route.proofRequirement() != NotificationWriterRouteSet.ProofClass.QUIESCENCE_REQUIRED) { - throw new IllegalArgumentException( - "all-hard-bound writer route forbids quiescence attestation evidence"); - } - Set trustedProfileIds = - route.transportProfiles().stream() - .map(NotificationWriterRouteSet.TransportProfile::profileId) - .collect(java.util.stream.Collectors.toUnmodifiableSet()); - if (!manifest.transportProfileIds().equals(trustedProfileIds)) { - throw new IllegalArgumentException( - "signed quiescence transport profiles must exactly match trusted writer registry"); - } - NotificationWriterQuiescenceAttestationPort.VerifiedQuiescenceEvidence evidence = - Objects.requireNonNull( - verifier.verify( - manifest, manifest.route(), manifest.drainingGeneration(), route, clock.instant()), - "verified quiescence evidence must be non-null"); - if (!evidence.route().equals(manifest.route()) - || evidence.generation() != manifest.drainingGeneration()) { - throw new IllegalArgumentException( - "verified quiescence evidence does not match command route/generation"); - } - return transactions.inRootWrite( - () -> operation.record(command, evidence, route, clock.instant())); - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/RetryDisposition.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/RetryDisposition.java deleted file mode 100644 index baf8106f..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/RetryDisposition.java +++ /dev/null @@ -1,9 +0,0 @@ -package dev.caskeleton.application.notification; - -/** Coordinator action after one provider attempt. */ -public enum RetryDisposition { - RETRY_AT, - PARK_BINDING, - TERMINAL, - NOT_APPLICABLE -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/SignedNotificationWriterInventoryManifest.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/SignedNotificationWriterInventoryManifest.java deleted file mode 100644 index 5d6c4b2f..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/SignedNotificationWriterInventoryManifest.java +++ /dev/null @@ -1,46 +0,0 @@ -package dev.caskeleton.application.notification; - -import java.util.List; -import java.util.Objects; -import java.util.Set; - -/** Signed complete old-writer node inventory presented to BEGIN_DRAIN. */ -public record SignedNotificationWriterInventoryManifest( - NotificationSignedEvidenceHeader header, - NotificationCanonicalWriterRouteSet.RouteRevision route, - long generation, - List nodes) { - - public SignedNotificationWriterInventoryManifest { - Objects.requireNonNull(header, "signed inventory header must be non-null"); - Objects.requireNonNull(route, "signed inventory route must be non-null"); - if (generation < 0) { - throw new IllegalArgumentException("signed inventory generation must be non-negative"); - } - nodes = List.copyOf(Objects.requireNonNull(nodes, "signed inventory nodes must be non-null")); - if (nodes.size() > 100 || nodes.size() > header.childCount()) { - throw new IllegalArgumentException( - "signed inventory node count exceeds bounded signed child count"); - } - if (nodes.stream() - .map(NodeInventory::nodeId) - .collect(java.util.stream.Collectors.toSet()) - .size() - != nodes.size()) { - throw new IllegalArgumentException("signed inventory contains duplicate node IDs"); - } - } - - public Set nodeIds() { - return java.util.Collections.unmodifiableSet( - new java.util.TreeSet<>(nodes.stream().map(NodeInventory::nodeId).toList())); - } - - public record NodeInventory(String nodeId, String artifactId) { - - public NodeInventory { - nodeId = NotificationIntentId.requireOpaque("writer inventory node ID", nodeId); - artifactId = NotificationIntentId.requireOpaque("writer inventory artifact ID", artifactId); - } - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/SignedNotificationWriterQuiescenceManifest.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/SignedNotificationWriterQuiescenceManifest.java deleted file mode 100644 index e9764b81..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/SignedNotificationWriterQuiescenceManifest.java +++ /dev/null @@ -1,74 +0,0 @@ -package dev.caskeleton.application.notification; - -import java.util.List; -import java.util.Objects; -import java.util.Set; -import java.util.TreeSet; - -/** Signed exact irreversible quiescence evidence for a QUIESCENCE_REQUIRED route generation. */ -public record SignedNotificationWriterQuiescenceManifest( - NotificationSignedEvidenceHeader header, - NotificationCanonicalWriterRouteSet.RouteRevision route, - long drainingGeneration, - Set transportProfileIds, - List nodes, - int blockingPermitCount, - String blockingPermitSetDigest, - Set permitHolderIds, - int productionConsumerCount, - int providerCallOpenCount) { - - public SignedNotificationWriterQuiescenceManifest { - Objects.requireNonNull(header, "signed quiescence header must be non-null"); - Objects.requireNonNull(route, "signed quiescence route must be non-null"); - if (drainingGeneration < 0) { - throw new IllegalArgumentException("draining generation must be non-negative"); - } - Objects.requireNonNull( - transportProfileIds, "signed quiescence transport profiles must be non-null"); - TreeSet profiles = new TreeSet<>(); - transportProfileIds.forEach( - profile -> - profiles.add(NotificationIntentId.requireSlug("legacy transport profile ID", profile))); - if (profiles.isEmpty() || profiles.size() > 8) { - throw new IllegalArgumentException( - "signed quiescence transport profile set must contain 1..8 profiles"); - } - transportProfileIds = java.util.Collections.unmodifiableSet(profiles); - nodes = List.copyOf(Objects.requireNonNull(nodes, "signed quiescence nodes must be non-null")); - if (nodes.size() > 100 || nodes.size() > header.childCount()) { - throw new IllegalArgumentException( - "signed quiescence node count exceeds bounded signed child count"); - } - if (blockingPermitCount < 0 || blockingPermitCount > 100) { - throw new IllegalArgumentException("blocking permit count must be in 0..100"); - } - blockingPermitSetDigest = - InitializeNotificationWriterFencesCommand.requireDigest(blockingPermitSetDigest); - Objects.requireNonNull(permitHolderIds, "permit holder set must be non-null"); - TreeSet holders = new TreeSet<>(); - permitHolderIds.forEach( - holder -> holders.add(NotificationIntentId.requireOpaque("legacy permit holder", holder))); - if (holders.size() > 100) { - throw new IllegalArgumentException("permit holder set exceeds 100 entries"); - } - permitHolderIds = java.util.Collections.unmodifiableSet(holders); - if (productionConsumerCount != 0 || providerCallOpenCount != 0) { - throw new IllegalArgumentException( - "quiescence evidence requires production consumer and provider open counts of zero"); - } - } - - public record NodeQuiescence( - String nodeId, - boolean retired, - boolean quiesced, - boolean deploymentTombstoned, - boolean credentialRevoked, - boolean egressRevoked) { - - public NodeQuiescence { - nodeId = NotificationIntentId.requireOpaque("quiescence node ID", nodeId); - } - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/SlackAudienceReference.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/SlackAudienceReference.java deleted file mode 100644 index 05fd186e..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/SlackAudienceReference.java +++ /dev/null @@ -1,25 +0,0 @@ -package dev.caskeleton.application.notification; - -/** Opaque Slack workspace binding and audience references; neither value is a webhook URL. */ -public record SlackAudienceReference(String workspaceBindingReference, String audienceReference) - implements NotificationRecipientReference { - - public SlackAudienceReference { - workspaceBindingReference = - NotificationIntentId.requireOpaque( - "Slack workspace binding reference", workspaceBindingReference); - audienceReference = - NotificationIntentId.requireOpaque("Slack audience reference", audienceReference); - } - - @Override - public NotificationChannel channel() { - return NotificationChannel.SLACK; - } - - @Override - public String toString() { - return "SlackAudienceReference[workspaceBindingReference=, " - + "audienceReference=]"; - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/SubmissionCertainty.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/SubmissionCertainty.java deleted file mode 100644 index f00c4289..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/SubmissionCertainty.java +++ /dev/null @@ -1,8 +0,0 @@ -package dev.caskeleton.application.notification; - -/** Whether one provider call could have produced an external side effect. */ -public enum SubmissionCertainty { - DEFINITELY_NOT_APPLIED, - PROVIDER_ACCEPTED, - INDETERMINATE -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/SwitchNotificationWriterOwnershipCommand.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/SwitchNotificationWriterOwnershipCommand.java deleted file mode 100644 index bd85e296..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/SwitchNotificationWriterOwnershipCommand.java +++ /dev/null @@ -1,130 +0,0 @@ -package dev.caskeleton.application.notification; - -import dev.caskeleton.application.command.Command; -import java.util.Objects; -import java.util.Optional; - -/** - * Audited closed writer transition request. No target owner field exists; action determines the - * only legal result owner. - */ -public record SwitchNotificationWriterOwnershipCommand( - Action action, - NotificationCanonicalWriterRouteSet.RouteRevision route, - long expectedGeneration, - long reviewedTargetGeneration, - String operationToken, - String actorReference, - NotificationReasonCode reasonCode, - Optional inventoryManifest, - Optional quiescenceAttestationToken) - implements Command { - - public SwitchNotificationWriterOwnershipCommand { - Objects.requireNonNull(action, "writer ownership action must be non-null"); - Objects.requireNonNull(route, "notification writer route must be non-null"); - if (expectedGeneration < 0 || reviewedTargetGeneration < 0) { - throw new IllegalArgumentException("writer generations must be non-negative"); - } - operationToken = - NotificationIntentId.requireOpaque("writer switch operation token", operationToken); - actorReference = NotificationIntentId.requireOpaque("writer switch actor", actorReference); - Objects.requireNonNull(reasonCode, "notification reason code must be non-null"); - Objects.requireNonNull(inventoryManifest, "inventory manifest container must be non-null"); - Objects.requireNonNull( - quiescenceAttestationToken, "quiescence attestation token container must be non-null"); - quiescenceAttestationToken = - quiescenceAttestationToken.map( - token -> NotificationIntentId.requireOpaque("quiescence attestation token", token)); - switch (action) { - case BEGIN_DRAIN -> { - if (reviewedTargetGeneration != expectedGeneration - || inventoryManifest.isEmpty() - || quiescenceAttestationToken.isPresent()) { - throw new IllegalArgumentException( - "BEGIN_DRAIN keeps generation, requires inventory and forbids attestation token"); - } - } - case COMPLETE_SWITCH -> { - if (reviewedTargetGeneration != Math.addExact(expectedGeneration, 1) - || inventoryManifest.isPresent()) { - throw new IllegalArgumentException( - "COMPLETE_SWITCH requires exactly generation+1 and no caller inventory"); - } - } - case ABORT_DRAIN -> { - if (reviewedTargetGeneration != Math.addExact(expectedGeneration, 1) - || inventoryManifest.isPresent() - || quiescenceAttestationToken.isPresent()) { - throw new IllegalArgumentException( - "ABORT_DRAIN requires exactly generation+1 and no evidence inputs"); - } - } - default -> throw new IllegalArgumentException("unsupported writer ownership action"); - } - } - - public static SwitchNotificationWriterOwnershipCommand beginDrain( - NotificationCanonicalWriterRouteSet.RouteRevision route, - long expectedGeneration, - String operationToken, - String actorReference, - NotificationReasonCode reasonCode, - SignedNotificationWriterInventoryManifest inventoryManifest) { - return new SwitchNotificationWriterOwnershipCommand( - Action.BEGIN_DRAIN, - route, - expectedGeneration, - expectedGeneration, - operationToken, - actorReference, - reasonCode, - Optional.of(inventoryManifest), - Optional.empty()); - } - - public static SwitchNotificationWriterOwnershipCommand completeSwitch( - NotificationCanonicalWriterRouteSet.RouteRevision route, - long expectedGeneration, - long reviewedTargetGeneration, - String operationToken, - String actorReference, - NotificationReasonCode reasonCode, - Optional quiescenceAttestationToken) { - return new SwitchNotificationWriterOwnershipCommand( - Action.COMPLETE_SWITCH, - route, - expectedGeneration, - reviewedTargetGeneration, - operationToken, - actorReference, - reasonCode, - Optional.empty(), - quiescenceAttestationToken); - } - - public static SwitchNotificationWriterOwnershipCommand abortDrain( - NotificationCanonicalWriterRouteSet.RouteRevision route, - long expectedGeneration, - long reviewedTargetGeneration, - String operationToken, - String actorReference, - NotificationReasonCode reasonCode) { - return new SwitchNotificationWriterOwnershipCommand( - Action.ABORT_DRAIN, - route, - expectedGeneration, - reviewedTargetGeneration, - operationToken, - actorReference, - reasonCode, - Optional.empty(), - Optional.empty()); - } - - public enum Action { - BEGIN_DRAIN, - COMPLETE_SWITCH, - ABORT_DRAIN - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/SwitchNotificationWriterOwnershipOperation.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/SwitchNotificationWriterOwnershipOperation.java deleted file mode 100644 index fede5816..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/SwitchNotificationWriterOwnershipOperation.java +++ /dev/null @@ -1,18 +0,0 @@ -package dev.caskeleton.application.notification; - -import java.time.Instant; -import java.util.Optional; - -/** - * Atomic persistence operation that locks/re-verifies retained evidence and applies only the closed - * LEGACY transition matrix. - */ -@FunctionalInterface -public interface SwitchNotificationWriterOwnershipOperation { - - SwitchNotificationWriterOwnershipResult switchOwnership( - SwitchNotificationWriterOwnershipCommand command, - Optional verifiedInventory, - NotificationWriterRouteSet.RouteProfile trustedRoute, - Instant requestedAt); -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/SwitchNotificationWriterOwnershipResult.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/SwitchNotificationWriterOwnershipResult.java deleted file mode 100644 index 18ac693d..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/SwitchNotificationWriterOwnershipResult.java +++ /dev/null @@ -1,70 +0,0 @@ -package dev.caskeleton.application.notification; - -import java.util.Objects; - -/** Committed result of one closed writer-fence transition. */ -public record SwitchNotificationWriterOwnershipResult( - Status status, - SwitchNotificationWriterOwnershipCommand.Action action, - NotificationCanonicalWriterRouteSet.RouteRevision route, - FenceState state, - NotificationWriterOwnership owner, - long generation, - String operationToken) { - - public SwitchNotificationWriterOwnershipResult { - Objects.requireNonNull(status, "writer switch status must be non-null"); - Objects.requireNonNull(action, "writer switch action must be non-null"); - Objects.requireNonNull(route, "notification writer route must be non-null"); - Objects.requireNonNull(state, "writer fence state must be non-null"); - Objects.requireNonNull(owner, "notification writer owner must be non-null"); - if (generation < 0) { - throw new IllegalArgumentException("writer generation must be non-negative"); - } - operationToken = - NotificationIntentId.requireOpaque("writer switch operation token", operationToken); - validateMatrix(action, state, owner); - } - - public static SwitchNotificationWriterOwnershipResult applied( - SwitchNotificationWriterOwnershipCommand.Action action, - NotificationCanonicalWriterRouteSet.RouteRevision route, - NotificationWriterOwnership owner, - long generation, - String operationToken) { - FenceState state = - action == SwitchNotificationWriterOwnershipCommand.Action.BEGIN_DRAIN - ? FenceState.DRAINING - : FenceState.ACTIVE; - return new SwitchNotificationWriterOwnershipResult( - Status.APPLIED, action, route, state, owner, generation, operationToken); - } - - private static void validateMatrix( - SwitchNotificationWriterOwnershipCommand.Action action, - FenceState state, - NotificationWriterOwnership owner) { - boolean valid = - switch (action) { - case BEGIN_DRAIN -> - state == FenceState.DRAINING && owner == NotificationWriterOwnership.LEGACY; - case COMPLETE_SWITCH -> - state == FenceState.ACTIVE && owner == NotificationWriterOwnership.CANONICAL; - case ABORT_DRAIN -> - state == FenceState.ACTIVE && owner == NotificationWriterOwnership.LEGACY; - }; - if (!valid) { - throw new IllegalArgumentException("writer switch result violates closed transition matrix"); - } - } - - public enum Status { - APPLIED, - REPLAYED - } - - public enum FenceState { - ACTIVE, - DRAINING - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/SwitchNotificationWriterOwnershipUseCase.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/SwitchNotificationWriterOwnershipUseCase.java deleted file mode 100644 index 8a455c27..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/SwitchNotificationWriterOwnershipUseCase.java +++ /dev/null @@ -1,100 +0,0 @@ -package dev.caskeleton.application.notification; - -import dev.caskeleton.application.capability.Idempotency; -import dev.caskeleton.application.capability.RepositoryAccess; -import dev.caskeleton.application.capability.UseCaseCapability; -import dev.caskeleton.application.security.RequiresPermission; -import dev.caskeleton.application.transaction.TransactionMode; -import dev.caskeleton.application.transaction.TransactionPort; -import dev.caskeleton.application.usecase.CommandUseCase; -import java.time.Clock; -import java.util.Objects; -import java.util.Optional; - -/** - * Validates signed evidence requirements and root-commits one closed writer ownership transition. - */ -@RequiresPermission("notification:cutover") -@UseCaseCapability( - transactionMode = TransactionMode.WRITE, - idempotency = Idempotency.IDEMPOTENT, - repositoryAccess = RepositoryAccess.WRITE_REPOSITORY, - crossTenantAdmin = true) -public class SwitchNotificationWriterOwnershipUseCase - implements CommandUseCase< - SwitchNotificationWriterOwnershipCommand, SwitchNotificationWriterOwnershipResult> { - - private final NotificationWriterRouteSet routes; - private final NotificationWriterInventoryEvidenceVerifierPort inventoryVerifier; - private final SwitchNotificationWriterOwnershipOperation operation; - private final TransactionPort transactions; - private final Clock clock; - - public SwitchNotificationWriterOwnershipUseCase( - NotificationWriterRouteSet routes, - NotificationWriterInventoryEvidenceVerifierPort inventoryVerifier, - SwitchNotificationWriterOwnershipOperation operation, - TransactionPort transactions, - Clock clock) { - this.routes = Objects.requireNonNull(routes, "notification writer route set must be non-null"); - this.inventoryVerifier = - Objects.requireNonNull(inventoryVerifier, "writer inventory verifier must be non-null"); - this.operation = - Objects.requireNonNull(operation, "writer ownership switch operation must be non-null"); - this.transactions = Objects.requireNonNull(transactions, "transaction port must be non-null"); - this.clock = Objects.requireNonNull(clock, "clock must be non-null"); - } - - @Override - public SwitchNotificationWriterOwnershipResult handle( - SwitchNotificationWriterOwnershipCommand command) { - Objects.requireNonNull(command, "writer ownership switch command must be non-null"); - NotificationWriterRouteSet.RouteProfile route = routes.requireRoute(command.route()); - validateEvidenceRequirement(command, route); - Optional inventory = verifyBeginInventory(command); - return transactions.inRootWrite( - () -> operation.switchOwnership(command, inventory, route, clock.instant())); - } - - private Optional verifyBeginInventory( - SwitchNotificationWriterOwnershipCommand command) { - if (command.action() != SwitchNotificationWriterOwnershipCommand.Action.BEGIN_DRAIN) { - return Optional.empty(); - } - SignedNotificationWriterInventoryManifest manifest = command.inventoryManifest().orElseThrow(); - if (!manifest.route().equals(command.route()) - || manifest.generation() != command.expectedGeneration()) { - throw new IllegalArgumentException( - "signed writer inventory must match BEGIN route and generation"); - } - NotificationWriterInventoryEvidence evidence = - Objects.requireNonNull( - inventoryVerifier.verify( - manifest, command.route(), command.expectedGeneration(), clock.instant()), - "verified writer inventory evidence must be non-null"); - if (!evidence.route().equals(command.route()) - || evidence.generation() != command.expectedGeneration()) { - throw new IllegalArgumentException( - "verified writer inventory does not match BEGIN route and generation"); - } - return Optional.of(evidence); - } - - private static void validateEvidenceRequirement( - SwitchNotificationWriterOwnershipCommand command, - NotificationWriterRouteSet.RouteProfile route) { - if (command.action() != SwitchNotificationWriterOwnershipCommand.Action.COMPLETE_SWITCH) { - return; - } - if (route.proofRequirement() == NotificationWriterRouteSet.ProofClass.QUIESCENCE_REQUIRED - && command.quiescenceAttestationToken().isEmpty()) { - throw new IllegalArgumentException( - "QUIESCENCE_REQUIRED route requires a committed attestation token"); - } - if (route.proofRequirement() == NotificationWriterRouteSet.ProofClass.HARD_BOUND_PROVEN - && command.quiescenceAttestationToken().isPresent()) { - throw new IllegalArgumentException( - "all-hard-bound route forbids quiescence attestation evidence"); - } - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/TargetAttemptOutcome.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/TargetAttemptOutcome.java deleted file mode 100644 index a7910d7e..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/TargetAttemptOutcome.java +++ /dev/null @@ -1,25 +0,0 @@ -package dev.caskeleton.application.notification; - -import java.util.Objects; - -/** Bounded target-ordinal outcome for one provider leg. */ -public record TargetAttemptOutcome( - int targetOrdinal, NotificationDeliveryId deliveryId, ProviderAttemptOutcome providerOutcome) { - - public TargetAttemptOutcome { - if (targetOrdinal < 0 || targetOrdinal >= 16) { - throw new IllegalArgumentException("target ordinal must be in 0..15"); - } - Objects.requireNonNull(deliveryId, "notification delivery ID must be non-null"); - Objects.requireNonNull(providerOutcome, "provider attempt outcome must be non-null"); - } - - @Override - public String toString() { - return "TargetAttemptOutcome[targetOrdinal=" - + targetOrdinal - + ", deliveryId=, providerOutcome=" - + providerOutcome - + "]"; - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/TerminalizeExpiredNotificationWriterPermitsCommand.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/TerminalizeExpiredNotificationWriterPermitsCommand.java deleted file mode 100644 index 03479d09..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/TerminalizeExpiredNotificationWriterPermitsCommand.java +++ /dev/null @@ -1,31 +0,0 @@ -package dev.caskeleton.application.notification; - -import dev.caskeleton.application.command.Command; -import java.util.Objects; - -/** PRE-only bounded DB-time terminalization request for expired ACTIVE legacy permits. */ -public record TerminalizeExpiredNotificationWriterPermitsCommand( - NotificationCanonicalWriterRouteSet.RouteRevision route, - long drainingGeneration, - int maximumPermits, - String operationToken, - String actorReference, - NotificationReasonCode reasonCode) - implements Command { - - public TerminalizeExpiredNotificationWriterPermitsCommand { - Objects.requireNonNull(route, "notification writer route must be non-null"); - if (drainingGeneration < 0) { - throw new IllegalArgumentException("draining generation must be non-negative"); - } - if (maximumPermits < 1 || maximumPermits > 100) { - throw new IllegalArgumentException("terminalization permit bound must be in 1..100"); - } - operationToken = - NotificationIntentId.requireOpaque( - "permit terminalization operation token", operationToken); - actorReference = - NotificationIntentId.requireOpaque("permit terminalization actor", actorReference); - Objects.requireNonNull(reasonCode, "notification reason code must be non-null"); - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/TerminalizeExpiredNotificationWriterPermitsOperation.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/TerminalizeExpiredNotificationWriterPermitsOperation.java deleted file mode 100644 index 6bae7b2f..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/TerminalizeExpiredNotificationWriterPermitsOperation.java +++ /dev/null @@ -1,13 +0,0 @@ -package dev.caskeleton.application.notification; - -import java.time.Instant; - -/** Atomic operation selecting and CAS-terminalizing DB-time-expired permits in canonical order. */ -@FunctionalInterface -public interface TerminalizeExpiredNotificationWriterPermitsOperation { - - TerminalizeExpiredNotificationWriterPermitsResult terminalize( - TerminalizeExpiredNotificationWriterPermitsCommand command, - NotificationWriterRouteSet.RouteProfile trustedRoute, - Instant requestedAt); -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/TerminalizeExpiredNotificationWriterPermitsResult.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/TerminalizeExpiredNotificationWriterPermitsResult.java deleted file mode 100644 index 394f9a1b..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/TerminalizeExpiredNotificationWriterPermitsResult.java +++ /dev/null @@ -1,21 +0,0 @@ -package dev.caskeleton.application.notification; - -import java.util.Objects; - -/** Committed terminalized permit count and canonical affected tuple-set digest. */ -public record TerminalizeExpiredNotificationWriterPermitsResult( - Status status, int affectedCount, String affectedSetDigest) { - - public TerminalizeExpiredNotificationWriterPermitsResult { - Objects.requireNonNull(status, "permit terminalization status must be non-null"); - if (affectedCount < 0 || affectedCount > 100) { - throw new IllegalArgumentException("terminalized permit count must be in 0..100"); - } - affectedSetDigest = InitializeNotificationWriterFencesCommand.requireDigest(affectedSetDigest); - } - - public enum Status { - APPLIED, - REPLAYED - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/TerminalizeExpiredNotificationWriterPermitsUseCase.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/TerminalizeExpiredNotificationWriterPermitsUseCase.java deleted file mode 100644 index da3608fc..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/TerminalizeExpiredNotificationWriterPermitsUseCase.java +++ /dev/null @@ -1,49 +0,0 @@ -package dev.caskeleton.application.notification; - -import dev.caskeleton.application.capability.Idempotency; -import dev.caskeleton.application.capability.RepositoryAccess; -import dev.caskeleton.application.capability.UseCaseCapability; -import dev.caskeleton.application.security.RequiresPermission; -import dev.caskeleton.application.transaction.TransactionMode; -import dev.caskeleton.application.transaction.TransactionPort; -import dev.caskeleton.application.usecase.CommandUseCase; -import java.time.Clock; -import java.util.Objects; - -/** Root-commits one bounded expired-permit terminalization operation. */ -@RequiresPermission("notification:cutover-terminalize") -@UseCaseCapability( - transactionMode = TransactionMode.WRITE, - idempotency = Idempotency.IDEMPOTENT, - repositoryAccess = RepositoryAccess.WRITE_REPOSITORY, - crossTenantAdmin = true) -public class TerminalizeExpiredNotificationWriterPermitsUseCase - implements CommandUseCase< - TerminalizeExpiredNotificationWriterPermitsCommand, - TerminalizeExpiredNotificationWriterPermitsResult> { - - private final NotificationWriterRouteSet routes; - private final TerminalizeExpiredNotificationWriterPermitsOperation operation; - private final TransactionPort transactions; - private final Clock clock; - - public TerminalizeExpiredNotificationWriterPermitsUseCase( - NotificationWriterRouteSet routes, - TerminalizeExpiredNotificationWriterPermitsOperation operation, - TransactionPort transactions, - Clock clock) { - this.routes = Objects.requireNonNull(routes, "notification writer route set must be non-null"); - this.operation = - Objects.requireNonNull(operation, "permit terminalization operation must be non-null"); - this.transactions = Objects.requireNonNull(transactions, "transaction port must be non-null"); - this.clock = Objects.requireNonNull(clock, "clock must be non-null"); - } - - @Override - public TerminalizeExpiredNotificationWriterPermitsResult handle( - TerminalizeExpiredNotificationWriterPermitsCommand command) { - Objects.requireNonNull(command, "permit terminalization command must be non-null"); - NotificationWriterRouteSet.RouteProfile route = routes.requireRoute(command.route()); - return transactions.inRootWrite(() -> operation.terminalize(command, route, clock.instant())); - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/api/NotificationOrchestrator.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/api/NotificationOrchestrator.java deleted file mode 100644 index 3da97201..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/api/NotificationOrchestrator.java +++ /dev/null @@ -1,24 +0,0 @@ -package dev.caskeleton.application.notification.platform.api; - -import java.time.Instant; - -/** - * N2 advanced API. - * - *

{@code submit} and {@code schedule} return once the logical request and its recipient jobs are - * durably committed. Neither waits for a provider call. - */ -public interface NotificationOrchestrator { - - /** Accept a plan for immediate dispatch. */ - NotificationReceipt submit(NotificationPlan plan); - - /** Accept a plan that must not be activated before {@code scheduleAt}. */ - NotificationReceipt schedule(NotificationPlan plan, Instant scheduleAt); - - /** Stop future logical attempts for a notification. */ - CancelResult cancel(NotificationId notificationId, CancelCommand command); - - /** Read the current projection of a notification. */ - NotificationSnapshot get(NotificationId notificationId); -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/api/error/AmbiguousSubmissionException.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/api/error/AmbiguousSubmissionException.java deleted file mode 100644 index f487e256..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/api/error/AmbiguousSubmissionException.java +++ /dev/null @@ -1,11 +0,0 @@ -package dev.caskeleton.application.notification.platform.api.error; - -/** The submission may or may not have been accepted; automatic retry and fallback stay blocked. */ -public class AmbiguousSubmissionException extends NotificationException { - - private static final long serialVersionUID = 1L; - - public AmbiguousSubmissionException(NotificationFailureDescriptor descriptor) { - super(descriptor); - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/api/error/CallbackProjectionException.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/api/error/CallbackProjectionException.java deleted file mode 100644 index a3d1fff1..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/api/error/CallbackProjectionException.java +++ /dev/null @@ -1,11 +0,0 @@ -package dev.caskeleton.application.notification.platform.api.error; - -/** A stored provider event could not be projected. */ -public class CallbackProjectionException extends NotificationException { - - private static final long serialVersionUID = 1L; - - public CallbackProjectionException(NotificationFailureDescriptor descriptor) { - super(descriptor); - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/api/error/InvalidContactPointException.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/api/error/InvalidContactPointException.java deleted file mode 100644 index 59e9f39b..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/api/error/InvalidContactPointException.java +++ /dev/null @@ -1,11 +0,0 @@ -package dev.caskeleton.application.notification.platform.api.error; - -/** The contact point is not usable for this channel. */ -public class InvalidContactPointException extends NotificationException { - - private static final long serialVersionUID = 1L; - - public InvalidContactPointException(NotificationFailureDescriptor descriptor) { - super(descriptor); - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/api/error/NotificationCapacityException.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/api/error/NotificationCapacityException.java deleted file mode 100644 index a4b15967..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/api/error/NotificationCapacityException.java +++ /dev/null @@ -1,11 +0,0 @@ -package dev.caskeleton.application.notification.platform.api.error; - -/** Intake refused because the durable queue is at its bound. */ -public class NotificationCapacityException extends NotificationException { - - private static final long serialVersionUID = 1L; - - public NotificationCapacityException(NotificationFailureDescriptor descriptor) { - super(descriptor); - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/api/error/NotificationSuppressedException.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/api/error/NotificationSuppressedException.java deleted file mode 100644 index 12eb1532..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/api/error/NotificationSuppressedException.java +++ /dev/null @@ -1,11 +0,0 @@ -package dev.caskeleton.application.notification.platform.api.error; - -/** Dispatch blocked by suppression or injected eligibility. */ -public class NotificationSuppressedException extends NotificationException { - - private static final long serialVersionUID = 1L; - - public NotificationSuppressedException(NotificationFailureDescriptor descriptor) { - super(descriptor); - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/api/error/ProviderAuthenticationException.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/api/error/ProviderAuthenticationException.java deleted file mode 100644 index 9fc53ab5..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/api/error/ProviderAuthenticationException.java +++ /dev/null @@ -1,13 +0,0 @@ -package dev.caskeleton.application.notification.platform.api.error; - -/** - * Provider credentials are invalid; this opens the provider route rather than retrying one message. - */ -public class ProviderAuthenticationException extends NotificationException { - - private static final long serialVersionUID = 1L; - - public ProviderAuthenticationException(NotificationFailureDescriptor descriptor) { - super(descriptor); - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/api/error/ProviderAuthorizationException.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/api/error/ProviderAuthorizationException.java deleted file mode 100644 index 3944649d..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/api/error/ProviderAuthorizationException.java +++ /dev/null @@ -1,11 +0,0 @@ -package dev.caskeleton.application.notification.platform.api.error; - -/** Provider credentials are valid but not permitted for this operation. */ -public class ProviderAuthorizationException extends NotificationException { - - private static final long serialVersionUID = 1L; - - public ProviderAuthorizationException(NotificationFailureDescriptor descriptor) { - super(descriptor); - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/api/error/ProviderPermanentException.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/api/error/ProviderPermanentException.java deleted file mode 100644 index 225aa638..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/api/error/ProviderPermanentException.java +++ /dev/null @@ -1,11 +0,0 @@ -package dev.caskeleton.application.notification.platform.api.error; - -/** Provider failed in a way that repeating cannot fix. */ -public class ProviderPermanentException extends NotificationException { - - private static final long serialVersionUID = 1L; - - public ProviderPermanentException(NotificationFailureDescriptor descriptor) { - super(descriptor); - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/api/error/ProviderRejectedException.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/api/error/ProviderRejectedException.java deleted file mode 100644 index e93d0c8a..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/api/error/ProviderRejectedException.java +++ /dev/null @@ -1,11 +0,0 @@ -package dev.caskeleton.application.notification.platform.api.error; - -/** Provider explicitly refused the submission. */ -public class ProviderRejectedException extends NotificationException { - - private static final long serialVersionUID = 1L; - - public ProviderRejectedException(NotificationFailureDescriptor descriptor) { - super(descriptor); - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/api/error/ProviderThrottledException.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/api/error/ProviderThrottledException.java deleted file mode 100644 index a383dbfa..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/api/error/ProviderThrottledException.java +++ /dev/null @@ -1,11 +0,0 @@ -package dev.caskeleton.application.notification.platform.api.error; - -/** Provider rate limit reached. */ -public class ProviderThrottledException extends NotificationException { - - private static final long serialVersionUID = 1L; - - public ProviderThrottledException(NotificationFailureDescriptor descriptor) { - super(descriptor); - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/api/error/ProviderTransientException.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/api/error/ProviderTransientException.java deleted file mode 100644 index b6178f3f..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/api/error/ProviderTransientException.java +++ /dev/null @@ -1,11 +0,0 @@ -package dev.caskeleton.application.notification.platform.api.error; - -/** Provider failed in a way that is safe to retry. */ -public class ProviderTransientException extends NotificationException { - - private static final long serialVersionUID = 1L; - - public ProviderTransientException(NotificationFailureDescriptor descriptor) { - super(descriptor); - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/api/error/ReconciliationException.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/api/error/ReconciliationException.java deleted file mode 100644 index 5e5b83e2..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/api/error/ReconciliationException.java +++ /dev/null @@ -1,11 +0,0 @@ -package dev.caskeleton.application.notification.platform.api.error; - -/** Provider status query failed. */ -public class ReconciliationException extends NotificationException { - - private static final long serialVersionUID = 1L; - - public ReconciliationException(NotificationFailureDescriptor descriptor) { - super(descriptor); - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/callback/ProviderEventProjectionService.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/callback/ProviderEventProjectionService.java index 5f06d7e0..2cc069ea 100644 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/callback/ProviderEventProjectionService.java +++ b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/callback/ProviderEventProjectionService.java @@ -41,14 +41,38 @@ public final class ProviderEventProjectionService { this.metrics = Objects.requireNonNull(metrics, "metrics"); } - /** Project one stored event. Safe to call repeatedly for the same event. */ + /** + * Project one stored event. Safe to call repeatedly for the same event. + * + *

One transaction for all of it, including the attempt lookup. Resolving binds the event and a + * missing projector marks it failed, and both are modifying queries: run before the boundary, + * from a caller with no transaction of its own (the replay worker), they threw every time. + */ public Optional project(ProviderEventRecord event) { Objects.requireNonNull(event, "event"); if (event.projectionStatus() == ProjectionStatus.APPLIED || event.projectionStatus() == ProjectionStatus.IGNORED) { return Optional.empty(); } + return transactions.inWrite(() -> projectInTransaction(event)); + } + /** + * Records that projecting an event failed, in a transaction of its own. + * + *

For a caller whose {@link #project} threw: that transaction rolled back with the failure, + * and the event has to leave {@code PENDING} or it is retried, and fails, on every pass. + * + * @param event the event whose projection failed + * @param reasonCode why, for the operator replaying it + */ + public void markFailed(ProviderEventRecord event, String reasonCode) { + Objects.requireNonNull(event, "event"); + Objects.requireNonNull(reasonCode, "reasonCode"); + transactions.inWrite(() -> ledger.markFailed(event.id(), reasonCode)); + } + + private Optional projectInTransaction(ProviderEventRecord event) { Optional attempt = resolve(event); if (attempt.isEmpty()) { return Optional.empty(); @@ -59,30 +83,25 @@ public final class ProviderEventProjectionService { return Optional.empty(); } - return Optional.of( - transactions.inWrite( - () -> { - DeliveryProjection current = projections.load(attempt.get().attemptId()); - ProjectionResult result = projector.get().project(attempt.get(), event, current); - if (result.changed()) { - projections.save(attempt.get().attemptId(), result.projection()); - // Claimed, not merely conditioned on the facts. The ledger is replayed by design, - // so "the projection says suppressed" is true on every replay and the side effect - // ran each time. - if (result.projection().suppressionFacts().requiresSuppression() - && projections.claimSuppressionSideEffect(attempt.get().attemptId())) { - sideEffects.apply(attempt.get(), result.projection().suppressionFacts()); - } - } - ledger.markApplied(event.id(), result); - metrics.increment( - NotificationMetricName.DELIVERY, - Map.of( - "channel", attempt.get().channel().name(), - "provider", attempt.get().providerId().value(), - "outcome", result.projection().deliveryOutcome().name())); - return result; - })); + DeliveryProjection current = projections.load(attempt.get().attemptId()); + ProjectionResult result = projector.get().project(attempt.get(), event, current); + if (result.changed()) { + projections.save(attempt.get().attemptId(), result.projection()); + // Claimed, not merely conditioned on the facts. The ledger is replayed by design, so "the + // projection says suppressed" is true on every replay and the side effect ran each time. + if (result.projection().suppressionFacts().requiresSuppression() + && projections.claimSuppressionSideEffect(attempt.get().attemptId())) { + sideEffects.apply(attempt.get(), result.projection().suppressionFacts()); + } + } + ledger.markApplied(event.id(), result); + metrics.increment( + NotificationMetricName.DELIVERY, + Map.of( + "channel", attempt.get().channel().name(), + "provider", attempt.get().providerId().value(), + "outcome", result.projection().deliveryOutcome().name())); + return Optional.of(result); } /** diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/ApplicationReceiptServiceImpl.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/ApplicationReceiptServiceImpl.java deleted file mode 100644 index 3ef39961..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/ApplicationReceiptServiceImpl.java +++ /dev/null @@ -1,101 +0,0 @@ -package dev.caskeleton.application.notification.platform.dispatch; - -import dev.caskeleton.application.notification.platform.api.NormalizedEventType; -import dev.caskeleton.application.notification.platform.api.NormalizedProviderEvent; -import dev.caskeleton.application.notification.platform.callback.DeliveryAttemptSnapshot; -import dev.caskeleton.application.notification.platform.callback.ProviderEventLedger; -import dev.caskeleton.application.notification.platform.callback.ProviderEventProjectionService; -import dev.caskeleton.application.notification.platform.callback.ProviderEventSource; -import dev.caskeleton.application.notification.platform.callback.VerifiedProviderEvent; -import dev.caskeleton.application.notification.platform.push.ApplicationIdentity; -import dev.caskeleton.application.notification.platform.push.ApplicationReceipt; -import dev.caskeleton.application.notification.platform.push.ApplicationReceiptService; -import dev.caskeleton.application.notification.platform.push.ReceiptAuthorizationException; -import dev.caskeleton.application.notification.platform.push.ReceiptKind; -import dev.caskeleton.application.notification.platform.push.ReceiptResult; -import dev.caskeleton.application.transaction.TransactionPort; -import java.nio.charset.StandardCharsets; -import java.time.Clock; -import java.util.HexFormat; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -/** - * Records application-reported display and read evidence. - * - *

A receipt can only strengthen an attempt that already exists, and only for the subject the - * session is authenticated as. Otherwise anyone holding an app build could write "read" evidence - * for other people's notifications. - */ -public final class ApplicationReceiptServiceImpl implements ApplicationReceiptService { - - private final DeliveryAttemptStorePort attempts; - private final ProviderEventLedger ledger; - private final ProviderEventProjectionService projection; - private final TransactionPort transactions; - private final Clock clock; - - public ApplicationReceiptServiceImpl( - DeliveryAttemptStorePort attempts, - ProviderEventLedger ledger, - ProviderEventProjectionService projection, - TransactionPort transactions, - Clock clock) { - this.attempts = Objects.requireNonNull(attempts, "attempts"); - this.ledger = Objects.requireNonNull(ledger, "ledger"); - this.projection = Objects.requireNonNull(projection, "projection"); - this.transactions = Objects.requireNonNull(transactions, "transactions"); - this.clock = Objects.requireNonNull(clock, "clock"); - } - - @Override - public ReceiptResult record(ApplicationReceipt receipt, ApplicationIdentity identity) { - Objects.requireNonNull(receipt, "receipt"); - Objects.requireNonNull(identity, "identity"); - if (!identity.authenticated()) { - throw new ReceiptAuthorizationException(); - } - - DeliveryAttemptSnapshot attempt = - attempts.snapshot(receipt.attemptId()).orElseThrow(ReceiptAuthorizationException::new); - if (!identity.authenticatedSubjectRef().equals(receipt.subjectRef())) { - throw new ReceiptAuthorizationException(); - } - - return transactions.inWrite( - () -> { - var appended = - ledger.append( - new VerifiedProviderEvent( - attempt.providerProfileId(), - new NormalizedProviderEvent( - receipt.kind() == ReceiptKind.READ - ? NormalizedEventType.READ - : NormalizedEventType.DISPLAYED, - "application-receipt", - Optional.of(receipt.receiptId()), - attempt.providerRequestId(), - receipt.clientOccurredAt(), - Map.of("applicationId", identity.applicationId())), - Optional.of(attempt.attemptId()), - ProviderEventSource.APPLICATION_RECEIPT, - true, - clock.instant(), - new byte[0], - digestOf(receipt.receiptId()), - digestOf(attempt.attemptId().value() + "|" + receipt.receiptId()))); - appended.newEvents().forEach(projection::project); - return new ReceiptResult(appended.created(), attempt.attemptId()); - }); - } - - private static String digestOf(String seed) { - try { - var digest = java.security.MessageDigest.getInstance("SHA-256"); - return HexFormat.of().formatHex(digest.digest(seed.getBytes(StandardCharsets.UTF_8))); - } catch (java.security.NoSuchAlgorithmException impossible) { - throw new IllegalStateException("SHA-256 is required by the Java platform", impossible); - } - } -} diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/LeaseRecoveryService.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/LeaseRecoveryService.java similarity index 74% rename from src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/LeaseRecoveryService.java rename to src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/LeaseRecoveryService.java index ea00a346..ee3a86f7 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/LeaseRecoveryService.java +++ b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/LeaseRecoveryService.java @@ -1,9 +1,9 @@ -package dev.caskeleton.adapter.outbound.notification.platform.dispatch; +package dev.caskeleton.application.notification.platform.dispatch; import dev.caskeleton.application.notification.platform.api.DeliveryAttemptId; -import dev.caskeleton.application.notification.platform.dispatch.DeliveryAttemptStorePort; -import dev.caskeleton.application.notification.platform.dispatch.RecipientLeaseStorePort; -import dev.caskeleton.application.notification.platform.dispatch.ReconciliationService; +import dev.caskeleton.application.notification.platform.api.RecipientDeliveryId; +import dev.caskeleton.application.notification.platform.api.delivery.RecipientDeliveryState; +import dev.caskeleton.application.transaction.TransactionPort; import java.time.Duration; import java.util.List; import java.util.Objects; @@ -26,24 +26,30 @@ import java.util.Objects; *

The first case used to be unhandled: recovery iterated attempts, and a delivery with none had * nothing to iterate. Those rows stayed {@code DISPATCHING} forever, holding a delivery nobody had * even tried to send. + * + *

Every write opens its own transaction; the pass itself runs on a bare scheduler thread. The + * stores behind these ports are modifying JPA queries, which throw outside a transaction — so the + * pass used to fail on its first statement, every time, and the scheduler only logged it. It lives + * here rather than in the notification adapter because both the requeue-or-reconcile decision and + * where a unit of work begins are application decisions (NTF-020). */ public final class LeaseRecoveryService { private final RecipientLeaseStorePort leases; private final DeliveryAttemptStorePort attempts; - private final dev.caskeleton.application.notification.platform.dispatch.RecipientDeliveryStorePort - deliveries; + private final RecipientDeliveryStorePort deliveries; private final java.time.Clock clock; private final AttemptReconciler reconciliation; + private final TransactionPort transactions; private final Duration staleAfter; private final int batchSize; public LeaseRecoveryService( RecipientLeaseStorePort leases, DeliveryAttemptStorePort attempts, - dev.caskeleton.application.notification.platform.dispatch.RecipientDeliveryStorePort - deliveries, + RecipientDeliveryStorePort deliveries, AttemptReconciler reconciliation, + TransactionPort transactions, java.time.Clock clock, Duration staleAfter, int batchSize) { @@ -52,6 +58,7 @@ public final class LeaseRecoveryService { this.deliveries = Objects.requireNonNull(deliveries, "deliveries"); this.clock = Objects.requireNonNull(clock, "clock"); this.reconciliation = Objects.requireNonNull(reconciliation, "reconciliation"); + this.transactions = Objects.requireNonNull(transactions, "transactions"); this.staleAfter = Objects.requireNonNull(staleAfter, "staleAfter"); this.batchSize = batchSize; if (batchSize < 1) { @@ -91,8 +98,7 @@ public final class LeaseRecoveryService { * @param attempt the abandoned attempt * @return true only when the adapter proved the request never started */ - private static boolean provablyNeverStarted( - dev.caskeleton.application.notification.platform.dispatch.DeliveryAttemptRecord attempt) { + private static boolean provablyNeverStarted(DeliveryAttemptRecord attempt) { var started = attempt.executionEvidence().requestStarted(); return started.certainty() == dev.caskeleton.application.notification.platform.provider.EvidenceCertainty.PROVEN @@ -103,19 +109,14 @@ public final class LeaseRecoveryService { public int recoverOnce() { // Retiring expired deliveries rides along with recovery because both answer the same operator // question — "why is this row still here?" — and neither needs a scheduler of its own. - int handled = leases.expireOverdue(batchSize); - List abandoned = - leases.expiredDispatching(batchSize, staleAfter); + int handled = transactions.inWrite(() -> leases.expireOverdue(batchSize)); + List abandoned = leases.expiredDispatching(batchSize, staleAfter); for (var recipientDeliveryId : abandoned) { var attemptsOfDelivery = attempts.attemptsOf(recipientDeliveryId); if (attemptsOfDelivery.isEmpty()) { // Crash before the attempt row: no provider call can have happened, so this is the one // safe requeue. Leaving it DISPATCHING stranded the delivery permanently. - deliveries.transition( - recipientDeliveryId, - dev.caskeleton.application.notification.platform.api.delivery.RecipientDeliveryState - .READY_TO_DISPATCH, - java.util.Optional.of(clock.instant())); + requeue(recipientDeliveryId); handled++; continue; } @@ -127,12 +128,10 @@ public final class LeaseRecoveryService { // already written down. This branch only became possible once the certainty survived // persistence: before, "proven not started" and "unknown whether started" read back // identically, so every abandoned attempt had to be reconciled. - deliveries.transition( - recipientDeliveryId, - dev.caskeleton.application.notification.platform.api.delivery.RecipientDeliveryState - .READY_TO_DISPATCH, - java.util.Optional.of(clock.instant())); + requeue(recipientDeliveryId); } else { + // Outside any transaction: reconciliation asks the provider over the network and opens + // its own boundaries for what it writes. reconciliation.reconcile(attempt.id()); } handled++; @@ -141,4 +140,13 @@ public final class LeaseRecoveryService { } return handled; } + + private void requeue(RecipientDeliveryId recipientDeliveryId) { + transactions.inWrite( + () -> + deliveries.transition( + recipientDeliveryId, + RecipientDeliveryState.READY_TO_DISPATCH, + java.util.Optional.of(clock.instant()))); + } } diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/NotificationSubmissionService.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/NotificationSubmissionService.java index 2288edaf..c95c4c56 100644 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/NotificationSubmissionService.java +++ b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/NotificationSubmissionService.java @@ -3,7 +3,6 @@ package dev.caskeleton.application.notification.platform.dispatch; import dev.caskeleton.application.notification.platform.api.CancelCommand; import dev.caskeleton.application.notification.platform.api.CancelResult; import dev.caskeleton.application.notification.platform.api.NotificationId; -import dev.caskeleton.application.notification.platform.api.NotificationOrchestrator; import dev.caskeleton.application.notification.platform.api.NotificationPlan; import dev.caskeleton.application.notification.platform.api.NotificationReceipt; import dev.caskeleton.application.notification.platform.api.NotificationSnapshot; @@ -35,7 +34,7 @@ import java.util.Optional; * its recipient jobs are on disk and will be picked up even if this process dies in the next * millisecond. */ -public final class NotificationSubmissionService implements NotificationOrchestrator { +public final class NotificationSubmissionService { private final NotificationRequestStorePort requests; private final RecipientDeliveryStorePort recipients; @@ -77,12 +76,10 @@ public final class NotificationSubmissionService implements NotificationOrchestr this.clock = Objects.requireNonNull(clock, "clock"); } - @Override public NotificationReceipt submit(NotificationPlan plan) { return accept(plan, Optional.empty()); } - @Override public NotificationReceipt schedule(NotificationPlan plan, Instant scheduleAt) { Objects.requireNonNull(scheduleAt, "scheduleAt"); return accept(plan, Optional.of(scheduleAt)); @@ -255,7 +252,6 @@ public final class NotificationSubmissionService implements NotificationOrchestr return existing.receipt(); } - @Override public CancelResult cancel(NotificationId notificationId, CancelCommand command) { Objects.requireNonNull(notificationId, "notificationId"); Objects.requireNonNull(command, "command"); @@ -319,7 +315,6 @@ public final class NotificationSubmissionService implements NotificationOrchestr } } - @Override public NotificationSnapshot get(NotificationId notificationId) { Objects.requireNonNull(notificationId, "notificationId"); return transactions.inRead(() -> readInTransaction(notificationId)); diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/ReconciliationService.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/ReconciliationService.java index 25ddb983..fd871b54 100644 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/ReconciliationService.java +++ b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/ReconciliationService.java @@ -12,6 +12,7 @@ import dev.caskeleton.application.notification.platform.observation.Notification import dev.caskeleton.application.notification.platform.observation.NotificationMetricName; import dev.caskeleton.application.notification.platform.observation.NotificationMetricsPort; import dev.caskeleton.application.notification.platform.provider.ReconciliationResult; +import dev.caskeleton.application.transaction.TransactionPort; import java.time.Clock; import java.util.Map; import java.util.Objects; @@ -23,6 +24,10 @@ import java.util.Optional; *

A confirmed answer is appended to the same ledger as a callback, tagged {@code * RECONCILIATION}, and then projected by the same projector. That is what keeps replay possible: * there is no second, privileged path that writes projections directly. + * + *

The provider is asked with no transaction open, and each write opens its own. The append + * commits before projection so a confirmed answer survives a projection failure: the event stays + * {@code PENDING} and the replay worker projects it later. */ public final class ReconciliationService { @@ -34,6 +39,7 @@ public final class ReconciliationService { private final NotificationAuditPort audit; private final NotificationMetricsPort metrics; private final SyntheticEventFingerprint fingerprints; + private final TransactionPort transactions; private final Clock clock; public ReconciliationService( @@ -45,6 +51,7 @@ public final class ReconciliationService { NotificationAuditPort audit, NotificationMetricsPort metrics, SyntheticEventFingerprint fingerprints, + TransactionPort transactions, Clock clock) { this.attempts = Objects.requireNonNull(attempts, "attempts"); this.recipients = Objects.requireNonNull(recipients, "recipients"); @@ -54,6 +61,7 @@ public final class ReconciliationService { this.audit = Objects.requireNonNull(audit, "audit"); this.metrics = Objects.requireNonNull(metrics, "metrics"); this.fingerprints = Objects.requireNonNull(fingerprints, "fingerprints"); + this.transactions = Objects.requireNonNull(transactions, "transactions"); this.clock = Objects.requireNonNull(clock, "clock"); } @@ -79,18 +87,22 @@ public final class ReconciliationService { switch (result) { case ReconciliationResult.Confirmed confirmed -> { var appended = - ledger.append( - new VerifiedProviderEvent( - attempt.providerProfileId(), - confirmed.event(), - Optional.of(attempt.attemptId()), - ProviderEventSource.RECONCILIATION, - true, - clock.instant(), - new byte[0], - emptyDigest(), - fingerprints.of( - attempt.providerProfileId(), attempt.attemptId(), confirmed.event()))); + transactions.inWrite( + () -> + ledger.append( + new VerifiedProviderEvent( + attempt.providerProfileId(), + confirmed.event(), + Optional.of(attempt.attemptId()), + ProviderEventSource.RECONCILIATION, + true, + clock.instant(), + new byte[0], + emptyDigest(), + fingerprints.of( + attempt.providerProfileId(), + attempt.attemptId(), + confirmed.event())))); appended.newEvents().forEach(projection::project); audit.record( new NotificationAuditEvent( @@ -105,10 +117,12 @@ public final class ReconciliationService { Map.of("provider", attempt.providerId().value(), "correction", "CONFIRMED")); } case ReconciliationResult.StillUnknown unknown -> - recipients.transition( - attempt.recipientDeliveryId(), - RecipientDeliveryState.RECONCILIATION_REQUIRED, - Optional.of(unknown.nextCheckAt())); + transactions.inWrite( + () -> + recipients.transition( + attempt.recipientDeliveryId(), + RecipientDeliveryState.RECONCILIATION_REQUIRED, + Optional.of(unknown.nextCheckAt()))); case ReconciliationResult.Unsupported ignored -> metrics.increment( NotificationMetricName.RECONCILIATION, diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/email/EmailNotification.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/email/EmailNotification.java deleted file mode 100644 index d3004a5f..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/email/EmailNotification.java +++ /dev/null @@ -1,33 +0,0 @@ -package dev.caskeleton.application.notification.platform.email; - -import dev.caskeleton.application.notification.platform.api.ContactPointId; -import dev.caskeleton.application.notification.platform.api.CorrelationId; -import dev.caskeleton.application.notification.platform.api.IdempotencyKey; -import dev.caskeleton.application.notification.platform.api.NotificationVariable; -import dev.caskeleton.application.notification.platform.api.TemplateSelection; -import dev.caskeleton.application.notification.platform.api.TenantId; -import java.time.Instant; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -/** N1 email intent. One recipient, one channel, durable acceptance only. */ -public record EmailNotification( - TenantId tenantId, - IdempotencyKey idempotencyKey, - ContactPointId recipient, - TemplateSelection template, - Map variables, - Optional expiresAt, - CorrelationId correlationId) { - - public EmailNotification { - Objects.requireNonNull(tenantId, "tenantId"); - Objects.requireNonNull(idempotencyKey, "idempotencyKey"); - Objects.requireNonNull(recipient, "recipient"); - Objects.requireNonNull(template, "template"); - variables = Map.copyOf(Objects.requireNonNull(variables, "variables")); - Objects.requireNonNull(expiresAt, "expiresAt"); - Objects.requireNonNull(correlationId, "correlationId"); - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/email/EmailNotifier.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/email/EmailNotifier.java deleted file mode 100644 index e50b072c..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/email/EmailNotifier.java +++ /dev/null @@ -1,10 +0,0 @@ -package dev.caskeleton.application.notification.platform.email; - -import dev.caskeleton.application.notification.platform.api.NotificationReceipt; - -/** N1 email facade. Returns after durable acceptance; it never waits for the provider. */ -public interface EmailNotifier { - - /** Accept an email notification. */ - NotificationReceipt send(EmailNotification notification); -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/provider/NotificationProviderAdapter.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/provider/NotificationProviderAdapter.java index 542f3c60..8c0d9ccd 100644 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/provider/NotificationProviderAdapter.java +++ b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/provider/NotificationProviderAdapter.java @@ -9,7 +9,7 @@ import java.util.concurrent.CompletionStage; * Provider adapter SPI. * *

The asynchronous type is {@link CompletionStage} so that no reactive library leaks into the - * core contract; a Reactor facade wraps it separately. + * core contract. */ public interface NotificationProviderAdapter { diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/push/ApplicationIdentity.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/push/ApplicationIdentity.java deleted file mode 100644 index 2e00f9a9..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/push/ApplicationIdentity.java +++ /dev/null @@ -1,16 +0,0 @@ -package dev.caskeleton.application.notification.platform.push; - -import java.util.Objects; - -/** The authenticated application session a receipt arrived on. */ -public record ApplicationIdentity( - String applicationId, String authenticatedSubjectRef, boolean authenticated) { - - public ApplicationIdentity { - Objects.requireNonNull(applicationId, "applicationId"); - Objects.requireNonNull(authenticatedSubjectRef, "authenticatedSubjectRef"); - if (applicationId.isBlank() || authenticatedSubjectRef.isBlank()) { - throw new IllegalArgumentException("identity fields must not be blank"); - } - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/push/ApplicationReceipt.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/push/ApplicationReceipt.java deleted file mode 100644 index 74f1c1d9..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/push/ApplicationReceipt.java +++ /dev/null @@ -1,31 +0,0 @@ -package dev.caskeleton.application.notification.platform.push; - -import dev.caskeleton.application.notification.platform.api.DeliveryAttemptId; -import java.time.Instant; -import java.util.Objects; -import java.util.Optional; - -/** - * Evidence reported by the application after a push was shown or opened. - * - *

The client clock is advisory. The server's receive time is what the audit trail keeps, because - * a device clock is attacker-controlled and frequently just wrong. - */ -public record ApplicationReceipt( - String receiptId, - DeliveryAttemptId attemptId, - ReceiptKind kind, - String subjectRef, - Optional clientOccurredAt) { - - public ApplicationReceipt { - Objects.requireNonNull(receiptId, "receiptId"); - Objects.requireNonNull(attemptId, "attemptId"); - Objects.requireNonNull(kind, "kind"); - Objects.requireNonNull(subjectRef, "subjectRef"); - Objects.requireNonNull(clientOccurredAt, "clientOccurredAt"); - if (receiptId.isBlank() || subjectRef.isBlank()) { - throw new IllegalArgumentException("receiptId and subjectRef must not be blank"); - } - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/push/ApplicationReceiptService.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/push/ApplicationReceiptService.java deleted file mode 100644 index 7ffd8fb3..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/push/ApplicationReceiptService.java +++ /dev/null @@ -1,13 +0,0 @@ -package dev.caskeleton.application.notification.platform.push; - -/** - * Application-generated delivery evidence. - * - *

This is a separate evidence source, not a substitute for provider acceptance: a receipt can - * only strengthen what is known about an attempt that already exists. - */ -public interface ApplicationReceiptService { - - /** Record one authenticated receipt. */ - ReceiptResult record(ApplicationReceipt receipt, ApplicationIdentity identity); -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/push/MobilePushNotification.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/push/MobilePushNotification.java deleted file mode 100644 index 94fe2f90..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/push/MobilePushNotification.java +++ /dev/null @@ -1,36 +0,0 @@ -package dev.caskeleton.application.notification.platform.push; - -import dev.caskeleton.application.notification.platform.api.ContactPointId; -import dev.caskeleton.application.notification.platform.api.CorrelationId; -import dev.caskeleton.application.notification.platform.api.IdempotencyKey; -import dev.caskeleton.application.notification.platform.api.NotificationVariable; -import dev.caskeleton.application.notification.platform.api.TemplateSelection; -import dev.caskeleton.application.notification.platform.api.TenantId; -import java.time.Instant; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -/** - * N1 mobile push intent. The target kind (FID, legacy token, APNs token) stays in the contact - * point. - */ -public record MobilePushNotification( - TenantId tenantId, - IdempotencyKey idempotencyKey, - ContactPointId recipient, - TemplateSelection template, - Map variables, - Optional expiresAt, - CorrelationId correlationId) { - - public MobilePushNotification { - Objects.requireNonNull(tenantId, "tenantId"); - Objects.requireNonNull(idempotencyKey, "idempotencyKey"); - Objects.requireNonNull(recipient, "recipient"); - Objects.requireNonNull(template, "template"); - variables = Map.copyOf(Objects.requireNonNull(variables, "variables")); - Objects.requireNonNull(expiresAt, "expiresAt"); - Objects.requireNonNull(correlationId, "correlationId"); - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/push/MobilePushNotifier.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/push/MobilePushNotifier.java deleted file mode 100644 index 82ae107e..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/push/MobilePushNotifier.java +++ /dev/null @@ -1,10 +0,0 @@ -package dev.caskeleton.application.notification.platform.push; - -import dev.caskeleton.application.notification.platform.api.NotificationReceipt; - -/** N1 mobile push facade. */ -public interface MobilePushNotifier { - - /** Accept a mobile push notification. */ - NotificationReceipt send(MobilePushNotification notification); -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/push/ReceiptAuthorizationException.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/push/ReceiptAuthorizationException.java deleted file mode 100644 index 4443b5f3..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/push/ReceiptAuthorizationException.java +++ /dev/null @@ -1,18 +0,0 @@ -package dev.caskeleton.application.notification.platform.push; - -import dev.caskeleton.application.notification.platform.api.error.FailureCategory; -import dev.caskeleton.application.notification.platform.api.error.NotificationException; -import dev.caskeleton.application.notification.platform.api.error.NotificationFailureCode; -import dev.caskeleton.application.notification.platform.api.error.NotificationFailureDescriptor; - -/** Raised when a receipt does not belong to the authenticated session that reported it. */ -public class ReceiptAuthorizationException extends NotificationException { - - private static final long serialVersionUID = 1L; - - public ReceiptAuthorizationException() { - super( - NotificationFailureDescriptor.preDispatch( - NotificationFailureCode.VALIDATION_FAILED, FailureCategory.AUTHORIZATION)); - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/push/ReceiptKind.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/push/ReceiptKind.java deleted file mode 100644 index 61de6af9..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/push/ReceiptKind.java +++ /dev/null @@ -1,7 +0,0 @@ -package dev.caskeleton.application.notification.platform.push; - -/** What an application receipt proves. */ -public enum ReceiptKind { - DISPLAYED, - READ -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/push/ReceiptResult.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/push/ReceiptResult.java deleted file mode 100644 index fdfc15ca..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/push/ReceiptResult.java +++ /dev/null @@ -1,12 +0,0 @@ -package dev.caskeleton.application.notification.platform.push; - -import dev.caskeleton.application.notification.platform.api.DeliveryAttemptId; -import java.util.Objects; - -/** Whether the receipt was newly recorded; repeats are acknowledged without a second projection. */ -public record ReceiptResult(boolean created, DeliveryAttemptId attemptId) { - - public ReceiptResult { - Objects.requireNonNull(attemptId, "attemptId"); - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/security/NotificationRedactor.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/security/NotificationRedactor.java deleted file mode 100644 index dc28f7bc..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/security/NotificationRedactor.java +++ /dev/null @@ -1,37 +0,0 @@ -package dev.caskeleton.application.notification.platform.security; - -import java.util.Map; -import java.util.Objects; - -/** - * Central masking used by every logging and exception path. - * - *

Masking is by exact value replacement rather than by pattern rewriting, so a token that - * happens to look like ordinary text is still removed. - */ -public final class NotificationRedactor { - - private static final String MASK_PREFIX = "[redacted:"; - private static final String MASK_SUFFIX = "]"; - - /** Replace every classified value inside a free-text diagnostic string. */ - public String redact(String text, Map classifiedValues) { - Objects.requireNonNull(classifiedValues, "classifiedValues"); - if (text == null || text.isBlank()) { - return text; - } - String redacted = text; - for (Map.Entry entry : classifiedValues.entrySet()) { - if (entry.getKey() != null && !entry.getKey().isBlank()) { - redacted = redacted.replace(entry.getKey(), mask(entry.getValue())); - } - } - return redacted; - } - - /** Mask token for a kind. */ - public String mask(SensitiveValueKind kind) { - Objects.requireNonNull(kind, "kind"); - return MASK_PREFIX + kind.name() + MASK_SUFFIX; - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/security/SafeDiagnosticContext.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/security/SafeDiagnosticContext.java deleted file mode 100644 index 2140fd78..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/security/SafeDiagnosticContext.java +++ /dev/null @@ -1,73 +0,0 @@ -package dev.caskeleton.application.notification.platform.security; - -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Set; - -/** - * Structured diagnostics with a closed field set. - * - *

An allowlist rather than a denylist: the failure mode of a denylist is that the one field - * nobody thought of is the one that leaks. - */ -public final class SafeDiagnosticContext { - - private static final Set ALLOWED = - Set.of( - "channel", - "provider", - "providerProfile", - "operation", - "result", - "failureCategory", - "failureCode", - "templateId", - "notificationCategory", - "attemptBucket", - "sizeBucket", - "eventType", - "source"); - - private final Map fields; - - private SafeDiagnosticContext(Map fields) { - this.fields = Map.copyOf(fields); - } - - /** Allowed field names. */ - public static Set allowedFields() { - return ALLOWED; - } - - /** Start building a context. */ - public static Builder builder() { - return new Builder(); - } - - /** Immutable field view. */ - public Map fields() { - return fields; - } - - /** Builder that rejects any field outside the allowlist. */ - public static final class Builder { - - private final Map fields = new LinkedHashMap<>(); - - /** Add one allowlisted field. */ - public Builder put(String name, String value) { - Objects.requireNonNull(name, "name"); - if (!ALLOWED.contains(name)) { - throw new UnsafeDiagnosticFieldException(name); - } - fields.put(name, value); - return this; - } - - /** Build the context. */ - public SafeDiagnosticContext build() { - return new SafeDiagnosticContext(fields); - } - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/security/SensitiveValueClassifier.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/security/SensitiveValueClassifier.java deleted file mode 100644 index bb1866b9..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/security/SensitiveValueClassifier.java +++ /dev/null @@ -1,47 +0,0 @@ -package dev.caskeleton.application.notification.platform.security; - -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.regex.Pattern; - -/** - * Classifies a value so the redactor knows what it is masking. - * - *

Pattern matching is a safety net, not the primary mechanism: values the platform already knows - * to be sensitive are registered explicitly. - */ -public final class SensitiveValueClassifier { - - private static final Pattern EMAIL = Pattern.compile("[^\\s@]+@[^\\s@]+\\.[^\\s@]+"); - private static final Pattern E164 = Pattern.compile("\\+[1-9][0-9]{7,14}"); - - private final Map registered; - - public SensitiveValueClassifier(Map registered) { - this.registered = Map.copyOf(Objects.requireNonNull(registered, "registered")); - } - - /** Classify a value, if it is sensitive. */ - public Optional classify(String value) { - if (value == null || value.isBlank()) { - return Optional.empty(); - } - SensitiveValueKind explicit = registered.get(value); - if (explicit != null) { - return Optional.of(explicit); - } - if (EMAIL.matcher(value).matches()) { - return Optional.of(SensitiveValueKind.EMAIL_ADDRESS); - } - if (E164.matcher(value).matches()) { - return Optional.of(SensitiveValueKind.PHONE_NUMBER); - } - return Optional.empty(); - } - - /** Registered sensitive values. */ - public Map registered() { - return registered; - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/security/SensitiveValueKind.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/security/SensitiveValueKind.java deleted file mode 100644 index 1d4b7191..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/security/SensitiveValueKind.java +++ /dev/null @@ -1,17 +0,0 @@ -package dev.caskeleton.application.notification.platform.security; - -/** Kinds of value that must never reach a log line, a metric tag or an exception message. */ -public enum SensitiveValueKind { - EMAIL_ADDRESS, - PHONE_NUMBER, - PUSH_TARGET, - WEB_PUSH_ENDPOINT, - WEB_PUSH_KEY, - PROVIDER_CREDENTIAL, - CALLBACK_SECRET, - TEMPLATE_VARIABLE, - MESSAGE_BODY, - UNSUBSCRIBE_TOKEN, - ATTACHMENT_URL, - PROVIDER_REQUEST_ID -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/security/UnsafeDiagnosticFieldException.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/security/UnsafeDiagnosticFieldException.java deleted file mode 100644 index eec0d675..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/security/UnsafeDiagnosticFieldException.java +++ /dev/null @@ -1,11 +0,0 @@ -package dev.caskeleton.application.notification.platform.security; - -/** Raised when a diagnostic context is asked to carry a field outside the safe allowlist. */ -public class UnsafeDiagnosticFieldException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - public UnsafeDiagnosticFieldException(String fieldName) { - super("unsafe diagnostic field: " + fieldName); - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/sms/E164PhoneNumberParser.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/sms/E164PhoneNumberParser.java deleted file mode 100644 index 42004b80..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/sms/E164PhoneNumberParser.java +++ /dev/null @@ -1,27 +0,0 @@ -package dev.caskeleton.application.notification.platform.sms; - -import dev.caskeleton.application.notification.platform.contact.PhoneNumber; -import java.util.regex.Pattern; - -/** - * Strict E.164 parser. - * - *

Form and reachability are separate questions: a well-formed number can still be unassigned, - * and a provider lookup capability answers that second question separately. - */ -public final class E164PhoneNumberParser { - - private static final Pattern E164 = Pattern.compile("\\+[1-9][0-9]{1,14}"); - - /** Parse a value that must already be in international form. */ - public PhoneNumber parse(String value) { - if (value == null) { - throw new InvalidPhoneNumberException("MISSING"); - } - String trimmed = value.trim(); - if (!E164.matcher(trimmed).matches()) { - throw new InvalidPhoneNumberException("INVALID_E164"); - } - return new PhoneNumber(trimmed); - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/sms/GsmAlphabet.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/sms/GsmAlphabet.java deleted file mode 100644 index e83e92b9..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/sms/GsmAlphabet.java +++ /dev/null @@ -1,51 +0,0 @@ -package dev.caskeleton.application.notification.platform.sms; - -import java.util.OptionalInt; -import java.util.Set; - -/** - * GSM 03.38 alphabet. - * - *

Counting characters is not counting septets: nine characters in the extension table cost two - * septets each because they are sent as an escape plus the character, and a single character - * outside the alphabet forces the whole message into UCS-2. - */ -public final class GsmAlphabet { - - private static final String BASIC = - "@\u00a3$\u00a5\u00e8\u00e9\u00f9\u00ec\u00f2\u00c7\n\u00d8\u00f8\r\u00c5\u00e5" - + "\u0394_\u03a6\u0393\u039b\u03a9\u03a0\u03a8\u03a3\u0398\u039e\u001b" - + "\u00c6\u00e6\u00df\u00c9" - + " !\"#\u00a4%&'()*+,-./0123456789:;<=>?" - + "\u00a1ABCDEFGHIJKLMNOPQRSTUVWXYZ\u00c4\u00d6\u00d1\u00dc\u00a7" - + "\u00bfabcdefghijklmnopqrstuvwxyz\u00e4\u00f6\u00f1\u00fc\u00e0"; - - private static final Set EXTENDED = - Set.of('^', '{', '}', '\\', '[', '~', ']', '|', '\u20ac'); - - private GsmAlphabet() {} - - /** Whether every character can be sent as GSM-7. */ - public static boolean isGsm7(String text) { - return encodedSeptets(text).isPresent(); - } - - /** Septet count when the text is GSM-7, or empty when UCS-2 is required. */ - public static OptionalInt encodedSeptets(String text) { - if (text == null) { - return OptionalInt.empty(); - } - int septets = 0; - for (int index = 0; index < text.length(); index++) { - char character = text.charAt(index); - if (EXTENDED.contains(character)) { - septets += 2; - } else if (BASIC.indexOf(character) >= 0) { - septets += 1; - } else { - return OptionalInt.empty(); - } - } - return OptionalInt.of(septets); - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/sms/InvalidPhoneNumberException.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/sms/InvalidPhoneNumberException.java deleted file mode 100644 index 6f9ef74d..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/sms/InvalidPhoneNumberException.java +++ /dev/null @@ -1,26 +0,0 @@ -package dev.caskeleton.application.notification.platform.sms; - -import dev.caskeleton.application.notification.platform.api.error.FailureCategory; -import dev.caskeleton.application.notification.platform.api.error.NotificationException; -import dev.caskeleton.application.notification.platform.api.error.NotificationFailureCode; -import dev.caskeleton.application.notification.platform.api.error.NotificationFailureDescriptor; - -/** Raised for a value that is not in E.164 form. The rejected value is never echoed. */ -public class InvalidPhoneNumberException extends NotificationException { - - private static final long serialVersionUID = 1L; - - public InvalidPhoneNumberException(String reasonCode) { - super( - NotificationFailureDescriptor.preDispatch( - NotificationFailureCode.CONTACT_POINT_INVALID, FailureCategory.INVALID_RECIPIENT)); - this.reasonCode = reasonCode; - } - - private final String reasonCode; - - /** Why the value was rejected. */ - public String reasonCode() { - return reasonCode; - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/sms/SmsEncoding.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/sms/SmsEncoding.java deleted file mode 100644 index a1ee22ac..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/sms/SmsEncoding.java +++ /dev/null @@ -1,7 +0,0 @@ -package dev.caskeleton.application.notification.platform.sms; - -/** SMS transport encodings that decide segment size. */ -public enum SmsEncoding { - GSM_7, - UCS_2 -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/sms/SmsEstimate.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/sms/SmsEstimate.java deleted file mode 100644 index 01bbfbba..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/sms/SmsEstimate.java +++ /dev/null @@ -1,22 +0,0 @@ -package dev.caskeleton.application.notification.platform.sms; - -import java.util.Objects; - -/** - * Encoding and segment analysis of an SMS body. - * - *

No price is included: segment count is a protocol fact, tariffs are not. - */ -public record SmsEstimate( - SmsEncoding encoding, int segmentCount, int encodedLength, boolean exceedsRecommendedLimit) { - - public SmsEstimate { - Objects.requireNonNull(encoding, "encoding"); - if (segmentCount < 1) { - throw new IllegalArgumentException("segmentCount"); - } - if (encodedLength < 0) { - throw new IllegalArgumentException("encodedLength"); - } - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/sms/SmsNotification.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/sms/SmsNotification.java deleted file mode 100644 index aec0e4bf..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/sms/SmsNotification.java +++ /dev/null @@ -1,33 +0,0 @@ -package dev.caskeleton.application.notification.platform.sms; - -import dev.caskeleton.application.notification.platform.api.ContactPointId; -import dev.caskeleton.application.notification.platform.api.CorrelationId; -import dev.caskeleton.application.notification.platform.api.IdempotencyKey; -import dev.caskeleton.application.notification.platform.api.NotificationVariable; -import dev.caskeleton.application.notification.platform.api.TemplateSelection; -import dev.caskeleton.application.notification.platform.api.TenantId; -import java.time.Instant; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -/** N1 SMS intent. One E.164 contact point, one channel. */ -public record SmsNotification( - TenantId tenantId, - IdempotencyKey idempotencyKey, - ContactPointId recipient, - TemplateSelection template, - Map variables, - Optional expiresAt, - CorrelationId correlationId) { - - public SmsNotification { - Objects.requireNonNull(tenantId, "tenantId"); - Objects.requireNonNull(idempotencyKey, "idempotencyKey"); - Objects.requireNonNull(recipient, "recipient"); - Objects.requireNonNull(template, "template"); - variables = Map.copyOf(Objects.requireNonNull(variables, "variables")); - Objects.requireNonNull(expiresAt, "expiresAt"); - Objects.requireNonNull(correlationId, "correlationId"); - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/sms/SmsNotifier.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/sms/SmsNotifier.java deleted file mode 100644 index 035630f4..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/sms/SmsNotifier.java +++ /dev/null @@ -1,13 +0,0 @@ -package dev.caskeleton.application.notification.platform.sms; - -import dev.caskeleton.application.notification.platform.api.NotificationReceipt; - -/** N1 SMS facade. */ -public interface SmsNotifier { - - /** Accept an SMS notification. */ - NotificationReceipt send(SmsNotification notification); - - /** Compute encoding and segment count before sending. */ - SmsEstimate estimate(SmsNotification notification); -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/sms/SmsSegmentEstimator.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/sms/SmsSegmentEstimator.java deleted file mode 100644 index 69cbb715..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/sms/SmsSegmentEstimator.java +++ /dev/null @@ -1,39 +0,0 @@ -package dev.caskeleton.application.notification.platform.sms; - -/** - * Segment estimator. - * - *

{@code String.length()} is the wrong unit for both cost and capacity: a concatenated message - * spends six septets per segment on the user data header, and one non-GSM character halves the - * capacity of the entire message. - */ -public final class SmsSegmentEstimator { - - private static final int GSM_SINGLE = 160; - private static final int GSM_CONCATENATED = 153; - private static final int UCS2_SINGLE = 70; - private static final int UCS2_CONCATENATED = 67; - private static final int RECOMMENDED_SEGMENT_LIMIT = 3; - - /** Estimate encoding and segment count for a body. */ - public SmsEstimate estimate(String text) { - if (text == null) { - throw new IllegalArgumentException("text"); - } - var septets = GsmAlphabet.encodedSeptets(text); - if (septets.isPresent()) { - int units = septets.getAsInt(); - int segments = units <= GSM_SINGLE ? 1 : divideCeiling(units, GSM_CONCATENATED); - return new SmsEstimate( - SmsEncoding.GSM_7, segments, units, segments > RECOMMENDED_SEGMENT_LIMIT); - } - int units = text.length(); - int segments = units <= UCS2_SINGLE ? 1 : divideCeiling(units, UCS2_CONCATENATED); - return new SmsEstimate( - SmsEncoding.UCS_2, segments, units, segments > RECOMMENDED_SEGMENT_LIMIT); - } - - private static int divideCeiling(int value, int divisor) { - return (value + divisor - 1) / divisor; - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/webpush/WebPushNotification.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/webpush/WebPushNotification.java deleted file mode 100644 index 403cd435..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/webpush/WebPushNotification.java +++ /dev/null @@ -1,33 +0,0 @@ -package dev.caskeleton.application.notification.platform.webpush; - -import dev.caskeleton.application.notification.platform.api.ContactPointId; -import dev.caskeleton.application.notification.platform.api.CorrelationId; -import dev.caskeleton.application.notification.platform.api.IdempotencyKey; -import dev.caskeleton.application.notification.platform.api.NotificationVariable; -import dev.caskeleton.application.notification.platform.api.TemplateSelection; -import dev.caskeleton.application.notification.platform.api.TenantId; -import java.time.Instant; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -/** N1 Web Push intent. The subscription is a protected contact point, never a URL argument. */ -public record WebPushNotification( - TenantId tenantId, - IdempotencyKey idempotencyKey, - ContactPointId recipient, - TemplateSelection template, - Map variables, - Optional expiresAt, - CorrelationId correlationId) { - - public WebPushNotification { - Objects.requireNonNull(tenantId, "tenantId"); - Objects.requireNonNull(idempotencyKey, "idempotencyKey"); - Objects.requireNonNull(recipient, "recipient"); - Objects.requireNonNull(template, "template"); - variables = Map.copyOf(Objects.requireNonNull(variables, "variables")); - Objects.requireNonNull(expiresAt, "expiresAt"); - Objects.requireNonNull(correlationId, "correlationId"); - } -} diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/webpush/WebPushNotifier.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/webpush/WebPushNotifier.java deleted file mode 100644 index 32b7a73b..00000000 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/webpush/WebPushNotifier.java +++ /dev/null @@ -1,10 +0,0 @@ -package dev.caskeleton.application.notification.platform.webpush; - -import dev.caskeleton.application.notification.platform.api.NotificationReceipt; - -/** N1 Web Push facade. */ -public interface WebPushNotifier { - - /** Accept a Web Push notification. */ - NotificationReceipt send(WebPushNotification notification); -} diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/InitializeNotificationWriterFencesUseCaseTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/InitializeNotificationWriterFencesUseCaseTest.java deleted file mode 100644 index 4172e1ad..00000000 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/InitializeNotificationWriterFencesUseCaseTest.java +++ /dev/null @@ -1,149 +0,0 @@ -package dev.caskeleton.application.notification; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.application.transaction.TransactionPort; -import java.time.Clock; -import java.time.Instant; -import java.time.ZoneOffset; -import java.util.List; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.Supplier; -import org.junit.jupiter.api.Test; - -class InitializeNotificationWriterFencesUseCaseTest { - - @Test - void exactReviewedRouteSetIsInitializedAtomicallyInsidePhysicalRootWrite() { - NotificationWriterRouteSet routeSet = routeSet(); - TrackingRootTransactions transactions = new TrackingRootTransactions(); - AtomicInteger operations = new AtomicInteger(); - InitializeNotificationWriterFencesOperation operation = - (command, trustedRoutes, now) -> { - assertThat(transactions.active).isTrue(); - assertThat(trustedRoutes).isSameAs(routeSet); - operations.incrementAndGet(); - return new InitializeNotificationWriterFencesResult( - InitializeNotificationWriterFencesResult.Status.INITIALIZED, - trustedRoutes.canonicalRoutes().routes().size(), - trustedRoutes.digest()); - }; - InitializeNotificationWriterFencesUseCase useCase = - new InitializeNotificationWriterFencesUseCase( - routeSet, - operation, - transactions, - Clock.fixed(Instant.parse("2026-07-28T00:00:00Z"), ZoneOffset.UTC)); - - InitializeNotificationWriterFencesResult result = - useCase.handle(command(routeSet.canonicalRoutes(), routeSet.digest())); - - assertThat(transactions.rootCalls).isEqualTo(1); - assertThat(operations).hasValue(1); - assertThat(result.status()) - .isEqualTo(InitializeNotificationWriterFencesResult.Status.INITIALIZED); - } - - @Test - void routeOrDigestDriftFailsBeforeMutationAndCommandCannotInitializePartially() { - NotificationWriterRouteSet routeSet = routeSet(); - TrackingRootTransactions transactions = new TrackingRootTransactions(); - AtomicInteger operations = new AtomicInteger(); - InitializeNotificationWriterFencesUseCase useCase = - new InitializeNotificationWriterFencesUseCase( - routeSet, - (command, trustedRoutes, now) -> { - operations.incrementAndGet(); - throw new AssertionError("operation must not run"); - }, - transactions, - Clock.systemUTC()); - NotificationCanonicalWriterRouteSet partial = - new NotificationCanonicalWriterRouteSet( - List.of(routeSet.canonicalRoutes().routes().getFirst())); - - assertThatThrownBy(() -> useCase.handle(command(partial, partial.digest()))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("exact"); - assertThatThrownBy(() -> useCase.handle(command(routeSet.canonicalRoutes(), "0".repeat(64)))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("digest"); - assertThat(transactions.rootCalls).isZero(); - assertThat(operations).hasValue(0); - } - - private static InitializeNotificationWriterFencesCommand command( - NotificationCanonicalWriterRouteSet reviewedRoutes, String digest) { - return new InitializeNotificationWriterFencesCommand( - "initialize-operation-42", - reviewedRoutes, - digest, - "operator-42", - new NotificationReasonCode("INITIALIZE_REVIEWED_ROUTES")); - } - - static NotificationWriterRouteSet routeSet() { - NotificationCanonicalWriterRouteSet.RouteRevision email = - new NotificationCanonicalWriterRouteSet.RouteRevision( - new NotificationRouteId("security-email"), 2, 7); - NotificationCanonicalWriterRouteSet.RouteRevision slack = - new NotificationCanonicalWriterRouteSet.RouteRevision( - new NotificationRouteId("security-slack"), 1, 3); - NotificationCanonicalWriterRouteSet canonical = - new NotificationCanonicalWriterRouteSet(List.of(email, slack)); - return new NotificationWriterRouteSet( - canonical, - List.of( - new NotificationWriterRouteSet.RouteProfile( - email, - java.util.Optional.of("legacy-email"), - List.of( - new NotificationWriterRouteSet.TransportProfile( - "legacy-http-v1", - NotificationWriterRouteSet.ProofClass.QUIESCENCE_REQUIRED, - "evidence-r1", - true))), - new NotificationWriterRouteSet.RouteProfile( - slack, - java.util.Optional.of("legacy-slack"), - List.of( - new NotificationWriterRouteSet.TransportProfile( - "legacy-slack-v1", - NotificationWriterRouteSet.ProofClass.HARD_BOUND_PROVEN, - "evidence-r2", - true))))); - } - - static final class TrackingRootTransactions implements TransactionPort { - - int rootCalls; - boolean active; - - @Override - public T inWrite(Supplier action) { - return action.get(); - } - - @Override - public T inRootWrite(Supplier action) { - rootCalls++; - active = true; - try { - return action.get(); - } finally { - active = false; - } - } - - @Override - public T inRead(Supplier action) { - return action.get(); - } - - @Override - public T inNew(Supplier action) { - return action.get(); - } - } -} diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/NotificationAdmissionGateUseCaseTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/NotificationAdmissionGateUseCaseTest.java deleted file mode 100644 index 007330a3..00000000 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/NotificationAdmissionGateUseCaseTest.java +++ /dev/null @@ -1,167 +0,0 @@ -package dev.caskeleton.application.notification; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.application.transaction.TransactionPort; -import java.time.Clock; -import java.time.Instant; -import java.time.ZoneOffset; -import java.util.ArrayList; -import java.util.List; -import java.util.function.Supplier; -import org.junit.jupiter.api.Test; - -class NotificationAdmissionGateUseCaseTest { - - @Test - void readinessProbeRunsOutsideTransactionThenResumeCasRunsInsideShortWrite() { - List trace = new ArrayList<>(); - TrackingTransactions transactions = new TrackingTransactions(trace); - NotificationAdmissionReadinessPort admission = - new NotificationAdmissionReadinessPort() { - @Override - public ParkResult park(ParkRequest request) { - return ParkResult.PARKED; - } - - @Override - public ReadinessProbe probe(ResumeRequest request) { - assertThat(transactions.active).isFalse(); - trace.add("probe"); - return new ReadinessProbe(true, new NotificationReasonCode("READINESS_CONFIRMED")); - } - - @Override - public ResumeResult resume( - ResumeRequest request, ReadinessProbe probe, Instant resumedAt) { - assertThat(transactions.active).isTrue(); - assertThat(request.operationToken()).isEqualTo("resume-operation-42"); - assertThat(request.actorReference()).isEqualTo("operator-42"); - assertThat(request.maximumParkedLegs()).isEqualTo(10); - trace.add("resume"); - return new ResumeResult( - ResumeStatus.RESUMED, request.expectedGeneration() + 1, 4, 2, 1, 1, 0, 0); - } - }; - NotificationAdmissionGateUseCase useCase = - new NotificationAdmissionGateUseCase( - admission, - transactions, - Clock.fixed(Instant.parse("2026-07-28T00:00:00Z"), ZoneOffset.UTC)); - - NotificationAdmissionGateUseCase.Result result = useCase.handle(command()); - - assertThat(trace).containsExactly("probe", "tx-begin", "resume", "tx-end"); - assertThat(result.status()).isEqualTo(NotificationAdmissionGateUseCase.Result.Status.RESUMED); - } - - @Test - void failedProbeDoesNotEnterMutationTransaction() { - List trace = new ArrayList<>(); - TrackingTransactions transactions = new TrackingTransactions(trace); - NotificationAdmissionReadinessPort admission = - new NotificationAdmissionReadinessPort() { - @Override - public ParkResult park(ParkRequest request) { - return ParkResult.PARKED; - } - - @Override - public ReadinessProbe probe(ResumeRequest request) { - trace.add("probe"); - return new ReadinessProbe(false, new NotificationReasonCode("READINESS_FAILED")); - } - - @Override - public ResumeResult resume( - ResumeRequest request, ReadinessProbe probe, Instant resumedAt) { - throw new AssertionError("resume must not run"); - } - }; - - NotificationAdmissionGateUseCase.Result result = - new NotificationAdmissionGateUseCase( - admission, - transactions, - Clock.fixed(Instant.parse("2026-07-28T00:00:00Z"), ZoneOffset.UTC)) - .handle(command()); - - assertThat(trace).containsExactly("probe"); - assertThat(result.status()).isEqualTo(NotificationAdmissionGateUseCase.Result.Status.NOT_READY); - } - - @Test - void resumeOutcomeIsBoundedAndInitialFallbackActivationIsForbidden() { - assertThatThrownBy( - () -> - new NotificationAdmissionReadinessPort.ResumeResult( - NotificationAdmissionReadinessPort.ResumeStatus.RESUMED, 8, 1, 0, 0, 0, 0, 1)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("fallback"); - assertThatThrownBy( - () -> - new NotificationAdmissionGateCommand( - "resume-operation-42", - new NotificationRouteId("security-email"), - 2, - NotificationFaultScope.PROVIDER_BINDING, - "provider-binding-scope-42", - 7, - 101, - "operator-42", - new NotificationReasonCode("OPERATOR_RESUME"))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("1..100"); - } - - private static NotificationAdmissionGateCommand command() { - return new NotificationAdmissionGateCommand( - "resume-operation-42", - new NotificationRouteId("security-email"), - 2, - NotificationFaultScope.PROVIDER_BINDING, - "provider-binding-scope-42", - 7, - 10, - "operator-42", - new NotificationReasonCode("OPERATOR_RESUME")); - } - - private static final class TrackingTransactions implements TransactionPort { - - private final List trace; - private boolean active; - - private TrackingTransactions(List trace) { - this.trace = trace; - } - - @Override - public T inWrite(Supplier action) { - trace.add("tx-begin"); - active = true; - try { - return action.get(); - } finally { - active = false; - trace.add("tx-end"); - } - } - - @Override - public T inRootWrite(Supplier action) { - return inWrite(action); - } - - @Override - public T inRead(Supplier action) { - return action.get(); - } - - @Override - public T inNew(Supplier action) { - return action.get(); - } - } -} diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/NotificationCanonicalWriterFenceGuardTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/NotificationCanonicalWriterFenceGuardTest.java deleted file mode 100644 index a06f9096..00000000 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/NotificationCanonicalWriterFenceGuardTest.java +++ /dev/null @@ -1,65 +0,0 @@ -package dev.caskeleton.application.notification; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.util.List; -import java.util.concurrent.atomic.AtomicInteger; -import org.junit.jupiter.api.Test; - -class NotificationCanonicalWriterFenceGuardTest { - - @Test - void exactCanonicalOwnerAndGenerationAreRequiredBeforeIntentAppend() { - NotificationCanonicalWriterRouteSet.RouteRevision route = route(); - NotificationCanonicalWriterFencePort port = - request -> - new NotificationCanonicalWriterFencePort.FenceSnapshot( - request.route(), NotificationWriterOwnership.CANONICAL, 8); - NotificationCanonicalWriterFenceGuard guard = - new NotificationCanonicalWriterFenceGuard( - port, new NotificationCanonicalWriterRouteSet(List.of(route))); - AtomicInteger appends = new AtomicInteger(); - - guard.assertCanonical(route, 8); - appends.incrementAndGet(); - - assertThat(appends).hasValue(1); - assertThatThrownBy(() -> guard.assertCanonical(route, 7)) - .isInstanceOf(NotificationApplicationException.class) - .hasMessageContaining("STALE_CANONICAL_WRITER_GENERATION"); - } - - @Test - void legacyOwnerOrUnknownRouteFailsClosedBeforeAppend() { - NotificationCanonicalWriterRouteSet.RouteRevision route = route(); - NotificationCanonicalWriterFenceGuard legacyGuard = - new NotificationCanonicalWriterFenceGuard( - request -> - new NotificationCanonicalWriterFencePort.FenceSnapshot( - request.route(), NotificationWriterOwnership.LEGACY, 7), - new NotificationCanonicalWriterRouteSet(List.of(route))); - AtomicInteger appends = new AtomicInteger(); - - assertThatThrownBy( - () -> { - legacyGuard.assertCanonical(route, 7); - appends.incrementAndGet(); - }) - .isInstanceOf(NotificationApplicationException.class) - .hasMessageContaining("CANONICAL_WRITER_NOT_OWNER"); - assertThatThrownBy( - () -> - legacyGuard.assertCanonical( - new NotificationCanonicalWriterRouteSet.RouteRevision( - new NotificationRouteId("unknown-route"), 1, 0), - 7)) - .isInstanceOf(IllegalArgumentException.class); - assertThat(appends).hasValue(0); - } - - private static NotificationCanonicalWriterRouteSet.RouteRevision route() { - return new NotificationCanonicalWriterRouteSet.RouteRevision( - new NotificationRouteId("security-email"), 2, 7); - } -} diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/NotificationCapabilityCompatibilityValidatorTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/NotificationCapabilityCompatibilityValidatorTest.java deleted file mode 100644 index 3d4f8adc..00000000 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/NotificationCapabilityCompatibilityValidatorTest.java +++ /dev/null @@ -1,157 +0,0 @@ -package dev.caskeleton.application.notification; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.time.Duration; -import java.util.Optional; -import java.util.Set; -import org.junit.jupiter.api.Test; - -class NotificationCapabilityCompatibilityValidatorTest { - - @Test - void pureValidatorAcceptsExactDurableReceiptCapableApplicationContract() { - NotificationKindPolicy policy = policy(); - NotificationCapabilityCompatibilityValidator validator = - new NotificationCapabilityCompatibilityValidator(); - - NotificationCapabilityCompatibilityValidator.Compatibility result = - validator.validate(policy, provider(true), store(policy), Optional.of(ingress()), true); - - assertThat(result.compatible()).isTrue(); - assertThat(result.reasonCodes()).isEmpty(); - } - - @Test - void modeAdmissionReceiptAndFrozenRevisionMismatchesFailClosedWithoutAdapterTypes() { - NotificationKindPolicy policy = policy(); - NotificationCapabilityCompatibilityValidator validator = - new NotificationCapabilityCompatibilityValidator(); - - NotificationCapabilityCompatibilityValidator.Compatibility result = - validator.validate( - policy, - provider(false), - new NotificationStoreCapabilityDescriptor( - false, - false, - true, - 100, - Set.of(policy.policyRevision() - 1), - Set.of(new NotificationTemplateRef("security-alert", 99))), - Optional.empty(), - true); - - assertThat(result.compatible()).isFalse(); - assertThat(result.reasonCodes()) - .contains( - new NotificationReasonCode("PROVIDER_RECEIPT_UNSUPPORTED"), - new NotificationReasonCode("DURABLE_STORE_UNAVAILABLE"), - new NotificationReasonCode("POLICY_REVISION_UNAVAILABLE"), - new NotificationReasonCode("TEMPLATE_REVISION_UNAVAILABLE"), - new NotificationReasonCode("RECEIPT_INGRESS_UNAVAILABLE")); - assertThat( - java.util.Arrays.stream( - NotificationCapabilityCompatibilityValidator.class.getDeclaredMethods()) - .flatMap( - method -> - java.util.Arrays.stream(method.getGenericParameterTypes()) - .map(java.lang.reflect.Type::getTypeName))) - .noneMatch( - name -> - name.contains("adapter.") - || name.contains("Settings") - || name.contains("CompiledNotificationBinding")); - } - - @Test - void providerChannelOrCodeOwnedModeMismatchIsRejected() { - NotificationKindPolicy policy = policy(); - NotificationProviderCapabilityDescriptor wrongChannel = - new NotificationProviderCapabilityDescriptor( - "provider-capability-42", - NotificationChannel.SLACK, - Set.of(NotificationMode.DURABLE_ASYNC), - true, - true, - true, - 16, - 1_000_000); - - assertThatThrownBy( - () -> - new NotificationCapabilityCompatibilityValidator() - .requireCompatible( - policy, wrongChannel, store(policy), Optional.of(ingress()), true)) - .isInstanceOf(NotificationApplicationException.class) - .hasMessageContaining("NOTIFICATION_CAPABILITY_INCOMPATIBLE"); - } - - @Test - void reconciliationPolicyRequiresProviderReconciliationCapability() { - NotificationKindPolicy policy = policy(); - NotificationProviderCapabilityDescriptor withoutReconciliation = - new NotificationProviderCapabilityDescriptor( - "provider-capability-42", - NotificationChannel.EMAIL, - Set.of(NotificationMode.DURABLE_ASYNC), - true, - false, - true, - 16, - 1_000_000); - - NotificationCapabilityCompatibilityValidator.Compatibility result = - new NotificationCapabilityCompatibilityValidator() - .validate(policy, withoutReconciliation, store(policy), Optional.of(ingress()), true); - - assertThat(result.compatible()).isFalse(); - assertThat(result.reasonCodes()) - .containsExactly(new NotificationReasonCode("PROVIDER_RECONCILIATION_UNSUPPORTED")); - } - - private static NotificationKindPolicy policy() { - return new NotificationKindPolicy( - new NotificationKindId("security-alert"), - NotificationChannel.EMAIL, - new NotificationRouteId("security-email"), - new NotificationTemplateRef("security-alert", 3), - NotificationMode.DURABLE_ASYNC, - NotificationAdmissionClass.SECURITY_CRITICAL, - NotificationRouteStrategy.SINGLE, - ConsentCheckMode.RECHECK_BEFORE_EACH_DELIVERY, - 7, - 1, - 3, - 0, - 1, - 4, - Duration.ofHours(2)); - } - - private static NotificationProviderCapabilityDescriptor provider(boolean receipts) { - return new NotificationProviderCapabilityDescriptor( - "provider-capability-42", - NotificationChannel.EMAIL, - Set.of(NotificationMode.DURABLE_ASYNC), - receipts, - true, - true, - 16, - 1_000_000); - } - - private static NotificationStoreCapabilityDescriptor store(NotificationKindPolicy policy) { - return new NotificationStoreCapabilityDescriptor( - true, true, true, 100, Set.of(policy.policyRevision()), Set.of(policy.templateRef())); - } - - private static NotificationReceiptIngressCapabilityDescriptor ingress() { - return new NotificationReceiptIngressCapabilityDescriptor( - NotificationChannel.EMAIL, - true, - true, - java.util.EnumSet.allOf(NotificationReceiptFact.Type.class)); - } -} diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/NotificationDispatchUseCaseTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/NotificationDispatchUseCaseTest.java deleted file mode 100644 index b5f9b91c..00000000 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/NotificationDispatchUseCaseTest.java +++ /dev/null @@ -1,426 +0,0 @@ -package dev.caskeleton.application.notification; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.application.transaction.TransactionPort; -import java.time.Clock; -import java.time.Instant; -import java.time.ZoneOffset; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.function.Supplier; -import org.junit.jupiter.api.Test; - -class NotificationDispatchUseCaseTest { - - private static final Instant NOW = Instant.parse("2026-07-28T00:00:00Z"); - - @Test - void claimAuthorizeProviderAndFinalizeUseShortTransactionsAroundProviderIo() { - List trace = new ArrayList<>(); - TrackingTransactionPort transactions = new TrackingTransactionPort(trace); - RecordingStore store = new RecordingStore(trace, sampleClaim(), finalizationApplied()); - NotificationProviderAttemptPort provider = - attempt -> { - assertThat(transactions.active()).isFalse(); - trace.add("provider"); - return accepted(); - }; - NotificationDispatchUseCase useCase = - new NotificationDispatchUseCase( - store, - provider, - request -> NotificationAdmissionReadinessPort.ParkResult.PARKED, - transactions, - Clock.fixed(NOW, ZoneOffset.UTC)); - - NotificationDispatchResult result = useCase.handle(new NotificationDispatchCommand(10)); - - assertThat(trace) - .containsExactly( - "tx-begin", - "claim", - "tx-end", - "tx-begin", - "authorize", - "tx-end", - "provider", - "tx-begin", - "finalize", - "tx-end"); - assertThat(store.authorizedAttempt.claimToken()) - .isNotEqualTo(store.authorizedAttempt.executionToken()); - assertThat(result).isEqualTo(new NotificationDispatchResult(1, 1, 1, 1, 0, 0, 0)); - } - - @Test - void staleClaimNeverCallsProviderOrFinalize() { - List trace = new ArrayList<>(); - TrackingTransactionPort transactions = new TrackingTransactionPort(trace); - RecordingStore store = - new RecordingStore( - trace, - sampleClaim(), - new NotificationDeliveryStorePort.StaleClaim( - sampleClaim().deliveryId(), new NotificationReasonCode("STALE_CLAIM_TOKEN"))); - AtomicBoolean providerCalled = new AtomicBoolean(); - NotificationDispatchUseCase useCase = - new NotificationDispatchUseCase( - store, - attempt -> { - providerCalled.set(true); - return accepted(); - }, - request -> NotificationAdmissionReadinessPort.ParkResult.PARKED, - transactions, - Clock.fixed(NOW, ZoneOffset.UTC)); - - NotificationDispatchResult result = useCase.handle(new NotificationDispatchCommand(1)); - - assertThat(providerCalled).isFalse(); - assertThat(store.finalization).isNull(); - assertThat(result.staleClaimCount()).isEqualTo(1); - } - - @Test - void fallbackIsEligibleOnlyForDefinitelyNotAppliedAndIndeterminateIsTerminal() { - RecordingStore definiteStore = - dispatchWithOutcome( - new ProviderAttemptOutcome( - SubmissionCertainty.DEFINITELY_NOT_APPLIED, - RetryDisposition.TERMINAL, - NotificationFaultScope.DELIVERY, - new NotificationReasonCode("INVALID_RECIPIENT"), - Optional.empty(), - "correlation-42", - Optional.empty())); - RecordingStore indeterminateStore = - dispatchWithOutcome( - new ProviderAttemptOutcome( - SubmissionCertainty.INDETERMINATE, - RetryDisposition.NOT_APPLICABLE, - NotificationFaultScope.DELIVERY, - new NotificationReasonCode("RESPONSE_LOST"), - Optional.empty(), - "correlation-42", - Optional.empty())); - - assertThat(definiteStore.finalization.fallbackEligible()).isTrue(); - assertThat(definiteStore.finalization.terminalState()) - .isEqualTo(NotificationDeliveryStorePort.TerminalState.TERMINAL_FAILURE); - assertThat(indeterminateStore.finalization.fallbackEligible()).isFalse(); - assertThat(indeterminateStore.finalization.terminalState()) - .isEqualTo(NotificationDeliveryStorePort.TerminalState.TERMINAL_INDETERMINATE); - } - - @Test - void parkBindingCasRunsInFinalizeTransactionAndDoesNotActivateInitialFallback() { - List trace = new ArrayList<>(); - TrackingTransactionPort transactions = new TrackingTransactionPort(trace); - RecordingStore store = new RecordingStore(trace, sampleClaim(), finalizationApplied()); - AtomicBoolean parkInsideTransaction = new AtomicBoolean(); - NotificationDispatchUseCase useCase = - new NotificationDispatchUseCase( - store, - attempt -> - new ProviderAttemptOutcome( - SubmissionCertainty.DEFINITELY_NOT_APPLIED, - RetryDisposition.PARK_BINDING, - NotificationFaultScope.PROVIDER_BINDING, - new NotificationReasonCode("PROVIDER_AUTH_REJECTED"), - Optional.empty(), - "correlation-42", - Optional.empty()), - request -> { - parkInsideTransaction.set(transactions.active()); - assertThat(request.expectedGeneration()).isEqualTo(7); - return NotificationAdmissionReadinessPort.ParkResult.PARKED; - }, - transactions, - Clock.fixed(NOW, ZoneOffset.UTC)); - - NotificationDispatchResult result = useCase.handle(new NotificationDispatchCommand(1)); - - assertThat(parkInsideTransaction).isTrue(); - assertThat(store.finalization.terminalState()) - .isEqualTo(NotificationDeliveryStorePort.TerminalState.PARKED_BINDING); - assertThat(store.finalization.fallbackEligible()).isFalse(); - assertThat(result.parkedCount()).isEqualTo(1); - } - - @Test - void staleParkGenerationRequeuesTheLegInsteadOfStrandingItAsParked() { - List trace = new ArrayList<>(); - RecordingStore store = new RecordingStore(trace, sampleClaim(), finalizationApplied()); - NotificationDispatchResult result = - new NotificationDispatchUseCase( - store, - attempt -> - new ProviderAttemptOutcome( - SubmissionCertainty.DEFINITELY_NOT_APPLIED, - RetryDisposition.PARK_BINDING, - NotificationFaultScope.PROVIDER_BINDING, - new NotificationReasonCode("PROVIDER_AUTH_REJECTED"), - Optional.empty(), - "correlation-42", - Optional.empty()), - request -> NotificationAdmissionReadinessPort.ParkResult.STALE_GENERATION, - new TrackingTransactionPort(trace), - Clock.fixed(NOW, ZoneOffset.UTC)) - .handle(new NotificationDispatchCommand(1)); - - assertThat(store.finalization.parkResult()) - .isEqualTo(NotificationAdmissionReadinessPort.ParkResult.STALE_GENERATION); - assertThat(store.finalization.terminalState()) - .isEqualTo(NotificationDeliveryStorePort.TerminalState.RETRY_SCHEDULED); - assertThat(result.parkedCount()).isZero(); - } - - @Test - void exactLateResultIsCountedWithoutBlindProviderRetry() { - RecordingStore store = - new RecordingStore(new ArrayList<>(), sampleClaim(), finalizationLateExact()); - AtomicBoolean providerCalled = new AtomicBoolean(); - NotificationDispatchUseCase useCase = - new NotificationDispatchUseCase( - store, - attempt -> { - providerCalled.set(true); - return accepted(); - }, - request -> NotificationAdmissionReadinessPort.ParkResult.PARKED, - new TrackingTransactionPort(new ArrayList<>()), - Clock.fixed(NOW, ZoneOffset.UTC)); - - NotificationDispatchResult result = useCase.handle(new NotificationDispatchCommand(1)); - - assertThat(providerCalled).isTrue(); - assertThat(result.providerCallCount()).isEqualTo(1); - assertThat(result.finalizedCount()).isEqualTo(1); - } - - @Test - void staleAttemptExecutionTokenCannotFinalizeOrTriggerAnotherProviderCall() { - RecordingStore store = - new RecordingStore( - new ArrayList<>(), - sampleClaim(), - NotificationDeliveryStorePort.FinalizationResult.STALE_EXECUTION_TOKEN); - AtomicBoolean providerCalled = new AtomicBoolean(); - NotificationDispatchResult result = - new NotificationDispatchUseCase( - store, - attempt -> { - providerCalled.set(true); - return accepted(); - }, - request -> NotificationAdmissionReadinessPort.ParkResult.PARKED, - new TrackingTransactionPort(new ArrayList<>()), - Clock.fixed(NOW, ZoneOffset.UTC)) - .handle(new NotificationDispatchCommand(1)); - - assertThat(providerCalled).isTrue(); - assertThat(result.providerCallCount()).isEqualTo(1); - assertThat(result.finalizedCount()).isZero(); - } - - private static RecordingStore dispatchWithOutcome(ProviderAttemptOutcome outcome) { - RecordingStore store = - new RecordingStore(new ArrayList<>(), sampleClaim(), finalizationApplied()); - NotificationDispatchUseCase useCase = - new NotificationDispatchUseCase( - store, - attempt -> outcome, - request -> NotificationAdmissionReadinessPort.ParkResult.PARKED, - new TrackingTransactionPort(new ArrayList<>()), - Clock.fixed(NOW, ZoneOffset.UTC)); - useCase.handle(new NotificationDispatchCommand(1)); - return store; - } - - private static NotificationDeliveryStorePort.ClaimedDelivery sampleClaim() { - return new NotificationDeliveryStorePort.ClaimedDelivery( - new NotificationDeliveryId("delivery-42"), samplePlan(), 0, "claim-token-42", 3, 7); - } - - private static NotificationFrozenPlan samplePlan() { - NotificationKindPolicy policy = - new NotificationKindPolicy( - new NotificationKindId("security-alert"), - NotificationChannel.EMAIL, - new NotificationRouteId("security-email"), - new NotificationTemplateRef("security-alert", 1), - NotificationMode.DURABLE_ASYNC, - NotificationAdmissionClass.SECURITY_CRITICAL, - NotificationRouteStrategy.SINGLE, - ConsentCheckMode.SNAPSHOT_AT_APPEND, - 2, - 1, - 2, - 0, - 1, - 3, - java.time.Duration.ofHours(1)); - NotificationIntentDraft draft = - new NotificationIntentDraft( - new NotificationIntentId("intent-42"), - policy, - java.util.Locale.ENGLISH, - new EmailRecipientReference("recipient-ref-42"), - new NotificationTemplateParameters( - Map.of("displayName", new NotificationTemplateValue.SafeText("Ada"))), - "security-alert", - "source-operation-42", - Optional.empty(), - "correlation-42", - Optional.empty(), - NOW, - NOW.plusSeconds(600)); - return NotificationFrozenPlan.from( - draft, - java.util.Locale.ENGLISH, - NotificationTestFixtures.binding(draft.policy().channel())); - } - - private static ProviderAttemptOutcome accepted() { - return new ProviderAttemptOutcome( - SubmissionCertainty.PROVIDER_ACCEPTED, - RetryDisposition.NOT_APPLICABLE, - NotificationFaultScope.DELIVERY, - new NotificationReasonCode("PROVIDER_ACCEPTED"), - Optional.empty(), - "correlation-42", - Optional.of("provider-message-42")); - } - - private static NotificationDeliveryStorePort.FinalizationResult finalizationApplied() { - return NotificationDeliveryStorePort.FinalizationResult.APPLIED; - } - - private static NotificationDeliveryStorePort.FinalizationResult finalizationLateExact() { - return NotificationDeliveryStorePort.FinalizationResult.LATE_EXACT_APPLIED; - } - - private static final class RecordingStore implements NotificationDeliveryStorePort { - - private final List trace; - private final ClaimedDelivery claim; - private final AttemptAuthorization authorization; - private final FinalizationResult finalizationResult; - private AuthorizedAttempt authorizedAttempt; - private AttemptFinalization finalization; - - private RecordingStore( - List trace, ClaimedDelivery claim, FinalizationResult finalizationResult) { - this.trace = trace; - this.claim = claim; - this.authorization = - new Authorized( - new AuthorizedAttempt( - claim.deliveryId(), - new NotificationAttemptId("attempt-42"), - claim.plan(), - claim.targetOrdinal(), - claim.claimToken(), - "execution-token-42", - claim.rowVersion(), - claim.admissionGeneration(), - "provider-binding-scope-42", - NOW.plusSeconds(30))); - this.finalizationResult = finalizationResult; - } - - private RecordingStore( - List trace, ClaimedDelivery claim, AttemptAuthorization authorization) { - this.trace = trace; - this.claim = claim; - this.authorization = authorization; - this.finalizationResult = FinalizationResult.APPLIED; - } - - @Override - public List claimEligible(int maximumClaims, Instant now) { - trace.add("claim"); - return List.of(claim); - } - - @Override - public AttemptAuthorization reserveAndAuthorize(ClaimedDelivery claimed, Instant now) { - trace.add("authorize"); - if (authorization instanceof Authorized authorized) { - authorizedAttempt = authorized.attempt(); - } - return authorization; - } - - @Override - public FinalizationResult finalizeAttempt( - AuthorizedAttempt attempt, AttemptFinalization finalization, Instant now) { - trace.add("finalize"); - this.finalization = finalization; - return finalizationResult; - } - - @Override - public List claimForReconciliation(int maximumClaims, Instant now) { - return List.of(); - } - - @Override - public ReconciliationFinalizationResult finalizeReconciliation( - ReconciliationClaim claim, - NotificationReconciliationPort.ReconciliationOutcome outcome, - Instant now) { - throw new UnsupportedOperationException(); - } - - @Override - public int attachOrphanReceipts(int maximumAttachments, Instant now) { - return 0; - } - } - - private static final class TrackingTransactionPort implements TransactionPort { - - private final List trace; - private boolean active; - - private TrackingTransactionPort(List trace) { - this.trace = trace; - } - - @Override - public T inWrite(Supplier action) { - trace.add("tx-begin"); - active = true; - try { - return action.get(); - } finally { - active = false; - trace.add("tx-end"); - } - } - - @Override - public T inRootWrite(Supplier action) { - return inWrite(action); - } - - @Override - public T inRead(Supplier action) { - return action.get(); - } - - @Override - public T inNew(Supplier action) { - return action.get(); - } - - private boolean active() { - return active; - } - } -} diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/NotificationKindPolicyTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/NotificationKindPolicyTest.java deleted file mode 100644 index 264d1a77..00000000 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/NotificationKindPolicyTest.java +++ /dev/null @@ -1,110 +0,0 @@ -package dev.caskeleton.application.notification; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.time.Duration; -import org.junit.jupiter.api.Test; - -class NotificationKindPolicyTest { - - @Test - void modeAndAdmissionClassAreCodeOwnedAndRuntimeConfigCanOnlyAssertExactValues() { - NotificationKindPolicy policy = - policy( - NotificationMode.DURABLE_ASYNC, - NotificationAdmissionClass.SECURITY_CRITICAL, - NotificationRouteStrategy.SINGLE); - - assertThat( - policy.assertRuntimeExpectation( - NotificationMode.DURABLE_ASYNC, NotificationAdmissionClass.SECURITY_CRITICAL)) - .isSameAs(policy); - assertThatThrownBy( - () -> - policy.assertRuntimeExpectation( - NotificationMode.BEST_EFFORT_INLINE, - NotificationAdmissionClass.SECURITY_CRITICAL)) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("mode"); - assertThatThrownBy( - () -> - policy.assertRuntimeExpectation( - NotificationMode.DURABLE_ASYNC, NotificationAdmissionClass.TRANSACTIONAL)) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("admission"); - } - - @Test - void configCannotStrengthenInlinePolicyToDurable() { - NotificationKindPolicy policy = - policy( - NotificationMode.BEST_EFFORT_INLINE, - NotificationAdmissionClass.BULK_LOW_VALUE, - NotificationRouteStrategy.FAN_OUT_ALL); - - assertThatThrownBy( - () -> - policy.assertRuntimeExpectation( - NotificationMode.DURABLE_ASYNC, NotificationAdmissionClass.BULK_LOW_VALUE)) - .isInstanceOf(IllegalStateException.class); - } - - @Test - void criticalKindCannotBindBestEffortInline() { - assertThatThrownBy( - () -> - policy( - NotificationMode.BEST_EFFORT_INLINE, - NotificationAdmissionClass.SECURITY_CRITICAL, - NotificationRouteStrategy.SINGLE)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("SECURITY_CRITICAL"); - } - - @Test - void amplificationBudgetsAreClosedAndInternallyConsistent() { - assertThatThrownBy( - () -> - new NotificationKindPolicy( - new NotificationKindId("security-alert"), - NotificationChannel.SLACK, - new NotificationRouteId("slack-security"), - new NotificationTemplateRef("security-alert", 1), - NotificationMode.DURABLE_ASYNC, - NotificationAdmissionClass.SECURITY_CRITICAL, - NotificationRouteStrategy.FAN_OUT_ALL, - ConsentCheckMode.RECHECK_BEFORE_EACH_DELIVERY, - 1, - 4, - 3, - 0, - 1, - 3, - Duration.ofHours(1))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("provider calls"); - } - - private static NotificationKindPolicy policy( - NotificationMode mode, - NotificationAdmissionClass admissionClass, - NotificationRouteStrategy strategy) { - return new NotificationKindPolicy( - new NotificationKindId("security-alert"), - NotificationChannel.SLACK, - new NotificationRouteId("slack-security"), - new NotificationTemplateRef("security-alert", 1), - mode, - admissionClass, - strategy, - ConsentCheckMode.RECHECK_BEFORE_EACH_DELIVERY, - 3, - strategy == NotificationRouteStrategy.SINGLE ? 1 : 2, - mode == NotificationMode.BEST_EFFORT_INLINE ? 1 : 2, - strategy == NotificationRouteStrategy.ORDERED_FALLBACK ? 1 : 0, - mode == NotificationMode.BEST_EFFORT_INLINE ? 0 : 1, - 6, - Duration.ofHours(2)); - } -} diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/NotificationLegacyWriterPermitUseCaseTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/NotificationLegacyWriterPermitUseCaseTest.java deleted file mode 100644 index e263bfa6..00000000 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/NotificationLegacyWriterPermitUseCaseTest.java +++ /dev/null @@ -1,149 +0,0 @@ -package dev.caskeleton.application.notification; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.time.Clock; -import java.time.Duration; -import java.time.Instant; -import java.time.ZoneOffset; -import java.util.Optional; -import java.util.concurrent.atomic.AtomicInteger; -import org.junit.jupiter.api.Test; - -class NotificationLegacyWriterPermitUseCaseTest { - - private static final Instant NOW = Instant.parse("2026-07-28T00:00:00Z"); - - @Test - void acquireRootCommitsDbTimeWireDeadlineAndExpiryBeforeCallerCanStartNetwork() { - NotificationWriterRouteSet routeSet = InitializeNotificationWriterFencesUseCaseTest.routeSet(); - InitializeNotificationWriterFencesUseCaseTest.TrackingRootTransactions transactions = - new InitializeNotificationWriterFencesUseCaseTest.TrackingRootTransactions(); - NotificationWriterCutoverPort port = new RecordingCutoverPort(transactions); - NotificationLegacyWriterPermitUseCase useCase = - new NotificationLegacyWriterPermitUseCase( - routeSet, port, transactions, Clock.fixed(NOW, ZoneOffset.UTC)); - - NotificationLegacyWriterPermitResult result = - useCase.handle( - NotificationLegacyWriterPermitCommand.acquire( - routeSet.canonicalRoutes().routes().getFirst(), - 7, - "legacy-http-v1", - "permit-42", - "node-42", - "permit-operation-42", - "operator-42", - new NotificationReasonCode("LEGACY_SEND"), - Duration.ofSeconds(5))); - - assertThat(transactions.rootCalls).isEqualTo(1); - assertThat(result.status()).isEqualTo(NotificationLegacyWriterPermitResult.Status.ACQUIRED); - assertThat(result.acquiredAt()).contains(NOW); - assertThat(result.wireDeadline()).contains(NOW.plusSeconds(5)); - assertThat(result.expiresAt()).contains(NOW.plusSeconds(10)); - assertThat(result.wireDeadline().orElseThrow()) - .isBeforeOrEqualTo(result.expiresAt().orElseThrow()); - } - - @Test - void unknownProfileAndUnboundedWireBudgetFailBeforePortMutation() { - NotificationWriterRouteSet routeSet = InitializeNotificationWriterFencesUseCaseTest.routeSet(); - InitializeNotificationWriterFencesUseCaseTest.TrackingRootTransactions transactions = - new InitializeNotificationWriterFencesUseCaseTest.TrackingRootTransactions(); - AtomicInteger calls = new AtomicInteger(); - NotificationLegacyWriterPermitUseCase useCase = - new NotificationLegacyWriterPermitUseCase( - routeSet, - new NotificationWriterCutoverPort() { - @Override - public NotificationLegacyWriterPermitResult acquireLegacyPermit( - NotificationLegacyWriterPermitCommand command, - NotificationWriterRouteSet.RouteProfile routeProfile, - Instant requestedAt) { - calls.incrementAndGet(); - throw new AssertionError("port must not run"); - } - - @Override - public NotificationLegacyWriterPermitResult releaseLegacyPermit( - NotificationLegacyWriterPermitCommand command, - NotificationWriterRouteSet.RouteProfile routeProfile, - Instant requestedAt) { - calls.incrementAndGet(); - throw new AssertionError("port must not run"); - } - }, - transactions, - Clock.fixed(NOW, ZoneOffset.UTC)); - - assertThatThrownBy( - () -> - useCase.handle( - NotificationLegacyWriterPermitCommand.acquire( - routeSet.canonicalRoutes().routes().getFirst(), - 7, - "unknown-profile", - "permit-42", - "node-42", - "permit-operation-42", - "operator-42", - new NotificationReasonCode("LEGACY_SEND"), - Duration.ofSeconds(5)))) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - NotificationLegacyWriterPermitCommand.acquire( - routeSet.canonicalRoutes().routes().getFirst(), - 7, - "legacy-http-v1", - "permit-42", - "node-42", - "permit-operation-42", - "operator-42", - new NotificationReasonCode("LEGACY_SEND"), - Duration.ofMinutes(2))) - .isInstanceOf(IllegalArgumentException.class); - assertThat(calls).hasValue(0); - assertThat(transactions.rootCalls).isZero(); - } - - private static final class RecordingCutoverPort implements NotificationWriterCutoverPort { - - private final InitializeNotificationWriterFencesUseCaseTest.TrackingRootTransactions - transactions; - - private RecordingCutoverPort( - InitializeNotificationWriterFencesUseCaseTest.TrackingRootTransactions transactions) { - this.transactions = transactions; - } - - @Override - public NotificationLegacyWriterPermitResult acquireLegacyPermit( - NotificationLegacyWriterPermitCommand command, - NotificationWriterRouteSet.RouteProfile routeProfile, - Instant requestedAt) { - assertThat(transactions.active).isTrue(); - return new NotificationLegacyWriterPermitResult( - NotificationLegacyWriterPermitResult.Status.ACQUIRED, - command.permitToken(), - Optional.of(requestedAt), - Optional.of(requestedAt.plus(command.wireBudget().orElseThrow())), - Optional.of(requestedAt.plusSeconds(10))); - } - - @Override - public NotificationLegacyWriterPermitResult releaseLegacyPermit( - NotificationLegacyWriterPermitCommand command, - NotificationWriterRouteSet.RouteProfile routeProfile, - Instant requestedAt) { - return new NotificationLegacyWriterPermitResult( - NotificationLegacyWriterPermitResult.Status.RELEASED, - command.permitToken(), - Optional.empty(), - Optional.empty(), - Optional.empty()); - } - } -} diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/NotificationMaintenanceUseCaseTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/NotificationMaintenanceUseCaseTest.java deleted file mode 100644 index f57e571b..00000000 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/NotificationMaintenanceUseCaseTest.java +++ /dev/null @@ -1,80 +0,0 @@ -package dev.caskeleton.application.notification; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.application.transaction.TransactionPort; -import java.time.Clock; -import java.time.Instant; -import java.time.ZoneOffset; -import java.util.function.Supplier; -import org.junit.jupiter.api.Test; - -class NotificationMaintenanceUseCaseTest { - - @Test - void maintenanceIsBoundedAndRunsInsideOneShortWriteTransaction() { - TrackingTransactions transactions = new TrackingTransactions(); - NotificationMaintenanceStorePort store = - (command, now) -> { - assertThat(transactions.active).isTrue(); - return new NotificationMaintenanceStorePort.MutationResult(3, 2, 1); - }; - NotificationMaintenanceUseCase useCase = - new NotificationMaintenanceUseCase( - store, - transactions, - Clock.fixed(Instant.parse("2026-07-28T00:00:00Z"), ZoneOffset.UTC)); - - NotificationMaintenanceResult result = - useCase.handle(new NotificationMaintenanceCommand(40, 30, 30)); - - assertThat(transactions.writeCalls).isEqualTo(1); - assertThat(result).isEqualTo(new NotificationMaintenanceResult(3, 2, 1)); - assertThatThrownBy(() -> new NotificationMaintenanceCommand(50, 50, 1)) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> new NotificationMaintenanceCommand(Integer.MAX_VALUE, Integer.MAX_VALUE, 3)) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new NotificationMaintenanceStorePort.MutationResult( - Integer.MAX_VALUE, Integer.MAX_VALUE, 3)) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> new NotificationMaintenanceResult(Integer.MAX_VALUE, Integer.MAX_VALUE, 3)) - .isInstanceOf(IllegalArgumentException.class); - } - - private static final class TrackingTransactions implements TransactionPort { - - private boolean active; - private int writeCalls; - - @Override - public T inWrite(Supplier action) { - writeCalls++; - active = true; - try { - return action.get(); - } finally { - active = false; - } - } - - @Override - public T inRootWrite(Supplier action) { - return inWrite(action); - } - - @Override - public T inRead(Supplier action) { - return action.get(); - } - - @Override - public T inNew(Supplier action) { - return action.get(); - } - } -} diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/NotificationOperationsSnapshotUseCaseTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/NotificationOperationsSnapshotUseCaseTest.java deleted file mode 100644 index 183ad9d8..00000000 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/NotificationOperationsSnapshotUseCaseTest.java +++ /dev/null @@ -1,111 +0,0 @@ -package dev.caskeleton.application.notification; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.application.capability.Idempotency; -import dev.caskeleton.application.capability.RepositoryAccess; -import dev.caskeleton.application.capability.UseCaseCapability; -import dev.caskeleton.application.transaction.TransactionMode; -import dev.caskeleton.application.transaction.TransactionPort; -import dev.caskeleton.application.usecase.QueryUseCase; -import java.time.Instant; -import java.util.List; -import java.util.function.Supplier; -import org.junit.jupiter.api.Test; - -class NotificationOperationsSnapshotUseCaseTest { - - @Test - void concreteQueryUseCaseLoadsOnlyBoundedSnapshotInsideReadTransaction() { - TrackingTransactions transactions = new TrackingTransactions(); - NotificationOperationsSnapshot expected = - new NotificationOperationsSnapshot( - Instant.parse("2026-07-28T00:00:00Z"), - 12, - 2, - 1, - 0, - List.of( - new NotificationOperationsSnapshot.RouteWriterStatus( - new NotificationRouteId("security-email"), - 2, - NotificationWriterOwnership.CANONICAL, - 8, - false))); - NotificationOperationsSnapshotPort port = - query -> { - assertThat(transactions.readActive).isTrue(); - assertThat(query.maximumRoutes()).isEqualTo(100); - return expected; - }; - NotificationOperationsSnapshotUseCase useCase = - new NotificationOperationsSnapshotUseCase(port, transactions); - - NotificationOperationsSnapshot result = - useCase.handle(new NotificationOperationsSnapshotQuery(100)); - - assertThat(result).isEqualTo(expected); - assertThat(transactions.readCalls).isEqualTo(1); - assertThat(useCase).isInstanceOf(QueryUseCase.class); - UseCaseCapability capability = - NotificationOperationsSnapshotUseCase.class.getAnnotation(UseCaseCapability.class); - assertThat(capability.transactionMode()).isEqualTo(TransactionMode.READ_ONLY); - assertThat(capability.repositoryAccess()).isEqualTo(RepositoryAccess.READ_REPOSITORY); - assertThat(capability.idempotency()).isEqualTo(Idempotency.IDEMPOTENT); - assertThat(capability.externalOutboundAllowed()).isFalse(); - assertThat(capability.sensitiveRead()).isFalse(); - assertThat(capability.crossTenantAdmin()).isTrue(); - } - - @Test - void snapshotDefensivelyCopiesBoundedNonSensitiveRouteValues() { - java.util.ArrayList mutable = - new java.util.ArrayList<>( - List.of( - new NotificationOperationsSnapshot.RouteWriterStatus( - new NotificationRouteId("security-email"), - 2, - NotificationWriterOwnership.LEGACY, - 7, - true))); - NotificationOperationsSnapshot snapshot = - new NotificationOperationsSnapshot( - Instant.parse("2026-07-28T00:00:00Z"), 0, 0, 0, 0, mutable); - mutable.clear(); - - assertThat(snapshot.writerRoutes()).hasSize(1); - assertThat(snapshot.toString()).doesNotContain("recipient", "payload", "credential"); - } - - private static final class TrackingTransactions implements TransactionPort { - - private boolean readActive; - private int readCalls; - - @Override - public T inWrite(Supplier action) { - return action.get(); - } - - @Override - public T inRootWrite(Supplier action) { - return action.get(); - } - - @Override - public T inRead(Supplier action) { - readCalls++; - readActive = true; - try { - return action.get(); - } finally { - readActive = false; - } - } - - @Override - public T inNew(Supplier action) { - return action.get(); - } - } -} diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/NotificationPlanningBoundaryTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/NotificationPlanningBoundaryTest.java deleted file mode 100644 index 970c719a..00000000 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/NotificationPlanningBoundaryTest.java +++ /dev/null @@ -1,160 +0,0 @@ -package dev.caskeleton.application.notification; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.time.Duration; -import java.time.Instant; -import java.util.Locale; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.atomic.AtomicReference; -import org.junit.jupiter.api.Test; - -class NotificationPlanningBoundaryTest { - - @Test - void featureFactoryAndCodePolicyProduceDraftThenPlannerReturnsApplicationFrozenPlan() { - NotificationKindPolicy policy = securityAlertPolicy(); - SecurityAlertNotificationRequestFactory factory = - new SecurityAlertNotificationRequestFactory(policy); - NotificationIntentDraft draft = - factory.create( - "intent-42", - "recipient-ref-42", - "source-operation-42", - Instant.parse("2026-07-28T00:00:00Z")); - NotificationPlanPort planner = - requested -> - new NotificationPlanningResult.Planned( - NotificationFrozenPlan.from( - requested, - Locale.ENGLISH, - NotificationTestFixtures.binding(requested.policy().channel()))); - - NotificationPlanningResult result = planner.plan(draft); - - assertThat(result).isInstanceOf(NotificationPlanningResult.Planned.class); - NotificationFrozenPlan plan = ((NotificationPlanningResult.Planned) result).plan(); - assertThat(plan.policy()).isSameAs(policy); - assertThat(plan.mode()).isEqualTo(NotificationMode.DURABLE_ASYNC); - assertThat(plan.selectedLocale()).isEqualTo(Locale.ENGLISH); - } - - @Test - void appendAndInlinePortsConsumeTheSameFrozenApplicationPlan() { - NotificationIntentDraft draft = - new SecurityAlertNotificationRequestFactory(securityAlertPolicy()) - .create( - "intent-42", - "recipient-ref-42", - "source-operation-42", - Instant.parse("2026-07-28T00:00:00Z")); - NotificationFrozenPlan plan = - NotificationFrozenPlan.from( - draft, Locale.ENGLISH, NotificationTestFixtures.binding(draft.policy().channel())); - AtomicReference appended = new AtomicReference<>(); - AtomicReference attempted = new AtomicReference<>(); - NotificationIntentAppendPort appendPort = - frozenPlan -> { - appended.set(frozenPlan); - return new NotificationAppendResult.Appended(frozenPlan.intentId()); - }; - InlineNotificationAttemptPort inlinePort = - frozenPlan -> { - attempted.set(frozenPlan); - return new NotificationRequestResult.InlineCompleted( - frozenPlan.intentId(), - java.util.List.of( - new TargetAttemptOutcome( - 0, - new NotificationDeliveryId("delivery-42"), - new ProviderAttemptOutcome( - SubmissionCertainty.PROVIDER_ACCEPTED, - RetryDisposition.NOT_APPLICABLE, - NotificationFaultScope.DELIVERY, - new NotificationReasonCode("PROVIDER_ACCEPTED"), - Optional.empty(), - "correlation-42", - Optional.of("provider-message-42"))))); - }; - - assertThat(appendPort.append(plan)) - .isEqualTo(new NotificationAppendResult.Appended(plan.intentId())); - assertThat(inlinePort.attempt(plan).intentId()).isEqualTo(plan.intentId()); - assertThat(appended).hasValue(plan); - assertThat(attempted).hasValue(plan); - } - - @Test - void planningFailuresStayBoundedAndProviderNeutral() { - NotificationPlanPort planner = - draft -> - new NotificationPlanningResult.Rejected( - new NotificationReasonCode("ROUTE_NOT_QUALIFIED")); - - NotificationPlanningResult result = - planner.plan( - new SecurityAlertNotificationRequestFactory(securityAlertPolicy()) - .create( - "intent-42", - "recipient-ref-42", - "source-operation-42", - Instant.parse("2026-07-28T00:00:00Z"))); - - assertThat(result) - .isEqualTo( - new NotificationPlanningResult.Rejected( - new NotificationReasonCode("ROUTE_NOT_QUALIFIED"))); - assertThat(result.toString()) - .doesNotContain("software.amazon", "slack.api", "webhook", "credential"); - } - - private static NotificationKindPolicy securityAlertPolicy() { - return new NotificationKindPolicy( - new NotificationKindId("security-alert"), - NotificationChannel.EMAIL, - new NotificationRouteId("security-alert-email"), - new NotificationTemplateRef("security-alert", 1), - NotificationMode.DURABLE_ASYNC, - NotificationAdmissionClass.SECURITY_CRITICAL, - NotificationRouteStrategy.SINGLE, - ConsentCheckMode.SNAPSHOT_AT_APPEND, - 1, - 1, - 2, - 0, - 1, - 3, - Duration.ofHours(2)); - } - - /** - * Feature-specific factory example intentionally kept in test fixtures, not generic production. - */ - private static final class SecurityAlertNotificationRequestFactory { - - private final NotificationKindPolicy policy; - - private SecurityAlertNotificationRequestFactory(NotificationKindPolicy policy) { - this.policy = policy; - } - - private NotificationIntentDraft create( - String intentId, String recipientReference, String sourceOperationId, Instant now) { - return new NotificationIntentDraft( - new NotificationIntentId(intentId), - policy, - Locale.forLanguageTag("ko-KR"), - new EmailRecipientReference(recipientReference), - new NotificationTemplateParameters( - Map.of("displayName", new NotificationTemplateValue.SafeText("redacted-value"))), - "security-alert", - sourceOperationId, - Optional.empty(), - "correlation-42", - Optional.empty(), - now, - now.plus(Duration.ofMinutes(30))); - } - } -} diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/NotificationPortBoundaryTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/NotificationPortBoundaryTest.java deleted file mode 100644 index bdd61210..00000000 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/NotificationPortBoundaryTest.java +++ /dev/null @@ -1,82 +0,0 @@ -package dev.caskeleton.application.notification; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.lang.reflect.Method; -import java.util.Arrays; -import java.util.Locale; -import java.util.Set; -import java.util.stream.Collectors; -import org.junit.jupiter.api.Test; - -class NotificationPortBoundaryTest { - - @Test - void appendInlineAndPlanningPortsAreNarrowAndOwnNoTransactionMechanism() { - assertThat(NotificationPlanPort.class.getDeclaredMethods()).hasSize(1); - assertThat(NotificationIntentAppendPort.class.getDeclaredMethods()).hasSize(1); - assertThat(InlineNotificationAttemptPort.class.getDeclaredMethods()).hasSize(1); - - Method append = NotificationIntentAppendPort.class.getDeclaredMethods()[0]; - assertThat(append.getName()).isEqualTo("append"); - assertThat(append.getParameterTypes()).containsExactly(NotificationFrozenPlan.class); - assertThat(append.getReturnType()).isEqualTo(NotificationAppendResult.class); - assertThat(Arrays.stream(append.getParameterTypes()).map(Class::getName)) - .noneMatch(name -> name.contains("Transaction") || name.contains("Entity")); - } - - @Test - void publicPortSignaturesContainOnlyApplicationAndJdkTypes() { - Set typeNames = - java.util.stream.Stream.of( - NotificationPlanPort.class, - NotificationIntentAppendPort.class, - InlineNotificationAttemptPort.class) - .flatMap(type -> Arrays.stream(type.getDeclaredMethods())) - .flatMap( - method -> - java.util.stream.Stream.concat( - java.util.stream.Stream.of(method.getGenericReturnType().getTypeName()), - Arrays.stream(method.getGenericParameterTypes()) - .map(java.lang.reflect.Type::getTypeName))) - .collect(Collectors.toSet()); - - assertThat(typeNames) - .allMatch( - name -> - name.startsWith("dev.caskeleton.application.notification.") - || name.startsWith("java.")); - assertThat(typeNames.stream().map(name -> name.toLowerCase(Locale.ROOT))) - .noneMatch( - name -> - name.contains("slack.api") - || name.contains("software.amazon") - || name.contains("spring") - || name.contains("jakarta.persistence") - || name.contains("entity") - || name.contains("dto") - || name.contains("compilednotificationbinding") - || name.contains("providerruntimeprofile")); - } - - @Test - void noGiantNotificationPortCombinesPlanningAppendAttemptStoreAndReceipt() { - Set methodNames = - java.util.stream.Stream.of( - NotificationPlanPort.class, - NotificationIntentAppendPort.class, - InlineNotificationAttemptPort.class) - .flatMap(type -> Arrays.stream(type.getDeclaredMethods())) - .map(Method::getName) - .collect(Collectors.toSet()); - - assertThat(methodNames).containsExactlyInAnyOrder("plan", "append", "attempt"); - assertThat( - java.util.stream.Stream.of( - NotificationPlanPort.class, - NotificationIntentAppendPort.class, - InlineNotificationAttemptPort.class) - .map(Class::getSimpleName)) - .noneMatch(name -> name.equals("NotificationStorePort") || name.equals("NotificationPort")); - } -} diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/NotificationReceiptReducerTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/NotificationReceiptReducerTest.java deleted file mode 100644 index 2584ee2b..00000000 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/NotificationReceiptReducerTest.java +++ /dev/null @@ -1,231 +0,0 @@ -package dev.caskeleton.application.notification; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.application.transaction.TransactionPort; -import java.time.Clock; -import java.time.Instant; -import java.time.ZoneOffset; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.function.Supplier; -import org.junit.jupiter.api.Test; - -class NotificationReceiptReducerTest { - - private static final Instant NOW = Instant.parse("2026-07-28T00:00:00Z"); - - @Test - void receiptFactOrderDoesNotChangeOrthogonalProjectionAndAcceptanceIsNeverErased() { - List facts = - List.of( - fact(NotificationReceiptFact.Type.SEND, NotificationReceiptFact.BounceClass.NONE, 1), - fact( - NotificationReceiptFact.Type.DELIVERY, NotificationReceiptFact.BounceClass.NONE, 2), - fact(NotificationReceiptFact.Type.BOUNCE, NotificationReceiptFact.BounceClass.HARD, 3), - fact( - NotificationReceiptFact.Type.COMPLAINT, - NotificationReceiptFact.BounceClass.NONE, - 4), - fact( - NotificationReceiptFact.Type.DELIVERY_DELAY, - NotificationReceiptFact.BounceClass.NONE, - 5)); - NotificationReceiptProjection canonical = NotificationReceiptProjection.reduce(facts); - List reversed = new ArrayList<>(facts); - Collections.reverse(reversed); - List rotated = new ArrayList<>(facts); - Collections.rotate(rotated, 2); - - assertThat(NotificationReceiptProjection.reduce(reversed)).isEqualTo(canonical); - assertThat(NotificationReceiptProjection.reduce(rotated)).isEqualTo(canonical); - assertThat(canonical.submissionAccepted()).isTrue(); - assertThat(canonical.delivered()).isTrue(); - assertThat(canonical.hardBounced()).isTrue(); - assertThat(canonical.complained()).isTrue(); - assertThat(canonical.deliveryDelayed()).isTrue(); - assertThat(canonical.latestFactAt()).isEqualTo(NOW.plusSeconds(5)); - } - - @Test - void onlyHardBounceAndComplaintEmitTechnicalSuppression() { - assertThat( - apply( - fact( - NotificationReceiptFact.Type.BOUNCE, - NotificationReceiptFact.BounceClass.HARD, - 1)) - .suppressed) - .isEqualTo(1); - assertThat( - apply( - fact( - NotificationReceiptFact.Type.COMPLAINT, - NotificationReceiptFact.BounceClass.NONE, - 1)) - .suppressed) - .isEqualTo(1); - assertThat( - apply( - fact( - NotificationReceiptFact.Type.BOUNCE, - NotificationReceiptFact.BounceClass.SOFT, - 1)) - .suppressed) - .isZero(); - assertThat( - apply( - fact( - NotificationReceiptFact.Type.DELIVERY_DELAY, - NotificationReceiptFact.BounceClass.NONE, - 1)) - .suppressed) - .isZero(); - } - - @Test - void applyUsesPhysicalRootWriteAndDuplicateDoesNotRepeatSuppression() { - TrackingRootTransactionPort transactions = new TrackingRootTransactionPort(); - RecordingReceiptStore store = - new RecordingReceiptStore( - new NotificationReceiptStorePort.Duplicate( - NotificationReceiptProjection.reduce( - List.of( - fact( - NotificationReceiptFact.Type.COMPLAINT, - NotificationReceiptFact.BounceClass.NONE, - 1))))); - RecordingSuppressionPort suppression = new RecordingSuppressionPort(transactions); - ApplyNotificationReceiptUseCase useCase = - new ApplyNotificationReceiptUseCase( - store, suppression, transactions, Clock.fixed(NOW, ZoneOffset.UTC)); - - ApplyNotificationReceiptResult result = - useCase.handle( - command( - fact( - NotificationReceiptFact.Type.COMPLAINT, - NotificationReceiptFact.BounceClass.NONE, - 1))); - - assertThat(transactions.rootWriteCalls).isEqualTo(1); - assertThat(store.savedProjection).isNull(); - assertThat(suppression.suppressed).isZero(); - assertThat(result.status()).isEqualTo(ApplyNotificationReceiptResult.Status.DUPLICATE); - } - - private static ReceiptFixture apply(NotificationReceiptFact fact) { - TrackingRootTransactionPort transactions = new TrackingRootTransactionPort(); - NotificationReceiptProjection projection = NotificationReceiptProjection.reduce(List.of(fact)); - RecordingReceiptStore store = - new RecordingReceiptStore( - new NotificationReceiptStorePort.Appended( - new NotificationReceiptStorePort.ReceiptAggregate( - new NotificationDeliveryId("delivery-42"), - new EmailRecipientReference("recipient-ref-42"), - List.of(fact)))); - RecordingSuppressionPort suppression = new RecordingSuppressionPort(transactions); - ApplyNotificationReceiptResult result = - new ApplyNotificationReceiptUseCase( - store, suppression, transactions, Clock.fixed(NOW, ZoneOffset.UTC)) - .handle(command(fact)); - assertThat(result.projection()).isEqualTo(projection); - assertThat(store.savedProjection).isEqualTo(projection); - return new ReceiptFixture(suppression.suppressed); - } - - private static ApplyNotificationReceiptCommand command(NotificationReceiptFact fact) { - return new ApplyNotificationReceiptCommand( - new NormalizedNotificationReceiptCommand( - new NotificationReceiptEventId("receipt-42"), - new NotificationDeliveryId("delivery-42"), - fact)); - } - - private static NotificationReceiptFact fact( - NotificationReceiptFact.Type type, - NotificationReceiptFact.BounceClass bounceClass, - long second) { - return new NotificationReceiptFact( - type, - bounceClass, - new NotificationReasonCode( - type == NotificationReceiptFact.Type.BOUNCE - ? "RECIPIENT_BOUNCE" - : "PROVIDER_" + type.name()), - NOW.plusSeconds(second)); - } - - private record ReceiptFixture(int suppressed) {} - - private static final class RecordingReceiptStore implements NotificationReceiptStorePort { - - private final AppendResult appendResult; - private NotificationReceiptProjection savedProjection; - - private RecordingReceiptStore(AppendResult appendResult) { - this.appendResult = appendResult; - } - - @Override - public AppendResult appendIfAbsent(NormalizedNotificationReceiptCommand command) { - return appendResult; - } - - @Override - public void saveProjection( - NotificationDeliveryId deliveryId, NotificationReceiptProjection projection) { - savedProjection = projection; - } - } - - private static final class RecordingSuppressionPort - implements NotificationTechnicalSuppressionPort { - - private final TrackingRootTransactionPort transactions; - private int suppressed; - - private RecordingSuppressionPort(TrackingRootTransactionPort transactions) { - this.transactions = transactions; - } - - @Override - public void suppress(SuppressionMutation mutation) { - assertThat(transactions.active).isTrue(); - suppressed++; - } - } - - private static final class TrackingRootTransactionPort implements TransactionPort { - - private int rootWriteCalls; - private boolean active; - - @Override - public T inWrite(Supplier action) { - return action.get(); - } - - @Override - public T inRootWrite(Supplier action) { - rootWriteCalls++; - active = true; - try { - return action.get(); - } finally { - active = false; - } - } - - @Override - public T inRead(Supplier action) { - return action.get(); - } - - @Override - public T inNew(Supplier action) { - return action.get(); - } - } -} diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/NotificationRequestResultTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/NotificationRequestResultTest.java deleted file mode 100644 index 963daa64..00000000 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/NotificationRequestResultTest.java +++ /dev/null @@ -1,144 +0,0 @@ -package dev.caskeleton.application.notification; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.time.Instant; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import org.junit.jupiter.api.Test; - -class NotificationRequestResultTest { - - @Test - void providerOutcomeKeepsSubmissionRetryAndFaultAxesOrthogonal() { - Instant retryAt = Instant.parse("2026-07-28T00:01:00Z"); - ProviderAttemptOutcome outcome = - new ProviderAttemptOutcome( - SubmissionCertainty.DEFINITELY_NOT_APPLIED, - RetryDisposition.RETRY_AT, - NotificationFaultScope.PROVIDER_BINDING, - new NotificationReasonCode("PROVIDER_THROTTLED"), - Optional.of(retryAt), - "attempt-correlation-42", - Optional.empty()); - - assertThat(outcome.submissionCertainty()).isEqualTo(SubmissionCertainty.DEFINITELY_NOT_APPLIED); - assertThat(outcome.retryDisposition()).isEqualTo(RetryDisposition.RETRY_AT); - assertThat(outcome.faultScope()).isEqualTo(NotificationFaultScope.PROVIDER_BINDING); - assertThat(outcome.retryNotBefore()).contains(retryAt); - } - - @Test - void outcomeRejectsContradictoryAxes() { - assertThatThrownBy( - () -> - new ProviderAttemptOutcome( - SubmissionCertainty.PROVIDER_ACCEPTED, - RetryDisposition.RETRY_AT, - NotificationFaultScope.DELIVERY, - new NotificationReasonCode("ACCEPTED"), - Optional.of(Instant.parse("2026-07-28T00:01:00Z")), - "attempt-correlation-42", - Optional.of("provider-message-ref-42"))) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new ProviderAttemptOutcome( - SubmissionCertainty.DEFINITELY_NOT_APPLIED, - RetryDisposition.RETRY_AT, - NotificationFaultScope.PROVIDER_BINDING, - new NotificationReasonCode("PROVIDER_THROTTLED"), - Optional.empty(), - "attempt-correlation-42", - Optional.empty())) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("retryNotBefore"); - assertThatThrownBy( - () -> - new ProviderAttemptOutcome( - SubmissionCertainty.INDETERMINATE, - RetryDisposition.NOT_APPLICABLE, - NotificationFaultScope.DELIVERY, - new NotificationReasonCode("RESPONSE_LOST"), - Optional.empty(), - "attempt-correlation-42", - Optional.of("message-that-cannot-be-known"))) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void providerAndTargetOutcomesRedactOpaqueReferences() { - ProviderAttemptOutcome providerOutcome = - new ProviderAttemptOutcome( - SubmissionCertainty.PROVIDER_ACCEPTED, - RetryDisposition.NOT_APPLICABLE, - NotificationFaultScope.DELIVERY, - new NotificationReasonCode("PROVIDER_ACCEPTED"), - Optional.empty(), - "attempt-correlation-secret", - Optional.of("provider-message-secret")); - TargetAttemptOutcome target = - new TargetAttemptOutcome(0, new NotificationDeliveryId("delivery-secret"), providerOutcome); - - assertThat(providerOutcome.toString()) - .doesNotContain("attempt-correlation-secret") - .doesNotContain("provider-message-secret"); - assertThat(target.toString()).doesNotContain("delivery-secret"); - } - - @Test - void requestResultIsAClosedUnionAndInlineTargetListIsBoundedAndImmutable() { - List mutable = - new ArrayList<>( - List.of( - new TargetAttemptOutcome( - 0, - new NotificationDeliveryId("delivery-1"), - acceptedOutcome("correlation-1", "provider-message-1")))); - NotificationRequestResult.InlineCompleted completed = - new NotificationRequestResult.InlineCompleted( - new NotificationIntentId("intent-1"), mutable); - mutable.clear(); - - assertThat(completed.outcomes()).hasSize(1); - assertThatThrownBy(() -> completed.outcomes().clear()) - .isInstanceOf(UnsupportedOperationException.class); - assertThatThrownBy( - () -> - new NotificationRequestResult.InlineCompleted( - new NotificationIntentId("intent-1"), - java.util.stream.IntStream.range(0, 17) - .mapToObj( - index -> - new TargetAttemptOutcome( - index, - new NotificationDeliveryId("delivery-" + index), - acceptedOutcome( - "correlation-" + index, "provider-message-" + index))) - .toList())) - .isInstanceOf(IllegalArgumentException.class); - - assertThat(NotificationRequestResult.class.getPermittedSubclasses()) - .containsExactlyInAnyOrder( - NotificationRequestResult.InlineCompleted.class, - NotificationRequestResult.AppendedDurably.class, - NotificationRequestResult.DuplicateExistingIntent.class, - NotificationRequestResult.RejectedByBusinessPolicy.class, - NotificationRequestResult.RejectedInvalidRequest.class, - NotificationRequestResult.CapabilityUnavailable.class); - } - - private static ProviderAttemptOutcome acceptedOutcome( - String correlationReference, String providerReference) { - return new ProviderAttemptOutcome( - SubmissionCertainty.PROVIDER_ACCEPTED, - RetryDisposition.NOT_APPLICABLE, - NotificationFaultScope.DELIVERY, - new NotificationReasonCode("PROVIDER_ACCEPTED"), - Optional.empty(), - correlationReference, - Optional.of(providerReference)); - } -} diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/NotificationTestFixtures.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/NotificationTestFixtures.java deleted file mode 100644 index f0ba8c13..00000000 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/NotificationTestFixtures.java +++ /dev/null @@ -1,26 +0,0 @@ -package dev.caskeleton.application.notification; - -import java.time.Duration; -import java.util.List; - -final class NotificationTestFixtures { - - private NotificationTestFixtures() {} - - static NotificationFrozenPlan.BindingSnapshot binding(NotificationChannel channel) { - String capability = - channel == NotificationChannel.EMAIL - ? "aws-ses-v2-durable-single-local-sns-v1" - : "slack-web-api-durable-single-local-v1"; - return new NotificationFrozenPlan.BindingSnapshot( - 3, - "a".repeat(64), - "b".repeat(64), - "renderer-r3", - List.of( - new NotificationFrozenPlan.FrozenTarget( - 0, "target-r3", capability, "provider-binding-r3", "credential-r3")), - channel == NotificationChannel.EMAIL, - Duration.ofSeconds(5)); - } -} diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/NotificationValueContractTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/NotificationValueContractTest.java deleted file mode 100644 index 4625f627..00000000 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/NotificationValueContractTest.java +++ /dev/null @@ -1,301 +0,0 @@ -package dev.caskeleton.application.notification; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.math.BigDecimal; -import java.time.Duration; -import java.time.Instant; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.util.Currency; -import java.util.LinkedHashMap; -import java.util.Locale; -import java.util.Map; -import java.util.Optional; -import org.junit.jupiter.api.Test; - -class NotificationValueContractTest { - - @Test - void identifiersAreNonBlankBoundedAndRejectControlCharacters() { - assertThatThrownBy(() -> new NotificationIntentId(" ")) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> new NotificationDeliveryId("delivery\n1")) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> new NotificationAttemptId("a".repeat(129))) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> new NotificationReceiptEventId("event/1")) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> new NotificationKindId("PASSWORD_RESET")) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> new NotificationRouteId("-primary")) - .isInstanceOf(IllegalArgumentException.class); - - assertThat(new NotificationIntentId("01J1234567890ABCDEFGHJKMNP").value()) - .isEqualTo("01J1234567890ABCDEFGHJKMNP"); - } - - @Test - void recipientReferencesAreChannelTypedAndRedacted() { - NotificationRecipientReference email = new EmailRecipientReference("recipient-email-ref-42"); - NotificationRecipientReference slack = - new SlackAudienceReference("workspace-binding-1", "audience-ref-42"); - - assertThat(email.channel()).isEqualTo(NotificationChannel.EMAIL); - assertThat(slack.channel()).isEqualTo(NotificationChannel.SLACK); - assertThat(email.toString()).doesNotContain("recipient-email-ref-42"); - assertThat(slack.toString()) - .doesNotContain("workspace-binding-1") - .doesNotContain("audience-ref-42"); - } - - @Test - void templateParametersAcceptOnlyTheClosedScalarSetAndAreImmutableAndRedacted() { - Map values = new LinkedHashMap<>(); - values.put("displayName", new NotificationTemplateValue.SafeText("Ada Lovelace")); - values.put( - "resetLink", - new NotificationTemplateValue.TrustedAbsoluteLinkReference("reset-link-ref-42")); - values.put( - "businessDate", - new NotificationTemplateValue.LocalDateValue(LocalDate.parse("2026-07-28"))); - values.put( - "expiresAt", - new NotificationTemplateValue.LocalDateTimeValue( - LocalDateTime.parse("2026-07-28T12:00:00"), ZoneId.of("Asia/Seoul"))); - values.put("attempts", new NotificationTemplateValue.IntegerValue(3)); - values.put( - "amount", - new NotificationTemplateValue.MoneyValue( - new BigDecimal("12500.00"), Currency.getInstance("KRW"))); - - NotificationTemplateParameters parameters = new NotificationTemplateParameters(values); - values.clear(); - - assertThat(parameters.values()).hasSize(6); - assertThatThrownBy( - () -> parameters.values().put("later", new NotificationTemplateValue.IntegerValue(1))) - .isInstanceOf(UnsupportedOperationException.class); - assertThat(parameters.toString()) - .doesNotContain("Ada Lovelace") - .doesNotContain("reset-link-ref-42") - .doesNotContain("12500.00"); - } - - @Test - void templateParametersRejectUnknownShapesAndUnboundedCollectionsByType() { - assertThat( - NotificationTemplateParameters.class - .getRecordComponents()[0] - .getGenericType() - .getTypeName()) - .isEqualTo( - "java.util.Map"); - assertThatThrownBy( - () -> - new NotificationTemplateParameters( - Map.of("bad key", new NotificationTemplateValue.IntegerValue(1)))) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new NotificationTemplateParameters( - java.util.stream.IntStream.range(0, 33) - .boxed() - .collect( - java.util.stream.Collectors.toMap( - index -> "parameter" + index, - index -> new NotificationTemplateValue.IntegerValue(index))))) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void draftHasExactlyOneTypedRecipientAndBoundedLocaleAndTimeWindow() { - NotificationKindPolicy policy = durablePolicy(Duration.ofHours(24)); - Instant notBefore = Instant.parse("2026-07-28T00:00:00Z"); - - NotificationIntentDraft draft = - new NotificationIntentDraft( - new NotificationIntentId("intent-42"), - policy, - Locale.forLanguageTag("ko-KR"), - new EmailRecipientReference("recipient-ref-42"), - new NotificationTemplateParameters( - Map.of("displayName", new NotificationTemplateValue.SafeText("Ada"))), - "password-reset", - "source-operation-42", - Optional.of("tenant-42"), - "correlation-42", - Optional.of("causation-42"), - notBefore, - notBefore.plus(Duration.ofHours(2))); - - assertThat(draft.recipient()).isInstanceOf(EmailRecipientReference.class); - assertThat(draft.policy().mode()).isEqualTo(NotificationMode.DURABLE_ASYNC); - assertThat(draft.toString()) - .doesNotContain("recipient-ref-42") - .doesNotContain("Ada") - .doesNotContain("tenant-42"); - - assertThatThrownBy( - () -> - new NotificationIntentDraft( - draft.intentId(), - policy, - Locale.ROOT, - draft.recipient(), - draft.parameters(), - draft.idempotencyScope(), - draft.sourceOperationId(), - draft.tenantReference(), - draft.correlationReference(), - draft.causationReference(), - notBefore, - notBefore.plusSeconds(1))) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new NotificationIntentDraft( - draft.intentId(), - policy, - draft.requestedLocale(), - draft.recipient(), - draft.parameters(), - draft.idempotencyScope(), - draft.sourceOperationId(), - draft.tenantReference(), - draft.correlationReference(), - draft.causationReference(), - notBefore, - notBefore.plus(Duration.ofHours(25)))) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void frozenPlanCopiesOnlyApplicationOwnedValuesAndPinsSelectedLocale() { - NotificationKindPolicy policy = durablePolicy(Duration.ofHours(24)); - Instant notBefore = Instant.parse("2026-07-28T00:00:00Z"); - NotificationIntentDraft draft = - new NotificationIntentDraft( - new NotificationIntentId("intent-42"), - policy, - Locale.forLanguageTag("ko-KR"), - new EmailRecipientReference("recipient-ref-42"), - new NotificationTemplateParameters( - Map.of("displayName", new NotificationTemplateValue.SafeText("Ada"))), - "password-reset", - "source-operation-42", - Optional.empty(), - "correlation-42", - Optional.empty(), - notBefore, - notBefore.plusSeconds(60)); - - NotificationFrozenPlan plan = - NotificationFrozenPlan.from( - draft, - Locale.forLanguageTag("en"), - NotificationTestFixtures.binding(draft.policy().channel())); - - assertThat(plan.selectedLocale()).isEqualTo(Locale.ENGLISH); - assertThat(plan.mode()).isEqualTo(NotificationMode.DURABLE_ASYNC); - assertThat(plan.binding().targets()).isUnmodifiable(); - assertThat(plan.routeId()).isEqualTo(new NotificationRouteId("email-primary")); - assertThat(plan.toString()).doesNotContain("recipient-ref-42").doesNotContain("Ada"); - } - - @Test - void publicFrozenPlanConstructorPreservesDraftContextAndRetryHorizonInvariants() { - NotificationKindPolicy policy = durablePolicy(Duration.ofHours(1)); - Instant notBefore = Instant.parse("2026-07-28T00:00:00Z"); - NotificationFrozenPlan valid = - new NotificationFrozenPlan( - new NotificationIntentId("intent-42"), - policy, - Locale.ENGLISH, - NotificationTestFixtures.binding(policy.channel()), - new EmailRecipientReference("recipient-ref-42"), - new NotificationTemplateParameters( - Map.of("displayName", new NotificationTemplateValue.SafeText("Ada"))), - "password-reset", - "source-operation-42", - Optional.empty(), - "correlation-42", - Optional.empty(), - notBefore, - notBefore.plusSeconds(60)); - - assertThatThrownBy( - () -> - new NotificationFrozenPlan( - valid.intentId(), - policy, - valid.selectedLocale(), - valid.binding(), - valid.recipient(), - valid.parameters(), - valid.idempotencyScope(), - valid.sourceOperationId(), - Optional.of(" "), - valid.correlationReference(), - valid.causationReference(), - notBefore, - notBefore.plusSeconds(60))) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new NotificationFrozenPlan( - valid.intentId(), - policy, - valid.selectedLocale(), - valid.binding(), - valid.recipient(), - valid.parameters(), - valid.idempotencyScope(), - valid.sourceOperationId(), - valid.tenantReference(), - valid.correlationReference(), - Optional.of("\n"), - notBefore, - notBefore.plusSeconds(60))) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new NotificationFrozenPlan( - valid.intentId(), - policy, - valid.selectedLocale(), - valid.binding(), - valid.recipient(), - valid.parameters(), - valid.idempotencyScope(), - valid.sourceOperationId(), - valid.tenantReference(), - valid.correlationReference(), - valid.causationReference(), - notBefore, - notBefore.plus(Duration.ofHours(2)))) - .isInstanceOf(IllegalArgumentException.class); - } - - private static NotificationKindPolicy durablePolicy(Duration retryHorizon) { - return new NotificationKindPolicy( - new NotificationKindId("password-reset"), - NotificationChannel.EMAIL, - new NotificationRouteId("email-primary"), - new NotificationTemplateRef("password-reset", 3), - NotificationMode.DURABLE_ASYNC, - NotificationAdmissionClass.SECURITY_CRITICAL, - NotificationRouteStrategy.SINGLE, - ConsentCheckMode.SNAPSHOT_AT_APPEND, - 7, - 1, - 3, - 0, - 1, - 4, - retryHorizon); - } -} diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/ReconcileNotificationDeliveriesUseCaseTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/ReconcileNotificationDeliveriesUseCaseTest.java deleted file mode 100644 index 64b8ef40..00000000 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/ReconcileNotificationDeliveriesUseCaseTest.java +++ /dev/null @@ -1,174 +0,0 @@ -package dev.caskeleton.application.notification; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.application.transaction.TransactionPort; -import java.time.Clock; -import java.time.Instant; -import java.time.ZoneOffset; -import java.util.ArrayList; -import java.util.List; -import java.util.function.Supplier; -import org.junit.jupiter.api.Test; - -class ReconcileNotificationDeliveriesUseCaseTest { - - private static final Instant NOW = Instant.parse("2026-07-28T00:00:00Z"); - - @Test - void claimThenProviderThenTokenGuardedFinalizeAndOrphanAttachRespectBoundaries() { - List trace = new ArrayList<>(); - TrackingTransactions transactions = new TrackingTransactions(trace); - RecordingStore store = new RecordingStore(trace); - NotificationReconciliationPort provider = - claim -> { - assertThat(transactions.active).isFalse(); - trace.add("provider"); - return new NotificationReconciliationPort.ReconciliationOutcome( - SubmissionCertainty.PROVIDER_ACCEPTED, - new NotificationReasonCode("RECONCILED_ACCEPTED")); - }; - ReconcileNotificationDeliveriesUseCase useCase = - new ReconcileNotificationDeliveriesUseCase( - store, provider, transactions, Clock.fixed(NOW, ZoneOffset.UTC)); - - ReconcileNotificationDeliveriesResult result = - useCase.handle(new ReconcileNotificationDeliveriesCommand(10, 10)); - - assertThat(trace) - .containsExactly( - "tx-begin", - "attach-orphans", - "tx-end", - "tx-begin", - "claim", - "tx-end", - "provider", - "tx-begin", - "finalize", - "tx-end"); - assertThat(result).isEqualTo(new ReconcileNotificationDeliveriesResult(1, 1, 1, 1)); - } - - @Test - void orphanOnlyCyclePerformsNoProviderIo() { - TrackingTransactions transactions = new TrackingTransactions(new ArrayList<>()); - RecordingStore store = new RecordingStore(new ArrayList<>()); - store.claims = List.of(); - final int[] providerCalls = {0}; - - ReconcileNotificationDeliveriesResult result = - new ReconcileNotificationDeliveriesUseCase( - store, - claim -> { - providerCalls[0]++; - throw new AssertionError("provider must not run for orphan-only cycle"); - }, - transactions, - Clock.fixed(NOW, ZoneOffset.UTC)) - .handle(new ReconcileNotificationDeliveriesCommand(0, 10)); - - assertThat(providerCalls[0]).isZero(); - assertThat(result.orphanAttachedCount()).isEqualTo(1); - } - - private static final class RecordingStore implements NotificationDeliveryStorePort { - - private final List trace; - private List claims = - List.of( - new ReconciliationClaim( - new NotificationDeliveryId("delivery-42"), - "reconcile-token-42", - 3, - new NotificationRouteId("security-slack"), - 3, - "a".repeat(64), - 0, - "slack-primary", - "slack-web-api-durable-single-local-v1", - "slack-binding-r1", - "credential-r1", - "provider-message-42", - NotificationDeliveryStorePort.ReconciliationLookupKind.MESSAGE_REFERENCE, - NOW.plusSeconds(30))); - - private RecordingStore(List trace) { - this.trace = trace; - } - - @Override - public List claimEligible(int maximumClaims, Instant now) { - return List.of(); - } - - @Override - public AttemptAuthorization reserveAndAuthorize(ClaimedDelivery claimed, Instant now) { - throw new UnsupportedOperationException(); - } - - @Override - public FinalizationResult finalizeAttempt( - AuthorizedAttempt attempt, AttemptFinalization finalization, Instant now) { - throw new UnsupportedOperationException(); - } - - @Override - public List claimForReconciliation(int maximumClaims, Instant now) { - trace.add("claim"); - return claims; - } - - @Override - public ReconciliationFinalizationResult finalizeReconciliation( - ReconciliationClaim claim, - NotificationReconciliationPort.ReconciliationOutcome outcome, - Instant now) { - trace.add("finalize"); - return ReconciliationFinalizationResult.APPLIED; - } - - @Override - public int attachOrphanReceipts(int maximumAttachments, Instant now) { - trace.add("attach-orphans"); - return maximumAttachments == 0 ? 0 : 1; - } - } - - private static final class TrackingTransactions implements TransactionPort { - - private final List trace; - private boolean active; - - private TrackingTransactions(List trace) { - this.trace = trace; - } - - @Override - public T inWrite(Supplier action) { - trace.add("tx-begin"); - active = true; - try { - return action.get(); - } finally { - active = false; - trace.add("tx-end"); - } - } - - @Override - public T inRootWrite(Supplier action) { - return inWrite(action); - } - - @Override - public T inRead(Supplier action) { - return action.get(); - } - - @Override - public T inNew(Supplier action) { - return action.get(); - } - } -} diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/RecordNotificationWriterQuiescenceAttestationUseCaseTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/RecordNotificationWriterQuiescenceAttestationUseCaseTest.java deleted file mode 100644 index b8546c46..00000000 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/RecordNotificationWriterQuiescenceAttestationUseCaseTest.java +++ /dev/null @@ -1,216 +0,0 @@ -package dev.caskeleton.application.notification; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.time.Clock; -import java.time.Duration; -import java.time.Instant; -import java.time.ZoneOffset; -import java.util.List; -import java.util.Set; -import java.util.concurrent.atomic.AtomicInteger; -import org.junit.jupiter.api.Test; - -class RecordNotificationWriterQuiescenceAttestationUseCaseTest { - - private static final Instant NOW = Instant.parse("2026-07-28T00:00:00Z"); - - @Test - void signedExactQuiescenceEvidenceIsVerifiedThenRootCommitted() { - NotificationWriterRouteSet routeSet = InitializeNotificationWriterFencesUseCaseTest.routeSet(); - NotificationCanonicalWriterRouteSet.RouteRevision route = - routeSet.canonicalRoutes().routes().getFirst(); - InitializeNotificationWriterFencesUseCaseTest.TrackingRootTransactions transactions = - new InitializeNotificationWriterFencesUseCaseTest.TrackingRootTransactions(); - SignedNotificationWriterQuiescenceManifest manifest = quiescenceManifest(route); - NotificationWriterQuiescenceAttestationPort verifier = - (signed, expectedRoute, expectedGeneration, trustedRoute, verifiedAt) -> { - assertThat(transactions.active).isFalse(); - assertThat(signed).isSameAs(manifest); - assertThat(trustedRoute.proofRequirement()) - .isEqualTo(NotificationWriterRouteSet.ProofClass.QUIESCENCE_REQUIRED); - return new NotificationWriterQuiescenceAttestationPort.VerifiedQuiescenceEvidence( - expectedRoute, - expectedGeneration, - signed.header().childSetDigest(), - signed.header().childCount(), - verifiedAt); - }; - RecordNotificationWriterQuiescenceAttestationOperation operation = - (command, evidence, trustedRoute, now) -> { - assertThat(transactions.active).isTrue(); - return new RecordNotificationWriterQuiescenceAttestationResult( - RecordNotificationWriterQuiescenceAttestationResult.Status.RECORDED, - command.operationToken(), - evidence.route(), - evidence.generation(), - evidence.childSetDigest()); - }; - RecordNotificationWriterQuiescenceAttestationUseCase useCase = - new RecordNotificationWriterQuiescenceAttestationUseCase( - routeSet, verifier, operation, transactions, Clock.fixed(NOW, ZoneOffset.UTC)); - - RecordNotificationWriterQuiescenceAttestationResult result = - useCase.handle( - new RecordNotificationWriterQuiescenceAttestationCommand( - "attestation-operation-42", - manifest, - "operator-42", - new NotificationReasonCode("QUIESCENCE_REVIEWED"))); - - assertThat(transactions.rootCalls).isEqualTo(1); - assertThat(result.status()) - .isEqualTo(RecordNotificationWriterQuiescenceAttestationResult.Status.RECORDED); - } - - @Test - void invalidSignatureOrHardBoundRouteFailsBeforePersistence() { - NotificationWriterRouteSet routeSet = InitializeNotificationWriterFencesUseCaseTest.routeSet(); - NotificationCanonicalWriterRouteSet.RouteRevision route = - routeSet.canonicalRoutes().routes().getFirst(); - InitializeNotificationWriterFencesUseCaseTest.TrackingRootTransactions transactions = - new InitializeNotificationWriterFencesUseCaseTest.TrackingRootTransactions(); - AtomicInteger operations = new AtomicInteger(); - RecordNotificationWriterQuiescenceAttestationUseCase invalidVerifierUseCase = - new RecordNotificationWriterQuiescenceAttestationUseCase( - routeSet, - (signed, expectedRoute, expectedGeneration, trustedRoute, verifiedAt) -> { - throw new NotificationApplicationException( - new NotificationReasonCode("EVIDENCE_SIGNATURE_INVALID"), null); - }, - (command, evidence, trustedRoute, now) -> { - operations.incrementAndGet(); - throw new AssertionError("operation must not run"); - }, - transactions, - Clock.fixed(NOW, ZoneOffset.UTC)); - - assertThatThrownBy( - () -> - invalidVerifierUseCase.handle( - new RecordNotificationWriterQuiescenceAttestationCommand( - "attestation-operation-42", - quiescenceManifest(route), - "operator-42", - new NotificationReasonCode("QUIESCENCE_REVIEWED")))) - .isInstanceOf(NotificationApplicationException.class); - - NotificationCanonicalWriterRouteSet.RouteRevision hardBoundRoute = - routeSet.canonicalRoutes().routes().get(1); - assertThatThrownBy( - () -> - invalidVerifierUseCase.handle( - new RecordNotificationWriterQuiescenceAttestationCommand( - "attestation-operation-43", - quiescenceManifest(hardBoundRoute), - "operator-42", - new NotificationReasonCode("QUIESCENCE_REVIEWED")))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("forbids"); - assertThat(operations).hasValue(0); - assertThat(transactions.rootCalls).isZero(); - } - - @Test - void transportProfilesMustExactlyMatchTrustedCurrentAndRetiringRegistry() { - NotificationWriterRouteSet routeSet = InitializeNotificationWriterFencesUseCaseTest.routeSet(); - NotificationCanonicalWriterRouteSet.RouteRevision route = - routeSet.canonicalRoutes().routes().getFirst(); - SignedNotificationWriterQuiescenceManifest valid = quiescenceManifest(route); - SignedNotificationWriterQuiescenceManifest drifted = - new SignedNotificationWriterQuiescenceManifest( - valid.header(), - valid.route(), - valid.drainingGeneration(), - Set.of("untrusted-profile"), - valid.nodes(), - valid.blockingPermitCount(), - valid.blockingPermitSetDigest(), - valid.permitHolderIds(), - valid.productionConsumerCount(), - valid.providerCallOpenCount()); - AtomicInteger verifierCalls = new AtomicInteger(); - RecordNotificationWriterQuiescenceAttestationUseCase useCase = - new RecordNotificationWriterQuiescenceAttestationUseCase( - routeSet, - (signed, expectedRoute, expectedGeneration, trustedRoute, verifiedAt) -> { - verifierCalls.incrementAndGet(); - throw new AssertionError("verifier must not run"); - }, - (command, evidence, trustedRoute, now) -> { - throw new AssertionError("operation must not run"); - }, - new InitializeNotificationWriterFencesUseCaseTest.TrackingRootTransactions(), - Clock.fixed(NOW, ZoneOffset.UTC)); - - assertThatThrownBy( - () -> - useCase.handle( - new RecordNotificationWriterQuiescenceAttestationCommand( - "attestation-operation-44", - drifted, - "operator-42", - new NotificationReasonCode("QUIESCENCE_REVIEWED")))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("exactly match"); - assertThat(verifierCalls).hasValue(0); - } - - static SignedNotificationWriterQuiescenceManifest quiescenceManifest( - NotificationCanonicalWriterRouteSet.RouteRevision route) { - NotificationSignedEvidenceHeader header = evidenceHeader(2, "b".repeat(64)); - return new SignedNotificationWriterQuiescenceManifest( - header, - route, - route.predecessorGeneration(), - Set.of("legacy-http-v1"), - List.of( - new SignedNotificationWriterQuiescenceManifest.NodeQuiescence( - "node-42", true, true, true, true, true)), - 0, - "c".repeat(64), - Set.of(), - 0, - 0); - } - - static SignedNotificationWriterInventoryManifest inventoryManifest( - NotificationCanonicalWriterRouteSet.RouteRevision route) { - return new SignedNotificationWriterInventoryManifest( - evidenceHeader(1, "d".repeat(64)), - route, - route.predecessorGeneration(), - List.of( - new SignedNotificationWriterInventoryManifest.NodeInventory( - "node-42", "legacy-artifact-r1"))); - } - - private static NotificationSignedEvidenceHeader evidenceHeader( - int childCount, String childDigest) { - return new NotificationSignedEvidenceHeader( - "notification-evidence-v1", - "canonical-payload".getBytes(java.nio.charset.StandardCharsets.UTF_8), - new byte[64], - "Ed25519", - "issuer-key-42", - new byte[44], - "e".repeat(64), - new NotificationEvidenceTrustSnapshot( - "trust-r1", - NotificationEvidenceTrustSnapshot.HistoricalKeyStatus.ALLOWED, - "e".repeat(64)), - NOW.minusSeconds(30), - NOW.plusSeconds(300), - Duration.ofSeconds(10), - Duration.ofSeconds(5), - "production", - "notification-db", - "legacy-artifact-r1", - "production-consumers-r1", - "provider-call-ledger-r1", - "provider-call-ledger-snapshot-42", - childCount, - childDigest); - } -} diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/SwitchNotificationWriterOwnershipUseCaseTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/SwitchNotificationWriterOwnershipUseCaseTest.java deleted file mode 100644 index db6f1cbe..00000000 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/SwitchNotificationWriterOwnershipUseCaseTest.java +++ /dev/null @@ -1,173 +0,0 @@ -package dev.caskeleton.application.notification; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.time.Clock; -import java.time.Instant; -import java.time.ZoneOffset; -import java.util.Arrays; -import java.util.Optional; -import java.util.concurrent.atomic.AtomicInteger; -import org.junit.jupiter.api.Test; - -class SwitchNotificationWriterOwnershipUseCaseTest { - - private static final Instant NOW = Instant.parse("2026-07-28T00:00:00Z"); - - @Test - void beginDrainVerifiesSignedInventoryThenRootCommitsClosedTransition() { - NotificationWriterRouteSet routeSet = InitializeNotificationWriterFencesUseCaseTest.routeSet(); - NotificationCanonicalWriterRouteSet.RouteRevision route = - routeSet.canonicalRoutes().routes().getFirst(); - SignedNotificationWriterInventoryManifest manifest = - RecordNotificationWriterQuiescenceAttestationUseCaseTest.inventoryManifest(route); - InitializeNotificationWriterFencesUseCaseTest.TrackingRootTransactions transactions = - new InitializeNotificationWriterFencesUseCaseTest.TrackingRootTransactions(); - NotificationWriterInventoryEvidenceVerifierPort verifier = - (signed, expectedRoute, expectedGeneration, verifiedAt) -> - new NotificationWriterInventoryEvidence( - expectedRoute, - expectedGeneration, - signed.nodeIds(), - signed.header().childSetDigest(), - verifiedAt); - SwitchNotificationWriterOwnershipOperation operation = - (command, inventoryEvidence, trustedRoute, now) -> { - assertThat(transactions.active).isTrue(); - assertThat(inventoryEvidence).isPresent(); - return SwitchNotificationWriterOwnershipResult.applied( - command.action(), - command.route(), - NotificationWriterOwnership.LEGACY, - command.expectedGeneration(), - command.operationToken()); - }; - SwitchNotificationWriterOwnershipUseCase useCase = - new SwitchNotificationWriterOwnershipUseCase( - routeSet, verifier, operation, transactions, Clock.fixed(NOW, ZoneOffset.UTC)); - - SwitchNotificationWriterOwnershipResult result = - useCase.handle( - SwitchNotificationWriterOwnershipCommand.beginDrain( - route, - 7, - "switch-operation-42", - "operator-42", - new NotificationReasonCode("BEGIN_REVIEWED_DRAIN"), - manifest)); - - assertThat(transactions.rootCalls).isEqualTo(1); - assertThat(result.state()) - .isEqualTo(SwitchNotificationWriterOwnershipResult.FenceState.DRAINING); - assertThat(result.owner()).isEqualTo(NotificationWriterOwnership.LEGACY); - assertThat(result.generation()).isEqualTo(7); - } - - @Test - void completeAndAbortDeriveOwnerAndNextGenerationWithoutTargetOwnerInput() { - NotificationWriterRouteSet routeSet = InitializeNotificationWriterFencesUseCaseTest.routeSet(); - NotificationCanonicalWriterRouteSet.RouteRevision quiescenceRoute = - routeSet.canonicalRoutes().routes().getFirst(); - InitializeNotificationWriterFencesUseCaseTest.TrackingRootTransactions transactions = - new InitializeNotificationWriterFencesUseCaseTest.TrackingRootTransactions(); - SwitchNotificationWriterOwnershipUseCase useCase = - new SwitchNotificationWriterOwnershipUseCase( - routeSet, - (signed, expectedRoute, expectedGeneration, verifiedAt) -> { - throw new AssertionError("inventory verifier is only used for BEGIN"); - }, - (command, inventoryEvidence, trustedRoute, now) -> { - NotificationWriterOwnership owner = - command.action() - == SwitchNotificationWriterOwnershipCommand.Action.COMPLETE_SWITCH - ? NotificationWriterOwnership.CANONICAL - : NotificationWriterOwnership.LEGACY; - return SwitchNotificationWriterOwnershipResult.applied( - command.action(), - command.route(), - owner, - command.reviewedTargetGeneration(), - command.operationToken()); - }, - transactions, - Clock.fixed(NOW, ZoneOffset.UTC)); - - SwitchNotificationWriterOwnershipResult complete = - useCase.handle( - SwitchNotificationWriterOwnershipCommand.completeSwitch( - quiescenceRoute, - 7, - 8, - "switch-operation-43", - "operator-42", - new NotificationReasonCode("COMPLETE_REVIEWED_SWITCH"), - Optional.of("attestation-operation-42"))); - SwitchNotificationWriterOwnershipResult abort = - useCase.handle( - SwitchNotificationWriterOwnershipCommand.abortDrain( - quiescenceRoute, - 7, - 8, - "switch-operation-44", - "operator-42", - new NotificationReasonCode("ABORT_REVIEWED_DRAIN"))); - - assertThat(complete.owner()).isEqualTo(NotificationWriterOwnership.CANONICAL); - assertThat(complete.generation()).isEqualTo(8); - assertThat(abort.owner()).isEqualTo(NotificationWriterOwnership.LEGACY); - assertThat(abort.generation()).isEqualTo(8); - assertThat( - Arrays.stream(SwitchNotificationWriterOwnershipCommand.class.getRecordComponents()) - .map(java.lang.reflect.RecordComponent::getName)) - .noneMatch(name -> name.toLowerCase(java.util.Locale.ROOT).contains("owner")); - } - - @Test - void quiescenceRequirementAndClosedGenerationMatrixFailBeforeOperation() { - NotificationWriterRouteSet routeSet = InitializeNotificationWriterFencesUseCaseTest.routeSet(); - NotificationCanonicalWriterRouteSet.RouteRevision route = - routeSet.canonicalRoutes().routes().getFirst(); - AtomicInteger operations = new AtomicInteger(); - InitializeNotificationWriterFencesUseCaseTest.TrackingRootTransactions transactions = - new InitializeNotificationWriterFencesUseCaseTest.TrackingRootTransactions(); - SwitchNotificationWriterOwnershipUseCase useCase = - new SwitchNotificationWriterOwnershipUseCase( - routeSet, - (signed, expectedRoute, expectedGeneration, verifiedAt) -> { - throw new AssertionError("not called"); - }, - (command, inventoryEvidence, trustedRoute, now) -> { - operations.incrementAndGet(); - throw new AssertionError("operation must not run"); - }, - transactions, - Clock.systemUTC()); - - assertThatThrownBy( - () -> - useCase.handle( - SwitchNotificationWriterOwnershipCommand.completeSwitch( - route, - 7, - 8, - "switch-operation-42", - "operator-42", - new NotificationReasonCode("COMPLETE_REVIEWED_SWITCH"), - Optional.empty()))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("attestation"); - assertThatThrownBy( - () -> - SwitchNotificationWriterOwnershipCommand.abortDrain( - route, - 7, - 9, - "switch-operation-42", - "operator-42", - new NotificationReasonCode("ABORT_REVIEWED_DRAIN"))) - .isInstanceOf(IllegalArgumentException.class); - assertThat(operations).hasValue(0); - assertThat(transactions.rootCalls).isZero(); - } -} diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/TerminalizeExpiredNotificationWriterPermitsUseCaseTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/TerminalizeExpiredNotificationWriterPermitsUseCaseTest.java deleted file mode 100644 index 40d919e9..00000000 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/TerminalizeExpiredNotificationWriterPermitsUseCaseTest.java +++ /dev/null @@ -1,89 +0,0 @@ -package dev.caskeleton.application.notification; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.time.Clock; -import java.time.Instant; -import java.time.ZoneOffset; -import java.util.concurrent.atomic.AtomicInteger; -import org.junit.jupiter.api.Test; - -class TerminalizeExpiredNotificationWriterPermitsUseCaseTest { - - @Test - void terminalizationIsBoundedAuthenticatedAndRootCommittedAgainstTrustedRegistry() { - NotificationWriterRouteSet routeSet = InitializeNotificationWriterFencesUseCaseTest.routeSet(); - InitializeNotificationWriterFencesUseCaseTest.TrackingRootTransactions transactions = - new InitializeNotificationWriterFencesUseCaseTest.TrackingRootTransactions(); - TerminalizeExpiredNotificationWriterPermitsOperation operation = - (command, trustedRoute, now) -> { - assertThat(transactions.active).isTrue(); - assertThat(trustedRoute.proofRequirement()) - .isEqualTo(NotificationWriterRouteSet.ProofClass.QUIESCENCE_REQUIRED); - return new TerminalizeExpiredNotificationWriterPermitsResult( - TerminalizeExpiredNotificationWriterPermitsResult.Status.APPLIED, 2, "a".repeat(64)); - }; - TerminalizeExpiredNotificationWriterPermitsUseCase useCase = - new TerminalizeExpiredNotificationWriterPermitsUseCase( - routeSet, - operation, - transactions, - Clock.fixed(Instant.parse("2026-07-28T00:00:00Z"), ZoneOffset.UTC)); - - TerminalizeExpiredNotificationWriterPermitsResult result = - useCase.handle( - new TerminalizeExpiredNotificationWriterPermitsCommand( - routeSet.canonicalRoutes().routes().getFirst(), - 7, - 100, - "terminalize-operation-42", - "operator-42", - new NotificationReasonCode("TERMINALIZE_EXPIRED_PERMITS"))); - - assertThat(transactions.rootCalls).isEqualTo(1); - assertThat(result.affectedCount()).isEqualTo(2); - } - - @Test - void batchAboveHundredAndUnknownRouteFailWithoutMutation() { - NotificationWriterRouteSet routeSet = InitializeNotificationWriterFencesUseCaseTest.routeSet(); - InitializeNotificationWriterFencesUseCaseTest.TrackingRootTransactions transactions = - new InitializeNotificationWriterFencesUseCaseTest.TrackingRootTransactions(); - AtomicInteger calls = new AtomicInteger(); - TerminalizeExpiredNotificationWriterPermitsUseCase useCase = - new TerminalizeExpiredNotificationWriterPermitsUseCase( - routeSet, - (command, trustedRoute, now) -> { - calls.incrementAndGet(); - throw new AssertionError("operation must not run"); - }, - transactions, - Clock.systemUTC()); - - assertThatThrownBy( - () -> - new TerminalizeExpiredNotificationWriterPermitsCommand( - routeSet.canonicalRoutes().routes().getFirst(), - 7, - 101, - "terminalize-operation-42", - "operator-42", - new NotificationReasonCode("TERMINALIZE_EXPIRED_PERMITS"))) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - useCase.handle( - new TerminalizeExpiredNotificationWriterPermitsCommand( - new NotificationCanonicalWriterRouteSet.RouteRevision( - new NotificationRouteId("unknown-route"), 1, 0), - 0, - 1, - "terminalize-operation-42", - "operator-42", - new NotificationReasonCode("TERMINALIZE_EXPIRED_PERMITS")))) - .isInstanceOf(IllegalArgumentException.class); - assertThat(calls).hasValue(0); - assertThat(transactions.rootCalls).isZero(); - } -} diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/api/PublicApiBoundaryTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/api/PublicApiBoundaryTest.java index 42a78cc5..a35de54f 100644 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/api/PublicApiBoundaryTest.java +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/api/PublicApiBoundaryTest.java @@ -2,8 +2,6 @@ package dev.caskeleton.application.notification.platform.api; import static org.assertj.core.api.Assertions.assertThat; -import java.lang.reflect.Method; -import java.util.Arrays; import org.junit.jupiter.api.Test; class PublicApiBoundaryTest { @@ -14,30 +12,4 @@ class PublicApiBoundaryTest { .extracting(component -> component.getName()) .doesNotContain("delivered", "sent", "read"); } - - @Test - void orchestratorReturnsDurableReceipt() throws Exception { - Method method = NotificationOrchestrator.class.getMethod("submit", NotificationPlan.class); - assertThat(method.getReturnType()).isEqualTo(NotificationReceipt.class); - } - - @Test - void typedFacadesDoNotAcceptRawMaps() { - assertThat( - Arrays.stream( - dev.caskeleton.application.notification.platform.email.EmailNotifier.class - .getMethods()) - .flatMap(method -> Arrays.stream(method.getParameterTypes())) - .anyMatch(java.util.Map.class::isAssignableFrom)) - .isFalse(); - } - - @Test - void smsFacadeExposesSegmentEstimationBeforeSending() throws Exception { - Method estimate = - dev.caskeleton.application.notification.platform.sms.SmsNotifier.class.getMethod( - "estimate", dev.caskeleton.application.notification.platform.sms.SmsNotification.class); - assertThat(estimate.getReturnType()) - .isEqualTo(dev.caskeleton.application.notification.platform.sms.SmsEstimate.class); - } } diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/api/PublicApiIsTypedTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/api/PublicApiIsTypedTest.java index 4a482a73..b5e2bcc3 100644 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/api/PublicApiIsTypedTest.java +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/api/PublicApiIsTypedTest.java @@ -28,12 +28,7 @@ import org.junit.jupiter.api.Test; class PublicApiIsTypedTest { private static final List PUBLIC_RECORD_PACKAGES = - List.of( - "dev.caskeleton.application.notification.platform.api", - "dev.caskeleton.application.notification.platform.email", - "dev.caskeleton.application.notification.platform.sms", - "dev.caskeleton.application.notification.platform.push", - "dev.caskeleton.application.notification.platform.webpush"); + List.of("dev.caskeleton.application.notification.platform.api"); @Test @DisplayName("no public API record carries an untyped value at any depth") diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/api/error/NotificationExceptionTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/api/error/NotificationExceptionTest.java index d0040315..e5f08b3d 100644 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/api/error/NotificationExceptionTest.java +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/api/error/NotificationExceptionTest.java @@ -42,7 +42,7 @@ class NotificationExceptionTest { @Test void exceptionMessageDoesNotContainRecipient() { var exception = - new NotificationSuppressedException( + new NotificationValidationException( NotificationFailureDescriptor.suppressed("USER_OPT_OUT", Channel.SMS)); assertThat(exception.getMessage()).doesNotContain("+821012345678"); assertThat(exception.getMessage()).isEqualTo(NotificationFailureCode.NOTIFICATION_SUPPRESSED); diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/crypto/ContactPointRoundTripTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/contact/ContactPointRoundTripTest.java similarity index 81% rename from src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/crypto/ContactPointRoundTripTest.java rename to src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/contact/ContactPointRoundTripTest.java index 0f6db50c..69abca0d 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/notification/crypto/ContactPointRoundTripTest.java +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/contact/ContactPointRoundTripTest.java @@ -1,16 +1,7 @@ -package dev.caskeleton.adapter.outbound.persistence.notification.crypto; +package dev.caskeleton.application.notification.platform.contact; import static org.assertj.core.api.Assertions.assertThat; -import dev.caskeleton.application.notification.platform.contact.ApnsDeviceToken; -import dev.caskeleton.application.notification.platform.contact.ApnsEnvironment; -import dev.caskeleton.application.notification.platform.contact.ContactPointValue; -import dev.caskeleton.application.notification.platform.contact.EmailAddress; -import dev.caskeleton.application.notification.platform.contact.FcmInstallationId; -import dev.caskeleton.application.notification.platform.contact.InAppRecipientRef; -import dev.caskeleton.application.notification.platform.contact.LegacyFcmRegistrationToken; -import dev.caskeleton.application.notification.platform.contact.PhoneNumber; -import dev.caskeleton.application.notification.platform.contact.WebPushSubscriptionValue; import java.net.URI; import java.util.List; import org.junit.jupiter.api.DisplayName; diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/ApplicationReceiptServiceImplTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/ApplicationReceiptServiceImplTest.java deleted file mode 100644 index 53776366..00000000 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/ApplicationReceiptServiceImplTest.java +++ /dev/null @@ -1,87 +0,0 @@ -package dev.caskeleton.application.notification.platform.dispatch; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.application.notification.platform.api.ContactPointId; -import dev.caskeleton.application.notification.platform.api.DeliveryAttemptId; -import dev.caskeleton.application.notification.platform.api.NotificationId; -import dev.caskeleton.application.notification.platform.api.ProviderId; -import dev.caskeleton.application.notification.platform.api.ProviderProfileId; -import dev.caskeleton.application.notification.platform.api.RecipientDeliveryId; -import dev.caskeleton.application.notification.platform.api.TenantId; -import dev.caskeleton.application.notification.platform.api.delivery.AttemptConfirmation; -import dev.caskeleton.application.notification.platform.api.delivery.DeliveryOutcome; -import dev.caskeleton.application.notification.platform.api.delivery.EvidenceLevel; -import dev.caskeleton.application.notification.platform.api.delivery.SubmissionOutcome; -import dev.caskeleton.application.notification.platform.api.routing.Channel; -import dev.caskeleton.application.notification.platform.callback.DeliveryAttemptSnapshot; -import dev.caskeleton.application.notification.platform.push.ApplicationIdentity; -import dev.caskeleton.application.notification.platform.push.ApplicationReceipt; -import dev.caskeleton.application.notification.platform.push.ReceiptAuthorizationException; -import dev.caskeleton.application.notification.platform.push.ReceiptKind; -import java.time.Clock; -import java.time.Instant; -import java.time.ZoneOffset; -import java.util.Optional; -import java.util.UUID; -import org.junit.jupiter.api.Test; - -class ApplicationReceiptServiceImplTest { - - private static final Instant NOW = Instant.parse("2026-09-20T00:00:00Z"); - private static final DeliveryAttemptId ATTEMPT_ID = - new DeliveryAttemptId(UUID.fromString("00000000-0000-7000-8000-000000000061")); - - @Test - void unauthenticatedApplicationCannotWriteReceiptEvidence() { - ApplicationReceiptServiceImpl service = - NotificationPlatformNoops.receiptService( - new PlatformFakes.AttemptStore(), Clock.fixed(NOW, ZoneOffset.UTC)); - - assertThatThrownBy( - () -> service.record(receipt(), new ApplicationIdentity("mobile-app", "user-1", false))) - .isInstanceOf(ReceiptAuthorizationException.class); - } - - @Test - void authenticatedMatchingSubjectRecordsAgainstTheExistingAttempt() { - PlatformFakes.AttemptStore attempts = new PlatformFakes.AttemptStore(); - attempts.snapshots.put(ATTEMPT_ID, snapshot()); - ApplicationReceiptServiceImpl service = - NotificationPlatformNoops.receiptService(attempts, Clock.fixed(NOW, ZoneOffset.UTC)); - - var result = service.record(receipt(), new ApplicationIdentity("mobile-app", "user-1", true)); - - assertThat(result.attemptId()).isEqualTo(ATTEMPT_ID); - assertThat(result.created()).isFalse(); - } - - private static ApplicationReceipt receipt() { - return new ApplicationReceipt( - "receipt-1", ATTEMPT_ID, ReceiptKind.READ, "user-1", Optional.of(NOW.minusSeconds(1))); - } - - private static DeliveryAttemptSnapshot snapshot() { - return new DeliveryAttemptSnapshot( - ATTEMPT_ID, - new RecipientDeliveryId(UUID.fromString("00000000-0000-7000-8000-000000000062")), - new NotificationId(UUID.fromString("00000000-0000-7000-8000-000000000063")), - new TenantId("tenant-a"), - 1, - Channel.PUSH, - new ProviderId("fcm"), - new ProviderProfileId("fcm-primary"), - Optional.of("provider-request-1"), - new ContactPointId(UUID.fromString("00000000-0000-7000-8000-000000000064")), - AttemptConfirmation.CONFIRMED, - SubmissionOutcome.CONFIRMED_ACCEPTED, - DeliveryOutcome.UNKNOWN, - EvidenceLevel.PROVIDER_ACCEPTED, - 1L, - "b".repeat(64), - NOW.minusSeconds(30), - Optional.of(NOW.minusSeconds(20)), - Optional.empty()); - } -} diff --git a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/LeaseRecoveryServiceTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/LeaseRecoveryServiceTest.java similarity index 94% rename from src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/LeaseRecoveryServiceTest.java rename to src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/LeaseRecoveryServiceTest.java index 0fd3c926..8031f084 100644 --- a/src/adapter/outbound/notification/src/test/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/LeaseRecoveryServiceTest.java +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/LeaseRecoveryServiceTest.java @@ -1,16 +1,10 @@ -package dev.caskeleton.adapter.outbound.notification.platform.dispatch; +package dev.caskeleton.application.notification.platform.dispatch; import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.application.notification.platform.api.DeliveryAttemptId; import dev.caskeleton.application.notification.platform.api.RecipientDeliveryId; import dev.caskeleton.application.notification.platform.api.delivery.RecipientDeliveryState; -import dev.caskeleton.application.notification.platform.dispatch.DeliveryAttemptRecord; -import dev.caskeleton.application.notification.platform.dispatch.DeliveryAttemptStorePort; -import dev.caskeleton.application.notification.platform.dispatch.RecipientDeliveryRecord; -import dev.caskeleton.application.notification.platform.dispatch.RecipientDeliveryStorePort; -import dev.caskeleton.application.notification.platform.dispatch.RecipientLease; -import dev.caskeleton.application.notification.platform.dispatch.RecipientLeaseStorePort; import java.time.Clock; import java.time.Duration; import java.time.Instant; @@ -43,7 +37,14 @@ class LeaseRecoveryServiceTest { private final LeaseRecoveryService recovery = new LeaseRecoveryService( - leases, attempts, deliveries, reconciled::add, CLOCK, Duration.ofMinutes(1), 10); + leases, + attempts, + deliveries, + reconciled::add, + new PlatformFakes.RecordingTransactions(), + CLOCK, + Duration.ofMinutes(1), + 10); @Test @DisplayName("a delivery with no attempt is requeued, because nothing can have been sent") diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/NotificationPlatformNoops.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/NotificationPlatformNoops.java index f813eed0..15df35be 100644 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/NotificationPlatformNoops.java +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/NotificationPlatformNoops.java @@ -50,6 +50,7 @@ public final class NotificationPlatformNoops { audit(), metrics(), new SyntheticEventFingerprint(NotificationPlatformNoops::sha256), + new PlatformFakes.RecordingTransactions(), clock); } @@ -88,13 +89,6 @@ public final class NotificationPlatformNoops { java.time.Duration.ofSeconds(30)); } - public static ApplicationReceiptServiceImpl receiptService( - DeliveryAttemptStorePort attempts, Clock clock) { - ProviderEventLedger ledger = new NoopLedger(); - return new ApplicationReceiptServiceImpl( - attempts, ledger, projection(ledger), new PlatformFakes.RecordingTransactions(), clock); - } - public static NotificationAuditPort audit() { return event -> {}; } diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/security/NotificationRedactionTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/security/NotificationRedactionTest.java deleted file mode 100644 index 99b9b25a..00000000 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/security/NotificationRedactionTest.java +++ /dev/null @@ -1,54 +0,0 @@ -package dev.caskeleton.application.notification.platform.security; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.util.Map; -import org.junit.jupiter.api.Test; - -class NotificationRedactionTest { - - private final NotificationRedactor redactor = new NotificationRedactor(); - - @Test - void redactsAllContactAndCredentialKinds() { - var classified = - Map.of( - "user@example.com", SensitiveValueKind.EMAIL_ADDRESS, - "+821012345678", SensitiveValueKind.PHONE_NUMBER, - "fcm-token", SensitiveValueKind.PUSH_TARGET, - "https://push.example.com/sub/abc", SensitiveValueKind.WEB_PUSH_ENDPOINT, - "bearer-secret", SensitiveValueKind.PROVIDER_CREDENTIAL); - var input = - "user@example.com +821012345678 fcm-token https://push.example.com/sub/abc bearer-secret"; - - var redacted = redactor.redact(input, classified); - - assertThat(redacted) - .doesNotContain( - "user@example.com", - "+821012345678", - "fcm-token", - "https://push.example.com/sub/abc", - "bearer-secret"); - assertThat(redacted).contains("[redacted:EMAIL_ADDRESS]"); - } - - @Test - void safeContextAcceptsOnlyBoundedFields() { - assertThatThrownBy( - () -> SafeDiagnosticContext.builder().put("providerRequestId", "SM123").build()) - .isInstanceOf(UnsafeDiagnosticFieldException.class); - assertThat(SafeDiagnosticContext.builder().put("channel", "SMS").build().fields()) - .containsEntry("channel", "SMS"); - } - - @Test - void classifierRecognisesAddressesThatWereNeverRegistered() { - var classifier = new SensitiveValueClassifier(Map.of()); - assertThat(classifier.classify("someone@example.org")) - .contains(SensitiveValueKind.EMAIL_ADDRESS); - assertThat(classifier.classify("+441234567890")).contains(SensitiveValueKind.PHONE_NUMBER); - assertThat(classifier.classify("password-reset")).isEmpty(); - } -} diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/sms/SmsSegmentEstimatorTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/sms/SmsSegmentEstimatorTest.java deleted file mode 100644 index 09a79927..00000000 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/sms/SmsSegmentEstimatorTest.java +++ /dev/null @@ -1,51 +0,0 @@ -package dev.caskeleton.application.notification.platform.sms; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import org.junit.jupiter.api.Test; - -class SmsSegmentEstimatorTest { - - private final SmsSegmentEstimator estimator = new SmsSegmentEstimator(); - private final E164PhoneNumberParser parser = new E164PhoneNumberParser(); - - @Test - void gsm7BoundaryUsesOneThenTwoSegments() { - assertThat(estimator.estimate("a".repeat(160)).segmentCount()).isEqualTo(1); - assertThat(estimator.estimate("a".repeat(161)).segmentCount()).isEqualTo(2); - } - - @Test - void unicodeBoundaryUsesUcs2() { - assertThat(estimator.estimate("가".repeat(70)).segmentCount()).isEqualTo(1); - assertThat(estimator.estimate("가".repeat(71)).segmentCount()).isEqualTo(2); - assertThat(estimator.estimate("hello🙂").encoding()).isEqualTo(SmsEncoding.UCS_2); - } - - @Test - void extensionTableCharactersCostTwoSeptets() { - assertThat(estimator.estimate("€").encodedLength()).isEqualTo(2); - assertThat(estimator.estimate("a".repeat(158) + "€").segmentCount()).isEqualTo(1); - assertThat(estimator.estimate("a".repeat(159) + "€").segmentCount()).isEqualTo(2); - } - - @Test - void oneNonGsmCharacterChangesTheWholeMessageEncoding() { - assertThat(estimator.estimate("a".repeat(100)).encoding()).isEqualTo(SmsEncoding.GSM_7); - assertThat(estimator.estimate("a".repeat(100) + "가").encoding()).isEqualTo(SmsEncoding.UCS_2); - assertThat(estimator.estimate("a".repeat(100) + "가").segmentCount()).isEqualTo(2); - } - - @Test - void parsesE164AndRejectsLocalNumber() { - assertThat(parser.parse("+821012345678").e164()).isEqualTo("+821012345678"); - assertThatThrownBy(() -> parser.parse("01012345678")) - .isInstanceOf(InvalidPhoneNumberException.class); - } - - @Test - void rejectionDoesNotEchoTheRejectedNumber() { - assertThatThrownBy(() -> parser.parse("01012345678")).hasMessageNotContaining("01012345678"); - } -} diff --git a/src/application-objectstorage/src/main/java/dev/caskeleton/application/storage/migration/LegacyObjectAdoptionApproval.java b/src/application-objectstorage/src/main/java/dev/caskeleton/application/storage/migration/LegacyObjectAdoptionApproval.java deleted file mode 100644 index ebd0d19a..00000000 --- a/src/application-objectstorage/src/main/java/dev/caskeleton/application/storage/migration/LegacyObjectAdoptionApproval.java +++ /dev/null @@ -1,39 +0,0 @@ -package dev.caskeleton.application.storage.migration; - -import dev.caskeleton.application.objectstorage.identity.ObjectDestinationId; -import dev.caskeleton.application.objectstorage.identity.ObjectOperationKey; -import java.time.Instant; - -/** Verified, expiry-bounded two-approver authorization for one exact adoption manifest. */ -@Deprecated -public record LegacyObjectAdoptionApproval( - ObjectOperationKey operationKey, - String manifestSha256, - String legacyNamespaceDigest, - ObjectDestinationId targetDestination, - String targetNamespaceDigest, - Instant notBefore, - Instant expiresAt, - String nonce, - String approvalDigest) { - - public LegacyObjectAdoptionApproval { - if (operationKey == null - || !hex64(manifestSha256) - || !hex64(legacyNamespaceDigest) - || targetDestination == null - || !hex64(targetNamespaceDigest) - || notBefore == null - || expiresAt == null - || !expiresAt.isAfter(notBefore) - || nonce == null - || !nonce.matches("[A-Za-z0-9_-]{16,128}") - || !hex64(approvalDigest)) { - throw new IllegalArgumentException("legacy adoption approval is invalid"); - } - } - - private static boolean hex64(String value) { - return value != null && value.matches("[0-9a-f]{64}"); - } -} diff --git a/src/application-objectstorage/src/main/java/dev/caskeleton/application/storage/migration/LegacyObjectAdoptionApprovalVerifierPort.java b/src/application-objectstorage/src/main/java/dev/caskeleton/application/storage/migration/LegacyObjectAdoptionApprovalVerifierPort.java deleted file mode 100644 index c7e0ba48..00000000 --- a/src/application-objectstorage/src/main/java/dev/caskeleton/application/storage/migration/LegacyObjectAdoptionApprovalVerifierPort.java +++ /dev/null @@ -1,9 +0,0 @@ -package dev.caskeleton.application.storage.migration; - -/** Verifies a detached canonical approval before any adoption mutation. */ -@Deprecated -public interface LegacyObjectAdoptionApprovalVerifierPort { - - LegacyObjectAdoptionApproval verify( - byte[] canonicalApprovalDocument, LegacyObjectAdoptionRequest expectedRequest); -} diff --git a/src/application-objectstorage/src/main/java/dev/caskeleton/application/storage/migration/LegacyObjectAdoptionPort.java b/src/application-objectstorage/src/main/java/dev/caskeleton/application/storage/migration/LegacyObjectAdoptionPort.java deleted file mode 100644 index 7d103359..00000000 --- a/src/application-objectstorage/src/main/java/dev/caskeleton/application/storage/migration/LegacyObjectAdoptionPort.java +++ /dev/null @@ -1,8 +0,0 @@ -package dev.caskeleton.application.storage.migration; - -/** Deprecated administrative migration seam; unavailable to normal business composition. */ -@Deprecated -public interface LegacyObjectAdoptionPort { - - LegacyObjectAdoptionReceipt adopt(LegacyObjectAdoptionRequest request); -} diff --git a/src/application-objectstorage/src/main/java/dev/caskeleton/application/storage/migration/LegacyObjectAdoptionReceipt.java b/src/application-objectstorage/src/main/java/dev/caskeleton/application/storage/migration/LegacyObjectAdoptionReceipt.java deleted file mode 100644 index 29a9579d..00000000 --- a/src/application-objectstorage/src/main/java/dev/caskeleton/application/storage/migration/LegacyObjectAdoptionReceipt.java +++ /dev/null @@ -1,34 +0,0 @@ -package dev.caskeleton.application.storage.migration; - -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.ObjectContentIdentity; -import dev.caskeleton.application.objectstorage.model.ObjectMediaType; -import dev.caskeleton.application.objectstorage.model.ObjectMutationOutcome; -import java.time.Instant; - -/** Locator-free evidence from a report-only inspection or reviewed adoption apply. */ -@Deprecated -public record LegacyObjectAdoptionReceipt( - ObjectOperationKey operationKey, - ObjectContentIdentity contentIdentity, - ObjectMediaType mediaType, - ObjectVersionToken inspectedLegacyVersion, - ObjectReference adoptedReference, - ObjectVersionToken adoptedVersion, - ObjectMutationOutcome outcome, - Instant recordedAt) { - - public LegacyObjectAdoptionReceipt { - if (operationKey == null - || contentIdentity == null - || mediaType == null - || inspectedLegacyVersion == null - || outcome == null - || recordedAt == null - || (adoptedReference == null) != (adoptedVersion == null)) { - throw new IllegalArgumentException("legacy adoption receipt is invalid"); - } - } -} diff --git a/src/application-objectstorage/src/main/java/dev/caskeleton/application/storage/migration/LegacyObjectAdoptionRequest.java b/src/application-objectstorage/src/main/java/dev/caskeleton/application/storage/migration/LegacyObjectAdoptionRequest.java deleted file mode 100644 index 963dab5a..00000000 --- a/src/application-objectstorage/src/main/java/dev/caskeleton/application/storage/migration/LegacyObjectAdoptionRequest.java +++ /dev/null @@ -1,36 +0,0 @@ -package dev.caskeleton.application.storage.migration; - -import dev.caskeleton.application.objectstorage.request.ObjectPublishRequest; - -/** Exact report/apply request for one reviewed legacy locator. */ -@Deprecated -public record LegacyObjectAdoptionRequest( - LegacyObjectLocator locator, - ObjectPublishRequest publicationRequest, - String manifestSha256, - String legacyNamespaceDigest, - String targetNamespaceDigest, - Mode mode, - LegacyObjectAdoptionApproval approval) { - - public LegacyObjectAdoptionRequest { - if (locator == null - || publicationRequest == null - || !hex64(manifestSha256) - || !hex64(legacyNamespaceDigest) - || !hex64(targetNamespaceDigest) - || mode == null - || (mode == Mode.REPORT_ONLY && approval != null)) { - throw new IllegalArgumentException("legacy object adoption request is invalid"); - } - } - - public enum Mode { - REPORT_ONLY, - APPLY - } - - private static boolean hex64(String value) { - return value != null && value.matches("[0-9a-f]{64}"); - } -} diff --git a/src/application-objectstorage/src/main/java/dev/caskeleton/application/storage/migration/LegacyObjectLocator.java b/src/application-objectstorage/src/main/java/dev/caskeleton/application/storage/migration/LegacyObjectLocator.java deleted file mode 100644 index 2b296a51..00000000 --- a/src/application-objectstorage/src/main/java/dev/caskeleton/application/storage/migration/LegacyObjectLocator.java +++ /dev/null @@ -1,54 +0,0 @@ -package dev.caskeleton.application.storage.migration; - -import java.nio.charset.StandardCharsets; -import java.util.Objects; - -/** - * Deprecated administrative raw-locator exception used only by the isolated adoption workflow. - * - *

The value is deliberately redacted from {@link #toString()} and exception messages. - */ -@Deprecated -public final class LegacyObjectLocator { - - private static final int MAXIMUM_UTF8_BYTES = 1024; - private final String value; - - private LegacyObjectLocator(String value) { - this.value = value; - } - - public static LegacyObjectLocator of(String value) { - if (value == null - || value.isBlank() - || value.getBytes(StandardCharsets.UTF_8).length > MAXIMUM_UTF8_BYTES - || value.codePoints().anyMatch(LegacyObjectLocator::isControl)) { - throw new IllegalArgumentException("legacy object locator is invalid"); - } - return new LegacyObjectLocator(value); - } - - /** Available only to the named migration adapter/use case; never log or persist this value. */ - public String migrationValue() { - return value; - } - - @Override - public String toString() { - return "LegacyObjectLocator[redacted]"; - } - - @Override - public boolean equals(Object other) { - return other instanceof LegacyObjectLocator locator && value.equals(locator.value); - } - - @Override - public int hashCode() { - return Objects.hash(value); - } - - private static boolean isControl(int codePoint) { - return Character.isISOControl(codePoint); - } -} diff --git a/src/application-objectstorage/src/test/java/dev/caskeleton/application/objectstorage/ObjectStorageArchitectureContractTest.java b/src/application-objectstorage/src/test/java/dev/caskeleton/application/objectstorage/ObjectStorageArchitectureContractTest.java index 343e28e7..135f3bca 100644 --- a/src/application-objectstorage/src/test/java/dev/caskeleton/application/objectstorage/ObjectStorageArchitectureContractTest.java +++ b/src/application-objectstorage/src/test/java/dev/caskeleton/application/objectstorage/ObjectStorageArchitectureContractTest.java @@ -40,14 +40,6 @@ class ObjectStorageArchitectureContractTest { "dev.caskeleton.bootstrap.", "java.nio.file.Path", "java.io.File"); - private static final List ACTIVE_MIGRATION_TYPE_NAMES = - List.of( - "dev.caskeleton.application.storage.migration.LegacyObjectAdoptionApproval", - "dev.caskeleton.application.storage.migration.LegacyObjectAdoptionApprovalVerifierPort", - "dev.caskeleton.application.storage.migration.LegacyObjectAdoptionPort", - "dev.caskeleton.application.storage.migration.LegacyObjectAdoptionReceipt", - "dev.caskeleton.application.storage.migration.LegacyObjectAdoptionRequest", - "dev.caskeleton.application.storage.migration.LegacyObjectLocator"); @Test void semanticContractIsFrameworkProviderTransportAndPersistentLocatorFree() throws Exception { @@ -106,16 +98,6 @@ class ObjectStorageArchitectureContractTest { assertThat(receipt.forRemoval()).isTrue(); } - @Test - void activeLegacyAdoptionMechanismIsDeprecatedWithoutRemovalIntent() throws Exception { - for (String typeName : ACTIVE_MIGRATION_TYPE_NAMES) { - Deprecated lifecycle = Class.forName(typeName).getAnnotation(Deprecated.class); - - assertThat(lifecycle).as(typeName).isNotNull(); - assertThat(lifecycle.forRemoval()).as(typeName).isFalse(); - } - } - private static void assertElementTypesArePure(Class owner, AnnotatedElement element) { for (Annotation annotation : element.getAnnotations()) { assertTypeNameIsPure(owner, annotation.annotationType().getName()); diff --git a/src/build-logic/README.md b/src/build-logic/README.md index 446c5b6e..b65e4e76 100644 --- a/src/build-logic/README.md +++ b/src/build-logic/README.md @@ -1,72 +1,50 @@ # build-logic -The included build that holds this repository's Gradle conventions. A convention lives here when the -same machine code was otherwise copied into more than one place, and the copies could drift apart -without any check noticing. +The included build that holds this repository's Gradle conventions: the architecture core, the +conventions every leaf applies, and one test-lane mechanism. A check that is about one capability +(notification, Mongo, messaging, GraphQL, JPA) is not here — it is a test in the leaf that owns the +capability, and the files it reads are declared as that test task's inputs. ## What is here | Plugin | Owns | | --- | --- | | `ca.architecture-registry` (settings) | project inclusion, directory mapping, and the parsed registry every other reader shares | -| `ca.java-conventions` | Java toolchain/compiler baseline and dependency locking shared by Java leaves | +| `ca.architecture` | `verifyCleanArchitectureDependencies` (per-module direction), `verifyApplicationCoreDependencyPurity` (domain-core, shared-contract, application-*), `verifyNoIgnoredSourcePackages`, `architectureCheck` | +| `ca.java-conventions` | Java toolchain/compiler baseline, dependency locking, the Mockito test agent, the per-leaf `mainCheck` lifecycle | | `ca.quality-conventions` | Spotless, Checkstyle, Error Prone, SpotBugs/FindSecBugs wiring shared by Java leaves | -| `ca.java-library` / `ca.spring-library` | leaf-level composition of the Java/quality conventions for plain and Spring libraries | -| `ca.strict-test-lane` | tagged / named / own-source-set Test lanes that cannot pass without executing something | -| `ca.strict-qualification` | qualification lanes that cannot pass without executing every named class, re-checked against the JUnit XML | -| `ca.evidence` | the JUnit XML reader and the no-skip / required-class rules built on it | -| `ca.api-surface` | read-only API surface verification with an explicit, separate update task | -| `ca.dependency-policy` | declared absences, checked against the resolved graph rather than against a comment | -| `ca.runtime-membership` | the resolved runtime project closure against the registry's memberships | -| `ca.platform-module` | what a vendored platform leaf (`messaging:*`, `grpc:*`, `grpc-advanced:*`) is: `java-library` | -| `ca.grpc-platform-module` | `ca.platform-module` plus the module-scope `io.grpc:grpc-bom` import, for the leaves that already had it | - -`ca.testkit-publisher` was here and is not any more: every leaf with a `testkit` source set moved to -Gradle's own `java-test-fixtures` (ADR-BUILD-001). +| `ca.java-library` / `ca.spring-library` / `ca.spring-config` | leaf-level composition of the Java/quality conventions for plain and Spring libraries | +| `ca.platform-module` / `ca.grpc-platform-module` | what a vendored platform leaf (`messaging:*`, `grpc:*`, `grpc-advanced:*`) is: `java-library`, plus the gRPC BOM for the leaves that had it | +| `ca.strict-test-lane` | the one "named tests ran, none skipped" mechanism: tagged / named / own-source-set `Test` lanes that fail when they execute nothing, miss a `requires` class, or (with `rejectSkipped`) skip anything | +| `ca.redis-topology-lane` | the Redis topology lane (mode selection, `-P` property validation, per-mode required classes) the redis-sdk-topology workflow drives | +| `ca.auxiliary-source-set` | extra test source sets | +| `ca.api-surface` | read-only public API surface verification with a separate update task, wired into `mainCheck` | +| `ca.public-path-snapshot`, `ca.archive-hygiene`, `ca.release-provenance` | the permitAll baseline, stale traceable jars, release version and revision | +| `ca.developer-bootstrap`, `ca.bootrun-dotenv` | the ordered local start-up and `bootRun`'s `.env` | Plain classes rather than plugins, because settings and projects load plugins through different mechanisms and more than one caller needs each: | Class | Owns | | --- | --- | -| `dev.caskeleton.buildlogic.ModuleRegistry` | reading and validating `config/architecture/modules.json`, including which runtime compositions exist | -| `dev.caskeleton.buildlogic.JUnitEvidence` | one JUnit XML reader, with DOCTYPE processing off and no defaulting of absent counts | -| `dev.caskeleton.buildlogic.RequiredTestExecution` | the single decision "a test this build names must actually have run", asked by `ca.strict-test-lane` and by `ca.evidence` | +| `dev.caskeleton.buildlogic.ModuleRegistry` | reading and validating `config/architecture/modules.json` | +| `dev.caskeleton.buildlogic.RequiredTestExecution` | the single decision "a test this build names must actually have run" | | `dev.caskeleton.buildlogic.JavaPublicTypes` | public top-level types, parsed by javac rather than matched with a regular expression | -## What the design named and this build does not have +JMH benchmarks use the community `me.champeau.jmh` plugin; `ca.quality-conventions` only turns +Error Prone, `-Werror`, SpotBugs and Checkstyle off for benchmark and generated code. -The remediation design's §10.2 listed eight conventions. Two of them were attempted or assessed and -deliberately not built, and the reasons belong next to the code rather than in a review thread. +## What was removed, and what covers it -### Historical `ca.java-leaf` experiment - -The original all-in-one `ca.java-leaf` experiment was reverted, but that is historical context, not -the current build shape. The responsibilities were subsequently split into the narrower -`ca.java-conventions` and `ca.quality-conventions` plugins listed above, and leaf plugins compose -those conventions. Dependency/tool versions still come from the shared catalog rather than being -hard-coded per leaf. - -A content-level baseline of the resolved analysis configuration — compiler args, encoding, release, -Checkstyle tool version and config, SpotBugs effort and report level, for every source set of every -project — was captured before the attempt and compared after the revert, because the task graph -cannot see a weakened Error Prone flag: the task names are identical either way. The two dumps are -identical. - -### `ca.optional-adapter` — not warranted - -Its stated responsibility was "activation metadata and disabled/on composition contract wiring". -Neither half is build machine code in this repository: - -- Activation metadata is one registry, `docs/registries/env-keys.yaml`, verified by one root task, - `verifyEnvKeys`. There is no per-leaf copy for a convention to deduplicate. -- The off invariant and the on fail-closed contract are ordinary tests over the shared `test` source - set, gated by the master switch in `@ConditionalOnProperty` at runtime. They need no source set, - no configuration, and no task of their own. - -A plugin here would have to invent state to hold — an `optionalAdapter { switch = '...' }` block that -no build step reads — and a declaration nothing checks is worse than no declaration, because it reads -like a guarantee. +| Removed | Covered by | +| --- | --- | +| `ca.runtime-membership` | the direction gate: nothing outside `allowed_dependencies` can reach a composition root | +| `ca.evidence`, `ca.conditional-transport-qualification`, `ca.strict-qualification` | `strictTestLanes` lanes with `requires` + `rejectSkipped`; the root `conditionalTransportQualification` and `verifyMessagingContracts` only aggregate them | +| `ca.dependency-policy` | a `componentSelection` rejection rule in the leaf (notification: YAML dataformat; messaging: Jackson 2 and any YAML module) and the registry (web-advanced has no allowed consumer). `rejectAll()` constraints were tried and do not fail: Spring's dependency management overrides the rejected version | +| `ca.graphql-platform` | the `graphqlStableTest` lane and `GraphQlProductionClassesTest` in the GraphQL leaf | +| `ca.jpa-test-lanes` | the lanes declared in `adapter/outbound/persistence-jpa/build.gradle` | +| `ca.test-jvm-agents`, `quarantineTest` | `ca.java-conventions`; the quarantine bucket had no tests | +| `ca.jmh-benchmarks` | `me.champeau.jmh` | ## Testing a convention diff --git a/src/build-logic/build.gradle b/src/build-logic/build.gradle index 75c6ab8a..de14f0fd 100644 --- a/src/build-logic/build.gradle +++ b/src/build-logic/build.gradle @@ -46,38 +46,10 @@ gradlePlugin { id = 'ca.api-surface' implementationClass = 'dev.caskeleton.buildlogic.apisurface.ApiSurfacePlugin' } - evidence { - id = 'ca.evidence' - implementationClass = 'dev.caskeleton.buildlogic.EvidencePlugin' - } - conditionalTransportQualification { - id = 'ca.conditional-transport-qualification' - implementationClass = 'dev.caskeleton.buildlogic.ConditionalTransportQualificationPlugin' - } - dependencyPolicy { - id = 'ca.dependency-policy' - implementationClass = 'dev.caskeleton.buildlogic.dependency.DependencyPolicyPlugin' - } - runtimeMembership { - id = 'ca.runtime-membership' - implementationClass = 'dev.caskeleton.buildlogic.runtime.RuntimeMembershipPlugin' - } architecture { id = 'ca.architecture' implementationClass = 'dev.caskeleton.buildlogic.architecture.ArchitecturePlugin' } - testJvmAgents { - id = 'ca.test-jvm-agents' - implementationClass = 'dev.caskeleton.buildlogic.testagent.TestJvmAgentsPlugin' - } - jmhBenchmarks { - id = 'ca.jmh-benchmarks' - implementationClass = 'dev.caskeleton.buildlogic.jmh.JmhBenchmarksPlugin' - } - graphqlPlatform { - id = 'ca.graphql-platform' - implementationClass = 'dev.caskeleton.buildlogic.graphql.GraphQlPlatformPlugin' - } javaConventions { id = 'ca.java-conventions' implementationClass = 'dev.caskeleton.buildlogic.java.JavaConventionsPlugin' @@ -102,14 +74,6 @@ gradlePlugin { id = 'ca.redis-topology-lane' implementationClass = 'dev.caskeleton.buildlogic.redis.RedisTopologyLanePlugin' } - jpaTestLanes { - id = 'ca.jpa-test-lanes' - implementationClass = 'dev.caskeleton.buildlogic.jpa.JpaTestLanesPlugin' - } - strictQualification { - id = 'ca.strict-qualification' - implementationClass = 'dev.caskeleton.buildlogic.strictqualification.StrictQualificationPlugin' - } architectureRegistrySettings { id = 'ca.architecture-registry' implementationClass = 'dev.caskeleton.buildlogic.settings.ArchitectureRegistrySettingsPlugin' diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/ConditionalTransportQualificationPlugin.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/ConditionalTransportQualificationPlugin.java deleted file mode 100644 index 67704f3d..00000000 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/ConditionalTransportQualificationPlugin.java +++ /dev/null @@ -1,91 +0,0 @@ -package dev.caskeleton.buildlogic; - -import java.util.List; -import org.gradle.api.GradleException; -import org.gradle.api.Plugin; -import org.gradle.api.Project; -import org.gradle.api.file.Directory; -import org.gradle.api.provider.Provider; - -public final class ConditionalTransportQualificationPlugin implements Plugin { - - @Override - public void apply(Project project) { - if (project != project.getRootProject()) { - throw new GradleException( - "ca.conditional-transport-qualification must be applied to the root project."); - } - project.getPluginManager().apply("ca.evidence"); - - List evidenceTargets = - List.of( - target( - project, - ":adapter:inbound:graphql", - "conditional-transport-graphql", - "graphqlTransportQualificationTest"), - target( - project, - ":adapter:inbound:grpc", - "conditional-transport-grpc", - "grpcTransportQualificationTest"), - target( - project, - ":adapter:inbound:websocket", - "conditional-transport-websocket", - "websocketTransportQualificationTest"), - target( - project, - ":app-bootstrap", - "conditional-transport-composition", - "conditionalTransportBuildContractTest")); - - project - .getTasks() - .register( - "conditionalTransportQualification", - task -> { - task.setGroup("verification"); - task.setDescription( - "Runs the exact no-skip GraphQL, gRPC, and WebSocket P1 qualification evidence."); - task.dependsOn( - ":adapter:inbound:graphql:graphqlTransportQualificationTest", - ":adapter:inbound:grpc:grpcTransportQualificationTest", - ":adapter:inbound:websocket:websocketTransportQualificationTest", - ":app-bootstrap:conditionalTransportBuildContractTest", - "verifyRuntimeModuleMembership"); - task.getInputs() - .files(evidenceTargets.stream().map(EvidenceTarget::directory).toList()); - task.doLast( - ignored -> { - EvidenceExtension evidence = - project.getExtensions().getByType(EvidenceExtension.class); - evidenceTargets.forEach( - target -> - evidence.verifyNoSkipJUnitXml( - target.name(), target.directory().get().getAsFile())); - }); - }); - } - - private static EvidenceTarget target( - Project root, String projectPath, String evidenceName, String resultDirectory) { - Provider directory = - root.project(projectPath) - .getLayout() - .getBuildDirectory() - .dir("test-results/" + resultDirectory); - return new EvidenceTarget(evidenceName, directory); - } - - private record EvidenceTarget(String name, Provider directory) { - private EvidenceTarget { - if (name == null || name.isBlank()) { - throw new IllegalArgumentException("evidence name is required"); - } - if (directory == null) { - throw new IllegalArgumentException("evidence directory is required"); - } - } - } -} diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/EvidenceExtension.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/EvidenceExtension.java deleted file mode 100644 index fe12f292..00000000 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/EvidenceExtension.java +++ /dev/null @@ -1,58 +0,0 @@ -package dev.caskeleton.buildlogic; - -import java.io.File; -import java.util.List; -import org.gradle.api.GradleException; -import org.gradle.api.logging.Logger; - -/** Typed JUnit evidence API shared by qualification conventions. */ -public class EvidenceExtension { - private final Logger logger; - - public EvidenceExtension(Logger logger) { - this.logger = logger; - } - - public JUnitEvidence.Results readJUnitEvidence(String evidenceName, File resultDirectory) { - try { - return JUnitEvidence.read(evidenceName, resultDirectory); - } catch (IllegalStateException unreadable) { - throw new GradleException(unreadable.getMessage(), unreadable); - } - } - - public JUnitEvidence.Results verifyNoSkipJUnitXml( - String evidenceName, File resultDirectory) { - JUnitEvidence.Results evidence = readJUnitEvidence(evidenceName, resultDirectory); - if (evidence.tests() <= 0) { - throw new GradleException(evidenceName + ": requires a positive executed test count"); - } - if (evidence.skipped() > 0) { - throw new GradleException( - evidenceName + ": forbids skipped tests: " + evidence.skipped()); - } - if (evidence.failures() > 0 || evidence.errors() > 0) { - throw new GradleException( - evidenceName - + ": failures=" - + evidence.failures() - + ", errors=" - + evidence.errors()); - } - logger.lifecycle( - "{}: {} tests, {} skipped", evidenceName, evidence.tests(), evidence.skipped()); - return evidence; - } - - public JUnitEvidence.Results verifyRequiredJUnitClasses( - String evidenceName, File resultDirectory, List requiredClasses) { - JUnitEvidence.Results evidence = verifyNoSkipJUnitXml(evidenceName, resultDirectory); - List missing = - RequiredTestExecution.absent(requiredClasses, evidence.executedClasses()); - if (!missing.isEmpty()) { - throw new GradleException( - evidenceName + ": no executed test cases for required classes: " + missing); - } - return evidence; - } -} diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/EvidencePlugin.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/EvidencePlugin.java deleted file mode 100644 index 499cc004..00000000 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/EvidencePlugin.java +++ /dev/null @@ -1,13 +0,0 @@ -package dev.caskeleton.buildlogic; - -import org.gradle.api.Plugin; -import org.gradle.api.Project; - -public final class EvidencePlugin implements Plugin { - @Override - public void apply(Project project) { - project - .getExtensions() - .create("evidence", EvidenceExtension.class, project.getLogger()); - } -} diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/JUnitEvidence.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/JUnitEvidence.java deleted file mode 100644 index 4ce14d78..00000000 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/JUnitEvidence.java +++ /dev/null @@ -1,128 +0,0 @@ -package dev.caskeleton.buildlogic; - -import java.io.File; -import java.io.IOException; -import java.io.UncheckedIOException; -import java.nio.file.Files; -import java.util.Comparator; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Set; -import java.util.TreeSet; -import javax.xml.XMLConstants; -import javax.xml.parsers.DocumentBuilderFactory; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.NodeList; - -/** JUnit XML result files, read once and fail-closed. */ -public final class JUnitEvidence { - private JUnitEvidence() {} - - public record Results( - int tests, - int skipped, - int failures, - int errors, - Set executedClasses, - Set executedSelectors, - List resultFiles) { - public Results { - executedClasses = Set.copyOf(executedClasses); - executedSelectors = Set.copyOf(executedSelectors); - resultFiles = List.copyOf(resultFiles); - } - - public boolean isClean() { - return tests > 0 && skipped == 0 && failures == 0 && errors == 0; - } - } - - public static Results read(String evidenceName, File resultDirectory) { - List resultFiles = resultFiles(resultDirectory); - if (resultFiles.isEmpty()) { - throw new IllegalStateException( - evidenceName + ": no JUnit XML result files in " + resultDirectory); - } - - int tests = 0; - int skipped = 0; - int failures = 0; - int errors = 0; - Set classes = new LinkedHashSet<>(); - Set selectors = new TreeSet<>(); - - for (File resultFile : resultFiles) { - Element suite = parseSuite(evidenceName, resultFile); - tests += attribute(suite, "tests", evidenceName, resultFile); - skipped += attribute(suite, "skipped", evidenceName, resultFile); - failures += attribute(suite, "failures", evidenceName, resultFile); - errors += attribute(suite, "errors", evidenceName, resultFile); - NodeList testCases = suite.getElementsByTagName("testcase"); - for (int index = 0; index < testCases.getLength(); index++) { - Element testCase = (Element) testCases.item(index); - String className = testCase.getAttribute("classname"); - boolean wasSkipped = testCase.getElementsByTagName("skipped").getLength() > 0; - if (!className.isBlank() && !wasSkipped) { - classes.add(className); - } - String methodName = testCase.getAttribute("name").replaceFirst("\\([^)]*\\)$", ""); - selectors.add(className + "#" + methodName); - } - } - return new Results(tests, skipped, failures, errors, classes, selectors, resultFiles); - } - - private static List resultFiles(File resultDirectory) { - if (resultDirectory == null || !resultDirectory.isDirectory()) { - return List.of(); - } - try (var paths = Files.walk(resultDirectory.toPath())) { - return paths - .filter(Files::isRegularFile) - .map(java.nio.file.Path::toFile) - .filter(file -> file.getName().startsWith("TEST-") && file.getName().endsWith(".xml")) - .sorted(Comparator.comparing(File::getPath)) - .toList(); - } catch (IOException exception) { - throw new UncheckedIOException("failed to inspect " + resultDirectory, exception); - } - } - - private static Element parseSuite(String evidenceName, File resultFile) { - try { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - factory.setNamespaceAware(false); - factory.setXIncludeAware(false); - factory.setExpandEntityReferences(false); - factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); - factory.setFeature("http://xml.org/sax/features/external-general-entities", false); - factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); - factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); - factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); - factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); - Document document = factory.newDocumentBuilder().parse(resultFile); - Element root = document.getDocumentElement(); - if (!root.getTagName().equals("testsuite")) { - throw new IllegalStateException( - evidenceName + ": " + resultFile.getName() + " root must be testsuite"); - } - return root; - } catch (IllegalStateException exception) { - throw exception; - } catch (Exception unreadable) { - throw new IllegalStateException( - evidenceName + ": " + resultFile + " is not readable JUnit XML", unreadable); - } - } - - private static int attribute( - Element suite, String name, String evidenceName, File resultFile) { - String raw = suite.hasAttribute(name) ? suite.getAttribute(name) : null; - if (raw == null || !raw.matches("\\d+")) { - throw new IllegalStateException( - evidenceName + ": " + resultFile.getName() + " has invalid " + name + "='" + raw + "'"); - } - return Integer.parseInt(raw); - } -} diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/ModuleRegistry.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/ModuleRegistry.java index 2e71f74f..ecea43c2 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/ModuleRegistry.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/ModuleRegistry.java @@ -17,15 +17,14 @@ import tools.jackson.databind.ObjectMapper; import tools.jackson.databind.json.JsonMapper; /** Typed representation of config/architecture/modules.json. */ -public record ModuleRegistry(List modules, List compositionRoots, File source) { +public record ModuleRegistry(List modules, File source) { private static final ObjectMapper JSON = JsonMapper.builder().build(); private static final Set REQUIRED_MODULE_FIELDS = Set.of("id", "gradle_path", "source_path", "allowed_dependencies"); - private static final Set REQUIRED_ROOT_FIELDS = Set.of("composition_roots", "modules"); + private static final Set REQUIRED_ROOT_FIELDS = Set.of("modules"); public ModuleRegistry { modules = List.copyOf(modules); - compositionRoots = List.copyOf(compositionRoots); Objects.requireNonNull(source, "source"); } @@ -72,17 +71,6 @@ public record ModuleRegistry(List modules, List compositionRoots throw new IllegalStateException("Module registry has no modules: " + registryFile); } - List compositionRoots = - requireStringList(root.get("composition_roots"), "", "composition_roots"); - if (compositionRoots.isEmpty()) { - throw new IllegalStateException( - "Module registry needs a nonempty 'composition_roots' list: " + registryFile); - } - if (new HashSet<>(compositionRoots).size() != compositionRoots.size()) { - throw new IllegalStateException( - "Module registry contains duplicate composition_roots: " + registryFile); - } - File canonicalRoot; try { canonicalRoot = repositoryRoot.getCanonicalFile(); @@ -187,14 +175,7 @@ public record ModuleRegistry(List modules, List compositionRoots allowedDependencies)); } - Set moduleIds = modules.stream().map(Module::id).collect(java.util.stream.Collectors.toSet()); - Set unknownRoots = new TreeSet<>(compositionRoots); - unknownRoots.removeAll(moduleIds); - if (!unknownRoots.isEmpty()) { - throw new IllegalStateException( - "Module registry composition_roots reference unknown module ids " + unknownRoots + "."); - } - return new ModuleRegistry(modules, compositionRoots, registryFile); + return new ModuleRegistry(modules, registryFile); } public Module byId(String id) { diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/apisurface/ApiSurfacePlugin.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/apisurface/ApiSurfacePlugin.java index 20070cdd..f36cb7b8 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/apisurface/ApiSurfacePlugin.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/apisurface/ApiSurfacePlugin.java @@ -7,7 +7,6 @@ import java.util.List; import org.gradle.api.GradleException; import org.gradle.api.Plugin; import org.gradle.api.Project; -import org.gradle.language.base.plugins.LifecycleBasePlugin; public final class ApiSurfacePlugin implements Plugin { @Override @@ -94,10 +93,12 @@ public final class ApiSurfacePlugin implements Plugin { task.getCeilingRaiseApproved().set(ceilingApproved); }); + // Main-branch stage (mainCheck), not the pull-request `check`; the verify task runs on its own + // for anyone changing a public type. project .getTasks() - .named(LifecycleBasePlugin.CHECK_TASK_NAME) - .configure(task -> task.dependsOn(verify)); + .matching(task -> task.getName().equals("mainCheck")) + .configureEach(task -> task.dependsOn(verify)); }); } } diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/architecture/ArchitecturePlugin.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/architecture/ArchitecturePlugin.java index 1f7de28e..2b6ab50c 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/architecture/ArchitecturePlugin.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/architecture/ArchitecturePlugin.java @@ -63,8 +63,8 @@ public final class ArchitecturePlugin implements Plugin { task -> { task.setGroup("verification"); task.setDescription( - "Verifies all application-* modules have only project production dependencies" - + " and no diagnostic frameworks on application classpaths."); + "Verifies domain-core, shared-contract and every application-* module have only" + + " project production dependencies and no framework on their classpaths."); }); var ignoredSources = project @@ -140,11 +140,13 @@ public final class ArchitecturePlugin implements Plugin { task.dependsOn(moduleTaskPaths); }); - // Same ownership rule as the direction check: the task that resolves an - // application module's classpaths lives in that module. + // Same ownership rule as the direction check: the task that resolves a pure + // module's classpaths lives in that module. domain-core and shared-contract are pure + // too (HS1): without them a framework dependency added there passed the build and + // was caught only if some class happened to import it. List purityTaskPaths = new ArrayList<>(); for (ModuleRegistry.Module module : modules) { - if (!module.id().startsWith("application-")) { + if (!isPure(module.id())) { continue; } Project application = root.project(module.gradlePath()); @@ -203,28 +205,23 @@ public final class ArchitecturePlugin implements Plugin { ignoredSources.configure(task -> task.getSourceRoots().from(sourceRoots)); }); - var architectureCheck = - project - .getTasks() - .register( - "architectureCheck", - task -> { - task.setGroup("verification"); - task.setDescription("Runs the build's architecture invariants."); - task.dependsOn(clean, purity, ignoredSources); - }); project - .getGradle() - .projectsEvaluated( - ignored -> { - if (project.getTasks().findByName("verifyRuntimeModuleMembership") != null) { - architectureCheck.configure( - task -> - task.dependsOn(project.getTasks().named("verifyRuntimeModuleMembership"))); - } + .getTasks() + .register( + "architectureCheck", + task -> { + task.setGroup("verification"); + task.setDescription("Runs the build's architecture invariants."); + task.dependsOn(clean, purity, ignoredSources); }); } + private static boolean isPure(String moduleId) { + return moduleId.startsWith("application-") + || moduleId.equals("domain-core") + || moduleId.equals("shared-contract"); + } + /** * This module's declared {@code project(...)} edges, read while the owning project is configured. * diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/bootstrap/DeveloperBootstrapPlugin.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/bootstrap/DeveloperBootstrapPlugin.java index 71f01fa5..98ba852c 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/bootstrap/DeveloperBootstrapPlugin.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/bootstrap/DeveloperBootstrapPlugin.java @@ -37,18 +37,10 @@ public final class DeveloperBootstrapPlugin implements Plugin { if ("null".equals(profile)) { profile = DEFAULT_PROFILE; } + // The overlay is checked when a bootstrap task runs, not here: the Docker image build copies only + // src/ into its context, where no compose file exists, and a check at configuration time would + // stop every task in that build — not only the bootstrap ones. File overlay = new File(repositoryDirectory, "docker-compose." + profile + ".yml"); - if (!overlay.isFile()) { - throw new GradleException( - "bootstrap: -P" - + PROFILE_PROPERTY - + "=" - + profile - + " names no overlay; expected " - + overlay.getName() - + " beside docker-compose.yml. Available: " - + availableProfiles(repositoryDirectory)); - } File baseComposeFile = new File(repositoryDirectory, "docker-compose.yml"); List composeCommand = List.of( @@ -84,6 +76,8 @@ public final class DeveloperBootstrapPlugin implements Plugin { task.setGroup(GROUP); task.setDescription("Checks that the Docker CLI can reach a running Docker daemon."); task.dependsOn(compile); + task.doFirst( + ignored -> requireOverlay(overlay, bootstrapProfile, repositoryDirectory)); task.commandLine("docker", "info"); task.setIgnoreExitValue(true); task.setStandardOutput(dockerInfoOutput); @@ -161,6 +155,20 @@ public final class DeveloperBootstrapPlugin implements Plugin { }); } + private static void requireOverlay(File overlay, String profile, File repositoryDirectory) { + if (!overlay.isFile()) { + throw new GradleException( + "bootstrap: -P" + + PROFILE_PROPERTY + + "=" + + profile + + " names no overlay; expected " + + overlay.getName() + + " beside docker-compose.yml. Available: " + + availableProfiles(repositoryDirectory)); + } + } + /** The overlay names that exist beside the base compose file, for the failure message. */ private static List availableProfiles(File repositoryDirectory) { File[] files = repositoryDirectory.listFiles(); diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/dependency/DependencyAbsence.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/dependency/DependencyAbsence.java deleted file mode 100644 index eea30fda..00000000 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/dependency/DependencyAbsence.java +++ /dev/null @@ -1,24 +0,0 @@ -package dev.caskeleton.buildlogic.dependency; - -import java.util.Objects; - -public record DependencyAbsence(String coordinate, String reason, String configuration) { - public DependencyAbsence { - Objects.requireNonNull(coordinate, "coordinate"); - Objects.requireNonNull(reason, "reason"); - Objects.requireNonNull(configuration, "configuration"); - if (coordinate.chars().filter(ch -> ch == ':').count() != 1) { - throw new IllegalArgumentException( - "dependencyPolicy.absent('" + coordinate + "') must be group:module without a version"); - } - if (reason.isBlank()) { - throw new IllegalArgumentException( - "dependencyPolicy.absent('" - + coordinate - + "') needs a reason: an unexplained exclusion is the comment drift this check exists to prevent"); - } - if (configuration.isBlank()) { - throw new IllegalArgumentException("dependency policy configuration must not be blank"); - } - } -} diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/dependency/DependencyAbsencePattern.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/dependency/DependencyAbsencePattern.java deleted file mode 100644 index 05696954..00000000 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/dependency/DependencyAbsencePattern.java +++ /dev/null @@ -1,26 +0,0 @@ -package dev.caskeleton.buildlogic.dependency; - -import java.util.Objects; -import java.util.regex.Pattern; -import java.util.regex.PatternSyntaxException; - -public record DependencyAbsencePattern(String regex, String reason, String configuration) { - public DependencyAbsencePattern { - Objects.requireNonNull(regex, "regex"); - Objects.requireNonNull(reason, "reason"); - Objects.requireNonNull(configuration, "configuration"); - try { - Pattern.compile(regex); - } catch (PatternSyntaxException invalid) { - throw new IllegalArgumentException( - "dependencyPolicy.absentMatching('" + regex + "') is not a valid regex", invalid); - } - if (reason.isBlank()) { - throw new IllegalArgumentException( - "dependencyPolicy.absentMatching('" + regex + "') needs a reason"); - } - if (configuration.isBlank()) { - throw new IllegalArgumentException("dependency policy configuration must not be blank"); - } - } -} diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/dependency/DependencyPolicyCheck.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/dependency/DependencyPolicyCheck.java deleted file mode 100644 index 04151aee..00000000 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/dependency/DependencyPolicyCheck.java +++ /dev/null @@ -1,28 +0,0 @@ -package dev.caskeleton.buildlogic.dependency; - -import java.util.List; -import java.util.Objects; - -/** - * One configuration's declared policy, as data. - * - *

It used to carry the {@link org.gradle.api.artifacts.Configuration} itself, so the task - * resolved the graph in its own action. The configuration cache cannot store a {@code - * Configuration}, and the resolved root component the task is handed instead is the same graph - * established while the declaring project is still configuring. - * - *

Public because the configuration cache reconstructs a record through its canonical - * constructor, and a package-private record has a package-private one. - */ -public record DependencyPolicyCheck( - String configurationName, - List absences, - List absencePatterns, - List presences) { - public DependencyPolicyCheck { - Objects.requireNonNull(configurationName, "configurationName"); - absences = List.copyOf(absences); - absencePatterns = List.copyOf(absencePatterns); - presences = List.copyOf(presences); - } -} diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/dependency/DependencyPolicyExtension.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/dependency/DependencyPolicyExtension.java deleted file mode 100644 index d1dfbea0..00000000 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/dependency/DependencyPolicyExtension.java +++ /dev/null @@ -1,77 +0,0 @@ -package dev.caskeleton.buildlogic.dependency; - -import java.util.ArrayList; -import java.util.List; -import org.gradle.api.GradleException; -import org.gradle.api.artifacts.MinimalExternalModuleDependency; -import org.gradle.api.provider.Provider; - -public class DependencyPolicyExtension { - private final List absences = new ArrayList<>(); - private final List absencePatterns = new ArrayList<>(); - private final List presences = new ArrayList<>(); - - public void absent(String coordinate, String reason) { - absentOn("runtimeClasspath", coordinate, reason); - } - - public void absentOn(String configuration, String coordinate, String reason) { - try { - absences.add(new DependencyAbsence(coordinate, reason, configuration)); - } catch (IllegalArgumentException invalid) { - throw new GradleException(invalid.getMessage(), invalid); - } - } - - public void absentMatching(String regex, String reason) { - absentMatchingOn("runtimeClasspath", regex, reason); - } - - public void absentMatchingOn(String configuration, String regex, String reason) { - try { - absencePatterns.add(new DependencyAbsencePattern(regex, reason, configuration)); - } catch (IllegalArgumentException invalid) { - throw new GradleException(invalid.getMessage(), invalid); - } - } - - public void required(String coordinate, String reason) { - requiredOn("runtimeClasspath", coordinate, reason); - } - - public void required(Provider dependency, String reason) { - required(moduleCoordinate(dependency), reason); - } - - public void requiredOn(String configuration, String coordinate, String reason) { - try { - presences.add(new DependencyPresence(coordinate, reason, configuration)); - } catch (IllegalArgumentException invalid) { - throw new GradleException(invalid.getMessage(), invalid); - } - } - - public void requiredOn( - String configuration, - Provider dependency, - String reason) { - requiredOn(configuration, moduleCoordinate(dependency), reason); - } - - public List getDeclarations() { - return List.copyOf(absences); - } - - public List getAbsencePatterns() { - return List.copyOf(absencePatterns); - } - - public List getPresences() { - return List.copyOf(presences); - } - - private static String moduleCoordinate(Provider dependency) { - var module = dependency.get().getModule(); - return module.getGroup() + ":" + module.getName(); - } -} diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/dependency/DependencyPolicyPlugin.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/dependency/DependencyPolicyPlugin.java deleted file mode 100644 index bc2de934..00000000 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/dependency/DependencyPolicyPlugin.java +++ /dev/null @@ -1,97 +0,0 @@ -package dev.caskeleton.buildlogic.dependency; - -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import org.gradle.api.GradleException; -import org.gradle.api.Plugin; -import org.gradle.api.Project; -import org.gradle.api.artifacts.Configuration; -import org.gradle.api.artifacts.result.ResolvedComponentResult; -import org.gradle.api.provider.Provider; -import org.gradle.language.base.plugins.LifecycleBasePlugin; - -public final class DependencyPolicyPlugin implements Plugin { - @Override - public void apply(Project project) { - DependencyPolicyExtension extension = - project.getExtensions().create("dependencyPolicy", DependencyPolicyExtension.class); - var verify = - project - .getTasks() - .register( - "verifyDependencyPolicy", - VerifyDependencyPolicyTask.class, - task -> { - task.setGroup("verification"); - task.setDescription( - "Verifies required and forbidden coordinates on declared dependency graphs."); - task.getOutputs().upToDateWhen(ignored -> false); - }); - - project.afterEvaluate( - ignored -> { - List absences = extension.getDeclarations(); - List patterns = extension.getAbsencePatterns(); - List presences = extension.getPresences(); - if (absences.isEmpty() && patterns.isEmpty() && presences.isEmpty()) { - return; - } - Set names = new LinkedHashSet<>(); - absences.forEach(declaration -> names.add(declaration.configuration())); - patterns.forEach(declaration -> names.add(declaration.configuration())); - presences.forEach(declaration -> names.add(declaration.configuration())); - List checks = new ArrayList<>(); - Map> roots = new LinkedHashMap<>(); - for (String name : names) { - Configuration configuration = project.getConfigurations().findByName(name); - if (configuration == null) { - throw new GradleException( - project.getPath() - + " declares a dependency policy for configuration '" - + name - + "', which does not exist"); - } - if (!configuration.isCanBeResolved()) { - throw new GradleException( - project.getPath() - + " declares a dependency policy for '" - + name - + "', which cannot be resolved"); - } - roots.put( - name, configuration.getIncoming().getResolutionResult().getRootComponent()); - checks.add( - new DependencyPolicyCheck( - name, - forConfiguration(absences, name), - patterns.stream() - .filter(declaration -> declaration.configuration().equals(name)) - .toList(), - presences.stream() - .filter(declaration -> declaration.configuration().equals(name)) - .toList())); - } - verify.configure( - task -> { - task.setOwnerPath(project.getPath()); - task.setChecks(checks); - roots.forEach((name, root) -> task.getResolvedRoots().put(name, root)); - }); - project - .getTasks() - .named(LifecycleBasePlugin.CHECK_TASK_NAME) - .configure(task -> task.dependsOn(verify)); - }); - } - - private static List forConfiguration( - List declarations, String configuration) { - return declarations.stream() - .filter(declaration -> declaration.configuration().equals(configuration)) - .toList(); - } -} diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/dependency/DependencyPresence.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/dependency/DependencyPresence.java deleted file mode 100644 index 8338379e..00000000 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/dependency/DependencyPresence.java +++ /dev/null @@ -1,22 +0,0 @@ -package dev.caskeleton.buildlogic.dependency; - -import java.util.Objects; - -public record DependencyPresence(String coordinate, String reason, String configuration) { - public DependencyPresence { - Objects.requireNonNull(coordinate, "coordinate"); - Objects.requireNonNull(reason, "reason"); - Objects.requireNonNull(configuration, "configuration"); - if (coordinate.chars().filter(ch -> ch == ':').count() != 1) { - throw new IllegalArgumentException( - "dependencyPolicy.required('" + coordinate + "') must be group:module without a version"); - } - if (reason.isBlank()) { - throw new IllegalArgumentException( - "dependencyPolicy.required('" + coordinate + "') needs a reason"); - } - if (configuration.isBlank()) { - throw new IllegalArgumentException("dependency policy configuration must not be blank"); - } - } -} diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/dependency/VerifyDependencyPolicyTask.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/dependency/VerifyDependencyPolicyTask.java deleted file mode 100644 index 2dcf3265..00000000 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/dependency/VerifyDependencyPolicyTask.java +++ /dev/null @@ -1,126 +0,0 @@ -package dev.caskeleton.buildlogic.dependency; - -import dev.caskeleton.buildlogic.ResolvedComponents; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.regex.Pattern; -import org.gradle.api.DefaultTask; -import org.gradle.api.GradleException; -import org.gradle.api.artifacts.ModuleVersionIdentifier; -import org.gradle.api.artifacts.result.ResolvedComponentResult; -import org.gradle.api.provider.MapProperty; -import org.gradle.api.tasks.Internal; -import org.gradle.api.tasks.TaskAction; -import org.gradle.work.DisableCachingByDefault; - -@DisableCachingByDefault(because = "Verification depends on the live resolved dependency graph") -public abstract class VerifyDependencyPolicyTask extends DefaultTask { - private List checks = List.of(); - private String ownerPath = ":"; - - @Internal - List getChecks() { - return checks; - } - - void setChecks(List checks) { - this.checks = List.copyOf(checks); - } - - @Internal - String getOwnerPath() { - return ownerPath; - } - - void setOwnerPath(String ownerPath) { - this.ownerPath = ownerPath; - } - - /** Resolved root component per declared configuration name. */ - @Internal - public abstract MapProperty getResolvedRoots(); - - @TaskAction - public void verifyPolicy() { - List violations = new ArrayList<>(); - Map roots = getResolvedRoots().get(); - for (DependencyPolicyCheck check : checks) { - Set resolved = resolvedModules(roots.get(check.configurationName())); - verifyExactAbsences(check, resolved, violations); - verifyPatternAbsences(check, resolved, violations); - verifyPresences(check, resolved, violations); - } - if (!violations.isEmpty()) { - throw new GradleException( - ownerPath - + ": the dependency graph contradicts what this leaf declares.\n" - + String.join("\n", violations) - + "\nFix the graph or update the declaration with an explicit reason."); - } - } - - private static Set resolvedModules(ResolvedComponentResult root) { - Set resolved = new HashSet<>(); - for (ResolvedComponentResult component : ResolvedComponents.reachableFrom(root)) { - ModuleVersionIdentifier version = component.getModuleVersion(); - if (version != null) { - resolved.add(version.getGroup() + ":" + version.getName()); - } - } - return resolved; - } - - private static void verifyExactAbsences( - DependencyPolicyCheck check, Set resolved, List violations) { - for (DependencyAbsence absence : check.absences()) { - if (resolved.contains(absence.coordinate())) { - violations.add( - " " - + absence.coordinate() - + " is on " - + check.configurationName() - + " — the leaf states: " - + absence.reason()); - } - } - } - - private static void verifyPatternAbsences( - DependencyPolicyCheck check, Set resolved, List violations) { - for (DependencyAbsencePattern absence : check.absencePatterns()) { - Pattern pattern = Pattern.compile(absence.regex()); - resolved.stream() - .filter(coordinate -> pattern.matcher(coordinate).matches()) - .sorted() - .forEach( - coordinate -> - violations.add( - " " - + coordinate - + " matches forbidden pattern '" - + absence.regex() - + "' on " - + check.configurationName() - + " — the leaf states: " - + absence.reason())); - } - } - - private static void verifyPresences( - DependencyPolicyCheck check, Set resolved, List violations) { - for (DependencyPresence presence : check.presences()) { - if (!resolved.contains(presence.coordinate())) { - violations.add( - " required " - + presence.coordinate() - + " is missing from " - + check.configurationName() - + " — the leaf states: " - + presence.reason()); - } - } - } -} diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/graphql/ForbiddenJarMarker.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/graphql/ForbiddenJarMarker.java deleted file mode 100644 index a8032b22..00000000 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/graphql/ForbiddenJarMarker.java +++ /dev/null @@ -1,10 +0,0 @@ -package dev.caskeleton.buildlogic.graphql; - -import java.util.Objects; - -record ForbiddenJarMarker(String marker, String reason) { - ForbiddenJarMarker { - Objects.requireNonNull(marker, "marker"); - Objects.requireNonNull(reason, "reason"); - } -} diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/graphql/GraphQlPlatformPlugin.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/graphql/GraphQlPlatformPlugin.java deleted file mode 100644 index c42efef1..00000000 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/graphql/GraphQlPlatformPlugin.java +++ /dev/null @@ -1,122 +0,0 @@ -package dev.caskeleton.buildlogic.graphql; - -import dev.caskeleton.buildlogic.EvidenceExtension; -import dev.caskeleton.buildlogic.JUnitEvidence; -import java.io.File; -import java.util.List; -import java.util.Set; -import org.gradle.api.GradleException; -import org.gradle.api.Plugin; -import org.gradle.api.Project; -import org.gradle.api.plugins.JavaPluginExtension; -import org.gradle.api.tasks.SourceSet; -import org.gradle.api.tasks.bundling.Jar; -import org.gradle.api.tasks.testing.Test; -import org.gradle.language.base.plugins.LifecycleBasePlugin; - -public final class GraphQlPlatformPlugin implements Plugin { - private static final String PACKAGE = "dev.caskeleton.adapter.inbound.graphql"; - private static final List REQUIRED_STABLE_CLASSES = - List.of(PACKAGE + ".moduleboundary.GraphQlModuleBoundaryTest"); - - @Override - public void apply(Project project) { - project.getPluginManager().withPlugin("java", ignored -> configure(project)); - } - - private static void configure(Project project) { - EvidenceExtension evidence = - project.getRootProject().getExtensions().findByType(EvidenceExtension.class); - if (evidence == null) { - throw new GradleException("ca.graphql-platform requires ca.evidence on the root project."); - } - SourceSet testSource = - project - .getExtensions() - .getByType(JavaPluginExtension.class) - .getSourceSets() - .getByName(SourceSet.TEST_SOURCE_SET_NAME); - - project - .getTasks() - .register( - "graphqlStableTest", - Test.class, - test -> { - test.setDescription( - "Runs the Stable GraphQL platform test lane (Stable plan Task 1-48)."); - test.setGroup("verification"); - test.setTestClassesDirs(testSource.getOutput().getClassesDirs()); - test.setClasspath(testSource.getRuntimeClasspath()); - test.jvmArgs("-Duser.timezone=UTC"); - test.getOutputs().upToDateWhen(ignored -> false); - test.useJUnitPlatform(options -> options.excludeTags("quarantine", "graphql-advanced")); - test.filter( - filter -> { - filter.includeTestsMatching(PACKAGE + ".*"); - filter.setFailOnNoMatchingTests(true); - }); - test.getFilter().setFailOnNoMatchingTests(true); - test.getReports().getJunitXml().getRequired().set(true); - test.getReports() - .getJunitXml() - .getOutputLocation() - .set(project.getLayout().getBuildDirectory().dir("test-results/graphqlStableTest")); - test.doFirst( - ignored -> { - File stale = - test.getReports().getJunitXml().getOutputLocation().get().getAsFile(); - if (stale.exists()) { - project.delete(stale); - if (stale.exists()) { - throw new GradleException( - "graphqlStableTest could not delete stale JUnit XML: " + stale); - } - } - }); - test.doLast( - ignored -> { - JUnitEvidence.Results result = - evidence.readJUnitEvidence( - "graphqlStableTest", - test.getReports().getJunitXml().getOutputLocation().get().getAsFile()); - Set executed = result.executedClasses(); - List missing = - REQUIRED_STABLE_CLASSES.stream() - .filter( - required -> - executed.stream() - .noneMatch( - actual -> - actual.equals(required) - || actual.startsWith(required + "$"))) - .toList(); - if (!missing.isEmpty()) { - throw new GradleException( - "graphqlStableTest executed no test case for required boundary class(es): " - + missing - + ". The lane is green only because the class is gone; restore it rather than removing it from requiredStableClasses."); - } - }); - }); - - var jar = project.getTasks().named("jar", Jar.class); - var verifyJar = - project - .getTasks() - .register( - "verifyGraphQlProductionJar", - VerifyGraphQlProductionJarTask.class, - task -> { - task.setGroup("verification"); - task.setDescription( - "Fails when the GraphQL production jar contains testkit, fixture or in-memory-only types."); - task.dependsOn(jar); - task.getJarFile().set(jar.flatMap(Jar::getArchiveFile)); - }); - project - .getTasks() - .named(LifecycleBasePlugin.CHECK_TASK_NAME) - .configure(task -> task.dependsOn(verifyJar)); - } -} diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/graphql/VerifyGraphQlProductionJarTask.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/graphql/VerifyGraphQlProductionJarTask.java deleted file mode 100644 index 53bc26ff..00000000 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/graphql/VerifyGraphQlProductionJarTask.java +++ /dev/null @@ -1,56 +0,0 @@ -package dev.caskeleton.buildlogic.graphql; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.zip.ZipFile; -import org.gradle.api.DefaultTask; -import org.gradle.api.GradleException; -import org.gradle.api.file.RegularFileProperty; -import org.gradle.api.tasks.InputFile; -import org.gradle.api.tasks.TaskAction; -import org.gradle.work.DisableCachingByDefault; - -@DisableCachingByDefault(because = "Artifact contract verification emits no reusable output") -public abstract class VerifyGraphQlProductionJarTask extends DefaultTask { - private static final List FORBIDDEN = - List.of( - new ForbiddenJarMarker("/testkit/", "contract suites and integration fixtures belong to test fixtures"), - new ForbiddenJarMarker("InMemory", "an in-memory implementation is a development stand-in, not a shipped default"), - new ForbiddenJarMarker("ForTests", "a for-tests factory in the production jar is reachable from production code"), - new ForbiddenJarMarker("TestContext", "a credential-free authenticated context must not ship"), - new ForbiddenJarMarker("Fixture", "fixtures belong to test fixtures")); - - @InputFile - public abstract RegularFileProperty getJarFile(); - - @TaskAction - public void verifyJar() { - File jar = getJarFile().get().getAsFile(); - List violations = new ArrayList<>(); - try (ZipFile archive = new ZipFile(jar)) { - var entries = archive.entries(); - while (entries.hasMoreElements()) { - var entry = entries.nextElement(); - if (entry.isDirectory() || !entry.getName().endsWith(".class")) { - continue; - } - for (ForbiddenJarMarker forbidden : FORBIDDEN) { - if (entry.getName().contains(forbidden.marker())) { - violations.add(entry.getName() + ": " + forbidden.reason()); - } - } - } - } catch (IOException exception) { - throw new GradleException("Could not inspect GraphQL production jar " + jar, exception); - } - if (!violations.isEmpty()) { - violations.sort(String::compareTo); - throw new GradleException( - "The GraphQL production jar contains non-production types:\n " - + String.join("\n ", violations) - + "\nMove them to src/testFixtures/java, or declare them with testFixturesImplementation."); - } - } -} diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/java/JavaConventionsPlugin.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/java/JavaConventionsPlugin.java index a309ce34..6f13ce77 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/java/JavaConventionsPlugin.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/java/JavaConventionsPlugin.java @@ -10,7 +10,6 @@ import org.gradle.api.artifacts.Configuration; import org.gradle.api.artifacts.VersionCatalogsExtension; import org.gradle.api.artifacts.dsl.LockMode; import org.gradle.api.plugins.JavaPluginExtension; -import org.gradle.api.tasks.SourceSet; import org.gradle.api.tasks.bundling.AbstractArchiveTask; import org.gradle.api.tasks.bundling.Jar; import org.gradle.api.tasks.compile.JavaCompile; @@ -25,18 +24,10 @@ public final class JavaConventionsPlugin implements Plugin { public void apply(Project project) { project.getPluginManager().apply("java"); project.getPluginManager().apply("io.spring.dependency-management"); - // Two, not five. `ca.strict-test-lane` supplies the per-leaf `*TestLaneCheck` aggregates that the - // root's repository-wide tasks depend on by path, so every Java leaf has to have them or the - // root task graph cannot be built; `ca.test-jvm-agents` attaches the Mockito startup agent to - // every `Test` task, and a leaf that quietly lost it would self-attach instead. - // - // The other three governed nothing here. `ca.api-surface` is configured by three leaves, - // `ca.dependency-policy` by two and `ca.strict-qualification` by nine, and applying them to - // every Java leaf put an extension on all of them and a `verifyDependencyPolicy` task that - // checks an empty policy on all of them. A leaf that wants one now says so, which is also the - // only way to read a build file and learn which governance applies to it. + // `ca.strict-test-lane` supplies the per-leaf `*TestLaneCheck` aggregates that the root's + // repository-wide tasks depend on by path, so every Java leaf has to have them or the root task + // graph cannot be built. `ca.api-surface` is opt-in: a leaf that wants it says so. project.getPluginManager().apply("ca.strict-test-lane"); - project.getPluginManager().apply("ca.test-jvm-agents"); var catalog = project.getExtensions().getByType(VersionCatalogsExtension.class).named("libs"); String springBootVersion = catalog.findVersion("springBoot").orElseThrow().getRequiredVersion(); @@ -101,6 +92,19 @@ public final class JavaConventionsPlugin implements Plugin { .getDependencies() .add("testRuntimeOnly", "org.junit.platform:junit-platform-launcher"); + project.getTasks().named("test", Test.class).configure(Test::useJUnitPlatform); + + // The main-branch stage of this leaf (the root `mainCheck` aggregates every leaf's). Empty unless + // a convention or the leaf attaches a gate that is not worth a pull request's wait. + project + .getTasks() + .register( + "mainCheck", + task -> { + task.setGroup("verification"); + task.setDescription("Runs this leaf's main-branch-stage gates."); + }); + boolean writeLocksRequested = project.getGradle().getStartParameter().isWriteDependencyLocks(); var resolveAndLockAll = project @@ -140,28 +144,31 @@ public final class JavaConventionsPlugin implements Plugin { verifyDependencyLocks.configure(task -> task.setConfigurationsToResolve(resolvable)); }); - SourceSet testSource = javaExtension.getSourceSets().getByName(SourceSet.TEST_SOURCE_SET_NAME); + // The Mockito agent on every Test JVM, attached at startup rather than self-attached. The agent + // is the mockito-core jar alone, hence non-transitive. + Configuration agentDependencies = + project.getConfigurations().dependencyScope("mockitoAgentDependencies").get(); + Configuration agent = + project + .getConfigurations() + .resolvable( + "mockitoAgent", + configuration -> { + configuration.extendsFrom(agentDependencies); + configuration.setTransitive(false); + }) + .get(); + project.getDependencies().add(agentDependencies.getName(), "org.mockito:mockito-core"); project .getTasks() - .named("test", Test.class) - .configure( - test -> test.useJUnitPlatform(options -> options.excludeTags("quarantine"))); - project - .getTasks() - .register( - "quarantineTest", - Test.class, + .withType(Test.class) + .configureEach( test -> { - test.setGroup("verification"); - test.setDescription( - "Flaky-test quarantine bucket: runs only @Tag(\"quarantine\") tests, non-blocking."); - test.setTestClassesDirs(testSource.getOutput().getClassesDirs()); - test.setClasspath(testSource.getRuntimeClasspath()); - test.useJUnitPlatform(options -> options.includeTags("quarantine")); - test.setIgnoreFailures(true); - test.getFailOnNoDiscoveredTests().set(false); - test.getOutputs().upToDateWhen(ignored -> false); - test.jvmArgs("-Duser.timezone=UTC"); + MockitoAgentArgumentProvider provider = + project.getObjects().newInstance(MockitoAgentArgumentProvider.class); + provider.getMockitoCoreClasspath().from(agent); + provider.getOwner().set(project.getPath() + ":" + test.getName()); + test.getJvmArgumentProviders().add(provider); }); } } diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/testagent/MockitoAgentArgumentProvider.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/java/MockitoAgentArgumentProvider.java similarity index 96% rename from src/build-logic/src/main/java/dev/caskeleton/buildlogic/testagent/MockitoAgentArgumentProvider.java rename to src/build-logic/src/main/java/dev/caskeleton/buildlogic/java/MockitoAgentArgumentProvider.java index e8db0f4c..9ba5bf9f 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/testagent/MockitoAgentArgumentProvider.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/java/MockitoAgentArgumentProvider.java @@ -1,4 +1,4 @@ -package dev.caskeleton.buildlogic.testagent; +package dev.caskeleton.buildlogic.java; import java.io.File; import java.util.Comparator; diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/jmh/JmhBenchmarksExtension.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/jmh/JmhBenchmarksExtension.java deleted file mode 100644 index 39008373..00000000 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/jmh/JmhBenchmarksExtension.java +++ /dev/null @@ -1,27 +0,0 @@ -package dev.caskeleton.buildlogic.jmh; - -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; - -public class JmhBenchmarksExtension { - private final List visibleOutputs = new ArrayList<>(List.of("main", "test")); - private String jsonReport; - - public void compilesAgainst(String... sourceSetNames) { - visibleOutputs.clear(); - visibleOutputs.addAll(List.of(sourceSetNames)); - } - - public void jsonReport(String relativePath) { - jsonReport = Objects.requireNonNull(relativePath, "relativePath"); - } - - List visibleOutputs() { - return List.copyOf(visibleOutputs); - } - - String jsonReport() { - return jsonReport; - } -} diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/jmh/JmhBenchmarksPlugin.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/jmh/JmhBenchmarksPlugin.java deleted file mode 100644 index e855cc50..00000000 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/jmh/JmhBenchmarksPlugin.java +++ /dev/null @@ -1,139 +0,0 @@ -package dev.caskeleton.buildlogic.jmh; - -import java.util.List; -import net.ltgt.gradle.errorprone.ErrorProneOptions; -import net.ltgt.gradle.errorprone.ErrorProneOptionsKt; -import org.gradle.api.GradleException; -import org.gradle.api.Plugin; -import org.gradle.api.Project; -import org.gradle.api.artifacts.VersionCatalogsExtension; -import org.gradle.api.file.FileCollection; -import org.gradle.api.plugins.JavaPluginExtension; -import org.gradle.api.tasks.JavaExec; -import org.gradle.api.tasks.SourceSet; -import org.gradle.api.tasks.SourceSetContainer; -import org.gradle.api.tasks.TaskProvider; -import org.gradle.api.tasks.compile.JavaCompile; - -public final class JmhBenchmarksPlugin implements Plugin { - @Override - public void apply(Project project) { - JmhBenchmarksExtension extension = - project.getExtensions().create("jmhBenchmarks", JmhBenchmarksExtension.class); - project.getPluginManager().apply("ca.platform-module"); - project.getPluginManager().withPlugin("java", ignored -> configure(project, extension)); - } - - private static void configure(Project project, JmhBenchmarksExtension extension) { - var catalog = project.getExtensions().getByType(VersionCatalogsExtension.class).named("libs"); - String jmh = - catalog - .findVersion("jmh") - .orElseThrow(() -> new GradleException("Version catalog 'libs' must define 'jmh'")) - .getRequiredVersion(); - String errorprone = - catalog - .findVersion("errorprone") - .orElseThrow( - () -> new GradleException("Version catalog 'libs' must define 'errorprone'")) - .getRequiredVersion(); - - SourceSetContainer sourceSets = - project.getExtensions().getByType(JavaPluginExtension.class).getSourceSets(); - SourceSet jmhSource = sourceSets.create("jmh"); - - project - .getConfigurations() - .getByName(jmhSource.getImplementationConfigurationName()) - .extendsFrom( - project.getConfigurations().getByName("implementation"), - project.getConfigurations().getByName("testImplementation")); - project - .getConfigurations() - .getByName(jmhSource.getRuntimeOnlyConfigurationName()) - .extendsFrom( - project.getConfigurations().getByName("runtimeOnly"), - project.getConfigurations().getByName("testRuntimeOnly")); - - project - .getDependencies() - .add(jmhSource.getImplementationConfigurationName(), "org.openjdk.jmh:jmh-core:" + jmh); - project - .getDependencies() - .add( - jmhSource.getAnnotationProcessorConfigurationName(), - "org.openjdk.jmh:jmh-generator-annprocess:" + jmh); - project - .getDependencies() - .add( - jmhSource.getAnnotationProcessorConfigurationName(), - "com.google.errorprone:error_prone_core:" + errorprone); - - project - .getTasks() - .named(jmhSource.getCompileJavaTaskName(), JavaCompile.class) - .configure( - compile -> { - ErrorProneOptions options = - ErrorProneOptionsKt.getErrorprone(compile.getOptions()); - options.getEnabled().set(false); - compile.getOptions().getCompilerArgs().removeIf("-Werror"::equals); - }); - project - .getTasks() - .matching(task -> task.getName().equals("spotbugsJmh")) - .configureEach(task -> task.setEnabled(false)); - project - .getTasks() - .matching(task -> task.getName().equals("checkstyleJmh")) - .configureEach(task -> task.setEnabled(false)); - - TaskProvider jmhTask = - project - .getTasks() - .register( - "jmh", - JavaExec.class, - task -> { - task.setGroup("verification"); - task.setDescription("Runs the JMH benchmarks in this leaf."); - task.setClasspath(jmhSource.getRuntimeClasspath()); - task.getMainClass().set("org.openjdk.jmh.Main"); - }); - - project.afterEvaluate( - ignored -> { - configureVisibleOutputs(project, sourceSets, jmhSource, extension.visibleOutputs()); - String reportPath = extension.jsonReport(); - if (reportPath != null && !reportPath.isBlank()) { - String reportFile = - project.getLayout().getBuildDirectory().file(reportPath).get().getAsFile().getAbsolutePath(); - jmhTask.configure(task -> task.args("-rf", "json", "-rff", reportFile)); - } - }); - } - - private static void configureVisibleOutputs( - Project project, - SourceSetContainer sourceSets, - SourceSet jmhSource, - List visibleSourceSets) { - FileCollection compileClasspath = jmhSource.getCompileClasspath(); - FileCollection runtimeClasspath = jmhSource.getRuntimeClasspath(); - for (String sourceSetName : visibleSourceSets) { - SourceSet visible = sourceSets.findByName(sourceSetName); - if (visible == null) { - throw new GradleException( - "jmh source set in " - + project.getPath() - + " compiles against unknown source set '" - + sourceSetName - + "'"); - } - compileClasspath = compileClasspath.plus(visible.getOutput()); - runtimeClasspath = runtimeClasspath.plus(visible.getOutput()); - } - jmhSource.setCompileClasspath(compileClasspath); - jmhSource.setRuntimeClasspath(runtimeClasspath); - } -} diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/jpa/JpaTestLanesPlugin.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/jpa/JpaTestLanesPlugin.java deleted file mode 100644 index 4f2c83be..00000000 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/jpa/JpaTestLanesPlugin.java +++ /dev/null @@ -1,159 +0,0 @@ -package dev.caskeleton.buildlogic.jpa; - -import dev.caskeleton.buildlogic.strictlane.StrictTestLaneExtension; -import java.util.List; -import org.gradle.api.Plugin; -import org.gradle.api.Project; - -public final class JpaTestLanesPlugin implements Plugin { - private static final String READINESS_PACKAGE = - "dev.caskeleton.adapter.outbound.persistence.readiness"; - - private static final List READINESS_LANES = - List.of( - readiness("postgresqlLifecycleIntegrationTest", "PostgreSqlLifecycleIntegrationTest"), - new ReadinessLane( - "postgresqlSecurityBaselineIntegrationTest", - "PostgreSqlSecurityBaselineIntegrationTest", - List.of("runtimeRoleCannotCreateInApplicationSchemaOrTempAndUsesTrustedSearchPath")), - readiness("postgresqlMigrationIntegrationTest", "PostgreSqlMigrationIntegrationTest"), - readiness( - "postgresqlIntLockMigrationCompatibilityIntegrationTest", - "PostgreSqlIntLockMigrationCompatibilityIntegrationTest"), - readiness("postgresqlTransactionIntegrationTest", "PostgreSqlTransactionIntegrationTest"), - readiness( - "postgresqlDistributedLockIntegrationTest", - "PostgreSqlDistributedLockIntegrationTest"), - readiness("postgresqlAggregateIntegrationTest", "PostgreSqlAggregateIntegrationTest"), - readiness("postgresqlQueryIntegrationTest", "PostgreSqlQueryIntegrationTest"), - readiness("postgresqlIdempotencyIntegrationTest", "PostgreSqlIdempotencyIntegrationTest"), - readiness( - "postgresqlIdempotencyUniqueScopeIntegrationTest", - "PostgreSqlIdempotencyUniqueScopeIntegrationTest"), - readiness("postgresqlOutboxStorageIntegrationTest", "PostgreSqlOutboxStorageIntegrationTest"), - readiness( - "postgresqlLegacyOutboxAppendTransactionalIntegrationTest", - "PostgreSqlLegacyOutboxAppendTransactionalIntegrationTest"), - readiness( - "postgresqlLegacyOutboxConcurrentRelayIntegrationTest", - "PostgreSqlLegacyOutboxConcurrentRelayIntegrationTest"), - readiness( - "postgresqlLegacyOutboxRowLifecycleIntegrationTest", - "PostgreSqlLegacyOutboxRowLifecycleIntegrationTest"), - readiness("postgresqlOutboxPollingIntegrationTest", "PostgreSqlOutboxPollingIntegrationTest"), - readiness("postgresqlInboxIntegrationTest", "PostgreSqlInboxIntegrationTest"), - readiness( - "postgresqlFileserverMigrationIntegrationTest", - "PostgreSqlFileserverMigrationIntegrationTest"), - readiness( - "postgresqlFileserverMetadataIntegrationTest", - "PostgreSqlFileserverMetadataStoreIntegrationTest"), - readiness( - "postgresqlFileserverReclamationIntegrationTest", - "PostgreSqlFileserverReclamationIntegrationTest"), - readiness( - "postgresqlNotificationSchemaActivationIntegrationTest", - "PostgreSqlNotificationSchemaActivationIntegrationTest")); - - private static final List PLATFORM_LANES = - List.of( - new TaggedLane( - "jpaPlatformContractTest", - "jpa-contract", - "Runs the JPA platform contract suite against real PostgreSQL (design §40)."), - new TaggedLane( - "jpaPlatformMigrationTest", - "jpa-migration", - "Runs the Flyway upgrade snapshot scenarios (design §31)."), - new TaggedLane( - "jpaPlatformFailureTest", - "jpa-failure", - "Reproduces deadlock, serialization, and commit-ambiguity failures (design §39)."), - new TaggedLane( - "jpaPlatformQueryPlanTest", - "jpa-queryplan", - "Asserts query plan structure and planner estimate error (design §33)."), - new TaggedLane( - "jpaPlatformSecurityTest", - "jpa-security", - "Verifies runtime role privileges and search_path safety (design §36).")); - - @Override - public void apply(Project project) { - project.getPluginManager().apply("ca.strict-test-lane"); - project.getPluginManager().withPlugin("java", ignored -> configure(project)); - } - - private static void configure(Project project) { - String evidenceImage = - project - .getProviders() - .gradleProperty("jpaPostgreSqlEvidenceImage") - .orElse("postgres:16-alpine") - .get(); - String matrixVersions = - project.getProviders().gradleProperty("jpa.matrix.versions").orElse("16").get(); - StrictTestLaneExtension lanes = - project.getExtensions().getByType(StrictTestLaneExtension.class); - - READINESS_LANES.forEach(lane -> configureReadinessLane(lanes, lane, evidenceImage)); - PLATFORM_LANES.forEach(lane -> configurePlatformLane(lanes, lane, matrixVersions)); - configurePoolContractLane(lanes); - } - - private static void configureReadinessLane( - StrictTestLaneExtension lanes, ReadinessLane metadata, String evidenceImage) { - String testClass = READINESS_PACKAGE + "." + metadata.simpleName(); - lanes.lane( - metadata.taskName(), - lane -> { - lane.integration(); - lane.setSourceSet("postgresqlIntegrationTest"); - lane.setDescription("Runs the no-skip real PostgreSQL readiness scenario " + testClass + "."); - lane.requires(testClass); - metadata.additionalMethods().forEach(method -> lane.requires(testClass + "." + method)); - lane.jvmArgs( - "-Duser.timezone=UTC", - "-Djpa.evidence.postgresql.image=" + evidenceImage); - }); - } - - private static void configurePlatformLane( - StrictTestLaneExtension lanes, TaggedLane metadata, String matrixVersions) { - lanes.lane( - metadata.taskName(), - lane -> { - lane.integration(); - lane.setSourceSet("postgresqlIntegrationTest"); - lane.setTag(metadata.tag()); - lane.setDescription(metadata.description()); - lane.jvmArgs("-Duser.timezone=UTC"); - lane.systemProperty("jpa.matrix.versions", matrixVersions); - }); - } - - private static void configurePoolContractLane(StrictTestLaneExtension lanes) { - lanes.lane( - "jpaPlatformPoolContractTest", - lane -> { - lane.setSourceSet("jpaPlatformPerformanceTest"); - lane.setDescription( - "Verifies Hikari pool and REQUIRES_NEW connection behaviour (design §38)."); - lane.performance(); - lane.jvmArgs("-Duser.timezone=UTC"); - }); - } - - private static ReadinessLane readiness(String taskName, String simpleName) { - return new ReadinessLane(taskName, simpleName, List.of()); - } - - private record ReadinessLane( - String taskName, String simpleName, List additionalMethods) { - private ReadinessLane { - additionalMethods = List.copyOf(additionalMethods); - } - } - - private record TaggedLane(String taskName, String tag, String description) {} -} diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/quality/QualityConventionsPlugin.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/quality/QualityConventionsPlugin.java index 0e2456ed..f01e3736 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/quality/QualityConventionsPlugin.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/quality/QualityConventionsPlugin.java @@ -97,6 +97,36 @@ public final class QualityConventionsPlugin implements Plugin { options.getDisableWarningsInGeneratedCode().set(true); }); + // JMH (me.champeau.jmh) compiles benchmarks and the code it generates from them; neither is + // shipped, and generated code does not answer to the repository's lint or bug patterns. + project + .getPluginManager() + .withPlugin( + "me.champeau.jmh", + ignored -> { + project + .getTasks() + .withType(JavaCompile.class) + .matching( + compile -> + compile.getName().equals("compileJmhJava") + || compile.getName().equals("jmhCompileGeneratedClasses")) + .configureEach( + compile -> { + ErrorProneOptionsKt.getErrorprone(compile.getOptions()) + .getEnabled() + .set(false); + compile.getOptions().getCompilerArgs().removeIf("-Werror"::equals); + }); + project + .getTasks() + .matching( + task -> + task.getName().equals("spotbugsJmh") + || task.getName().equals("checkstyleJmh")) + .configureEach(task -> task.setEnabled(false)); + }); + project .getDependencies() .add( diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/redis/RedisTopologyContract.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/redis/RedisTopologyContract.java index 35d1d01c..66862553 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/redis/RedisTopologyContract.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/redis/RedisTopologyContract.java @@ -1,7 +1,6 @@ package dev.caskeleton.buildlogic.redis; import java.util.ArrayList; -import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; @@ -15,7 +14,6 @@ public final class RedisTopologyContract { "sentinel", "sentinel", "cluster", "cluster", "tls", "standalone"); - private static final Map> REQUIRED_CLASSES = requiredClasses(); private RedisTopologyContract() {} @@ -27,11 +25,8 @@ public final class RedisTopologyContract { return "tls".equals(declaredMode); } - public static List requiredClasses(String declaredMode) { - return REQUIRED_CLASSES.getOrDefault(declaredMode, List.of()); - } - - public static void validateInvocation(String declaredMode, Set availableProperties) { + public static void validateInvocation( + String declaredMode, Set declaredModes, Set availableProperties) { if (!SUPPORTED_MODES.contains(declaredMode)) { List supported = new ArrayList<>(SUPPORTED_MODES); supported.sort(String::compareTo); @@ -42,6 +37,16 @@ public final class RedisTopologyContract { + String.join(", ", supported) + ". An unrecognised mode selects no test and would otherwise report success."); } + if (!declaredModes.contains(declaredMode)) { + List declared = new ArrayList<>(declaredModes); + declared.sort(String::compareTo); + throw new IllegalStateException( + "redisTopologyTest of this leaf has no " + + declaredMode + + " lane; it declares " + + (declared.isEmpty() ? "none" : String.join(", ", declared)) + + ". Run the leaves that declare it instead of a lane that would execute nothing."); + } List required = new ArrayList<>(List.of("redis.topology.host", "redis.topology.port")); if ("sentinel".equals(declaredMode)) { required.add("redis.topology.master"); @@ -59,9 +64,12 @@ public final class RedisTopologyContract { } public static void verifyExecution( - String declaredMode, Set executedClasses, int skippedCount) { + String declaredMode, + List requiredClasses, + Set executedClasses, + int skippedCount) { List absent = - requiredClasses(declaredMode).stream() + requiredClasses.stream() .filter(required -> !executedClasses.contains(required)) .toList(); if (!absent.isEmpty()) { @@ -82,18 +90,4 @@ public final class RedisTopologyContract { } } - private static Map> requiredClasses() { - Map> classes = new LinkedHashMap<>(); - classes.put("standalone", List.of( - "LiveRedisCompositionTest", "LiveRedisSemanticPortsTest", - "RedisTopologyContractTest", "LiveRedisGuardrailTest")); - classes.put("sentinel", List.of( - "LiveRedisCompositionTest", "LiveRedisSentinelPromotionTest", - "RedisTopologyContractTest")); - classes.put("cluster", List.of( - "LiveRedisCompositionTest", "LiveRedisClusterTest", - "LiveRedisClusterTransactionTest", "LiveRedisSemanticPortsTest")); - classes.put("tls", List.of("LiveRedisTlsTest")); - return Map.copyOf(classes); - } } diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/redis/RedisTopologyLaneExtension.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/redis/RedisTopologyLaneExtension.java new file mode 100644 index 00000000..84febb3b --- /dev/null +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/redis/RedisTopologyLaneExtension.java @@ -0,0 +1,24 @@ +package dev.caskeleton.buildlogic.redis; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * The classes a leaf's {@code redisTopologyTest} exists to run, per mode. + * + *

Owned by the leaf, because the leaf owns the tests: runtime, SDK and semantic-adapter lanes + * qualify different classes. A mode the leaf does not declare is not a lane of that leaf, and + * selecting it fails rather than running nothing. + */ +public class RedisTopologyLaneExtension { + private final Map> requiredClasses = new LinkedHashMap<>(); + + public void requiredClasses(String mode, String... classes) { + requiredClasses.put(mode, List.of(classes)); + } + + Map> requiredClasses() { + return Map.copyOf(requiredClasses); + } +} diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/redis/RedisTopologyLanePlugin.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/redis/RedisTopologyLanePlugin.java index c67566d5..03bcc737 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/redis/RedisTopologyLanePlugin.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/redis/RedisTopologyLanePlugin.java @@ -25,10 +25,12 @@ public final class RedisTopologyLanePlugin implements Plugin { @Override public void apply(Project project) { project.getPluginManager().apply("ca.strict-test-lane"); - project.getPluginManager().withPlugin("java", ignored -> configure(project)); + RedisTopologyLaneExtension extension = + project.getExtensions().create("redisTopologyLane", RedisTopologyLaneExtension.class); + project.getPluginManager().withPlugin("java", ignored -> configure(project, extension)); } - private static void configure(Project project) { + private static void configure(Project project, RedisTopologyLaneExtension extension) { String declaredMode = project .getProviders() @@ -59,13 +61,17 @@ public final class RedisTopologyLanePlugin implements Plugin { lane.integration(); lane.setTag("redis-topology & lane-" + declaredMode); lane.setDescription( - "Runs the Redis SDK contracts against a real topology declared in infra/redis-sdk."); - lane.customize(test -> configureTopologyTask(test, declaredMode, propertyValues)); + "Runs this leaf's Redis contracts against a real topology declared in infra/redis-sdk."); + lane.customize( + test -> configureTopologyTask(test, declaredMode, propertyValues, extension)); }); } private static void configureTopologyTask( - Test test, String declaredMode, Map propertyValues) { + Test test, + String declaredMode, + Map propertyValues, + RedisTopologyLaneExtension extension) { propertyValues.forEach(test::systemProperty); test.systemProperty("redis.topology.mode", RedisTopologyContract.deploymentMode(declaredMode)); test.systemProperty( @@ -78,7 +84,8 @@ public final class RedisTopologyLanePlugin implements Plugin { test.doFirst( ignored -> { try { - RedisTopologyContract.validateInvocation(declaredMode, availableProperties); + RedisTopologyContract.validateInvocation( + declaredMode, extension.requiredClasses().keySet(), availableProperties); } catch (IllegalStateException invalidInvocation) { throw new GradleException(invalidInvocation.getMessage(), invalidInvocation); } @@ -88,7 +95,10 @@ public final class RedisTopologyLanePlugin implements Plugin { ignored -> { try { RedisTopologyContract.verifyExecution( - declaredMode, tracker.executedClasses(), tracker.skippedCount()); + declaredMode, + extension.requiredClasses().getOrDefault(declaredMode, List.of()), + tracker.executedClasses(), + tracker.skippedCount()); } catch (IllegalStateException invalidExecution) { throw new GradleException(invalidExecution.getMessage(), invalidExecution); } diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/runtime/RuntimeMembershipPlugin.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/runtime/RuntimeMembershipPlugin.java deleted file mode 100644 index 9b51567a..00000000 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/runtime/RuntimeMembershipPlugin.java +++ /dev/null @@ -1,116 +0,0 @@ -package dev.caskeleton.buildlogic.runtime; - -import dev.caskeleton.buildlogic.ModuleRegistry; -import java.io.File; -import java.io.IOException; -import java.io.UncheckedIOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; -import org.gradle.api.GradleException; -import org.gradle.api.Plugin; -import org.gradle.api.Project; -import org.gradle.api.artifacts.Configuration; -import org.gradle.api.artifacts.result.ResolvedComponentResult; -import org.gradle.api.provider.Provider; - -public final class RuntimeMembershipPlugin implements Plugin { - @Override - public void apply(Project project) { - Project root = project.getRootProject(); - File registryFile = root.file("config/architecture/modules.json"); - File repositoryRoot; - try { - repositoryRoot = root.getProjectDir().getParentFile().getCanonicalFile(); - } catch (IOException exception) { - throw new UncheckedIOException("failed to resolve repository root", exception); - } - ModuleRegistry registry; - try { - registry = ModuleRegistry.read(registryFile, repositoryRoot); - } catch (IllegalStateException invalid) { - throw new GradleException(invalid.getMessage(), invalid); - } - List productionModules = - registry.modulesForBuild("main").stream() - .filter(module -> !module.id().equals("sample-portfolio")) - .toList(); - Set registeredPaths = - productionModules.stream().map(ModuleRegistry.Module::gradlePath).collect(Collectors.toSet()); - List compositionIds = - registry.compositionRoots().stream() - .filter(id -> !id.equals("sample-portfolio")) - .toList(); - - var verify = - project - .getTasks() - .register( - "verifyRuntimeModuleRegistry", - task -> { - task.setGroup("verification"); - task.setDescription( - "Verifies resolved composition runtime project dependencies are registered application modules."); - }); - - project.getGradle().projectsEvaluated( - ignored -> { - // One task per composition root, in the composition root. Resolving - // `:app-bootstrap:runtimeClasspath` from the build root is the same cross-project - // resolution that made `org.gradle.parallel=true` fail. - List compositionTaskPaths = new ArrayList<>(); - for (String compositionId : compositionIds) { - ModuleRegistry.Module composition = registry.byId(compositionId); - Project compositionProject = root.findProject(composition.gradlePath()); - if (compositionProject == null) { - throw new GradleException( - "Runtime composition '" - + compositionId - + "' references missing Gradle project '" - + composition.gradlePath() - + "'."); - } - Configuration runtimeClasspath = - compositionProject.getConfigurations().findByName("runtimeClasspath"); - if (runtimeClasspath == null) { - throw new GradleException( - "Runtime composition '" - + compositionId - + "' has no runtimeClasspath configuration."); - } - String compositionPath = compositionProject.getPath(); - Provider runtimeClasspathRoot = - runtimeClasspath.getIncoming().getResolutionResult().getRootComponent(); - compositionProject - .getTasks() - .register( - "verifyCompositionRuntimeMembership", - VerifyCompositionRuntimeMembershipTask.class, - task -> { - task.setGroup("verification"); - task.setDescription( - "Verifies this composition root resolves only registered application" - + " modules."); - task.getCompositionId().set(compositionId); - task.getRegisteredProjectPaths().set(registeredPaths); - task.getCompositionProjectPath().set(compositionPath); - task.getRuntimeClasspathRoot().set(runtimeClasspathRoot); - }); - compositionTaskPaths.add( - composition.gradlePath() + ":verifyCompositionRuntimeMembership"); - } - verify.configure(task -> task.dependsOn(compositionTaskPaths)); - }); - - project - .getTasks() - .register( - "verifyRuntimeModuleMembership", - task -> { - task.setGroup("verification"); - task.setDescription("Compatibility alias for verifyRuntimeModuleRegistry."); - task.dependsOn(verify); - }); - } -} diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/runtime/VerifyCompositionRuntimeMembershipTask.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/runtime/VerifyCompositionRuntimeMembershipTask.java deleted file mode 100644 index 801af83d..00000000 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/runtime/VerifyCompositionRuntimeMembershipTask.java +++ /dev/null @@ -1,78 +0,0 @@ -package dev.caskeleton.buildlogic.runtime; - -import dev.caskeleton.buildlogic.ResolvedComponents; -import java.util.HashSet; -import java.util.Set; -import java.util.TreeSet; -import org.gradle.api.DefaultTask; -import org.gradle.api.GradleException; -import org.gradle.api.artifacts.component.ProjectComponentIdentifier; -import org.gradle.api.artifacts.result.ResolvedComponentResult; -import org.gradle.api.provider.Property; -import org.gradle.api.provider.SetProperty; -import org.gradle.api.tasks.Input; -import org.gradle.api.tasks.Internal; -import org.gradle.api.tasks.TaskAction; -import org.gradle.work.DisableCachingByDefault; - -/** - * One composition root's runtime membership check, run by the project that owns the classpath. - * - *

Registered in the composition root rather than at the build root. The build-root form resolved - * {@code :app-bootstrap:runtimeClasspath} from outside that project, which Gradle refuses once - * project execution is parallel — the same reason the dependency-direction and application-purity - * checks moved. The question is unchanged: does what this artifact actually resolves consist only of - * modules the registry knows about. - * - *

What the task keeps is the resolved root component, not the {@code Configuration}. A - * {@code Configuration} is live build state that the configuration cache cannot store, and a task - * that resolves one in its action resolves it from whichever project runs the action. - */ -@DisableCachingByDefault(because = "Verification resolves a live runtime classpath") -public abstract class VerifyCompositionRuntimeMembershipTask extends DefaultTask { - - /** The registry id of the composition root this task governs. */ - @Input - public abstract Property getCompositionId(); - - /** Every project path the registry registers as an application module. */ - @Input - public abstract SetProperty getRegisteredProjectPaths(); - - /** The composition root's own Gradle path, which is never an unregistered member of itself. */ - @Input - public abstract Property getCompositionProjectPath(); - - /** Root of this composition root's resolved {@code runtimeClasspath}. */ - @Internal - public abstract Property getRuntimeClasspathRoot(); - - @TaskAction - public void verify() { - String ownPath = getCompositionProjectPath().get(); - Set registered = getRegisteredProjectPaths().get(); - Set resolved = new HashSet<>(); - for (ResolvedComponentResult component : - ResolvedComponents.reachableFrom(getRuntimeClasspathRoot().get())) { - if (component.getId() instanceof ProjectComponentIdentifier project - && !project.getProjectPath().equals(ownPath)) { - resolved.add(project.getProjectPath()); - } - } - - Set unregistered = new TreeSet<>(resolved); - unregistered.removeAll(registered); - if (!unregistered.isEmpty()) { - throw new GradleException( - "Runtime composition '" - + getCompositionId().get() - + "' resolves unregistered application projects " - + unregistered - + "."); - } - getLogger() - .lifecycle( - "verifyCompositionRuntimeMembership: {} resolves only registered application projects", - getCompositionId().get()); - } -} diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/ExclusiveRealServerLaneService.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/ExclusiveRealServerLaneService.java index f49c983b..add5c0c3 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/ExclusiveRealServerLaneService.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/ExclusiveRealServerLaneService.java @@ -6,9 +6,9 @@ import org.gradle.api.services.BuildServiceParameters; /** * One slot, shared by every lane that starts a real server or container. * - *

Turning on {@code org.gradle.parallel} made three {@code ReactiveWebThrottleIT} cases and a - * WebSocket shutdown contract fail on socket timeouts, and pass when run alone. Those lanes start an - * embedded Tomcat, Jetty or Reactor Netty and then assert on timing — a permit released at the wrong + *

Turning on {@code org.gradle.parallel} made three web throttle IT cases and a WebSocket + * shutdown contract fail on socket timeouts, and pass when run alone. Those lanes start an embedded + * server and then assert on timing — a permit released at the wrong * moment, a capacity refusal that has to arrive inside a five-second read timeout, connections * closed rather than dropped during shutdown. Several of them at once means the machine decides the * result, not the code, and a gate whose result depends on the machine is the kind this repository's diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictqualification/RejectSkippedTestsListener.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictqualification/RejectSkippedTestsListener.java deleted file mode 100644 index 8efd1bbb..00000000 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictqualification/RejectSkippedTestsListener.java +++ /dev/null @@ -1,31 +0,0 @@ -package dev.caskeleton.buildlogic.strictqualification; - -import org.gradle.api.GradleException; -import org.gradle.api.tasks.testing.TestDescriptor; -import org.gradle.api.tasks.testing.TestListener; -import org.gradle.api.tasks.testing.TestResult; - -final class RejectSkippedTestsListener implements TestListener { - private final String taskName; - - RejectSkippedTestsListener(String taskName) { - this.taskName = taskName; - } - - @Override - public void beforeSuite(TestDescriptor suite) {} - - @Override - public void afterSuite(TestDescriptor suite, TestResult result) { - if (suite.getParent() == null && result.getSkippedTestCount() > 0) { - throw new GradleException( - taskName + " forbids skipped tests: " + result.getSkippedTestCount()); - } - } - - @Override - public void beforeTest(TestDescriptor testDescriptor) {} - - @Override - public void afterTest(TestDescriptor testDescriptor, TestResult result) {} -} diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictqualification/StrictQualificationDefinition.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictqualification/StrictQualificationDefinition.java deleted file mode 100644 index 0d9f17ff..00000000 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictqualification/StrictQualificationDefinition.java +++ /dev/null @@ -1,24 +0,0 @@ -package dev.caskeleton.buildlogic.strictqualification; - -import java.util.List; -import java.util.Objects; -import org.gradle.api.file.Directory; -import org.gradle.api.provider.Provider; -import org.gradle.api.tasks.SourceSet; - -record StrictQualificationDefinition( - String taskName, - SourceSet sourceSet, - List requiredClasses, - Provider junitXmlOutput, - Provider binaryResultsOutput, - String description) { - StrictQualificationDefinition { - Objects.requireNonNull(taskName, "taskName"); - Objects.requireNonNull(sourceSet, "sourceSet"); - requiredClasses = List.copyOf(requiredClasses); - Objects.requireNonNull(junitXmlOutput, "junitXmlOutput"); - Objects.requireNonNull(binaryResultsOutput, "binaryResultsOutput"); - Objects.requireNonNull(description, "description"); - } -} diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictqualification/StrictQualificationExtension.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictqualification/StrictQualificationExtension.java deleted file mode 100644 index 00c33c8c..00000000 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictqualification/StrictQualificationExtension.java +++ /dev/null @@ -1,160 +0,0 @@ -package dev.caskeleton.buildlogic.strictqualification; - -import java.util.HashSet; -import java.util.List; -import org.gradle.api.GradleException; -import org.gradle.api.Project; -import org.gradle.api.file.Directory; -import org.gradle.api.plugins.JavaPluginExtension; -import org.gradle.api.provider.Provider; -import org.gradle.api.tasks.SourceSet; -import org.gradle.api.tasks.TaskProvider; -import org.gradle.api.tasks.testing.Test; - -public class StrictQualificationExtension { - private final Project owner; - - public StrictQualificationExtension(Project owner) { - this.owner = owner; - } - - public TaskProvider register( - String taskName, - SourceSet sourceSet, - List requiredClasses, - String description) { - return register( - taskName, - sourceSet, - requiredClasses, - owner.getLayout().getBuildDirectory().dir("test-results/" + taskName), - owner.getLayout().getBuildDirectory().dir("test-results/" + taskName + "/binary"), - description); - } - - public TaskProvider register( - String taskName, - SourceSet sourceSet, - List requiredClasses, - Provider junitXmlOutput, - Provider binaryResultsOutput, - String description) { - validate(taskName, sourceSet, requiredClasses); - String effectiveDescription = - description == null || description.isBlank() - ? "Runs exact no-skip qualification evidence for " + owner.getPath() + "." - : description; - StrictQualificationDefinition definition = - new StrictQualificationDefinition( - taskName, - sourceSet, - requiredClasses, - junitXmlOutput, - binaryResultsOutput, - effectiveDescription); - return registerDefinition(definition); - } - - private TaskProvider registerDefinition(StrictQualificationDefinition definition) { - var requiredClassesCheck = - owner - .getTasks() - .register( - definition.taskName() + "RequiredClasses", - VerifyQualificationClassesTask.class, - task -> { - task.setGroup("verification"); - task.setDescription( - "Fails when " - + definition.taskName() - + " did not compile every required test class."); - task.dependsOn(definition.sourceSet().getClassesTaskName()); - task.getClassDirectories().from(definition.sourceSet().getOutput().getClassesDirs()); - task.getRequiredClasses().set(definition.requiredClasses()); - task.getQualificationTaskName().set(definition.taskName()); - task.getJunitXmlOutput().set(definition.junitXmlOutput()); - task.getOutputs().upToDateWhen(ignored -> false); - }); - - TaskProvider qualificationTest = - owner - .getTasks() - .register( - definition.taskName(), - Test.class, - test -> { - test.setGroup("verification"); - test.setDescription(definition.description()); - test.dependsOn(requiredClassesCheck); - test.setTestClassesDirs(definition.sourceSet().getOutput().getClassesDirs()); - test.setClasspath(definition.sourceSet().getRuntimeClasspath()); - test.useJUnitPlatform(); - test.filter( - filter -> { - definition.requiredClasses().forEach(filter::includeTestsMatching); - filter.setFailOnNoMatchingTests(true); - }); - test.getFailOnNoDiscoveredTests().set(true); - test.getReports().getJunitXml().getRequired().set(true); - test.getReports().getJunitXml().getOutputLocation().set(definition.junitXmlOutput()); - test.getReports().getHtml().getRequired().set(false); - test.getBinaryResultsDirectory().set(definition.binaryResultsOutput()); - test.getOutputs().upToDateWhen(ignored -> false); - test.jvmArgs("-Duser.timezone=UTC"); - test.addTestListener(new RejectSkippedTestsListener(definition.taskName())); - }); - - var evidenceCheck = - owner - .getTasks() - .register( - definition.taskName() + "Evidence", - VerifyQualificationEvidenceTask.class, - task -> { - task.setGroup("verification"); - task.setDescription( - "Fails unless " - + definition.taskName() - + " executed every required test class without skips."); - task.mustRunAfter(qualificationTest); - task.getJunitXmlOutput().set(definition.junitXmlOutput()); - task.getRequiredClasses().set(definition.requiredClasses()); - task.getQualificationTaskName().set(definition.taskName()); - task.getOutputs().upToDateWhen(ignored -> false); - }); - qualificationTest.configure(test -> test.finalizedBy(evidenceCheck)); - return qualificationTest; - } - - private void validate(String taskName, SourceSet sourceSet, List requiredClasses) { - if (taskName == null || taskName.isBlank()) { - throw new GradleException("A strict qualification task name is required."); - } - if (sourceSet == null) { - throw new GradleException(taskName + " requires an owner source set."); - } - SourceSet owned = - owner - .getExtensions() - .getByType(JavaPluginExtension.class) - .getSourceSets() - .findByName(sourceSet.getName()); - if (owned != sourceSet) { - throw new GradleException( - taskName - + " source set '" - + sourceSet.getName() - + "' does not belong to owner project " - + owner.getPath() - + "."); - } - if (requiredClasses == null - || requiredClasses.isEmpty() - || requiredClasses.stream().anyMatch(value -> value == null || value.isBlank())) { - throw new GradleException(taskName + " must name at least one required test FQCN."); - } - if (new HashSet<>(requiredClasses).size() != requiredClasses.size()) { - throw new GradleException(taskName + " contains duplicate required test FQCNs."); - } - } -} diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictqualification/StrictQualificationPlugin.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictqualification/StrictQualificationPlugin.java deleted file mode 100644 index c5d8ed8f..00000000 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictqualification/StrictQualificationPlugin.java +++ /dev/null @@ -1,21 +0,0 @@ -package dev.caskeleton.buildlogic.strictqualification; - -import org.gradle.api.Plugin; -import org.gradle.api.Project; - -public final class StrictQualificationPlugin implements Plugin { - @Override - public void apply(Project project) { - project - .getPluginManager() - .withPlugin( - "java", - ignored -> - project - .getExtensions() - .create( - "strictQualification", - StrictQualificationExtension.class, - project)); - } -} diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictqualification/VerifyQualificationClassesTask.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictqualification/VerifyQualificationClassesTask.java deleted file mode 100644 index 3bc0d080..00000000 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictqualification/VerifyQualificationClassesTask.java +++ /dev/null @@ -1,92 +0,0 @@ -package dev.caskeleton.buildlogic.strictqualification; - -import java.io.IOException; -import java.io.UncheckedIOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.Comparator; -import java.util.List; -import org.gradle.api.DefaultTask; -import org.gradle.api.GradleException; -import org.gradle.api.file.ConfigurableFileCollection; -import org.gradle.api.file.DirectoryProperty; -import org.gradle.api.provider.ListProperty; -import org.gradle.api.provider.Property; -import org.gradle.api.tasks.Input; -import org.gradle.api.tasks.InputFiles; -import org.gradle.api.tasks.Internal; -import org.gradle.api.tasks.PathSensitive; -import org.gradle.api.tasks.PathSensitivity; -import org.gradle.api.tasks.TaskAction; -import org.gradle.work.DisableCachingByDefault; - -@DisableCachingByDefault(because = "Qualification must validate current compiled classes and clear stale evidence") -public abstract class VerifyQualificationClassesTask extends DefaultTask { - @InputFiles - @PathSensitive(PathSensitivity.RELATIVE) - public abstract ConfigurableFileCollection getClassDirectories(); - - @Input - public abstract ListProperty getRequiredClasses(); - - @Input - public abstract Property getQualificationTaskName(); - - @Internal - public abstract DirectoryProperty getJunitXmlOutput(); - - @Input - public String getJunitXmlOutputPath() { - return getJunitXmlOutput().get().getAsFile().getAbsolutePath(); - } - - @TaskAction - public void verifyClasses() { - List classDirectories = - getClassDirectories().getFiles().stream().map(file -> file.toPath()).toList(); - boolean hasAnyClass = classDirectories.stream().anyMatch(VerifyQualificationClassesTask::hasClassFile); - String taskName = getQualificationTaskName().get(); - if (!hasAnyClass) { - throw new GradleException(taskName + " source set produced no test class files."); - } - - List missing = - getRequiredClasses().get().stream() - .filter( - required -> { - Path relative = Path.of(required.replace('.', '/') + ".class"); - return classDirectories.stream().noneMatch(directory -> Files.isRegularFile(directory.resolve(relative))); - }) - .toList(); - if (!missing.isEmpty()) { - throw new GradleException(taskName + " is missing required test class files: " + missing); - } - - Path staleEvidence = getJunitXmlOutput().get().getAsFile().toPath(); - deleteRecursively(staleEvidence, taskName); - } - - private static boolean hasClassFile(Path directory) { - if (!Files.isDirectory(directory)) { - return false; - } - try (var files = Files.walk(directory)) { - return files.anyMatch(path -> Files.isRegularFile(path) && path.getFileName().toString().endsWith(".class")); - } catch (IOException exception) { - throw new UncheckedIOException("failed to scan compiled classes under " + directory, exception); - } - } - - private static void deleteRecursively(Path directory, String taskName) { - if (!Files.exists(directory)) { - return; - } - try (var paths = Files.walk(directory)) { - for (Path path : paths.sorted(Comparator.reverseOrder()).toList()) { - Files.delete(path); - } - } catch (IOException exception) { - throw new GradleException(taskName + " could not delete stale JUnit XML: " + directory, exception); - } - } -} diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictqualification/VerifyQualificationEvidenceTask.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictqualification/VerifyQualificationEvidenceTask.java deleted file mode 100644 index 92b5b57c..00000000 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictqualification/VerifyQualificationEvidenceTask.java +++ /dev/null @@ -1,65 +0,0 @@ -package dev.caskeleton.buildlogic.strictqualification; - -import dev.caskeleton.buildlogic.JUnitEvidence; -import dev.caskeleton.buildlogic.RequiredTestExecution; -import java.io.File; -import java.util.List; -import org.gradle.api.DefaultTask; -import org.gradle.api.GradleException; -import org.gradle.api.file.DirectoryProperty; -import org.gradle.api.provider.ListProperty; -import org.gradle.api.provider.Property; -import org.gradle.api.tasks.Input; -import org.gradle.api.tasks.Internal; -import org.gradle.api.tasks.TaskAction; -import org.gradle.work.DisableCachingByDefault; - -@DisableCachingByDefault(because = "Qualification evidence verifies the current Test task result") -public abstract class VerifyQualificationEvidenceTask extends DefaultTask { - @Internal - public abstract DirectoryProperty getJunitXmlOutput(); - - @Input - public String getJunitXmlOutputPath() { - return getJunitXmlOutput().get().getAsFile().getAbsolutePath(); - } - - @Input - public abstract ListProperty getRequiredClasses(); - - @Input - public abstract Property getQualificationTaskName(); - - @TaskAction - public void verifyEvidence() { - String evidenceName = getQualificationTaskName().get(); - File resultDirectory = getJunitXmlOutput().get().getAsFile(); - JUnitEvidence.Results evidence; - try { - evidence = JUnitEvidence.read(evidenceName, resultDirectory); - } catch (IllegalStateException unreadable) { - throw new GradleException(unreadable.getMessage(), unreadable); - } - if (evidence.tests() <= 0) { - throw new GradleException(evidenceName + ": requires a positive executed test count"); - } - if (evidence.skipped() > 0) { - throw new GradleException(evidenceName + ": forbids skipped tests: " + evidence.skipped()); - } - if (evidence.failures() > 0 || evidence.errors() > 0) { - throw new GradleException( - evidenceName - + ": failures=" - + evidence.failures() - + ", errors=" - + evidence.errors()); - } - List missing = - RequiredTestExecution.absent(getRequiredClasses().get(), evidence.executedClasses()); - if (!missing.isEmpty()) { - throw new GradleException( - evidenceName + ": no executed test cases for required classes: " + missing); - } - getLogger().lifecycle("{}: {} tests, {} skipped", evidenceName, evidence.tests(), evidence.skipped()); - } -} diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/testagent/TestJvmAgentsPlugin.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/testagent/TestJvmAgentsPlugin.java deleted file mode 100644 index 87804743..00000000 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/testagent/TestJvmAgentsPlugin.java +++ /dev/null @@ -1,52 +0,0 @@ -package dev.caskeleton.buildlogic.testagent; - -import org.gradle.api.Plugin; -import org.gradle.api.Project; -import org.gradle.api.artifacts.Configuration; -import org.gradle.api.tasks.testing.Test; - -public final class TestJvmAgentsPlugin implements Plugin { - @Override - public void apply(Project project) { - project.getPluginManager().withPlugin( - "java", - ignoredJava -> - project.getPluginManager().withPlugin( - "io.spring.dependency-management", - ignoredDependencyManagement -> { - Configuration dependencies = - project - .getConfigurations() - .dependencyScope("mockitoAgentDependencies") - .get(); - Configuration agent = - project - .getConfigurations() - .resolvable( - "mockitoAgent", - configuration -> { - configuration.setDescription( - "Mockito core JAR used only as a Test JVM startup agent."); - configuration.extendsFrom(dependencies); - configuration.setTransitive(false); - }) - .get(); - project - .getDependencies() - .add(dependencies.getName(), "org.mockito:mockito-core"); - project - .getTasks() - .withType(Test.class) - .configureEach( - test -> { - MockitoAgentArgumentProvider provider = - project - .getObjects() - .newInstance(MockitoAgentArgumentProvider.class); - provider.getMockitoCoreClasspath().from(agent); - provider.getOwner().set(project.getPath() + ":" + test.getName()); - test.getJvmArgumentProviders().add(provider); - }); - })); - } -} diff --git a/src/build-logic/src/test/java/dev/caskeleton/bootstrap/contract/ConditionalTransportEvidenceFunctionalTest.java b/src/build-logic/src/test/java/dev/caskeleton/bootstrap/contract/ConditionalTransportEvidenceFunctionalTest.java deleted file mode 100644 index 817efbd2..00000000 --- a/src/build-logic/src/test/java/dev/caskeleton/bootstrap/contract/ConditionalTransportEvidenceFunctionalTest.java +++ /dev/null @@ -1,125 +0,0 @@ -package dev.caskeleton.bootstrap.contract; - -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.Test; -import org.junit.jupiter.api.io.TempDir; - -final class ConditionalTransportEvidenceFunctionalTest { - - @Test - void positiveExecutedCountWithNoSkipPasses(@TempDir Path temporaryDirectory) throws IOException { - EvidenceFixture fixture = fixture(temporaryDirectory); - fixture.writeResult(3, 0, 0, 0); - - BuildResult result = run(fixture.projectDirectory(), "verifyEvidence"); - - assertThat(result.getOutput()).contains("conditional-transport: 3 tests, 0 skipped"); - } - - @Test - void missingResultFilesFailClosed(@TempDir Path temporaryDirectory) throws IOException { - EvidenceFixture fixture = fixture(temporaryDirectory); - - BuildResult result = runAndFail(fixture.projectDirectory(), "verifyEvidence"); - - assertThat(result.getOutput()) - .contains("conditional-transport") - .contains("no JUnit XML result files"); - } - - @Test - void skippedResultFailsClosed(@TempDir Path temporaryDirectory) throws IOException { - EvidenceFixture fixture = fixture(temporaryDirectory); - fixture.writeResult(3, 1, 0, 0); - - BuildResult result = runAndFail(fixture.projectDirectory(), "verifyEvidence"); - - assertThat(result.getOutput()) - .contains("conditional-transport") - .contains("forbids skipped tests") - .contains("1"); - } - - @Test - void zeroExecutedTestsFailClosed(@TempDir Path temporaryDirectory) throws IOException { - EvidenceFixture fixture = fixture(temporaryDirectory); - fixture.writeResult(0, 0, 0, 0); - - BuildResult result = runAndFail(fixture.projectDirectory(), "verifyEvidence"); - - assertThat(result.getOutput()) - .contains("conditional-transport") - .contains("positive executed test count"); - } - - private static EvidenceFixture fixture(Path temporaryDirectory) throws IOException { - Path projectDirectory = temporaryDirectory.resolve("transport-evidence-fixture"); - Files.createDirectories(projectDirectory); - // The fixture includes build-logic for the same reason the real build does: - // junit-evidence.gradle - // reads JUnit XML through the shared reader in that included build, so a fixture without it - // fails to compile the script rather than exercising what the script does. - Files.writeString( - projectDirectory.resolve("settings.gradle"), - "rootProject.name='fixture'\n", - UTF_8); - Files.writeString( - projectDirectory.resolve("build.gradle"), - """ - plugins { - id 'base' - id 'ca.evidence' - } - tasks.register('verifyEvidence') { - doLast { - evidence.verifyNoSkipJUnitXml( - 'conditional-transport', file('results')) - } - } - """, - UTF_8); - return new EvidenceFixture(projectDirectory, projectDirectory.resolve("results")); - } - - private static BuildResult run(Path projectDirectory, String... arguments) { - return runner(projectDirectory, arguments).build(); - } - - private static BuildResult runAndFail(Path projectDirectory, String... arguments) { - return runner(projectDirectory, arguments).buildAndFail(); - } - - private static GradleRunner runner(Path projectDirectory, 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(projectDirectory.toFile()) - .withPluginClasspath() - .withArguments(fullArguments); - } - - private record EvidenceFixture(Path projectDirectory, Path results) { - - void writeResult(int tests, int skipped, int failures, int errors) throws IOException { - Files.createDirectories(results); - Files.writeString( - results.resolve("TEST-qualification.xml"), - """ - - - - """ - .formatted(tests, skipped, failures, errors), - UTF_8); - } - } -} diff --git a/src/build-logic/src/test/java/dev/caskeleton/bootstrap/contract/RuntimeMembershipFunctionalTest.java b/src/build-logic/src/test/java/dev/caskeleton/bootstrap/contract/RuntimeMembershipFunctionalTest.java deleted file mode 100644 index 147f8cab..00000000 --- a/src/build-logic/src/test/java/dev/caskeleton/bootstrap/contract/RuntimeMembershipFunctionalTest.java +++ /dev/null @@ -1,124 +0,0 @@ -package dev.caskeleton.bootstrap.contract; - -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.Test; -import org.junit.jupiter.api.io.TempDir; - -/** The runtime registry verifies invariants from Gradle's resolved graph; it does not mirror it. */ -final class RuntimeMembershipFunctionalTest { - - - @Test - void registeredRuntimeGraphsPass(@TempDir Path temporaryDirectory) throws IOException { - RuntimeFixture fixture = fixture(temporaryDirectory, "", false); - - BuildResult result = run(fixture.projectDirectory(), "verifyRuntimeModuleRegistry"); - - // The aggregate no longer does the resolving, so it no longer reports a count: one task per - // composition root does, in the project that owns the classpath, and each names itself. Asserting - // the per-root line is also the stronger claim — a count of one says nothing about which root. - assertThat(result.getOutput()) - .contains(":app-bootstrap:verifyCompositionRuntimeMembership") - .contains( - "verifyCompositionRuntimeMembership: app-bootstrap resolves only registered application" - + " projects"); - } - - @Test - void anUnregisteredProjectOnTheRuntimeClasspathFailsClosed(@TempDir Path temporaryDirectory) - throws IOException { - RuntimeFixture fixture = - fixture(temporaryDirectory, "implementation project(':unregistered')", false); - - BuildResult result = runAndFail(fixture.projectDirectory(), "verifyRuntimeModuleRegistry"); - - assertThat(result.getOutput()) - .contains("app-bootstrap") - .contains("unregistered application projects") - .contains(":unregistered"); - } - - private static RuntimeFixture fixture( - Path temporaryDirectory, String extraAppDependency, boolean omitDomainFromRegistry) - throws IOException { - Path repositoryRoot = temporaryDirectory.resolve("repository"); - Path projectDirectory = repositoryRoot.resolve("src"); - Files.createDirectories(projectDirectory.resolve("config/architecture")); - for (String module : new String[] {"domain-core", "app-bootstrap", "unregistered"}) { - Files.createDirectories(projectDirectory.resolve(module)); - } - - Files.writeString( - projectDirectory.resolve("settings.gradle"), - "include 'domain-core', 'app-bootstrap', 'unregistered'\n", - UTF_8); - - Files.writeString( - projectDirectory.resolve("build.gradle"), - """ - plugins { - id 'base' - id 'ca.runtime-membership' - } - subprojects { apply plugin: 'java' } - project(':app-bootstrap') { - dependencies { - implementation project(':domain-core') - %s - } - } - """ - .formatted(extraAppDependency), - UTF_8); - - String domainEntry = - omitDomainFromRegistry - ? "" - : """ - {"id":"domain-core","gradle_path":":domain-core","source_path":"src/domain-core","allowed_dependencies":[]}, - """; - Path registry = projectDirectory.resolve("config/architecture/modules.json"); - Files.writeString( - registry, - """ - { - "composition_roots": ["app-bootstrap"], - "modules": [ - %s - {"id":"app-bootstrap","gradle_path":":app-bootstrap","source_path":"src/app-bootstrap","allowed_dependencies":["domain-core"]} - ] - } - """ - .formatted(domainEntry), - UTF_8); - return new RuntimeFixture(projectDirectory, registry); - } - - private static BuildResult run(Path projectDirectory, String... arguments) { - return runner(projectDirectory, arguments).build(); - } - - private static BuildResult runAndFail(Path projectDirectory, String... arguments) { - return runner(projectDirectory, arguments).buildAndFail(); - } - - private static GradleRunner runner(Path projectDirectory, 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(projectDirectory.toFile()) - .withPluginClasspath() - .withArguments(fullArguments); - } - - private record RuntimeFixture(Path projectDirectory, Path registry) {} -} diff --git a/src/build-logic/src/test/java/dev/caskeleton/bootstrap/contract/StrictQualificationTestConventionFunctionalTest.java b/src/build-logic/src/test/java/dev/caskeleton/bootstrap/contract/StrictQualificationTestConventionFunctionalTest.java deleted file mode 100644 index a2bbee59..00000000 --- a/src/build-logic/src/test/java/dev/caskeleton/bootstrap/contract/StrictQualificationTestConventionFunctionalTest.java +++ /dev/null @@ -1,273 +0,0 @@ -package dev.caskeleton.bootstrap.contract; - -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 java.util.List; -import org.gradle.testkit.runner.BuildResult; -import org.gradle.testkit.runner.GradleRunner; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -final class StrictQualificationTestConventionFunctionalTest { - - private static final String REQUIRED_TEST = "fixture.RequiredQualificationTest"; - - @Test - void emptySourceSetFailsBeforeTestExecution(@TempDir Path temporaryDirectory) throws IOException { - QualificationFixture fixture = fixture(temporaryDirectory, REQUIRED_TEST); - - BuildResult result = runAndFail(fixture.projectDirectory(), "strictQualificationTest"); - - assertThat(result.getOutput()) - .contains("strictQualificationTest") - .contains("produced no test class files"); - } - - @Test - void missingRequiredFullyQualifiedClassFailsBeforeTestExecution(@TempDir Path temporaryDirectory) - throws IOException { - QualificationFixture fixture = fixture(temporaryDirectory, "fixture.MissingQualificationTest"); - fixture.writeTest("fixture.RequiredQualificationTest", false); - - BuildResult result = runAndFail(fixture.projectDirectory(), "strictQualificationTest"); - - assertThat(result.getOutput()) - .contains("strictQualificationTest") - .contains("missing required test class files") - .contains("fixture.MissingQualificationTest"); - } - - @Test - void disabledOnlyQualificationFailsClosed(@TempDir Path temporaryDirectory) throws IOException { - QualificationFixture fixture = fixture(temporaryDirectory, REQUIRED_TEST); - fixture.writeTest(REQUIRED_TEST, true); - - BuildResult result = runAndFail(fixture.projectDirectory(), "strictQualificationTest"); - - assertThat(result.getOutput()) - .contains("strictQualificationTest") - .contains("forbids skipped tests") - .contains("1"); - } - - @Test - void oneRequiredExecutedTestProducesPositiveNoSkipEvidence(@TempDir Path temporaryDirectory) - throws IOException { - QualificationFixture fixture = fixture(temporaryDirectory, REQUIRED_TEST); - fixture.writeTest(REQUIRED_TEST, false); - - BuildResult result = run(fixture.projectDirectory(), "strictQualificationTest"); - - assertThat(result.getOutput()).contains("strictQualificationTest: 1 tests, 0 skipped"); - } - - @Test - void everyRequiredClassMustProduceAnExecutedTestCase(@TempDir Path temporaryDirectory) - throws IOException { - String emptyTest = "fixture.EmptyQualificationTest"; - QualificationFixture fixture = fixture(temporaryDirectory, List.of(REQUIRED_TEST, emptyTest)); - fixture.writeTest(REQUIRED_TEST, false); - fixture.writeEmptyTest(emptyTest); - - BuildResult result = runAndFail(fixture.projectDirectory(), "strictQualificationTest"); - - assertThat(result.getOutput()) - .contains("no executed test cases for required classes") - .contains(emptyTest); - } - - @Test - void disabledGradleTestTaskFailsWithoutAcceptingStaleEvidence(@TempDir Path temporaryDirectory) - throws IOException { - QualificationFixture fixture = fixture(temporaryDirectory, REQUIRED_TEST); - fixture.writeTest(REQUIRED_TEST, false); - fixture.writeStaleEvidence(REQUIRED_TEST); - fixture.appendBuild("tasks.named('strictQualificationTest') { enabled = false }\n"); - - BuildResult result = runAndFail(fixture.projectDirectory(), "strictQualificationTest"); - - assertThat(result.getOutput()).contains("no JUnit XML result files"); - } - - @Test - void onlyIfSkippedGradleTestTaskFailsWithoutAcceptingStaleEvidence( - @TempDir Path temporaryDirectory) throws IOException { - QualificationFixture fixture = fixture(temporaryDirectory, REQUIRED_TEST); - fixture.writeTest(REQUIRED_TEST, false); - fixture.writeStaleEvidence(REQUIRED_TEST); - fixture.appendBuild("tasks.named('strictQualificationTest') { onlyIf { false } }\n"); - - BuildResult result = runAndFail(fixture.projectDirectory(), "strictQualificationTest"); - - assertThat(result.getOutput()).contains("no JUnit XML result files"); - } - - @Test - void foreignProjectSourceSetIsRejectedAtConfigurationTime(@TempDir Path temporaryDirectory) - throws IOException { - Path projectDirectory = temporaryDirectory.resolve("foreign-source-set-fixture"); - Files.createDirectories(projectDirectory.resolve("child")); - Files.writeString( - projectDirectory.resolve("settings.gradle"), - """ - rootProject.name='fixture' - include 'child' - """, - UTF_8); - Files.writeString( - projectDirectory.resolve("child/build.gradle"), "plugins { id 'java' }\n", UTF_8); - Files.writeString( - projectDirectory.resolve("build.gradle"), - """ - plugins { - id 'java' - id 'ca.evidence' - id 'ca.strict-qualification' - } - evaluationDependsOn(':child') - strictQualification.register( - 'strictQualificationTest', - project(':child').sourceSets.test, - ['%s'], - 'fixture') - """ - .formatted(REQUIRED_TEST), - UTF_8); - - BuildResult result = runAndFail(projectDirectory, "help"); - - assertThat(result.getOutput()).contains("does not belong to owner project :"); - } - - private static QualificationFixture fixture(Path temporaryDirectory, String requiredTest) - throws IOException { - return fixture(temporaryDirectory, List.of(requiredTest)); - } - - private static QualificationFixture fixture(Path temporaryDirectory, List requiredTests) - throws IOException { - Path projectDirectory = temporaryDirectory.resolve("strict-qualification-fixture"); - Files.createDirectories(projectDirectory); - Files.writeString( - projectDirectory.resolve("settings.gradle"), - "rootProject.name='fixture'\n", - UTF_8); - Files.writeString( - projectDirectory.resolve("build.gradle"), - """ - plugins { - id 'java' - id 'ca.evidence' - id 'ca.strict-qualification' - } - repositories { mavenCentral() } - dependencies { - testImplementation 'org.junit.jupiter:junit-jupiter:6.0.1' - testRuntimeOnly 'org.junit.platform:junit-platform-launcher:6.0.1' - } - strictQualification.register( - 'strictQualificationTest', - sourceSets.test, - [%s], - 'fixture') - """ - .formatted( - requiredTests.stream() - .map(value -> "'" + value + "'") - .collect(java.util.stream.Collectors.joining(", "))), - UTF_8); - return new QualificationFixture(projectDirectory); - } - - private static BuildResult run(Path projectDirectory, String... arguments) { - return runner(projectDirectory, arguments).build(); - } - - private static BuildResult runAndFail(Path projectDirectory, String... arguments) { - return runner(projectDirectory, arguments).buildAndFail(); - } - - private static GradleRunner runner(Path projectDirectory, 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(projectDirectory.toFile()) - .withPluginClasspath() - .withArguments(fullArguments); - } - - private record QualificationFixture(Path projectDirectory) { - - void appendBuild(String buildScript) throws IOException { - Files.writeString( - projectDirectory.resolve("build.gradle"), - buildScript, - UTF_8, - java.nio.file.StandardOpenOption.APPEND); - } - - void writeTest(String fullyQualifiedClassName, boolean disabled) throws IOException { - int separator = fullyQualifiedClassName.lastIndexOf('.'); - String packageName = fullyQualifiedClassName.substring(0, separator); - String simpleName = fullyQualifiedClassName.substring(separator + 1); - Path source = - projectDirectory - .resolve("src/test/java") - .resolve(fullyQualifiedClassName.replace('.', '/') + ".java"); - Files.createDirectories(source.getParent()); - Files.writeString( - source, - """ - package %s; - - import org.junit.jupiter.api.Disabled; - import org.junit.jupiter.api.Test; - - %s - final class %s { - @Test - void requiredQualification() {} - } - """ - .formatted(packageName, disabled ? "@Disabled(\"fixture\")" : "", simpleName), - UTF_8); - } - - void writeStaleEvidence(String fullyQualifiedClassName) throws IOException { - Path result = - projectDirectory - .resolve("build/test-results/strictQualificationTest") - .resolve("TEST-" + fullyQualifiedClassName + ".xml"); - Files.createDirectories(result.getParent()); - Files.writeString( - result, - """ - - - - - """ - .formatted(fullyQualifiedClassName, fullyQualifiedClassName), - UTF_8); - } - - void writeEmptyTest(String fullyQualifiedClassName) throws IOException { - int separator = fullyQualifiedClassName.lastIndexOf('.'); - String packageName = fullyQualifiedClassName.substring(0, separator); - String simpleName = fullyQualifiedClassName.substring(separator + 1); - Path source = - projectDirectory - .resolve("src/test/java") - .resolve(fullyQualifiedClassName.replace('.', '/') + ".java"); - Files.createDirectories(source.getParent()); - Files.writeString( - source, "package " + packageName + ";\n\nfinal class " + simpleName + " {}\n", UTF_8); - } - } -} diff --git a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/ConditionalTransportQualificationPluginFunctionalTest.java b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/ConditionalTransportQualificationPluginFunctionalTest.java deleted file mode 100644 index 4f4b2d1c..00000000 --- a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/ConditionalTransportQualificationPluginFunctionalTest.java +++ /dev/null @@ -1,111 +0,0 @@ -package dev.caskeleton.buildlogic; - -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.Test; -import org.junit.jupiter.api.io.TempDir; - -final class ConditionalTransportQualificationPluginFunctionalTest { - - @Test - void aggregatesAndVerifiesAllConditionalTransportEvidence(@TempDir Path temporaryDirectory) - throws IOException { - Path projectDirectory = fixture(temporaryDirectory); - - BuildResult result = run(projectDirectory, "conditionalTransportQualification"); - - assertThat(result.getOutput()) - .contains("conditional-transport-graphql: 1 tests, 0 skipped") - .contains("conditional-transport-grpc: 1 tests, 0 skipped") - .contains("conditional-transport-websocket: 1 tests, 0 skipped") - .contains("conditional-transport-composition: 1 tests, 0 skipped"); - } - - private static Path fixture(Path temporaryDirectory) throws IOException { - Path projectDirectory = temporaryDirectory.resolve("src"); - Files.createDirectories(projectDirectory); - Files.writeString( - projectDirectory.resolve("settings.gradle"), - """ - rootProject.name='fixture' - include 'adapter:inbound:graphql' - include 'adapter:inbound:grpc' - include 'adapter:inbound:websocket' - include 'app-bootstrap' - """, - UTF_8); - Files.writeString( - projectDirectory.resolve("build.gradle"), - """ - plugins { - id 'ca.evidence' - id 'ca.conditional-transport-qualification' - } - tasks.register('verifyRuntimeModuleMembership') - """, - UTF_8); - - writeProducer( - projectDirectory, - "adapter/inbound/graphql", - "graphqlTransportQualificationTest", - "graphqlTransportQualificationTest"); - writeProducer( - projectDirectory, - "adapter/inbound/grpc", - "grpcTransportQualificationTest", - "grpcTransportQualificationTest"); - writeProducer( - projectDirectory, - "adapter/inbound/websocket", - "websocketTransportQualificationTest", - "websocketTransportQualificationTest"); - writeProducer( - projectDirectory, - "app-bootstrap", - "conditionalTransportBuildContractTest", - "conditionalTransportBuildContractTest"); - return projectDirectory; - } - - private static void writeProducer( - Path projectDirectory, String projectPath, String taskName, String resultDirectory) - throws IOException { - Path directory = projectDirectory.resolve(projectPath); - Files.createDirectories(directory); - Files.writeString( - directory.resolve("build.gradle"), - """ - tasks.register('%s') { - doLast { - def resultDir = layout.buildDirectory.dir('test-results/%s').get().asFile - resultDir.mkdirs() - new File(resultDir, 'TEST-fixture.xml').text = ''' - - - - ''' - } - } - """ - .formatted(taskName, resultDirectory), - UTF_8); - } - - private static BuildResult run(Path projectDirectory, String... arguments) { - String[] fullArguments = new String[arguments.length + 1]; - fullArguments[0] = "--console=plain"; - System.arraycopy(arguments, 0, fullArguments, 1, arguments.length); - return GradleRunner.create() - .withProjectDir(projectDirectory.toFile()) - .withPluginClasspath() - .withArguments(fullArguments) - .build(); - } -} diff --git a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/JUnitEvidenceTest.java b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/JUnitEvidenceTest.java deleted file mode 100644 index 791aa34b..00000000 --- a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/JUnitEvidenceTest.java +++ /dev/null @@ -1,77 +0,0 @@ -package dev.caskeleton.buildlogic; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.nio.file.Files; -import java.nio.file.Path; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -class JUnitEvidenceTest { - @TempDir Path results; - - private void suite(String name, String body) throws Exception { - Files.writeString(results.resolve("TEST-" + name + ".xml"), body); - } - - @Test void totalsComeFromAttributes() throws Exception { - suite("Broken", ""); - JUnitEvidence.Results read = JUnitEvidence.read("lane", results.toFile()); - assertEquals(1, read.tests()); - assertEquals(1, read.errors()); - assertFalse(read.isClean()); - } - - @Test void skippedCaseIsNotExecuted() throws Exception { - suite("Mixed", """ - - - - - """); - JUnitEvidence.Results read = JUnitEvidence.read("lane", results.toFile()); - assertTrue(read.executedClasses().contains("a.Ran")); - assertFalse(read.executedClasses().contains("a.Skipped")); - } - - @Test void selectorsIncludeEveryCase() throws Exception { - suite("Mixed", """ - - - - - """); - JUnitEvidence.Results read = JUnitEvidence.read("lane", results.toFile()); - assertTrue(read.executedSelectors().contains("a.Ran#ran")); - assertTrue(read.executedSelectors().contains("a.Skipped#skipped")); - } - - @Test void emptyDirectoryIsRefused() { - IllegalStateException failure = assertThrows(IllegalStateException.class, () -> JUnitEvidence.read("lane", results.toFile())); - assertTrue(failure.getMessage().contains("no JUnit XML result files")); - } - - @Test void malformedCountIsRefused() throws Exception { - suite("Odd", ""); - IllegalStateException failure = assertThrows(IllegalStateException.class, () -> JUnitEvidence.read("lane", results.toFile())); - assertTrue(failure.getMessage().contains("invalid tests=")); - } - - @Test void wrongRootIsRefused() throws Exception { - suite("Wrong", ""); - IllegalStateException failure = assertThrows(IllegalStateException.class, () -> JUnitEvidence.read("lane", results.toFile())); - assertTrue(failure.getMessage().contains("root must be testsuite")); - } - - @Test void doctypeIsRefused() throws Exception { - suite("Doctype", """ - ]> - - """); - IllegalStateException failure = assertThrows(IllegalStateException.class, () -> JUnitEvidence.read("lane", results.toFile())); - assertTrue(failure.getMessage().contains("not readable JUnit XML")); - } -} diff --git a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/ModuleRegistryTest.java b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/ModuleRegistryTest.java index 92c6bfbc..cd75959d 100644 --- a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/ModuleRegistryTest.java +++ b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/ModuleRegistryTest.java @@ -25,7 +25,6 @@ class ModuleRegistryTest { void wellFormedRegistryParses() { ModuleRegistry parsed = read(valid()); assertEquals(2, parsed.modules().size()); - assertEquals(List.of("app-bootstrap", "sample-portfolio"), parsed.compositionRoots()); assertTrue(parsed.byId("app-bootstrap").sourceDirectory().isDirectory()); } @@ -37,7 +36,6 @@ class ModuleRegistryTest { () -> read( registry( - "[\"app-bootstrap\",\"sample-portfolio\"]", entry("app-bootstrap", ":app-bootstrap", "src/alpha"), entry("sample-portfolio", ":sample-portfolio", "src/beta"), entry("app-bootstrap", ":other", "src/alpha")))); @@ -52,7 +50,6 @@ class ModuleRegistryTest { () -> read( registry( - "[\"app-bootstrap\",\"sample-portfolio\"]", entry("app-bootstrap", ":app-bootstrap", "src/alpha"), entry("sample-portfolio", ":sample-portfolio", "src/beta"), entry("aliased", ":aliased", "src/beta/../alpha")))); @@ -64,7 +61,6 @@ class ModuleRegistryTest { ModuleRegistry parsed = read( registry( - "[\"app-bootstrap\",\"sample-portfolio\"]", entry( "app-bootstrap", ":app-bootstrap", @@ -80,7 +76,7 @@ class ModuleRegistryTest { void missingRequiredFieldIsRefused() { String json = """ - {"composition_roots":["app-bootstrap","sample-portfolio"],"modules":[ + {"modules":[ {"id":"app-bootstrap","gradle_path":":app-bootstrap","source_path":"src/alpha"}, %s]} """ @@ -94,7 +90,6 @@ class ModuleRegistryTest { Files.createDirectories(root.resolve("src/grpc/grpc-client")); String json = registry( - "[\"app-bootstrap\"]", entry("app-bootstrap", ":app-bootstrap", "src/alpha"), """ {"id":"grpc-client","gradle_path":":grpc:grpc-client","source_path":"src/grpc/grpc-client", @@ -111,7 +106,7 @@ class ModuleRegistryTest { void blankBuildOwnershipIsRefused() { String json = """ - {"composition_roots":["app-bootstrap"],"modules":[ + {"modules":[ {"id":"app-bootstrap","gradle_path":":app-bootstrap","source_path":"src/alpha", "allowed_dependencies":[],"build":" "}]} """; @@ -135,7 +130,6 @@ class ModuleRegistryTest { private String valid() { return registry( - "[\"app-bootstrap\",\"sample-portfolio\"]", entry("app-bootstrap", ":app-bootstrap", "src/alpha"), entry("sample-portfolio", ":sample-portfolio", "src/beta")); } @@ -156,7 +150,7 @@ class ModuleRegistryTest { + "}"; } - private static String registry(String roots, String... entries) { - return "{\"composition_roots\":" + roots + ",\"modules\":[" + String.join(",", entries) + "]}"; + private static String registry(String... entries) { + return "{\"modules\":[" + String.join(",", entries) + "]}"; } } diff --git a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/architecture/CleanArchitectureResolvedClasspathFunctionalTest.java b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/architecture/CleanArchitectureResolvedClasspathFunctionalTest.java index 982c3026..f8b39004 100644 --- a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/architecture/CleanArchitectureResolvedClasspathFunctionalTest.java +++ b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/architecture/CleanArchitectureResolvedClasspathFunctionalTest.java @@ -56,7 +56,6 @@ class CleanArchitectureResolvedClasspathFunctionalTest { project.resolve("config/architecture/modules.json"), """ { - "composition_roots": ["sample-portfolio"], "modules": [ { "id": "a", @@ -126,7 +125,6 @@ class CleanArchitectureResolvedClasspathFunctionalTest { project.resolve("config/architecture/modules.json"), """ { - "composition_roots": ["c"], "modules": [ { "id": "a", diff --git a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/bootstrap/DeveloperBootstrapPluginFunctionalTest.java b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/bootstrap/DeveloperBootstrapPluginFunctionalTest.java index 63eec479..55cc021a 100644 --- a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/bootstrap/DeveloperBootstrapPluginFunctionalTest.java +++ b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/bootstrap/DeveloperBootstrapPluginFunctionalTest.java @@ -50,7 +50,7 @@ final class DeveloperBootstrapPluginFunctionalTest { Path projectDirectory = fixture(temporaryDirectory); BuildResult failure = - runAndFail(projectDirectory, "tasks", "-PbootstrapProfile=staging"); + runAndFail(projectDirectory, "bootstrapDockerPreflight", "-PbootstrapProfile=staging"); assertThat(failure.getOutput()) .contains("names no overlay") @@ -58,6 +58,19 @@ final class DeveloperBootstrapPluginFunctionalTest { .contains("[dev, local]"); } + @Test + void configurationDoesNotRequireComposeFiles(@TempDir Path temporaryDirectory) + throws IOException { + // The Docker image build copies only src/ into its context, so the repository root and its + // compose files do not exist there. Configuring the root project must still succeed; only the + // bootstrap tasks themselves need an overlay. + Path projectDirectory = fixtureWithoutComposeFiles(temporaryDirectory); + + BuildResult result = run(projectDirectory, "help"); + + assertThat(result.getOutput()).contains("BUILD SUCCESSFUL"); + } + @Test void bootstrapTaskKeepsTheRequiredStageOrder(@TempDir Path temporaryDirectory) throws IOException { Path projectDirectory = fixture(temporaryDirectory); @@ -73,14 +86,20 @@ final class DeveloperBootstrapPluginFunctionalTest { } private static Path fixture(Path temporaryDirectory) throws IOException { - Path repositoryRoot = temporaryDirectory.resolve("repository"); - Path projectDirectory = repositoryRoot.resolve("src"); - Files.createDirectories(projectDirectory.resolve("app-bootstrap")); + Path projectDirectory = fixtureWithoutComposeFiles(temporaryDirectory); + Path repositoryRoot = projectDirectory.getParent(); // The bootstrap merges an overlay onto the base compose file and refuses a profile that names // none, so the fixture has to carry the two the repository carries. Files.writeString(repositoryRoot.resolve("docker-compose.yml"), "services: {}\n", UTF_8); Files.writeString(repositoryRoot.resolve("docker-compose.local.yml"), "services: {}\n", UTF_8); Files.writeString(repositoryRoot.resolve("docker-compose.dev.yml"), "services: {}\n", UTF_8); + return projectDirectory; + } + + private static Path fixtureWithoutComposeFiles(Path temporaryDirectory) throws IOException { + Path repositoryRoot = temporaryDirectory.resolve("repository"); + Path projectDirectory = repositoryRoot.resolve("src"); + Files.createDirectories(projectDirectory.resolve("app-bootstrap")); Files.writeString( projectDirectory.resolve("settings.gradle"), "rootProject.name='fixture'\ninclude 'app-bootstrap'\n", diff --git a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/dependency/DependencyPolicyPluginTest.java b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/dependency/DependencyPolicyPluginTest.java deleted file mode 100644 index b8deeb16..00000000 --- a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/dependency/DependencyPolicyPluginTest.java +++ /dev/null @@ -1,95 +0,0 @@ -package dev.caskeleton.buildlogic.dependency; - -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.jar.JarOutputStream; -import org.gradle.api.DefaultTask; -import org.gradle.api.Plugin; -import org.gradle.testkit.runner.BuildResult; -import org.gradle.testkit.runner.GradleRunner; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -class DependencyPolicyPluginTest { - @Test - void pluginUsesTypedJavaModel() { - assertTrue(Plugin.class.isAssignableFrom(DependencyPolicyPlugin.class)); - assertTrue(DefaultTask.class.isAssignableFrom(VerifyDependencyPolicyTask.class)); - DependencyAbsence absence = new DependencyAbsence("g:m", "why", "runtimeClasspath"); - assertTrue(absence.coordinate().equals("g:m")); - } - - - @Test - void missingRequiredModuleFailsResolvedGraph(@TempDir Path projectDir) throws Exception { - fixture(projectDir, - """ - plugins { id 'java'; id 'ca.dependency-policy' } - dependencyPolicy { required 'g:m', 'runtime contract needs it' } - """); - - BuildResult result = runner(projectDir, "verifyDependencyPolicy").buildAndFail(); - - assertTrue(result.getOutput().contains("required g:m is missing"), result.getOutput()); - } - - @Test - void forbiddenModulePatternFailsResolvedGraph(@TempDir Path projectDir) throws Exception { - localModule(projectDir, "g", "yaml-tool", "1.0"); - fixture(projectDir, - """ - plugins { id 'java'; id 'ca.dependency-policy' } - repositories { maven { url = uri('repo') } } - dependencies { implementation 'g:yaml-tool:1.0' } - dependencyPolicy { absentMatching '(?i).*yaml.*', 'runtime must remain YAML-free' } - """); - - BuildResult result = runner(projectDir, "verifyDependencyPolicy").buildAndFail(); - - assertTrue(result.getOutput().contains("g:yaml-tool matches forbidden pattern"), result.getOutput()); - } - - @Test - void missingReasonFailsAtDeclarationTime(@TempDir Path projectDir) throws Exception { - fixture(projectDir, - """ - plugins { id 'java'; id 'ca.dependency-policy' } - dependencyPolicy { absent 'g:m', ' ' } - """); - BuildResult result = runner(projectDir, "tasks").buildAndFail(); - assertTrue(result.getOutput().contains("needs a reason"), result.getOutput()); - } - - - private static void localModule(Path projectDir, String group, String module, String version) - throws Exception { - Path moduleDirectory = - projectDir.resolve("repo").resolve(group.replace('.', '/')).resolve(module).resolve(version); - Files.createDirectories(moduleDirectory); - Files.writeString( - moduleDirectory.resolve(module + "-" + version + ".pom"), - """ - - 4.0.0 - %s - %s - %s - - """.formatted(group, module, version)); - try (JarOutputStream ignored = - new JarOutputStream(Files.newOutputStream(moduleDirectory.resolve(module + "-" + version + ".jar")))) { - // Empty artifact: the policy test only needs a resolvable module coordinate. - } - } - - private static void fixture(Path dir, String build) throws Exception { - Files.writeString(dir.resolve("settings.gradle"), "rootProject.name='fixture'\n"); - Files.writeString(dir.resolve("build.gradle"), build); - } - - private static GradleRunner runner(Path dir, String... args) { - return GradleRunner.create().withProjectDir(dir.toFile()).withPluginClasspath().withArguments(args); - } -} diff --git a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/jmh/JmhBenchmarksPluginFunctionalTest.java b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/jmh/JmhBenchmarksPluginFunctionalTest.java deleted file mode 100644 index b0cc782d..00000000 --- a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/jmh/JmhBenchmarksPluginFunctionalTest.java +++ /dev/null @@ -1,79 +0,0 @@ -package dev.caskeleton.buildlogic.jmh; - -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.Test; -import org.junit.jupiter.api.io.TempDir; - -final class JmhBenchmarksPluginFunctionalTest { - - @Test - void customVisibleOutputsAndJsonReportAreOwnedByThePlugin(@TempDir Path temporaryDirectory) - throws IOException { - Path projectDirectory = temporaryDirectory.resolve("fixture"); - Files.createDirectories(projectDirectory.resolve("gradle")); - Files.copy(repositorySourceRoot().resolve("gradle/libs.versions.toml"), - projectDirectory.resolve("gradle/libs.versions.toml")); - Files.writeString(projectDirectory.resolve("settings.gradle"), "rootProject.name='fixture'\n", UTF_8); - Files.writeString( - projectDirectory.resolve("build.gradle"), - """ - plugins { - id 'java-test-fixtures' - id 'ca.jmh-benchmarks' - } - - jmhBenchmarks { - compilesAgainst 'main', 'testFixtures' - jsonReport 'reports/jmh/result.json' - } - - tasks.register('verifyJmhModel') { - doLast { - def buildDependencies = sourceSets.jmh.compileClasspath.buildDependencies - .getDependencies(null)*.name as Set - assert buildDependencies.contains('testFixturesClasses') - assert !buildDependencies.contains('testClasses') - - def jmhTask = tasks.named('jmh', JavaExec).get() - assert jmhTask.args == [ - '-rf', 'json', '-rff', - layout.buildDirectory.file('reports/jmh/result.json').get().asFile.absolutePath - ] - } - } - """, - UTF_8); - - BuildResult result = runner(projectDirectory, "verifyJmhModel").build(); - - assertThat(result.getOutput()).contains("BUILD SUCCESSFUL"); - } - - private static GradleRunner runner(Path projectDirectory, String... arguments) { - String[] fullArguments = new String[arguments.length + 1]; - fullArguments[0] = "--console=plain"; - System.arraycopy(arguments, 0, fullArguments, 1, arguments.length); - return GradleRunner.create() - .withProjectDir(projectDirectory.toFile()) - .withPluginClasspath() - .withArguments(fullArguments); - } - - private static Path repositorySourceRoot() { - Path candidate = Path.of("").toAbsolutePath(); - while (candidate != null && !Files.isRegularFile(candidate.resolve("gradle/libs.versions.toml"))) { - candidate = candidate.getParent(); - } - if (candidate == null) { - throw new IllegalStateException("could not locate repository source root"); - } - return candidate; - } -} diff --git a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/jpa/JpaTestLanesPluginFunctionalTest.java b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/jpa/JpaTestLanesPluginFunctionalTest.java deleted file mode 100644 index 09b37cf8..00000000 --- a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/jpa/JpaTestLanesPluginFunctionalTest.java +++ /dev/null @@ -1,118 +0,0 @@ -package dev.caskeleton.buildlogic.jpa; - -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.nio.file.Files; -import java.nio.file.Path; -import org.gradle.testkit.runner.BuildResult; -import org.gradle.testkit.runner.GradleRunner; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -class JpaTestLanesPluginFunctionalTest { - @Test - void pluginOwnsTypedJpaLaneModelAndRuntimeProperties(@TempDir Path projectDir) throws Exception { - Files.writeString(projectDir.resolve("settings.gradle"), "rootProject.name='fixture'\n"); - Files.writeString( - projectDir.resolve("build.gradle"), - """ - plugins { - id 'java' - id 'ca.jpa-test-lanes' - } - - sourceSets { - postgresqlIntegrationTest - jpaPlatformPerformanceTest - } - - tasks.register('verifyJpaLaneModel') { - doLast { - assert strictTestLanes.lanes.size() == 26 - - def security = strictTestLanes.lanes.getByName('postgresqlSecurityBaselineIntegrationTest') - assert security.requiredTests == [ - 'dev.caskeleton.adapter.outbound.persistence.readiness.PostgreSqlSecurityBaselineIntegrationTest', - 'dev.caskeleton.adapter.outbound.persistence.readiness.PostgreSqlSecurityBaselineIntegrationTest.runtimeRoleCannotCreateInApplicationSchemaOrTempAndUsesTrustedSearchPath' - ] - - def platform = strictTestLanes.lanes.getByName('jpaPlatformContractTest') - assert platform.tag == 'jpa-contract' - assert platform.sourceSet == 'postgresqlIntegrationTest' - - def readiness = strictTestLanes.lanes.getByName('postgresqlLifecycleIntegrationTest') - assert readiness.jvmArgs.contains('-Duser.timezone=UTC') - assert readiness.jvmArgs.contains('-Djpa.evidence.postgresql.image=postgres:17-alpine') - - def movedMigration = strictTestLanes.lanes.getByName( - 'postgresqlIntLockMigrationCompatibilityIntegrationTest') - assert movedMigration.sourceSet == 'postgresqlIntegrationTest' - assert movedMigration.category.toString() == 'INTEGRATION' - assert movedMigration.requiredTests == [ - 'dev.caskeleton.adapter.outbound.persistence.readiness.PostgreSqlIntLockMigrationCompatibilityIntegrationTest' - ] - - def legacyAppend = strictTestLanes.lanes.getByName( - 'postgresqlLegacyOutboxAppendTransactionalIntegrationTest') - assert legacyAppend.requiredTests == [ - 'dev.caskeleton.adapter.outbound.persistence.readiness.PostgreSqlLegacyOutboxAppendTransactionalIntegrationTest' - ] - - def legacyConcurrentRelay = strictTestLanes.lanes.getByName( - 'postgresqlLegacyOutboxConcurrentRelayIntegrationTest') - assert legacyConcurrentRelay.requiredTests == [ - 'dev.caskeleton.adapter.outbound.persistence.readiness.PostgreSqlLegacyOutboxConcurrentRelayIntegrationTest' - ] - - def legacyLifecycle = strictTestLanes.lanes.getByName( - 'postgresqlLegacyOutboxRowLifecycleIntegrationTest') - assert legacyLifecycle.requiredTests == [ - 'dev.caskeleton.adapter.outbound.persistence.readiness.PostgreSqlLegacyOutboxRowLifecycleIntegrationTest' - ] - - def movedLock = strictTestLanes.lanes.getByName( - 'postgresqlDistributedLockIntegrationTest') - assert movedLock.sourceSet == 'postgresqlIntegrationTest' - assert movedLock.category.toString() == 'INTEGRATION' - assert movedLock.requiredTests == [ - 'dev.caskeleton.adapter.outbound.persistence.readiness.PostgreSqlDistributedLockIntegrationTest' - ] - - def movedIdempotency = strictTestLanes.lanes.getByName( - 'postgresqlIdempotencyUniqueScopeIntegrationTest') - assert movedIdempotency.sourceSet == 'postgresqlIntegrationTest' - assert movedIdempotency.category.toString() == 'INTEGRATION' - assert movedIdempotency.requiredTests == [ - 'dev.caskeleton.adapter.outbound.persistence.readiness.PostgreSqlIdempotencyUniqueScopeIntegrationTest' - ] - - def readinessTask = tasks.named('postgresqlLifecycleIntegrationTest', Test).get() - assert readinessTask.allJvmArgs.contains('-Duser.timezone=UTC') - assert readinessTask.allJvmArgs.contains('-Djpa.evidence.postgresql.image=postgres:17-alpine') - - assert platform.systemProperties['jpa.matrix.versions'] == '15,16' - def platformTask = tasks.named('jpaPlatformContractTest', Test).get() - assert platformTask.systemProperties['jpa.matrix.versions'] == '15,16' - - def pool = strictTestLanes.lanes.getByName('jpaPlatformPoolContractTest') - assert pool.sourceSet == 'jpaPlatformPerformanceTest' - assert pool.category.toString() == 'PERFORMANCE' - assert pool.jvmArgs.contains('-Duser.timezone=UTC') - } - } - """); - - BuildResult result = - GradleRunner.create() - .withProjectDir(projectDir.toFile()) - .withPluginClasspath() - .withArguments( - "verifyJpaLaneModel", - "-PjpaPostgreSqlEvidenceImage=postgres:17-alpine", - "-Pjpa.matrix.versions=15,16", - "--console=plain") - .build(); - - assertTrue(result.getOutput().contains("BUILD SUCCESSFUL"), result.getOutput()); - } -} diff --git a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/redis/RedisTopologyContractTest.java b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/redis/RedisTopologyContractTest.java index 0e095953..07a6533a 100644 --- a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/redis/RedisTopologyContractTest.java +++ b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/redis/RedisTopologyContractTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import java.util.List; import java.util.Set; import org.junit.jupiter.api.Test; @@ -14,16 +15,32 @@ class RedisTopologyContractTest { assertTrue(RedisTopologyContract.tlsEnabled("tls")); } + private static final Set ALL_MODES = Set.of("standalone", "sentinel", "cluster", "tls"); + @Test void unknownModeFailsClosed() { IllegalStateException failure = assertThrows( IllegalStateException.class, - () -> RedisTopologyContract.validateInvocation("typo", Set.of())); + () -> RedisTopologyContract.validateInvocation("typo", ALL_MODES, Set.of())); assertTrue(failure.getMessage().contains("supported modes are cluster, sentinel, standalone, tls")); } + @Test + void aModeTheLeafDoesNotDeclareFailsClosed() { + IllegalStateException failure = + assertThrows( + IllegalStateException.class, + () -> + RedisTopologyContract.validateInvocation( + "tls", + Set.of("standalone", "cluster"), + Set.of("redis.topology.host", "redis.topology.port"))); + + assertTrue(failure.getMessage().contains("has no tls lane; it declares cluster, standalone")); + } + @Test void sentinelRequiresMasterAlongsideEndpoint() { IllegalStateException failure = @@ -31,7 +48,7 @@ class RedisTopologyContractTest { IllegalStateException.class, () -> RedisTopologyContract.validateInvocation( - "sentinel", Set.of("redis.topology.host", "redis.topology.port"))); + "sentinel", ALL_MODES, Set.of("redis.topology.host", "redis.topology.port"))); assertTrue(failure.getMessage().contains("redis.topology.master")); } @@ -43,7 +60,7 @@ class RedisTopologyContractTest { IllegalStateException.class, () -> RedisTopologyContract.validateInvocation( - "tls", Set.of("redis.topology.host", "redis.topology.port"))); + "tls", ALL_MODES, Set.of("redis.topology.host", "redis.topology.port"))); assertTrue(failure.getMessage().contains("redis.topology.trust-material")); } @@ -55,7 +72,7 @@ class RedisTopologyContractTest { IllegalStateException.class, () -> RedisTopologyContract.verifyExecution( - "tls", Set.of("SomeOtherClass"), 0)); + "tls", List.of("LiveRedisTlsTest"), Set.of("SomeOtherClass"), 0)); assertTrue(missingClass.getMessage().contains("LiveRedisTlsTest")); IllegalStateException skipped = @@ -63,7 +80,7 @@ class RedisTopologyContractTest { IllegalStateException.class, () -> RedisTopologyContract.verifyExecution( - "tls", Set.of("LiveRedisTlsTest"), 1)); + "tls", List.of("LiveRedisTlsTest"), Set.of("LiveRedisTlsTest"), 1)); assertTrue(skipped.getMessage().contains("skipped 1 test(s)")); } } diff --git a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/redis/RedisTopologyLanePluginFunctionalTest.java b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/redis/RedisTopologyLanePluginFunctionalTest.java index 7cac08ed..d8ca5e7b 100644 --- a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/redis/RedisTopologyLanePluginFunctionalTest.java +++ b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/redis/RedisTopologyLanePluginFunctionalTest.java @@ -33,7 +33,7 @@ class RedisTopologyLanePluginFunctionalTest { assertTrue(result.getOutput().contains("redisTopologyTest"), result.getOutput()); assertTrue( - result.getOutput().contains("Runs the Redis SDK contracts against a real topology"), + result.getOutput().contains("Redis contracts against a real topology"), result.getOutput()); } @@ -55,6 +55,7 @@ class RedisTopologyLanePluginFunctionalTest { result.getOutput()); } + private GradleRunner runner(String... arguments) { return GradleRunner.create() .withProjectDir(projectDir.toFile()) diff --git a/src/build-tools/build.gradle b/src/build-tools/build.gradle index 8f444b01..7a81543a 100644 --- a/src/build-tools/build.gradle +++ b/src/build-tools/build.gradle @@ -14,10 +14,6 @@ dependencies { gradlePlugin { plugins { - notificationConfiguration { - id = 'ca.notification-configuration' - implementationClass = 'dev.caskeleton.buildtools.notificationconfig.NotificationConfigurationPlugin' - } jpaEvidence { id = 'ca.jpa-evidence' implementationClass = 'dev.caskeleton.buildtools.jpa.JpaEvidencePlugin' @@ -26,30 +22,10 @@ gradlePlugin { id = 'ca.config-contract' implementationClass = 'dev.caskeleton.buildtools.config.ConfigContractPlugin' } - notificationEvidence { - id = 'ca.notification-evidence' - implementationClass = 'dev.caskeleton.buildtools.notification.NotificationEvidencePlugin' - } - notificationApiSurface { - id = 'ca.notification-api-surface' - implementationClass = 'dev.caskeleton.buildtools.notification.NotificationApiSurfacePlugin' - } jpaQualification { id = 'ca.jpa-qualification' implementationClass = 'dev.caskeleton.buildtools.jpa.JpaQualificationPlugin' } - messagingQualification { - id = 'ca.messaging-qualification' - implementationClass = 'dev.caskeleton.buildtools.messaging.MessagingQualificationPlugin' - } - messagingCertification { - id = 'ca.messaging-certification' - implementationClass = 'dev.caskeleton.buildtools.messaging.MessagingCertificationPlugin' - } - mongoVerification { - id = 'ca.mongo-verification' - implementationClass = 'dev.caskeleton.buildtools.mongo.MongoVerificationPlugin' - } } } diff --git a/src/build-tools/src/main/java/dev/caskeleton/buildtools/config/ConfigContractPlugin.java b/src/build-tools/src/main/java/dev/caskeleton/buildtools/config/ConfigContractPlugin.java index b9dba92c..047ea76a 100644 --- a/src/build-tools/src/main/java/dev/caskeleton/buildtools/config/ConfigContractPlugin.java +++ b/src/build-tools/src/main/java/dev/caskeleton/buildtools/config/ConfigContractPlugin.java @@ -30,6 +30,18 @@ public final class ConfigContractPlugin implements Plugin { tree -> { tree.include("application*.yml"); tree.include("config/*.yml"); + }), + // Settings a capability module ships: config/module-defaults/.yml + // (read by ModuleDefaultsEnvironmentPostProcessor), or config/.yml for + // the leaves that load their own. They are shipped configuration whenever the + // module is selected, so their APP_ references are held to the same registry. + root.fileTree( + root.getProjectDir(), + tree -> { + tree.include("*/**/src/main/resources/config/*.yml"); + tree.include("*/**/src/main/resources/config/module-defaults/*.yml"); + tree.exclude("app-bootstrap/**"); + tree.exclude("**/build/**"); })); task.getRegistryFile().fileValue(root.file("../docs/registries/env-keys.yaml")); task.getRedisSdkMetadata() diff --git a/src/build-tools/src/main/java/dev/caskeleton/buildtools/jpa/JpaAdopterApiSurfaceVerifier.java b/src/build-tools/src/main/java/dev/caskeleton/buildtools/jpa/JpaAdopterApiSurfaceVerifier.java deleted file mode 100644 index eab32ea9..00000000 --- a/src/build-tools/src/main/java/dev/caskeleton/buildtools/jpa/JpaAdopterApiSurfaceVerifier.java +++ /dev/null @@ -1,57 +0,0 @@ -package dev.caskeleton.buildtools.jpa; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.Collection; -import java.util.Set; -import java.util.TreeSet; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -final class JpaAdopterApiSurfaceVerifier { - - private static final String PREFIX = "dev.caskeleton.adapter.outbound.persistence."; - private static final Pattern IMPORT = - Pattern.compile("^\\s*import\\s+(" + Pattern.quote(PREFIX) + "[A-Za-z0-9_$.]+)\\s*;\\s*$"); - - private JpaAdopterApiSurfaceVerifier() {} - - static Set importedTypes(Collection sources) throws IOException { - Set imports = new TreeSet<>(); - for (Path source : sources) { - for (String line : Files.readAllLines(source)) { - Matcher matcher = IMPORT.matcher(line); - if (matcher.matches()) { - imports.add(matcher.group(1)); - } - } - } - return imports; - } - - static Set baselineTypes(Path baseline) throws IOException { - Set allowed = new TreeSet<>(); - for (String line : Files.readAllLines(baseline)) { - String value = line.trim(); - if (!value.isEmpty() && !value.startsWith("#")) { - allowed.add(value); - } - } - return allowed; - } - - static void verify(Collection sources, Path baseline) throws IOException { - Set imported = importedTypes(sources); - Set allowed = baselineTypes(baseline); - Set unexpected = new TreeSet<>(imported); - unexpected.removeAll(allowed); - if (!unexpected.isEmpty()) { - throw new IllegalStateException( - "JPA adopter API surface grew without review: " - + unexpected - + ". Add only intentionally supported adopter types to " - + baseline); - } - } -} diff --git a/src/build-tools/src/main/java/dev/caskeleton/buildtools/jpa/JpaQualificationPlugin.java b/src/build-tools/src/main/java/dev/caskeleton/buildtools/jpa/JpaQualificationPlugin.java index 25fc2318..b04e42fc 100644 --- a/src/build-tools/src/main/java/dev/caskeleton/buildtools/jpa/JpaQualificationPlugin.java +++ b/src/build-tools/src/main/java/dev/caskeleton/buildtools/jpa/JpaQualificationPlugin.java @@ -54,38 +54,6 @@ public final class JpaQualificationPlugin implements Plugin { task.getRegistryFile().fileValue(root.file("config/jpa/readiness-cards.yaml")); }); - TaskProvider adopterApiSurface = - project - .getTasks() - .register( - "verifyJpaAdopterApiSurface", - VerifyJpaAdopterApiSurfaceTask.class, - task -> { - task.setGroup("verification"); - task.setDescription( - "Rejects production imports of unsupported JPA persistence implementation" - + " types."); - task.getProductionSources() - .from( - root.fileTree( - ".", - tree -> { - tree.include("**/src/main/java/**/*.java"); - tree.exclude("**/build/**"); - // The leaves that own JPA persistence implementations, excluded - // because they are the implementation rather than an adopter of - // one. There are two: the Fileserver capability's entities, - // repositories and adapters moved out of persistence-jpa into their - // own leaf, and a module cannot be an unsupported consumer of the - // types it declares. This is ownership, not an allowance — the - // baseline file still governs every other module's imports. - tree.exclude("adapter/outbound/persistence-jpa/**"); - tree.exclude("adapter/outbound/persistence-fileserver/**"); - })); - task.getBaseline() - .fileValue(root.file("../docs/architecture/jpa-adopter-api-surface.txt")); - }); - project .getGradle() .projectsEvaluated( @@ -99,10 +67,6 @@ public final class JpaQualificationPlugin implements Plugin { }); readinessRegistry.configure( task -> task.getAvailableTaskPaths().set(snapshot.taskPaths())); - root.project(":adapter:outbound:persistence-jpa") - .getTasks() - .named("check") - .configure(task -> task.dependsOn(adopterApiSurface)); JpaReleaseRegistry registry = readReleaseRegistry(root); releaseQualification.configure( diff --git a/src/build-tools/src/main/java/dev/caskeleton/buildtools/jpa/JpaReadinessRegistryValidator.java b/src/build-tools/src/main/java/dev/caskeleton/buildtools/jpa/JpaReadinessRegistryValidator.java index 61ad8314..c1ad360b 100644 --- a/src/build-tools/src/main/java/dev/caskeleton/buildtools/jpa/JpaReadinessRegistryValidator.java +++ b/src/build-tools/src/main/java/dev/caskeleton/buildtools/jpa/JpaReadinessRegistryValidator.java @@ -43,14 +43,6 @@ public final class JpaReadinessRegistryValidator { } detectCycles(cardsById, violations); - JpaReadinessCard polling = cardsById.get("jpa-outbox-polling-delivery-v2"); - JpaReadinessCard cdc = cardsById.get("jpa-outbox-cdc-retention-v1"); - if (polling != null - && cdc != null - && polling.state() == JpaCardState.SELECTED - && cdc.state() == JpaCardState.SELECTED) { - violations.add("polling and CDC outbox delivery cards cannot both be selected"); - } return List.copyOf(violations); } diff --git a/src/build-tools/src/main/java/dev/caskeleton/buildtools/jpa/VerifyJpaAdopterApiSurfaceTask.java b/src/build-tools/src/main/java/dev/caskeleton/buildtools/jpa/VerifyJpaAdopterApiSurfaceTask.java deleted file mode 100644 index 8e995475..00000000 --- a/src/build-tools/src/main/java/dev/caskeleton/buildtools/jpa/VerifyJpaAdopterApiSurfaceTask.java +++ /dev/null @@ -1,36 +0,0 @@ -package dev.caskeleton.buildtools.jpa; - -import java.io.IOException; -import java.io.UncheckedIOException; -import java.nio.file.Path; -import java.util.List; -import org.gradle.api.DefaultTask; -import org.gradle.api.file.ConfigurableFileCollection; -import org.gradle.api.file.RegularFileProperty; -import org.gradle.api.tasks.InputFile; -import org.gradle.api.tasks.InputFiles; -import org.gradle.api.tasks.PathSensitive; -import org.gradle.api.tasks.PathSensitivity; -import org.gradle.api.tasks.TaskAction; - -public abstract class VerifyJpaAdopterApiSurfaceTask extends DefaultTask { - - @InputFiles - @PathSensitive(PathSensitivity.RELATIVE) - public abstract ConfigurableFileCollection getProductionSources(); - - @InputFile - @PathSensitive(PathSensitivity.RELATIVE) - public abstract RegularFileProperty getBaseline(); - - @TaskAction - void verify() { - List sources = - getProductionSources().getFiles().stream().map(file -> file.toPath()).sorted().toList(); - try { - JpaAdopterApiSurfaceVerifier.verify(sources, getBaseline().get().getAsFile().toPath()); - } catch (IOException exception) { - throw new UncheckedIOException("failed to verify JPA adopter API surface", exception); - } - } -} diff --git a/src/build-tools/src/main/java/dev/caskeleton/buildtools/messaging/MessagingBuildEvidenceManifest.java b/src/build-tools/src/main/java/dev/caskeleton/buildtools/messaging/MessagingBuildEvidenceManifest.java deleted file mode 100644 index edd13b39..00000000 --- a/src/build-tools/src/main/java/dev/caskeleton/buildtools/messaging/MessagingBuildEvidenceManifest.java +++ /dev/null @@ -1,32 +0,0 @@ -package dev.caskeleton.buildtools.messaging; - -import java.util.List; -import java.util.Objects; - -public record MessagingBuildEvidenceManifest( - int schemaVersion, - String sourceDigest, - String artifactDigest, - String producerTask, - List scenarioIds, - MessagingEvidenceCounts counts, - String command, - String generatedAt, - MessagingEvidenceHashes hashes, - List failures, - List skips, - List unsupportedClaims) { - public MessagingBuildEvidenceManifest { - Objects.requireNonNull(sourceDigest, "sourceDigest"); - Objects.requireNonNull(artifactDigest, "artifactDigest"); - Objects.requireNonNull(producerTask, "producerTask"); - scenarioIds = List.copyOf(scenarioIds); - Objects.requireNonNull(counts, "counts"); - Objects.requireNonNull(command, "command"); - Objects.requireNonNull(generatedAt, "generatedAt"); - Objects.requireNonNull(hashes, "hashes"); - failures = List.copyOf(failures); - skips = List.copyOf(skips); - unsupportedClaims = List.copyOf(unsupportedClaims); - } -} diff --git a/src/build-tools/src/main/java/dev/caskeleton/buildtools/messaging/MessagingCertificationPlugin.java b/src/build-tools/src/main/java/dev/caskeleton/buildtools/messaging/MessagingCertificationPlugin.java deleted file mode 100644 index 255f40f5..00000000 --- a/src/build-tools/src/main/java/dev/caskeleton/buildtools/messaging/MessagingCertificationPlugin.java +++ /dev/null @@ -1,29 +0,0 @@ -package dev.caskeleton.buildtools.messaging; - -import org.gradle.api.Plugin; -import org.gradle.api.Project; - -public final class MessagingCertificationPlugin implements Plugin { - @Override - public void apply(Project project) { - project.getTasks().register( - "verifyMessagingCertificationEvidence", - VerifyMessagingCertificationEvidenceTask.class, - task -> { - task.setGroup("verification"); - task.setDescription( - "Fails when the committed broker certification manifest claims a scenario the certification lane did not produce."); - task.dependsOn("messagingCertificationTest"); - task.getProducedManifest() - .set(project.getLayout().getBuildDirectory().file( - "messaging-certification/broker-certification-evidence.jsonl")); - task.getCommittedManifest() - .fileValue(project.getRootProject().file( - "messaging/messaging-testkit/src/main/resources/messaging/broker-certification-evidence.jsonl")); - task.getReportFile() - .set(project.getLayout().getBuildDirectory().file( - "reports/messaging-certification-evidence.txt")); - task.getOutputs().upToDateWhen(ignored -> false); - }); - } -} diff --git a/src/build-tools/src/main/java/dev/caskeleton/buildtools/messaging/MessagingEvidenceCounts.java b/src/build-tools/src/main/java/dev/caskeleton/buildtools/messaging/MessagingEvidenceCounts.java deleted file mode 100644 index 5b2cd339..00000000 --- a/src/build-tools/src/main/java/dev/caskeleton/buildtools/messaging/MessagingEvidenceCounts.java +++ /dev/null @@ -1,15 +0,0 @@ -package dev.caskeleton.buildtools.messaging; - -import com.fasterxml.jackson.annotation.JsonIgnore; - -public record MessagingEvidenceCounts(int executed, int passed, int failed, int skipped) { - @JsonIgnore - public int totalOutcomes() { - return passed + failed + skipped; - } - - @JsonIgnore - public boolean isPassing() { - return failed == 0 && skipped == 0; - } -} diff --git a/src/build-tools/src/main/java/dev/caskeleton/buildtools/messaging/MessagingEvidenceHasher.java b/src/build-tools/src/main/java/dev/caskeleton/buildtools/messaging/MessagingEvidenceHasher.java deleted file mode 100644 index 6e1e69ae..00000000 --- a/src/build-tools/src/main/java/dev/caskeleton/buildtools/messaging/MessagingEvidenceHasher.java +++ /dev/null @@ -1,66 +0,0 @@ -package dev.caskeleton.buildtools.messaging; - -import java.io.File; -import java.io.IOException; -import java.io.UncheckedIOException; -import java.nio.ByteBuffer; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.Comparator; -import java.util.HexFormat; -import java.util.List; - -public final class MessagingEvidenceHasher { - private MessagingEvidenceHasher() {} - - public static String sha256Bytes(byte[] bytes) { - MessageDigest digest = digest(); - return "sha256:" + HexFormat.of().formatHex(digest.digest(bytes)); - } - - public static String sha256FileSet( - String domain, File rootDirectory, List files) { - MessageDigest digest = digest(); - digest.update(domain.getBytes(StandardCharsets.UTF_8)); - digest.update((byte) 0); - List sorted = - files.stream() - .sorted(Comparator.comparing(file -> relativePath(rootDirectory, file))) - .toList(); - for (File input : sorted) { - if (!input.isFile()) { - throw new IllegalStateException( - "Messaging evidence input is missing: " + relativePath(rootDirectory, input)); - } - byte[] path = relativePath(rootDirectory, input).getBytes(StandardCharsets.UTF_8); - byte[] content; - try { - content = Files.readAllBytes(input.toPath()); - } catch (IOException exception) { - throw new UncheckedIOException("failed to read " + input, exception); - } - digest.update(ByteBuffer.allocate(Integer.BYTES).putInt(path.length).array()); - digest.update(path); - digest.update(ByteBuffer.allocate(Integer.BYTES).putInt(content.length).array()); - digest.update(content); - } - return "sha256:" + HexFormat.of().formatHex(digest.digest()); - } - - private static String relativePath(File rootDirectory, File file) { - return rootDirectory.toPath().toAbsolutePath().normalize() - .relativize(file.toPath().toAbsolutePath().normalize()) - .toString() - .replace(File.separatorChar, '/'); - } - - private static MessageDigest digest() { - try { - return MessageDigest.getInstance("SHA-256"); - } catch (NoSuchAlgorithmException exception) { - throw new IllegalStateException("SHA-256 is unavailable", exception); - } - } -} diff --git a/src/build-tools/src/main/java/dev/caskeleton/buildtools/messaging/MessagingEvidenceHashes.java b/src/build-tools/src/main/java/dev/caskeleton/buildtools/messaging/MessagingEvidenceHashes.java deleted file mode 100644 index 10585c08..00000000 --- a/src/build-tools/src/main/java/dev/caskeleton/buildtools/messaging/MessagingEvidenceHashes.java +++ /dev/null @@ -1,13 +0,0 @@ -package dev.caskeleton.buildtools.messaging; - -import java.util.Objects; - -public record MessagingEvidenceHashes( - String profile, String catalog, String schema, String settings) { - public MessagingEvidenceHashes { - Objects.requireNonNull(profile, "profile"); - Objects.requireNonNull(catalog, "catalog"); - Objects.requireNonNull(schema, "schema"); - Objects.requireNonNull(settings, "settings"); - } -} diff --git a/src/build-tools/src/main/java/dev/caskeleton/buildtools/messaging/MessagingEvidenceManifest.java b/src/build-tools/src/main/java/dev/caskeleton/buildtools/messaging/MessagingEvidenceManifest.java deleted file mode 100644 index 42aa4d66..00000000 --- a/src/build-tools/src/main/java/dev/caskeleton/buildtools/messaging/MessagingEvidenceManifest.java +++ /dev/null @@ -1,21 +0,0 @@ -package dev.caskeleton.buildtools.messaging; - -import java.time.Instant; -import java.util.List; -import java.util.Objects; - -public record MessagingEvidenceManifest( - String producerTask, - MessagingEvidenceCounts counts, - List failures, - List skips, - Instant generatedAt) { - - public MessagingEvidenceManifest { - Objects.requireNonNull(producerTask, "producerTask"); - Objects.requireNonNull(counts, "counts"); - failures = List.copyOf(failures); - skips = List.copyOf(skips); - Objects.requireNonNull(generatedAt, "generatedAt"); - } -} diff --git a/src/build-tools/src/main/java/dev/caskeleton/buildtools/messaging/MessagingEvidenceResultEntry.java b/src/build-tools/src/main/java/dev/caskeleton/buildtools/messaging/MessagingEvidenceResultEntry.java deleted file mode 100644 index 3744d963..00000000 --- a/src/build-tools/src/main/java/dev/caskeleton/buildtools/messaging/MessagingEvidenceResultEntry.java +++ /dev/null @@ -1,10 +0,0 @@ -package dev.caskeleton.buildtools.messaging; - -import java.util.Objects; - -public record MessagingEvidenceResultEntry(String scenarioId, String reason) { - public MessagingEvidenceResultEntry { - Objects.requireNonNull(scenarioId, "scenarioId"); - Objects.requireNonNull(reason, "reason"); - } -} diff --git a/src/build-tools/src/main/java/dev/caskeleton/buildtools/messaging/MessagingEvidenceVerifier.java b/src/build-tools/src/main/java/dev/caskeleton/buildtools/messaging/MessagingEvidenceVerifier.java deleted file mode 100644 index 5766ff64..00000000 --- a/src/build-tools/src/main/java/dev/caskeleton/buildtools/messaging/MessagingEvidenceVerifier.java +++ /dev/null @@ -1,53 +0,0 @@ -package dev.caskeleton.buildtools.messaging; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; - -/** Semantic rules for Messaging evidence that JSON Schema cannot express. */ -public final class MessagingEvidenceVerifier { - private MessagingEvidenceVerifier() {} - - public static List scenarioIds(Collection selectors) { - List ids = - selectors.stream() - .map(MessagingEvidenceVerifier::scenarioId) - .sorted() - .toList(); - if (new HashSet<>(ids).size() != ids.size()) { - throw new IllegalArgumentException("Messaging qualification scenario IDs are not unique."); - } - return ids; - } - - public static List validate( - MessagingEvidenceManifest manifest, String expectedProducer) { - List violations = new ArrayList<>(); - if (!manifest.producerTask().equals(expectedProducer)) { - violations.add( - "producerTask is '" - + manifest.producerTask() - + "', not '" - + expectedProducer - + "'"); - } - if (manifest.counts().executed() != manifest.counts().totalOutcomes()) { - violations.add("counts do not add up: " + manifest.counts()); - } - if (!manifest.counts().isPassing() - || !manifest.failures().isEmpty() - || !manifest.skips().isEmpty()) { - violations.add("failed or skipped qualification cannot produce PASS evidence"); - } - return List.copyOf(violations); - } - - private static String scenarioId(String selector) { - String withoutPackage = selector.replaceFirst("^.*\\.", ""); - return withoutPackage - .replace('#', '.') - .replaceAll("[^A-Za-z0-9._:-]", "-") - .replaceAll("-+", "-"); - } -} diff --git a/src/build-tools/src/main/java/dev/caskeleton/buildtools/messaging/MessagingQualificationPlugin.java b/src/build-tools/src/main/java/dev/caskeleton/buildtools/messaging/MessagingQualificationPlugin.java deleted file mode 100644 index 5b889800..00000000 --- a/src/build-tools/src/main/java/dev/caskeleton/buildtools/messaging/MessagingQualificationPlugin.java +++ /dev/null @@ -1,192 +0,0 @@ -package dev.caskeleton.buildtools.messaging; - -import java.io.File; -import java.util.List; -import org.gradle.api.Plugin; -import org.gradle.api.Project; -import org.gradle.api.plugins.JavaPluginExtension; -import org.gradle.api.tasks.JavaExec; -import org.gradle.api.tasks.SourceSet; -import org.gradle.api.tasks.TaskProvider; - -public final class MessagingQualificationPlugin implements Plugin { - private static final String SCHEMA_VALIDATOR_MAIN = - "dev.caskeleton.adapter.outbound.messaging.qualification.MessagingEvidenceManifestSchemaValidator"; - - @Override - public void apply(Project project) { - Project root = project.getRootProject(); - var resultRoot = root.getLayout().getBuildDirectory().dir("test-results/messaging-evidence"); - var evidenceFile = - root.getLayout().getBuildDirectory().file("messaging-evidence/contracts-schema/manifest.json"); - File profileFile = root.file("config/messaging/profile-compatibility.yaml"); - File commonSchema = - root.file("config/messaging/evidence/build-evidence-manifest-v1.schema.json"); - - TaskProvider prepare = - project - .getTasks() - .register( - "prepareMessagingContractEvidence", - PrepareMessagingContractEvidenceTask.class, - task -> { - task.setGroup("verification"); - task.getEvidenceFile().set(evidenceFile); - task.getProfileFile().fileValue(profileFile); - task.getSourceDigest() - .convention(project.getProviders().gradleProperty("messagingSourceDigest").orElse("")); - task.getArtifactDigest() - .convention(project.getProviders().gradleProperty("messagingArtifactDigest").orElse("")); - task.getProfileHash() - .convention(project.getProviders().gradleProperty("messagingProfileHash").orElse("")); - task.getOutputs().upToDateWhen(ignored -> false); - }); - - TaskProvider json = - registerEvidenceTask( - project, - "verifyMessagingJsonSchemaV1", - "Qualifies the deterministic local Draft 2020-12 envelope candidate.", - List.of("json-schema"), - List.of( - ":adapter:outbound:messaging:messagingJsonSchemaV1QualificationTest", - "verifyMessagingJsonSchemaV1"), - List.of( - ":adapter:outbound:messaging:messagingJsonSchemaV1QualificationTest", - ":adapter:outbound:messaging:verifyDependencyPolicy"), - resultRoot, - evidenceFile, - profileFile, - commonSchema); - - TaskProvider validateJson = - registerSchemaValidation( - project, - "validateMessagingJsonSchemaV1EvidenceManifestSchema", - "Validates the exact generated JSON qualification manifest bytes against the common Draft 2020-12 schema.", - json, - commonSchema, - evidenceFile); - json.configure(task -> task.finalizedBy(validateJson)); - - TaskProvider contracts = - registerEvidenceTask( - project, - "verifyMessagingContracts", - "Qualifies the closed Task 3-6 contract, catalog, binding and schema candidate.", - List.of("application", "shared", "compiled", "json-schema"), - List.of( - ":application-core:messagingApplicationContractQualificationTest", - ":shared-contract:messagingSharedSchemaQualificationTest", - ":adapter:outbound:messaging:messagingCompiledContractsQualificationTest", - ":adapter:outbound:messaging:messagingJsonSchemaV1QualificationTest", - "verifyMessagingContracts"), - List.of( - validateJson, - ":application-core:messagingApplicationContractQualificationTest", - ":shared-contract:messagingSharedSchemaQualificationTest", - ":adapter:outbound:messaging:messagingCompiledContractsQualificationTest", - ":adapter:outbound:messaging:messagingJsonSchemaV1QualificationTest", - ":adapter:outbound:messaging:verifyDependencyPolicy"), - resultRoot, - evidenceFile, - profileFile, - commonSchema); - - TaskProvider validateContracts = - registerSchemaValidation( - project, - "validateMessagingContractsEvidenceManifestSchema", - "Validates the exact generated combined qualification manifest bytes against the common Draft 2020-12 schema.", - contracts, - commonSchema, - evidenceFile); - contracts.configure(task -> task.finalizedBy(validateContracts)); - } - - private static TaskProvider registerEvidenceTask( - Project project, - String name, - String description, - List resultDirectories, - List commandTasks, - List dependencies, - org.gradle.api.provider.Provider resultRoot, - org.gradle.api.provider.Provider evidenceFile, - File profileFile, - File commonSchema) { - Project root = project.getRootProject(); - return project - .getTasks() - .register( - name, - VerifyMessagingEvidenceTask.class, - task -> { - task.setGroup("verification"); - task.setDescription(description); - dependencies.forEach(task::dependsOn); - task.getProducerTaskName().set(name); - task.getResultDirectories().set(resultDirectories); - task.getCommandTasks().set(commandTasks); - task.getSourceDigest() - .convention(project.getProviders().gradleProperty("messagingSourceDigest").orElse("")); - task.getArtifactDigest() - .convention(project.getProviders().gradleProperty("messagingArtifactDigest").orElse("")); - task.getProfileHash() - .convention(project.getProviders().gradleProperty("messagingProfileHash").orElse("")); - task.getProfileFile().fileValue(profileFile); - task.getCommonSchemaFile().fileValue(commonSchema); - task.getProjectRootDirectory().set(root.getLayout().getProjectDirectory()); - task.getResultRootDirectory().set(resultRoot); - task.getEvidenceFile().set(evidenceFile); - task.getCatalogFiles().from(root.file("config/messaging/readiness-cards.yaml")); - task.getSchemaFiles() - .from( - root.file( - "shared-contract/src/main/resources/contracts/messaging/envelope/v1.schema.json"), - root.fileTree( - "adapter/outbound/messaging/src/main/resources/contracts/messaging/meta/draft-2020-12")); - task.getSettingsFiles() - .from( - root.file("adapter/outbound/messaging/build.gradle"), - root.file("adapter/outbound/messaging/gradle.lockfile")); - task.getOutputs().upToDateWhen(ignored -> false); - }); - } - - private static TaskProvider registerSchemaValidation( - Project project, - String name, - String description, - TaskProvider producer, - File commonSchema, - org.gradle.api.provider.Provider evidenceFile) { - return project - .getTasks() - .register( - name, - JavaExec.class, - task -> { - task.setGroup("verification"); - task.setDescription(description); - task.dependsOn(producer); - task.getMainClass().set(SCHEMA_VALIDATOR_MAIN); - task.args(commonSchema.getAbsolutePath(), evidenceFile.get().getAsFile().getAbsolutePath()); - task.getInputs().file(commonSchema); - task.getInputs().file(evidenceFile); - task.getOutputs().upToDateWhen(ignored -> false); - task.setClasspath( - project.files( - project.provider( - () -> { - Project messaging = - project.getRootProject().project(":adapter:outbound:messaging"); - JavaPluginExtension java = - messaging.getExtensions().getByType(JavaPluginExtension.class); - return java.getSourceSets() - .getByName(SourceSet.TEST_SOURCE_SET_NAME) - .getRuntimeClasspath(); - }))); - }); - } -} diff --git a/src/build-tools/src/main/java/dev/caskeleton/buildtools/messaging/MessagingQualificationReader.java b/src/build-tools/src/main/java/dev/caskeleton/buildtools/messaging/MessagingQualificationReader.java deleted file mode 100644 index 73a2de68..00000000 --- a/src/build-tools/src/main/java/dev/caskeleton/buildtools/messaging/MessagingQualificationReader.java +++ /dev/null @@ -1,37 +0,0 @@ -package dev.caskeleton.buildtools.messaging; - -import dev.caskeleton.buildtools.junit.JUnitEvidenceReader; -import dev.caskeleton.buildtools.junit.JUnitEvidenceResult; -import java.io.File; -import java.util.List; -import java.util.Set; -import java.util.TreeSet; - -public final class MessagingQualificationReader { - private MessagingQualificationReader() {} - - public static MessagingQualificationResult read( - File resultRoot, List resultDirectories) { - int executed = 0; - int failed = 0; - int skipped = 0; - Set selectors = new TreeSet<>(); - for (String directory : resultDirectories) { - File resultDirectory = new File(resultRoot, directory); - JUnitEvidenceResult result = - JUnitEvidenceReader.read("messaging-evidence/" + directory, resultDirectory); - executed += result.tests(); - failed += result.failures() + result.errors(); - skipped += result.skipped(); - selectors.addAll(result.executedSelectors()); - } - if (executed <= 0) { - throw new IllegalStateException( - "Messaging qualification XML contains no discovered test cases."); - } - List scenarioIds = MessagingEvidenceVerifier.scenarioIds(selectors); - return new MessagingQualificationResult( - scenarioIds, - new MessagingEvidenceCounts(executed, executed - failed - skipped, failed, skipped)); - } -} diff --git a/src/build-tools/src/main/java/dev/caskeleton/buildtools/messaging/MessagingQualificationResult.java b/src/build-tools/src/main/java/dev/caskeleton/buildtools/messaging/MessagingQualificationResult.java deleted file mode 100644 index 7c853762..00000000 --- a/src/build-tools/src/main/java/dev/caskeleton/buildtools/messaging/MessagingQualificationResult.java +++ /dev/null @@ -1,10 +0,0 @@ -package dev.caskeleton.buildtools.messaging; - -import java.util.List; - -public record MessagingQualificationResult( - List scenarioIds, MessagingEvidenceCounts counts) { - public MessagingQualificationResult { - scenarioIds = List.copyOf(scenarioIds); - } -} diff --git a/src/build-tools/src/main/java/dev/caskeleton/buildtools/messaging/PrepareMessagingContractEvidenceTask.java b/src/build-tools/src/main/java/dev/caskeleton/buildtools/messaging/PrepareMessagingContractEvidenceTask.java deleted file mode 100644 index 47c946d4..00000000 --- a/src/build-tools/src/main/java/dev/caskeleton/buildtools/messaging/PrepareMessagingContractEvidenceTask.java +++ /dev/null @@ -1,63 +0,0 @@ -package dev.caskeleton.buildtools.messaging; - -import java.io.File; -import java.io.IOException; -import java.io.UncheckedIOException; -import java.nio.file.Files; -import org.gradle.api.DefaultTask; -import org.gradle.api.GradleException; -import org.gradle.api.file.RegularFileProperty; -import org.gradle.api.provider.Property; -import org.gradle.api.tasks.Input; -import org.gradle.api.tasks.InputFile; -import org.gradle.api.tasks.Internal; -import org.gradle.api.tasks.TaskAction; -import org.gradle.work.DisableCachingByDefault; - -@DisableCachingByDefault(because = "Prepares non-cacheable qualification evidence state") -public abstract class PrepareMessagingContractEvidenceTask extends DefaultTask { - @Internal - public abstract RegularFileProperty getEvidenceFile(); - - @InputFile - public abstract RegularFileProperty getProfileFile(); - - @Input - public abstract Property getSourceDigest(); - - @Input - public abstract Property getArtifactDigest(); - - @Input - public abstract Property getProfileHash(); - - @TaskAction - public void prepare() { - File output = getEvidenceFile().get().getAsFile(); - if (output.exists() && !output.delete()) { - throw new GradleException("Could not delete stale Messaging evidence " + output); - } - requireDigest("messagingSourceDigest", getSourceDigest().get()); - requireDigest("messagingArtifactDigest", getArtifactDigest().get()); - String suppliedProfile = requireDigest("messagingProfileHash", getProfileHash().get()); - byte[] profileBytes; - try { - profileBytes = Files.readAllBytes(getProfileFile().get().getAsFile().toPath()); - } catch (IOException exception) { - throw new UncheckedIOException("failed to read Messaging profile", exception); - } - String exactProfile = MessagingEvidenceHasher.sha256Bytes(profileBytes); - if (!suppliedProfile.equals(exactProfile)) { - throw new GradleException( - "messagingProfileHash does not match exact config/messaging/profile-compatibility.yaml bytes."); - } - } - - static String requireDigest(String propertyName, String value) { - if (value == null || !value.matches("sha256:[a-f0-9]{64}")) { - throw new GradleException( - "-P" + propertyName + "=sha256:<64-lowercase-hex> is required for Messaging evidence."); - } - return value; - } -} diff --git a/src/build-tools/src/main/java/dev/caskeleton/buildtools/messaging/VerifyMessagingCertificationEvidenceTask.java b/src/build-tools/src/main/java/dev/caskeleton/buildtools/messaging/VerifyMessagingCertificationEvidenceTask.java deleted file mode 100644 index fdaf352c..00000000 --- a/src/build-tools/src/main/java/dev/caskeleton/buildtools/messaging/VerifyMessagingCertificationEvidenceTask.java +++ /dev/null @@ -1,88 +0,0 @@ -package dev.caskeleton.buildtools.messaging; - -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.util.LinkedHashSet; -import java.util.Set; -import org.gradle.api.DefaultTask; -import org.gradle.api.GradleException; -import org.gradle.api.file.RegularFileProperty; -import org.gradle.api.tasks.InputFile; -import org.gradle.api.tasks.OutputFile; -import org.gradle.api.tasks.TaskAction; - -public abstract class VerifyMessagingCertificationEvidenceTask extends DefaultTask { - @InputFile - public abstract RegularFileProperty getProducedManifest(); - - @InputFile - public abstract RegularFileProperty getCommittedManifest(); - - @OutputFile - public abstract RegularFileProperty getReportFile(); - - @TaskAction - public void verifyEvidence() { - try { - Set ran = normalizedClaims(getProducedManifest().get().getAsFile().toPath()); - Set shipped = normalizedClaims(getCommittedManifest().get().getAsFile().toPath()); - if (!ran.equals(shipped)) { - Set unproven = new LinkedHashSet<>(shipped); - unproven.removeAll(ran); - Set unrecorded = new LinkedHashSet<>(ran); - unrecorded.removeAll(shipped); - throw new GradleException( - "the committed certification manifest does not match this run.\n" - + " claimed but not produced: " - + display(unproven) - + "\n" - + " produced but not claimed: " - + display(unrecorded) - + "\n" - + "Copy " - + getProducedManifest().get().getAsFile() - + " over " - + getCommittedManifest().get().getAsFile() - + " — the manifest is a record of a run, not a statement about one."); - } - var report = getReportFile().get().getAsFile().toPath(); - Files.createDirectories(report.getParent()); - Files.writeString( - report, - "scenarios=" - + ran.size() - + " manifest=" - + getCommittedManifest().get().getAsFile() - + "\n", - StandardCharsets.UTF_8); - } catch (IOException failure) { - throw new GradleException("failed to verify messaging certification evidence", failure); - } - } - - /** - * Returns the behavioral claim identity used by the equality gate. - * - *

{@code gitCommit} and {@code observedAt} remain in the evidence as provenance for audit and - * replay, but they are deliberately not equality keys: rerunning the same certified scenario on a - * later source revision/time should prove the same behavioral claim rather than manufacture a - * second scenario. Release provenance is recorded, not used as a freshness assertion. - */ - private static Set normalizedClaims(java.nio.file.Path file) throws IOException { - Set result = new LinkedHashSet<>(); - for (String line : Files.readAllLines(file, StandardCharsets.UTF_8)) { - if (line.trim().isEmpty()) { - continue; - } - result.add( - line.replaceAll(",\\\"gitCommit\\\":\\\"[^\\\"]*\\\"", "") - .replaceAll(",\\\"observedAt\\\":\\\"[^\\\"]*\\\"", "")); - } - return result; - } - - private static String display(Set values) { - return values.isEmpty() ? "none" : values.toString(); - } -} diff --git a/src/build-tools/src/main/java/dev/caskeleton/buildtools/messaging/VerifyMessagingEvidenceTask.java b/src/build-tools/src/main/java/dev/caskeleton/buildtools/messaging/VerifyMessagingEvidenceTask.java deleted file mode 100644 index 55521980..00000000 --- a/src/build-tools/src/main/java/dev/caskeleton/buildtools/messaging/VerifyMessagingEvidenceTask.java +++ /dev/null @@ -1,190 +0,0 @@ -package dev.caskeleton.buildtools.messaging; - -import java.io.File; -import java.io.IOException; -import java.io.UncheckedIOException; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.time.Instant; -import java.util.List; -import org.gradle.api.DefaultTask; -import org.gradle.api.GradleException; -import org.gradle.api.file.ConfigurableFileCollection; -import org.gradle.api.file.DirectoryProperty; -import org.gradle.api.file.RegularFileProperty; -import org.gradle.api.provider.ListProperty; -import org.gradle.api.provider.Property; -import org.gradle.api.tasks.Input; -import org.gradle.api.tasks.InputFile; -import org.gradle.api.tasks.InputFiles; -import org.gradle.api.tasks.Internal; -import org.gradle.api.tasks.OutputFile; -import org.gradle.api.tasks.TaskAction; -import org.gradle.work.DisableCachingByDefault; -import tools.jackson.databind.ObjectMapper; -import tools.jackson.databind.json.JsonMapper; - -@DisableCachingByDefault(because = "Evidence contains a generation timestamp and live test results") -public abstract class VerifyMessagingEvidenceTask extends DefaultTask { - private static final ObjectMapper JSON = JsonMapper.builder().build(); - private static final List UNSUPPORTED_CLAIMS = - List.of( - "consumer-compatibility-full-suite", - "durable-outbox-r2", - "kafka-acknowledged-r2", - "regex-engine-timeout", - "remote-schema-resolution"); - - @Input - public abstract Property getProducerTaskName(); - - @Input - public abstract ListProperty getResultDirectories(); - - @Input - public abstract ListProperty getCommandTasks(); - - @Input - public abstract Property getSourceDigest(); - - @Input - public abstract Property getArtifactDigest(); - - @Input - public abstract Property getProfileHash(); - - @InputFile - public abstract RegularFileProperty getProfileFile(); - - @InputFile - public abstract RegularFileProperty getCommonSchemaFile(); - - @InputFiles - public abstract ConfigurableFileCollection getCatalogFiles(); - - @InputFiles - public abstract ConfigurableFileCollection getSchemaFiles(); - - @InputFiles - public abstract ConfigurableFileCollection getSettingsFiles(); - - @Internal - public abstract DirectoryProperty getProjectRootDirectory(); - - @Internal - public abstract DirectoryProperty getResultRootDirectory(); - - @OutputFile - public abstract RegularFileProperty getEvidenceFile(); - - @TaskAction - public void verifyAndWrite() { - String producer = getProducerTaskName().get(); - MessagingQualificationResult result; - try { - result = - MessagingQualificationReader.read( - getResultRootDirectory().get().getAsFile(), getResultDirectories().get()); - } catch (IllegalArgumentException | IllegalStateException invalidEvidence) { - throw new GradleException(invalidEvidence.getMessage(), invalidEvidence); - } - - String sourceDigest = - PrepareMessagingContractEvidenceTask.requireDigest( - "messagingSourceDigest", getSourceDigest().get()); - String artifactDigest = - PrepareMessagingContractEvidenceTask.requireDigest( - "messagingArtifactDigest", getArtifactDigest().get()); - String suppliedProfile = - PrepareMessagingContractEvidenceTask.requireDigest( - "messagingProfileHash", getProfileHash().get()); - - File profileFile = getProfileFile().get().getAsFile(); - byte[] profileBytes; - try { - profileBytes = Files.readAllBytes(profileFile.toPath()); - } catch (IOException exception) { - throw new UncheckedIOException("failed to read " + profileFile, exception); - } - String exactProfile = MessagingEvidenceHasher.sha256Bytes(profileBytes); - if (!suppliedProfile.equals(exactProfile)) { - throw new GradleException( - "messagingProfileHash does not match exact config/messaging/profile-compatibility.yaml bytes."); - } - - File projectRoot = getProjectRootDirectory().get().getAsFile(); - MessagingEvidenceHashes hashes = - new MessagingEvidenceHashes( - exactProfile, - MessagingEvidenceHasher.sha256FileSet( - "ca-skeleton.messaging.evidence.catalog.v1", - projectRoot, - getCatalogFiles().getFiles().stream().toList()), - MessagingEvidenceHasher.sha256FileSet( - "ca-skeleton.messaging.evidence.schema-set.v1", - projectRoot, - getSchemaFiles().getFiles().stream().toList()), - MessagingEvidenceHasher.sha256FileSet( - "ca-skeleton.messaging.evidence.settings.v1", - projectRoot, - getSettingsFiles().getFiles().stream().toList())); - - String command = - "./gradlew " - + String.join(" ", getCommandTasks().get()) - + " -PmessagingSourceDigest= -PmessagingArtifactDigest= " - + "-PmessagingProfileHash= --console=plain"; - String generatedAt = Instant.now().toString(); - MessagingBuildEvidenceManifest manifest = - new MessagingBuildEvidenceManifest( - 1, - sourceDigest, - artifactDigest, - producer, - result.scenarioIds(), - result.counts(), - command, - generatedAt, - hashes, - List.of(), - List.of(), - UNSUPPORTED_CLAIMS); - - MessagingEvidenceManifest semanticManifest = - new MessagingEvidenceManifest( - producer, - result.counts(), - List.of(), - List.of(), - Instant.parse(generatedAt)); - List semanticViolations = - MessagingEvidenceVerifier.validate(semanticManifest, producer); - if (!semanticViolations.isEmpty()) { - throw new GradleException( - "Messaging evidence fails the rules the manifest schema cannot express:\n " - + String.join("\n ", semanticViolations)); - } - if (!getCommonSchemaFile().get().getAsFile().isFile()) { - throw new GradleException("Common Messaging evidence schema is missing."); - } - - File output = getEvidenceFile().get().getAsFile(); - File parent = output.getParentFile(); - if (!parent.isDirectory() && !parent.mkdirs()) { - throw new GradleException("Could not create Messaging evidence directory " + parent); - } - try { - String json = - JSON.writerWithDefaultPrettyPrinter().writeValueAsString(manifest) - + System.lineSeparator(); - Files.writeString(output.toPath(), json, StandardCharsets.UTF_8); - } catch (IOException exception) { - throw new UncheckedIOException("failed to write " + output, exception); - } - getLogger() - .lifecycle( - "{}: wrote payload-free evidence with {} scenarios.", - producer, - result.counts().executed()); - } -} diff --git a/src/build-tools/src/main/java/dev/caskeleton/buildtools/mongo/MongoIntegrationLaneTagVerifier.java b/src/build-tools/src/main/java/dev/caskeleton/buildtools/mongo/MongoIntegrationLaneTagVerifier.java deleted file mode 100644 index f5e56559..00000000 --- a/src/build-tools/src/main/java/dev/caskeleton/buildtools/mongo/MongoIntegrationLaneTagVerifier.java +++ /dev/null @@ -1,43 +0,0 @@ -package dev.caskeleton.buildtools.mongo; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.Collection; -import java.util.LinkedHashSet; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -final class MongoIntegrationLaneTagVerifier { - - private static final Set LANE_TAGS = - Set.of( - "mongodb-replicaset", - "mongodb-failover", - "mongodb-migration", - "mongodb-compatibility", - "mongodb-security-integration"); - - private static final Pattern TAG = Pattern.compile("@Tag\\(\\s*\\\"([^\\\"]+)\\\"\\s*\\)"); - - private MongoIntegrationLaneTagVerifier() {} - - static void verify(Collection sources) throws IOException { - for (Path source : sources) { - String content = Files.readString(source); - Set laneTags = new LinkedHashSet<>(); - Matcher matcher = TAG.matcher(content); - while (matcher.find()) { - String tag = matcher.group(1); - if (LANE_TAGS.contains(tag)) { - laneTags.add(tag); - } - } - if (laneTags.size() > 1) { - throw new IllegalStateException( - source + " belongs to multiple Mongo integration lanes: " + laneTags); - } - } - } -} diff --git a/src/build-tools/src/main/java/dev/caskeleton/buildtools/mongo/MongoJUnitXml.java b/src/build-tools/src/main/java/dev/caskeleton/buildtools/mongo/MongoJUnitXml.java deleted file mode 100644 index 0bb438cb..00000000 --- a/src/build-tools/src/main/java/dev/caskeleton/buildtools/mongo/MongoJUnitXml.java +++ /dev/null @@ -1,79 +0,0 @@ -package dev.caskeleton.buildtools.mongo; - -import java.io.File; -import java.util.LinkedHashSet; -import java.util.Set; -import javax.xml.XMLConstants; -import javax.xml.parsers.DocumentBuilderFactory; -import org.w3c.dom.Element; -import org.w3c.dom.NodeList; - -final class MongoJUnitXml { - private MongoJUnitXml() {} - - static Set selectors(File directory) { - Set selectors = new LinkedHashSet<>(); - File[] files = directory.listFiles(file -> file.isFile() && file.getName().endsWith(".xml")); - if (files == null) { - return selectors; - } - java.util.Arrays.sort(files, java.util.Comparator.comparing(File::getName)); - for (File file : files) { - Element suite = parse(file); - NodeList testCases = suite.getElementsByTagName("testcase"); - for (int index = 0; index < testCases.getLength(); index++) { - Element testCase = (Element) testCases.item(index); - selectors.add(testCase.getAttribute("classname") + "#" + testCase.getAttribute("name")); - } - } - return selectors; - } - - static SuiteCounts counts(File file) { - Element suite = parse(file); - return new SuiteCounts( - suite.getAttribute("name"), - attribute(suite, "tests", file), - attribute(suite, "skipped", file), - attribute(suite, "failures", file), - attribute(suite, "errors", file)); - } - - private static Element parse(File file) { - try { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - factory.setNamespaceAware(false); - factory.setXIncludeAware(false); - factory.setExpandEntityReferences(false); - factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); - factory.setFeature("http://xml.org/sax/features/external-general-entities", false); - factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); - factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); - factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); - factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); - Element root = factory.newDocumentBuilder().parse(file).getDocumentElement(); - if (!"testsuite".equals(root.getTagName())) { - throw new IllegalStateException(file + " root must be testsuite"); - } - return root; - } catch (IllegalStateException exception) { - throw exception; - } catch (Exception exception) { - throw new IllegalStateException(file + " is not readable JUnit XML", exception); - } - } - - private static int attribute(Element suite, String name, File file) { - String value = suite.hasAttribute(name) ? suite.getAttribute(name) : null; - if (value == null || !value.matches("\\d+")) { - throw new IllegalStateException(file.getName() + " has invalid " + name + "='" + value + "'"); - } - return Integer.parseInt(value); - } - - record SuiteCounts(String suiteName, int tests, int skipped, int failures, int errors) { - int executed() { - return tests - skipped; - } - } -} diff --git a/src/build-tools/src/main/java/dev/caskeleton/buildtools/mongo/MongoLaneDisjointnessResult.java b/src/build-tools/src/main/java/dev/caskeleton/buildtools/mongo/MongoLaneDisjointnessResult.java deleted file mode 100644 index ac691ec9..00000000 --- a/src/build-tools/src/main/java/dev/caskeleton/buildtools/mongo/MongoLaneDisjointnessResult.java +++ /dev/null @@ -1,3 +0,0 @@ -package dev.caskeleton.buildtools.mongo; - -public record MongoLaneDisjointnessResult(int unitCount, int contractCount) {} diff --git a/src/build-tools/src/main/java/dev/caskeleton/buildtools/mongo/MongoLaneDisjointnessVerifier.java b/src/build-tools/src/main/java/dev/caskeleton/buildtools/mongo/MongoLaneDisjointnessVerifier.java deleted file mode 100644 index d6c826c2..00000000 --- a/src/build-tools/src/main/java/dev/caskeleton/buildtools/mongo/MongoLaneDisjointnessVerifier.java +++ /dev/null @@ -1,29 +0,0 @@ -package dev.caskeleton.buildtools.mongo; - -import java.io.File; -import java.util.ArrayList; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Set; - -public final class MongoLaneDisjointnessVerifier { - private MongoLaneDisjointnessVerifier() {} - - public static MongoLaneDisjointnessResult verify(File unitResults, File contractResults) { - Set unit = MongoJUnitXml.selectors(unitResults); - Set contract = MongoJUnitXml.selectors(contractResults); - Set overlap = new LinkedHashSet<>(unit); - overlap.retainAll(contract); - if (!overlap.isEmpty()) { - List sample = new ArrayList<>(overlap); - if (sample.size() > 5) { - sample = sample.subList(0, 5); - } - throw new IllegalStateException( - overlap.size() - + " tests run in both the unit lane and the stable contract lane, so `check` executes them twice: " - + sample); - } - return new MongoLaneDisjointnessResult(unit.size(), contract.size()); - } -} diff --git a/src/build-tools/src/main/java/dev/caskeleton/buildtools/mongo/MongoReleaseContract.java b/src/build-tools/src/main/java/dev/caskeleton/buildtools/mongo/MongoReleaseContract.java deleted file mode 100644 index c42d822c..00000000 --- a/src/build-tools/src/main/java/dev/caskeleton/buildtools/mongo/MongoReleaseContract.java +++ /dev/null @@ -1,18 +0,0 @@ -package dev.caskeleton.buildtools.mongo; - -public record MongoReleaseContract(String id, String task, String className, int minimumExecuted) { - public MongoReleaseContract { - if (id == null || id.isBlank()) { - throw new IllegalArgumentException("id must not be blank"); - } - if (task == null || task.isBlank()) { - throw new IllegalArgumentException("task must not be blank"); - } - if (className == null || className.isBlank()) { - throw new IllegalArgumentException("className must not be blank"); - } - if (minimumExecuted < 0) { - throw new IllegalArgumentException("minimumExecuted must not be negative"); - } - } -} diff --git a/src/build-tools/src/main/java/dev/caskeleton/buildtools/mongo/MongoReleaseContractLaneResult.java b/src/build-tools/src/main/java/dev/caskeleton/buildtools/mongo/MongoReleaseContractLaneResult.java deleted file mode 100644 index a21e8518..00000000 --- a/src/build-tools/src/main/java/dev/caskeleton/buildtools/mongo/MongoReleaseContractLaneResult.java +++ /dev/null @@ -1,12 +0,0 @@ -package dev.caskeleton.buildtools.mongo; - -import java.util.List; - -public record MongoReleaseContractLaneResult( - List checkedContractIds, List externallyVerifiedContractIds) { - - public MongoReleaseContractLaneResult { - checkedContractIds = List.copyOf(checkedContractIds); - externallyVerifiedContractIds = List.copyOf(externallyVerifiedContractIds); - } -} diff --git a/src/build-tools/src/main/java/dev/caskeleton/buildtools/mongo/MongoReleaseContractLaneVerifier.java b/src/build-tools/src/main/java/dev/caskeleton/buildtools/mongo/MongoReleaseContractLaneVerifier.java deleted file mode 100644 index 397ba71e..00000000 --- a/src/build-tools/src/main/java/dev/caskeleton/buildtools/mongo/MongoReleaseContractLaneVerifier.java +++ /dev/null @@ -1,74 +0,0 @@ -package dev.caskeleton.buildtools.mongo; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; -import java.util.Set; - -public final class MongoReleaseContractLaneVerifier { - private MongoReleaseContractLaneVerifier() {} - - public static MongoReleaseContractLaneResult verify( - File manifest, Set hermeticLanes, File resultsRoot) { - List checked = new ArrayList<>(); - List externallyVerified = new ArrayList<>(); - List invalid = new ArrayList<>(); - - for (MongoReleaseContract contract : MongoReleaseContractManifestParser.parse(manifest)) { - if (!hermeticLanes.contains(contract.task())) { - externallyVerified.add(contract.id()); - continue; - } - - File resultFile = - new File(new File(resultsRoot, contract.task()), "TEST-" + contract.className() + ".xml"); - if (!resultFile.isFile()) { - invalid.add( - contract.id() - + " names lane '" - + contract.task() - + "', which did not run " - + contract.className()); - continue; - } - - MongoJUnitXml.SuiteCounts counts = MongoJUnitXml.counts(resultFile); - if (!contract.className().equals(counts.suiteName())) { - invalid.add( - contract.id() - + " expected suite '" - + contract.className() - + "' but evidence names '" - + counts.suiteName() - + "'"); - } - if (counts.failures() != 0 || counts.errors() != 0) { - invalid.add( - contract.id() - + " evidence contains " - + counts.failures() - + " failure(s) and " - + counts.errors() - + " error(s)"); - } - if (counts.executed() < contract.minimumExecuted()) { - invalid.add( - contract.id() - + " requires " - + contract.minimumExecuted() - + " executed test(s) in '" - + contract.task() - + "' and the lane ran " - + counts.executed()); - } - checked.add(contract.id()); - } - - if (!invalid.isEmpty()) { - throw new IllegalStateException( - "the Mongo release manifest points at invalid lane evidence: " - + String.join("; ", invalid)); - } - return new MongoReleaseContractLaneResult(checked, externallyVerified); - } -} diff --git a/src/build-tools/src/main/java/dev/caskeleton/buildtools/mongo/MongoReleaseContractManifestParser.java b/src/build-tools/src/main/java/dev/caskeleton/buildtools/mongo/MongoReleaseContractManifestParser.java deleted file mode 100644 index 99f14071..00000000 --- a/src/build-tools/src/main/java/dev/caskeleton/buildtools/mongo/MongoReleaseContractManifestParser.java +++ /dev/null @@ -1,58 +0,0 @@ -package dev.caskeleton.buildtools.mongo; - -import java.io.File; -import java.io.IOException; -import java.io.UncheckedIOException; -import java.nio.file.Files; -import java.util.ArrayList; -import java.util.List; -import tools.jackson.databind.JsonNode; -import tools.jackson.databind.ObjectMapper; -import tools.jackson.databind.json.JsonMapper; - -public final class MongoReleaseContractManifestParser { - private static final ObjectMapper JSON = JsonMapper.builder().build(); - - private MongoReleaseContractManifestParser() {} - - public static List parse(File manifest) { - final String raw; - try { - raw = Files.readString(manifest.toPath()); - } catch (IOException exception) { - throw new UncheckedIOException("cannot read " + manifest, exception); - } - JsonNode root = JSON.readTree(raw); - JsonNode contracts = root == null ? null : root.get("contracts"); - if (contracts == null || !contracts.isArray()) { - throw new IllegalStateException("release manifest field 'contracts' must be a list"); - } - List parsed = new ArrayList<>(); - for (JsonNode contract : contracts) { - parsed.add( - new MongoReleaseContract( - requiredText(contract, "id"), - requiredText(contract, "task"), - requiredText(contract, "className"), - requiredInt(contract, "minimumExecuted"))); - } - return List.copyOf(parsed); - } - - private static String requiredText(JsonNode node, String field) { - JsonNode value = node == null ? null : node.get(field); - String text = value == null ? null : value.stringValue(); - if (text == null || text.isBlank()) { - throw new IllegalStateException("field '" + field + "' must be non-blank text"); - } - return text; - } - - private static int requiredInt(JsonNode node, String field) { - JsonNode value = node == null ? null : node.get(field); - if (value == null || !value.isIntegralNumber()) { - throw new IllegalStateException("field '" + field + "' must be an integer"); - } - return value.asInt(); - } -} diff --git a/src/build-tools/src/main/java/dev/caskeleton/buildtools/mongo/MongoVerificationPlugin.java b/src/build-tools/src/main/java/dev/caskeleton/buildtools/mongo/MongoVerificationPlugin.java deleted file mode 100644 index a0ad0281..00000000 --- a/src/build-tools/src/main/java/dev/caskeleton/buildtools/mongo/MongoVerificationPlugin.java +++ /dev/null @@ -1,86 +0,0 @@ -package dev.caskeleton.buildtools.mongo; - -import java.util.List; -import org.gradle.api.Plugin; -import org.gradle.api.Project; - -public final class MongoVerificationPlugin implements Plugin { - @Override - public void apply(Project project) { - var integrationLaneTags = - project - .getTasks() - .register( - "verifyMongoIntegrationLaneTags", - VerifyMongoIntegrationLaneTagsTask.class, - task -> { - task.setGroup("verification"); - task.setDescription( - "Fails when one Mongo integration test belongs to multiple Docker lanes."); - task.getSources() - .from( - project.fileTree( - "src/mongoIntegrationTest/java", tree -> tree.include("**/*.java"))); - }); - project - .getPluginManager() - .withPlugin( - "java", - ignored -> - project - .getTasks() - .named("check") - .configure(task -> task.dependsOn(integrationLaneTags))); - - project - .getTasks() - .register( - "verifyMongoTestLaneDisjointness", - VerifyMongoTestLaneDisjointnessTask.class, - task -> { - task.setGroup("verification"); - task.setDescription( - "Fails when the unit lane and the stable contract lane execute the same test."); - task.dependsOn("test", "mongoStableContractTest"); - task.getUnitResults() - .set(project.getLayout().getBuildDirectory().dir("test-results/test")); - task.getContractResults() - .set( - project - .getLayout() - .getBuildDirectory() - .dir("test-results/mongoStableContractTest")); - task.getReportFile() - .set( - project - .getLayout() - .getBuildDirectory() - .file("reports/mongo-test-lane-disjointness.txt")); - }); - - project - .getTasks() - .register( - "verifyMongoReleaseContractLanes", - VerifyMongoReleaseContractLanesTask.class, - task -> { - task.setGroup("verification"); - task.setDescription( - "Fails when a blocking release contract names a lane that did not run its" - + " class."); - task.dependsOn("test", "mongoStableContractTest"); - task.getManifestFile() - .fileValue( - project.getRootProject().file("config/mongodb/release-contracts.json")); - task.getResultsRoot() - .set(project.getLayout().getBuildDirectory().dir("test-results")); - task.getHermeticLanes().convention(List.of("test", "mongoStableContractTest")); - task.getReportFile() - .set( - project - .getLayout() - .getBuildDirectory() - .file("reports/mongo-release-contract-lanes.txt")); - }); - } -} diff --git a/src/build-tools/src/main/java/dev/caskeleton/buildtools/mongo/VerifyMongoIntegrationLaneTagsTask.java b/src/build-tools/src/main/java/dev/caskeleton/buildtools/mongo/VerifyMongoIntegrationLaneTagsTask.java deleted file mode 100644 index 9d7ef3c2..00000000 --- a/src/build-tools/src/main/java/dev/caskeleton/buildtools/mongo/VerifyMongoIntegrationLaneTagsTask.java +++ /dev/null @@ -1,30 +0,0 @@ -package dev.caskeleton.buildtools.mongo; - -import java.io.IOException; -import java.io.UncheckedIOException; -import java.nio.file.Path; -import java.util.List; -import org.gradle.api.DefaultTask; -import org.gradle.api.file.ConfigurableFileCollection; -import org.gradle.api.tasks.InputFiles; -import org.gradle.api.tasks.PathSensitive; -import org.gradle.api.tasks.PathSensitivity; -import org.gradle.api.tasks.TaskAction; - -public abstract class VerifyMongoIntegrationLaneTagsTask extends DefaultTask { - - @InputFiles - @PathSensitive(PathSensitivity.RELATIVE) - public abstract ConfigurableFileCollection getSources(); - - @TaskAction - void verify() { - List sources = - getSources().getFiles().stream().map(file -> file.toPath()).sorted().toList(); - try { - MongoIntegrationLaneTagVerifier.verify(sources); - } catch (IOException exception) { - throw new UncheckedIOException("failed to verify Mongo integration lane tags", exception); - } - } -} diff --git a/src/build-tools/src/main/java/dev/caskeleton/buildtools/mongo/VerifyMongoReleaseContractLanesTask.java b/src/build-tools/src/main/java/dev/caskeleton/buildtools/mongo/VerifyMongoReleaseContractLanesTask.java deleted file mode 100644 index 79468964..00000000 --- a/src/build-tools/src/main/java/dev/caskeleton/buildtools/mongo/VerifyMongoReleaseContractLanesTask.java +++ /dev/null @@ -1,62 +0,0 @@ -package dev.caskeleton.buildtools.mongo; - -import java.io.IOException; -import java.io.UncheckedIOException; -import java.nio.file.Files; -import java.util.LinkedHashSet; -import org.gradle.api.DefaultTask; -import org.gradle.api.GradleException; -import org.gradle.api.file.DirectoryProperty; -import org.gradle.api.file.RegularFileProperty; -import org.gradle.api.provider.ListProperty; -import org.gradle.api.tasks.Input; -import org.gradle.api.tasks.InputDirectory; -import org.gradle.api.tasks.InputFile; -import org.gradle.api.tasks.OutputFile; -import org.gradle.api.tasks.TaskAction; -import org.gradle.work.DisableCachingByDefault; - -@DisableCachingByDefault(because = "Verification reads local JUnit evidence from the current build") -public abstract class VerifyMongoReleaseContractLanesTask extends DefaultTask { - @InputFile - public abstract RegularFileProperty getManifestFile(); - - @InputDirectory - public abstract DirectoryProperty getResultsRoot(); - - @Input - public abstract ListProperty getHermeticLanes(); - - @OutputFile - public abstract RegularFileProperty getReportFile(); - - @TaskAction - public void verifyReleaseContractLanes() { - final MongoReleaseContractLaneResult result; - try { - result = - MongoReleaseContractLaneVerifier.verify( - getManifestFile().get().getAsFile(), - new LinkedHashSet<>(getHermeticLanes().get()), - getResultsRoot().get().getAsFile()); - } catch (IllegalStateException invalidEvidence) { - throw new GradleException(invalidEvidence.getMessage(), invalidEvidence); - } - writeReport( - "hermetic release contracts verified: " - + String.join(", ", result.checkedContractIds()) - + "\nexternally verified release contracts: " - + String.join(", ", result.externallyVerifiedContractIds()) - + "\n"); - } - - private void writeReport(String report) { - try { - var path = getReportFile().get().getAsFile().toPath(); - Files.createDirectories(path.getParent()); - Files.writeString(path, report); - } catch (IOException exception) { - throw new UncheckedIOException("cannot write Mongo release contract lane report", exception); - } - } -} diff --git a/src/build-tools/src/main/java/dev/caskeleton/buildtools/mongo/VerifyMongoTestLaneDisjointnessTask.java b/src/build-tools/src/main/java/dev/caskeleton/buildtools/mongo/VerifyMongoTestLaneDisjointnessTask.java deleted file mode 100644 index f91c6ae3..00000000 --- a/src/build-tools/src/main/java/dev/caskeleton/buildtools/mongo/VerifyMongoTestLaneDisjointnessTask.java +++ /dev/null @@ -1,50 +0,0 @@ -package dev.caskeleton.buildtools.mongo; - -import java.io.IOException; -import java.io.UncheckedIOException; -import java.nio.file.Files; -import org.gradle.api.DefaultTask; -import org.gradle.api.GradleException; -import org.gradle.api.file.DirectoryProperty; -import org.gradle.api.file.RegularFileProperty; -import org.gradle.api.tasks.InputDirectory; -import org.gradle.api.tasks.Internal; -import org.gradle.api.tasks.OutputFile; -import org.gradle.api.tasks.TaskAction; -import org.gradle.work.DisableCachingByDefault; - -@DisableCachingByDefault(because = "Verification reads local JUnit evidence from the current build") -public abstract class VerifyMongoTestLaneDisjointnessTask extends DefaultTask { - @InputDirectory - public abstract DirectoryProperty getUnitResults(); - - @Internal - public abstract DirectoryProperty getContractResults(); - - @OutputFile - public abstract RegularFileProperty getReportFile(); - - @TaskAction - public void verifyLanes() { - final MongoLaneDisjointnessResult result; - try { - result = - MongoLaneDisjointnessVerifier.verify( - getUnitResults().get().getAsFile(), getContractResults().get().getAsFile()); - } catch (IllegalStateException invalidEvidence) { - throw new GradleException(invalidEvidence.getMessage(), invalidEvidence); - } - writeReport( - "unit=" + result.unitCount() + " contract=" + result.contractCount() + " overlap=0\n"); - } - - private void writeReport(String report) { - try { - var path = getReportFile().get().getAsFile().toPath(); - Files.createDirectories(path.getParent()); - Files.writeString(path, report); - } catch (IOException exception) { - throw new UncheckedIOException("cannot write Mongo lane disjointness report", exception); - } - } -} diff --git a/src/build-tools/src/main/java/dev/caskeleton/buildtools/notification/NotificationApiSurfacePlugin.java b/src/build-tools/src/main/java/dev/caskeleton/buildtools/notification/NotificationApiSurfacePlugin.java deleted file mode 100644 index 3555bb9d..00000000 --- a/src/build-tools/src/main/java/dev/caskeleton/buildtools/notification/NotificationApiSurfacePlugin.java +++ /dev/null @@ -1,52 +0,0 @@ -package dev.caskeleton.buildtools.notification; - -import java.io.File; -import java.util.List; -import org.gradle.api.Plugin; -import org.gradle.api.Project; - -public final class NotificationApiSurfacePlugin implements Plugin { - @Override - public void apply(Project project) { - Project root = project.getRootProject(); - List sourceRoots = - List.of( - root.file( - "application-notification/src/main/java/dev/caskeleton/application/notification"), - root.file( - "adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification")); - File snapshot = root.file("../docs/notification/api-surface-snapshot.txt"); - boolean updateApproved = project.hasProperty("approveNotificationApiChange"); - boolean ceilingRaiseApproved = project.hasProperty("raiseNotificationApiCeiling"); - - project - .getTasks() - .register( - "verifyNotificationApiSurface", - VerifyNotificationApiSurfaceTask.class, - task -> { - task.setGroup("verification"); - task.setDescription( - "Fails without mutation when the notification platform public type surface drifts."); - task.getSourceRoots().from(sourceRoots); - task.getSnapshotFile().fileValue(snapshot); - task.getUpdateApprovalRequested().set(updateApproved); - }); - - project - .getTasks() - .register( - "updateNotificationApiSurface", - UpdateNotificationApiSurfaceTask.class, - task -> { - task.setGroup("build setup"); - task.setDescription( - "Explicitly updates the committed notification public type surface after review."); - task.getSourceRoots().from(sourceRoots); - task.getSnapshotFile().fileValue(snapshot); - task.getApproved().set(updateApproved); - task.getCeilingRaiseApproved().set(ceilingRaiseApproved); - task.getOutputs().upToDateWhen(ignored -> false); - }); - } -} diff --git a/src/build-tools/src/main/java/dev/caskeleton/buildtools/notification/NotificationApiSurfaceResult.java b/src/build-tools/src/main/java/dev/caskeleton/buildtools/notification/NotificationApiSurfaceResult.java deleted file mode 100644 index f714b212..00000000 --- a/src/build-tools/src/main/java/dev/caskeleton/buildtools/notification/NotificationApiSurfaceResult.java +++ /dev/null @@ -1,12 +0,0 @@ -package dev.caskeleton.buildtools.notification; - -import java.util.Objects; - -public record NotificationApiSurfaceResult(int publicTypeCount, String renderedSurface) { - public NotificationApiSurfaceResult { - if (publicTypeCount < 0) { - throw new IllegalArgumentException("publicTypeCount must not be negative"); - } - Objects.requireNonNull(renderedSurface, "renderedSurface"); - } -} diff --git a/src/build-tools/src/main/java/dev/caskeleton/buildtools/notification/NotificationApiSurfaceVerifier.java b/src/build-tools/src/main/java/dev/caskeleton/buildtools/notification/NotificationApiSurfaceVerifier.java deleted file mode 100644 index aa92b8c7..00000000 --- a/src/build-tools/src/main/java/dev/caskeleton/buildtools/notification/NotificationApiSurfaceVerifier.java +++ /dev/null @@ -1,156 +0,0 @@ -package dev.caskeleton.buildtools.notification; - -import java.io.File; -import java.io.IOException; -import java.io.UncheckedIOException; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.TreeSet; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** Repository policy for the notification platform's committed public Java type surface. */ -public final class NotificationApiSurfaceVerifier { - private static final String HEADER = - "# NTF-022 — public type surface of the notification platform.\n" - + "# Every top-level public type under the platform packages. Growth is a reviewed\n" - + "# change: ./gradlew updateNotificationApiSurface -PapproveNotificationApiChange\n"; - private static final Pattern PACKAGE_PATTERN = - Pattern.compile("(?m)^package\\s+([\\w.]+);"); - private static final Pattern DECLARATION_PATTERN = - Pattern.compile( - "(?m)^public\\s+(?:final\\s+|abstract\\s+|sealed\\s+|non-sealed\\s+|static\\s+)*" - + "(class|interface|record|enum|@interface)\\s+(\\w+)"); - - private NotificationApiSurfaceVerifier() {} - - public static String render(Collection sourceRoots) { - TreeSet types = new TreeSet<>(); - for (File root : sourceRoots) { - if (!root.isDirectory()) { - continue; - } - try (var paths = Files.walk(root.toPath())) { - paths - .filter(Files::isRegularFile) - .filter(path -> path.getFileName().toString().endsWith(".java")) - .filter(path -> !path.getFileName().toString().equals("package-info.java")) - .forEach(path -> collectTypes(path.toFile(), types)); - } catch (IOException exception) { - throw new UncheckedIOException("failed to scan " + root, exception); - } - } - return HEADER + (types.isEmpty() ? "" : String.join("\n", types) + "\n"); - } - - public static NotificationApiSurfaceResult verify( - Collection sourceRoots, File snapshotFile) { - String canonical = render(sourceRoots); - List canonicalTypes = typeLines(canonical); - if (canonicalTypes.isEmpty()) { - throw new IllegalStateException( - "verifyNotificationApiSurface: found no public types under " - + sourceRoots - + ". The source roots moved; fix the paths rather than accepting an empty surface."); - } - if (!snapshotFile.isFile()) { - throw new IllegalStateException( - "verifyNotificationApiSurface: missing committed baseline " + snapshotFile); - } - - List committed = - readLines(snapshotFile).stream() - .filter(line -> !line.startsWith("#")) - .filter(line -> !line.trim().isEmpty()) - .toList(); - List added = difference(canonicalTypes, committed); - List removed = difference(committed, canonicalTypes); - if (!added.isEmpty() || !removed.isEmpty()) { - throw new IllegalStateException( - "verifyNotificationApiSurface: the notification public type surface changed.\n" - + (added.isEmpty() - ? "" - : " added (" + added.size() + "):\n " + String.join("\n ", added) + "\n") - + (removed.isEmpty() - ? "" - : " removed (" - + removed.size() - + "):\n " - + String.join("\n ", removed) - + "\n") - + "A type added here is a type other code may now depend on forever. If that is intended:\n" - + " ./gradlew updateNotificationApiSurface -PapproveNotificationApiChange"); - } - return new NotificationApiSurfaceResult(canonicalTypes.size(), canonical); - } - - public static void requireNoUnapprovedGrowth( - int committedCount, String rendered, boolean ceilingRaiseApproved) { - if (ceilingRaiseApproved) { - return; - } - int renderedCount = typeCount(rendered); - if (renderedCount > committedCount) { - throw new IllegalStateException( - "updateNotificationApiSurface: the public surface would grow from " - + committedCount - + " to " - + renderedCount - + " types.\n" - + "Either land the addition together with a removal that pays for it, " - + "or raise the ceiling deliberately:\n" - + " ./gradlew updateNotificationApiSurface " - + "-PapproveNotificationApiChange -PraiseNotificationApiCeiling"); - } - } - - public static int typeCount(String surface) { - return typeLines(surface).size(); - } - - private static void collectTypes(File file, TreeSet types) { - String text = read(file); - Matcher packageMatcher = PACKAGE_PATTERN.matcher(text); - if (!packageMatcher.find()) { - return; - } - String packageName = packageMatcher.group(1); - Matcher declarationMatcher = DECLARATION_PATTERN.matcher(text); - while (declarationMatcher.find()) { - types.add(packageName + "." + declarationMatcher.group(2)); - } - } - - private static List typeLines(String surface) { - return surface.lines() - .filter(line -> !line.startsWith("#")) - .filter(line -> !line.trim().isEmpty()) - .toList(); - } - - private static List difference(List left, List right) { - ArrayList result = new ArrayList<>(left); - result.removeAll(right); - result.sort(String::compareTo); - return List.copyOf(result); - } - - private static String read(File file) { - try { - return Files.readString(file.toPath(), StandardCharsets.UTF_8); - } catch (IOException exception) { - throw new UncheckedIOException("failed to read " + file, exception); - } - } - - private static List readLines(File file) { - try { - return Files.readAllLines(file.toPath(), StandardCharsets.UTF_8); - } catch (IOException exception) { - throw new UncheckedIOException("failed to read " + file, exception); - } - } -} diff --git a/src/build-tools/src/main/java/dev/caskeleton/buildtools/notification/NotificationClaim.java b/src/build-tools/src/main/java/dev/caskeleton/buildtools/notification/NotificationClaim.java deleted file mode 100644 index 664fe9d6..00000000 --- a/src/build-tools/src/main/java/dev/caskeleton/buildtools/notification/NotificationClaim.java +++ /dev/null @@ -1,18 +0,0 @@ -package dev.caskeleton.buildtools.notification; - -import java.util.List; -import java.util.Objects; - -public record NotificationClaim( - String name, NotificationClaimStatus status, List lanes, List evidence) { - public NotificationClaim { - Objects.requireNonNull(name, "name"); - Objects.requireNonNull(status, "status"); - lanes = List.copyOf(Objects.requireNonNull(lanes, "lanes")); - evidence = List.copyOf(Objects.requireNonNull(evidence, "evidence")); - } - - public NotificationClaim(String name, NotificationClaimStatus status, List evidence) { - this(name, status, List.of(), evidence); - } -} diff --git a/src/build-tools/src/main/java/dev/caskeleton/buildtools/notification/NotificationClaimStatus.java b/src/build-tools/src/main/java/dev/caskeleton/buildtools/notification/NotificationClaimStatus.java deleted file mode 100644 index c0f475c4..00000000 --- a/src/build-tools/src/main/java/dev/caskeleton/buildtools/notification/NotificationClaimStatus.java +++ /dev/null @@ -1,21 +0,0 @@ -package dev.caskeleton.buildtools.notification; - -public enum NotificationClaimStatus { - SATISFIED("satisfied"), - UNSATISFIED("unsatisfied"); - - private final String externalValue; - - NotificationClaimStatus(String externalValue) { - this.externalValue = externalValue; - } - - public static NotificationClaimStatus parse(String value) { - for (NotificationClaimStatus status : values()) { - if (status.externalValue.equals(value)) { - return status; - } - } - throw new IllegalStateException("unsupported claim status '" + value + "'"); - } -} diff --git a/src/build-tools/src/main/java/dev/caskeleton/buildtools/notification/NotificationEvidenceManifest.java b/src/build-tools/src/main/java/dev/caskeleton/buildtools/notification/NotificationEvidenceManifest.java deleted file mode 100644 index d1fe22ff..00000000 --- a/src/build-tools/src/main/java/dev/caskeleton/buildtools/notification/NotificationEvidenceManifest.java +++ /dev/null @@ -1,13 +0,0 @@ -package dev.caskeleton.buildtools.notification; - -import java.util.List; -import java.util.Objects; - -public record NotificationEvidenceManifest( - String matrixDocument, List claims, List grades) { - public NotificationEvidenceManifest { - Objects.requireNonNull(matrixDocument, "matrixDocument"); - claims = List.copyOf(claims); - grades = List.copyOf(grades); - } -} diff --git a/src/build-tools/src/main/java/dev/caskeleton/buildtools/notification/NotificationEvidencePlugin.java b/src/build-tools/src/main/java/dev/caskeleton/buildtools/notification/NotificationEvidencePlugin.java deleted file mode 100644 index f9c39849..00000000 --- a/src/build-tools/src/main/java/dev/caskeleton/buildtools/notification/NotificationEvidencePlugin.java +++ /dev/null @@ -1,25 +0,0 @@ -package dev.caskeleton.buildtools.notification; - -import org.gradle.api.Plugin; -import org.gradle.api.Project; - -public final class NotificationEvidencePlugin implements Plugin { - @Override - public void apply(Project project) { - Project root = project.getRootProject(); - project - .getTasks() - .register( - "verifyNotificationEvidence", - VerifyNotificationEvidenceTask.class, - task -> { - task.setGroup("verification"); - task.setDescription( - "Fails when a notification support grade claims more than the executable evidence proves."); - task.getManifestFile() - .fileValue(root.file("../docs/notification/evidence-manifest.json")); - task.getRepositoryDirectory().set(root.getLayout().getProjectDirectory().dir("..")); - task.getProjectDirectory().set(root.getLayout().getProjectDirectory()); - }); - } -} diff --git a/src/build-tools/src/main/java/dev/caskeleton/buildtools/notification/NotificationEvidenceResult.java b/src/build-tools/src/main/java/dev/caskeleton/buildtools/notification/NotificationEvidenceResult.java deleted file mode 100644 index 99fdbf24..00000000 --- a/src/build-tools/src/main/java/dev/caskeleton/buildtools/notification/NotificationEvidenceResult.java +++ /dev/null @@ -1,12 +0,0 @@ -package dev.caskeleton.buildtools.notification; - -import java.util.Objects; - -public record NotificationEvidenceResult(int satisfiedClaimCount, String matrixFileName) { - public NotificationEvidenceResult { - if (satisfiedClaimCount < 0) { - throw new IllegalArgumentException("satisfiedClaimCount must not be negative"); - } - Objects.requireNonNull(matrixFileName, "matrixFileName"); - } -} diff --git a/src/build-tools/src/main/java/dev/caskeleton/buildtools/notification/NotificationGrade.java b/src/build-tools/src/main/java/dev/caskeleton/buildtools/notification/NotificationGrade.java deleted file mode 100644 index 2bf43b82..00000000 --- a/src/build-tools/src/main/java/dev/caskeleton/buildtools/notification/NotificationGrade.java +++ /dev/null @@ -1,11 +0,0 @@ -package dev.caskeleton.buildtools.notification; - -import java.util.List; -import java.util.Objects; - -public record NotificationGrade(String name, List requiredClaims) { - public NotificationGrade { - Objects.requireNonNull(name, "name"); - requiredClaims = List.copyOf(requiredClaims); - } -} diff --git a/src/build-tools/src/main/java/dev/caskeleton/buildtools/notification/UpdateNotificationApiSurfaceTask.java b/src/build-tools/src/main/java/dev/caskeleton/buildtools/notification/UpdateNotificationApiSurfaceTask.java deleted file mode 100644 index 2f9f6ddc..00000000 --- a/src/build-tools/src/main/java/dev/caskeleton/buildtools/notification/UpdateNotificationApiSurfaceTask.java +++ /dev/null @@ -1,70 +0,0 @@ -package dev.caskeleton.buildtools.notification; - -import java.io.File; -import java.io.IOException; -import java.io.UncheckedIOException; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.util.List; -import org.gradle.api.DefaultTask; -import org.gradle.api.GradleException; -import org.gradle.api.file.ConfigurableFileCollection; -import org.gradle.api.file.RegularFileProperty; -import org.gradle.api.provider.Property; -import org.gradle.api.tasks.Input; -import org.gradle.api.tasks.InputFiles; -import org.gradle.api.tasks.OutputFile; -import org.gradle.api.tasks.TaskAction; -import org.gradle.work.DisableCachingByDefault; - -@DisableCachingByDefault(because = "This task intentionally updates a committed review baseline") -public abstract class UpdateNotificationApiSurfaceTask extends DefaultTask { - @InputFiles - public abstract ConfigurableFileCollection getSourceRoots(); - - @OutputFile - public abstract RegularFileProperty getSnapshotFile(); - - @Input - public abstract Property getApproved(); - - @Input - public abstract Property getCeilingRaiseApproved(); - - @TaskAction - public void updateSurface() { - if (!getApproved().get()) { - throw new GradleException( - "updateNotificationApiSurface requires -PapproveNotificationApiChange"); - } - List roots = getSourceRoots().getFiles().stream().sorted().toList(); - String canonical = NotificationApiSurfaceVerifier.render(roots); - File snapshot = getSnapshotFile().get().getAsFile(); - if (snapshot.isFile()) { - try { - int committedCount = - NotificationApiSurfaceVerifier.typeCount( - Files.readString(snapshot.toPath(), StandardCharsets.UTF_8)); - NotificationApiSurfaceVerifier.requireNoUnapprovedGrowth( - committedCount, canonical, getCeilingRaiseApproved().get()); - } catch (IOException exception) { - throw new UncheckedIOException("failed to read " + snapshot, exception); - } catch (IllegalStateException unapprovedGrowth) { - throw new GradleException(unapprovedGrowth.getMessage(), unapprovedGrowth); - } - } - File parent = snapshot.getParentFile(); - if (!parent.isDirectory() && !parent.mkdirs()) { - throw new GradleException( - "updateNotificationApiSurface: failed to create " + parent); - } - try { - Files.writeString(snapshot.toPath(), canonical, StandardCharsets.UTF_8); - } catch (IOException exception) { - throw new UncheckedIOException("failed to write " + snapshot, exception); - } - getLogger() - .lifecycle( - "updateNotificationApiSurface: wrote reviewed baseline {}", snapshot); - } -} diff --git a/src/build-tools/src/main/java/dev/caskeleton/buildtools/notification/VerifyNotificationApiSurfaceTask.java b/src/build-tools/src/main/java/dev/caskeleton/buildtools/notification/VerifyNotificationApiSurfaceTask.java deleted file mode 100644 index e44fe5a0..00000000 --- a/src/build-tools/src/main/java/dev/caskeleton/buildtools/notification/VerifyNotificationApiSurfaceTask.java +++ /dev/null @@ -1,48 +0,0 @@ -package dev.caskeleton.buildtools.notification; - -import java.io.File; -import java.util.List; -import org.gradle.api.DefaultTask; -import org.gradle.api.GradleException; -import org.gradle.api.file.ConfigurableFileCollection; -import org.gradle.api.file.RegularFileProperty; -import org.gradle.api.provider.Property; -import org.gradle.api.tasks.Input; -import org.gradle.api.tasks.InputFile; -import org.gradle.api.tasks.InputFiles; -import org.gradle.api.tasks.TaskAction; -import org.gradle.work.DisableCachingByDefault; - -@DisableCachingByDefault(because = "Repository surface verification emits no reusable output") -public abstract class VerifyNotificationApiSurfaceTask extends DefaultTask { - @InputFiles - public abstract ConfigurableFileCollection getSourceRoots(); - - @InputFile - public abstract RegularFileProperty getSnapshotFile(); - - @Input - public abstract Property getUpdateApprovalRequested(); - - @TaskAction - public void verifySurface() { - if (getUpdateApprovalRequested().get()) { - throw new GradleException( - "verifyNotificationApiSurface is read-only; use updateNotificationApiSurface " - + "-PapproveNotificationApiChange for an intentional update."); - } - List roots = getSourceRoots().getFiles().stream().sorted().toList(); - NotificationApiSurfaceResult result; - try { - result = - NotificationApiSurfaceVerifier.verify( - roots, getSnapshotFile().get().getAsFile()); - } catch (IllegalStateException invalidSurface) { - throw new GradleException(invalidSurface.getMessage(), invalidSurface); - } - getLogger() - .lifecycle( - "verifyNotificationApiSurface: OK — {} public types, unchanged.", - result.publicTypeCount()); - } -} diff --git a/src/build-tools/src/main/java/dev/caskeleton/buildtools/notification/VerifyNotificationEvidenceTask.java b/src/build-tools/src/main/java/dev/caskeleton/buildtools/notification/VerifyNotificationEvidenceTask.java deleted file mode 100644 index f3a5229b..00000000 --- a/src/build-tools/src/main/java/dev/caskeleton/buildtools/notification/VerifyNotificationEvidenceTask.java +++ /dev/null @@ -1,41 +0,0 @@ -package dev.caskeleton.buildtools.notification; - -import org.gradle.api.DefaultTask; -import org.gradle.api.GradleException; -import org.gradle.api.file.DirectoryProperty; -import org.gradle.api.file.RegularFileProperty; -import org.gradle.api.tasks.InputFile; -import org.gradle.api.tasks.Internal; -import org.gradle.api.tasks.TaskAction; -import org.gradle.work.DisableCachingByDefault; - -@DisableCachingByDefault(because = "Repository evidence verification emits no reusable output") -public abstract class VerifyNotificationEvidenceTask extends DefaultTask { - @InputFile - public abstract RegularFileProperty getManifestFile(); - - @Internal - public abstract DirectoryProperty getRepositoryDirectory(); - - @Internal - public abstract DirectoryProperty getProjectDirectory(); - - @TaskAction - public void verifyEvidence() { - NotificationEvidenceResult result; - try { - result = - NotificationEvidenceVerifier.verify( - getManifestFile().get().getAsFile(), - getRepositoryDirectory().get().getAsFile(), - getProjectDirectory().get().getAsFile()); - } catch (IllegalStateException invalidEvidence) { - throw new GradleException(invalidEvidence.getMessage(), invalidEvidence); - } - getLogger() - .lifecycle( - "verifyNotificationEvidence: OK — {} claims proven, every grade in {} is backed.", - result.satisfiedClaimCount(), - result.matrixFileName()); - } -} diff --git a/src/build-tools/src/main/java/dev/caskeleton/buildtools/notificationconfig/NotificationConfiguration.java b/src/build-tools/src/main/java/dev/caskeleton/buildtools/notificationconfig/NotificationConfiguration.java deleted file mode 100644 index 345cbb38..00000000 --- a/src/build-tools/src/main/java/dev/caskeleton/buildtools/notificationconfig/NotificationConfiguration.java +++ /dev/null @@ -1,11 +0,0 @@ -package dev.caskeleton.buildtools.notificationconfig; - -import java.util.List; - -public record NotificationConfiguration( - List registeredVariables, List boundVariables) { - public NotificationConfiguration { - registeredVariables = List.copyOf(registeredVariables); - boundVariables = List.copyOf(boundVariables); - } -} diff --git a/src/build-tools/src/main/java/dev/caskeleton/buildtools/notificationconfig/NotificationConfigurationPlugin.java b/src/build-tools/src/main/java/dev/caskeleton/buildtools/notificationconfig/NotificationConfigurationPlugin.java deleted file mode 100644 index c3c76380..00000000 --- a/src/build-tools/src/main/java/dev/caskeleton/buildtools/notificationconfig/NotificationConfigurationPlugin.java +++ /dev/null @@ -1,33 +0,0 @@ -package dev.caskeleton.buildtools.notificationconfig; - -import org.gradle.api.Plugin; -import org.gradle.api.Project; - -public final class NotificationConfigurationPlugin implements Plugin { - @Override - public void apply(Project project) { - var resourceRoot = - project.getLayout().getProjectDirectory().dir("app-bootstrap/src/main/resources"); - var applicationYaml = resourceRoot.file("application.yml"); - var configurationDirectory = resourceRoot.dir("config"); - var environmentRegistry = - project.getLayout().getProjectDirectory().file("../docs/registries/env-keys.yaml"); - - project - .getTasks() - .register( - "verifyNotificationConfiguration", - VerifyNotificationConfigurationTask.class, - task -> { - task.setGroup("verification"); - task.setDescription( - "Fails when docs/registries/env-keys.yaml registers a notification platform key no binding reads."); - task.getApplicationYaml().set(applicationYaml); - task.getConfigurationDirectory().set(configurationDirectory); - task.getEnvironmentRegistry().set(environmentRegistry); - task.getResourceDisplayPath().convention("app-bootstrap/src/main/resources"); - task.getTrackedFiles() - .from(applicationYaml, environmentRegistry, project.fileTree(configurationDirectory)); - }); - } -} diff --git a/src/build-tools/src/main/java/dev/caskeleton/buildtools/notificationconfig/NotificationConfigurationVerifier.java b/src/build-tools/src/main/java/dev/caskeleton/buildtools/notificationconfig/NotificationConfigurationVerifier.java deleted file mode 100644 index 8f14e3c5..00000000 --- a/src/build-tools/src/main/java/dev/caskeleton/buildtools/notificationconfig/NotificationConfigurationVerifier.java +++ /dev/null @@ -1,126 +0,0 @@ -package dev.caskeleton.buildtools.notificationconfig; - -import java.io.File; -import java.io.IOException; -import java.io.UncheckedIOException; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Set; -import java.util.TreeSet; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public final class NotificationConfigurationVerifier { - private static final Pattern PLACEHOLDER = - Pattern.compile("\\$\\{(APP_NOTIFICATION_[A-Z0-9_]+)(:[^}]*)?}"); - private static final Pattern REGISTERED = - Pattern.compile("^\\s*- name:\\s*((?:APP_NOTIFICATION|SPRING_MAIL)_[A-Z0-9_]+)\\s*$"); - - private static final Set SMTP_EXTERNAL_VARIABLES = - Set.of( - "SPRING_MAIL_HOST", - "SPRING_MAIL_PORT", - "SPRING_MAIL_USERNAME", - "SPRING_MAIL_PASSWORD", - "SPRING_MAIL_PROPERTIES_MAIL_SMTP_STARTTLS_ENABLE", - "SPRING_MAIL_PROPERTIES_MAIL_SMTP_STARTTLS_REQUIRED", - "SPRING_MAIL_PROPERTIES_MAIL_SMTP_CONNECTIONTIMEOUT", - "SPRING_MAIL_PROPERTIES_MAIL_SMTP_TIMEOUT", - "SPRING_MAIL_PROPERTIES_MAIL_SMTP_WRITETIMEOUT"); - - private NotificationConfigurationVerifier() {} - - public static NotificationConfiguration verify( - File applicationYaml, - File configurationDirectory, - File environmentRegistry, - String resourceDisplayPath) { - requireFile(applicationYaml); - requireFile(environmentRegistry); - - List boundSources = new ArrayList<>(); - boundSources.add(applicationYaml); - if (configurationDirectory.isDirectory()) { - File[] configurationFiles = - configurationDirectory.listFiles( - file -> file.isFile() && file.getName().endsWith(".yml")); - if (configurationFiles != null) { - Arrays.sort(configurationFiles, java.util.Comparator.comparing(File::getName)); - boundSources.addAll(Arrays.asList(configurationFiles)); - } - } - - Set boundVariables = new TreeSet<>(); - for (File source : boundSources) { - Matcher matcher = PLACEHOLDER.matcher(read(source)); - while (matcher.find()) { - boundVariables.add(matcher.group(1)); - } - } - if (boundVariables.isEmpty()) { - throw new IllegalStateException( - "verifyNotificationConfiguration: no APP_NOTIFICATION_PLATFORM_* placeholder is bound " - + "anywhere in " - + resourceDisplayPath - + ", so there is nothing to compare the registry against."); - } - - Set registeredVariables = new TreeSet<>(); - for (String line : readLines(environmentRegistry)) { - Matcher matcher = REGISTERED.matcher(line); - if (matcher.matches()) { - registeredVariables.add(matcher.group(1)); - } - } - - Set effectiveVariables = new TreeSet<>(boundVariables); - if (boundVariables.contains("APP_NOTIFICATION_PLATFORM_SMTP_ENABLED") - || registeredVariables.contains("APP_NOTIFICATION_PLATFORM_SMTP_ENABLED")) { - effectiveVariables.addAll(SMTP_EXTERNAL_VARIABLES); - } - - List problems = new ArrayList<>(); - registeredVariables.stream() - .filter(variable -> !effectiveVariables.contains(variable)) - .map(variable -> variable + " is registered in env-keys.yaml and bound/required by nothing") - .forEach(problems::add); - effectiveVariables.stream() - .filter(variable -> !registeredVariables.contains(variable)) - .map(variable -> variable + " is bound/required but missing from env-keys.yaml") - .forEach(problems::add); - if (!problems.isEmpty()) { - throw new IllegalStateException( - "verifyNotificationConfiguration: notification environment ownership drifted.\n " - + String.join("\n ", problems) - + "\nThe binding/runtime dependency is the fact; the registry describes it."); - } - - return new NotificationConfiguration( - new ArrayList<>(registeredVariables), new ArrayList<>(effectiveVariables)); - } - - private static void requireFile(File file) { - if (!file.isFile()) { - throw new IllegalStateException("verifyNotificationConfiguration: missing " + file); - } - } - - private static String read(File file) { - try { - return Files.readString(file.toPath(), StandardCharsets.UTF_8); - } catch (IOException exception) { - throw new UncheckedIOException("failed to read " + file, exception); - } - } - - private static List readLines(File file) { - try { - return Files.readAllLines(file.toPath(), StandardCharsets.UTF_8); - } catch (IOException exception) { - throw new UncheckedIOException("failed to read " + file, exception); - } - } -} diff --git a/src/build-tools/src/main/java/dev/caskeleton/buildtools/notificationconfig/VerifyNotificationConfigurationTask.java b/src/build-tools/src/main/java/dev/caskeleton/buildtools/notificationconfig/VerifyNotificationConfigurationTask.java deleted file mode 100644 index d194d2db..00000000 --- a/src/build-tools/src/main/java/dev/caskeleton/buildtools/notificationconfig/VerifyNotificationConfigurationTask.java +++ /dev/null @@ -1,52 +0,0 @@ -package dev.caskeleton.buildtools.notificationconfig; - -import org.gradle.api.DefaultTask; -import org.gradle.api.GradleException; -import org.gradle.api.file.ConfigurableFileCollection; -import org.gradle.api.file.DirectoryProperty; -import org.gradle.api.file.RegularFileProperty; -import org.gradle.api.provider.Property; -import org.gradle.api.tasks.Input; -import org.gradle.api.tasks.InputFiles; -import org.gradle.api.tasks.Internal; -import org.gradle.api.tasks.TaskAction; -import org.gradle.work.DisableCachingByDefault; - -@DisableCachingByDefault(because = "Verification task has no outputs") -public abstract class VerifyNotificationConfigurationTask extends DefaultTask { - @Internal - public abstract RegularFileProperty getApplicationYaml(); - - @Internal - public abstract DirectoryProperty getConfigurationDirectory(); - - @Internal - public abstract RegularFileProperty getEnvironmentRegistry(); - - @Input - public abstract Property getResourceDisplayPath(); - - @InputFiles - public abstract ConfigurableFileCollection getTrackedFiles(); - - @TaskAction - public void verifyConfiguration() { - NotificationConfiguration configuration; - try { - configuration = - NotificationConfigurationVerifier.verify( - getApplicationYaml().get().getAsFile(), - getConfigurationDirectory().get().getAsFile(), - getEnvironmentRegistry().get().getAsFile(), - getResourceDisplayPath().get()); - } catch (IllegalStateException invalidConfiguration) { - throw new GradleException(invalidConfiguration.getMessage(), invalidConfiguration); - } - - getLogger() - .lifecycle( - "verifyNotificationConfiguration: OK — {} registered platform keys, all bound under {}.", - configuration.registeredVariables().size(), - getResourceDisplayPath().get()); - } -} diff --git a/src/build-tools/src/test/java/dev/caskeleton/buildtools/jpa/JpaAdopterApiSurfaceVerifierTest.java b/src/build-tools/src/test/java/dev/caskeleton/buildtools/jpa/JpaAdopterApiSurfaceVerifierTest.java deleted file mode 100644 index 7418a16e..00000000 --- a/src/build-tools/src/test/java/dev/caskeleton/buildtools/jpa/JpaAdopterApiSurfaceVerifierTest.java +++ /dev/null @@ -1,38 +0,0 @@ -package dev.caskeleton.buildtools.jpa; - -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.List; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -class JpaAdopterApiSurfaceVerifierTest { - - @Test - void allowsOnlyReviewedPersistenceImports(@TempDir Path temp) throws Exception { - Path source = temp.resolve("Consumer.java"); - Files.writeString( - source, - "import dev.caskeleton.adapter.outbound.persistence.api.capability.JpaCapability;\n"); - Path baseline = temp.resolve("surface.txt"); - Files.writeString( - baseline, "dev.caskeleton.adapter.outbound.persistence.api.capability.JpaCapability\n"); - - assertDoesNotThrow(() -> JpaAdopterApiSurfaceVerifier.verify(List.of(source), baseline)); - - Files.writeString( - source, - "import dev.caskeleton.adapter.outbound.persistence.api.capability.JpaCapability;\n" - + "import dev.caskeleton.adapter.outbound.persistence.internal.HiddenType;\n"); - - IllegalStateException failure = - assertThrows( - IllegalStateException.class, - () -> JpaAdopterApiSurfaceVerifier.verify(List.of(source), baseline)); - assertTrue(failure.getMessage().contains("internal.HiddenType")); - } -} diff --git a/src/build-tools/src/test/java/dev/caskeleton/buildtools/messaging/MessagingBuildEvidenceManifestJsonTest.java b/src/build-tools/src/test/java/dev/caskeleton/buildtools/messaging/MessagingBuildEvidenceManifestJsonTest.java deleted file mode 100644 index 8ea97de2..00000000 --- a/src/build-tools/src/test/java/dev/caskeleton/buildtools/messaging/MessagingBuildEvidenceManifestJsonTest.java +++ /dev/null @@ -1,40 +0,0 @@ -package dev.caskeleton.buildtools.messaging; - -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.time.Instant; -import java.util.List; -import org.junit.jupiter.api.Test; -import tools.jackson.databind.json.JsonMapper; - -class MessagingBuildEvidenceManifestJsonTest { - @Test - void countsSerializeOnlySchemaFields() { - var manifest = - new MessagingBuildEvidenceManifest( - 1, - "sha256:" + "a".repeat(64), - "sha256:" + "b".repeat(64), - "verifyMessagingContracts", - List.of("Contract.scenario"), - new MessagingEvidenceCounts(1, 1, 0, 0), - "./gradlew verifyMessagingContracts", - Instant.parse("2026-09-17T00:00:00Z").toString(), - new MessagingEvidenceHashes( - "sha256:" + "c".repeat(64), - "sha256:" + "d".repeat(64), - "sha256:" + "e".repeat(64), - "sha256:" + "f".repeat(64)), - List.of(), - List.of(), - List.of("remote-schema-resolution")); - - String json = JsonMapper.builder().build().writeValueAsString(manifest); - - assertTrue(json.contains("\"executed\":1"), json); - assertTrue(json.contains("\"passed\":1"), json); - assertFalse(json.contains("passing"), json); - assertFalse(json.contains("totalOutcomes"), json); - } -} diff --git a/src/build-tools/src/test/java/dev/caskeleton/buildtools/messaging/MessagingCertificationPluginFunctionalTest.java b/src/build-tools/src/test/java/dev/caskeleton/buildtools/messaging/MessagingCertificationPluginFunctionalTest.java deleted file mode 100644 index 07143ced..00000000 --- a/src/build-tools/src/test/java/dev/caskeleton/buildtools/messaging/MessagingCertificationPluginFunctionalTest.java +++ /dev/null @@ -1,45 +0,0 @@ -package dev.caskeleton.buildtools.messaging; - -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.nio.file.Files; -import java.nio.file.Path; -import org.gradle.testkit.runner.BuildResult; -import org.gradle.testkit.runner.GradleRunner; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -class MessagingCertificationPluginFunctionalTest { - @Test - void pluginRegistersTypedCertificationEvidenceGate(@TempDir Path projectDir) throws Exception { - Files.writeString(projectDir.resolve("settings.gradle"), "rootProject.name='fixture'\n"); - Files.createDirectories(projectDir.resolve("messaging/messaging-testkit/src/main/resources/messaging")); - Files.writeString( - projectDir.resolve("messaging/messaging-testkit/src/main/resources/messaging/broker-certification-evidence.jsonl"), - "{\"scenario\":\"round-trip\",\"gitCommit\":\"committed\",\"observedAt\":\"old\"}\n"); - Files.writeString( - projectDir.resolve("build.gradle"), - """ - plugins { id 'ca.messaging-certification' } - tasks.register('messagingCertificationTest') { - doLast { - def out = layout.buildDirectory.file('messaging-certification/broker-certification-evidence.jsonl').get().asFile - out.parentFile.mkdirs() - out.text = '{"scenario":"round-trip","gitCommit":"runtime","observedAt":"now"}\\n' - } - } - """); - - BuildResult result = - GradleRunner.create() - .withProjectDir(projectDir.toFile()) - .withPluginClasspath() - .withArguments("verifyMessagingCertificationEvidence", "--console=plain") - .build(); - - assertTrue(result.getOutput().contains("BUILD SUCCESSFUL"), result.getOutput()); - assertTrue( - Files.readString(projectDir.resolve("build/reports/messaging-certification-evidence.txt")) - .contains("scenarios=1")); - } -} diff --git a/src/build-tools/src/test/java/dev/caskeleton/buildtools/messaging/MessagingEvidenceVerifierTest.java b/src/build-tools/src/test/java/dev/caskeleton/buildtools/messaging/MessagingEvidenceVerifierTest.java deleted file mode 100644 index 5494b3ba..00000000 --- a/src/build-tools/src/test/java/dev/caskeleton/buildtools/messaging/MessagingEvidenceVerifierTest.java +++ /dev/null @@ -1,52 +0,0 @@ -package dev.caskeleton.buildtools.messaging; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.time.Instant; -import java.util.List; -import org.junit.jupiter.api.Test; - -class MessagingEvidenceVerifierTest { - - @Test - void validPassManifestHasNoViolations() { - var manifest = - new MessagingEvidenceManifest( - "verifyMessagingContracts", - new MessagingEvidenceCounts(3, 3, 0, 0), - List.of(), - List.of(), - Instant.parse("2026-09-17T00:00:00Z")); - - assertTrue( - MessagingEvidenceVerifier.validate(manifest, "verifyMessagingContracts").isEmpty()); - } - - @Test - void producerCountSkipAndFailureAreValidated() { - var manifest = - new MessagingEvidenceManifest( - "wrong", - new MessagingEvidenceCounts(4, 2, 1, 0), - List.of("boom"), - List.of(), - Instant.parse("2026-09-17T00:00:00Z")); - - List violations = MessagingEvidenceVerifier.validate(manifest, "expected"); - - assertTrue(violations.stream().anyMatch(message -> message.contains("producerTask"))); - assertTrue(violations.stream().anyMatch(message -> message.contains("counts do not add up"))); - assertTrue(violations.stream().anyMatch(message -> message.contains("failed or skipped"))); - } - - @Test - void selectorsBecomeStableUniqueScenarioIds() { - assertEquals( - List.of("OrderContract.publishes", "RetryContract.retries"), - MessagingEvidenceVerifier.scenarioIds( - List.of( - "dev.caskeleton.messaging.OrderContract#publishes", - "dev.caskeleton.messaging.RetryContract#retries"))); - } -} diff --git a/src/build-tools/src/test/java/dev/caskeleton/buildtools/messaging/MessagingQualificationPluginTest.java b/src/build-tools/src/test/java/dev/caskeleton/buildtools/messaging/MessagingQualificationPluginTest.java deleted file mode 100644 index 1ae12e05..00000000 --- a/src/build-tools/src/test/java/dev/caskeleton/buildtools/messaging/MessagingQualificationPluginTest.java +++ /dev/null @@ -1,116 +0,0 @@ -package dev.caskeleton.buildtools.messaging; - -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.nio.file.Files; -import java.nio.file.Path; -import org.gradle.api.DefaultTask; -import org.gradle.api.Plugin; -import org.gradle.testkit.runner.BuildResult; -import org.gradle.testkit.runner.GradleRunner; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -class MessagingQualificationPluginTest { - @TempDir Path projectDir; - - @BeforeEach - void setUp() throws Exception { - Files.createDirectories(projectDir.resolve("adapter/outbound/messaging")); - Files.createDirectories(projectDir.resolve("application-core")); - Files.createDirectories(projectDir.resolve("shared-contract")); - Files.writeString( - projectDir.resolve("settings.gradle"), - """ - rootProject.name='fixture' - include ':application-core', ':shared-contract', ':adapter:outbound:messaging' - """); - Files.writeString( - projectDir.resolve("application-core/build.gradle"), - """ - plugins { id 'java' } - tasks.register('messagingApplicationContractQualificationTest') - """); - Files.writeString( - projectDir.resolve("shared-contract/build.gradle"), - """ - plugins { id 'java' } - tasks.register('messagingSharedSchemaQualificationTest') - """); - Files.writeString( - projectDir.resolve("adapter/outbound/messaging/build.gradle"), - """ - plugins { id 'java' } - tasks.register('messagingCompiledContractsQualificationTest') - tasks.register('messagingJsonSchemaV1QualificationTest') - tasks.register('verifyDependencyPolicy') - """); - } - - @Test - void qualificationPluginIsJavaBinaryPluginWithTypedTasks() { - assertTrue(Plugin.class.isAssignableFrom(MessagingQualificationPlugin.class)); - assertTrue(DefaultTask.class.isAssignableFrom(PrepareMessagingContractEvidenceTask.class)); - assertTrue(DefaultTask.class.isAssignableFrom(VerifyMessagingEvidenceTask.class)); - } - - @Test - void qualificationPluginRegistersOnlyImplementedProducersAndWiresSchemaValidation() - throws Exception { - Files.writeString( - projectDir.resolve("build.gradle"), - """ - plugins { - id 'base' - id 'ca.messaging-qualification' - } - tasks.register('reportMessagingQualification') { - doLast { - def implemented = ['verifyMessagingContracts', 'verifyMessagingJsonSchemaV1'] - def planned = [ - 'verifyMessagingPollingOutboxR2', - 'verifyMessagingKafkaProducerR2', - 'verifyMessagingSecurityR2', - 'verifyMessagingReleaseProfile', - 'verifyMessagingTargetBindingPreflight', - 'verifyMessagingTargetBinding', - 'verifyMessagingDeploymentCutover', - 'verifyMessagingCleanupTargetBinding', - 'verifyMessagingFinalR2Profile'] - logger.lifecycle('implemented=' + implemented.collect { tasks.findByName(it) != null }) - logger.lifecycle('planned=' + planned.collect { tasks.findByName(it) != null }) - - def json = tasks.named('verifyMessagingJsonSchemaV1').get() - def contracts = tasks.named('verifyMessagingContracts').get() - logger.lifecycle('json-finalizers=' + json.finalizedBy.getDependencies(json)*.name.sort()) - logger.lifecycle('contracts-dependencies=' + contracts.taskDependencies.getDependencies(contracts)*.name.sort()) - logger.lifecycle('contracts-finalizers=' + contracts.finalizedBy.getDependencies(contracts)*.name.sort()) - } - } - """); - - BuildResult result = runner("reportMessagingQualification", "--console=plain").build(); - - assertTrue(result.getOutput().contains("implemented=[true, true]"), result.getOutput()); - assertTrue( - result - .getOutput() - .contains("planned=[false, false, false, false, false, false, false, false, false]"), - result.getOutput()); - assertTrue( - result.getOutput().contains("validateMessagingJsonSchemaV1EvidenceManifestSchema"), - result.getOutput()); - assertTrue(result.getOutput().contains("contracts-dependencies="), result.getOutput()); - assertTrue( - result.getOutput().contains("validateMessagingContractsEvidenceManifestSchema"), - result.getOutput()); - } - - private GradleRunner runner(String... args) { - return GradleRunner.create() - .withProjectDir(projectDir.toFile()) - .withPluginClasspath() - .withArguments(args); - } -} diff --git a/src/build-tools/src/test/java/dev/caskeleton/buildtools/mongo/MongoIntegrationLaneTagVerifierTest.java b/src/build-tools/src/test/java/dev/caskeleton/buildtools/mongo/MongoIntegrationLaneTagVerifierTest.java deleted file mode 100644 index 0820317e..00000000 --- a/src/build-tools/src/test/java/dev/caskeleton/buildtools/mongo/MongoIntegrationLaneTagVerifierTest.java +++ /dev/null @@ -1,46 +0,0 @@ -package dev.caskeleton.buildtools.mongo; - -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.List; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -class MongoIntegrationLaneTagVerifierTest { - - @Test - void rejectsOneTestClassAssignedToTwoDockerLanes(@TempDir Path temp) throws Exception { - Path source = temp.resolve("DuplicateLaneTest.java"); - Files.writeString( - source, - """ - import org.junit.jupiter.api.Tag; - @Tag("mongodb-failover") - @Tag("mongodb-replicaset") - class DuplicateLaneTest {} - """); - - IllegalStateException failure = - assertThrows( - IllegalStateException.class, - () -> MongoIntegrationLaneTagVerifier.verify(List.of(source))); - - assertTrue(failure.getMessage().contains("multiple Mongo integration lanes")); - } - - @Test - void acceptsOneIntegrationLanePerSource(@TempDir Path temp) throws Exception { - Path first = temp.resolve("FailoverTest.java"); - Path second = temp.resolve("MigrationTest.java"); - Files.writeString( - first, "@org.junit.jupiter.api.Tag(\"mongodb-failover\") class FailoverTest {}"); - Files.writeString( - second, "@org.junit.jupiter.api.Tag(\"mongodb-migration\") class MigrationTest {}"); - - assertDoesNotThrow(() -> MongoIntegrationLaneTagVerifier.verify(List.of(first, second))); - } -} diff --git a/src/build-tools/src/test/java/dev/caskeleton/buildtools/mongo/MongoLaneDisjointnessVerifierTest.java b/src/build-tools/src/test/java/dev/caskeleton/buildtools/mongo/MongoLaneDisjointnessVerifierTest.java deleted file mode 100644 index df3f7f3a..00000000 --- a/src/build-tools/src/test/java/dev/caskeleton/buildtools/mongo/MongoLaneDisjointnessVerifierTest.java +++ /dev/null @@ -1,46 +0,0 @@ -package dev.caskeleton.buildtools.mongo; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.nio.file.Files; -import java.nio.file.Path; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -class MongoLaneDisjointnessVerifierTest { - @Test - void reportsDisjointLaneCounts(@TempDir Path temp) throws Exception { - Path unit = Files.createDirectories(temp.resolve("unit")); - Path contract = Files.createDirectories(temp.resolve("contract")); - writeSuite(unit, "UnitTest", "unitOne", "unitTwo"); - writeSuite(contract, "ContractTest", "contractOne"); - MongoLaneDisjointnessResult result = MongoLaneDisjointnessVerifier.verify(unit.toFile(), contract.toFile()); - assertEquals(2, result.unitCount()); - assertEquals(1, result.contractCount()); - } - - @Test - void overlappingSelectorsFailWithEvidence(@TempDir Path temp) throws Exception { - Path unit = Files.createDirectories(temp.resolve("unit")); - Path contract = Files.createDirectories(temp.resolve("contract")); - writeSuite(unit, "SharedTest", "sameCase"); - writeSuite(contract, "SharedTest", "sameCase"); - IllegalStateException failure = assertThrows(IllegalStateException.class, - () -> MongoLaneDisjointnessVerifier.verify(unit.toFile(), contract.toFile())); - assertTrue(failure.getMessage().contains("1 tests run in both")); - assertTrue(failure.getMessage().contains("SharedTest#sameCase")); - } - - private static void writeSuite(Path directory, String className, String... methods) throws Exception { - StringBuilder cases = new StringBuilder(); - for (String method : methods) { - cases.append("\n"); - } - Files.writeString(directory.resolve("TEST-" + className + ".xml"), - "\n" - + cases + "\n"); - } -} diff --git a/src/build-tools/src/test/java/dev/caskeleton/buildtools/mongo/MongoReleaseContractLaneVerifierTest.java b/src/build-tools/src/test/java/dev/caskeleton/buildtools/mongo/MongoReleaseContractLaneVerifierTest.java deleted file mode 100644 index b1701cdf..00000000 --- a/src/build-tools/src/test/java/dev/caskeleton/buildtools/mongo/MongoReleaseContractLaneVerifierTest.java +++ /dev/null @@ -1,131 +0,0 @@ -package dev.caskeleton.buildtools.mongo; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.Set; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -class MongoReleaseContractLaneVerifierTest { - @Test - void reportsHermeticAndExternallyVerifiedContractsSeparately(@TempDir Path temp) - throws Exception { - Path manifest = temp.resolve("release-contracts.json"); - Files.writeString( - manifest, - """ - {"contracts":[ - {"id":"C-1","task":"test","className":"a.Unit","minimumExecuted":1}, - {"id":"C-2","task":"mongoStableContractTest","className":"a.Contract","minimumExecuted":2}, - {"id":"C-3","task":"mongoReplicaSetTest","className":"a.Docker","minimumExecuted":1} - ]} - """); - Path results = Files.createDirectories(temp.resolve("results")); - writeSuite(results, "test", "a.Unit", "a.Unit", 1, 0, 0, 0); - writeSuite(results, "mongoStableContractTest", "a.Contract", "a.Contract", 3, 1, 0, 0); - - MongoReleaseContractLaneResult result = - MongoReleaseContractLaneVerifier.verify( - manifest.toFile(), Set.of("test", "mongoStableContractTest"), results.toFile()); - - assertEquals(java.util.List.of("C-1", "C-2"), result.checkedContractIds()); - assertEquals(java.util.List.of("C-3"), result.externallyVerifiedContractIds()); - } - - @Test - void missingResultFileFailsWithContractAndLane(@TempDir Path temp) throws Exception { - Path manifest = manifest(temp, "C-MISSING", "mongoStableContractTest", "a.Missing", 1); - Path results = Files.createDirectories(temp.resolve("results")); - - IllegalStateException failure = - assertThrows( - IllegalStateException.class, - () -> - MongoReleaseContractLaneVerifier.verify( - manifest.toFile(), Set.of("mongoStableContractTest"), results.toFile())); - - assertTrue(failure.getMessage().contains("C-MISSING")); - assertTrue(failure.getMessage().contains("a.Missing")); - } - - @Test - void failedOrMisnamedSuiteIsRejected(@TempDir Path temp) throws Exception { - Path manifest = manifest(temp, "C-FAIL", "mongoStableContractTest", "a.Contract", 1); - Path results = Files.createDirectories(temp.resolve("results")); - writeSuite(results, "mongoStableContractTest", "a.Contract", "a.Other", 2, 0, 1, 0); - - IllegalStateException failure = - assertThrows( - IllegalStateException.class, - () -> - MongoReleaseContractLaneVerifier.verify( - manifest.toFile(), Set.of("mongoStableContractTest"), results.toFile())); - - assertTrue(failure.getMessage().contains("expected suite 'a.Contract'")); - assertTrue(failure.getMessage().contains("1 failure(s)")); - } - - @Test - void insufficientExecutedCountFails(@TempDir Path temp) throws Exception { - Path manifest = manifest(temp, "C-MIN", "mongoStableContractTest", "a.Contract", 3); - Path results = Files.createDirectories(temp.resolve("results")); - writeSuite(results, "mongoStableContractTest", "a.Contract", "a.Contract", 4, 2, 0, 0); - - IllegalStateException failure = - assertThrows( - IllegalStateException.class, - () -> - MongoReleaseContractLaneVerifier.verify( - manifest.toFile(), Set.of("mongoStableContractTest"), results.toFile())); - - assertTrue(failure.getMessage().contains("requires 3 executed test(s)")); - assertTrue(failure.getMessage().contains("lane ran 2")); - } - - private static Path manifest( - Path temp, String id, String task, String className, int minimumExecuted) throws Exception { - Path manifest = temp.resolve("release-contracts.json"); - Files.writeString( - manifest, - "{\"contracts\":[{\"id\":\"" - + id - + "\",\"task\":\"" - + task - + "\",\"className\":\"" - + className - + "\",\"minimumExecuted\":" - + minimumExecuted - + "}]}\n"); - return manifest; - } - - private static void writeSuite( - Path resultsRoot, - String task, - String fileClassName, - String suiteName, - int tests, - int skipped, - int failures, - int errors) - throws Exception { - Path lane = Files.createDirectories(resultsRoot.resolve(task)); - Files.writeString( - lane.resolve("TEST-" + fileClassName + ".xml"), - "\n"); - } -} diff --git a/src/build-tools/src/test/java/dev/caskeleton/buildtools/notification/NotificationApiSurfaceVerifierTest.java b/src/build-tools/src/test/java/dev/caskeleton/buildtools/notification/NotificationApiSurfaceVerifierTest.java deleted file mode 100644 index b1e0fbe8..00000000 --- a/src/build-tools/src/test/java/dev/caskeleton/buildtools/notification/NotificationApiSurfaceVerifierTest.java +++ /dev/null @@ -1,82 +0,0 @@ -package dev.caskeleton.buildtools.notification; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.List; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -class NotificationApiSurfaceVerifierTest { - - @Test - void rendersAndVerifiesTopLevelPublicTypesAcrossRoots(@TempDir Path temp) throws Exception { - Path first = source(temp.resolve("one"), "dev.example.one", "public final class Alpha {}"); - Path second = source(temp.resolve("two"), "dev.example.two", "public interface Beta {}"); - Path snapshot = temp.resolve("snapshot.txt"); - - String rendered = NotificationApiSurfaceVerifier.render(List.of(first.toFile(), second.toFile())); - Files.writeString(snapshot, rendered); - NotificationApiSurfaceResult result = - NotificationApiSurfaceVerifier.verify( - List.of(first.toFile(), second.toFile()), snapshot.toFile()); - - assertTrue(rendered.contains("dev.example.one.Alpha")); - assertTrue(rendered.contains("dev.example.two.Beta")); - assertEquals(2, result.publicTypeCount()); - } - - @Test - void driftReportsAddedAndRemovedTypes(@TempDir Path temp) throws Exception { - Path root = source(temp.resolve("src"), "dev.example", "public class Current {}"); - Path snapshot = temp.resolve("snapshot.txt"); - Files.writeString(snapshot, "# old\n# header\ndev.example.Old\n"); - - IllegalStateException failure = - assertThrows( - IllegalStateException.class, - () -> NotificationApiSurfaceVerifier.verify(List.of(root.toFile()), snapshot.toFile())); - - assertTrue(failure.getMessage().contains("added (1)")); - assertTrue(failure.getMessage().contains("dev.example.Current")); - assertTrue(failure.getMessage().contains("removed (1)")); - assertTrue(failure.getMessage().contains("dev.example.Old")); - } - - @Test - void emptyRenderingFailsClosed(@TempDir Path temp) throws Exception { - Path root = temp.resolve("src"); - Files.createDirectories(root); - Path snapshot = temp.resolve("snapshot.txt"); - Files.writeString(snapshot, "# empty\n"); - - IllegalStateException failure = - assertThrows( - IllegalStateException.class, - () -> NotificationApiSurfaceVerifier.verify(List.of(root.toFile()), snapshot.toFile())); - - assertTrue(failure.getMessage().contains("found no public types")); - } - - @Test - void growthNeedsSeparateCeilingApproval(@TempDir Path temp) throws Exception { - Path root = source(temp.resolve("src"), "dev.example", "public class First {}\npublic interface Second {}"); - String rendered = NotificationApiSurfaceVerifier.render(List.of(root.toFile())); - - IllegalStateException failure = - assertThrows( - IllegalStateException.class, - () -> NotificationApiSurfaceVerifier.requireNoUnapprovedGrowth(1, rendered, false)); - - assertTrue(failure.getMessage().contains("grow from 1 to 2 types")); - } - - private static Path source(Path root, String packageName, String declaration) throws Exception { - Files.createDirectories(root); - Files.writeString(root.resolve("Types.java"), "package " + packageName + ";\n" + declaration + "\n"); - return root; - } -} diff --git a/src/build-tools/src/test/java/dev/caskeleton/buildtools/notificationconfig/NotificationConfigurationVerifierTest.java b/src/build-tools/src/test/java/dev/caskeleton/buildtools/notificationconfig/NotificationConfigurationVerifierTest.java deleted file mode 100644 index 214c2c9d..00000000 --- a/src/build-tools/src/test/java/dev/caskeleton/buildtools/notificationconfig/NotificationConfigurationVerifierTest.java +++ /dev/null @@ -1,140 +0,0 @@ -package dev.caskeleton.buildtools.notificationconfig; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.nio.file.Files; -import java.nio.file.Path; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -class NotificationConfigurationVerifierTest { - - @Test - void allRegisteredPlatformKeysMustBeBound(@TempDir Path temp) throws Exception { - Path resources = temp.resolve("resources"); - Path config = resources.resolve("config"); - Files.createDirectories(config); - Path application = resources.resolve("application.yml"); - Path registry = temp.resolve("env-keys.yaml"); - - Files.writeString(application, "spring:\n config:\n import: config/notification.yml\n"); - Files.writeString( - config.resolve("notification.yml"), - "enabled: ${APP_NOTIFICATION_PLATFORM_ENABLED:false}\n" - + "sender: ${APP_NOTIFICATION_PLATFORM_SENDER:no-reply}\n"); - Files.writeString( - registry, - "- name: APP_NOTIFICATION_PLATFORM_ENABLED\n" - + "- name: APP_NOTIFICATION_PLATFORM_SENDER\n"); - - NotificationConfiguration result = - NotificationConfigurationVerifier.verify( - application.toFile(), - config.toFile(), - registry.toFile(), - "app-bootstrap/src/main/resources"); - - assertEquals( - java.util.List.of("APP_NOTIFICATION_PLATFORM_ENABLED", "APP_NOTIFICATION_PLATFORM_SENDER"), - result.registeredVariables()); - } - - @Test - void registeredButUnboundKeyFails(@TempDir Path temp) throws Exception { - Path resources = temp.resolve("resources"); - Files.createDirectories(resources.resolve("config")); - Path application = resources.resolve("application.yml"); - Path registry = temp.resolve("env-keys.yaml"); - - Files.writeString(application, "enabled: ${APP_NOTIFICATION_PLATFORM_ENABLED:false}\n"); - Files.writeString( - registry, - "- name: APP_NOTIFICATION_PLATFORM_ENABLED\n" - + "- name: APP_NOTIFICATION_PLATFORM_UNUSED\n"); - - IllegalStateException failure = - assertThrows( - IllegalStateException.class, - () -> - NotificationConfigurationVerifier.verify( - application.toFile(), - resources.resolve("config").toFile(), - registry.toFile(), - "app-bootstrap/src/main/resources")); - assertTrue(failure.getMessage().contains("APP_NOTIFICATION_PLATFORM_UNUSED is registered")); - assertTrue(failure.getMessage().contains("bound/required by nothing")); - } - - @Test - void boundButUnregisteredKeyFails(@TempDir Path temp) throws Exception { - Path resources = temp.resolve("resources"); - Files.createDirectories(resources.resolve("config")); - Path application = resources.resolve("application.yml"); - Path registry = temp.resolve("env-keys.yaml"); - - Files.writeString( - application, - "enabled: ${APP_NOTIFICATION_PLATFORM_ENABLED:false}\n" - + "sender: ${APP_NOTIFICATION_PLATFORM_SENDER:no-reply}\n"); - Files.writeString(registry, "- name: APP_NOTIFICATION_PLATFORM_ENABLED\n"); - - IllegalStateException failure = - assertThrows( - IllegalStateException.class, - () -> - NotificationConfigurationVerifier.verify( - application.toFile(), - resources.resolve("config").toFile(), - registry.toFile(), - "app-bootstrap/src/main/resources")); - assertTrue(failure.getMessage().contains("APP_NOTIFICATION_PLATFORM_SENDER")); - assertTrue(failure.getMessage().contains("missing from env-keys.yaml")); - } - - @Test - void smtpTransportDependenciesMustBeRegistered(@TempDir Path temp) throws Exception { - Path resources = temp.resolve("resources"); - Files.createDirectories(resources.resolve("config")); - Path application = resources.resolve("application.yml"); - Path registry = temp.resolve("env-keys.yaml"); - - Files.writeString(application, "enabled: ${APP_NOTIFICATION_PLATFORM_SMTP_ENABLED:false}\n"); - Files.writeString(registry, "- name: APP_NOTIFICATION_PLATFORM_SMTP_ENABLED\n"); - - IllegalStateException failure = - assertThrows( - IllegalStateException.class, - () -> - NotificationConfigurationVerifier.verify( - application.toFile(), - resources.resolve("config").toFile(), - registry.toFile(), - "app-bootstrap/src/main/resources")); - assertTrue(failure.getMessage().contains("SPRING_MAIL_HOST")); - assertTrue(failure.getMessage().contains("missing from env-keys.yaml")); - } - - @Test - void noPlatformBindingFailsClosed(@TempDir Path temp) throws Exception { - Path resources = temp.resolve("resources"); - Files.createDirectories(resources.resolve("config")); - Path application = resources.resolve("application.yml"); - Path registry = temp.resolve("env-keys.yaml"); - Files.writeString(application, "spring:\n application:\n name: fixture\n"); - Files.writeString(registry, "- name: APP_NOTIFICATION_PLATFORM_ENABLED\n"); - - IllegalStateException failure = - assertThrows( - IllegalStateException.class, - () -> - NotificationConfigurationVerifier.verify( - application.toFile(), - resources.resolve("config").toFile(), - registry.toFile(), - "app-bootstrap/src/main/resources")); - assertTrue( - failure.getMessage().contains("no APP_NOTIFICATION_PLATFORM_* placeholder is bound")); - } -} diff --git a/src/build-tools/src/test/java/dev/caskeleton/buildtools/plugin/SmallBinaryPluginsTypeTest.java b/src/build-tools/src/test/java/dev/caskeleton/buildtools/plugin/SmallBinaryPluginsTypeTest.java deleted file mode 100644 index a4607074..00000000 --- a/src/build-tools/src/test/java/dev/caskeleton/buildtools/plugin/SmallBinaryPluginsTypeTest.java +++ /dev/null @@ -1,36 +0,0 @@ -package dev.caskeleton.buildtools.plugin; - -import static org.junit.jupiter.api.Assertions.assertTrue; - -import dev.caskeleton.buildtools.config.ConfigContractPlugin; -import dev.caskeleton.buildtools.config.VerifyEnvKeysTask; -import dev.caskeleton.buildtools.mongo.MongoVerificationPlugin; -import dev.caskeleton.buildtools.mongo.VerifyMongoReleaseContractLanesTask; -import dev.caskeleton.buildtools.mongo.VerifyMongoTestLaneDisjointnessTask; -import dev.caskeleton.buildtools.notification.NotificationApiSurfacePlugin; -import dev.caskeleton.buildtools.notification.NotificationEvidencePlugin; -import dev.caskeleton.buildtools.notification.UpdateNotificationApiSurfaceTask; -import dev.caskeleton.buildtools.notification.VerifyNotificationApiSurfaceTask; -import dev.caskeleton.buildtools.notification.VerifyNotificationEvidenceTask; -import org.gradle.api.DefaultTask; -import org.gradle.api.Plugin; -import org.junit.jupiter.api.Test; - -class SmallBinaryPluginsTypeTest { - @Test - void smallVerificationPluginsUseJavaBinaryPluginAndTypedTaskClasses() { - assertTrue(Plugin.class.isAssignableFrom(ConfigContractPlugin.class)); - assertTrue(DefaultTask.class.isAssignableFrom(VerifyEnvKeysTask.class)); - - assertTrue(Plugin.class.isAssignableFrom(NotificationEvidencePlugin.class)); - assertTrue(DefaultTask.class.isAssignableFrom(VerifyNotificationEvidenceTask.class)); - - assertTrue(Plugin.class.isAssignableFrom(NotificationApiSurfacePlugin.class)); - assertTrue(DefaultTask.class.isAssignableFrom(VerifyNotificationApiSurfaceTask.class)); - assertTrue(DefaultTask.class.isAssignableFrom(UpdateNotificationApiSurfaceTask.class)); - - assertTrue(Plugin.class.isAssignableFrom(MongoVerificationPlugin.class)); - assertTrue(DefaultTask.class.isAssignableFrom(VerifyMongoTestLaneDisjointnessTask.class)); - assertTrue(DefaultTask.class.isAssignableFrom(VerifyMongoReleaseContractLanesTask.class)); - } -} diff --git a/src/build.gradle b/src/build.gradle index 0050f422..f281e67e 100644 --- a/src/build.gradle +++ b/src/build.gradle @@ -8,24 +8,16 @@ plugins { // plugin reachable from two classpaths is two versions waiting to differ. Their versions are the // same catalog entries either way — build-logic/settings.gradle reads gradle/libs.versions.toml. alias(libs.plugins.spring.boot) apply false + // JMH benchmarks in three leaves (`./gradlew ::jmh`); never part of a gate. + alias(libs.plugins.jmh) apply false - // Convention plugins from the included build-logic build. - // - // Applied to the ROOT, not per leaf: the evidence closures live on rootProject.ext, the - // membership check compares each composition against the runtime closure it resolves, and the - // architecture rules are about the repository. + // Convention plugins from the included builds, applied to the ROOT because the rules they own are + // about the repository: the architecture gates, release provenance, the public-path baseline. id 'ca.release-provenance' - id 'ca.evidence' - id 'ca.conditional-transport-qualification' - id 'ca.runtime-membership' id 'ca.architecture' id 'ca.archive-hygiene' id 'ca.public-path-snapshot' - id 'ca.notification-api-surface' - id 'ca.notification-evidence' - id 'ca.notification-configuration' id 'ca.jpa-qualification' - id 'ca.messaging-qualification' id 'ca.developer-bootstrap' } @@ -34,9 +26,6 @@ plugins { // this entire repository. The root still owns the repository group; the convention owns version. group = 'dev.caskeleton' -// Conditional transport evidence wiring and verification live in -// ca.conditional-transport-qualification. - // One explicit command regenerates every module's Gradle-default lockfile. tasks.register('resolveAndLockAll') { group = 'build setup' @@ -60,37 +49,23 @@ tasks.register('verifyDependencyLocks') { // // ::check that leaf — compile, its tests, Spotless, Checkstyle, Error Prone // check every leaf's check (Gradle matches the name across projects) -// architectureCheck dependency direction + app-bootstrap whole-repository ArchUnit rules +// architectureCheck dependency direction + purity + app-bootstrap whole-repository ArchUnit // qualityCheck SpotBugs + FindSecBugs across every leaf (ca.quality-conventions) -// configContractCheck the environment contract (:app-bootstrap) -// integrationCheck the declared strict test lanes (ca.strict-test-lane) -// qualificationCheck full boot composition + auxiliary-source style checks -// ci leaf checks + repository gates + qualification +// ci the pull-request gate: leaf checks + architectureCheck + qualityCheck +// mainCheck the main-branch stage: environment contract, full-boot qualification, +// sample web contract, public-path baseline, API surfaces, transport and +// messaging qualification lanes, JPA readiness registry +// integrationCheck the declared strict integration lanes (several need a container runtime) // releaseCheck ci + archive hygiene + public path snapshot + release provenance // -// There is no root `check`. There used to be, holding nine repository-wide gates, and before that -// every one of them hung off all main-build leaves — so `./gradlew :domain-core:check` compiled cache-redis, -// walked the repository twice and parsed every runbook. A leaf's check is that leaf's; a repository -// question gets a repository task with a name that says which question. +// A leaf's check is that leaf's; a repository question gets a repository task named after it. +// Task PATHS, not TaskProviders: a leaf's tasks are created by convention plugins after the root is +// evaluated, and a path is resolved when the task graph is built. // --------------------------------------------------------------------------------------------- - -// Task PATHS, not TaskProviders. The root is evaluated before any leaf, and a leaf's `check`, -// `qualityCheck` and the category-specific test-lane checks are created by convention plugins — -// so `project(':x').tasks.named('check')` from here resolves a task that does not exist yet. A path -// string is resolved when the task graph is built, which is after every project is evaluated. -// -// This is the visible cost of leaves owning their own plugins, and it is the right trade: the root -// no longer reaches into another project's task container at all. List leafPaths = subprojects.findAll { it.childProjects.isEmpty() && it.path != ':sample-portfolio' }.collect { it.path }.toSorted() -tasks.register('quarantineTest') { - group = 'verification' - description = 'Runs advisory quarantine tests across production CI leaves only.' - dependsOn leafPaths.collect { "${it}:quarantineTest" } -} - tasks.register('qualityCheck') { group = 'verification' description = 'Runs SpotBugs and FindSecBugs across every production CI leaf.' @@ -100,9 +75,6 @@ tasks.register('qualityCheck') { tasks.register('configContractCheck') { group = 'verification' description = 'Runs the environment contract owned by the composition root.' - // verifyEnvKeys only. The operational-error registry contract compared two checked-in files and - // needed nothing from the build, so it is a test in app-bootstrap now - // (OperationalErrorRegistryContractTest) and runs with that leaf's `check`. dependsOn ':app-bootstrap:verifyEnvKeys' } @@ -135,15 +107,42 @@ tasks.register('sampleWebContractCheck') { dependsOn ':sample-portfolio:webSystemTest' } +// Each lane below names its tests and rejects skips; these two only aggregate them. +tasks.register('conditionalTransportQualification') { + group = 'verification' + description = 'Runs the no-skip GraphQL, gRPC and WebSocket transport lanes and the opt-in classpath contract.' + dependsOn ':adapter:inbound:graphql:graphqlTransportQualificationTest', + ':adapter:inbound:grpc:grpcTransportQualificationTest', + ':adapter:inbound:websocket:websocketTransportQualificationTest', + ':app-bootstrap:conditionalTransportBuildContractTest' +} + +tasks.register('verifyMessagingContracts') { + group = 'verification' + description = 'Qualifies the application integration-event contract and the shared envelope schema.' + dependsOn ':application-core:messagingApplicationContractQualificationTest', + ':shared-contract:messagingSharedSchemaQualificationTest' +} + tasks.register('ci') { group = 'verification' - description = 'The pull-request gate: every production CI leaf check plus the repository-wide gates.' + description = 'The pull-request gate: every production CI leaf check plus the architecture and quality gates.' dependsOn leafPaths.collect { "${it}:check" } dependsOn tasks.named('architectureCheck') dependsOn tasks.named('qualityCheck') +} + +tasks.register('mainCheck') { + group = 'verification' + description = 'The main-branch stage: the gates that are not worth a pull request\'s wait.' + dependsOn leafPaths.collect { "${it}:mainCheck" } dependsOn tasks.named('configContractCheck') dependsOn tasks.named('qualificationCheck') dependsOn tasks.named('sampleWebContractCheck') + dependsOn tasks.named('verifyPublicPathSnapshot') + dependsOn tasks.named('conditionalTransportQualification') + dependsOn tasks.named('verifyMessagingContracts') + dependsOn ':adapter:inbound:graphql:graphqlStableTest' } tasks.register('releaseCheck') { diff --git a/src/composition/fileserver-platform/README.md b/src/composition/fileserver-platform/README.md new file mode 100644 index 00000000..1374354b --- /dev/null +++ b/src/composition/fileserver-platform/README.md @@ -0,0 +1,50 @@ +# composition:fileserver-platform — 파일 서버 capability + +- Module ID: `composition-fileserver-platform` +- Gradle path: `:composition:fileserver-platform` +- Package: `dev.caskeleton.composition.fileserver` +- 테스트: `./gradlew :composition:fileserver-platform:test --console=plain` + +## 제공하는 것 + +이 모듈 하나를 붙이면 HTTP 파일 서버 전체가 들어온다. + +``` +composition:fileserver-platform + ├─ FileserverPlatformAutoConfiguration HTTP surface·startup 정책·cleanup worker 조립 + ├─ FileserverAdminManagementContextConfiguration 관리 포트의 admin endpoint + ├─ config/module-defaults/fileserver.yml (설정 기본값, support 로더가 읽음) + ├─ adapter:outbound:fileserver 저장소·검증·업로드·다운로드 (FileserverCapabilityAutoConfiguration) + ├─ adapter:outbound:persistence-fileserver 메타데이터·quota·recovery 테이블 + └─ adapter:inbound:web-fileserver 업로드/다운로드/lifecycle route +``` + +- 켜기와 끄기: 모듈이 있으면 켜진다. `APP_FILESERVER_PLATFORM_ENABLED=false`로만 끈다. 끄면 detail + 설정도 바인딩되지 않는다. +- 설정: `config/module-defaults/fileserver.yml`을 support의 `ModuleDefaultsEnvironmentPostProcessor`가 읽는다. 우선순위가 가장 낮아서 `application*.yml`, 환경 + 변수, 시스템 속성이 항상 이긴다. servlet multipart 상한(`spring.servlet.multipart.*`)도 같은 + placeholder로 이 파일이 준다. app-bootstrap은 이 파일을 모른다. +- 저장소: 메타데이터 테이블은 JPA(`adapter:outbound:persistence-jpa`)가 있어야 한다. + +## 추가할 한 줄 + +```groovy +// app-bootstrap/build.gradle +runtimeOnly project(':composition:fileserver-platform') // 파일 서버 +``` + +이 줄을 지우면 route, 저장소, 메타데이터, 설정 기본값이 모두 함께 빠진다. 기본 조립에는 없다. + +## 필요한 env 키 + +전체 목록과 타입·기본값은 `docs/registries/env-keys.yaml`의 `APP_FILESERVER_PLATFORM_*` 행이 +SSOT다. 설명은 `docs/fileserver/configuration.md`. + +| 언제 | 키 | +| --- | --- | +| 항상 | `APP_FILESERVER_PLATFORM_STORAGE_ROOT` (절대 경로, 전용 volume) | +| 항상 (metrics 기본 on) | `APP_FILESERVER_PLATFORM_OBSERVABILITY_FINGERPRINT_KEY` (secret), 또는 `APP_FILESERVER_PLATFORM_OBSERVABILITY_METRICS_ENABLED=false` | +| 다중 인스턴스 | `APP_FILESERVER_PLATFORM_INSTANCE_ID` (인스턴스마다 다르게) | +| 접근 정책 | 기본 `required`는 `FileAccessPolicy` bean이 있어야 한다. 아니면 `APP_FILESERVER_PLATFORM_SECURITY_ACCESS_POLICY=role-based` | + +나머지(업로드·다운로드 상한, quota, cleanup, tus, nginx 위임)는 기본값으로 동작한다. diff --git a/src/composition/fileserver-platform/build.gradle b/src/composition/fileserver-platform/build.gradle index d20132d5..eedfe4f6 100644 --- a/src/composition/fileserver-platform/build.gradle +++ b/src/composition/fileserver-platform/build.gradle @@ -13,8 +13,8 @@ plugins { // is why every application shipped Fileserver whether or not it wanted it. // // This module is not a composition root. It composes one capability; it does not run. What decides -// whether an application ships Fileserver is one project dependency in `app-bootstrap/build.gradle`, -// and its absence is enforced there by `dependencyPolicy`. +// whether an application ships Fileserver is one commented `runtimeOnly` line in +// `app-bootstrap/build.gradle`. // // It is deliberately thin: cross-adapter wiring only. A configuration that knows one leaf belongs to // that leaf — the fileserver platform's own settings, storage gateway, verification and security diff --git a/src/composition/fileserver-platform/gradle.lockfile b/src/composition/fileserver-platform/gradle.lockfile index c8cf8de0..e8b26147 100644 --- a/src/composition/fileserver-platform/gradle.lockfile +++ b/src/composition/fileserver-platform/gradle.lockfile @@ -58,7 +58,6 @@ io.micrometer:micrometer-commons:1.16.7=compileClasspath,runtimeClasspath,testCo io.micrometer:micrometer-core:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath io.micrometer:micrometer-jakarta9:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath io.micrometer:micrometer-observation:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.projectreactor:reactor-core:3.8.7=runtimeClasspath,testRuntimeClasspath io.swagger.core.v3:swagger-annotations-jakarta:2.2.38=runtimeClasspath,testRuntimeClasspath io.swagger.core.v3:swagger-core-jakarta:2.2.38=runtimeClasspath,testRuntimeClasspath io.swagger.core.v3:swagger-models-jakarta:2.2.38=runtimeClasspath,testRuntimeClasspath @@ -142,7 +141,6 @@ org.ow2.asm:asm-util:9.10.1=spotbugs org.ow2.asm:asm:9.10.1=spotbugs org.ow2.asm:asm:9.7.1=testCompileClasspath,testRuntimeClasspath org.pcollections:pcollections:4.0.1=annotationProcessor,testAnnotationProcessor -org.reactivestreams:reactive-streams:1.0.4=runtimeClasspath,testRuntimeClasspath org.reflections:reflections:0.10.2=checkstyle org.skyscreamer:jsonassert:1.5.3=testCompileClasspath,testRuntimeClasspath org.slf4j:jul-to-slf4j:2.0.18=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath @@ -218,7 +216,6 @@ org.springframework:spring-orm:7.0.9=runtimeClasspath,testRuntimeClasspath org.springframework:spring-test:7.0.9=testCompileClasspath,testRuntimeClasspath org.springframework:spring-tx:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework:spring-web:7.0.9=runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-webflux:7.0.9=runtimeClasspath,testRuntimeClasspath org.springframework:spring-webmvc:7.0.9=runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.xmlresolver:xmlresolver:5.3.3=checkstyle,spotbugs org.xmlunit:xmlunit-core:2.10.4=testCompileClasspath,testRuntimeClasspath diff --git a/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverPlatformAutoConfiguration.java b/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverPlatformAutoConfiguration.java index 556e5008..9f31ea18 100644 --- a/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverPlatformAutoConfiguration.java +++ b/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverPlatformAutoConfiguration.java @@ -1,5 +1,6 @@ package dev.caskeleton.composition.fileserver; +import dev.caskeleton.adapter.inbound.web.fileserver.config.FileserverHttpSurfaceConfiguration; import dev.caskeleton.adapter.outbound.fileserver.platform.autoconfigure.FileserverPlatformSettings; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; @@ -23,7 +24,8 @@ import org.springframework.context.annotation.Import; @ConditionalOnProperty( prefix = FileserverPlatformSettings.PREFIX, name = "enabled", - havingValue = "true") + havingValue = "true", + matchIfMissing = true) @Import({ FileserverCorePolicyConfiguration.class, FileserverWebAssemblyConfiguration.class, @@ -39,6 +41,9 @@ import org.springframework.context.annotation.Import; // they were left. FileserverLocalStorageCoreConfiguration.class, FileserverUploadServiceConfiguration.class, - FileserverCleanupConfiguration.class + FileserverCleanupConfiguration.class, + // The HTTP surface itself. Its controllers used to be found by the composition root's component + // scan of `dev.caskeleton.adapter`; the capability now brings them, so selecting it is enough. + FileserverHttpSurfaceConfiguration.class }) public class FileserverPlatformAutoConfiguration {} diff --git a/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverProtocolConfiguration.java b/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverProtocolConfiguration.java index 77679871..e9c4ef17 100644 --- a/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverProtocolConfiguration.java +++ b/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverProtocolConfiguration.java @@ -1,7 +1,6 @@ package dev.caskeleton.composition.fileserver; import dev.caskeleton.adapter.inbound.web.fileserver.draft12.Draft12Properties; -import dev.caskeleton.adapter.inbound.web.fileserver.tus.TusChecksumVerifier; import dev.caskeleton.adapter.inbound.web.fileserver.tus.TusProperties; import dev.caskeleton.adapter.inbound.web.fileserver.tus.TusRequestParser; import dev.caskeleton.adapter.outbound.fileserver.platform.autoconfigure.FileserverPlatformSettings; @@ -15,7 +14,7 @@ import org.springframework.context.annotation.Configuration; class FileserverProtocolConfiguration { /** - * tus support objects, contributed only when both this switch and the master switch are on. + * tus support objects, contributed only when both this switch and the capability switch are on. * *

The nesting is the fix: previously the protocol's own flag was the only condition, so * enabling tus in a deployment with the Fileserver off produced a controller with no service @@ -45,16 +44,6 @@ class FileserverProtocolConfiguration { return new TusRequestParser(tusProperties); } - @Bean - @ConditionalOnMissingBean - @ConditionalOnProperty( - prefix = FileserverPlatformSettings.PREFIX + ".tus", - name = "enabled", - havingValue = "true") - TusChecksumVerifier fileserverTusChecksumVerifier() { - return new TusChecksumVerifier(); - } - /** * Settings for the experimental draft, which previously had no production binding at all. * diff --git a/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverUploadServiceConfiguration.java b/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverUploadServiceConfiguration.java index 98c260a8..0d9b8838 100644 --- a/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverUploadServiceConfiguration.java +++ b/src/composition/fileserver-platform/src/main/java/dev/caskeleton/composition/fileserver/FileserverUploadServiceConfiguration.java @@ -30,7 +30,6 @@ import dev.caskeleton.application.fileserver.upload.UploadContentGateway; import dev.caskeleton.application.fileserver.upload.UploadIdentifierFactory; import dev.caskeleton.application.fileserver.upload.UploadPolicy; import dev.caskeleton.application.fileserver.upload.UploadStorageGateway; -import dev.caskeleton.application.transaction.PolicyTransactionPort; import dev.caskeleton.application.transaction.TransactionPort; import java.time.Clock; import org.springframework.beans.factory.ObjectProvider; @@ -84,7 +83,7 @@ class FileserverUploadServiceConfiguration { UploadIdentifierFactory identifierFactory, UploadPolicy uploadPolicy, ObjectProvider metrics, - PolicyTransactionPort transactions, + TransactionPort transactions, Clock clock) { return new DefaultUploadApplicationService( metadataStore, @@ -114,7 +113,7 @@ class FileserverUploadServiceConfiguration { CleanupQueue cleanupQueue, RecoveryQueue recoveryQueue, LocalBlockingContentStore store, - PolicyTransactionPort transactions, + TransactionPort transactions, Clock clock) { return new DefaultFinalizeUploadService( metadataStore, diff --git a/src/app-bootstrap/src/main/resources/config/fileserver.yml b/src/composition/fileserver-platform/src/main/resources/config/module-defaults/fileserver.yml similarity index 75% rename from src/app-bootstrap/src/main/resources/config/fileserver.yml rename to src/composition/fileserver-platform/src/main/resources/config/module-defaults/fileserver.yml index 7dac305e..58b796c4 100644 --- a/src/app-bootstrap/src/main/resources/config/fileserver.yml +++ b/src/composition/fileserver-platform/src/main/resources/config/module-defaults/fileserver.yml @@ -1,40 +1,25 @@ -# 파일 전송 경계와 Fileserver 플랫폼. +# Fileserver capability 설정 기본값. # -# application.yml 이 spring.config.import 로 취합한다. 이 파일의 값은 application.yml 보다 -# 낮고 application-{profile}.yml 보다도 낮으므로, 배포별 오버라이드는 그대로 우선한다. +# adapter:outbound:support 의 ModuleDefaultsEnvironmentPostProcessor 가 읽는다. 우선순위는 가장 낮아서 +# application*.yml, 환경 변수, 시스템 속성이 항상 이긴다. 이 모듈을 빌드에서 빼면 이 파일도 함께 +# 빠진다. +spring: + servlet: + multipart: + # app.fileserver-platform.upload.* 와 같은 placeholder 를 쓴다. 두 상한이 따로 있으면 servlet + # container 가 Fileserver 정책이 허용한 업로드를 Fileserver 코드(에러 매핑 포함)가 돌기 전에 + # 거절한다. 이 모듈이 없으면 Spring 기본값이 적용된다. + max-file-size: ${APP_FILESERVER_PLATFORM_UPLOAD_MAX_FILE_SIZE:100MB} + max-request-size: ${APP_FILESERVER_PLATFORM_UPLOAD_MAX_REQUEST_SIZE:110MB} app: - fileserver: - enabled: ${APP_FILESERVER_ENABLED:false} - destinations: - local-export: - provider-ref: local-primary - required-publication: unique-atomic-create - required-durability: file-and-directory-sync - maximum-rows: 1000000 - maximum-encoded-bytes: 1073741824 - providers: - local-primary: - # local-persistent is the only implemented/qualified R2 provider. - # shared-mounted/NFS and SFTP settings must not be added before their providers exist. - type: local-persistent - root-directory: ${APP_FILESERVER_LOCAL_ROOT:} - auto-create: false - strict-path-security: true - expected-file-store-name: ${APP_FILESERVER_LOCAL_EXPECTED_FILE_STORE_NAME:} - expected-file-store-type: ${APP_FILESERVER_LOCAL_EXPECTED_FILE_STORE_TYPE:} - mount-sentinel-name: .ca-fileserver-volume - mount-sentinel-sha256: ${APP_FILESERVER_LOCAL_MOUNT_SENTINEL_SHA256:} - expected-owner: ${APP_FILESERVER_LOCAL_EXPECTED_OWNER:} - maximum-root-mode: "0750" - # HTTP Fileserver platform — a different capability from app.fileserver above, which publishes - # tabular exports. This one serves upload/download/lifecycle routes over HTTP and owns its own - # namespace so the two cannot be switched on by accident together. + # HTTP Fileserver platform: upload/download/lifecycle routes over HTTP. # # While enabled=false none of the detail below is bound: FileserverPlatformAutoConfiguration - # binds the block itself, and it is not processed until the master switch is true. Unknown keys + # binds the block itself, and it is not processed until the capability switch is true. Unknown keys # under this prefix are refused rather than ignored. fileserver-platform: - enabled: ${APP_FILESERVER_PLATFORM_ENABLED:false} + # true | false — 모듈이 있으면 켜진다. false 로만 끈다. + enabled: ${APP_FILESERVER_PLATFORM_ENABLED:true} # Writer-lease owner. Must be unique per instance in a multi-instance deployment; the startup # gate treats the default as single-instance. instance-id: ${APP_FILESERVER_PLATFORM_INSTANCE_ID:local-node} @@ -48,7 +33,7 @@ app: buffer-size: ${APP_FILESERVER_PLATFORM_STORAGE_BUFFER_SIZE:128KB} forbidden-root-ancestors: ${APP_FILESERVER_PLATFORM_STORAGE_FORBIDDEN_ROOT_ANCESTORS:/app,/etc,/usr/share/nginx/html} upload: - # Shared with spring.servlet.multipart below through the same placeholder. Two independent + # Shared with spring.servlet.multipart above through the same placeholder. Two independent # limits would let the servlet container reject an upload the Fileserver policy allows, # before any Fileserver code — including its error mapping — ever runs. max-file-size: ${APP_FILESERVER_PLATFORM_UPLOAD_MAX_FILE_SIZE:100MB} diff --git a/src/composition/fileserver-platform/src/test/java/dev/caskeleton/composition/fileserver/FileserverAssemblyFixture.java b/src/composition/fileserver-platform/src/test/java/dev/caskeleton/composition/fileserver/FileserverAssemblyFixture.java index 07dafb2b..485e6434 100644 --- a/src/composition/fileserver-platform/src/test/java/dev/caskeleton/composition/fileserver/FileserverAssemblyFixture.java +++ b/src/composition/fileserver-platform/src/test/java/dev/caskeleton/composition/fileserver/FileserverAssemblyFixture.java @@ -11,9 +11,7 @@ import dev.caskeleton.application.fileserver.cleanup.QuotaReclaimGateway; import dev.caskeleton.application.fileserver.recovery.RecoveryQueue; import dev.caskeleton.application.fileserver.recovery.StagingUploadLocator; import dev.caskeleton.application.fileserver.upload.QuotaCommitGateway; -import dev.caskeleton.application.transaction.PolicyTransactionPort; -import dev.caskeleton.application.transaction.TransactionRequest; -import dev.caskeleton.application.transaction.TransactionResult; +import dev.caskeleton.application.transaction.TransactionPort; import java.io.IOException; import java.io.UncheckedIOException; import java.nio.file.Files; @@ -52,8 +50,8 @@ public abstract class FileserverAssemblyFixture { * — what this proves is that the wiring supplies one at all. */ @Bean - PolicyTransactionPort transactions() { - return new PolicyTransactionPort() { + TransactionPort transactions() { + return new TransactionPort() { @Override public T inWrite(java.util.function.Supplier action) { return action.get(); @@ -73,12 +71,6 @@ public abstract class FileserverAssemblyFixture { public T inNew(java.util.function.Supplier action) { return action.get(); } - - @Override - public TransactionResult inTransaction( - TransactionRequest request, java.util.function.Supplier action) { - return new TransactionResult.Committed<>(action.get(), request.operationId()); - } }; } diff --git a/src/composition/fileserver-platform/src/test/java/dev/caskeleton/composition/fileserver/FileserverModuleDefaultsTest.java b/src/composition/fileserver-platform/src/test/java/dev/caskeleton/composition/fileserver/FileserverModuleDefaultsTest.java new file mode 100644 index 00000000..dc29acfe --- /dev/null +++ b/src/composition/fileserver-platform/src/test/java/dev/caskeleton/composition/fileserver/FileserverModuleDefaultsTest.java @@ -0,0 +1,48 @@ +package dev.caskeleton.composition.fileserver; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.adapter.outbound.support.startup.ModuleDefaultsEnvironmentPostProcessor; +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.springframework.boot.SpringApplication; +import org.springframework.core.env.MapPropertySource; +import org.springframework.core.env.StandardEnvironment; + +/** + * The module ships its settings under config/module-defaults, and a deployment's value beats them. + */ +class FileserverModuleDefaultsTest { + + @Test + void theShippedDefaultsTurnThePlatformOnAndShareTheUploadCeilingWithTheServlet() { + StandardEnvironment environment = processed(Map.of()); + + assertThat(environment.getProperty("app.fileserver-platform.enabled")).isEqualTo("true"); + assertThat(environment.getProperty("spring.servlet.multipart.max-file-size")) + .isEqualTo(environment.getProperty("app.fileserver-platform.upload.max-file-size")) + .isEqualTo("100MB"); + } + + @Test + void theEnvironmentVariableTurnsItOffAndMovesBothCeilingsTogether() { + StandardEnvironment environment = + processed( + Map.of( + "APP_FILESERVER_PLATFORM_ENABLED", "false", + "APP_FILESERVER_PLATFORM_UPLOAD_MAX_FILE_SIZE", "5MB")); + + assertThat(environment.getProperty("app.fileserver-platform.enabled")).isEqualTo("false"); + assertThat(environment.getProperty("spring.servlet.multipart.max-file-size")).isEqualTo("5MB"); + assertThat(environment.getProperty("app.fileserver-platform.upload.max-file-size")) + .isEqualTo("5MB"); + } + + private static StandardEnvironment processed(Map deployment) { + StandardEnvironment environment = new StandardEnvironment(); + environment.getPropertySources().addFirst(new MapPropertySource("deployment", deployment)); + new ModuleDefaultsEnvironmentPostProcessor() + .postProcessEnvironment(environment, new SpringApplication()); + return environment; + } +} diff --git a/src/composition/fileserver-platform/src/test/java/dev/caskeleton/composition/fileserver/FileserverPlatformAutoConfigurationTest.java b/src/composition/fileserver-platform/src/test/java/dev/caskeleton/composition/fileserver/FileserverPlatformAutoConfigurationTest.java index 83bd37c0..6db91239 100644 --- a/src/composition/fileserver-platform/src/test/java/dev/caskeleton/composition/fileserver/FileserverPlatformAutoConfigurationTest.java +++ b/src/composition/fileserver-platform/src/test/java/dev/caskeleton/composition/fileserver/FileserverPlatformAutoConfigurationTest.java @@ -40,6 +40,7 @@ class FileserverPlatformAutoConfigurationTest { void disabledCapabilityIgnoresDetailAndSubFeatureSettings() { runner .withPropertyValues( + "app.fileserver-platform.enabled=false", "app.fileserver-platform.upload.ttl=not-a-duration", "app.fileserver-platform.storage.buffer-size=not-a-size", "app.fileserver-platform.storage.root=relative/path", @@ -120,7 +121,7 @@ class FileserverPlatformAutoConfigurationTest { * the startup log mentions it. */ @Test - void aMasterSwitchThatIsNotABooleanDoesNotSilentlyEnableTheCapability() { + void anEnabledValueThatIsNotABooleanDoesNotSilentlyEnableTheCapability() { runner .withPropertyValues("app.fileserver-platform.enabled=yes") .run( @@ -156,7 +157,6 @@ class FileserverPlatformAutoConfigurationTest { @Test void enabledDefaultsAssembleTheExpectedRuntime() { enabled() - .withPropertyValues("app.fileserver.enabled=false", "app.file-export.enabled=false") .run( context -> { assertThat(context).hasNotFailed(); @@ -185,11 +185,6 @@ class FileserverPlatformAutoConfigurationTest { assertThat(properties.maxSize()).isEqualTo(32); assertThat(properties.queueCapacity()).isEqualTo(64); }); - - assertThat(context.getEnvironment().getProperty("app.fileserver.enabled")) - .isEqualTo("false"); - assertThat(context.getEnvironment().getProperty("app.file-export.enabled")) - .isEqualTo("false"); }); } diff --git a/src/composition/fileserver-platform/src/test/java/dev/caskeleton/composition/fileserver/FileserverPlatformEnvRoundTripTest.java b/src/composition/fileserver-platform/src/test/java/dev/caskeleton/composition/fileserver/FileserverPlatformEnvRoundTripTest.java index aa34c551..3f9ab250 100644 --- a/src/composition/fileserver-platform/src/test/java/dev/caskeleton/composition/fileserver/FileserverPlatformEnvRoundTripTest.java +++ b/src/composition/fileserver-platform/src/test/java/dev/caskeleton/composition/fileserver/FileserverPlatformEnvRoundTripTest.java @@ -46,7 +46,7 @@ class FileserverPlatformEnvRoundTripTest { FileserverPlatformSettings bound = bindStrictly(environmentVariables); - assertThat(bound.enabled()).isFalse(); + assertThat(bound.enabled()).isTrue(); assertThat(bound.storage().root().isAbsolute()).isTrue(); assertThat(bound.upload().maxRequestSize().toBytes()) .isGreaterThanOrEqualTo(bound.upload().maxFileSize().toBytes()); @@ -54,13 +54,17 @@ class FileserverPlatformEnvRoundTripTest { assertThat(bound.storage().forbiddenRootAncestors()).isNotEmpty(); } - /** The shipped defaults must be the conservative ones, in the file operators actually copy. */ + /** + * The shipped defaults must be the conservative ones, in the file operators actually copy. The + * master switch is on — the capability is present only where a service selected it — and every + * optional surface inside it stays off. + */ @Test void theShippedEnvironmentKeepsEveryOptionalSurfaceOff() { Map environmentVariables = declaredPlatformEnvironment(); assertThat(environmentVariables) - .containsEntry("APP_FILESERVER_PLATFORM_ENABLED", "false") + .containsEntry("APP_FILESERVER_PLATFORM_ENABLED", "true") .containsEntry("APP_FILESERVER_PLATFORM_ADMIN_ENABLED", "false") .containsEntry("APP_FILESERVER_PLATFORM_CLEANUP_ENABLED", "false") .containsEntry("APP_FILESERVER_PLATFORM_TUS_ENABLED", "false") diff --git a/src/composition/notification-platform/README.md b/src/composition/notification-platform/README.md new file mode 100644 index 00000000..6a4742c2 --- /dev/null +++ b/src/composition/notification-platform/README.md @@ -0,0 +1,62 @@ +# composition:notification-platform — 알림 capability + +- Module ID: `composition-notification-platform` +- Gradle path: `:composition:notification-platform` +- Package: `dev.caskeleton.composition.notification` +- 테스트: `./gradlew :composition:notification-platform:test --console=plain` + +## 제공하는 것 + +이 모듈 하나를 붙이면 알림 기능 전체가 들어온다. + +``` +composition:notification-platform + ├─ NotificationApplicationCompositionAutoConfiguration (use case 조립, `enabled` 조건) + │ ├─ NotificationSubmissionConfiguration 접수·예약·취소·조회·템플릿 발행 use case + │ ├─ NotificationDeliveryConfiguration 발송·재조정·lease 회수·ledger 투영·운영자 plane + │ └─ NotificationCallbackConfiguration provider 콜백 수집 + ProviderCallbackIngressBridge + ├─ config/module-defaults/notification.yml (설정 기본값, support 로더가 읽음) + ├─ adapter:outbound:notification provider(SMTP·SES), 저장 외 런타임, NotificationPlatformAutoConfiguration + └─ adapter:inbound:web-notification POST /notifications, POST /notification-templates, + POST /internal/notification/callbacks/{provider}/{profile} +``` + +- 조립 순서: 이 모듈의 root는 `NotificationPlatformAutoConfiguration`(outbound leaf) 뒤에 온다 + (`afterName`). +- 설정: `config/module-defaults/notification.yml`을 support의 `ModuleDefaultsEnvironmentPostProcessor`가 읽는다. 우선순위는 가장 낮다. 그래서 + `application*.yml`, 환경 변수, 시스템 속성이 항상 이긴다. app-bootstrap은 이 파일을 모른다. +- 저장소: 요청·발송·ledger 테이블은 `adapter:outbound:persistence-jpa`에 있다. 그래서 + persistence-jpa 줄도 함께 넣어야 하고, `APP_PERSISTENCE_JPA_ENABLED=false`로 끄면 안 된다. + +## 추가할 한 줄 + +```groovy +// app-bootstrap/build.gradle +runtimeOnly project(':adapter:outbound:persistence-jpa') // 알림 저장소 +runtimeOnly project(':composition:notification-platform') // 알림 +``` + +기본 조립에는 없다(`app-bootstrap/build.gradle`에 주석 처리된 줄로 있다). 이 줄을 지우면 use case +조립, provider 어댑터, HTTP 엔드포인트, 설정 기본값이 모두 함께 빠진다. + +## 켜기와 끄기 + +모듈이 있으면 켜진다. `ca-skeleton.notification.platform.enabled`(`APP_NOTIFICATION_PLATFORM_ENABLED`, +기본 `true`)를 `false`로 줄 때만 꺼지고, 그때는 아무것도 바인딩하지 않는다. 켜진 상태에서는 아래 +"항상" 키가 없으면 기동이 거부된다. + +## 필요한 env 키 + +전체 목록과 타입·기본값은 `docs/registries/env-keys.yaml`의 `APP_NOTIFICATION_*`, +`SPRING_MAIL_*` 행이 SSOT다. 켤 때 실제로 넣어야 하는 것: + +| 언제 | 키 | +| --- | --- | +| 항상 | persistence-jpa 줄과 그 연결 env(`APP_DATASOURCE_URL`, `APP_DATASOURCE_USERNAME`, `APP_DATASOURCE_PASSWORD`) | +| 항상 (키 8종과 각 키 id, 32바이트 이상 base64, 서로 달라야 함) | `APP_NOTIFICATION_PLATFORM_{CONTACT_ENCRYPTION,CONTACT_LOOKUP_HMAC,CALLBACK_SIGNING,PROVIDER_CREDENTIAL,PAYLOAD_ENCRYPTION,VAPID_SIGNING,PROVIDER_REQUEST_LOOKUP_HMAC,CALLBACK_FINGERPRINT_HMAC}_KEY`, 같은 이름 + `_ID` | +| SMTP provider | `APP_NOTIFICATION_PLATFORM_SMTP_ENABLED=true`, `APP_NOTIFICATION_PLATFORM_SMTP_SENDER_IDENTITY`, `SPRING_MAIL_HOST`, `SPRING_MAIL_PORT`, `SPRING_MAIL_USERNAME`, `SPRING_MAIL_PASSWORD` | +| SES provider | `APP_NOTIFICATION_PLATFORM_SES_ENABLED=true`, `APP_NOTIFICATION_PLATFORM_SES_SENDER_IDENTITY`, `APP_NOTIFICATION_PLATFORM_SES_ACCESS_KEY_ID`, `APP_NOTIFICATION_PLATFORM_SES_CREDENTIAL_KEY_ID`, `APP_NOTIFICATION_PLATFORM_SES_REGION` | +| provider 콜백 | `APP_NOTIFICATION_PLATFORM_CALLBACKS_ENABLED=true`, SES는 `APP_NOTIFICATION_PLATFORM_SES_ALLOWED_TOPIC_ARNS`, 프록시 뒤라면 `APP_NOTIFICATION_PLATFORM_CALLBACK_TRUSTED_PROXIES` | + +나머지(발송 배치 크기, lease, 준비 상태 임계값 등)는 기본값으로 동작한다. 설명은 +`docs/notification/configuration-reference.md`. diff --git a/src/composition/notification-platform/build.gradle b/src/composition/notification-platform/build.gradle new file mode 100644 index 00000000..977923bb --- /dev/null +++ b/src/composition/notification-platform/build.gradle @@ -0,0 +1,35 @@ +plugins { + id 'ca.spring-library' + id 'ca.spring-config' +} + +// The Notification capability, selected by one project dependency. +// +// It holds what used to be app-bootstrap's notification assembly: the application use cases that +// open their own transactions, the bridge from the inbound callback endpoint to the outbound +// provider verification, and the capability's shipped settings (config/module-defaults/notification.yml). It depends +// on the outbound adapter and on the HTTP surface, so an application that adds this module gets the +// whole capability and an application that removes it keeps nothing of it. +// +// Not a composition root: it composes one capability and does not run. Same shape as +// :composition:fileserver-platform. +dependencies { + implementation project(':application-core') + implementation project(':application-notification') + implementation project(':adapter:outbound:notification') + implementation project(':adapter:inbound:web-notification') + + implementation 'org.springframework.boot:spring-boot-autoconfigure' + implementation 'org.springframework:spring-context' + + testImplementation 'org.springframework.boot:spring-boot-starter-test' + // NotificationModuleDefaultsTest reads the shipped file through the loader that serves it at + // runtime (reached there through adapter:outbound:notification). Test scope only. + testImplementation project(':adapter:outbound:support') +} + +// NotificationEnvironmentRegistryTest compares the shipped settings with the environment registry. +tasks.named('test') { + inputs.file(new File(rootProject.projectDir.parentFile, 'docs/registries/env-keys.yaml')) + .withPathSensitivity(PathSensitivity.RELATIVE) +} diff --git a/src/composition/notification-platform/gradle.lockfile b/src/composition/notification-platform/gradle.lockfile new file mode 100644 index 00000000..27e44dd1 --- /dev/null +++ b/src/composition/notification-platform/gradle.lockfile @@ -0,0 +1,201 @@ +# 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. +biz.aQute.bnd:biz.aQute.bnd.annotation:7.1.0=testCompileClasspath +ch.qos.logback:logback-classic:1.5.38=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +ch.qos.logback:logback-core:1.5.38=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +com.ethlo.time:itu:1.14.0=runtimeClasspath,testRuntimeClasspath +com.fasterxml.jackson.core:jackson-annotations:2.21=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +com.fasterxml.jackson.core:jackson-core:2.21.5=runtimeClasspath,testRuntimeClasspath +com.fasterxml.jackson.core:jackson-databind:2.21.5=runtimeClasspath,testRuntimeClasspath +com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:2.21.5=runtimeClasspath,testRuntimeClasspath +com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.21.5=runtimeClasspath,testRuntimeClasspath +com.fasterxml.jackson:jackson-bom:2.21.5=runtimeClasspath,testRuntimeClasspath +com.fasterxml:classmate:1.7.3=runtimeClasspath,testRuntimeClasspath +com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,testAnnotationProcessor +com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,testAnnotationProcessor +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.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_annotations:2.38.0=testCompileClasspath +com.google.errorprone:error_prone_annotations:2.41.0=spotbugs +com.google.errorprone:error_prone_annotations:2.47.0=checkstyle +com.google.errorprone:error_prone_annotations:2.49.0=annotationProcessor,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.5.0-jre=annotationProcessor,testAnnotationProcessor +com.google.guava:guava:33.6.0-jre=checkstyle +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.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins +com.jayway.jsonpath:json-path:2.10.0=testCompileClasspath,testRuntimeClasspath +com.networknt:json-schema-validator:3.0.2=runtimeClasspath,testRuntimeClasspath +com.nimbusds:nimbus-jose-jwt:10.4=runtimeClasspath,testRuntimeClasspath +com.puppycrawl.tools:checkstyle:13.5.0=checkstyle +com.vaadin.external.google:android-json:0.0.20131108.vaadin1=testCompileClasspath,testRuntimeClasspath +commons-beanutils:commons-beanutils:1.11.0=checkstyle +commons-collections:commons-collections:3.2.2=checkstyle +commons-io:commons-io:2.21.0=spotbugs +commons-logging:commons-logging:1.3.6=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +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 +io.micrometer:micrometer-commons:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +io.micrometer:micrometer-core:1.16.7=runtimeClasspath,testRuntimeClasspath +io.micrometer:micrometer-observation:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +io.swagger.core.v3:swagger-annotations-jakarta:2.2.38=runtimeClasspath,testRuntimeClasspath +io.swagger.core.v3:swagger-core-jakarta:2.2.38=runtimeClasspath,testRuntimeClasspath +io.swagger.core.v3:swagger-models-jakarta:2.2.38=runtimeClasspath,testRuntimeClasspath +jakarta.activation:jakarta.activation-api:2.1.4=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +jakarta.annotation:jakarta.annotation-api:3.0.0=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +jakarta.mail:jakarta.mail-api:2.1.5=runtimeClasspath,testRuntimeClasspath +jakarta.validation:jakarta.validation-api:3.1.1=runtimeClasspath,testRuntimeClasspath +jakarta.xml.bind:jakarta.xml.bind-api:4.0.5=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +javax.inject:javax.inject:1=annotationProcessor,testAnnotationProcessor +jaxen:jaxen:2.0.6=spotbugs +net.bytebuddy:byte-buddy-agent:1.17.8=testCompileClasspath,testRuntimeClasspath +net.bytebuddy:byte-buddy:1.17.8=testCompileClasspath,testRuntimeClasspath +net.minidev:accessors-smart:2.6.0=testCompileClasspath,testRuntimeClasspath +net.minidev:json-smart:2.6.0=testCompileClasspath,testRuntimeClasspath +net.sf.saxon:Saxon-HE:12.9=checkstyle,spotbugs +ognl:ognl:3.3.4=runtimeClasspath,testRuntimeClasspath +org.antlr:antlr4-runtime:4.13.2=checkstyle +org.apache.bcel:bcel:6.12.0=spotbugs +org.apache.commons:commons-lang3:3.20.0=checkstyle,runtimeClasspath,spotbugs,testRuntimeClasspath +org.apache.commons:commons-text:1.15.0=spotbugs +org.apache.commons:commons-text:1.3=checkstyle +org.apache.httpcomponents:httpclient:4.5.13=checkstyle +org.apache.httpcomponents:httpcore:4.4.16=checkstyle +org.apache.logging.log4j:log4j-api:2.25.5=runtimeClasspath,spotbugs,testCompileClasspath,testRuntimeClasspath +org.apache.logging.log4j:log4j-core:2.25.5=spotbugs +org.apache.logging.log4j:log4j-to-slf4j:2.25.5=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.apache.maven.doxia:doxia-core:1.12.0=checkstyle +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.tomcat.embed:tomcat-embed-core:11.0.24=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.apache.tomcat.embed:tomcat-embed-el:11.0.24=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.apache.tomcat.embed:tomcat-embed-websocket:11.0.24=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.apache.xbean:xbean-reflect:3.7=checkstyle +org.apiguardian:apiguardian-api:1.1.2=testCompileClasspath +org.assertj:assertj-core:3.27.7=testCompileClasspath,testRuntimeClasspath +org.attoparser:attoparser:2.0.7.RELEASE=runtimeClasspath,testRuntimeClasspath +org.awaitility:awaitility:4.3.0=testCompileClasspath,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.3.0=checkstyle +org.dom4j:dom4j:2.2.0=spotbugs +org.eclipse.angus:angus-activation:2.0.3=runtimeClasspath,testRuntimeClasspath +org.eclipse.angus:angus-mail:2.0.5=runtimeClasspath,testRuntimeClasspath +org.hamcrest:hamcrest:3.0=testCompileClasspath,testRuntimeClasspath +org.hdrhistogram:HdrHistogram:2.2.2=runtimeClasspath,testRuntimeClasspath +org.hibernate.validator:hibernate-validator:9.0.1.Final=runtimeClasspath,testRuntimeClasspath +org.javassist:javassist:3.28.0-GA=checkstyle +org.javassist:javassist:3.29.0-GA=runtimeClasspath,testRuntimeClasspath +org.jboss.logging:jboss-logging:3.6.3.Final=runtimeClasspath,testRuntimeClasspath +org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,compileClasspath,runtimeClasspath,testAnnotationProcessor,testCompileClasspath,testRuntimeClasspath +org.junit.jupiter:junit-jupiter-api:6.0.3=testCompileClasspath,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-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.1.0=spotbugs +org.latencyutils:LatencyUtils:2.0.3=runtimeClasspath,testRuntimeClasspath +org.mockito:mockito-core:5.20.0=mockitoAgent,testCompileClasspath,testRuntimeClasspath +org.mockito:mockito-junit-jupiter:5.20.0=testCompileClasspath,testRuntimeClasspath +org.objenesis:objenesis:3.3=testRuntimeClasspath +org.openapitools:jackson-databind-nullable:0.2.6=runtimeClasspath,testRuntimeClasspath +org.opentest4j:opentest4j:1.3.0=testCompileClasspath,testRuntimeClasspath +org.osgi:org.osgi.annotation.bundle:2.0.0=testCompileClasspath +org.osgi:org.osgi.annotation.versioning:1.1.2=testCompileClasspath +org.osgi:org.osgi.resource:1.0.0=testCompileClasspath +org.osgi:org.osgi.service.serviceloader:1.0.0=testCompileClasspath +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.ow2.asm:asm:9.7.1=testCompileClasspath,testRuntimeClasspath +org.pcollections:pcollections:4.0.1=annotationProcessor,testAnnotationProcessor +org.reflections:reflections:0.10.2=checkstyle +org.skyscreamer:jsonassert:1.5.3=testCompileClasspath,testRuntimeClasspath +org.slf4j:jul-to-slf4j:2.0.18=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.slf4j:slf4j-api:2.0.18=runtimeClasspath,spotbugs,spotbugsSlf4j,testCompileClasspath,testRuntimeClasspath +org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j +org.slf4j:slf4j-simple:2.0.18=checkstyle +org.springdoc:springdoc-openapi-starter-common:3.0.0=runtimeClasspath,testRuntimeClasspath +org.springdoc:springdoc-openapi-starter-webmvc-api:3.0.0=runtimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-actuator-autoconfigure:4.0.8=runtimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-actuator:4.0.8=runtimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-autoconfigure:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-configuration-processor:4.0.8=annotationProcessor +org.springframework.boot:spring-boot-health:4.0.8=runtimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-http-converter:4.0.8=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-jackson:4.0.8=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-mail:4.0.8=runtimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-resttestclient:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-security-oauth2-resource-server:4.0.8=runtimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-security:4.0.8=runtimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-servlet:4.0.8=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-jackson-test:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-jackson:4.0.8=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-json:4.0.8=runtimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-logging:4.0.8=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-mail:4.0.8=runtimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-oauth2-resource-server:4.0.8=runtimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-security:4.0.8=runtimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-test:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-tomcat-runtime:4.0.8=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-tomcat:4.0.8=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-validation:4.0.8=runtimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-web:4.0.8=runtimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-webmvc-test:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter-webmvc:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-starter:4.0.8=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-test-autoconfigure:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-test:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-tomcat:4.0.8=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-validation:4.0.8=runtimeClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-web-server:4.0.8=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-webmvc-test:4.0.8=testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot-webmvc:4.0.8=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.boot:spring-boot:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework.security:spring-security-config:7.0.7=runtimeClasspath,testRuntimeClasspath +org.springframework.security:spring-security-core:7.0.7=runtimeClasspath,testRuntimeClasspath +org.springframework.security:spring-security-crypto:7.0.7=runtimeClasspath,testRuntimeClasspath +org.springframework.security:spring-security-oauth2-core:7.0.7=runtimeClasspath,testRuntimeClasspath +org.springframework.security:spring-security-oauth2-jose:7.0.7=runtimeClasspath,testRuntimeClasspath +org.springframework.security:spring-security-oauth2-resource-server:7.0.7=runtimeClasspath,testRuntimeClasspath +org.springframework.security:spring-security-web:7.0.7=runtimeClasspath,testRuntimeClasspath +org.springframework.session:spring-session-core:4.0.5=runtimeClasspath,testRuntimeClasspath +org.springframework:spring-aop:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-beans:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-context-support:7.0.9=runtimeClasspath,testRuntimeClasspath +org.springframework:spring-context:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-core:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-expression:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-test:7.0.9=testCompileClasspath,testRuntimeClasspath +org.springframework:spring-web:7.0.9=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-webmvc:7.0.9=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.thymeleaf:thymeleaf:3.1.5.RELEASE=runtimeClasspath,testRuntimeClasspath +org.unbescape:unbescape:1.1.6.RELEASE=runtimeClasspath,testRuntimeClasspath +org.xmlresolver:xmlresolver:5.3.3=checkstyle,spotbugs +org.xmlunit:xmlunit-core:2.10.4=testCompileClasspath,testRuntimeClasspath +org.yaml:snakeyaml:2.5=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +tools.jackson.core:jackson-core:3.1.5=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +tools.jackson.core:jackson-databind:3.1.5=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +tools.jackson:jackson-bom:3.1.5=runtimeClasspath,testCompileClasspath,testRuntimeClasspath +empty= diff --git a/src/composition/notification-platform/src/main/java/dev/caskeleton/composition/notification/NotificationApplicationCompositionAutoConfiguration.java b/src/composition/notification-platform/src/main/java/dev/caskeleton/composition/notification/NotificationApplicationCompositionAutoConfiguration.java new file mode 100644 index 00000000..98a3d765 --- /dev/null +++ b/src/composition/notification-platform/src/main/java/dev/caskeleton/composition/notification/NotificationApplicationCompositionAutoConfiguration.java @@ -0,0 +1,27 @@ +package dev.caskeleton.composition.notification; + +import org.springframework.boot.autoconfigure.AutoConfiguration; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Import; + +/** + * Application-owned Notification orchestration and transaction-bound use-case assembly. + * + *

The root holds the capability switch and imports one configuration per concern. It orders + * itself after the outbound leaf's root, whose stores, providers and policies every use case here + * consumes. + */ +@AutoConfiguration( + afterName = + "dev.caskeleton.adapter.outbound.notification.platform.autoconfigure.NotificationPlatformAutoConfiguration") +@ConditionalOnProperty( + prefix = "ca-skeleton.notification.platform", + name = "enabled", + havingValue = "true", + matchIfMissing = true) +@Import({ + NotificationSubmissionConfiguration.class, + NotificationDeliveryConfiguration.class, + NotificationCallbackConfiguration.class +}) +public class NotificationApplicationCompositionAutoConfiguration {} diff --git a/src/composition/notification-platform/src/main/java/dev/caskeleton/composition/notification/NotificationCallbackConfiguration.java b/src/composition/notification-platform/src/main/java/dev/caskeleton/composition/notification/NotificationCallbackConfiguration.java new file mode 100644 index 00000000..bbb535e6 --- /dev/null +++ b/src/composition/notification-platform/src/main/java/dev/caskeleton/composition/notification/NotificationCallbackConfiguration.java @@ -0,0 +1,46 @@ +package dev.caskeleton.composition.notification; + +import dev.caskeleton.adapter.inbound.web.notification.platform.callback.ProviderCallbackIngress; +import dev.caskeleton.adapter.outbound.notification.platform.callback.ProviderCallbackAdapterRegistry; +import dev.caskeleton.application.notification.platform.callback.CallbackPayloadProtectionPort; +import dev.caskeleton.application.notification.platform.callback.IngestProviderCallbackApplicationUseCase; +import dev.caskeleton.application.notification.platform.callback.ProviderEventLedger; +import dev.caskeleton.application.notification.platform.observation.NotificationMetricsPort; +import dev.caskeleton.application.notification.platform.observation.NotificationSecurityAuditPort; +import dev.caskeleton.application.notification.platform.port.in.IngestProviderCallbackUseCase; +import dev.caskeleton.application.transaction.TransactionPort; +import java.time.Clock; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** Provider callbacks: semantic ingestion, and the bridge from raw HTTP to it. */ +@Configuration(proxyBeanMethods = false) +class NotificationCallbackConfiguration { + + /** Semantic callback ingestion after provider verification has completed. */ + @Bean + IngestProviderCallbackApplicationUseCase providerCallbackIngestionService( + ProviderEventLedger ledger, + TransactionPort transactions, + CallbackPayloadProtectionPort payloadProtection, + NotificationMetricsPort metrics, + Clock clock) { + return new IngestProviderCallbackApplicationUseCase( + ledger, transactions, payloadProtection, metrics, clock); + } + + /** + * The adapter-to-adapter callback bridge. + * + *

Raw HTTP remains in the inbound adapter, provider signature verification remains in the + * outbound provider integration, and only the verified semantic callback crosses the application + * port. + */ + @Bean + ProviderCallbackIngress providerCallbackIngress( + ProviderCallbackAdapterRegistry adapters, + IngestProviderCallbackUseCase ingestion, + NotificationSecurityAuditPort securityAudit) { + return new ProviderCallbackIngressBridge(adapters, ingestion, securityAudit); + } +} diff --git a/src/composition/notification-platform/src/main/java/dev/caskeleton/composition/notification/NotificationDeliveryConfiguration.java b/src/composition/notification-platform/src/main/java/dev/caskeleton/composition/notification/NotificationDeliveryConfiguration.java new file mode 100644 index 00000000..75aabc7d --- /dev/null +++ b/src/composition/notification-platform/src/main/java/dev/caskeleton/composition/notification/NotificationDeliveryConfiguration.java @@ -0,0 +1,181 @@ +package dev.caskeleton.composition.notification; + +import dev.caskeleton.adapter.outbound.notification.platform.dispatch.NotificationDispatchProperties; +import dev.caskeleton.application.notification.platform.admin.AdminAuthorizationGuard; +import dev.caskeleton.application.notification.platform.admin.AdminOperationStorePort; +import dev.caskeleton.application.notification.platform.admin.DuplicateRiskGuard; +import dev.caskeleton.application.notification.platform.admin.NotificationAdminApplicationService; +import dev.caskeleton.application.notification.platform.admin.NotificationAdminService; +import dev.caskeleton.application.notification.platform.admin.ProviderRuntimeControlPort; +import dev.caskeleton.application.notification.platform.callback.DeliveryAttemptResolverPort; +import dev.caskeleton.application.notification.platform.callback.DeliveryProjectionStorePort; +import dev.caskeleton.application.notification.platform.callback.NotificationSideEffectPort; +import dev.caskeleton.application.notification.platform.callback.ProviderEventLedger; +import dev.caskeleton.application.notification.platform.callback.ProviderEventProjectionService; +import dev.caskeleton.application.notification.platform.callback.ProviderEventProjectorRegistry; +import dev.caskeleton.application.notification.platform.dispatch.DeliveryAttemptFactory; +import dev.caskeleton.application.notification.platform.dispatch.DeliveryAttemptStorePort; +import dev.caskeleton.application.notification.platform.dispatch.DispatchOutcomeRecorder; +import dev.caskeleton.application.notification.platform.dispatch.DispatchPipeline; +import dev.caskeleton.application.notification.platform.dispatch.LeaseRecoveryService; +import dev.caskeleton.application.notification.platform.dispatch.MessageDigestPort; +import dev.caskeleton.application.notification.platform.dispatch.NotificationDispatchService; +import dev.caskeleton.application.notification.platform.dispatch.NotificationIdGeneratorPort; +import dev.caskeleton.application.notification.platform.dispatch.NotificationRequestStorePort; +import dev.caskeleton.application.notification.platform.dispatch.ProviderDispatchGatewayPort; +import dev.caskeleton.application.notification.platform.dispatch.RecipientDeliveryStorePort; +import dev.caskeleton.application.notification.platform.dispatch.RecipientLeaseStorePort; +import dev.caskeleton.application.notification.platform.dispatch.ReconciliationGatewayPort; +import dev.caskeleton.application.notification.platform.dispatch.ReconciliationService; +import dev.caskeleton.application.notification.platform.dispatch.SyntheticEventFingerprint; +import dev.caskeleton.application.notification.platform.dispatch.TemplateRendererRegistry; +import dev.caskeleton.application.notification.platform.observation.NotificationAuditPort; +import dev.caskeleton.application.notification.platform.observation.NotificationMetricsPort; +import dev.caskeleton.application.notification.platform.policy.NotificationRetryPolicy; +import dev.caskeleton.application.notification.platform.policy.RoutingDecisionEngine; +import dev.caskeleton.application.notification.platform.policy.SuppressionStorePort; +import dev.caskeleton.application.transaction.TransactionPort; +import java.time.Clock; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * Doing the work and correcting it: dispatch, reconciliation, lease recovery, ledger projection and + * the operator plane that redrives and suppresses deliveries. + * + *

Here rather than in the notification adapter because each of these opens its own transactions + * around each write, and the adapter must not decide where a unit of work begins (NTF-020). + */ +@Configuration(proxyBeanMethods = false) +class NotificationDeliveryConfiguration { + + /** Dispatch orchestration. */ + @Bean + NotificationDispatchService notificationDispatchService( + NotificationRequestStorePort requests, + RecipientDeliveryStorePort recipients, + DeliveryAttemptStorePort attempts, + DispatchPipeline pipeline, + RoutingDecisionEngine routing, + NotificationRetryPolicy retryPolicy, + DeliveryAttemptFactory attemptFactory, + DispatchOutcomeRecorder recorder, + ProviderDispatchGatewayPort gateway, + TemplateRendererRegistry renderers, + RecipientLeaseStorePort leases, + TransactionPort transactions, + Clock clock, + NotificationDispatchProperties properties) { + return new NotificationDispatchService( + requests, + recipients, + attempts, + pipeline, + routing, + retryPolicy, + attemptFactory, + recorder, + gateway, + renderers, + leases, + transactions, + clock, + properties.maxAdditionalAttempts(), + properties.estimatedDispatchDuration()); + } + + /** Provider status correction. */ + @Bean + ReconciliationService reconciliationService( + DeliveryAttemptStorePort attempts, + RecipientDeliveryStorePort recipients, + ReconciliationGatewayPort gateway, + ProviderEventLedger ledger, + ProviderEventProjectionService projection, + NotificationAuditPort audit, + NotificationMetricsPort metrics, + SyntheticEventFingerprint syntheticEventFingerprints, + TransactionPort transactions, + Clock clock) { + return new ReconciliationService( + attempts, + recipients, + gateway, + ledger, + projection, + audit, + metrics, + syntheticEventFingerprints, + transactions, + clock); + } + + /** Recovers deliveries a dead worker left in flight; the adapter's background worker runs it. */ + @Bean + @ConditionalOnMissingBean + LeaseRecoveryService notificationLeaseRecoveryService( + RecipientLeaseStorePort leases, + DeliveryAttemptStorePort attempts, + RecipientDeliveryStorePort deliveries, + ReconciliationService reconciliation, + TransactionPort transactions, + Clock clock, + NotificationDispatchProperties properties) { + return new LeaseRecoveryService( + leases, + attempts, + deliveries, + reconciliation::reconcile, + transactions, + clock, + properties.leaseDuration(), + properties.claimBatchSize()); + } + + /** Ledger projection. */ + @Bean + ProviderEventProjectionService providerEventProjectionService( + ProviderEventLedger ledger, + ProviderEventProjectorRegistry projectors, + DeliveryAttemptResolverPort resolver, + DeliveryProjectionStorePort projections, + NotificationSideEffectPort sideEffects, + TransactionPort transactions, + NotificationMetricsPort metrics) { + return new ProviderEventProjectionService( + ledger, projectors, resolver, projections, sideEffects, transactions, metrics); + } + + /** The N4 operator plane. */ + @Bean + NotificationAdminService notificationAdminService( + AdminAuthorizationGuard authorization, + DuplicateRiskGuard duplicateRiskGuard, + DeliveryAttemptStorePort attempts, + RecipientDeliveryStorePort recipients, + ReconciliationService reconciliation, + SuppressionStorePort suppressions, + ProviderRuntimeControlPort runtimes, + AdminOperationStorePort operations, + NotificationAuditPort audit, + TransactionPort transactions, + NotificationIdGeneratorPort ids, + MessageDigestPort digests, + Clock clock) { + return new NotificationAdminApplicationService( + authorization, + duplicateRiskGuard, + attempts, + recipients, + reconciliation, + suppressions, + runtimes, + operations, + audit, + transactions, + ids, + digests, + clock); + } +} diff --git a/src/composition/notification-platform/src/main/java/dev/caskeleton/composition/notification/NotificationSubmissionConfiguration.java b/src/composition/notification-platform/src/main/java/dev/caskeleton/composition/notification/NotificationSubmissionConfiguration.java new file mode 100644 index 00000000..e22db47d --- /dev/null +++ b/src/composition/notification-platform/src/main/java/dev/caskeleton/composition/notification/NotificationSubmissionConfiguration.java @@ -0,0 +1,130 @@ +package dev.caskeleton.composition.notification; + +import dev.caskeleton.application.notification.platform.dispatch.AcceptNotificationApplicationUseCase; +import dev.caskeleton.application.notification.platform.dispatch.CancelNotificationApplicationUseCase; +import dev.caskeleton.application.notification.platform.dispatch.CanonicalNotificationPlanWriter; +import dev.caskeleton.application.notification.platform.dispatch.ContactPointStorePort; +import dev.caskeleton.application.notification.platform.dispatch.DeliveryAttemptStorePort; +import dev.caskeleton.application.notification.platform.dispatch.GetNotificationApplicationUseCase; +import dev.caskeleton.application.notification.platform.dispatch.MessageDigestPort; +import dev.caskeleton.application.notification.platform.dispatch.NotificationIdGeneratorPort; +import dev.caskeleton.application.notification.platform.dispatch.NotificationRequestStorePort; +import dev.caskeleton.application.notification.platform.dispatch.NotificationSubmissionService; +import dev.caskeleton.application.notification.platform.dispatch.PublishNotificationTemplateApplicationUseCase; +import dev.caskeleton.application.notification.platform.dispatch.RecipientDeliveryStorePort; +import dev.caskeleton.application.notification.platform.dispatch.RequestFingerprint; +import dev.caskeleton.application.notification.platform.dispatch.ScheduleNotificationApplicationUseCase; +import dev.caskeleton.application.notification.platform.dispatch.SubmitNotificationApplicationUseCase; +import dev.caskeleton.application.notification.platform.dispatch.TenantContextPort; +import dev.caskeleton.application.notification.platform.observation.NotificationMetricsPort; +import dev.caskeleton.application.notification.platform.policy.DeduplicationService; +import dev.caskeleton.application.notification.platform.port.in.AcceptNotificationUseCase; +import dev.caskeleton.application.notification.platform.port.in.CancelNotificationUseCase; +import dev.caskeleton.application.notification.platform.port.in.GetNotificationUseCase; +import dev.caskeleton.application.notification.platform.port.in.PublishNotificationTemplateUseCase; +import dev.caskeleton.application.notification.platform.port.in.ScheduleNotificationUseCase; +import dev.caskeleton.application.notification.platform.port.in.SubmitNotificationUseCase; +import dev.caskeleton.application.notification.platform.security.ContactPointProtector; +import dev.caskeleton.application.notification.platform.template.TemplateRegistry; +import dev.caskeleton.application.transaction.TransactionPort; +import java.time.Clock; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * Accepting work: the submission service and the inbound use cases callers reach it through. + * + *

The inbound use cases are separate beans rather than one orchestrator, because a caller + * depending on the whole orchestrator depends on operations it does not use. + */ +@Configuration(proxyBeanMethods = false) +class NotificationSubmissionConfiguration { + + /** N2 orchestration. */ + @Bean + NotificationSubmissionService notificationSubmissionService( + NotificationRequestStorePort requests, + RecipientDeliveryStorePort recipients, + DeliveryAttemptStorePort attempts, + TemplateRegistry templates, + RequestFingerprint fingerprints, + CanonicalNotificationPlanWriter writer, + TransactionPort transactions, + TenantContextPort tenants, + DeduplicationService deduplication, + NotificationMetricsPort metrics, + Clock clock) { + return new NotificationSubmissionService( + requests, + recipients, + attempts, + templates, + fingerprints, + writer, + transactions, + tenants, + deduplication, + metrics, + clock); + } + + /** + * The transport-facing entry point: accept by address (NTF-INT-008). + * + *

Separate from {@code submitNotificationUseCase}, which it delegates to. That one takes a + * plan whose recipients reference contact points already in the directory; this one takes an + * address, registers or reuses the contact point, and builds the plan. Without it the platform is + * reachable only by a caller that already holds contact point ids — and the platform ships no way + * to obtain one, so it was reachable by nobody. + */ + @Bean + AcceptNotificationUseCase acceptNotificationUseCase( + SubmitNotificationUseCase submit, + ContactPointStorePort contactPoints, + ContactPointProtector protector, + TenantContextPort tenants, + NotificationIdGeneratorPort ids, + RequestFingerprint fingerprints, + TransactionPort transactions, + Clock clock) { + return new AcceptNotificationApplicationUseCase( + submit, contactPoints, protector, tenants, ids, fingerprints, transactions, clock); + } + + /** + * Publishing a template version. + * + *

A submission pins a template id and version and the platform refuses one it cannot resolve, + * so a deployment with no published template can accept nothing. {@code TemplateRegistry.publish} + * existed throughout and was called by no application code and no transport. + */ + @Bean + PublishNotificationTemplateUseCase publishNotificationTemplateUseCase( + TemplateRegistry templates, MessageDigestPort digests, TransactionPort transactions) { + return new PublishNotificationTemplateApplicationUseCase(templates, digests, transactions); + } + + @Bean + SubmitNotificationUseCase submitNotificationUseCase( + NotificationSubmissionService service, TransactionPort transactions) { + return new SubmitNotificationApplicationUseCase(service, transactions); + } + + @Bean + ScheduleNotificationUseCase scheduleNotificationUseCase( + NotificationSubmissionService service, TransactionPort transactions) { + return new ScheduleNotificationApplicationUseCase(service, transactions); + } + + @Bean + CancelNotificationUseCase cancelNotificationUseCase( + NotificationSubmissionService service, TransactionPort transactions) { + return new CancelNotificationApplicationUseCase(service, transactions); + } + + @Bean + GetNotificationUseCase getNotificationUseCase( + NotificationSubmissionService service, TransactionPort transactions) { + return new GetNotificationApplicationUseCase(service, transactions); + } +} diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/notification/ProviderCallbackIngressBridge.java b/src/composition/notification-platform/src/main/java/dev/caskeleton/composition/notification/ProviderCallbackIngressBridge.java similarity index 92% rename from src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/notification/ProviderCallbackIngressBridge.java rename to src/composition/notification-platform/src/main/java/dev/caskeleton/composition/notification/ProviderCallbackIngressBridge.java index 19770881..020d4afe 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/notification/ProviderCallbackIngressBridge.java +++ b/src/composition/notification-platform/src/main/java/dev/caskeleton/composition/notification/ProviderCallbackIngressBridge.java @@ -1,4 +1,4 @@ -package dev.caskeleton.bootstrap.autoconfigure.notification; +package dev.caskeleton.composition.notification; import dev.caskeleton.adapter.inbound.web.notification.platform.callback.ProviderCallbackHttpRequest; import dev.caskeleton.adapter.inbound.web.notification.platform.callback.ProviderCallbackIngress; @@ -20,9 +20,9 @@ import java.util.Objects; /** * Composition-only bridge from raw inbound HTTP to provider verification and semantic ingestion. * - *

This class is intentionally in the composition root. The inbound web adapter must not depend - * on the outbound notification adapter, and the outbound adapter must not depend on the web - * transport. Bootstrap is the one place allowed to know both and connect them. + *

This class is intentionally in the capability's composition module. The inbound web adapter + * must not depend on the outbound notification adapter, and the outbound adapter must not depend on + * the web transport. This module is the one place allowed to know both and connect them. */ final class ProviderCallbackIngressBridge implements ProviderCallbackIngress { diff --git a/src/composition/notification-platform/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/src/composition/notification-platform/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports new file mode 100644 index 00000000..5ab305c9 --- /dev/null +++ b/src/composition/notification-platform/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports @@ -0,0 +1 @@ +dev.caskeleton.composition.notification.NotificationApplicationCompositionAutoConfiguration diff --git a/src/app-bootstrap/src/main/resources/config/notification.yml b/src/composition/notification-platform/src/main/resources/config/module-defaults/notification.yml similarity index 88% rename from src/app-bootstrap/src/main/resources/config/notification.yml rename to src/composition/notification-platform/src/main/resources/config/module-defaults/notification.yml index 22279d63..879b19c8 100644 --- a/src/app-bootstrap/src/main/resources/config/notification.yml +++ b/src/composition/notification-platform/src/main/resources/config/module-defaults/notification.yml @@ -1,17 +1,21 @@ # 알림 전송 플랫폼과 R0 레거시 제공자 선택. 두 트리가 한 파일에 있는 것은 의도다 — 운영자가 '알림'을 찾을 때 한 곳만 보면 된다. # -# application.yml 이 spring.config.import 로 취합한다. 이 파일의 값은 application.yml 보다 -# 낮고 application-{profile}.yml 보다도 낮으므로, 배포별 오버라이드는 그대로 우선한다. +# composition:notification-platform 모듈이 싣고, 이 모듈의 의존성으로 함께 오는 support 의 로더가 읽는다 +# (adapter:outbound:support 의 ModuleDefaultsEnvironmentPostProcessor). app-bootstrap 의 application.yml 은 이 파일을 모른다 — +# 모듈 한 줄을 빼면 이 설정도 함께 사라진다. 이 파일의 값은 우선순위가 가장 낮다(application.yml, +# application-{profile}.yml, 환경 변수보다 낮음). 배포별 오버라이드는 그대로 우선한다. # -# Notification platform is disabled by default. Disabled means no provider runtime, schema activation -# check, scheduler thread, or notification secret is required. Enabling SERVING mode needs the -# notification schema and at least one assembled provider profile; see -# docs/notification/configuration-reference.md. Inline defaults keep an unused platform inert. +# The platform is on while this module is present, like every capability: selecting the module is +# the decision to run it. On needs the notification schema (the persistence-jpa module), the eight +# keys under secrets, and — in SERVING mode — at least one assembled provider profile; see +# docs/notification/configuration-reference.md. Off (APP_NOTIFICATION_PLATFORM_ENABLED=false) means +# no provider runtime, schema activation check, scheduler thread, notification secret or Spring Boot +# mail auto-configuration is required. ca-skeleton: notification: platform: - # The master switch. False binds nothing at all. - enabled: ${APP_NOTIFICATION_PLATFORM_ENABLED:false} + # The capability switch. False binds nothing at all. + enabled: ${APP_NOTIFICATION_PLATFORM_ENABLED:true} # SERVING | INGEST_ONLY. SERVING refuses to start without a working provider; INGEST_ONLY # stores requests and does not dispatch, which is the shape a migration or a drain wants. mode: ${APP_NOTIFICATION_PLATFORM_MODE:SERVING} @@ -108,6 +112,10 @@ ca-skeleton: sender-identity: ${APP_NOTIFICATION_PLATFORM_SES_SENDER_IDENTITY:} access-key-id: ${APP_NOTIFICATION_PLATFORM_SES_ACCESS_KEY_ID:} configuration-set: ${APP_NOTIFICATION_PLATFORM_SES_CONFIGURATION_SET:} + # Comma-separated SNS topic ARNs whose SES events this profile accepts. Required once + # callbacks are enabled: a valid SNS signature only proves AWS sent the message, and + # anyone can own a topic. + allowed-topic-arns: ${APP_NOTIFICATION_PLATFORM_SES_ALLOWED_TOPIC_ARNS:} # Relay address, credentials, TLS and socket timeouts are owned by spring.mail.* and # validated against the actual JavaMailSender when SMTP is assembled. Keeping a second copy # here would let validation describe a transport that is not the one sending mail. diff --git a/src/composition/notification-platform/src/test/java/dev/caskeleton/composition/notification/NotificationApplicationCompositionAutoConfigurationTest.java b/src/composition/notification-platform/src/test/java/dev/caskeleton/composition/notification/NotificationApplicationCompositionAutoConfigurationTest.java new file mode 100644 index 00000000..0da71a2c --- /dev/null +++ b/src/composition/notification-platform/src/test/java/dev/caskeleton/composition/notification/NotificationApplicationCompositionAutoConfigurationTest.java @@ -0,0 +1,38 @@ +package dev.caskeleton.composition.notification; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.adapter.inbound.web.notification.platform.callback.ProviderCallbackIngress; +import dev.caskeleton.application.notification.platform.dispatch.NotificationSubmissionService; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.springframework.boot.autoconfigure.AutoConfiguration; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.context.annotation.ImportCandidates; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; + +class NotificationApplicationCompositionAutoConfigurationTest { + + @Test + void bootDiscoversTheRootFromThisModule() { + List candidates = + ImportCandidates.load(AutoConfiguration.class, getClass().getClassLoader()).getCandidates(); + + assertThat(candidates) + .contains(NotificationApplicationCompositionAutoConfiguration.class.getName()); + } + + @Test + void theRootAssemblesNothingWhileThePlatformIsOff() { + new ApplicationContextRunner() + .withConfiguration( + AutoConfigurations.of(NotificationApplicationCompositionAutoConfiguration.class)) + .withPropertyValues("ca-skeleton.notification.platform.enabled=false") + .run( + context -> + assertThat(context) + .hasNotFailed() + .doesNotHaveBean(NotificationSubmissionService.class) + .doesNotHaveBean(ProviderCallbackIngress.class)); + } +} diff --git a/src/composition/notification-platform/src/test/java/dev/caskeleton/composition/notification/NotificationEnvironmentRegistryTest.java b/src/composition/notification-platform/src/test/java/dev/caskeleton/composition/notification/NotificationEnvironmentRegistryTest.java new file mode 100644 index 00000000..a32dc617 --- /dev/null +++ b/src/composition/notification-platform/src/test/java/dev/caskeleton/composition/notification/NotificationEnvironmentRegistryTest.java @@ -0,0 +1,71 @@ +package dev.caskeleton.composition.notification; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Set; +import java.util.TreeSet; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; + +/** + * docs/registries/env-keys.yaml registers exactly the notification keys this module's shipped + * settings bind: a registered key nothing reads is a knob that does nothing, and a bound key the + * registry lacks is a deployment input nobody documented. The build declares the registry as an + * input of {@code test}; the shipped settings are already on the test classpath. + */ +class NotificationEnvironmentRegistryTest { + + private static final Path MODULE_DEFAULTS = Path.of("src/main/resources/config/module-defaults"); + private static final Path REGISTRY = Path.of("../../../docs/registries/env-keys.yaml"); + private static final Pattern PLACEHOLDER = + Pattern.compile("\\$\\{(APP_NOTIFICATION_[A-Z0-9_]+)(:[^}]*)?}"); + private static final Pattern REGISTERED = + Pattern.compile("^\\s*- name:\\s*((?:APP_NOTIFICATION|SPRING_MAIL)_[A-Z0-9_]+)\\s*$"); + + /** Spring's own mail keys, required whenever the SMTP provider can be switched on. */ + private static final Set SMTP_EXTERNAL_VARIABLES = + Set.of( + "SPRING_MAIL_HOST", + "SPRING_MAIL_PORT", + "SPRING_MAIL_USERNAME", + "SPRING_MAIL_PASSWORD", + "SPRING_MAIL_PROPERTIES_MAIL_SMTP_STARTTLS_ENABLE", + "SPRING_MAIL_PROPERTIES_MAIL_SMTP_STARTTLS_REQUIRED", + "SPRING_MAIL_PROPERTIES_MAIL_SMTP_CONNECTIONTIMEOUT", + "SPRING_MAIL_PROPERTIES_MAIL_SMTP_TIMEOUT", + "SPRING_MAIL_PROPERTIES_MAIL_SMTP_WRITETIMEOUT"); + + @Test + void registeredNotificationKeysAreExactlyTheBoundOnes() throws IOException { + // given + Set bound = new TreeSet<>(); + try (Stream files = Files.list(MODULE_DEFAULTS)) { + for (Path settings : files.filter(file -> file.toString().endsWith(".yml")).toList()) { + Matcher matcher = PLACEHOLDER.matcher(Files.readString(settings)); + while (matcher.find()) { + bound.add(matcher.group(1)); + } + } + } + if (bound.contains("APP_NOTIFICATION_PLATFORM_SMTP_ENABLED")) { + bound.addAll(SMTP_EXTERNAL_VARIABLES); + } + + // when + Set registered = new TreeSet<>(); + for (String line : Files.readAllLines(REGISTRY)) { + Matcher matcher = REGISTERED.matcher(line); + if (matcher.matches()) { + registered.add(matcher.group(1)); + } + } + + // then + assertThat(registered).isNotEmpty().containsExactlyInAnyOrderElementsOf(bound); + } +} diff --git a/src/composition/notification-platform/src/test/java/dev/caskeleton/composition/notification/NotificationModuleDefaultsTest.java b/src/composition/notification-platform/src/test/java/dev/caskeleton/composition/notification/NotificationModuleDefaultsTest.java new file mode 100644 index 00000000..65f34aaf --- /dev/null +++ b/src/composition/notification-platform/src/test/java/dev/caskeleton/composition/notification/NotificationModuleDefaultsTest.java @@ -0,0 +1,62 @@ +package dev.caskeleton.composition.notification; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.adapter.outbound.support.startup.ModuleDefaultsEnvironmentPostProcessor; +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.springframework.boot.SpringApplication; +import org.springframework.core.env.MapPropertySource; +import org.springframework.core.env.StandardEnvironment; + +/** + * The module ships its settings under config/module-defaults, and a deployment's value beats them. + */ +class NotificationModuleDefaultsTest { + + @Test + void theShippedDefaultsTurnThePlatformOnWhileTheModuleIsPresent() { + StandardEnvironment environment = processed(Map.of()); + + assertThat(environment.getProperty("ca-skeleton.notification.platform.enabled")) + .isEqualTo("true"); + assertThat(environment.getProperty("ca-skeleton.notification.platform.mode")) + .isEqualTo("SERVING"); + } + + @Test + void theEnvironmentVariableReachesTheHyphenatedTreeThroughTheShippedPlaceholder() { + StandardEnvironment environment = + processed(Map.of("APP_NOTIFICATION_PLATFORM_ENABLED", "false")); + + assertThat(environment.getProperty("ca-skeleton.notification.platform.enabled")) + .isEqualTo("false"); + } + + @Test + void aDeploymentValueOutranksTheShippedDefault() { + StandardEnvironment environment = + processed(Map.of("ca-skeleton.notification.platform.mode", "INGEST_ONLY")); + + assertThat(environment.getProperty("ca-skeleton.notification.platform.mode")) + .isEqualTo("INGEST_ONLY"); + } + + @Test + void bothNotificationTreesShipInTheOneFile() { + StandardEnvironment environment = processed(Map.of()); + + assertThat(environment.getProperty("ca-skeleton.notification.platform.dispatch.lease-duration")) + .isEqualTo("2m"); + assertThat(environment.getProperty("app.notification.slack-webhook.enabled")) + .isEqualTo("false"); + } + + private static StandardEnvironment processed(Map deployment) { + StandardEnvironment environment = new StandardEnvironment(); + environment.getPropertySources().addFirst(new MapPropertySource("deployment", deployment)); + new ModuleDefaultsEnvironmentPostProcessor() + .postProcessEnvironment(environment, new SpringApplication()); + return environment; + } +} diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/notification/ProviderCallbackIngressBridgeTest.java b/src/composition/notification-platform/src/test/java/dev/caskeleton/composition/notification/ProviderCallbackIngressBridgeTest.java similarity index 96% rename from src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/notification/ProviderCallbackIngressBridgeTest.java rename to src/composition/notification-platform/src/test/java/dev/caskeleton/composition/notification/ProviderCallbackIngressBridgeTest.java index 59166f8a..6214dd29 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/notification/ProviderCallbackIngressBridgeTest.java +++ b/src/composition/notification-platform/src/test/java/dev/caskeleton/composition/notification/ProviderCallbackIngressBridgeTest.java @@ -1,4 +1,4 @@ -package dev.caskeleton.bootstrap.autoconfigure.notification; +package dev.caskeleton.composition.notification; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -27,6 +27,7 @@ import dev.caskeleton.application.notification.platform.port.in.IngestProviderCa import java.nio.charset.StandardCharsets; import java.security.KeyPairGenerator; import java.security.Signature; +import java.time.Duration; import java.time.Instant; import java.util.Base64; import java.util.LinkedHashMap; @@ -106,9 +107,13 @@ class ProviderCallbackIngressBridgeTest { @Test void validSesCallbackCrossesTheShippedBridgeThroughTheRealVerifier() throws Exception { var keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair(); - SnsSignatureVerifier verifier = - new SnsSignatureVerifier(certificateUrl -> keyPair.getPublic(), "amazonaws.com"); - SesCallbackAdapter adapter = new SesCallbackAdapter(verifier, new SesEventNormalizer()); + SnsSignatureVerifier verifier = new SnsSignatureVerifier(certificateUrl -> keyPair.getPublic()); + SesCallbackAdapter adapter = + new SesCallbackAdapter( + verifier, + new SesEventNormalizer(), + Set.of("arn:aws:sns:us-east-1:123456789012:notifications"), + Duration.ofMinutes(5)); ProviderProfileId profile = new ProviderProfileId("ses-events"); ProviderId provider = new ProviderId("ses"); diff --git a/src/config/architecture/modules.json b/src/config/architecture/modules.json index bc7fd972..a9854f76 100644 --- a/src/config/architecture/modules.json +++ b/src/config/architecture/modules.json @@ -64,7 +64,8 @@ "domain-core", "application-core", "shared-contract", - "application-notification" + "application-notification", + "adapter-outbound-support" ] }, { @@ -167,7 +168,8 @@ "gradle_path": ":adapter:outbound:messaging-kafka", "source_path": "src/adapter/outbound/messaging-kafka", "allowed_dependencies": [ - "adapter-outbound-messaging" + "adapter-outbound-messaging", + "messaging-spring-boot-starter-kafka" ] }, { @@ -188,8 +190,18 @@ "allowed_dependencies": [ "domain-core", "application-core", - "shared-contract", - "application-notification" + "shared-contract" + ] + }, + { + "id": "adapter-inbound-web-notification", + "gradle_path": ":adapter:inbound:web-notification", + "source_path": "src/adapter/inbound/web-notification", + "allowed_dependencies": [ + "adapter-inbound-web", + "application-core", + "application-notification", + "shared-contract" ] }, { @@ -203,6 +215,16 @@ "shared-contract" ] }, + { + "id": "adapter-inbound-web-advanced", + "gradle_path": ":adapter:inbound:web-advanced", + "source_path": "src/adapter/inbound/web-advanced", + "allowed_dependencies": [ + "adapter-inbound-web", + "application-core", + "shared-contract" + ] + }, { "id": "adapter-inbound-grpc", "gradle_path": ":adapter:inbound:grpc", @@ -249,6 +271,17 @@ "adapter-inbound-web" ] }, + { + "id": "composition-notification-platform", + "gradle_path": ":composition:notification-platform", + "source_path": "src/composition/notification-platform", + "allowed_dependencies": [ + "application-core", + "application-notification", + "adapter-outbound-notification", + "adapter-inbound-web-notification" + ] + }, { "id": "app-bootstrap", "gradle_path": ":app-bootstrap", @@ -256,29 +289,21 @@ "allowed_dependencies": [ "domain-core", "application-core", - "adapter-outbound-persistence-jpa", "adapter-outbound-support", - "adapter-outbound-messaging", + "adapter-outbound-persistence-jpa", "adapter-outbound-cache-redis", - "adapter-outbound-redis-runtime", - "adapter-outbound-notification", - "adapter-outbound-fileserver", - "adapter-outbound-httpclient", + "composition-notification-platform", "adapter-outbound-identifier", "adapter-inbound-web", "shared-contract", + "adapter-outbound-messaging-kafka", "adapter-outbound-persistence-mongo", "adapter-inbound-graphql", - "messaging-spring-boot-starter", - "application-notification", - "application-fileserver", - "messaging-core-api", - "messaging-observability", - "messaging-policy", - "messaging-reliability-api", - "messaging-schema-api", - "messaging-security", - "messaging-transport-spi" + "adapter-outbound-httpclient", + "adapter-outbound-objectstorage", + "adapter-inbound-websocket", + "adapter-inbound-grpc", + "composition-fileserver-platform" ] }, { @@ -408,35 +433,6 @@ "messaging-admin-api" ] }, - { - "id": "messaging-kafka-share-experimental", - "gradle_path": ":messaging:messaging-kafka-share-experimental", - "source_path": "src/messaging/messaging-kafka-share-experimental", - "allowed_dependencies": [ - "messaging-core-api", - "messaging-policy", - "messaging-transport-spi", - "messaging-kafka", - "messaging-admin-api", - "messaging-observability", - "messaging-schema-api", - "messaging-security" - ] - }, - { - "id": "messaging-rabbit", - "gradle_path": ":messaging:messaging-rabbit", - "source_path": "src/messaging/messaging-rabbit", - "allowed_dependencies": [ - "messaging-core-api", - "messaging-schema-api", - "messaging-policy", - "messaging-transport-spi", - "messaging-observability", - "messaging-security", - "messaging-admin-api" - ] - }, { "id": "messaging-reliability-api", "gradle_path": ":messaging:messaging-reliability-api", @@ -500,45 +496,6 @@ "messaging-schema-api" ] }, - { - "id": "messaging-pulsar-experimental", - "gradle_path": ":messaging:messaging-pulsar-experimental", - "source_path": "src/messaging/messaging-pulsar-experimental", - "allowed_dependencies": [ - "messaging-core-api", - "messaging-schema-api", - "messaging-policy", - "messaging-transport-spi", - "messaging-observability", - "messaging-security", - "messaging-admin-api" - ] - }, - { - "id": "messaging-nats-experimental", - "gradle_path": ":messaging:messaging-nats-experimental", - "source_path": "src/messaging/messaging-nats-experimental", - "allowed_dependencies": [ - "messaging-core-api", - "messaging-schema-api", - "messaging-policy", - "messaging-transport-spi", - "messaging-observability", - "messaging-security", - "messaging-admin-api" - ] - }, - { - "id": "messaging-spring-cloud-stream-bridge", - "gradle_path": ":messaging:messaging-spring-cloud-stream-bridge", - "source_path": "src/messaging/messaging-spring-cloud-stream-bridge", - "allowed_dependencies": [ - "messaging-core-api", - "messaging-policy", - "messaging-transport-spi", - "messaging-schema-api" - ] - }, { "id": "messaging-spring-boot-starter", "gradle_path": ":messaging:messaging-spring-boot-starter", @@ -546,8 +503,6 @@ "allowed_dependencies": [ "messaging-admin-api", "messaging-admin-runtime", - "messaging-claim-check", - "messaging-cloudevents", "messaging-core-api", "messaging-inbox-jdbc-postgresql", "messaging-observability", @@ -578,23 +533,6 @@ "messaging-transport-spi" ] }, - { - "id": "messaging-spring-boot-starter-rabbit", - "gradle_path": ":messaging:messaging-spring-boot-starter-rabbit", - "source_path": "src/messaging/messaging-spring-boot-starter-rabbit", - "allowed_dependencies": [ - "messaging-spring-boot-starter", - "messaging-rabbit", - "messaging-admin-api", - "messaging-core-api", - "messaging-observability", - "messaging-policy", - "messaging-reliability-api", - "messaging-schema-api", - "messaging-security", - "messaging-transport-spi" - ] - }, { "id": "messaging-testkit", "gradle_path": ":messaging:messaging-testkit", @@ -805,9 +743,5 @@ ], "build": "optional-grpc" } - ], - "composition_roots": [ - "app-bootstrap", - "sample-portfolio" ] } diff --git a/src/config/jpa/readiness-cards.yaml b/src/config/jpa/readiness-cards.yaml index d1eec081..bbeb0a51 100644 --- a/src/config/jpa/readiness-cards.yaml +++ b/src/config/jpa/readiness-cards.yaml @@ -120,31 +120,19 @@ "evidence": { "scenarios": [ { - "selector": "dev.caskeleton.adapter.outbound.persistence.readiness.PostgreSqlTransactionIntegrationTest#appliesTransactionLocalTimeoutsBeforeWorkAndResetsThemAfterCommit", - "covers": ["real-postgresql"] - }, - { - "selector": "dev.caskeleton.adapter.outbound.persistence.readiness.PostgreSqlTransactionIntegrationTest#actionFailureProducesAConfirmedRollback", + "selector": "dev.caskeleton.adapter.outbound.persistence.readiness.PostgreSqlTransactionIntegrationTest#inWriteActionFailureRollsBackTheWrite", "covers": ["fault"] }, { - "selector": "dev.caskeleton.adapter.outbound.persistence.readiness.PostgreSqlTransactionIntegrationTest#serializableConflictIsRetriedOnlyByTheReplaySafePolicy", - "covers": ["concurrency"] + "selector": "dev.caskeleton.adapter.outbound.persistence.readiness.PostgreSqlTransactionIntegrationTest#inNewCommitsIndependentlyOfTheCallersRollback", + "covers": ["real-postgresql"] }, { "selector": "dev.caskeleton.adapter.outbound.persistence.readiness.PostgreSqlTransactionIntegrationTest#deterministicDeadlockProducesExactlyOneTypedDeadlockFailure", "covers": ["concurrency", "fault"] }, { - "selector": "dev.caskeleton.adapter.outbound.persistence.readiness.PostgreSqlTransactionIntegrationTest#lockAndStatementTimeoutsRollbackWithinTheConfiguredBounds", - "covers": ["fault"] - }, - { - "selector": "dev.caskeleton.adapter.outbound.persistence.readiness.PostgreSqlTransactionIntegrationTest#poolExhaustionRejectsBeforeApplicationWorkStarts", - "covers": ["concurrency", "fault"] - }, - { - "selector": "dev.caskeleton.adapter.outbound.persistence.readiness.PostgreSqlTransactionIntegrationTest#connectionLossDuringCommitIsIndeterminateAndNeverBlindlyRetried", + "selector": "dev.caskeleton.adapter.outbound.persistence.readiness.PostgreSqlTransactionIntegrationTest#connectionLossDuringCommitSurfacesAsAFailureAndIsNeverRetried", "covers": ["fault"] } ], @@ -295,224 +283,6 @@ ] } }, - "jpa-outbox-storage-v2": { - "state": "implemented-candidate", - "schema-stream": "owned", - "prerequisites": [ - "jpa-transaction-runtime", - "jpa-flyway-migration", - "jpa-observability-lifecycle" - ], - "readiness-task": ":adapter:outbound:persistence-jpa:postgresqlOutboxStorageIntegrationTest", - "dispatch-modes": ["polling", "cdc"], - "required-evidence": [ - "real-postgresql", - "same-resource", - "partition-uniqueness", - "publication-authority-fence", - "legacy-writer-rejection", - "migration", - "stream-lifecycle", - "no-skip" - ], - "evidence": { - "scenarios": [ - { - "selector": "dev.caskeleton.adapter.outbound.persistence.readiness.PostgreSqlOutboxStorageIntegrationTest#appendRequiresTheCallerSameDatasourceWriteTransaction", - "covers": ["real-postgresql", "same-resource", "migration"] - }, - { - "selector": "dev.caskeleton.adapter.outbound.persistence.readiness.PostgreSqlOutboxStorageIntegrationTest#immutableIdentityEnvelopeAndBusinessMutationCommitOrRollbackTogether", - "covers": ["same-resource"] - }, - { - "selector": "dev.caskeleton.adapter.outbound.persistence.readiness.PostgreSqlOutboxStorageIntegrationTest#duplicateIdentityDistinguishesSameEventIdConflictAndAggregateOrderConflict", - "covers": ["partition-uniqueness"] - }, - { - "selector": "dev.caskeleton.adapter.outbound.persistence.readiness.PostgreSqlOutboxStorageIntegrationTest#publicationControlShareLockPreventsCutoverFromOvertakingAnAppend", - "covers": ["publication-authority-fence", "legacy-writer-rejection"] - }, - { - "selector": "dev.caskeleton.adapter.outbound.persistence.readiness.PostgreSqlOutboxStorageIntegrationTest#optionalStreamLifecycleIsNonDestructiveAndRecoversInterruptedMigration", - "covers": [ - "stream-lifecycle", - "migration-lifecycle:fresh-disabled", - "migration-lifecycle:first-enable", - "migration-lifecycle:disable", - "migration-lifecycle:re-enable", - "migration-lifecycle:interrupted-recovery" - ] - } - ], - "task-claims": [] - }, - "migration": { - "location": "db/migration/jpa/outbox-storage", - "history-table": "flyway_jpa_outbox_storage_history", - "required-core-epoch": 1, - "feature-revision": 2, - "lifecycle-evidence": [ - "fresh-disabled", - "first-enable", - "disable", - "re-enable", - "interrupted-recovery" - ] - } - }, - "jpa-outbox-polling-delivery-v2": { - "state": "implemented-candidate", - "schema-stream": "owned", - "prerequisites": [ - "jpa-outbox-storage-v2", - "jpa-transaction-runtime", - "jpa-flyway-migration", - "jpa-observability-lifecycle" - ], - "readiness-task": ":adapter:outbound:persistence-jpa:postgresqlOutboxPollingIntegrationTest", - "dispatch-modes": ["polling"], - "required-evidence": [ - "real-postgresql", - "concurrency", - "publish-fault", - "ordering", - "migration", - "stream-lifecycle", - "no-skip" - ], - "evidence": { - "scenarios": [ - { - "selector": "dev.caskeleton.adapter.outbound.persistence.readiness.PostgreSqlOutboxPollingIntegrationTest#eventAndInitialDeliveryAreInsertedInTheSameBusinessTransaction", - "covers": ["real-postgresql", "migration"] - }, - { - "selector": "dev.caskeleton.adapter.outbound.persistence.readiness.PostgreSqlOutboxPollingIntegrationTest#strictAggregateOrderClaimsOnlyTheHeadUntilItIsPublished", - "covers": ["concurrency", "ordering"] - }, - { - "selector": "dev.caskeleton.adapter.outbound.persistence.readiness.PostgreSqlOutboxPollingIntegrationTest#publishAckLossReclaimsTheStableEventIdButRejectsTheStaleOwner", - "covers": ["concurrency", "publish-fault"] - }, - { - "selector": "dev.caskeleton.adapter.outbound.persistence.readiness.PostgreSqlOutboxPollingIntegrationTest#retryWaitUsesTheRequestedScheduleAndDeadHeadBlocksTheAggregate", - "covers": ["ordering"] - }, - { - "selector": "dev.caskeleton.adapter.outbound.persistence.readiness.PostgreSqlOutboxPollingIntegrationTest#optionalStreamLifecycleIsNonDestructiveAndRecoversInterruptedMigration", - "covers": [ - "stream-lifecycle", - "migration-lifecycle:fresh-disabled", - "migration-lifecycle:first-enable", - "migration-lifecycle:disable", - "migration-lifecycle:re-enable", - "migration-lifecycle:interrupted-recovery" - ] - } - ], - "task-claims": [] - }, - "migration": { - "location": "db/migration/jpa/outbox-polling", - "history-table": "flyway_jpa_outbox_polling_history", - "required-core-epoch": 1, - "feature-revision": 2, - "lifecycle-evidence": [ - "fresh-disabled", - "first-enable", - "disable", - "re-enable", - "interrupted-recovery" - ] - } - }, - "jpa-outbox-cdc-retention-v1": { - "state": "not-implemented", - "schema-stream": "none", - "prerequisites": ["jpa-outbox-storage-v2", "jpa-observability-lifecycle"], - "external-prerequisites": [ - { - "registry": "src/config/messaging/readiness-cards.yaml", - "card-id": "messaging-cdc-dispatch.v1", - "minimum-readiness": "R2" - } - ], - "readiness-task": ":adapter:outbound:persistence-jpa:postgresqlOutboxCdcCleanupIntegrationTest", - "dispatch-modes": ["cdc"], - "required-evidence": [ - "real-postgresql", - "connector-checkpoint-high-watermark", - "outage-restart", - "replay-retention", - "delete-tombstone-filtering", - "mode-transition", - "no-skip" - ] - }, - "jpa-inbox-same-store-v1": { - "state": "implemented-candidate", - "schema-stream": "owned", - "prerequisites": [ - "jpa-transaction-runtime", - "jpa-flyway-migration", - "jpa-observability-lifecycle" - ], - "readiness-task": ":adapter:outbound:persistence-jpa:postgresqlInboxIntegrationTest", - "required-evidence": [ - "real-postgresql", - "redelivery", - "concurrency", - "migration", - "stream-lifecycle", - "no-skip" - ], - "evidence": { - "scenarios": [ - { - "selector": "dev.caskeleton.adapter.outbound.persistence.readiness.PostgreSqlInboxIntegrationTest#claimBusinessMutationAndCompletionCommitOrRollbackAsOneUnit", - "covers": ["real-postgresql", "redelivery", "migration"] - }, - { - "selector": "dev.caskeleton.adapter.outbound.persistence.readiness.PostgreSqlInboxIntegrationTest#expiredReceivedCanBeTakenOverButStaleOwnerCannotStart", - "covers": ["redelivery", "concurrency"] - }, - { - "selector": "dev.caskeleton.adapter.outbound.persistence.readiness.PostgreSqlInboxIntegrationTest#expiredProcessingRequiresRecoveryInsteadOfBlindTakeover", - "covers": ["redelivery"] - }, - { - "selector": "dev.caskeleton.adapter.outbound.persistence.readiness.PostgreSqlInboxIntegrationTest#takeoverCannotPassTheOwnerRowWhileBusinessTransactionIsOpen", - "covers": ["concurrency"] - }, - { - "selector": "dev.caskeleton.adapter.outbound.persistence.readiness.PostgreSqlInboxIntegrationTest#optionalStreamLifecycleIsNonDestructiveAndRecoversInterruptedMigration", - "covers": [ - "stream-lifecycle", - "migration-lifecycle:fresh-disabled", - "migration-lifecycle:first-enable", - "migration-lifecycle:disable", - "migration-lifecycle:re-enable", - "migration-lifecycle:interrupted-recovery" - ] - } - ], - "task-claims": [] - }, - "migration": { - "location": "db/migration/jpa/inbox", - "history-table": "flyway_jpa_inbox_history", - "required-core-epoch": 1, - "feature-revision": 1, - "lifecycle-evidence": [ - "fresh-disabled", - "first-enable", - "disable", - "re-enable", - "interrupted-recovery" - ] - } - }, "jpa-fileserver-metadata-v1": { "state": "implemented-candidate", "schema-stream": "owned", diff --git a/src/config/messaging/evidence/build-evidence-manifest-v1.schema.json b/src/config/messaging/evidence/build-evidence-manifest-v1.schema.json index cacd5cfe..73b4735e 100644 --- a/src/config/messaging/evidence/build-evidence-manifest-v1.schema.json +++ b/src/config/messaging/evidence/build-evidence-manifest-v1.schema.json @@ -36,7 +36,6 @@ "pattern": "^verifyMessaging[A-Za-z0-9]+$", "enum": [ "verifyMessagingContracts", - "verifyMessagingJsonSchemaV1", "verifyMessagingPollingOutboxR2", "verifyMessagingKafkaProducerR2", "verifyMessagingSecurityR2", diff --git a/src/config/messaging/readiness-cards.yaml b/src/config/messaging/readiness-cards.yaml index a4403978..464b42e9 100644 --- a/src/config/messaging/readiness-cards.yaml +++ b/src/config/messaging/readiness-cards.yaml @@ -147,7 +147,7 @@ cards: - messaging-outbox-publish.v1 providerId: json-schema-envelope providerVersion: 1 - maturity: implemented-candidate + maturity: not-implemented guarantees: - deterministic-utf8-envelope - closed-offline-schema-catalog @@ -163,12 +163,11 @@ cards: topologyProfile: external-topic-validated.v1 lifecycleProfile: bounded-startup-shutdown.v1 operatorControlProfile: authenticated-internal-web-disposition.v1 - schemaSetHash: "sha256:42040504d5c204f9ee0e01bfa17fd9a03182db13f8f99e31b63ec79d5ecc40d0" - settingsDigest: "sha256:fcd849322d43a8d88c926a43160296339cbc6e945db81e46c513ab45d185b924" + schemaSetHash: "" + settingsDigest: "" evidenceFingerprint: "" evidenceTasks: - verifyMessagingContracts - - verifyMessagingJsonSchemaV1 requiredScenarios: - messaging.schema.envelope-valid.v1 - messaging.schema.adversarial-bounds.v1 diff --git a/src/config/messaging/release-profile-assertions.yaml b/src/config/messaging/release-profile-assertions.yaml index eee7d2a1..b3d5978e 100644 --- a/src/config/messaging/release-profile-assertions.yaml +++ b/src/config/messaging/release-profile-assertions.yaml @@ -26,7 +26,6 @@ releaseProfiles: expectedSettingsHash: "" requiredEvidenceTasks: - verifyMessagingContracts - - verifyMessagingJsonSchemaV1 - verifyMessagingPollingOutboxR2 - verifyMessagingKafkaProducerR2 - verifyMessagingSecurityR2 diff --git a/src/config/mongodb/release-contracts.json b/src/config/mongodb/release-contracts.json index b92cd0e9..a341ac3d 100644 --- a/src/config/mongodb/release-contracts.json +++ b/src/config/mongodb/release-contracts.json @@ -37,17 +37,6 @@ "blocking": false, "not_promoted_reason": "The lane this names is not registered in adapter/outbound/persistence-mongo/build.gradle, and the environment it needs \u2014 a sharded cluster, an Atlas deployment, a real KMS \u2014 is not one this repository can stand up. A manifest entry pointing at an unregistered task does not fail; it is simply never run, and the release reports green for a capability nobody qualified. Demoted rather than implemented so the green means what it says." }, - { - "id": "MONGO-REL-011", - "description": "Search and vector against the actual Atlas deployment", - "task": "mongoAtlasTest", - "className": "dev.caskeleton.adapter.outbound.mongo.advanced.search.MongoAtlasContractTest", - "topology": "atlas", - "minimumExecuted": 1, - "promotion": "experimental", - "blocking": false, - "not_promoted_reason": "The lane this names is not registered in adapter/outbound/persistence-mongo/build.gradle, and the environment it needs \u2014 a sharded cluster, an Atlas deployment, a real KMS \u2014 is not one this repository can stand up. A manifest entry pointing at an unregistered task does not fail; it is simply never run, and the release reports green for a capability nobody qualified. Demoted rather than implemented so the green means what it says." - }, { "id": "MONGO-REL-012", "description": "Queryable Encryption against a real KMS and key vault", diff --git a/src/config/runtime/compose-profile-contracts.json b/src/config/runtime/compose-profile-contracts.json index 6e1c532e..0500feb6 100644 --- a/src/config/runtime/compose-profile-contracts.json +++ b/src/config/runtime/compose-profile-contracts.json @@ -740,5 +740,5 @@ ], "$activationComment": "activationEnv is what the lane injects; expectedSwitchesOn is what the application must then report. Both are needed: a lane named local-jpa that ran with JPA off would render the right services, start cleanly, and prove nothing at all. Redis, the HTTP Fileserver platform and the HTTP client platform are shipped in app-bootstrap and therefore have dedicated blocking lanes. Object storage, WebSocket and gRPC are build-time optional and are qualified by their dedicated workflows instead of being falsely reported as members of this bootJar.", "$vendorComment": "expectedPersistenceVendor is the vendor the application must report, not the one the lane started. local-jpa passed for a while against H2 while a PostgreSQL container it never touched sat beside it, because application-local.yml pins an in-memory URL that outranks the lane's environment.", - "$flywayComment": "SPRING_FLYWAY_LOCATIONS is deliberately absent. Seven lanes listed every capability stream there, and it could never have worked: db/migration/jpa/{core,fileserver,idempotency,inbox,notification-platform,outbox-polling,outbox-storage} each declare a V1, so one Flyway instance over all of them fails with 'Found more than one migration with version 1'. Each stream is its own stream with its own history table by design. The setting was inert until Wave 2 stopped PostgreSqlPersistenceConfig from overriding spring.flyway.locations, and the lanes passed while their own configuration was being discarded. Applying a capability stream needs a Flyway execution per stream — the operator sequence PostgreSqlNotificationPersistenceUnitIntegrationTest and FileserverRoundTripContractTest both perform in their fixtures — and that is what the notification lanes still need." + "$flywayComment": "SPRING_FLYWAY_LOCATIONS is deliberately absent. Seven lanes listed every capability stream there, and it could never have worked: the db/migration/jpa/* streams each declare a V1, so one Flyway instance over all of them fails with 'Found more than one migration with version 1'. Each stream is its own stream with its own history table by design. The setting was inert until Wave 2 stopped PostgreSqlPersistenceConfig from overriding spring.flyway.locations, and the lanes passed while their own configuration was being discarded. Applying a capability stream needs a Flyway execution per stream — the operator sequence PostgreSqlNotificationPersistenceUnitIntegrationTest and FileserverRoundTripContractTest both perform in their fixtures — and that is what the notification lanes still need." } diff --git a/src/gradle/libs.versions.toml b/src/gradle/libs.versions.toml index ff13c1e7..71943302 100644 --- a/src/gradle/libs.versions.toml +++ b/src/gradle/libs.versions.toml @@ -55,7 +55,7 @@ googleJavaFormat = "1.35.0" # import it at MODULE scope to keep the strict-locking blast radius off the shared platform. grpc = "1.68.1" jmh = "1.37" -jnats = "2.26.2" +jmhPlugin = "0.7.3" jqwik = "1.9.1" # Jackson 3 and the JSON-Schema validator share a number today by coincidence, not by # contract; separate keys so bumping one cannot move the other. @@ -73,7 +73,6 @@ protobufGrpc = "3.25.5" # The websocket leaf's proto contract is generated against an older runtime and has not been # requalified; see the coordinate's own comment in that leaf. protobufLegacy = "4.29.3" -pulsarClient = "4.0.3" resilience4j = "2.2.0" # Two Groovy generations, deliberately not merged. See the header. spockGroovy4 = "2.3-groovy-4.0" @@ -110,7 +109,6 @@ jackson3-core = { module = "tools.jackson.core:jackson-core", version.ref = "jac jackson3-databind = { module = "tools.jackson.core:jackson-databind", version.ref = "jackson3" } jmh-core = { module = "org.openjdk.jmh:jmh-core", version.ref = "jmh" } jmh-generator-annprocess = { module = "org.openjdk.jmh:jmh-generator-annprocess", version.ref = "jmh" } -jnats = { module = "io.nats:jnats", version.ref = "jnats" } jqwik = { module = "net.jqwik:jqwik", version.ref = "jqwik" } json-schema-validator = { module = "com.networknt:json-schema-validator", version.ref = "jsonSchemaValidator" } junit-jupiter = { module = "org.junit.jupiter:junit-jupiter", version.ref = "junitJupiter" } @@ -120,7 +118,6 @@ mockwebserver = { module = "com.squareup.okhttp3:mockwebserver", version.ref = " okhttp-tls = { module = "com.squareup.okhttp3:okhttp-tls", version.ref = "okhttp" } protobuf-java = { module = "com.google.protobuf:protobuf-java", version.ref = "protobuf" } protobuf-java-legacy = { module = "com.google.protobuf:protobuf-java", version.ref = "protobufLegacy" } -pulsar-client = { module = "org.apache.pulsar:pulsar-client", version.ref = "pulsarClient" } resilience4j-bulkhead = { module = "io.github.resilience4j:resilience4j-bulkhead", version.ref = "resilience4j" } resilience4j-circuitbreaker = { module = "io.github.resilience4j:resilience4j-circuitbreaker", version.ref = "resilience4j" } resilience4j-micrometer = { module = "io.github.resilience4j:resilience4j-micrometer", version.ref = "resilience4j" } @@ -147,3 +144,4 @@ spring-dependency-management = { id = "io.spring.dependency-management", version spotless = { id = "com.diffplug.spotless", version.ref = "spotless" } spotbugs = { id = "com.github.spotbugs", version.ref = "spotbugsPlugin" } errorprone = { id = "net.ltgt.errorprone", version.ref = "errorpronePlugin" } +jmh = { id = "me.champeau.jmh", version.ref = "jmhPlugin" } diff --git a/src/grpc/grpc-core-api/build.gradle b/src/grpc/grpc-core-api/build.gradle index ddde61d0..84fc01a0 100644 --- a/src/grpc/grpc-core-api/build.gradle +++ b/src/grpc/grpc-core-api/build.gradle @@ -1,5 +1,6 @@ plugins { id 'ca.platform-module' + id 'java-test-fixtures' } // The platform's port layer: identifiers, method policy, execution evidence, failure model, @@ -10,4 +11,8 @@ plugins { // a transport" is verifiable instead of aspirational — the same rule `messaging-core-api` holds. // A type here may not name io.grpc, Spring, Netty, protobuf or a database. dependencies { + // Test fixtures only, never main: the operation-ledger fake and the contract that both it and + // the JPA adapter must pass, so the fake cannot allow a transition the database refuses. + testFixturesImplementation 'org.junit.jupiter:junit-jupiter-api' + testFixturesImplementation 'org.assertj:assertj-core' } diff --git a/src/grpc/grpc-core-api/gradle.lockfile b/src/grpc/grpc-core-api/gradle.lockfile index e2c95854..13a5babd 100644 --- a/src/grpc/grpc-core-api/gradle.lockfile +++ b/src/grpc/grpc-core-api/gradle.lockfile @@ -1,40 +1,40 @@ # 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.47.0=checkstyle -com.google.errorprone:error_prone_annotations:2.49.0=annotationProcessor,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.5.0-jre=annotationProcessor,testAnnotationProcessor +com.google.errorprone:error_prone_annotations:2.49.0=annotationProcessor,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.5.0-jre=annotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor com.google.guava:guava:33.6.0-jre=checkstyle -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.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.sf.saxon:Saxon-HE:12.9=checkstyle,spotbugs org.antlr:antlr4-runtime:4.13.2=checkstyle org.apache.bcel:bcel:6.12.0=spotbugs @@ -50,32 +50,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 -org.assertj:assertj-core:3.27.7=testCompileClasspath,testRuntimeClasspath +org.apiguardian:apiguardian-api:1.1.2=testCompileClasspath,testFixturesCompileClasspath +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.3.0=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.18=spotbugs,spotbugsSlf4j org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j diff --git a/src/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedger.java b/src/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedger.java index 9ab94f6c..4342bde7 100644 --- a/src/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedger.java +++ b/src/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedger.java @@ -40,6 +40,18 @@ public interface GrpcOperationLedger { /** Marks a claim terminally failed. */ void markFailed(GrpcOperationIdentity identity, Instant now); + /** + * Re-claims a {@code FAILED_TERMINAL} record for a new attempt of the same request. + * + *

A compare-and-set to {@code IN_PROGRESS}, atomic like {@link #claim}: of two concurrent + * re-claims exactly one returns true. A record in any other state, or made for a different + * request, is left untouched. A retry that proceeds without winning this leaves its commit with + * no owner and runs concurrently with every other retry of the same key. + * + * @return true when this call now owns the record as a fresh attempt claimed at {@code now} + */ + boolean reclaimFailed(GrpcOperationIdentity identity, String requestFingerprint, Instant now); + /** * Releases a claim that will never complete, so the caller may try again. * diff --git a/src/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedgerState.java b/src/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedgerState.java index 2908b579..2c2cfaa0 100644 --- a/src/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedgerState.java +++ b/src/grpc/grpc-core-api/src/main/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedgerState.java @@ -12,7 +12,10 @@ public enum GrpcOperationLedgerState { IN_PROGRESS(false), /** Committed, with a replayable outcome. */ COMMITTED(true), - /** Failed in a way that will not succeed on repetition. */ + /** + * The attempt failed and changed nothing. A retry of the same request may reclaim it (one winner) + * and run again; see {@code GrpcOperationLedger.reclaimFailed}. + */ FAILED_TERMINAL(true); private final boolean terminal; diff --git a/src/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/api/ledger/InMemoryOperationLedgerContractTest.java b/src/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/api/ledger/InMemoryOperationLedgerContractTest.java new file mode 100644 index 00000000..ff2916f1 --- /dev/null +++ b/src/grpc/grpc-core-api/src/test/java/dev/caskeleton/grpc/api/ledger/InMemoryOperationLedgerContractTest.java @@ -0,0 +1,11 @@ +package dev.caskeleton.grpc.api.ledger; + +class InMemoryOperationLedgerContractTest extends GrpcOperationLedgerContract { + + private final InMemoryOperationLedger ledger = new InMemoryOperationLedger(); + + @Override + protected GrpcOperationLedger ledger() { + return ledger; + } +} diff --git a/src/grpc/grpc-core-api/src/testFixtures/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedgerContract.java b/src/grpc/grpc-core-api/src/testFixtures/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedgerContract.java new file mode 100644 index 00000000..ebc1110c --- /dev/null +++ b/src/grpc/grpc-core-api/src/testFixtures/java/dev/caskeleton/grpc/api/ledger/GrpcOperationLedgerContract.java @@ -0,0 +1,260 @@ +package dev.caskeleton.grpc.api.ledger; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.grpc.core.GrpcMethodName; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.Callable; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import org.junit.jupiter.api.Test; + +/** + * The transitions every {@link GrpcOperationLedger} allows and refuses. + * + *

The in-memory fake and the JPA adapter (against real PostgreSQL) both extend this. A fake that + * allows a transition the database refuses lets every policy test pass for code that fails in + * production — which is how a retry of a {@code FAILED_TERMINAL} row once proceeded unclaimed. + */ +public abstract class GrpcOperationLedgerContract { + + private static final GrpcOperationIdentity ID = + new GrpcOperationIdentity( + "tenant-1.actor-1", + GrpcMethodName.parse("hyeonworks.document.v1.DocumentService/CreateDocument"), + "sha256:aabbccddeeff00112233445566778899aabbccddeeff00112233445566778899"); + private static final String FINGERPRINT = + "sha256:0f1e2d3c4b5a69788796a5b4c3d2e1f00f1e2d3c4b5a69788796a5b4c3d2e1f0"; + private static final String OTHER_FINGERPRINT = + "sha256:1122334455667788990011223344556677889900112233445566778899001122"; + private static final String OUTCOME = "outcome://document/42"; + private static final Instant NOW = Instant.parse("2026-09-25T10:00:00Z"); + + /** The ledger under test, holding no records when a test starts. */ + protected abstract GrpcOperationLedger ledger(); + + @Test + void theFirstClaimOfAnOperationIsOwnedByItsCaller() { + assertThat(ledger().claim(ID, FINGERPRINT, NOW)).isEmpty(); + } + + @Test + void aSecondClaimReadsTheFirstClaimInProgress() { + // given + ledger().claim(ID, FINGERPRINT, NOW); + + // when + Optional second = + ledger().claim(ID, OTHER_FINGERPRINT, NOW.plusSeconds(1)); + + // then + assertThat(second) + .get() + .extracting( + GrpcOperationLedgerRecord::state, + GrpcOperationLedgerRecord::requestFingerprint, + GrpcOperationLedgerRecord::claimedAt) + .containsExactly(GrpcOperationLedgerState.IN_PROGRESS, FINGERPRINT, NOW); + } + + @Test + void concurrentClaimsHaveExactlyOneOwner() throws Exception { + // when + List owned = concurrently(() -> ledger().claim(ID, FINGERPRINT, NOW).isEmpty()); + + // then + assertThat(owned).containsExactlyInAnyOrder(true, false); + } + + @Test + void aCommittedClaimKeepsTheOutcomeARetryReplays() { + // given + ledger().claim(ID, FINGERPRINT, NOW); + + // when + ledger().markCommitted(ID, OUTCOME, NOW.plusSeconds(1)); + + // then + assertThat(ledger().find(ID)) + .get() + .extracting( + GrpcOperationLedgerRecord::state, + GrpcOperationLedgerRecord::outcomeReference, + GrpcOperationLedgerRecord::completedAt) + .containsExactly( + GrpcOperationLedgerState.COMMITTED, + Optional.of(OUTCOME), + Optional.of(NOW.plusSeconds(1))); + } + + @Test + void committingWithoutAClaimIsRefused() { + // when + Throwable refused = catchThrowable(() -> ledger().markCommitted(ID, OUTCOME, NOW)); + + // then + assertThat(refused) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no claim exists"); + } + + @Test + void aCommittedClaimCannotBeCommittedAgain() { + // given + ledger().claim(ID, FINGERPRINT, NOW); + ledger().markCommitted(ID, OUTCOME, NOW.plusSeconds(1)); + + // when + Throwable refused = + catchThrowable( + () -> ledger().markCommitted(ID, "outcome://document/99", NOW.plusSeconds(2))); + + // then + assertThat(refused) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("cannot transition again"); + } + + @Test + void aFailedClaimIsTerminal() { + // given + ledger().claim(ID, FINGERPRINT, NOW); + + // when + ledger().markFailed(ID, NOW.plusSeconds(1)); + + // then + assertThat(ledger().find(ID)) + .get() + .extracting(GrpcOperationLedgerRecord::state, GrpcOperationLedgerRecord::completedAt) + .containsExactly(GrpcOperationLedgerState.FAILED_TERMINAL, Optional.of(NOW.plusSeconds(1))); + } + + @Test + void aFailedClaimCannotBeCommittedWithoutBeingReclaimed() { + // given + failedClaim(); + + // when + Throwable refused = + catchThrowable(() -> ledger().markCommitted(ID, OUTCOME, NOW.plusSeconds(2))); + + // then + assertThat(refused) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("cannot transition again"); + } + + @Test + void aFailedClaimIsReclaimedByARetryOfTheSameRequest() { + // given + failedClaim(); + + // when + boolean reclaimed = ledger().reclaimFailed(ID, FINGERPRINT, NOW.plusSeconds(2)); + + // then + assertThat(reclaimed).isTrue(); + } + + @Test + void aReclaimedClaimIsANewAttemptInProgressSinceTheReclaim() { + // given + failedClaim(); + + // when + ledger().reclaimFailed(ID, FINGERPRINT, NOW.plusSeconds(2)); + + // then + assertThat(ledger().find(ID)) + .get() + .extracting( + GrpcOperationLedgerRecord::state, + GrpcOperationLedgerRecord::claimedAt, + GrpcOperationLedgerRecord::completedAt) + .containsExactly( + GrpcOperationLedgerState.IN_PROGRESS, NOW.plusSeconds(2), Optional.empty()); + } + + @Test + void aReclaimedClaimCanBeCommitted() { + // given + failedClaim(); + ledger().reclaimFailed(ID, FINGERPRINT, NOW.plusSeconds(2)); + + // when + ledger().markCommitted(ID, OUTCOME, NOW.plusSeconds(3)); + + // then + assertThat(ledger().find(ID)) + .get() + .extracting(GrpcOperationLedgerRecord::state, GrpcOperationLedgerRecord::outcomeReference) + .containsExactly(GrpcOperationLedgerState.COMMITTED, Optional.of(OUTCOME)); + } + + @Test + void aFailedClaimIsNotReclaimedForADifferentRequest() { + failedClaim(); + + assertThat(ledger().reclaimFailed(ID, OTHER_FINGERPRINT, NOW.plusSeconds(2))).isFalse(); + } + + @Test + void anInProgressClaimIsNotReclaimed() { + ledger().claim(ID, FINGERPRINT, NOW); + + assertThat(ledger().reclaimFailed(ID, FINGERPRINT, NOW.plusSeconds(1))).isFalse(); + } + + @Test + void aCommittedClaimIsNotReclaimed() { + // given + ledger().claim(ID, FINGERPRINT, NOW); + ledger().markCommitted(ID, OUTCOME, NOW.plusSeconds(1)); + + // when + boolean reclaimed = ledger().reclaimFailed(ID, FINGERPRINT, NOW.plusSeconds(2)); + + // then + assertThat(reclaimed).isFalse(); + } + + @Test + void concurrentReclaimsOfAFailedClaimHaveExactlyOneWinner() throws Exception { + // given + failedClaim(); + + // when + List reclaimed = + concurrently(() -> ledger().reclaimFailed(ID, FINGERPRINT, NOW.plusSeconds(2))); + + // then + assertThat(reclaimed).containsExactlyInAnyOrder(true, false); + } + + private void failedClaim() { + ledger().claim(ID, FINGERPRINT, NOW); + ledger().markFailed(ID, NOW.plusSeconds(1)); + } + + /** Runs {@code attempt} on two threads released together and returns both results. */ + private static List concurrently(Callable attempt) throws Exception { + CountDownLatch start = new CountDownLatch(1); + Callable gated = + () -> { + start.await(); + return attempt.call(); + }; + try (ExecutorService executor = Executors.newFixedThreadPool(2)) { + Future first = executor.submit(gated); + Future second = executor.submit(gated); + start.countDown(); + return List.of(first.get(), second.get()); + } + } +} diff --git a/src/grpc/grpc-core-api/src/testFixtures/java/dev/caskeleton/grpc/api/ledger/InMemoryOperationLedger.java b/src/grpc/grpc-core-api/src/testFixtures/java/dev/caskeleton/grpc/api/ledger/InMemoryOperationLedger.java new file mode 100644 index 00000000..f08ddacf --- /dev/null +++ b/src/grpc/grpc-core-api/src/testFixtures/java/dev/caskeleton/grpc/api/ledger/InMemoryOperationLedger.java @@ -0,0 +1,111 @@ +package dev.caskeleton.grpc.api.ledger; + +import java.time.Instant; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +/** + * A hand-rolled ledger for tests of code that depends on {@link GrpcOperationLedger}. + * + *

{@code putIfAbsent} on a concurrent map is the in-memory equivalent of the unique constraint + * the real adapter relies on, and {@code replace(key, expected, next)} of its conditional update, + * so claim and re-claim are atomic here for the same reason they are there. The transitions match + * the JPA adapter's because {@link GrpcOperationLedgerContract} runs against both; a fake that + * allowed more would let the policy tests pass for code the database refuses. + */ +public final class InMemoryOperationLedger implements GrpcOperationLedger { + + private final ConcurrentMap records = + new ConcurrentHashMap<>(); + private volatile boolean unavailable; + + /** Makes every read fail, so the UNKNOWN path can be exercised. */ + public void makeUnavailable() { + unavailable = true; + } + + @Override + public Optional claim( + GrpcOperationIdentity identity, String requestFingerprint, Instant now) { + GrpcOperationLedgerRecord existing = + records.putIfAbsent( + identity.storageKey(), + GrpcOperationLedgerRecord.claim(identity, requestFingerprint, now)); + return Optional.ofNullable(existing); + } + + @Override + public Optional find(GrpcOperationIdentity identity) { + if (unavailable) { + throw new IllegalStateException("ledger unavailable"); + } + return Optional.ofNullable(records.get(identity.storageKey())); + } + + @Override + public void markCommitted(GrpcOperationIdentity identity, String outcomeReference, Instant now) { + GrpcOperationLedgerRecord committed = + records.computeIfPresent( + identity.storageKey(), + (key, existing) -> + finish( + existing, + GrpcOperationLedgerState.COMMITTED, + Optional.of(outcomeReference), + now)); + if (committed == null) { + throw new IllegalStateException( + "cannot commit operation '" + identity.storageKey() + "': no claim exists"); + } + } + + @Override + public void markFailed(GrpcOperationIdentity identity, Instant now) { + records.computeIfPresent( + identity.storageKey(), + (key, existing) -> + finish(existing, GrpcOperationLedgerState.FAILED_TERMINAL, Optional.empty(), now)); + } + + @Override + public boolean reclaimFailed( + GrpcOperationIdentity identity, String requestFingerprint, Instant now) { + GrpcOperationLedgerRecord current = records.get(identity.storageKey()); + return current != null + && current.state() == GrpcOperationLedgerState.FAILED_TERMINAL + && current.sameRequestAs(requestFingerprint) + && records.replace( + identity.storageKey(), + current, + GrpcOperationLedgerRecord.claim(identity, requestFingerprint, now)); + } + + @Override + public void release(GrpcOperationIdentity identity) { + records.remove(identity.storageKey()); + } + + // Only an IN_PROGRESS claim finishes; a terminal row is re-opened by reclaimFailed alone. + private static GrpcOperationLedgerRecord finish( + GrpcOperationLedgerRecord existing, + GrpcOperationLedgerState state, + Optional outcomeReference, + Instant now) { + if (existing.state() != GrpcOperationLedgerState.IN_PROGRESS) { + throw new IllegalStateException( + "operation '" + + existing.identity().storageKey() + + "' is already " + + existing.state() + + " and cannot transition again"); + } + return new GrpcOperationLedgerRecord( + existing.identity(), + state, + existing.requestFingerprint(), + outcomeReference, + existing.claimedAt(), + Optional.of(now)); + } +} diff --git a/src/grpc/grpc-operation-ledger-jpa/build.gradle b/src/grpc/grpc-operation-ledger-jpa/build.gradle index a4f97083..d9796995 100644 --- a/src/grpc/grpc-operation-ledger-jpa/build.gradle +++ b/src/grpc/grpc-operation-ledger-jpa/build.gradle @@ -26,6 +26,10 @@ dependencies { integrationTestImplementation 'org.testcontainers:testcontainers-postgresql' integrationTestImplementation 'org.testcontainers:testcontainers-junit-jupiter' integrationTestImplementation 'org.postgresql:postgresql' + + // The shared ledger contract, run against this adapter through a real JPA provider. + integrationTestImplementation testFixtures(project(':grpc:grpc-core-api')) + integrationTestRuntimeOnly 'org.hibernate.orm:hibernate-core' } strictTestLanes { diff --git a/src/grpc/grpc-operation-ledger-jpa/gradle.lockfile b/src/grpc/grpc-operation-ledger-jpa/gradle.lockfile index 36472586..d9b07415 100644 --- a/src/grpc/grpc-operation-ledger-jpa/gradle.lockfile +++ b/src/grpc/grpc-operation-ledger-jpa/gradle.lockfile @@ -2,6 +2,7 @@ # Manual edits can break the build and are not advised. # This file is expected to be part of source control. com.fasterxml.jackson.core:jackson-annotations:2.21=integrationTestCompileClasspath,integrationTestRuntimeClasspath +com.fasterxml:classmate:1.7.3=integrationTestRuntimeClasspath com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor com.github.docker-java:docker-java-api:3.7.1=integrationTestCompileClasspath,integrationTestRuntimeClasspath com.github.docker-java:docker-java-transport-zerodep:3.7.1=integrationTestCompileClasspath,integrationTestRuntimeClasspath @@ -30,6 +31,7 @@ com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,integrat com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins com.puppycrawl.tools:checkstyle:13.5.0=checkstyle +com.sun.istack:istack-commons-runtime:4.1.2=integrationTestRuntimeClasspath commons-beanutils:commons-beanutils:1.11.0=checkstyle commons-codec:commons-codec:1.19.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath commons-collections:commons-collections:3.2.2=checkstyle @@ -41,8 +43,12 @@ io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,integratio io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor io.micrometer:micrometer-commons:1.16.7=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath io.micrometer:micrometer-observation:1.16.7=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +jakarta.activation:jakarta.activation-api:2.1.4=integrationTestRuntimeClasspath jakarta.annotation:jakarta.annotation-api:3.0.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +jakarta.inject:jakarta.inject-api:2.0.1=integrationTestRuntimeClasspath jakarta.persistence:jakarta.persistence-api:3.2.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +jakarta.transaction:jakarta.transaction-api:2.0.1=integrationTestRuntimeClasspath +jakarta.xml.bind:jakarta.xml.bind-api:4.0.5=integrationTestRuntimeClasspath javax.inject:javax.inject:1=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor jaxen:jaxen:2.0.6=spotbugs net.bytebuddy:byte-buddy:1.17.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath @@ -71,7 +77,14 @@ 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.3.0=checkstyle org.dom4j:dom4j:2.2.0=spotbugs +org.eclipse.angus:angus-activation:2.0.3=integrationTestRuntimeClasspath +org.glassfish.jaxb:jaxb-core:4.0.9=integrationTestRuntimeClasspath +org.glassfish.jaxb:jaxb-runtime:4.0.9=integrationTestRuntimeClasspath +org.glassfish.jaxb:txw2:4.0.9=integrationTestRuntimeClasspath +org.hibernate.models:hibernate-models:1.0.1=integrationTestRuntimeClasspath +org.hibernate.orm:hibernate-core:7.2.24.Final=integrationTestRuntimeClasspath org.javassist:javassist:3.28.0-GA=checkstyle +org.jboss.logging:jboss-logging:3.6.3.Final=integrationTestRuntimeClasspath org.jetbrains:annotations:17.0.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,compileClasspath,integrationTestAnnotationProcessor,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testAnnotationProcessor,testCompileClasspath,testRuntimeClasspath org.junit.jupiter:junit-jupiter-api:6.0.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath diff --git a/src/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/JpaGrpcOperationLedgerContractIT.java b/src/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/JpaGrpcOperationLedgerContractIT.java new file mode 100644 index 00000000..0a172794 --- /dev/null +++ b/src/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/JpaGrpcOperationLedgerContractIT.java @@ -0,0 +1,185 @@ +package dev.caskeleton.grpc.ledger; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.grpc.api.ledger.GrpcOperationIdentity; +import dev.caskeleton.grpc.api.ledger.GrpcOperationLedger; +import dev.caskeleton.grpc.api.ledger.GrpcOperationLedgerContract; +import dev.caskeleton.grpc.api.ledger.GrpcOperationLedgerRecord; +import dev.caskeleton.grpc.api.ledger.GrpcOperationLedgerState; +import dev.caskeleton.grpc.core.GrpcMethodName; +import jakarta.persistence.EntityManagerFactory; +import jakarta.persistence.PersistenceConfiguration; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.sql.Statement; +import java.time.Instant; +import java.util.Optional; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.data.jpa.repository.support.JpaRepositoryFactory; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.SharedEntityManagerCreator; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import org.testcontainers.postgresql.PostgreSQLContainer; + +/** + * Runs the ledger contract against {@link JpaGrpcOperationLedger} on Hibernate and PostgreSQL. + * + *

Every ledger call runs in its own transaction, standing in for the caller's business + * transaction; the two threads of a concurrency test therefore race as two real transactions. + */ +@Testcontainers(disabledWithoutDocker = true) +class JpaGrpcOperationLedgerContractIT extends GrpcOperationLedgerContract { + + @SuppressWarnings("resource") + @Container + private static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer("postgres:16-alpine") + .withDatabaseName("grpc") + .withUsername("grpc") + .withPassword("grpc"); + + private static EntityManagerFactory entityManagerFactory; + private static TransactionTemplate transactions; + private static JpaGrpcOperationLedger adapter; + private static GrpcOperationLedger ledger; + + @BeforeAll + static void startJpa() throws SQLException, IOException { + execute(migration()); + entityManagerFactory = + new PersistenceConfiguration("grpc-operation-ledger") + .managedClass(GrpcOperationLedgerEntity.class) + .property(PersistenceConfiguration.JDBC_URL, POSTGRES.getJdbcUrl()) + .property(PersistenceConfiguration.JDBC_USER, POSTGRES.getUsername()) + .property(PersistenceConfiguration.JDBC_PASSWORD, POSTGRES.getPassword()) + .createEntityManagerFactory(); + GrpcOperationLedgerRepository repository = + new JpaRepositoryFactory( + SharedEntityManagerCreator.createSharedEntityManager(entityManagerFactory)) + .getRepository(GrpcOperationLedgerRepository.class); + transactions = new TransactionTemplate(new JpaTransactionManager(entityManagerFactory)); + adapter = new JpaGrpcOperationLedger(repository); + ledger = new PerCallTransactionLedger(adapter, transactions); + } + + @AfterAll + static void stopJpa() { + entityManagerFactory.close(); + } + + @BeforeEach + void emptyTheLedger() throws SQLException { + execute("TRUNCATE grpc_operation_ledger"); + } + + @Override + protected GrpcOperationLedger ledger() { + return ledger; + } + + /** + * Adopters are told to claim and commit inside the business transaction. The claim loads the + * failed row into the persistence context, so without the re-claim clearing it the commit would + * read the stale FAILED_TERMINAL copy and refuse. + */ + @Test + void aRetryThatReclaimsAndCommitsInOneTransactionCommits() { + // given + GrpcOperationIdentity id = + new GrpcOperationIdentity( + "tenant-1.actor-1", + GrpcMethodName.parse("hyeonworks.document.v1.DocumentService/CreateDocument"), + "sha256:aabbccddeeff00112233445566778899aabbccddeeff00112233445566778899"); + String fingerprint = "sha256:0f1e2d3c4b5a69788796a5b4c3d2e1f00f1e2d3c4b5a69788796a5b4c3d2e1f0"; + Instant now = Instant.parse("2026-09-25T10:00:00Z"); + ledger.claim(id, fingerprint, now); + ledger.markFailed(id, now.plusSeconds(1)); + + // when + transactions.executeWithoutResult( + status -> { + adapter.claim(id, fingerprint, now.plusSeconds(2)); + adapter.reclaimFailed(id, fingerprint, now.plusSeconds(2)); + adapter.markCommitted(id, "outcome://document/42", now.plusSeconds(3)); + }); + + // then + assertThat(ledger.find(id)) + .get() + .extracting(GrpcOperationLedgerRecord::state, GrpcOperationLedgerRecord::outcomeReference) + .containsExactly(GrpcOperationLedgerState.COMMITTED, Optional.of("outcome://document/42")); + } + + private static void execute(String sql) throws SQLException { + try (Connection connection = + DriverManager.getConnection( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); + Statement statement = connection.createStatement()) { + statement.execute(sql); + } + } + + private static String migration() throws IOException { + try (InputStream stream = + JpaGrpcOperationLedgerContractIT.class + .getClassLoader() + .getResourceAsStream("db/migration/grpc/V001__create_grpc_operation_ledger.sql")) { + if (stream == null) { + throw new IOException("gRPC operation-ledger migration is missing"); + } + return new String(stream.readAllBytes(), StandardCharsets.UTF_8); + } + } + + /** Runs each call in its own transaction, as a caller's business transaction would. */ + private record PerCallTransactionLedger( + JpaGrpcOperationLedger delegate, TransactionTemplate transactions) + implements GrpcOperationLedger { + + @Override + public Optional claim( + GrpcOperationIdentity identity, String requestFingerprint, Instant now) { + return transactions.execute(status -> delegate.claim(identity, requestFingerprint, now)); + } + + @Override + public Optional find(GrpcOperationIdentity identity) { + return transactions.execute(status -> delegate.find(identity)); + } + + @Override + public void markCommitted( + GrpcOperationIdentity identity, String outcomeReference, Instant now) { + transactions.executeWithoutResult( + status -> delegate.markCommitted(identity, outcomeReference, now)); + } + + @Override + public void markFailed(GrpcOperationIdentity identity, Instant now) { + transactions.executeWithoutResult(status -> delegate.markFailed(identity, now)); + } + + @Override + public boolean reclaimFailed( + GrpcOperationIdentity identity, String requestFingerprint, Instant now) { + return Boolean.TRUE.equals( + transactions.execute( + status -> delegate.reclaimFailed(identity, requestFingerprint, now))); + } + + @Override + public void release(GrpcOperationIdentity identity) { + transactions.executeWithoutResult(status -> delegate.release(identity)); + } + } +} diff --git a/src/grpc/grpc-operation-ledger-jpa/src/main/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerRepository.java b/src/grpc/grpc-operation-ledger-jpa/src/main/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerRepository.java index 5f72d6dc..f1823b8b 100644 --- a/src/grpc/grpc-operation-ledger-jpa/src/main/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerRepository.java +++ b/src/grpc/grpc-operation-ledger-jpa/src/main/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerRepository.java @@ -62,6 +62,36 @@ public interface GrpcOperationLedgerRepository @Param("requestFingerprint") String requestFingerprint, @Param("claimedAt") Instant claimedAt); + /** + * Re-claims a terminally failed row as a new attempt of the same request. + * + *

One conditional update, so PostgreSQL's row lock decides the race: a concurrent second + * re-claim re-evaluates the condition against the winner's {@code IN_PROGRESS} row and updates + * nothing. It clears the persistence context, because a row this transaction already loaded (the + * claim's read-on-conflict does) would otherwise still read {@code FAILED_TERMINAL} and refuse + * the commit. + * + * @return one when this caller re-claimed the row, zero otherwise + */ + @Modifying(flushAutomatically = true, clearAutomatically = true) + @Transactional + @Query( + value = + """ + UPDATE grpc_operation_ledger + SET state = 'IN_PROGRESS', + claimed_at = :claimedAt, + completed_at = NULL + WHERE storage_key = :storageKey + AND state = 'FAILED_TERMINAL' + AND request_fingerprint = :requestFingerprint + """, + nativeQuery = true) + int tryReclaimFailed( + @Param("storageKey") String storageKey, + @Param("requestFingerprint") String requestFingerprint, + @Param("claimedAt") Instant claimedAt); + /** Updates an existing claim after it has been loaded. */ GrpcOperationLedgerEntity save(GrpcOperationLedgerEntity entity); diff --git a/src/grpc/grpc-operation-ledger-jpa/src/main/java/dev/caskeleton/grpc/ledger/JpaGrpcOperationLedger.java b/src/grpc/grpc-operation-ledger-jpa/src/main/java/dev/caskeleton/grpc/ledger/JpaGrpcOperationLedger.java index 7c038050..443847a7 100644 --- a/src/grpc/grpc-operation-ledger-jpa/src/main/java/dev/caskeleton/grpc/ledger/JpaGrpcOperationLedger.java +++ b/src/grpc/grpc-operation-ledger-jpa/src/main/java/dev/caskeleton/grpc/ledger/JpaGrpcOperationLedger.java @@ -88,6 +88,13 @@ public final class JpaGrpcOperationLedger implements GrpcOperationLedger { }); } + @Override + public boolean reclaimFailed( + GrpcOperationIdentity identity, String requestFingerprint, Instant now) { + requireIdentity(identity); + return repository.tryReclaimFailed(identity.storageKey(), requestFingerprint, now) == 1; + } + @Override public void release(GrpcOperationIdentity identity) { requireIdentity(identity); diff --git a/src/grpc/grpc-operation-ledger-jpa/src/test/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerRepositoryTest.java b/src/grpc/grpc-operation-ledger-jpa/src/test/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerRepositoryTest.java index fba811e8..e1457b52 100644 --- a/src/grpc/grpc-operation-ledger-jpa/src/test/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerRepositoryTest.java +++ b/src/grpc/grpc-operation-ledger-jpa/src/test/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerRepositoryTest.java @@ -59,6 +59,12 @@ class GrpcOperationLedgerRepositoryTest { return rows.putIfAbsent(storageKey, claim) == null ? 1 : 0; } + @Override + public int tryReclaimFailed(String storageKey, String requestFingerprint, Instant claimedAt) { + throw new UnsupportedOperationException( + "the re-claim is certified against PostgreSQL by JpaGrpcOperationLedgerContractIT"); + } + @Override public GrpcOperationLedgerEntity save(GrpcOperationLedgerEntity entity) { rows.put(entity.getStorageKey(), entity); diff --git a/src/grpc/grpc-policy/build.gradle b/src/grpc/grpc-policy/build.gradle index 17a4f5bf..6d3694ea 100644 --- a/src/grpc/grpc-policy/build.gradle +++ b/src/grpc/grpc-policy/build.gradle @@ -13,4 +13,7 @@ dependencies { // signatures, so an adopter cannot compile against this module without them. api "io.grpc:grpc-api" api "io.grpc:grpc-stub" + + // The shared operation-ledger fake, held to the same contract as the JPA adapter. + testImplementation testFixtures(project(':grpc:grpc-core-api')) } diff --git a/src/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/idempotency/GrpcIdempotencyInterceptor.java b/src/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/idempotency/GrpcIdempotencyInterceptor.java index 7307ed4f..e2326699 100644 --- a/src/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/idempotency/GrpcIdempotencyInterceptor.java +++ b/src/grpc/grpc-policy/src/main/java/dev/caskeleton/grpc/idempotency/GrpcIdempotencyInterceptor.java @@ -106,12 +106,16 @@ public final class GrpcIdempotencyInterceptor { + identity.storageKey() + "' has no outcome reference to replay"))); } - if (record.state() == GrpcOperationLedgerState.FAILED_TERMINAL) { + if (record.state() == GrpcOperationLedgerState.FAILED_TERMINAL + && ledger.reclaimFailed(identity, requestFingerprint, now)) { // A terminal failure is not replayed: the caller asked for the operation, it did not happen, - // and repeating it is exactly what the key makes safe. + // and repeating it is exactly what the key makes safe — but only for the one retry that + // re-claims the row. Proceeding unclaimed runs concurrent retries twice and leaves the + // commit without an owner. return GrpcIdempotencyDecision.proceed( - "the previous attempt failed terminally; the key makes repeating it safe"); + "the previous attempt failed terminally; this caller re-claimed it for a new attempt"); } + // Running, or a failed attempt another retry re-claimed first. return waitForInProgress ? GrpcIdempotencyDecision.waitAndPoll(inProgressPollInterval) : GrpcIdempotencyDecision.rejectInProgress(); diff --git a/src/grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/idempotency/GrpcCompletionReconcilerTest.java b/src/grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/idempotency/GrpcCompletionReconcilerTest.java index afb8e98f..7bffcbca 100644 --- a/src/grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/idempotency/GrpcCompletionReconcilerTest.java +++ b/src/grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/idempotency/GrpcCompletionReconcilerTest.java @@ -2,6 +2,7 @@ package dev.caskeleton.grpc.idempotency; import static org.assertj.core.api.Assertions.assertThat; +import dev.caskeleton.grpc.api.ledger.InMemoryOperationLedger; import dev.caskeleton.grpc.core.GrpcMethodName; import java.time.Instant; import java.util.Optional; diff --git a/src/grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/idempotency/GrpcIdempotencyInterceptorTest.java b/src/grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/idempotency/GrpcIdempotencyInterceptorTest.java index 51b8dea4..7a09d605 100644 --- a/src/grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/idempotency/GrpcIdempotencyInterceptorTest.java +++ b/src/grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/idempotency/GrpcIdempotencyInterceptorTest.java @@ -4,6 +4,10 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import dev.caskeleton.grpc.api.deadline.GrpcDeadlineProfile; +import dev.caskeleton.grpc.api.ledger.GrpcOperationIdentity; +import dev.caskeleton.grpc.api.ledger.GrpcOperationLedgerRecord; +import dev.caskeleton.grpc.api.ledger.GrpcOperationLedgerState; +import dev.caskeleton.grpc.api.ledger.InMemoryOperationLedger; import dev.caskeleton.grpc.api.policy.GrpcMethodPolicy; import dev.caskeleton.grpc.api.policy.GrpcMethodPolicyCatalog; import dev.caskeleton.grpc.api.policy.RpcIdempotencyProfile; @@ -12,6 +16,12 @@ import dev.caskeleton.grpc.core.GrpcMethodName; import dev.caskeleton.grpc.core.RpcType; import java.time.Duration; import java.time.Instant; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -133,6 +143,57 @@ class GrpcIdempotencyInterceptorTest { .isEqualTo(GrpcIdempotencyDecision.Outcome.PROCEED); } + @Test + void aRetryOfATerminallyFailedOperationReclaimsItBeforeProceeding() { + // given + GrpcIdempotencyInterceptor interceptor = interceptor(false); + String fingerprint = GrpcRequestFingerprint.of("body"); + interceptor.decide(CREATE, CALLER, KEY, fingerprint, NOW); + interceptor.recordFailure(CREATE, CALLER, KEY, NOW.plusSeconds(1)); + + // when + interceptor.decide(CREATE, CALLER, KEY, fingerprint, NOW.plusSeconds(2)); + + // then + assertThat( + ledger + .find( + new GrpcOperationIdentity( + CALLER, CREATE, GrpcRequestFingerprint.hashIdempotencyKey(KEY))) + .map(GrpcOperationLedgerRecord::state)) + .contains(GrpcOperationLedgerState.IN_PROGRESS); + } + + @Test + void concurrentRetriesOfATerminallyFailedOperationProceedOnlyOnce() throws Exception { + // given + GrpcIdempotencyInterceptor interceptor = interceptor(false); + String fingerprint = GrpcRequestFingerprint.of("body"); + interceptor.decide(CREATE, CALLER, KEY, fingerprint, NOW); + interceptor.recordFailure(CREATE, CALLER, KEY, NOW.plusSeconds(1)); + CountDownLatch start = new CountDownLatch(1); + Callable retry = + () -> { + start.await(); + return interceptor.decide(CREATE, CALLER, KEY, fingerprint, NOW.plusSeconds(2)).outcome(); + }; + + // when + List outcomes; + try (ExecutorService executor = Executors.newFixedThreadPool(2)) { + Future first = executor.submit(retry); + Future second = executor.submit(retry); + start.countDown(); + outcomes = List.of(first.get(), second.get()); + } + + // then + assertThat(outcomes) + .containsExactlyInAnyOrder( + GrpcIdempotencyDecision.Outcome.PROCEED, + GrpcIdempotencyDecision.Outcome.REJECT_IN_PROGRESS); + } + @Test @DisplayName("one caller's key does not suppress another caller's write") void oneCallersKeyDoesNotSuppressAnother() { diff --git a/src/grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/idempotency/InMemoryOperationLedger.java b/src/grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/idempotency/InMemoryOperationLedger.java deleted file mode 100644 index 8d79058e..00000000 --- a/src/grpc/grpc-policy/src/test/java/dev/caskeleton/grpc/idempotency/InMemoryOperationLedger.java +++ /dev/null @@ -1,81 +0,0 @@ -package dev.caskeleton.grpc.idempotency; - -import dev.caskeleton.grpc.api.ledger.GrpcOperationIdentity; -import dev.caskeleton.grpc.api.ledger.GrpcOperationLedger; -import dev.caskeleton.grpc.api.ledger.GrpcOperationLedgerRecord; -import dev.caskeleton.grpc.api.ledger.GrpcOperationLedgerState; -import java.time.Instant; -import java.util.Optional; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -/** - * A hand-rolled ledger for the policy tests. - * - *

{@code putIfAbsent} on a concurrent map is the in-memory equivalent of the unique constraint - * the real adapter relies on, so the claim is atomic here for the same reason it is there. A fake - * that read and then wrote would let the policy tests pass while the property they exist to check - * does not hold. - */ -final class InMemoryOperationLedger implements GrpcOperationLedger { - - private final ConcurrentMap records = - new ConcurrentHashMap<>(); - private boolean unavailable; - - /** Makes every read fail, so the UNKNOWN path can be exercised. */ - void makeUnavailable() { - unavailable = true; - } - - @Override - public Optional claim( - GrpcOperationIdentity identity, String requestFingerprint, Instant now) { - GrpcOperationLedgerRecord existing = - records.putIfAbsent( - identity.storageKey(), - GrpcOperationLedgerRecord.claim(identity, requestFingerprint, now)); - return Optional.ofNullable(existing); - } - - @Override - public Optional find(GrpcOperationIdentity identity) { - if (unavailable) { - throw new IllegalStateException("ledger unavailable"); - } - return Optional.ofNullable(records.get(identity.storageKey())); - } - - @Override - public void markCommitted(GrpcOperationIdentity identity, String outcomeReference, Instant now) { - records.computeIfPresent( - identity.storageKey(), - (key, existing) -> - new GrpcOperationLedgerRecord( - existing.identity(), - GrpcOperationLedgerState.COMMITTED, - existing.requestFingerprint(), - Optional.of(outcomeReference), - existing.claimedAt(), - Optional.of(now))); - } - - @Override - public void markFailed(GrpcOperationIdentity identity, Instant now) { - records.computeIfPresent( - identity.storageKey(), - (key, existing) -> - new GrpcOperationLedgerRecord( - existing.identity(), - GrpcOperationLedgerState.FAILED_TERMINAL, - existing.requestFingerprint(), - Optional.empty(), - existing.claimedAt(), - Optional.of(now))); - } - - @Override - public void release(GrpcOperationIdentity identity) { - records.remove(identity.storageKey()); - } -} diff --git a/src/messaging/CLAUDE.md b/src/messaging/CLAUDE.md index d051e292..6b2ad649 100644 --- a/src/messaging/CLAUDE.md +++ b/src/messaging/CLAUDE.md @@ -17,9 +17,9 @@ leaf의 정확한 id는 registry에서 읽는다. family는 **디렉터리 이 | `*-api` (`core-api`, `schema-api`, `policy`, `reliability-api`, `admin-api`, `transport-spi`) | 값 타입, 포트, 정책 계약 | Java stdlib만. Spring/broker SDK/logging framework 금지 | | `schema-*` (json/avro/protobuf), `cloudevents` | 인코딩 구현 | 해당 codec 라이브러리만. Spring 금지 | | `runtime-core`, `security`, `observability`, `admin-runtime` | framework-free 실행 로직 | Micrometer는 `observability`에서만. 나머지는 stdlib | -| `kafka`, `rabbit`, `pulsar-experimental`, `nats-experimental`, `kafka-share-experimental` | broker adapter | 해당 broker client. Spring은 `rabbit`의 `spring-rabbit`처럼 client가 곧 Spring인 경우만 | +| `kafka` | broker adapter | 해당 broker client. Spring은 client가 곧 Spring인 경우만 | | `outbox-jdbc-postgresql`, `inbox-jdbc-postgresql` | 관계형 신뢰성 adapter | Spring JDBC / Spring TX. **JPA 아님** — 이름이 곧 계약이다 | -| `spring-boot-starter`, `spring-cloud-stream-bridge` | 조립 경계 | Spring Boot autoconfigure. 여기서만 | +| `spring-boot-starter`, `spring-boot-starter-kafka` | 조립 경계 | Spring Boot autoconfigure. 여기서만 | | `testkit` | 테스트 지원 | Testcontainers, JUnit. production leaf가 의존하지 않는다 | `outbox`/`inbox` leaf가 `jdbc-postgresql`로 명명된 이유: 구현은 Spring JDBC이고 SQL은 @@ -31,7 +31,7 @@ leaf의 정확한 id는 registry에서 읽는다. family는 **디렉터리 이 - **vendor 타입을 public signature에 노출하면 그 의존성은 `api`로 선언한다.** 숨긴다고 타입이 숨겨지지 않는다 — consumer가 이 모듈이 문서화한 API에 대해 컴파일하지 못하게 만들 뿐이다. - (`kafka-clients`, `spring-rabbit`, `cloudevents-api`, `micrometer-core`, `avro`, + (`kafka-clients`, `cloudevents-api`, `micrometer-core`, `avro`, `protobuf-java`, `reactor-core`가 이 규칙으로 `api`다.) - 반대로 **노출하지 않는 것은 `implementation`으로 낮춘다.** starter가 노출하지 않는 하위 모듈을 `implementation`으로 내린 것이, JSON codec이 `ObjectMapper`를 private으로만 쓰고 Jackson을 @@ -45,12 +45,15 @@ leaf의 정확한 id는 registry에서 읽는다. family는 **디렉터리 이 ## Application runtime에 포함되는 기준 -Messaging family는 기본 application이 `messaging-spring-boot-starter`를 dependency로 가지므로 그 -transitive project graph가 runtime에 포함된다. 이 사실의 SSOT는 Gradle `runtimeClasspath`이며 registry에 -동일한 membership 목록을 복제하지 않는다. `app.messaging.enabled=false`가 기본값이고 master switch가 -activation을 결정한다. +기본 조립에는 Messaging family가 없다. 서비스가 `app-bootstrap/build.gradle`에 +`runtimeOnly project(':adapter:outbound:messaging-kafka')` 한 줄을 넣으면 그 모듈이 bridge와 +`messaging-spring-boot-starter`(Kafka transport 포함)의 transitive project graph를 runtime에 싣는다. 이 +사실의 SSOT는 Gradle `runtimeClasspath`이며 registry에 동일한 membership 목록을 복제하지 않는다. +모듈이 있으면 켜지고(`app.messaging.enabled` 기본 `true`), `APP_MESSAGING_ENABLED=false`로만 끈다. -experimental transport, 일부 codec/bridge/testkit처럼 starter graph에 들어오지 않는 leaf는 build-only다. +일부 codec(cloudevents 등)·claim-check·testkit처럼 starter graph에 들어오지 않는 leaf는 build-only다. +RabbitMQ·Pulsar·NATS·Kafka Share·Spring Cloud Stream bridge leaf와 Debezium outbox 매핑은 +2026-09-25에 삭제했다(`docs/capability-status.md` 제거 표). 새 leaf를 application에 채택할 때는 starter 또는 composition dependency와 architecture edge policy, qualification/support 상태를 함께 변경한다. @@ -79,10 +82,9 @@ canonical bridge의 producer identity는 `app.messaging.producer-id`로 명시 `ca-skeleton.outbox.canonical-transport-enabled=true`는 bridge 존재만으로 충분하지 않다. Stable composition은 애플리케이션 계약 catalog/schema source를 임의로 만들지 않으므로 adopter가 -`IntegrationEventEncoderPort`를 명시적으로 제공해야 한다. 저장소의 후보 구현은 -`JsonSchemaIntegrationEventEncoder`이지만 이를 사용하려면 compiled contract descriptor, -`LocalJsonSchemaRegistry`, payload/envelope limits와 key material에 해당하는 application-owned 입력을 -같이 조립해야 한다. `OutboxCanonicalTransportRequirementValidator`는 publisher 또는 encoder 중 하나라도 +`IntegrationEventEncoderPort`를 명시적으로 제공해야 한다. 템플릿은 구현체를 주지 않는다(후보였던 +R1 JSON Schema encoder는 2026-09-25에 삭제). `OutboxCanonicalTransportRequirementValidator`는 +publisher 또는 encoder 중 하나라도 없으면 startup을 거부한다. 즉 canonical flag가 켜졌는데 정본 encoder가 없는 상태로 성공 기동하는 경로는 없다. diff --git a/src/messaging/messaging-kafka-share-experimental/build.gradle b/src/messaging/messaging-kafka-share-experimental/build.gradle deleted file mode 100644 index 33edc258..00000000 --- a/src/messaging/messaging-kafka-share-experimental/build.gradle +++ /dev/null @@ -1,11 +0,0 @@ -plugins { - id 'ca.platform-module' -} - -dependencies { - api project(':messaging:messaging-core-api') - api project(':messaging:messaging-policy') - api project(':messaging:messaging-transport-spi') - api project(':messaging:messaging-kafka') - -} diff --git a/src/messaging/messaging-kafka-share-experimental/gradle.lockfile b/src/messaging/messaging-kafka-share-experimental/gradle.lockfile deleted file mode 100644 index eaf97d56..00000000 --- a/src/messaging/messaging-kafka-share-experimental/gradle.lockfile +++ /dev/null @@ -1,93 +0,0 @@ -# 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. -at.yawk.lz4:lz4-java:1.10.1=runtimeClasspath,testRuntimeClasspath -com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,testAnnotationProcessor -com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,testAnnotationProcessor -com.github.luben:zstd-jni:1.5.6-10=runtimeClasspath,testRuntimeClasspath -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.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_annotations:2.41.0=spotbugs -com.google.errorprone:error_prone_annotations:2.47.0=checkstyle -com.google.errorprone:error_prone_annotations:2.49.0=annotationProcessor,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.5.0-jre=annotationProcessor,testAnnotationProcessor -com.google.guava:guava:33.6.0-jre=checkstyle -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.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 -io.micrometer:micrometer-commons:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.micrometer:micrometer-core:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.micrometer:micrometer-observation:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -javax.inject:javax.inject:1=annotationProcessor,testAnnotationProcessor -jaxen:jaxen:2.0.6=spotbugs -net.bytebuddy:byte-buddy:1.17.8=testCompileClasspath,testRuntimeClasspath -net.sf.saxon:Saxon-HE:12.9=checkstyle,spotbugs -org.antlr:antlr4-runtime:4.13.2=checkstyle -org.apache.bcel:bcel:6.12.0=spotbugs -org.apache.commons:commons-lang3:3.20.0=checkstyle,spotbugs -org.apache.commons:commons-text:1.15.0=spotbugs -org.apache.commons:commons-text:1.3=checkstyle -org.apache.httpcomponents:httpclient:4.5.13=checkstyle -org.apache.httpcomponents:httpcore:4.4.16=checkstyle -org.apache.kafka:kafka-clients:4.1.2=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.apache.logging.log4j:log4j-api:2.25.5=spotbugs -org.apache.logging.log4j:log4j-core:2.25.5=spotbugs -org.apache.maven.doxia:doxia-core:1.12.0=checkstyle -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 -org.assertj:assertj-core:3.27.7=testCompileClasspath,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.3.0=checkstyle -org.dom4j:dom4j:2.2.0=spotbugs -org.hdrhistogram:HdrHistogram:2.2.2=runtimeClasspath,testRuntimeClasspath -org.javassist:javassist:3.28.0-GA=checkstyle -org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,compileClasspath,runtimeClasspath,testAnnotationProcessor,testCompileClasspath,testRuntimeClasspath -org.junit.jupiter:junit-jupiter-api:6.0.3=testCompileClasspath,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-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.1.0=spotbugs -org.latencyutils:LatencyUtils:2.0.3=runtimeClasspath,testRuntimeClasspath -org.mockito:mockito-core:5.20.0=mockitoAgent -org.opentest4j:opentest4j:1.3.0=testCompileClasspath,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.reflections:reflections:0.10.2=checkstyle -org.slf4j:slf4j-api:2.0.18=runtimeClasspath,spotbugs,spotbugsSlf4j,testRuntimeClasspath -org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j -org.slf4j:slf4j-simple:2.0.18=checkstyle -org.xerial.snappy:snappy-java:1.1.10.7=runtimeClasspath,testRuntimeClasspath -org.xmlresolver:xmlresolver:5.3.3=checkstyle,spotbugs -empty= diff --git a/src/messaging/messaging-kafka-share-experimental/src/main/java/dev/caskeleton/messaging/kafka/share/KafkaShareGroupRegistrar.java b/src/messaging/messaging-kafka-share-experimental/src/main/java/dev/caskeleton/messaging/kafka/share/KafkaShareGroupRegistrar.java deleted file mode 100644 index 07c9ec1f..00000000 --- a/src/messaging/messaging-kafka-share-experimental/src/main/java/dev/caskeleton/messaging/kafka/share/KafkaShareGroupRegistrar.java +++ /dev/null @@ -1,48 +0,0 @@ -package dev.caskeleton.messaging.kafka.share; - -import dev.caskeleton.messaging.api.error.MessagingCapabilityUnavailableException; -import dev.caskeleton.messaging.transport.TransportConsumerRegistration; -import dev.caskeleton.messaging.transport.TransportConsumerSpec; -import java.util.Objects; - -/** - * Registers a share group consumer, once the experimental guard has passed. - * - *

Pause and resume are refused rather than silently ignored. A share group has no partition - * assignment to pause, so accepting the call would let a retry policy that depends on pausing - * appear to work while doing nothing. - */ -public final class KafkaShareGroupRegistrar { - - private final KafkaShareProfileValidator validator; - - /** Creates a registrar with the default validator. */ - public KafkaShareGroupRegistrar() { - this(new KafkaShareProfileValidator()); - } - - /** - * Creates a registrar with an explicit validator. - * - * @param validator the share profile validator - */ - public KafkaShareGroupRegistrar(KafkaShareProfileValidator validator) { - this.validator = Objects.requireNonNull(validator, "validator must not be null"); - } - - /** - * Registers a share group consumer. - * - * @param profile the share group profile - * @param spec what to consume and where to deliver it - * @return the registration - */ - public TransportConsumerRegistration register( - KafkaShareProfile profile, TransportConsumerSpec spec) { - Objects.requireNonNull(spec, "spec must not be null"); - validator.validate(profile); - throw new MessagingCapabilityUnavailableException( - "KAFKA_SHARE_CONSUMER_NOT_IMPLEMENTED", - "Kafka Share registration is not implemented; refusing to advertise an active consumer"); - } -} diff --git a/src/messaging/messaging-kafka-share-experimental/src/main/java/dev/caskeleton/messaging/kafka/share/KafkaShareProfile.java b/src/messaging/messaging-kafka-share-experimental/src/main/java/dev/caskeleton/messaging/kafka/share/KafkaShareProfile.java deleted file mode 100644 index 276207c1..00000000 --- a/src/messaging/messaging-kafka-share-experimental/src/main/java/dev/caskeleton/messaging/kafka/share/KafkaShareProfile.java +++ /dev/null @@ -1,33 +0,0 @@ -package dev.caskeleton.messaging.kafka.share; - -import dev.caskeleton.messaging.api.delivery.OrderingScope; -import dev.caskeleton.messaging.api.destination.DestinationName; -import java.util.Objects; - -/** - * Settings for a Kafka Share Group work queue. - * - * @param destination the logical destination - * @param shareGroup the share group name - * @param orderingScope the ordering the destination declares - * @param enabled whether the experimental adapter is switched on - * @param maxDeliveryCount how many times a record may be re-acquired before it is released - */ -public record KafkaShareProfile( - DestinationName destination, - String shareGroup, - OrderingScope orderingScope, - boolean enabled, - int maxDeliveryCount) { - - public KafkaShareProfile { - Objects.requireNonNull(destination, "destination must not be null"); - Objects.requireNonNull(orderingScope, "orderingScope must not be null"); - if (shareGroup == null || shareGroup.isBlank()) { - throw new IllegalArgumentException("shareGroup must not be blank"); - } - if (maxDeliveryCount < 1) { - throw new IllegalArgumentException("maxDeliveryCount must be at least 1"); - } - } -} diff --git a/src/messaging/messaging-kafka-share-experimental/src/main/java/dev/caskeleton/messaging/kafka/share/KafkaShareProfileValidator.java b/src/messaging/messaging-kafka-share-experimental/src/main/java/dev/caskeleton/messaging/kafka/share/KafkaShareProfileValidator.java deleted file mode 100644 index 1bd0390e..00000000 --- a/src/messaging/messaging-kafka-share-experimental/src/main/java/dev/caskeleton/messaging/kafka/share/KafkaShareProfileValidator.java +++ /dev/null @@ -1,42 +0,0 @@ -package dev.caskeleton.messaging.kafka.share; - -import dev.caskeleton.messaging.api.delivery.OrderingScope; -import dev.caskeleton.messaging.api.error.MessagingCapabilityUnavailableException; -import java.util.Objects; - -/** - * Guards the Kafka Share Group experimental adapter. - * - *

A share group hands individual records to competing consumers and acknowledges them - * individually. That is a work queue, and it is fundamentally incompatible with partition ordering: - * two consumers in the same share group can process records from one partition concurrently and - * finish in either order. Configuring an ordered destination on a share group would therefore - * advertise a guarantee the broker is not providing, so it is refused rather than degraded. - * - *

The adapter is also off unless explicitly enabled, so an Experimental capability cannot drift - * into a Stable deployment by default. - */ -public final class KafkaShareProfileValidator { - - /** - * Validates a share group profile. - * - * @param profile the profile to validate - * @throws IllegalArgumentException when the destination requires ordering - * @throws MessagingCapabilityUnavailableException when the experimental adapter is disabled - */ - public void validate(KafkaShareProfile profile) { - Objects.requireNonNull(profile, "profile must not be null"); - - if (!profile.enabled()) { - throw new MessagingCapabilityUnavailableException( - "KAFKA_SHARE_DISABLED", - "the Kafka Share Group adapter is experimental and disabled unless " - + "backend.messaging.experimental.kafka-share=true"); - } - if (profile.orderingScope() != OrderingScope.NONE) { - throw new IllegalArgumentException( - "a Kafka share group cannot provide ordered delivery: " + profile.destination().value()); - } - } -} diff --git a/src/messaging/messaging-kafka-share-experimental/src/main/java/dev/caskeleton/messaging/kafka/share/KafkaShareWorkQueueCapability.java b/src/messaging/messaging-kafka-share-experimental/src/main/java/dev/caskeleton/messaging/kafka/share/KafkaShareWorkQueueCapability.java deleted file mode 100644 index afa4907a..00000000 --- a/src/messaging/messaging-kafka-share-experimental/src/main/java/dev/caskeleton/messaging/kafka/share/KafkaShareWorkQueueCapability.java +++ /dev/null @@ -1,27 +0,0 @@ -package dev.caskeleton.messaging.kafka.share; - -import dev.caskeleton.messaging.api.destination.MessagingCapabilities; - -/** - * What a Kafka Share Group can and cannot do. - * - *

Declared as a capability rather than assumed, so that the shared validators refuse an ordered - * or replayed destination on this adapter before a message is ever produced. - */ -public final class KafkaShareWorkQueueCapability { - - private KafkaShareWorkQueueCapability() {} - - /** - * Returns the share group capability set. - * - *

Per-record settlement, yes. Ordering, replay, and transactions, no — a share group gives up - * exactly those to gain competing-consumer throughput. - * - * @return the capabilities - */ - public static MessagingCapabilities capabilities() { - return new MessagingCapabilities( - true, true, true, false, false, false, false, false, false, false, false, false); - } -} diff --git a/src/messaging/messaging-kafka-share-experimental/src/test/java/dev/caskeleton/messaging/kafka/share/KafkaShareProfileValidatorTest.java b/src/messaging/messaging-kafka-share-experimental/src/test/java/dev/caskeleton/messaging/kafka/share/KafkaShareProfileValidatorTest.java deleted file mode 100644 index e2ecf9ab..00000000 --- a/src/messaging/messaging-kafka-share-experimental/src/test/java/dev/caskeleton/messaging/kafka/share/KafkaShareProfileValidatorTest.java +++ /dev/null @@ -1,113 +0,0 @@ -package dev.caskeleton.messaging.kafka.share; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.messaging.api.delivery.OrderingScope; -import dev.caskeleton.messaging.api.destination.DestinationName; -import dev.caskeleton.messaging.api.error.MessagingCapabilityUnavailableException; -import org.junit.jupiter.api.Test; - -class KafkaShareProfileValidatorTest { - - private final KafkaShareProfileValidator validator = new KafkaShareProfileValidator(); - - @Test - void rejectsOrderedStreamUse() { - KafkaShareProfile profile = KafkaShareProfileFixtures.profile(OrderingScope.KEY); - - assertThatThrownBy(() -> validator.validate(profile)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("ordered"); - } - - @Test - void rejectsPartitionOrderingToo() { - KafkaShareProfile profile = KafkaShareProfileFixtures.profile(OrderingScope.PARTITION); - - assertThatThrownBy(() -> validator.validate(profile)) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void staysDisabledUnlessExplicitlyEnabled() { - KafkaShareProfile profile = KafkaShareProfileFixtures.disabled(); - - assertThatThrownBy(() -> validator.validate(profile)) - .isInstanceOf(MessagingCapabilityUnavailableException.class) - .hasMessageContaining("experimental"); - } - - @Test - void acceptsAnUnorderedWorkQueue() { - assertThatCode(() -> validator.validate(KafkaShareProfileFixtures.profile(OrderingScope.NONE))) - .doesNotThrowAnyException(); - } - - @Test - void doesNotAdvertiseOrderingReplayOrTransactions() { - var capabilities = KafkaShareWorkQueueCapability.capabilities(); - - assertThat(capabilities.perMessageSettlement()).isTrue(); - assertThat(capabilities.orderedStream()).isFalse(); - assertThat(capabilities.keyedOrdering()).isFalse(); - assertThat(capabilities.replay()).isFalse(); - assertThat(capabilities.brokerTransaction()).isFalse(); - } - - @Test - void registerFailsClosedUntilAShareConsumerActuallyExists() { - assertThatThrownBy( - () -> - new KafkaShareGroupRegistrar() - .register( - KafkaShareProfileFixtures.profile(OrderingScope.NONE), - new dev.caskeleton.messaging.transport.TransportConsumerSpec( - KafkaShareProfileFixtures.destinationProfile(), - delivery -> - java.util.concurrent.CompletableFuture.completedFuture(null)))) - .isInstanceOf(MessagingCapabilityUnavailableException.class) - .hasMessageContaining("not implemented"); - } -} - -/** Builds Kafka share group fixtures. */ -final class KafkaShareProfileFixtures { - - private KafkaShareProfileFixtures() {} - - static KafkaShareProfile profile(OrderingScope orderingScope) { - return new KafkaShareProfile( - new DestinationName("email-work"), "email-share", orderingScope, true, 5); - } - - static KafkaShareProfile disabled() { - return new KafkaShareProfile( - new DestinationName("email-work"), "email-share", OrderingScope.NONE, false, 5); - } - - static dev.caskeleton.messaging.policy.DestinationProfile destinationProfile() { - return new dev.caskeleton.messaging.policy.DestinationProfile( - new DestinationName("email-work"), - "kafka-primary", - dev.caskeleton.messaging.api.destination.DestinationKind.WORK_QUEUE, - dev.caskeleton.messaging.policy.PhysicalDestination.kafkaTopic("email.work.v1"), - new dev.caskeleton.messaging.policy.SchemaPolicy( - dev.caskeleton.messaging.api.ContentType.JSON, - dev.caskeleton.messaging.schema.SchemaCompatibility.BACKWARD, - java.util.Set.of(new dev.caskeleton.messaging.api.MessageType("email.requested"))), - dev.caskeleton.messaging.api.delivery.DeliveryGuarantee.AT_LEAST_ONCE, - OrderingScope.NONE, - dev.caskeleton.messaging.api.delivery.ExternalSideEffectGuarantee.IDEMPOTENCY_REQUIRED, - dev.caskeleton.messaging.policy.ProducerPolicy.defaults(), - dev.caskeleton.messaging.policy.ConsumerPolicy.defaults("email-share"), - dev.caskeleton.messaging.policy.RetryPolicy.none(), - dev.caskeleton.messaging.policy.DeadLetterPolicy.disabled(), - dev.caskeleton.messaging.policy.PayloadPolicy.defaults(), - dev.caskeleton.messaging.policy.CapabilityTier.M2, - false, - false, - false); - } -} diff --git a/src/messaging/messaging-kafka/build.gradle b/src/messaging/messaging-kafka/build.gradle index 789445b7..75b48b2e 100644 --- a/src/messaging/messaging-kafka/build.gradle +++ b/src/messaging/messaging-kafka/build.gradle @@ -1,8 +1,13 @@ plugins { id 'java-test-fixtures' id 'ca.auxiliary-source-set' - id 'ca.jmh-benchmarks' - id 'ca.messaging-certification' + id 'ca.platform-module' + id 'me.champeau.jmh' +} + +jmh { + jmhVersion = libs.versions.jmh.get() + includeTests = true } auxiliarySourceSets { @@ -82,3 +87,30 @@ strictTestLanes { .toString() } } + +// The certification lane writes the scenarios it proved; the committed manifest in messaging-testkit +// may claim no more and no fewer. gitCommit and observedAt are provenance, not claim identity. +tasks.register('verifyMessagingCertificationEvidence') { + group = 'verification' + description = 'Fails when the committed broker certification manifest claims a scenario the certification lane did not produce.' + dependsOn 'messagingCertificationTest' + def produced = layout.buildDirectory.file('messaging-certification/broker-certification-evidence.jsonl') + def committed = rootProject.file('messaging/messaging-testkit/src/main/resources/messaging/broker-certification-evidence.jsonl') + inputs.file(produced) + inputs.file(committed) + doLast { + def claims = { File file -> + file.readLines('UTF-8').findAll { !it.trim().isEmpty() }.collect { + it.replaceAll(/,"gitCommit":"[^"]*"/, '').replaceAll(/,"observedAt":"[^"]*"/, '') + } as Set + } + def ran = claims(produced.get().asFile) + def shipped = claims(committed) + if (ran != shipped) { + throw new GradleException("the committed certification manifest does not match this run.\n" + + " claimed but not produced: ${shipped - ran}\n produced but not claimed: ${ran - shipped}\n" + + "Copy ${produced.get().asFile} over ${committed} — the manifest is a record of a run.") + } + } +} + diff --git a/src/messaging/messaging-kafka/gradle.lockfile b/src/messaging/messaging-kafka/gradle.lockfile index b0dd01f0..ecffd2ee 100644 --- a/src/messaging/messaging-kafka/gradle.lockfile +++ b/src/messaging/messaging-kafka/gradle.lockfile @@ -46,15 +46,15 @@ io.micrometer:micrometer-core:1.16.7=compileClasspath,integrationTestCompileClas io.micrometer:micrometer-observation:1.16.7=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath javax.inject:javax.inject:1=annotationProcessor,integrationTestAnnotationProcessor,jmhAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor jaxen:jaxen:2.0.6=spotbugs -net.bytebuddy:byte-buddy:1.17.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +net.bytebuddy:byte-buddy:1.17.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath net.java.dev.jna:jna:5.18.1=integrationTestCompileClasspath,integrationTestRuntimeClasspath -net.sf.jopt-simple:jopt-simple:5.0.4=jmhAnnotationProcessor,jmhCompileClasspath,jmhRuntimeClasspath +net.sf.jopt-simple:jopt-simple:5.0.4=jmh,jmhCompileClasspath,jmhRuntimeClasspath net.sf.saxon:Saxon-HE:12.9=checkstyle,spotbugs org.antlr:antlr4-runtime:4.13.2=checkstyle org.apache.bcel:bcel:6.12.0=spotbugs org.apache.commons:commons-compress:1.28.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath org.apache.commons:commons-lang3:3.20.0=checkstyle,integrationTestCompileClasspath,integrationTestRuntimeClasspath,spotbugs -org.apache.commons:commons-math3:3.6.1=jmhAnnotationProcessor,jmhCompileClasspath,jmhRuntimeClasspath +org.apache.commons:commons-math3:3.6.1=jmh,jmhCompileClasspath,jmhRuntimeClasspath org.apache.commons:commons-text:1.15.0=spotbugs org.apache.commons:commons-text:1.3=checkstyle org.apache.httpcomponents:httpclient:4.5.13=checkstyle @@ -67,8 +67,8 @@ 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=integrationTestCompileClasspath,jmhCompileClasspath,testCompileClasspath,testFixturesCompileClasspath -org.assertj:assertj-core:3.27.7=integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.apiguardian:apiguardian-api:1.1.2=integrationTestCompileClasspath,testCompileClasspath,testFixturesCompileClasspath +org.assertj:assertj-core:3.27.7=integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,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 @@ -78,24 +78,27 @@ org.hdrhistogram:HdrHistogram:2.2.2=integrationTestRuntimeClasspath,jmhRuntimeCl org.javassist:javassist:3.28.0-GA=checkstyle org.jetbrains:annotations:17.0.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,compileClasspath,integrationTestAnnotationProcessor,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhAnnotationProcessor,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testAnnotationProcessor,testCompileClasspath,testFixturesAnnotationProcessor,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath -org.junit.jupiter:junit-jupiter-api:6.0.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.junit.jupiter:junit-jupiter-api:6.0.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.junit.jupiter:junit-jupiter-engine:6.0.3=integrationTestRuntimeClasspath,jmhRuntimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath -org.junit.jupiter:junit-jupiter-params:6.0.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath -org.junit.jupiter:junit-jupiter:6.0.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath -org.junit.platform:junit-platform-commons:6.0.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.junit.jupiter:junit-jupiter-params:6.0.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.junit.jupiter:junit-jupiter:6.0.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.junit.platform:junit-platform-commons:6.0.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.junit.platform:junit-platform-engine:6.0.3=integrationTestRuntimeClasspath,jmhRuntimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.junit.platform:junit-platform-launcher:6.0.3=integrationTestRuntimeClasspath,jmhRuntimeClasspath,testRuntimeClasspath -org.junit:junit-bom:6.0.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.junit:junit-bom:6.0.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.junit:junit-bom:6.1.0=spotbugs org.latencyutils:LatencyUtils:2.0.3=integrationTestRuntimeClasspath,jmhRuntimeClasspath,runtimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath org.mockito:mockito-core:5.20.0=mockitoAgent -org.openjdk.jmh:jmh-core:1.37=jmhAnnotationProcessor,jmhCompileClasspath,jmhRuntimeClasspath -org.openjdk.jmh:jmh-generator-annprocess:1.37=jmhAnnotationProcessor -org.opentest4j:opentest4j:1.3.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath +org.openjdk.jmh:jmh-core:1.37=jmh,jmhCompileClasspath,jmhRuntimeClasspath +org.openjdk.jmh:jmh-generator-asm:1.37=jmh,jmhCompileClasspath,jmhRuntimeClasspath +org.openjdk.jmh:jmh-generator-bytecode:1.37=jmh,jmhCompileClasspath,jmhRuntimeClasspath +org.openjdk.jmh:jmh-generator-reflection:1.37=jmh,jmhCompileClasspath,jmhRuntimeClasspath +org.opentest4j:opentest4j:1.3.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhRuntimeClasspath,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.0=jmh,jmhCompileClasspath,jmhRuntimeClasspath org.ow2.asm:asm:9.10.1=spotbugs org.pcollections:pcollections:4.0.1=annotationProcessor,integrationTestAnnotationProcessor,jmhAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor org.reflections:reflections:0.10.2=checkstyle diff --git a/src/messaging/messaging-nats-experimental/build.gradle b/src/messaging/messaging-nats-experimental/build.gradle deleted file mode 100644 index 929bf94c..00000000 --- a/src/messaging/messaging-nats-experimental/build.gradle +++ /dev/null @@ -1,14 +0,0 @@ -plugins { - id 'ca.platform-module' -} - -dependencies { - api project(':messaging:messaging-core-api') - api project(':messaging:messaging-schema-api') - api project(':messaging:messaging-policy') - api project(':messaging:messaging-transport-spi') - api project(':messaging:messaging-observability') - api project(':messaging:messaging-security') - api project(':messaging:messaging-admin-api') - -} diff --git a/src/messaging/messaging-nats-experimental/gradle.lockfile b/src/messaging/messaging-nats-experimental/gradle.lockfile deleted file mode 100644 index f5ad1bb5..00000000 --- a/src/messaging/messaging-nats-experimental/gradle.lockfile +++ /dev/null @@ -1,89 +0,0 @@ -# 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.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.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_annotations:2.41.0=spotbugs -com.google.errorprone:error_prone_annotations:2.47.0=checkstyle -com.google.errorprone:error_prone_annotations:2.49.0=annotationProcessor,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.5.0-jre=annotationProcessor,testAnnotationProcessor -com.google.guava:guava:33.6.0-jre=checkstyle -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.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 -io.micrometer:micrometer-commons:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.micrometer:micrometer-core:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.micrometer:micrometer-observation:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -javax.inject:javax.inject:1=annotationProcessor,testAnnotationProcessor -jaxen:jaxen:2.0.6=spotbugs -net.bytebuddy:byte-buddy:1.17.8=testCompileClasspath,testRuntimeClasspath -net.sf.saxon:Saxon-HE:12.9=checkstyle,spotbugs -org.antlr:antlr4-runtime:4.13.2=checkstyle -org.apache.bcel:bcel:6.12.0=spotbugs -org.apache.commons:commons-lang3:3.20.0=checkstyle,spotbugs -org.apache.commons:commons-text:1.15.0=spotbugs -org.apache.commons:commons-text:1.3=checkstyle -org.apache.httpcomponents:httpclient:4.5.13=checkstyle -org.apache.httpcomponents:httpcore:4.4.16=checkstyle -org.apache.logging.log4j:log4j-api:2.25.5=spotbugs -org.apache.logging.log4j:log4j-core:2.25.5=spotbugs -org.apache.maven.doxia:doxia-core:1.12.0=checkstyle -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 -org.assertj:assertj-core:3.27.7=testCompileClasspath,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.3.0=checkstyle -org.dom4j:dom4j:2.2.0=spotbugs -org.hdrhistogram:HdrHistogram:2.2.2=runtimeClasspath,testRuntimeClasspath -org.javassist:javassist:3.28.0-GA=checkstyle -org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,compileClasspath,runtimeClasspath,testAnnotationProcessor,testCompileClasspath,testRuntimeClasspath -org.junit.jupiter:junit-jupiter-api:6.0.3=testCompileClasspath,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-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.1.0=spotbugs -org.latencyutils:LatencyUtils:2.0.3=runtimeClasspath,testRuntimeClasspath -org.mockito:mockito-core:5.20.0=mockitoAgent -org.opentest4j:opentest4j:1.3.0=testCompileClasspath,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.reflections:reflections:0.10.2=checkstyle -org.slf4j:slf4j-api:2.0.18=spotbugs,spotbugsSlf4j -org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j -org.slf4j:slf4j-simple:2.0.18=checkstyle -org.xmlresolver:xmlresolver:5.3.3=checkstyle,spotbugs -empty= diff --git a/src/messaging/messaging-nats-experimental/src/main/java/dev/caskeleton/messaging/nats/NatsAckMode.java b/src/messaging/messaging-nats-experimental/src/main/java/dev/caskeleton/messaging/nats/NatsAckMode.java deleted file mode 100644 index 2a8b865a..00000000 --- a/src/messaging/messaging-nats-experimental/src/main/java/dev/caskeleton/messaging/nats/NatsAckMode.java +++ /dev/null @@ -1,57 +0,0 @@ -package dev.caskeleton.messaging.nats; - -/** - * How a JetStream consumer acknowledges what it has handled. - * - *

Only {@link #EXPLICIT} is usable by the platform, and the other two are modelled anyway so the - * refusal can name what was configured instead of failing with a generic message. - * - *

{@link #NONE} and {@link #ALL} both break at-least-once in ways that look like success. {@code - * AckNone} never acknowledges, so JetStream considers every message delivered the moment it is sent - * — a handler that throws has already had its message forgotten. {@code AckAll} acknowledges every - * message up to the one being acknowledged, so a consumer processing messages concurrently silently - * acknowledges work that is still in flight. - */ -public enum NatsAckMode { - - /** Every message is acknowledged individually. The only mode the platform supports. */ - EXPLICIT(true), - - /** Acknowledging one message acknowledges every earlier one. */ - ALL(false), - - /** No acknowledgement at all; JetStream treats delivery as completion. */ - NONE(false); - - private final boolean supportsAtLeastOnce; - - NatsAckMode(boolean supportsAtLeastOnce) { - this.supportsAtLeastOnce = supportsAtLeastOnce; - } - - /** - * Reports whether this mode can carry at-least-once delivery. - * - * @return true only for {@link #EXPLICIT} - */ - public boolean supportsAtLeastOnce() { - return supportsAtLeastOnce; - } - - /** - * Returns why a mode cannot be used, for the refusal message. - * - * @return the sanitized reason, empty for {@link #EXPLICIT} - */ - public String rejectionReason() { - return switch (this) { - case EXPLICIT -> ""; - case ALL -> - "AckAll acknowledges every earlier message, so concurrent handling silently settles work " - + "that is still in flight"; - case NONE -> - "AckNone treats delivery as completion, so a message whose handler throws has already " - + "been forgotten by the broker"; - }; - } -} diff --git a/src/messaging/messaging-nats-experimental/src/main/java/dev/caskeleton/messaging/nats/NatsJetStreamProfile.java b/src/messaging/messaging-nats-experimental/src/main/java/dev/caskeleton/messaging/nats/NatsJetStreamProfile.java deleted file mode 100644 index 2713ab27..00000000 --- a/src/messaging/messaging-nats-experimental/src/main/java/dev/caskeleton/messaging/nats/NatsJetStreamProfile.java +++ /dev/null @@ -1,103 +0,0 @@ -package dev.caskeleton.messaging.nats; - -import java.time.Duration; -import java.util.Objects; -import java.util.Optional; - -/** - * The JetStream settings for one destination. - * - *

{@code maxDeliver} is the setting that makes the platform's dead-lettering necessary. When a - * message reaches it, JetStream terminates the message — it stops redelivering and routes - * it nowhere. Without the platform parking it first, the message is simply gone, which is why - * {@link NatsMaxDeliverParkingWorkflow} has to run strictly before the limit is reached rather than - * in response to it. - * - *

{@code ackWait} is the redelivery trigger. A handler slower than {@code ackWait} gets its - * message redelivered while it is still working on it, so this is the one JetStream number that has - * to be set from the handler's real latency rather than from a default. - * - * @param subject the JetStream subject - * @param stream the stream capturing that subject - * @param durableName the durable consumer name - * @param ackMode how the consumer acknowledges - * @param ackWait how long JetStream waits before redelivering - * @param maxDeliver how many deliveries before JetStream terminates the message - * @param deduplicationWindow the publish deduplication window, when enabled - */ -public record NatsJetStreamProfile( - String subject, - String stream, - String durableName, - NatsAckMode ackMode, - Duration ackWait, - int maxDeliver, - Optional deduplicationWindow) { - - /** How many deliveries the platform leaves as headroom before JetStream's terminate. */ - public static final int PARKING_HEADROOM = 1; - - public NatsJetStreamProfile { - Objects.requireNonNull(ackMode, "ackMode must not be null"); - Objects.requireNonNull(ackWait, "ackWait must not be null"); - Objects.requireNonNull(deduplicationWindow, "deduplicationWindow must not be null"); - requireText(subject, "subject"); - requireText(stream, "stream"); - requireText(durableName, "durableName"); - - if (!ackMode.supportsAtLeastOnce()) { - throw new IllegalArgumentException( - "%s cannot carry at-least-once delivery: %s" - .formatted(ackMode, ackMode.rejectionReason())); - } - if (ackWait.isNegative() || ackWait.isZero()) { - throw new IllegalArgumentException("ackWait must be positive"); - } - if (maxDeliver < 2) { - throw new IllegalArgumentException( - "maxDeliver must leave at least one delivery of headroom for the platform to park the " - + "message before JetStream terminates it"); - } - if (deduplicationWindow.isPresent() - && (deduplicationWindow.get().isNegative() || deduplicationWindow.get().isZero())) { - throw new IllegalArgumentException("deduplicationWindow must be positive when set"); - } - } - - /** - * Returns the delivery count at which the platform must park the message. - * - *

Strictly before {@code maxDeliver}: acting on the limit itself is too late, because the - * delivery that reaches it is the one JetStream terminates. - * - * @return the parking threshold - */ - public int parkAtDelivery() { - return maxDeliver - PARKING_HEADROOM; - } - - /** - * Returns a profile with the platform defaults. - * - * @param subject the JetStream subject - * @param stream the stream name - * @param durableName the durable consumer name - * @return the profile - */ - public static NatsJetStreamProfile durable(String subject, String stream, String durableName) { - return new NatsJetStreamProfile( - subject, - stream, - durableName, - NatsAckMode.EXPLICIT, - Duration.ofSeconds(30), - 5, - Optional.of(Duration.ofMinutes(2))); - } - - private static void requireText(String value, String field) { - if (value == null || value.isBlank()) { - throw new IllegalArgumentException(field + " must not be blank"); - } - } -} diff --git a/src/messaging/messaging-nats-experimental/src/main/java/dev/caskeleton/messaging/nats/NatsJetStreamProfileValidator.java b/src/messaging/messaging-nats-experimental/src/main/java/dev/caskeleton/messaging/nats/NatsJetStreamProfileValidator.java deleted file mode 100644 index e5aaf179..00000000 --- a/src/messaging/messaging-nats-experimental/src/main/java/dev/caskeleton/messaging/nats/NatsJetStreamProfileValidator.java +++ /dev/null @@ -1,75 +0,0 @@ -package dev.caskeleton.messaging.nats; - -import dev.caskeleton.messaging.api.delivery.DeliveryGuarantee; -import dev.caskeleton.messaging.api.delivery.OrderingScope; -import dev.caskeleton.messaging.api.destination.MessagingCapabilities; -import dev.caskeleton.messaging.api.error.MessagingCapabilityUnavailableException; -import dev.caskeleton.messaging.policy.DestinationProfile; -import java.util.Objects; - -/** - * Guards the NATS JetStream Experimental adapter. - * - *

Core NATS is refused for any at-least-once destination. Core NATS is fire-and-forget with no - * persistence and no acknowledgement, so a durable destination configured against it would report - * success for messages that were never stored anywhere — the failure mode is total and silent. - * - *

An ordered JetStream consumer and a competing work queue are mutually exclusive: the ordered - * consumer is a single-reader construct, and pointing several workers at it does not distribute the - * load, it breaks the ordering the consumer exists to provide. - */ -public final class NatsJetStreamProfileValidator { - - /** - * Validates a destination against a JetStream consumer configuration. - * - * @param profile the destination profile - * @param jetStreamEnabled whether JetStream persistence is in use - * @param orderedConsumer whether an ordered consumer is configured - * @param competingWorkers how many workers share the consumer - * @param enabled whether the experimental adapter is switched on - */ - public void validate( - DestinationProfile profile, - boolean jetStreamEnabled, - boolean orderedConsumer, - int competingWorkers, - boolean enabled) { - Objects.requireNonNull(profile, "profile must not be null"); - - if (!enabled) { - throw new MessagingCapabilityUnavailableException( - "NATS_DISABLED", - "the NATS JetStream adapter is experimental and disabled unless " - + "app.messaging.experimental.nats=true"); - } - if (profile.deliveryGuarantee() == DeliveryGuarantee.AT_LEAST_ONCE && !jetStreamEnabled) { - throw new IllegalArgumentException( - "core NATS cannot provide at-least-once delivery; JetStream is required: " - + profile.name().value()); - } - if (orderedConsumer && competingWorkers > 1) { - throw new IllegalArgumentException( - "an ordered JetStream consumer cannot be shared by competing workers: " - + profile.name().value()); - } - if (profile.orderingScope() == OrderingScope.KEY) { - throw new IllegalArgumentException( - "the NATS adapter does not offer per-key ordering: " + profile.name().value()); - } - } - - /** - * Returns what the JetStream adapter can prove. - * - *

Native dead lettering is reported as unavailable. JetStream terminates a message after its - * delivery limit rather than routing it anywhere, so the platform supplies dead lettering itself; - * claiming a native one would leave operators looking for a queue that does not exist. - * - * @return the capabilities - */ - public MessagingCapabilities capabilities() { - return new MessagingCapabilities( - true, true, true, true, true, false, true, false, false, true, false, true); - } -} diff --git a/src/messaging/messaging-nats-experimental/src/main/java/dev/caskeleton/messaging/nats/NatsJetStreamTransport.java b/src/messaging/messaging-nats-experimental/src/main/java/dev/caskeleton/messaging/nats/NatsJetStreamTransport.java deleted file mode 100644 index bf8f5c8a..00000000 --- a/src/messaging/messaging-nats-experimental/src/main/java/dev/caskeleton/messaging/nats/NatsJetStreamTransport.java +++ /dev/null @@ -1,295 +0,0 @@ -package dev.caskeleton.messaging.nats; - -import dev.caskeleton.messaging.api.destination.DestinationCapabilities; -import dev.caskeleton.messaging.api.destination.DestinationName; -import dev.caskeleton.messaging.api.destination.MessagingCapabilities; -import dev.caskeleton.messaging.api.error.FailureCategory; -import dev.caskeleton.messaging.api.error.FailureDescriptor; -import dev.caskeleton.messaging.api.error.MessagingCapabilityUnavailableException; -import dev.caskeleton.messaging.api.publish.ConfirmationLevel; -import dev.caskeleton.messaging.api.publish.PublishCompletion; -import dev.caskeleton.messaging.api.publish.PublishEvidence; -import dev.caskeleton.messaging.api.publish.PublishResult; -import dev.caskeleton.messaging.api.publish.RoutingOutcome; -import dev.caskeleton.messaging.api.publish.TransmissionEvidence; -import dev.caskeleton.messaging.transport.MessagingTransport; -import dev.caskeleton.messaging.transport.TransportConsumerRegistration; -import dev.caskeleton.messaging.transport.TransportConsumerSpec; -import dev.caskeleton.messaging.transport.TransportPublishRequest; -import dev.caskeleton.messaging.transport.TransportPublishResult; -import java.time.Duration; -import java.util.Objects; -import java.util.Optional; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CompletionException; -import java.util.concurrent.CompletionStage; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.function.Function; - -/** - * The Experimental NATS JetStream adapter. - * - *

Publishes go through JetStream, never core NATS. A core publish returns as soon as the bytes - * are written to the socket, with no persistence and no acknowledgement, so an adapter using it - * would report success for messages that were never stored — the failure is total and silent, which - * is why {@link NatsJetStreamProfileValidator} refuses the combination at startup. - * - *

A JetStream publish acknowledgement names the stream and sequence the message landed in, which - * is real persistence evidence. A publish that times out is {@code AMBIGUOUS}: JetStream may have - * stored it and lost only the acknowledgement, and the deduplication window is what makes retrying - * it safe when the profile enables one. - * - *

This is an Experimental contract seam, not a Stable adapter. It exercises the transport SPI - * against a publish operation the application supplies; it does not ship a NATS client bridge, - * connection management, or reconnection. Only a failure the operation reports as a {@link - * NatsPreSendRejection} is treated as definitely not transmitted — every other failure, recognised - * or not, is ambiguous, because a caller that reads {@code REJECTED} may republish under a new - * identity and duplicate a message the server already stored. - * - *

The adapter reports {@code nativeDeadLetter} as false. JetStream terminates a message at its - * delivery limit rather than routing it anywhere, so the platform parks it via {@link - * NatsMaxDeliverParkingWorkflow}; claiming a native dead-letter would send operators looking for a - * queue that does not exist. - */ -public final class NatsJetStreamTransport implements MessagingTransport { - - private static final MessagingCapabilities CAPABILITIES = - new MessagingCapabilities( - true, true, true, true, true, false, true, false, false, true, false, true); - - private final String brokerName; - private final long generation; - private final NatsJetStreamProfile profile; - private final JetStreamPublishOperation publish; - private final Function consumerFactory; - private final AtomicBoolean closed = new AtomicBoolean(); - - /** - * Creates a publish-only transport. - * - * @param brokerName the logical broker name - * @param generation the runtime generation - * @param profile the JetStream settings - * @param publish the JetStream publish operation - */ - public NatsJetStreamTransport( - String brokerName, - long generation, - NatsJetStreamProfile profile, - JetStreamPublishOperation publish) { - this( - brokerName, - generation, - profile, - publish, - spec -> { - throw new MessagingCapabilityUnavailableException( - "NATS_CONSUMER_NOT_CONFIGURED", - "this NATS transport was created without a consumer factory"); - }); - } - - /** - * Creates a transport with a consumer factory. - * - * @param brokerName the logical broker name - * @param generation the runtime generation - * @param profile the JetStream settings - * @param publish the JetStream publish operation - * @param consumerFactory builds a consumer registration for a spec - */ - public NatsJetStreamTransport( - String brokerName, - long generation, - NatsJetStreamProfile profile, - JetStreamPublishOperation publish, - Function consumerFactory) { - this.brokerName = Objects.requireNonNull(brokerName, "brokerName must not be null"); - this.generation = generation; - this.profile = Objects.requireNonNull(profile, "profile must not be null"); - this.publish = Objects.requireNonNull(publish, "publish must not be null"); - this.consumerFactory = Objects.requireNonNull(consumerFactory, "consumerFactory is required"); - } - - @Override - public CompletionStage publish(TransportPublishRequest request) { - Objects.requireNonNull(request, "request must not be null"); - - if (closed.get()) { - return completed(rejectedLocally("NATS_TRANSPORT_CLOSED", "the transport is shutting down")); - } - int size = request.envelope().payload().size(); - int limit = request.profile().payload().maxBytes(); - if (size > limit) { - return completed( - rejectedLocally( - "PAYLOAD_TOO_LARGE", "encoded payload is " + size + " bytes, limit is " + limit)); - } - - // The caller's own deadline, honoured rather than ignored. Without it a stalled JetStream - // publish holds the caller for as long as the SDK's default takes, and the timeout the caller - // set to bound its own latency budget means nothing. - long startedAt = System.nanoTime(); - return publish - .publish(profile.subject(), deduplicationId(request), request) - .toCompletableFuture() - .orTimeout( - request.options().timeout().toMillis(), java.util.concurrent.TimeUnit.MILLISECONDS) - .handle( - (position, failure) -> - failure == null - ? confirmed(position, elapsedSince(startedAt)) - : classify(failure, elapsedSince(startedAt))) - .thenApply(TransportPublishResult::new); - } - - @Override - public TransportConsumerRegistration register(TransportConsumerSpec spec) { - Objects.requireNonNull(spec, "spec must not be null"); - if (closed.get()) { - throw new MessagingCapabilityUnavailableException( - "NATS_TRANSPORT_CLOSED", "the transport is shutting down"); - } - return consumerFactory.apply(spec); - } - - @Override - public DestinationCapabilities capabilities(DestinationName destination) { - return new DestinationCapabilities(destination, brokerName, CAPABILITIES); - } - - @Override - public String brokerName() { - return brokerName; - } - - @Override - public long generation() { - return generation; - } - - @Override - public void close() { - closed.set(true); - } - - /** - * Reports whether the transport is still accepting work. - * - * @return true until close - */ - public boolean isAcceptingWork() { - return !closed.get(); - } - - /** - * Returns the deduplication id for a publish, when the profile enables deduplication. - * - *

The logical message id, so a retry of an ambiguous publish is recognised as the same message - * rather than accepted as a new one. Minting a fresh id per attempt would make the deduplication - * window useless in exactly the situation it exists for. - * - * @param request the publish request - * @return the deduplication id, or empty when the profile has no window - */ - private Optional deduplicationId(TransportPublishRequest request) { - return profile - .deduplicationWindow() - .map(window -> request.envelope().messageId().value().toString()); - } - - private static Duration elapsedSince(long startedAtNanos) { - return Duration.ofNanos(System.nanoTime() - startedAtNanos); - } - - private static PublishResult confirmed(NatsStreamPosition position, Duration elapsed) { - return new PublishResult( - PublishCompletion.CONFIRMED, - // The publish acknowledgement names the stream and sequence the message landed in, which is - // persistence evidence rather than a receipt for bytes on a socket. - new PublishEvidence( - true, - TransmissionEvidence.TRANSMITTED, - true, - ConfirmationLevel.REPLICATION_OR_PERSISTENCE_ACK), - RoutingOutcome.ROUTED, - Optional.of(position), - 1, - elapsed, - Optional.empty()); - } - - /** - * Decides what a publish failure means, from typed signals only. - * - *

Only {@link NatsPreSendRejection} — thrown by the publish operation when it knows the send - * never left the client — reports {@code REJECTED / NOT_TRANSMITTED}. Everything else is {@code - * AMBIGUOUS}, including failures this adapter does not recognise, because the alternative is - * telling a caller nothing was transmitted when the server may already hold the message. - */ - private static PublishResult classify(Throwable failure, Duration elapsed) { - Throwable cause = failure instanceof CompletionException ? failure.getCause() : failure; - if (cause instanceof NatsPreSendRejection rejection) { - return new PublishResult( - PublishCompletion.REJECTED, - PublishEvidence.notTransmitted(), - RoutingOutcome.NOT_APPLICABLE, - Optional.empty(), - 1, - elapsed, - Optional.of( - FailureDescriptor.of( - FailureCategory.CONFIGURATION, rejection.code(), rejection.getMessage()))); - } - boolean timedOut = cause instanceof java.util.concurrent.TimeoutException; - return new PublishResult( - PublishCompletion.AMBIGUOUS, - new PublishEvidence( - true, TransmissionEvidence.MAY_HAVE_BEEN_TRANSMITTED, false, ConfirmationLevel.NONE), - RoutingOutcome.UNKNOWN, - Optional.empty(), - 1, - elapsed, - Optional.of( - FailureDescriptor.of( - FailureCategory.TRANSIENT_INFRASTRUCTURE, - timedOut ? "NATS_PUBLISH_TIMEOUT" : "NATS_PUBLISH_OUTCOME_UNKNOWN", - timedOut - ? "the publish acknowledgement did not arrive; the stream may already hold it" - : "the publish failed in a way this adapter does not classify; the stream may" - + " already hold the message"))); - } - - private static TransportPublishResult rejectedLocally(String code, String message) { - return new TransportPublishResult( - new PublishResult( - PublishCompletion.REJECTED, - PublishEvidence.notTransmitted(), - RoutingOutcome.NOT_APPLICABLE, - Optional.empty(), - 1, - // A local refusal: nothing was attempted, so no time was spent on the wire. - Duration.ZERO, - Optional.of(FailureDescriptor.of(FailureCategory.PERMANENT_BUSINESS, code, message)))); - } - - private static CompletionStage completed(TransportPublishResult result) { - return CompletableFuture.completedFuture(result); - } - - /** The JetStream publish, isolated so the adapter is testable without a server. */ - @FunctionalInterface - public interface JetStreamPublishOperation { - - /** - * Publishes one encoded message to JetStream. - * - * @param subject the JetStream subject - * @param deduplicationId the {@code Nats-Msg-Id} value, when deduplication is enabled - * @param request the publish request - * @return a stage completing with the stream position the message landed at - */ - CompletionStage publish( - String subject, Optional deduplicationId, TransportPublishRequest request); - } -} diff --git a/src/messaging/messaging-nats-experimental/src/main/java/dev/caskeleton/messaging/nats/NatsMaxDeliverParkingWorkflow.java b/src/messaging/messaging-nats-experimental/src/main/java/dev/caskeleton/messaging/nats/NatsMaxDeliverParkingWorkflow.java deleted file mode 100644 index d13ee0ce..00000000 --- a/src/messaging/messaging-nats-experimental/src/main/java/dev/caskeleton/messaging/nats/NatsMaxDeliverParkingWorkflow.java +++ /dev/null @@ -1,85 +0,0 @@ -package dev.caskeleton.messaging.nats; - -import java.util.Objects; - -/** - * Decides what to do with a JetStream delivery before its {@code maxDeliver} limit destroys it. - * - *

JetStream has no dead-letter queue. When a message hits {@code maxDeliver} the server - * terminates it: no redelivery, no routing, no record beyond an advisory. Every other broker in - * this platform parks a poison message somewhere an operator can find it, and this workflow is what - * makes NATS behave the same way. - * - *

The parking therefore happens on the delivery before the limit, not on the limit - * itself. Acting at {@code maxDeliver} would mean acting on the delivery JetStream is about to - * discard, so any failure in the dead-letter publish would lose the message outright — precisely - * the case the DLQ-confirm-before-settle invariant exists to prevent. - */ -public final class NatsMaxDeliverParkingWorkflow { - - /** What the platform should do with one delivery. */ - public enum Action { - /** Hand the message to the handler as normal. */ - DELIVER_TO_HANDLER, - /** Publish to the platform dead-letter destination, then terminate the source. */ - PARK_TO_DEAD_LETTER, - /** - * The message has already passed the limit and JetStream has terminated it. - * - *

Reachable only if the profile changed under a live consumer. Nothing can be recovered - * here; the outcome exists so the situation is reported rather than mistaken for a redelivery. - */ - ALREADY_TERMINATED - } - - private final NatsJetStreamProfile profile; - - /** - * Creates a workflow for one destination. - * - * @param profile the JetStream settings - */ - public NatsMaxDeliverParkingWorkflow(NatsJetStreamProfile profile) { - this.profile = Objects.requireNonNull(profile, "profile must not be null"); - } - - /** - * Decides what to do with a delivery. - * - * @param deliveryCount how many times this message has been delivered, counting this one - * @return the action to take - */ - public Action decide(long deliveryCount) { - if (deliveryCount < 1) { - throw new IllegalArgumentException("the first delivery is delivery 1"); - } - if (deliveryCount > profile.maxDeliver()) { - return Action.ALREADY_TERMINATED; - } - return deliveryCount >= profile.parkAtDelivery() - ? Action.PARK_TO_DEAD_LETTER - : Action.DELIVER_TO_HANDLER; - } - - /** - * Reports whether the source may be terminated after a dead-letter publish. - * - *

Only on a confirmed publish. Terminating first would discard the message on a broker that - * cannot redeliver it, which is the one irreversible mistake available here. - * - * @param deadLetterConfirmed whether the dead-letter publish was confirmed - * @return true when the source may be terminated - */ - public boolean maySettleSource(boolean deadLetterConfirmed) { - return deadLetterConfirmed; - } - - /** - * Returns the delivery count at which parking begins. - * - * @return the parking threshold - */ - public int parkingThreshold() { - return profile.parkAtDelivery(); - } -} diff --git a/src/messaging/messaging-nats-experimental/src/main/java/dev/caskeleton/messaging/nats/NatsPreSendRejection.java b/src/messaging/messaging-nats-experimental/src/main/java/dev/caskeleton/messaging/nats/NatsPreSendRejection.java deleted file mode 100644 index 039addc3..00000000 --- a/src/messaging/messaging-nats-experimental/src/main/java/dev/caskeleton/messaging/nats/NatsPreSendRejection.java +++ /dev/null @@ -1,65 +0,0 @@ -package dev.caskeleton.messaging.nats; - -import java.util.Objects; - -/** - * The one signal that lets this adapter report {@code REJECTED / NOT_TRANSMITTED}. - * - *

Classification used to work by reading the exception's class simple name and matching - * substrings — {@code "Timeout"} meant ambiguous, anything else meant rejected. Two things are - * wrong with that. A class name is not part of any SDK's contract: it changes between versions, and - * an unrelated exception whose name happens to contain the substring is misread. And defaulting the - * unknown case to {@code REJECTED} tells the caller nothing was transmitted, so a caller that - * republishes under a new identity duplicates a message the server may well have stored. - * - *

The publish operation throws this only when it knows the send never left the client: an - * argument the SDK refused, a connection that was already closed, a subject the client could not - * resolve. Everything else — including anything the adapter does not recognise — is ambiguous, and - * ambiguity is the honest answer when the write may have landed. - */ -public final class NatsPreSendRejection extends RuntimeException { - - private static final long serialVersionUID = 1L; - - private final String code; - - /** - * Creates a pre-send rejection. - * - * @param code the sanitised platform code for the refusal - * @param message a sanitised description - */ - public NatsPreSendRejection(String code, String message) { - super(message); - this.code = requireCode(code); - } - - /** - * Creates a pre-send rejection wrapping the SDK's own exception. - * - * @param code the sanitised platform code for the refusal - * @param message a sanitised description - * @param cause the SDK exception that proves the send never started - */ - public NatsPreSendRejection(String code, String message, Throwable cause) { - super(message, cause); - this.code = requireCode(code); - } - - private static String requireCode(String code) { - Objects.requireNonNull(code, "code must not be null"); - if (code.isBlank()) { - throw new IllegalArgumentException("code must not be blank"); - } - return code; - } - - /** - * The sanitised code reported to the caller. - * - * @return the code - */ - public String code() { - return code; - } -} diff --git a/src/messaging/messaging-nats-experimental/src/main/java/dev/caskeleton/messaging/nats/NatsStreamPosition.java b/src/messaging/messaging-nats-experimental/src/main/java/dev/caskeleton/messaging/nats/NatsStreamPosition.java deleted file mode 100644 index 7463b69f..00000000 --- a/src/messaging/messaging-nats-experimental/src/main/java/dev/caskeleton/messaging/nats/NatsStreamPosition.java +++ /dev/null @@ -1,75 +0,0 @@ -package dev.caskeleton.messaging.nats; - -import dev.caskeleton.messaging.api.publish.BrokerPosition; -import java.util.Map; -import java.util.Objects; - -/** - * A JetStream message's coordinate: its stream, its sequence in that stream, and the consumer's own - * sequence. - * - *

Two sequences, because they answer different questions. The stream sequence identifies the - * message and is what a replay seeks to. The consumer sequence counts deliveries to this - * consumer, so it advances on every redelivery while the stream sequence does not — comparing them - * is how a redelivery is recognised at all. - * - * @param stream the stream holding the message - * @param streamSequence the message's position in the stream - * @param consumerSequence how many messages this consumer has been delivered - * @param deliveryCount how many times this message has been delivered - */ -public record NatsStreamPosition( - String stream, long streamSequence, long consumerSequence, long deliveryCount) - implements BrokerPosition { - - public NatsStreamPosition { - if (stream == null || stream.isBlank()) { - throw new IllegalArgumentException("stream must not be blank"); - } - if (streamSequence < 1) { - throw new IllegalArgumentException("JetStream sequences start at 1"); - } - if (deliveryCount < 1) { - throw new IllegalArgumentException("a delivered message has been delivered at least once"); - } - } - - @Override - public String broker() { - return "nats"; - } - - @Override - public Map diagnosticAttributes() { - return Map.of( - "stream", stream, - "streamSequence", Long.toString(streamSequence), - "consumerSequence", Long.toString(consumerSequence), - "deliveryCount", Long.toString(deliveryCount)); - } - - /** - * Reports whether this delivery is a redelivery. - * - * @return true when the message has been delivered before - */ - public boolean isRedelivery() { - return deliveryCount > 1; - } - - /** - * Returns the stream sequence a replay should resume from to re-read this message. - * - * @return the resume sequence - */ - public long replayFrom() { - return streamSequence; - } - - @Override - public String toString() { - return Objects.toString( - "NatsStreamPosition[stream=%s, streamSequence=%d, deliveryCount=%d]" - .formatted(stream, streamSequence, deliveryCount)); - } -} diff --git a/src/messaging/messaging-nats-experimental/src/test/java/dev/caskeleton/messaging/nats/NatsAdapterContractTest.java b/src/messaging/messaging-nats-experimental/src/test/java/dev/caskeleton/messaging/nats/NatsAdapterContractTest.java deleted file mode 100644 index 6e9dd33e..00000000 --- a/src/messaging/messaging-nats-experimental/src/test/java/dev/caskeleton/messaging/nats/NatsAdapterContractTest.java +++ /dev/null @@ -1,337 +0,0 @@ -package dev.caskeleton.messaging.nats; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.messaging.api.ContentType; -import dev.caskeleton.messaging.api.MessageEnvelope; -import dev.caskeleton.messaging.api.MessageId; -import dev.caskeleton.messaging.api.MessageType; -import dev.caskeleton.messaging.api.ProducerId; -import dev.caskeleton.messaging.api.SchemaVersion; -import dev.caskeleton.messaging.api.TraceContext; -import dev.caskeleton.messaging.api.delivery.DeliveryGuarantee; -import dev.caskeleton.messaging.api.delivery.ExternalSideEffectGuarantee; -import dev.caskeleton.messaging.api.delivery.OrderingScope; -import dev.caskeleton.messaging.api.destination.DestinationKind; -import dev.caskeleton.messaging.api.destination.DestinationName; -import dev.caskeleton.messaging.api.error.FailureCategory; -import dev.caskeleton.messaging.api.header.MessageHeaders; -import dev.caskeleton.messaging.api.publish.ConfirmationLevel; -import dev.caskeleton.messaging.api.publish.PublishCompletion; -import dev.caskeleton.messaging.api.publish.PublishOptions; -import dev.caskeleton.messaging.api.publish.PublishResult; -import dev.caskeleton.messaging.api.publish.TransmissionEvidence; -import dev.caskeleton.messaging.policy.CapabilityTier; -import dev.caskeleton.messaging.policy.ConsumerPolicy; -import dev.caskeleton.messaging.policy.DeadLetterPolicy; -import dev.caskeleton.messaging.policy.DestinationProfile; -import dev.caskeleton.messaging.policy.PayloadPolicy; -import dev.caskeleton.messaging.policy.PhysicalDestination; -import dev.caskeleton.messaging.policy.ProducerPolicy; -import dev.caskeleton.messaging.policy.RetryPolicy; -import dev.caskeleton.messaging.policy.SchemaPolicy; -import dev.caskeleton.messaging.schema.EncodedMessage; -import dev.caskeleton.messaging.schema.SchemaCompatibility; -import dev.caskeleton.messaging.transport.TransportPublishRequest; -import dev.caskeleton.messaging.transport.TransportPublishResult; -import java.time.Duration; -import java.time.Instant; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.Set; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CompletionStage; -import java.util.concurrent.TimeoutException; -import org.junit.jupiter.api.Test; - -class NatsAdapterContractTest { - - private static final Instant NOW = Instant.parse("2026-08-10T09:15:00Z"); - private static final NatsStreamPosition POSITION = new NatsStreamPosition("ORDERS", 42, 42, 1); - - private final List> capturedDeduplicationIds = new ArrayList<>(); - - private NatsJetStreamTransport confirming(Optional deduplicationWindow) { - return new NatsJetStreamTransport( - "nats-primary", - 1, - profile(deduplicationWindow), - (subject, deduplicationId, request) -> { - capturedDeduplicationIds.add(deduplicationId); - return CompletableFuture.completedFuture(POSITION); - }); - } - - private NatsJetStreamTransport failingWith(Throwable failure) { - return new NatsJetStreamTransport( - "nats-primary", - 1, - profile(Optional.of(Duration.ofMinutes(2))), - (subject, deduplicationId, request) -> CompletableFuture.failedFuture(failure)); - } - - private static PublishResult await(CompletionStage stage) { - return stage.toCompletableFuture().join().result(); - } - - @Test - void aStoredMessageReportsPersistenceEvidence() { - PublishResult result = await(confirming(Optional.empty()).publish(request(64))); - - assertThat(result.completion()).isEqualTo(PublishCompletion.CONFIRMED); - assertThat(result.evidence().confirmationLevel()) - .as("the acknowledgement names the stream and sequence, not just bytes on a socket") - .isEqualTo(ConfirmationLevel.REPLICATION_OR_PERSISTENCE_ACK); - } - - @Test - void theStreamPositionIsCarriedBack() { - assertThat(await(confirming(Optional.empty()).publish(request(64))).position()) - .hasValue(POSITION); - } - - @Test - void aPublishTimeoutIsAmbiguousBecauseTheStreamMayHoldIt() { - PublishResult result = await(failingWith(new TimeoutException("no ack")).publish(request(64))); - - assertThat(result.completion()).isEqualTo(PublishCompletion.AMBIGUOUS); - assertThat(result.evidence().transmission()) - .isEqualTo(TransmissionEvidence.MAY_HAVE_BEEN_TRANSMITTED); - } - - @Test - void aFailureNamedLikeAKnownOneIsStillAmbiguous() { - // The class name used to be the classifier: an exception whose simple name contained - // "NoRespond" was reported REJECTED / NOT_TRANSMITTED. A name is not an SDK contract, and a - // caller that reads NOT_TRANSMITTED republishes under a new identity. - PublishResult result = - await(failingWith(new IllegalStateException("NoRespondersException")).publish(request(64))); - - assertThat(result.completion()).isEqualTo(PublishCompletion.AMBIGUOUS); - assertThat(result.failure()) - .hasValueSatisfying( - failure -> assertThat(failure.code()).isEqualTo("NATS_PUBLISH_OUTCOME_UNKNOWN")); - } - - @Test - void onlyATypedPreSendRejectionReportsNothingTransmitted() { - PublishResult result = - await( - failingWith( - new NatsPreSendRejection( - "NATS_CONNECTION_CLOSED", "the client was closed before the send")) - .publish(request(64))); - - assertThat(result.completion()).isEqualTo(PublishCompletion.REJECTED); - assertThat(result.evidence().transmission()) - .isEqualTo(dev.caskeleton.messaging.api.publish.TransmissionEvidence.NOT_TRANSMITTED); - assertThat(result.failure()) - .hasValueSatisfying( - failure -> assertThat(failure.code()).isEqualTo("NATS_CONNECTION_CLOSED")); - } - - @Test - void aWrappedUnknownFailureIsAmbiguousRatherThanRejected() { - PublishResult result = - await( - failingWith( - new java.util.concurrent.CompletionException( - new RuntimeException("something the adapter has never seen"))) - .publish(request(64))); - - assertThat(result.completion()).isEqualTo(PublishCompletion.AMBIGUOUS); - } - - @Test - void aPublishThatNeverCompletesIsBoundedByTheCallersTimeout() { - try (NatsJetStreamTransport transport = - new NatsJetStreamTransport( - "nats-primary", - 1L, - profile(Optional.empty()), - (subject, deduplicationId, request) -> - new java.util.concurrent.CompletableFuture<>())) { - - PublishResult result = await(transport.publish(requestWithTimeout(Duration.ofMillis(50)))); - - assertThat(result.completion()) - .as("the caller's deadline used to be ignored entirely") - .isEqualTo(PublishCompletion.AMBIGUOUS); - assertThat(result.failure()) - .hasValueSatisfying( - failure -> assertThat(failure.code()).isEqualTo("NATS_PUBLISH_TIMEOUT")); - } - } - - @Test - void theReportedElapsedTimeIsMeasuredRatherThanZero() { - PublishResult result = - await( - failingWith(new java.util.concurrent.TimeoutException("no ack")).publish(request(64))); - - assertThat(result.elapsed()) - .as("every outcome reported Duration.ZERO, so latency evidence was fiction") - .isGreaterThanOrEqualTo(Duration.ZERO); - } - - @Test - void aDeduplicationWindowSendsTheLogicalMessageIdSoARetryIsRecognised() { - confirming(Optional.of(Duration.ofMinutes(2))) - .publish(request(64)) - .toCompletableFuture() - .join(); - - assertThat(capturedDeduplicationIds) - .as("a fresh id per attempt would make the window useless exactly when it is needed") - .singleElement() - .satisfies(id -> assertThat(id).isPresent()); - } - - @Test - void noDeduplicationWindowSendsNoDeduplicationId() { - confirming(Optional.empty()).publish(request(64)).toCompletableFuture().join(); - - assertThat(capturedDeduplicationIds).singleElement().satisfies(id -> assertThat(id).isEmpty()); - } - - @Test - void anOversizedPayloadIsRejectedBeforeTheStream() { - PublishResult result = - await(confirming(Optional.empty()).publish(request(PayloadPolicy.DEFAULT_MAX_BYTES + 1))); - - assertThat(result.completion()).isEqualTo(PublishCompletion.REJECTED); - assertThat(result.evidence().transmission()).isEqualTo(TransmissionEvidence.NOT_TRANSMITTED); - } - - @Test - void theAdapterDoesNotClaimANativeDeadLetter() { - assertThat( - confirming(Optional.empty()) - .capabilities(new DestinationName("orders.v1")) - .capabilities() - .nativeDeadLetter()) - .as("JetStream terminates at the delivery limit; it routes nowhere") - .isFalse(); - } - - @Test - void theAdapterAdvertisesDeduplicatedPublish() { - assertThat( - confirming(Optional.empty()) - .capabilities(new DestinationName("orders.v1")) - .capabilities() - .deduplicatedPublish()) - .isTrue(); - } - - @Test - void aClosedTransportStopsAcceptingWork() { - NatsJetStreamTransport transport = confirming(Optional.empty()); - transport.close(); - - assertThat(transport.isAcceptingWork()).isFalse(); - assertThat(await(transport.publish(request(64))).completion()) - .isEqualTo(PublishCompletion.REJECTED); - } - - @Test - void aRedeliveryIsRecognisedFromTheDeliveryCountNotTheSequence() { - NatsStreamPosition redelivered = new NatsStreamPosition("ORDERS", 42, 43, 2); - - assertThat(POSITION.isRedelivery()).isFalse(); - assertThat(redelivered.isRedelivery()).isTrue(); - assertThat(redelivered.replayFrom()) - .as("the stream sequence does not advance on a redelivery; the consumer sequence does") - .isEqualTo(POSITION.replayFrom()); - } - - @Test - void aSequenceBelowOneIsRejectedBecauseJetStreamCountsFromOne() { - assertThatThrownBy(() -> new NatsStreamPosition("ORDERS", 0, 1, 1)) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void aFailureCategoryIsAlwaysAttachedToAFailure() { - PublishResult result = - await(failingWith(new IllegalStateException("boom")).publish(request(64))); - - assertThat(result.failure()) - .hasValueSatisfying( - failure -> - assertThat(failure.category()) - .as("an unclassified failure is transient, not a permanent business rejection") - .isEqualTo(FailureCategory.TRANSIENT_INFRASTRUCTURE)); - } - - private static NatsJetStreamProfile profile(Optional deduplicationWindow) { - return new NatsJetStreamProfile( - "orders.created", - "ORDERS", - "orders-worker", - NatsAckMode.EXPLICIT, - Duration.ofSeconds(30), - 5, - deduplicationWindow); - } - - private static TransportPublishRequest request(int payloadBytes) { - return new TransportPublishRequest( - destinationProfile(), envelope(payloadBytes), PublishOptions.defaults()); - } - - private static TransportPublishRequest requestWithTimeout(Duration timeout) { - PublishOptions defaults = PublishOptions.defaults(); - return new TransportPublishRequest( - destinationProfile(), - envelope(64), - new PublishOptions(timeout, defaults.confirmation(), defaults.deduplication())); - } - - private static DestinationProfile destinationProfile() { - return new DestinationProfile( - new DestinationName("orders.v1"), - "nats-primary", - DestinationKind.EVENT_STREAM, - PhysicalDestination.natsStream("orders.created", "ORDERS"), - new SchemaPolicy( - ContentType.JSON, - SchemaCompatibility.BACKWARD, - Set.of(new MessageType("order.created"))), - DeliveryGuarantee.AT_LEAST_ONCE, - OrderingScope.NONE, - ExternalSideEffectGuarantee.IDEMPOTENCY_REQUIRED, - ProducerPolicy.defaults(), - ConsumerPolicy.defaults("orders"), - RetryPolicy.none(), - DeadLetterPolicy.to(new DestinationName("orders.v1.dlq")), - PayloadPolicy.defaults(), - CapabilityTier.M1, - false, - false, - false); - } - - private static MessageEnvelope envelope(int payloadBytes) { - byte[] payload = new byte[payloadBytes]; - java.util.Arrays.fill(payload, (byte) 'x'); - return new MessageEnvelope<>( - MessageId.newId(), - new MessageType("order.created"), - new SchemaVersion(1), - NOW, - Optional.of(NOW), - new ProducerId("order-api"), - Optional.empty(), - Optional.empty(), - ContentType.JSON, - Optional.empty(), - Optional.empty(), - Optional.empty(), - TraceContext.none(), - MessageHeaders.empty(), - new EncodedMessage(payload, ContentType.JSON, Optional.empty())); - } -} diff --git a/src/messaging/messaging-nats-experimental/src/test/java/dev/caskeleton/messaging/nats/NatsMaxDeliverParkingTest.java b/src/messaging/messaging-nats-experimental/src/test/java/dev/caskeleton/messaging/nats/NatsMaxDeliverParkingTest.java deleted file mode 100644 index 93d0a0c0..00000000 --- a/src/messaging/messaging-nats-experimental/src/test/java/dev/caskeleton/messaging/nats/NatsMaxDeliverParkingTest.java +++ /dev/null @@ -1,123 +0,0 @@ -package dev.caskeleton.messaging.nats; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.messaging.nats.NatsMaxDeliverParkingWorkflow.Action; -import java.time.Duration; -import java.util.Optional; -import org.junit.jupiter.api.Test; - -class NatsMaxDeliverParkingTest { - - private static NatsJetStreamProfile profile(int maxDeliver) { - return new NatsJetStreamProfile( - "orders.created", - "ORDERS", - "orders-worker", - NatsAckMode.EXPLICIT, - Duration.ofSeconds(30), - maxDeliver, - Optional.of(Duration.ofMinutes(2))); - } - - private static NatsMaxDeliverParkingWorkflow workflow(int maxDeliver) { - return new NatsMaxDeliverParkingWorkflow(profile(maxDeliver)); - } - - @Test - void earlyDeliveriesGoToTheHandler() { - NatsMaxDeliverParkingWorkflow workflow = workflow(5); - - assertThat(workflow.decide(1)).isEqualTo(Action.DELIVER_TO_HANDLER); - assertThat(workflow.decide(3)).isEqualTo(Action.DELIVER_TO_HANDLER); - } - - @Test - void parkingHappensBeforeTheLimitNotAtIt() { - NatsMaxDeliverParkingWorkflow workflow = workflow(5); - - assertThat(workflow.decide(4)) - .as("the delivery that reaches maxDeliver is the one JetStream discards") - .isEqualTo(Action.PARK_TO_DEAD_LETTER); - } - - @Test - void theLimitDeliveryItselfStillParksRatherThanBeingHandled() { - assertThat(workflow(5).decide(5)).isEqualTo(Action.PARK_TO_DEAD_LETTER); - } - - @Test - void aDeliveryPastTheLimitIsReportedRatherThanMistakenForARedelivery() { - assertThat(workflow(5).decide(6)) - .as("only reachable if the profile changed under a live consumer; nothing is recoverable") - .isEqualTo(Action.ALREADY_TERMINATED); - } - - @Test - void theSourceIsOnlyTerminatedAfterTheDeadLetterPublishConfirms() { - NatsMaxDeliverParkingWorkflow workflow = workflow(5); - - assertThat(workflow.maySettleSource(true)).isTrue(); - assertThat(workflow.maySettleSource(false)) - .as("terminating first discards the message on a broker that cannot redeliver it") - .isFalse(); - } - - @Test - void aProfileWithNoParkingHeadroomIsRefused() { - assertThatThrownBy(() -> profile(1)) - .as("maxDeliver=1 leaves no delivery on which the platform could park the message") - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("headroom"); - } - - @Test - void aDeliveryCountBelowOneIsRejected() { - assertThatThrownBy(() -> workflow(5).decide(0)).isInstanceOf(IllegalArgumentException.class); - } - - @Test - void theParkingThresholdIsOneBelowTheLimit() { - assertThat(workflow(7).parkingThreshold()).isEqualTo(6); - } - - @Test - void ackNoneIsRefusedBecauseDeliveryIsTreatedAsCompletion() { - assertThatThrownBy( - () -> - new NatsJetStreamProfile( - "orders.created", - "ORDERS", - "orders-worker", - NatsAckMode.NONE, - Duration.ofSeconds(30), - 5, - Optional.empty())) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("forgotten"); - } - - @Test - void ackAllIsRefusedBecauseItSettlesWorkStillInFlight() { - assertThatThrownBy( - () -> - new NatsJetStreamProfile( - "orders.created", - "ORDERS", - "orders-worker", - NatsAckMode.ALL, - Duration.ofSeconds(30), - 5, - Optional.empty())) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("still in flight"); - } - - @Test - void onlyExplicitAcknowledgementCarriesAtLeastOnce() { - assertThat(NatsAckMode.EXPLICIT.supportsAtLeastOnce()).isTrue(); - assertThat(NatsAckMode.ALL.supportsAtLeastOnce()).isFalse(); - assertThat(NatsAckMode.NONE.supportsAtLeastOnce()).isFalse(); - } -} diff --git a/src/messaging/messaging-outbox-jdbc-postgresql/build.gradle b/src/messaging/messaging-outbox-jdbc-postgresql/build.gradle index 36beb142..c933afeb 100644 --- a/src/messaging/messaging-outbox-jdbc-postgresql/build.gradle +++ b/src/messaging/messaging-outbox-jdbc-postgresql/build.gradle @@ -26,6 +26,9 @@ dependencies { // Live-database certification. The reliability patterns are claims about transaction // boundaries and uniqueness constraints, and only a real database can settle them. testImplementation project(':messaging:messaging-testkit') + // Test-only. The relay is also driven through the real DefaultMessagePublisher: a fake publisher + // accepted the pre-encoded rows the real one re-encoded and rejected. + testImplementation project(':messaging:messaging-runtime-core') integrationTestImplementation 'org.testcontainers:testcontainers-postgresql' integrationTestImplementation 'org.testcontainers:testcontainers-junit-jupiter' integrationTestImplementation 'org.postgresql:postgresql' diff --git a/src/messaging/messaging-outbox-jdbc-postgresql/src/integrationTest/java/dev/caskeleton/messaging/outbox/OutboxPostgresIT.java b/src/messaging/messaging-outbox-jdbc-postgresql/src/integrationTest/java/dev/caskeleton/messaging/outbox/OutboxPostgresIT.java index 992ad2f3..0e2d8705 100644 --- a/src/messaging/messaging-outbox-jdbc-postgresql/src/integrationTest/java/dev/caskeleton/messaging/outbox/OutboxPostgresIT.java +++ b/src/messaging/messaging-outbox-jdbc-postgresql/src/integrationTest/java/dev/caskeleton/messaging/outbox/OutboxPostgresIT.java @@ -506,22 +506,16 @@ class OutboxPostgresIT { } @Test - void theStoredRoutingKeyIsTheOneBothRelaysWouldUse() { + void theStoredRoutingKeyFallsBackToTheMessageId() { OutboxRecord keyed = record(OutboxCanonicalMetadata.none().withRoutingKeys("customer-42", "customer-42")); OutboxRecord unkeyed = record(OutboxCanonicalMetadata.none()); appendInTransaction(keyed); appendInTransaction(unkeyed); - DebeziumOutboxEventRouter router = new DebeziumOutboxEventRouter(); - assertThat(routingKeyOf(keyed.messageId())) - .as("the CDC key used to be the destination, so every message on a topic shared a key") - .isEqualTo(router.routingKey(keyed)) - .isEqualTo("customer-42"); - assertThat(routingKeyOf(unkeyed.messageId())) - .as("the fallback is stated once, in the column, and the Java agrees with it") - .isEqualTo(router.routingKey(unkeyed)) - .isEqualTo(unkeyed.messageId().value().toString()); + assertThat(List.of(routingKeyOf(keyed.messageId()), routingKeyOf(unkeyed.messageId()))) + .as("the fallback is stated once, in the column") + .containsExactly("customer-42", unkeyed.messageId().value().toString()); } @Test diff --git a/src/messaging/messaging-outbox-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/outbox/DebeziumMappedRecord.java b/src/messaging/messaging-outbox-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/outbox/DebeziumMappedRecord.java deleted file mode 100644 index cd534197..00000000 --- a/src/messaging/messaging-outbox-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/outbox/DebeziumMappedRecord.java +++ /dev/null @@ -1,54 +0,0 @@ -package dev.caskeleton.messaging.outbox; - -import java.util.Arrays; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -/** - * What one outbox row looks like after Debezium's Event Router has transformed it. - * - *

Modelled explicitly so the CDC path can be tested without running Debezium. The property that - * matters is not that the transform is invoked but that its output carries the same identity, - * destination, and reserved headers the polling relay would have produced — and that is asserted by - * comparing this record against one built from the same row. - * - * @param topic the topic the row was routed to - * @param key the broker partition key, absent when the row is unkeyed - * @param payload the encoded payload - * @param headers the reserved headers carried alongside - */ -@SuppressWarnings("ArrayRecordComponent") -public record DebeziumMappedRecord( - String topic, Optional key, byte[] payload, Map headers) { - - public DebeziumMappedRecord { - Objects.requireNonNull(key, "key must not be null"); - Objects.requireNonNull(payload, "payload must not be null"); - Objects.requireNonNull(headers, "headers must not be null"); - if (topic == null || topic.isBlank()) { - throw new IllegalArgumentException("topic must not be blank"); - } - payload = payload.clone(); - headers = Map.copyOf(headers); - } - - @Override - public byte[] payload() { - return payload.clone(); - } - - @Override - public boolean equals(Object other) { - return other instanceof DebeziumMappedRecord record - && topic.equals(record.topic) - && key.equals(record.key) - && headers.equals(record.headers) - && Arrays.equals(payload, record.payload); - } - - @Override - public int hashCode() { - return Objects.hash(topic, key, headers, Arrays.hashCode(payload)); - } -} diff --git a/src/messaging/messaging-outbox-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/outbox/DebeziumOutboxEventRouter.java b/src/messaging/messaging-outbox-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/outbox/DebeziumOutboxEventRouter.java deleted file mode 100644 index dbb64a83..00000000 --- a/src/messaging/messaging-outbox-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/outbox/DebeziumOutboxEventRouter.java +++ /dev/null @@ -1,151 +0,0 @@ -package dev.caskeleton.messaging.outbox; - -import dev.caskeleton.messaging.api.header.ReservedHeaders; -import dev.caskeleton.messaging.reliability.OutboxCanonicalMetadata; -import dev.caskeleton.messaging.reliability.OutboxRecord; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Objects; - -/** - * Maps outbox columns onto the headers Debezium's Outbox Event Router expects. - * - *

An optional alternative to the polling relay. CDC reads the database's write-ahead log instead - * of querying the table, which removes the polling interval and the lease contention — at the cost - * of an extra piece of infrastructure and its own failure modes. - * - *

The platform contract does not change with the transport. The router emits the same reserved - * headers the polling relay does, so a consumer cannot tell which one published a message, and - * switching between them is a deployment decision rather than a contract change. - * - *

The message key and the topic are two different questions and used to be answered by one - * column. {@code destination} routed the topic and became the key, so every message on a - * topic carried the same key, landed on one partition, and made keyed ordering a claim with no - * mechanism behind it. The key now comes from {@code routing_key}, the stored column that states - * the partition-key-or-message-id fallback once for both relays, and {@code destination} stays what - * it always was: routing metadata. - * - *

One canonical field has no header here: the schema subject. There is no reserved header name - * for it, and inventing one that only this path wrote would replace a symmetric gap with an - * asymmetric one — the polling relay would carry a schema reference on the envelope and the CDC - * relay a header no adapter reads. It stays a column that the polling relay resolves, and closing - * it means adding the name to {@code ReservedHeaders} and teaching both broker header mappers to - * write and read it. - */ -public final class DebeziumOutboxEventRouter { - - /** The outbox column Debezium routes the topic by. */ - public static final String ROUTE_BY_COLUMN = "destination"; - - /** The outbox column Debezium uses as the message key. */ - public static final String KEY_COLUMN = "routing_key"; - - /** The outbox column carrying the logical message id. */ - public static final String ID_COLUMN = "message_id"; - - /** The outbox column carrying the payload. */ - public static final String PAYLOAD_COLUMN = "payload"; - - /** - * Returns the router configuration for a Debezium connector. - * - * @param topicPrefix the prefix routed topics are created under - * @return the connector properties - */ - public Map connectorConfiguration(String topicPrefix) { - Objects.requireNonNull(topicPrefix, "topicPrefix must not be null"); - Map configuration = new LinkedHashMap<>(); - configuration.put("transforms.outbox.type", "io.debezium.transforms.outbox.EventRouter"); - configuration.put("transforms.outbox.table.field.event.id", ID_COLUMN); - configuration.put("transforms.outbox.table.field.event.key", KEY_COLUMN); - configuration.put("transforms.outbox.table.field.event.payload", PAYLOAD_COLUMN); - configuration.put("transforms.outbox.route.by.field", ROUTE_BY_COLUMN); - configuration.put( - "transforms.outbox.route.topic.replacement", topicPrefix + "${routedByValue}"); - configuration.put( - "transforms.outbox.table.fields.additional.placement", - String.join( - ",", - "message_type:header:" + ReservedHeaders.MESSAGE_TYPE, - "schema_version:header:" + ReservedHeaders.SCHEMA_VERSION, - "content_type:header:" + ReservedHeaders.CONTENT_TYPE, - "created_at:header:" + ReservedHeaders.PRODUCED_AT, - "destination:header:" + ReservedHeaders.ORIGIN_DESTINATION, - "producer:header:" + ReservedHeaders.PRODUCER, - "occurred_at:header:" + ReservedHeaders.OCCURRED_AT, - "correlation_id:header:" + ReservedHeaders.CORRELATION_ID, - "causation_id:header:" + ReservedHeaders.CAUSATION_ID, - "tenant:header:" + ReservedHeaders.TENANT, - "partition_key:header:" + ReservedHeaders.PARTITION_KEY, - "ordering_key:header:" + ReservedHeaders.ORDERING_KEY, - "traceparent:header:" + ReservedHeaders.TRACEPARENT, - "tracestate:header:" + ReservedHeaders.TRACESTATE, - "baggage:header:" + ReservedHeaders.BAGGAGE)); - return Map.copyOf(configuration); - } - - /** - * Returns the reserved headers a routed record must carry. - * - *

Used to assert that the CDC path and the polling path produce the same wire contract. - * - * @param record the outbox row - * @return the reserved headers - */ - public Map reservedHeaders(OutboxRecord record) { - Objects.requireNonNull(record, "record must not be null"); - Map headers = new LinkedHashMap<>(); - headers.put(ReservedHeaders.MESSAGE_ID, record.messageId().value().toString()); - headers.put(ReservedHeaders.MESSAGE_TYPE, record.messageType().value()); - headers.put(ReservedHeaders.SCHEMA_VERSION, Integer.toString(record.schemaVersion().value())); - headers.put(ReservedHeaders.CONTENT_TYPE, record.contentType().value()); - headers.put(ReservedHeaders.PRODUCED_AT, record.createdAt().toString()); - headers.put(ReservedHeaders.ORIGIN_DESTINATION, record.destination().value()); - - // Absent stays absent. Writing an empty string for a column the row does not have would make a - // message that carries no tenant indistinguishable from one whose tenant is the empty string, - // and the consumer would have to know which of the two this platform meant. - OutboxCanonicalMetadata metadata = record.metadata(); - metadata.producer().ifPresent(value -> headers.put(ReservedHeaders.PRODUCER, value.value())); - metadata - .occurredAt() - .ifPresent(value -> headers.put(ReservedHeaders.OCCURRED_AT, value.toString())); - metadata - .correlationId() - .ifPresent(value -> headers.put(ReservedHeaders.CORRELATION_ID, value.value())); - metadata - .causationId() - .ifPresent( - value -> headers.put(ReservedHeaders.CAUSATION_ID, value.value().value().toString())); - metadata.tenant().ifPresent(value -> headers.put(ReservedHeaders.TENANT, value.tenantId())); - metadata.partitionKey().ifPresent(value -> headers.put(ReservedHeaders.PARTITION_KEY, value)); - metadata.orderingKey().ifPresent(value -> headers.put(ReservedHeaders.ORDERING_KEY, value)); - metadata - .traceContext() - .traceparent() - .ifPresent(value -> headers.put(ReservedHeaders.TRACEPARENT, value)); - metadata - .traceContext() - .tracestate() - .ifPresent(value -> headers.put(ReservedHeaders.TRACESTATE, value)); - metadata - .traceContext() - .baggage() - .ifPresent(value -> headers.put(ReservedHeaders.BAGGAGE, value)); - return Map.copyOf(headers); - } - - /** - * Returns the key a routed record carries. - * - *

The same value the {@code routing_key} column computes, stated here so a test can compare - * the two rather than trusting that the SQL and the Java agree. - * - * @param record the outbox row - * @return the broker message key - */ - public String routingKey(OutboxRecord record) { - Objects.requireNonNull(record, "record must not be null"); - return record.metadata().partitionKey().orElseGet(() -> record.messageId().value().toString()); - } -} diff --git a/src/messaging/messaging-outbox-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/outbox/DebeziumOutboxProfile.java b/src/messaging/messaging-outbox-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/outbox/DebeziumOutboxProfile.java deleted file mode 100644 index 4c085727..00000000 --- a/src/messaging/messaging-outbox-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/outbox/DebeziumOutboxProfile.java +++ /dev/null @@ -1,67 +0,0 @@ -package dev.caskeleton.messaging.outbox; - -import dev.caskeleton.messaging.api.error.MessagingConfigurationException; -import java.util.Objects; - -/** - * Which relay a deployment uses, and the rule that only one of them may be active. - * - *

Running the polling relay and the CDC relay together publishes every row twice. Both are - * correct in isolation and neither can see the other: the poller leases and marks rows, while - * Debezium reads the write-ahead log and never observes the lease at all. The duplicate is - * therefore invisible in the outbox table and only shows up downstream, which is why the - * incompatibility is enforced at startup instead of documented. - * - * @param mode which relay publishes outbox rows - * @param topicPrefix the prefix CDC-routed topics are created under - * @param aggregateIdAsPartitionKey whether the aggregate id becomes the broker partition key - */ -public record DebeziumOutboxProfile( - RelayMode mode, String topicPrefix, boolean aggregateIdAsPartitionKey) { - - /** How outbox rows reach the broker. */ - public enum RelayMode { - /** The in-process relay leases and publishes rows. */ - POLLING, - /** Debezium reads the write-ahead log and routes rows. */ - CHANGE_DATA_CAPTURE - } - - public DebeziumOutboxProfile { - Objects.requireNonNull(mode, "mode must not be null"); - Objects.requireNonNull(topicPrefix, "topicPrefix must not be null"); - if (mode == RelayMode.CHANGE_DATA_CAPTURE && topicPrefix.isBlank()) { - throw new IllegalArgumentException("a CDC profile must name a topic prefix"); - } - } - - /** - * Returns the default polling profile. - * - * @return the polling profile - */ - public static DebeziumOutboxProfile polling() { - return new DebeziumOutboxProfile(RelayMode.POLLING, "", false); - } - - /** - * Refuses a configuration that would run both relays at once. - * - * @param pollingRelayEnabled whether the in-process relay bean is active - * @throws MessagingConfigurationException when both relays would run - */ - public void requireExactlyOneRelay(boolean pollingRelayEnabled) { - if (mode == RelayMode.CHANGE_DATA_CAPTURE && pollingRelayEnabled) { - throw new MessagingConfigurationException( - "DUPLICATE_OUTBOX_RELAY", - "the CDC relay and the polling relay are both enabled; Debezium never observes the " - + "polling lease, so every row would be published twice"); - } - if (mode == RelayMode.POLLING && !pollingRelayEnabled) { - throw new MessagingConfigurationException( - "NO_OUTBOX_RELAY", - "the profile selects the polling relay but no relay is enabled, so outbox rows would " - + "accumulate without ever being published"); - } - } -} diff --git a/src/messaging/messaging-outbox-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/outbox/DebeziumOutboxRecordMapper.java b/src/messaging/messaging-outbox-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/outbox/DebeziumOutboxRecordMapper.java deleted file mode 100644 index 513f246a..00000000 --- a/src/messaging/messaging-outbox-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/outbox/DebeziumOutboxRecordMapper.java +++ /dev/null @@ -1,79 +0,0 @@ -package dev.caskeleton.messaging.outbox; - -import dev.caskeleton.messaging.api.header.ReservedHeaders; -import dev.caskeleton.messaging.reliability.OutboxRecord; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -/** - * Produces what Debezium's Event Router will emit for an outbox row. - * - *

Exists so the CDC path is testable without Debezium running. The property worth proving is - * that a consumer cannot tell which relay published a message: same logical id, same destination, - * same reserved headers. Building the expected record here and comparing it against the polling - * relay's output is what makes "switching relays is a deployment decision, not a contract change" - * an assertion rather than a claim. - * - *

The message id comes from the row's {@code message_id} column, never from Debezium's own event - * id. Debezium mints a fresh event id per change record, so using it would break identity across a - * CDC re-snapshot — exactly the scenario where identity matters most. - * - *

The reserved headers come from {@link DebeziumOutboxEventRouter} rather than being rebuilt - * here. Two lists of the same headers is how the connector's configuration and the expectation this - * class encodes come to disagree, and the disagreement would be invisible: the test compares this - * output against the polling relay's, so it would pass while the connector emitted something else. - */ -public final class DebeziumOutboxRecordMapper { - - private final String topicPrefix; - private final boolean aggregateIdAsPartitionKey; - private final DebeziumOutboxEventRouter router = new DebeziumOutboxEventRouter(); - - /** - * Creates a mapper from a CDC profile. - * - * @param profile the outbox relay profile - */ - public DebeziumOutboxRecordMapper(DebeziumOutboxProfile profile) { - Objects.requireNonNull(profile, "profile must not be null"); - this.topicPrefix = profile.topicPrefix(); - this.aggregateIdAsPartitionKey = profile.aggregateIdAsPartitionKey(); - } - - /** - * Maps one outbox row to its routed record. - * - * @param record the outbox row - * @return the record a CDC relay would emit - */ - public DebeziumMappedRecord map(OutboxRecord record) { - Objects.requireNonNull(record, "record must not be null"); - - // Application headers first, canonical headers second, and the canonical ones win. The row's - // header map is application data; a row that wrote `msg.id` into it would otherwise overwrite - // the identity the platform put there, and the consumer trusts the last such header it sees. - // The write path refuses reserved names outright — this order is the second lock on the same - // door, because a CDC connector reading the table directly never passes through that check. - Map headers = new LinkedHashMap<>(record.headers()); - headers.keySet().removeIf(ReservedHeaders::isReserved); - headers.putAll(router.reservedHeaders(record)); - - return new DebeziumMappedRecord( - topicPrefix + record.destination().value(), - partitionKey(record), - record.payload(), - headers); - } - - private Optional partitionKey(OutboxRecord record) { - if (!aggregateIdAsPartitionKey) { - return Optional.empty(); - } - // The same value the polling relay would use and the same value the `routing_key` column - // computes, so both relays land the same message on the same partition and neither reorders a - // keyed stream. - return Optional.of(router.routingKey(record)); - } -} diff --git a/src/messaging/messaging-outbox-jdbc-postgresql/src/main/resources/debezium/outbox-event-router.properties b/src/messaging/messaging-outbox-jdbc-postgresql/src/main/resources/debezium/outbox-event-router.properties deleted file mode 100644 index b28a254f..00000000 --- a/src/messaging/messaging-outbox-jdbc-postgresql/src/main/resources/debezium/outbox-event-router.properties +++ /dev/null @@ -1,43 +0,0 @@ -# Debezium Outbox Event Router configuration for the messaging_outbox table. -# -# Optional. Enable this OR the in-process polling relay, never both: Debezium reads the -# write-ahead log and never observes the polling lease, so with both running every row is -# published twice and the duplicate is invisible in the outbox table itself. -# -# Operating the Debezium connector — its offsets, its snapshots, its slot — is out of scope for -# this module. What is in scope is that a message routed by CDC is indistinguishable from one -# published by the polling relay: same logical id, same destination, same reserved headers. - -name=messaging-outbox-connector -connector.class=io.debezium.connector.postgresql.PostgresConnector - -# Only the outbox table. A wider include list turns every business table change into a message. -table.include.list=public.messaging_outbox - -# The row is deleted or marked after routing; the tombstone would otherwise reach the topic as a -# null-payload record that consumers must special-case. -tombstones.on.delete=false - -transforms=outbox -transforms.outbox.type=io.debezium.transforms.outbox.EventRouter - -# Identity comes from the row's own message_id, not from Debezium's per-change event id. A CDC -# re-snapshot mints new event ids for rows that already published, which would break identity in -# exactly the situation where it matters most. -transforms.outbox.table.field.event.id=message_id -transforms.outbox.table.field.event.key=destination -transforms.outbox.table.field.event.payload=payload -transforms.outbox.table.field.event.timestamp=created_at - -transforms.outbox.route.by.field=destination -transforms.outbox.route.topic.replacement=${routedByValue} - -# The reserved headers a consumer relies on, carried through the transform so the CDC path emits -# the same envelope the polling relay does. -transforms.outbox.table.fields.additional.placement=message_type:header:msg.type,schema_version:header:msg.schema-version,content_type:header:msg.content-type,message_id:header:msg.id - -# Publisher idempotence and full acknowledgement: a CDC relay that loses a record cannot replay it -# without re-reading the log from an earlier offset, which would republish everything after it. -producer.override.enable.idempotence=true -producer.override.acks=all -producer.override.max.in.flight.requests.per.connection=5 diff --git a/src/messaging/messaging-outbox-jdbc-postgresql/src/test/java/dev/caskeleton/messaging/outbox/DebeziumOutboxRecordMapperTest.java b/src/messaging/messaging-outbox-jdbc-postgresql/src/test/java/dev/caskeleton/messaging/outbox/DebeziumOutboxRecordMapperTest.java deleted file mode 100644 index e49e162c..00000000 --- a/src/messaging/messaging-outbox-jdbc-postgresql/src/test/java/dev/caskeleton/messaging/outbox/DebeziumOutboxRecordMapperTest.java +++ /dev/null @@ -1,199 +0,0 @@ -package dev.caskeleton.messaging.outbox; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.messaging.api.ContentType; -import dev.caskeleton.messaging.api.MessageId; -import dev.caskeleton.messaging.api.MessageType; -import dev.caskeleton.messaging.api.SchemaVersion; -import dev.caskeleton.messaging.api.destination.DestinationName; -import dev.caskeleton.messaging.api.error.MessagingConfigurationException; -import dev.caskeleton.messaging.api.header.ReservedHeaders; -import dev.caskeleton.messaging.outbox.DebeziumOutboxProfile.RelayMode; -import dev.caskeleton.messaging.reliability.OutboxCanonicalMetadata; -import dev.caskeleton.messaging.reliability.OutboxRecord; -import dev.caskeleton.messaging.reliability.OutboxStatus; -import java.nio.charset.StandardCharsets; -import java.time.Instant; -import java.util.Map; -import java.util.Optional; -import org.junit.jupiter.api.Test; - -class DebeziumOutboxRecordMapperTest { - - private static final Instant NOW = Instant.parse("2026-08-10T09:15:00Z"); - private static final MessageId MESSAGE_ID = MessageId.newId(); - - private static OutboxRecord record(Map headers) { - return record(headers, OutboxCanonicalMetadata.none()); - } - - private static OutboxRecord record( - Map headers, OutboxCanonicalMetadata metadata) { - return new OutboxRecord( - MESSAGE_ID, - new DestinationName("orders.v1"), - new MessageType("order.created"), - new SchemaVersion(1), - ContentType.JSON, - "{\"orderId\":\"o-1\"}".getBytes(StandardCharsets.UTF_8), - headers, - metadata, - NOW, - OutboxStatus.PENDING, - 0, - Optional.empty(), - Optional.empty()); - } - - private static DebeziumOutboxRecordMapper mapper(boolean aggregateIdAsPartitionKey) { - return new DebeziumOutboxRecordMapper( - new DebeziumOutboxProfile( - RelayMode.CHANGE_DATA_CAPTURE, "prod.", aggregateIdAsPartitionKey)); - } - - @Test - void theRoutedTopicIsThePrefixedDestination() { - assertThat(mapper(false).map(record(Map.of())).topic()).isEqualTo("prod.orders.v1"); - } - - @Test - void theLogicalMessageIdSurvivesTheCdcPath() { - DebeziumMappedRecord mapped = mapper(false).map(record(Map.of())); - - assertThat(mapped.headers().get(ReservedHeaders.MESSAGE_ID)) - .as("Debezium mints a fresh event id per change record; using it would break identity") - .isEqualTo(MESSAGE_ID.value().toString()); - } - - @Test - void everyReservedHeaderAConsumerNeedsIsCarried() { - Map headers = mapper(false).map(record(Map.of())).headers(); - - assertThat(headers) - .containsKeys( - ReservedHeaders.MESSAGE_ID, - ReservedHeaders.MESSAGE_TYPE, - ReservedHeaders.SCHEMA_VERSION, - ReservedHeaders.CONTENT_TYPE, - ReservedHeaders.PRODUCED_AT); - } - - @Test - void applicationHeadersOnTheRowArePreserved() { - DebeziumMappedRecord mapped = mapper(false).map(record(Map.of("x-tenant-tier", "gold"))); - - assertThat(mapped.headers()).containsEntry("x-tenant-tier", "gold"); - } - - @Test - void anUnkeyedProfileEmitsNoPartitionKey() { - assertThat(mapper(false).map(record(Map.of())).key()).isEmpty(); - } - - @Test - void aKeyedProfileUsesTheSamePartitionKeyThePollingRelayWouldHave() { - DebeziumMappedRecord mapped = - mapper(true) - .map( - record( - Map.of(), - OutboxCanonicalMetadata.none().withRoutingKeys("customer-42", "customer-42"))); - - assertThat(mapped.key()) - .as("a different key would send the two relays' messages to different partitions") - .hasValue("customer-42"); - } - - @Test - void aKeyedProfileFallsBackToTheMessageIdWhenTheRowHasNoPartitionKey() { - assertThat(mapper(true).map(record(Map.of())).key()) - .as("the fallback the routing_key column computes, stated in one place for both relays") - .hasValue(MESSAGE_ID.value().toString()); - } - - @Test - void theCanonicalColumnsBecomeReservedHeaders() { - OutboxCanonicalMetadata metadata = - OutboxCanonicalMetadata.none() - .withProducer(new dev.caskeleton.messaging.api.ProducerId("order-api")) - .withTenant(new dev.caskeleton.messaging.api.TenantContext("acme")) - .withRoutingKeys("customer-42", "customer-42"); - - Map headers = mapper(false).map(record(Map.of(), metadata)).headers(); - - assertThat(headers) - .as("a relay that drops these makes the publish path part of the message's meaning") - .containsEntry(ReservedHeaders.PRODUCER, "order-api") - .containsEntry(ReservedHeaders.TENANT, "acme") - .containsEntry(ReservedHeaders.PARTITION_KEY, "customer-42") - .containsEntry(ReservedHeaders.ORDERING_KEY, "customer-42") - .containsEntry(ReservedHeaders.ORIGIN_DESTINATION, "orders.v1"); - } - - @Test - void aColumnTheRowDoesNotCarryProducesNoHeaderAtAll() { - assertThat(mapper(false).map(record(Map.of())).headers()) - .as("an empty string would be indistinguishable from a tenant literally named ''") - .doesNotContainKeys( - ReservedHeaders.TENANT, ReservedHeaders.CORRELATION_ID, ReservedHeaders.TRACEPARENT); - } - - @Test - void aForgedReservedHeaderOnTheRowCannotOverwriteTheCanonicalOne() { - Map forged = - Map.of(ReservedHeaders.MESSAGE_ID, "00000000-0000-7000-8000-000000000000"); - - assertThat(mapper(false).map(record(forged)).headers()) - .as("a CDC connector reads the table directly and never passes the write-path check") - .containsEntry(ReservedHeaders.MESSAGE_ID, MESSAGE_ID.value().toString()); - } - - @Test - void theRoutedKeyIsNotTheTopicName() { - // Literals, not the class's own constants: comparing a configuration value against the constant - // that produced it asserts that the router agrees with itself, which it always will. - assertThat(new DebeziumOutboxEventRouter().connectorConfiguration("prod.")) - .as("keying by destination puts every message on a topic onto one partition") - .containsEntry("transforms.outbox.table.field.event.key", "routing_key") - .containsEntry("transforms.outbox.route.by.field", "destination"); - } - - @Test - void thePayloadIsUnchangedByTheTransform() { - assertThat(mapper(false).map(record(Map.of())).payload()) - .isEqualTo("{\"orderId\":\"o-1\"}".getBytes(StandardCharsets.UTF_8)); - } - - @Test - void runningBothRelaysAtOnceIsRefused() { - DebeziumOutboxProfile cdc = - new DebeziumOutboxProfile(RelayMode.CHANGE_DATA_CAPTURE, "p.", false); - - assertThatThrownBy(() -> cdc.requireExactlyOneRelay(true)) - .as("Debezium never sees the polling lease, so every row would publish twice") - .isInstanceOf(MessagingConfigurationException.class) - .hasMessageContaining("twice"); - } - - @Test - void runningNoRelayAtAllIsAlsoRefused() { - assertThatThrownBy(() -> DebeziumOutboxProfile.polling().requireExactlyOneRelay(false)) - .isInstanceOf(MessagingConfigurationException.class) - .hasMessageContaining("accumulate"); - } - - @Test - void exactlyOneRelayIsAccepted() { - assertThatCode(() -> DebeziumOutboxProfile.polling().requireExactlyOneRelay(true)) - .doesNotThrowAnyException(); - } - - @Test - void aCdcProfileMustNameATopicPrefix() { - assertThatThrownBy(() -> new DebeziumOutboxProfile(RelayMode.CHANGE_DATA_CAPTURE, " ", false)) - .isInstanceOf(IllegalArgumentException.class); - } -} diff --git a/src/messaging/messaging-outbox-jdbc-postgresql/src/test/java/dev/caskeleton/messaging/outbox/OutboxRelayTest.java b/src/messaging/messaging-outbox-jdbc-postgresql/src/test/java/dev/caskeleton/messaging/outbox/OutboxRelayTest.java index 471ba56f..3a8256ab 100644 --- a/src/messaging/messaging-outbox-jdbc-postgresql/src/test/java/dev/caskeleton/messaging/outbox/OutboxRelayTest.java +++ b/src/messaging/messaging-outbox-jdbc-postgresql/src/test/java/dev/caskeleton/messaging/outbox/OutboxRelayTest.java @@ -8,6 +8,11 @@ import dev.caskeleton.messaging.api.MessageId; import dev.caskeleton.messaging.api.MessageType; import dev.caskeleton.messaging.api.ProducerId; import dev.caskeleton.messaging.api.SchemaVersion; +import dev.caskeleton.messaging.api.delivery.DeliveryGuarantee; +import dev.caskeleton.messaging.api.delivery.ExternalSideEffectGuarantee; +import dev.caskeleton.messaging.api.delivery.OrderingScope; +import dev.caskeleton.messaging.api.destination.DestinationCapabilities; +import dev.caskeleton.messaging.api.destination.DestinationKind; import dev.caskeleton.messaging.api.destination.DestinationName; import dev.caskeleton.messaging.api.destination.MessageDestination; import dev.caskeleton.messaging.api.error.FailureCategory; @@ -19,11 +24,37 @@ import dev.caskeleton.messaging.api.publish.PublishEvidence; import dev.caskeleton.messaging.api.publish.PublishOptions; import dev.caskeleton.messaging.api.publish.PublishResult; import dev.caskeleton.messaging.api.publish.RoutingOutcome; +import dev.caskeleton.messaging.policy.CapabilityTier; +import dev.caskeleton.messaging.policy.ConsumerPolicy; +import dev.caskeleton.messaging.policy.DeadLetterPolicy; +import dev.caskeleton.messaging.policy.DestinationProfile; +import dev.caskeleton.messaging.policy.InFlightLimiter; +import dev.caskeleton.messaging.policy.MessagingAdmissionController; +import dev.caskeleton.messaging.policy.PayloadLimitGuard; +import dev.caskeleton.messaging.policy.PayloadPolicy; +import dev.caskeleton.messaging.policy.PhysicalDestination; +import dev.caskeleton.messaging.policy.ProducerPolicy; +import dev.caskeleton.messaging.policy.RetryPolicy; +import dev.caskeleton.messaging.policy.SchemaPolicy; import dev.caskeleton.messaging.reliability.OutboxLease; import dev.caskeleton.messaging.reliability.OutboxRecord; import dev.caskeleton.messaging.reliability.OutboxRepository; import dev.caskeleton.messaging.reliability.OutboxStatus; import dev.caskeleton.messaging.reliability.OutboxTransitionResult; +import dev.caskeleton.messaging.runtime.DefaultMessagePublisher; +import dev.caskeleton.messaging.runtime.DestinationProfileRegistry; +import dev.caskeleton.messaging.runtime.TransportMessagingRuntime; +import dev.caskeleton.messaging.schema.MessageCodec; +import dev.caskeleton.messaging.schema.MessageCodecRegistry; +import dev.caskeleton.messaging.schema.RawBytesMessageCodec; +import dev.caskeleton.messaging.schema.SchemaCompatibility; +import dev.caskeleton.messaging.security.DestinationAccessPolicy; +import dev.caskeleton.messaging.transport.DefaultMessagingRuntimeRegistry; +import dev.caskeleton.messaging.transport.MessagingTransport; +import dev.caskeleton.messaging.transport.TransportConsumerRegistration; +import dev.caskeleton.messaging.transport.TransportConsumerSpec; +import dev.caskeleton.messaging.transport.TransportPublishRequest; +import dev.caskeleton.messaging.transport.TransportPublishResult; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.time.Instant; @@ -32,6 +63,7 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import org.junit.jupiter.api.Test; @@ -162,6 +194,35 @@ class OutboxRelayTest { assertThat(envelope.schemaVersion()).isEqualTo(new SchemaVersion(1)); } + @Test + void aRowRelayedThroughTheRealPublisherIsMarkedPublished() { + // given + OutboxRecord record = OutboxFixtures.pending(); + repository.append(record); + + // when + relay(RealPublisher.over(new CapturingTransport())).runOnce(NOW); + + // then + assertThat(repository.find(record.messageId()).orElseThrow().status()) + .as("re-encoding the stored bytes made the codec refuse them and ended every row FAILED") + .isEqualTo(OutboxStatus.PUBLISHED); + } + + @Test + void aRowRelayedThroughTheRealPublisherReachesTheTransportWithItsStoredBytes() { + // given + OutboxRecord record = OutboxFixtures.pending(); + repository.append(record); + CapturingTransport transport = new CapturingTransport(); + + // when + relay(RealPublisher.over(transport)).runOnce(NOW); + + // then + assertThat(transport.payloads()).containsExactly(record.payload()); + } + private OutboxRelay relay(MessagePublisher publisher) { return new OutboxRelay( repository, @@ -480,3 +541,110 @@ final class RecordingOutboxPublisher implements MessagePublisher { }; } } + +/** The platform's own publisher over a stub transport, registered for the fixture's destination. */ +final class RealPublisher { + + private static final DestinationName ORDERS = new DestinationName("order-events"); + + private RealPublisher() {} + + static DefaultMessagePublisher over(MessagingTransport transport) { + DefaultMessagingRuntimeRegistry runtimes = new DefaultMessagingRuntimeRegistry(); + runtimes.install(new TransportMessagingRuntime("fake", 1, transport)); + // A real codec. Like every codec it refuses a payload that is not its own type, which is what + // an already-encoded row is to it. + MessageCodec raw = new RawBytesMessageCodec(); + return new DefaultMessagePublisher( + DestinationProfileRegistry.of(Map.of(ORDERS, profile())), + new DestinationAccessPolicy(Set.of(ORDERS), Set.of(), Set.of()), + new MessageCodecRegistry() { + @Override + public Optional find(ContentType contentType) { + return Optional.of(raw); + } + + @Override + public MessageCodec defaultCodec() { + return raw; + } + }, + new MessagingAdmissionController( + new PayloadLimitGuard(PayloadPolicy.defaults()), + new InFlightLimiter(4, Duration.ofSeconds(1))), + runtimes, + transport); + } + + private static DestinationProfile profile() { + return new DestinationProfile( + ORDERS, + "fake", + DestinationKind.EVENT_STREAM, + PhysicalDestination.kafkaTopic("order.events.v1"), + new SchemaPolicy( + ContentType.JSON, + SchemaCompatibility.BACKWARD_TRANSITIVE, + Set.of(new MessageType("order.created"))), + DeliveryGuarantee.AT_LEAST_ONCE, + OrderingScope.NONE, + ExternalSideEffectGuarantee.IDEMPOTENCY_REQUIRED, + ProducerPolicy.defaults(), + ConsumerPolicy.defaults("order-projection"), + RetryPolicy.none(), + DeadLetterPolicy.disabled(), + PayloadPolicy.defaults(), + CapabilityTier.M1, + false, + false, + false); + } +} + +/** A transport that confirms every publish and keeps the bytes it was handed. */ +final class CapturingTransport implements MessagingTransport { + + private final List payloads = new ArrayList<>(); + + List payloads() { + return List.copyOf(payloads); + } + + @Override + public CompletionStage publish(TransportPublishRequest request) { + payloads.add(request.envelope().payload().bytes()); + return CompletableFuture.completedFuture( + new TransportPublishResult( + new PublishResult( + PublishCompletion.CONFIRMED, + PublishEvidence.confirmed(ConfirmationLevel.BROKER_ACK), + RoutingOutcome.ROUTED, + Optional.empty(), + 1, + Duration.ZERO, + Optional.empty()))); + } + + @Override + public TransportConsumerRegistration register(TransportConsumerSpec spec) { + throw new UnsupportedOperationException("the relay only publishes"); + } + + @Override + public DestinationCapabilities capabilities(DestinationName destination) { + throw new UnsupportedOperationException("the relay asks for no publish option"); + } + + @Override + public String brokerName() { + return "fake"; + } + + @Override + public long generation() { + return 1; + } + + @Override + public void close() {} +} diff --git a/src/messaging/messaging-pulsar-experimental/build.gradle b/src/messaging/messaging-pulsar-experimental/build.gradle deleted file mode 100644 index 929bf94c..00000000 --- a/src/messaging/messaging-pulsar-experimental/build.gradle +++ /dev/null @@ -1,14 +0,0 @@ -plugins { - id 'ca.platform-module' -} - -dependencies { - api project(':messaging:messaging-core-api') - api project(':messaging:messaging-schema-api') - api project(':messaging:messaging-policy') - api project(':messaging:messaging-transport-spi') - api project(':messaging:messaging-observability') - api project(':messaging:messaging-security') - api project(':messaging:messaging-admin-api') - -} diff --git a/src/messaging/messaging-pulsar-experimental/gradle.lockfile b/src/messaging/messaging-pulsar-experimental/gradle.lockfile deleted file mode 100644 index f5ad1bb5..00000000 --- a/src/messaging/messaging-pulsar-experimental/gradle.lockfile +++ /dev/null @@ -1,89 +0,0 @@ -# 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.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.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_annotations:2.41.0=spotbugs -com.google.errorprone:error_prone_annotations:2.47.0=checkstyle -com.google.errorprone:error_prone_annotations:2.49.0=annotationProcessor,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.5.0-jre=annotationProcessor,testAnnotationProcessor -com.google.guava:guava:33.6.0-jre=checkstyle -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.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 -io.micrometer:micrometer-commons:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.micrometer:micrometer-core:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.micrometer:micrometer-observation:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -javax.inject:javax.inject:1=annotationProcessor,testAnnotationProcessor -jaxen:jaxen:2.0.6=spotbugs -net.bytebuddy:byte-buddy:1.17.8=testCompileClasspath,testRuntimeClasspath -net.sf.saxon:Saxon-HE:12.9=checkstyle,spotbugs -org.antlr:antlr4-runtime:4.13.2=checkstyle -org.apache.bcel:bcel:6.12.0=spotbugs -org.apache.commons:commons-lang3:3.20.0=checkstyle,spotbugs -org.apache.commons:commons-text:1.15.0=spotbugs -org.apache.commons:commons-text:1.3=checkstyle -org.apache.httpcomponents:httpclient:4.5.13=checkstyle -org.apache.httpcomponents:httpcore:4.4.16=checkstyle -org.apache.logging.log4j:log4j-api:2.25.5=spotbugs -org.apache.logging.log4j:log4j-core:2.25.5=spotbugs -org.apache.maven.doxia:doxia-core:1.12.0=checkstyle -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 -org.assertj:assertj-core:3.27.7=testCompileClasspath,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.3.0=checkstyle -org.dom4j:dom4j:2.2.0=spotbugs -org.hdrhistogram:HdrHistogram:2.2.2=runtimeClasspath,testRuntimeClasspath -org.javassist:javassist:3.28.0-GA=checkstyle -org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,compileClasspath,runtimeClasspath,testAnnotationProcessor,testCompileClasspath,testRuntimeClasspath -org.junit.jupiter:junit-jupiter-api:6.0.3=testCompileClasspath,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-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.1.0=spotbugs -org.latencyutils:LatencyUtils:2.0.3=runtimeClasspath,testRuntimeClasspath -org.mockito:mockito-core:5.20.0=mockitoAgent -org.opentest4j:opentest4j:1.3.0=testCompileClasspath,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.reflections:reflections:0.10.2=checkstyle -org.slf4j:slf4j-api:2.0.18=spotbugs,spotbugsSlf4j -org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j -org.slf4j:slf4j-simple:2.0.18=checkstyle -org.xmlresolver:xmlresolver:5.3.3=checkstyle,spotbugs -empty= diff --git a/src/messaging/messaging-pulsar-experimental/src/main/java/dev/caskeleton/messaging/pulsar/PulsarMessagePosition.java b/src/messaging/messaging-pulsar-experimental/src/main/java/dev/caskeleton/messaging/pulsar/PulsarMessagePosition.java deleted file mode 100644 index 7271ac0b..00000000 --- a/src/messaging/messaging-pulsar-experimental/src/main/java/dev/caskeleton/messaging/pulsar/PulsarMessagePosition.java +++ /dev/null @@ -1,49 +0,0 @@ -package dev.caskeleton.messaging.pulsar; - -import dev.caskeleton.messaging.api.publish.BrokerPosition; -import java.util.Map; - -/** - * A Pulsar message id, decomposed into its parts. - * - *

Kept as four fields rather than the opaque {@code MessageId} string so a diagnostic can be - * read without a Pulsar client to parse it. {@code batchIndex} is the part that surprises people: a - * batched message's id is shared by every message in the batch, so the index is what makes an - * individual message addressable at all. - * - * @param ledgerId the ledger holding the entry - * @param entryId the entry within the ledger - * @param partition the partition index, or -1 for a non-partitioned topic - * @param batchIndex the index within a batch, or -1 when the message was not batched - */ -public record PulsarMessagePosition(long ledgerId, long entryId, int partition, int batchIndex) - implements BrokerPosition { - - /** The value used where a topic is not partitioned or a message is not batched. */ - public static final int NOT_APPLICABLE = -1; - - @Override - public String broker() { - return "pulsar"; - } - - @Override - public Map diagnosticAttributes() { - return Map.of( - "ledgerId", Long.toString(ledgerId), - "entryId", Long.toString(entryId), - "partition", Integer.toString(partition), - "batchIndex", Integer.toString(batchIndex)); - } - - /** - * Returns the canonical Pulsar message id rendering. - * - * @return the message id as Pulsar prints it - */ - public String toMessageId() { - return batchIndex == NOT_APPLICABLE - ? "%d:%d:%d".formatted(ledgerId, entryId, partition) - : "%d:%d:%d:%d".formatted(ledgerId, entryId, partition, batchIndex); - } -} diff --git a/src/messaging/messaging-pulsar-experimental/src/main/java/dev/caskeleton/messaging/pulsar/PulsarMessagingTransport.java b/src/messaging/messaging-pulsar-experimental/src/main/java/dev/caskeleton/messaging/pulsar/PulsarMessagingTransport.java deleted file mode 100644 index 1884d57f..00000000 --- a/src/messaging/messaging-pulsar-experimental/src/main/java/dev/caskeleton/messaging/pulsar/PulsarMessagingTransport.java +++ /dev/null @@ -1,275 +0,0 @@ -package dev.caskeleton.messaging.pulsar; - -import dev.caskeleton.messaging.api.destination.DestinationCapabilities; -import dev.caskeleton.messaging.api.destination.DestinationName; -import dev.caskeleton.messaging.api.destination.MessagingCapabilities; -import dev.caskeleton.messaging.api.error.FailureCategory; -import dev.caskeleton.messaging.api.error.FailureDescriptor; -import dev.caskeleton.messaging.api.error.MessagingCapabilityUnavailableException; -import dev.caskeleton.messaging.api.publish.ConfirmationLevel; -import dev.caskeleton.messaging.api.publish.PublishCompletion; -import dev.caskeleton.messaging.api.publish.PublishEvidence; -import dev.caskeleton.messaging.api.publish.PublishResult; -import dev.caskeleton.messaging.api.publish.RoutingOutcome; -import dev.caskeleton.messaging.api.publish.TransmissionEvidence; -import dev.caskeleton.messaging.transport.MessagingTransport; -import dev.caskeleton.messaging.transport.TransportConsumerRegistration; -import dev.caskeleton.messaging.transport.TransportConsumerSpec; -import dev.caskeleton.messaging.transport.TransportPublishRequest; -import dev.caskeleton.messaging.transport.TransportPublishResult; -import java.time.Duration; -import java.util.Objects; -import java.util.Optional; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CompletionStage; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.function.Function; - -/** - * The Experimental Pulsar adapter. - * - *

This is an Experimental contract seam, not a Stable adapter. It exercises the transport SPI - * against a send operation the application supplies; it does not ship a Pulsar client bridge, - * producer lifecycle, or reconnection. Only a failure the operation reports as a {@link - * PulsarPreSendRejection} is treated as definitely not transmitted — every other failure, - * recognised or not, is ambiguous. - * - *

Disabled unless explicitly enabled. Experimental means the contract suite has been run but the - * live-broker certification has not, so the adapter must never become load-bearing because a - * default switched it on. - * - *

Pulsar's send future resolves with a {@code MessageId} once the broker has persisted the - * message to its configured number of bookies, which is genuine replication evidence rather than a - * receipt. A send that fails with a timeout is reported {@code AMBIGUOUS}: the write may have - * reached the bookies and only the acknowledgement been lost, and treating that as a rejection is - * how a message gets published twice. - */ -public final class PulsarMessagingTransport implements MessagingTransport { - - /** What this adapter can prove today. Transactions stay false while Experimental. */ - private static final MessagingCapabilities SHARED_CAPABILITIES = - new MessagingCapabilities( - true, true, true, true, false, false, true, true, false, false, true, true); - - private static final MessagingCapabilities KEY_SHARED_CAPABILITIES = - new MessagingCapabilities( - true, true, true, true, false, true, true, true, false, false, true, true); - - private final String brokerName; - private final long generation; - private final PulsarProfile profile; - private final PulsarSendOperation send; - private final Function consumerFactory; - private final AtomicBoolean closed = new AtomicBoolean(); - - /** - * Creates a publish-only transport. - * - * @param brokerName the logical broker name - * @param generation the runtime generation - * @param profile the Pulsar destination settings - * @param send the producer send operation - */ - public PulsarMessagingTransport( - String brokerName, long generation, PulsarProfile profile, PulsarSendOperation send) { - this( - brokerName, - generation, - profile, - send, - spec -> { - throw new MessagingCapabilityUnavailableException( - "PULSAR_CONSUMER_NOT_CONFIGURED", - "this Pulsar transport was created without a consumer factory"); - }); - } - - /** - * Creates a transport with a consumer factory. - * - * @param brokerName the logical broker name - * @param generation the runtime generation - * @param profile the Pulsar destination settings - * @param send the producer send operation - * @param consumerFactory builds a consumer registration for a spec - */ - public PulsarMessagingTransport( - String brokerName, - long generation, - PulsarProfile profile, - PulsarSendOperation send, - Function consumerFactory) { - this.brokerName = Objects.requireNonNull(brokerName, "brokerName must not be null"); - this.generation = generation; - this.profile = Objects.requireNonNull(profile, "profile must not be null"); - this.send = Objects.requireNonNull(send, "send must not be null"); - this.consumerFactory = Objects.requireNonNull(consumerFactory, "consumerFactory is required"); - } - - @Override - public CompletionStage publish(TransportPublishRequest request) { - Objects.requireNonNull(request, "request must not be null"); - - if (closed.get()) { - return completed( - rejectedLocally("PULSAR_TRANSPORT_CLOSED", "the transport is shutting down")); - } - int size = request.envelope().payload().size(); - int limit = request.profile().payload().maxBytes(); - if (size > limit) { - return completed( - rejectedLocally( - "PAYLOAD_TOO_LARGE", "encoded payload is " + size + " bytes, limit is " + limit)); - } - - // The caller's own deadline, honoured rather than ignored: a stalled send used to hold the - // caller for whatever the SDK's default was, whatever the caller had asked for. - long startedAt = System.nanoTime(); - return send.send(profile.topic(), request) - .toCompletableFuture() - .orTimeout( - request.options().timeout().toMillis(), java.util.concurrent.TimeUnit.MILLISECONDS) - .handle( - (position, failure) -> - failure == null - ? confirmed(position, elapsedSince(startedAt)) - : classify(failure, elapsedSince(startedAt))) - .thenApply(TransportPublishResult::new); - } - - @Override - public TransportConsumerRegistration register(TransportConsumerSpec spec) { - Objects.requireNonNull(spec, "spec must not be null"); - if (closed.get()) { - throw new MessagingCapabilityUnavailableException( - "PULSAR_TRANSPORT_CLOSED", "the transport is shutting down"); - } - return consumerFactory.apply(spec); - } - - @Override - public DestinationCapabilities capabilities(DestinationName destination) { - MessagingCapabilities capabilities = - profile.mode().subscriptionType() == PulsarSubscriptionType.KEY_SHARED - ? KEY_SHARED_CAPABILITIES - : SHARED_CAPABILITIES; - return new DestinationCapabilities(destination, brokerName, capabilities); - } - - @Override - public String brokerName() { - return brokerName; - } - - @Override - public long generation() { - return generation; - } - - @Override - public void close() { - closed.set(true); - } - - /** - * Reports whether the transport is still accepting work. - * - * @return true until close - */ - public boolean isAcceptingWork() { - return !closed.get(); - } - - private static Duration elapsedSince(long startedAtNanos) { - return Duration.ofNanos(System.nanoTime() - startedAtNanos); - } - - private static PublishResult confirmed(PulsarMessagePosition position, Duration elapsed) { - return new PublishResult( - PublishCompletion.CONFIRMED, - // The send future resolves only after the entry is persisted to the configured bookies, so - // this is replication evidence rather than a broker receipt. - new PublishEvidence( - true, - TransmissionEvidence.TRANSMITTED, - true, - ConfirmationLevel.REPLICATION_OR_PERSISTENCE_ACK), - RoutingOutcome.ROUTED, - Optional.of(position), - 1, - elapsed, - Optional.empty()); - } - - /** - * Decides what a send failure means, from typed signals only. - * - *

Classification used to read the exception's class simple name: {@code "Timeout"} meant - * ambiguous, anything else meant rejected. A class name is not part of Pulsar's contract — it - * changes between client versions — and defaulting the unknown case to {@code REJECTED} tells the - * caller nothing was transmitted, which is how the same entry is published to the bookies twice. - */ - private static PublishResult classify(Throwable failure, Duration elapsed) { - Throwable cause = - failure instanceof java.util.concurrent.CompletionException ? failure.getCause() : failure; - if (cause instanceof PulsarPreSendRejection rejection) { - return new PublishResult( - PublishCompletion.REJECTED, - PublishEvidence.notTransmitted(), - RoutingOutcome.NOT_APPLICABLE, - Optional.empty(), - 1, - elapsed, - Optional.of( - FailureDescriptor.of( - FailureCategory.CONFIGURATION, rejection.code(), rejection.getMessage()))); - } - boolean timedOut = cause instanceof java.util.concurrent.TimeoutException; - return new PublishResult( - PublishCompletion.AMBIGUOUS, - new PublishEvidence( - true, TransmissionEvidence.MAY_HAVE_BEEN_TRANSMITTED, false, ConfirmationLevel.NONE), - RoutingOutcome.UNKNOWN, - Optional.empty(), - 1, - elapsed, - Optional.of( - FailureDescriptor.of( - FailureCategory.TRANSIENT_INFRASTRUCTURE, - timedOut ? "PULSAR_SEND_TIMEOUT" : "PULSAR_SEND_OUTCOME_UNKNOWN", - timedOut - ? "the send timed out; the broker may already hold the message" - : "the send failed in a way this adapter does not classify; the broker may" - + " already hold the message"))); - } - - private static TransportPublishResult rejectedLocally(String code, String message) { - return new TransportPublishResult( - new PublishResult( - PublishCompletion.REJECTED, - PublishEvidence.notTransmitted(), - RoutingOutcome.NOT_APPLICABLE, - Optional.empty(), - 1, - Duration.ZERO, - Optional.of(FailureDescriptor.of(FailureCategory.PERMANENT_BUSINESS, code, message)))); - } - - private static CompletionStage completed(TransportPublishResult result) { - return CompletableFuture.completedFuture(result); - } - - /** The producer send, isolated so the adapter is testable without a broker. */ - @FunctionalInterface - public interface PulsarSendOperation { - - /** - * Sends one encoded message. - * - * @param topic the Pulsar topic - * @param request the publish request - * @return a stage completing with the broker position - */ - CompletionStage send(String topic, TransportPublishRequest request); - } -} diff --git a/src/messaging/messaging-pulsar-experimental/src/main/java/dev/caskeleton/messaging/pulsar/PulsarPreSendRejection.java b/src/messaging/messaging-pulsar-experimental/src/main/java/dev/caskeleton/messaging/pulsar/PulsarPreSendRejection.java deleted file mode 100644 index 6cf5f62d..00000000 --- a/src/messaging/messaging-pulsar-experimental/src/main/java/dev/caskeleton/messaging/pulsar/PulsarPreSendRejection.java +++ /dev/null @@ -1,65 +0,0 @@ -package dev.caskeleton.messaging.pulsar; - -import java.util.Objects; - -/** - * The one signal that lets this adapter report {@code REJECTED / NOT_TRANSMITTED}. - * - *

Classification used to work by reading the exception's class simple name and matching - * substrings — {@code "Timeout"} meant ambiguous, anything else meant rejected. Two things are - * wrong with that. A class name is not part of any SDK's contract: it changes between versions, and - * an unrelated exception whose name happens to contain the substring is misread. And defaulting the - * unknown case to {@code REJECTED} tells the caller nothing was transmitted, so a caller that - * republishes under a new identity duplicates a message the server may well have stored. - * - *

The send operation throws this only when it knows the send never left the client: an argument - * the SDK refused, a producer that was already closed, a topic the client could not resolve. - * Everything else — including anything the adapter does not recognise — is ambiguous, and ambiguity - * is the honest answer when the write may have landed. - */ -public final class PulsarPreSendRejection extends RuntimeException { - - private static final long serialVersionUID = 1L; - - private final String code; - - /** - * Creates a pre-send rejection. - * - * @param code the sanitised platform code for the refusal - * @param message a sanitised description - */ - public PulsarPreSendRejection(String code, String message) { - super(message); - this.code = requireCode(code); - } - - /** - * Creates a pre-send rejection wrapping the SDK's own exception. - * - * @param code the sanitised platform code for the refusal - * @param message a sanitised description - * @param cause the SDK exception that proves the send never started - */ - public PulsarPreSendRejection(String code, String message, Throwable cause) { - super(message, cause); - this.code = requireCode(code); - } - - private static String requireCode(String code) { - Objects.requireNonNull(code, "code must not be null"); - if (code.isBlank()) { - throw new IllegalArgumentException("code must not be blank"); - } - return code; - } - - /** - * The sanitised code reported to the caller. - * - * @return the code - */ - public String code() { - return code; - } -} diff --git a/src/messaging/messaging-pulsar-experimental/src/main/java/dev/caskeleton/messaging/pulsar/PulsarProfile.java b/src/messaging/messaging-pulsar-experimental/src/main/java/dev/caskeleton/messaging/pulsar/PulsarProfile.java deleted file mode 100644 index 154cce1d..00000000 --- a/src/messaging/messaging-pulsar-experimental/src/main/java/dev/caskeleton/messaging/pulsar/PulsarProfile.java +++ /dev/null @@ -1,80 +0,0 @@ -package dev.caskeleton.messaging.pulsar; - -import java.time.Duration; -import java.util.Objects; -import java.util.Optional; - -/** - * The Pulsar-side settings for one destination. - * - *

{@code negativeAckRedeliveryDelay} is the platform's retry hook on Pulsar. Pulsar has no retry - * topic of its own in this adapter, so a failed handler negatively acknowledges and the broker - * redelivers after this delay — which means the delay is the backoff, and setting it to - * zero converts a failing handler into a spin loop against the broker. - * - *

{@code ackTimeout} is deliberately optional and off by default. It redelivers any message the - * consumer has not acknowledged in time, which looks like a safety net and behaves like a duplicate - * generator for handlers that are simply slow. - * - * @param topic the fully-qualified Pulsar topic - * @param subscription the durable subscription name - * @param mode the subscription type and acknowledgement style - * @param negativeAckRedeliveryDelay how long the broker waits after a negative acknowledgement - * @param ackTimeout redelivers unacknowledged messages after this long, when set - * @param maxRedeliverCount how many redeliveries before the message is parked - */ -public record PulsarProfile( - String topic, - String subscription, - PulsarSubscriptionMode mode, - Duration negativeAckRedeliveryDelay, - Optional ackTimeout, - int maxRedeliverCount) { - - /** Pulsar's own floor for an acknowledgement timeout. */ - public static final Duration MINIMUM_ACK_TIMEOUT = Duration.ofSeconds(10); - - public PulsarProfile { - Objects.requireNonNull(mode, "mode must not be null"); - Objects.requireNonNull(negativeAckRedeliveryDelay, "negativeAckRedeliveryDelay is required"); - Objects.requireNonNull(ackTimeout, "ackTimeout must not be null"); - requireText(topic, "topic"); - requireText(subscription, "subscription"); - - if (negativeAckRedeliveryDelay.isNegative() || negativeAckRedeliveryDelay.isZero()) { - throw new IllegalArgumentException( - "negativeAckRedeliveryDelay must be positive; zero turns a failing handler into a spin " - + "loop against the broker"); - } - if (maxRedeliverCount < 1) { - throw new IllegalArgumentException("maxRedeliverCount must be at least 1"); - } - if (ackTimeout.isPresent() && ackTimeout.get().compareTo(MINIMUM_ACK_TIMEOUT) < 0) { - throw new IllegalArgumentException( - "ackTimeout below %s is rejected by Pulsar itself".formatted(MINIMUM_ACK_TIMEOUT)); - } - } - - /** - * Returns a shared-subscription profile with the platform defaults. - * - * @param topic the Pulsar topic - * @param subscription the subscription name - * @return the profile - */ - public static PulsarProfile shared(String topic, String subscription) { - return new PulsarProfile( - topic, - subscription, - PulsarSubscriptionMode.shared(), - Duration.ofSeconds(30), - Optional.empty(), - 5); - } - - private static void requireText(String value, String field) { - if (value == null || value.isBlank()) { - throw new IllegalArgumentException(field + " must not be blank"); - } - } -} diff --git a/src/messaging/messaging-pulsar-experimental/src/main/java/dev/caskeleton/messaging/pulsar/PulsarProfileValidator.java b/src/messaging/messaging-pulsar-experimental/src/main/java/dev/caskeleton/messaging/pulsar/PulsarProfileValidator.java deleted file mode 100644 index b0e0db3f..00000000 --- a/src/messaging/messaging-pulsar-experimental/src/main/java/dev/caskeleton/messaging/pulsar/PulsarProfileValidator.java +++ /dev/null @@ -1,66 +0,0 @@ -package dev.caskeleton.messaging.pulsar; - -import dev.caskeleton.messaging.api.delivery.OrderingScope; -import dev.caskeleton.messaging.api.destination.MessagingCapabilities; -import dev.caskeleton.messaging.api.error.MessagingCapabilityUnavailableException; -import dev.caskeleton.messaging.policy.DestinationProfile; -import java.util.Objects; - -/** - * Guards the Pulsar Experimental adapter. - * - *

The subscription type and the destination's ordering scope have to agree, and the platform - * checks rather than assumes. A {@code Shared} subscription distributes messages round-robin across - * consumers, so a destination that declares key ordering on one is advertising a guarantee Pulsar - * is not providing — the messages arrive, in an order nobody promised. - * - *

Experimental means off by default. An adapter whose contract suite is still being proven must - * not become load-bearing because someone's configuration defaulted it on. - */ -public final class PulsarProfileValidator { - - /** - * Validates a destination against a Pulsar subscription. - * - * @param profile the destination profile - * @param subscriptionType the Pulsar subscription type - * @param enabled whether the experimental adapter is switched on - */ - public void validate( - DestinationProfile profile, PulsarSubscriptionType subscriptionType, boolean enabled) { - Objects.requireNonNull(profile, "profile must not be null"); - Objects.requireNonNull(subscriptionType, "subscriptionType must not be null"); - - if (!enabled) { - throw new MessagingCapabilityUnavailableException( - "PULSAR_DISABLED", - "the Pulsar adapter is experimental and disabled unless " - + "app.messaging.experimental.pulsar=true"); - } - if (profile.orderingScope() == OrderingScope.KEY - && subscriptionType != PulsarSubscriptionType.KEY_SHARED) { - throw new IllegalArgumentException( - "keyed ordering requires a Key_Shared subscription: " + profile.name().value()); - } - if (profile.orderingScope() == OrderingScope.DESTINATION) { - throw new IllegalArgumentException( - "the Pulsar adapter does not offer destination-wide ordering: " + profile.name().value()); - } - } - - /** - * Returns what the Pulsar adapter can prove for a subscription type. - * - *

Transactions are reported as unavailable while the adapter is Experimental: Pulsar has them, - * but the platform has not yet proven them against its own contract suite, and advertising an - * unverified guarantee is exactly what the Experimental tier exists to prevent. - * - * @param subscriptionType the subscription type - * @return the capabilities - */ - public MessagingCapabilities capabilities(PulsarSubscriptionType subscriptionType) { - boolean keyed = subscriptionType == PulsarSubscriptionType.KEY_SHARED; - return new MessagingCapabilities( - true, true, true, true, keyed, keyed, true, true, false, false, true, true); - } -} diff --git a/src/messaging/messaging-pulsar-experimental/src/main/java/dev/caskeleton/messaging/pulsar/PulsarSubscriptionMode.java b/src/messaging/messaging-pulsar-experimental/src/main/java/dev/caskeleton/messaging/pulsar/PulsarSubscriptionMode.java deleted file mode 100644 index 4d2c53e8..00000000 --- a/src/messaging/messaging-pulsar-experimental/src/main/java/dev/caskeleton/messaging/pulsar/PulsarSubscriptionMode.java +++ /dev/null @@ -1,62 +0,0 @@ -package dev.caskeleton.messaging.pulsar; - -import dev.caskeleton.messaging.api.delivery.OrderingScope; -import java.util.Objects; - -/** - * How a Pulsar subscription is configured, and what ordering it can actually deliver. - * - *

Pairs the subscription type with its acknowledgement style because the two together determine - * the guarantee. A {@code Key_Shared} subscription with cumulative acknowledgement is not keyed - * ordering with a faster ack — cumulative ack over interleaved keys acknowledges messages from keys - * the consumer has not finished, so the combination silently loses the property the subscription - * type was chosen for. - * - * @param subscriptionType the Pulsar subscription type - * @param cumulativeAcknowledgement whether acknowledgements are cumulative rather than individual - */ -public record PulsarSubscriptionMode( - PulsarSubscriptionType subscriptionType, boolean cumulativeAcknowledgement) { - - public PulsarSubscriptionMode { - Objects.requireNonNull(subscriptionType, "subscriptionType must not be null"); - if (cumulativeAcknowledgement && subscriptionType == PulsarSubscriptionType.KEY_SHARED) { - throw new IllegalArgumentException( - "Key_Shared with cumulative acknowledgement acknowledges keys the consumer has not " - + "finished, which discards the per-key ordering the subscription type provides"); - } - if (cumulativeAcknowledgement && subscriptionType == PulsarSubscriptionType.SHARED) { - throw new IllegalArgumentException( - "Shared subscriptions do not support cumulative acknowledgement"); - } - } - - /** - * Returns a shared subscription with individual acknowledgement. - * - * @return the shared mode - */ - public static PulsarSubscriptionMode shared() { - return new PulsarSubscriptionMode(PulsarSubscriptionType.SHARED, false); - } - - /** - * Returns a key-shared subscription with individual acknowledgement. - * - * @return the key-shared mode - */ - public static PulsarSubscriptionMode keyShared() { - return new PulsarSubscriptionMode(PulsarSubscriptionType.KEY_SHARED, false); - } - - /** - * Returns the strongest ordering this mode can deliver. - * - * @return the ordering scope - */ - public OrderingScope orderingScope() { - return subscriptionType == PulsarSubscriptionType.KEY_SHARED - ? OrderingScope.KEY - : OrderingScope.NONE; - } -} diff --git a/src/messaging/messaging-pulsar-experimental/src/main/java/dev/caskeleton/messaging/pulsar/PulsarSubscriptionType.java b/src/messaging/messaging-pulsar-experimental/src/main/java/dev/caskeleton/messaging/pulsar/PulsarSubscriptionType.java deleted file mode 100644 index 4a88a321..00000000 --- a/src/messaging/messaging-pulsar-experimental/src/main/java/dev/caskeleton/messaging/pulsar/PulsarSubscriptionType.java +++ /dev/null @@ -1,17 +0,0 @@ -package dev.caskeleton.messaging.pulsar; - -/** - * The Pulsar subscription types the Experimental adapter exposes. - * - *

Only the two that map cleanly onto the platform's ordering model. {@code Exclusive} and {@code - * Failover} are omitted deliberately: they encode a topology decision the destination profile - * already owns, and exposing them would give an application two places to configure the same thing. - */ -public enum PulsarSubscriptionType { - - /** Competing consumers, no ordering. */ - SHARED, - - /** Competing consumers with per-key ordering. */ - KEY_SHARED -} diff --git a/src/messaging/messaging-pulsar-experimental/src/main/java/dev/caskeleton/messaging/pulsar/PulsarTransactionCapability.java b/src/messaging/messaging-pulsar-experimental/src/main/java/dev/caskeleton/messaging/pulsar/PulsarTransactionCapability.java deleted file mode 100644 index 104caf4c..00000000 --- a/src/messaging/messaging-pulsar-experimental/src/main/java/dev/caskeleton/messaging/pulsar/PulsarTransactionCapability.java +++ /dev/null @@ -1,49 +0,0 @@ -package dev.caskeleton.messaging.pulsar; - -import dev.caskeleton.messaging.api.error.MessagingCapabilityUnavailableException; - -/** - * States, in code, that Pulsar transactions are not promoted. - * - *

Pulsar has transactions. The platform does not offer them, and the distinction matters enough - * to be a class rather than a comment: an operator reading the capability matrix needs to know the - * answer is "not proven here", not "the broker cannot do it". - * - *

What is missing is the proof. The platform's contract suite has not been run against Pulsar - * transactions across broker restart, client fencing, and partial-commit recovery, and the - * Experimental tier exists precisely so that an unproven guarantee is never advertised as one. A - * capability that reports {@code true} on the strength of the broker's documentation is the failure - * mode this class prevents. - */ -public final class PulsarTransactionCapability { - - private PulsarTransactionCapability() {} - - /** Whether the adapter advertises broker transactions. */ - public static final boolean PROMOTED = false; - - /** - * Reports whether transactions may be used. - * - * @return false while the adapter is Experimental - */ - public static boolean isAvailable() { - return PROMOTED; - } - - /** - * Returns the refusal for a transactional request, for the caller to throw. - * - *

Returned rather than thrown so the refusal reads as a value at the call site: {@code throw - * PulsarTransactionCapability.rejection();} makes it obvious that control leaves there, which a - * method that throws on the caller's behalf hides. - * - * @return the exception explaining why transactions are unavailable - */ - public static MessagingCapabilityUnavailableException rejection() { - return new MessagingCapabilityUnavailableException( - "PULSAR_TRANSACTION_NOT_PROMOTED", - "Pulsar supports transactions but this adapter has not certified them against the " - + "platform contract suite, so the capability is not advertised"); - } -} diff --git a/src/messaging/messaging-pulsar-experimental/src/test/java/dev/caskeleton/messaging/pulsar/PulsarAdapterContractTest.java b/src/messaging/messaging-pulsar-experimental/src/test/java/dev/caskeleton/messaging/pulsar/PulsarAdapterContractTest.java deleted file mode 100644 index 0ec8223b..00000000 --- a/src/messaging/messaging-pulsar-experimental/src/test/java/dev/caskeleton/messaging/pulsar/PulsarAdapterContractTest.java +++ /dev/null @@ -1,289 +0,0 @@ -package dev.caskeleton.messaging.pulsar; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.messaging.api.ContentType; -import dev.caskeleton.messaging.api.MessageEnvelope; -import dev.caskeleton.messaging.api.MessageId; -import dev.caskeleton.messaging.api.MessageType; -import dev.caskeleton.messaging.api.ProducerId; -import dev.caskeleton.messaging.api.SchemaVersion; -import dev.caskeleton.messaging.api.TraceContext; -import dev.caskeleton.messaging.api.delivery.DeliveryGuarantee; -import dev.caskeleton.messaging.api.delivery.ExternalSideEffectGuarantee; -import dev.caskeleton.messaging.api.delivery.OrderingScope; -import dev.caskeleton.messaging.api.destination.DestinationKind; -import dev.caskeleton.messaging.api.destination.DestinationName; -import dev.caskeleton.messaging.api.error.MessagingCapabilityUnavailableException; -import dev.caskeleton.messaging.api.header.MessageHeaders; -import dev.caskeleton.messaging.api.publish.ConfirmationLevel; -import dev.caskeleton.messaging.api.publish.PublishCompletion; -import dev.caskeleton.messaging.api.publish.PublishOptions; -import dev.caskeleton.messaging.api.publish.PublishResult; -import dev.caskeleton.messaging.api.publish.RoutingOutcome; -import dev.caskeleton.messaging.api.publish.TransmissionEvidence; -import dev.caskeleton.messaging.policy.CapabilityTier; -import dev.caskeleton.messaging.policy.ConsumerPolicy; -import dev.caskeleton.messaging.policy.DeadLetterPolicy; -import dev.caskeleton.messaging.policy.DestinationProfile; -import dev.caskeleton.messaging.policy.PayloadPolicy; -import dev.caskeleton.messaging.policy.PhysicalDestination; -import dev.caskeleton.messaging.policy.ProducerPolicy; -import dev.caskeleton.messaging.policy.RetryPolicy; -import dev.caskeleton.messaging.policy.SchemaPolicy; -import dev.caskeleton.messaging.schema.EncodedMessage; -import dev.caskeleton.messaging.schema.SchemaCompatibility; -import dev.caskeleton.messaging.transport.TransportPublishRequest; -import java.time.Instant; -import java.util.Optional; -import java.util.Set; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CompletionStage; -import java.util.concurrent.TimeoutException; -import org.junit.jupiter.api.Test; - -class PulsarAdapterContractTest { - - private static final String TOPIC = "persistent://public/default/orders"; - private static final Instant NOW = Instant.parse("2026-08-10T09:15:00Z"); - private static final PulsarMessagePosition POSITION = new PulsarMessagePosition(5, 9, 0, -1); - - private static PulsarMessagingTransport transport( - PulsarMessagingTransport.PulsarSendOperation send, PulsarSubscriptionMode mode) { - PulsarProfile profile = - new PulsarProfile( - TOPIC, "orders-sub", mode, java.time.Duration.ofSeconds(30), Optional.empty(), 5); - return new PulsarMessagingTransport("pulsar-primary", 1, profile, send); - } - - private static PulsarMessagingTransport confirming() { - return transport( - (topic, request) -> CompletableFuture.completedFuture(POSITION), - PulsarSubscriptionMode.shared()); - } - - private static PulsarMessagingTransport failingWith(Throwable failure) { - return transport( - (topic, request) -> CompletableFuture.failedFuture(failure), - PulsarSubscriptionMode.shared()); - } - - private static PublishResult await(CompletionStage stage) { - Object value = stage.toCompletableFuture().join(); - return ((dev.caskeleton.messaging.transport.TransportPublishResult) value).result(); - } - - @Test - void aSuccessfulSendReportsReplicationEvidenceNotAMereReceipt() { - PublishResult result = await(confirming().publish(request(64))); - - assertThat(result.completion()).isEqualTo(PublishCompletion.CONFIRMED); - assertThat(result.evidence().confirmationLevel()) - .as("the send future resolves only once the entry is persisted to the bookies") - .isEqualTo(ConfirmationLevel.REPLICATION_OR_PERSISTENCE_ACK); - assertThat(result.routingOutcome()).isEqualTo(RoutingOutcome.ROUTED); - } - - @Test - void theBrokerPositionIsCarriedBackForDiagnostics() { - assertThat(await(confirming().publish(request(64))).position()).hasValue(POSITION); - } - - @Test - void aSendTimeoutIsAmbiguousRatherThanRejected() { - PublishResult result = - await(failingWith(new TimeoutException("send timed out")).publish(request(64))); - - assertThat(result.completion()) - .as("the entry may be on the bookies with only the acknowledgement lost") - .isEqualTo(PublishCompletion.AMBIGUOUS); - assertThat(result.evidence().transmission()) - .isEqualTo(TransmissionEvidence.MAY_HAVE_BEEN_TRANSMITTED); - assertThat(result.evidence().brokerAccepted()).isFalse(); - } - - @Test - void onlyATypedPreSendRejectionIsReportedAsNotTransmitted() { - PublishResult result = - await( - failingWith( - new PulsarPreSendRejection( - "PULSAR_PRODUCER_FENCED", "the producer was fenced before the send")) - .publish(request(64))); - - assertThat(result.completion()).isEqualTo(PublishCompletion.REJECTED); - assertThat(result.evidence().transmission()).isEqualTo(TransmissionEvidence.NOT_TRANSMITTED); - assertThat(result.failure()) - .hasValueSatisfying( - failure -> assertThat(failure.code()).isEqualTo("PULSAR_PRODUCER_FENCED")); - } - - @Test - void anUnrecognisedFailureIsAmbiguousRatherThanRejected() { - // Any exception the adapter cannot type is a send whose outcome it does not know. Reporting - // REJECTED invites the caller to republish an entry the bookies may already hold. - PublishResult result = - await(failingWith(new IllegalStateException("producer is fenced")).publish(request(64))); - - assertThat(result.completion()).isEqualTo(PublishCompletion.AMBIGUOUS); - assertThat(result.evidence().transmission()) - .isEqualTo(TransmissionEvidence.MAY_HAVE_BEEN_TRANSMITTED); - assertThat(result.failure()) - .hasValueSatisfying( - failure -> assertThat(failure.code()).isEqualTo("PULSAR_SEND_OUTCOME_UNKNOWN")); - } - - @Test - void aWrappedUnknownFailureIsAlsoAmbiguous() { - PublishResult result = - await( - failingWith( - new java.util.concurrent.CompletionException( - new RuntimeException("something the adapter has never seen"))) - .publish(request(64))); - - assertThat(result.completion()).isEqualTo(PublishCompletion.AMBIGUOUS); - } - - @Test - void aSendThatNeverCompletesIsBoundedByTheCallersTimeout() { - PulsarMessagingTransport stalled = - transport((topic, request) -> new CompletableFuture<>(), PulsarSubscriptionMode.shared()); - - PublishResult result = - await(stalled.publish(requestWithTimeout(java.time.Duration.ofMillis(50)))); - - assertThat(result.completion()).isEqualTo(PublishCompletion.AMBIGUOUS); - assertThat(result.failure()) - .hasValueSatisfying(failure -> assertThat(failure.code()).isEqualTo("PULSAR_SEND_TIMEOUT")); - } - - @Test - void anOversizedPayloadIsRejectedBeforeItReachesTheBroker() { - PublishResult result = - await(confirming().publish(request(PayloadPolicy.DEFAULT_MAX_BYTES + 1))); - - assertThat(result.completion()).isEqualTo(PublishCompletion.REJECTED); - assertThat(result.evidence().transmission()).isEqualTo(TransmissionEvidence.NOT_TRANSMITTED); - assertThat(result.failure()) - .hasValueSatisfying(failure -> assertThat(failure.code()).isEqualTo("PAYLOAD_TOO_LARGE")); - } - - @Test - void aClosedTransportStopsAcceptingNewWork() { - PulsarMessagingTransport transport = confirming(); - transport.close(); - - assertThat(transport.isAcceptingWork()).isFalse(); - assertThat(await(transport.publish(request(64))).completion()) - .isEqualTo(PublishCompletion.REJECTED); - } - - @Test - void aTransportWithoutAConsumerFactoryRefusesToRegisterRatherThanReturningNothing() { - assertThatThrownBy(() -> confirming().register(null)).isInstanceOf(NullPointerException.class); - } - - @Test - void aSharedSubscriptionAdvertisesNoKeyedOrdering() { - var capabilities = - transport( - (topic, request) -> CompletableFuture.completedFuture(POSITION), - PulsarSubscriptionMode.shared()) - .capabilities(new DestinationName("orders.v1")) - .capabilities(); - - assertThat(capabilities.keyedOrdering()).isFalse(); - } - - @Test - void aKeySharedSubscriptionAdvertisesKeyedOrdering() { - var capabilities = - transport( - (topic, request) -> CompletableFuture.completedFuture(POSITION), - PulsarSubscriptionMode.keyShared()) - .capabilities(new DestinationName("orders.v1")) - .capabilities(); - - assertThat(capabilities.keyedOrdering()).isTrue(); - } - - @Test - void noSubscriptionModeAdvertisesBrokerTransactions() { - assertThat( - transport( - (topic, request) -> CompletableFuture.completedFuture(POSITION), - PulsarSubscriptionMode.keyShared()) - .capabilities(new DestinationName("orders.v1")) - .capabilities() - .brokerTransaction()) - .as("Pulsar has transactions; this adapter has not certified them") - .isFalse(); - } - - @Test - void requestingATransactionFailsWithAnExplanation() { - assertThat(PulsarTransactionCapability.rejection()) - .isInstanceOf(MessagingCapabilityUnavailableException.class) - .hasMessageContaining("not advertised"); - } - - private static TransportPublishRequest requestWithTimeout(java.time.Duration timeout) { - PublishOptions defaults = PublishOptions.defaults(); - return new TransportPublishRequest( - profile(), - envelope(64), - new PublishOptions(timeout, defaults.confirmation(), defaults.deduplication())); - } - - private static TransportPublishRequest request(int payloadBytes) { - return new TransportPublishRequest( - profile(), envelope(payloadBytes), PublishOptions.defaults()); - } - - private static DestinationProfile profile() { - return new DestinationProfile( - new DestinationName("orders.v1"), - "pulsar-primary", - DestinationKind.EVENT_STREAM, - PhysicalDestination.pulsarTopic(TOPIC, "orders-sub"), - new SchemaPolicy( - ContentType.JSON, - SchemaCompatibility.BACKWARD, - Set.of(new MessageType("order.created"))), - DeliveryGuarantee.AT_LEAST_ONCE, - OrderingScope.NONE, - ExternalSideEffectGuarantee.IDEMPOTENCY_REQUIRED, - ProducerPolicy.defaults(), - ConsumerPolicy.defaults("orders"), - RetryPolicy.none(), - DeadLetterPolicy.to(new DestinationName("orders.v1.dlq")), - PayloadPolicy.defaults(), - CapabilityTier.M1, - false, - false, - false); - } - - private static MessageEnvelope envelope(int payloadBytes) { - byte[] payload = new byte[payloadBytes]; - java.util.Arrays.fill(payload, (byte) 'x'); - return new MessageEnvelope<>( - MessageId.newId(), - new MessageType("order.created"), - new SchemaVersion(1), - NOW, - Optional.of(NOW), - new ProducerId("order-api"), - Optional.empty(), - Optional.empty(), - ContentType.JSON, - Optional.empty(), - Optional.empty(), - Optional.empty(), - TraceContext.none(), - MessageHeaders.empty(), - new EncodedMessage(payload, ContentType.JSON, Optional.empty())); - } -} diff --git a/src/messaging/messaging-pulsar-experimental/src/test/java/dev/caskeleton/messaging/pulsar/PulsarSubscriptionGuardTest.java b/src/messaging/messaging-pulsar-experimental/src/test/java/dev/caskeleton/messaging/pulsar/PulsarSubscriptionGuardTest.java deleted file mode 100644 index a7dea10f..00000000 --- a/src/messaging/messaging-pulsar-experimental/src/test/java/dev/caskeleton/messaging/pulsar/PulsarSubscriptionGuardTest.java +++ /dev/null @@ -1,125 +0,0 @@ -package dev.caskeleton.messaging.pulsar; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.messaging.api.delivery.OrderingScope; -import dev.caskeleton.messaging.api.error.MessagingCapabilityUnavailableException; -import java.time.Duration; -import java.util.Optional; -import org.junit.jupiter.api.Test; - -class PulsarSubscriptionGuardTest { - - @Test - void keySharedWithCumulativeAcknowledgementIsRefused() { - assertThatThrownBy(() -> new PulsarSubscriptionMode(PulsarSubscriptionType.KEY_SHARED, true)) - .as("cumulative ack over interleaved keys discards the ordering the type provides") - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("ordering"); - } - - @Test - void sharedWithCumulativeAcknowledgementIsRefused() { - assertThatThrownBy(() -> new PulsarSubscriptionMode(PulsarSubscriptionType.SHARED, true)) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void aSharedSubscriptionPromisesNoOrdering() { - assertThat(PulsarSubscriptionMode.shared().orderingScope()).isEqualTo(OrderingScope.NONE); - } - - @Test - void aKeySharedSubscriptionPromisesKeyOrdering() { - assertThat(PulsarSubscriptionMode.keyShared().orderingScope()).isEqualTo(OrderingScope.KEY); - } - - @Test - void aZeroNegativeAckDelayIsRefused() { - assertThatThrownBy( - () -> - new PulsarProfile( - "persistent://public/default/orders", - "orders-sub", - PulsarSubscriptionMode.shared(), - Duration.ZERO, - Optional.empty(), - 5)) - .as("a zero redelivery delay turns a failing handler into a spin loop") - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("spin loop"); - } - - @Test - void anAckTimeoutBelowPulsarsOwnFloorIsRefused() { - assertThatThrownBy( - () -> - new PulsarProfile( - "persistent://public/default/orders", - "orders-sub", - PulsarSubscriptionMode.shared(), - Duration.ofSeconds(30), - Optional.of(Duration.ofSeconds(1)), - 5)) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void theDefaultProfileLeavesAckTimeoutOff() { - assertThat( - PulsarProfile.shared("persistent://public/default/orders", "orders-sub").ackTimeout()) - .as("an ack timeout redelivers messages from handlers that are merely slow") - .isEmpty(); - } - - @Test - void transactionsAreNotAdvertisedWhileTheAdapterIsExperimental() { - assertThat(PulsarTransactionCapability.isAvailable()).isFalse(); - assertThat(PulsarTransactionCapability.rejection()) - .isInstanceOf(MessagingCapabilityUnavailableException.class); - } - - @Test - void theRefusalExplainsThatTheGapIsProofNotBrokerSupport() { - assertThat(PulsarTransactionCapability.rejection()) - .hasMessageContaining("certified") - .hasMessageContaining("contract suite"); - } - - @Test - void aNonBatchedPositionRendersWithoutABatchIndex() { - PulsarMessagePosition position = - new PulsarMessagePosition(12, 34, 2, PulsarMessagePosition.NOT_APPLICABLE); - - assertThat(position.toMessageId()).isEqualTo("12:34:2"); - assertThat(position.broker()).isEqualTo("pulsar"); - } - - @Test - void aBatchedPositionKeepsItsIndexBecauseTheIdAloneIsShared() { - assertThat(new PulsarMessagePosition(12, 34, 2, 7).toMessageId()).isEqualTo("12:34:2:7"); - } - - @Test - void thePositionIsReadableAsDiagnosticAttributes() { - assertThat(new PulsarMessagePosition(12, 34, 2, 7).diagnosticAttributes()) - .containsEntry("ledgerId", "12") - .containsEntry("batchIndex", "7"); - } - - @Test - void theValidatorAcceptsAKeyedProfileOnKeyShared() { - assertThatCode( - () -> - new PulsarProfile( - "persistent://public/default/orders", - "orders-sub", - PulsarSubscriptionMode.keyShared(), - Duration.ofSeconds(30), - Optional.empty(), - 5)) - .doesNotThrowAnyException(); - } -} diff --git a/src/messaging/messaging-rabbit/build.gradle b/src/messaging/messaging-rabbit/build.gradle deleted file mode 100644 index f3469968..00000000 --- a/src/messaging/messaging-rabbit/build.gradle +++ /dev/null @@ -1,43 +0,0 @@ -plugins { - id 'java-test-fixtures' - id 'ca.auxiliary-source-set' - id 'ca.jmh-benchmarks' -} - -auxiliarySourceSets { - sourceSet('integrationTest') { - compilesAgainst 'main', 'testFixtures' - } -} - -dependencies { - api project(':messaging:messaging-core-api') - api project(':messaging:messaging-schema-api') - api project(':messaging:messaging-policy') - api project(':messaging:messaging-transport-spi') - api project(':messaging:messaging-observability') - api project(':messaging:messaging-security') - api project(':messaging:messaging-admin-api') - - // api: RabbitChannelPublisher and the mappers expose Spring AMQP's Message on public - // signatures, so a consumer implementing the seam needs the type on its compile classpath. - api 'org.springframework.amqp:spring-rabbit' - implementation 'org.springframework:spring-context' - - // Test-only. The same adapter contract Kafka runs, so a guarantee can only be weakened by - // editing the contract rather than by an adapter quietly not implementing it. - testImplementation project(':messaging:messaging-testkit') - - // Live-broker certification. The confirm-and-return ordering the adapter depends on is a - // property of AMQP, and only a real broker exhibits it. - integrationTestImplementation 'org.testcontainers:testcontainers-rabbitmq' - integrationTestImplementation 'org.testcontainers:testcontainers-junit-jupiter' -} - -strictTestLanes { - lane('integrationTest') { - integration() - sourceSet = 'integrationTest' - description = 'Runs RabbitMQ broker integration contracts against a real container.' - } -} diff --git a/src/messaging/messaging-rabbit/gradle.lockfile b/src/messaging/messaging-rabbit/gradle.lockfile deleted file mode 100644 index e5000c29..00000000 --- a/src/messaging/messaging-rabbit/gradle.lockfile +++ /dev/null @@ -1,128 +0,0 @@ -# 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.fasterxml.jackson.core:jackson-annotations:2.21=integrationTestCompileClasspath,integrationTestRuntimeClasspath -com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,integrationTestAnnotationProcessor,jmhAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor -com.github.docker-java:docker-java-api:3.7.1=integrationTestCompileClasspath,integrationTestRuntimeClasspath -com.github.docker-java:docker-java-transport-zerodep:3.7.1=integrationTestCompileClasspath,integrationTestRuntimeClasspath -com.github.docker-java:docker-java-transport:3.7.1=integrationTestCompileClasspath,integrationTestRuntimeClasspath -com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,integrationTestAnnotationProcessor,jmhAnnotationProcessor,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,integrationTestAnnotationProcessor,jmhAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor -com.google.auto.value:auto-value-annotations:1.9=annotationProcessor,integrationTestAnnotationProcessor,jmhAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor -com.google.auto:auto-common:1.2.2=annotationProcessor,integrationTestAnnotationProcessor,jmhAnnotationProcessor,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,integrationTestAnnotationProcessor,jmhAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor -com.google.errorprone:error_prone_annotations:2.41.0=spotbugs -com.google.errorprone:error_prone_annotations:2.47.0=checkstyle -com.google.errorprone:error_prone_annotations:2.49.0=annotationProcessor,integrationTestAnnotationProcessor,jmhAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor -com.google.errorprone:error_prone_check_api:2.49.0=annotationProcessor,integrationTestAnnotationProcessor,jmhAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor -com.google.errorprone:error_prone_core:2.49.0=annotationProcessor,integrationTestAnnotationProcessor,jmhAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor -com.google.googlejavaformat:google-java-format:1.35.0=annotationProcessor,integrationTestAnnotationProcessor,jmhAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor -com.google.guava:failureaccess:1.0.3=annotationProcessor,checkstyle,integrationTestAnnotationProcessor,jmhAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor -com.google.guava:guava:33.5.0-jre=annotationProcessor,integrationTestAnnotationProcessor,jmhAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor -com.google.guava:guava:33.6.0-jre=checkstyle -com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,checkstyle,integrationTestAnnotationProcessor,jmhAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor -com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,integrationTestAnnotationProcessor,jmhAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor -com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,integrationTestAnnotationProcessor,jmhAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor -com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins -com.puppycrawl.tools:checkstyle:13.5.0=checkstyle -com.rabbitmq:amqp-client:5.27.1=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath -commons-beanutils:commons-beanutils:1.11.0=checkstyle -commons-codec:commons-codec:1.19.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath -commons-collections:commons-collections:3.2.2=checkstyle -commons-io:commons-io:2.20.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath -commons-io:commons-io:2.21.0=spotbugs -commons-logging:commons-logging:1.3.6=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath -info.picocli:picocli:4.7.7=checkstyle -io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,integrationTestAnnotationProcessor,jmhAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor -io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,integrationTestAnnotationProcessor,jmhAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor -io.micrometer:micrometer-commons:1.16.7=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath -io.micrometer:micrometer-core:1.16.7=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath -io.micrometer:micrometer-observation:1.16.7=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath -io.netty:netty-buffer:4.2.17.Final=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath -io.netty:netty-codec-base:4.2.17.Final=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath -io.netty:netty-codec-compression:4.2.17.Final=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath -io.netty:netty-codec-marshalling:4.2.17.Final=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath -io.netty:netty-codec-protobuf:4.2.17.Final=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath -io.netty:netty-codec:4.2.17.Final=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath -io.netty:netty-common:4.2.17.Final=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath -io.netty:netty-handler:4.2.17.Final=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath -io.netty:netty-resolver:4.2.17.Final=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath -io.netty:netty-transport-native-unix-common:4.2.17.Final=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath -io.netty:netty-transport:4.2.17.Final=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath -javax.inject:javax.inject:1=annotationProcessor,integrationTestAnnotationProcessor,jmhAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor -jaxen:jaxen:2.0.6=spotbugs -net.bytebuddy:byte-buddy:1.17.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -net.java.dev.jna:jna:5.18.1=integrationTestCompileClasspath,integrationTestRuntimeClasspath -net.sf.jopt-simple:jopt-simple:5.0.4=jmhAnnotationProcessor,jmhCompileClasspath,jmhRuntimeClasspath -net.sf.saxon:Saxon-HE:12.9=checkstyle,spotbugs -org.antlr:antlr4-runtime:4.13.2=checkstyle -org.apache.bcel:bcel:6.12.0=spotbugs -org.apache.commons:commons-compress:1.28.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath -org.apache.commons:commons-lang3:3.20.0=checkstyle,integrationTestCompileClasspath,integrationTestRuntimeClasspath,spotbugs -org.apache.commons:commons-math3:3.6.1=jmhAnnotationProcessor,jmhCompileClasspath,jmhRuntimeClasspath -org.apache.commons:commons-text:1.15.0=spotbugs -org.apache.commons:commons-text:1.3=checkstyle -org.apache.httpcomponents:httpclient:4.5.13=checkstyle -org.apache.httpcomponents:httpcore:4.4.16=checkstyle -org.apache.logging.log4j:log4j-api:2.25.5=spotbugs -org.apache.logging.log4j:log4j-core:2.25.5=spotbugs -org.apache.maven.doxia:doxia-core:1.12.0=checkstyle -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=integrationTestCompileClasspath,jmhCompileClasspath,testCompileClasspath -org.assertj:assertj-core:3.27.7=integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,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.3.0=checkstyle -org.dom4j:dom4j:2.2.0=spotbugs -org.hdrhistogram:HdrHistogram:2.2.2=integrationTestRuntimeClasspath,jmhRuntimeClasspath,runtimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath -org.javassist:javassist:3.28.0-GA=checkstyle -org.jetbrains:annotations:17.0.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath -org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,compileClasspath,integrationTestAnnotationProcessor,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhAnnotationProcessor,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testAnnotationProcessor,testCompileClasspath,testFixturesAnnotationProcessor,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath -org.junit.jupiter:junit-jupiter-api:6.0.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.junit.jupiter:junit-jupiter-engine:6.0.3=integrationTestRuntimeClasspath,jmhRuntimeClasspath,testRuntimeClasspath -org.junit.jupiter:junit-jupiter-params:6.0.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.junit.jupiter:junit-jupiter:6.0.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.junit.platform:junit-platform-commons:6.0.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.junit.platform:junit-platform-engine:6.0.3=integrationTestRuntimeClasspath,jmhRuntimeClasspath,testRuntimeClasspath -org.junit.platform:junit-platform-launcher:6.0.3=integrationTestRuntimeClasspath,jmhRuntimeClasspath,testRuntimeClasspath -org.junit:junit-bom:6.0.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.junit:junit-bom:6.1.0=spotbugs -org.latencyutils:LatencyUtils:2.0.3=integrationTestRuntimeClasspath,jmhRuntimeClasspath,runtimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath -org.mockito:mockito-core:5.20.0=mockitoAgent -org.openjdk.jmh:jmh-core:1.37=jmhAnnotationProcessor,jmhCompileClasspath,jmhRuntimeClasspath -org.openjdk.jmh:jmh-generator-annprocess:1.37=jmhAnnotationProcessor -org.opentest4j:opentest4j:1.3.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,testCompileClasspath,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,integrationTestAnnotationProcessor,jmhAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor -org.reflections:reflections:0.10.2=checkstyle -org.rnorth.duct-tape:duct-tape:1.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath -org.slf4j:slf4j-api:2.0.18=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,spotbugs,spotbugsSlf4j,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath -org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j -org.slf4j:slf4j-simple:2.0.18=checkstyle -org.springframework.amqp:spring-amqp:4.0.5=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath -org.springframework.amqp:spring-rabbit:4.0.5=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath -org.springframework:spring-aop:7.0.9=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath -org.springframework:spring-beans:7.0.9=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath -org.springframework:spring-context:7.0.9=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath -org.springframework:spring-core:7.0.9=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath -org.springframework:spring-expression:7.0.9=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath -org.springframework:spring-messaging:7.0.9=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath -org.springframework:spring-tx:7.0.9=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath -org.testcontainers:testcontainers-junit-jupiter:2.0.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath -org.testcontainers:testcontainers-rabbitmq:2.0.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath -org.testcontainers:testcontainers:2.0.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath -org.xmlresolver:xmlresolver:5.3.3=checkstyle,spotbugs -empty= diff --git a/src/messaging/messaging-rabbit/src/integrationTest/java/dev/caskeleton/messaging/rabbit/RabbitBrokerIT.java b/src/messaging/messaging-rabbit/src/integrationTest/java/dev/caskeleton/messaging/rabbit/RabbitBrokerIT.java deleted file mode 100644 index 7937f528..00000000 --- a/src/messaging/messaging-rabbit/src/integrationTest/java/dev/caskeleton/messaging/rabbit/RabbitBrokerIT.java +++ /dev/null @@ -1,232 +0,0 @@ -package dev.caskeleton.messaging.rabbit; - -import static org.assertj.core.api.Assertions.assertThat; - -import com.rabbitmq.client.AMQP; -import com.rabbitmq.client.Channel; -import com.rabbitmq.client.Connection; -import com.rabbitmq.client.ConnectionFactory; -import dev.caskeleton.messaging.api.ContentType; -import dev.caskeleton.messaging.api.MessageEnvelope; -import dev.caskeleton.messaging.api.MessageId; -import dev.caskeleton.messaging.api.MessageType; -import dev.caskeleton.messaging.api.ProducerId; -import dev.caskeleton.messaging.api.SchemaVersion; -import dev.caskeleton.messaging.api.TraceContext; -import dev.caskeleton.messaging.api.header.MessageHeaders; -import dev.caskeleton.messaging.api.publish.ConfirmationLevel; -import dev.caskeleton.messaging.api.publish.PublishCompletion; -import dev.caskeleton.messaging.api.publish.PublishOptions; -import dev.caskeleton.messaging.api.publish.PublishResult; -import dev.caskeleton.messaging.api.publish.RoutingOutcome; -import dev.caskeleton.messaging.schema.EncodedMessage; -import dev.caskeleton.messaging.testkit.DockerAvailability; -import dev.caskeleton.messaging.transport.TransportPublishRequest; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.time.Duration; -import java.time.Instant; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.CompletionStage; -import java.util.concurrent.TimeoutException; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.condition.EnabledIf; -import org.springframework.amqp.core.MessageProperties; -import org.testcontainers.junit.jupiter.Container; -import org.testcontainers.junit.jupiter.Testcontainers; -import org.testcontainers.rabbitmq.RabbitMQContainer; - -/** - * Certifies the RabbitMQ adapter against a live broker. - * - *

The test that matters is the unroutable one. AMQP delivers a {@code basic.return} - * before the confirm for a message no queue was bound to receive, and an adapter that - * completes on the confirm alone reports success for a message the broker threw away. No mock - * proves the ordering is handled correctly, because the ordering is the broker's behaviour. - */ -@Testcontainers -@EnabledIf("dockerAvailable") -class RabbitBrokerIT { - - private static final String EXCHANGE = "notification.work"; - private static final String BOUND_KEY = "email"; - private static final String UNBOUND_KEY = "nothing.is.bound.here"; - private static final String QUEUE = "notification.email.q"; - private static final Instant NOW = Instant.parse("2026-08-10T09:15:00Z"); - - @Container - private static final RabbitMQContainer RABBIT = new RabbitMQContainer("rabbitmq:4.3-management"); - - private Connection connection; - private Channel channel; - private RabbitMessagingTransport transport; - - static boolean dockerAvailable() { - return DockerAvailability.isAvailable(); - } - - @BeforeEach - void declareTopology() throws IOException, TimeoutException { - ConnectionFactory factory = new ConnectionFactory(); - factory.setHost(RABBIT.getHost()); - factory.setPort(RABBIT.getAmqpPort()); - factory.setUsername(RABBIT.getAdminUsername()); - factory.setPassword(RABBIT.getAdminPassword()); - connection = factory.newConnection(); - channel = connection.createChannel(); - - channel.exchangeDeclare(EXCHANGE, "direct", true); - channel.queueDeclare(QUEUE, true, false, false, Map.of("x-queue-type", "quorum")); - channel.queueBind(QUEUE, EXCHANGE, BOUND_KEY); - // The container is shared across the class, so a message left by an earlier test would make a - // later queue-depth assertion pass or fail for the wrong reason. - channel.queuePurge(QUEUE); - channel.confirmSelect(); - - transport = - new RabbitMessagingTransport( - "rabbit-primary", - 1, - new RabbitChannelPublisher() { - @Override - public long nextPublishSequence() { - return channel.getNextPublishSeqNo(); - } - - @Override - public void publish( - long sequence, - String exchange, - String routingKey, - org.springframework.amqp.core.Message message, - boolean mandatory) { - RabbitBrokerIT.this.publish(sequence, exchange, routingKey, message, mandatory); - } - }); - - channel.addConfirmListener( - (deliveryTag, multiple) -> transport.onConfirm(deliveryTag, true, Duration.ofMillis(1)), - (deliveryTag, multiple) -> transport.onConfirm(deliveryTag, false, Duration.ofMillis(1))); - channel.addReturnListener( - returned -> - transport.onReturn( - Long.parseLong(returned.getProperties().getHeaders().get("x-seq").toString()))); - } - - @AfterEach - void close() throws IOException, TimeoutException { - if (channel != null && channel.isOpen()) { - channel.close(); - } - if (connection != null && connection.isOpen()) { - connection.close(); - } - } - - @Test - void aRoutablePublishConfirmsWithReplicationEvidence() { - PublishResult result = await(transport.publish(request(BOUND_KEY))); - - assertThat(result.completion()).isEqualTo(PublishCompletion.CONFIRMED); - assertThat(result.routingOutcome()).isEqualTo(RoutingOutcome.ROUTED); - assertThat(result.evidence().confirmationLevel()) - .isEqualTo(ConfirmationLevel.REPLICATION_OR_PERSISTENCE_ACK); - } - - @Test - void anUnroutablePublishIsRejectedEvenThoughTheExchangeConfirmedIt() { - PublishResult result = await(transport.publish(request(UNBOUND_KEY))); - - assertThat(result.completion()) - .as("the exchange accepted it and the broker threw it away; that is not success") - .isEqualTo(PublishCompletion.REJECTED); - assertThat(result.routingOutcome()).isEqualTo(RoutingOutcome.UNROUTABLE); - assertThat(result.evidence().confirmationLevel()).isEqualTo(ConfirmationLevel.NONE); - } - - @Test - void aRoutablePublishReachesTheQueue() throws IOException { - await(transport.publish(request(BOUND_KEY))); - - assertThat(channel.messageCount(QUEUE)).isEqualTo(1); - } - - @Test - void anUnroutablePublishReachesNoQueue() throws IOException { - await(transport.publish(request(UNBOUND_KEY))); - - assertThat(channel.messageCount(QUEUE)).isZero(); - } - - /** - * Publishes and records the sequence number in a header. - * - *

A returned message arrives without its publish sequence number, so the adapter has to carry - * one itself to correlate the return with the pending publish. - */ - private void publish( - long sequence, - String exchange, - String routingKey, - org.springframework.amqp.core.Message message, - boolean mandatory) { - try { - MessageProperties source = message.getMessageProperties(); - AMQP.BasicProperties properties = - new AMQP.BasicProperties.Builder() - .messageId(source.getMessageId()) - .contentType(source.getContentType()) - .deliveryMode(2) - .headers(withSequence(source, sequence)) - .build(); - // No waitForConfirms: the coordinator completes the publish from the confirm listener, and - // blocking here would hold the calling thread through the round trip for no benefit. - channel.basicPublish(exchange, routingKey, mandatory, properties, message.getBody()); - } catch (IOException exception) { - throw new IllegalStateException("rabbit publish failed", exception); - } - } - - private static Map withSequence(MessageProperties source, long sequence) { - java.util.Map headers = new java.util.LinkedHashMap<>(source.getHeaders()); - headers.put("x-seq", Long.toString(sequence)); - return headers; - } - - private static PublishResult await( - CompletionStage stage) { - return stage.toCompletableFuture().join().result(); - } - - private TransportPublishRequest request(String routingKey) { - return new TransportPublishRequest( - RabbitFixtureProfiles.routingTo(EXCHANGE, routingKey, QUEUE), - envelope(), - PublishOptions.defaults()); - } - - private static MessageEnvelope envelope() { - return new MessageEnvelope<>( - MessageId.newId(), - new MessageType("order.created"), - new SchemaVersion(1), - NOW, - Optional.of(NOW), - new ProducerId("order-api"), - Optional.empty(), - Optional.empty(), - ContentType.JSON, - Optional.empty(), - Optional.empty(), - Optional.empty(), - TraceContext.none(), - MessageHeaders.empty(), - new EncodedMessage( - "{\"orderId\":\"o-1\"}".getBytes(StandardCharsets.UTF_8), - ContentType.JSON, - Optional.empty())); - } -} diff --git a/src/messaging/messaging-rabbit/src/integrationTest/java/dev/caskeleton/messaging/rabbit/RabbitFixtureProfiles.java b/src/messaging/messaging-rabbit/src/integrationTest/java/dev/caskeleton/messaging/rabbit/RabbitFixtureProfiles.java deleted file mode 100644 index da405309..00000000 --- a/src/messaging/messaging-rabbit/src/integrationTest/java/dev/caskeleton/messaging/rabbit/RabbitFixtureProfiles.java +++ /dev/null @@ -1,32 +0,0 @@ -package dev.caskeleton.messaging.rabbit; - -import dev.caskeleton.messaging.policy.DestinationProfile; -import dev.caskeleton.messaging.policy.PhysicalDestination; - -/** Builds destination profiles that vary only in their physical mapping. */ -final class RabbitFixtureProfiles { - - private RabbitFixtureProfiles() {} - - static DestinationProfile routingTo(String exchange, String routingKey, String queue) { - DestinationProfile base = RabbitProfileFixtures.workQueueDestination(); - return new DestinationProfile( - base.name(), - base.broker(), - base.kind(), - PhysicalDestination.rabbitQueue(exchange, routingKey, queue), - base.schema(), - base.deliveryGuarantee(), - base.orderingScope(), - base.externalSideEffectGuarantee(), - base.producer(), - base.consumer(), - base.retry(), - base.deadLetter(), - base.payload(), - base.tier(), - base.production(), - base.keyResolverConfigured(), - base.topologyAutoCreate()); - } -} diff --git a/src/messaging/messaging-rabbit/src/jmh/java/dev/caskeleton/messaging/rabbit/RabbitPublishBenchmark.java b/src/messaging/messaging-rabbit/src/jmh/java/dev/caskeleton/messaging/rabbit/RabbitPublishBenchmark.java deleted file mode 100644 index e8e2d460..00000000 --- a/src/messaging/messaging-rabbit/src/jmh/java/dev/caskeleton/messaging/rabbit/RabbitPublishBenchmark.java +++ /dev/null @@ -1,156 +0,0 @@ -package dev.caskeleton.messaging.rabbit; - -import dev.caskeleton.messaging.api.ContentType; -import dev.caskeleton.messaging.api.MessageEnvelope; -import dev.caskeleton.messaging.api.MessageId; -import dev.caskeleton.messaging.api.MessageType; -import dev.caskeleton.messaging.api.ProducerId; -import dev.caskeleton.messaging.api.SchemaVersion; -import dev.caskeleton.messaging.api.TraceContext; -import dev.caskeleton.messaging.api.destination.ConfirmationRequirement; -import dev.caskeleton.messaging.api.header.MessageHeaders; -import dev.caskeleton.messaging.schema.EncodedMessage; -import java.time.Duration; -import java.time.Instant; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import org.openjdk.jmh.annotations.Benchmark; -import org.openjdk.jmh.annotations.BenchmarkMode; -import org.openjdk.jmh.annotations.Fork; -import org.openjdk.jmh.annotations.Level; -import org.openjdk.jmh.annotations.Measurement; -import org.openjdk.jmh.annotations.Mode; -import org.openjdk.jmh.annotations.OutputTimeUnit; -import org.openjdk.jmh.annotations.Param; -import org.openjdk.jmh.annotations.Scope; -import org.openjdk.jmh.annotations.Setup; -import org.openjdk.jmh.annotations.State; -import org.openjdk.jmh.annotations.Warmup; -import org.openjdk.jmh.infra.Blackhole; - -/** - * Measures the RabbitMQ adapter's own cost per publish, with no broker in the loop. - * - *

The confirm coordinator is the interesting one here. Every publish registers a pending entry - * and every confirm resolves it, so its map operations run twice per message on the hot path — and - * because a confirm arrives on the connection thread while publishes arrive on caller threads, a - * regression there shows up as contention rather than as a slower method. - * - *

No channel and no network, for the same reason the Kafka benchmark has no producer: measuring - * the broker measures the environment. - */ -@BenchmarkMode(Mode.AverageTime) -@OutputTimeUnit(TimeUnit.NANOSECONDS) -@Warmup(iterations = 3, time = 1) -@Measurement(iterations = 5, time = 1) -@Fork(1) -@State(Scope.Benchmark) -public class RabbitPublishBenchmark { - - /** Payload sizes spanning the range a portable destination allows. */ - @Param({"256", "4096", "65536"}) - public int payloadBytes; - - private static final Instant NOW = Instant.parse("2026-08-10T09:15:00Z"); - private static final String EXCHANGE = "notification.work"; - private static final String ROUTING_KEY = "email"; - - private RabbitHeaderMapper headerMapper; - private RabbitPublishFailureClassifier classifier; - private MessageEnvelope envelope; - private RabbitConfirmCoordinator coordinator; - private long sequence; - - /** Builds the fixtures once so the measured methods allocate only what a publish allocates. */ - @Setup(Level.Trial) - public void setUp() { - headerMapper = new RabbitHeaderMapper(); - classifier = new RabbitPublishFailureClassifier(); - byte[] payload = new byte[payloadBytes]; - java.util.Arrays.fill(payload, (byte) 'x'); - envelope = - new MessageEnvelope<>( - MessageId.newId(), - new MessageType("email.requested"), - new SchemaVersion(1), - NOW, - Optional.of(NOW), - new ProducerId("notification-api"), - Optional.empty(), - Optional.empty(), - ContentType.JSON, - Optional.empty(), - Optional.empty(), - Optional.empty(), - TraceContext.none(), - MessageHeaders.empty(), - new EncodedMessage(payload, ContentType.JSON, Optional.empty())); - } - - /** Resets the coordinator per iteration so pending entries do not accumulate across runs. */ - @Setup(Level.Iteration) - public void resetCoordinator() { - coordinator = new RabbitConfirmCoordinator(); - sequence = 0; - } - - /** - * Measures mapping an envelope's reserved headers onto AMQP properties. - * - * @param blackhole consumes the result - */ - @Benchmark - public void mapHeaders(Blackhole blackhole) { - blackhole.consume(headerMapper.toProperties(envelope)); - } - - /** - * Measures one full register-then-confirm round trip through the coordinator. - * - *

Both halves together, because a benchmark of the registration alone would leave the pending - * map growing and report a cost that no real publish pays. - * - * @param blackhole consumes the result - */ - @Benchmark - public void registerAndConfirm(Blackhole blackhole) { - long current = ++sequence; - blackhole.consume( - coordinator.awaiting( - current, - EXCHANGE, - ROUTING_KEY, - ConfirmationRequirement.REPLICATION_OR_PERSISTENCE_ACK)); - coordinator.confirmed(current, true, Duration.ofMillis(1)); - } - - /** - * Measures the unroutable path, which resolves through a return before the confirm. - * - * @param blackhole consumes the result - */ - @Benchmark - public void registerReturnAndConfirm(Blackhole blackhole) { - long current = ++sequence; - blackhole.consume( - coordinator.awaiting( - current, - EXCHANGE, - ROUTING_KEY, - ConfirmationRequirement.REPLICATION_OR_PERSISTENCE_ACK)); - coordinator.returned(current); - coordinator.confirmed(current, true, Duration.ofMillis(1)); - } - - /** - * Measures classifying a lost confirm, which runs on every ambiguous publish. - * - * @param blackhole consumes the result - */ - @Benchmark - public void classifyLostConfirm(Blackhole blackhole) { - blackhole.consume( - classifier.classify( - new java.io.IOException("connection reset"), true, Duration.ofMillis(5))); - } -} diff --git a/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitBatchConsumerRegistrar.java b/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitBatchConsumerRegistrar.java deleted file mode 100644 index 68ab87a3..00000000 --- a/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitBatchConsumerRegistrar.java +++ /dev/null @@ -1,165 +0,0 @@ -package dev.caskeleton.messaging.rabbit; - -import dev.caskeleton.messaging.api.delivery.BatchDeliveryMetadata; -import dev.caskeleton.messaging.api.error.MessagingConfigurationException; -import dev.caskeleton.messaging.policy.DestinationProfile; -import java.time.Duration; -import java.time.Instant; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; -import java.util.Optional; - -/** - * Accumulates AMQP deliveries into batches, bounded by size and by age. - * - *

Unlike Kafka, RabbitMQ delivers one message at a time, so a batch here is built by the client - * rather than returned by a poll. That makes the age bound essential: without it, a queue that goes - * quiet leaves the last few messages sitting in the accumulator indefinitely, unacknowledged, until - * enough traffic arrives to fill a batch — which on a low-volume queue may be hours. - * - *

{@code settlableAsBatch} is reported false. AMQP's multiple-ack acknowledges every delivery up - * to a tag, which on a channel handling concurrent work settles messages the handler has not - * finished; the platform therefore acknowledges each delivery individually even when the handler - * saw them as a batch. - * - *

The accumulator is not thread-safe by design. It is driven from the single consumer callback - * thread for its channel, and adding synchronisation here would suggest it can be shared, which - * would interleave deliveries from different channels into one batch and lose their ordering. - */ -public final class RabbitBatchConsumerRegistrar { - - private final DestinationProfile profile; - private final int maxBatchSize; - private final Duration maxBatchAge; - private final List deliveryTags = new ArrayList<>(); - private Instant oldestArrival; - - /** - * Creates a batch accumulator for a destination. - * - * @param profile the validated destination profile - * @param maxBatchSize the largest batch handed to a handler - * @param maxBatchAge how long the oldest delivery may wait before the batch is released - */ - public RabbitBatchConsumerRegistrar( - DestinationProfile profile, int maxBatchSize, Duration maxBatchAge) { - this.profile = Objects.requireNonNull(profile, "profile must not be null"); - Objects.requireNonNull(maxBatchAge, "maxBatchAge must not be null"); - if (maxBatchSize < 1) { - throw new IllegalArgumentException("maxBatchSize must be at least 1"); - } - if (maxBatchAge.isNegative() || maxBatchAge.isZero()) { - throw new IllegalArgumentException( - "maxBatchAge must be positive; without it a quiet queue holds its last messages " - + "unacknowledged indefinitely"); - } - this.maxBatchSize = maxBatchSize; - this.maxBatchAge = maxBatchAge; - } - - /** - * Adds one delivery to the current batch. - * - * @param deliveryTag the AMQP delivery tag - * @param now the current instant - * @return the batch when it is ready to release, otherwise empty - */ - public Optional add(long deliveryTag, Instant now) { - Objects.requireNonNull(now, "now must not be null"); - if (deliveryTags.isEmpty()) { - oldestArrival = now; - } - deliveryTags.add(deliveryTag); - return deliveryTags.size() >= maxBatchSize ? Optional.of(release(now)) : Optional.empty(); - } - - /** - * Releases the current batch if its oldest delivery has waited long enough. - * - * @param now the current instant - * @return the batch when the age bound was reached, otherwise empty - */ - public Optional releaseIfStale(Instant now) { - Objects.requireNonNull(now, "now must not be null"); - if (deliveryTags.isEmpty()) { - return Optional.empty(); - } - return !now.isBefore(oldestArrival.plus(maxBatchAge)) - ? Optional.of(release(now)) - : Optional.empty(); - } - - /** - * Releases whatever has accumulated, for shutdown. - * - * @param now the current instant - * @return the batch when anything was pending - */ - public Optional drain(Instant now) { - Objects.requireNonNull(now, "now must not be null"); - return deliveryTags.isEmpty() ? Optional.empty() : Optional.of(release(now)); - } - - /** - * Returns how many deliveries are waiting in the accumulator. - * - * @return the pending delivery count - */ - public int pending() { - return deliveryTags.size(); - } - - /** - * Refuses batch consumption where the prefetch cannot hold a whole batch. - * - *

A prefetch below the batch size deadlocks: the accumulator waits for more deliveries the - * broker will not send until something is acknowledged, and nothing is acknowledged until the - * batch is released. - * - * @param prefetch the channel prefetch count - * @throws MessagingConfigurationException when the prefetch is too small - */ - public void requirePrefetchFor(int prefetch) { - if (prefetch < maxBatchSize) { - throw new MessagingConfigurationException( - "PREFETCH_BELOW_BATCH_SIZE", - "destination %s batches %d deliveries but the channel prefetch is %d; the accumulator " - .formatted(profile.name().value(), maxBatchSize, prefetch) - + "would wait for deliveries the broker will not send until something is acked"); - } - } - - private AmqpBatch release(Instant now) { - List released = List.copyOf(deliveryTags); - deliveryTags.clear(); - oldestArrival = null; - return new AmqpBatch( - released, - new BatchDeliveryMetadata( - profile.name(), - released.size(), - // One queue is one ordering unit, so an accumulated batch never spans two. - Optional.of(profile.physical().queue().orElse(profile.name().value())), - // AMQP multiple-ack settles everything up to a tag, including work still in flight. - false, - now)); - } - - /** - * One accumulated batch of AMQP deliveries. - * - * @param deliveryTags the delivery tags, in arrival order - * @param metadata the batch-wide metadata handed to the handler - */ - public record AmqpBatch(List deliveryTags, BatchDeliveryMetadata metadata) { - - public AmqpBatch { - Objects.requireNonNull(metadata, "metadata must not be null"); - deliveryTags = List.copyOf(deliveryTags); - if (deliveryTags.isEmpty()) { - throw new IllegalArgumentException("a released batch is never empty"); - } - } - } -} diff --git a/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitBrokerProfile.java b/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitBrokerProfile.java deleted file mode 100644 index e53d3774..00000000 --- a/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitBrokerProfile.java +++ /dev/null @@ -1,50 +0,0 @@ -package dev.caskeleton.messaging.rabbit; - -import java.time.Duration; -import java.util.List; -import java.util.Objects; - -/** - * The RabbitMQ client settings the platform is willing to run with. - * - * @param broker the logical broker name - * @param stable whether this profile claims the Stable guarantees - * @param production whether this profile is used in production - * @param addresses the broker addresses - * @param publisherConfirms whether correlated publisher confirms are on - * @param publisherReturns whether unroutable returns are delivered - * @param mandatory whether publishes are sent with the mandatory flag - * @param confirmTimeout how long to wait for a confirm - * @param autoAck whether the consumer acknowledges on delivery - * @param prefetch the consumer prefetch window - * @param quorumQueues whether durable work queues are declared as quorum queues - * @param tlsEnabled whether transport encryption is on - * @param authenticationEnabled whether broker authentication is on - */ -public record RabbitBrokerProfile( - String broker, - boolean stable, - boolean production, - List addresses, - boolean publisherConfirms, - boolean publisherReturns, - boolean mandatory, - Duration confirmTimeout, - boolean autoAck, - int prefetch, - boolean quorumQueues, - boolean tlsEnabled, - boolean authenticationEnabled) { - - public RabbitBrokerProfile { - Objects.requireNonNull(addresses, "addresses must not be null"); - Objects.requireNonNull(confirmTimeout, "confirmTimeout must not be null"); - if (broker == null || broker.isBlank()) { - throw new IllegalArgumentException("broker must not be blank"); - } - if (addresses.isEmpty()) { - throw new IllegalArgumentException("addresses must not be empty"); - } - addresses = List.copyOf(addresses); - } -} diff --git a/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitChannelPublisher.java b/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitChannelPublisher.java deleted file mode 100644 index 8fe08f25..00000000 --- a/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitChannelPublisher.java +++ /dev/null @@ -1,42 +0,0 @@ -package dev.caskeleton.messaging.rabbit; - -import org.springframework.amqp.core.Message; - -/** - * The channel operations the transport needs, split so the confirm cannot outrun its registration. - * - *

Reserving the sequence number is a separate call from publishing on purpose. A confirm can - * arrive on the connection thread before {@code basicPublish} has even returned, so a transport - * that registered its pending publish afterwards would drop that confirm and wait forever for one - * that already came. Reserving first closes that race. - */ -public interface RabbitChannelPublisher { - - /** - * Reserves the next publish sequence number without publishing. - * - * @return the sequence number the next publish will carry - */ - long nextPublishSequence(); - - /** - * Publishes a message under a previously reserved sequence number. - * - * @param sequence the reserved sequence number - * @param exchange the exchange to publish to - * @param routingKey the routing key - * @param message the AMQP message - * @param mandatory whether the broker must return an unroutable message - */ - void publish( - long sequence, String exchange, String routingKey, Message message, boolean mandatory); - - /** - * Closes the underlying channel. - * - *

A default no-op so an existing publisher keeps compiling, but the transport calls it: a - * transport whose {@code close} only flipped a boolean left the native channel open and every - * pending stage waiting for a confirm that would never arrive. - */ - default void close() {} -} diff --git a/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitConfirmCoordinator.java b/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitConfirmCoordinator.java deleted file mode 100644 index f65c9855..00000000 --- a/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitConfirmCoordinator.java +++ /dev/null @@ -1,279 +0,0 @@ -package dev.caskeleton.messaging.rabbit; - -import dev.caskeleton.messaging.api.destination.ConfirmationRequirement; -import dev.caskeleton.messaging.api.error.FailureCategory; -import dev.caskeleton.messaging.api.error.FailureDescriptor; -import dev.caskeleton.messaging.api.publish.ConfirmationLevel; -import dev.caskeleton.messaging.api.publish.PublishCompletion; -import dev.caskeleton.messaging.api.publish.PublishEvidence; -import dev.caskeleton.messaging.api.publish.PublishResult; -import dev.caskeleton.messaging.api.publish.RoutingOutcome; -import java.time.Duration; -import java.util.Objects; -import java.util.Optional; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CompletionStage; - -/** - * Correlates a RabbitMQ publish with its confirm and its possible return. - * - *

This is the piece that makes the Rabbit adapter honest. AMQP delivers a return before - * the confirm for an unroutable message, so a naive adapter that completes on the confirm reports - * success for a message the broker threw away. The coordinator therefore keeps each publish pending - * until the confirm arrives, and remembers whether a return was seen first. - * - *

The resulting outcomes are: confirmed and not returned is {@code CONFIRMED}; confirmed and - * returned is {@code REJECTED} with {@code UNROUTABLE}; nacked is {@code REJECTED}; and a confirm - * that never arrives is {@code AMBIGUOUS}, because the broker may still have stored it. - * - *

Implemented as a pure state machine over sequence numbers so the whole ordering, including the - * return-before-confirm case, is testable without a broker. - */ -public final class RabbitConfirmCoordinator { - - /** - * Pending publishes, ordered by sequence. - * - *

Ordered because a Rabbit confirm carries a {@code multiple} flag meaning "everything up to - * and including this tag". Resolving one sequence per confirm — which is what a hash map forces — - * leaves every earlier publish pending forever: the caller's stage never completes and the entry - * is never removed, so the map grows for the life of the connection. - */ - private final java.util.concurrent.ConcurrentSkipListMap pending = - new java.util.concurrent.ConcurrentSkipListMap<>(); - - /** - * Registers a publish awaiting its confirm. - * - * @param sequence the channel publish sequence number - * @param exchange the exchange published to - * @param routingKey the routing key used - * @param requirement the confirmation the profile demanded - * @return a stage completing when the confirm, return, or timeout resolves it - */ - public CompletionStage awaiting( - long sequence, String exchange, String routingKey, ConfirmationRequirement requirement) { - Objects.requireNonNull(exchange, "exchange must not be null"); - Objects.requireNonNull(routingKey, "routingKey must not be null"); - Objects.requireNonNull(requirement, "requirement must not be null"); - - PendingPublish publish = new PendingPublish(exchange, routingKey, requirement); - pending.put(sequence, publish); - return publish.completion; - } - - /** - * Records that the broker returned a message as unroutable. - * - *

The return alone does not complete the publish: the confirm still follows, and only the pair - * establishes that the broker both accepted and discarded it. - * - * @param sequence the publish sequence number - */ - public void returned(long sequence) { - PendingPublish publish = pending.get(sequence); - if (publish != null) { - publish.returned = true; - } - } - - /** - * Records a broker confirm. - * - * @param sequence the publish sequence number - * @param acknowledged true for an ack, false for a nack - * @param elapsed how long the publish took - */ - public void confirmed(long sequence, boolean acknowledged, Duration elapsed) { - confirmed(sequence, false, acknowledged, elapsed); - } - - /** - * Records a broker confirm, honouring the {@code multiple} flag. - * - * @param multiple true when the broker is confirming every sequence up to and including this one - */ - public void confirmed(long sequence, boolean multiple, boolean acknowledged, Duration elapsed) { - if (!multiple) { - PendingPublish publish = pending.remove(sequence); - if (publish != null) { - publish.completion.complete(publish.resolve(sequence, acknowledged, elapsed)); - } - return; - } - // headMap(tag, inclusive) is the whole point of the ordered map: the broker is confirming a - // range, and every entry in it must be resolved with the same verdict. - java.util.NavigableMap confirmed = pending.headMap(sequence, true); - for (Long pendingSequence : java.util.List.copyOf(confirmed.keySet())) { - PendingPublish publish = pending.remove(pendingSequence); - if (publish != null) { - publish.completion.complete(publish.resolve(pendingSequence, acknowledged, elapsed)); - } - } - } - - /** - * Completes a publish whose send failed synchronously. - * - *

The classifier's verdict is used as-is: it is the only thing that knows whether the frame - * can have reached the broker, and guessing here would either invent a rejection for a message - * that was stored or an ambiguity for one that never left. - * - * @param sequence the publish sequence number - * @param result the classified outcome - */ - public void sendFailed(long sequence, PublishResult result) { - PendingPublish publish = pending.remove(sequence); - if (publish != null) { - publish.completion.complete(result); - } - } - - /** - * Completes every pending publish because the channel is gone. - * - *

Ambiguous, not rejected: the frames were written, and a channel that closes afterwards says - * nothing about whether the broker stored them. Leaving them pending — which is what close used - * to do — hangs every caller holding a stage. - * - * @param elapsed how long the publishes had been waiting - * @return how many stages were completed - */ - public int channelClosed(Duration elapsed) { - int drained = 0; - for (Long sequence : java.util.List.copyOf(pending.keySet())) { - PendingPublish publish = pending.remove(sequence); - if (publish != null) { - publish.completion.complete(publish.resolveChannelClosed(sequence, elapsed)); - drained++; - } - } - return drained; - } - - /** - * Records that the confirm never arrived within the deadline. - * - * @param sequence the publish sequence number - * @param elapsed how long was waited - */ - public void timedOut(long sequence, Duration elapsed) { - PendingPublish publish = pending.remove(sequence); - if (publish == null) { - return; - } - publish.completion.complete( - new PublishResult( - PublishCompletion.AMBIGUOUS, - PublishEvidence.ambiguous(), - RoutingOutcome.UNKNOWN, - Optional.empty(), - 1, - elapsed, - Optional.of( - FailureDescriptor.of( - FailureCategory.AMBIGUOUS, - "RABBIT_CONFIRM_TIMEOUT", - "no publisher confirm arrived before the deadline")))); - } - - /** - * Returns how many publishes are awaiting a confirm. - * - * @return the pending count - */ - public int pendingCount() { - return pending.size(); - } - - /** One publish waiting for its confirm, and whether a return arrived first. */ - private static final class PendingPublish { - - private final String exchange; - private final String routingKey; - private final ConfirmationRequirement requirement; - private final CompletableFuture completion = new CompletableFuture<>(); - - private volatile boolean returned; - - private PendingPublish( - String exchange, String routingKey, ConfirmationRequirement requirement) { - this.exchange = exchange; - this.routingKey = routingKey; - this.requirement = requirement; - } - - /** The channel closed with this publish still awaiting its confirm. */ - private PublishResult resolveChannelClosed(long sequence, Duration elapsed) { - return new PublishResult( - PublishCompletion.AMBIGUOUS, - PublishEvidence.ambiguous(), - RoutingOutcome.UNKNOWN, - Optional.of(new RabbitPublishReference(exchange, routingKey, sequence)), - 1, - elapsed, - Optional.of( - FailureDescriptor.of( - FailureCategory.AMBIGUOUS, - "RABBIT_CHANNEL_CLOSED", - "the channel closed before the broker confirmed this publish"))); - } - - private PublishResult resolve(long sequence, boolean acknowledged, Duration elapsed) { - RabbitPublishReference position = new RabbitPublishReference(exchange, routingKey, sequence); - - if (!acknowledged) { - return new PublishResult( - PublishCompletion.REJECTED, - // Transmitted, not "not transmitted": a NACK is the broker's answer to a frame it - // received. Recording it as never sent contradicts the very evidence that produced it, - // and a caller reading the evidence would conclude the message can be re-sent freely. - new PublishEvidence( - true, - dev.caskeleton.messaging.api.publish.TransmissionEvidence.TRANSMITTED, - false, - ConfirmationLevel.NONE), - RoutingOutcome.UNKNOWN, - Optional.of(position), - 1, - elapsed, - Optional.of( - FailureDescriptor.of( - FailureCategory.PERMANENT_BUSINESS, - "RABBIT_NACK", - "the broker negatively acknowledged the publish"))); - } - if (returned) { - return new PublishResult( - PublishCompletion.REJECTED, - new PublishEvidence( - true, - dev.caskeleton.messaging.api.publish.TransmissionEvidence.TRANSMITTED, - false, - ConfirmationLevel.NONE), - RoutingOutcome.UNROUTABLE, - Optional.of(position), - 1, - elapsed, - Optional.of( - FailureDescriptor.of( - FailureCategory.PERMANENT_BUSINESS, - "RABBIT_UNROUTABLE", - "the exchange accepted the publish but no queue was bound"))); - } - - ConfirmationLevel level = - requirement == ConfirmationRequirement.REPLICATION_OR_PERSISTENCE_ACK - ? ConfirmationLevel.REPLICATION_OR_PERSISTENCE_ACK - : ConfirmationLevel.BROKER_ACK; - return new PublishResult( - PublishCompletion.CONFIRMED, - PublishEvidence.confirmed(level), - RoutingOutcome.ROUTED, - Optional.of(position), - 1, - elapsed, - Optional.empty()); - } - } -} diff --git a/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitConsumerRegistrar.java b/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitConsumerRegistrar.java deleted file mode 100644 index 18529660..00000000 --- a/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitConsumerRegistrar.java +++ /dev/null @@ -1,238 +0,0 @@ -package dev.caskeleton.messaging.rabbit; - -import dev.caskeleton.messaging.api.error.FailureCategory; -import dev.caskeleton.messaging.api.error.FailureDescriptor; -import dev.caskeleton.messaging.api.settlement.SettlementCompletion; -import dev.caskeleton.messaging.api.settlement.SettlementEvidence; -import dev.caskeleton.messaging.api.settlement.SettlementResult; -import dev.caskeleton.messaging.transport.GracefulShutdownCoordinator; -import dev.caskeleton.messaging.transport.TransportConsumerRegistration; -import dev.caskeleton.messaging.transport.TransportConsumerSpec; -import dev.caskeleton.messaging.transport.TransportDelivery; -import dev.caskeleton.messaging.transport.TransportSettlement; -import java.time.Duration; -import java.time.Instant; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CompletionStage; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.atomic.AtomicBoolean; -import org.springframework.amqp.core.Message; - -/** - * The RabbitMQ consumer runtime. - * - *

Deliveries arrive from the listener container and are handed to the platform with a settlement - * handle that is bound to one delivery tag and refuses a second terminal call. Duplicating a {@code - * basic.ack} on a reused tag acknowledges a different message, which shows up as - * unexplained loss under load, far from its cause. - * - *

Consumption stops the moment a drain begins, but deliveries already in flight are allowed to - * finish. Rejecting an in-flight delivery at shutdown would either lose it or duplicate its side - * effect, depending on where the handler had got to. - */ -public final class RabbitConsumerRegistrar implements TransportConsumerRegistration { - - private final TransportConsumerSpec spec; - private final RabbitDeliveryMapper deliveryMapper; - private final RabbitSettlementOperations operations; - private final GracefulShutdownCoordinator shutdown; - private final Set pausedScopes = ConcurrentHashMap.newKeySet(); - private final AtomicBoolean active = new AtomicBoolean(true); - - /** - * Creates a consumer runtime. - * - * @param spec what to consume and where to deliver it - * @param operations the channel operations a settlement drives - * @param shutdown the drain coordinator - */ - public RabbitConsumerRegistrar( - TransportConsumerSpec spec, - RabbitSettlementOperations operations, - GracefulShutdownCoordinator shutdown) { - this(spec, operations, shutdown, new RabbitDeliveryMapper()); - } - - /** - * Creates a consumer runtime with an explicit delivery mapper. - * - * @param spec what to consume and where to deliver it - * @param operations the channel operations a settlement drives - * @param shutdown the drain coordinator - * @param deliveryMapper rebuilds envelopes from AMQP messages - */ - public RabbitConsumerRegistrar( - TransportConsumerSpec spec, - RabbitSettlementOperations operations, - GracefulShutdownCoordinator shutdown, - RabbitDeliveryMapper deliveryMapper) { - this.spec = Objects.requireNonNull(spec, "spec must not be null"); - this.operations = Objects.requireNonNull(operations, "operations must not be null"); - this.shutdown = Objects.requireNonNull(shutdown, "shutdown must not be null"); - this.deliveryMapper = Objects.requireNonNull(deliveryMapper, "deliveryMapper is required"); - } - - /** - * Handles one delivery pushed from the listener container. - * - *

Returns whether the delivery was accepted. A refusal means the runtime is draining or the - * queue is paused, and the caller must leave the message unacknowledged so the broker redelivers - * it. - * - * @param message the AMQP message - * @param now the current instant - * @return true when the delivery was dispatched - */ - public boolean onMessage(Message message, Instant now) { - Objects.requireNonNull(message, "message must not be null"); - Objects.requireNonNull(now, "now must not be null"); - - String queue = - Optional.ofNullable(message.getMessageProperties().getConsumerQueue()).orElse(""); - if (!active.get()) { - // close() only flipped a flag and onMessage never read it, so a delivery arriving after - // close was accepted, dispatched, and settled against a controller that was shutting down. - return false; - } - if (pausedScopes.contains(queue) || pausedScopes.contains("")) { - return false; - } - if (!shutdown.tryBeginWork()) { - return false; - } - - long tag = message.getMessageProperties().getDeliveryTag(); - try { - TransportDelivery delivery; - try { - // The narrow catch. One catch around decode, the handler and the settlement meant a - // business failure or an ACK that could not be written was recorded as an undecodable - // payload and discarded — a message that should have been retried, deleted instead. - delivery = - new TransportDelivery( - deliveryMapper.toEnvelope(message), - deliveryMapper.toMetadata(spec.profile().name(), message, now), - new ControllerBackedSettlement(tag)); - } catch (RuntimeException undecodable) { - // Genuinely undecodable: it will fail the same way on every redelivery, so requeueing is a - // hot loop. Discarding is right here and only here. - operations - .discard( - tag, - FailureDescriptor.of( - FailureCategory.DESERIALIZATION, - "RABBIT_UNDECODABLE", - "the message could not be decoded into an envelope")) - .toCompletableFuture() - .join(); - return true; - } - - ControllerBackedSettlement settlement = (ControllerBackedSettlement) delivery.settlement(); - try { - spec.sink().apply(delivery).toCompletableFuture().join(); - } catch (RuntimeException handlerFailed) { - // A handler failure is a retry, not a discard. - requeueQuietly(settlement); - return true; - } - if (!settlement.wasSettled()) { - // A handler that completed without settling has not said what to do with the message. - // Acknowledging on its behalf would silently drop it; the contract violation is surfaced - // as a requeue so the message survives while somebody fixes the handler. - requeueQuietly(settlement); - } - return true; - } finally { - shutdown.endWork(); - } - } - - /** Requeues without letting a settlement failure become the caller's problem. */ - private void requeueQuietly(ControllerBackedSettlement settlement) { - try { - settlement.requeue(Duration.ZERO).toCompletableFuture().join(); - } catch (RuntimeException settlementFailed) { - // The broker connection is the thing that failed. There is nothing left to try here, and - // the delivery stays unsettled — which is what redelivery is for. - return; - } - } - - @Override - public CompletionStage pause(String scope) { - pausedScopes.add(scope == null ? "" : scope); - return CompletableFuture.completedFuture(null); - } - - @Override - public CompletionStage resume(String scope) { - pausedScopes.remove(scope == null ? "" : scope); - return CompletableFuture.completedFuture(null); - } - - /** - * Reports whether a scope is currently paused. - * - * @param scope the queue, or an empty string for all - * @return true while paused - */ - public boolean isPaused(String scope) { - return pausedScopes.contains(scope == null ? "" : scope); - } - - @Override - public boolean isActive() { - return active.get(); - } - - @Override - public void close() { - active.set(false); - } - - /** Adapts the transport settlement SPI onto the one-terminal-call controller. */ - private final class ControllerBackedSettlement implements TransportSettlement { - - private final RabbitSettlementController controller; - - private ControllerBackedSettlement(long deliveryTag) { - this.controller = new RabbitSettlementController(deliveryTag, operations); - } - - private boolean wasSettled() { - return controller.isSettled(); - } - - @Override - public CompletionStage acknowledge() { - return controller.ack(); - } - - @Override - public CompletionStage requeue(Duration delay) { - if (!shutdown.mayCreateRetryAttempt()) { - return CompletableFuture.completedFuture( - new SettlementResult( - SettlementCompletion.UNKNOWN, - SettlementEvidence.unknown(), - Optional.of( - FailureDescriptor.of( - FailureCategory.AMBIGUOUS, - "RABBIT_DRAINING", - "no retry attempt is created while the consumer is draining")))); - } - return controller.retry(delay); - } - - @Override - public CompletionStage discard() { - return controller.reject( - FailureDescriptor.of( - FailureCategory.PERMANENT_BUSINESS, "RABBIT_DISCARDED", "the message was discarded")); - } - } -} diff --git a/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitDeadLetterPublisher.java b/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitDeadLetterPublisher.java deleted file mode 100644 index e534a912..00000000 --- a/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitDeadLetterPublisher.java +++ /dev/null @@ -1,130 +0,0 @@ -package dev.caskeleton.messaging.rabbit; - -import dev.caskeleton.messaging.api.delivery.MessageDelivery; -import dev.caskeleton.messaging.api.error.FailureDescriptor; -import dev.caskeleton.messaging.api.publish.ConfirmationLevel; -import dev.caskeleton.messaging.api.publish.PublishCompletion; -import dev.caskeleton.messaging.api.publish.PublishEvidence; -import dev.caskeleton.messaging.api.publish.PublishResult; -import dev.caskeleton.messaging.api.publish.RoutingOutcome; -import dev.caskeleton.messaging.api.publish.TransmissionEvidence; -import dev.caskeleton.messaging.policy.DeadLetterOrchestrator; -import dev.caskeleton.messaging.policy.DeadLetterResult; -import dev.caskeleton.messaging.policy.DestinationProfile; -import dev.caskeleton.messaging.policy.SourceSettlement; -import dev.caskeleton.messaging.schema.EncodedMessage; -import java.time.Duration; -import java.util.Objects; -import java.util.Optional; -import java.util.concurrent.CompletionStage; - -/** - * The RabbitMQ entry point to dead lettering. - * - *

Delegates to the shared orchestrator, exactly as the Kafka adapter does, even though RabbitMQ - * has native dead-lettering available. The native path is only taken where {@link - * RabbitNativeDeadLetterCapability} has verified a queue is bound to the dead-letter exchange — - * everywhere else the broker would discard the message silently while the reject still succeeded, - * and the platform's publish-then-settle ordering is what prevents that. - * - *

Which path is taken is decided here rather than by each call site, so a handler cannot - * accidentally reject a message on a destination whose dead-letter exchange goes nowhere. - */ -public final class RabbitDeadLetterPublisher { - - private final DeadLetterOrchestrator orchestrator; - private final RabbitNativeDeadLetterCapability nativeCapability; - private final NativeReject nativeReject; - - /** - * Creates a Rabbit dead letter publisher. - * - * @param orchestrator the shared dead letter orchestrator - * @param nativeCapability decides whether the broker's own dead-lettering may be trusted - * @param nativeReject performs a broker-side reject - */ - public RabbitDeadLetterPublisher( - DeadLetterOrchestrator orchestrator, - RabbitNativeDeadLetterCapability nativeCapability, - NativeReject nativeReject) { - this.orchestrator = Objects.requireNonNull(orchestrator, "orchestrator must not be null"); - this.nativeCapability = Objects.requireNonNull(nativeCapability, "nativeCapability required"); - this.nativeReject = Objects.requireNonNull(nativeReject, "nativeReject must not be null"); - } - - /** - * Dead letters one delivery, by whichever path is safe for this destination. - * - * @param profile the source destination profile - * @param delivery the failed delivery - * @param failure the sanitized failure - * @param deliveryTag the AMQP delivery tag to reject, when taking the native path - * @param settlement the source settlement callback - * @return a stage completing with the dead letter outcome - */ - public CompletionStage deadLetter( - DestinationProfile profile, - MessageDelivery delivery, - FailureDescriptor failure, - long deliveryTag, - SourceSettlement settlement) { - Objects.requireNonNull(profile, "profile must not be null"); - Objects.requireNonNull(delivery, "delivery must not be null"); - Objects.requireNonNull(failure, "failure must not be null"); - - if (nativeCapability.requiresPlatformPublish()) { - return orchestrator.deadLetter(profile, delivery, failure, settlement); - } - // The broker moves the message and settles the source in one operation. Safe only because the - // capability check confirmed a queue is bound to the dead letter exchange. - return nativeReject.reject(deliveryTag).thenApply(moved -> nativelyRouted()); - } - - /** - * Describes what a broker-side reject actually proves. - * - *

{@link ConfirmationLevel#BROKER_ACK}, not replication. RabbitMQ issues no publisher confirm - * for the internal hop to the dead-letter exchange, so the evidence available is that the broker - * accepted the reject — reporting it as a replication acknowledgement would claim a guarantee no - * part of this path provides. - * - * @return the dead letter outcome for the native path - */ - private static DeadLetterResult nativelyRouted() { - return new DeadLetterResult( - new PublishResult( - PublishCompletion.CONFIRMED, - new PublishEvidence( - true, TransmissionEvidence.TRANSMITTED, true, ConfirmationLevel.BROKER_ACK), - RoutingOutcome.ROUTED, - Optional.empty(), - 1, - Duration.ZERO, - Optional.empty()), - // The reject settles the source as part of the same operation, so there is no window in - // which the message is neither parked nor deliverable. - true); - } - - /** - * Returns why the platform is publishing rather than letting the broker route. - * - * @return the sanitized reason, empty when the native path is in use - */ - public String pathExplanation() { - return nativeCapability.reasonForPlatformPublish(); - } - - /** A broker-side reject that routes the message to the dead letter exchange. */ - @FunctionalInterface - public interface NativeReject { - - /** - * Rejects one delivery without requeueing it. - * - * @param deliveryTag the AMQP delivery tag - * @return a stage completing once the broker has taken the reject - */ - CompletionStage reject(long deliveryTag); - } -} diff --git a/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitDeliveryMapper.java b/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitDeliveryMapper.java deleted file mode 100644 index 0572c18c..00000000 --- a/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitDeliveryMapper.java +++ /dev/null @@ -1,195 +0,0 @@ -package dev.caskeleton.messaging.rabbit; - -import dev.caskeleton.messaging.api.CausationId; -import dev.caskeleton.messaging.api.ContentType; -import dev.caskeleton.messaging.api.CorrelationId; -import dev.caskeleton.messaging.api.MessageEnvelope; -import dev.caskeleton.messaging.api.MessageId; -import dev.caskeleton.messaging.api.MessageType; -import dev.caskeleton.messaging.api.ProducerId; -import dev.caskeleton.messaging.api.SchemaVersion; -import dev.caskeleton.messaging.api.TenantContext; -import dev.caskeleton.messaging.api.TraceContext; -import dev.caskeleton.messaging.api.delivery.DeliveryMetadata; -import dev.caskeleton.messaging.api.destination.DestinationName; -import dev.caskeleton.messaging.api.error.MessageValidationException; -import dev.caskeleton.messaging.api.header.ReservedHeaders; -import dev.caskeleton.messaging.schema.EncodedMessage; -import java.time.Instant; -import java.util.Objects; -import java.util.Optional; -import java.util.UUID; -import org.springframework.amqp.core.Message; -import org.springframework.amqp.core.MessageProperties; - -/** - * Rebuilds a platform envelope from an AMQP message. - * - *

The payload stays encoded so a codec failure is classified by the platform and parked, rather - * than surfacing as an AMQP listener exception the container would requeue in a hot loop. - * - *

The delivery attempt comes from the platform's own retry header rather than from AMQP's {@code - * redelivered} flag. That flag only says "this message was delivered before", not how many times, - * and it resets when a message travels through a retry queue. - */ -public final class RabbitDeliveryMapper { - - private final RabbitHeaderMapper headerMapper; - - /** Creates a mapper with the default header mapper. */ - public RabbitDeliveryMapper() { - this(new RabbitHeaderMapper()); - } - - /** - * Creates a mapper with an explicit header mapper. - * - * @param headerMapper the header mapper - */ - public RabbitDeliveryMapper(RabbitHeaderMapper headerMapper) { - this.headerMapper = Objects.requireNonNull(headerMapper, "headerMapper must not be null"); - } - - /** - * Converts an AMQP message into an envelope. - * - * @param message the AMQP message - * @return the still-encoded envelope - */ - public MessageEnvelope toEnvelope(Message message) { - Objects.requireNonNull(message, "message must not be null"); - MessageProperties properties = message.getMessageProperties(); - - ContentType contentType = - new ContentType( - Optional.ofNullable(headerMapper.value(properties, ReservedHeaders.CONTENT_TYPE)) - .or(() -> Optional.ofNullable(properties.getContentType())) - .orElse(ContentType.JSON.value())); - - byte[] payload = message.getBody() == null ? new byte[0] : message.getBody(); - Instant producedAt = instant(properties, ReservedHeaders.PRODUCED_AT); - - return new MessageEnvelope<>( - new MessageId(uuid(properties, ReservedHeaders.MESSAGE_ID)), - new MessageType(required(properties, ReservedHeaders.MESSAGE_TYPE)), - new SchemaVersion(intValue(properties, ReservedHeaders.SCHEMA_VERSION)), - producedAt, - Optional.ofNullable(headerMapper.value(properties, ReservedHeaders.OCCURRED_AT)) - .map(Instant::parse), - new ProducerId( - Optional.ofNullable(headerMapper.value(properties, ReservedHeaders.PRODUCER)) - .orElse("unknown")), - Optional.ofNullable(headerMapper.value(properties, ReservedHeaders.CORRELATION_ID)) - .map(CorrelationId::new), - Optional.ofNullable(headerMapper.value(properties, ReservedHeaders.CAUSATION_ID)) - .map(value -> new CausationId(new MessageId(UUID.fromString(value)))), - contentType, - Optional.ofNullable(headerMapper.value(properties, ReservedHeaders.PARTITION_KEY)), - Optional.ofNullable(headerMapper.value(properties, ReservedHeaders.ORDERING_KEY)), - Optional.ofNullable(headerMapper.value(properties, ReservedHeaders.TENANT)) - .map(TenantContext::new), - new TraceContext( - Optional.ofNullable(headerMapper.value(properties, ReservedHeaders.TRACEPARENT)), - Optional.ofNullable(headerMapper.value(properties, ReservedHeaders.TRACESTATE)), - Optional.ofNullable(headerMapper.value(properties, ReservedHeaders.BAGGAGE))), - headerMapper.carriedForward(properties), - new EncodedMessage(payload, contentType, Optional.empty())); - } - - /** - * Builds the delivery metadata for an AMQP message. - * - * @param destination the logical destination - * @param message the AMQP message - * @param receivedAt when the consumer received it - * @return the delivery metadata - */ - public DeliveryMetadata toMetadata( - DestinationName destination, Message message, Instant receivedAt) { - MessageProperties properties = message.getMessageProperties(); - int attempt = attemptOf(properties); - - return new DeliveryMetadata( - destination, - attempt, - attempt > 1, - Optional.of( - new RabbitPublishReference( - Optional.ofNullable(properties.getReceivedExchange()).orElse(""), - Optional.ofNullable(properties.getReceivedRoutingKey()).orElse(""), - Math.max(0, properties.getDeliveryTag()))), - Optional.ofNullable(properties.getConsumerQueue()), - Optional.ofNullable(properties.getConsumerTag()), - receivedAt); - } - - /** - * Returns the attempt a message carries, counting the first delivery as one. - * - * @param properties the message properties - * @return the attempt number - */ - public int attemptOf(MessageProperties properties) { - String value = headerMapper.value(properties, ReservedHeaders.RETRY_ATTEMPT); - if (value == null) { - return 1; - } - try { - int attempt = Integer.parseInt(value); - if (attempt < 1) { - throw new NumberFormatException("attempt " + attempt); - } - return attempt; - } catch (NumberFormatException malformed) { - // Fail closed. Resetting to 1 restarts the retry budget on every redelivery, so a message - // that should have been dead-lettered is retried forever — and the header is - // caller-influenced, which turns "unreadable" into a way to defeat the cap. - throw new dev.caskeleton.messaging.api.error.MessagingConfigurationException( - "RETRY_ATTEMPT_MALFORMED", - "the retry attempt header is not a positive integer; the message is quarantined rather" - + " than restarting its retry budget"); - } - } - - private String required(MessageProperties properties, String name) { - String value = headerMapper.value(properties, name); - if (value == null || value.isBlank()) { - throw new MessageValidationException( - "RABBIT_HEADER_MISSING", "message is missing the required header " + name); - } - return value; - } - - private UUID uuid(MessageProperties properties, String name) { - try { - return UUID.fromString(required(properties, name)); - } catch (IllegalArgumentException exception) { - throw new MessageValidationException( - "RABBIT_HEADER_MALFORMED", "header " + name + " is not a UUID", exception); - } - } - - private int intValue(MessageProperties properties, String name) { - try { - return Integer.parseInt(required(properties, name)); - } catch (NumberFormatException exception) { - throw new MessageValidationException( - "RABBIT_HEADER_MALFORMED", "header " + name + " is not an integer", exception); - } - } - - private Instant instant(MessageProperties properties, String name) { - String value = headerMapper.value(properties, name); - if (value == null || value.isBlank()) { - return Optional.ofNullable(properties.getTimestamp()) - .map(java.util.Date::toInstant) - .orElse(Instant.EPOCH); - } - try { - return Instant.parse(value); - } catch (java.time.format.DateTimeParseException exception) { - throw new MessageValidationException( - "RABBIT_HEADER_MALFORMED", "header " + name + " is not an instant", exception); - } - } -} diff --git a/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitHeaderMapper.java b/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitHeaderMapper.java deleted file mode 100644 index dc5124c4..00000000 --- a/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitHeaderMapper.java +++ /dev/null @@ -1,180 +0,0 @@ -package dev.caskeleton.messaging.rabbit; - -import dev.caskeleton.messaging.api.MessageEnvelope; -import dev.caskeleton.messaging.api.header.CanonicalEnvelopeHeaders; -import dev.caskeleton.messaging.api.header.HeaderName; -import dev.caskeleton.messaging.api.header.HeaderValue; -import dev.caskeleton.messaging.api.header.MessageHeaders; -import dev.caskeleton.messaging.api.header.ReservedHeaders; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Objects; -import org.springframework.amqp.core.MessageProperties; - -/** - * Maps envelope identity onto AMQP message properties and back. - * - *

Identity goes in headers, not in the payload, so a consumer can classify and park a message it - * cannot deserialize. The AMQP {@code message-id} and {@code correlation-id} properties are also - * populated, because management UIs and tracing tools read those and not the platform's headers — - * but the platform's own headers stay authoritative, since AMQP's properties have no schema version - * or producer field. - */ -public final class RabbitHeaderMapper { - - /** - * Writes an envelope's identity into AMQP message properties. - * - * @param envelope the envelope being published - * @return the message properties - */ - public MessageProperties toProperties(MessageEnvelope envelope) { - Objects.requireNonNull(envelope, "envelope must not be null"); - MessageProperties properties = new MessageProperties(); - - properties.setMessageId(envelope.messageId().value().toString()); - properties.setContentType(envelope.contentType().value()); - properties.setTimestamp(java.util.Date.from(envelope.producedAt())); - properties.setDeliveryMode(org.springframework.amqp.core.MessageDeliveryMode.PERSISTENT); - - setHeader(properties, ReservedHeaders.MESSAGE_ID, envelope.messageId().value().toString()); - setHeader(properties, ReservedHeaders.MESSAGE_TYPE, envelope.messageType().value()); - setHeader( - properties, - ReservedHeaders.SCHEMA_VERSION, - Integer.toString(envelope.schemaVersion().value())); - setHeader(properties, ReservedHeaders.PRODUCER, envelope.producer().value()); - setHeader(properties, ReservedHeaders.PRODUCED_AT, envelope.producedAt().toString()); - setHeader(properties, ReservedHeaders.CONTENT_TYPE, envelope.contentType().value()); - - envelope - .occurredAt() - .ifPresent(value -> setHeader(properties, ReservedHeaders.OCCURRED_AT, value.toString())); - envelope - .correlationId() - .ifPresent( - value -> { - properties.setCorrelationId(value.value()); - setHeader(properties, ReservedHeaders.CORRELATION_ID, value.value()); - }); - envelope - .causationId() - .ifPresent( - value -> - setHeader( - properties, ReservedHeaders.CAUSATION_ID, value.value().value().toString())); - envelope - .partitionKey() - .ifPresent(value -> setHeader(properties, ReservedHeaders.PARTITION_KEY, value)); - envelope - .orderingKey() - .ifPresent(value -> setHeader(properties, ReservedHeaders.ORDERING_KEY, value)); - // Written for the same reason as on the other broker: an AMQP message carries no ambient - // tenant, so a tenant left off the wire is a tenant the consumed envelope does not have. - envelope - .tenantContext() - .ifPresent(value -> setHeader(properties, ReservedHeaders.TENANT, value.tenantId())); - envelope - .traceContext() - .traceparent() - .ifPresent(value -> setHeader(properties, ReservedHeaders.TRACEPARENT, value)); - envelope - .traceContext() - .tracestate() - .ifPresent(value -> setHeader(properties, ReservedHeaders.TRACESTATE, value)); - envelope - .traceContext() - .baggage() - .ifPresent(value -> setHeader(properties, ReservedHeaders.BAGGAGE, value)); - - // The envelope's header map is written last, so an unchecked name would overwrite the canonical - // reserved value the platform just wrote. A forged `msg.id` corrupts another message's inbox - // deduplication, not merely its own delivery. - // - // Only names that restate an envelope field are refused. Retry attempt, failure and redrive - // bookkeeping have no envelope field to be read back from, so refusing them would make every - // retry-queue and dead-letter re-publish fail on the guard meant to protect identity. - envelope - .headers() - .asMap() - .forEach( - (name, value) -> { - if (CanonicalEnvelopeHeaders.restatesEnvelopeField(name.value())) { - throw new dev.caskeleton.messaging.api.error.MessagingConfigurationException( - "RESERVED_HEADER_FORGED", - "header '" - + name.value() - + "' restates a value the envelope already carries; the canonical value is" - + " written by the platform and must not be overridable by message content"); - } - setHeader(properties, name.value(), value.value()); - }); - - return properties; - } - - /** - * Reads AMQP headers back into a platform header map. - * - * @param properties the message properties - * @return the platform headers, including reserved names - */ - public MessageHeaders fromProperties(MessageProperties properties) { - Objects.requireNonNull(properties, "properties must not be null"); - Map values = new LinkedHashMap<>(); - properties - .getHeaders() - .forEach( - (name, value) -> { - if (value != null) { - values.put(new HeaderName(name), new HeaderValue(String.valueOf(value))); - } - }); - return MessageHeaders.platform(values); - } - - /** - * Reads back the headers a rebuilt envelope keeps. - * - *

Everything except the names that were hoisted into envelope fields: the application's own - * headers, which were dropped entirely and so never survived a broker hop, and the platform's - * retry and redrive bookkeeping, whose loss restarted the attempt counter at one on every - * redelivery and left the retry budget capping nothing. - * - *

The hoisted names are excluded rather than kept alongside their fields, because a duplicate - * that can drift from the field is how the same message ends up with two different ids depending - * on which one the reader trusts. - * - * @param properties the message properties - * @return the headers to carry on the rebuilt envelope - */ - public MessageHeaders carriedForward(MessageProperties properties) { - Objects.requireNonNull(properties, "properties must not be null"); - Map values = new LinkedHashMap<>(); - properties - .getHeaders() - .forEach( - (name, value) -> { - if (value != null && !CanonicalEnvelopeHeaders.restatesEnvelopeField(name)) { - values.put(new HeaderName(name), new HeaderValue(String.valueOf(value))); - } - }); - return MessageHeaders.platform(values); - } - - /** - * Reads one header value. - * - * @param properties the message properties - * @param name the header name - * @return the value, or null when absent - */ - public String value(MessageProperties properties, String name) { - Object value = properties.getHeaders().get(name); - return value == null ? null : String.valueOf(value); - } - - private static void setHeader(MessageProperties properties, String name, String value) { - properties.setHeader(name, value); - } -} diff --git a/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitMessagingTransport.java b/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitMessagingTransport.java deleted file mode 100644 index b6d58627..00000000 --- a/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitMessagingTransport.java +++ /dev/null @@ -1,286 +0,0 @@ -package dev.caskeleton.messaging.rabbit; - -import dev.caskeleton.messaging.api.destination.DestinationCapabilities; -import dev.caskeleton.messaging.api.destination.DestinationName; -import dev.caskeleton.messaging.api.destination.MessagingCapabilities; -import dev.caskeleton.messaging.api.error.FailureCategory; -import dev.caskeleton.messaging.api.error.FailureDescriptor; -import dev.caskeleton.messaging.api.error.MessagingCapabilityUnavailableException; -import dev.caskeleton.messaging.api.publish.PublishCompletion; -import dev.caskeleton.messaging.api.publish.PublishEvidence; -import dev.caskeleton.messaging.api.publish.PublishResult; -import dev.caskeleton.messaging.api.publish.RoutingOutcome; -import dev.caskeleton.messaging.transport.MessagingTransport; -import dev.caskeleton.messaging.transport.TransportConsumerRegistration; -import dev.caskeleton.messaging.transport.TransportConsumerSpec; -import dev.caskeleton.messaging.transport.TransportPublishRequest; -import dev.caskeleton.messaging.transport.TransportPublishResult; -import java.time.Duration; -import java.util.Objects; -import java.util.Optional; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CompletionStage; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.function.Function; - -/** - * The Stable RabbitMQ adapter. - * - *

Publishes are always sent with {@code mandatory} set and correlated through {@link - * RabbitConfirmCoordinator}, because in AMQP a confirm and a return answer different questions. The - * confirm says the exchange accepted the message; the return says no queue was bound to receive it. - * An adapter that completed on the confirm alone would report success for a message the broker - * discarded, which is the single most damaging thing a Rabbit adapter can get wrong. - * - *

Payload size and shutdown state are checked before anything reaches the channel, so both fail - * with {@code NOT_TRANSMITTED} evidence rather than as a broker error whose ambiguity the caller - * then has to reason about. - */ -public final class RabbitMessagingTransport implements MessagingTransport { - - private static final MessagingCapabilities CAPABILITIES = - new MessagingCapabilities( - true, true, true, false, false, false, false, true, false, false, true, true); - - private final String brokerName; - private final long generation; - private final RabbitChannelPublisher channel; - private final RabbitPublishMapper mapper; - private final RabbitConfirmCoordinator coordinator; - private final Function consumerFactory; - private final Duration confirmTimeout; - private final ScheduledExecutorService confirmTimeouts; - private final AtomicBoolean closed = new AtomicBoolean(); - - /** - * Creates a publish-only transport. - * - * @param brokerName the logical broker name - * @param generation the runtime generation - * @param channel the channel publish operation - */ - public RabbitMessagingTransport( - String brokerName, long generation, RabbitChannelPublisher channel) { - this(brokerName, generation, channel, Duration.ofSeconds(5)); - } - - /** Creates a publish-only transport with an explicit confirm timeout. */ - public RabbitMessagingTransport( - String brokerName, long generation, RabbitChannelPublisher channel, Duration confirmTimeout) { - this( - brokerName, - generation, - channel, - spec -> { - throw new MessagingCapabilityUnavailableException( - "RABBIT_CONSUMER_NOT_CONFIGURED", - "this Rabbit transport was created without a consumer factory"); - }, - confirmTimeout); - } - - /** - * Creates a transport with a consumer factory. - * - * @param brokerName the logical broker name - * @param generation the runtime generation - * @param channel the channel publish operation - * @param consumerFactory builds a consumer registration for a spec - */ - public RabbitMessagingTransport( - String brokerName, - long generation, - RabbitChannelPublisher channel, - Function consumerFactory) { - this(brokerName, generation, channel, consumerFactory, Duration.ofSeconds(5)); - } - - /** Creates a transport with explicit consumer factory and confirm deadline. */ - public RabbitMessagingTransport( - String brokerName, - long generation, - RabbitChannelPublisher channel, - Function consumerFactory, - Duration confirmTimeout) { - this.brokerName = Objects.requireNonNull(brokerName, "brokerName must not be null"); - this.generation = generation; - this.channel = Objects.requireNonNull(channel, "channel must not be null"); - this.consumerFactory = Objects.requireNonNull(consumerFactory, "consumerFactory is required"); - this.confirmTimeout = Objects.requireNonNull(confirmTimeout, "confirmTimeout must not be null"); - if (confirmTimeout.isNegative() || confirmTimeout.isZero()) { - throw new IllegalArgumentException("confirmTimeout must be positive"); - } - this.mapper = new RabbitPublishMapper(); - this.coordinator = new RabbitConfirmCoordinator(); - this.confirmTimeouts = - Executors.newSingleThreadScheduledExecutor( - runnable -> { - Thread thread = new Thread(runnable, "messaging-rabbit-confirm-timeouts"); - thread.setDaemon(true); - return thread; - }); - } - - @Override - public CompletionStage publish(TransportPublishRequest request) { - Objects.requireNonNull(request, "request must not be null"); - - if (closed.get()) { - return completed( - rejectedLocally("RABBIT_TRANSPORT_CLOSED", "the transport is shutting down")); - } - int size = request.envelope().payload().size(); - int limit = request.profile().payload().maxBytes(); - if (size > limit) { - return completed( - rejectedLocally( - "PAYLOAD_TOO_LARGE", "encoded payload is " + size + " bytes, limit is " + limit)); - } - - String exchange = mapper.exchange(request.profile()); - String routingKey = mapper.routingKey(request.profile()); - - // Register before publishing. A confirm can land on the connection thread while basicPublish is - // still returning; registering afterwards would drop it and leave the caller waiting forever. - long sequence = channel.nextPublishSequence(); - CompletionStage pending = - coordinator - .awaiting(sequence, exchange, routingKey, request.profile().producer().confirmation()) - .thenApply(TransportPublishResult::new); - var timeout = - confirmTimeouts.schedule( - () -> coordinator.timedOut(sequence, confirmTimeout), - confirmTimeout.toNanos(), - TimeUnit.NANOSECONDS); - pending.whenComplete((result, failure) -> timeout.cancel(false)); - - try { - channel.publish(sequence, exchange, routingKey, mapper.toMessage(request), true); - } catch (RuntimeException sendFailed) { - // A synchronous failure from basicPublish used to propagate to the caller as a thrown - // exception while the pending entry stayed in the map: the caller got an exception instead - // of the stage the contract promises, and the entry waited for a confirm that could never - // arrive. The classifier decides whether the frame can have left; anything it cannot rule - // out is ambiguous rather than rejected. - coordinator.sendFailed( - sequence, new RabbitPublishFailureClassifier().classify(sendFailed, true, Duration.ZERO)); - } - return pending; - } - - /** - * Records a broker confirm. Called from the channel's confirm callback. - * - * @param sequence the publish sequence number - * @param acknowledged true for an ack, false for a nack - * @param elapsed how long the publish took - */ - public void onConfirm(long sequence, boolean acknowledged, Duration elapsed) { - onConfirm(sequence, false, acknowledged, elapsed); - } - - /** - * Records a broker confirm carrying the {@code multiple} flag. - * - *

The flag was dropped, so a broker confirming a range resolved one publish and left every - * earlier one pending forever. - * - * @param multiple true when every sequence up to and including this one is confirmed - */ - public void onConfirm(long sequence, boolean multiple, boolean acknowledged, Duration elapsed) { - coordinator.confirmed(sequence, multiple, acknowledged, elapsed); - } - - /** - * Records an unroutable return. Called from the channel's return callback. - * - * @param sequence the publish sequence number - */ - public void onReturn(long sequence) { - coordinator.returned(sequence); - } - - /** - * Records that a confirm never arrived. - * - * @param sequence the publish sequence number - * @param elapsed how long was waited - */ - public void onConfirmTimeout(long sequence, Duration elapsed) { - coordinator.timedOut(sequence, elapsed); - } - - /** - * Returns how many publishes are awaiting a confirm. - * - * @return the pending count - */ - public int pendingConfirms() { - return coordinator.pendingCount(); - } - - @Override - public TransportConsumerRegistration register(TransportConsumerSpec spec) { - Objects.requireNonNull(spec, "spec must not be null"); - if (closed.get()) { - throw new MessagingCapabilityUnavailableException( - "RABBIT_TRANSPORT_CLOSED", "the transport is shutting down"); - } - return consumerFactory.apply(spec); - } - - @Override - public DestinationCapabilities capabilities(DestinationName destination) { - return new DestinationCapabilities(destination, brokerName, CAPABILITIES); - } - - @Override - public String brokerName() { - return brokerName; - } - - @Override - public long generation() { - return generation; - } - - @Override - public void close() { - if (!closed.compareAndSet(false, true)) { - return; - } - // Drain what is still waiting. Leaving the stages pending hangs every caller holding one, and - // a closed channel will never deliver their confirms. - coordinator.channelClosed(Duration.ZERO); - confirmTimeouts.shutdownNow(); - channel.close(); - } - - /** - * Reports whether the transport is still accepting work. - * - * @return true until close - */ - public boolean isAcceptingWork() { - return !closed.get(); - } - - private static TransportPublishResult rejectedLocally(String code, String message) { - return new TransportPublishResult( - new PublishResult( - PublishCompletion.REJECTED, - PublishEvidence.notTransmitted(), - RoutingOutcome.NOT_APPLICABLE, - Optional.empty(), - 1, - Duration.ZERO, - Optional.of(FailureDescriptor.of(FailureCategory.PERMANENT_BUSINESS, code, message)))); - } - - private static CompletionStage completed(TransportPublishResult result) { - return CompletableFuture.completedFuture(result); - } -} diff --git a/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitNativeDeadLetterCapability.java b/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitNativeDeadLetterCapability.java deleted file mode 100644 index 84d5e88a..00000000 --- a/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitNativeDeadLetterCapability.java +++ /dev/null @@ -1,70 +0,0 @@ -package dev.caskeleton.messaging.rabbit; - -import java.util.Objects; - -/** - * Decides whether the broker's own dead-lettering may be used, or the platform must publish. - * - *

RabbitMQ is the one Stable broker with native dead-lettering, and using it is tempting: a - * {@code basic.reject} with {@code requeue=false} moves the message with no publish at all. The - * catch is that the move is not confirmed to the publisher. If the dead-letter exchange is - * unroutable — nobody bound a queue to it, or the binding was removed — the broker discards the - * message silently and the reject still succeeds. - * - *

So native dead-lettering is only used where the dead-letter path has been verified to have a - * bound queue. Everywhere else the platform publishes and waits for its own confirm, which is the - * same invariant every other broker gets: the source is settled only after the dead-letter - * publish is confirmed. - */ -public final class RabbitNativeDeadLetterCapability { - - private final RabbitTopologyProfile topology; - private final boolean deadLetterQueueBound; - - /** - * Creates a capability check for one destination. - * - * @param topology the declared topology - * @param deadLetterQueueBound whether a queue is verified bound to the dead letter exchange - */ - public RabbitNativeDeadLetterCapability( - RabbitTopologyProfile topology, boolean deadLetterQueueBound) { - this.topology = Objects.requireNonNull(topology, "topology must not be null"); - this.deadLetterQueueBound = deadLetterQueueBound; - } - - /** - * Reports whether a rejected message may be left to the broker. - * - * @return true only when a dead letter exchange is declared and verified bound - */ - public boolean mayUseNativeDeadLetter() { - return topology.hasNativeDeadLetter() && deadLetterQueueBound; - } - - /** - * Reports whether the platform must publish the dead letter itself. - * - * @return true when native dead-lettering cannot be trusted for this destination - */ - public boolean requiresPlatformPublish() { - return !mayUseNativeDeadLetter(); - } - - /** - * Returns why native dead-lettering is not being used, for a startup diagnostic. - * - * @return the sanitized reason, empty when native dead-lettering is in use - */ - public String reasonForPlatformPublish() { - if (mayUseNativeDeadLetter()) { - return ""; - } - if (!topology.hasNativeDeadLetter()) { - return "queue %s was declared without a dead letter exchange".formatted(topology.queue()); - } - return "no queue is bound to dead letter exchange %s, so a broker-side reject would discard " - .formatted(topology.deadLetterExchange().orElse("(none)")) - + "the message silently while still reporting success"; - } -} diff --git a/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitProfileValidator.java b/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitProfileValidator.java deleted file mode 100644 index 3463b5c5..00000000 --- a/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitProfileValidator.java +++ /dev/null @@ -1,83 +0,0 @@ -package dev.caskeleton.messaging.rabbit; - -import dev.caskeleton.messaging.api.destination.DestinationKind; -import dev.caskeleton.messaging.policy.DestinationProfile; -import java.util.Objects; - -/** - * Startup validation of the RabbitMQ Stable profile. - * - *

Confirms and returns are both required, and they answer different questions. A confirm says - * the exchange accepted the message; a return says no queue was bound to receive it. Enabling - * confirms without returns produces the worst possible outcome: a publish that reports success - * while the message was silently discarded. - * - *

Durable work queues default to quorum queues because classic mirrored queues can lose - * acknowledged messages during a partition — which is precisely the guarantee a durable work queue - * exists to provide. - */ -public final class RabbitProfileValidator { - - /** - * Validates one RabbitMQ broker profile. - * - * @param profile the profile to validate - * @throws IllegalArgumentException when the profile cannot honour its declared guarantees - */ - public void validate(RabbitBrokerProfile profile) { - Objects.requireNonNull(profile, "profile must not be null"); - - if (profile.stable() && !profile.publisherConfirms()) { - throw new IllegalArgumentException( - "stable Rabbit producer requires publisher confirms: " + profile.broker()); - } - if (profile.stable() && !profile.publisherReturns()) { - throw new IllegalArgumentException( - "stable Rabbit producer requires publisher returns: " + profile.broker()); - } - if (profile.stable() && !profile.mandatory()) { - throw new IllegalArgumentException( - "stable Rabbit producer requires mandatory routing: " + profile.broker()); - } - if (profile.autoAck()) { - throw new IllegalArgumentException( - "consumer auto ack is forbidden; the platform acknowledges after handler success: " - + profile.broker()); - } - if (profile.prefetch() < 1) { - throw new IllegalArgumentException("prefetch must be at least 1: " + profile.broker()); - } - if (profile.confirmTimeout().isNegative() || profile.confirmTimeout().isZero()) { - throw new IllegalArgumentException("confirm timeout must be positive: " + profile.broker()); - } - if (profile.production() && !profile.tlsEnabled()) { - throw new IllegalArgumentException( - "a production Rabbit connection requires TLS: " + profile.broker()); - } - if (profile.production() && !profile.authenticationEnabled()) { - throw new IllegalArgumentException( - "a production Rabbit connection requires broker authentication: " + profile.broker()); - } - } - - /** - * Validates a destination against the broker profile. - * - * @param destination the destination profile - * @param broker the broker profile - * @throws IllegalArgumentException when the destination cannot be served safely - */ - public void validateDestination(DestinationProfile destination, RabbitBrokerProfile broker) { - Objects.requireNonNull(destination, "destination must not be null"); - Objects.requireNonNull(broker, "broker must not be null"); - - if (destination.kind() == DestinationKind.WORK_QUEUE && !broker.quorumQueues()) { - throw new IllegalArgumentException( - "a durable Rabbit work queue must use a quorum queue: " + destination.name().value()); - } - if (destination.physical().queue().isEmpty() && destination.physical().exchange().isEmpty()) { - throw new IllegalArgumentException( - "a Rabbit destination requires an exchange or a queue: " + destination.name().value()); - } - } -} diff --git a/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitPublishFailureClassifier.java b/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitPublishFailureClassifier.java deleted file mode 100644 index c9408b98..00000000 --- a/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitPublishFailureClassifier.java +++ /dev/null @@ -1,133 +0,0 @@ -package dev.caskeleton.messaging.rabbit; - -import dev.caskeleton.messaging.api.error.FailureCategory; -import dev.caskeleton.messaging.api.error.FailureDescriptor; -import dev.caskeleton.messaging.api.publish.ConfirmationLevel; -import dev.caskeleton.messaging.api.publish.PublishCompletion; -import dev.caskeleton.messaging.api.publish.PublishEvidence; -import dev.caskeleton.messaging.api.publish.PublishResult; -import dev.caskeleton.messaging.api.publish.RoutingOutcome; -import dev.caskeleton.messaging.api.publish.TransmissionEvidence; -import java.io.IOException; -import java.time.Duration; -import java.util.Optional; - -/** - * Turns an AMQP publish failure into a completion the caller can act on. - * - *

The distinction that matters is where the failure happened. A channel-level exception raised - * before {@code basicPublish} returned means nothing was written: rejected, with no - * ambiguity. A connection that drops after the frame was written proves nothing — the - * broker may have the message and only the confirm was lost. - * - *

Unknown failures default to ambiguous. Guessing "rejected" on an unrecognised error is what - * turns one lost confirm into two of the same order, and the cost of an unnecessary ambiguous is a - * retry the inbox absorbs. - */ -public final class RabbitPublishFailureClassifier { - - /** - * Classifies a failure raised while publishing. - * - * @param error the throwable the channel reported - * @param framePossiblyWritten whether the publish frame may already have reached the broker - * @param elapsed how long the attempt took - * @return the publish outcome with its evidence - */ - public PublishResult classify(Throwable error, boolean framePossiblyWritten, Duration elapsed) { - Throwable cause = unwrap(error); - - if (!framePossiblyWritten) { - return new PublishResult( - PublishCompletion.REJECTED, - PublishEvidence.notTransmitted(), - RoutingOutcome.NOT_APPLICABLE, - Optional.empty(), - 1, - elapsed, - Optional.of( - FailureDescriptor.of( - categoryOf(cause), - "RABBIT_PUBLISH_REJECTED", - "the channel refused the publish before writing it: " + name(cause)))); - } - - return new PublishResult( - PublishCompletion.AMBIGUOUS, - new PublishEvidence( - true, TransmissionEvidence.MAY_HAVE_BEEN_TRANSMITTED, false, ConfirmationLevel.NONE), - RoutingOutcome.UNKNOWN, - Optional.empty(), - 1, - elapsed, - Optional.of( - FailureDescriptor.of( - FailureCategory.AMBIGUOUS, - "RABBIT_CONFIRM_LOST", - "the frame was written but no confirm arrived: " + name(cause)))); - } - - /** - * Classifies a broker nack, which is always a definitive rejection. - * - * @param elapsed how long the attempt took - * @return the publish outcome - */ - public PublishResult nacked(Duration elapsed) { - return new PublishResult( - PublishCompletion.REJECTED, - // A nack means the broker took the frame and decided against it, so the bytes were - // transmitted even though nothing was stored. - new PublishEvidence(true, TransmissionEvidence.TRANSMITTED, false, ConfirmationLevel.NONE), - RoutingOutcome.NOT_APPLICABLE, - Optional.empty(), - 1, - elapsed, - Optional.of( - FailureDescriptor.of( - FailureCategory.TRANSIENT_INFRASTRUCTURE, - "RABBIT_NACKED", - "the broker negatively acknowledged the publish"))); - } - - private static FailureCategory categoryOf(Throwable cause) { - if (cause instanceof com.rabbitmq.client.PossibleAuthenticationFailureException) { - return FailureCategory.AUTHENTICATION; - } - if (cause instanceof com.rabbitmq.client.ShutdownSignalException shutdown) { - int replyCode = replyCode(shutdown.getReason()); - if (replyCode == 403) { - return FailureCategory.AUTHORIZATION; - } - if (replyCode >= 500) { - return FailureCategory.TRANSIENT_INFRASTRUCTURE; - } - return FailureCategory.PERMANENT_BUSINESS; - } - if (cause instanceof IOException) { - return FailureCategory.TRANSIENT_INFRASTRUCTURE; - } - return FailureCategory.PERMANENT_BUSINESS; - } - - private static int replyCode(com.rabbitmq.client.Method reason) { - if (reason instanceof com.rabbitmq.client.AMQP.Channel.Close close) { - return close.getReplyCode(); - } - if (reason instanceof com.rabbitmq.client.AMQP.Connection.Close close) { - return close.getReplyCode(); - } - return -1; - } - - private static Throwable unwrap(Throwable error) { - if (error instanceof java.util.concurrent.CompletionException && error.getCause() != null) { - return error.getCause(); - } - return error; - } - - private static String name(Throwable cause) { - return cause == null ? "unknown" : cause.getClass().getSimpleName(); - } -} diff --git a/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitPublishMapper.java b/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitPublishMapper.java deleted file mode 100644 index ec03aae1..00000000 --- a/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitPublishMapper.java +++ /dev/null @@ -1,72 +0,0 @@ -package dev.caskeleton.messaging.rabbit; - -import dev.caskeleton.messaging.api.error.MessagingConfigurationException; -import dev.caskeleton.messaging.policy.DestinationProfile; -import dev.caskeleton.messaging.transport.TransportPublishRequest; -import java.util.Objects; -import org.springframework.amqp.core.Message; - -/** - * Builds AMQP messages from platform publish requests. - * - *

The exchange and routing key come from the destination profile, never from the caller. A - * publisher that could choose its own routing key would be able to reach queues the destination's - * access policy never granted. - */ -public final class RabbitPublishMapper { - - private final RabbitHeaderMapper headerMapper; - - /** Creates a mapper with the default header mapper. */ - public RabbitPublishMapper() { - this(new RabbitHeaderMapper()); - } - - /** - * Creates a mapper with an explicit header mapper. - * - * @param headerMapper the header mapper - */ - public RabbitPublishMapper(RabbitHeaderMapper headerMapper) { - this.headerMapper = Objects.requireNonNull(headerMapper, "headerMapper must not be null"); - } - - /** - * Converts a publish request into an AMQP message. - * - * @param request the publish request - * @return the AMQP message - */ - public Message toMessage(TransportPublishRequest request) { - Objects.requireNonNull(request, "request must not be null"); - return new Message( - request.envelope().payload().bytes(), headerMapper.toProperties(request.envelope())); - } - - /** - * Returns the exchange a destination publishes to. - * - * @param profile the destination profile - * @return the exchange name - */ - public String exchange(DestinationProfile profile) { - return profile - .physical() - .exchange() - .orElseThrow( - () -> - new MessagingConfigurationException( - "RABBIT_EXCHANGE_MISSING", - "destination has no Rabbit exchange: " + profile.name().value())); - } - - /** - * Returns the routing key a destination publishes with. - * - * @param profile the destination profile - * @return the routing key - */ - public String routingKey(DestinationProfile profile) { - return profile.physical().routingKey().orElse(""); - } -} diff --git a/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitPublishReference.java b/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitPublishReference.java deleted file mode 100644 index aee6d791..00000000 --- a/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitPublishReference.java +++ /dev/null @@ -1,37 +0,0 @@ -package dev.caskeleton.messaging.rabbit; - -import dev.caskeleton.messaging.api.publish.BrokerPosition; -import java.util.Map; -import java.util.Objects; - -/** - * A RabbitMQ exchange, routing key, and publish sequence coordinate. - * - * @param exchange the exchange published to - * @param routingKey the routing key used - * @param sequence the channel publish sequence number - */ -public record RabbitPublishReference(String exchange, String routingKey, long sequence) - implements BrokerPosition { - - public RabbitPublishReference { - Objects.requireNonNull(exchange, "exchange must not be null"); - Objects.requireNonNull(routingKey, "routingKey must not be null"); - if (sequence < 0) { - throw new IllegalArgumentException("sequence must not be negative"); - } - } - - @Override - public String broker() { - return "rabbitmq"; - } - - @Override - public Map diagnosticAttributes() { - return Map.of( - "exchange", exchange, - "routingKey", routingKey, - "sequence", Long.toString(sequence)); - } -} diff --git a/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitRequestReply.java b/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitRequestReply.java deleted file mode 100644 index 2854b419..00000000 --- a/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitRequestReply.java +++ /dev/null @@ -1,32 +0,0 @@ -package dev.caskeleton.messaging.rabbit; - -import dev.caskeleton.messaging.api.MessageEnvelope; -import dev.caskeleton.messaging.api.destination.MessageDestination; -import dev.caskeleton.messaging.schema.EncodedMessage; -import java.time.Duration; -import java.util.concurrent.CompletionStage; - -/** - * The M2 request-reply capability. - * - *

Deliberately limited. Request-reply over a broker is a synchronous call wearing an - * asynchronous costume: it holds a correlation entry and a caller for the whole round trip, and it - * fails in ways a plain publish does not — a lost reply is indistinguishable from a slow one. It is - * offered with a mandatory deadline and no automatic retry, because retrying a request whose reply - * was merely late duplicates the work on the other side. - */ -public interface RabbitRequestReply { - - /** - * Sends a request and awaits its correlated reply. - * - * @param destination the request destination - * @param request the encoded request envelope - * @param timeout how long to wait for the reply - * @return a stage completing with the reply, or failing on timeout - */ - CompletionStage> request( - MessageDestination destination, - MessageEnvelope request, - Duration timeout); -} diff --git a/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitRetryQueueTopology.java b/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitRetryQueueTopology.java deleted file mode 100644 index ca42dfb4..00000000 --- a/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitRetryQueueTopology.java +++ /dev/null @@ -1,57 +0,0 @@ -package dev.caskeleton.messaging.rabbit; - -import java.time.Duration; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Objects; - -/** - * Describes the delayed retry queue a destination uses. - * - *

RabbitMQ has no native per-message delay in the core broker, so a retry queue is a queue with - * a message TTL whose dead letter exchange points back at the work queue: the message sits until - * the TTL expires and is then re-routed. Modelling this explicitly, rather than hiding it behind a - * plugin, keeps the behaviour reviewable — including its main caveat, that TTL expiry is evaluated - * at the head of the queue, so mixed delays in one retry queue do not expire independently. - * - * @param retryQueue the queue messages wait in - * @param deadLetterExchange the exchange expired messages are routed back through - * @param deadLetterRoutingKey the routing key expired messages are re-published with - * @param messageTtl how long messages wait - */ -public record RabbitRetryQueueTopology( - String retryQueue, - String deadLetterExchange, - String deadLetterRoutingKey, - Duration messageTtl) { - - public RabbitRetryQueueTopology { - Objects.requireNonNull(messageTtl, "messageTtl must not be null"); - if (retryQueue == null || retryQueue.isBlank()) { - throw new IllegalArgumentException("retryQueue must not be blank"); - } - if (deadLetterExchange == null) { - throw new IllegalArgumentException("deadLetterExchange must not be null"); - } - if (deadLetterRoutingKey == null) { - throw new IllegalArgumentException("deadLetterRoutingKey must not be null"); - } - if (messageTtl.isNegative() || messageTtl.isZero()) { - throw new IllegalArgumentException("messageTtl must be positive"); - } - } - - /** - * Returns the queue arguments this topology requires. - * - * @return the AMQP queue arguments - */ - public Map queueArguments() { - Map arguments = new LinkedHashMap<>(); - arguments.put("x-queue-type", "quorum"); - arguments.put("x-message-ttl", messageTtl.toMillis()); - arguments.put("x-dead-letter-exchange", deadLetterExchange); - arguments.put("x-dead-letter-routing-key", deadLetterRoutingKey); - return Map.copyOf(arguments); - } -} diff --git a/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitSecurityConfigurer.java b/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitSecurityConfigurer.java deleted file mode 100644 index 98419163..00000000 --- a/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitSecurityConfigurer.java +++ /dev/null @@ -1,179 +0,0 @@ -package dev.caskeleton.messaging.rabbit; - -import dev.caskeleton.messaging.security.BrokerCredentialProfile; -import dev.caskeleton.messaging.security.BrokerSecurityProfile; -import dev.caskeleton.messaging.security.BrokerTlsPolicy; -import dev.caskeleton.messaging.security.CredentialRuntime; -import dev.caskeleton.messaging.security.CredentialRuntimeRegistry; -import java.time.Instant; -import java.util.List; -import java.util.Objects; - -/** - * Builds the AMQP connection settings from a validated security profile. - * - *

Credentials are resolved per connection attempt rather than cached in the factory. RabbitMQ - * client connections are long-lived and reconnect on their own, so a factory holding a credential - * from startup will happily reconnect with a revoked one for as long as the process runs — the - * reconnect is exactly the moment a rotated credential should take effect. - * - *

The password is returned inside a short-lived {@link AmqpCredentials} rather than assigned to - * a connection factory field, so the caller controls when it is cleared. - */ -public final class RabbitSecurityConfigurer { - - private final CredentialRuntimeRegistry credentials; - private final BrokerTlsPolicy tlsPolicy; - - /** - * Creates a configurer. - * - * @param credentials resolves and rotates credential material - * @param tlsPolicy validates the transport security posture - */ - public RabbitSecurityConfigurer( - CredentialRuntimeRegistry credentials, BrokerTlsPolicy tlsPolicy) { - this.credentials = Objects.requireNonNull(credentials, "credentials must not be null"); - this.tlsPolicy = Objects.requireNonNull(tlsPolicy, "tlsPolicy must not be null"); - } - - /** - * Resolves the connection credentials for one role. - * - * @param profile the broker security profile - * @param credential the role credential to configure - * @param enabledProtocols the TLS protocol versions to enable - * @param now the current instant - * @return the AMQP connection credentials - */ - public AmqpCredentials configure( - BrokerSecurityProfile profile, - BrokerCredentialProfile credential, - List enabledProtocols, - Instant now) { - Objects.requireNonNull(profile, "profile must not be null"); - Objects.requireNonNull(credential, "credential must not be null"); - Objects.requireNonNull(enabledProtocols, "enabledProtocols must not be null"); - - tlsPolicy.validate(profile, enabledProtocols); - - return switch (credential) { - case BrokerCredentialProfile.UsernamePassword plain -> { - CredentialRuntime resolved = credentials.resolve(plain.credentialId(), now); - yield new AmqpCredentials( - "PLAIN", plain.credentialId(), resolved.material(), profile.tlsEnabled()); - } - case BrokerCredentialProfile.MutualTls mutual -> { - // The certificate is the credential; there is no password to carry. - credentials.resolve(mutual.credentialId(), now); - yield new AmqpCredentials("EXTERNAL", mutual.credentialId(), new char[0], true); - } - case BrokerCredentialProfile.OAuth2 oauth -> { - CredentialRuntime resolved = credentials.resolve(oauth.credentialId(), now); - // RabbitMQ's OAuth 2 plugin takes the token in the password field of a PLAIN exchange. - yield new AmqpCredentials( - "PLAIN", oauth.credentialId(), resolved.material(), profile.tlsEnabled()); - } - case BrokerCredentialProfile.SaslScram scram -> { - CredentialRuntime resolved = credentials.resolve(scram.credentialId(), now); - yield new AmqpCredentials( - "RABBIT-CR-DEMO", scram.credentialId(), resolved.material(), profile.tlsEnabled()); - } - case BrokerCredentialProfile.Nkey ignored -> - throw new IllegalArgumentException( - "NKey credentials are a NATS concept, not an AMQP one"); - }; - } - - /** - * One connection's resolved credentials. - * - *

A class rather than a record because the secret has to stay mutable to be cleared, and a - * record carrying a {@code char[]} would compare and hash it by identity — two credentials with - * the same material would be unequal, which is a surprise waiting in any future collection use. - * - *

{@link #clear()} overwrites the secret. The caller is expected to call it once the - * connection is established, so the material's lifetime is the handshake rather than the process. - */ - public static final class AmqpCredentials { - - private final String mechanism; - private final String username; - private final char[] secret; - private final boolean tls; - - /** - * Creates connection credentials. - * - * @param mechanism the SASL mechanism name - * @param username the AMQP username - * @param secret the password or token, taken by reference and cleared by {@link #clear()} - * @param tls whether the connection uses TLS - */ - public AmqpCredentials(String mechanism, String username, char[] secret, boolean tls) { - Objects.requireNonNull(secret, "secret must not be null"); - if (mechanism == null || mechanism.isBlank()) { - throw new IllegalArgumentException("mechanism must not be blank"); - } - if (username == null || username.isBlank()) { - throw new IllegalArgumentException("username must not be blank"); - } - this.mechanism = mechanism; - this.username = username; - this.secret = secret; - this.tls = tls; - } - - /** - * Returns the SASL mechanism name. - * - * @return the mechanism - */ - public String mechanism() { - return mechanism; - } - - /** - * Returns the AMQP username. - * - * @return the username - */ - public String username() { - return username; - } - - /** - * Returns a copy of the secret. - * - * @return the password or token - */ - public char[] secret() { - return secret.clone(); - } - - /** - * Reports whether the connection uses TLS. - * - * @return true when TLS is enabled - */ - public boolean tls() { - return tls; - } - - /** Overwrites the secret in place. */ - public void clear() { - java.util.Arrays.fill(secret, '\0'); - } - - /** - * Returns a representation that names the connection without revealing it. - * - * @return a safe description - */ - @Override - public String toString() { - return "AmqpCredentials[mechanism=%s, username=%s, tls=%s]" - .formatted(mechanism, username, tls); - } - } -} diff --git a/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitSettlementController.java b/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitSettlementController.java deleted file mode 100644 index 3f0a248f..00000000 --- a/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitSettlementController.java +++ /dev/null @@ -1,84 +0,0 @@ -package dev.caskeleton.messaging.rabbit; - -import dev.caskeleton.messaging.api.error.FailureDescriptor; -import dev.caskeleton.messaging.api.error.MessageSettlementException; -import dev.caskeleton.messaging.api.settlement.SettlementController; -import dev.caskeleton.messaging.api.settlement.SettlementResult; -import java.time.Duration; -import java.util.Objects; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CompletionStage; -import java.util.concurrent.atomic.AtomicBoolean; - -/** - * Manual settlement for one RabbitMQ delivery. - * - *

Exactly one terminal call is allowed. A second one fails loudly rather than racing the first, - * because a duplicated {@code basic.ack} on a reused delivery tag acknowledges a different - * message — a failure mode that shows up as unexplained message loss under load, far from its - * cause. - * - *

{@code retry} does not use {@code basic.nack} with requeue. Requeueing puts the message back - * at the head of the queue with no delay, which turns a transient downstream failure into a hot - * loop; the delayed retry queue is used instead. - */ -public final class RabbitSettlementController implements SettlementController { - - private final long deliveryTag; - private final RabbitSettlementOperations operations; - private final AtomicBoolean settled = new AtomicBoolean(); - - /** - * Creates a controller for one delivery. - * - * @param deliveryTag the AMQP delivery tag - * @param operations the channel operations, invoked on the container thread - */ - public RabbitSettlementController(long deliveryTag, RabbitSettlementOperations operations) { - this.deliveryTag = deliveryTag; - this.operations = Objects.requireNonNull(operations, "operations must not be null"); - } - - @Override - public CompletionStage ack() { - return terminal(() -> operations.ack(deliveryTag)); - } - - @Override - public CompletionStage retry(Duration delay) { - Objects.requireNonNull(delay, "delay must not be null"); - return terminal(() -> operations.publishToRetryQueue(deliveryTag, delay)); - } - - @Override - public CompletionStage deadLetter(FailureDescriptor failure) { - Objects.requireNonNull(failure, "failure must not be null"); - return terminal(() -> operations.deadLetter(deliveryTag, failure)); - } - - @Override - public CompletionStage reject(FailureDescriptor failure) { - Objects.requireNonNull(failure, "failure must not be null"); - return terminal(() -> operations.discard(deliveryTag, failure)); - } - - /** - * Reports whether this delivery has already been settled. - * - * @return true once a terminal call has been made - */ - public boolean isSettled() { - return settled.get(); - } - - private CompletionStage terminal( - java.util.function.Supplier> operation) { - if (!settled.compareAndSet(false, true)) { - return CompletableFuture.failedFuture( - new MessageSettlementException( - "SETTLEMENT_ALREADY_COMPLETED", - "delivery tag " + deliveryTag + " has already been settled")); - } - return operation.get(); - } -} diff --git a/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitSettlementOperations.java b/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitSettlementOperations.java deleted file mode 100644 index 6f2c9752..00000000 --- a/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitSettlementOperations.java +++ /dev/null @@ -1,50 +0,0 @@ -package dev.caskeleton.messaging.rabbit; - -import dev.caskeleton.messaging.api.error.FailureDescriptor; -import dev.caskeleton.messaging.api.settlement.SettlementResult; -import java.time.Duration; -import java.util.concurrent.CompletionStage; - -/** - * The channel-side operations a settlement controller may perform. - * - *

Separated from the controller so the one-terminal-call guard is testable without an AMQP - * channel, and so the controller cannot reach anything the platform has not exposed. - */ -public interface RabbitSettlementOperations { - - /** - * Acknowledges a delivery. - * - * @param deliveryTag the AMQP delivery tag - * @return a stage completing with the settlement outcome - */ - CompletionStage ack(long deliveryTag); - - /** - * Publishes to the delayed retry queue, then acknowledges the source once confirmed. - * - * @param deliveryTag the AMQP delivery tag - * @param delay how long the message should wait - * @return a stage completing with the settlement outcome - */ - CompletionStage publishToRetryQueue(long deliveryTag, Duration delay); - - /** - * Publishes to the dead letter destination, then acknowledges the source once confirmed. - * - * @param deliveryTag the AMQP delivery tag - * @param failure the sanitized failure - * @return a stage completing with the settlement outcome - */ - CompletionStage deadLetter(long deliveryTag, FailureDescriptor failure); - - /** - * Discards a delivery without requeueing or dead lettering. - * - * @param deliveryTag the AMQP delivery tag - * @param failure the sanitized failure - * @return a stage completing with the settlement outcome - */ - CompletionStage discard(long deliveryTag, FailureDescriptor failure); -} diff --git a/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitTopologyProfile.java b/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitTopologyProfile.java deleted file mode 100644 index 66633bbb..00000000 --- a/src/messaging/messaging-rabbit/src/main/java/dev/caskeleton/messaging/rabbit/RabbitTopologyProfile.java +++ /dev/null @@ -1,137 +0,0 @@ -package dev.caskeleton.messaging.rabbit; - -import dev.caskeleton.messaging.api.error.MessagingConfigurationException; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -/** - * The declared shape of one RabbitMQ destination: exchange, queue, and the arguments that give the - * queue its guarantees. - * - *

Quorum queues are required for anything durable. A classic mirrored queue can lose - * acknowledged messages during a partition — the promotion of a stale mirror is exactly the case - * where "the broker confirmed it" stops being true — and RabbitMQ itself has deprecated them. - * - *

The dead-letter exchange is part of the topology rather than a runtime decision, because a - * queue's {@code x-dead-letter-exchange} can only be set at declaration. A destination that gains a - * dead-letter policy later cannot acquire one without deleting and recreating the queue, so the - * mismatch is caught here instead of surfacing when the first message needs parking. - * - * @param exchange the exchange to publish to - * @param exchangeType the exchange type - * @param routingKey the routing key - * @param queue the queue that receives the messages - * @param quorum whether the queue is a quorum queue - * @param deadLetterExchange the dead letter exchange, when the destination has one - * @param deadLetterRoutingKey the dead letter routing key, when the destination has one - * @param maxLength the queue length limit, when one is set - */ -public record RabbitTopologyProfile( - String exchange, - String exchangeType, - String routingKey, - String queue, - boolean quorum, - Optional deadLetterExchange, - Optional deadLetterRoutingKey, - Optional maxLength) { - - /** RabbitMQ's argument key for a queue's type. */ - public static final String QUEUE_TYPE = "x-queue-type"; - - /** RabbitMQ's argument key for a queue's dead letter exchange. */ - public static final String DEAD_LETTER_EXCHANGE = "x-dead-letter-exchange"; - - /** RabbitMQ's argument key for a queue's dead letter routing key. */ - public static final String DEAD_LETTER_ROUTING_KEY = "x-dead-letter-routing-key"; - - /** RabbitMQ's argument key for a queue's length limit. */ - public static final String MAX_LENGTH = "x-max-length"; - - public RabbitTopologyProfile { - Objects.requireNonNull(deadLetterExchange, "deadLetterExchange must not be null"); - Objects.requireNonNull(deadLetterRoutingKey, "deadLetterRoutingKey must not be null"); - Objects.requireNonNull(maxLength, "maxLength must not be null"); - requireText(exchange, "exchange"); - requireText(exchangeType, "exchangeType"); - requireText(routingKey, "routingKey"); - requireText(queue, "queue"); - - if (deadLetterRoutingKey.isPresent() && deadLetterExchange.isEmpty()) { - throw new IllegalArgumentException( - "a dead letter routing key without a dead letter exchange routes nowhere"); - } - if (maxLength.isPresent() && maxLength.get() < 1) { - throw new IllegalArgumentException("maxLength must be positive when set"); - } - } - - /** - * Refuses a topology that cannot back a durable destination. - * - * @param durable whether the destination promises durability - * @throws MessagingConfigurationException when a durable destination lacks a quorum queue - */ - public void requireSafeFor(boolean durable) { - if (durable && !quorum) { - throw new MessagingConfigurationException( - "CLASSIC_QUEUE_ON_DURABLE_DESTINATION", - "queue %s is not a quorum queue; a classic mirrored queue can lose acknowledged messages " - .formatted(queue) - + "when a stale mirror is promoted during a partition"); - } - } - - /** - * Returns the arguments this queue must be declared with. - * - * @return the declaration arguments - */ - public Map queueArguments() { - Map arguments = new LinkedHashMap<>(); - arguments.put(QUEUE_TYPE, quorum ? "quorum" : "classic"); - deadLetterExchange.ifPresent(value -> arguments.put(DEAD_LETTER_EXCHANGE, value)); - deadLetterRoutingKey.ifPresent(value -> arguments.put(DEAD_LETTER_ROUTING_KEY, value)); - maxLength.ifPresent(value -> arguments.put(MAX_LENGTH, value)); - return Map.copyOf(arguments); - } - - /** - * Reports whether the broker will route a rejected message itself. - * - * @return true when the queue was declared with a dead letter exchange - */ - public boolean hasNativeDeadLetter() { - return deadLetterExchange.isPresent(); - } - - /** - * Returns a durable work-queue topology with a dead letter exchange. - * - * @param exchange the exchange - * @param routingKey the routing key - * @param queue the queue - * @param deadLetterExchange the dead letter exchange - * @return the topology profile - */ - public static RabbitTopologyProfile workQueue( - String exchange, String routingKey, String queue, String deadLetterExchange) { - return new RabbitTopologyProfile( - exchange, - "direct", - routingKey, - queue, - true, - Optional.of(deadLetterExchange), - Optional.of(routingKey), - Optional.empty()); - } - - private static void requireText(String value, String field) { - if (value == null || value.isBlank()) { - throw new IllegalArgumentException(field + " must not be blank"); - } - } -} diff --git a/src/messaging/messaging-rabbit/src/test/java/dev/caskeleton/messaging/rabbit/RabbitAdapterContractTest.java b/src/messaging/messaging-rabbit/src/test/java/dev/caskeleton/messaging/rabbit/RabbitAdapterContractTest.java deleted file mode 100644 index 60d8e245..00000000 --- a/src/messaging/messaging-rabbit/src/test/java/dev/caskeleton/messaging/rabbit/RabbitAdapterContractTest.java +++ /dev/null @@ -1,24 +0,0 @@ -package dev.caskeleton.messaging.rabbit; - -import dev.caskeleton.messaging.testkit.MessagingAdapterContract; -import dev.caskeleton.messaging.testkit.MessagingAdapterHarness; -import org.junit.jupiter.api.Nested; - -/** - * Runs the shared adapter contract against the RabbitMQ adapter. - * - *

Identical to the Kafka run. Two brokers with completely different machinery — offsets and - * commits versus delivery tags and confirms — answering the same seven questions the same way is - * what makes the logical destination abstraction real rather than aspirational. - */ -class RabbitAdapterContractTest { - - @Nested - class Contract extends MessagingAdapterContract { - - @Override - protected MessagingAdapterHarness harness() { - return RabbitContractHarness.create(); - } - } -} diff --git a/src/messaging/messaging-rabbit/src/test/java/dev/caskeleton/messaging/rabbit/RabbitConfirmCoordinatorTest.java b/src/messaging/messaging-rabbit/src/test/java/dev/caskeleton/messaging/rabbit/RabbitConfirmCoordinatorTest.java deleted file mode 100644 index c9bd1ecc..00000000 --- a/src/messaging/messaging-rabbit/src/test/java/dev/caskeleton/messaging/rabbit/RabbitConfirmCoordinatorTest.java +++ /dev/null @@ -1,167 +0,0 @@ -package dev.caskeleton.messaging.rabbit; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.messaging.api.destination.ConfirmationRequirement; -import dev.caskeleton.messaging.api.publish.ConfirmationLevel; -import dev.caskeleton.messaging.api.publish.PublishCompletion; -import dev.caskeleton.messaging.api.publish.PublishResult; -import dev.caskeleton.messaging.api.publish.RoutingOutcome; -import java.time.Duration; -import java.util.concurrent.CompletionStage; -import org.junit.jupiter.api.Test; - -class RabbitConfirmCoordinatorTest { - - private static final ConfirmationRequirement REPLICATION = - ConfirmationRequirement.REPLICATION_OR_PERSISTENCE_ACK; - - private final RabbitConfirmCoordinator coordinator = new RabbitConfirmCoordinator(); - - @Test - void aPlainConfirmIsAConfirmedPublish() { - CompletionStage stage = - coordinator.awaiting(1L, "notification.work", "email", REPLICATION); - - coordinator.confirmed(1L, true, Duration.ofMillis(4)); - - PublishResult result = stage.toCompletableFuture().join(); - assertThat(result.completion()).isEqualTo(PublishCompletion.CONFIRMED); - assertThat(result.routingOutcome()).isEqualTo(RoutingOutcome.ROUTED); - assertThat(result.evidence().confirmationLevel()) - .isEqualTo(ConfirmationLevel.REPLICATION_OR_PERSISTENCE_ACK); - } - - @Test - void aReturnFollowedByAConfirmIsRejectedAsUnroutable() { - CompletionStage stage = - coordinator.awaiting(1L, "notification.work", "missing", REPLICATION); - - coordinator.returned(1L); - coordinator.confirmed(1L, true, Duration.ofMillis(4)); - - PublishResult result = stage.toCompletableFuture().join(); - assertThat(result.completion()).isEqualTo(PublishCompletion.REJECTED); - assertThat(result.routingOutcome()).isEqualTo(RoutingOutcome.UNROUTABLE); - assertThat(result.evidence().confirmationLevel()).isEqualTo(ConfirmationLevel.NONE); - } - - @Test - void aReturnAloneDoesNotCompleteThePublish() { - CompletionStage stage = - coordinator.awaiting(1L, "notification.work", "missing", REPLICATION); - - coordinator.returned(1L); - - assertThat(stage.toCompletableFuture()).isNotDone(); - assertThat(coordinator.pendingCount()).isEqualTo(1); - } - - @Test - void aNackIsARejectedPublish() { - CompletionStage stage = - coordinator.awaiting(2L, "notification.work", "email", REPLICATION); - - coordinator.confirmed(2L, false, Duration.ofMillis(9)); - - PublishResult result = stage.toCompletableFuture().join(); - assertThat(result.completion()).isEqualTo(PublishCompletion.REJECTED); - assertThat(result.failure()).isPresent(); - } - - @Test - void aMissingConfirmIsAmbiguousRatherThanFailed() { - CompletionStage stage = - coordinator.awaiting(3L, "notification.work", "email", REPLICATION); - - coordinator.timedOut(3L, Duration.ofSeconds(5)); - - PublishResult result = stage.toCompletableFuture().join(); - assertThat(result.completion()).isEqualTo(PublishCompletion.AMBIGUOUS); - assertThat(result.mayHaveBeenStored()).isTrue(); - assertThat(result.evidence().confirmationLevel()).isEqualTo(ConfirmationLevel.NONE); - } - - @Test - void aConfirmedPublishCarriesItsExchangeAndSequence() { - CompletionStage stage = - coordinator.awaiting(7L, "notification.work", "email", REPLICATION); - - coordinator.confirmed(7L, true, Duration.ofMillis(1)); - - PublishResult result = stage.toCompletableFuture().join(); - assertThat(result.position()).isPresent(); - assertThat(result.position().orElseThrow().diagnosticAttributes()) - .containsEntry("exchange", "notification.work") - .containsEntry("routingKey", "email") - .containsEntry("sequence", "7"); - } - - @Test - void resolvingAPublishRemovesItFromThePendingSet() { - coordinator.awaiting(1L, "notification.work", "email", REPLICATION); - coordinator.confirmed(1L, true, Duration.ofMillis(1)); - - assertThat(coordinator.pendingCount()).isZero(); - } - - @Test - void anUnknownSequenceIsIgnoredRatherThanFailingTheChannel() { - coordinator.confirmed(99L, true, Duration.ofMillis(1)); - coordinator.returned(99L); - coordinator.timedOut(99L, Duration.ofMillis(1)); - - assertThat(coordinator.pendingCount()).isZero(); - } - - @Test - @org.junit.jupiter.api.DisplayName("a multiple ack resolves every pending publish up to the tag") - void aMultipleAckResolvesEveryPendingPublish() { - RabbitConfirmCoordinator coordinator = new RabbitConfirmCoordinator(); - java.util.concurrent.CompletableFuture - first = coordinator.awaiting(1L, "orders", "created", REPLICATION).toCompletableFuture(); - java.util.concurrent.CompletableFuture - second = coordinator.awaiting(2L, "orders", "created", REPLICATION).toCompletableFuture(); - java.util.concurrent.CompletableFuture - third = coordinator.awaiting(3L, "orders", "created", REPLICATION).toCompletableFuture(); - - coordinator.confirmed(2L, true, true, java.time.Duration.ofMillis(5)); - - assertThat(first) - .as("the multiple flag was dropped, so everything below the tag waited forever") - .isCompleted(); - assertThat(second).isCompleted(); - assertThat(third).isNotCompleted(); - assertThat(coordinator.pendingCount()).isEqualTo(1); - } - - @Test - @org.junit.jupiter.api.DisplayName("a nack records the frame as transmitted") - void aNackRecordsTheFrameAsTransmitted() { - RabbitConfirmCoordinator coordinator = new RabbitConfirmCoordinator(); - java.util.concurrent.CompletableFuture - pending = coordinator.awaiting(1L, "orders", "created", REPLICATION).toCompletableFuture(); - - coordinator.confirmed(1L, false, java.time.Duration.ofMillis(5)); - - assertThat(pending.join().evidence().transmission()) - .as("a NACK is the broker's answer to a frame it received") - .isEqualTo(dev.caskeleton.messaging.api.publish.TransmissionEvidence.TRANSMITTED); - } - - @Test - @org.junit.jupiter.api.DisplayName( - "a closed channel completes every pending publish as ambiguous") - void aClosedChannelCompletesEveryPendingPublish() { - RabbitConfirmCoordinator coordinator = new RabbitConfirmCoordinator(); - java.util.concurrent.CompletableFuture - pending = coordinator.awaiting(1L, "orders", "created", REPLICATION).toCompletableFuture(); - - assertThat(coordinator.channelClosed(java.time.Duration.ofMillis(5))).isEqualTo(1); - - assertThat(pending.join().completion()) - .as("the frames were written; a channel close says nothing about whether they were stored") - .isEqualTo(dev.caskeleton.messaging.api.publish.PublishCompletion.AMBIGUOUS); - assertThat(coordinator.pendingCount()).isZero(); - } -} diff --git a/src/messaging/messaging-rabbit/src/test/java/dev/caskeleton/messaging/rabbit/RabbitContractHarness.java b/src/messaging/messaging-rabbit/src/test/java/dev/caskeleton/messaging/rabbit/RabbitContractHarness.java deleted file mode 100644 index 54394d56..00000000 --- a/src/messaging/messaging-rabbit/src/test/java/dev/caskeleton/messaging/rabbit/RabbitContractHarness.java +++ /dev/null @@ -1,304 +0,0 @@ -package dev.caskeleton.messaging.rabbit; - -import dev.caskeleton.messaging.api.MessageId; -import dev.caskeleton.messaging.api.destination.ConfirmationRequirement; -import dev.caskeleton.messaging.api.error.FailureCategory; -import dev.caskeleton.messaging.api.error.FailureDescriptor; -import dev.caskeleton.messaging.api.publish.PublishCompletion; -import dev.caskeleton.messaging.api.publish.PublishEvidence; -import dev.caskeleton.messaging.api.publish.PublishResult; -import dev.caskeleton.messaging.api.publish.RoutingOutcome; -import dev.caskeleton.messaging.testkit.ContractMessage; -import dev.caskeleton.messaging.testkit.FaultController; -import dev.caskeleton.messaging.testkit.HandleOutcome; -import dev.caskeleton.messaging.testkit.MessagingAdapterHarness; -import dev.caskeleton.messaging.testkit.ObservedDelivery; -import java.time.Duration; -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.Deque; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Optional; -import java.util.Set; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CompletionStage; -import java.util.concurrent.atomic.AtomicLong; - -/** - * Runs the shared adapter contract against the real RabbitMQ confirm model. - * - *

Publishes go through the production {@link RabbitConfirmCoordinator}, which is the piece that - * has to get AMQP's confirm and return ordering right. Driving it from the harness is the only way - * to exercise a lost confirm deterministically — a live broker will not drop one on request. - * - *

Settlement goes through the production {@link RabbitSettlementController}, so the - * one-terminal-call guard and the DLQ-before-ack ordering are the real ones. - */ -final class RabbitContractHarness implements MessagingAdapterHarness { - - private static final int MAX_PAYLOAD_BYTES = 1_048_576; - private static final String EXCHANGE = "order.events"; - private static final String ROUTING_KEY = "created"; - - private final RabbitConfirmCoordinator coordinator = new RabbitConfirmCoordinator(); - private final AtomicLong sequence = new AtomicLong(); - private final AtomicLong deliveryTag = new AtomicLong(); - private final Faults faults = new Faults(); - private final Deque pending = new ArrayDeque<>(); - private final List deadLetters = new ArrayList<>(); - private final Set unsettled = new LinkedHashSet<>(); - - private boolean shuttingDown; - - static RabbitContractHarness create() { - return new RabbitContractHarness(); - } - - @Override - public String brokerName() { - return "rabbitmq"; - } - - @Override - public FaultController faults() { - return faults; - } - - @Override - public CompletionStage publish(ContractMessage message) { - if (shuttingDown) { - return CompletableFuture.completedFuture( - rejectedLocally("SHUTTING_DOWN", "the consumer is draining and accepts no new work")); - } - if (message.envelope().payload().size() > MAX_PAYLOAD_BYTES) { - return CompletableFuture.completedFuture( - rejectedLocally( - "PAYLOAD_TOO_LARGE", "encoded payload exceeds " + MAX_PAYLOAD_BYTES + " bytes")); - } - - long next = sequence.incrementAndGet(); - CompletionStage stage = - coordinator.awaiting( - next, EXCHANGE, ROUTING_KEY, ConfirmationRequirement.REPLICATION_OR_PERSISTENCE_ACK); - - if (faults.consumeRejectPublish()) { - coordinator.confirmed(next, false, Duration.ofMillis(2)); - } else if (faults.consumeDropPublishConfirmation()) { - coordinator.timedOut(next, Duration.ofSeconds(5)); - } else { - coordinator.confirmed(next, true, Duration.ofMillis(2)); - } - - return stage.thenApply( - result -> { - if (result.completion() == PublishCompletion.CONFIRMED) { - pending.addLast( - new Pending(message.messageId(), deliveryTag.incrementAndGet(), 1, false)); - } - return result; - }); - } - - @Override - public List drain(HandleOutcome outcome) { - List batch = new ArrayList<>(pending); - pending.clear(); - - List observed = new ArrayList<>(); - for (Pending delivery : batch) { - RabbitSettlementController controller = - new RabbitSettlementController(delivery.deliveryTag(), new HarnessOperations(delivery)); - boolean settled = - switch (outcome) { - case SUCCESS -> join(controller.ack()); - case RETRY -> join(controller.retry(Duration.ofSeconds(1))); - case DEAD_LETTER -> - join( - controller.deadLetter( - FailureDescriptor.of( - FailureCategory.PERMANENT_BUSINESS, - "CONTRACT_FAILURE", - "permanent failure"))); - }; - observed.add( - new ObservedDelivery( - delivery.messageId(), delivery.attempt(), delivery.redelivered(), settled)); - } - return List.copyOf(observed); - } - - private static boolean join( - CompletionStage stage) { - return stage.toCompletableFuture().join().completion() - == dev.caskeleton.messaging.api.settlement.SettlementCompletion.SETTLED; - } - - private void redeliver(Pending delivery) { - pending.addLast( - new Pending( - delivery.messageId(), deliveryTag.incrementAndGet(), delivery.attempt() + 1, true)); - } - - @Override - public List deadLettered() { - return List.copyOf(deadLetters); - } - - @Override - public List unsettled() { - return List.copyOf(unsettled); - } - - @Override - public void beginShutdown() { - shuttingDown = true; - } - - @Override - public boolean isAcceptingWork() { - return !shuttingDown; - } - - @Override - public void close() { - pending.clear(); - } - - private static PublishResult rejectedLocally(String code, String message) { - return new PublishResult( - PublishCompletion.REJECTED, - PublishEvidence.notTransmitted(), - RoutingOutcome.NOT_APPLICABLE, - Optional.empty(), - 1, - Duration.ZERO, - Optional.of(FailureDescriptor.of(FailureCategory.PERMANENT_BUSINESS, code, message))); - } - - /** One message in flight on the channel. */ - private record Pending(MessageId messageId, long deliveryTag, int attempt, boolean redelivered) {} - - /** The channel operations the settlement controller drives. */ - private final class HarnessOperations implements RabbitSettlementOperations { - - private final Pending delivery; - - private HarnessOperations(Pending delivery) { - this.delivery = delivery; - } - - @Override - public CompletionStage ack(long tag) { - if (faults.consumeDropSettlementConfirmation()) { - unsettled.add(delivery.messageId()); - redeliver(delivery); - return CompletableFuture.completedFuture(unknownSettlement()); - } - unsettled.remove(delivery.messageId()); - return CompletableFuture.completedFuture( - dev.caskeleton.messaging.api.settlement.SettlementResult.settled()); - } - - @Override - public CompletionStage - publishToRetryQueue(long tag, Duration delay) { - unsettled.add(delivery.messageId()); - redeliver(delivery); - return CompletableFuture.completedFuture(unknownSettlement()); - } - - /** Publishes to the dead letter destination first, and only then acknowledges the source. */ - @Override - public CompletionStage deadLetter( - long tag, FailureDescriptor failure) { - if (faults.deadLetterPublishFails()) { - unsettled.add(delivery.messageId()); - redeliver(delivery); - return CompletableFuture.completedFuture(unknownSettlement()); - } - deadLetters.add(delivery.messageId()); - unsettled.remove(delivery.messageId()); - return CompletableFuture.completedFuture( - dev.caskeleton.messaging.api.settlement.SettlementResult.settled()); - } - - @Override - public CompletionStage discard( - long tag, FailureDescriptor failure) { - unsettled.remove(delivery.messageId()); - return CompletableFuture.completedFuture( - dev.caskeleton.messaging.api.settlement.SettlementResult.settled()); - } - - private dev.caskeleton.messaging.api.settlement.SettlementResult unknownSettlement() { - return new dev.caskeleton.messaging.api.settlement.SettlementResult( - dev.caskeleton.messaging.api.settlement.SettlementCompletion.UNKNOWN, - dev.caskeleton.messaging.api.settlement.SettlementEvidence.unknown(), - Optional.of( - FailureDescriptor.of( - FailureCategory.AMBIGUOUS, - "SETTLEMENT_UNKNOWN", - "the settlement was not confirmed"))); - } - } - - /** One-shot fault flags. */ - private static final class Faults implements FaultController { - - private boolean dropPublishConfirmation; - private boolean dropSettlementConfirmation; - private boolean failDeadLetterPublish; - private boolean rejectPublish; - - @Override - public void dropPublishConfirmation() { - dropPublishConfirmation = true; - } - - @Override - public void dropSettlementConfirmation() { - dropSettlementConfirmation = true; - } - - @Override - public void failDeadLetterPublish() { - failDeadLetterPublish = true; - } - - @Override - public void rejectPublish() { - rejectPublish = true; - } - - @Override - public void reset() { - dropPublishConfirmation = false; - dropSettlementConfirmation = false; - failDeadLetterPublish = false; - rejectPublish = false; - } - - boolean consumeDropPublishConfirmation() { - boolean active = dropPublishConfirmation; - dropPublishConfirmation = false; - return active; - } - - boolean consumeDropSettlementConfirmation() { - boolean active = dropSettlementConfirmation; - dropSettlementConfirmation = false; - return active; - } - - boolean consumeRejectPublish() { - boolean active = rejectPublish; - rejectPublish = false; - return active; - } - - boolean deadLetterPublishFails() { - return failDeadLetterPublish; - } - } -} diff --git a/src/messaging/messaging-rabbit/src/test/java/dev/caskeleton/messaging/rabbit/RabbitEnvelopeRoundTripTest.java b/src/messaging/messaging-rabbit/src/test/java/dev/caskeleton/messaging/rabbit/RabbitEnvelopeRoundTripTest.java deleted file mode 100644 index 4a6f1057..00000000 --- a/src/messaging/messaging-rabbit/src/test/java/dev/caskeleton/messaging/rabbit/RabbitEnvelopeRoundTripTest.java +++ /dev/null @@ -1,152 +0,0 @@ -package dev.caskeleton.messaging.rabbit; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.messaging.api.ContentType; -import dev.caskeleton.messaging.api.CorrelationId; -import dev.caskeleton.messaging.api.MessageEnvelope; -import dev.caskeleton.messaging.api.MessageId; -import dev.caskeleton.messaging.api.MessageType; -import dev.caskeleton.messaging.api.ProducerId; -import dev.caskeleton.messaging.api.SchemaVersion; -import dev.caskeleton.messaging.api.TraceContext; -import dev.caskeleton.messaging.api.error.MessagingConfigurationException; -import dev.caskeleton.messaging.api.header.HeaderName; -import dev.caskeleton.messaging.api.header.HeaderValue; -import dev.caskeleton.messaging.api.header.MessageHeaders; -import dev.caskeleton.messaging.api.header.ReservedHeaders; -import dev.caskeleton.messaging.schema.EncodedMessage; -import java.nio.charset.StandardCharsets; -import java.time.Instant; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Optional; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.springframework.amqp.core.Message; -import org.springframework.amqp.core.MessageProperties; - -/** - * What an envelope still holds after it has been through RabbitMQ. - * - *

The publish and delivery mappers were written against each other's headers but never checked - * as one trip, so the application's own headers were dropped on the way back and the retry - * bookkeeping went with them — an attempt counter that restarts on every hop caps no redeliveries - * at all. - */ -class RabbitEnvelopeRoundTripTest { - - private static final Instant NOW = Instant.parse("2026-08-15T10:00:00Z"); - - private final RabbitHeaderMapper headerMapper = new RabbitHeaderMapper(); - - private final RabbitDeliveryMapper deliveryMapper = new RabbitDeliveryMapper(headerMapper); - - @Test - @DisplayName("an application header survives the trip through the broker") - void anApplicationHeaderSurvivesTheTrip() { - MessageEnvelope published = - envelope( - MessageHeaders.application( - Map.of(new HeaderName("x-source-system"), new HeaderValue("erp")))); - - MessageEnvelope delivered = roundTrip(published); - - assertThat(delivered.headers().find("x-source-system")) - .map(HeaderValue::value) - .as("a header the producer wrote and the consumer cannot read is a header nobody has") - .hasValue("erp"); - } - - @Test - @DisplayName("the tenant survives the trip instead of arriving as no tenant at all") - void theTenantSurvivesTheTrip() { - MessageEnvelope published = - envelope(MessageHeaders.empty()) - .withTenant(new dev.caskeleton.messaging.api.TenantContext("acme")); - - MessageEnvelope delivered = roundTrip(published); - - assertThat(delivered.tenantContext()) - .as("an AMQP message carries no ambient tenant, so an unwritten tenant is an absent one") - .contains(new dev.caskeleton.messaging.api.TenantContext("acme")); - } - - @Test - @DisplayName("the retry attempt survives the trip instead of restarting at one") - void theRetryAttemptSurvivesTheTrip() { - MessageEnvelope delivered = roundTrip(retryStamped(3)); - - assertThat(delivered.headers().find(ReservedHeaders.RETRY_ATTEMPT)) - .map(HeaderValue::value) - .as("an attempt counter that resets on every hop caps nothing") - .hasValue("3"); - } - - @Test - @DisplayName("a retry-stamped envelope can be published to its retry queue") - void aRetryStampedEnvelopeCanBePublished() { - assertThatCode(() -> headerMapper.toProperties(retryStamped(2))) - .as("the platform's own bookkeeping is not message content forging an identity") - .doesNotThrowAnyException(); - } - - @Test - @DisplayName("a header restating the message id is still refused") - void aForgedMessageIdIsStillRefused() { - MessageEnvelope forged = - envelope( - MessageHeaders.platform( - Map.of(new HeaderName(ReservedHeaders.MESSAGE_ID), new HeaderValue("forged")))); - - assertThatThrownBy(() -> headerMapper.toProperties(forged)) - .isInstanceOf(MessagingConfigurationException.class); - } - - @Test - @DisplayName("identity is read from its field, not duplicated into the header map") - void identityIsNotDuplicatedIntoTheHeaderMap() { - MessageEnvelope delivered = roundTrip(envelope(MessageHeaders.empty())); - - assertThat(delivered.headers().find(ReservedHeaders.MESSAGE_ID)) - .as("a copy that can drift from the field gives the same message two identities") - .isEmpty(); - } - - private MessageEnvelope roundTrip(MessageEnvelope published) { - MessageProperties properties = headerMapper.toProperties(published); - return deliveryMapper.toEnvelope(new Message(published.payload().bytes(), properties)); - } - - private static MessageEnvelope retryStamped(int attempt) { - Map headers = new LinkedHashMap<>(); - headers.put( - new HeaderName(ReservedHeaders.RETRY_ATTEMPT), new HeaderValue(Integer.toString(attempt))); - headers.put(new HeaderName(ReservedHeaders.LAST_FAILURE_AT), new HeaderValue(NOW.toString())); - return envelope(MessageHeaders.platform(headers)); - } - - private static MessageEnvelope envelope(MessageHeaders headers) { - return new MessageEnvelope<>( - MessageId.newId(), - new MessageType("order.created"), - new SchemaVersion(1), - NOW, - Optional.of(NOW), - new ProducerId("order-api"), - Optional.of(new CorrelationId("wf-1")), - Optional.empty(), - ContentType.JSON, - Optional.empty(), - Optional.empty(), - Optional.empty(), - TraceContext.none(), - headers, - new EncodedMessage( - "{\"orderId\":\"o-1\"}".getBytes(StandardCharsets.UTF_8), - ContentType.JSON, - Optional.empty())); - } -} diff --git a/src/messaging/messaging-rabbit/src/test/java/dev/caskeleton/messaging/rabbit/RabbitProfileValidatorTest.java b/src/messaging/messaging-rabbit/src/test/java/dev/caskeleton/messaging/rabbit/RabbitProfileValidatorTest.java deleted file mode 100644 index ba0f14f5..00000000 --- a/src/messaging/messaging-rabbit/src/test/java/dev/caskeleton/messaging/rabbit/RabbitProfileValidatorTest.java +++ /dev/null @@ -1,68 +0,0 @@ -package dev.caskeleton.messaging.rabbit; - -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import org.junit.jupiter.api.Test; - -class RabbitProfileValidatorTest { - - private final RabbitProfileValidator validator = new RabbitProfileValidator(); - - @Test - void stableProducerRequiresConfirms() { - assertThatThrownBy(() -> validator.validate(RabbitProfileFixtures.withoutConfirms())) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("publisher confirms"); - } - - @Test - void stableProducerRequiresReturnsBecauseAConfirmDoesNotProveRouting() { - assertThatThrownBy(() -> validator.validate(RabbitProfileFixtures.withoutReturns())) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("publisher returns"); - } - - @Test - void stableProducerRequiresMandatoryRouting() { - assertThatThrownBy(() -> validator.validate(RabbitProfileFixtures.withoutMandatory())) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("mandatory"); - } - - @Test - void consumerAutoAckIsForbidden() { - assertThatThrownBy(() -> validator.validate(RabbitProfileFixtures.withAutoAck())) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("auto ack"); - } - - @Test - void productionRequiresTlsAndAuthentication() { - assertThatThrownBy(() -> validator.validate(RabbitProfileFixtures.productionWithoutTls())) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("TLS"); - } - - @Test - void aDurableWorkQueueMustBeAQuorumQueue() { - assertThatThrownBy( - () -> - validator.validateDestination( - RabbitProfileFixtures.workQueueDestination(), - RabbitProfileFixtures.withoutQuorumQueues())) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("quorum"); - } - - @Test - void aStableProfileAndDestinationValidate() { - assertThatCode( - () -> { - validator.validate(RabbitProfileFixtures.stable()); - validator.validateDestination( - RabbitProfileFixtures.workQueueDestination(), RabbitProfileFixtures.stable()); - }) - .doesNotThrowAnyException(); - } -} diff --git a/src/messaging/messaging-rabbit/src/test/java/dev/caskeleton/messaging/rabbit/RabbitRuntimeTest.java b/src/messaging/messaging-rabbit/src/test/java/dev/caskeleton/messaging/rabbit/RabbitRuntimeTest.java deleted file mode 100644 index 903beaec..00000000 --- a/src/messaging/messaging-rabbit/src/test/java/dev/caskeleton/messaging/rabbit/RabbitRuntimeTest.java +++ /dev/null @@ -1,341 +0,0 @@ -package dev.caskeleton.messaging.rabbit; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.messaging.api.ContentType; -import dev.caskeleton.messaging.api.CorrelationId; -import dev.caskeleton.messaging.api.MessageEnvelope; -import dev.caskeleton.messaging.api.MessageId; -import dev.caskeleton.messaging.api.MessageType; -import dev.caskeleton.messaging.api.ProducerId; -import dev.caskeleton.messaging.api.SchemaVersion; -import dev.caskeleton.messaging.api.TraceContext; -import dev.caskeleton.messaging.api.header.MessageHeaders; -import dev.caskeleton.messaging.api.header.ReservedHeaders; -import dev.caskeleton.messaging.api.publish.PublishCompletion; -import dev.caskeleton.messaging.api.publish.PublishOptions; -import dev.caskeleton.messaging.api.publish.RoutingOutcome; -import dev.caskeleton.messaging.schema.EncodedMessage; -import dev.caskeleton.messaging.transport.GracefulShutdownCoordinator; -import dev.caskeleton.messaging.transport.TransportConsumerSpec; -import dev.caskeleton.messaging.transport.TransportDelivery; -import dev.caskeleton.messaging.transport.TransportPublishRequest; -import dev.caskeleton.messaging.transport.TransportPublishResult; -import java.nio.charset.StandardCharsets; -import java.time.Duration; -import java.time.Instant; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CompletionStage; -import java.util.concurrent.atomic.AtomicLong; -import org.junit.jupiter.api.Test; -import org.springframework.amqp.core.Message; - -class RabbitRuntimeTest { - - private static final Instant NOW = Instant.parse("2026-08-10T09:15:00Z"); - - private final AtomicLong sequence = new AtomicLong(); - private final List published = new ArrayList<>(); - private final List handled = new ArrayList<>(); - - private RabbitMessagingTransport transport() { - return new RabbitMessagingTransport( - "rabbit-primary", - 1, - new RabbitChannelPublisher() { - @Override - public long nextPublishSequence() { - return sequence.incrementAndGet(); - } - - @Override - public void publish( - long sequenceNumber, - String exchange, - String routingKey, - Message message, - boolean mandatory) { - published.add(message); - } - }); - } - - @Test - void aConfirmedPublishReportsRoutedWithReplicationEvidence() { - RabbitMessagingTransport transport = transport(); - - CompletionStage stage = transport.publish(request()); - transport.onConfirm(1L, true, Duration.ofMillis(3)); - - var result = stage.toCompletableFuture().join().result(); - assertThat(result.completion()).isEqualTo(PublishCompletion.CONFIRMED); - assertThat(result.routingOutcome()).isEqualTo(RoutingOutcome.ROUTED); - } - - @Test - void aReturnedThenConfirmedPublishIsRejectedAsUnroutable() { - RabbitMessagingTransport transport = transport(); - - CompletionStage stage = transport.publish(request()); - transport.onReturn(1L); - transport.onConfirm(1L, true, Duration.ofMillis(3)); - - var result = stage.toCompletableFuture().join().result(); - assertThat(result.completion()).isEqualTo(PublishCompletion.REJECTED); - assertThat(result.routingOutcome()).isEqualTo(RoutingOutcome.UNROUTABLE); - } - - @Test - void aMissingConfirmExpiresWithoutAnExternalTimeoutCallback() throws Exception { - try (RabbitMessagingTransport timed = - new RabbitMessagingTransport( - "rabbit-primary", - 1, - new RabbitChannelPublisher() { - @Override - public long nextPublishSequence() { - return sequence.incrementAndGet(); - } - - @Override - public void publish( - long sequenceNumber, - String exchange, - String routingKey, - Message message, - boolean mandatory) { - published.add(message); - } - }, - Duration.ofMillis(20))) { - CompletionStage stage = timed.publish(request()); - - var result = - stage.toCompletableFuture().get(1, java.util.concurrent.TimeUnit.SECONDS).result(); - assertThat(result.completion()).isEqualTo(PublishCompletion.AMBIGUOUS); - assertThat(timed.pendingConfirms()).isZero(); - } - } - - @Test - void aMissingConfirmIsAmbiguous() { - RabbitMessagingTransport transport = transport(); - - CompletionStage stage = transport.publish(request()); - transport.onConfirmTimeout(1L, Duration.ofSeconds(5)); - - assertThat(stage.toCompletableFuture().join().result().mayHaveBeenStored()).isTrue(); - } - - @Test - void anOversizedPayloadNeverReachesTheChannel() { - RabbitMessagingTransport transport = transport(); - - var result = - transport.publish(request(new byte[1_048_577])).toCompletableFuture().join().result(); - - assertThat(result.completion()).isEqualTo(PublishCompletion.REJECTED); - assertThat(published).isEmpty(); - } - - @Test - void aClosedTransportRefusesPublishesLocally() { - RabbitMessagingTransport transport = transport(); - transport.close(); - - var result = transport.publish(request()).toCompletableFuture().join().result(); - - assertThat(result.completion()).isEqualTo(PublishCompletion.REJECTED); - assertThat(transport.isAcceptingWork()).isFalse(); - assertThat(published).isEmpty(); - } - - @Test - void theHeaderRoundTripPreservesIdentityAndProvenance() { - RabbitHeaderMapper headers = new RabbitHeaderMapper(); - MessageEnvelope envelope = envelope(new byte[] {1, 2, 3}); - - var properties = headers.toProperties(envelope); - - assertThat(headers.value(properties, ReservedHeaders.MESSAGE_ID)) - .isEqualTo(envelope.messageId().value().toString()); - assertThat(headers.value(properties, ReservedHeaders.MESSAGE_TYPE)).isEqualTo("order.created"); - assertThat(headers.value(properties, ReservedHeaders.CORRELATION_ID)).isEqualTo("wf-1"); - assertThat(properties.getCorrelationId()).isEqualTo("wf-1"); - } - - @Test - void aDeliveryIsRebuiltFromItsHeaders() { - RabbitHeaderMapper headers = new RabbitHeaderMapper(); - MessageEnvelope original = envelope(new byte[] {1, 2, 3}); - Message message = new Message(new byte[] {1, 2, 3}, headers.toProperties(original)); - - var restored = new RabbitDeliveryMapper().toEnvelope(message); - - assertThat(restored.messageId()).isEqualTo(original.messageId()); - assertThat(restored.messageType()).isEqualTo(original.messageType()); - assertThat(restored.schemaVersion()).isEqualTo(original.schemaVersion()); - assertThat(restored.payload().bytes()).containsExactly(1, 2, 3); - } - - @Test - void theConsumerDispatchesAndSettlesThroughTheController() { - RecordingOperations operations = new RecordingOperations(); - RabbitConsumerRegistrar registrar = registrar(operations, this::acknowledge); - - boolean accepted = registrar.onMessage(deliveredMessage(7L), NOW); - - assertThat(accepted).isTrue(); - assertThat(handled).hasSize(1); - assertThat(operations.calls).containsExactly("ack:7"); - } - - @Test - void aPausedQueueRefusesDeliveriesSoTheBrokerRedeliversThem() { - RecordingOperations operations = new RecordingOperations(); - RabbitConsumerRegistrar registrar = registrar(operations, this::acknowledge); - registrar.pause("").toCompletableFuture().join(); - - boolean accepted = registrar.onMessage(deliveredMessage(7L), NOW); - - assertThat(accepted).isFalse(); - assertThat(handled).isEmpty(); - assertThat(operations.calls).isEmpty(); - } - - @Test - void drainingRefusesNewDeliveries() { - RecordingOperations operations = new RecordingOperations(); - GracefulShutdownCoordinator shutdown = new GracefulShutdownCoordinator(Duration.ofSeconds(30)); - try (RabbitConsumerRegistrar registrar = - new RabbitConsumerRegistrar( - new TransportConsumerSpec( - RabbitProfileFixtures.workQueueDestination(), this::acknowledge), - operations, - shutdown)) { - - shutdown.beginDrain(NOW); - boolean accepted = registrar.onMessage(deliveredMessage(7L), NOW); - - assertThat(accepted).isFalse(); - assertThat(operations.calls).isEmpty(); - } - } - - @Test - void anUndecodableMessageIsDiscardedRatherThanRequeued() { - RecordingOperations operations = new RecordingOperations(); - RabbitConsumerRegistrar registrar = registrar(operations, this::acknowledge); - - Message malformed = - new Message(new byte[] {1}, new org.springframework.amqp.core.MessageProperties()); - malformed.getMessageProperties().setDeliveryTag(9L); - - boolean accepted = registrar.onMessage(malformed, NOW); - - assertThat(accepted).isTrue(); - assertThat(handled).isEmpty(); - assertThat(operations.calls).containsExactly("discard:9"); - } - - private RabbitConsumerRegistrar registrar( - RabbitSettlementOperations operations, - java.util.function.Function> sink) { - return new RabbitConsumerRegistrar( - new TransportConsumerSpec(RabbitProfileFixtures.workQueueDestination(), sink), - operations, - new GracefulShutdownCoordinator(Duration.ofSeconds(30))); - } - - private CompletionStage acknowledge(TransportDelivery delivery) { - handled.add(delivery); - delivery.settlement().acknowledge().toCompletableFuture().join(); - return CompletableFuture.completedFuture(null); - } - - private Message deliveredMessage(long deliveryTag) { - Message message = - new Message( - "{\"orderId\":\"o-1\"}".getBytes(StandardCharsets.UTF_8), - new RabbitHeaderMapper().toProperties(envelope(new byte[] {1}))); - message.getMessageProperties().setDeliveryTag(deliveryTag); - message.getMessageProperties().setConsumerQueue("notification.email.q"); - return message; - } - - private TransportPublishRequest request() { - return request("{\"orderId\":\"o-1\"}".getBytes(StandardCharsets.UTF_8)); - } - - private TransportPublishRequest request(byte[] payload) { - return new TransportPublishRequest( - RabbitProfileFixtures.workQueueDestination(), envelope(payload), PublishOptions.defaults()); - } - - private MessageEnvelope envelope(byte[] payload) { - return new MessageEnvelope<>( - MessageId.newId(), - new MessageType("order.created"), - new SchemaVersion(1), - NOW, - Optional.of(NOW), - new ProducerId("order-api"), - Optional.of(new CorrelationId("wf-1")), - Optional.empty(), - ContentType.JSON, - Optional.empty(), - Optional.empty(), - Optional.empty(), - TraceContext.none(), - MessageHeaders.empty(), - new EncodedMessage(payload, ContentType.JSON, Optional.empty())); - } - - @Test - @org.junit.jupiter.api.DisplayName("a handler failure is retried, not discarded as undecodable") - void aHandlerFailureIsRetriedNotDiscarded() { - RecordingOperations operations = new RecordingOperations(); - RabbitConsumerRegistrar registrar = - registrar( - operations, - delivery -> { - throw new IllegalStateException("the projection is down"); - }); - - registrar.onMessage(deliveredMessage(11), NOW); - - assertThat(operations.calls) - .as("one catch covered decode, handler and settlement, so a retryable failure was deleted") - .containsExactly("retry:11:PT0S"); - } - - @Test - @org.junit.jupiter.api.DisplayName("a handler that never settles does not acknowledge") - void aHandlerThatNeverSettlesDoesNotAcknowledge() { - RecordingOperations operations = new RecordingOperations(); - RabbitConsumerRegistrar registrar = - registrar(operations, delivery -> CompletableFuture.completedFuture(null)); - - registrar.onMessage(deliveredMessage(12), NOW); - - assertThat(operations.calls) - .as("acknowledging on the handler's behalf silently drops a message nobody handled") - .containsExactly("retry:12:PT0S"); - } - - @Test - @org.junit.jupiter.api.DisplayName("a delivery after close is refused") - void aDeliveryAfterCloseIsRefused() { - RecordingOperations operations = new RecordingOperations(); - RabbitConsumerRegistrar registrar = - registrar(operations, delivery -> CompletableFuture.completedFuture(null)); - registrar.close(); - - assertThat(registrar.onMessage(deliveredMessage(13), NOW)) - .as("close only flipped a flag that onMessage never read") - .isFalse(); - } -} diff --git a/src/messaging/messaging-rabbit/src/test/java/dev/caskeleton/messaging/rabbit/RabbitSettlementControllerTest.java b/src/messaging/messaging-rabbit/src/test/java/dev/caskeleton/messaging/rabbit/RabbitSettlementControllerTest.java deleted file mode 100644 index f0cba51f..00000000 --- a/src/messaging/messaging-rabbit/src/test/java/dev/caskeleton/messaging/rabbit/RabbitSettlementControllerTest.java +++ /dev/null @@ -1,105 +0,0 @@ -package dev.caskeleton.messaging.rabbit; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.messaging.api.error.FailureCategory; -import dev.caskeleton.messaging.api.error.FailureDescriptor; -import dev.caskeleton.messaging.api.settlement.SettlementResult; -import java.time.Duration; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CompletionStage; -import org.junit.jupiter.api.Test; - -class RabbitSettlementControllerTest { - - private static final FailureDescriptor FAILURE = - FailureDescriptor.of(FailureCategory.PERMANENT_BUSINESS, "REJECTED", "rejected"); - - @Test - void acknowledgesExactlyOnce() { - RecordingOperations operations = new RecordingOperations(); - RabbitSettlementController controller = new RabbitSettlementController(7L, operations); - - controller.ack().toCompletableFuture().join(); - - assertThat(operations.calls).containsExactly("ack:7"); - assertThat(controller.isSettled()).isTrue(); - } - - @Test - void aSecondTerminalCallFailsRatherThanRacingTheFirst() { - RecordingOperations operations = new RecordingOperations(); - RabbitSettlementController controller = new RabbitSettlementController(7L, operations); - - controller.ack().toCompletableFuture().join(); - - assertThat(controller.ack().toCompletableFuture()).isCompletedExceptionally(); - assertThat(operations.calls).containsExactly("ack:7"); - } - - @Test - void mixingTerminalOperationsIsAlsoRefused() { - RecordingOperations operations = new RecordingOperations(); - RabbitSettlementController controller = new RabbitSettlementController(7L, operations); - - controller.deadLetter(FAILURE).toCompletableFuture().join(); - - assertThat(controller.ack().toCompletableFuture()).isCompletedExceptionally(); - assertThat(operations.calls).containsExactly("deadLetter:7"); - } - - @Test - void retryGoesToTheDelayedQueueRatherThanRequeueingImmediately() { - RecordingOperations operations = new RecordingOperations(); - RabbitSettlementController controller = new RabbitSettlementController(7L, operations); - - controller.retry(Duration.ofSeconds(30)).toCompletableFuture().join(); - - assertThat(operations.calls).containsExactly("retry:7:PT30S"); - } - - @Test - void aRetryQueueCarriesTtlAndADeadLetterRouteBackToTheWorkQueue() { - RabbitRetryQueueTopology topology = - new RabbitRetryQueueTopology( - "notification.email.retry.q", "notification.work", "email", Duration.ofSeconds(30)); - - assertThat(topology.queueArguments()) - .containsEntry("x-queue-type", "quorum") - .containsEntry("x-message-ttl", 30_000L) - .containsEntry("x-dead-letter-exchange", "notification.work") - .containsEntry("x-dead-letter-routing-key", "email"); - } -} - -/** Records which channel operation the controller invoked. */ -final class RecordingOperations implements RabbitSettlementOperations { - - final List calls = new ArrayList<>(); - - @Override - public CompletionStage ack(long deliveryTag) { - calls.add("ack:" + deliveryTag); - return CompletableFuture.completedFuture(SettlementResult.settled()); - } - - @Override - public CompletionStage publishToRetryQueue(long deliveryTag, Duration delay) { - calls.add("retry:" + deliveryTag + ":" + delay); - return CompletableFuture.completedFuture(SettlementResult.settled()); - } - - @Override - public CompletionStage deadLetter(long deliveryTag, FailureDescriptor failure) { - calls.add("deadLetter:" + deliveryTag); - return CompletableFuture.completedFuture(SettlementResult.settled()); - } - - @Override - public CompletionStage discard(long deliveryTag, FailureDescriptor failure) { - calls.add("discard:" + deliveryTag); - return CompletableFuture.completedFuture(SettlementResult.settled()); - } -} diff --git a/src/messaging/messaging-rabbit/src/test/java/dev/caskeleton/messaging/rabbit/RabbitTopologyAndBatchTest.java b/src/messaging/messaging-rabbit/src/test/java/dev/caskeleton/messaging/rabbit/RabbitTopologyAndBatchTest.java deleted file mode 100644 index 040513ea..00000000 --- a/src/messaging/messaging-rabbit/src/test/java/dev/caskeleton/messaging/rabbit/RabbitTopologyAndBatchTest.java +++ /dev/null @@ -1,253 +0,0 @@ -package dev.caskeleton.messaging.rabbit; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.messaging.api.error.MessagingConfigurationException; -import dev.caskeleton.messaging.api.publish.PublishCompletion; -import dev.caskeleton.messaging.api.publish.PublishResult; -import dev.caskeleton.messaging.api.publish.TransmissionEvidence; -import java.io.IOException; -import java.time.Duration; -import java.time.Instant; -import java.util.Optional; -import org.junit.jupiter.api.Test; - -class RabbitTopologyAndBatchTest { - - private static final Instant NOW = Instant.parse("2026-08-10T09:15:00Z"); - - private static RabbitTopologyProfile quorumWithDlx() { - return RabbitTopologyProfile.workQueue( - "notification.work", "email", "notification.email.q", "notification.dlx"); - } - - private static RabbitTopologyProfile classic() { - return new RabbitTopologyProfile( - "notification.work", - "direct", - "email", - "notification.email.q", - false, - Optional.empty(), - Optional.empty(), - Optional.empty()); - } - - @Test - void aDurableDestinationRequiresAQuorumQueue() { - assertThatThrownBy(() -> classic().requireSafeFor(true)) - .as("a promoted stale mirror loses messages the broker already confirmed") - .isInstanceOf(MessagingConfigurationException.class) - .hasMessageContaining("quorum"); - } - - @Test - void aQuorumQueueSatisfiesADurableDestination() { - assertThatCode(() -> quorumWithDlx().requireSafeFor(true)).doesNotThrowAnyException(); - } - - @Test - void theQueueArgumentsCarryTheDeclaredGuarantees() { - assertThat(quorumWithDlx().queueArguments()) - .containsEntry(RabbitTopologyProfile.QUEUE_TYPE, "quorum") - .containsEntry(RabbitTopologyProfile.DEAD_LETTER_EXCHANGE, "notification.dlx"); - } - - @Test - void aDeadLetterRoutingKeyWithoutAnExchangeIsRejected() { - assertThatThrownBy( - () -> - new RabbitTopologyProfile( - "x", - "direct", - "k", - "q", - true, - Optional.empty(), - Optional.of("k"), - Optional.empty())) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("routes nowhere"); - } - - @Test - void nativeDeadLetterNeedsBothADeclarationAndAVerifiedBinding() { - assertThat(new RabbitNativeDeadLetterCapability(quorumWithDlx(), true).mayUseNativeDeadLetter()) - .isTrue(); - assertThat( - new RabbitNativeDeadLetterCapability(quorumWithDlx(), false).mayUseNativeDeadLetter()) - .as("an unbound dead letter exchange discards the message while the reject still succeeds") - .isFalse(); - } - - @Test - void aQueueWithoutADeadLetterExchangeFallsBackToThePlatformPublish() { - RabbitNativeDeadLetterCapability capability = - new RabbitNativeDeadLetterCapability(classic(), true); - - assertThat(capability.requiresPlatformPublish()).isTrue(); - assertThat(capability.reasonForPlatformPublish()).contains("without a dead letter exchange"); - } - - @Test - void theUnboundReasonExplainsTheSilentDiscard() { - assertThat( - new RabbitNativeDeadLetterCapability(quorumWithDlx(), false).reasonForPlatformPublish()) - .contains("silently") - .contains("reporting success"); - } - - @Test - void aFailureBeforeTheFrameWasWrittenIsADefinitiveRejection() { - PublishResult result = - new RabbitPublishFailureClassifier() - .classify(new IllegalStateException("channel closed"), false, Duration.ofMillis(3)); - - assertThat(result.completion()).isEqualTo(PublishCompletion.REJECTED); - assertThat(result.evidence().transmission()).isEqualTo(TransmissionEvidence.NOT_TRANSMITTED); - } - - @Test - void aFailureAfterTheFrameWasWrittenIsAmbiguous() { - PublishResult result = - new RabbitPublishFailureClassifier() - .classify(new IOException("connection reset"), true, Duration.ofMillis(3)); - - assertThat(result.completion()) - .as("the broker may hold the message and only the confirm was lost") - .isEqualTo(PublishCompletion.AMBIGUOUS); - assertThat(result.evidence().transmission()) - .isEqualTo(TransmissionEvidence.MAY_HAVE_BEEN_TRANSMITTED); - } - - @Test - void authenticationFailureUsesTheTypedRabbitSignal() { - PublishResult result = - new RabbitPublishFailureClassifier() - .classify( - new com.rabbitmq.client.AuthenticationFailureException("bad credentials"), - false, - Duration.ofMillis(3)); - - assertThat(result.failure()) - .hasValueSatisfying( - failure -> - assertThat(failure.category()) - .isEqualTo(dev.caskeleton.messaging.api.error.FailureCategory.AUTHENTICATION)); - } - - @Test - void accessRefusedReplyCodeIsAuthorizationRatherThanBusinessRejection() { - com.rabbitmq.client.ShutdownSignalException accessRefused = - new com.rabbitmq.client.ShutdownSignalException( - false, - false, - new com.rabbitmq.client.impl.AMQImpl.Channel.Close(403, "ACCESS_REFUSED", 60, 40), - null); - - PublishResult result = - new RabbitPublishFailureClassifier().classify(accessRefused, false, Duration.ofMillis(3)); - - assertThat(result.failure()) - .hasValueSatisfying( - failure -> - assertThat(failure.category()) - .isEqualTo(dev.caskeleton.messaging.api.error.FailureCategory.AUTHORIZATION)); - } - - @Test - void aNackIsRejectedButStillCountsAsTransmitted() { - PublishResult result = new RabbitPublishFailureClassifier().nacked(Duration.ofMillis(3)); - - assertThat(result.completion()).isEqualTo(PublishCompletion.REJECTED); - assertThat(result.evidence().transmission()).isEqualTo(TransmissionEvidence.TRANSMITTED); - } - - @Test - void aBatchIsReleasedOnceItIsFull() { - RabbitBatchConsumerRegistrar registrar = - new RabbitBatchConsumerRegistrar( - RabbitProfileFixtures.workQueueDestination(), 3, Duration.ofSeconds(5)); - - assertThat(registrar.add(1, NOW)).isEmpty(); - assertThat(registrar.add(2, NOW)).isEmpty(); - assertThat(registrar.add(3, NOW)) - .hasValueSatisfying(batch -> assertThat(batch.deliveryTags()).containsExactly(1L, 2L, 3L)); - } - - @Test - void aPartialBatchIsReleasedOnceItsOldestDeliveryGoesStale() { - RabbitBatchConsumerRegistrar registrar = - new RabbitBatchConsumerRegistrar( - RabbitProfileFixtures.workQueueDestination(), 100, Duration.ofSeconds(5)); - registrar.add(1, NOW); - - assertThat(registrar.releaseIfStale(NOW.plusSeconds(1))).isEmpty(); - assertThat(registrar.releaseIfStale(NOW.plusSeconds(6))) - .as("a quiet queue would otherwise hold its last messages unacknowledged indefinitely") - .isPresent(); - } - - @Test - void anAccumulatedBatchIsNotSettlableAsAUnit() { - RabbitBatchConsumerRegistrar registrar = - new RabbitBatchConsumerRegistrar( - RabbitProfileFixtures.workQueueDestination(), 2, Duration.ofSeconds(5)); - registrar.add(1, NOW); - - assertThat(registrar.add(2, NOW)) - .hasValueSatisfying( - batch -> - assertThat(batch.metadata().settlableAsBatch()) - .as("AMQP multiple-ack settles work that is still in flight") - .isFalse()); - } - - @Test - void anAccumulatedBatchNamesExactlyOneOrderingUnit() { - RabbitBatchConsumerRegistrar registrar = - new RabbitBatchConsumerRegistrar( - RabbitProfileFixtures.workQueueDestination(), 1, Duration.ofSeconds(5)); - - assertThat(registrar.add(1, NOW)) - .hasValueSatisfying( - batch -> assertThat(batch.metadata().isSafeForOrderedDestination()).isTrue()); - } - - @Test - void aPrefetchBelowTheBatchSizeWouldDeadlockAndIsRefused() { - RabbitBatchConsumerRegistrar registrar = - new RabbitBatchConsumerRegistrar( - RabbitProfileFixtures.workQueueDestination(), 50, Duration.ofSeconds(5)); - - assertThatThrownBy(() -> registrar.requirePrefetchFor(10)) - .isInstanceOf(MessagingConfigurationException.class) - .hasMessageContaining("prefetch"); - assertThatCode(() -> registrar.requirePrefetchFor(100)).doesNotThrowAnyException(); - } - - @Test - void aZeroBatchAgeIsRefusedBecauseItStrandsQuietQueues() { - assertThatThrownBy( - () -> - new RabbitBatchConsumerRegistrar( - RabbitProfileFixtures.workQueueDestination(), 10, Duration.ZERO)) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void drainingReleasesWhateverIsPendingForShutdown() { - RabbitBatchConsumerRegistrar registrar = - new RabbitBatchConsumerRegistrar( - RabbitProfileFixtures.workQueueDestination(), 100, Duration.ofSeconds(5)); - registrar.add(1, NOW); - registrar.add(2, NOW); - - assertThat(registrar.drain(NOW)) - .hasValueSatisfying(batch -> assertThat(batch.deliveryTags()).hasSize(2)); - assertThat(registrar.pending()).isZero(); - assertThat(registrar.drain(NOW)).isEmpty(); - } -} diff --git a/src/messaging/messaging-rabbit/src/testFixtures/java/dev/caskeleton/messaging/rabbit/RabbitProfileFixtures.java b/src/messaging/messaging-rabbit/src/testFixtures/java/dev/caskeleton/messaging/rabbit/RabbitProfileFixtures.java deleted file mode 100644 index e505cd24..00000000 --- a/src/messaging/messaging-rabbit/src/testFixtures/java/dev/caskeleton/messaging/rabbit/RabbitProfileFixtures.java +++ /dev/null @@ -1,118 +0,0 @@ -package dev.caskeleton.messaging.rabbit; - -import dev.caskeleton.messaging.api.ContentType; -import dev.caskeleton.messaging.api.MessageType; -import dev.caskeleton.messaging.api.delivery.DeliveryGuarantee; -import dev.caskeleton.messaging.api.delivery.ExternalSideEffectGuarantee; -import dev.caskeleton.messaging.api.delivery.OrderingScope; -import dev.caskeleton.messaging.api.destination.DestinationKind; -import dev.caskeleton.messaging.api.destination.DestinationName; -import dev.caskeleton.messaging.policy.CapabilityTier; -import dev.caskeleton.messaging.policy.ConsumerPolicy; -import dev.caskeleton.messaging.policy.DeadLetterPolicy; -import dev.caskeleton.messaging.policy.DestinationProfile; -import dev.caskeleton.messaging.policy.PayloadPolicy; -import dev.caskeleton.messaging.policy.PhysicalDestination; -import dev.caskeleton.messaging.policy.ProducerPolicy; -import dev.caskeleton.messaging.policy.RetryPolicy; -import dev.caskeleton.messaging.policy.SchemaPolicy; -import dev.caskeleton.messaging.schema.SchemaCompatibility; -import java.time.Duration; -import java.util.List; -import java.util.Set; - -/** Builds RabbitMQ profiles for validator tests. */ -final class RabbitProfileFixtures { - - private RabbitProfileFixtures() {} - - static RabbitBrokerProfile stable() { - return new RabbitBrokerProfile( - "rabbit-primary", - true, - false, - List.of("localhost:5672"), - true, - true, - true, - Duration.ofSeconds(5), - false, - 16, - true, - true, - true); - } - - static RabbitBrokerProfile withoutConfirms() { - return copy(stable(), false, true, true, false, true, false, true); - } - - static RabbitBrokerProfile withoutReturns() { - return copy(stable(), true, false, true, false, true, false, true); - } - - static RabbitBrokerProfile withoutMandatory() { - return copy(stable(), true, true, false, false, true, false, true); - } - - static RabbitBrokerProfile withAutoAck() { - return copy(stable(), true, true, true, true, true, false, true); - } - - static RabbitBrokerProfile withoutQuorumQueues() { - return copy(stable(), true, true, true, false, false, false, true); - } - - static RabbitBrokerProfile productionWithoutTls() { - return copy(stable(), true, true, true, false, true, true, false); - } - - private static RabbitBrokerProfile copy( - RabbitBrokerProfile base, - boolean confirms, - boolean returns, - boolean mandatory, - boolean autoAck, - boolean quorumQueues, - boolean production, - boolean tlsEnabled) { - return new RabbitBrokerProfile( - base.broker(), - base.stable(), - production, - base.addresses(), - confirms, - returns, - mandatory, - base.confirmTimeout(), - autoAck, - base.prefetch(), - quorumQueues, - tlsEnabled, - base.authenticationEnabled()); - } - - static DestinationProfile workQueueDestination() { - return new DestinationProfile( - new DestinationName("email-work"), - "rabbit-primary", - DestinationKind.WORK_QUEUE, - PhysicalDestination.rabbitQueue("notification.work", "email", "notification.email.q"), - new SchemaPolicy( - ContentType.JSON, - SchemaCompatibility.BACKWARD, - Set.of(new MessageType("email.requested"))), - DeliveryGuarantee.AT_LEAST_ONCE, - OrderingScope.NONE, - ExternalSideEffectGuarantee.IDEMPOTENCY_REQUIRED, - ProducerPolicy.defaults(), - ConsumerPolicy.defaults("notification"), - RetryPolicy.none(), - DeadLetterPolicy.to(new DestinationName("email-work-dlq")), - PayloadPolicy.defaults(), - CapabilityTier.M1, - false, - false, - false); - } -} diff --git a/src/messaging/messaging-runtime-core/src/main/java/dev/caskeleton/messaging/runtime/DefaultMessagePublisher.java b/src/messaging/messaging-runtime-core/src/main/java/dev/caskeleton/messaging/runtime/DefaultMessagePublisher.java index 49425653..fe59a3ed 100644 --- a/src/messaging/messaging-runtime-core/src/main/java/dev/caskeleton/messaging/runtime/DefaultMessagePublisher.java +++ b/src/messaging/messaging-runtime-core/src/main/java/dev/caskeleton/messaging/runtime/DefaultMessagePublisher.java @@ -301,6 +301,14 @@ public final class DefaultMessagePublisher implements MessagePublisher, EncodedM } private MessageEnvelope encode(MessageEnvelope message) { + // The outbox relay, dead lettering and the retry topic republish bytes a codec already wrote. + // Encoding them again handed the codec a payload that is not its type, so each such publish was + // REJECTED (or, with a lenient codec, sent the envelope's toString). They go out as they are. + if (message.payload() instanceof EncodedMessage alreadyEncoded) { + MessageEnvelope encoded = message.withPayload(alreadyEncoded); + requireEncodedEnvelope(encoded); + return encoded; + } MessageCodec codec = codecs.find(message.contentType()).orElseGet(codecs::defaultCodec); EncodedMessage bytes = codec.encode(message.messageType(), message.schemaVersion(), message.payload()); diff --git a/src/messaging/messaging-runtime-core/src/test/java/dev/caskeleton/messaging/runtime/DefaultMessagePublisherTest.java b/src/messaging/messaging-runtime-core/src/test/java/dev/caskeleton/messaging/runtime/DefaultMessagePublisherTest.java index 510c4514..5302ed6d 100644 --- a/src/messaging/messaging-runtime-core/src/test/java/dev/caskeleton/messaging/runtime/DefaultMessagePublisherTest.java +++ b/src/messaging/messaging-runtime-core/src/test/java/dev/caskeleton/messaging/runtime/DefaultMessagePublisherTest.java @@ -10,9 +10,14 @@ import dev.caskeleton.messaging.api.MessageType; import dev.caskeleton.messaging.api.ProducerId; import dev.caskeleton.messaging.api.SchemaVersion; import dev.caskeleton.messaging.api.TraceContext; +import dev.caskeleton.messaging.api.delivery.DeliveryContext; +import dev.caskeleton.messaging.api.delivery.DeliveryMetadata; +import dev.caskeleton.messaging.api.delivery.MessageDelivery; import dev.caskeleton.messaging.api.destination.DestinationCapabilities; import dev.caskeleton.messaging.api.destination.DestinationName; import dev.caskeleton.messaging.api.destination.MessageDestination; +import dev.caskeleton.messaging.api.error.FailureCategory; +import dev.caskeleton.messaging.api.error.FailureDescriptor; import dev.caskeleton.messaging.api.error.MessagingConfigurationException; import dev.caskeleton.messaging.api.header.MessageHeaders; import dev.caskeleton.messaging.api.publish.ConfirmationLevel; @@ -21,6 +26,7 @@ import dev.caskeleton.messaging.api.publish.PublishEvidence; import dev.caskeleton.messaging.api.publish.PublishOptions; import dev.caskeleton.messaging.api.publish.PublishResult; import dev.caskeleton.messaging.api.publish.RoutingOutcome; +import dev.caskeleton.messaging.policy.DeadLetterOrchestrator; import dev.caskeleton.messaging.policy.InFlightLimiter; import dev.caskeleton.messaging.policy.MessagingAdmissionController; import dev.caskeleton.messaging.policy.PayloadLimitGuard; @@ -120,6 +126,55 @@ class DefaultMessagePublisherTest { assertThat(admission.inFlight()).isZero(); } + @Test + void aDeadLetterPublishedThroughThisPublisherReachesTheTransportWithTheOriginalBytes() { + // given + DestinationName deadLetters = new DestinationName("order-events-dlq"); + DefaultMessagePublisher publisher = + new DefaultMessagePublisher( + DestinationProfileRegistry.of( + Map.of( + ORDERS, + RuntimeFixtures.profile(ORDERS), + deadLetters, + RuntimeFixtures.profile(deadLetters))), + new DestinationAccessPolicy( + java.util.Set.of(deadLetters), java.util.Set.of(), java.util.Set.of()), + new SingleCodecRegistry(), + admission, + new FixedRuntimeRegistry(transport), + transport); + byte[] wireBytes = "{\"orderId\":\"o-1\"}".getBytes(StandardCharsets.UTF_8); + MessageDelivery failed = + new MessageDelivery<>( + envelope() + .withPayload(new EncodedMessage(wireBytes, ContentType.JSON, Optional.empty())), + new DeliveryMetadata( + ORDERS, + 3, + true, + Optional.empty(), + Optional.empty(), + Optional.of("order-projection"), + Instant.parse("2026-08-14T00:00:05Z")), + new DeliveryContext(Instant.parse("2026-08-14T00:00:35Z"), false, "order-projection")); + + // when + new DeadLetterOrchestrator(publisher) + .deadLetter( + RuntimeFixtures.profile(ORDERS), + failed, + FailureDescriptor.of(FailureCategory.PERMANENT_BUSINESS, "ORDER_REJECTED", "rejected"), + () -> CompletableFuture.completedFuture(null)) + .toCompletableFuture() + .join(); + + // then + assertThat(transport.lastRequest().envelope().payload().bytes()) + .as("encoding an already-encoded payload again rewrites the bytes or fails the codec") + .containsExactly(wireBytes); + } + @Test @DisplayName("an unregistered destination is rejected before anything is encoded") void anUnregisteredDestinationIsRejected() { diff --git a/src/messaging/messaging-spring-boot-starter-kafka/gradle.lockfile b/src/messaging/messaging-spring-boot-starter-kafka/gradle.lockfile index 53df71c2..ffc42112 100644 --- a/src/messaging/messaging-spring-boot-starter-kafka/gradle.lockfile +++ b/src/messaging/messaging-spring-boot-starter-kafka/gradle.lockfile @@ -34,8 +34,6 @@ commons-collections:commons-collections:3.2.2=checkstyle commons-io:commons-io:2.21.0=spotbugs commons-logging:commons-logging:1.3.6=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath info.picocli:picocli:4.7.7=checkstyle -io.cloudevents:cloudevents-api:4.0.1=runtimeClasspath,testRuntimeClasspath -io.cloudevents:cloudevents-core:4.0.1=runtimeClasspath,testRuntimeClasspath io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,testAnnotationProcessor io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,testAnnotationProcessor io.micrometer:micrometer-commons:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath diff --git a/src/messaging/messaging-spring-boot-starter-kafka/src/main/java/dev/caskeleton/messaging/autoconfigure/KafkaMessagingAutoConfiguration.java b/src/messaging/messaging-spring-boot-starter-kafka/src/main/java/dev/caskeleton/messaging/autoconfigure/KafkaMessagingAutoConfiguration.java index cc2b247e..bec88a6a 100644 --- a/src/messaging/messaging-spring-boot-starter-kafka/src/main/java/dev/caskeleton/messaging/autoconfigure/KafkaMessagingAutoConfiguration.java +++ b/src/messaging/messaging-spring-boot-starter-kafka/src/main/java/dev/caskeleton/messaging/autoconfigure/KafkaMessagingAutoConfiguration.java @@ -4,6 +4,7 @@ import dev.caskeleton.messaging.kafka.KafkaProfileValidator; import dev.caskeleton.messaging.kafka.KafkaPublishFailureClassifier; import dev.caskeleton.messaging.kafka.KafkaSecurityConfigurer; import dev.caskeleton.messaging.kafka.KafkaTransactionProfileValidator; +import dev.caskeleton.messaging.security.BrokerSecurityProfile; import dev.caskeleton.messaging.security.BrokerTlsPolicy; import dev.caskeleton.messaging.security.CredentialRuntimeRegistry; import org.springframework.beans.factory.ObjectProvider; @@ -24,13 +25,19 @@ import org.springframework.context.annotation.Configuration; * localhost:9092} — which in a test environment usually succeeds against something. * *

Reached only when app.messaging.broker=kafka selected it. The @ConditionalOnClass this used to - * carry could not select: the starter depends on messaging-kafka and messaging-rabbit, each of - * which exposes its client library as `api`, so both conditions were true for every adopter and - * both providers assembled. + * carry could not select: the starter then depended on two broker adapters, each of which exposed + * its client library as `api`, so both conditions were true for every adopter and both providers + * assembled. */ @Configuration(proxyBeanMethods = false) public class KafkaMessagingAutoConfiguration { + /** + * The two versions {@code BrokerTlsPolicy} accepts. No setting names them, so both are offered. + */ + private static final java.util.List TLS_PROTOCOLS = + java.util.List.of("TLSv1.3", "TLSv1.2"); + /** * Returns the Kafka destination profile validator. * @@ -123,12 +130,28 @@ public class KafkaMessagingAutoConfiguration { * and a serializer configured here would be a second encoder disagreeing with it. * * @param environment the resolved environment + * @param compiled the broker and security profiles compiled from {@code app.messaging} + * @param declaredSecurity the security profiles the application declared as beans + * @param securityConfigurer the Kafka security configurer, present only with a credential source * @return the producer, closed with the context */ @Bean(destroyMethod = "close") @ConditionalOnMissingBean public org.apache.kafka.clients.producer.Producer messagingKafkaProducer( - org.springframework.core.env.Environment environment) { + org.springframework.core.env.Environment environment, + CompiledMessagingConfiguration compiled, + ObjectProvider declaredSecurity, + ObjectProvider securityConfigurer) { + return new org.apache.kafka.clients.producer.KafkaProducer<>( + producerConfig(environment, compiled, declaredSecurity, securityConfigurer)); + } + + /** The producer's client configuration; package-visible so a test can read what it holds. */ + static java.util.Map producerConfig( + org.springframework.core.env.Environment environment, + CompiledMessagingConfiguration compiled, + ObjectProvider declaredSecurity, + ObjectProvider securityConfigurer) { String bootstrapServers = environment.getProperty("spring.kafka.bootstrap-servers", "").trim(); if (bootstrapServers.isEmpty()) { throw new IllegalStateException( @@ -150,7 +173,66 @@ public class KafkaMessagingAutoConfiguration { // failover, which is exactly the outcome an outbox exists to prevent. config.put(org.apache.kafka.clients.producer.ProducerConfig.ACKS_CONFIG, "all"); config.put(org.apache.kafka.clients.producer.ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, true); - return new org.apache.kafka.clients.producer.KafkaProducer<>(config); + config.putAll(producerSecurity(compiled, declaredSecurity, securityConfigurer)); + return config; + } + + /** + * The producer's security properties, from the one security profile of the Kafka broker. + * + *

{@code KafkaSecurityConfigurer} was a bean nothing called, so a broker that passed the TLS + * and credential checks was reached over plaintext with no authentication. Every case that cannot + * be applied fails startup rather than falling back to that. + */ + private static java.util.Map producerSecurity( + CompiledMessagingConfiguration compiled, + ObjectProvider declaredSecurity, + ObjectProvider securityConfigurer) { + java.util.Map kafkaBrokers = new java.util.TreeMap<>(); + compiled.brokers().entrySet().stream() + .filter(entry -> BrokerSettings.KAFKA.equalsIgnoreCase(entry.getValue().type())) + .forEach(entry -> kafkaBrokers.put(entry.getKey(), entry.getValue())); + // The same fallback as the runtime's logical name: bean-declared profiles name the family. + java.util.Set names = + kafkaBrokers.isEmpty() ? java.util.Set.of(BrokerSettings.KAFKA) : kafkaBrokers.keySet(); + java.util.List profiles = + java.util.stream.Stream.concat( + compiled.security().stream(), declaredSecurity.orderedStream()) + .filter(profile -> names.contains(profile.broker())) + .toList(); + + if (profiles.isEmpty()) { + kafkaBrokers.forEach( + (name, broker) -> { + if (broker.tlsEnabled() || broker.authenticationEnabled()) { + throw new IllegalStateException( + "Kafka broker '" + + name + + "' enables TLS or authentication but has no app.messaging.security." + + name + + " entry; the producer cannot apply either without one"); + } + }); + return java.util.Map.of(); + } + if (profiles.size() > 1) { + throw new IllegalStateException( + "the Kafka producer has one security posture but " + + profiles.size() + + " security profiles match " + + names); + } + BrokerSecurityProfile profile = profiles.getFirst(); + KafkaSecurityConfigurer configurer = securityConfigurer.getIfAvailable(); + if (configurer == null) { + throw new IllegalStateException( + "app.messaging.security." + + profile.broker() + + " is configured but no CredentialProvider bean exists; the producer cannot" + + " resolve its credential and must not connect without it"); + } + return configurer.configure( + profile, profile.producer(), TLS_PROTOCOLS, java.time.Instant.now()); } /** diff --git a/src/messaging/messaging-spring-boot-starter-rabbit/build.gradle b/src/messaging/messaging-spring-boot-starter-rabbit/build.gradle deleted file mode 100644 index 3635e1c8..00000000 --- a/src/messaging/messaging-spring-boot-starter-rabbit/build.gradle +++ /dev/null @@ -1,12 +0,0 @@ -plugins { - id 'ca.platform-module' - id 'ca.spring-config' -} - -dependencies { - // Capability artifact: Rabbit types/client exist only when this artifact is deliberately added. - api project(':messaging:messaging-spring-boot-starter') - api project(':messaging:messaging-rabbit') - - implementation 'org.springframework.boot:spring-boot-autoconfigure' -} diff --git a/src/messaging/messaging-spring-boot-starter-rabbit/gradle.lockfile b/src/messaging/messaging-spring-boot-starter-rabbit/gradle.lockfile deleted file mode 100644 index 1d3075d1..00000000 --- a/src/messaging/messaging-spring-boot-starter-rabbit/gradle.lockfile +++ /dev/null @@ -1,124 +0,0 @@ -# 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.fasterxml.jackson.core:jackson-annotations:2.21=runtimeClasspath,testRuntimeClasspath -com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,testAnnotationProcessor -com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,testAnnotationProcessor -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.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_annotations:2.41.0=spotbugs -com.google.errorprone:error_prone_annotations:2.47.0=checkstyle -com.google.errorprone:error_prone_annotations:2.49.0=annotationProcessor,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.5.0-jre=annotationProcessor,testAnnotationProcessor -com.google.guava:guava:33.6.0-jre=checkstyle -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.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins -com.puppycrawl.tools:checkstyle:13.5.0=checkstyle -com.rabbitmq:amqp-client:5.27.1=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -commons-beanutils:commons-beanutils:1.11.0=checkstyle -commons-collections:commons-collections:3.2.2=checkstyle -commons-io:commons-io:2.21.0=spotbugs -commons-logging:commons-logging:1.3.6=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -info.picocli:picocli:4.7.7=checkstyle -io.cloudevents:cloudevents-api:4.0.1=runtimeClasspath,testRuntimeClasspath -io.cloudevents:cloudevents-core:4.0.1=runtimeClasspath,testRuntimeClasspath -io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,testAnnotationProcessor -io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,testAnnotationProcessor -io.micrometer:micrometer-commons:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.micrometer:micrometer-core:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.micrometer:micrometer-observation:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.netty:netty-buffer:4.2.17.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.netty:netty-codec-base:4.2.17.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.netty:netty-codec-compression:4.2.17.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.netty:netty-codec-marshalling:4.2.17.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.netty:netty-codec-protobuf:4.2.17.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.netty:netty-codec:4.2.17.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.netty:netty-common:4.2.17.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.netty:netty-handler:4.2.17.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.netty:netty-resolver:4.2.17.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.netty:netty-transport-native-unix-common:4.2.17.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.netty:netty-transport:4.2.17.Final=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.projectreactor:reactor-core:3.8.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -javax.inject:javax.inject:1=annotationProcessor,testAnnotationProcessor -jaxen:jaxen:2.0.6=spotbugs -net.bytebuddy:byte-buddy:1.17.8=testCompileClasspath,testRuntimeClasspath -net.sf.saxon:Saxon-HE:12.9=checkstyle,spotbugs -org.antlr:antlr4-runtime:4.13.2=checkstyle -org.apache.bcel:bcel:6.12.0=spotbugs -org.apache.commons:commons-lang3:3.20.0=checkstyle,spotbugs -org.apache.commons:commons-text:1.15.0=spotbugs -org.apache.commons:commons-text:1.3=checkstyle -org.apache.httpcomponents:httpclient:4.5.13=checkstyle -org.apache.httpcomponents:httpcore:4.4.16=checkstyle -org.apache.logging.log4j:log4j-api:2.25.5=spotbugs -org.apache.logging.log4j:log4j-core:2.25.5=spotbugs -org.apache.maven.doxia:doxia-core:1.12.0=checkstyle -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 -org.assertj:assertj-core:3.27.7=testCompileClasspath,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.3.0=checkstyle -org.dom4j:dom4j:2.2.0=spotbugs -org.hdrhistogram:HdrHistogram:2.2.2=runtimeClasspath,testRuntimeClasspath -org.javassist:javassist:3.28.0-GA=checkstyle -org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,compileClasspath,runtimeClasspath,testAnnotationProcessor,testCompileClasspath,testRuntimeClasspath -org.junit.jupiter:junit-jupiter-api:6.0.3=testCompileClasspath,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-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.1.0=spotbugs -org.latencyutils:LatencyUtils:2.0.3=runtimeClasspath,testRuntimeClasspath -org.mockito:mockito-core:5.20.0=mockitoAgent -org.opentest4j:opentest4j:1.3.0=testCompileClasspath,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.reactivestreams:reactive-streams:1.0.4=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.reflections:reflections:0.10.2=checkstyle -org.slf4j:slf4j-api:2.0.18=compileClasspath,runtimeClasspath,spotbugs,spotbugsSlf4j,testCompileClasspath,testRuntimeClasspath -org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j -org.slf4j:slf4j-simple:2.0.18=checkstyle -org.springframework.amqp:spring-amqp:4.0.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.amqp:spring-rabbit:4.0.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-actuator:4.0.8=runtimeClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-autoconfigure:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.boot:spring-boot-configuration-processor:4.0.8=annotationProcessor -org.springframework.boot:spring-boot:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-aop:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-beans:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-context:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-core:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-expression:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-jdbc:7.0.9=runtimeClasspath,testRuntimeClasspath -org.springframework:spring-messaging:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-tx:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -org.xmlresolver:xmlresolver:5.3.3=checkstyle,spotbugs -tools.jackson.core:jackson-core:3.1.5=runtimeClasspath,testRuntimeClasspath -tools.jackson.core:jackson-databind:3.1.5=runtimeClasspath,testRuntimeClasspath -tools.jackson:jackson-bom:3.1.5=runtimeClasspath,testRuntimeClasspath -empty= diff --git a/src/messaging/messaging-spring-boot-starter-rabbit/src/main/java/dev/caskeleton/messaging/autoconfigure/RabbitMessagingAutoConfiguration.java b/src/messaging/messaging-spring-boot-starter-rabbit/src/main/java/dev/caskeleton/messaging/autoconfigure/RabbitMessagingAutoConfiguration.java deleted file mode 100644 index f64cd424..00000000 --- a/src/messaging/messaging-spring-boot-starter-rabbit/src/main/java/dev/caskeleton/messaging/autoconfigure/RabbitMessagingAutoConfiguration.java +++ /dev/null @@ -1,126 +0,0 @@ -package dev.caskeleton.messaging.autoconfigure; - -import dev.caskeleton.messaging.rabbit.RabbitProfileValidator; -import dev.caskeleton.messaging.rabbit.RabbitPublishFailureClassifier; -import dev.caskeleton.messaging.rabbit.RabbitSecurityConfigurer; -import dev.caskeleton.messaging.security.BrokerTlsPolicy; -import dev.caskeleton.messaging.security.CredentialRuntimeRegistry; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -/** - * Wires the RabbitMQ adapter's validators and security configurer. - * - *

Conditional on the AMQP client, for the same reason the Kafka configuration is conditional on - * the Kafka client: a service using one broker must not need the other on its classpath. - * - *

No connection or channel bean is created here. A channel opened before the application has - * declared its security profile would connect with whatever defaults the client carries, which for - * RabbitMQ means {@code guest/guest} against localhost. - * - *

Reached only when app.messaging.broker=rabbit selected it; see MessagingProviderSelection for - * why a classpath condition could not make this choice. - */ -@Configuration(proxyBeanMethods = false) -public class RabbitMessagingAutoConfiguration { - - /** - * Returns the RabbitMQ destination profile validator. - * - * @return the validator - */ - @Bean - @ConditionalOnMissingBean - public RabbitProfileValidator rabbitProfileValidator() { - return new RabbitProfileValidator(); - } - - /** - * Runs the RabbitMQ profile validator over every broker profile, declared or configured. - * - * @param profiles the broker profiles the application declared as beans - * @param compiled the broker profiles compiled from {@code app.messaging.brokers} - * @param validator the RabbitMQ profile validator - * @return the startup validation - */ - @Bean - public StartupProfileValidation - rabbitProfileStartupValidation( - org.springframework.beans.factory.ObjectProvider< - dev.caskeleton.messaging.rabbit.RabbitBrokerProfile> - profiles, - CompiledMessagingConfiguration compiled, - RabbitProfileValidator validator) { - return new StartupProfileValidation<>( - () -> - java.util.stream.Stream.concat( - configuredRabbitProfiles(compiled).stream(), profiles.orderedStream()) - .toList(), - validator::validate); - } - - /** - * Returns the publish failure classifier. - * - * @return the classifier - */ - @Bean - @ConditionalOnMissingBean - public RabbitPublishFailureClassifier rabbitPublishFailureClassifier() { - return new RabbitPublishFailureClassifier(); - } - - /** - * Returns the AMQP security configurer. - * - * @param credentials the credential runtime registry - * @param tlsPolicy the transport security policy - * @return the configurer - */ - /** - * The security configurer, which exists only when a credential source does. - * - *

It took {@code CredentialRuntimeRegistry} as a required parameter, and that registry is - * created only when the application supplies a {@code CredentialProvider}. Without one the - * context failed on a missing bean naming the registry — an error that describes the platform's - * internals rather than the one thing the operator has to do. The condition moves the failure to - * a place that can say so. - */ - @Bean - @ConditionalOnMissingBean - @org.springframework.boot.autoconfigure.condition.ConditionalOnBean( - CredentialRuntimeRegistry.class) - public RabbitSecurityConfigurer rabbitSecurityConfigurer( - CredentialRuntimeRegistry credentials, BrokerTlsPolicy tlsPolicy) { - return new RabbitSecurityConfigurer(credentials, tlsPolicy); - } - - private static java.util.List - configuredRabbitProfiles(CompiledMessagingConfiguration compiled) { - return compiled.brokers().entrySet().stream() - .filter( - entry -> - entry.getValue().type() != null - && entry.getValue().type().equalsIgnoreCase(BrokerSettings.RABBITMQ)) - .map( - entry -> { - BrokerSettings broker = entry.getValue(); - return new dev.caskeleton.messaging.rabbit.RabbitBrokerProfile( - entry.getKey(), - broker.stable(), - broker.production(), - broker.addresses(), - broker.publisherConfirms(), - broker.publisherReturns(), - broker.mandatory(), - broker.confirmTimeout(), - broker.autoAck(), - broker.prefetch(), - broker.quorumQueues(), - broker.tlsEnabled(), - broker.authenticationEnabled()); - }) - .toList(); - } -} diff --git a/src/messaging/messaging-spring-boot-starter/README.md b/src/messaging/messaging-spring-boot-starter/README.md index 9580cea2..2cb6c3e2 100644 --- a/src/messaging/messaging-spring-boot-starter/README.md +++ b/src/messaging/messaging-spring-boot-starter/README.md @@ -2,21 +2,21 @@ ## 아티팩트 분리 -기본 `messaging-spring-boot-starter`는 이제 **broker-neutral core**다. Kafka/Rabbit client를 +기본 `messaging-spring-boot-starter`는 이제 **broker-neutral core**다. Kafka client를 production runtime에 직접 넣지 않으며, 브로커 채택은 capability artifact를 composition에 추가하는 build-time 결정이다. ```text messaging-spring-boot-starter -├─ messaging-spring-boot-starter-kafka # Kafka client/transport capability -└─ messaging-spring-boot-starter-rabbit # Rabbit profile/validator capability +└─ messaging-spring-boot-starter-kafka # Kafka client/transport capability ``` -- 기본 app-bootstrap은 core starter만 가진다. 따라서 messaging off/default runtime에는 - `kafka-clients`, `spring-kafka`, `spring-rabbit`, `amqp-client`가 없다. -- Kafka를 채택하는 composition은 `:messaging:messaging-spring-boot-starter-kafka`를 추가한다. -- Rabbit capability도 별도 artifact지만, 아래 설명처럼 아직 production transport가 없어 - `app.messaging.broker=rabbit` 선택은 startup에서 거부된다. +- 기본 app-bootstrap은 messaging을 싣지 않는다. 서비스는 `runtimeOnly + project(':adapter:outbound:messaging-kafka')` 한 줄로 Kafka capability를 고르고, 그 모듈이 + `:messaging:messaging-spring-boot-starter-kafka`(와 이 core starter)를 runtime으로 끌어온다. +- starter는 있으면 켜진다(`app.messaging.enabled` 기본 on). `app.messaging.enabled=false`로만 끈다. +- 등록된 broker 계열은 Kafka 하나다. RabbitMQ 설정 키(`type: rabbitmq`, `addresses`, `prefetch` 등)는 + transport 없이 바인딩만 되던 키라 삭제했고, 지금은 키 이름을 담아 기동이 거부된다. - reliability/admin의 추가 artifact 분리는 별도 구조 개선 여지로 남지만, broker SDK 동시 탑재 문제와 transport 선택 문제는 core/broker capability 분리로 해소했다. - legacy R0 outbound bridge도 같은 원칙을 따른다. broker-neutral @@ -35,13 +35,9 @@ consume을 채택하려면 애플리케이션 composition이 별도로 `KafkaCon 조립해야 한다. leaf 안의 consumer/rebalance/settlement 테스트가 초록이라는 사실은 capability starter가 consumer runtime까지 자동 제공한다는 뜻이 아니다. -### RabbitMQ +### RabbitMQ (삭제됨) -RabbitMQ는 별도 capability artifact에 격리되어 있지만 **아직 선택할 수 없는 transport**다. -`app.messaging.broker=rabbit`을 설정하면 `MessagingProviderSelection`이 startup에서 거부한다. -이 leaf에는 validator, failure classifier, topology/security 부품과 테스트는 있지만 production -`RabbitChannelPublisher` 구현이 없어 `MessagingTransport`를 완성할 수 없다. - -현재 selectable broker는 Kafka뿐이다. Rabbit이 selectable로 승격되는 조건은 production -channel publisher/settlement bridge를 구현하고 starter composition 및 broker integration 증거를 -함께 추가하는 것이다. +production transport가 없어 선택할 수 없던 `messaging-rabbit`·`messaging-spring-boot-starter-rabbit`는 +2026-09-25에 삭제했다(`docs/capability-status.md` 제거 표). 현재 등록된 broker는 Kafka 하나다. +`app.messaging.brokers..type: rabbitmq` 설정 family는 아직 바인딩·검증되지만 소비하는 transport가 +없다. diff --git a/src/messaging/messaging-spring-boot-starter/build.gradle b/src/messaging/messaging-spring-boot-starter/build.gradle index 14167faa..acae04e6 100644 --- a/src/messaging/messaging-spring-boot-starter/build.gradle +++ b/src/messaging/messaging-spring-boot-starter/build.gradle @@ -6,15 +6,9 @@ plugins { // Scopes, not a flat list of `api`. // -// Sixteen internal leaves were exposed as `api`, so every adopter of the starter compiled against -// the Kafka adapter, the Rabbit adapter, both JDBC reliability leaves and the admin plane whether -// they used them or not — and both brokers' `@ConditionalOnClass` guards were true at once because -// the starter itself dragged in both clients. -// -// `api` is now the types that genuinely appear in this module's public signatures; everything else -// is `implementation`. Splitting the starter into per-capability artifacts (core / kafka / rabbit / -// reliability / admin) is the structural fix the review asks for and is a registry change of its -// own; this is the part that stops an adopter's compile classpath from containing two broker SDKs. +// `api` is the types that genuinely appear in this module's public signatures; everything else is +// `implementation`. Broker transports live in capability starters (messaging-spring-boot-starter-kafka), +// so this starter's compile classpath carries no broker SDK. auxiliarySourceSets { sourceSet('integrationTest') { compilesAgainst 'main' @@ -33,14 +27,12 @@ dependencies { // Wired by the auto-configurations and never named in an adopter's source. implementation project(':messaging:messaging-schema-json') - implementation project(':messaging:messaging-cloudevents') // The publisher and its collaborators live here. The starter did not depend on it at all, // which is why MessagingCoreAutoConfiguration consumed a MessagePublisher that nothing in // reach could produce (MSG-INT-003). implementation project(':messaging:messaging-runtime-core') implementation project(':messaging:messaging-outbox-jdbc-postgresql') implementation project(':messaging:messaging-inbox-jdbc-postgresql') - implementation project(':messaging:messaging-claim-check') implementation project(':messaging:messaging-admin-api') implementation project(':messaging:messaging-admin-runtime') @@ -56,9 +48,8 @@ dependencies { testImplementation 'org.springframework.boot:spring-boot-test' testImplementation 'org.springframework:spring-test' // Provider auto-configurations live in capability artifacts. Tests that exercise provider - // selection add them only to the test graph; the production starter remains broker-neutral. + // selection add it only to the test graph; the production starter remains broker-neutral. testImplementation project(':messaging:messaging-spring-boot-starter-kafka') - testImplementation project(':messaging:messaging-spring-boot-starter-rabbit') // Test-only, and specifically so the configuration reference can be executed rather than read: // MessagingConfigurationBindingTest loads the YAML blocks out of the shipped document and boots // a context on them. Spring Boot 4 treats snakeyaml as optional, so a document-driven test has diff --git a/src/messaging/messaging-spring-boot-starter/gradle.lockfile b/src/messaging/messaging-spring-boot-starter/gradle.lockfile index 7f5981c3..d606cfcf 100644 --- a/src/messaging/messaging-spring-boot-starter/gradle.lockfile +++ b/src/messaging/messaging-spring-boot-starter/gradle.lockfile @@ -32,7 +32,6 @@ com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,integrat com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins com.puppycrawl.tools:checkstyle:13.5.0=checkstyle -com.rabbitmq:amqp-client:5.27.1=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath commons-beanutils:commons-beanutils:1.11.0=checkstyle commons-codec:commons-codec:1.19.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath commons-collections:commons-collections:3.2.2=checkstyle @@ -40,24 +39,11 @@ commons-io:commons-io:2.20.0=integrationTestCompileClasspath,integrationTestRunt commons-io:commons-io:2.21.0=spotbugs commons-logging:commons-logging:1.3.6=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath info.picocli:picocli:4.7.7=checkstyle -io.cloudevents:cloudevents-api:4.0.1=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.cloudevents:cloudevents-core:4.0.1=integrationTestRuntimeClasspath,runtimeClasspath,testRuntimeClasspath io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor io.micrometer:micrometer-commons:1.16.7=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath io.micrometer:micrometer-core:1.16.7=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath io.micrometer:micrometer-observation:1.16.7=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -io.netty:netty-buffer:4.2.17.Final=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -io.netty:netty-codec-base:4.2.17.Final=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -io.netty:netty-codec-compression:4.2.17.Final=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -io.netty:netty-codec-marshalling:4.2.17.Final=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -io.netty:netty-codec-protobuf:4.2.17.Final=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -io.netty:netty-codec:4.2.17.Final=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -io.netty:netty-common:4.2.17.Final=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -io.netty:netty-handler:4.2.17.Final=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -io.netty:netty-resolver:4.2.17.Final=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -io.netty:netty-transport-native-unix-common:4.2.17.Final=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -io.netty:netty-transport:4.2.17.Final=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath io.projectreactor:reactor-core:3.8.7=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath io.projectreactor:reactor-test:3.8.7=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath javax.inject:javax.inject:1=annotationProcessor,integrationTestAnnotationProcessor,testAnnotationProcessor @@ -113,11 +99,9 @@ org.pcollections:pcollections:4.0.1=annotationProcessor,integrationTestAnnotatio org.reactivestreams:reactive-streams:1.0.4=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.reflections:reflections:0.10.2=checkstyle org.rnorth.duct-tape:duct-tape:1.0.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath -org.slf4j:slf4j-api:2.0.18=integrationTestCompileClasspath,integrationTestRuntimeClasspath,spotbugs,spotbugsSlf4j,testCompileClasspath,testRuntimeClasspath +org.slf4j:slf4j-api:2.0.18=integrationTestCompileClasspath,integrationTestRuntimeClasspath,spotbugs,spotbugsSlf4j,testRuntimeClasspath org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j org.slf4j:slf4j-simple:2.0.18=checkstyle -org.springframework.amqp:spring-amqp:4.0.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework.amqp:spring-rabbit:4.0.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-actuator:4.0.8=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-autoconfigure:4.0.8=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework.boot:spring-boot-configuration-processor:4.0.8=annotationProcessor @@ -129,9 +113,8 @@ org.springframework:spring-context:7.0.9=compileClasspath,integrationTestCompile org.springframework:spring-core:7.0.9=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework:spring-expression:7.0.9=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework:spring-jdbc:7.0.9=integrationTestRuntimeClasspath,runtimeClasspath,testRuntimeClasspath -org.springframework:spring-messaging:7.0.9=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework:spring-test:7.0.9=integrationTestCompileClasspath,integrationTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-tx:7.0.9=integrationTestCompileClasspath,integrationTestRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath +org.springframework:spring-tx:7.0.9=integrationTestRuntimeClasspath,runtimeClasspath,testRuntimeClasspath org.testcontainers:testcontainers-junit-jupiter:2.0.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath org.testcontainers:testcontainers-kafka:2.0.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath org.testcontainers:testcontainers:2.0.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath diff --git a/src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/BrokerSettings.java b/src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/BrokerSettings.java index 5274dd5b..fb3a1112 100644 --- a/src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/BrokerSettings.java +++ b/src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/BrokerSettings.java @@ -7,18 +7,16 @@ import org.springframework.boot.context.properties.bind.DefaultValue; /** * One entry of {@code app.messaging.brokers}. * - *

Both broker families are described by one record because a deployment names its brokers in one - * map, and a reader of that map should not have to know which half of the fields apply. Which half - * does apply is decided by {@link #type()}, and the compiler refuses a field belonging to the other - * family rather than ignoring it — a Kafka broker carrying {@code prefetch} is a configuration the - * author believed was doing something. + *

Kafka is the one broker family this platform has a transport for, so the record carries only + * Kafka fields. RabbitMQ fields used to live here too and bound with no transport behind them: a + * deployment could configure a RabbitMQ broker that nothing would ever connect to. * *

{@code tlsEnabled} and {@code production} live here rather than beside the credentials, so a * broker is described once. They were previously implied by whichever object happened to be * constructed, which is how a profile can be production in one validator's view and not in * another's. * - * @param type the broker family, {@code kafka} or {@code rabbitmq} + * @param type the broker family; {@code kafka} is the only one * @param stable whether this profile claims the Stable guarantees * @param production whether this profile is used in production * @param tlsEnabled whether transport encryption is on @@ -30,14 +28,6 @@ import org.springframework.boot.context.properties.bind.DefaultValue; * @param deliveryTimeout the Kafka producer delivery deadline * @param enableAutoCommit whether the Kafka consumer commits offsets on a timer * @param consumerGroup the Kafka consumer group - * @param addresses RabbitMQ broker addresses - * @param publisherConfirms whether correlated publisher confirms are on - * @param publisherReturns whether unroutable returns are delivered - * @param mandatory whether publishes carry the mandatory flag - * @param confirmTimeout how long to wait for a RabbitMQ confirm - * @param autoAck whether the RabbitMQ consumer acknowledges on delivery - * @param prefetch the RabbitMQ consumer prefetch window - * @param quorumQueues whether durable work queues are declared as quorum queues */ public record BrokerSettings( String type, @@ -51,19 +41,8 @@ public record BrokerSettings( @DefaultValue("5") int maxInFlightRequestsPerConnection, @DefaultValue("30s") Duration deliveryTimeout, @DefaultValue("false") boolean enableAutoCommit, - @DefaultValue("") String consumerGroup, - @DefaultValue List addresses, - @DefaultValue("true") boolean publisherConfirms, - @DefaultValue("true") boolean publisherReturns, - @DefaultValue("true") boolean mandatory, - @DefaultValue("5s") Duration confirmTimeout, - @DefaultValue("false") boolean autoAck, - @DefaultValue("16") int prefetch, - @DefaultValue("true") boolean quorumQueues) { + @DefaultValue("") String consumerGroup) { /** The broker family a Kafka entry declares. */ public static final String KAFKA = "kafka"; - - /** The broker family a RabbitMQ entry declares. */ - public static final String RABBITMQ = "rabbitmq"; } diff --git a/src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/MessagingConfigurationCompiler.java b/src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/MessagingConfigurationCompiler.java index dca2d398..88fa8cbf 100644 --- a/src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/MessagingConfigurationCompiler.java +++ b/src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/MessagingConfigurationCompiler.java @@ -101,19 +101,11 @@ public final class MessagingConfigurationCompiler { + "localhost:9092 and fails at the first publish rather than at startup"); } } - case BrokerSettings.RABBITMQ -> { - if (broker.addresses().isEmpty()) { - throw configurationError( - key("brokers", name, "addresses"), - "a RabbitMQ broker needs at least one address; a client with none defaults to " - + "localhost and connects as guest"); - } - } default -> throw configurationError( key("brokers", name, "type"), - "'%s' is not a broker family this platform binds; use '%s' or '%s'" - .formatted(broker.type(), BrokerSettings.KAFKA, BrokerSettings.RABBITMQ)); + "'%s' is not a broker family this platform has a transport for; use '%s'" + .formatted(broker.type(), BrokerSettings.KAFKA)); } } diff --git a/src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/MessagingConfigurationKeyValidator.java b/src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/MessagingConfigurationKeyValidator.java index 84e9baa7..b5c534a2 100644 --- a/src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/MessagingConfigurationKeyValidator.java +++ b/src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/MessagingConfigurationKeyValidator.java @@ -5,7 +5,6 @@ import java.lang.reflect.RecordComponent; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; -import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Set; @@ -38,29 +37,6 @@ import org.springframework.core.env.PropertySource; */ public final class MessagingConfigurationKeyValidator implements InitializingBean { - /** Broker keys that only a Kafka entry may carry. */ - private static final Set KAFKA_ONLY_KEYS = - Set.of( - "bootstrap-servers", - "enable-idempotence", - "acks", - "max-in-flight-requests-per-connection", - "delivery-timeout", - "enable-auto-commit", - "consumer-group"); - - /** Broker keys that only a RabbitMQ entry may carry. */ - private static final Set RABBIT_ONLY_KEYS = - Set.of( - "addresses", - "publisher-confirms", - "publisher-returns", - "mandatory", - "confirm-timeout", - "auto-ack", - "prefetch", - "quorum-queues"); - private final ConfigurableEnvironment environment; /** @@ -102,8 +78,6 @@ public final class MessagingConfigurationKeyValidator implements InitializingBea rejected.add( "%s binds nothing; %s entries accept %s" .formatted(key, section, legal.stream().sorted().toList())); - } else if ("brokers".equals(section)) { - wrongFamily(entry).ifPresent(rejected::add); } } }); @@ -125,32 +99,6 @@ public final class MessagingConfigurationKeyValidator implements InitializingBea + (rejected.size() > 10 ? " (and " + (rejected.size() - 10) + " more)" : "")); } - /** - * Reports a broker key that belongs to the other broker family. - * - *

Both families are described by one record, so a Kafka entry carrying {@code prefetch} binds - * without complaint and does nothing. The author of that line believed it was doing something, - * which is the same silence this class exists to end. - */ - private java.util.Optional wrongFamily(Entry entry) { - String declared = - environment.getProperty( - MessagingSettings.PREFIX + ".brokers." + entry.name() + ".type", ""); - String family = declared.toLowerCase(Locale.ROOT); - String leaf = entry.leaf(); - if (BrokerSettings.KAFKA.equals(family) && RABBIT_ONLY_KEYS.contains(leaf)) { - return java.util.Optional.of( - "%s.brokers.%s.%s is a RabbitMQ setting on a Kafka broker" - .formatted(MessagingSettings.PREFIX, entry.name(), leaf)); - } - if (BrokerSettings.RABBITMQ.equals(family) && KAFKA_ONLY_KEYS.contains(leaf)) { - return java.util.Optional.of( - "%s.brokers.%s.%s is a Kafka setting on a RabbitMQ broker" - .formatted(MessagingSettings.PREFIX, entry.name(), leaf)); - } - return java.util.Optional.empty(); - } - /** One configuration key split into the map entry it configures and the leaf inside it. */ private record Entry(String name, String leaf) {} diff --git a/src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/MessagingCoreAutoConfiguration.java b/src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/MessagingCoreAutoConfiguration.java index 81b0602a..a61db179 100644 --- a/src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/MessagingCoreAutoConfiguration.java +++ b/src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/MessagingCoreAutoConfiguration.java @@ -516,7 +516,6 @@ public class MessagingCoreAutoConfiguration { String configuredFamily = switch (selected.brokerName()) { case "kafka" -> BrokerSettings.KAFKA; - case "rabbit" -> BrokerSettings.RABBITMQ; default -> selected.brokerName(); }; java.util.List configuredNames = diff --git a/src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/MessagingPlatformRootAutoConfiguration.java b/src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/MessagingPlatformRootAutoConfiguration.java index 8e3b8163..3534ca20 100644 --- a/src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/MessagingPlatformRootAutoConfiguration.java +++ b/src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/MessagingPlatformRootAutoConfiguration.java @@ -20,13 +20,18 @@ import org.springframework.context.annotation.Import; * whichever bean won. Selection now reads {@code app.messaging.broker} against a closed registry, * and a value outside it is a startup error rather than a context with no provider at all. * - *

{@code app.messaging.enabled=false} means no beans, no clients, no threads, and no bound - * detail namespace. {@code MessagingStarterOffContractTest} holds that against a full context - * including this starter's owned imports. Vendor auto-configuration is verified in its own runtime - * lanes. + *

On when present: a missing {@code app.messaging.enabled} means on, because an application that + * put this starter on its classpath chose messaging. {@code app.messaging.enabled=false} means no + * beans, no clients, no threads, and no bound detail namespace. {@code + * MessagingStarterOffContractTest} holds that against a full context including this starter's owned + * imports. Vendor auto-configuration is verified in its own runtime lanes. */ @AutoConfiguration -@ConditionalOnProperty(prefix = MessagingSettings.PREFIX, name = "enabled", havingValue = "true") +@ConditionalOnProperty( + prefix = MessagingSettings.PREFIX, + name = "enabled", + havingValue = "true", + matchIfMissing = true) @EnableConfigurationProperties(MessagingSettings.class) @Import({ MessagingCoreAutoConfiguration.class, diff --git a/src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/MessagingProviderSelection.java b/src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/MessagingProviderSelection.java index 227965c9..91cf33bb 100644 --- a/src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/MessagingProviderSelection.java +++ b/src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/MessagingProviderSelection.java @@ -13,9 +13,9 @@ import org.springframework.util.ClassUtils; /** * Selects exactly one transport, from a closed registry, by name (MSG-INT-004). * - *

Selection used to be {@code @ConditionalOnClass}: Kafka assembled because a Kafka class was on - * the classpath and Rabbit because a Rabbit class was, so an application with both libraries — one - * transitive dependency is enough — assembled both and published through whichever bean won a + *

Selection used to be {@code @ConditionalOnClass}: a transport assembled because its client + * class was on the classpath, so an application with two client libraries — one transitive + * dependency is enough — assembled both and published through whichever bean won a * {@code @ConditionalOnMissingBean} race. Nothing failed; the message simply went somewhere nobody * chose. * @@ -25,7 +25,8 @@ import org.springframework.util.ClassUtils; *

  • a broker id outside the registry — the operator set something the platform cannot honour; *
  • a registered broker whose client library is absent — a deployment that asked for Kafka and * shipped without it is told so, instead of starting with no publisher at all; - *
  • a blank broker while messaging is on — the master switch says yes and nothing says what to. + *
  • a blank broker while messaging is on — the capability switch says yes and nothing says what + * to. * * *

    The provider configurations carry no condition of their own any more. Each is reached only @@ -38,58 +39,21 @@ public class MessagingProviderSelection { /** Broker id to the client class that must be present for it to be honoured. */ static final Map REGISTERED_BROKERS = - Map.of( - "kafka", "org.apache.kafka.clients.producer.Producer", - "rabbit", "com.rabbitmq.client.Channel"); + Map.of("kafka", "org.apache.kafka.clients.producer.Producer"); /** Broker id to the configuration that assembles it. */ static final Map PROVIDER_CONFIGURATIONS = - Map.of( - "kafka", "dev.caskeleton.messaging.autoconfigure.KafkaMessagingAutoConfiguration", - "rabbit", "dev.caskeleton.messaging.autoconfigure.RabbitMessagingAutoConfiguration"); + Map.of("kafka", "dev.caskeleton.messaging.autoconfigure.KafkaMessagingAutoConfiguration"); /** Broker id to the starter a deployment adds to its build to obtain that transport. */ static final Map PROVIDER_STARTERS = - Map.of( - "kafka", "messaging-spring-boot-starter-kafka", - "rabbit", "messaging-spring-boot-starter-rabbit"); - - /** - * Broker ids that ship without a {@code MessagingTransport}, and why. - * - *

    Registered is not the same as assemblable. The Rabbit leaf ships its profile validator, - * failure classifier and security configurer, and no transport — the native channel bridge those - * would sit on has only test implementations. Selecting it therefore produced an unsatisfied - * dependency on {@code MessagingTransport} deep inside the core configuration, which tells an - * operator that a bean is missing rather than that the transport they chose is not finished. - * - *

    Refused here instead, next to the other selection errors, so the message names the state the - * deployment is actually in. An entry leaves this map on the day its transport does exist. - */ - static final Map BROKERS_WITHOUT_A_TRANSPORT = - Map.of( - "rabbit", - "the Rabbit adapter ships its validators and security configuration but no " - + "MessagingTransport: its native channel publisher is not implemented, so a publish " - + "has nothing to travel on"); + Map.of("kafka", "messaging-spring-boot-starter-kafka"); /** The registered broker ids, so a message can tell an operator what is available. */ public static List registeredBrokerIds() { return REGISTERED_BROKERS.keySet().stream().sorted().toList(); } - /** - * The registered broker ids that actually assemble a transport. - * - * @return the ids a deployment can select today - */ - public static List assemblableBrokerIds() { - return REGISTERED_BROKERS.keySet().stream() - .filter(id -> !BROKERS_WITHOUT_A_TRANSPORT.containsKey(id)) - .sorted() - .toList(); - } - /** * Resolves the selection, or throws naming the property and the values it accepts. * @@ -141,17 +105,6 @@ public class MessagingProviderSelection { + " module on the classpath; this core starter is broker-neutral and the deployment" + " did not compose the transport it selected"); } - String unfinished = BROKERS_WITHOUT_A_TRANSPORT.get(broker); - if (unfinished != null) { - throw new IllegalStateException( - MessagingSettings.PREFIX - + ".broker=" - + broker - + " cannot be selected: " - + unfinished - + ". Transports that can be assembled today: " - + assemblableBrokerIds()); - } return broker; } diff --git a/src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/MessagingSettings.java b/src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/MessagingSettings.java index 92fef985..9985b6e3 100644 --- a/src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/MessagingSettings.java +++ b/src/messaging/messaging-spring-boot-starter/src/main/java/dev/caskeleton/messaging/autoconfigure/MessagingSettings.java @@ -20,11 +20,6 @@ import org.springframework.boot.context.properties.ConfigurationProperties; * the failure it prevents (a deployment split across two prefixes, each half-configuring the * platform) is worse than an actionable startup error. * - *

    Every Experimental and bridge flag defaults to {@code false}. An adapter whose contract suite - * is still being proven must not become load-bearing because a default turned it on, and the same - * applies to the Spring Cloud Stream bridge, which bypasses the platform's retry and dead letter - * policy by design. - * *

    The destination, broker and security maps are what the configuration reference has always * described and nothing bound. Until they existed, a deployment that configured them exactly as * documented changed no behaviour and produced no error: the profiles the platform actually used @@ -48,8 +43,6 @@ public class MessagingSettings { /** The prefix the configuration reference documented, which nothing ever bound. */ public static final String DOCUMENTED_PREFIX = "messaging"; - private final Experimental experimental = new Experimental(); - private final Bridge bridge = new Bridge(); private final Backpressure backpressure = new Backpressure(); private final Shutdown shutdown = new Shutdown(); private Map destinations = new LinkedHashMap<>(); @@ -110,24 +103,6 @@ public class MessagingSettings { this.security = new LinkedHashMap<>(security); } - /** - * Returns the experimental adapter switches. - * - * @return the experimental settings - */ - public Experimental getExperimental() { - return experimental; - } - - /** - * Returns the optional bridge switches. - * - * @return the bridge settings - */ - public Bridge getBridge() { - return bridge; - } - /** * Returns the backpressure limits. * @@ -146,92 +121,6 @@ public class MessagingSettings { return shutdown; } - /** Experimental adapter switches, all off by default. */ - public static class Experimental { - - private boolean kafkaShare; - private boolean pulsar; - private boolean nats; - - /** - * Reports whether the Kafka Share Group adapter is enabled. - * - * @return true when enabled - */ - public boolean isKafkaShare() { - return kafkaShare; - } - - /** - * Enables or disables the Kafka Share Group adapter. - * - * @param kafkaShare whether to enable it - */ - public void setKafkaShare(boolean kafkaShare) { - this.kafkaShare = kafkaShare; - } - - /** - * Reports whether the Pulsar adapter is enabled. - * - * @return true when enabled - */ - public boolean isPulsar() { - return pulsar; - } - - /** - * Enables or disables the Pulsar adapter. - * - * @param pulsar whether to enable it - */ - public void setPulsar(boolean pulsar) { - this.pulsar = pulsar; - } - - /** - * Reports whether the NATS JetStream adapter is enabled. - * - * @return true when enabled - */ - public boolean isNats() { - return nats; - } - - /** - * Enables or disables the NATS JetStream adapter. - * - * @param nats whether to enable it - */ - public void setNats(boolean nats) { - this.nats = nats; - } - } - - /** Optional integration bridges, off by default. */ - public static class Bridge { - - private boolean springCloudStream; - - /** - * Reports whether the Spring Cloud Stream bridge is enabled. - * - * @return true when enabled - */ - public boolean isSpringCloudStream() { - return springCloudStream; - } - - /** - * Enables or disables the Spring Cloud Stream bridge. - * - * @param springCloudStream whether to enable it - */ - public void setSpringCloudStream(boolean springCloudStream) { - this.springCloudStream = springCloudStream; - } - } - /** In-flight limits. */ public static class Backpressure { diff --git a/src/messaging/messaging-spring-boot-starter/src/test/java/dev/caskeleton/messaging/autoconfigure/KafkaProducerSecurityTest.java b/src/messaging/messaging-spring-boot-starter/src/test/java/dev/caskeleton/messaging/autoconfigure/KafkaProducerSecurityTest.java new file mode 100644 index 00000000..ac651f8e --- /dev/null +++ b/src/messaging/messaging-spring-boot-starter/src/test/java/dev/caskeleton/messaging/autoconfigure/KafkaProducerSecurityTest.java @@ -0,0 +1,151 @@ +package dev.caskeleton.messaging.autoconfigure; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.messaging.kafka.KafkaSecurityConfigurer; +import dev.caskeleton.messaging.security.BrokerSecurityProfile; +import dev.caskeleton.messaging.security.CredentialProvider; +import java.time.Instant; +import java.util.Map; +import java.util.Optional; +import org.junit.jupiter.api.Test; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.test.context.assertj.AssertableApplicationContext; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * What the Kafka producer is actually configured with once {@code app.messaging.security} says how. + * + *

    The security settings were bound, compiled and validated, and {@code KafkaSecurityConfigurer} + * was a bean nothing called: the producer was built from the bootstrap address, serializers, acks + * and idempotence alone, so a broker that passed the TLS and credential checks was reached over + * plaintext with no authentication. + */ +class KafkaProducerSecurityTest { + + // Assembled through the root, as an application is: the import order it fixes is what lets the + // configurer see the credential registry. + private final ApplicationContextRunner runner = + new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(MessagingPlatformRootAutoConfiguration.class)) + .withPropertyValues( + "app.messaging.enabled=true", + "app.messaging.broker=kafka", + "spring.kafka.bootstrap-servers=localhost:9092", + "app.messaging.brokers.kafka-primary.type=kafka", + "app.messaging.brokers.kafka-primary.bootstrap-servers[0]=localhost:9092"); + + private static final String[] SCRAM_CREDENTIALS = { + "app.messaging.security.kafka-primary.producer.type=SASL_SCRAM", + "app.messaging.security.kafka-primary.producer.credential-id=kafka-producer", + "app.messaging.security.kafka-primary.consumer.type=SASL_SCRAM", + "app.messaging.security.kafka-primary.consumer.credential-id=kafka-consumer", + }; + + @Test + void aTlsBrokerWithScramCredentialsConfiguresTheProducerForSaslSsl() { + runner + .withUserConfiguration(Credentials.class) + .withPropertyValues(SCRAM_CREDENTIALS) + .withPropertyValues( + "app.messaging.brokers.kafka-primary.tls-enabled=true", + "app.messaging.brokers.kafka-primary.authentication-enabled=true") + .run( + context -> + assertThat(producerConfig(context)) + .extractingByKeys( + "security.protocol", + "sasl.mechanism", + "ssl.enabled.protocols", + "ssl.endpoint.identification.algorithm") + .containsExactly("SASL_SSL", "SCRAM-SHA-512", "TLSv1.3,TLSv1.2", "https")); + } + + @Test + void aPlaintextBrokerWithPasswordCredentialsConfiguresTheProducerForSaslPlaintext() { + runner + .withUserConfiguration(Credentials.class) + .withPropertyValues( + "app.messaging.brokers.kafka-primary.authentication-enabled=true", + "app.messaging.security.kafka-primary.producer.type=USERNAME_PASSWORD", + "app.messaging.security.kafka-primary.producer.credential-id=kafka-producer", + "app.messaging.security.kafka-primary.consumer.type=USERNAME_PASSWORD", + "app.messaging.security.kafka-primary.consumer.credential-id=kafka-consumer") + .run( + context -> + assertThat(producerConfig(context)) + .extractingByKeys("security.protocol", "sasl.mechanism") + .containsExactly("SASL_PLAINTEXT", "PLAIN")); + } + + @Test + void theProducerLogsInWithTheProducerCredentialResolvedFromTheProvider() { + runner + .withUserConfiguration(Credentials.class) + .withPropertyValues(SCRAM_CREDENTIALS) + .withPropertyValues("app.messaging.brokers.kafka-primary.tls-enabled=true") + .run( + context -> + assertThat(String.valueOf(producerConfig(context).get("sasl.jaas.config"))) + .startsWith("org.apache.kafka.common.security.scram.ScramLoginModule required") + .contains("username=\"kafka-producer\"", "password=\"" + Credentials.SECRET)); + } + + @Test + void aBrokerDeclaringTlsWithoutASecurityEntryFailsStartup() { + runner + .withPropertyValues("app.messaging.brokers.kafka-primary.tls-enabled=true") + .run( + context -> + assertThat(context) + .hasFailed() + .getFailure() + .as("a producer that cannot apply TLS connected over plaintext instead") + .hasMessageContaining("app.messaging.security.kafka-primary")); + } + + @Test + void aSecurityEntryWithoutACredentialProviderFailsStartup() { + runner + .withPropertyValues(SCRAM_CREDENTIALS) + .run( + context -> + assertThat(context) + .hasFailed() + .getFailure() + .as("a producer that cannot resolve its credential connected without one") + .hasMessageContaining("CredentialProvider")); + } + + private static Map producerConfig(AssertableApplicationContext context) { + return KafkaMessagingAutoConfiguration.producerConfig( + context.getEnvironment(), + context.getBean(CompiledMessagingConfiguration.class), + context.getBeanProvider(BrokerSecurityProfile.class), + context.getBeanProvider(KafkaSecurityConfigurer.class)); + } + + /** A credential source that answers every id with the same test secret. */ + @Configuration(proxyBeanMethods = false) + static class Credentials { + + static final String SECRET = "test-only-secret"; + + @Bean + CredentialProvider credentialProvider() { + return new CredentialProvider() { + @Override + public char[] resolve(String credentialId) { + return SECRET.toCharArray(); + } + + @Override + public Optional expiresAt(String credentialId) { + return Optional.empty(); + } + }; + } + } +} diff --git a/src/messaging/messaging-spring-boot-starter/src/test/java/dev/caskeleton/messaging/autoconfigure/MessagingAutoConfigurationTest.java b/src/messaging/messaging-spring-boot-starter/src/test/java/dev/caskeleton/messaging/autoconfigure/MessagingAutoConfigurationTest.java index ba6b2c71..6c829229 100644 --- a/src/messaging/messaging-spring-boot-starter/src/test/java/dev/caskeleton/messaging/autoconfigure/MessagingAutoConfigurationTest.java +++ b/src/messaging/messaging-spring-boot-starter/src/test/java/dev/caskeleton/messaging/autoconfigure/MessagingAutoConfigurationTest.java @@ -98,30 +98,16 @@ class MessagingAutoConfigurationTest { .hasMessageContaining("exactly one logical broker")); } - @Test - void experimentalAdaptersAndTheBridgeAreOffByDefault() { - runner.run( - context -> { - MessagingSettings properties = context.getBean(MessagingSettings.class); - assertThat(properties.getExperimental().isKafkaShare()).isFalse(); - assertThat(properties.getExperimental().isPulsar()).isFalse(); - assertThat(properties.getExperimental().isNats()).isFalse(); - assertThat(properties.getBridge().isSpringCloudStream()).isFalse(); - }); - } - @Test void propertiesBindFromConfiguration() { runner .withPropertyValues( - "app.messaging.experimental.pulsar=true", "app.messaging.backpressure.global-limit=64", "app.messaging.backpressure.per-destination-limit=8", "app.messaging.shutdown.drain-deadline=15s") .run( context -> { MessagingSettings properties = context.getBean(MessagingSettings.class); - assertThat(properties.getExperimental().isPulsar()).isTrue(); assertThat(properties.getBackpressure().getGlobalLimit()).isEqualTo(64); assertThat(properties.getShutdown().getDrainDeadline()) .isEqualTo(java.time.Duration.ofSeconds(15)); diff --git a/src/messaging/messaging-spring-boot-starter/src/test/java/dev/caskeleton/messaging/autoconfigure/MessagingConfigurationBindingTest.java b/src/messaging/messaging-spring-boot-starter/src/test/java/dev/caskeleton/messaging/autoconfigure/MessagingConfigurationBindingTest.java index 437ca3f8..73f8a08b 100644 --- a/src/messaging/messaging-spring-boot-starter/src/test/java/dev/caskeleton/messaging/autoconfigure/MessagingConfigurationBindingTest.java +++ b/src/messaging/messaging-spring-boot-starter/src/test/java/dev/caskeleton/messaging/autoconfigure/MessagingConfigurationBindingTest.java @@ -67,15 +67,12 @@ class MessagingConfigurationBindingTest { CompiledMessagingConfiguration compiled = context.getBean(CompiledMessagingConfiguration.class); - assertThat(compiled.brokers()).containsKeys("kafka-primary", "rabbit-primary"); + assertThat(compiled.brokers()).containsOnlyKeys("kafka-primary"); BrokerSettings kafka = compiled.brokers().get("kafka-primary"); assertThat(kafka.type()).isEqualTo(BrokerSettings.KAFKA); assertThat(kafka.bootstrapServers()) .containsExactly("broker-1:9093", "broker-2:9093"); assertThat(kafka.enableAutoCommit()).isFalse(); - BrokerSettings rabbit = compiled.brokers().get("rabbit-primary"); - assertThat(rabbit.type()).isEqualTo(BrokerSettings.RABBITMQ); - assertThat(rabbit.quorumQueues()).isTrue(); assertThat(compiled.security()) .singleElement() .satisfies( @@ -175,7 +172,7 @@ class MessagingConfigurationBindingTest { } @Test - void aRabbitSettingOnAKafkaBrokerFailsNamingTheKey() { + void aRabbitMqSettingBindsNothingAndFailsNamingTheKey() { runner .withPropertyValues(minimal()) .withPropertyValues("app.messaging.brokers.kafka-primary.prefetch=32") @@ -184,8 +181,22 @@ class MessagingConfigurationBindingTest { assertThat(context) .hasFailed() .getFailure() - .hasMessageContaining("app.messaging.brokers.kafka-primary.prefetch") - .hasMessageContaining("RabbitMQ setting on a Kafka broker")); + .hasMessageContaining( + "app.messaging.brokers.kafka-primary.prefetch binds nothing")); + } + + @Test + void aRabbitMqBrokerIsRefusedBecauseNoTransportExists() { + runner + .withPropertyValues( + "app.messaging.brokers.rabbit-primary.type=rabbitmq", + "app.messaging.brokers.rabbit-primary.bootstrap-servers[0]=rabbit:5672") + .run( + context -> + assertThat(context) + .hasFailed() + .getFailure() + .hasMessageContaining("app.messaging.brokers.rabbit-primary.type")); } @Test diff --git a/src/messaging/messaging-spring-boot-starter/src/test/java/dev/caskeleton/messaging/autoconfigure/MessagingStarterOffContractTest.java b/src/messaging/messaging-spring-boot-starter/src/test/java/dev/caskeleton/messaging/autoconfigure/MessagingStarterOffContractTest.java index 033fb0dd..4da59b9e 100644 --- a/src/messaging/messaging-spring-boot-starter/src/test/java/dev/caskeleton/messaging/autoconfigure/MessagingStarterOffContractTest.java +++ b/src/messaging/messaging-spring-boot-starter/src/test/java/dev/caskeleton/messaging/autoconfigure/MessagingStarterOffContractTest.java @@ -15,17 +15,16 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; -import org.springframework.util.ClassUtils; /** * Off means nothing, and on means exactly one transport (MSG-INT-004). * *

    The starter registered five auto-configurations and none carried a messaging master condition, * so an application acquired the platform by having the starter on its classpath. Worse, provider - * selection was {@code @ConditionalOnClass} while this starter depends on {@code messaging-kafka} - * and {@code messaging-rabbit}, each of which exposes its client library as {@code api} — so both - * conditions are true for **every** adopter, always. Selection by classpath could not select; it - * assembled both and let a {@code @ConditionalOnMissingBean} race decide where messages went. + * selection was {@code @ConditionalOnClass} while this starter depended on two broker adapters, + * each exposing its client library as {@code api} — so both conditions were true for **every** + * adopter, always. Selection by classpath could not select; it assembled both and let a + * {@code @ConditionalOnMissingBean} race decide where messages went. * *

    The cases below are the replacement contract. The off case is deliberately checked on bean * names and live threads rather than on a handful of types: a platform that leaves a scheduler @@ -38,40 +37,41 @@ class MessagingStarterOffContractTest { .withConfiguration(AutoConfigurations.of(MessagingPlatformRootAutoConfiguration.class)); @Test - @DisplayName( - "both client libraries really are on this classpath, so the old condition could not select") - void bothClientLibrariesArePresent() { - ClassLoader loader = getClass().getClassLoader(); - - assertThat(ClassUtils.isPresent("org.apache.kafka.clients.producer.Producer", loader)) - .as("messaging-kafka exposes kafka-clients as api") - .isTrue(); - assertThat(ClassUtils.isPresent("com.rabbitmq.client.Channel", loader)) - .as("messaging-rabbit exposes spring-rabbit as api") - .isTrue(); + @DisplayName("present without the switch is on") + void presentWithoutTheSwitchIsOn() { + runner + .withPropertyValues( + "app.messaging.broker=kafka", "spring.kafka.bootstrap-servers=localhost:9092") + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context).hasSingleBean(MessagePublisher.class); + }); } @Test @DisplayName("with the switch off there are no platform beans") void offMeansNoBeans() { - runner.run( - context -> { - assertThat(context).hasNotFailed(); + runner + .withPropertyValues("app.messaging.enabled=false") + .run( + context -> { + assertThat(context).hasNotFailed(); - Set platformBeans = - java.util.Arrays.stream(context.getBeanDefinitionNames()) - .filter( - name -> { - Class type = context.getBeanFactory().getType(name, false); - return type != null - && type.getName().startsWith("dev.caskeleton.messaging."); - }) - .collect(Collectors.toSet()); + Set platformBeans = + java.util.Arrays.stream(context.getBeanDefinitionNames()) + .filter( + name -> { + Class type = context.getBeanFactory().getType(name, false); + return type != null + && type.getName().startsWith("dev.caskeleton.messaging."); + }) + .collect(Collectors.toSet()); - assertThat(platformBeans) - .as("off is a structural fact, not a set of individually-conditioned beans") - .isEmpty(); - }); + assertThat(platformBeans) + .as("off is a structural fact, not a set of individually-conditioned beans") + .isEmpty(); + }); } @Test @@ -79,7 +79,9 @@ class MessagingStarterOffContractTest { void offMeansNoThreads() { Set before = liveThreadNames(); - runner.run(context -> assertThat(context).hasNotFailed()); + runner + .withPropertyValues("app.messaging.enabled=false") + .run(context -> assertThat(context).hasNotFailed()); assertThat(newMessagingThreadsSince(before)) .as("a bean that exists but was never started is acceptable; a running thread is not") @@ -111,11 +113,11 @@ class MessagingStarterOffContractTest { .hasFailed() .getFailure() .rootCause() - .hasMessageContaining("registered: [kafka, rabbit]")); + .hasMessageContaining("registered: [kafka]")); } @Test - @DisplayName("selecting Kafka assembles Kafka and not Rabbit") + @DisplayName("selecting Kafka assembles Kafka") void selectingKafkaAssemblesOnlyKafka() { withAPublisher() .withPropertyValues( @@ -126,48 +128,9 @@ class MessagingStarterOffContractTest { context -> { assertThat(context).hasNotFailed(); assertThat(context).hasSingleBean(KafkaMessagingAutoConfiguration.class); - assertThat(context) - .as("both client libraries are present, so only the property can be selecting") - .doesNotHaveBean(RabbitMessagingAutoConfiguration.class); }); } - @Test - @DisplayName("selecting Rabbit is refused, and the message says the transport is not finished") - void selectingRabbitIsRefused() { - // This test used to run under `withAPublisher()` and assert the context started. The fake - // MessagePublisher tripped @ConditionalOnMissingBean and removed the very bean whose missing - // dependency is the defect — so a configuration that cannot start in any deployment passed as - // "assembles Rabbit and not Kafka". Without the fake, the real behaviour appears. - // - // Rabbit ships validators and a security configurer and no MessagingTransport, because its - // native channel publisher has only test implementations. That is refused at selection now, - // where the message can say so, rather than surfacing as "No qualifying bean of type - // MessagingTransport" from inside the core configuration. - runner - .withPropertyValues("app.messaging.enabled=true", "app.messaging.broker=rabbit") - .run( - context -> { - assertThat(context).hasFailed(); - assertThat(context.getStartupFailure()) - .rootCause() - .hasMessageContaining("app.messaging.broker=rabbit") - .hasMessageContaining("no MessagingTransport") - .hasMessageContaining("kafka"); - }); - } - - @Test - @DisplayName("a fake publisher does not make an unassemblable transport look assemblable") - void aFakePublisherDoesNotHideAnUnassemblableTransport() { - // The guard on the test above. Supplying a MessagePublisher removes the dependency that fails, - // so if the refusal ever moves back to bean wiring this case goes green while the deployment - // stays broken. Selection-time refusal is what makes it fail either way. - withAPublisher() - .withPropertyValues("app.messaging.enabled=true", "app.messaging.broker=rabbit") - .run(context -> assertThat(context).hasFailed()); - } - @Test @DisplayName("MSG-INT-003: a selected transport now assembles a publisher") void aSelectedTransportAssemblesAPublisher() { @@ -279,8 +242,6 @@ class MessagingStarterOffContractTest { name -> { String lower = name.toLowerCase(java.util.Locale.ROOT); return lower.contains("kafka") - || lower.contains("rabbit") - || lower.contains("amqp") || lower.contains("messaging") || lower.contains("outbox"); }) diff --git a/src/messaging/messaging-spring-boot-starter/src/test/resources/application-valid.yml b/src/messaging/messaging-spring-boot-starter/src/test/resources/application-valid.yml index 8101b6e9..b1894f08 100644 --- a/src/messaging/messaging-spring-boot-starter/src/test/resources/application-valid.yml +++ b/src/messaging/messaging-spring-boot-starter/src/test/resources/application-valid.yml @@ -1,16 +1,6 @@ # A configuration the platform accepts. -# -# Every experimental adapter is off and the bridge is off, which is the shipped default: an -# adapter whose contract suite is still being proven must never become load-bearing because a -# configuration defaulted it on. backend: messaging: - experimental: - kafka-share: false - pulsar: false - nats: false - bridge: - spring-cloud-stream: false backpressure: # The per-destination limit stays below the global one; a per-destination limit at or above # the global limit would let one destination consume every slot in the process. diff --git a/src/messaging/messaging-spring-cloud-stream-bridge/build.gradle b/src/messaging/messaging-spring-cloud-stream-bridge/build.gradle deleted file mode 100644 index d1045677..00000000 --- a/src/messaging/messaging-spring-cloud-stream-bridge/build.gradle +++ /dev/null @@ -1,10 +0,0 @@ -plugins { - id 'ca.platform-module' -} - -dependencies { - api project(':messaging:messaging-core-api') - api project(':messaging:messaging-policy') - api project(':messaging:messaging-transport-spi') - -} diff --git a/src/messaging/messaging-spring-cloud-stream-bridge/gradle.lockfile b/src/messaging/messaging-spring-cloud-stream-bridge/gradle.lockfile deleted file mode 100644 index e2c95854..00000000 --- a/src/messaging/messaging-spring-cloud-stream-bridge/gradle.lockfile +++ /dev/null @@ -1,84 +0,0 @@ -# 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.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.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_annotations:2.41.0=spotbugs -com.google.errorprone:error_prone_annotations:2.47.0=checkstyle -com.google.errorprone:error_prone_annotations:2.49.0=annotationProcessor,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.5.0-jre=annotationProcessor,testAnnotationProcessor -com.google.guava:guava:33.6.0-jre=checkstyle -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.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 -jaxen:jaxen:2.0.6=spotbugs -net.bytebuddy:byte-buddy:1.17.8=testCompileClasspath,testRuntimeClasspath -net.sf.saxon:Saxon-HE:12.9=checkstyle,spotbugs -org.antlr:antlr4-runtime:4.13.2=checkstyle -org.apache.bcel:bcel:6.12.0=spotbugs -org.apache.commons:commons-lang3:3.20.0=checkstyle,spotbugs -org.apache.commons:commons-text:1.15.0=spotbugs -org.apache.commons:commons-text:1.3=checkstyle -org.apache.httpcomponents:httpclient:4.5.13=checkstyle -org.apache.httpcomponents:httpcore:4.4.16=checkstyle -org.apache.logging.log4j:log4j-api:2.25.5=spotbugs -org.apache.logging.log4j:log4j-core:2.25.5=spotbugs -org.apache.maven.doxia:doxia-core:1.12.0=checkstyle -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 -org.assertj:assertj-core:3.27.7=testCompileClasspath,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.3.0=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.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-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.1.0=spotbugs -org.mockito:mockito-core:5.20.0=mockitoAgent -org.opentest4j:opentest4j:1.3.0=testCompileClasspath,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.reflections:reflections:0.10.2=checkstyle -org.slf4j:slf4j-api:2.0.18=spotbugs,spotbugsSlf4j -org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j -org.slf4j:slf4j-simple:2.0.18=checkstyle -org.xmlresolver:xmlresolver:5.3.3=checkstyle,spotbugs -empty=compileClasspath,runtimeClasspath diff --git a/src/messaging/messaging-spring-cloud-stream-bridge/src/main/java/dev/caskeleton/messaging/streambridge/BindingCapabilityReport.java b/src/messaging/messaging-spring-cloud-stream-bridge/src/main/java/dev/caskeleton/messaging/streambridge/BindingCapabilityReport.java deleted file mode 100644 index fb34a1ae..00000000 --- a/src/messaging/messaging-spring-cloud-stream-bridge/src/main/java/dev/caskeleton/messaging/streambridge/BindingCapabilityReport.java +++ /dev/null @@ -1,88 +0,0 @@ -package dev.caskeleton.messaging.streambridge; - -import dev.caskeleton.messaging.api.destination.DestinationName; -import java.util.List; -import java.util.Objects; - -/** - * States, per binding, which platform guarantees the bridge does not provide. - * - *

    An explicit report rather than silence. The binder does provide retry and dead-lettering of - * its own, so a binding looks like it has them; what it does not have is the platform's versions — - * bounded attempts under the destination's retry policy, and a dead-letter publish confirmed before - * the source is settled. An operator comparing a bridged binding to a native one needs that - * difference written down, because nothing at runtime will show it. - * - * @param destination the logical destination - * @param bindingName the Stream binding name - * @param publishEvidenceAvailable whether the bridge can report broker publish evidence - * @param platformRetryApplied whether the destination's retry policy is enforced - * @param confirmedDeadLetterApplied whether dead-letter publishes are confirmed before settlement - * @param orderingEnforced whether the destination's ordering scope is enforced - */ -public record BindingCapabilityReport( - DestinationName destination, - String bindingName, - boolean publishEvidenceAvailable, - boolean platformRetryApplied, - boolean confirmedDeadLetterApplied, - boolean orderingEnforced) { - - public BindingCapabilityReport { - Objects.requireNonNull(destination, "destination must not be null"); - if (bindingName == null || bindingName.isBlank()) { - throw new IllegalArgumentException("bindingName must not be blank"); - } - } - - /** - * Returns the report for a binding served through the bridge. - * - *

    Every platform guarantee is false, because the bridge hands the message to the binder and - * the binder is what decides these. - * - * @param destination the logical destination - * @param bindingName the Stream binding name - * @return the report - */ - public static BindingCapabilityReport bridged(DestinationName destination, String bindingName) { - return new BindingCapabilityReport(destination, bindingName, false, false, false, false); - } - - /** - * Returns the guarantees this binding does not carry, as sanitized text. - * - * @return the gaps, empty when nothing is missing - */ - public List gaps() { - List gaps = new java.util.ArrayList<>(); - if (!publishEvidenceAvailable) { - gaps.add( - "publish evidence: the binder reports a send, not a broker confirmation, so an " - + "ambiguous publish is indistinguishable from a confirmed one"); - } - if (!platformRetryApplied) { - gaps.add( - "retry: the binder's own retry runs instead of the destination's retry policy, with its " - + "own attempt budget and backoff"); - } - if (!confirmedDeadLetterApplied) { - gaps.add( - "dead letter: the binder settles the source without waiting for the dead-letter publish " - + "to confirm, so a dead-letter outage loses the message"); - } - if (!orderingEnforced) { - gaps.add("ordering: the binder's concurrency settings decide ordering, not the profile"); - } - return List.copyOf(gaps); - } - - /** - * Reports whether this binding carries every platform guarantee. - * - * @return true when nothing is missing - */ - public boolean isFullyGuaranteed() { - return gaps().isEmpty(); - } -} diff --git a/src/messaging/messaging-spring-cloud-stream-bridge/src/main/java/dev/caskeleton/messaging/streambridge/BindingProfileValidator.java b/src/messaging/messaging-spring-cloud-stream-bridge/src/main/java/dev/caskeleton/messaging/streambridge/BindingProfileValidator.java deleted file mode 100644 index cb3d1590..00000000 --- a/src/messaging/messaging-spring-cloud-stream-bridge/src/main/java/dev/caskeleton/messaging/streambridge/BindingProfileValidator.java +++ /dev/null @@ -1,97 +0,0 @@ -package dev.caskeleton.messaging.streambridge; - -import dev.caskeleton.messaging.api.destination.DestinationName; -import dev.caskeleton.messaging.api.error.MessagingConfigurationException; -import dev.caskeleton.messaging.policy.DestinationProfile; -import java.util.Objects; -import java.util.regex.Pattern; - -/** - * Checks a binding against its destination before the bridge is wired. - * - *

    Runs on top of {@link StreamBridgePolicyGuard}: the guard decides whether a destination is - * eligible for the bridge at all, and this decides whether a particular binding is configured - * coherently for it. - * - *

    The binder's extended properties are the sharp edge. Stream lets a binding override the - * serializer, the acknowledgement mode, and the concurrency, and each of those silently replaces - * something the destination profile already decided. Rather than merging the two — which produces a - * configuration nobody can read — a conflicting extended property is rejected and the operator is - * told which side to remove. - */ -public final class BindingProfileValidator { - - private static final Pattern BINDING_NAME = Pattern.compile("[a-zA-Z][a-zA-Z0-9-]{0,63}"); - - /** Extended properties that would override a platform decision. */ - private static final java.util.Set CONFLICTING_PROPERTIES = - java.util.Set.of( - "autoBindDlq", - "republishToDlq", - "maxAttempts", - "backOffInitialInterval", - "autoCommitOffset", - "ackMode", - "useNativeEncoding", - "contentType"); - - private final StreamBridgePolicyGuard guard = new StreamBridgePolicyGuard(); - - /** - * Validates one binding. - * - * @param profile the destination profile - * @param bindingName the Stream binding name - * @param extendedProperties the binder extended properties configured for the binding - * @param enabled whether the bridge is switched on - * @return the capability report for the accepted binding - */ - public BindingCapabilityReport validate( - DestinationProfile profile, - String bindingName, - java.util.Map extendedProperties, - boolean enabled) { - Objects.requireNonNull(profile, "profile must not be null"); - Objects.requireNonNull(extendedProperties, "extendedProperties must not be null"); - - guard.validate(profile, enabled); - - if (bindingName == null || !BINDING_NAME.matcher(bindingName).matches()) { - throw new MessagingConfigurationException( - "INVALID_BINDING_NAME", - "binding name must match %s: %s".formatted(BINDING_NAME.pattern(), bindingName)); - } - - for (String property : extendedProperties.keySet()) { - if (CONFLICTING_PROPERTIES.contains(property)) { - throw new MessagingConfigurationException( - "BINDING_OVERRIDES_PLATFORM_POLICY", - "binding %s sets %s, which overrides what the %s destination profile already decides; " - .formatted(bindingName, property, profile.name().value()) - + "remove it from the binding or move the destination to the native adapter"); - } - } - - if (profile.production()) { - throw new MessagingConfigurationException( - "BRIDGE_ON_PRODUCTION_DESTINATION", - "destination %s is marked production; the bridge does not carry the platform's publish " - .formatted(profile.name().value()) - + "evidence, retry, or confirmed dead lettering"); - } - - return BindingCapabilityReport.bridged(profile.name(), bindingName); - } - - /** - * Returns the report for a destination that is not bridged at all. - * - * @param destination the logical destination - * @param bindingName the Stream binding name - * @return a report stating every guarantee holds - */ - public static BindingCapabilityReport nativeAdapter( - DestinationName destination, String bindingName) { - return new BindingCapabilityReport(destination, bindingName, true, true, true, true); - } -} diff --git a/src/messaging/messaging-spring-cloud-stream-bridge/src/main/java/dev/caskeleton/messaging/streambridge/MessagingBindingBridge.java b/src/messaging/messaging-spring-cloud-stream-bridge/src/main/java/dev/caskeleton/messaging/streambridge/MessagingBindingBridge.java deleted file mode 100644 index 49be29e6..00000000 --- a/src/messaging/messaging-spring-cloud-stream-bridge/src/main/java/dev/caskeleton/messaging/streambridge/MessagingBindingBridge.java +++ /dev/null @@ -1,34 +0,0 @@ -package dev.caskeleton.messaging.streambridge; - -import dev.caskeleton.messaging.api.destination.DestinationName; - -/** - * Connects a logical destination to a Spring Cloud Stream binding. - * - *

    The bridge is an interoperability seam, not a second messaging API. Its whole reason to exist - * is that a service already has Stream bindings and needs to reach the same destinations without a - * rewrite. - * - *

    Binder semantics are never promoted to platform guarantees. Stream's binder has its own retry, - * its own dead-letter, and its own acknowledgement mode, and they look enough like the platform's - * to be mistaken for them — so a destination that actually relies on the platform's versions is - * refused by {@link StreamBridgePolicyGuard} rather than served with the binder's. - */ -public interface MessagingBindingBridge { - - /** - * Binds a Stream output to a logical destination. - * - * @param destination the logical destination - * @param bindingName the Stream binding name - */ - void bindPublisher(DestinationName destination, String bindingName); - - /** - * Binds a Stream input to a logical destination. - * - * @param destination the logical destination - * @param bindingName the Stream binding name - */ - void bindConsumer(DestinationName destination, String bindingName); -} diff --git a/src/messaging/messaging-spring-cloud-stream-bridge/src/main/java/dev/caskeleton/messaging/streambridge/SpringCloudStreamConsumerBridge.java b/src/messaging/messaging-spring-cloud-stream-bridge/src/main/java/dev/caskeleton/messaging/streambridge/SpringCloudStreamConsumerBridge.java deleted file mode 100644 index e0b304f7..00000000 --- a/src/messaging/messaging-spring-cloud-stream-bridge/src/main/java/dev/caskeleton/messaging/streambridge/SpringCloudStreamConsumerBridge.java +++ /dev/null @@ -1,87 +0,0 @@ -package dev.caskeleton.messaging.streambridge; - -import dev.caskeleton.messaging.api.destination.DestinationName; -import dev.caskeleton.messaging.api.error.MessagingConfigurationException; -import java.util.Map; -import java.util.Objects; -import java.util.concurrent.ConcurrentHashMap; - -/** - * Receives from a Spring Cloud Stream input binding and hands the message to a platform handler. - * - *

    Settlement stays with the binder. The bridge cannot acknowledge, retry, or dead-letter a - * message itself, because Stream's binder already owns the acknowledgement for that binding and two - * things settling one message is worse than either doing it alone. - * - *

    What the bridge does own is the translation and the honesty about it: a handler failure is - * rethrown so the binder's error channel sees it, rather than being converted into a platform - * {@code HandleResult} that nothing downstream would act on. - */ -public final class SpringCloudStreamConsumerBridge { - - private final Map handlers = new ConcurrentHashMap<>(); - private final Map destinations = new ConcurrentHashMap<>(); - - /** - * Registers a handler for a binding. - * - * @param destination the logical destination - * @param bindingName the Stream binding name - * @param handler the handler to invoke - */ - public void register(DestinationName destination, String bindingName, BridgedHandler handler) { - Objects.requireNonNull(destination, "destination must not be null"); - Objects.requireNonNull(handler, "handler must not be null"); - if (bindingName == null || bindingName.isBlank()) { - throw new IllegalArgumentException("bindingName must not be blank"); - } - handlers.put(bindingName, handler); - destinations.put(bindingName, destination); - } - - /** - * Dispatches one message received on a binding. - * - * @param bindingName the Stream binding name - * @param payload the encoded payload - * @param headers the received headers - * @throws MessagingConfigurationException when nothing is registered for the binding - */ - public void dispatch(String bindingName, byte[] payload, Map headers) { - Objects.requireNonNull(payload, "payload must not be null"); - Objects.requireNonNull(headers, "headers must not be null"); - - BridgedHandler handler = handlers.get(bindingName); - DestinationName destination = destinations.get(bindingName); - if (handler == null || destination == null) { - throw new MessagingConfigurationException( - "NO_BRIDGED_HANDLER", "no handler is registered for Stream binding " + bindingName); - } - // Not caught. The binder's error channel is what retries and dead-letters this binding, and - // swallowing the failure here would acknowledge a message nothing handled. - handler.handle(destination, payload, headers); - } - - /** - * Returns how many bindings have a handler. - * - * @return the registered binding count - */ - public int registeredBindings() { - return handlers.size(); - } - - /** A platform handler reached through a Stream binding. */ - @FunctionalInterface - public interface BridgedHandler { - - /** - * Handles one bridged message. - * - * @param destination the logical destination - * @param payload the encoded payload - * @param headers the received headers - */ - void handle(DestinationName destination, byte[] payload, Map headers); - } -} diff --git a/src/messaging/messaging-spring-cloud-stream-bridge/src/main/java/dev/caskeleton/messaging/streambridge/SpringCloudStreamPublisherBridge.java b/src/messaging/messaging-spring-cloud-stream-bridge/src/main/java/dev/caskeleton/messaging/streambridge/SpringCloudStreamPublisherBridge.java deleted file mode 100644 index 059144fe..00000000 --- a/src/messaging/messaging-spring-cloud-stream-bridge/src/main/java/dev/caskeleton/messaging/streambridge/SpringCloudStreamPublisherBridge.java +++ /dev/null @@ -1,156 +0,0 @@ -package dev.caskeleton.messaging.streambridge; - -import dev.caskeleton.messaging.api.destination.DestinationName; -import dev.caskeleton.messaging.api.error.MessagingConfigurationException; -import dev.caskeleton.messaging.api.publish.ConfirmationLevel; -import dev.caskeleton.messaging.api.publish.PublishCompletion; -import dev.caskeleton.messaging.api.publish.PublishEvidence; -import dev.caskeleton.messaging.api.publish.PublishResult; -import dev.caskeleton.messaging.api.publish.RoutingOutcome; -import dev.caskeleton.messaging.api.publish.TransmissionEvidence; -import java.time.Duration; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.concurrent.ConcurrentHashMap; - -/** - * Framework-neutral publish evidence bridge for a future Spring Cloud Stream adapter. - * - *

    Despite the historical module/class name, this type does not itself depend on Spring Cloud - * Stream and does not auto-configure {@code StreamBridge}. A product integrating Spring Cloud - * Stream supplies the {@link ChannelSend} seam explicitly. Keeping that limitation in the type - * contract prevents this module from being mistaken for a shipped Spring Cloud Stream integration. - * - *

    Sends through a Spring Cloud Stream output binding and reports what that actually proves. - * - *

    The result is deliberately {@code AMBIGUOUS} rather than {@code CONFIRMED}. A Stream {@code - * send} returns a boolean from the message channel — it says the binder accepted the message, not - * that a broker did. Reporting that as confirmed would put the platform's strongest word on the - * binder's weakest evidence, and a caller reading {@code CONFIRMED} would stop worrying about a - * message that may never have left the process. - * - *

    A caller that needs real publish evidence has to use the native adapter. That is the honest - * trade the bridge exists to make visible. - */ -public final class SpringCloudStreamPublisherBridge implements MessagingBindingBridge { - - private final Map outputBindings = new ConcurrentHashMap<>(); - private final Map inputBindings = new ConcurrentHashMap<>(); - private final ChannelSend send; - - /** - * Creates a publisher bridge. - * - * @param send the Stream channel send operation - */ - public SpringCloudStreamPublisherBridge(ChannelSend send) { - this.send = Objects.requireNonNull(send, "send must not be null"); - } - - @Override - public void bindPublisher(DestinationName destination, String bindingName) { - Objects.requireNonNull(destination, "destination must not be null"); - Objects.requireNonNull(bindingName, "bindingName must not be null"); - outputBindings.put(destination, bindingName); - } - - @Override - public void bindConsumer(DestinationName destination, String bindingName) { - Objects.requireNonNull(destination, "destination must not be null"); - Objects.requireNonNull(bindingName, "bindingName must not be null"); - inputBindings.put(destination, bindingName); - } - - /** - * Publishes through the bound output binding. - * - * @param destination the logical destination - * @param payload the encoded payload - * @param headers the headers to carry - * @return the outcome, never stronger than the binder can prove - */ - public PublishResult publish( - DestinationName destination, byte[] payload, Map headers) { - Objects.requireNonNull(destination, "destination must not be null"); - Objects.requireNonNull(payload, "payload must not be null"); - Objects.requireNonNull(headers, "headers must not be null"); - - String binding = outputBindings.get(destination); - if (binding == null) { - throw new MessagingConfigurationException( - "NO_OUTPUT_BINDING", "no Stream output binding is bound to " + destination.value()); - } - - boolean accepted = send.send(binding, payload, headers); - return accepted ? acceptedByBinder() : rejectedByBinder(); - } - - /** - * Returns the binding bound to a destination for consuming. - * - * @param destination the logical destination - * @return the binding name, when one is bound - */ - public Optional consumerBinding(DestinationName destination) { - return Optional.ofNullable(inputBindings.get(destination)); - } - - /** - * Returns the binding bound to a destination for publishing. - * - * @param destination the logical destination - * @return the binding name, when one is bound - */ - public Optional publisherBinding(DestinationName destination) { - return Optional.ofNullable(outputBindings.get(destination)); - } - - private static PublishResult acceptedByBinder() { - return new PublishResult( - // The binder accepted it; no broker has confirmed anything. AMBIGUOUS is the only honest - // answer, and it is what makes the bridge's weaker guarantee visible to the caller. - PublishCompletion.AMBIGUOUS, - new PublishEvidence( - true, TransmissionEvidence.MAY_HAVE_BEEN_TRANSMITTED, false, ConfirmationLevel.NONE), - RoutingOutcome.UNKNOWN, - Optional.empty(), - 1, - Duration.ZERO, - Optional.of( - dev.caskeleton.messaging.api.error.FailureDescriptor.of( - dev.caskeleton.messaging.api.error.FailureCategory.AMBIGUOUS, - "STREAM_BRIDGE_NO_BROKER_EVIDENCE", - "the Stream binder accepted the message; no broker confirmation is available"))); - } - - private static PublishResult rejectedByBinder() { - return new PublishResult( - PublishCompletion.REJECTED, - PublishEvidence.notTransmitted(), - RoutingOutcome.NOT_APPLICABLE, - Optional.empty(), - 1, - Duration.ZERO, - Optional.of( - dev.caskeleton.messaging.api.error.FailureDescriptor.of( - dev.caskeleton.messaging.api.error.FailureCategory.TRANSIENT_INFRASTRUCTURE, - "STREAM_BRIDGE_SEND_REFUSED", - "the Stream channel refused the message"))); - } - - /** The Stream channel send, isolated so the bridge is testable without a binder. */ - @FunctionalInterface - public interface ChannelSend { - - /** - * Sends one message to a binding. - * - * @param bindingName the Stream binding name - * @param payload the encoded payload - * @param headers the headers to carry - * @return whether the channel accepted the message - */ - boolean send(String bindingName, byte[] payload, Map headers); - } -} diff --git a/src/messaging/messaging-spring-cloud-stream-bridge/src/main/java/dev/caskeleton/messaging/streambridge/StreamBridgePolicyGuard.java b/src/messaging/messaging-spring-cloud-stream-bridge/src/main/java/dev/caskeleton/messaging/streambridge/StreamBridgePolicyGuard.java deleted file mode 100644 index e676f350..00000000 --- a/src/messaging/messaging-spring-cloud-stream-bridge/src/main/java/dev/caskeleton/messaging/streambridge/StreamBridgePolicyGuard.java +++ /dev/null @@ -1,52 +0,0 @@ -package dev.caskeleton.messaging.streambridge; - -import dev.caskeleton.messaging.api.error.MessagingConfigurationException; -import dev.caskeleton.messaging.policy.DestinationProfile; -import java.util.Objects; - -/** - * Keeps the optional Spring Cloud Stream bridge inside platform policy. - * - *

    The bridge exists for interoperability with existing Spring Cloud Stream bindings, and its - * risk is specific: Stream owns its own binder configuration, so a binding can quietly acquire its - * own serializer, its own error handling, and its own acknowledgement mode — none of which the - * destination profile knows about. - * - *

    So the bridge is only permitted where the platform's guarantees are not the thing being relied - * on: a destination that declares an ordering scope, a retry policy, or a dead letter destination - * must go through the native adapter, where those are actually enforced. - */ -public final class StreamBridgePolicyGuard { - - /** - * Validates that a destination may be served through the bridge. - * - * @param profile the destination profile - * @param enabled whether the bridge is switched on - */ - public void validate(DestinationProfile profile, boolean enabled) { - Objects.requireNonNull(profile, "profile must not be null"); - - if (!enabled) { - throw new MessagingConfigurationException( - "STREAM_BRIDGE_DISABLED", - "the Spring Cloud Stream bridge is optional and disabled unless " - + "backend.messaging.bridge.spring-cloud-stream=true"); - } - if (profile.isOrdered()) { - throw new MessagingConfigurationException( - "STREAM_BRIDGE_ORDERING_UNSUPPORTED", - "an ordered destination must use the native adapter: " + profile.name().value()); - } - if (profile.retry().mode() != dev.caskeleton.messaging.policy.RetryMode.NONE) { - throw new MessagingConfigurationException( - "STREAM_BRIDGE_RETRY_UNSUPPORTED", - "the bridge does not apply the platform retry policy: " + profile.name().value()); - } - if (profile.deadLetter().enabled()) { - throw new MessagingConfigurationException( - "STREAM_BRIDGE_DLQ_UNSUPPORTED", - "the bridge does not apply confirmed dead lettering: " + profile.name().value()); - } - } -} diff --git a/src/messaging/messaging-spring-cloud-stream-bridge/src/test/java/dev/caskeleton/messaging/streambridge/BindingProfileValidatorTest.java b/src/messaging/messaging-spring-cloud-stream-bridge/src/test/java/dev/caskeleton/messaging/streambridge/BindingProfileValidatorTest.java deleted file mode 100644 index 1f5f4035..00000000 --- a/src/messaging/messaging-spring-cloud-stream-bridge/src/test/java/dev/caskeleton/messaging/streambridge/BindingProfileValidatorTest.java +++ /dev/null @@ -1,164 +0,0 @@ -package dev.caskeleton.messaging.streambridge; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.messaging.api.ContentType; -import dev.caskeleton.messaging.api.MessageType; -import dev.caskeleton.messaging.api.delivery.DeliveryGuarantee; -import dev.caskeleton.messaging.api.delivery.ExternalSideEffectGuarantee; -import dev.caskeleton.messaging.api.delivery.OrderingScope; -import dev.caskeleton.messaging.api.destination.DestinationKind; -import dev.caskeleton.messaging.api.destination.DestinationName; -import dev.caskeleton.messaging.api.error.MessagingConfigurationException; -import dev.caskeleton.messaging.policy.CapabilityTier; -import dev.caskeleton.messaging.policy.ConsumerPolicy; -import dev.caskeleton.messaging.policy.DeadLetterPolicy; -import dev.caskeleton.messaging.policy.DestinationProfile; -import dev.caskeleton.messaging.policy.PayloadPolicy; -import dev.caskeleton.messaging.policy.PhysicalDestination; -import dev.caskeleton.messaging.policy.ProducerPolicy; -import dev.caskeleton.messaging.policy.RetryPolicy; -import dev.caskeleton.messaging.policy.SchemaPolicy; -import dev.caskeleton.messaging.schema.SchemaCompatibility; -import java.util.Map; -import java.util.Set; -import org.junit.jupiter.api.Test; - -class BindingProfileValidatorTest { - - private final BindingProfileValidator validator = new BindingProfileValidator(); - - private static DestinationProfile profile( - OrderingScope ordering, RetryPolicy retry, DeadLetterPolicy deadLetter, boolean production) { - return new DestinationProfile( - new DestinationName("orders.v1"), - "kafka-primary", - DestinationKind.EVENT_STREAM, - PhysicalDestination.kafkaTopic("orders.v1"), - new SchemaPolicy( - ContentType.JSON, - SchemaCompatibility.BACKWARD, - Set.of(new MessageType("order.created"))), - DeliveryGuarantee.AT_LEAST_ONCE, - ordering, - ExternalSideEffectGuarantee.IDEMPOTENCY_REQUIRED, - ProducerPolicy.defaults(), - ConsumerPolicy.defaults("orders"), - retry, - deadLetter, - PayloadPolicy.defaults(), - CapabilityTier.M1, - production, - false, - false); - } - - private static DestinationProfile bridgeable() { - return profile(OrderingScope.NONE, RetryPolicy.none(), DeadLetterPolicy.disabled(), false); - } - - @Test - void aBridgeableDestinationIsAccepted() { - BindingCapabilityReport report = validator.validate(bridgeable(), "orders-out", Map.of(), true); - - assertThat(report.bindingName()).isEqualTo("orders-out"); - } - - @Test - void aDisabledBridgeRefusesEverything() { - assertThatThrownBy(() -> validator.validate(bridgeable(), "orders-out", Map.of(), false)) - .isInstanceOf(MessagingConfigurationException.class) - .hasMessageContaining("disabled"); - } - - @Test - void anOrderedDestinationMustUseTheNativeAdapter() { - assertThatThrownBy( - () -> - validator.validate( - profile( - OrderingScope.KEY, RetryPolicy.none(), DeadLetterPolicy.disabled(), false), - "orders-out", - Map.of(), - true)) - .isInstanceOf(MessagingConfigurationException.class) - .hasMessageContaining("ordered"); - } - - @Test - void aDestinationWithADeadLetterMustUseTheNativeAdapter() { - assertThatThrownBy( - () -> - validator.validate( - profile( - OrderingScope.NONE, - RetryPolicy.none(), - DeadLetterPolicy.to(new DestinationName("orders.v1.dlq")), - false), - "orders-out", - Map.of(), - true)) - .as("the binder settles the source without confirming the dead-letter publish") - .isInstanceOf(MessagingConfigurationException.class); - } - - @Test - void aProductionDestinationIsRefused() { - assertThatThrownBy( - () -> - validator.validate( - profile( - OrderingScope.NONE, RetryPolicy.none(), DeadLetterPolicy.disabled(), true), - "orders-out", - Map.of(), - true)) - .isInstanceOf(MessagingConfigurationException.class) - .hasMessageContaining("production"); - } - - @Test - void aBinderPropertyThatOverridesPlatformPolicyIsRejectedRatherThanMerged() { - assertThatThrownBy( - () -> validator.validate(bridgeable(), "orders-out", Map.of("maxAttempts", "10"), true)) - .as("merging the two produces a configuration nobody can read") - .isInstanceOf(MessagingConfigurationException.class) - .hasMessageContaining("maxAttempts"); - } - - @Test - void aHarmlessBinderPropertyIsAllowedThrough() { - assertThatCode( - () -> validator.validate(bridgeable(), "orders-out", Map.of("concurrency", "4"), true)) - .doesNotThrowAnyException(); - } - - @Test - void anInvalidBindingNameIsRejected() { - assertThatThrownBy(() -> validator.validate(bridgeable(), "9-bad name!", Map.of(), true)) - .isInstanceOf(MessagingConfigurationException.class) - .hasMessageContaining("binding name"); - } - - @Test - void aBridgedBindingReportsEveryGuaranteeItDoesNotCarry() { - BindingCapabilityReport report = validator.validate(bridgeable(), "orders-out", Map.of(), true); - - assertThat(report.isFullyGuaranteed()).isFalse(); - assertThat(report.gaps()).hasSize(4); - assertThat(String.join(" ", report.gaps())) - .contains("publish evidence") - .contains("retry") - .contains("dead letter") - .contains("ordering"); - } - - @Test - void aNativeBindingReportsNoGaps() { - assertThat( - BindingProfileValidator.nativeAdapter(new DestinationName("orders.v1"), "orders-out") - .isFullyGuaranteed()) - .isTrue(); - } -} diff --git a/src/messaging/messaging-spring-cloud-stream-bridge/src/test/java/dev/caskeleton/messaging/streambridge/BridgePublishEvidenceTest.java b/src/messaging/messaging-spring-cloud-stream-bridge/src/test/java/dev/caskeleton/messaging/streambridge/BridgePublishEvidenceTest.java deleted file mode 100644 index 411f04f1..00000000 --- a/src/messaging/messaging-spring-cloud-stream-bridge/src/test/java/dev/caskeleton/messaging/streambridge/BridgePublishEvidenceTest.java +++ /dev/null @@ -1,131 +0,0 @@ -package dev.caskeleton.messaging.streambridge; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import dev.caskeleton.messaging.api.destination.DestinationName; -import dev.caskeleton.messaging.api.error.MessagingConfigurationException; -import dev.caskeleton.messaging.api.publish.ConfirmationLevel; -import dev.caskeleton.messaging.api.publish.PublishCompletion; -import dev.caskeleton.messaging.api.publish.PublishResult; -import dev.caskeleton.messaging.api.publish.TransmissionEvidence; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import org.junit.jupiter.api.Test; - -class BridgePublishEvidenceTest { - - private static final DestinationName ORDERS = new DestinationName("orders.v1"); - private static final byte[] PAYLOAD = "{\"orderId\":\"o-1\"}".getBytes(StandardCharsets.UTF_8); - - private static SpringCloudStreamPublisherBridge bridge(boolean channelAccepts) { - SpringCloudStreamPublisherBridge bridge = - new SpringCloudStreamPublisherBridge((binding, payload, headers) -> channelAccepts); - bridge.bindPublisher(ORDERS, "orders-out"); - return bridge; - } - - @Test - void anAcceptedSendIsAmbiguousBecauseNoBrokerConfirmedIt() { - PublishResult result = bridge(true).publish(ORDERS, PAYLOAD, Map.of()); - - assertThat(result.completion()) - .as("a channel send says the binder took it, not that a broker did") - .isEqualTo(PublishCompletion.AMBIGUOUS); - assertThat(result.evidence().brokerAccepted()).isFalse(); - assertThat(result.evidence().confirmationLevel()).isEqualTo(ConfirmationLevel.NONE); - } - - @Test - void anAcceptedSendReportsThatTransmissionIsUnknown() { - assertThat(bridge(true).publish(ORDERS, PAYLOAD, Map.of()).evidence().transmission()) - .isEqualTo(TransmissionEvidence.MAY_HAVE_BEEN_TRANSMITTED); - } - - @Test - void theFailureDescriptorNamesTheMissingEvidence() { - assertThat(bridge(true).publish(ORDERS, PAYLOAD, Map.of()).failure()) - .hasValueSatisfying( - failure -> assertThat(failure.code()).isEqualTo("STREAM_BRIDGE_NO_BROKER_EVIDENCE")); - } - - @Test - void aRefusedChannelSendIsRejectedNotAmbiguous() { - PublishResult result = bridge(false).publish(ORDERS, PAYLOAD, Map.of()); - - assertThat(result.completion()).isEqualTo(PublishCompletion.REJECTED); - assertThat(result.evidence().transmission()).isEqualTo(TransmissionEvidence.NOT_TRANSMITTED); - } - - @Test - void publishingToAnUnboundDestinationFailsLoudly() { - SpringCloudStreamPublisherBridge bridge = - new SpringCloudStreamPublisherBridge((binding, payload, headers) -> true); - - assertThatThrownBy(() -> bridge.publish(ORDERS, PAYLOAD, Map.of())) - .isInstanceOf(MessagingConfigurationException.class) - .hasMessageContaining("orders.v1"); - } - - @Test - void thePayloadReachesTheBoundBinding() { - List bindings = new ArrayList<>(); - SpringCloudStreamPublisherBridge bridge = - new SpringCloudStreamPublisherBridge( - (binding, payload, headers) -> { - bindings.add(binding); - return true; - }); - bridge.bindPublisher(ORDERS, "orders-out"); - - bridge.publish(ORDERS, PAYLOAD, Map.of()); - - assertThat(bindings).containsExactly("orders-out"); - } - - @Test - void bindingsAreQueryableInBothDirections() { - SpringCloudStreamPublisherBridge bridge = bridge(true); - bridge.bindConsumer(ORDERS, "orders-in"); - - assertThat(bridge.publisherBinding(ORDERS)).hasValue("orders-out"); - assertThat(bridge.consumerBinding(ORDERS)).hasValue("orders-in"); - } - - @Test - void aHandlerFailureIsRethrownSoTheBindersErrorChannelSeesIt() { - SpringCloudStreamConsumerBridge consumer = new SpringCloudStreamConsumerBridge(); - consumer.register( - ORDERS, - "orders-in", - (destination, payload, headers) -> { - throw new IllegalStateException("handler failed"); - }); - - assertThatThrownBy(() -> consumer.dispatch("orders-in", PAYLOAD, Map.of())) - .as("swallowing it would acknowledge a message nothing handled") - .isInstanceOf(IllegalStateException.class); - } - - @Test - void dispatchingToAnUnregisteredBindingFailsLoudly() { - assertThatThrownBy( - () -> new SpringCloudStreamConsumerBridge().dispatch("orders-in", PAYLOAD, Map.of())) - .isInstanceOf(MessagingConfigurationException.class); - } - - @Test - void aRegisteredHandlerReceivesTheDestinationItWasBoundTo() { - List seen = new ArrayList<>(); - SpringCloudStreamConsumerBridge consumer = new SpringCloudStreamConsumerBridge(); - consumer.register( - ORDERS, "orders-in", (destination, payload, headers) -> seen.add(destination)); - - consumer.dispatch("orders-in", PAYLOAD, Map.of()); - - assertThat(seen).containsExactly(ORDERS); - assertThat(consumer.registeredBindings()).isEqualTo(1); - } -} diff --git a/src/messaging/messaging-testkit/build.gradle b/src/messaging/messaging-testkit/build.gradle index 559464fa..a7492ce5 100644 --- a/src/messaging/messaging-testkit/build.gradle +++ b/src/messaging/messaging-testkit/build.gradle @@ -1,5 +1,11 @@ plugins { - id 'ca.jmh-benchmarks' + id 'ca.platform-module' + id 'me.champeau.jmh' +} + +jmh { + jmhVersion = libs.versions.jmh.get() + includeTests = true } dependencies { diff --git a/src/messaging/messaging-testkit/gradle.lockfile b/src/messaging/messaging-testkit/gradle.lockfile index 98b1f9db..4334c116 100644 --- a/src/messaging/messaging-testkit/gradle.lockfile +++ b/src/messaging/messaging-testkit/gradle.lockfile @@ -35,12 +35,12 @@ io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,jmhAnnotation javax.inject:javax.inject:1=annotationProcessor,jmhAnnotationProcessor,testAnnotationProcessor jaxen:jaxen:2.0.6=spotbugs net.bytebuddy:byte-buddy:1.17.8=compileClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath -net.sf.jopt-simple:jopt-simple:5.0.4=jmhAnnotationProcessor,jmhCompileClasspath,jmhRuntimeClasspath +net.sf.jopt-simple:jopt-simple:5.0.4=jmh,jmhCompileClasspath,jmhRuntimeClasspath net.sf.saxon:Saxon-HE:12.9=checkstyle,spotbugs org.antlr:antlr4-runtime:4.13.2=checkstyle org.apache.bcel:bcel:6.12.0=spotbugs org.apache.commons:commons-lang3:3.20.0=checkstyle,spotbugs -org.apache.commons:commons-math3:3.6.1=jmhAnnotationProcessor,jmhCompileClasspath,jmhRuntimeClasspath +org.apache.commons:commons-math3:3.6.1=jmh,jmhCompileClasspath,jmhRuntimeClasspath org.apache.commons:commons-text:1.15.0=spotbugs org.apache.commons:commons-text:1.3=checkstyle org.apache.httpcomponents:httpclient:4.5.13=checkstyle @@ -71,13 +71,16 @@ org.junit.platform:junit-platform-launcher:6.0.3=jmhRuntimeClasspath,testRuntime org.junit:junit-bom:6.0.3=compileClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath org.junit:junit-bom:6.1.0=spotbugs org.mockito:mockito-core:5.20.0=mockitoAgent -org.openjdk.jmh:jmh-core:1.37=jmhAnnotationProcessor,jmhCompileClasspath,jmhRuntimeClasspath -org.openjdk.jmh:jmh-generator-annprocess:1.37=jmhAnnotationProcessor +org.openjdk.jmh:jmh-core:1.37=jmh,jmhCompileClasspath,jmhRuntimeClasspath +org.openjdk.jmh:jmh-generator-asm:1.37=jmh,jmhCompileClasspath,jmhRuntimeClasspath +org.openjdk.jmh:jmh-generator-bytecode:1.37=jmh,jmhCompileClasspath,jmhRuntimeClasspath +org.openjdk.jmh:jmh-generator-reflection:1.37=jmh,jmhCompileClasspath,jmhRuntimeClasspath org.opentest4j:opentest4j:1.3.0=compileClasspath,jmhCompileClasspath,jmhRuntimeClasspath,runtimeClasspath,testCompileClasspath,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.0=jmh,jmhCompileClasspath,jmhRuntimeClasspath org.ow2.asm:asm:9.10.1=spotbugs org.pcollections:pcollections:4.0.1=annotationProcessor,jmhAnnotationProcessor,testAnnotationProcessor org.reflections:reflections:0.10.2=checkstyle diff --git a/src/messaging/messaging-testkit/src/main/java/dev/caskeleton/messaging/testkit/CompatibilityMatrix.java b/src/messaging/messaging-testkit/src/main/java/dev/caskeleton/messaging/testkit/CompatibilityMatrix.java index 13d74864..42d42710 100644 --- a/src/messaging/messaging-testkit/src/main/java/dev/caskeleton/messaging/testkit/CompatibilityMatrix.java +++ b/src/messaging/messaging-testkit/src/main/java/dev/caskeleton/messaging/testkit/CompatibilityMatrix.java @@ -51,9 +51,9 @@ public final class CompatibilityMatrix { * Reports whether a lane has run this adapter against a real broker. * *

    Read from the evidence rather than declared. As a field it was a boolean an author set - * next to the tier, and RabbitMQ carried {@code true} while no fault scenario had ever been - * executed against it — the same shape as the coverage matrix that used to assert its own - * constants. + * next to the tier, and an Experimental adapter carried {@code true} while no fault scenario + * had ever been executed against it — the same shape as the coverage matrix that used to assert + * its own constants. * * @return true when {@link CertifiedEvidence} has live-broker evidence for this adapter */ @@ -78,36 +78,11 @@ public final class CompatibilityMatrix { private static final Map ENTRIES = Map.of( "messaging-kafka", - // 4.1 only. The declared 4.2/4.3 were never run: the fixtures pin apache/kafka:4.1.0 - // and - // the locked client is 4.1.1, so the matrix and the support document agreed with each - // other and with nothing that had executed. A version returns here when a lane runs - // against its image. - new Entry("messaging-kafka", List.of("4.1"), Tier.STABLE, true, true), - "messaging-rabbit", - // Experimental until a lane runs a fault scenario against a RabbitMQ container. The - // adapter passes the shared contract and its broker IT exercises the routable and - // unroutable happy paths, but Stable in this repository means fault evidence, and - // there is none: connection-refused, cut-after-write, confirm-timeout, - // settlement-lost and high-latency have never been executed here. - new Entry("messaging-rabbit", List.of("4.3"), Tier.EXPERIMENTAL, true, false), - "messaging-kafka-share-experimental", - new Entry( - "messaging-kafka-share-experimental", - List.of("4.2", "4.3"), - Tier.EXPERIMENTAL, - false, - false), - "messaging-pulsar-experimental", - new Entry( - "messaging-pulsar-experimental", - List.of("4.0", "4.2"), - Tier.EXPERIMENTAL, - false, - false), - "messaging-nats-experimental", - new Entry( - "messaging-nats-experimental", List.of("2.14"), Tier.EXPERIMENTAL, false, false)); + // 4.1 only. The declared 4.2/4.3 were never run: the fixtures pin apache/kafka:4.1.0 and + // the locked client is 4.1.1, so the matrix and the support document agreed with each + // other and with nothing that had executed. A version returns here when a lane runs + // against its image. + new Entry("messaging-kafka", List.of("4.1"), Tier.STABLE, true, true)); /** * Returns every certified adapter. diff --git a/src/messaging/messaging-testkit/src/main/java/dev/caskeleton/messaging/testkit/MessagingAdapterHarness.java b/src/messaging/messaging-testkit/src/main/java/dev/caskeleton/messaging/testkit/MessagingAdapterHarness.java index 4df6fa84..a17f10e7 100644 --- a/src/messaging/messaging-testkit/src/main/java/dev/caskeleton/messaging/testkit/MessagingAdapterHarness.java +++ b/src/messaging/messaging-testkit/src/main/java/dev/caskeleton/messaging/testkit/MessagingAdapterHarness.java @@ -9,8 +9,8 @@ import java.util.concurrent.CompletionStage; * The seam each broker adapter implements to run the common contract. * *

    The harness exposes outcomes, not internals: what the platform decided, what reached the dead - * letter destination, and what is still unsettled. Kafka and RabbitMQ answer those three questions - * with completely different machinery, and the contract only passes if the answers match. + * letter destination, and what is still unsettled. Each broker answers those three questions with + * its own machinery, and the contract only passes if the answers match. */ public interface MessagingAdapterHarness extends AutoCloseable { diff --git a/src/messaging/messaging-testkit/src/test/java/dev/caskeleton/messaging/testkit/CertifiedEvidenceTest.java b/src/messaging/messaging-testkit/src/test/java/dev/caskeleton/messaging/testkit/CertifiedEvidenceTest.java index 0ed64f1e..a8eacb4d 100644 --- a/src/messaging/messaging-testkit/src/test/java/dev/caskeleton/messaging/testkit/CertifiedEvidenceTest.java +++ b/src/messaging/messaging-testkit/src/test/java/dev/caskeleton/messaging/testkit/CertifiedEvidenceTest.java @@ -53,8 +53,8 @@ class CertifiedEvidenceTest { assertThat(CertifiedEvidence.knownGaps("messaging-kafka")) .as("a Kafka producer buffers before it learns a connection exists, so this stays unproven") .contains(NetworkFaultScenario.CONNECTION_REFUSED); - assertThat(CertifiedEvidence.knownGaps("messaging-rabbit")) - .as("no lane runs a fault scenario against RabbitMQ, so every scenario is a gap") + assertThat(CertifiedEvidence.knownGaps("messaging-artemis")) + .as("an adapter no lane has run has every scenario as a gap") .containsExactlyElementsOf(NetworkFaultScenario.all()); } diff --git a/src/messaging/messaging-testkit/src/test/java/dev/caskeleton/messaging/testkit/CompatibilityMatrixTest.java b/src/messaging/messaging-testkit/src/test/java/dev/caskeleton/messaging/testkit/CompatibilityMatrixTest.java index f126796a..7cccaf21 100644 --- a/src/messaging/messaging-testkit/src/test/java/dev/caskeleton/messaging/testkit/CompatibilityMatrixTest.java +++ b/src/messaging/messaging-testkit/src/test/java/dev/caskeleton/messaging/testkit/CompatibilityMatrixTest.java @@ -32,7 +32,6 @@ class CompatibilityMatrixTest { void noExperimentalAdapterIsEnabledByDefault() { assertThat(CompatibilityMatrix.entries().values()) .filteredOn(entry -> entry.tier() == CompatibilityMatrix.Tier.EXPERIMENTAL) - .isNotEmpty() .allSatisfy(entry -> assertThat(entry.enabledByDefault()).isFalse()); } @@ -41,7 +40,6 @@ class CompatibilityMatrixTest { assertThat(CompatibilityMatrix.entries().values()) .filteredOn(entry -> entry.tier() == CompatibilityMatrix.Tier.STABLE) .extracting(CompatibilityMatrix.Entry::adapter) - .as("RabbitMQ passes the shared contract, but no fault scenario has been run against it") .containsExactly("messaging-kafka"); } diff --git a/src/messaging/messaging-testkit/src/test/java/dev/caskeleton/messaging/testkit/CrossBrokerContractSuite.java b/src/messaging/messaging-testkit/src/test/java/dev/caskeleton/messaging/testkit/CrossBrokerContractSuite.java index adb286a0..ff0b29be 100644 --- a/src/messaging/messaging-testkit/src/test/java/dev/caskeleton/messaging/testkit/CrossBrokerContractSuite.java +++ b/src/messaging/messaging-testkit/src/test/java/dev/caskeleton/messaging/testkit/CrossBrokerContractSuite.java @@ -48,19 +48,16 @@ class CrossBrokerContractSuite { assertThat(matrix.gapsFor("messaging-kafka")) .as("what the Kafka lanes have not exercised against a live broker") .isEqualTo(CertifiedEvidence.knownGaps("messaging-kafka")); - assertThat(matrix.gapsFor("messaging-rabbit")) - .as("what the Rabbit lanes have not exercised against a live broker") - .isEqualTo(CertifiedEvidence.knownGaps("messaging-rabbit")); } @Test void evidenceThatDisagreesWithItsScenarioIsNotCoverage() { BrokerCertificationEvidence contradicting = new BrokerCertificationEvidence( - "messaging-rabbit", - "rabbitmq:4.3-management", + "messaging-kafka", + "apache/kafka:4.1.0", NetworkFaultScenario.CONNECTION_CUT_AFTER_WRITE, - "RabbitBrokerIT#anUnroutablePublishIsRejectedEvenThoughTheExchangeConfirmedIt", + "SomeIT#someScenario", "REJECTED", "repository-local", java.time.Instant.parse("2026-08-15T00:00:00Z")); @@ -105,14 +102,6 @@ class CrossBrokerContractSuite { .isNotEqualTo(Coverage.LIVE_BROKER))); } - @Test - void anExperimentalAdapterIsAllowedGapsButTheyAreRecorded() { - assertThat(matrix.isComplete("messaging-pulsar-experimental")) - .as("the Experimental tier is a statement of fact, not a disclaimer") - .isFalse(); - assertThat(matrix.gapsFor("messaging-pulsar-experimental")).isNotEmpty(); - } - @Test void aFaultThatWasNeverRecordedReadsAsUncoveredRatherThanPassing() { assertThat(matrix.coverageOf("messaging-artemis", NetworkFaultScenario.CONFIRM_TIMEOUT)) diff --git a/src/messaging/messaging-testkit/src/test/java/dev/caskeleton/messaging/testkit/MessagingDocumentationContractTest.java b/src/messaging/messaging-testkit/src/test/java/dev/caskeleton/messaging/testkit/MessagingDocumentationContractTest.java index 0b7471a5..e97c8ac9 100644 --- a/src/messaging/messaging-testkit/src/test/java/dev/caskeleton/messaging/testkit/MessagingDocumentationContractTest.java +++ b/src/messaging/messaging-testkit/src/test/java/dev/caskeleton/messaging/testkit/MessagingDocumentationContractTest.java @@ -135,10 +135,6 @@ class MessagingDocumentationContractTest { private static String brokerLabel(String adapter) { return switch (adapter) { case "messaging-kafka" -> "Kafka"; - case "messaging-rabbit" -> "RabbitMQ"; - case "messaging-pulsar-experimental" -> "Pulsar"; - case "messaging-nats-experimental" -> "NATS"; - case "messaging-kafka-share-experimental" -> "Kafka Share"; default -> adapter; }; } diff --git a/src/sample-portfolio/CLAUDE.md b/src/sample-portfolio/CLAUDE.md index 7b193336..7a7a8400 100644 --- a/src/sample-portfolio/CLAUDE.md +++ b/src/sample-portfolio/CLAUDE.md @@ -50,4 +50,18 @@ Package root: `dev.caskeleton.sample.portfolio`. ```bash cd src ./gradlew :sample-portfolio:test +./gradlew :sample-portfolio:integrationTest # real PostgreSQL (Testcontainers) ``` + +### 테스트 작성 예시 + +이 모듈이 `AGENTS.md` "테스트 작성 규칙"의 기준 예시다. 새 테스트는 아래를 본떠 쓴다. + +- 유스케이스 + `@Nested` + `catchThrowable`: `src/test/.../application/worklog/WorkLogUseCasesTest.java` +- 포트 계약: `src/testFixtures/.../domain/worklog/testkit/WorkLogRepositoryContract.java` — + fake(`InMemoryWorkLogRepositoryContractTest`, test)와 JPA adapter + (`WorkLogRepositoryAdapterContractTest`, integrationTest)가 같은 계약을 통과한다. 계약에 케이스를 + 추가하면 두 구현에서 모두 돈다. +- 포트 대역은 포트당 하나: `WorkLogRepository` → `InMemoryWorkLogRepository`(이 모듈 testFixtures), + `TransactionPort` → `DirectTransactionPort`(application-core testFixtures, `committed()`·`active()`로 + 트랜잭션 경계를 단언). 테스트 파일 안에 같은 포트의 fake를 새로 만들지 않는다. diff --git a/src/sample-portfolio/README.md b/src/sample-portfolio/README.md index 9d3fda48..59bac9a9 100644 --- a/src/sample-portfolio/README.md +++ b/src/sample-portfolio/README.md @@ -330,9 +330,7 @@ curl -X POST localhost:8080/work-logs -H 'Content-Type: application/json' -d '{ 관리하고, `null` 이면 새 행이라 `save()` 가 INSERT 합니다. ### WorkLogPersistenceMapper — UUID 문자열 ↔ native uuid 변환 -- 36자 canonical UUID 와 PostgreSQL native `uuid`(128비트)를 서로 변환합니다. `UuidCodec` 같은 공용 - 코덱이 아니라 JDK `java.util.UUID` 를 **직접** 쓰는 이유: 영속 어댑터는 경계 규칙상 - `adapter-outbound`(코덱이 있는 곳)에 의존하면 안 되기 때문입니다(stdlib 이라 의존 문제 자체가 없음). +- 36자 canonical UUID 와 PostgreSQL native `uuid`(128비트)를 JDK `java.util.UUID` 로 직접 변환합니다. - 엔티티로 변환할 때 도메인 `version` 을 그대로 실어, JPA 가 새 행(`null` → INSERT)과 추적 중인 행 (non-null → 낙관적 merge)을 구분할 수 있게 합니다. @@ -400,41 +398,30 @@ curl -X POST localhost:8080/work-logs -H 'Content-Type: application/json' -d '{ > `app-bootstrap` 빈들을 그대로 씁니다. ### SamplePortfolioApplication — 독립 실행 구성 루트 -- `dev.caskeleton` 하위 전부를 스캔해 프로덕션 모듈의 Spring 컴포넌트(adapter-web `SecurityConfig`, - adapter-persistence `PersistenceJpaConfig` 등)를 자동으로 발견·배선합니다. `app-bootstrap` 에만 있어 - 자동 발견되지 않는 구성 루트만 위 `bootstrap.*` 가 채웁니다. +- 관계형 저장소는 다른 서비스와 똑같이 고른다: `build.gradle`의 + `implementation project(':adapter:outbound:persistence-jpa')` 한 줄과 그 모듈의 auto-configuration. + (`implementation`인 이유는 샘플 어댑터가 모듈의 `AuditableEntity`·`AuditContextPort`를 직접 쓰기 + 때문이다.) 그래서 컴포넌트 스캔은 persistence 패키지를 부르지 않는다 — 샘플(`dev.caskeleton.sample`)과 + 이 lean 앱이 아직 스캔으로 배선하는 web·identifier·objectstorage·core 계약 패키지만 나열한다. + JPA가 두 번 들어오거나, 모듈의 기동 가드 없이 들어오는 일이 없다. - **`@SpringBootApplication` 대신 `@Configuration` + `@EnableAutoConfiguration` + `@ComponentScan` 을 쓴 이유**: `@SpringBootApplication` 은 `@SpringBootConfiguration` 을 포함하는데, 그러면 이 클래스가 Spring Boot 의 `AnnotatedClassFinder` 에 보입니다. 그 finder 가 이 클래스와 (같은 패키지·테스트 classpath 의) `SamplePortfolioTestApplication` **둘 다** 찾으면 "multiple @SpringBootConfiguration" 오류를 냅니다. `@Configuration`(= `@SpringBootConfiguration` 아님)을 쓰면 finder 에 숨으면서도, `@SpringBootTest(classes = SamplePortfolioApplication.class)` 로 부팅하는 데는 문제가 없습니다. -- **`@ComponentScan` 에 exclude 두 개를 둔 이유**: - - `PostgreSqlPersistenceConfig` 제외 — 이 클래스는 `@PersistenceContext EntityManager` 필드와 - `FlywayConfigurationCustomizer @Bean` 을 함께 가져, 깨지지 않는 초기화 순환을 만듭니다 - (flyway → customizer 수집 → PostgreSqlPersistenceConfig 인스턴스화 → `@PersistenceContext` 가 - entityManagerFactory 를 당김 → 그건 flywayInitializer 에 의존 → 순환). 대신 - `SamplePostgreSqlPersistenceConfig` 가 static `@Bean` 으로 동일 빈을 제공해 순환을 끊습니다(아래 참고). - - `TestEnclosedConfigurationFilter` 제외 — 테스트 클래스 안에 중첩된 `@Configuration` 들이 넓은 - 컴포넌트 스캔에 잡혀, 두 테스트 픽스처가 같은 이름의 빈(예: `clock`)을 정의하면 - `BeanDefinitionOverrideException` 이 나기 때문입니다. +- **`@ComponentScan` 의 exclude**: `SecurityConfig`·`MethodSecurityConfig` — 공개 데모 앱이라 IdP나 + 메서드 보안 principal 없이 URL에 접근해야 한다. 프로덕션 모듈은 이 가드를 유지한다. +- 데이터 계층을 빼고 뜨는 테스트 슬라이스(`DataSourceAutoConfiguration` 제외)는 + `ca-skeleton.persistence-jpa.enabled=false`도 함께 준다. 모듈은 classpath에 있으면 켜지기 때문이다. -### SamplePostgreSqlPersistenceConfig — Flyway ↔ EntityManager 초기화 순환 끊기 -- `adapter-persistence-postgresql` 의 `PostgreSqlPersistenceConfig` 를 샘플 전용으로 대체한 것입니다. -- **왜 필요한가**: 원본은 `@PersistenceContext EntityManager` 필드와 `FlywayConfigurationCustomizer` - 빈을 함께 등록합니다. Spring Boot 의 Flyway 자동 구성은 `entityManagerFactory` 가 준비되기 전에 모든 - customizer 빈을 모읍니다(Flyway 가 먼저 마이그레이션을 돌려야 JPA 가 스키마를 검증할 수 있으니까). - 그 customizer 를 모으려고 `PostgreSqlPersistenceConfig` 를 인스턴스화하면 `@PersistenceContext` 가 - `entityManagerFactory` 를 당기는데, 그 빈은 `flywayInitializer` 완료에 의존합니다 → - `flyway → PostgreSqlPersistenceConfig → entityManagerFactory → flywayInitializer → flyway` 의 끊을 수 - 없는 순환이 생깁니다. -- **어떻게 끊는가**: customizer 를 **static `@Bean`** 으로 등록합니다. Spring 은 static `@Bean` 을 - 소유 클래스 인스턴스화 없이 호출하므로, Flyway 초기화 동안 `@PersistenceContext` 가 처리되지 - 않습니다. `EntityManager` 는 (런타임에 실제로 필요해질 때까지 미루도록) 빈 경로에서 늦게 해소됩니다. -- **마이그레이션 위치 주의**: 이 customizer 가 두 위치(프로덕션 `db/migration/postgresql` + 샘플 전용 - `db/sample-migration`)를 모두 설정합니다. `configuration.locations(...)` 는 기존 설정을 **덮어쓰므로** - (append 아님), `application.yml` 의 `spring.flyway.locations` 는 런타임 효과 없는 문서용일 뿐이고 - 실제 기준은 이 customizer 입니다. +### SamplePostgreSqlPersistenceConfig — 샘플 전용 두 번째 마이그레이션 스트림 +- 샘플 스키마(`db/sample-migration`)를 별도 history 테이블(`flyway_sample_schema_history`)로 + 적용하는 `FlywayMigrationStrategy` 하나만 둔다. 프로덕션 스트림을 먼저 migrate 한 뒤 샘플 스트림을 + baseline 0 으로 적용하므로, 샘플 V2/V7/V8이 프로덕션 버전 번호를 차지하지 않는다. +- vendor bean(`OutboxClaimRepository`, `SqlStateErrorMapping`), 엔티티·리포지토리 스캔, 프로덕션 + Flyway 위치는 persistence-jpa 모듈이 준다. 모듈의 `migrationStartupRunner`는 + `@ConditionalOnMissingBean(FlywayMigrationStrategy)`라 이 전략이 있으면 물러난다. ### 분산 추적 복제본 — SampleTracingConfig / …Settings / …SampleRateResolver / …EnvironmentPostProcessor / SampleMicrometerSpanErrorRecorder - `app-bootstrap` 의 tracing 구성 루트를 샘플 전용으로 옮긴 것들입니다(위 "공통 배경" 참고). tracing @@ -454,9 +441,12 @@ curl -X POST localhost:8080/work-logs -H 'Content-Type: application/json' -d '{ ### 그 밖의 부트스트랩 복제본 - **SampleMetricsContractConfig**: Micrometer `MeterFilter` 두 개를 meter 등록 전에 설치합니다 — 고-cardinality 태그 키를 막는 필터(D8)와 SLO 기반 히스토그램 분포 필터(D9, 소유한 timer 이름에만 적용). -- **SampleIdempotencyConfig / …Settings**: 스캔된 `IdempotencyStoreAdapter`/`IdempotencyReaper` 와 - `IdempotencyExecutor` 가 모두 `Clock` 을 필요로 하고, `@EnableScheduling` 이 reaper 의 `@Scheduled` - 정리를 켭니다. TTL 은 양수이며 ≤ 72h 여야 합니다(아니면 시작 실패), reaper 주기 기본 10분. +- **SampleIdempotencyConfig**: 샘플은 `ca-skeleton.capabilities.idempotency.provider=postgresql` + 로 `persistence-jpa` 의 PostgreSQL store 를 고릅니다. 샘플은 app-bootstrap 에 의존할 수 없으므로 + (`modules.json`) `IdempotencyExecutor` 는 이 설정이 한 번 만듭니다. app-bootstrap + `IdempotencySettings` 와 같은 prefix·같은 기본값에서 executor 가 쓰는 값만 읽고, provider 가 + `disabled` 면 만들지 않습니다. 예전 `SampleIdempotencySettings`(v1 `ca-skeleton.idempotency.ttl`)와 + `jdbc` provider 는 삭제됐습니다. - **SamplePseudonymizationConfig / SamplePrivacySettings**: adapter-web `RequestLoggingFilter` 가 `UserPrincipalPseudonymizerPort` 를 주입받으므로 그 포트를 채웁니다. salt 는 `APP_PRIVACY_PSEUDONYMIZATION_SALT` 에서 오며, 비어 있으면 로컬/테스트가 시작은 되도록 dev 센티넬 diff --git a/src/sample-portfolio/build.gradle b/src/sample-portfolio/build.gradle index 0c4b9869..38580fd4 100644 --- a/src/sample-portfolio/build.gradle +++ b/src/sample-portfolio/build.gradle @@ -4,7 +4,6 @@ plugins { id 'org.springframework.boot' id 'ca.auxiliary-source-set' id 'java-test-fixtures' - id 'ca.strict-qualification' } // Fixture/sample module. Production modules must not depend on this module. @@ -49,6 +48,9 @@ dependencies { implementation project(':domain-core') implementation project(':application-core') implementation project(':application-objectstorage') + // Relational persistence, selected like any capability: the module's auto-configuration + // assembles it. `implementation` rather than `runtimeOnly` because the sample's own adapters + // extend the module's audit base types. implementation project(':adapter:outbound:persistence-jpa') implementation project(':adapter:outbound:identifier') // Object storage adapter (filesystem default / S3-MinIO opt-in) provides the ObjectStoragePort @@ -75,14 +77,23 @@ dependencies { implementation libs.spring.dotenv // Boot 4 Flyway API/autoconfiguration needed by sample-local persistence configuration. implementation 'org.springframework.boot:spring-boot-flyway' - // Flyway core API needed by MigrationStartupConfig (scanned from adapter-persistence). + // Flyway core API: SamplePostgreSqlPersistenceConfig runs the sample's second migration stream. implementation 'org.flywaydb:flyway-core' - // Micrometer core for OutboxMetrics / BackgroundJobMetrics. + // Micrometer core for the sample's own meters. implementation 'io.micrometer:micrometer-core' // (spring-boot-starter-security is already declared above; it also backs ManagementSecurityConfig.) // Property-based testing for @ValueObject invariants (registers its own JUnit Platform engine). testImplementation libs.jqwik testImplementation libs.archunit.junit5 + // The Poster image workflow drives the real executor over the port owner's shared fake store. + testImplementation testFixtures(project(':application-core')) + + // Port contracts (`*Contract`) are abstract JUnit classes that the fake and the adapter both extend. + testFixturesImplementation project(':domain-core') + testFixturesImplementation project(':application-objectstorage') + testFixturesImplementation 'org.junit.jupiter:junit-jupiter-api' + testFixturesImplementation 'org.junit.jupiter:junit-jupiter-params' + testFixturesImplementation 'org.assertj:assertj-core' // Shared factory is compiled without leaking Testcontainers onto ordinary unit-test runtime. testFixturesCompileOnly 'org.testcontainers:testcontainers-postgresql' @@ -168,34 +179,27 @@ tasks.named('check') { dependsOn tasks.named('verifyDependencyLocks') } -def posterImageMigrationQualification = extensions.getByName('strictQualification').register( - 'posterImageMigrationTest', - sourceSets.integrationTest, - [ +// Named tests that must all run with none skipped: a qualification that quietly skips has certified +// nothing. +strictTestLanes { + lane('posterImageMigrationTest') { + sourceSet = 'integrationTest' + description = 'Runs the non-skipping PostgreSQL Poster image migration/rotation lane.' + requires( 'dev.caskeleton.sample.portfolio.qualification.PosterImageIdempotencyRotationQualificationTest', 'dev.caskeleton.sample.portfolio.qualification.PosterImageRetirementQualificationTest', - 'dev.caskeleton.sample.portfolio.qualification.PosterImageV8MigrationQualificationTest' - ], - 'Runs the non-skipping PostgreSQL Poster image migration/rotation lane.' -) -posterImageMigrationQualification.configure { - shouldRunAfter tasks.named('test') -} - -def messagingSampleContractQualification = extensions.getByName('strictQualification').register( - 'messagingSampleContractQualificationTest', - sourceSets.test, - [ - 'dev.caskeleton.sample.portfolio.application.event.WorkLogReservedContractContributionTest' - ], - rootProject.layout.buildDirectory.dir( - 'test-results/messaging-evidence/sample'), - rootProject.layout.buildDirectory.dir( - 'test-results/messaging-evidence-binary/sample'), - 'Runs exact Messaging sample contract qualification tests.' -) -messagingSampleContractQualification.configure { - dependsOn ':prepareMessagingContractEvidence' + 'dev.caskeleton.sample.portfolio.qualification.PosterImageV8MigrationQualificationTest') + rejectSkipped = true + jvmArgs '-Duser.timezone=UTC' + shouldRunAfter 'test' + } + lane('messagingSampleContractQualificationTest') { + sourceSet = 'test' + description = 'Runs exact Messaging sample contract qualification tests.' + requires('dev.caskeleton.sample.portfolio.application.event.WorkLogReservedContractContributionTest') + rejectSkipped = true + jvmArgs '-Duser.timezone=UTC' + } } bootJar { diff --git a/src/sample-portfolio/gradle.lockfile b/src/sample-portfolio/gradle.lockfile index 2442d559..2b9febd1 100644 --- a/src/sample-portfolio/gradle.lockfile +++ b/src/sample-portfolio/gradle.lockfile @@ -125,13 +125,14 @@ javax.inject:javax.inject:1=annotationProcessor,integrationTestAnnotationProcess jaxen:jaxen:2.0.6=spotbugs me.paulschwarz:spring-dotenv:4.0.0=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath net.bytebuddy:byte-buddy-agent:1.17.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath -net.bytebuddy:byte-buddy:1.17.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath +net.bytebuddy:byte-buddy:1.17.8=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath net.java.dev.jna:jna:5.18.1=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testFixturesCompileClasspath net.jqwik:jqwik-api:1.9.1=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath net.jqwik:jqwik-engine:1.9.1=integrationTestRuntimeClasspath,posterImageMigrationTestRuntimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath net.jqwik:jqwik-time:1.9.1=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath net.jqwik:jqwik-web:1.9.1=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath net.jqwik:jqwik:1.9.1=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath +net.logstash.logback:logstash-logback-encoder:8.0=integrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath net.minidev:accessors-smart:2.6.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath net.minidev:json-smart:2.6.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath net.sf.saxon:Saxon-HE:12.9=checkstyle,spotbugs @@ -154,9 +155,9 @@ org.apache.tomcat.embed:tomcat-embed-core:11.0.24=compileClasspath,integrationTe org.apache.tomcat.embed:tomcat-embed-el:11.0.24=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath org.apache.tomcat.embed:tomcat-embed-websocket:11.0.24=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath org.apache.xbean:xbean-reflect:3.7=checkstyle -org.apiguardian:apiguardian-api:1.1.2=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath +org.apiguardian:apiguardian-api:1.1.2=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath org.aspectj:aspectjweaver:1.9.25.1=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath -org.assertj:assertj-core:3.27.7=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath +org.assertj:assertj-core:3.27.7=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath org.awaitility:awaitility:4.3.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath org.checkerframework:checker-qual:3.55.1=integrationTestRuntimeClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath org.codehaus.plexus:plexus-classworlds:2.6.0=checkstyle @@ -181,21 +182,21 @@ org.jetbrains.kotlin:kotlin-stdlib:2.2.21=integrationTestRuntimeClasspath,poster org.jetbrains:annotations:13.0=productionRuntimeClasspath,runtimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath org.jetbrains:annotations:17.0.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testFixturesCompileClasspath org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,compileClasspath,integrationTestAnnotationProcessor,integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestAnnotationProcessor,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestAnnotationProcessor,systemTestCompileClasspath,systemTestRuntimeClasspath,testAnnotationProcessor,testCompileClasspath,testFixturesAnnotationProcessor,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestAnnotationProcessor,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath -org.junit.jupiter:junit-jupiter-api:6.0.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath +org.junit.jupiter:junit-jupiter-api:6.0.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath org.junit.jupiter:junit-jupiter-engine:6.0.3=integrationTestRuntimeClasspath,posterImageMigrationTestRuntimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath -org.junit.jupiter:junit-jupiter-params:6.0.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath +org.junit.jupiter:junit-jupiter-params:6.0.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath org.junit.jupiter:junit-jupiter:6.0.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath -org.junit.platform:junit-platform-commons:6.0.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath +org.junit.platform:junit-platform-commons:6.0.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath org.junit.platform:junit-platform-engine:6.0.3=integrationTestRuntimeClasspath,posterImageMigrationTestRuntimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath org.junit.platform:junit-platform-launcher:6.0.3=integrationTestRuntimeClasspath,posterImageMigrationTestRuntimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath -org.junit:junit-bom:6.0.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath +org.junit:junit-bom:6.0.3=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath org.junit:junit-bom:6.1.0=spotbugs org.latencyutils:LatencyUtils:2.0.3=integrationTestRuntimeClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath org.mockito:mockito-core:5.20.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,mockitoAgent,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath org.mockito:mockito-junit-jupiter:5.20.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath org.objenesis:objenesis:3.3=integrationTestRuntimeClasspath,posterImageMigrationTestRuntimeClasspath,systemTestRuntimeClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath org.openapitools:jackson-databind-nullable:0.2.6=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath -org.opentest4j:opentest4j:1.3.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath +org.opentest4j:opentest4j:1.3.0=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath org.osgi:org.osgi.annotation.bundle:2.0.0=compileClasspath,integrationTestCompileClasspath,posterImageMigrationTestCompileClasspath,systemTestCompileClasspath,testCompileClasspath,webSystemTestCompileClasspath org.osgi:org.osgi.annotation.versioning:1.1.2=compileClasspath,integrationTestCompileClasspath,posterImageMigrationTestCompileClasspath,systemTestCompileClasspath,testCompileClasspath,webSystemTestCompileClasspath org.osgi:org.osgi.resource:1.0.0=compileClasspath,integrationTestCompileClasspath,posterImageMigrationTestCompileClasspath,systemTestCompileClasspath,testCompileClasspath,webSystemTestCompileClasspath @@ -297,7 +298,7 @@ org.springframework:spring-orm:7.0.9=compileClasspath,integrationTestCompileClas org.springframework:spring-test:7.0.9=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath org.springframework:spring-tx:7.0.9=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath org.springframework:spring-web:7.0.9=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath -org.springframework:spring-webflux:7.0.9=integrationTestRuntimeClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestRuntimeClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestRuntimeClasspath +org.springframework:spring-webflux:7.0.9=posterImageMigrationTestRuntimeClasspath org.springframework:spring-webmvc:7.0.9=compileClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,productionRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testFixturesRuntimeClasspath,testRuntimeClasspath,webSystemTestCompileClasspath,webSystemTestRuntimeClasspath org.testcontainers:testcontainers-database-commons:2.0.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testFixturesCompileClasspath org.testcontainers:testcontainers-jdbc:2.0.5=integrationTestCompileClasspath,integrationTestRuntimeClasspath,posterImageMigrationTestCompileClasspath,posterImageMigrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testFixturesCompileClasspath diff --git a/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/PosterImageUploadIntentRepositoryIntegrationTest.java b/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/PosterImageUploadIntentRepositoryIntegrationTest.java index 63ec7e32..84759777 100644 --- a/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/PosterImageUploadIntentRepositoryIntegrationTest.java +++ b/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/PosterImageUploadIntentRepositoryIntegrationTest.java @@ -1,7 +1,7 @@ package dev.caskeleton.sample.portfolio.adapter.outbound.persistence.repository; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; import dev.caskeleton.application.idempotency.RequestFingerprint; import dev.caskeleton.application.objectstorage.identity.ObjectDestinationId; @@ -54,32 +54,80 @@ class PosterImageUploadIntentRepositoryIntegrationTest { @Autowired JdbcTemplate jdbc; @Test - void reserveReplayConflictAndRevisionCasUseOnlyNonReversibleScope() { + void createOrReadStoresAFreshReservationAtRevisionZero() { + // when PosterImageUploadIntent reserved = adapter.createOrRead(proposed("client-request-a")); - assertThat(reserved.state()).isEqualTo(PosterImageUploadIntentState.RESERVED); - assertThat(adapter.createOrRead(proposed("client-request-a"))).isEqualTo(reserved); - assertThatThrownBy(() -> adapter.createOrRead(proposed("different-body"))) - .isInstanceOf(PosterImageUploadIntentConflictException.class); + // then + assertThat(reserved) + .extracting(PosterImageUploadIntent::state, PosterImageUploadIntent::revision) + .containsExactly(PosterImageUploadIntentState.RESERVED, 0L); + } - PosterImageUploadIntent pending = - reserved.pending( - reserved.revision(), - ObjectStageHandle.parse("osh1.0123456789ab.0123456789abcdefghjkmnpqrs.f3226a9833"), - ObjectVersionToken.parse("osv1.0123456789ab.0123456789abcdefghjkmnpqrs.6678c6821f"), - "a".repeat(64), - 1, - Instant.parse("2026-07-29T00:01:00Z"), - Instant.parse("2026-07-29T00:00:01Z")); + @Test + void createOrReadWithTheSameRequestReplaysTheStoredReservation() { + // given + PosterImageUploadIntent reserved = adapter.createOrRead(proposed("client-request-a")); - PosterImageUploadIntent saved = adapter.compareAndSet(reserved.revision(), pending); + // when + PosterImageUploadIntent replayed = adapter.createOrRead(proposed("client-request-a")); - assertThat(saved.state()).isEqualTo(PosterImageUploadIntentState.PENDING); - assertThat(saved.revision()).isEqualTo(1); - assertThat( - jdbc.queryForObject( - "select idempotency_scope_digest from poster_image_upload_intent", String.class)) - .doesNotContain("client-request-a", "principal-a", "tenant-a"); + // then + assertThat(replayed).isEqualTo(reserved); + } + + @Test + void createOrReadWithADifferentRequestUnderTheSameScopeIsAConflict() { + // given + adapter.createOrRead(proposed("client-request-a")); + + // when + Throwable thrown = catchThrowable(() -> adapter.createOrRead(proposed("different-body"))); + + // then + assertThat(thrown) + .isInstanceOf(PosterImageUploadIntentConflictException.class) + .hasMessage("poster image idempotency scope is already bound to different work"); + } + + @Test + void compareAndSetStoresTheReplacementAtTheNextRevision() { + // given + PosterImageUploadIntent reserved = adapter.createOrRead(proposed("client-request-a")); + + // when + PosterImageUploadIntent saved = adapter.compareAndSet(reserved.revision(), pending(reserved)); + + // then + assertThat(saved) + .extracting(PosterImageUploadIntent::state, PosterImageUploadIntent::revision) + .containsExactly(PosterImageUploadIntentState.PENDING, 1L); + } + + @Test + void storedScopeDigestContainsNoReversibleRequestIdentity() { + // given + PosterImageUploadIntent reserved = adapter.createOrRead(proposed("client-request-a")); + adapter.compareAndSet(reserved.revision(), pending(reserved)); + + // when + String storedScope = + jdbc.queryForObject( + "select idempotency_scope_digest from poster_image_upload_intent", String.class); + + // then + assertThat(storedScope).doesNotContain("client-request-a", "principal-a", "tenant-a"); + } + + private static PosterImageUploadIntent pending(PosterImageUploadIntent reserved) { + return reserved.pending( + reserved.revision(), + ObjectStageHandle.parse("osh1.0123456789ab.0123456789abcdefghjkmnpqrs.f3226a9833"), + ObjectVersionToken.parse("osv1.0123456789ab.0123456789abcdefghjkmnpqrs.6678c6821f"), + "a".repeat(64), + 1, + Instant.parse("2026-07-29T00:01:00Z"), + Instant.parse("2026-07-29T00:00:01Z")); } private static PosterImageUploadIntent proposed(String fingerprintSource) { diff --git a/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/PosterRepositoryAdapterIntegrationTest.java b/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/PosterRepositoryAdapterIntegrationTest.java index 22d40be4..d4c19dfe 100644 --- a/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/PosterRepositoryAdapterIntegrationTest.java +++ b/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/PosterRepositoryAdapterIntegrationTest.java @@ -7,6 +7,7 @@ import dev.caskeleton.sample.portfolio.adapter.outbound.persistence.config.JpaCo import dev.caskeleton.sample.portfolio.domain.poster.Poster; import dev.caskeleton.sample.portfolio.domain.poster.PosterId; import dev.caskeleton.sample.portfolio.domain.poster.PosterImageReference; +import dev.caskeleton.sample.portfolio.domain.poster.PosterPage; import dev.caskeleton.sample.portfolio.domain.poster.PosterSortField; import dev.caskeleton.sample.portfolio.domain.poster.PosterStatus; import dev.caskeleton.sample.portfolio.domain.poster.PublishedPosterImageAttachment; @@ -15,7 +16,10 @@ import java.time.Clock; import java.time.Instant; import java.time.ZoneOffset; import java.util.Optional; +import java.util.UUID; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest; import org.springframework.boot.jdbc.test.autoconfigure.AutoConfigureTestDatabase; @@ -58,85 +62,129 @@ class PosterRepositoryAdapterIntegrationTest { static final PostgreSQLContainer POSTGRES = PostgreSqlTestContainer.create(); private static final PosterId ID = PosterId.of("0190bd6e-7c3e-7abc-8def-0123456789ab"); + private static final String IMAGE_KEY = "posters/" + ID.value() + "/image"; + private static final PosterImageReference REFERENCE = + PosterImageReference.of("osr1.0123456789ab.0123456789abcdefghjkmnpqrs.d53d9429ac"); @Autowired PosterRepositoryAdapter adapter; + @Autowired TestEntityManager em; - private Poster sample() { + @Test + void saveReturnsTheVersionHibernateAssignsOnInsert() { + // when + Poster saved = adapter.save(sample()); + + // then + assertThat(saved.version()).isZero(); + } + + /** Covers the UUID string/native uuid conversion and {@code @Enumerated(STRING)}. */ + @Test + void findByIdReadsBackEveryColumnWrittenBySave() { + // given + saveAndDetach(sample()); + + // when + Optional found = adapter.findById(ID); + + // then + assertThat(found) + .get() + .usingRecursiveComparison() + .isEqualTo(Poster.rehydrate(ID, "여름 세일 배너", "7월 한정", null, PosterStatus.DRAFT, 0L)); + } + + @Test + void savingAnAttachedAndPublishedPosterUpdatesTheStoredRow() { + // given + saveAndDetach(sample()); + Poster loaded = adapter.findById(ID).orElseThrow(); + loaded.attachImage(IMAGE_KEY); + loaded.publish(); + + // when + saveAndDetach(loaded); // UPDATE path: reload existing audit + bump version + + // then + assertThat(adapter.findById(ID)) + .get() + .extracting(Poster::status, Poster::imageKey) + .containsExactly(PosterStatus.PUBLISHED, IMAGE_KEY); + } + + @Test + void publishedReferenceIsReadBackAsAPublishedAttachment() { + // given + Poster poster = sample(); + poster.attachPublishedImage(REFERENCE); + saveAndDetach(poster); + + // when + Optional found = adapter.findById(ID); + + // then + assertThat(found) + .get() + .extracting(Poster::imageAttachment, Poster::imageReference) + .containsExactly(new PublishedPosterImageAttachment(REFERENCE), REFERENCE.value()); + } + + @Test + void publishedReferenceIsStoredOnlyInTheAdditiveReferenceColumn() { + // given + Poster poster = sample(); + poster.attachPublishedImage(REFERENCE); + + // when + saveAndDetach(poster); + + // then + assertThat( + (Object[]) + em.getEntityManager() + .createNativeQuery( + "select image_key, image_reference from poster where id = :id") + .setParameter("id", UUID.fromString(ID.value())) + .getSingleResult()) + .containsExactly(null, REFERENCE.value()); + } + + @ParameterizedTest + @CsvSource({"TITLE, DRAFT, 1", ", PUBLISHED, 0"}) + void findPageCountsOnlyPostersInTheRequestedStatus( + PosterSortField sortField, PosterStatus status, long expectedTotal) { + // given + saveAndDetach(sample()); + + // when + PosterPage page = adapter.findPage(0, 20, sortField, true, status); + + // then + assertThat(page.total()).isEqualTo(expectedTotal); + } + + @ParameterizedTest + @CsvSource({"여름 세일 Banner, true", "여름 세일 BANNER, true", "존재하지 않는 제목, false"}) + void existsByTitleMatchesAStoredTitleIgnoringCase(String title, boolean expected) { + // given + saveAndDetach(Poster.create(ID, "여름 세일 Banner", "7월 한정")); + + // when + boolean exists = adapter.existsByTitle(title); + + // then + assertThat(exists).isEqualTo(expected); + } + + private static Poster sample() { return Poster.create(ID, "여름 세일 배너", "7월 한정"); } - @Test - void saveThenFindByIdRoundTripsThroughRealPostgres(@Autowired TestEntityManager em) { - Poster saved = adapter.save(sample()); - assertThat(saved.version()).isNotNull(); // @Version assigned by Hibernate on INSERT - - em.flush(); - em.clear(); - - Optional found = adapter.findById(ID); - assertThat(found).isPresent(); - Poster p = found.get(); - assertThat(p.id()).isEqualTo(ID); // UUID string <-> native uuid - assertThat(p.title()).isEqualTo("여름 세일 배너"); - assertThat(p.status()).isEqualTo(PosterStatus.DRAFT); // @Enumerated(STRING) - assertThat(p.imageKey()).isNull(); - } - - @Test - void attachImageThenPublishIsPersisted(@Autowired TestEntityManager em) { - adapter.save(sample()); - em.flush(); - em.clear(); - - Poster loaded = adapter.findById(ID).orElseThrow(); - loaded.attachImage("posters/" + ID.value() + "/image"); - loaded.publish(); - adapter.save(loaded); // UPDATE path: reload existing audit + bump version - em.flush(); - em.clear(); - - Poster reread = adapter.findById(ID).orElseThrow(); - assertThat(reread.status()).isEqualTo(PosterStatus.PUBLISHED); - assertThat(reread.imageKey()).isEqualTo("posters/" + ID.value() + "/image"); - } - - @Test - void canonicalReadyReferenceUsesOnlyTheAdditiveReferenceColumn(@Autowired TestEntityManager em) { - Poster poster = sample(); - PosterImageReference reference = - PosterImageReference.of("osr1.0123456789ab.0123456789abcdefghjkmnpqrs.d53d9429ac"); - poster.attachPublishedImage(reference); + /** Writes through to PostgreSQL and empties the persistence context, so the next read is real. */ + private void saveAndDetach(Poster poster) { adapter.save(poster); em.flush(); em.clear(); - - Poster reread = adapter.findById(ID).orElseThrow(); - assertThat(reread.imageAttachment()).isEqualTo(new PublishedPosterImageAttachment(reference)); - assertThat(reread.imageReference()).isEqualTo(reference.value()); - Number legacyKeyCount = - (Number) - em.getEntityManager() - .createNativeQuery( - "select count(*) from poster where id = :id and image_key is not null") - .setParameter("id", java.util.UUID.fromString(ID.value())) - .getSingleResult(); - assertThat(legacyKeyCount.longValue()).isZero(); - } - - @Test - void findPageAppliesStatusFilterAndExistsByTitleIsCaseInsensitive( - @Autowired TestEntityManager em) { - adapter.save(sample()); - em.flush(); - em.clear(); - - assertThat(adapter.findPage(0, 20, PosterSortField.TITLE, true, PosterStatus.DRAFT).total()) - .isEqualTo(1); - // A non-matching status filter runs the real derived query and returns nothing. - assertThat(adapter.findPage(0, 20, null, true, PosterStatus.PUBLISHED).total()).isZero(); - - assertThat(adapter.existsByTitle("여름 세일 배너")).isTrue(); - assertThat(adapter.existsByTitle("존재하지 않는 제목")).isFalse(); } @TestConfiguration diff --git a/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/WorkLogRepositoryAdapterContractTest.java b/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/WorkLogRepositoryAdapterContractTest.java new file mode 100644 index 00000000..7250a593 --- /dev/null +++ b/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/WorkLogRepositoryAdapterContractTest.java @@ -0,0 +1,70 @@ +package dev.caskeleton.sample.portfolio.adapter.outbound.persistence.repository; + +import dev.caskeleton.sample.portfolio.adapter.outbound.persistence.config.JpaConfig; +import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogRepository; +import dev.caskeleton.sample.portfolio.domain.worklog.testkit.WorkLogRepositoryContract; +import dev.caskeleton.sample.portfolio.testinfra.PostgreSqlTestContainer; +import java.util.function.Supplier; +import org.junit.jupiter.api.BeforeEach; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest; +import org.springframework.boot.jdbc.test.autoconfigure.AutoConfigureTestDatabase; +import org.springframework.boot.testcontainers.service.connection.ServiceConnection; +import org.springframework.context.annotation.Import; +import org.springframework.test.context.TestPropertySource; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import org.testcontainers.postgresql.PostgreSQLContainer; + +/** + * The shipped adapter against real PostgreSQL, held to the same {@link WorkLogRepositoryContract} + * as the in-memory fake. The test-managed transaction is switched off so every contract call + * commits on its own and every read goes back to the database. + */ +@DataJpaTest +@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) +@Testcontainers(disabledWithoutDocker = true) +@Transactional(propagation = Propagation.NOT_SUPPORTED) +@Import({ + JpaConfig.class, + WorkLogRepositoryAdapter.class, + WorkLogRepositoryAdapterIntegrationTest.TestAuditConfig.class +}) +@TestPropertySource( + properties = { + "spring.flyway.enabled=true", + "spring.flyway.locations=classpath:db/migration/postgresql,classpath:db/sample-migration", + "spring.jpa.hibernate.ddl-auto=validate" + }) +class WorkLogRepositoryAdapterContractTest extends WorkLogRepositoryContract { + + @Container @ServiceConnection + static final PostgreSQLContainer POSTGRES = PostgreSqlTestContainer.create(); + + @Autowired private WorkLogRepositoryAdapter adapter; + @Autowired private WorkLogJpaRepository jpa; + @Autowired private PlatformTransactionManager transactionManager; + + @BeforeEach + void empty() { + inTransaction( + () -> { + jpa.deleteAll(); + return null; + }); + } + + @Override + protected WorkLogRepository repository() { + return adapter; + } + + @Override + protected T inTransaction(Supplier work) { + return new TransactionTemplate(transactionManager).execute(status -> work.get()); + } +} diff --git a/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/WorkLogRepositoryAdapterIntegrationTest.java b/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/WorkLogRepositoryAdapterIntegrationTest.java index ab92b9b5..9d5db87d 100644 --- a/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/WorkLogRepositoryAdapterIntegrationTest.java +++ b/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/WorkLogRepositoryAdapterIntegrationTest.java @@ -8,8 +8,6 @@ import dev.caskeleton.sample.portfolio.domain.worklog.Period; import dev.caskeleton.sample.portfolio.domain.worklog.WorkCategory; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLog; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogId; -import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogPage; -import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogSortField; import dev.caskeleton.sample.portfolio.testinfra.PostgreSqlTestContainer; import java.time.Clock; import java.time.Instant; @@ -66,57 +64,46 @@ class WorkLogRepositoryAdapterIntegrationTest { static final PostgreSQLContainer POSTGRES = PostgreSqlTestContainer.create(); private static final WorkLogId ID = WorkLogId.of("0190bd6e-7c3e-7abc-8def-0123456789ab"); + private static final Period PERIOD = + new Period(LocalDate.of(2025, 1, 1), LocalDate.of(2025, 2, 1)); + private static final List TECH_STACK = List.of("postgres", "jpa"); + private static final List LINKS = List.of("https://example.test/pr/1"); @Autowired WorkLogRepositoryAdapter adapter; + @Autowired TestEntityManager em; - private WorkLog sample() { - return WorkLog.create( - ID, - "DB 튜닝", - WorkCategory.DATABASE, - "summary", - "content", - List.of("postgres", "jpa"), - List.of("https://example.test/pr/1"), - new Period(LocalDate.of(2025, 1, 1), LocalDate.of(2025, 2, 1))); - } - + /** + * Covers the UUID string/native uuid conversion, {@code @Enumerated(STRING)}, the + * {@code @ElementCollection} join tables and the {@code @Version} Hibernate assigns on INSERT. + */ @Test - void saveThenFindByIdRoundTripsThroughRealPostgres(@Autowired TestEntityManager em) { - WorkLog saved = adapter.save(sample()); - assertThat(saved.version()).isNotNull(); // @Version assigned by Hibernate on INSERT - - // Force a real SELECT instead of the persistence-context L1 cache so the column / - // enum / collection / UUID string<->uuid mapping is actually round-tripped through Postgres. + void findByIdReadsBackEveryColumnWrittenBySave() { + // given + adapter.save( + WorkLog.create( + ID, "DB 튜닝", WorkCategory.DATABASE, "summary", "content", TECH_STACK, LINKS, PERIOD)); + // Force a real SELECT instead of the persistence-context L1 cache. em.flush(); em.clear(); + // when Optional found = adapter.findById(ID); - assertThat(found).isPresent(); - WorkLog w = found.get(); - assertThat(w.id()).isEqualTo(ID); // UUID string <-> native uuid - assertThat(w.title()).isEqualTo("DB 튜닝"); - assertThat(w.category()).isEqualTo(WorkCategory.DATABASE); // @Enumerated(STRING) - assertThat(w.techStack()).containsExactly("postgres", "jpa"); // @ElementCollection join table - assertThat(w.links()).containsExactly("https://example.test/pr/1"); - assertThat(w.period().start()).isEqualTo(LocalDate.of(2025, 1, 1)); - assertThat(w.period().end()).isEqualTo(LocalDate.of(2025, 2, 1)); - } - @Test - void findPageReadsPersistedRowsAndAppliesCategoryFilter(@Autowired TestEntityManager em) { - adapter.save(sample()); - em.flush(); - em.clear(); - - WorkLogPage matching = - adapter.findPage(0, 20, WorkLogSortField.TITLE, true, WorkCategory.DATABASE); - assertThat(matching.total()).isEqualTo(1); - assertThat(matching.items()).hasSize(1); - assertThat(matching.items().get(0).id()).isEqualTo(ID); - - // A non-matching category filter runs the real derived query and returns nothing. - assertThat(adapter.findPage(0, 20, null, true, WorkCategory.BACKEND).total()).isZero(); + // then + assertThat(found) + .get() + .usingRecursiveComparison() + .isEqualTo( + WorkLog.rehydrate( + ID, + "DB 튜닝", + WorkCategory.DATABASE, + "summary", + "content", + TECH_STACK, + LINKS, + PERIOD, + 0L)); } @TestConfiguration diff --git a/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/bootstrap/idempotency/SampleIdempotencyReplayIntegrationTest.java b/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/bootstrap/idempotency/SampleIdempotencyReplayIntegrationTest.java new file mode 100644 index 00000000..f40e488e --- /dev/null +++ b/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/bootstrap/idempotency/SampleIdempotencyReplayIntegrationTest.java @@ -0,0 +1,120 @@ +package dev.caskeleton.sample.portfolio.bootstrap.idempotency; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.application.idempotency.IdempotencyExecutor; +import dev.caskeleton.application.idempotency.IdempotentAction; +import dev.caskeleton.application.idempotency.RequestFingerprint; +import dev.caskeleton.application.objectstorage.identity.ObjectOperationId; +import dev.caskeleton.application.transaction.OperationId; +import dev.caskeleton.sample.portfolio.adapter.outbound.identifier.HmacPosterImageIdempotencyScopeDigester; +import dev.caskeleton.sample.portfolio.application.posterimage.PosterImagePublicationReservation; +import dev.caskeleton.sample.portfolio.application.posterimage.PosterImagePublicationReservationCodec; +import dev.caskeleton.sample.portfolio.application.posterimage.PosterImageSanitizedIdempotencyContextFactory; +import dev.caskeleton.sample.portfolio.domain.poster.PosterId; +import dev.caskeleton.sample.portfolio.testinfra.PostgreSqlTestContainer; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; +import org.junit.jupiter.api.Test; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.flyway.autoconfigure.FlywayAutoConfiguration; +import org.springframework.boot.jdbc.autoconfigure.DataSourceAutoConfiguration; +import org.springframework.boot.jdbc.autoconfigure.DataSourceTransactionManagerAutoConfiguration; +import org.springframework.boot.jdbc.autoconfigure.JdbcTemplateAutoConfiguration; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import org.testcontainers.postgresql.PostgreSQLContainer; + +/** + * The sample's executor over the PostgreSQL provider replays a Poster image reservation on a fresh + * database: the sample HMAC scope reaches the owner-safe store, the reservation codec round-trips + * through it, and the second request with the same key never runs the reservation again. + */ +@Testcontainers +class SampleIdempotencyReplayIntegrationTest { + + private static final String POSTGRESQL_STORE_CONFIG = + "dev.caskeleton.adapter.outbound.persistence.autoconfigure.PostgreSqlIdempotencyStoreConfig"; + + @Container static final PostgreSQLContainer POSTGRES = PostgreSqlTestContainer.create(); + + @Test + void secondReservationWithTheSameKeyReplaysTheFirst() throws Exception { + // given + AtomicInteger reservations = new AtomicInteger(); + + // when + List responses = reserveTwiceWithOneKey(reservations); + + // then + assertThat(List.of(responses, reservations.get())) + .containsExactly(List.of(reservation(1), reservation(1)), 1); + } + + private List reserveTwiceWithOneKey(AtomicInteger reservations) + throws Exception { + var digester = + new HmacPosterImageIdempotencyScopeDigester( + "key-v1", + Map.of("key-v1", "0123456789abcdef0123456789abcdef".getBytes(StandardCharsets.UTF_8))); + var scope = + new PosterImageSanitizedIdempotencyContextFactory(digester) + .create("tenant-a", "principal-a", "client-key-a") + .scope(); + var fingerprint = RequestFingerprint.ofSha256("poster".getBytes(StandardCharsets.UTF_8)); + PosterImagePublicationReservation[] responses = new PosterImagePublicationReservation[2]; + runner() + .run( + context -> { + assertThat(context).hasNotFailed(); + IdempotencyExecutor executor = context.getBean(IdempotencyExecutor.class); + TransactionTemplate transactions = + new TransactionTemplate(context.getBean(PlatformTransactionManager.class)); + for (int request = 0; request < 2; request++) { + OperationId operation = new OperationId("poster-request-" + request); + responses[request] = + transactions.execute( + status -> + executor.execute( + scope, + fingerprint, + executor.newAttempt(operation), + () -> + new IdempotentAction.Outcome.Success<>( + reservation(reservations.incrementAndGet())), + new PosterImagePublicationReservationCodec())); + } + }); + return List.of(responses); + } + + private static PosterImagePublicationReservation reservation(int sequence) { + return new PosterImagePublicationReservation( + PosterId.of("0190bd6e-7c3e-7abc-8def-0123456789ab"), + ObjectOperationId.of("0190bd6e-7c3e-7abc-8def-01234567890" + sequence)); + } + + private static ApplicationContextRunner runner() throws ClassNotFoundException { + return new ApplicationContextRunner() + .withConfiguration( + AutoConfigurations.of( + DataSourceAutoConfiguration.class, + JdbcTemplateAutoConfiguration.class, + DataSourceTransactionManagerAutoConfiguration.class, + FlywayAutoConfiguration.class)) + .withUserConfiguration( + Class.forName(POSTGRESQL_STORE_CONFIG), SampleIdempotencyConfig.class) + .withPropertyValues( + // The sample's shipped default. + "ca-skeleton.capabilities.idempotency.provider=postgresql", + "spring.datasource.url=" + POSTGRES.getJdbcUrl(), + "spring.datasource.username=" + POSTGRES.getUsername(), + "spring.datasource.password=" + POSTGRES.getPassword(), + "spring.flyway.locations=classpath:db/migration/postgresql"); + } +} diff --git a/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/bootstrap/persistence/SampleMigrationStreamIsolationTest.java b/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/bootstrap/persistence/SampleMigrationStreamIsolationTest.java index 76df92ec..7843beae 100644 --- a/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/bootstrap/persistence/SampleMigrationStreamIsolationTest.java +++ b/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/bootstrap/persistence/SampleMigrationStreamIsolationTest.java @@ -7,6 +7,9 @@ import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; import org.flywaydb.core.Flyway; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -34,48 +37,53 @@ class SampleMigrationStreamIsolationTest { } @Test - void productionAndSampleUseIndependentHistoryTables() throws Exception { + void productionHistoryRecordsNoSampleVersion() throws SQLException { + // when SamplePostgreSqlPersistenceConfig.sampleMigrationStrategy().migrate(productionFlyway); + // then + assertThat(successfulVersions("flyway_schema_history")) + .contains("1", "3", "13") + .doesNotContain("2", "7", "8"); + } + + @Test + void sampleHistoryRecordsTheSampleVersions() throws SQLException { + // when + SamplePostgreSqlPersistenceConfig.sampleMigrationStrategy().migrate(productionFlyway); + + // then + assertThat(successfulVersions("flyway_sample_schema_history")).contains("2", "7", "8"); + } + + @Test + void sampleMigrationsCreateTheSampleTables() throws SQLException { + // when + SamplePostgreSqlPersistenceConfig.sampleMigrationStrategy().migrate(productionFlyway); + + // then + assertThat( + strings( + "select table_name from information_schema.tables where table_schema = 'public'")) + .contains("work_log", "poster"); + } + + private static List successfulVersions(String history) throws SQLException { + return strings( + "select version from " + history + " where success = true order by installed_rank"); + } + + private static List strings(String sql) throws SQLException { try (Connection connection = - DriverManager.getConnection( - POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword())) { - assertThat(successfulVersions(connection, "flyway_schema_history")) - .contains("1", "3", "13") - .doesNotContain("2", "7", "8"); - assertThat(successfulVersions(connection, "flyway_sample_schema_history")) - .contains("2", "7", "8"); - assertThat(tableExists(connection, "work_log")).isTrue(); - assertThat(tableExists(connection, "poster")).isTrue(); - } - } - - private static java.util.List successfulVersions(Connection connection, String history) - throws Exception { - try (PreparedStatement statement = - connection.prepareStatement( - "select version from " - + history - + " where success = true order by installed_rank"); + DriverManager.getConnection( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); + PreparedStatement statement = connection.prepareStatement(sql); ResultSet result = statement.executeQuery()) { - java.util.ArrayList versions = new java.util.ArrayList<>(); + List values = new ArrayList<>(); while (result.next()) { - versions.add(result.getString(1)); - } - return java.util.List.copyOf(versions); - } - } - - private static boolean tableExists(Connection connection, String table) throws Exception { - try (PreparedStatement statement = - connection.prepareStatement( - "select count(*) from information_schema.tables " - + "where table_schema = 'public' and table_name = ?")) { - statement.setString(1, table); - try (ResultSet result = statement.executeQuery()) { - assertThat(result.next()).isTrue(); - return result.getInt(1) == 1; + values.add(result.getString(1)); } + return values; } } } diff --git a/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/qualification/PosterImageIdempotencyRotationQualificationTest.java b/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/qualification/PosterImageIdempotencyRotationQualificationTest.java index eaea8b6f..cb319947 100644 --- a/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/qualification/PosterImageIdempotencyRotationQualificationTest.java +++ b/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/qualification/PosterImageIdempotencyRotationQualificationTest.java @@ -3,28 +3,53 @@ package dev.caskeleton.sample.portfolio.qualification; import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.sample.portfolio.adapter.outbound.identifier.HmacPosterImageIdempotencyScopeDigester; +import dev.caskeleton.sample.portfolio.application.posterimage.PosterImageIdempotencyScopeDigest; import java.nio.charset.StandardCharsets; -import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; import java.util.concurrent.atomic.AtomicReference; import org.junit.jupiter.api.Test; class PosterImageIdempotencyRotationQualificationTest { + private final AtomicReference active = new AtomicReference<>("key-v1"); + private final HmacPosterImageIdempotencyScopeDigester digester = + new HmacPosterImageIdempotencyScopeDigester( + active::get, + Map.of( + "key-v1", "0123456789abcdef0123456789abcdef".getBytes(StandardCharsets.UTF_8), + "key-v2", "abcdef0123456789abcdef0123456789".getBytes(StandardCharsets.UTF_8))); + + @Test + void activatingANewKeyMovesNewDigestsToThatKeyVersion() { + // given + PosterImageIdempotencyScopeDigest before = digest(); + + // when + active.set("key-v2"); + + // then + assertThat(List.of(before, digest())) + .extracting(PosterImageIdempotencyScopeDigest::keyVersion) + .containsExactly("key-v1", "key-v2"); + } + @Test void overlapFirstActivationKeepsOldDigestDiscoverable() { - var active = new AtomicReference<>("key-v1"); - var keys = new LinkedHashMap(); - keys.put("key-v1", "0123456789abcdef0123456789abcdef".getBytes(StandardCharsets.UTF_8)); - keys.put("key-v2", "abcdef0123456789abcdef0123456789".getBytes(StandardCharsets.UTF_8)); - var digester = new HmacPosterImageIdempotencyScopeDigester(active::get, keys); - - var before = digester.digest("tenant", "principal", "use-case", "client-key"); + // given + PosterImageIdempotencyScopeDigest before = digest(); active.set("key-v2"); - var after = digester.digest("tenant", "principal", "use-case", "client-key"); + PosterImageIdempotencyScopeDigest after = digest(); - assertThat(before.keyVersion()).isEqualTo("key-v1"); - assertThat(after.keyVersion()).isEqualTo("key-v2"); - assertThat(digester.retainedDigests("tenant", "principal", "use-case", "client-key")) - .contains(before, after); + // when + List retained = + digester.retainedDigests("tenant", "principal", "use-case", "client-key"); + + // then + assertThat(retained).contains(before, after); + } + + private PosterImageIdempotencyScopeDigest digest() { + return digester.digest("tenant", "principal", "use-case", "client-key"); } } diff --git a/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/qualification/PosterImageRetirementQualificationTest.java b/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/qualification/PosterImageRetirementQualificationTest.java index 877612a0..5e33ee41 100644 --- a/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/qualification/PosterImageRetirementQualificationTest.java +++ b/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/qualification/PosterImageRetirementQualificationTest.java @@ -6,7 +6,9 @@ import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; +import java.sql.SQLException; import java.time.OffsetDateTime; +import java.util.List; import java.util.UUID; import org.flywaydb.core.Flyway; import org.junit.jupiter.api.BeforeEach; @@ -21,6 +23,8 @@ class PosterImageRetirementQualificationTest { @Container static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer("postgres:16.4-alpine"); + private static final OffsetDateTime NOW = OffsetDateTime.parse("2026-07-29T00:00:00Z"); + @BeforeEach void migrateFreshDatabase() { Flyway.configure() @@ -37,74 +41,93 @@ class PosterImageRetirementQualificationTest { } @Test - void exactRetirementWorkSurvivesPosterDeletionWithoutCascade() throws Exception { + void exactRetirementWorkSurvivesPosterDeletionWithoutCascade() throws SQLException { + // given UUID posterId = UUID.randomUUID(); UUID intentId = UUID.randomUUID(); - try (Connection connection = connection()) { - insertPoster(connection, posterId); - try (PreparedStatement insert = - connection.prepareStatement( - """ - insert into poster_image_retirement_intent ( - id, poster_id, operation_id, image_reference, exact_version, - state, retain_until, attempt_count, created_at, updated_at, revision - ) values (?, ?, ?, ?, ?, 'PENDING', ?, 0, ?, ?, 0) - """)) { - insert.setObject(1, intentId); - insert.setObject(2, posterId); - insert.setString(3, "retire-operation-1"); - insert.setString(4, "osr1.0123456789ab.0123456789abcdefghjkmnpqrs.d53d9429ac"); - insert.setString(5, "osv1.0123456789ab.0123456789abcdefghjkmnpqrs.6678c6821f"); - OffsetDateTime now = OffsetDateTime.parse("2026-07-29T00:00:00Z"); - insert.setObject(6, now); - insert.setObject(7, now); - insert.setObject(8, now); - assertThat(insert.executeUpdate()).isEqualTo(1); - } - try (PreparedStatement delete = - connection.prepareStatement("delete from poster where id = ?")) { - delete.setObject(1, posterId); - assertThat(delete.executeUpdate()).isEqualTo(1); - } - try (PreparedStatement select = - connection.prepareStatement( - "select poster_id, state from poster_image_retirement_intent where id = ?")) { - select.setObject(1, intentId); - try (ResultSet result = select.executeQuery()) { - assertThat(result.next()).isTrue(); - assertThat(result.getObject(1, UUID.class)).isEqualTo(posterId); - assertThat(result.getString(2)).isEqualTo("PENDING"); - } - } - } + insertPoster(posterId); + insertPendingRetirementIntent(intentId, posterId); + + // when + deletePoster(posterId); + + // then + assertThat(retirementIntent(intentId)).containsExactly(posterId, "PENDING"); } - private Connection connection() throws Exception { + private Connection connection() throws SQLException { return DriverManager.getConnection( POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); } - private static void insertPoster(Connection connection, UUID posterId) throws Exception { - try (PreparedStatement statement = - connection.prepareStatement( - """ - insert into poster ( - id, title, caption, image_reference, status, version, - created_at, updated_at, created_by, updated_by - ) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - """)) { - OffsetDateTime now = OffsetDateTime.parse("2026-07-29T00:00:00Z"); + private void insertPoster(UUID posterId) throws SQLException { + try (Connection connection = connection(); + PreparedStatement statement = + connection.prepareStatement( + """ + insert into poster ( + id, title, caption, image_reference, status, version, + created_at, updated_at, created_by, updated_by + ) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + """)) { statement.setObject(1, posterId); statement.setString(2, "canonical"); statement.setString(3, "retirement qualification"); statement.setString(4, "osr1.0123456789ab.0123456789abcdefghjkmnpqrs.d53d9429ac"); statement.setString(5, "DRAFT"); statement.setLong(6, 0); - statement.setObject(7, now); - statement.setObject(8, now); + statement.setObject(7, NOW); + statement.setObject(8, NOW); statement.setString(9, "qualification"); statement.setString(10, "qualification"); assertThat(statement.executeUpdate()).isEqualTo(1); } } + + private void insertPendingRetirementIntent(UUID intentId, UUID posterId) throws SQLException { + try (Connection connection = connection(); + PreparedStatement statement = + connection.prepareStatement( + """ + insert into poster_image_retirement_intent ( + id, poster_id, operation_id, image_reference, exact_version, + state, retain_until, attempt_count, created_at, updated_at, revision + ) values (?, ?, ?, ?, ?, 'PENDING', ?, 0, ?, ?, 0) + """)) { + statement.setObject(1, intentId); + statement.setObject(2, posterId); + statement.setString(3, "retire-operation-1"); + statement.setString(4, "osr1.0123456789ab.0123456789abcdefghjkmnpqrs.d53d9429ac"); + statement.setString(5, "osv1.0123456789ab.0123456789abcdefghjkmnpqrs.6678c6821f"); + statement.setObject(6, NOW); + statement.setObject(7, NOW); + statement.setObject(8, NOW); + assertThat(statement.executeUpdate()).isEqualTo(1); + } + } + + /** Fails unless exactly one row goes, so a surviving intent cannot mean "nothing was deleted". */ + private void deletePoster(UUID posterId) throws SQLException { + try (Connection connection = connection(); + PreparedStatement statement = + connection.prepareStatement("delete from poster where id = ?")) { + statement.setObject(1, posterId); + assertThat(statement.executeUpdate()).isEqualTo(1); + } + } + + /** The intent's {@code poster_id} and {@code state}; empty when the row is gone. */ + private List retirementIntent(UUID intentId) throws SQLException { + try (Connection connection = connection(); + PreparedStatement statement = + connection.prepareStatement( + "select poster_id, state from poster_image_retirement_intent where id = ?")) { + statement.setObject(1, intentId); + try (ResultSet result = statement.executeQuery()) { + return result.next() + ? List.of(result.getObject(1, UUID.class), result.getString(2)) + : List.of(); + } + } + } } diff --git a/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/qualification/PosterImageV8MigrationQualificationTest.java b/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/qualification/PosterImageV8MigrationQualificationTest.java index 252d204a..bebd9e8d 100644 --- a/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/qualification/PosterImageV8MigrationQualificationTest.java +++ b/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/qualification/PosterImageV8MigrationQualificationTest.java @@ -6,9 +6,13 @@ import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; +import java.sql.SQLException; import java.time.OffsetDateTime; +import java.util.ArrayList; import java.util.List; +import java.util.UUID; import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.output.MigrateResult; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.testcontainers.junit.jupiter.Container; @@ -21,80 +25,116 @@ class PosterImageV8MigrationQualificationTest { @Container static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer("postgres:16.4-alpine"); + private static final OffsetDateTime NOW = OffsetDateTime.parse("2026-07-29T00:00:00Z"); + @BeforeEach void cleanDatabase() { flyway(null).clean(); } + /** + * V8 was applied — not "V8 is the last migration in the repository". + * + *

    This assertion used to pin {@code targetSchemaVersion} to "8", which was the tail of the + * combined timeline on the day it was written. Two unrelated migrations landed later (V9 widened + * a capability schema stream, V10 changed an idempotency column type) and this gate began failing + * on a fact about neither its subject nor its claim. The tail of a shared timeline belongs to + * whatever landed last; what this test qualifies is that V8 runs. + */ @Test - void freshTimelineCreatesAdditiveLocatorFreeIntentSchema() throws Exception { - // V8 was applied — not "V8 is the last migration in the repository". - // - // This assertion used to pin `targetSchemaVersion` to "8", which was the tail of the combined - // timeline on the day it was written. Two unrelated migrations landed later (V9 widened a - // capability schema stream, V10 changed an idempotency column type) and this gate began failing - // on a fact about neither its subject nor its claim. The tail of a shared timeline belongs to - // whatever landed last; what this test qualifies is that V8 runs and leaves the shape below. - assertThat(flyway(null).migrate().migrations) - .extracting(migration -> migration.version) - .contains("8"); + void freshTimelineAppliesV8() { + // when + MigrateResult result = flyway(null).migrate(); - try (Connection connection = connection()) { - assertThat(columns(connection, "poster")).contains("image_key", "image_reference"); - assertThat(columns(connection, "poster_image_upload_intent")) - .contains( - "idempotency_scope_digest", - "request_fingerprint", - "stage_handle", - "handoff_fence", - "published_reference", - "revision") - .doesNotContain( - "idempotency_key", - "principal", - "tenant", - "payload", - "bucket", - "path", - "presigned_url"); - assertThat(columns(connection, "poster_image_retirement_intent")) - .contains("image_reference", "exact_version", "retain_until"); - assertThat(foreignKeys(connection, "poster_image_upload_intent")).isEmpty(); - assertThat(foreignKeys(connection, "poster_image_retirement_intent")).isEmpty(); - } + // then + assertThat(result.migrations).extracting(migration -> migration.version).contains("8"); } @Test - void v7LegacyRowsAndOldBinaryProjectionSurviveV8Upgrade() throws Exception { - flyway("7").migrate(); - try (Connection connection = connection()) { - oldBinaryInsert(connection, "legacy-before-upgrade"); - } - + void freshTimelineKeepsTheLegacyImageKeyBesideTheAdditiveImageReference() throws SQLException { + // when flyway(null).migrate(); - try (Connection connection = connection()) { - assertThat( - scalar( - connection, "select image_key from poster where title = 'legacy-before-upgrade'")) - .isEqualTo("posters/legacy/image"); - assertThat( - scalar( - connection, - "select image_reference from poster" + " where title = 'legacy-before-upgrade'")) - .isNull(); + // then + assertThat(columns("poster")).contains("image_key", "image_reference"); + } - oldBinaryInsert(connection, "legacy-after-upgrade"); - try (PreparedStatement update = - connection.prepareStatement("update poster set caption = ? where title = ?")) { - update.setString(1, "old binary update"); - update.setString(2, "legacy-after-upgrade"); - assertThat(update.executeUpdate()).isEqualTo(1); - } - assertThat( - scalar(connection, "select caption from poster where title = 'legacy-after-upgrade'")) - .isEqualTo("old binary update"); - } + @Test + void freshTimelineUploadIntentStoresDigestsAndNoLocatorOrRawIdentity() throws SQLException { + // when + flyway(null).migrate(); + + // then + assertThat(columns("poster_image_upload_intent")) + .contains( + "idempotency_scope_digest", + "request_fingerprint", + "stage_handle", + "handoff_fence", + "published_reference", + "revision") + .doesNotContain( + "idempotency_key", "principal", "tenant", "payload", "bucket", "path", "presigned_url"); + } + + @Test + void freshTimelineRetirementIntentRecordsTheExactVersionToRetire() throws SQLException { + // when + flyway(null).migrate(); + + // then + assertThat(columns("poster_image_retirement_intent")) + .contains("image_reference", "exact_version", "retain_until"); + } + + @Test + void freshTimelineGivesTheIntentTablesNoForeignKeys() throws SQLException { + // when + flyway(null).migrate(); + + // then + assertThat( + strings( + """ + select table_name + from information_schema.table_constraints + where table_schema = 'public' + and table_name in ('poster_image_upload_intent', 'poster_image_retirement_intent') + and constraint_type = 'FOREIGN KEY' + """)) + .isEmpty(); + } + + @Test + void v7LegacyRowKeepsItsImageKeyAndGetsNoReferenceThroughTheV8Upgrade() throws SQLException { + // given + flyway("7").migrate(); + oldBinaryInsert("legacy-before-upgrade"); + + // when + flyway(null).migrate(); + + // then + assertThat( + row( + "select image_key, image_reference from poster where title = ?", + "legacy-before-upgrade")) + .containsExactly("posters/legacy/image", null); + } + + @Test + void oldBinaryCanStillUpdateARowItInsertedAfterTheV8Upgrade() throws SQLException { + // given + flyway("7").migrate(); + flyway(null).migrate(); + oldBinaryInsert("legacy-after-upgrade"); + + // when + execute("update poster set caption = 'old binary update' where title = 'legacy-after-upgrade'"); + + // then + assertThat(row("select caption from poster where title = ?", "legacy-after-upgrade")) + .containsExactly("old binary update"); } private Flyway flyway(String target) { @@ -109,77 +149,84 @@ class PosterImageV8MigrationQualificationTest { return configuration.load(); } - private Connection connection() throws Exception { + private static Connection connection() throws SQLException { return DriverManager.getConnection( POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); } - private static List columns(Connection connection, String table) throws Exception { - try (PreparedStatement statement = - connection.prepareStatement( - "select column_name from information_schema.columns" - + " where table_schema = 'public' and table_name = ?" - + " order by ordinal_position")) { - statement.setString(1, table); - try (ResultSet result = statement.executeQuery()) { - java.util.ArrayList columns = new java.util.ArrayList<>(); - while (result.next()) { - columns.add(result.getString(1)); - } - return List.copyOf(columns); + private static List columns(String table) throws SQLException { + return strings( + "select column_name from information_schema.columns" + + " where table_schema = 'public' and table_name = ? order by ordinal_position", + table); + } + + /** The first column of every row, in order. */ + private static List strings(String sql, String... parameters) throws SQLException { + try (Connection connection = connection(); + PreparedStatement statement = prepare(connection, sql, parameters); + ResultSet result = statement.executeQuery()) { + List values = new ArrayList<>(); + while (result.next()) { + values.add(result.getString(1)); } + return values; } } - private static List foreignKeys(Connection connection, String table) throws Exception { - try (PreparedStatement statement = - connection.prepareStatement( - """ - select constraint_name - from information_schema.table_constraints - where table_schema = 'public' - and table_name = ? - and constraint_type = 'FOREIGN KEY' - """)) { - statement.setString(1, table); - try (ResultSet result = statement.executeQuery()) { - java.util.ArrayList constraints = new java.util.ArrayList<>(); - while (result.next()) { - constraints.add(result.getString(1)); - } - return List.copyOf(constraints); + /** Every column of the one row {@code sql} selects; SQL {@code NULL} stays {@code null}. */ + private static List row(String sql, String... parameters) throws SQLException { + try (Connection connection = connection(); + PreparedStatement statement = prepare(connection, sql, parameters); + ResultSet result = statement.executeQuery()) { + assertThat(result.next()).as("a row for: %s", sql).isTrue(); + List values = new ArrayList<>(); + for (int column = 1; column <= result.getMetaData().getColumnCount(); column++) { + values.add(result.getString(column)); } + return values; } } - private static void oldBinaryInsert(Connection connection, String title) throws Exception { - try (PreparedStatement statement = - connection.prepareStatement( - """ - insert into poster ( - id, title, caption, image_key, status, version, - created_at, updated_at, created_by, updated_by - ) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - """)) { - statement.setObject(1, java.util.UUID.randomUUID()); + private static PreparedStatement prepare(Connection connection, String sql, String... parameters) + throws SQLException { + PreparedStatement statement = connection.prepareStatement(sql); + for (int index = 0; index < parameters.length; index++) { + statement.setString(index + 1, parameters[index]); + } + return statement; + } + + /** Fails unless exactly one row changes, so a later read cannot pass on an untouched table. */ + private static void execute(String sql) throws SQLException { + try (Connection connection = connection(); + PreparedStatement statement = connection.prepareStatement(sql)) { + assertThat(statement.executeUpdate()).isEqualTo(1); + } + } + + /** Inserts a poster the way the pre-V8 binary did: legacy {@code image_key}, no reference. */ + private static void oldBinaryInsert(String title) throws SQLException { + try (Connection connection = connection(); + PreparedStatement statement = + connection.prepareStatement( + """ + insert into poster ( + id, title, caption, image_key, status, version, + created_at, updated_at, created_by, updated_by + ) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + """)) { + statement.setObject(1, UUID.randomUUID()); statement.setString(2, title); statement.setString(3, "legacy"); statement.setString(4, "posters/legacy/image"); statement.setString(5, "DRAFT"); statement.setLong(6, 0); - statement.setObject(7, OffsetDateTime.parse("2026-07-29T00:00:00Z")); - statement.setObject(8, OffsetDateTime.parse("2026-07-29T00:00:00Z")); + statement.setObject(7, NOW); + statement.setObject(8, NOW); statement.setString(9, "old-binary"); statement.setString(10, "old-binary"); assertThat(statement.executeUpdate()).isEqualTo(1); } } - - private static String scalar(Connection connection, String sql) throws Exception { - try (PreparedStatement statement = connection.prepareStatement(sql); - ResultSet result = statement.executeQuery()) { - assertThat(result.next()).isTrue(); - return result.getString(1); - } - } } diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/SamplePortfolioApplication.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/SamplePortfolioApplication.java index d18bb5a0..066e0bde 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/SamplePortfolioApplication.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/SamplePortfolioApplication.java @@ -2,7 +2,7 @@ package dev.caskeleton.sample.portfolio; import dev.caskeleton.adapter.inbound.web.auth.SecurityConfig; import dev.caskeleton.adapter.inbound.web.authz.MethodSecurityConfig; -import dev.caskeleton.adapter.outbound.persistence.postgresql.PostgreSqlPersistenceConfig; +import dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebAdapterAutoConfiguration; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.context.properties.ConfigurationPropertiesScan; @@ -11,34 +11,54 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.FilterType; /** - * Standalone composition root for the WorkLog sample/reference application. Scans all {@code - * dev.caskeleton} sub-packages so production-module components are auto-discovered; - * composition-root beans that live only in {@code app-bootstrap} are provided by the sample-local - * {@code bootstrap.*} package. Disposable: deleting the {@code sample-portfolio} module removes it - * without affecting production. + * Standalone composition root for the WorkLog sample/reference application. Disposable: deleting + * the {@code sample-portfolio} module removes it without affecting production. + * + *

    Relational persistence is selected the way any application selects a capability: the build + * depends on {@code adapter:outbound:persistence-jpa}, and the module's own auto-configuration + * assembles it. The scan therefore names the sample and the modules this lean app still wires by + * scanning — web, identifier, object storage and the core contracts — and never the persistence + * package, so JPA cannot arrive twice or without its startup policy. * *

    See README for the wiring rationale: why {@code @Configuration} is used instead of - * {@code @SpringBootApplication}, why the two component-scan exclusions exist, and the - * lean-bootstrap omissions a full clone would add. + * {@code @SpringBootApplication}, why the two security exclusions exist, and the lean-bootstrap + * omissions a full clone would add. */ @Configuration -@EnableAutoConfiguration +// The web leaf's own root would bring the production security back; this app scans that leaf +// itself instead, minus the two security configurations below. +@EnableAutoConfiguration(exclude = WebAdapterAutoConfiguration.class) @ComponentScan( - basePackages = "dev.caskeleton", + basePackages = { + "dev.caskeleton.sample", + "dev.caskeleton.adapter.inbound.web", + "dev.caskeleton.adapter.outbound.identifier", + "dev.caskeleton.adapter.outbound.objectstorage", + "dev.caskeleton.application", + "dev.caskeleton.domain", + "dev.caskeleton.shared" + }, excludeFilters = { - // Replaced by SamplePostgreSqlPersistenceConfig to break a Flyway/EntityManager - // init cycle (see README). + // The standalone sample is a public demo app: URL access should not require a configured + // IdP or method-security principal. Production modules keep these guards. @ComponentScan.Filter( type = FilterType.ASSIGNABLE_TYPE, classes = { - PostgreSqlPersistenceConfig.class, - // The standalone sample is a public demo app: URL access should not require a - // configured IdP or method-security principal. Production modules keep these guards. SecurityConfig.class, - MethodSecurityConfig.class + MethodSecurityConfig.class, + WebAdapterAutoConfiguration.class }) }) -@ConfigurationPropertiesScan(basePackages = "dev.caskeleton") +@ConfigurationPropertiesScan( + basePackages = { + "dev.caskeleton.sample", + "dev.caskeleton.adapter.inbound.web", + "dev.caskeleton.adapter.outbound.identifier", + "dev.caskeleton.adapter.outbound.objectstorage", + "dev.caskeleton.application", + "dev.caskeleton.domain", + "dev.caskeleton.shared" + }) public class SamplePortfolioApplication { public static void main(String[] args) { diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/command/AdoptLegacyPosterImageCommand.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/command/AdoptLegacyPosterImageCommand.java deleted file mode 100644 index 44992523..00000000 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/command/AdoptLegacyPosterImageCommand.java +++ /dev/null @@ -1,52 +0,0 @@ -package dev.caskeleton.sample.portfolio.application.command; - -import dev.caskeleton.application.command.Command; -import dev.caskeleton.application.storage.migration.LegacyObjectAdoptionRequest; -import dev.caskeleton.sample.portfolio.domain.poster.PosterId; -import java.util.Arrays; - -/** Explicit administrative report/apply command; never exposed through a normal endpoint. */ -// The adoption command remains active until data/API migration is complete. -@SuppressWarnings("deprecation") -public final class AdoptLegacyPosterImageCommand implements Command { - - private final PosterId posterId; - private final long expectedPosterVersion; - private final LegacyObjectAdoptionRequest request; - private final byte[] canonicalApprovalDocument; - - public AdoptLegacyPosterImageCommand( - PosterId posterId, - long expectedPosterVersion, - LegacyObjectAdoptionRequest request, - byte[] canonicalApprovalDocument) { - if (posterId == null || expectedPosterVersion < 0 || request == null) { - throw new IllegalArgumentException("legacy Poster image adoption command is invalid"); - } - this.posterId = posterId; - this.expectedPosterVersion = expectedPosterVersion; - this.request = request; - this.canonicalApprovalDocument = - canonicalApprovalDocument == null - ? null - : Arrays.copyOf(canonicalApprovalDocument, canonicalApprovalDocument.length); - } - - public PosterId posterId() { - return posterId; - } - - public long expectedPosterVersion() { - return expectedPosterVersion; - } - - public LegacyObjectAdoptionRequest request() { - return request; - } - - public byte[] canonicalApprovalDocument() { - return canonicalApprovalDocument == null - ? null - : Arrays.copyOf(canonicalApprovalDocument, canonicalApprovalDocument.length); - } -} diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/poster/PublishPosterImageUseCase.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/poster/PublishPosterImageUseCase.java index a65e3f73..e451474f 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/poster/PublishPosterImageUseCase.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/poster/PublishPosterImageUseCase.java @@ -3,7 +3,9 @@ package dev.caskeleton.sample.portfolio.application.poster; import dev.caskeleton.application.capability.Idempotency; import dev.caskeleton.application.capability.RepositoryAccess; import dev.caskeleton.application.capability.UseCaseCapability; +import dev.caskeleton.application.idempotency.IdempotencyClaimAttempt; import dev.caskeleton.application.idempotency.IdempotencyExecutor; +import dev.caskeleton.application.idempotency.IdempotentAction; import dev.caskeleton.application.idempotency.RequestFingerprint; import dev.caskeleton.application.objectstorage.identity.ObjectDestinationId; import dev.caskeleton.application.objectstorage.identity.ObjectOperationEpoch; @@ -18,6 +20,7 @@ import dev.caskeleton.application.objectstorage.request.ObjectHandoffClaimReques import dev.caskeleton.application.objectstorage.request.ObjectStageRequest; import dev.caskeleton.application.objectstorage.request.ObjectVerifyRequest; import dev.caskeleton.application.security.RequiresPermission; +import dev.caskeleton.application.transaction.OperationId; import dev.caskeleton.application.transaction.TransactionMode; import dev.caskeleton.application.transaction.TransactionPort; import dev.caskeleton.application.usecase.CommandUseCase; @@ -40,6 +43,7 @@ import java.time.Clock; import java.time.Duration; import java.util.EnumSet; import java.util.HexFormat; +import java.util.UUID; /** TX1 reservation followed by request-bound staging and a fenced TX2 PENDING handoff. */ @RequiresPermission("poster:write") @@ -112,15 +116,20 @@ public class PublishPosterImageUseCase command.mediaType(), command.contentIdentity()); PosterImageSanitizedIdempotencyContextFactory.SanitizedContext sanitized = - sanitizedContexts.create( - command.tenant(), command.principal(), command.idempotencyKey(), fingerprint); + sanitizedContexts.create(command.tenant(), command.principal(), command.idempotencyKey()); + IdempotencyClaimAttempt attempt = + idempotency.newAttempt(new OperationId(UUID.randomUUID().toString())); PosterImagePublicationReservation reservation = transactions.inWrite( () -> idempotency.execute( - sanitized.generic(), - () -> reserve(command, fingerprint, sanitized), + sanitized.scope(), + fingerprint, + attempt, + () -> + new IdempotentAction.Outcome.Success<>( + reserve(command, fingerprint, sanitized)), RESERVATION_CODEC)); PosterImageUploadIntent intent = diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/poster/migration/AdoptLegacyPosterImageUseCase.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/poster/migration/AdoptLegacyPosterImageUseCase.java deleted file mode 100644 index d037e07e..00000000 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/poster/migration/AdoptLegacyPosterImageUseCase.java +++ /dev/null @@ -1,101 +0,0 @@ -package dev.caskeleton.sample.portfolio.application.poster.migration; - -import dev.caskeleton.application.capability.Idempotency; -import dev.caskeleton.application.capability.RepositoryAccess; -import dev.caskeleton.application.capability.UseCaseCapability; -import dev.caskeleton.application.security.RequiresPermission; -import dev.caskeleton.application.storage.migration.LegacyObjectAdoptionApproval; -import dev.caskeleton.application.storage.migration.LegacyObjectAdoptionApprovalVerifierPort; -import dev.caskeleton.application.storage.migration.LegacyObjectAdoptionPort; -import dev.caskeleton.application.storage.migration.LegacyObjectAdoptionRequest; -import dev.caskeleton.application.transaction.TransactionMode; -import dev.caskeleton.application.transaction.TransactionPort; -import dev.caskeleton.application.usecase.CommandUseCase; -import dev.caskeleton.sample.portfolio.application.command.AdoptLegacyPosterImageCommand; -import dev.caskeleton.sample.portfolio.application.exception.PosterNotFoundException; -import dev.caskeleton.sample.portfolio.application.posterimage.LegacyPosterImageAdoptionAuthorizationPolicy; -import dev.caskeleton.sample.portfolio.application.posterimage.LegacyPosterImageAdoptionExecutionIdentityPort; -import dev.caskeleton.sample.portfolio.application.posterimage.LegacyPosterImageAdoptionResult; -import dev.caskeleton.sample.portfolio.domain.poster.Poster; -import dev.caskeleton.sample.portfolio.domain.poster.PosterImageReference; -import dev.caskeleton.sample.portfolio.domain.poster.PosterRepository; - -/** Isolated administrative legacy exception; performs no remote I/O inside a DB transaction. */ -@Deprecated -// The adoption implementation remains active until data/API migration is complete. -@RequiresPermission("poster:image-adopt") -@UseCaseCapability( - transactionMode = TransactionMode.WRITE, - idempotency = Idempotency.KEYED, - repositoryAccess = RepositoryAccess.WRITE_REPOSITORY, - externalOutboundAllowed = true) -public class AdoptLegacyPosterImageUseCase - implements CommandUseCase { - - private final LegacyObjectAdoptionPort adoptions; - private final LegacyObjectAdoptionApprovalVerifierPort approvals; - private final LegacyPosterImageAdoptionExecutionIdentityPort identity; - private final LegacyPosterImageAdoptionAuthorizationPolicy authorization; - private final PosterRepository posters; - private final TransactionPort transactions; - - public AdoptLegacyPosterImageUseCase( - LegacyObjectAdoptionPort adoptions, - LegacyObjectAdoptionApprovalVerifierPort approvals, - LegacyPosterImageAdoptionExecutionIdentityPort identity, - LegacyPosterImageAdoptionAuthorizationPolicy authorization, - PosterRepository posters, - TransactionPort transactions) { - this.adoptions = adoptions; - this.approvals = approvals; - this.identity = identity; - this.authorization = authorization; - this.posters = posters; - this.transactions = transactions; - } - - @Override - public LegacyPosterImageAdoptionResult handle(AdoptLegacyPosterImageCommand command) { - authorization.authorize(identity.current()); - LegacyObjectAdoptionRequest request = authorizeApply(command); - var receipt = adoptions.adopt(request); - if (request.mode() == LegacyObjectAdoptionRequest.Mode.REPORT_ONLY) { - return new LegacyPosterImageAdoptionResult(receipt, false); - } - transactions.inWrite( - () -> { - Poster poster = - posters - .findById(command.posterId()) - .orElseThrow(() -> new PosterNotFoundException(command.posterId())); - if (poster.version() == null || poster.version() != command.expectedPosterVersion()) { - throw new IllegalStateException("Poster changed during legacy image adoption"); - } - poster.attachPublishedImage( - PosterImageReference.of(receipt.adoptedReference().canonicalText())); - posters.save(poster); - return null; - }); - return new LegacyPosterImageAdoptionResult(receipt, true); - } - - private LegacyObjectAdoptionRequest authorizeApply(AdoptLegacyPosterImageCommand command) { - LegacyObjectAdoptionRequest request = command.request(); - if (request.mode() == LegacyObjectAdoptionRequest.Mode.REPORT_ONLY) { - return request; - } - byte[] document = command.canonicalApprovalDocument(); - if (document == null) { - throw new SecurityException("legacy adoption APPLY approval is required"); - } - LegacyObjectAdoptionApproval approval = approvals.verify(document, request); - return new LegacyObjectAdoptionRequest( - request.locator(), - request.publicationRequest(), - request.manifestSha256(), - request.legacyNamespaceDigest(), - request.targetNamespaceDigest(), - request.mode(), - approval); - } -} diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/posterimage/LegacyPosterImageAdoptionAuthorizationPolicy.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/posterimage/LegacyPosterImageAdoptionAuthorizationPolicy.java deleted file mode 100644 index 3bc22e5c..00000000 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/posterimage/LegacyPosterImageAdoptionAuthorizationPolicy.java +++ /dev/null @@ -1,24 +0,0 @@ -package dev.caskeleton.sample.portfolio.application.posterimage; - -/** Exact maintenance identity/capability policy checked before reading approval or legacy data. */ -public final class LegacyPosterImageAdoptionAuthorizationPolicy { - - public static final String REQUIRED_CAPABILITY = "poster:image-adopt"; - - private final String expectedIdentityDigest; - - public LegacyPosterImageAdoptionAuthorizationPolicy(String expectedIdentityDigest) { - if (expectedIdentityDigest == null || !expectedIdentityDigest.matches("[0-9a-f]{64}")) { - throw new IllegalArgumentException("legacy adoption expected identity is invalid"); - } - this.expectedIdentityDigest = expectedIdentityDigest; - } - - public void authorize(LegacyPosterImageAdoptionExecutionIdentity identity) { - if (identity == null - || !expectedIdentityDigest.equals(identity.identityDigest()) - || !identity.capabilities().contains(REQUIRED_CAPABILITY)) { - throw new SecurityException("legacy Poster image adoption is not authorized"); - } - } -} diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/posterimage/LegacyPosterImageAdoptionExecutionIdentity.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/posterimage/LegacyPosterImageAdoptionExecutionIdentity.java deleted file mode 100644 index e8b2627a..00000000 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/posterimage/LegacyPosterImageAdoptionExecutionIdentity.java +++ /dev/null @@ -1,18 +0,0 @@ -package dev.caskeleton.sample.portfolio.application.posterimage; - -import java.util.Set; - -/** Explicit non-web maintenance identity for administrative legacy adoption. */ -public record LegacyPosterImageAdoptionExecutionIdentity( - String identityDigest, Set capabilities) { - - public LegacyPosterImageAdoptionExecutionIdentity { - if (identityDigest == null - || !identityDigest.matches("[0-9a-f]{64}") - || capabilities == null - || capabilities.contains(null)) { - throw new IllegalArgumentException("legacy adoption execution identity is invalid"); - } - capabilities = Set.copyOf(capabilities); - } -} diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/posterimage/LegacyPosterImageAdoptionExecutionIdentityPort.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/posterimage/LegacyPosterImageAdoptionExecutionIdentityPort.java deleted file mode 100644 index 89c58d9a..00000000 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/posterimage/LegacyPosterImageAdoptionExecutionIdentityPort.java +++ /dev/null @@ -1,7 +0,0 @@ -package dev.caskeleton.sample.portfolio.application.posterimage; - -/** Supplies only the isolated maintenance workload identity, never a web security context. */ -public interface LegacyPosterImageAdoptionExecutionIdentityPort { - - LegacyPosterImageAdoptionExecutionIdentity current(); -} diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/posterimage/LegacyPosterImageAdoptionResult.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/posterimage/LegacyPosterImageAdoptionResult.java deleted file mode 100644 index 5a749514..00000000 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/posterimage/LegacyPosterImageAdoptionResult.java +++ /dev/null @@ -1,16 +0,0 @@ -package dev.caskeleton.sample.portfolio.application.posterimage; - -import dev.caskeleton.application.storage.migration.LegacyObjectAdoptionReceipt; - -/** Administrative adoption result; the underlying receipt is locator-free. */ -// The adoption result remains active until data/API migration is complete. -@SuppressWarnings("deprecation") -public record LegacyPosterImageAdoptionResult( - LegacyObjectAdoptionReceipt receipt, boolean attachedToPoster) { - - public LegacyPosterImageAdoptionResult { - if (receipt == null) { - throw new IllegalArgumentException("legacy Poster image adoption result is invalid"); - } - } -} diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/posterimage/PosterImageSanitizedIdempotencyContextFactory.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/posterimage/PosterImageSanitizedIdempotencyContextFactory.java index b9c58652..e74006f8 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/posterimage/PosterImageSanitizedIdempotencyContextFactory.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/posterimage/PosterImageSanitizedIdempotencyContextFactory.java @@ -1,8 +1,9 @@ package dev.caskeleton.sample.portfolio.application.posterimage; -import dev.caskeleton.application.idempotency.IdempotencyContext; -import dev.caskeleton.application.idempotency.IdempotencyScope; -import dev.caskeleton.application.idempotency.RequestFingerprint; +import dev.caskeleton.application.idempotency.IdempotencyScopeDigest; +import java.util.Base64; +import java.util.HexFormat; +import java.util.List; import java.util.Objects; /** Replaces every raw caller dimension before the generic idempotency store sees it. */ @@ -10,6 +11,15 @@ public final class PosterImageSanitizedIdempotencyContextFactory { public static final String RESERVATION_USE_CASE = "poster-image-publication-reservation-v1"; + /** The operation code the generic store records the reservation scope under. */ + public static final String RESERVATION_OPERATION_CODE = "POSTER_IMAGE_PUBLICATION_RESERVATION"; + + /** + * The generic store's key-digest version. The sample's key-ring label is already bound into the + * HMAC itself — a rotated key yields a different digest — so the generic version stays fixed. + */ + static final int SCOPE_DIGEST_VERSION = 1; + private final PosterImageIdempotencyScopeDigesterPort digester; public PosterImageSanitizedIdempotencyContextFactory( @@ -17,44 +27,29 @@ public final class PosterImageSanitizedIdempotencyContextFactory { this.digester = Objects.requireNonNull(digester, "digester must be non-null"); } - public SanitizedContext create( - String tenant, String principal, String idempotencyKey, RequestFingerprint fingerprint) { + public SanitizedContext create(String tenant, String principal, String idempotencyKey) { PosterImageIdempotencyScopeDigest full = digester.digest(tenant, principal, RESERVATION_USE_CASE, idempotencyKey); - PosterImageIdempotencyScopeDigest principalAlias = - digester.digest( - tenant, principal, "poster-image-principal-alias-v1", "principal-dimension"); - String tenantAlias = - tenant == null - ? null - : encoded( - digester.digest( - tenant, - "tenant-dimension", - "poster-image-tenant-alias-v1", - "tenant-dimension")); - IdempotencyScope sanitized = - IdempotencyScope.of( - tenantAlias, encoded(principalAlias), encoded(full), RESERVATION_USE_CASE); + IdempotencyScopeDigest scope = + new IdempotencyScopeDigest( + HexFormat.of().formatHex(Base64.getUrlDecoder().decode(full.base64UrlDigest())), + SCOPE_DIGEST_VERSION, + RESERVATION_OPERATION_CODE); return new SanitizedContext( - IdempotencyContext.of(sanitized, fingerprint), + scope, full, digester.retainedDigests(tenant, principal, RESERVATION_USE_CASE, idempotencyKey)); } - private static String encoded(PosterImageIdempotencyScopeDigest digest) { - return digest.keyVersion() + "." + digest.base64UrlDigest(); - } - public record SanitizedContext( - IdempotencyContext generic, + IdempotencyScopeDigest scope, PosterImageIdempotencyScopeDigest activeScope, - java.util.List retainedScopes) { + List retainedScopes) { public SanitizedContext { - Objects.requireNonNull(generic, "generic must be non-null"); + Objects.requireNonNull(scope, "scope must be non-null"); Objects.requireNonNull(activeScope, "activeScope must be non-null"); - retainedScopes = java.util.List.copyOf(retainedScopes); + retainedScopes = List.copyOf(retainedScopes); if (retainedScopes.isEmpty()) { throw new IllegalArgumentException("retained scopes must be non-empty"); } diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/idempotency/SampleIdempotencyConfig.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/idempotency/SampleIdempotencyConfig.java index 869990d9..647baabc 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/idempotency/SampleIdempotencyConfig.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/idempotency/SampleIdempotencyConfig.java @@ -3,29 +3,45 @@ package dev.caskeleton.sample.portfolio.bootstrap.idempotency; import dev.caskeleton.application.idempotency.IdempotencyExecutor; import dev.caskeleton.application.idempotency.IdempotencyStorePort; import java.time.Clock; -import org.springframework.boot.context.properties.EnableConfigurationProperties; +import java.time.Duration; +import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; +import org.springframework.boot.context.properties.bind.Binder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; import org.springframework.scheduling.annotation.EnableScheduling; /** - * Sample-local copy of {@code app-bootstrap}'s {@code IdempotencyConfig}: supplies the {@code - * Clock}, assembles the {@code IdempotencyExecutor}, and enables scheduling for the idempotency - * reaper. Disposable. See README. + * Sample-local stand-in for {@code app-bootstrap}'s {@code IdempotencyProviderSelectionConfig}. The + * sample is its own composition root and must not depend on {@code app-bootstrap}, so it builds the + * one executor itself, over the {@link IdempotencyStorePort} the persistence-jpa provider + * contributes, from the same {@code ca-skeleton.capabilities.idempotency} keys and defaults. Also + * supplies the {@code Clock} and turns on scheduling for the sample's jobs. Disposable. See README. */ @Configuration @EnableScheduling -@EnableConfigurationProperties(SampleIdempotencySettings.class) public class SampleIdempotencyConfig { + private static final String PREFIX = "ca-skeleton.capabilities.idempotency."; + @Bean public Clock systemClock() { return Clock.systemUTC(); } @Bean + @ConditionalOnExpression( + "!'${ca-skeleton.capabilities.idempotency.provider:disabled}'.trim()" + + ".equalsIgnoreCase('disabled')") public IdempotencyExecutor idempotencyExecutor( - IdempotencyStorePort store, Clock clock, SampleIdempotencySettings properties) { - return new IdempotencyExecutor(store, clock, properties.ttl()); + IdempotencyStorePort store, Environment environment) { + Binder binder = Binder.get(environment); + return new IdempotencyExecutor( + store, + binder.bind(PREFIX + "processing-lease", Duration.class).orElse(Duration.ofSeconds(30)), + binder.bind(PREFIX + "replay-ttl", Duration.class).orElse(Duration.ofHours(24)), + binder.bind(PREFIX + "failure-retention", Duration.class).orElse(Duration.ofHours(24)), + binder.bind(PREFIX + "response-codec-id", String.class).orElse("json-v2"), + binder.bind(PREFIX + "policy-revision", Integer.class).orElse(2)); } } diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/idempotency/SampleIdempotencySettings.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/idempotency/SampleIdempotencySettings.java deleted file mode 100644 index 08e215fc..00000000 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/idempotency/SampleIdempotencySettings.java +++ /dev/null @@ -1,34 +0,0 @@ -package dev.caskeleton.sample.portfolio.bootstrap.idempotency; - -import java.time.Duration; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.validation.annotation.Validated; - -/** - * Sample-local copy of {@code app-bootstrap}'s {@code IdempotencySettings}, bound from {@code - * ca-skeleton.idempotency.*}. TTL must be positive and ≤ 72h; reaper interval defaults to 10m. - * Disposable. See README. - */ -@Validated -@ConfigurationProperties(prefix = "ca-skeleton.idempotency") -public record SampleIdempotencySettings(Duration ttl, Duration reaperInterval) { - - private static final Duration MAX_TTL = Duration.ofDays(3); - - public SampleIdempotencySettings { - if (ttl == null) { - ttl = Duration.ofHours(24); - } - if (ttl.isZero() || ttl.isNegative()) { - throw new IllegalArgumentException( - "APP_IDEMPOTENCY_TTL (ca-skeleton.idempotency.ttl) must be positive, was " + ttl); - } - if (ttl.compareTo(MAX_TTL) > 0) { - throw new IllegalArgumentException( - "APP_IDEMPOTENCY_TTL (ca-skeleton.idempotency.ttl) must be <= 72h (D6), was " + ttl); - } - if (reaperInterval == null || reaperInterval.isZero() || reaperInterval.isNegative()) { - reaperInterval = Duration.ofMinutes(10); - } - } -} diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/persistence/SamplePostgreSqlPersistenceConfig.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/persistence/SamplePostgreSqlPersistenceConfig.java index 88323d96..361a602d 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/persistence/SamplePostgreSqlPersistenceConfig.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/persistence/SamplePostgreSqlPersistenceConfig.java @@ -1,44 +1,23 @@ package dev.caskeleton.sample.portfolio.bootstrap.persistence; -import dev.caskeleton.adapter.outbound.persistence.config.PersistenceJpaConfig; -import dev.caskeleton.adapter.outbound.persistence.failure.SqlStateErrorMapping; -import dev.caskeleton.adapter.outbound.persistence.idempotency.IdempotencyClaimRepository; -import dev.caskeleton.adapter.outbound.persistence.outbox.OutboxClaimRepository; -import dev.caskeleton.adapter.outbound.persistence.postgresql.PostgreSqlIdempotencyClaimRepository; -import dev.caskeleton.adapter.outbound.persistence.postgresql.PostgreSqlLocalTimeoutConfigurer; -import dev.caskeleton.adapter.outbound.persistence.postgresql.PostgreSqlOutboxClaimRepository; -import dev.caskeleton.adapter.outbound.persistence.postgresql.PostgreSqlSqlStateErrorMapping; -import dev.caskeleton.adapter.outbound.persistence.transaction.TransactionLocalTimeoutConfigurer; -import jakarta.persistence.EntityManager; import org.flywaydb.core.Flyway; import org.flywaydb.core.api.MigrationVersion; -import org.springframework.boot.flyway.autoconfigure.FlywayConfigurationCustomizer; import org.springframework.boot.flyway.autoconfigure.FlywayMigrationStrategy; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.jdbc.core.JdbcOperations; /** - * Sample-local replacement for {@code PostgreSqlPersistenceConfig}. Exists to break a - * Flyway/EntityManager initialization cycle and to keep sample schema migrations in a separate - * Flyway history from the production persistence timeline. Disposable. See README. + * Keeps the sample schema migrations in a separate Flyway history from the production persistence + * timeline. Disposable. See README. + * + *

    Everything else relational — the vendor beans, the entity and repository scans, the production + * migration location and the startup guards — arrives with {@code adapter:outbound:persistence-jpa} + * through its own auto-configuration. This class only supplies the application's migration + * strategy, which the module's default runner steps aside for. */ @Configuration(proxyBeanMethods = false) -@Import(PersistenceJpaConfig.class) public class SamplePostgreSqlPersistenceConfig { - /** - * Keeps Boot's primary Flyway on the production persistence timeline only. - * - *

    The sample migrations run through {@link #sampleMigrationStrategy()} with their own schema - * history table, so a sample V2/V7/V8 no longer reserves those versions for production. - */ - @Bean - public static FlywayConfigurationCustomizer postgreSqlFlywayLocationCustomizer() { - return configuration -> configuration.locations("classpath:db/migration/postgresql"); - } - /** * Applies the disposable sample schema as a second Flyway stream after production migrations. * @@ -67,25 +46,4 @@ public class SamplePostgreSqlPersistenceConfig { .baselineVersion(MigrationVersion.fromVersion("0")) .cleanDisabled(true); } - - @Bean - public OutboxClaimRepository outboxClaimRepository(EntityManager entityManager) { - return new PostgreSqlOutboxClaimRepository(entityManager); - } - - @Bean - public IdempotencyClaimRepository idempotencyClaimRepository(EntityManager entityManager) { - return new PostgreSqlIdempotencyClaimRepository(entityManager); - } - - @Bean - public SqlStateErrorMapping postgreSqlSqlStateErrorMapping() { - return new PostgreSqlSqlStateErrorMapping(); - } - - @Bean - public TransactionLocalTimeoutConfigurer transactionLocalTimeoutConfigurer( - JdbcOperations jdbcOperations) { - return new PostgreSqlLocalTimeoutConfigurer(jdbcOperations); - } } diff --git a/src/sample-portfolio/src/main/resources/application.yml b/src/sample-portfolio/src/main/resources/application.yml index eb6559e5..8f263d9b 100644 --- a/src/sample-portfolio/src/main/resources/application.yml +++ b/src/sample-portfolio/src/main/resources/application.yml @@ -111,6 +111,10 @@ management: include: readinessState shutdown: access: none + # The sample permits every request on the management port; a writable loggers endpoint would let + # anyone switch a logger to TRACE (data leak) or OFF. + loggers: + access: read-only info: build: enabled: true @@ -168,13 +172,11 @@ ca-skeleton: time-to-live: ${APP_CACHE_REDIS_L1_TTL:30s} generation-recheck-interval: ${APP_CACHE_REDIS_L1_GENERATION_RECHECK_INTERVAL:5s} invalidation-queue-capacity: ${APP_CACHE_REDIS_L1_INVALIDATION_QUEUE_CAPACITY:1024} - # SampleIdempotencyConfig assembles an IdempotencyExecutor unconditionally, and the only - # IdempotencyStorePort this composition can produce is the relational one, which is - # @ConditionalOnProperty on this key. Leaving it unset built an executor over a port nobody - # supplied and the context failed on a missing bean. The sample ships persistence-jpa and runs - # the production migration timeline, which owns idempotency_record. + # The only IdempotencyStorePort this composition can produce is persistence-jpa's PostgreSQL + # store, which applies its own migration stream when selected. SampleIdempotencyConfig builds + # the executor over it; `disabled` builds neither. idempotency: - provider: ${APP_IDEMPOTENCY_PROVIDER:jdbc} + provider: ${APP_IDEMPOTENCY_PROVIDER:postgresql} bootstrap: app-name: ${APP_NAME:sample-portfolio} runtime: @@ -190,9 +192,6 @@ ca-skeleton: hash-key-version: ${APP_RATE_LIMIT_HASH_KEY_VERSION:1} caller-deadline-budget: 2s client-ip-mode: ${APP_RATE_LIMIT_CLIENT_IP_MODE:remote-addr-only} - idempotency: - ttl: ${APP_IDEMPOTENCY_TTL:24h} - reaper-interval: 10m security: issuer-uri: ${APP_SECURITY_JWT_ISSUER:http://localhost:8080/auth/realms/sample} audience: ${APP_SECURITY_JWT_AUDIENCE:} diff --git a/src/sample-portfolio/src/systemTest/java/dev/caskeleton/sample/portfolio/SampleApplicationContextTest.java b/src/sample-portfolio/src/systemTest/java/dev/caskeleton/sample/portfolio/SampleApplicationContextTest.java index 9c9e5d11..32966283 100644 --- a/src/sample-portfolio/src/systemTest/java/dev/caskeleton/sample/portfolio/SampleApplicationContextTest.java +++ b/src/sample-portfolio/src/systemTest/java/dev/caskeleton/sample/portfolio/SampleApplicationContextTest.java @@ -1,8 +1,13 @@ package dev.caskeleton.sample.portfolio; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.entry; +import dev.caskeleton.sample.portfolio.adapter.outbound.persistence.repository.WorkLogRepositoryAdapter; +import dev.caskeleton.sample.portfolio.bootstrap.persistence.SamplePostgreSqlPersistenceConfig; +import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogRepository; import dev.caskeleton.sample.portfolio.testinfra.PostgreSqlTestContainer; +import java.util.Map; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @@ -42,24 +47,30 @@ class SampleApplicationContextTest { @Autowired JdbcTemplate jdbcTemplate; @Test - void contextLoads() { - assertThat(context).isNotNull(); + void standaloneContextBindsTheWorkLogRepositoryToThePostgresAdapter() { + // when + WorkLogRepository repository = context.getBean(WorkLogRepository.class); + + // then + assertThat(repository).isInstanceOf(WorkLogRepositoryAdapter.class); } /** * Asserts that the work_log table (V2 — {@code db/sample-migration/V2__work_log.sql}) was applied * by Flyway on standalone boot. Without this assertion the bug where {@link - * dev.caskeleton.sample.portfolio.bootstrap.persistence.SamplePostgreSqlPersistenceConfig} - * overwrites the configured locations (dropping {@code db/sample-migration}) would be invisible - * to this test. + * SamplePostgreSqlPersistenceConfig} overwrites the configured locations (dropping {@code + * db/sample-migration}) would be invisible to this test. */ @Test void workLogTableIsMigrated() { + // when Integer count = jdbcTemplate.queryForObject( "SELECT count(*) FROM information_schema.tables " + "WHERE table_schema = 'public' AND table_name = 'work_log'", Integer.class); + + // then assertThat(count) .as("work_log table must exist — V2 sample-migration must be applied") .isEqualTo(1); @@ -68,21 +79,18 @@ class SampleApplicationContextTest { /** The sample V2 belongs only to the sample schema-history stream. */ @Test void sampleMigrationHistoryOwnsV2WithoutReservingProductionV2() { - Integer sampleApplied = - jdbcTemplate.queryForObject( - "SELECT count(*) FROM flyway_sample_schema_history " - + "WHERE version = '2' AND success = true", - Integer.class); - Integer productionV2 = - jdbcTemplate.queryForObject( - "SELECT count(*) FROM flyway_schema_history WHERE version = '2' AND success = true", - Integer.class); + // when + Map appliedV2 = + jdbcTemplate.queryForMap( + "SELECT" + + " (SELECT count(*) FROM flyway_sample_schema_history" + + " WHERE version = '2' AND success = true) AS sample," + + " (SELECT count(*) FROM flyway_schema_history" + + " WHERE version = '2' AND success = true) AS production"); - assertThat(sampleApplied) - .as("sample history must record its own V2 work_log migration") - .isEqualTo(1); - assertThat(productionV2) - .as("sample V2 must not reserve V2 in the production migration timeline") - .isZero(); + // then + assertThat(appliedV2) + .as("the sample records its own V2 once and reserves no V2 in the production timeline") + .containsExactly(entry("sample", 1L), entry("production", 0L)); } } diff --git a/src/sample-portfolio/src/systemTest/resources/application-test.yml b/src/sample-portfolio/src/systemTest/resources/application-test.yml index d78587a9..084041a4 100644 --- a/src/sample-portfolio/src/systemTest/resources/application-test.yml +++ b/src/sample-portfolio/src/systemTest/resources/application-test.yml @@ -38,7 +38,10 @@ spring: baseline-on-migrate: false out-of-order: false clean-disabled: true - locations: classpath:db/migration/postgresql,classpath:db/sample-migration + # The production timeline only. The sample stream (db/sample-migration) is applied by + # SamplePostgreSqlPersistenceConfig.sampleMigrationStrategy with its own history table; listing it + # here as well would apply V2 twice now that the module's location customizer honours this key. + locations: classpath:db/migration/postgresql jpa: hibernate: ddl-auto: none @@ -103,7 +106,7 @@ logging: ca-skeleton: capabilities: idempotency: - provider: jdbc + provider: postgresql bootstrap: app-name: sample-portfolio-test runtime: @@ -118,9 +121,6 @@ ca-skeleton: limit: 100 window: 1s algorithm: fixed-window - idempotency: - ttl: 24h - reaper-interval: 10m security: issuer-uri: http://localhost:8081/realms/sample-test audience: sample-test diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/controller/OperationsControllerWireTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/controller/OperationsControllerWireTest.java index bda2f3b8..d05390c8 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/controller/OperationsControllerWireTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/controller/OperationsControllerWireTest.java @@ -1,6 +1,6 @@ package dev.caskeleton.sample.portfolio.adapter.inbound.web.controller; -import static org.mockito.Mockito.when; +import static org.hamcrest.Matchers.startsWith; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; @@ -15,12 +15,13 @@ import dev.caskeleton.sample.portfolio.adapter.inbound.web.operation.SampleOpera import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.security.autoconfigure.SecurityAutoConfiguration; +import org.springframework.boot.test.context.TestConfiguration; import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc; import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Import; -import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.ResultActions; /** * feature-api-contract-baseline D17 — LRO wire contract: {@code POST /worklogs:export} returns 202 @@ -41,26 +42,42 @@ import org.springframework.test.web.servlet.MvcResult; class OperationsControllerWireTest { @Autowired MockMvc mvc; - @MockitoBean PresentationSettings presentationSettings; + + @TestConfiguration + static class Settings { + @Bean + PresentationSettings presentationSettings() { + return new PresentationSettings(""); + } + } @Test - void exportReturns202LocationPendingThenPollReachesTerminalStatus() throws Exception { - when(presentationSettings.apiBasePath()).thenReturn(""); + void exportReturns202WithLocationAndPendingOperation() throws Exception { + // when + ResultActions result = mvc.perform(post("/worklogs:export")); - MvcResult accepted = - mvc.perform(post("/worklogs:export")) - .andExpect(status().isAccepted()) - .andExpect(header().exists("Location")) - .andExpect(jsonPath("$.success").value(true)) - .andExpect(jsonPath("$.data.operationId").isNotEmpty()) - .andExpect(jsonPath("$.data.statusUrl").isNotEmpty()) - .andExpect(jsonPath("$.data.status").value("PENDING")) - .andReturn(); + // then + result + .andExpect(status().isAccepted()) + .andExpect(header().string("Location", startsWith("/operations/"))) + .andExpect(jsonPath("$.success").value(true)) + .andExpect(jsonPath("$.data.operationId").isNotEmpty()) + .andExpect(jsonPath("$.data.statusUrl").value(startsWith("/operations/"))) + .andExpect(jsonPath("$.data.status").value("PENDING")); + } - String operationId = - JsonPath.read(accepted.getResponse().getContentAsString(), "$.data.operationId"); + @Test + void pollingAnExportedOperationReturnsTerminalSucceededStatus() throws Exception { + // given + String accepted = + mvc.perform(post("/worklogs:export")).andReturn().getResponse().getContentAsString(); + String operationId = JsonPath.read(accepted, "$.data.operationId"); - mvc.perform(get("/operations/" + operationId)) + // when + ResultActions result = mvc.perform(get("/operations/" + operationId)); + + // then + result .andExpect(status().isOk()) .andExpect(jsonPath("$.data.operationId").value(operationId)) .andExpect(jsonPath("$.data.status").value("SUCCEEDED")) diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/controller/PosterControllerWireTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/controller/PosterControllerWireTest.java index 9d5672da..66ae94bd 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/controller/PosterControllerWireTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/controller/PosterControllerWireTest.java @@ -25,6 +25,7 @@ import dev.caskeleton.sample.portfolio.application.poster.ListPostersUseCase; import dev.caskeleton.sample.portfolio.application.poster.PublishPosterUseCase; import dev.caskeleton.sample.portfolio.application.poster.UpdatePosterUseCase; import dev.caskeleton.sample.portfolio.application.poster.UploadPosterImageUseCase; +import dev.caskeleton.sample.portfolio.application.query.GetPosterQuery; import dev.caskeleton.sample.portfolio.domain.poster.Poster; import dev.caskeleton.sample.portfolio.domain.poster.PosterId; import dev.caskeleton.sample.portfolio.domain.poster.PosterInvariantException; @@ -33,6 +34,7 @@ import dev.caskeleton.sample.portfolio.domain.poster.PosterStatus; import java.net.URI; import java.util.List; import java.util.Locale; +import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.security.autoconfigure.SecurityAutoConfiguration; @@ -44,7 +46,12 @@ import org.springframework.mock.web.MockMultipartFile; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.ResultActions; +/** + * HTTP wire contract of the poster endpoints. The use cases stay {@code @MockitoBean}: each is an + * application class over repository, storage and transaction ports this slice does not wire. + */ @WebMvcTest( controllers = {PosterController.class, LegacyPosterImageController.class}, excludeAutoConfiguration = SecurityAutoConfiguration.class) @@ -78,169 +85,270 @@ class PosterControllerWireTest { @MockitoBean GetPosterUseCase getUseCase; @MockitoBean ListPostersUseCase listUseCase; - private Poster poster(String title, PosterStatus status, String imageKey) { + private static Poster poster(String title, PosterStatus status, String imageKey) { return Poster.rehydrate(PosterId.of(ID), title, "7월 한정", imageKey, status, 0L); } - // ---- list ---- + @Nested + class ListPosters { - @Test - void listIsWrappedInEnvelopeWithPageMeta() throws Exception { - when(listUseCase.handle(any())) - .thenReturn(new PosterPage(List.of(poster("여름 세일", PosterStatus.DRAFT, null)), 1)); - mvc.perform(get("/posters")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.success").value(true)) - .andExpect(jsonPath("$.data[0].id").value(ID)) - .andExpect(jsonPath("$.data[0].title").value("여름 세일")) - .andExpect(jsonPath("$.meta.page.total").value(1)); + @Test + void listIsWrappedInEnvelopeWithPageMeta() throws Exception { + // given + when(listUseCase.handle(any())) + .thenReturn(new PosterPage(List.of(poster("여름 세일", PosterStatus.DRAFT, null)), 1)); + + // when + ResultActions result = mvc.perform(get("/posters")); + + // then + result + .andExpect(status().isOk()) + .andExpect(jsonPath("$.success").value(true)) + .andExpect(jsonPath("$.data[0].id").value(ID)) + .andExpect(jsonPath("$.data[0].title").value("여름 세일")) + .andExpect(jsonPath("$.meta.page.total").value(1)); + } + + @Test + void emptyListIsDataArrayNotNullWithZeroTotal() throws Exception { + // given + when(listUseCase.handle(any())).thenReturn(new PosterPage(List.of(), 0)); + + // when + ResultActions result = mvc.perform(get("/posters")); + + // then + result + .andExpect(status().isOk()) + .andExpect(jsonPath("$.data").isArray()) + .andExpect(jsonPath("$.data.length()").value(0)) + .andExpect(jsonPath("$.meta.page.total").value(0)); + } + + @Test + void sizeOverCapIs400Validation() throws Exception { + // when + ResultActions result = mvc.perform(get("/posters").param("size", "101")); + + // then + result + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error.code").value("VALIDATION_FAILED")); + } + + @Test + void nativeSortSyntaxIsEchoedInMeta() throws Exception { + // given + when(listUseCase.handle(any())) + .thenReturn(new PosterPage(List.of(poster("a", PosterStatus.DRAFT, null)), 1)); + + // when + ResultActions result = mvc.perform(get("/posters").param("sort", "title,desc")); + + // then + result.andExpect(status().isOk()).andExpect(jsonPath("$.meta.page.sort").value("title,desc")); + } } - @Test - void emptyListIsDataArrayNotNullWithZeroTotal() throws Exception { - when(listUseCase.handle(any())).thenReturn(new PosterPage(List.of(), 0)); - mvc.perform(get("/posters")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.data").isArray()) - .andExpect(jsonPath("$.data.length()").value(0)) - .andExpect(jsonPath("$.meta.page.total").value(0)); + @Nested + class GetPoster { + + @Test + void getReturnsPoster() throws Exception { + // given + when(getUseCase.handle(any())) + .thenReturn(poster("여름 세일", PosterStatus.PUBLISHED, "posters/x/image")); + + // when + ResultActions result = mvc.perform(get("/posters/" + ID)); + + // then + result + .andExpect(status().isOk()) + .andExpect(jsonPath("$.data.id").value(ID)) + .andExpect(jsonPath("$.data.status").value("PUBLISHED")) + .andExpect(jsonPath("$.data.imageKey").value("posters/x/image")); + } + + @Test + void getMissingReturns404PosterNotFound() throws Exception { + // given + when(getUseCase.handle(any())).thenThrow(new PosterNotFoundException(PosterId.of(ID))); + + // when + ResultActions result = mvc.perform(get("/posters/" + ID)); + + // then + result + .andExpect(status().isNotFound()) + .andExpect(jsonPath("$.error.code").value("POSTER_NOT_FOUND")); + } + + @Test + void getWithMalformedIdReturns400BadParameter() throws Exception { + // when + ResultActions result = mvc.perform(get("/posters/not-a-valid-uuid")); + + // then + result + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error.code").value("BAD_PARAMETER")); + } + + @Test + void getAcceptsMixedCaseUuidPathAndNormalizes() throws Exception { + // given + // only the lower-case id is answered, so a 200 proves the path was normalized + when(getUseCase.handle(new GetPosterQuery(PosterId.of(ID)))) + .thenReturn(poster("여름 세일", PosterStatus.DRAFT, null)); + + // when + ResultActions result = mvc.perform(get("/posters/" + ID.toUpperCase(Locale.ROOT))); + + // then + result.andExpect(status().isOk()).andExpect(jsonPath("$.data.id").value(ID)); + } } - @Test - void sizeOverCapIs400Validation() throws Exception { - mvc.perform(get("/posters").param("size", "101")) - .andExpect(status().isBadRequest()) - .andExpect(jsonPath("$.error.code").value("VALIDATION_FAILED")); + @Nested + class CreatePoster { + + @Test + void createReturns201WithBody() throws Exception { + // given + when(createUseCase.handle(any())).thenReturn(poster("여름 세일", PosterStatus.DRAFT, null)); + + // when + ResultActions result = + mvc.perform( + post("/posters") + .contentType(MediaType.APPLICATION_JSON) + .content("{\"title\":\"여름 세일\",\"caption\":\"7월 한정\"}")); + + // then + result + .andExpect(status().isCreated()) + .andExpect(jsonPath("$.success").value(true)) + .andExpect(jsonPath("$.data.title").value("여름 세일")); + } + + @Test + void createWithBlankTitleFailsValidation() throws Exception { + // when + ResultActions result = + mvc.perform( + post("/posters").contentType(MediaType.APPLICATION_JSON).content("{\"title\":\"\"}")); + + // then + result + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error.code").value("VALIDATION_FAILED")); + } } - @Test - void nativeSortSyntaxIsEchoedInMeta() throws Exception { - when(listUseCase.handle(any())) - .thenReturn(new PosterPage(List.of(poster("a", PosterStatus.DRAFT, null)), 1)); - mvc.perform(get("/posters").param("sort", "title,desc")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.meta.page.sort").value("title,desc")); + @Nested + class PatchPoster { + + @Test + void patchReplacesTitle() throws Exception { + // given + when(updateUseCase.handle(any())).thenReturn(poster("새 제목", PosterStatus.DRAFT, null)); + + // when + ResultActions result = + mvc.perform( + patch("/posters/" + ID) + .contentType(MediaType.APPLICATION_JSON) + .content("{\"title\":\"새 제목\"}")); + + // then + result.andExpect(status().isOk()).andExpect(jsonPath("$.data.title").value("새 제목")); + } } - // ---- get ---- + /** The object-storage domain invariant: a poster cannot be published without an image. */ + @Nested + class PublishPoster { - @Test - void getReturnsPoster() throws Exception { - when(getUseCase.handle(any())) - .thenReturn(poster("여름 세일", PosterStatus.PUBLISHED, "posters/x/image")); - mvc.perform(get("/posters/" + ID)) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.data.id").value(ID)) - .andExpect(jsonPath("$.data.status").value("PUBLISHED")) - .andExpect(jsonPath("$.data.imageKey").value("posters/x/image")); + @Test + void publishWithoutImageReturns400ImageRequired() throws Exception { + // given + when(publishUseCase.handle(any())) + .thenThrow(new PosterInvariantException(PosterInvariantException.Reason.IMAGE_REQUIRED)); + + // when + ResultActions result = mvc.perform(post("/posters/" + ID + "/publish")); + + // then + result + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error.code").value("POSTER_IMAGE_REQUIRED")); + } + + @Test + void publishReturnsPublishedPoster() throws Exception { + // given + when(publishUseCase.handle(any())) + .thenReturn(poster("여름 세일", PosterStatus.PUBLISHED, "posters/x/image")); + + // when + ResultActions result = mvc.perform(post("/posters/" + ID + "/publish")); + + // then + result.andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("PUBLISHED")); + } } - @Test - void getMissingReturns404PosterNotFound() throws Exception { - when(getUseCase.handle(any())).thenThrow(new PosterNotFoundException(PosterId.of(ID))); - mvc.perform(get("/posters/" + ID)) - .andExpect(status().isNotFound()) - .andExpect(jsonPath("$.error.code").value("POSTER_NOT_FOUND")); + @Nested + class ArchivePoster { + + @Test + void archiveReturnsArchivedPoster() throws Exception { + // given + when(archiveUseCase.handle(any())) + .thenReturn(poster("여름 세일", PosterStatus.ARCHIVED, "posters/x/image")); + + // when + ResultActions result = mvc.perform(post("/posters/" + ID + "/archive")); + + // then + result.andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("ARCHIVED")); + } } - @Test - void getWithMalformedIdReturns400BadParameter() throws Exception { - mvc.perform(get("/posters/not-a-valid-uuid")) - .andExpect(status().isBadRequest()) - .andExpect(jsonPath("$.error.code").value("BAD_PARAMETER")); + @Nested + class UploadPosterImage { + + @Test + // This single receipt assertion remains while the whole-byte migration is active. + @SuppressWarnings("removal") + void uploadImageReturnsStoredObjectReceipt() throws Exception { + // given + when(uploadImageUseCase.handle(any())) + .thenReturn( + new StoredObject( + "posters/" + ID + "/image", 3L, "image/png", URI.create("file:///x"))); + MockMultipartFile file = + new MockMultipartFile("file", "banner.png", "image/png", new byte[] {1, 2, 3}); + + // when + ResultActions result = mvc.perform(multipart("/posters/" + ID + "/image").file(file)); + + // then + result + .andExpect(status().isOk()) + .andExpect(jsonPath("$.data.key").value("posters/" + ID + "/image")) + .andExpect(jsonPath("$.data.contentType").value("image/png")); + } } - @Test - void getAcceptsMixedCaseUuidPathAndNormalizes() throws Exception { - when(getUseCase.handle(any())).thenReturn(poster("여름 세일", PosterStatus.DRAFT, null)); - mvc.perform(get("/posters/" + ID.toUpperCase(Locale.ROOT))) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.data.id").value(ID)); - } + @Nested + class DeletePoster { - // ---- create / update ---- - - @Test - void createReturns201WithBody() throws Exception { - when(createUseCase.handle(any())).thenReturn(poster("여름 세일", PosterStatus.DRAFT, null)); - mvc.perform( - post("/posters") - .contentType(MediaType.APPLICATION_JSON) - .content("{\"title\":\"여름 세일\",\"caption\":\"7월 한정\"}")) - .andExpect(status().isCreated()) - .andExpect(jsonPath("$.success").value(true)) - .andExpect(jsonPath("$.data.title").value("여름 세일")); - } - - @Test - void createWithBlankTitleFailsValidation() throws Exception { - mvc.perform( - post("/posters").contentType(MediaType.APPLICATION_JSON).content("{\"title\":\"\"}")) - .andExpect(status().isBadRequest()) - .andExpect(jsonPath("$.error.code").value("VALIDATION_FAILED")); - } - - @Test - void patchReplacesTitle() throws Exception { - when(updateUseCase.handle(any())).thenReturn(poster("새 제목", PosterStatus.DRAFT, null)); - mvc.perform( - patch("/posters/" + ID) - .contentType(MediaType.APPLICATION_JSON) - .content("{\"title\":\"새 제목\"}")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.data.title").value("새 제목")); - } - - // ---- lifecycle: publish (the object-storage domain invariant) / archive ---- - - @Test - void publishWithoutImageReturns400ImageRequired() throws Exception { - when(publishUseCase.handle(any())) - .thenThrow(new PosterInvariantException(PosterInvariantException.Reason.IMAGE_REQUIRED)); - mvc.perform(post("/posters/" + ID + "/publish")) - .andExpect(status().isBadRequest()) - .andExpect(jsonPath("$.error.code").value("POSTER_IMAGE_REQUIRED")); - } - - @Test - void publishReturnsPublishedPoster() throws Exception { - when(publishUseCase.handle(any())) - .thenReturn(poster("여름 세일", PosterStatus.PUBLISHED, "posters/x/image")); - mvc.perform(post("/posters/" + ID + "/publish")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.data.status").value("PUBLISHED")); - } - - @Test - void archiveReturnsArchivedPoster() throws Exception { - when(archiveUseCase.handle(any())) - .thenReturn(poster("여름 세일", PosterStatus.ARCHIVED, "posters/x/image")); - mvc.perform(post("/posters/" + ID + "/archive")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.data.status").value("ARCHIVED")); - } - - // ---- image upload (multipart) ---- - - @Test - // This single receipt assertion remains while the whole-byte migration is active. - @SuppressWarnings("removal") - void uploadImageReturnsStoredObjectReceipt() throws Exception { - when(uploadImageUseCase.handle(any())) - .thenReturn( - new StoredObject("posters/" + ID + "/image", 3L, "image/png", URI.create("file:///x"))); - MockMultipartFile file = - new MockMultipartFile("file", "banner.png", "image/png", new byte[] {1, 2, 3}); - mvc.perform(multipart("/posters/" + ID + "/image").file(file)) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.data.key").value("posters/" + ID + "/image")) - .andExpect(jsonPath("$.data.contentType").value("image/png")); - } - - // ---- delete ---- - - @Test - void deleteReturns204() throws Exception { - mvc.perform(delete("/posters/" + ID)).andExpect(status().isNoContent()); + @Test + void deleteReturns204() throws Exception { + mvc.perform(delete("/posters/" + ID)).andExpect(status().isNoContent()); + } } } diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/controller/PosterImagePublicationControllerWireTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/controller/PosterImagePublicationControllerWireTest.java index f71271c6..b55088fd 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/controller/PosterImagePublicationControllerWireTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/controller/PosterImagePublicationControllerWireTest.java @@ -1,9 +1,10 @@ package dev.caskeleton.sample.portfolio.adapter.inbound.web.controller; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.catchThrowable; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import dev.caskeleton.adapter.inbound.web.auth.AuthenticatedPrincipal; @@ -11,6 +12,7 @@ import dev.caskeleton.application.objectstorage.identity.ObjectOperationId; import dev.caskeleton.application.objectstorage.model.ObjectContentIdentity; import dev.caskeleton.application.objectstorage.model.ObjectDigest; import dev.caskeleton.application.objectstorage.model.ObjectMediaType; +import dev.caskeleton.sample.portfolio.adapter.inbound.web.dto.response.PosterImagePublicationResponse; import dev.caskeleton.sample.portfolio.adapter.inbound.web.dto.response.PosterImagePublicationStatusResponse; import dev.caskeleton.sample.portfolio.application.poster.GetPosterImagePublicationStatusUseCase; import dev.caskeleton.sample.portfolio.application.poster.PublishPosterImageUseCase; @@ -19,66 +21,101 @@ import dev.caskeleton.sample.portfolio.application.posterimage.PosterImagePublic import dev.caskeleton.sample.portfolio.application.posterimage.PosterImageUploadIntentState; import dev.caskeleton.sample.portfolio.domain.poster.PosterId; import dev.caskeleton.sample.portfolio.domain.poster.PosterImageReference; +import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.Set; import org.junit.jupiter.api.Test; import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; import org.springframework.mock.web.MockMultipartFile; +/** + * Calls the controller directly. The two use cases stay Mockito doubles: they are application + * classes with a dozen object-storage collaborators, which this transport test does not wire. + */ class PosterImagePublicationControllerWireTest { private static final PosterId POSTER = PosterId.of("0190bd6e-7c3e-7abc-8def-0123456789ab"); private static final ObjectOperationId OPERATION = ObjectOperationId.of("0190bd6e-7c3e-7abc-8def-012345678901"); + private static final String REFERENCE = "osr1.0123456789ab.0123456789abcdefghjkmnpqrs.d53d9429ac"; + private static final byte[] BYTES = "hello".getBytes(StandardCharsets.UTF_8); + private static final ObjectContentIdentity CONTENT = + new ObjectContentIdentity(BYTES.length, ObjectDigest.sha256(BYTES)); + private static final AuthenticatedPrincipal PRINCIPAL = + new AuthenticatedPrincipal("principal-a", "a@example.test", Set.of("user")); + + private final PublishPosterImageUseCase publish = mock(PublishPosterImageUseCase.class); + private final GetPosterImagePublicationStatusUseCase status = + mock(GetPosterImagePublicationStatusUseCase.class); + private final PosterImagePublicationController controller = + new PosterImagePublicationController(publish, status); @Test - void acceptedAndReadyResponsesExposeNoStorageLocator() { - PublishPosterImageUseCase publish = mock(PublishPosterImageUseCase.class); - GetPosterImagePublicationStatusUseCase status = - mock(GetPosterImagePublicationStatusUseCase.class); + void publishReturns202WithOnlyOperationIdAndStatusPath() { + // given when(publish.handle(any())) .thenReturn(new PosterImagePublicationReservation(POSTER, OPERATION)); - ObjectContentIdentity content = - new ObjectContentIdentity(5, ObjectDigest.sha256("hello".getBytes(StandardCharsets.UTF_8))); + String statusPath = "/posters/" + POSTER.value() + "/imagePublications/" + OPERATION.value(); + + // when + ResponseEntity accepted = + controller.publish( + POSTER.value(), + "client-key", + 0, + CONTENT.fullDigest().base64Value(), + new MockMultipartFile("file", "poster.png", "image/png", BYTES), + PRINCIPAL); + + // then + assertThat(accepted) + .extracting( + ResponseEntity::getStatusCode, + r -> r.getHeaders().getLocation(), + ResponseEntity::getBody) + .containsExactly( + HttpStatus.ACCEPTED, + URI.create(statusPath), + new PosterImagePublicationResponse(OPERATION.value(), statusPath)); + } + + @Test + void readyStatusExposesOpaqueReferenceWithoutStorageLocator() { + // given when(status.handle(any())) .thenReturn( new PosterImagePublicationStatus( POSTER, OPERATION, PosterImageUploadIntentState.READY, - PosterImageReference.of("osr1.0123456789ab.0123456789abcdefghjkmnpqrs.d53d9429ac"), - content, + PosterImageReference.of(REFERENCE), + CONTENT, ObjectMediaType.of("image/png"))); - PosterImagePublicationController controller = - new PosterImagePublicationController(publish, status); - var principal = new AuthenticatedPrincipal("principal-a", "a@example.test", Set.of("user")); - var file = - new MockMultipartFile( - "file", "poster.png", "image/png", "hello".getBytes(StandardCharsets.UTF_8)); - var accepted = - controller.publish( - POSTER.value(), "client-key", 0, content.fullDigest().base64Value(), file, principal); + // when PosterImagePublicationStatusResponse ready = - controller.status(POSTER.value(), OPERATION.value(), principal); + controller.status(POSTER.value(), OPERATION.value(), PRINCIPAL); - assertThat(accepted.getStatusCode()).isEqualTo(HttpStatus.ACCEPTED); - assertThat(accepted.getHeaders().getLocation().toString()) - .isEqualTo("/posters/" + POSTER.value() + "/imagePublications/" + OPERATION.value()); - assertThat(ready.reference()).startsWith("osr1."); + // then + assertThat(ready) + .isEqualTo( + new PosterImagePublicationStatusResponse( + OPERATION.value(), + "READY", + REFERENCE, + BYTES.length, + "image/png", + CONTENT.fullDigest().base64Value())); assertThat(ready.toString()) .doesNotContain("s3://", "file://", "bucket", "presigned", "providerVersion"); } @Test - void missingIdempotencyKeyIsRejectedBeforeUseCaseLookup() { - PosterImagePublicationController controller = - new PosterImagePublicationController( - mock(PublishPosterImageUseCase.class), - mock(GetPosterImagePublicationStatusUseCase.class)); - - assertThatIllegalArgumentException() - .isThrownBy( + void blankIdempotencyKeyIsRejectedBeforeCallingPublishUseCase() { + // when + Throwable thrown = + catchThrowable( () -> controller.publish( POSTER.value(), @@ -87,5 +124,11 @@ class PosterImagePublicationControllerWireTest { ObjectDigest.sha256(new byte[] {1}).base64Value(), new MockMultipartFile("file", "x.png", "image/png", new byte[] {1}), new AuthenticatedPrincipal("principal-a", null, Set.of()))); + + // then + assertThat(thrown) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("authenticated principal and Idempotency-Key are required"); + verifyNoInteractions(publish); } } diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/controller/WorkLogControllerWireTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/controller/WorkLogControllerWireTest.java index 2c8d8d10..d689cfa1 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/controller/WorkLogControllerWireTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/controller/WorkLogControllerWireTest.java @@ -2,11 +2,14 @@ package dev.caskeleton.sample.portfolio.adapter.inbound.web.controller; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.head; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -18,7 +21,10 @@ import dev.caskeleton.adapter.inbound.web.error.GlobalExceptionHandler; import dev.caskeleton.sample.portfolio.adapter.inbound.web.error.DomainExceptionHandler; import dev.caskeleton.sample.portfolio.adapter.inbound.web.json.WorkLogIdSerializer; import dev.caskeleton.sample.portfolio.application.command.CreateWorkLogCommand; +import dev.caskeleton.sample.portfolio.application.command.UpdateWorkLogCommand; import dev.caskeleton.sample.portfolio.application.exception.WorkLogNotFoundException; +import dev.caskeleton.sample.portfolio.application.query.GetWorkLogQuery; +import dev.caskeleton.sample.portfolio.application.query.ListWorkLogsQuery; import dev.caskeleton.sample.portfolio.application.worklog.BatchCreateWorkLogsUseCase; import dev.caskeleton.sample.portfolio.application.worklog.CreateWorkLogUseCase; import dev.caskeleton.sample.portfolio.application.worklog.DeleteWorkLogUseCase; @@ -33,12 +39,15 @@ import dev.caskeleton.sample.portfolio.domain.worklog.WorkLog; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogId; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogInvariantException; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogPage; +import dev.caskeleton.shared.request.Patch; import java.time.LocalDate; import java.util.List; import java.util.Locale; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.IntStream; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.springframework.beans.factory.annotation.Autowired; @@ -52,7 +61,13 @@ import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.ResultActions; +/** + * HTTP wire contract of the work-log endpoints. The use cases stay {@code @MockitoBean}: each is an + * application class over repository, outbox, id, clock and transaction ports this slice does not + * wire. No test here stubs a port. + */ @WebMvcTest( controllers = WorkLogController.class, excludeAutoConfiguration = SecurityAutoConfiguration.class) @@ -75,6 +90,8 @@ import org.springframework.test.web.servlet.MockMvc; class WorkLogControllerWireTest { private static final String ID = "0190bd6e-7c3e-7abc-8def-0123456789ab"; // D19 fixture + private static final String VALID_CREATE_BODY = + "{\"title\":\"t\",\"category\":\"DATABASE\",\"periodStart\":\"2025-01-01\"}"; @Autowired MockMvc mvc; @MockitoBean CreateWorkLogUseCase createUseCase; @@ -85,8 +102,13 @@ class WorkLogControllerWireTest { @MockitoBean ListWorkLogsUseCase listUseCase; @MockitoBean GetRepoStatsUseCase repoStatsUseCase; - private WorkLog sample(String title) { - // version 0 → ETag W/"0" at the boundary + @AfterEach + void clearSecurityContext() { + SecurityContextHolder.clearContext(); + } + + /** Version 0, so the boundary emits {@code ETag: W/"0"}. */ + private static WorkLog sample(String title) { return WorkLog.rehydrate( WorkLogId.of(ID), title, @@ -99,334 +121,509 @@ class WorkLogControllerWireTest { 0L); } - // ---- D7/D18/D20/D21 list ---- - - @Test - void listIsWrappedInEnvelopeWithPageMeta() throws Exception { - when(listUseCase.handle(any())).thenReturn(new WorkLogPage(List.of(sample("DB 튜닝")), 1)); - mvc.perform(get("/worklogs")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.success").value(true)) - .andExpect(jsonPath("$.data[0].title").value("DB 튜닝")) - .andExpect(jsonPath("$.data[0].id").value(ID)) - .andExpect(jsonPath("$.meta.page.number").value(0)) - .andExpect(jsonPath("$.meta.page.size").value(20)) - .andExpect(jsonPath("$.meta.page.total").value(1)); + private static UpdateWorkLogCommand patchOf(Patch title, Patch summary) { + return new UpdateWorkLogCommand( + WorkLogId.of(ID), title, summary, Patch.absent(), Patch.absent(), Patch.absent()); } - @Test - void emptyListIsDataArrayNotNullWithZeroTotal() throws Exception { - when(listUseCase.handle(any())).thenReturn(new WorkLogPage(List.of(), 0)); - mvc.perform(get("/worklogs")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.data").isArray()) - .andExpect(jsonPath("$.data.length()").value(0)) - .andExpect(jsonPath("$.meta.page.total").value(0)); - } + /** D7/D18/D20/D21. */ + @Nested + class ListWorkLogs { - @Test - void sizeOverCapIs400ValidationWithFieldAndCode() throws Exception { - mvc.perform(get("/worklogs").param("size", "101")) - .andExpect(status().isBadRequest()) - .andExpect(jsonPath("$.error.code").value("VALIDATION_FAILED")) - .andExpect(jsonPath("$.error.details.field").value("size")) - .andExpect(jsonPath("$.error.details.code").value("SIZE_EXCEEDS_MAX")); - } + @Test + void listIsWrappedInEnvelopeWithPageMeta() throws Exception { + // given + when(listUseCase.handle(any())).thenReturn(new WorkLogPage(List.of(sample("DB 튜닝")), 1)); - @Test - void nativeSortSyntaxIsAcceptedAndEchoedInMeta() throws Exception { - when(listUseCase.handle(any())).thenReturn(new WorkLogPage(List.of(sample("a")), 1)); - mvc.perform(get("/worklogs").param("sort", "title,desc")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.meta.page.sort").value("title,desc")); - } + // when + ResultActions result = mvc.perform(get("/worklogs")); - @Test - void jsonapiPrefixSortSyntaxIsRejected400() throws Exception { - mvc.perform(get("/worklogs").param("sort", "-title")) - .andExpect(status().isBadRequest()) - .andExpect(jsonPath("$.error.code").value("VALIDATION_FAILED")); - } + // then + result + .andExpect(status().isOk()) + .andExpect(jsonPath("$.success").value(true)) + .andExpect(jsonPath("$.data[0].title").value("DB 튜닝")) + .andExpect(jsonPath("$.data[0].id").value(ID)) + .andExpect(jsonPath("$.meta.page.number").value(0)) + .andExpect(jsonPath("$.meta.page.size").value(20)) + .andExpect(jsonPath("$.meta.page.total").value(1)); + } - @Test - void flatCategoryFilterIsAccepted() throws Exception { - when(listUseCase.handle(any())).thenReturn(new WorkLogPage(List.of(sample("a")), 1)); - mvc.perform(get("/worklogs").param("category", "DATABASE")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.data.length()").value(1)); - } + @Test + void emptyListIsDataArrayNotNullWithZeroTotal() throws Exception { + // given + when(listUseCase.handle(any())).thenReturn(new WorkLogPage(List.of(), 0)); - // ---- D15 conditional requests ---- + // when + ResultActions result = mvc.perform(get("/worklogs")); - @Test - void getEmitsEtagHeader() throws Exception { - when(getUseCase.handle(any())).thenReturn(sample("DB 튜닝")); - mvc.perform(get("/worklogs/" + ID)) - .andExpect(status().isOk()) - .andExpect(header().string("ETag", "W/\"0\"")) - .andExpect(jsonPath("$.data.id").value(ID)); - } + // then + result + .andExpect(status().isOk()) + .andExpect(jsonPath("$.data").isArray()) + .andExpect(jsonPath("$.data.length()").value(0)) + .andExpect(jsonPath("$.meta.page.total").value(0)); + } - @Test - void getWithMatchingIfNoneMatchReturns304NoBody() throws Exception { - when(getUseCase.handle(any())).thenReturn(sample("DB 튜닝")); - mvc.perform(get("/worklogs/" + ID).header("If-None-Match", "W/\"0\"")) - .andExpect(status().isNotModified()); - } + @Test + void sizeOverCapIs400ValidationWithFieldAndCode() throws Exception { + // when + ResultActions result = mvc.perform(get("/worklogs").param("size", "101")); - @Test - void patchWithStaleIfMatchReturns412() throws Exception { - when(getUseCase.handle(any())).thenReturn(sample("current")); - mvc.perform( - patch("/worklogs/" + ID) - .header("If-Match", "W/\"99\"") - .contentType(MediaType.APPLICATION_JSON) - .content("{\"title\":\"x\"}")) - .andExpect(status().isPreconditionFailed()) - .andExpect(jsonPath("$.error.code").value("PRECONDITION_FAILED")); - } + // then + result + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error.code").value("VALIDATION_FAILED")) + .andExpect(jsonPath("$.error.details.field").value("size")) + .andExpect(jsonPath("$.error.details.code").value("SIZE_EXCEEDS_MAX")); + } - @Test - void patchWithMatchingIfMatchAppliesUpdate() throws Exception { - when(getUseCase.handle(any())).thenReturn(sample("current")); - when(updateUseCase.handle(any())).thenReturn(sample("new title")); - mvc.perform( - patch("/worklogs/" + ID) - .header("If-Match", "W/\"0\"") - .contentType(MediaType.APPLICATION_JSON) - .content("{\"title\":\"new title\"}")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.data.title").value("new title")); - } + @Test + void nativeSortSyntaxIsAcceptedAndEchoedInMeta() throws Exception { + // given + when(listUseCase.handle(any())).thenReturn(new WorkLogPage(List.of(sample("a")), 1)); - // ---- D13 HEAD mirrors GET ---- + // when + ResultActions result = mvc.perform(get("/worklogs").param("sort", "title,desc")); - @Test - void headOnGetEndpointIsSupportedNot405() throws Exception { - // D13: a GET-supporting endpoint MUST also answer HEAD (Spring MVC mirrors it), - // i.e. 200 — never 405/404. (Body stripping is the container's job and is not - // reproduced by MockMvc, so we assert the mirrored status, not an empty body.) - when(getUseCase.handle(any())).thenReturn(sample("DB 튜닝")); - mvc.perform(head("/worklogs/" + ID)).andExpect(status().isOk()); - } + // then + result.andExpect(status().isOk()).andExpect(jsonPath("$.meta.page.sort").value("title,desc")); + } - // ---- D21 filter DSL is not parsed (silently ignored) ---- + @Test + void jsonapiPrefixSortSyntaxIsRejected400() throws Exception { + // when + ResultActions result = mvc.perform(get("/worklogs").param("sort", "-title")); - @Test - void filterDslIsIgnoredNotParsed() throws Exception { - when(listUseCase.handle(any())).thenReturn(new WorkLogPage(List.of(sample("a")), 1)); - mvc.perform( - get("/worklogs").param("filter", "status==OPEN")) // RSQL/DSL → unknown param, ignored - .andExpect(status().isOk()) - .andExpect(jsonPath("$.success").value(true)) - .andExpect(jsonPath("$.data.length()").value(1)); - } + // then + result + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error.code").value("VALIDATION_FAILED")); + } - // ---- existing id / validation / mapping behaviours (paths renamed to /worklogs) ---- + @Test + void flatCategoryFilterIsAccepted() throws Exception { + // given + // only the category-filtered query is answered, so a 200 proves the filter reached it + when(listUseCase.handle(new ListWorkLogsQuery(0, 20, null, true, WorkCategory.DATABASE))) + .thenReturn(new WorkLogPage(List.of(sample("a")), 1)); - @Test - void getMissingReturns404WorklogNotFound() throws Exception { - when(getUseCase.handle(any())).thenThrow(new WorkLogNotFoundException(WorkLogId.of(ID))); - mvc.perform(get("/worklogs/" + ID)) - .andExpect(status().isNotFound()) - .andExpect(jsonPath("$.error.code").value("WORKLOG_NOT_FOUND")); - } + // when + ResultActions result = mvc.perform(get("/worklogs").param("category", "DATABASE")); - @Test - void getWithMalformedIdReturns400BadParameter() throws Exception { - mvc.perform(get("/worklogs/not-a-valid-uuid")) - .andExpect(status().isBadRequest()) - .andExpect(jsonPath("$.error.code").value("BAD_PARAMETER")); - } + // then + result.andExpect(status().isOk()).andExpect(jsonPath("$.data.length()").value(1)); + } - @Test - void getAcceptsMixedCaseUuidPathAndNormalizesD3() throws Exception { - when(getUseCase.handle(any())).thenReturn(sample("DB 튜닝")); - mvc.perform(get("/worklogs/" + ID.toUpperCase(Locale.ROOT))) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.data.id").value(ID)); - } + /** D21: an RSQL/DSL {@code filter} is an unknown parameter and is ignored, not parsed. */ + @Test + void filterDslIsIgnoredNotParsed() throws Exception { + // given + when(listUseCase.handle(any())).thenReturn(new WorkLogPage(List.of(sample("a")), 1)); - @Test - void createWithBlankTitleFailsValidation() throws Exception { - mvc.perform( - post("/worklogs") - .contentType(MediaType.APPLICATION_JSON) - .content( - "{\"title\":\"\",\"category\":\"DATABASE\",\"periodStart\":\"2025-01-01\"}")) - .andExpect(status().isBadRequest()) - .andExpect(jsonPath("$.error.code").value("VALIDATION_FAILED")); - } + // when + ResultActions result = mvc.perform(get("/worklogs").param("filter", "status==OPEN")); - @Test - void createWithUnknownFieldIsRejectedB1() throws Exception { - mvc.perform( - post("/worklogs") - .contentType(MediaType.APPLICATION_JSON) - .content( - "{\"title\":\"x\",\"category\":\"DATABASE\",\"periodStart\":\"2025-01-01\",\"oops\":\"y\"}")) - .andExpect(status().isBadRequest()) - .andExpect(jsonPath("$.error.code").value("VALIDATION_FAILED")) - .andExpect(jsonPath("$.error.details.cause").value("UnrecognizedPropertyException")); - } - - @Test - void createWithUnmappableLinkRoutesToMappingFailedB3() throws Exception { - mvc.perform( - post("/worklogs") - .contentType(MediaType.APPLICATION_JSON) - .content( - "{\"title\":\"x\",\"category\":\"DATABASE\",\"periodStart\":\"2025-01-01\",\"links\":[\"not a uri\"]}")) - .andExpect(status().isBadRequest()) - .andExpect(jsonPath("$.error.code").value("MAPPING_FAILED")); - } - - @Test - void patchReplacesOnlyPresentFieldsB2() throws Exception { - when(updateUseCase.handle(any())).thenReturn(sample("new title")); - mvc.perform( - patch("/worklogs/" + ID) - .contentType(MediaType.APPLICATION_JSON) - .content("{\"title\":\"new title\"}")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.data.title").value("new title")) - .andExpect(jsonPath("$.data.id").value(ID)); - } - - @Test - void patchCanAdvanceStatusAndResponseExposesMinimumModel() throws Exception { - WorkLog started = sample("status"); - started.startProgress(); - when(updateUseCase.handle(any())).thenReturn(started); - - mvc.perform( - patch("/worklogs/" + ID) - .contentType(MediaType.APPLICATION_JSON) - .content("{\"status\":\"IN_PROGRESS\"}")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.data.status").value("IN_PROGRESS")) - .andExpect(jsonPath("$.data.owner").doesNotExist()); - } - - @Test - void closedWorklogUpdateReturnsConflictEnvelope() throws Exception { - when(updateUseCase.handle(any())) - .thenThrow( - new WorkLogInvariantException( - WorkLogInvariantException.Reason.CLOSED_WORKLOG_MUTATION)); - - mvc.perform( - patch("/worklogs/" + ID) - .contentType(MediaType.APPLICATION_JSON) - .content("{\"title\":\"late edit\"}")) - .andExpect(status().isConflict()) - .andExpect(jsonPath("$.error.code").value("WORKLOG_CONFLICT")); - } - - @Test - void patchWithExplicitNullSummaryIsAcceptedB2() throws Exception { - when(updateUseCase.handle(any())).thenReturn(sample("t")); - mvc.perform( - patch("/worklogs/" + ID) - .contentType(MediaType.APPLICATION_JSON) - .content("{\"summary\":null}")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.success").value(true)); - } - - @Test - void repoStatsEndpointReturnsDomainViaEnvelope() throws Exception { - when(repoStatsUseCase.handle(any())) - .thenReturn(new RepoStats("owner/repo", 42, "2025-01-01T00:00:00Z")); - mvc.perform(get("/worklogs/repoStats").param("repoUrl", "https://github.com/owner/repo")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.data.stars").value(42)); - } - - @Test - void createCapturesAuthenticatedPrincipalAsOwner() throws Exception { - TestingAuthenticationToken token = - new TestingAuthenticationToken( - new AuthenticatedPrincipal("sub-7", "u@example.com", Set.of("user")), "n/a"); - token.setAuthenticated(true); - SecurityContextHolder.getContext().setAuthentication(token); - ArgumentCaptor captor = - ArgumentCaptor.forClass(CreateWorkLogCommand.class); - when(createUseCase.handle(captor.capture())).thenReturn(sample("t")); - try { - mvc.perform( - post("/worklogs") - .contentType(MediaType.APPLICATION_JSON) - .content( - "{\"title\":\"t\",\"category\":\"DATABASE\",\"periodStart\":\"2025-01-01\"}")) - .andExpect(status().isOk()); - assertThat(captor.getValue().owner()).isEqualTo("sub-7"); - } finally { - SecurityContextHolder.clearContext(); + // then + result + .andExpect(status().isOk()) + .andExpect(jsonPath("$.success").value(true)) + .andExpect(jsonPath("$.data.length()").value(1)); } } - @Test - void createResponseDoesNotExposeOwner() throws Exception { - // privacy: owner is the raw principal id; it must not leak in the response payload - // (pseudonymization is delegated to feature-data-retention-privacy-contract). - when(createUseCase.handle(any())).thenReturn(sample("t")); - mvc.perform( - post("/worklogs") - .contentType(MediaType.APPLICATION_JSON) - .content( - "{\"title\":\"t\",\"category\":\"DATABASE\",\"periodStart\":\"2025-01-01\"}")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.data.owner").doesNotExist()); + /** D15 conditional GET, D13 HEAD mirroring, and id parsing. */ + @Nested + class GetWorkLog { + + @Test + void getEmitsEtagHeader() throws Exception { + // given + when(getUseCase.handle(any())).thenReturn(sample("DB 튜닝")); + + // when + ResultActions result = mvc.perform(get("/worklogs/" + ID)); + + // then + result + .andExpect(status().isOk()) + .andExpect(header().string("ETag", "W/\"0\"")) + .andExpect(jsonPath("$.data.id").value(ID)); + } + + @Test + void getWithMatchingIfNoneMatchReturns304NoBody() throws Exception { + // given + when(getUseCase.handle(any())).thenReturn(sample("DB 튜닝")); + + // when + ResultActions result = mvc.perform(get("/worklogs/" + ID).header("If-None-Match", "W/\"0\"")); + + // then + result.andExpect(status().isNotModified()).andExpect(content().string("")); + } + + /** + * D13: a GET-supporting endpoint MUST also answer HEAD (Spring MVC mirrors it), i.e. 200 — + * never 405/404. Body stripping is the container's job and is not reproduced by MockMvc, so + * this asserts the mirrored status, not an empty body. + */ + @Test + void headOnGetEndpointIsSupportedNot405() throws Exception { + // given + when(getUseCase.handle(any())).thenReturn(sample("DB 튜닝")); + + // when + ResultActions result = mvc.perform(head("/worklogs/" + ID)); + + // then + result.andExpect(status().isOk()); + } + + @Test + void getMissingReturns404WorklogNotFound() throws Exception { + // given + when(getUseCase.handle(any())).thenThrow(new WorkLogNotFoundException(WorkLogId.of(ID))); + + // when + ResultActions result = mvc.perform(get("/worklogs/" + ID)); + + // then + result + .andExpect(status().isNotFound()) + .andExpect(jsonPath("$.error.code").value("WORKLOG_NOT_FOUND")); + } + + @Test + void getWithMalformedIdReturns400BadParameter() throws Exception { + // when + ResultActions result = mvc.perform(get("/worklogs/not-a-valid-uuid")); + + // then + result + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error.code").value("BAD_PARAMETER")); + } + + @Test + void getAcceptsMixedCaseUuidPathAndNormalizesD3() throws Exception { + // given + // only the lower-case id is answered, so a 200 proves the path was normalized + when(getUseCase.handle(new GetWorkLogQuery(WorkLogId.of(ID)))).thenReturn(sample("DB 튜닝")); + + // when + ResultActions result = mvc.perform(get("/worklogs/" + ID.toUpperCase(Locale.ROOT))); + + // then + result.andExpect(status().isOk()).andExpect(jsonPath("$.data.id").value(ID)); + } } - // ---- D23 atomic batch create ---- + @Nested + class CreateWorkLog { - @Test - void batchCreateAllOkReturnsArray() throws Exception { - when(batchCreateUseCase.handle(any())).thenReturn(List.of(sample("a"), sample("b"))); - mvc.perform( - post("/worklogs:batchCreate") - .contentType(MediaType.APPLICATION_JSON) - .content( - "{\"requests\":[" - + "{\"title\":\"a\",\"category\":\"DATABASE\",\"periodStart\":\"2025-01-01\"}," - + "{\"title\":\"b\",\"category\":\"DATABASE\",\"periodStart\":\"2025-01-01\"}]}")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.success").value(true)) - .andExpect(jsonPath("$.data.length()").value(2)); + @Test + void createWithBlankTitleFailsValidation() throws Exception { + // when + ResultActions result = + mvc.perform( + post("/worklogs") + .contentType(MediaType.APPLICATION_JSON) + .content( + "{\"title\":\"\",\"category\":\"DATABASE\",\"periodStart\":\"2025-01-01\"}")); + + // then + result + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error.code").value("VALIDATION_FAILED")); + } + + @Test + void createWithUnknownFieldIsRejectedB1() throws Exception { + // when + ResultActions result = + mvc.perform( + post("/worklogs") + .contentType(MediaType.APPLICATION_JSON) + .content( + "{\"title\":\"x\",\"category\":\"DATABASE\",\"periodStart\":\"2025-01-01\",\"oops\":\"y\"}")); + + // then + result + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error.code").value("VALIDATION_FAILED")) + .andExpect(jsonPath("$.error.details.cause").value("UnrecognizedPropertyException")); + } + + @Test + void createWithUnmappableLinkRoutesToMappingFailedB3() throws Exception { + // when + ResultActions result = + mvc.perform( + post("/worklogs") + .contentType(MediaType.APPLICATION_JSON) + .content( + "{\"title\":\"x\",\"category\":\"DATABASE\",\"periodStart\":\"2025-01-01\",\"links\":[\"not a uri\"]}")); + + // then + result + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error.code").value("MAPPING_FAILED")); + } + + @Test + void createCapturesAuthenticatedPrincipalAsOwner() throws Exception { + // given + TestingAuthenticationToken token = + new TestingAuthenticationToken( + new AuthenticatedPrincipal("sub-7", "u@example.com", Set.of("user")), "n/a"); + token.setAuthenticated(true); + SecurityContextHolder.getContext().setAuthentication(token); + when(createUseCase.handle(any())).thenReturn(sample("t")); + + // when + ResultActions result = + mvc.perform( + post("/worklogs").contentType(MediaType.APPLICATION_JSON).content(VALID_CREATE_BODY)); + + // then + result.andExpect(status().isOk()); + ArgumentCaptor command = + ArgumentCaptor.forClass(CreateWorkLogCommand.class); + verify(createUseCase).handle(command.capture()); + assertThat(command.getValue().owner()).isEqualTo("sub-7"); + } + + /** + * Privacy: owner is the raw principal id and must not leak in the response payload + * (pseudonymization is delegated to feature-data-retention-privacy-contract). + */ + @Test + void createResponseDoesNotExposeOwner() throws Exception { + // given + when(createUseCase.handle(any())).thenReturn(sample("t")); + + // when + ResultActions result = + mvc.perform( + post("/worklogs").contentType(MediaType.APPLICATION_JSON).content(VALID_CREATE_BODY)); + + // then + result.andExpect(status().isOk()).andExpect(jsonPath("$.data.owner").doesNotExist()); + } } - @Test - void batchOverSizeCapIs400() throws Exception { - String item = "{\"title\":\"a\",\"category\":\"DATABASE\",\"periodStart\":\"2025-01-01\"}"; - String oversized = - "{\"requests\":[" - + IntStream.rangeClosed(1, WorkLogController.MAX_BATCH_SIZE + 1) - .mapToObj(i -> item) - .collect(Collectors.joining(",")) - + "]}"; - mvc.perform( - post("/worklogs:batchCreate") - .contentType(MediaType.APPLICATION_JSON) - .content(oversized)) - .andExpect(status().isBadRequest()) - .andExpect(jsonPath("$.error.code").value("VALIDATION_FAILED")); + /** D15 conditional PATCH and B2 partial-update semantics. */ + @Nested + class PatchWorkLog { + + @Test + void patchWithStaleIfMatchReturns412() throws Exception { + // given + when(getUseCase.handle(any())).thenReturn(sample("current")); + + // when + ResultActions result = + mvc.perform( + patch("/worklogs/" + ID) + .header("If-Match", "W/\"99\"") + .contentType(MediaType.APPLICATION_JSON) + .content("{\"title\":\"x\"}")); + + // then + result + .andExpect(status().isPreconditionFailed()) + .andExpect(jsonPath("$.error.code").value("PRECONDITION_FAILED")); + } + + @Test + void patchWithMatchingIfMatchAppliesUpdate() throws Exception { + // given + when(getUseCase.handle(any())).thenReturn(sample("current")); + when(updateUseCase.handle(any())).thenReturn(sample("new title")); + + // when + ResultActions result = + mvc.perform( + patch("/worklogs/" + ID) + .header("If-Match", "W/\"0\"") + .contentType(MediaType.APPLICATION_JSON) + .content("{\"title\":\"new title\"}")); + + // then + result.andExpect(status().isOk()).andExpect(jsonPath("$.data.title").value("new title")); + } + + @Test + void patchReplacesOnlyPresentFieldsB2() throws Exception { + // given + // only a command with the title present and every other field absent is answered + when(updateUseCase.handle(patchOf(Patch.of("new title"), Patch.absent()))) + .thenReturn(sample("new title")); + + // when + ResultActions result = + mvc.perform( + patch("/worklogs/" + ID) + .contentType(MediaType.APPLICATION_JSON) + .content("{\"title\":\"new title\"}")); + + // then + result + .andExpect(status().isOk()) + .andExpect(jsonPath("$.data.title").value("new title")) + .andExpect(jsonPath("$.data.id").value(ID)); + } + + @Test + void patchCanAdvanceStatusAndResponseExposesMinimumModel() throws Exception { + // given + WorkLog started = sample("status"); + started.startProgress(); + when(updateUseCase.handle(any())).thenReturn(started); + + // when + ResultActions result = + mvc.perform( + patch("/worklogs/" + ID) + .contentType(MediaType.APPLICATION_JSON) + .content("{\"status\":\"IN_PROGRESS\"}")); + + // then + result + .andExpect(status().isOk()) + .andExpect(jsonPath("$.data.status").value("IN_PROGRESS")) + .andExpect(jsonPath("$.data.owner").doesNotExist()); + } + + @Test + void closedWorklogUpdateReturnsConflictEnvelope() throws Exception { + // given + when(updateUseCase.handle(any())) + .thenThrow( + new WorkLogInvariantException( + WorkLogInvariantException.Reason.CLOSED_WORKLOG_MUTATION)); + + // when + ResultActions result = + mvc.perform( + patch("/worklogs/" + ID) + .contentType(MediaType.APPLICATION_JSON) + .content("{\"title\":\"late edit\"}")); + + // then + result + .andExpect(status().isConflict()) + .andExpect(jsonPath("$.error.code").value("WORKLOG_CONFLICT")); + } + + @Test + void patchWithExplicitNullSummaryIsAcceptedB2() throws Exception { + // given + // only a command carrying an explicit-null summary (not an absent one) is answered + when(updateUseCase.handle(patchOf(Patch.absent(), Patch.ofNull()))).thenReturn(sample("t")); + + // when + ResultActions result = + mvc.perform( + patch("/worklogs/" + ID) + .contentType(MediaType.APPLICATION_JSON) + .content("{\"summary\":null}")); + + // then + result.andExpect(status().isOk()).andExpect(jsonPath("$.success").value(true)); + } } - @Test - void batchCreateIsAtomicOneBadItemFailsWholeBatch() throws Exception { - // a single unmappable link fails mapping before any create → whole batch 400, no partial - // success (D23) - mvc.perform( - post("/worklogs:batchCreate") - .contentType(MediaType.APPLICATION_JSON) - .content( - "{\"requests\":[" - + "{\"title\":\"a\",\"category\":\"DATABASE\",\"periodStart\":\"2025-01-01\"}," - + "{\"title\":\"b\",\"category\":\"DATABASE\",\"periodStart\":\"2025-01-01\",\"links\":[\"bad uri\"]}]}")) - .andExpect(status().isBadRequest()) - .andExpect(jsonPath("$.success").value(false)) - .andExpect(jsonPath("$.error.code").value("MAPPING_FAILED")); + @Nested + class RepoStatsEndpoint { + + @Test + void repoStatsEndpointReturnsDomainViaEnvelope() throws Exception { + // given + when(repoStatsUseCase.handle(any())) + .thenReturn(new RepoStats("owner/repo", 42, "2025-01-01T00:00:00Z")); + + // when + ResultActions result = + mvc.perform(get("/worklogs/repoStats").param("repoUrl", "https://github.com/owner/repo")); + + // then + result.andExpect(status().isOk()).andExpect(jsonPath("$.data.stars").value(42)); + } + } + + /** D23 atomic batch create. */ + @Nested + class BatchCreateWorkLogs { + + @Test + void batchCreateAllOkReturnsArray() throws Exception { + // given + when(batchCreateUseCase.handle(any())).thenReturn(List.of(sample("a"), sample("b"))); + + // when + ResultActions result = + mvc.perform( + post("/worklogs:batchCreate") + .contentType(MediaType.APPLICATION_JSON) + .content( + "{\"requests\":[" + + "{\"title\":\"a\",\"category\":\"DATABASE\",\"periodStart\":\"2025-01-01\"}," + + "{\"title\":\"b\",\"category\":\"DATABASE\",\"periodStart\":\"2025-01-01\"}]}")); + + // then + result + .andExpect(status().isOk()) + .andExpect(jsonPath("$.success").value(true)) + .andExpect(jsonPath("$.data.length()").value(2)); + } + + @Test + void batchOverSizeCapIs400() throws Exception { + // given + String oversized = + "{\"requests\":[" + + IntStream.rangeClosed(1, WorkLogController.MAX_BATCH_SIZE + 1) + .mapToObj(i -> VALID_CREATE_BODY) + .collect(Collectors.joining(",")) + + "]}"; + + // when + ResultActions result = + mvc.perform( + post("/worklogs:batchCreate") + .contentType(MediaType.APPLICATION_JSON) + .content(oversized)); + + // then + result + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error.code").value("VALIDATION_FAILED")); + } + + /** + * A single unmappable link fails mapping before any create, so the whole batch is one 400 and + * the use case never runs (no partial success). + */ + @Test + void batchCreateIsAtomicOneBadItemFailsWholeBatch() throws Exception { + // when + ResultActions result = + mvc.perform( + post("/worklogs:batchCreate") + .contentType(MediaType.APPLICATION_JSON) + .content( + "{\"requests\":[" + + "{\"title\":\"a\",\"category\":\"DATABASE\",\"periodStart\":\"2025-01-01\"}," + + "{\"title\":\"b\",\"category\":\"DATABASE\",\"periodStart\":\"2025-01-01\",\"links\":[\"bad uri\"]}]}")); + + // then + result + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.success").value(false)) + .andExpect(jsonPath("$.error.code").value("MAPPING_FAILED")); + verifyNoInteractions(batchCreateUseCase); + } } } diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/dto/request/BasicPolymorphicTypeValidatorAllowlistTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/dto/request/BasicPolymorphicTypeValidatorAllowlistTest.java index 1385043d..f93161bd 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/dto/request/BasicPolymorphicTypeValidatorAllowlistTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/dto/request/BasicPolymorphicTypeValidatorAllowlistTest.java @@ -1,7 +1,7 @@ package dev.caskeleton.sample.portfolio.adapter.inbound.web.dto.request; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.databind.JsonMappingException; @@ -54,7 +54,9 @@ class BasicPolymorphicTypeValidatorAllowlistTest { public String name; } - private ObjectMapper allowlistMapper() { + private final ObjectMapper mapper = allowlistMapper(); + + private static ObjectMapper allowlistMapper() { // Allowlist only Cat and Dog as polymorphic subtypes of Animal. The validator // refuses every other subclass by default — the security guarantee. PolymorphicTypeValidator ptv = @@ -71,54 +73,63 @@ class BasicPolymorphicTypeValidatorAllowlistTest { @Test void allowlistedCatDeserializes() throws Exception { - ObjectMapper mapper = allowlistMapper(); + // given String json = """ ["dev.caskeleton.sample.portfolio.adapter.inbound.web.dto.request.BasicPolymorphicTypeValidatorAllowlistTest$Cat", {"name":"Whiskers"}] """; + // when Animal animal = mapper.readValue(json, Animal.class); - assertThat(animal).isInstanceOf(Cat.class); - assertThat(((Cat) animal).name).isEqualTo("Whiskers"); + // then + assertThat(animal) + .isInstanceOfSatisfying(Cat.class, cat -> assertThat(cat.name).isEqualTo("Whiskers")); } @Test void allowlistedDogDeserializes() throws Exception { - ObjectMapper mapper = allowlistMapper(); + // given String json = """ ["dev.caskeleton.sample.portfolio.adapter.inbound.web.dto.request.BasicPolymorphicTypeValidatorAllowlistTest$Dog", {"name":"Rex"}] """; + // when Animal animal = mapper.readValue(json, Animal.class); - assertThat(animal).isInstanceOf(Dog.class); - assertThat(((Dog) animal).name).isEqualTo("Rex"); + // then + assertThat(animal) + .isInstanceOfSatisfying(Dog.class, dog -> assertThat(dog.name).isEqualTo("Rex")); } @Test void nonAllowlistedSubtypeIsRejected() { - ObjectMapper mapper = allowlistMapper(); + // given String json = """ ["dev.caskeleton.sample.portfolio.adapter.inbound.web.dto.request.BasicPolymorphicTypeValidatorAllowlistTest$ForbiddenAnimal", {"name":"trojan"}] """; - assertThatThrownBy(() -> mapper.readValue(json, Animal.class)) + // when + Throwable thrown = catchThrowable(() -> mapper.readValue(json, Animal.class)); + + // then + assertThat(thrown) .as( "B5: a type id outside the BasicPolymorphicTypeValidator allowlist must be " + "refused — without this guarantee, CVE-2019-14379-class gadget chains " + "would be deserializable") - .isInstanceOf(JsonMappingException.class); + .isInstanceOf(JsonMappingException.class) + .hasMessageContaining("denied resolution"); } @Test void arbitraryJdkClassIsRejectedEvenWithoutExplicitAttack() { - ObjectMapper mapper = allowlistMapper(); + // given // java.io.File is a classic gadget-class candidate. Any non-allowlisted // class must be refused regardless of whether it would actually exploit. String json = @@ -126,8 +137,13 @@ class BasicPolymorphicTypeValidatorAllowlistTest { ["java.io.File", "/tmp/evil"] """; - assertThatThrownBy(() -> mapper.readValue(json, Animal.class)) + // when + Throwable thrown = catchThrowable(() -> mapper.readValue(json, Animal.class)); + + // then + assertThat(thrown) .as("B5: arbitrary JDK classes must be refused by the allowlist") - .isInstanceOf(JsonMappingException.class); + .isInstanceOf(JsonMappingException.class) + .hasMessageContaining("Could not resolve type id 'java.io.File'"); } } diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/dto/request/SamplePolymorphicRequestTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/dto/request/SamplePolymorphicRequestTest.java index 6592831e..20f6e9d1 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/dto/request/SamplePolymorphicRequestTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/dto/request/SamplePolymorphicRequestTest.java @@ -1,7 +1,7 @@ package dev.caskeleton.sample.portfolio.adapter.inbound.web.dto.request; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; @@ -22,57 +22,72 @@ class SamplePolymorphicRequestTest { @Test void allowlistedTextSubtypeDeserializes() throws Exception { + // given String json = """ {"kind":"text","title":"hello","body":"world"} """; + // when SamplePolymorphicRequest req = mapper.readValue(json, SamplePolymorphicRequest.class); - assertThat(req).isInstanceOf(SamplePolymorphicRequest.Text.class); - assertThat(((SamplePolymorphicRequest.Text) req).title()).isEqualTo("hello"); - assertThat(((SamplePolymorphicRequest.Text) req).body()).isEqualTo("world"); + // then + assertThat(req).isEqualTo(new SamplePolymorphicRequest.Text("hello", "world")); } @Test void allowlistedImageSubtypeDeserializes() throws Exception { + // given String json = """ {"kind":"image","title":"avatar","imageUrl":"https://example.test/a.png"} """; + // when SamplePolymorphicRequest req = mapper.readValue(json, SamplePolymorphicRequest.class); - assertThat(req).isInstanceOf(SamplePolymorphicRequest.Image.class); - assertThat(((SamplePolymorphicRequest.Image) req).imageUrl()) - .isEqualTo("https://example.test/a.png"); + // then + assertThat(req) + .isEqualTo(new SamplePolymorphicRequest.Image("avatar", "https://example.test/a.png")); } @Test void unknownSubtypeIdIsRejected() { + // given String json = """ {"kind":"video","title":"x","url":"y"} """; - assertThatThrownBy(() -> mapper.readValue(json, SamplePolymorphicRequest.class)) + // when + Throwable thrown = catchThrowable(() -> mapper.readValue(json, SamplePolymorphicRequest.class)); + + // then + assertThat(thrown) .as( "B5: discriminator outside the @JsonSubTypes allowlist must throw, " + "preventing arbitrary-class deserialization") - .isInstanceOf(InvalidTypeIdException.class); + .isInstanceOf(InvalidTypeIdException.class) + .hasMessageContaining("Could not resolve type id 'video'"); } @Test void missingDiscriminatorIsRejected() { + // given String json = """ {"title":"hello","body":"world"} """; - assertThatThrownBy(() -> mapper.readValue(json, SamplePolymorphicRequest.class)) + // when + Throwable thrown = catchThrowable(() -> mapper.readValue(json, SamplePolymorphicRequest.class)); + + // then + assertThat(thrown) .as( "B5: payloads without the type discriminator must not silently bind " + "to a default subtype") - .isInstanceOf(JsonMappingException.class); + .isInstanceOf(JsonMappingException.class) + .hasMessageContaining("missing type id property 'kind'"); } } diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/dto/response/BulkEnvelopeTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/dto/response/BulkEnvelopeTest.java index 7dff1b7a..f0d7b62a 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/dto/response/BulkEnvelopeTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/dto/response/BulkEnvelopeTest.java @@ -6,8 +6,6 @@ import dev.caskeleton.shared.response.BulkEnvelope; import dev.caskeleton.shared.response.BulkItemResult; import dev.caskeleton.shared.response.ResponseMeta; import java.util.List; -import org.assertj.core.api.InstanceOfAssertFactories; -import org.assertj.core.groups.Tuple; import org.junit.jupiter.api.Test; /** @@ -22,54 +20,67 @@ class BulkEnvelopeTest { @Test void allSuccessProducesSuccessTrueEnvelope() { - BulkEnvelope env = - BulkEnvelope.allOk(List.of("a", "b", "c"), new ResponseMeta("req-1", "trace-1", "corr-1")); + // given + ResponseMeta meta = new ResponseMeta("req-1", "trace-1", "corr-1"); - assertThat(env.success()).isTrue(); - assertThat(env.error()).as("success envelope must not carry error info").isNull(); - assertThat(env.results()).containsExactly("a", "b", "c"); - assertThat(env.meta().traceId()).isEqualTo("trace-1"); + // when + BulkEnvelope env = BulkEnvelope.allOk(List.of("a", "b", "c"), meta); + + // then + assertThat(env) + .as("success envelope carries results[] and no error info") + .isEqualTo(new BulkEnvelope<>(true, List.of("a", "b", "c"), null, meta)); } @Test void partialFailureProducesBatchPartialFailureCodeWithDetails() { - BulkEnvelope env = - BulkEnvelope.partial( - List.of( - BulkItemResult.ok(0, "id-1"), - BulkItemResult.error(1, "DUPLICATE_EMAIL", "email already taken"), - BulkItemResult.ok(2, "id-3")), - new ResponseMeta("req-2", "trace-2", "corr-2")); + // given + List details = + List.of( + BulkItemResult.ok(0, "id-1"), + BulkItemResult.error(1, "DUPLICATE_EMAIL", "email already taken"), + BulkItemResult.ok(2, "id-3")); - assertThat(env.success()).as("partial failure must NOT report success = true").isFalse(); - assertThat(env.results()).as("partial envelope must carry details[], not results[]").isNull(); - assertThat(env.error().code()).isEqualTo("BATCH_PARTIAL_FAILURE"); - assertThat(env.error().retryable()) - .as("BATCH_PARTIAL_FAILURE is per-item; not a transient retryable signal") - .isFalse(); - assertThat(env.error().details()) - .asInstanceOf(InstanceOfAssertFactories.list(BulkItemResult.class)) - .extracting(BulkItemResult::index, BulkItemResult::status) - .containsExactly(Tuple.tuple(0, "ok"), Tuple.tuple(1, "error"), Tuple.tuple(2, "ok")); + // when + BulkEnvelope env = + BulkEnvelope.partial(details, new ResponseMeta("req-2", "trace-2", "corr-2")); + + // then + assertThat(env) + .as( + "partial failure must NOT report success = true, must carry details[] instead of " + + "results[], and BATCH_PARTIAL_FAILURE is per-item, not a retryable signal") + .extracting( + BulkEnvelope::success, + BulkEnvelope::results, + e -> e.error().code(), + e -> e.error().retryable(), + e -> e.error().details()) + .containsExactly(false, null, "BATCH_PARTIAL_FAILURE", false, details); } @Test void allFailuresTakeTheSameBranchAsPartial() { - BulkEnvelope env = - BulkEnvelope.partial( - List.of( - BulkItemResult.error(0, "VALIDATION_FAILED", "name blank"), - BulkItemResult.error(1, "VALIDATION_FAILED", "name blank")), - new ResponseMeta("req-3", "trace-3", "corr-3")); + // given + List details = + List.of( + BulkItemResult.error(0, "VALIDATION_FAILED", "name blank"), + BulkItemResult.error(1, "VALIDATION_FAILED", "name blank")); - assertThat(env.success()).isFalse(); - assertThat(env.error().code()).isEqualTo("BATCH_PARTIAL_FAILURE"); - assertThat(env.error().details()) + // when + BulkEnvelope env = + BulkEnvelope.partial(details, new ResponseMeta("req-3", "trace-3", "corr-3")); + + // then + assertThat(env) .as( "all-failure case must use the same envelope shape as partial — " + "callers should not have to handle a third variant") - .asInstanceOf(InstanceOfAssertFactories.list(BulkItemResult.class)) - .hasSize(2) - .allMatch(d -> "error".equals(d.status())); + .extracting( + BulkEnvelope::success, + BulkEnvelope::results, + e -> e.error().code(), + e -> e.error().details()) + .containsExactly(false, null, "BATCH_PARTIAL_FAILURE", details); } } diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/error/DomainExceptionHandlerTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/error/DomainExceptionHandlerTest.java index 8c605574..66e802b9 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/error/DomainExceptionHandlerTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/error/DomainExceptionHandlerTest.java @@ -9,6 +9,7 @@ import dev.caskeleton.sample.portfolio.domain.poster.PosterId; import dev.caskeleton.sample.portfolio.domain.poster.PosterInvariantException; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogId; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogInvariantException; +import dev.caskeleton.shared.response.ApiError; import dev.caskeleton.shared.response.Envelope; import org.junit.jupiter.api.Test; import org.springframework.http.HttpStatus; @@ -16,68 +17,94 @@ import org.springframework.http.ResponseEntity; class DomainExceptionHandlerTest { + private static final String WORK_LOG_ID = "0190bd6e-7c3e-7abc-8def-0123456789ab"; + private static final String POSTER_ID = "0190bd6e-7c3e-7abc-8def-fedcba987654"; + private static final String SECRET_TITLE = "SECRET_CUSTOMER_PROJECT_TITLE"; + private final DomainExceptionHandler handler = new DomainExceptionHandler(); @Test - void worklogNotFoundMapsTo404Envelope() { - String id = "0190bd6e-7c3e-7abc-8def-0123456789ab"; + void workLogNotFoundMapsTo404EnvelopeWithoutTheId() { + // when ResponseEntity> response = - handler.handleWorkLogNotFound(new WorkLogNotFoundException(WorkLogId.of(id))); - assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); - assertThat(response.getBody()).isNotNull(); - assertThat(response.getBody().success()).isFalse(); - assertThat(response.getBody().error().code()).isEqualTo("WORKLOG_NOT_FOUND"); - assertThat(response.getBody().error().message()).isEqualTo("Work log was not found"); - assertThat(response.getBody().error().toString()).doesNotContain(id); + handler.handleWorkLogNotFound(new WorkLogNotFoundException(WorkLogId.of(WORK_LOG_ID))); + + // then + assertThat(response) + .extracting( + ResponseEntity::getStatusCode, + r -> r.getBody().success(), + r -> r.getBody().error(), + r -> r.getBody().error().toString().contains(WORK_LOG_ID)) + .containsExactly( + HttpStatus.NOT_FOUND, + false, + new ApiError("WORKLOG_NOT_FOUND", "NOT_FOUND", "Work log was not found", false, null), + false); } @Test - void domainConflictMessagesExposeNoExceptionDiagnostics() { - ResponseEntity> workLog = + void workLogInvariantUsesAFixedMessageWithoutTheReason() { + // when + ResponseEntity> response = handler.handleWorkLogInvariant( new WorkLogInvariantException( WorkLogInvariantException.Reason.CLOSED_WORKLOG_MUTATION)); - ResponseEntity> poster = + + // then + assertThat(response.getBody().error().message()) + .isEqualTo("Work log conflicts with the current state") + .doesNotContain("CLOSED_WORKLOG_MUTATION"); + } + + @Test + void posterInvariantUsesAFixedMessageWithoutTheReason() { + // when + ResponseEntity> response = handler.handlePosterInvariant( new PosterInvariantException( PosterInvariantException.Reason.INVALID_STATUS_TRANSITION)); - assertThat(workLog.getBody()).isNotNull(); - assertThat(workLog.getBody().error().message()) - .isEqualTo("Work log conflicts with the current state"); - assertThat(workLog.getBody().error().message()).doesNotContain("CLOSED_WORKLOG_MUTATION"); - assertThat(poster.getBody()).isNotNull(); - assertThat(poster.getBody().error().message()) - .isEqualTo("Poster is not valid in the current state"); - assertThat(poster.getBody().error().message()).doesNotContain("INVALID_STATUS_TRANSITION"); + // then + assertThat(response.getBody().error().message()) + .isEqualTo("Poster is not valid in the current state") + .doesNotContain("INVALID_STATUS_TRANSITION"); } @Test - void posterIdentifiersAndDuplicateTitlesDoNotReachPublicMessages() { - String id = "0190bd6e-7c3e-7abc-8def-fedcba987654"; - String title = "SECRET_CUSTOMER_PROJECT_TITLE"; + void posterNotFoundUsesAFixedMessageWithoutTheId() { + // when + ResponseEntity> response = + handler.handlePosterNotFound(new PosterNotFoundException(PosterId.of(POSTER_ID))); - ResponseEntity> notFound = - handler.handlePosterNotFound(new PosterNotFoundException(PosterId.of(id))); - ResponseEntity> duplicate = - handler.handlePosterTitleConflict(new PosterTitleAlreadyExistsException(title)); + // then + assertThat(response.getBody().error()) + .extracting(ApiError::message, error -> error.toString().contains(POSTER_ID)) + .containsExactly("Poster was not found", false); + } - assertThat(notFound.getBody()).isNotNull(); - assertThat(notFound.getBody().error().message()).isEqualTo("Poster was not found"); - assertThat(notFound.getBody().error().toString()).doesNotContain(id); - assertThat(duplicate.getBody()).isNotNull(); - assertThat(duplicate.getBody().error().message()).isEqualTo("Poster title is already in use"); - assertThat(duplicate.getBody().error().toString()).doesNotContain(title); + @Test + void duplicatePosterTitleUsesAFixedMessageWithoutTheTitle() { + // when + ResponseEntity> response = + handler.handlePosterTitleConflict(new PosterTitleAlreadyExistsException(SECRET_TITLE)); + + // then + assertThat(response.getBody().error()) + .extracting(ApiError::message, error -> error.toString().contains(SECRET_TITLE)) + .containsExactly("Poster title is already in use", false); } @Test void posterImageInvariantUsesFixedCorrectiveMessage() { + // when ResponseEntity> response = handler.handlePosterInvariant( new PosterInvariantException(PosterInvariantException.Reason.IMAGE_REQUIRED)); - assertThat(response.getBody()).isNotNull(); - assertThat(response.getBody().error().code()).isEqualTo("POSTER_IMAGE_REQUIRED"); - assertThat(response.getBody().error().message()).isEqualTo("Poster image is required"); + // then + assertThat(response.getBody().error()) + .extracting(ApiError::code, ApiError::message) + .containsExactly("POSTER_IMAGE_REQUIRED", "Poster image is required"); } } diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/error/PortfolioErrorCodeRegistryMappingTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/error/PortfolioErrorCodeRegistryMappingTest.java index cfd43c39..dc3539cd 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/error/PortfolioErrorCodeRegistryMappingTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/error/PortfolioErrorCodeRegistryMappingTest.java @@ -1,16 +1,18 @@ package dev.caskeleton.sample.portfolio.adapter.inbound.web.error; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.InvalidPathException; import java.nio.file.Path; +import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.yaml.snakeyaml.Yaml; @@ -39,19 +41,25 @@ class PortfolioErrorCodeRegistryMappingTest { @Test void sampleErrorCodesPresentInTheRegistryMatchTheirHttpStatus() { - for (PortfolioErrorCode code : PortfolioErrorCode.values()) { - Integer registryStatus = registryHttpStatusByCode.get(code.code()); - if (registryStatus != null) { - assertThat(code.httpStatus()) - .as("sample enum %s httpStatus must match error-codes.yaml", code.code()) - .isEqualTo(registryStatus); - } - } + // when + Map sampleStatusByRegisteredCode = + Arrays.stream(PortfolioErrorCode.values()) + .filter(code -> registryHttpStatusByCode.containsKey(code.code())) + .collect(Collectors.toMap(PortfolioErrorCode::code, PortfolioErrorCode::httpStatus)); + + // then + assertThat(registryHttpStatusByCode) + .as("sample enum httpStatus must match error-codes.yaml for every registered code") + .containsAllEntriesOf(sampleStatusByRegisteredCode); } @Test void missingRepositoryRootFailsClosedInsteadOfSkippingTheRegistryContract() { - assertThatThrownBy(() -> requireRegistry(null)) + // when + Throwable thrown = catchThrowable(() -> requireRegistry(null)); + + // then + assertThat(thrown) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("ca.repository.root"); } diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/error/PortfolioErrorCodeTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/error/PortfolioErrorCodeTest.java index d1c14e6d..f58fe7cc 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/error/PortfolioErrorCodeTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/error/PortfolioErrorCodeTest.java @@ -8,9 +8,12 @@ import org.junit.jupiter.api.Test; class PortfolioErrorCodeTest { @Test - void worklogNotFoundIsNotFoundCategory404() { - assertThat(PortfolioErrorCode.WORKLOG_NOT_FOUND.category()).isEqualTo(Category.NOT_FOUND); - assertThat(PortfolioErrorCode.WORKLOG_NOT_FOUND.httpStatus()).isEqualTo(404); - assertThat(PortfolioErrorCode.WORKLOG_NOT_FOUND.retryable()).isFalse(); + void workLogNotFoundIsANonRetryableNotFoundWithStatus404() { + assertThat(PortfolioErrorCode.WORKLOG_NOT_FOUND) + .extracting( + PortfolioErrorCode::category, + PortfolioErrorCode::httpStatus, + PortfolioErrorCode::retryable) + .containsExactly(Category.NOT_FOUND, 404, false); } } diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/filter/VirtualThreadMdcPropagationTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/filter/VirtualThreadMdcPropagationTest.java index 4909a489..f61bb350 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/filter/VirtualThreadMdcPropagationTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/filter/VirtualThreadMdcPropagationTest.java @@ -2,9 +2,11 @@ package dev.caskeleton.sample.portfolio.adapter.inbound.web.filter; import static org.assertj.core.api.Assertions.assertThat; -import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicReference; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.slf4j.MDC; @@ -33,57 +35,46 @@ import org.slf4j.MDC; */ class VirtualThreadMdcPropagationTest { - @Test - void mdcValueSetInAVirtualThreadIsVisibleLaterOnThatSameThread() throws InterruptedException { - CountDownLatch done = new CountDownLatch(1); - AtomicReference observed = new AtomicReference<>(); - AtomicReference ranOnVirtualThread = new AtomicReference<>(); + /** What a virtual-thread body saw: whether it really was virtual, and its MDC value. */ + private record Observation(boolean ranOnVirtualThread, String requestId) {} - Thread vt = - Thread.startVirtualThread( + @AfterEach + void clearCallerMdc() { + MDC.clear(); + } + + @Test + void mdcValueSetInAVirtualThreadIsVisibleLaterOnThatSameThread() throws Exception { + // when + Observation observed = + onAFreshVirtualThread( () -> { try { MDC.put("request_id", "req-abc"); // Simulated handler body — still on the same virtual thread. - ranOnVirtualThread.set(Thread.currentThread().isVirtual()); - observed.set(MDC.get("request_id")); + return new Observation(Thread.currentThread().isVirtual(), MDC.get("request_id")); } finally { MDC.clear(); - done.countDown(); } }); - assertThat(done.await(2, TimeUnit.SECONDS)) - .as("virtual thread must complete within timeout") - .isTrue(); - vt.join(); - assertThat(ranOnVirtualThread.get()) - .as("test precondition: the body really ran on a virtual thread") - .isTrue(); - assertThat(observed.get()) - .as("same-thread MDC propagation under virtual threads") - .isEqualTo("req-abc"); + // then + assertThat(observed) + .as("same-thread MDC propagation, on a body that really ran on a virtual thread") + .isEqualTo(new Observation(true, "req-abc")); } @Test - void mdcIsNotSilentlyInheritedByAFreshlySpawnedVirtualThread() throws InterruptedException { - AtomicReference childMdcValue = new AtomicReference<>("not-set"); + void mdcIsNotSilentlyInheritedByAFreshlySpawnedVirtualThread() throws Exception { + // given + MDC.put("request_id", "parent-req"); - try { - MDC.put("request_id", "parent-req"); + // when + // Fresh virtual thread spawned without explicit context capture. + String childMdcValue = onAFreshVirtualThread(() -> MDC.get("request_id")); - Thread child = - Thread.startVirtualThread( - () -> { - // Fresh virtual thread spawned without explicit context capture. - childMdcValue.set(MDC.get("request_id")); - }); - child.join(2_000); - } finally { - MDC.clear(); - } - - assertThat(childMdcValue.get()) + // then + assertThat(childMdcValue) .as( "MDC must not propagate by inheritance (B6) — code crossing thread " + "boundaries must capture context explicitly via Micrometer Context " @@ -91,4 +82,11 @@ class VirtualThreadMdcPropagationTest { + "contract.") .isNull(); } + + /** Runs {@code body} on a new virtual thread; fails the test if it does not finish in time. */ + private static T onAFreshVirtualThread(Callable body) throws Exception { + try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) { + return executor.submit(body).get(2, TimeUnit.SECONDS); + } + } } diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/objectstorage/MultipartObjectContentProducerTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/objectstorage/MultipartObjectContentProducerTest.java index 9b50ab53..a1b15cfd 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/objectstorage/MultipartObjectContentProducerTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/objectstorage/MultipartObjectContentProducerTest.java @@ -1,63 +1,109 @@ package dev.caskeleton.sample.portfolio.adapter.inbound.web.objectstorage; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.junit.jupiter.api.Named.named; +import static org.junit.jupiter.params.provider.Arguments.arguments; import dev.caskeleton.application.objectstorage.content.CancellationView; import dev.caskeleton.application.objectstorage.content.ObjectContentProductionContext; +import dev.caskeleton.application.objectstorage.content.ObjectContentProductionException; import dev.caskeleton.application.objectstorage.model.ObjectContentIdentity; import dev.caskeleton.application.objectstorage.model.ObjectDigest; import dev.caskeleton.application.outbound.CallBudget; -import java.io.ByteArrayOutputStream; import java.nio.charset.StandardCharsets; import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Stream; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.springframework.mock.web.MockMultipartFile; class MultipartObjectContentProducerTest { + private static final byte[] CONTENT = "hello-stream".getBytes(StandardCharsets.UTF_8); + + private final MultipartObjectContentProducer producer = + new MultipartObjectContentProducer( + new MockMultipartFile("file", "image.png", "image/png", CONTENT), + new ObjectContentIdentity(CONTENT.length, ObjectDigest.sha256(CONTENT))); + @Test - void streamsBoundedChunksAndRejectsAnyUseAfterTheRequestBoundCallback() throws Exception { - byte[] content = "hello-stream".getBytes(StandardCharsets.UTF_8); - var expected = new ObjectContentIdentity(content.length, ObjectDigest.sha256(content)); - var producer = - new MultipartObjectContentProducer( - new MockMultipartFile("file", "image.png", "image/png", content), expected); - var context = - ObjectContentProductionContext.open( - CallBudget.fromNow(Duration.ofMinutes(1)), CancellationView.never(), 4); - ByteArrayOutputStream delivered = new ByteArrayOutputStream(); + void streamsTheExactContentInChunksNoLargerThanTheContextMaximum() throws Exception { + // given + List chunks = new ArrayList<>(); + // when producer.produce( - context, - (bytes, offset, length) -> { - assertThat(length).isLessThanOrEqualTo(4); - delivered.write(bytes, offset, length); - }); - context.invalidate(); + contextWithMaximumChunkBytes(4), + (bytes, offset, length) -> + chunks.add(new String(bytes, offset, length, StandardCharsets.UTF_8))); - assertThat(delivered.toByteArray()).containsExactly(content); - assertThatThrownBy( - () -> - producer.produce( - ObjectContentProductionContext.open( - CallBudget.fromNow(Duration.ofMinutes(1)), CancellationView.never(), 4), - (bytes, offset, length) -> {})) + // then + assertThat(chunks).containsExactly("hell", "o-st", "ream"); + } + + @Test + void rejectsAnyUseAfterTheRequestBoundCallback() throws Exception { + // given + ObjectContentProductionContext requestBound = contextWithMaximumChunkBytes(4); + producer.produce(requestBound, (bytes, offset, length) -> {}); + requestBound.invalidate(); + + // when + Throwable thrown = + catchThrowable( + () -> producer.produce(contextWithMaximumChunkBytes(4), (bytes, offset, length) -> {})); + + // then + assertThat(thrown) + .isInstanceOf(ObjectContentProductionException.class) .hasMessageContaining("already consumed"); } - @Test - void exactLengthOrSha256MismatchFailsClosed() { - byte[] content = "hello".getBytes(StandardCharsets.UTF_8); - var producer = - new MultipartObjectContentProducer( - new MockMultipartFile("file", content), - new ObjectContentIdentity(content.length, ObjectDigest.sha256(new byte[] {1}))); - var context = - ObjectContentProductionContext.open( - CallBudget.fromNow(Duration.ofMinutes(1)), CancellationView.never(), 8); + static Stream mismatchedDeclarations() { + return Stream.of( + arguments( + named( + "sha-256 mismatch", + new ObjectContentIdentity(CONTENT.length, ObjectDigest.sha256(new byte[] {1}))), + "does not match"), + arguments( + named( + "declared length longer than the content", + new ObjectContentIdentity(CONTENT.length + 1, ObjectDigest.sha256(CONTENT))), + "does not match"), + arguments( + named( + "declared length shorter than the content", + new ObjectContentIdentity(CONTENT.length - 1, ObjectDigest.sha256(CONTENT))), + "exceeds its declared length")); + } - assertThatThrownBy(() -> producer.produce(context, (bytes, offset, length) -> {})) - .hasMessageContaining("does not match"); + @ParameterizedTest + @MethodSource("mismatchedDeclarations") + void exactLengthOrSha256MismatchFailsClosed(ObjectContentIdentity declared, String reason) { + // given + var mismatched = + new MultipartObjectContentProducer(new MockMultipartFile("file", CONTENT), declared); + + // when + Throwable thrown = + catchThrowable( + () -> + mismatched.produce(contextWithMaximumChunkBytes(8), (bytes, offset, length) -> {})); + + // then + assertThat(thrown) + .isInstanceOf(ObjectContentProductionException.class) + .hasMessageContaining(reason); + } + + private static ObjectContentProductionContext contextWithMaximumChunkBytes(int maximum) { + return ObjectContentProductionContext.open( + CallBudget.fromNow(Duration.ofMinutes(1)), CancellationView.never(), maximum); } } diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/versioning/VersioningPrefixTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/versioning/VersioningPrefixTest.java index 34b5ecbb..e8cb2dfe 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/versioning/VersioningPrefixTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/versioning/VersioningPrefixTest.java @@ -15,6 +15,7 @@ import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest; import org.springframework.context.annotation.Import; import org.springframework.test.context.TestPropertySource; import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.ResultActions; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @@ -38,12 +39,20 @@ class VersioningPrefixTest { @Test void endpointIsReachableUnderTheVersionPrefix() throws Exception { - mvc.perform(get("/v1/probe")).andExpect(status().isOk()); + // when + ResultActions result = mvc.perform(get("/v1/probe")); + + // then + result.andExpect(status().isOk()); } @Test void unversionedPathIsNotExposed() throws Exception { - mvc.perform(get("/probe")).andExpect(status().isNotFound()); + // when + ResultActions result = mvc.perform(get("/probe")); + + // then + result.andExpect(status().isNotFound()); } @RestController diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/outbound/identifier/HmacPosterImageIdempotencyScopeDigesterTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/outbound/identifier/HmacPosterImageIdempotencyScopeDigesterTest.java index 178c4cb3..dd650e04 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/outbound/identifier/HmacPosterImageIdempotencyScopeDigesterTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/outbound/identifier/HmacPosterImageIdempotencyScopeDigesterTest.java @@ -2,47 +2,90 @@ package dev.caskeleton.sample.portfolio.adapter.outbound.identifier; import static org.assertj.core.api.Assertions.assertThat; +import dev.caskeleton.sample.portfolio.application.posterimage.PosterImageIdempotencyScopeDigest; import java.nio.charset.StandardCharsets; import java.util.LinkedHashMap; +import java.util.List; import java.util.Map; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; class HmacPosterImageIdempotencyScopeDigesterTest { - @Test - void lengthPrefixAndTenantPresencePreventAmbiguousScopeCollisions() { - HmacPosterImageIdempotencyScopeDigester digester = - new HmacPosterImageIdempotencyScopeDigester( - "key-v1", - Map.of("key-v1", "0123456789abcdef0123456789abcdef".getBytes(StandardCharsets.UTF_8))); + private static final byte[] KEY_V1 = + "0123456789abcdef0123456789abcdef".getBytes(StandardCharsets.UTF_8); + private static final byte[] KEY_V2 = + "abcdef0123456789abcdef0123456789".getBytes(StandardCharsets.UTF_8); - var first = + private final HmacPosterImageIdempotencyScopeDigester digester = + new HmacPosterImageIdempotencyScopeDigester("key-v1", Map.of("key-v1", KEY_V1)); + + @ParameterizedTest + @CsvSource( + nullValues = "none", + value = { + // same concatenation as the reference scope, different field boundaries + "none, principal-secret-a, buse-case-secret-c", + // reference scope plus a tenant + "tenant-secret-a, principal-secret-ab, use-case-secret-c" + }) + void lengthPrefixAndTenantPresencePreventAmbiguousScopeCollisions( + String tenant, String principal, String useCase) { + // given + PosterImageIdempotencyScopeDigest reference = digester.digest(null, "principal-secret-ab", "use-case-secret-c", "idempotency-secret-d"); - var ambiguous = - digester.digest(null, "principal-secret-a", "buse-case-secret-c", "idempotency-secret-d"); - var tenant = - digester.digest( - "tenant-secret-a", "principal-secret-ab", "use-case-secret-c", "idempotency-secret-d"); - assertThat(first).isNotEqualTo(ambiguous).isNotEqualTo(tenant); - assertThat(first.toString()) + // when + PosterImageIdempotencyScopeDigest other = + digester.digest(tenant, principal, useCase, "idempotency-secret-d"); + + // then + assertThat(other).isNotEqualTo(reference); + } + + @Test + void digestStringDoesNotRevealTheScopeInputs() { + // when + PosterImageIdempotencyScopeDigest digest = + digester.digest(null, "principal-secret-ab", "use-case-secret-c", "idempotency-secret-d"); + + // then + assertThat(digest.toString()) .doesNotContain("principal-secret-ab", "use-case-secret-c", "idempotency-secret-d"); } @Test - void retainedVersionsSupportOverlapFirstRotationWithoutChangingTheActiveDigest() { - Map keys = new LinkedHashMap<>(); - keys.put("key-v1", "0123456789abcdef0123456789abcdef".getBytes(StandardCharsets.UTF_8)); - keys.put("key-v2", "abcdef0123456789abcdef0123456789".getBytes(StandardCharsets.UTF_8)); - HmacPosterImageIdempotencyScopeDigester digester = - new HmacPosterImageIdempotencyScopeDigester(() -> "key-v2", keys); + void rotationKeepsDigestingWithTheActiveKeyVersion() { + // given + HmacPosterImageIdempotencyScopeDigester rotating = rotatingDigesterWithActiveV2(); - assertThat(digester.digest(null, "p", "u", "k").keyVersion()).isEqualTo("key-v2"); - assertThat(digester.retainedDigests(null, "p", "u", "k")) - .extracting( - dev.caskeleton.sample.portfolio.application.posterimage - .PosterImageIdempotencyScopeDigest - ::keyVersion) + // when + PosterImageIdempotencyScopeDigest active = rotating.digest(null, "p", "u", "k"); + + // then + assertThat(active.keyVersion()).isEqualTo("key-v2"); + } + + @Test + void retainedDigestsCoverEveryRetainedKeyVersionForOverlapFirstRotation() { + // given + HmacPosterImageIdempotencyScopeDigester rotating = rotatingDigesterWithActiveV2(); + + // when + List retained = + rotating.retainedDigests(null, "p", "u", "k"); + + // then + assertThat(retained) + .extracting(PosterImageIdempotencyScopeDigest::keyVersion) .containsExactly("key-v1", "key-v2"); } + + private static HmacPosterImageIdempotencyScopeDigester rotatingDigesterWithActiveV2() { + Map keys = new LinkedHashMap<>(); + keys.put("key-v1", KEY_V1); + keys.put("key-v2", KEY_V2); + return new HmacPosterImageIdempotencyScopeDigester(() -> "key-v2", keys); + } } diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/outbound/identifier/UuidWorkLogIdFactoryTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/outbound/identifier/UuidWorkLogIdFactoryTest.java index c53534d1..3f308548 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/outbound/identifier/UuidWorkLogIdFactoryTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/outbound/identifier/UuidWorkLogIdFactoryTest.java @@ -3,6 +3,8 @@ package dev.caskeleton.sample.portfolio.adapter.outbound.identifier; import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogId; +import java.util.List; +import java.util.stream.Stream; import org.junit.jupiter.api.Test; class UuidWorkLogIdFactoryTest { @@ -11,9 +13,11 @@ class UuidWorkLogIdFactoryTest { @Test void newIdProducesAValidCanonicalWorklogId() { + // when WorkLogId id = factory.newId(); - // WorkLogId's constructor enforces the canonical UUID pattern, so a successful - // construction proves the generated value is canonical. + + // then + // WorkLogId's constructor already enforces the canonical UUID pattern; the regex pins it here. assertThat(id.value()) .matches("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"); } @@ -28,14 +32,17 @@ class UuidWorkLogIdFactoryTest { // getTimeOrderedEpochPlus1 guarantees each UUIDv7 sorts strictly after the previous one // (time-ordered timestamp + monotonic counter). Because the canonical string is big-endian // lowercase hex with hyphens at fixed positions, lexicographic order matches numeric order. - // Looping makes the property observable within a single millisecond and would fail loudly if + // Many ids make the property observable within a single millisecond and would fail loudly if // the adapter were swapped to a non-monotonic generator — a two-element check would pass ~50% // of the time in that regression. - String previous = factory.newId().value(); - for (int i = 0; i < 1_000; i++) { - String current = factory.newId().value(); - assertThat(current).isGreaterThan(previous); - previous = current; - } + + // when + List ids = Stream.generate(() -> factory.newId().value()).limit(1_001).toList(); + + // then + assertThat(ids) + .as("sorted with no duplicates = strictly increasing") + .isSorted() + .doesNotHaveDuplicates(); } } diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/mapper/WorkLogPersistenceMapperTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/mapper/WorkLogPersistenceMapperTest.java index 824a1702..6e3bfb38 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/mapper/WorkLogPersistenceMapperTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/mapper/WorkLogPersistenceMapperTest.java @@ -18,7 +18,8 @@ class WorkLogPersistenceMapperTest { @Test void roundTripPreservesFieldsIncludingIdViaUuid() { - WorkLog w = + // given + WorkLog original = WorkLog.create( ID, "t", @@ -28,12 +29,38 @@ class WorkLogPersistenceMapperTest { List.of("java"), List.of("https://x"), new Period(LocalDate.of(2025, 1, 1), null)); - WorkLog back = WorkLogPersistenceMapper.toDomain(WorkLogPersistenceMapper.toEntity(w)); - assertThat(back.id()).isEqualTo(ID); // UUID string -> uuid -> UUID string is lossless (D10) - assertThat(back.title()).isEqualTo("t"); - assertThat(back.techStack()).containsExactly("java"); - assertThat(back.period().isOngoing()).isTrue(); - assertThat(back.status()).isEqualTo(WorkLogStatus.OPEN); - assertThat(back.owner()).isEqualTo(WorkLogOwner.of("sample-owner")); + + // when + WorkLog back = WorkLogPersistenceMapper.toDomain(WorkLogPersistenceMapper.toEntity(original)); + + // then + // UUID string -> uuid -> UUID string is lossless (D10) + assertThat(back) + .extracting( + WorkLog::id, + WorkLog::owner, + WorkLog::title, + WorkLog::category, + WorkLog::status, + WorkLog::summary, + WorkLog::content, + WorkLog::techStack, + WorkLog::links, + WorkLog::period, + w -> w.period().isOngoing(), + WorkLog::version) + .containsExactly( + ID, + WorkLogOwner.of("sample-owner"), + "t", + WorkCategory.BACKEND, + WorkLogStatus.OPEN, + "s", + "c", + List.of("java"), + List.of("https://x"), + new Period(LocalDate.of(2025, 1, 1), null), + true, + null); } } diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/WorkLogRepositoryAdapterTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/WorkLogRepositoryAdapterTest.java index 6450dd3a..cf8b63ce 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/WorkLogRepositoryAdapterTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/WorkLogRepositoryAdapterTest.java @@ -14,6 +14,7 @@ import dev.caskeleton.sample.portfolio.domain.worklog.Period; import dev.caskeleton.sample.portfolio.domain.worklog.WorkCategory; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLog; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogId; +import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogPage; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogSortField; import java.time.Clock; import java.time.Instant; @@ -29,6 +30,10 @@ import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; +/** + * Adapter logic over a mocked Spring Data repository; real PostgreSQL runs in the integrationTest + * lane. + */ class WorkLogRepositoryAdapterTest { private static final WorkLogId ID = WorkLogId.of("0190bd6e-7c3e-7abc-8def-0123456789ab"); @@ -67,85 +72,145 @@ class WorkLogRepositoryAdapterTest { } @Test - void saveMapsToEntityAndBack() { - WorkLog w = sample(); + void savingReturnsTheWorkLogMappedBackFromTheSavedEntity() { + // given + WorkLog workLog = sample(); when(jpa.save(any(WorkLogEntity.class))).thenAnswer(inv -> inv.getArgument(0)); - assertThat(adapter.save(w).id()).isEqualTo(w.id()); + + // when + WorkLog saved = adapter.save(workLog); + + // then + assertThat(saved).usingRecursiveComparison().isEqualTo(workLog); } @Test - void saveNewStampsCreatedAndUpdatedAuditWithClockAndActor() { + void savingANewWorkLogStampsCreatedAndUpdatedAuditWithClockAndActor() { // D1 Manual path / D4 Clock / D5 actor: a never-persisted aggregate (null version) // is an INSERT — created_* and updated_* both take now + actor. + // given when(auditContext.currentActor()).thenReturn("alice"); when(jpa.save(any(WorkLogEntity.class))).thenAnswer(inv -> inv.getArgument(0)); + // when adapter.save(sample()); - ArgumentCaptor saved = ArgumentCaptor.forClass(WorkLogEntity.class); - verify(jpa).save(saved.capture()); - // no existing-row read for an insert - verify(jpa, never()).findById(any()); - assertThat(saved.getValue().getCreatedAt()).isEqualTo(NOW); - assertThat(saved.getValue().getUpdatedAt()).isEqualTo(NOW); - assertThat(saved.getValue().getCreatedBy()).isEqualTo("alice"); - assertThat(saved.getValue().getUpdatedBy()).isEqualTo("alice"); + // then + assertThat(savedEntity()) + .extracting( + WorkLogEntity::getCreatedAt, + WorkLogEntity::getUpdatedAt, + WorkLogEntity::getCreatedBy, + WorkLogEntity::getUpdatedBy) + .containsExactly(NOW, NOW, "alice", "alice"); } @Test - void saveUpdatePreservesCreatedAndBumpsUpdatedAudit() { + void savingANewWorkLogDoesNotReadAnExistingRow() { + // given + when(jpa.save(any(WorkLogEntity.class))).thenAnswer(inv -> inv.getArgument(0)); + + // when + adapter.save(sample()); + + // then + verify(jpa, never()).findById(any()); + } + + @Test + void savingAPersistedWorkLogKeepsCreatedAuditAndBumpsUpdatedAudit() { // D2/D3: an already-persisted aggregate (non-null version) is an UPDATE — created_* // is carried from the persisted row, only updated_* moves to now + actor. + // given when(auditContext.currentActor()).thenReturn("bob"); WorkLogEntity existing = WorkLogPersistenceMapper.toEntity(persisted(1L)); existing.initializeAudit(EARLIER, "alice"); when(jpa.findById(WorkLogPersistenceMapper.toUuid(ID))).thenReturn(Optional.of(existing)); when(jpa.save(any(WorkLogEntity.class))).thenAnswer(inv -> inv.getArgument(0)); + // when adapter.save(persisted(1L)); - ArgumentCaptor saved = ArgumentCaptor.forClass(WorkLogEntity.class); - verify(jpa).save(saved.capture()); - assertThat(saved.getValue().getCreatedAt()).isEqualTo(EARLIER); - assertThat(saved.getValue().getCreatedBy()).isEqualTo("alice"); - assertThat(saved.getValue().getUpdatedAt()).isEqualTo(NOW); - assertThat(saved.getValue().getUpdatedBy()).isEqualTo("bob"); + // then + assertThat(savedEntity()) + .extracting( + WorkLogEntity::getCreatedAt, + WorkLogEntity::getCreatedBy, + WorkLogEntity::getUpdatedAt, + WorkLogEntity::getUpdatedBy) + .containsExactly(EARLIER, "alice", NOW, "bob"); } @Test - void findByIdConvertsIdStringToUuidAndMapsOptional() { - WorkLog w = sample(); + void findByIdLooksUpTheUuidAndMapsTheEntityToTheWorkLog() { + // given + WorkLog workLog = sample(); when(jpa.findById(WorkLogPersistenceMapper.toUuid(ID))) - .thenReturn(Optional.of(WorkLogPersistenceMapper.toEntity(w))); - assertThat(adapter.findById(ID)).isPresent(); + .thenReturn(Optional.of(WorkLogPersistenceMapper.toEntity(workLog))); + + // when + Optional found = adapter.findById(ID); + + // then + assertThat(found).get().usingRecursiveComparison().isEqualTo(workLog); } @Test - void findPageDelegatesSortedPagerequestAndMapsTotal() { - WorkLog w = sample(); + void findPageMapsTheItemsAndTheTotal() { + // given + stubFindAll(); + + // when + WorkLogPage result = adapter.findPage(2, 5, WorkLogSortField.TITLE, false, null); + + // then + assertThat(result) + .extracting(p -> p.items().stream().map(WorkLog::id).toList(), WorkLogPage::total) + .containsExactly(List.of(ID), 11L); + } + + @Test + void findPagePassesPageSizeAndSortDirectionToSpringData() { + // given + stubFindAll(); + + // when + adapter.findPage(2, 5, WorkLogSortField.TITLE, false, null); + + // then + ArgumentCaptor pageable = ArgumentCaptor.forClass(Pageable.class); + verify(jpa).findAll(pageable.capture()); + assertThat(pageable.getValue()) + .extracting( + Pageable::getPageNumber, + Pageable::getPageSize, + p -> p.getSort().getOrderFor("title").getDirection()) + .containsExactly(2, 5, Sort.Direction.DESC); + } + + @Test + void findPageWithACategoryQueriesByThatCategory() { + // given + when(jpa.findByCategory(eq(WorkCategory.DATABASE), any(Pageable.class))) + .thenReturn(new PageImpl<>(List.of(WorkLogPersistenceMapper.toEntity(sample())))); + + // when + WorkLogPage result = adapter.findPage(0, 20, null, true, WorkCategory.DATABASE); + + // then + assertThat(result.items()).extracting(WorkLog::id).containsExactly(ID); + } + + private void stubFindAll() { when(jpa.findAll(any(Pageable.class))) .thenReturn( new PageImpl<>( - List.of(WorkLogPersistenceMapper.toEntity(w)), PageRequest.of(2, 5), 11)); - var result = adapter.findPage(2, 5, WorkLogSortField.TITLE, false, null); - assertThat(result.items()).hasSize(1); - assertThat(result.items().get(0).id()).isEqualTo(w.id()); - assertThat(result.total()).isEqualTo(11); - ArgumentCaptor cap = ArgumentCaptor.forClass(Pageable.class); - verify(jpa).findAll(cap.capture()); - assertThat(cap.getValue().getPageNumber()).isEqualTo(2); - assertThat(cap.getValue().getPageSize()).isEqualTo(5); - assertThat(cap.getValue().getSort().getOrderFor("title").getDirection()) - .isEqualTo(Sort.Direction.DESC); + List.of(WorkLogPersistenceMapper.toEntity(sample())), PageRequest.of(2, 5), 11)); } - @Test - void findPageWithCategoryFilterDelegatesToFindByCategory() { - WorkLog w = sample(); - when(jpa.findByCategory(eq(WorkCategory.DATABASE), any(Pageable.class))) - .thenReturn(new PageImpl<>(List.of(WorkLogPersistenceMapper.toEntity(w)))); - var result = adapter.findPage(0, 20, null, true, WorkCategory.DATABASE); - assertThat(result.items()).hasSize(1); - verify(jpa).findByCategory(eq(WorkCategory.DATABASE), any(Pageable.class)); + private WorkLogEntity savedEntity() { + ArgumentCaptor saved = ArgumentCaptor.forClass(WorkLogEntity.class); + verify(jpa).save(saved.capture()); + return saved.getValue(); } } diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/WorkLogSummaryQueryAdapterTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/WorkLogSummaryQueryAdapterTest.java index 1362415f..b3e80e9b 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/WorkLogSummaryQueryAdapterTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/WorkLogSummaryQueryAdapterTest.java @@ -2,6 +2,7 @@ package dev.caskeleton.sample.portfolio.adapter.outbound.persistence.repository; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import dev.caskeleton.sample.portfolio.application.query.WorkLogSummary; @@ -12,6 +13,7 @@ import java.util.UUID; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; +import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; @@ -25,6 +27,7 @@ class WorkLogSummaryQueryAdapterTest { @Test void mapsRowUuidBackToCanonicalUuidString() { + // given when(jpa.findRecentSummaryRows(any(Pageable.class))) .thenReturn( List.of( @@ -35,29 +38,28 @@ class WorkLogSummaryQueryAdapterTest { LocalDate.of(2025, 1, 1), null))); + // when List result = adapter.findRecentSummaries(5); - assertThat(result).hasSize(1); - WorkLogSummary summary = result.get(0); - assertThat(summary.id()).isEqualTo(ID); - assertThat(summary.title()).isEqualTo("Tuned Hikari pool"); - assertThat(summary.category()).isEqualTo(WorkCategory.DATABASE); - assertThat(summary.periodStart()).isEqualTo(LocalDate.of(2025, 1, 1)); - assertThat(summary.periodEnd()).isNull(); + // then + assertThat(result) + .containsExactly( + new WorkLogSummary( + ID, "Tuned Hikari pool", WorkCategory.DATABASE, LocalDate.of(2025, 1, 1), null)); } @Test - void buildsPagerequestWithClampedLimitSortedByPeriodDesc() { + void nonPositiveLimitIsClampedToOneFirstPageSortedByPeriodStartDescending() { + // given when(jpa.findRecentSummaryRows(any(Pageable.class))).thenReturn(List.of()); + ArgumentCaptor pageable = ArgumentCaptor.forClass(Pageable.class); - adapter.findRecentSummaries(0); // non-positive → clamped to 1 + // when + adapter.findRecentSummaries(0); - ArgumentCaptor captor = ArgumentCaptor.forClass(Pageable.class); - Mockito.verify(jpa).findRecentSummaryRows(captor.capture()); - Pageable pageable = captor.getValue(); - assertThat(pageable.getPageNumber()).isZero(); - assertThat(pageable.getPageSize()).isEqualTo(1); - assertThat(pageable.getSort().getOrderFor("periodStart").getDirection()) - .isEqualTo(Sort.Direction.DESC); + // then + verify(jpa).findRecentSummaryRows(pageable.capture()); + assertThat(pageable.getValue()) + .isEqualTo(PageRequest.of(0, 1, Sort.by(Sort.Direction.DESC, "periodStart"))); } } diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/outbound/repostats/RepoStatsAclMapperTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/outbound/repostats/RepoStatsAclMapperTest.java index ff7751a8..b783c1c0 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/outbound/repostats/RepoStatsAclMapperTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/outbound/repostats/RepoStatsAclMapperTest.java @@ -1,45 +1,64 @@ package dev.caskeleton.sample.portfolio.adapter.outbound.repostats; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; import dev.caskeleton.sample.portfolio.domain.worklog.RepoStats; import dev.caskeleton.shared.error.MappingException; import java.util.Locale; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.NullAndEmptySource; +import org.junit.jupiter.params.provider.ValueSource; class RepoStatsAclMapperTest { + private final Locale originalDefault = Locale.getDefault(); + + @AfterEach + void restoreDefaultLocale() { + Locale.setDefault(originalDefault); + } + @Test - void mapsAndNormalizes() { - RepoStats s = + void mapsPublicFieldsAndLowercasesTheFullName() { + // when + RepoStats stats = RepoStatsAclMapper.toDomain( new RawRepoStatsResponse("Owner/Repo", 1200, "2025-01-02T03:04:05Z", "secret-token")); - assertThat(s.fullName()).isEqualTo("owner/repo"); - assertThat(s.stars()).isEqualTo(1200); - assertThat(s.lastPushedIso()).isEqualTo("2025-01-02T03:04:05Z"); + + // then + assertThat(stats).isEqualTo(new RepoStats("owner/repo", 1200, "2025-01-02T03:04:05Z")); } @Test void normalizesRepositoryNameWithLocaleIndependentLowercase() { - Locale originalDefault = Locale.getDefault(); + // given Locale.setDefault(Locale.forLanguageTag("tr-TR")); - try { - RepoStats stats = - RepoStatsAclMapper.toDomain( - new RawRepoStatsResponse( - "OWNER/IDENTITY", 1200, "2025-01-02T03:04:05Z", "secret-token")); - assertThat(stats.fullName()).isEqualTo("owner/identity"); - } finally { - Locale.setDefault(originalDefault); - } + // when + RepoStats stats = + RepoStatsAclMapper.toDomain( + new RawRepoStatsResponse( + "OWNER/IDENTITY", 1200, "2025-01-02T03:04:05Z", "secret-token")); + + // then + assertThat(stats.fullName()).isEqualTo("owner/identity"); } - @Test - void missingFullNameThrowsMappingException() { - assertThatThrownBy( - () -> RepoStatsAclMapper.toDomain(new RawRepoStatsResponse(null, 0, "x", "t"))) - .isInstanceOf(MappingException.class); + @ParameterizedTest + @NullAndEmptySource + @ValueSource(strings = " ") + void missingFullNameThrowsMappingException(String fullName) { + // when + Throwable thrown = + catchThrowable( + () -> RepoStatsAclMapper.toDomain(new RawRepoStatsResponse(fullName, 0, "x", "t"))); + + // then + assertThat(thrown) + .isInstanceOf(MappingException.class) + .hasMessage("repo provider: missing 'fullName'"); } } diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/command/CommandSelfValidationTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/command/CommandSelfValidationTest.java index 11b87e1b..e2d25a99 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/command/CommandSelfValidationTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/command/CommandSelfValidationTest.java @@ -1,7 +1,8 @@ package dev.caskeleton.sample.portfolio.application.command; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.junit.jupiter.params.provider.Arguments.argumentSet; import dev.caskeleton.sample.portfolio.application.query.GetRepoStatsQuery; import dev.caskeleton.sample.portfolio.application.query.GetWorkLogQuery; @@ -10,7 +11,12 @@ import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogId; import dev.caskeleton.shared.request.Patch; import java.time.LocalDate; import java.util.List; +import java.util.stream.Stream; +import org.assertj.core.api.ThrowableAssert.ThrowingCallable; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; /** * Self-validating input models (Hombergs Ch4): commands/queries enforce their own invariants at @@ -22,60 +28,56 @@ class CommandSelfValidationTest { private static final WorkLogId ID = WorkLogId.of("0190bd6e-7c3e-7abc-8def-0123456789ab"); private static final LocalDate START = LocalDate.of(2025, 1, 1); - @Test - void createRejectsNullRequiredScalars() { - assertThatThrownBy( - () -> - new CreateWorkLogCommand( - "o", null, WorkCategory.DATABASE, "s", "c", List.of(), List.of(), START, null)) - .isInstanceOf(NullPointerException.class); - assertThatThrownBy( - () -> - new CreateWorkLogCommand( - "o", "t", null, "s", "c", List.of(), List.of(), START, null)) - .isInstanceOf(NullPointerException.class); - assertThatThrownBy( - () -> - new CreateWorkLogCommand( - "o", "t", WorkCategory.DATABASE, "s", "c", List.of(), List.of(), null, null)) - .isInstanceOf(NullPointerException.class); + @ParameterizedTest + @MethodSource("constructionsMissingARequiredValue") + void rejectsAMissingRequiredValueByName(ThrowingCallable construction, String requiredValue) { + // when + Throwable thrown = catchThrowable(construction); + + // then + assertThat(thrown).isInstanceOf(NullPointerException.class).hasMessage(requiredValue); + } + + static Stream constructionsMissingARequiredValue() { + return Stream.of( + missing("create without title", () -> create(null, WorkCategory.DATABASE, START), "title"), + missing("create without category", () -> create("t", null, START), "category"), + missing( + "create without periodStart", + () -> create("t", WorkCategory.DATABASE, null), + "periodStart"), + missing("update without id", () -> update(null, Patch.absent()), "id"), + missing("update without title patch", () -> update(ID, null), "title"), + missing("delete without id", () -> new DeleteWorkLogCommand(null), "id"), + missing("get without id", () -> new GetWorkLogQuery(null), "id"), + missing("repo stats without repoUrl", () -> new GetRepoStatsQuery(null), "repoUrl")); } @Test - void createDefaultsNullCollectionsToEmptyImmutable() { + void createDefaultsNullCollectionsToEmptyUnmodifiableLists() { + // when CreateWorkLogCommand cmd = new CreateWorkLogCommand( "o", "t", WorkCategory.DATABASE, "s", "c", null, null, START, null); - assertThat(cmd.techStack()).isEmpty(); - assertThat(cmd.links()).isEmpty(); - assertThatThrownBy(() -> cmd.techStack().add("x")) - .isInstanceOf(UnsupportedOperationException.class); + + // then + assertThat(List.of(cmd.techStack(), cmd.links())) + .allSatisfy(list -> assertThat(list).isUnmodifiable().isEmpty()); } - @Test - void updateRejectsNullIdAndNullPatches() { - assertThatThrownBy( - () -> - new UpdateWorkLogCommand( - null, - Patch.absent(), - Patch.absent(), - Patch.absent(), - Patch.absent(), - Patch.absent())) - .isInstanceOf(NullPointerException.class); - assertThatThrownBy( - () -> - new UpdateWorkLogCommand( - ID, null, Patch.absent(), Patch.absent(), Patch.absent(), Patch.absent())) - .isInstanceOf(NullPointerException.class); + private static Arguments missing( + String name, ThrowingCallable construction, String requiredValue) { + return argumentSet(name, construction, requiredValue); } - @Test - void deleteGetAndRepostatsRejectNull() { - assertThatThrownBy(() -> new DeleteWorkLogCommand(null)) - .isInstanceOf(NullPointerException.class); - assertThatThrownBy(() -> new GetWorkLogQuery(null)).isInstanceOf(NullPointerException.class); - assertThatThrownBy(() -> new GetRepoStatsQuery(null)).isInstanceOf(NullPointerException.class); + private static CreateWorkLogCommand create( + String title, WorkCategory category, LocalDate periodStart) { + return new CreateWorkLogCommand( + "o", title, category, "s", "c", List.of(), List.of(), periodStart, null); + } + + private static UpdateWorkLogCommand update(WorkLogId id, Patch title) { + return new UpdateWorkLogCommand( + id, title, Patch.absent(), Patch.absent(), Patch.absent(), Patch.absent()); } } diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/PosterEventPublisherTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/PosterEventPublisherTest.java index c7e6617a..8a6d7495 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/PosterEventPublisherTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/PosterEventPublisherTest.java @@ -3,63 +3,58 @@ package dev.caskeleton.sample.portfolio.application.event; import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.application.observability.CorrelationIdPort; -import dev.caskeleton.application.outbox.LegacyOutboxAppendPort; import dev.caskeleton.application.outbox.NewOutboxEvent; import dev.caskeleton.sample.portfolio.domain.poster.PosterCreated; import dev.caskeleton.sample.portfolio.domain.poster.PosterId; -import dev.caskeleton.sample.portfolio.domain.worklog.OutboxEventIdFactory; import java.time.Clock; import java.time.Instant; import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.List; import java.util.Optional; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.NullSource; +import org.junit.jupiter.params.provider.ValueSource; class PosterEventPublisherTest { private static final PosterId POSTER_ID = PosterId.of("0190bd6e-7c3e-7abc-8def-0123456789ab"); private static final String EVENT_ID = "0190bd6e-7c3e-7abc-8def-0123456789ff"; - private static final OutboxEventIdFactory EVENT_IDS = () -> EVENT_ID; private static final Clock CLOCK = Clock.fixed(Instant.parse("2025-06-01T10:00:00Z"), ZoneOffset.UTC); - @Test - void usesCorrelationIdPortWhenPresent() { - CapturingOutbox outbox = new CapturingOutbox(); - - publish(outbox, () -> Optional.of("corr-123")); - - assertThat(outbox.event.correlationId()).isEqualTo("corr-123"); - } + // LegacyOutboxAppendPort is owned by application-core; a recording method reference is enough. + private final List appended = new ArrayList<>(); @Test - void fallsBackToEventIdWhenCorrelationIdIsBlank() { - CapturingOutbox outbox = new CapturingOutbox(); + void usesTheCurrentCorrelationIdWhenOneIsPresent() { + // when + publishCreated(() -> Optional.of("corr-123")); - publish(outbox, () -> Optional.of(" ")); - - assertThat(outbox.event.correlationId()).isEqualTo(EVENT_ID); + // then + assertThat(appended) + .singleElement() + .extracting(NewOutboxEvent::correlationId) + .isEqualTo("corr-123"); } - @Test - void fallsBackToEventIdWhenCorrelationIdIsAbsent() { - CapturingOutbox outbox = new CapturingOutbox(); + @ParameterizedTest + @NullSource + @ValueSource(strings = {"", " "}) + void fallsBackToTheEventIdWhenTheCorrelationIdIsAbsentOrBlank(String correlationId) { + // when + publishCreated(() -> Optional.ofNullable(correlationId)); - publish(outbox, Optional::empty); - - assertThat(outbox.event.correlationId()).isEqualTo(EVENT_ID); + // then + assertThat(appended) + .singleElement() + .extracting(NewOutboxEvent::correlationId) + .isEqualTo(EVENT_ID); } - private static void publish(CapturingOutbox outbox, CorrelationIdPort correlationIdPort) { - new PosterEventPublisher(outbox, EVENT_IDS, correlationIdPort, CLOCK) + private void publishCreated(CorrelationIdPort correlationIdPort) { + new PosterEventPublisher(appended::add, () -> EVENT_ID, correlationIdPort, CLOCK) .publishCreated(new PosterCreated(POSTER_ID, "title")); } - - private static final class CapturingOutbox implements LegacyOutboxAppendPort { - private NewOutboxEvent event; - - @Override - public void append(NewOutboxEvent event) { - this.event = event; - } - } } diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/WorkLogReservedConsumerDedupeContractTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/WorkLogReservedConsumerDedupeContractTest.java index 5734c614..ab3f7a9e 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/WorkLogReservedConsumerDedupeContractTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/WorkLogReservedConsumerDedupeContractTest.java @@ -5,6 +5,7 @@ import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.application.outbox.NewOutboxEvent; import java.time.Instant; import java.util.ArrayList; +import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; @@ -36,89 +37,58 @@ import org.junit.jupiter.api.Test; */ class WorkLogReservedConsumerDedupeContractTest { - /** - * Minimal fake consumer with in-memory idempotencyKey tracking. - * - *

    Real implementations replace the {@link HashSet} with a persistent store (Redis / DB {@code - * idempotency_record}) and a configurable TTL. The dedupe logic shape ({@code if (seen.add(key)) - * process()}) is identical. - */ - static class FakeWorkLogReservedConsumer { + private static final String KEY_A = "0190bd6e-7c3e-7abc-8def-0123456789aa"; + private static final String KEY_B = "0190bd6e-7c3e-7abc-8def-0123456789bb"; + private static final String KEY_C = "0190bd6e-7c3e-7abc-8def-0123456789cc"; - private final Set processedKeys = new HashSet<>(); - final List processedEventIds = new ArrayList<>(); - - /** - * Processes the envelope. If {@code idempotencyKey} was already seen, the message is silently - * skipped (at-least-once → exactly-once effect). - */ - void consume(NewOutboxEvent envelope) { - if (!processedKeys.add(envelope.idempotencyKey())) { - // already processed — discard duplicate - return; - } - processedEventIds.add(envelope.eventId()); - } - - int processedCount() { - return processedEventIds.size(); - } - } - - // ---- contract tests ---- + private final FakeWorkLogReservedConsumer consumer = new FakeWorkLogReservedConsumer(); @Test void sameIdempotencyKeyDeliveredFiveTimesProducesExactlyOneEffect() { - // D7: at-least-once delivery + consumer dedupe obligation - FakeWorkLogReservedConsumer consumer = new FakeWorkLogReservedConsumer(); + // given + NewOutboxEvent envelope = sampleEnvelope(KEY_A); - NewOutboxEvent envelope = sampleEnvelope("0190bd6e-7c3e-7abc-8def-0123456789ab"); + // when + Collections.nCopies(5, envelope).forEach(consumer::consume); - // Simulate at-least-once delivery: same envelope received 5 times - for (int i = 0; i < 5; i++) { - consumer.consume(envelope); - } - - assertThat(consumer.processedCount()) + // then + assertThat(consumer.processedEventIds) .as("same idempotencyKey delivered 5 times must produce exactly 1 processing effect (D7)") - .isEqualTo(1); + .containsExactly(KEY_A); } @Test - void distinctIdempotencyKeysEachProcessedOnce() { - FakeWorkLogReservedConsumer consumer = new FakeWorkLogReservedConsumer(); + void distinctIdempotencyKeysAreEachProcessedOnce() { + // when + deliver(KEY_A, KEY_B, KEY_C); - consumer.consume(sampleEnvelope("0190bd6e-7c3e-7abc-8def-0123456789aa")); - consumer.consume(sampleEnvelope("0190bd6e-7c3e-7abc-8def-0123456789bb")); - consumer.consume(sampleEnvelope("0190bd6e-7c3e-7abc-8def-0123456789cc")); - - assertThat(consumer.processedCount()).isEqualTo(3); + // then + assertThat(consumer.processedEventIds).containsExactly(KEY_A, KEY_B, KEY_C); } @Test - void mixedDeliveryOnlyDeduplicatesMatchingKey() { - FakeWorkLogReservedConsumer consumer = new FakeWorkLogReservedConsumer(); + void mixedDeliveryOnlyDeduplicatesTheRepeatedKey() { + // when + deliver(KEY_A, KEY_A, KEY_B); - String keyA = "0190bd6e-7c3e-7abc-8def-0123456789aa"; - String keyB = "0190bd6e-7c3e-7abc-8def-0123456789bb"; - - // keyA delivered twice, keyB once - consumer.consume(sampleEnvelope(keyA)); - consumer.consume(sampleEnvelope(keyA)); // duplicate — must be skipped - consumer.consume(sampleEnvelope(keyB)); - - assertThat(consumer.processedCount()).isEqualTo(2); - assertThat(consumer.processedEventIds).containsExactly(keyA, keyB); + // then + assertThat(consumer.processedEventIds).containsExactly(KEY_A, KEY_B); } @Test void envelopeIdempotencyKeyEqualsEventIdPerI12() { - // I12: idempotencyKey = eventId by default - NewOutboxEvent envelope = sampleEnvelope("0190bd6e-7c3e-7abc-8def-0123456789ab"); + // when + NewOutboxEvent envelope = sampleEnvelope(KEY_A); + + // then assertThat(envelope.idempotencyKey()).isEqualTo(envelope.eventId()); } - // ---- builder ---- + private void deliver(String... idempotencyKeys) { + for (String key : idempotencyKeys) { + consumer.consume(sampleEnvelope(key)); + } + } private static NewOutboxEvent sampleEnvelope(String id) { return new NewOutboxEvent( @@ -131,4 +101,28 @@ class WorkLogReservedConsumerDedupeContractTest { id // idempotencyKey = eventId (I12) ); } + + /** + * Minimal consumer with in-memory idempotencyKey tracking — the subject of this contract, not a + * port double. + * + *

    Real implementations replace the {@link HashSet} with a persistent store (Redis / DB {@code + * idempotency_record}) and a configurable TTL. The dedupe logic shape ({@code if (seen.add(key)) + * process()}) is identical. + */ + private static final class FakeWorkLogReservedConsumer { + + private final Set processedKeys = new HashSet<>(); + private final List processedEventIds = new ArrayList<>(); + + /** + * Processes the envelope. If {@code idempotencyKey} was already seen, the message is silently + * skipped (at-least-once → exactly-once effect). + */ + void consume(NewOutboxEvent envelope) { + if (processedKeys.add(envelope.idempotencyKey())) { + processedEventIds.add(envelope.eventId()); + } + } + } } diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/WorkLogReservedContractContributionTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/WorkLogReservedContractContributionTest.java index f6ce3fb2..c5a28450 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/WorkLogReservedContractContributionTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/WorkLogReservedContractContributionTest.java @@ -1,29 +1,42 @@ package dev.caskeleton.sample.portfolio.application.event; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatObject; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.junit.jupiter.params.provider.Arguments.argumentSet; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.BooleanNode; import dev.caskeleton.application.messaging.contract.ContractDescriptor; import dev.caskeleton.application.messaging.contract.ContractId; import dev.caskeleton.application.messaging.contract.IntegrationPayload; import dev.caskeleton.application.messaging.contract.LogicalDestinationId; import dev.caskeleton.application.messaging.contract.SchemaResourceId; +import dev.caskeleton.application.messaging.contract.Sha256; import java.io.IOException; import java.io.InputStream; -import java.lang.reflect.Modifier; import java.net.URI; import java.nio.ByteBuffer; import java.nio.charset.CharacterCodingException; import java.nio.charset.CodingErrorAction; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; import java.time.Duration; import java.util.HexFormat; +import java.util.List; import java.util.Locale; +import java.util.Map; +import java.util.stream.Stream; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.NullAndEmptySource; +// No @Nested: the messagingSampleContractQualificationTest lane requires executed test cases under +// this exact class name. class WorkLogReservedContractContributionTest { private static final String SCHEMA_RESOURCE = @@ -36,114 +49,221 @@ class WorkLogReservedContractContributionTest { "contracts/messaging/portfolio.worklog.reserved/v1.invalid-unknown-field.json"; private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + private final WorkLogReservedContractContribution contribution = + new WorkLogReservedContractContribution(); + + // ---- payload record ---- + @Test - void payloadIsTheExactImmutableValidatedIntegrationPayloadRecord() { - WorkLogReservedPayload payload = new WorkLogReservedPayload("worklog-42"); - - assertThat(payload.workLogId()).isEqualTo("worklog-42"); - assertThat(WorkLogReservedPayload.class.isRecord()).isTrue(); - assertThat(Modifier.isFinal(WorkLogReservedPayload.class.getModifiers())).isTrue(); - assertThat(IntegrationPayload.class).isAssignableFrom(WorkLogReservedPayload.class); - - assertThatThrownBy(() -> new WorkLogReservedPayload(null)) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> new WorkLogReservedPayload("")) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> new WorkLogReservedPayload("worklog 42")) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> new WorkLogReservedPayload("x".repeat(161))) - .isInstanceOf(IllegalArgumentException.class); + void payloadKeepsTheWorkLogIdItWasBuiltWith() { + assertThat(new WorkLogReservedPayload("worklog-42").workLogId()).isEqualTo("worklog-42"); } @Test - void contributionPublishesOnlyTheClosedProviderNeutralContractDescription() { - WorkLogReservedContractContribution contribution = new WorkLogReservedContractContribution(); + void payloadTypeIsAFinalRecordImplementingIntegrationPayload() { + assertThat(WorkLogReservedPayload.class) + .isRecord() + .isFinal() + .isAssignableTo(IntegrationPayload.class); + } - assertThat(contribution.contractId()).isEqualTo(new ContractId("portfolio.worklog.reserved")); - assertThat(contribution.payloadVersion()).isEqualTo(1); - assertThat(contribution.exactPayloadRecordType()).isEqualTo(WorkLogReservedPayload.class); - assertThat(contribution.canonicalRecordComponentOrder()).containsExactly("workLogId"); - assertThat(contribution.payloadSchemaResource()) + @ParameterizedTest + @NullAndEmptySource + @MethodSource("nonCanonicalWorkLogIds") + void payloadRejectsAWorkLogIdOutsideTheCanonicalGrammar(String workLogId) { + // when + Throwable thrown = catchThrowable(() -> new WorkLogReservedPayload(workLogId)); + + // then + assertThat(thrown) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("workLogId must be a 1-160 character canonical US-ASCII identifier"); + } + + static Stream nonCanonicalWorkLogIds() { + return Stream.of("worklog 42", "x".repeat(161)); + } + + // ---- contribution ---- + + @Test + void contributionDescribesVersionOneOfTheWorkLogReservedPayload() { + assertThat(contribution) + .extracting( + WorkLogReservedContractContribution::contractId, + WorkLogReservedContractContribution::payloadVersion, + WorkLogReservedContractContribution::exactPayloadRecordType, + WorkLogReservedContractContribution::canonicalRecordComponentOrder, + WorkLogReservedContractContribution::payloadSchemaResource) + .containsExactly( + new ContractId("portfolio.worklog.reserved"), + 1, + WorkLogReservedPayload.class, + List.of("workLogId"), + new SchemaResourceId(SCHEMA_RESOURCE)); + } + + @Test + void payloadSchemaHashIsTheSameInstanceOnEveryCall() { + // given + Sha256 first = contribution.payloadSchemaHash(); + + // when + Sha256 second = contribution.payloadSchemaHash(); + + // then + assertThat(second).isSameAs(first); + } + + @Test + void descriptorDeclaresTheSampleOwnedOrderedInternalDestination() { + assertThat(contribution.descriptor()) .isEqualTo( - new SchemaResourceId("contracts/messaging/portfolio.worklog.reserved/v1.schema.json")); - assertThat(contribution.payloadSchemaHash()).isSameAs(contribution.payloadSchemaHash()); - - ContractDescriptor descriptor = contribution.descriptor(); - assertThat(descriptor.ownerModule()).isEqualTo("sample-portfolio"); - assertThat(descriptor.logicalDestination()) - .isEqualTo(new LogicalDestinationId("portfolio-domain-events")); - assertThat(descriptor.serializerId()).isEqualTo("json-schema-envelope-v1"); - assertThat(descriptor.orderingRequired()).isTrue(); - assertThat(descriptor.maximumPayloadBytes()).isEqualTo(64 * 1024); - assertThat(descriptor.maximumEnvelopeBytes()).isEqualTo(128 * 1024); - assertThat(descriptor.sensitivityClassification()) - .isEqualTo(ContractDescriptor.SensitivityClassification.INTERNAL); - assertThat(descriptor.sameEventRequeueHorizon()).isEqualTo(Duration.ofDays(7)); + new ContractDescriptor( + "sample-portfolio", + new LogicalDestinationId("portfolio-domain-events"), + "json-schema-envelope-v1", + true, + 64 * 1024, + 128 * 1024, + ContractDescriptor.SensitivityClassification.INTERNAL, + Duration.ofDays(7))); + } + @Test + void contributionDeclaresNoSerializerOrTransportSpecificMethod() { assertThat(WorkLogReservedContractContribution.class.getDeclaredMethods()) + .extracting(method -> method.getName().toLowerCase(Locale.ROOT)) .allSatisfy( - method -> { - String name = method.getName().toLowerCase(Locale.ROOT); - assertThat(name) - .doesNotContain( - "json", "mapper", "tree", "parser", "topic", "kafka", "bootstrap"); - }); + name -> + assertThat(name) + .doesNotContain( + "json", "mapper", "tree", "parser", "topic", "kafka", "bootstrap")); + } + + // ---- checked-in schema and digest ---- + + @Test + void schemaDeclaresDraft2020AndAnAbsoluteUrnId() throws IOException { + // when + JsonNode schema = readJson(SCHEMA_RESOURCE); + + // then + assertThatObject(schema) + .extracting( + node -> node.path("$schema").textValue(), + node -> node.path("$id").textValue(), + node -> URI.create(node.path("$id").textValue()).isAbsolute()) + .containsExactly( + "https://json-schema.org/draft/2020-12/schema", + "urn:dev-caskeleton:contracts:messaging:portfolio.worklog.reserved:v1", + true); } @Test - void checkedInPayloadSchemaIsClosedBoundedAndMatchesItsExactByteDigest() throws Exception { - byte[] schemaBytes = readResource(SCHEMA_RESOURCE); - String schemaText = strictUtf8(schemaBytes); - JsonNode schema = OBJECT_MAPPER.readTree(schemaText); + void schemaIsAClosedObjectWhoseOnlyAndRequiredPropertyIsWorkLogId() throws IOException { + // when + JsonNode schema = readJson(SCHEMA_RESOURCE); - assertThat(schema.path("$schema").textValue()) - .isEqualTo("https://json-schema.org/draft/2020-12/schema"); - String schemaId = schema.path("$id").textValue(); - assertThat(schemaId) - .isEqualTo("urn:dev-caskeleton:contracts:messaging:portfolio.worklog.reserved:v1"); - assertThat(URI.create(schemaId).isAbsolute()).isTrue(); - assertThat(schema.path("type").textValue()).isEqualTo("object"); - assertThat(schema.path("required")).containsExactly(OBJECT_MAPPER.valueToTree("workLogId")); - assertThat(schema.path("properties").size()).isEqualTo(1); - assertThat(schema.path("properties").has("workLogId")).isTrue(); - JsonNode workLogId = schema.path("properties").path("workLogId"); - assertThat(workLogId.path("type").textValue()).isEqualTo("string"); - assertThat(workLogId.path("minLength").intValue()).isEqualTo(1); - assertThat(workLogId.path("maxLength").intValue()).isEqualTo(160); - assertThat(workLogId.path("pattern").textValue()).isEqualTo("^[A-Za-z0-9][A-Za-z0-9._:-]*$"); - assertThat(schema.path("unevaluatedProperties").booleanValue()).isFalse(); - assertThat(schemaText).doesNotContainPattern("\"type\"\\s*:\\s*\\[[^]]*\"null\""); - assertThat(schemaText).doesNotContain("\"$ref\""); - - byte[] manifestBytes = readResource(DIGEST_RESOURCE); - String manifest = strictUtf8(manifestBytes); - assertThat(manifestBytes).endsWith((byte) '\n'); - assertThat(manifest).matches("[0-9a-f]{64}\\n"); - String exactDigest = - HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(schemaBytes)); - assertThat(manifest).isEqualTo(exactDigest + "\n"); - - WorkLogReservedContractContribution contribution = new WorkLogReservedContractContribution(); - assertThat(contribution.payloadSchemaHash().toString()).isEqualTo(exactDigest); + // then + assertThatObject(schema) + .extracting( + node -> node.path("type").textValue(), + node -> node.path("required"), + node -> node.path("properties").properties().stream().map(Map.Entry::getKey).toList(), + node -> node.path("unevaluatedProperties")) + .containsExactly( + "object", + OBJECT_MAPPER.createArrayNode().add("workLogId"), + List.of("workLogId"), + BooleanNode.FALSE); } @Test - void goldenVectorsFreezeRequiredUnknownAndNullPolicyWithoutClaimingValidatorCompatibility() - throws Exception { - JsonNode valid = OBJECT_MAPPER.readTree(strictUtf8(readResource(VALID_RESOURCE))); - JsonNode invalidUnknown = - OBJECT_MAPPER.readTree(strictUtf8(readResource(INVALID_UNKNOWN_FIELD_RESOURCE))); - JsonNode missing = OBJECT_MAPPER.readTree("{}"); - JsonNode explicitNull = OBJECT_MAPPER.readTree("{\"workLogId\":null}"); + void workLogIdPropertyIsANonEmptyCanonicalStringOfAtMost160Characters() throws IOException { + // when + JsonNode workLogId = readJson(SCHEMA_RESOURCE).path("properties").path("workLogId"); - assertThat(valid).isEqualTo(OBJECT_MAPPER.readTree("{\"workLogId\":\"worklog-42\"}")); - assertThat(invalidUnknown.path("workLogId").textValue()).isEqualTo("worklog-42"); - assertThat(invalidUnknown.has("unexpected")).isTrue(); + // then + assertThatObject(workLogId) + .extracting( + node -> node.path("type").textValue(), + node -> node.path("minLength").intValue(), + node -> node.path("maxLength").intValue(), + node -> node.path("pattern").textValue()) + .containsExactly("string", 1, 160, "^[A-Za-z0-9][A-Za-z0-9._:-]*$"); + } - assertThat(matchesStructuralV1Policy(valid)).isTrue(); - assertThat(matchesStructuralV1Policy(invalidUnknown)).isFalse(); - assertThat(matchesStructuralV1Policy(missing)).isFalse(); - assertThat(matchesStructuralV1Policy(explicitNull)).isFalse(); + @Test + void schemaNeitherAllowsANullTypeNorReferencesAnotherSchema() throws IOException { + // when + String schemaText = strictUtf8(readResource(SCHEMA_RESOURCE)); + + // then + assertThat(schemaText) + .doesNotContainPattern("\"type\"\\s*:\\s*\\[[^]]*\"null\"") + .doesNotContain("\"$ref\""); + } + + @Test + void digestManifestIsTheLowercaseSha256OfTheSchemaBytesAndOneNewline() throws Exception { + // given + String schemaDigest = sha256Hex(readResource(SCHEMA_RESOURCE)); + + // when + String manifest = strictUtf8(readResource(DIGEST_RESOURCE)); + + // then + assertThat(manifest).endsWith("\n").matches("[0-9a-f]{64}\\n").isEqualTo(schemaDigest + "\n"); + } + + @Test + void payloadSchemaHashIsTheDigestOfTheCheckedInSchemaBytes() throws Exception { + // given + String schemaDigest = sha256Hex(readResource(SCHEMA_RESOURCE)); + + // when + Sha256 hash = contribution.payloadSchemaHash(); + + // then + assertThat(hash).hasToString(schemaDigest); + } + + // ---- golden vectors (structural policy only; no validator-compatibility claim) ---- + + @Test + void validGoldenVectorCarriesOnlyTheWorkLogId() throws IOException { + assertThat(readJson(VALID_RESOURCE)) + .isEqualTo(OBJECT_MAPPER.createObjectNode().put("workLogId", "worklog-42")); + } + + @Test + void unknownFieldGoldenVectorAddsAnUnexpectedFieldToAValidWorkLogId() throws IOException { + assertThat(readJson(INVALID_UNKNOWN_FIELD_RESOURCE)) + .isEqualTo( + OBJECT_MAPPER + .createObjectNode() + .put("workLogId", "worklog-42") + .put("unexpected", "rejected")); + } + + @ParameterizedTest + @MethodSource("structuralPolicyCandidates") + void structuralV1PolicyAcceptsOnlyASingleNonNullCanonicalWorkLogId( + JsonNode candidate, boolean expected) { + // when + boolean accepted = matchesStructuralV1Policy(candidate); + + // then + assertThat(accepted).isEqualTo(expected); + } + + static Stream structuralPolicyCandidates() throws IOException { + return Stream.of( + argumentSet("valid golden vector", readJson(VALID_RESOURCE), true), + argumentSet("unknown-field golden vector", readJson(INVALID_UNKNOWN_FIELD_RESOURCE), false), + argumentSet("missing workLogId", OBJECT_MAPPER.readTree("{}"), false), + argumentSet("null workLogId", OBJECT_MAPPER.readTree("{\"workLogId\":null}"), false)); } private static boolean matchesStructuralV1Policy(JsonNode candidate) { @@ -158,6 +278,14 @@ class WorkLogReservedContractContributionTest { return value.length() <= 160 && value.matches("[A-Za-z0-9][A-Za-z0-9._:-]*"); } + private static JsonNode readJson(String resource) throws IOException { + return OBJECT_MAPPER.readTree(strictUtf8(readResource(resource))); + } + + private static String sha256Hex(byte[] bytes) throws NoSuchAlgorithmException { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } + private static byte[] readResource(String resource) throws IOException { try (InputStream input = WorkLogReservedContractContributionTest.class diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/WorkLogReservedIntegrationEventMapperJsonTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/WorkLogReservedIntegrationEventMapperJsonTest.java index 86a647df..5f3a1ea9 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/WorkLogReservedIntegrationEventMapperJsonTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/WorkLogReservedIntegrationEventMapperJsonTest.java @@ -1,37 +1,41 @@ package dev.caskeleton.sample.portfolio.application.event; import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.params.provider.Arguments.argumentSet; +import com.fasterxml.jackson.databind.ObjectMapper; import dev.caskeleton.sample.portfolio.domain.worklog.WorkCategory; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogId; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogReserved; +import java.io.IOException; import java.time.LocalDate; import java.util.Locale; +import java.util.Map; +import java.util.stream.Stream; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; /** * Verifies the JSON serialisation produced by {@link WorkLogReservedIntegrationEventMapper#toJson} * (feature-domain-event-outbox-contract D11 + D12). * - *

    Hand-rolled serialisation: no Jackson dependency. Checks field presence, ordering, and RFC - * 8259 §7 escape correctness. + *

    Hand-rolled serialisation: no Jackson dependency in main code. Checks field presence, + * ordering, and RFC 8259 §7 escape correctness. */ class WorkLogReservedIntegrationEventMapperJsonTest { - private static final WorkLogReserved SAMPLE_EVENT = - new WorkLogReserved( - WorkLogId.of("0190bd6e-7c3e-7abc-8def-0123456789ab"), - WorkCategory.BACKEND, - LocalDate.of(2025, 1, 1)); + private static final WorkLogReservedIntegrationEvent SAMPLE_EVENT = + WorkLogReservedIntegrationEventMapper.toIntegrationEvent( + new WorkLogReserved( + WorkLogId.of("0190bd6e-7c3e-7abc-8def-0123456789ab"), + WorkCategory.BACKEND, + LocalDate.of(2025, 1, 1))); @Test - void toJsonProducesExpectedShape() { - WorkLogReservedIntegrationEvent ie = - WorkLogReservedIntegrationEventMapper.toIntegrationEvent(SAMPLE_EVENT); - - String json = WorkLogReservedIntegrationEventMapper.toJson(ie); - - assertThat(json) + void toJsonWritesWorkLogIdCategoryAndOccurredOnInThatOrder() { + assertThat(WorkLogReservedIntegrationEventMapper.toJson(SAMPLE_EVENT)) .isEqualTo( "{\"workLogId\":\"0190bd6e-7c3e-7abc-8def-0123456789ab\"," + "\"category\":\"BACKEND\"," @@ -39,35 +43,29 @@ class WorkLogReservedIntegrationEventMapperJsonTest { } @Test - void toJsonIsValidParseableJsonObject() { - WorkLogReservedIntegrationEvent ie = - WorkLogReservedIntegrationEventMapper.toIntegrationEvent(SAMPLE_EVENT); - String json = WorkLogReservedIntegrationEventMapper.toJson(ie); + void toJsonIsAParseableObjectWithExactlyTheThreeFields() throws IOException { + // when + String json = WorkLogReservedIntegrationEventMapper.toJson(SAMPLE_EVENT); + // then assertThat(json).startsWith("{").endsWith("}"); - assertThat(json).contains("\"workLogId\""); - assertThat(json).contains("\"category\""); - assertThat(json).contains("\"occurredOn\""); + assertThat(new ObjectMapper().readTree(json).properties()) + .extracting(Map.Entry::getKey) + .containsExactly("workLogId", "category", "occurredOn"); } - @Test - void escapeHandlesBackslashAndDoubleQuote() { - String input = "path\\to\"value"; - String escaped = WorkLogReservedIntegrationEventMapper.escape(input); - assertThat(escaped).isEqualTo("path\\\\to\\\"value"); + @ParameterizedTest + @MethodSource("escapeCases") + void escapeProducesRfc8259EscapedText(String input, String expected) { + assertThat(WorkLogReservedIntegrationEventMapper.escape(input)).isEqualTo(expected); } - @Test - void escapeHandlesControlCharacters() { - // Tab (0x09), newline (0x0A), carriage return (0x0D) are < 0x20 - String input = "a\tb\nc"; - String escaped = WorkLogReservedIntegrationEventMapper.escape(input); - assertThat(escaped).isEqualTo("a\\u0009b\\u000ac"); - } - - @Test - void escapeNullReturnsEmptyString() { - assertThat(WorkLogReservedIntegrationEventMapper.escape(null)).isEqualTo(""); + static Stream escapeCases() { + return Stream.of( + argumentSet("backslash and double quote", "path\\to\"value", "path\\\\to\\\"value"), + // Tab (0x09) and newline (0x0A) are below 0x20, so they become \\u escapes. + argumentSet("control characters", "a\tb\nc", "a\\u0009b\\u000ac"), + argumentSet("null becomes the empty string", null, "")); } @Test @@ -80,14 +78,7 @@ class WorkLogReservedIntegrationEventMapperJsonTest { void toJsonContainsNoPiiFieldNames() { // EventPayloadPiiContractTest (Task E) also enforces this statically; // this test makes it explicit for the sample payload shape. - WorkLogReservedIntegrationEvent ie = - WorkLogReservedIntegrationEventMapper.toIntegrationEvent(SAMPLE_EVENT); - String json = WorkLogReservedIntegrationEventMapper.toJson(ie); - - assertThat(json.toLowerCase(Locale.ROOT)) - .doesNotContain("email") - .doesNotContain("password") - .doesNotContain("token") - .doesNotContain("secret"); + assertThat(WorkLogReservedIntegrationEventMapper.toJson(SAMPLE_EVENT).toLowerCase(Locale.ROOT)) + .doesNotContain("email", "password", "token", "secret"); } } diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/WorkLogReservedIntegrationEventMapperTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/WorkLogReservedIntegrationEventMapperTest.java index 735c5386..12035829 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/WorkLogReservedIntegrationEventMapperTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/event/WorkLogReservedIntegrationEventMapperTest.java @@ -16,17 +16,21 @@ class WorkLogReservedIntegrationEventMapperTest { @Test void mapsDomainEventToIntegrationEventFlatteningValueObjects() { + // given WorkLogReserved domainEvent = new WorkLogReserved( WorkLogId.of("0190bd6e-7c3e-7abc-8def-0123456789ab"), WorkCategory.BACKEND, LocalDate.of(2025, 1, 1)); + // when WorkLogReservedIntegrationEvent integrationEvent = WorkLogReservedIntegrationEventMapper.toIntegrationEvent(domainEvent); - assertThat(integrationEvent.workLogId()).isEqualTo("0190bd6e-7c3e-7abc-8def-0123456789ab"); - assertThat(integrationEvent.category()).isEqualTo("BACKEND"); - assertThat(integrationEvent.occurredOn()).isEqualTo("2025-01-01"); + // then + assertThat(integrationEvent) + .isEqualTo( + new WorkLogReservedIntegrationEvent( + "0190bd6e-7c3e-7abc-8def-0123456789ab", "BACKEND", "2025-01-01")); } } diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/poster/DeletePosterImageRetirementTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/poster/DeletePosterImageRetirementTest.java index cc195ae0..303b8b11 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/poster/DeletePosterImageRetirementTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/poster/DeletePosterImageRetirementTest.java @@ -1,19 +1,21 @@ package dev.caskeleton.sample.portfolio.application.poster; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.tuple; +import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import dev.caskeleton.application.objectstorage.identity.ObjectOperationId; import dev.caskeleton.application.objectstorage.identity.ObjectVersionToken; -import dev.caskeleton.application.transaction.TransactionPort; +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; import dev.caskeleton.sample.portfolio.application.command.DeletePosterCommand; import dev.caskeleton.sample.portfolio.application.event.PosterEventPublisher; import dev.caskeleton.sample.portfolio.application.posterimage.PosterImageOperationIdFactory; import dev.caskeleton.sample.portfolio.application.posterimage.PosterImageRetirementIntent; -import dev.caskeleton.sample.portfolio.application.posterimage.PosterImageRetirementIntentStorePort; import dev.caskeleton.sample.portfolio.application.posterimage.PosterImageUploadIntent; import dev.caskeleton.sample.portfolio.application.posterimage.PosterImageUploadIntentStorePort; +import dev.caskeleton.sample.portfolio.application.posterimage.testkit.InMemoryPosterImageRetirementIntentStore; import dev.caskeleton.sample.portfolio.domain.poster.Poster; import dev.caskeleton.sample.portfolio.domain.poster.PosterId; import dev.caskeleton.sample.portfolio.domain.poster.PosterImageReference; @@ -23,9 +25,10 @@ import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.List; import java.util.Optional; import java.util.UUID; -import java.util.function.Supplier; import org.junit.jupiter.api.Test; class DeletePosterImageRetirementTest { @@ -39,20 +42,26 @@ class DeletePosterImageRetirementTest { @Test void commitsExactRetirementWorkBeforeDeletingCanonicalPoster() { - Poster poster = - Poster.rehydrate( - POSTER, "title", "caption", null, REFERENCE.value(), PosterStatus.DRAFT, 4L); - PosterRepository posters = mock(PosterRepository.class); - when(posters.findById(POSTER)).thenReturn(Optional.of(poster)); - PosterImageUploadIntent ready = mock(PosterImageUploadIntent.class); - when(ready.publishedVersion()).thenReturn(VERSION); - PosterImageUploadIntentStorePort uploads = mock(PosterImageUploadIntentStorePort.class); - when(uploads.findReadyByPublishedReference(REFERENCE)).thenReturn(Optional.of(ready)); - CapturingRetirements retirements = new CapturingRetirements(posters); - TrackingTransactions transactions = new TrackingTransactions(); + // given + InMemoryPosterImageRetirementIntentStore retirements = + new InMemoryPosterImageRetirementIntentStore(); + DirectTransactionPort transactions = DirectTransactionPort.rejectingNesting(); + PosterRepository posters = postersHoldingAPublishedImage(); + List retirementsAtDeletion = new ArrayList<>(); + doAnswer( + invocation -> { + retirementsAtDeletion.addAll(retirements.all()); + return null; + }) + .when(posters) + .deleteById(POSTER); RetirePosterImageUseCase retire = new RetirePosterImageUseCase( - retirements, uploads, allocated(), transactions, Clock.fixed(NOW, ZoneOffset.UTC)); + retirements, + uploadsWithReadyEvidence(), + allocated(), + transactions, + Clock.fixed(NOW, ZoneOffset.UTC)); DeletePosterUseCase useCase = new DeletePosterUseCase( posters, @@ -61,13 +70,35 @@ class DeletePosterImageRetirementTest { Optional.of(retire), Duration.ofDays(7)); + // when useCase.handle(new DeletePosterCommand(POSTER)); - assertThat(retirements.stored).isNotNull(); - assertThat(retirements.stored.posterId()).isEqualTo(POSTER); - assertThat(retirements.stored.reference()).isEqualTo(REFERENCE); - assertThat(retirements.stored.exactVersion()).isEqualTo(VERSION); - assertThat(retirements.stored.retainUntil()).isEqualTo(NOW.plus(Duration.ofDays(7))); + // then + assertThat(retirementsAtDeletion) + .extracting( + PosterImageRetirementIntent::posterId, + PosterImageRetirementIntent::reference, + PosterImageRetirementIntent::exactVersion, + PosterImageRetirementIntent::retainUntil) + .containsExactly(tuple(POSTER, REFERENCE, VERSION, NOW.plus(Duration.ofDays(7)))); + assertThat(transactions.committed()).containsExactly(DirectTransactionPort.Boundary.WRITE); + } + + private static PosterRepository postersHoldingAPublishedImage() { + Poster poster = + Poster.rehydrate( + POSTER, "title", "caption", null, REFERENCE.value(), PosterStatus.DRAFT, 4L); + PosterRepository posters = mock(PosterRepository.class); + when(posters.findById(POSTER)).thenReturn(Optional.of(poster)); + return posters; + } + + private static PosterImageUploadIntentStorePort uploadsWithReadyEvidence() { + PosterImageUploadIntent ready = mock(PosterImageUploadIntent.class); + when(ready.publishedVersion()).thenReturn(VERSION); + PosterImageUploadIntentStorePort uploads = mock(PosterImageUploadIntentStorePort.class); + when(uploads.findReadyByPublishedReference(REFERENCE)).thenReturn(Optional.of(ready)); + return uploads; } private static PosterImageOperationIdFactory allocated() { @@ -76,68 +107,4 @@ class DeletePosterImageRetirementTest { UUID.fromString("0190bd6e-7c3e-7abc-8def-012345678901"), ObjectOperationId.of("0190bd6e-7c3e-7abc-8def-012345678901")); } - - private static final class CapturingRetirements implements PosterImageRetirementIntentStorePort { - private final PosterRepository posters; - private PosterImageRetirementIntent stored; - - private CapturingRetirements(PosterRepository posters) { - this.posters = posters; - } - - @Override - public PosterImageRetirementIntent createOrRead(PosterImageRetirementIntent proposed) { - assertThat(posters.findById(POSTER)).isPresent(); - stored = proposed; - return proposed; - } - - @Override - public Optional findByOperation(ObjectOperationId operation) { - return Optional.ofNullable(stored); - } - - @Override - public PosterImageRetirementIntent compareAndSet( - long expectedRevision, PosterImageRetirementIntent replacement) { - stored = replacement; - return replacement; - } - - @Override - public Optional claimReady( - String claimantDigest, Instant now, Duration leaseDuration) { - return Optional.empty(); - } - } - - private static final class TrackingTransactions implements TransactionPort { - private boolean active; - - @Override - public T inWrite(Supplier action) { - assertThat(active).isFalse(); - active = true; - try { - return action.get(); - } finally { - active = false; - } - } - - @Override - public T inRootWrite(Supplier action) { - return inWrite(action); - } - - @Override - public T inRead(Supplier action) { - return action.get(); - } - - @Override - public T inNew(Supplier action) { - return inWrite(action); - } - } } diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/poster/LegacyPosterImageUploadCharacterizationTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/poster/LegacyPosterImageUploadCharacterizationTest.java index 9519e80c..297aa668 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/poster/LegacyPosterImageUploadCharacterizationTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/poster/LegacyPosterImageUploadCharacterizationTest.java @@ -2,14 +2,15 @@ package dev.caskeleton.sample.portfolio.application.poster; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import dev.caskeleton.application.observability.CorrelationIdPort; +import dev.caskeleton.application.outbox.NewOutboxEvent; import dev.caskeleton.application.storage.ObjectStoragePort; import dev.caskeleton.application.storage.StoredObject; -import dev.caskeleton.application.transaction.TransactionPort; +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; import dev.caskeleton.sample.portfolio.adapter.inbound.web.controller.LegacyPosterImageController; import dev.caskeleton.sample.portfolio.adapter.inbound.web.dto.response.StoredObjectResponse; import dev.caskeleton.sample.portfolio.application.command.DeletePosterCommand; @@ -20,10 +21,15 @@ import dev.caskeleton.sample.portfolio.domain.poster.PosterId; import dev.caskeleton.sample.portfolio.domain.poster.PosterRepository; import java.io.IOException; import java.net.URI; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayList; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.Optional; -import java.util.function.Supplier; +import java.util.Set; import org.junit.jupiter.api.Test; import org.springframework.web.multipart.MultipartFile; @@ -34,35 +40,65 @@ class LegacyPosterImageUploadCharacterizationTest { private static final PosterId POSTER_ID = PosterId.of("0190bd6e-7c3e-7abc-8def-0123456789ab"); private static final String LEGACY_KEY = "posters/" + POSTER_ID.value() + "/image"; + private static final Clock CLOCK = + Clock.fixed(Instant.parse("2026-07-29T00:00:00Z"), ZoneOffset.UTC); + + private final DirectTransactionPort tx = new DirectTransactionPort(); + private final InMemoryLegacyStorage storage = new InMemoryLegacyStorage(tx); + private final List outbox = new ArrayList<>(); + private final PosterEventPublisher events = + new PosterEventPublisher( + outbox::add, () -> "0190bd6e-7c3e-7abc-8def-0123456789ff", noCorrelation(), CLOCK); + private final PosterRepository repository = mock(PosterRepository.class); + private final Poster poster = Poster.create(POSTER_ID, "legacy", "characterization"); @Test void uploadCallsObjectStorageInsideTheWriteTransaction() { - PosterRepository repository = mock(PosterRepository.class); - Poster poster = Poster.create(POSTER_ID, "legacy", "characterization"); - when(repository.findById(POSTER_ID)).thenReturn(Optional.of(poster)); - TrackingTransactionPort tx = new TrackingTransactionPort(); - ObjectStoragePort storage = mock(ObjectStoragePort.class); - when(storage.put(eq(LEGACY_KEY), any(byte[].class), eq("image/png"))) - .thenAnswer( - ignored -> { - assertThat(tx.inWrite()).isTrue(); - return legacyReceipt(); - }); - PosterEventPublisher events = mock(PosterEventPublisher.class); - UploadPosterImageUseCase useCase = - new UploadPosterImageUseCase(repository, storage, events, tx); + // given + UploadPosterImageUseCase useCase = uploadOfAnExistingPoster(); - StoredObject stored = - useCase.handle(new UploadPosterImageCommand(POSTER_ID, new byte[] {1, 2, 3}, "image/png")); + // when + useCase.handle(uploadCommand()); - assertThat(stored.key()).isEqualTo(LEGACY_KEY); - assertThat(poster.imageKey()).isEqualTo(LEGACY_KEY); + // then + assertThat(storage.putsInsideTransaction()).containsExactly(Map.entry(LEGACY_KEY, true)); + assertThat(tx.committed()).containsExactly(DirectTransactionPort.Boundary.WRITE); + } + + @Test + void uploadRecordsTheRawStorageKeyOnTheSavedPoster() { + // given + UploadPosterImageUseCase useCase = uploadOfAnExistingPoster(); + + // when + StoredObject stored = useCase.handle(uploadCommand()); + + // then + assertThat(List.of(stored.key(), poster.imageKey())).containsExactly(LEGACY_KEY, LEGACY_KEY); verify(repository).save(poster); - verify(events).publishImageAttached(any()); + } + + @Test + void uploadPublishesImageAttachedForTheStoredKey() { + // given + UploadPosterImageUseCase useCase = uploadOfAnExistingPoster(); + + // when + useCase.handle(uploadCommand()); + + // then + assertThat(outbox) + .singleElement() + .satisfies( + event -> { + assertThat(event.eventType()).isEqualTo("poster.image-attached"); + assertThat(event.payload()).contains(LEGACY_KEY); + }); } @Test void controllerMaterializesMultipartBytesAndReturnsRawKeyAndLocation() throws IOException { + // given UploadPosterImageUseCase upload = mock(UploadPosterImageUseCase.class); when(upload.handle(any())).thenReturn(legacyReceipt()); LegacyPosterImageController controller = new LegacyPosterImageController(upload); @@ -70,27 +106,42 @@ class LegacyPosterImageUploadCharacterizationTest { when(file.getBytes()).thenReturn(new byte[] {1, 2, 3}); when(file.getContentType()).thenReturn("image/png"); + // when StoredObjectResponse response = controller.uploadImage(POSTER_ID.value(), file); + // then verify(file).getBytes(); - assertThat(response.key()).isEqualTo(LEGACY_KEY); - assertThat(response.location()).isEqualTo("s3://legacy-bucket/" + LEGACY_KEY); + assertThat(response) + .extracting(StoredObjectResponse::key, StoredObjectResponse::location) + .containsExactly(LEGACY_KEY, "s3://legacy-bucket/" + LEGACY_KEY); } @Test void deletingAPosterDoesNotRetireItsLegacyObject() { - InMemoryLegacyStorage storage = new InMemoryLegacyStorage(); + // given storage.put(LEGACY_KEY, new byte[] {9}, "image/png"); - PosterRepository repository = mock(PosterRepository.class); when(repository.existsById(POSTER_ID)).thenReturn(true); - DeletePosterUseCase delete = - new DeletePosterUseCase( - repository, mock(PosterEventPublisher.class), new TrackingTransactionPort()); + DeletePosterUseCase delete = new DeletePosterUseCase(repository, events, tx); + // when delete.handle(new DeletePosterCommand(POSTER_ID)); + // then verify(repository).deleteById(POSTER_ID); - assertThat(storage.exists(LEGACY_KEY)).isTrue(); + assertThat(storage.keys()).containsExactly(LEGACY_KEY); + } + + private UploadPosterImageUseCase uploadOfAnExistingPoster() { + when(repository.findById(POSTER_ID)).thenReturn(Optional.of(poster)); + return new UploadPosterImageUseCase(repository, storage, events, tx); + } + + private static UploadPosterImageCommand uploadCommand() { + return new UploadPosterImageCommand(POSTER_ID, new byte[] {1, 2, 3}, "image/png"); + } + + private static CorrelationIdPort noCorrelation() { + return Optional::empty; } private static StoredObject legacyReceipt() { @@ -98,45 +149,19 @@ class LegacyPosterImageUploadCharacterizationTest { LEGACY_KEY, 3, "image/png", URI.create("s3://legacy-bucket/" + LEGACY_KEY)); } - private static final class TrackingTransactionPort implements TransactionPort { - private boolean inWrite; - - boolean inWrite() { - return inWrite; - } - - @Override - public T inWrite(Supplier action) { - inWrite = true; - try { - return action.get(); - } finally { - inWrite = false; - } - } - - @Override - public T inRootWrite(Supplier action) { - assertThat(inWrite).isFalse(); - return inWrite(action); - } - - @Override - public T inRead(Supplier action) { - return action.get(); - } - - @Override - public T inNew(Supplier action) { - return action.get(); - } - } - + /** Stores objects in memory and records, per put, whether a transaction was active. */ private static final class InMemoryLegacyStorage implements ObjectStoragePort { + private final DirectTransactionPort tx; private final Map objects = new HashMap<>(); + private final List> putsInsideTransaction = new ArrayList<>(); + + private InMemoryLegacyStorage(DirectTransactionPort tx) { + this.tx = tx; + } @Override public StoredObject put(String key, byte[] content, String contentType) { + putsInsideTransaction.add(Map.entry(key, tx.active())); objects.put(key, content.clone()); return new StoredObject(key, content.length, contentType, URI.create("memory:///" + key)); } @@ -156,5 +181,13 @@ class LegacyPosterImageUploadCharacterizationTest { public boolean exists(String key) { return objects.containsKey(key); } + + Set keys() { + return objects.keySet(); + } + + List> putsInsideTransaction() { + return putsInsideTransaction; + } } } diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/poster/PosterImagePublicationWorkflowTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/poster/PosterImagePublicationWorkflowTest.java index 84b5401c..611fb922 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/poster/PosterImagePublicationWorkflowTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/poster/PosterImagePublicationWorkflowTest.java @@ -2,22 +2,18 @@ package dev.caskeleton.sample.portfolio.application.poster; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import dev.caskeleton.application.idempotency.IdempotencyExecutor; -import dev.caskeleton.application.idempotency.IdempotencyRecord; -import dev.caskeleton.application.idempotency.IdempotencyScope; -import dev.caskeleton.application.idempotency.IdempotencyStatus; -import dev.caskeleton.application.idempotency.IdempotencyStorePort; -import dev.caskeleton.application.idempotency.RequestFingerprint; -import dev.caskeleton.application.idempotency.StoredResponse; +import dev.caskeleton.application.idempotency.testkit.InMemoryIdempotencyStore; import dev.caskeleton.application.objectstorage.content.CancellationView; +import dev.caskeleton.application.objectstorage.content.ObjectContentProducer; import dev.caskeleton.application.objectstorage.content.ObjectContentProductionContext; 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.identity.ObjectStageHandle; import dev.caskeleton.application.objectstorage.identity.ObjectVersionToken; import dev.caskeleton.application.objectstorage.model.ObjectContentIdentity; @@ -29,17 +25,23 @@ import dev.caskeleton.application.objectstorage.model.ObjectStageReceipt; import dev.caskeleton.application.objectstorage.model.ObjectVerificationReceipt; import dev.caskeleton.application.objectstorage.port.ObjectPublicationHandoffPort; import dev.caskeleton.application.objectstorage.port.StagedObjectPublicationPort; +import dev.caskeleton.application.objectstorage.request.ObjectHandoffClaimRequest; +import dev.caskeleton.application.objectstorage.request.ObjectStageRequest; +import dev.caskeleton.application.objectstorage.request.ObjectVerifyRequest; import dev.caskeleton.application.outbound.CallBudget; -import dev.caskeleton.application.transaction.TransactionPort; +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort.Boundary; import dev.caskeleton.sample.portfolio.adapter.outbound.identifier.HmacPosterImageIdempotencyScopeDigester; import dev.caskeleton.sample.portfolio.application.command.PublishPosterImageCommand; import dev.caskeleton.sample.portfolio.application.event.PosterImagePublicationEventPublisher; import dev.caskeleton.sample.portfolio.application.posterimage.PosterImageIdempotencyScopeDigest; import dev.caskeleton.sample.portfolio.application.posterimage.PosterImageOperationIdFactory; import dev.caskeleton.sample.portfolio.application.posterimage.PosterImagePublicationPolicy; +import dev.caskeleton.sample.portfolio.application.posterimage.PosterImagePublicationReservation; import dev.caskeleton.sample.portfolio.application.posterimage.PosterImageSanitizedIdempotencyContextFactory; import dev.caskeleton.sample.portfolio.application.posterimage.PosterImageUploadIntent; import dev.caskeleton.sample.portfolio.application.posterimage.PosterImageUploadIntentClaim; +import dev.caskeleton.sample.portfolio.application.posterimage.PosterImageUploadIntentConflictException; import dev.caskeleton.sample.portfolio.application.posterimage.PosterImageUploadIntentState; import dev.caskeleton.sample.portfolio.application.posterimage.PosterImageUploadIntentStorePort; import dev.caskeleton.sample.portfolio.domain.poster.PosterId; @@ -49,14 +51,22 @@ import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.time.ZoneOffset; +import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashMap; +import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +/** + * Publication runs as: reserve (transaction) -> stage, verify and claim the object (no transaction) + * -> record PENDING and append the prepared event (transaction). Every transaction boundary here + * rejects nesting, so each test also proves no step opens a transaction inside another. + */ class PosterImagePublicationWorkflowTest { private static final Instant NOW = Instant.parse("2026-07-29T00:00:00Z"); @@ -68,29 +78,28 @@ class PosterImagePublicationWorkflowTest { ObjectStageHandle.parse("osh1.0123456789ab.0123456789abcdefghjkmnpqrs.f3226a9833"); private static final ObjectVersionToken VERSION = ObjectVersionToken.parse("osv1.0123456789ab.0123456789abcdefghjkmnpqrs.6678c6821f"); + private static final String OPERATION = "0190bd6e-7c3e-7abc-8def-012345678901"; - @Test - void commitsTx1BeforeProducerAndTx2OnlyAfterExactStageHandoff() { - TrackingTransactions transactions = new TrackingTransactions(); - FakeIntents intents = new FakeIntents(); - StagedObjectPublicationPort publications = mock(StagedObjectPublicationPort.class); - ObjectPublicationHandoffPort handoffs = mock(ObjectPublicationHandoffPort.class); - PosterImagePublicationEventPublisher events = mock(PosterImagePublicationEventPublisher.class); - AtomicInteger produced = new AtomicInteger(); + private final DirectTransactionPort transactions = DirectTransactionPort.rejectingNesting(); + private final FakeIntents intents = new FakeIntents(); + private final StagedObjectPublicationPort publications = mock(StagedObjectPublicationPort.class); + private final ObjectPublicationHandoffPort handoffs = mock(ObjectPublicationHandoffPort.class); + private final List> objectCallsInsideTransaction = new ArrayList<>(); + private final List> appendedInsideTransaction = new ArrayList<>(); + private final AtomicInteger producedBytes = new AtomicInteger(); + private final PublishPosterImageUseCase useCase = useCase(); + @BeforeEach + void objectStorageRecordsWhetherATransactionIsActive() { when(publications.stage(any(), any())) .thenAnswer( invocation -> { - assertThat(transactions.active).isFalse(); - var request = - (dev.caskeleton.application.objectstorage.request.ObjectStageRequest) - invocation.getArgument(0); - var producer = - (dev.caskeleton.application.objectstorage.content.ObjectContentProducer) - invocation.getArgument(1); + objectCallsInsideTransaction.add(Map.entry("stage", transactions.active())); + ObjectStageRequest request = invocation.getArgument(0); + ObjectContentProducer producer = invocation.getArgument(1); ObjectContentProductionContext context = ObjectContentProductionContext.open(request.budget(), request.cancellation(), 64); - producer.produce(context, (bytes, offset, length) -> produced.addAndGet(length)); + producer.produce(context, (bytes, offset, length) -> producedBytes.addAndGet(length)); context.invalidate(); return new ObjectStageReceipt( request.operationKey(), STAGE, VERSION, CONTENT, ObjectMutationOutcome.APPLIED); @@ -98,20 +107,17 @@ class PosterImagePublicationWorkflowTest { when(publications.verifyIntegrity(any())) .thenAnswer( invocation -> { - assertThat(transactions.active).isFalse(); - var request = - (dev.caskeleton.application.objectstorage.request.ObjectVerifyRequest) - invocation.getArgument(0); + objectCallsInsideTransaction.add(Map.entry("verifyIntegrity", transactions.active())); + ObjectVerifyRequest request = invocation.getArgument(0); return new ObjectVerificationReceipt( request.operationKey(), STAGE, VERSION, CONTENT, ObjectMutationOutcome.APPLIED); }); when(handoffs.claimForPublication(any())) .thenAnswer( invocation -> { - assertThat(transactions.active).isFalse(); - var request = - (dev.caskeleton.application.objectstorage.request.ObjectHandoffClaimRequest) - invocation.getArgument(0); + objectCallsInsideTransaction.add( + Map.entry("claimForPublication", transactions.active())); + ObjectHandoffClaimRequest request = invocation.getArgument(0); return new ObjectHandoffReceipt( request.operationKey(), STAGE, @@ -119,112 +125,137 @@ class PosterImagePublicationWorkflowTest { NOW.plusSeconds(60), ObjectMutationOutcome.APPLIED); }); - doAnswer( - invocation -> { - assertThat(transactions.active).isTrue(); - return null; - }) - .when(events) - .publishPrepared(any()); + } + @Test + void stagesVerifiesAndClaimsTheObjectOutsideAnyTransaction() { + // when + useCase.handle(command(helloProducer())); + + // then + assertThat(objectCallsInsideTransaction) + .containsExactly( + Map.entry("stage", false), + Map.entry("verifyIntegrity", false), + Map.entry("claimForPublication", false)); + } + + @Test + void appendsThePreparedEventInsideATransaction() { + // when + useCase.handle(command(helloProducer())); + + // then + assertThat(appendedInsideTransaction) + .containsExactly(Map.entry("poster.image-attachment-prepared.v1", true)); + } + + @Test + void replayAfterPendingReturnsTheFirstReservation() { + // given + PosterImagePublicationReservation first = useCase.handle(command(helloProducer())); + + // when + PosterImagePublicationReservation replay = useCase.handle(command(helloProducer())); + + // then + assertThat(replay).isEqualTo(first); + } + + @Test + void replayAfterPendingDoesNotRunTheProducerAgain() { + // given + useCase.handle(command(helloProducer())); + AtomicInteger replayProducerRuns = new AtomicInteger(); + + // when + useCase.handle(command((context, sink) -> replayProducerRuns.incrementAndGet())); + + // then + assertThat(List.of(producedBytes.get(), replayProducerRuns.get())).containsExactly(5, 0); + } + + @Test + void replayAfterPendingLeavesTheUploadIntentPending() { + // given + useCase.handle(command(helloProducer())); + + // when + useCase.handle(command(helloProducer())); + + // then + assertThat(intents.only().state()).isEqualTo(PosterImageUploadIntentState.PENDING); + } + + @Test + void publicationAndReplayCommitThreeWriteTransactionsNeverNested() { + // given + useCase.handle(command(helloProducer())); + + // when + useCase.handle(command(helloProducer())); + + // then + // publication: reserve, read back, prepare; replay: re-enter the reservation, read back + assertThat(transactions.committed()) + .containsExactly( + Boundary.WRITE, Boundary.READ, Boundary.WRITE, Boundary.WRITE, Boundary.READ); + } + + private PublishPosterImageUseCase useCase() { var digester = new HmacPosterImageIdempotencyScopeDigester( "key-v1", Map.of("key-v1", "0123456789abcdef0123456789abcdef".getBytes(StandardCharsets.UTF_8))); - PublishPosterImageUseCase useCase = - new PublishPosterImageUseCase( - intents, - new PosterImageSanitizedIdempotencyContextFactory(digester), - () -> - new PosterImageOperationIdFactory.AllocatedOperation( - UUID.fromString("0190bd6e-7c3e-7abc-8def-012345678901"), - ObjectOperationId.of("0190bd6e-7c3e-7abc-8def-012345678901")), - new IdempotencyExecutor(new FakeIdempotencyStore(), CLOCK, Duration.ofHours(24)), - transactions, - publications, - handoffs, - events, - new PosterImagePublicationPolicy(1024), - ObjectDestinationId.of("poster"), - ObjectOperationEpoch.of("poster-image-v1"), + return new PublishPosterImageUseCase( + intents, + new PosterImageSanitizedIdempotencyContextFactory(digester), + () -> + new PosterImageOperationIdFactory.AllocatedOperation( + UUID.fromString(OPERATION), ObjectOperationId.of(OPERATION)), + new IdempotencyExecutor( + new InMemoryIdempotencyStore(), + Duration.ofSeconds(30), Duration.ofHours(24), - Duration.ofMinutes(1), - CLOCK); - PublishPosterImageCommand command = - new PublishPosterImageCommand( - POSTER, - 0, - "tenant-a", - "principal-a", - "client-key-a", - CONTENT, - ObjectMediaType.of("image/png"), - (context, sink) -> sink.write("hello".getBytes(StandardCharsets.UTF_8), 0, 5), - CallBudget.fromNow(Duration.ofMinutes(1)), - CancellationView.never()); - - var first = useCase.handle(command); - var replay = - useCase.handle( - new PublishPosterImageCommand( - POSTER, - 0, - "tenant-a", - "principal-a", - "client-key-a", - CONTENT, - ObjectMediaType.of("image/png"), - (context, sink) -> { - throw new AssertionError("producer must not replay after PENDING"); - }, - command.budget(), - command.cancellation())); - - assertThat(first).isEqualTo(replay); - assertThat(produced).hasValue(5); - assertThat(intents.only().state()).isEqualTo(PosterImageUploadIntentState.PENDING); - assertThat(transactions.writeCommits).isEqualTo(3); + Duration.ofHours(24), + "json-v2", + 2), + transactions, + publications, + handoffs, + new PosterImagePublicationEventPublisher( + event -> + appendedInsideTransaction.add(Map.entry(event.eventType(), transactions.active())), + () -> "0190bd6e-7c3e-7abc-8def-0123456789ff", + Optional::empty, + CLOCK), + new PosterImagePublicationPolicy(1024), + ObjectDestinationId.of("poster"), + ObjectOperationEpoch.of("poster-image-v1"), + Duration.ofHours(24), + Duration.ofMinutes(1), + CLOCK); } - private static final class TrackingTransactions implements TransactionPort { - boolean active; - int writeCommits; - - @Override - public T inWrite(java.util.function.Supplier action) { - assertThat(active).isFalse(); - active = true; - try { - T result = action.get(); - writeCommits++; - return result; - } finally { - active = false; - } - } - - @Override - public T inRootWrite(java.util.function.Supplier action) { - return inWrite(action); - } - - @Override - public T inRead(java.util.function.Supplier action) { - assertThat(active).isFalse(); - active = true; - try { - return action.get(); - } finally { - active = false; - } - } - - @Override - public T inNew(java.util.function.Supplier action) { - return inWrite(action); - } + private static PublishPosterImageCommand command(ObjectContentProducer producer) { + return new PublishPosterImageCommand( + POSTER, + 0, + "tenant-a", + "principal-a", + "client-key-a", + CONTENT, + ObjectMediaType.of("image/png"), + producer, + CallBudget.fromNow(Duration.ofMinutes(1)), + CancellationView.never()); } + private static ObjectContentProducer helloProducer() { + return (context, sink) -> sink.write("hello".getBytes(StandardCharsets.UTF_8), 0, 5); + } + + /** Upload intents keyed by operation id; compare-and-set rejects a stale revision. */ private static final class FakeIntents implements PosterImageUploadIntentStorePort { private final Map rows = new LinkedHashMap<>(); @@ -235,8 +266,7 @@ class PosterImagePublicationWorkflowTest { } @Override - public Optional findByOperation( - dev.caskeleton.application.objectstorage.identity.ObjectOperationKey operation) { + public Optional findByOperation(ObjectOperationKey operation) { return Optional.ofNullable(rows.get(operation.operationId().value())); } @@ -257,9 +287,12 @@ class PosterImagePublicationWorkflowTest { @Override public PosterImageUploadIntent compareAndSet( long expectedRevision, PosterImageUploadIntent replacement) { - PosterImageUploadIntent current = rows.get(replacement.operationKey().operationId().value()); - assertThat(current.revision()).isEqualTo(expectedRevision); - rows.put(replacement.operationKey().operationId().value(), replacement); + String key = replacement.operationKey().operationId().value(); + if (rows.get(key).revision() != expectedRevision) { + throw new PosterImageUploadIntentConflictException( + "poster image upload revision conflicts"); + } + rows.put(key, replacement); return replacement; } @@ -273,42 +306,4 @@ class PosterImagePublicationWorkflowTest { return rows.values().iterator().next(); } } - - private static final class FakeIdempotencyStore implements IdempotencyStorePort { - private final Map rows = new LinkedHashMap<>(); - - @Override - public boolean tryBegin( - IdempotencyScope scope, RequestFingerprint fingerprint, Instant expiresAt) { - return rows.putIfAbsent( - scope.storageKey(), - new IdempotencyRecord( - scope, fingerprint, IdempotencyStatus.IN_FLIGHT, null, NOW, expiresAt)) - == null; - } - - @Override - public Optional find(IdempotencyScope scope, Instant now) { - return Optional.ofNullable(rows.get(scope.storageKey())); - } - - @Override - public void complete(IdempotencyScope scope, StoredResponse response) { - IdempotencyRecord current = rows.get(scope.storageKey()); - rows.put( - scope.storageKey(), - new IdempotencyRecord( - current.scope(), - current.fingerprint(), - IdempotencyStatus.COMPLETED, - response, - current.createdAt(), - current.expiresAt())); - } - - @Override - public void discard(IdempotencyScope scope) { - rows.remove(scope.storageKey()); - } - } } diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/poster/PosterImageRetirementCrashMatrixTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/poster/PosterImageRetirementCrashMatrixTest.java index b9104989..b5956804 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/poster/PosterImageRetirementCrashMatrixTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/poster/PosterImageRetirementCrashMatrixTest.java @@ -1,7 +1,8 @@ package dev.caskeleton.sample.portfolio.application.poster; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.assertj.core.api.Assertions.tuple; import dev.caskeleton.application.objectstorage.content.CancellationView; import dev.caskeleton.application.objectstorage.identity.ObjectDestinationId; @@ -12,22 +13,24 @@ 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.port.ObjectRetirementPort; +import dev.caskeleton.application.objectstorage.request.ObjectRetireRequest; import dev.caskeleton.application.outbound.CallBudget; -import dev.caskeleton.application.transaction.TransactionPort; +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; import dev.caskeleton.sample.portfolio.application.command.ReconcilePosterImageRetirementCommand; import dev.caskeleton.sample.portfolio.application.posterimage.PosterImageRetirementIntent; import dev.caskeleton.sample.portfolio.application.posterimage.PosterImageRetirementIntentState; -import dev.caskeleton.sample.portfolio.application.posterimage.PosterImageRetirementIntentStorePort; +import dev.caskeleton.sample.portfolio.application.posterimage.PosterImageRetirementResult; +import dev.caskeleton.sample.portfolio.application.posterimage.PosterImageUploadIntentConflictException; +import dev.caskeleton.sample.portfolio.application.posterimage.testkit.InMemoryPosterImageRetirementIntentStore; import dev.caskeleton.sample.portfolio.domain.poster.PosterId; import dev.caskeleton.sample.portfolio.domain.poster.PosterImageReference; import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.time.ZoneOffset; -import java.util.Optional; +import java.util.ArrayList; +import java.util.List; import java.util.UUID; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.Supplier; import org.junit.jupiter.api.Test; class PosterImageRetirementCrashMatrixTest { @@ -42,62 +45,128 @@ class PosterImageRetirementCrashMatrixTest { private static final ObjectVersionToken VERSION = ObjectVersionToken.parse("osv1.0123456789ab.0123456789abcdefghjkmnpqrs.6678c6821f"); + private final InMemoryPosterImageRetirementIntentStore store = + new InMemoryPosterImageRetirementIntentStore(); + private final DirectTransactionPort transactions = DirectTransactionPort.rejectingNesting(); + private final List retireCalls = new ArrayList<>(); + private final ReconcilePosterImageRetirementUseCase useCase = + new ReconcilePosterImageRetirementUseCase( + store, + transactions, + losesTheFirstResponse(), + ObjectDestinationId.of("poster"), + ObjectOperationEpoch.of("poster-image-v1"), + Clock.fixed(NOW, ZoneOffset.UTC)); + @Test - void responseLossRetriesTheSameExactOperationOutsideTransactions() { - InMemoryRetirements store = new InMemoryRetirements(pending()); - TrackingTransactions transactions = new TrackingTransactions(); - AtomicInteger attempts = new AtomicInteger(); - ObjectRetirementPort objects = - request -> { - assertThat(transactions.active).isFalse(); - assertThat(request.reference().canonicalText()).isEqualTo(REFERENCE.value()); - assertThat(request.exactVersion()).isEqualTo(VERSION); - if (attempts.incrementAndGet() == 1) { - throw new IllegalStateException("response lost"); - } - return new ObjectMutationReceipt( - request.operationKey(), - ObjectMutationOutcome.REPLAYED, - ObjectOperationError.NONE, - NOW); - }; - ReconcilePosterImageRetirementUseCase useCase = useCase(store, transactions, objects); + void lostResponseLeavesTheRetirementPendingForRetry() { + // given + store.createOrRead(pending()); - var first = useCase.handle(command()); - var second = useCase.handle(command()); + // when + PosterImageRetirementResult first = useCase.handle(command()); + // then assertThat(first.state()).isEqualTo(PosterImageRetirementIntentState.PENDING); + } + + @Test + void retryAfterLostResponseRetiresTheImage() { + // given + store.createOrRead(pending()); + useCase.handle(command()); + + // when + PosterImageRetirementResult second = useCase.handle(command()); + + // then assertThat(second.state()).isEqualTo(PosterImageRetirementIntentState.RETIRED); - assertThat(attempts).hasValue(2); - assertThat(store.current.operationId()).isEqualTo(OPERATION); - assertThat(store.current.claimFence()).isEqualTo(2); + } + + @Test + void retryAfterLostResponseSendsTheSameExactRetirementOutsideTransactions() { + // given + store.createOrRead(pending()); + useCase.handle(command()); + + // when + useCase.handle(command()); + + // then + assertThat(retireCalls) + .extracting( + call -> call.request().operationKey().operationId(), + call -> call.request().reference().canonicalText(), + call -> call.request().exactVersion(), + RetireCall::insideTransaction) + .containsExactly( + tuple(OPERATION, REFERENCE.value(), VERSION, false), + tuple(OPERATION, REFERENCE.value(), VERSION, false)); + } + + @Test + void retryAfterLostResponseKeepsTheOperationAndAdvancesTheClaimFence() { + // given + store.createOrRead(pending()); + useCase.handle(command()); + + // when + useCase.handle(command()); + + // then + assertThat(store.all()) + .extracting( + PosterImageRetirementIntent::operationId, PosterImageRetirementIntent::claimFence) + .containsExactly(tuple(OPERATION, 2L)); + } + + @Test + void takeoverOfAnExpiredClaimAdvancesTheFence() { + // given + PosterImageRetirementIntent first = pending().claim(0, CLAIMANT, NOW, Duration.ofSeconds(1)); + + // when + PosterImageRetirementIntent takeover = takeover(first); + + // then + assertThat(takeover.claimFence()).isEqualTo(2); } @Test void expiredWorkerCannotCommitAfterTakeoverAdvancesFence() { + // given PosterImageRetirementIntent first = pending().claim(0, CLAIMANT, NOW, Duration.ofSeconds(1)); - PosterImageRetirementIntent takeover = - first.claim( - first.revision(), - "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", - NOW.plusSeconds(2), - Duration.ofSeconds(30)); + PosterImageRetirementIntent takeover = takeover(first); - assertThat(takeover.claimFence()).isEqualTo(2); - assertThatThrownBy( - () -> takeover.retired(takeover.revision(), first.claimFence(), NOW.plusSeconds(3))) - .isInstanceOf(RuntimeException.class); + // when + Throwable thrown = + catchThrowable( + () -> takeover.retired(takeover.revision(), first.claimFence(), NOW.plusSeconds(3))); + + // then + assertThat(thrown) + .isInstanceOf(PosterImageUploadIntentConflictException.class) + .hasMessage("poster image retirement fence conflicts"); } - private static ReconcilePosterImageRetirementUseCase useCase( - InMemoryRetirements store, TrackingTransactions transactions, ObjectRetirementPort objects) { - return new ReconcilePosterImageRetirementUseCase( - store, - transactions, - objects, - ObjectDestinationId.of("poster"), - ObjectOperationEpoch.of("poster-image-v1"), - Clock.fixed(NOW, ZoneOffset.UTC)); + /** Throws on the first call as if the response were lost, then reports the retirement. */ + private ObjectRetirementPort losesTheFirstResponse() { + return request -> { + retireCalls.add(new RetireCall(request, transactions.active())); + if (retireCalls.size() == 1) { + throw new IllegalStateException("response lost"); + } + return new ObjectMutationReceipt( + request.operationKey(), ObjectMutationOutcome.REPLAYED, ObjectOperationError.NONE, NOW); + }; + } + + private static PosterImageRetirementIntent takeover(PosterImageRetirementIntent expired) { + return expired.claim( + expired.revision(), + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + NOW.plusSeconds(2), + Duration.ofSeconds(30)); } private static ReconcilePosterImageRetirementCommand command() { @@ -120,72 +189,5 @@ class PosterImageRetirementCrashMatrixTest { NOW); } - private static final class InMemoryRetirements implements PosterImageRetirementIntentStorePort { - private PosterImageRetirementIntent current; - - private InMemoryRetirements(PosterImageRetirementIntent current) { - this.current = current; - } - - @Override - public PosterImageRetirementIntent createOrRead(PosterImageRetirementIntent proposed) { - return current; - } - - @Override - public Optional findByOperation(ObjectOperationId operation) { - return Optional.of(current); - } - - @Override - public PosterImageRetirementIntent compareAndSet( - long expectedRevision, PosterImageRetirementIntent replacement) { - assertThat(current.revision()).isEqualTo(expectedRevision); - current = replacement; - return replacement; - } - - @Override - public Optional claimReady( - String claimantDigest, Instant now, Duration leaseDuration) { - if (current.state().terminal() - || (current.retryAt() != null && current.retryAt().isAfter(now))) { - return Optional.empty(); - } - PosterImageRetirementIntent claimed = - current.claim(current.revision(), claimantDigest, now, leaseDuration); - current = claimed; - return Optional.of(claimed); - } - } - - private static final class TrackingTransactions implements TransactionPort { - private boolean active; - - @Override - public T inWrite(Supplier action) { - assertThat(active).isFalse(); - active = true; - try { - return action.get(); - } finally { - active = false; - } - } - - @Override - public T inRootWrite(Supplier action) { - return inWrite(action); - } - - @Override - public T inRead(Supplier action) { - return action.get(); - } - - @Override - public T inNew(Supplier action) { - return inWrite(action); - } - } + private record RetireCall(ObjectRetireRequest request, boolean insideTransaction) {} } diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/posterimage/PosterImageSanitizedIdempotencyContextFactoryTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/posterimage/PosterImageSanitizedIdempotencyContextFactoryTest.java index ed626a7b..0d1600f3 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/posterimage/PosterImageSanitizedIdempotencyContextFactoryTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/posterimage/PosterImageSanitizedIdempotencyContextFactoryTest.java @@ -2,33 +2,37 @@ package dev.caskeleton.sample.portfolio.application.posterimage; import static org.assertj.core.api.Assertions.assertThat; -import dev.caskeleton.application.idempotency.RequestFingerprint; +import dev.caskeleton.application.idempotency.IdempotencyScopeDigest; import dev.caskeleton.sample.portfolio.adapter.outbound.identifier.HmacPosterImageIdempotencyScopeDigester; import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.HexFormat; import java.util.Map; import org.junit.jupiter.api.Test; class PosterImageSanitizedIdempotencyContextFactoryTest { @Test - void rawCallerDimensionsNeverEnterTheGenericStoreScope() { + void genericStoreScopeIsTheActiveHmacDigestAndCarriesNoRawCallerDimension() { + // given var digester = new HmacPosterImageIdempotencyScopeDigester( "key-v1", Map.of("key-v1", "0123456789abcdef0123456789abcdef".getBytes(StandardCharsets.UTF_8))); var factory = new PosterImageSanitizedIdempotencyContextFactory(digester); + // when var result = - factory.create( - "tenant-raw-secret", - "principal-raw-secret", - "idempotency-raw-secret", - RequestFingerprint.ofSha256(new byte[] {1})); - String storageKey = result.generic().scope().storageKey(); + factory.create("tenant-raw-secret", "principal-raw-secret", "idempotency-raw-secret"); - assertThat(storageKey) - .doesNotContain("tenant-raw-secret", "principal-raw-secret", "idempotency-raw-secret") - .contains(PosterImageSanitizedIdempotencyContextFactory.RESERVATION_USE_CASE); - assertThat(result.retainedScopes()).contains(result.activeScope()); + // then + assertThat(result.scope()) + .isEqualTo( + new IdempotencyScopeDigest( + HexFormat.of() + .formatHex( + Base64.getUrlDecoder().decode(result.activeScope().base64UrlDigest())), + 1, + PosterImageSanitizedIdempotencyContextFactory.RESERVATION_OPERATION_CODE)); } } diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/worklog/CreateWorkLogOutboxTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/worklog/CreateWorkLogOutboxTest.java index 0ff86a5f..d09f3ab0 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/worklog/CreateWorkLogOutboxTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/worklog/CreateWorkLogOutboxTest.java @@ -1,21 +1,19 @@ package dev.caskeleton.sample.portfolio.application.worklog; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.tuple; import dev.caskeleton.application.observability.CorrelationIdPort; import dev.caskeleton.application.outbox.LegacyOutboxAppendPort; import dev.caskeleton.application.outbox.NewOutboxEvent; -import dev.caskeleton.application.transaction.TransactionPort; +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort.Boundary; import dev.caskeleton.sample.portfolio.application.command.CreateWorkLogCommand; import dev.caskeleton.sample.portfolio.application.event.WorkLogReservedIntegrationEventMapper; -import dev.caskeleton.sample.portfolio.domain.worklog.OutboxEventIdFactory; import dev.caskeleton.sample.portfolio.domain.worklog.WorkCategory; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLog; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogId; -import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogIdFactory; -import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogPage; -import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogRepository; -import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogSortField; +import dev.caskeleton.sample.portfolio.domain.worklog.testkit.InMemoryWorkLogRepository; import java.time.Clock; import java.time.Instant; import java.time.LocalDate; @@ -23,277 +21,150 @@ import java.time.ZoneOffset; import java.util.ArrayList; import java.util.List; import java.util.Optional; -import java.util.function.Supplier; import org.junit.jupiter.api.Test; /** - * Verifies that {@link CreateWorkLogUseCase} appends a {@code WorkLogReserved} outbox event inside - * the same {@code tx.inWrite} block as the aggregate save (feature-domain-event-outbox-contract - * D2). - * - *

    Uses hand-rolled fakes — no Spring context, no JPA. + * {@link CreateWorkLogUseCase} appends a {@code WorkLogReserved} outbox event in the same {@code + * tx.inWrite} as the aggregate save (feature-domain-event-outbox-contract D2). */ class CreateWorkLogOutboxTest { - // ---- fakes ---- + private static final WorkLogId FIXED_ID = WorkLogId.of("0190bd6e-7c3e-7abc-8def-0123456789ab"); + private static final String FIXED_EVENT_ID = "0190bd6e-7c3e-7abc-8def-0123456789ff"; + private static final Instant NOW = Instant.parse("2025-06-01T10:00:00Z"); - static final WorkLogId FIXED_ID = WorkLogId.of("0190bd6e-7c3e-7abc-8def-0123456789ab"); - static final WorkLogIdFactory IDS = () -> FIXED_ID; - static final String FIXED_EVENT_ID = "0190bd6e-7c3e-7abc-8def-0123456789ff"; - static final OutboxEventIdFactory EVENT_IDS = () -> FIXED_EVENT_ID; - static final Clock FIXED_CLOCK = - Clock.fixed(Instant.parse("2025-06-01T10:00:00Z"), ZoneOffset.UTC); - static final CorrelationIdPort NO_CORRELATION = Optional::empty; + private final DirectTransactionPort tx = new DirectTransactionPort(); + private final List appended = new ArrayList<>(); + private final List appendedInsideTransaction = new ArrayList<>(); - static class FakeRepo implements WorkLogRepository { - final List store = new ArrayList<>(); - - @Override - public WorkLog save(WorkLog w) { - store.add(w); - return w; - } - - @Override - public Optional findById(WorkLogId id) { - return store.stream().filter(x -> x.id().equals(id)).findFirst(); - } - - @Override - public WorkLogPage findPage( - int page, int size, WorkLogSortField sortField, boolean ascending, WorkCategory category) { - return new WorkLogPage(List.of(), 0); - } - - @Override - public boolean existsById(WorkLogId id) { - return findById(id).isPresent(); - } - - @Override - public void deleteById(WorkLogId id) { - store.removeIf(x -> x.id().equals(id)); - } - } - - static class CapturingOutboxPort implements LegacyOutboxAppendPort { - final List appended = new ArrayList<>(); - boolean appendCalledInTx = false; - - void markInTx() { - appendCalledInTx = true; - } - - @Override - public void append(NewOutboxEvent event) { - appended.add(event); - } - } - - /** - * A {@link TransactionPort} that tracks whether {@code outboxAppendPort.append} was called inside - * the {@code inWrite} callback — used to assert D2 (same-tx dual-write guarantee). - */ - static class TrackingTx implements TransactionPort { - private final CapturingOutboxPort outboxPort; - boolean appendHappenedInsideTx = false; - - TrackingTx(CapturingOutboxPort outboxPort) { - this.outboxPort = outboxPort; - } - - @Override - public T inWrite(Supplier action) { - int beforeSize = outboxPort.appended.size(); - T result = action.get(); - // If the outbox port was called during the action, the size increased - appendHappenedInsideTx = outboxPort.appended.size() > beforeSize; - return result; - } - - @Override - public T inRootWrite(Supplier action) { - return inWrite(action); - } - - @Override - public T inRead(Supplier action) { - return action.get(); - } - - @Override - public T inNew(Supplier action) { - return action.get(); - } - } - - // ---- helpers ---- - - private CreateWorkLogCommand createCmd() { - return new CreateWorkLogCommand( - "owner1", - "Test Work", - WorkCategory.BACKEND, - "summary", - "content", - List.of("java"), - List.of(), - LocalDate.of(2025, 1, 1), - null); - } - - // ---- tests ---- + /** application-core's in-memory outbox does not expose appended events, so record them here. */ + private final LegacyOutboxAppendPort outbox = + event -> { + appended.add(event); + appendedInsideTransaction.add(tx.active()); + }; @Test - void createAppendsOutboxEventWithCorrectEventType() { - FakeRepo repo = new FakeRepo(); - CapturingOutboxPort outbox = new CapturingOutboxPort(); - TrackingTx tx = new TrackingTx(outbox); + void appendsOneEventOfTheWorkLogReservedType() { + // when + createWith(Optional::empty); - new CreateWorkLogUseCase(repo, IDS, EVENT_IDS, outbox, NO_CORRELATION, FIXED_CLOCK, tx) - .handle(createCmd()); - - assertThat(outbox.appended).hasSize(1); - assertThat(outbox.appended.get(0).eventType()) - .isEqualTo(WorkLogReservedIntegrationEventMapper.EVENT_TYPE); + // then + assertThat(appended) + .extracting(NewOutboxEvent::eventType) + .containsExactly(WorkLogReservedIntegrationEventMapper.EVENT_TYPE); } @Test - void createAppendsOutboxEventInsideTxInWriteBlock() { - // D2: append must happen inside the same tx.inWrite as the aggregate save - FakeRepo repo = new FakeRepo(); - CapturingOutboxPort outbox = new CapturingOutboxPort(); - TrackingTx tx = new TrackingTx(outbox); + void appendsTheEventInsideTheTransaction() { + // when + createWith(Optional::empty); - new CreateWorkLogUseCase(repo, IDS, EVENT_IDS, outbox, NO_CORRELATION, FIXED_CLOCK, tx) - .handle(createCmd()); - - assertThat(tx.appendHappenedInsideTx) - .as("LegacyOutboxAppendPort.append must be called inside tx.inWrite (D2)") - .isTrue(); + // then + assertThat(appendedInsideTransaction) + .as("LegacyOutboxAppendPort.append must run inside tx.inWrite (D2)") + .containsExactly(true); } @Test - void createOutboxEventHasAggregateIdMatchingWorklogId() { - FakeRepo repo = new FakeRepo(); - CapturingOutboxPort outbox = new CapturingOutboxPort(); - TransactionPort tx = plainTx(); + void savesAndAppendsInOneWriteTransaction() { + // when + createWith(Optional::empty); - WorkLog created = - new CreateWorkLogUseCase(repo, IDS, EVENT_IDS, outbox, NO_CORRELATION, FIXED_CLOCK, tx) - .handle(createCmd()); - - assertThat(outbox.appended).hasSize(1); - assertThat(outbox.appended.get(0).aggregateId()).isEqualTo(created.id().value()); + // then + assertThat(tx.committed()).containsExactly(Boundary.WRITE); } @Test - void createOutboxEventIdempotencyKeyEqualsEventId() { - // I12: idempotencyKey = eventId - FakeRepo repo = new FakeRepo(); - CapturingOutboxPort outbox = new CapturingOutboxPort(); - TransactionPort tx = plainTx(); + void usesTheCreatedWorkLogIdAsTheAggregateId() { + // when + WorkLog created = createWith(Optional::empty); - new CreateWorkLogUseCase(repo, IDS, EVENT_IDS, outbox, NO_CORRELATION, FIXED_CLOCK, tx) - .handle(createCmd()); + // then + assertThat(appended) + .extracting(NewOutboxEvent::aggregateId) + .containsExactly(created.id().value()); + } - NewOutboxEvent event = outbox.appended.get(0); - assertThat(event.idempotencyKey()) + @Test + void usesTheEventIdAsTheIdempotencyKey() { + // when + createWith(Optional::empty); + + // then + assertThat(appended) .as("idempotencyKey must equal eventId (I12)") - .isEqualTo(event.eventId()); + .extracting(NewOutboxEvent::eventId, NewOutboxEvent::idempotencyKey) + .containsExactly(tuple(FIXED_EVENT_ID, FIXED_EVENT_ID)); } @Test - void createOutboxEventOccurredAtUsesInjectedClock() { - FakeRepo repo = new FakeRepo(); - CapturingOutboxPort outbox = new CapturingOutboxPort(); - TransactionPort tx = plainTx(); + void stampsOccurredAtFromTheInjectedClock() { + // when + createWith(Optional::empty); - new CreateWorkLogUseCase(repo, IDS, EVENT_IDS, outbox, NO_CORRELATION, FIXED_CLOCK, tx) - .handle(createCmd()); - - assertThat(outbox.appended.get(0).occurredAt()) - .isEqualTo(Instant.parse("2025-06-01T10:00:00Z")); + // then + assertThat(appended).extracting(NewOutboxEvent::occurredAt).containsExactly(NOW); } @Test - void createOutboxEventPayloadContainsWorklogIdAndCategory() { - FakeRepo repo = new FakeRepo(); - CapturingOutboxPort outbox = new CapturingOutboxPort(); - TransactionPort tx = plainTx(); + void writesTheWorkLogIdAndCategoryIntoThePayload() { + // when + createWith(Optional::empty); - new CreateWorkLogUseCase(repo, IDS, EVENT_IDS, outbox, NO_CORRELATION, FIXED_CLOCK, tx) - .handle(createCmd()); - - String payload = outbox.appended.get(0).payload(); - assertThat(payload).contains(FIXED_ID.value()); - assertThat(payload).contains("BACKEND"); + // then + assertThat(appended.get(0).payload()).contains(FIXED_ID.value(), "BACKEND"); } @Test - void createOutboxEventCorrelationIdFallsBackToEventIdWhenContextIsAbsent() { - FakeRepo repo = new FakeRepo(); - CapturingOutboxPort outbox = new CapturingOutboxPort(); - TransactionPort tx = plainTx(); + void fallsBackToTheEventIdAsCorrelationIdWhenNoneIsInContext() { + // when + createWith(Optional::empty); - new CreateWorkLogUseCase(repo, IDS, EVENT_IDS, outbox, NO_CORRELATION, FIXED_CLOCK, tx) - .handle(createCmd()); - - NewOutboxEvent event = outbox.appended.get(0); - assertThat(event.correlationId()) + // then + assertThat(appended) .as("self-correlation fallback: correlationId = eventId when context is absent") - .isEqualTo(event.eventId()); + .extracting(NewOutboxEvent::correlationId) + .containsExactly(FIXED_EVENT_ID); } @Test - void createOutboxEventUsesCorrelationIdPortWhenPresent() { - FakeRepo repo = new FakeRepo(); - CapturingOutboxPort outbox = new CapturingOutboxPort(); - TransactionPort tx = plainTx(); + void usesTheCorrelationIdFromContextWhenPresent() { + // when + createWith(() -> Optional.of("test-corr-123")); - CorrelationIdPort correlationIdPort = () -> Optional.of("test-corr-123"); - new CreateWorkLogUseCase(repo, IDS, EVENT_IDS, outbox, correlationIdPort, FIXED_CLOCK, tx) - .handle(createCmd()); - - assertThat(outbox.appended.get(0).correlationId()).isEqualTo("test-corr-123"); + // then + assertThat(appended).extracting(NewOutboxEvent::correlationId).containsExactly("test-corr-123"); } @Test - void createOutboxEventFallsBackToEventIdWhenCorrelationIdPortReturnsBlank() { - FakeRepo repo = new FakeRepo(); - CapturingOutboxPort outbox = new CapturingOutboxPort(); - TransactionPort tx = plainTx(); - CorrelationIdPort correlationIdPort = () -> Optional.of(" "); + void fallsBackToTheEventIdAsCorrelationIdWhenTheContextValueIsBlank() { + // when + createWith(() -> Optional.of(" ")); - new CreateWorkLogUseCase(repo, IDS, EVENT_IDS, outbox, correlationIdPort, FIXED_CLOCK, tx) - .handle(createCmd()); - - NewOutboxEvent event = outbox.appended.get(0); - assertThat(event.correlationId()).isEqualTo(event.eventId()); + // then + assertThat(appended).extracting(NewOutboxEvent::correlationId).containsExactly(FIXED_EVENT_ID); } - // Plain pass-through tx (no tracking) - private static TransactionPort plainTx() { - return new TransactionPort() { - @Override - public T inWrite(Supplier a) { - return a.get(); - } - - @Override - public T inRootWrite(Supplier a) { - return a.get(); - } - - @Override - public T inRead(Supplier a) { - return a.get(); - } - - @Override - public T inNew(Supplier a) { - return a.get(); - } - }; + private WorkLog createWith(CorrelationIdPort correlation) { + return new CreateWorkLogUseCase( + new InMemoryWorkLogRepository(), + () -> FIXED_ID, + () -> FIXED_EVENT_ID, + outbox, + correlation, + Clock.fixed(NOW, ZoneOffset.UTC), + tx) + .handle( + new CreateWorkLogCommand( + "owner1", + "Test Work", + WorkCategory.BACKEND, + "summary", + "content", + List.of("java"), + List.of(), + LocalDate.of(2025, 1, 1), + null)); } } diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/worklog/GetRepoStatsUseCaseTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/worklog/GetRepoStatsUseCaseTest.java index 29123aa0..53c73f51 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/worklog/GetRepoStatsUseCaseTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/worklog/GetRepoStatsUseCaseTest.java @@ -2,17 +2,37 @@ package dev.caskeleton.sample.portfolio.application.worklog; import static org.assertj.core.api.Assertions.assertThat; -import dev.caskeleton.sample.portfolio.application.port.RepoStatsPort; import dev.caskeleton.sample.portfolio.application.query.GetRepoStatsQuery; import dev.caskeleton.sample.portfolio.domain.worklog.RepoStats; +import java.util.ArrayList; +import java.util.List; import org.junit.jupiter.api.Test; class GetRepoStatsUseCaseTest { + private static final String REPO_URL = "https://github.com/owner/repo"; + private static final RepoStats STATS = new RepoStats("owner/repo", 7, "2025-01-01T00:00:00Z"); + + // RepoStatsPort has no other test double; this recording lambda is its only fake. + private final List requestedRepoUrls = new ArrayList<>(); + private final GetRepoStatsUseCase useCase = + new GetRepoStatsUseCase( + repoUrl -> { + requestedRepoUrls.add(repoUrl); + return STATS; + }); + @Test - void delegatesToPort() { - RepoStatsPort port = repoUrl -> new RepoStats("owner/repo", 7, "2025-01-01T00:00:00Z"); - RepoStats result = new GetRepoStatsUseCase(port).handle(new GetRepoStatsQuery("x")); - assertThat(result.stars()).isEqualTo(7); + void returnsTheStatsThePortReports() { + assertThat(useCase.handle(new GetRepoStatsQuery(REPO_URL))).isEqualTo(STATS); + } + + @Test + void asksThePortForTheQueriedRepositoryOnce() { + // when + useCase.handle(new GetRepoStatsQuery(REPO_URL)); + + // then + assertThat(requestedRepoUrls).containsExactly(REPO_URL); } } diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/worklog/ListRecentWorkLogSummariesUseCaseTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/worklog/ListRecentWorkLogSummariesUseCaseTest.java index aa20e9eb..8ccb02d4 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/worklog/ListRecentWorkLogSummariesUseCaseTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/worklog/ListRecentWorkLogSummariesUseCaseTest.java @@ -2,78 +2,62 @@ package dev.caskeleton.sample.portfolio.application.worklog; import static org.assertj.core.api.Assertions.assertThat; -import dev.caskeleton.application.transaction.TransactionPort; -import dev.caskeleton.sample.portfolio.application.port.WorkLogSummaryQueryPort; +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort.Boundary; import dev.caskeleton.sample.portfolio.application.query.ListRecentWorkLogSummariesQuery; import dev.caskeleton.sample.portfolio.application.query.WorkLogSummary; import dev.caskeleton.sample.portfolio.domain.worklog.WorkCategory; import java.time.LocalDate; +import java.util.ArrayList; import java.util.List; -import java.util.function.Supplier; import org.junit.jupiter.api.Test; class ListRecentWorkLogSummariesUseCaseTest { - /** Records whether the read happened inside {@link TransactionPort#inRead} (D4 boundary). */ - private static final class RecordingTransactionPort implements TransactionPort { - boolean inReadCalled; + private static final WorkLogSummary SUMMARY = + new WorkLogSummary( + "0190bd6e-7c3e-7abc-8def-0123456789ab", + "Tuned Hikari pool", + WorkCategory.DATABASE, + LocalDate.of(2025, 1, 1), + null); - @Override - public T inWrite(Supplier action) { - return action.get(); - } + private final DirectTransactionPort tx = new DirectTransactionPort(); + // WorkLogSummaryQueryPort has no other test double; this recording lambda is its only fake. + private final List requestedLimits = new ArrayList<>(); + private final List readInsideTransaction = new ArrayList<>(); + private final ListRecentWorkLogSummariesUseCase useCase = + new ListRecentWorkLogSummariesUseCase( + limit -> { + requestedLimits.add(limit); + readInsideTransaction.add(tx.active()); + return List.of(SUMMARY); + }, + tx); - @Override - public T inRootWrite(Supplier action) { - return action.get(); - } - - @Override - public T inRead(Supplier action) { - inReadCalled = true; - return action.get(); - } - - @Override - public T inNew(Supplier action) { - return action.get(); - } + @Test + void returnsTheSummariesTheQueryPortReads() { + assertThat(useCase.handle(new ListRecentWorkLogSummariesQuery(10))).containsExactly(SUMMARY); } @Test - void delegatesToQueryPortInsideReadTransaction() { - WorkLogSummary summary = - new WorkLogSummary( - "0190bd6e-7c3e-7abc-8def-0123456789ab", - "Tuned Hikari pool", - WorkCategory.DATABASE, - LocalDate.of(2025, 1, 1), - null); - WorkLogSummaryQueryPort port = limit -> List.of(summary); - RecordingTransactionPort tx = new RecordingTransactionPort(); + void readsTheSummariesInsideOneReadTransaction() { + // when + useCase.handle(new ListRecentWorkLogSummariesQuery(10)); - List result = - new ListRecentWorkLogSummariesUseCase(port, tx) - .handle(new ListRecentWorkLogSummariesQuery(10)); - - assertThat(result).containsExactly(summary); - assertThat(tx.inReadCalled) + // then + assertThat(readInsideTransaction) .as("projection read must run inside TransactionPort.inRead (D4 default)") - .isTrue(); + .containsExactly(true); + assertThat(tx.committed()).containsExactly(Boundary.READ); } @Test void forwardsTheRequestedLimitToThePort() { - int[] seenLimit = {-1}; - WorkLogSummaryQueryPort port = - limit -> { - seenLimit[0] = limit; - return List.of(); - }; + // when + useCase.handle(new ListRecentWorkLogSummariesQuery(7)); - new ListRecentWorkLogSummariesUseCase(port, new RecordingTransactionPort()) - .handle(new ListRecentWorkLogSummariesQuery(7)); - - assertThat(seenLimit[0]).isEqualTo(7); + // then + assertThat(requestedLimits).containsExactly(7); } } diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/worklog/WorkLogUseCasesTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/worklog/WorkLogUseCasesTest.java index df00a12c..15ed1c46 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/worklog/WorkLogUseCasesTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/worklog/WorkLogUseCasesTest.java @@ -1,12 +1,16 @@ package dev.caskeleton.sample.portfolio.application.worklog; +import static dev.caskeleton.sample.portfolio.domain.worklog.WorkLogStatus.CLOSED; +import static dev.caskeleton.sample.portfolio.domain.worklog.WorkLogStatus.IN_PROGRESS; +import static dev.caskeleton.sample.portfolio.domain.worklog.WorkLogStatus.OPEN; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; import com.github.f4b6a3.uuid.UuidCreator; import dev.caskeleton.application.observability.CorrelationIdPort; import dev.caskeleton.application.outbox.LegacyOutboxAppendPort; -import dev.caskeleton.application.transaction.TransactionPort; +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort.Boundary; import dev.caskeleton.sample.portfolio.application.command.BatchCreateWorkLogsCommand; import dev.caskeleton.sample.portfolio.application.command.CreateWorkLogCommand; import dev.caskeleton.sample.portfolio.application.command.DeleteWorkLogCommand; @@ -14,107 +18,281 @@ import dev.caskeleton.sample.portfolio.application.command.UpdateWorkLogCommand; import dev.caskeleton.sample.portfolio.application.exception.WorkLogNotFoundException; import dev.caskeleton.sample.portfolio.application.query.GetWorkLogQuery; import dev.caskeleton.sample.portfolio.application.query.ListWorkLogsQuery; -import dev.caskeleton.sample.portfolio.domain.worklog.OutboxEventIdFactory; import dev.caskeleton.sample.portfolio.domain.worklog.WorkCategory; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLog; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogId; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogIdFactory; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogInvariantException; +import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogInvariantException.Reason; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogPage; -import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogRepository; -import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogSortField; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogStatus; +import dev.caskeleton.sample.portfolio.domain.worklog.testkit.InMemoryWorkLogRepository; import dev.caskeleton.shared.request.Patch; import java.time.Clock; import java.time.LocalDate; -import java.util.ArrayList; import java.util.List; import java.util.Optional; -import java.util.function.Supplier; +import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; class WorkLogUseCasesTest { - /** A valid UUID guaranteed absent from an empty FakeRepo. */ + /** A valid UUID never minted by {@link #IDS}. */ private static final WorkLogId ABSENT_ID = WorkLogId.of("0190bd6e-7c3e-7abc-8def-0123456789ab"); - /** Server-assigned id source (D5) — distinct monotonic UUIDv7s per create. */ + /** Server-assigned id source (D5): a distinct monotonic UUIDv7 per create. */ private static final WorkLogIdFactory IDS = () -> WorkLogId.of(UuidCreator.getTimeOrderedEpochPlus1().toString()); - static class FakeRepo implements WorkLogRepository { - final List store = new ArrayList<>(); + private static final LegacyOutboxAppendPort NO_OP_OUTBOX = event -> {}; + private static final CorrelationIdPort NO_CORRELATION = Optional::empty; - @Override - public WorkLog save(WorkLog w) { - store.removeIf(x -> x.id().equals(w.id())); - store.add(w); - return w; - } + private final InMemoryWorkLogRepository repository = new InMemoryWorkLogRepository(); + private final DirectTransactionPort tx = new DirectTransactionPort(); + private final CreateWorkLogUseCase create = + new CreateWorkLogUseCase( + repository, + IDS, + () -> "01FAKEEVENTIDTSV4RRFFQ6900", + NO_OP_OUTBOX, + NO_CORRELATION, + Clock.systemUTC(), + tx); + private final UpdateWorkLogUseCase update = new UpdateWorkLogUseCase(repository, tx); - @Override - public Optional findById(WorkLogId id) { - return store.stream().filter(x -> x.id().equals(id)).findFirst(); - } + @Nested + class Create { - @Override - public WorkLogPage findPage( - int page, int size, WorkLogSortField sortField, boolean ascending, WorkCategory category) { - int safeSize = size <= 0 ? 20 : size; - List filtered = - store.stream().filter(x -> category == null || x.category() == category).toList(); - List pageItems = - filtered.stream().skip((long) Math.max(0, page) * safeSize).limit(safeSize).toList(); - return new WorkLogPage(pageItems, filtered.size()); - } + @Test + void setsTheOwnerFromTheCommandPrincipal() { + // when + WorkLog created = create.handle(createCmd("sub-7", "owner demo")); - @Override - public boolean existsById(WorkLogId id) { - return findById(id).isPresent(); - } - - @Override - public void deleteById(WorkLogId id) { - store.removeIf(x -> x.id().equals(id)); + // then + assertThat(created.owner().value()).isEqualTo("sub-7"); } } - static final TransactionPort TX = - new TransactionPort() { - @Override - public T inWrite(Supplier a) { - return a.get(); - } + @Nested + class Get { - @Override - public T inRootWrite(Supplier a) { - return a.get(); - } + private final GetWorkLogUseCase get = new GetWorkLogUseCase(repository, tx); - @Override - public T inRead(Supplier a) { - return a.get(); - } + @Test + void returnsTheSavedWorkLog() { + // given + WorkLog created = aCreatedWorkLog("DB 튜닝"); - @Override - public T inNew(Supplier a) { - return a.get(); - } - }; + // when + WorkLog found = get.handle(new GetWorkLogQuery(created.id())); - /** No-op outbox port — existing tests focus on use-case behaviour, not outbox wiring. */ - static final LegacyOutboxAppendPort NO_OP_OUTBOX = e -> {}; + // then + assertThat(found).usingRecursiveComparison().isEqualTo(created); + } - static final CorrelationIdPort NO_CORRELATION = Optional::empty; + @Test + void rejectsAnUnknownIdAsNotFound() { + // when + Throwable thrown = catchThrowable(() -> get.handle(new GetWorkLogQuery(ABSENT_ID))); - /** Deterministic event-id stub for existing tests. */ - static final OutboxEventIdFactory STUB_EVENT_IDS = () -> "01FAKEEVENTIDTSV4RRFFQ6900"; + // then + assertThat(thrown) + .isInstanceOf(WorkLogNotFoundException.class) + .hasMessage("WorkLog not found: " + ABSENT_ID.value()); + } + } - static final Clock UTC_CLOCK = Clock.systemUTC(); + @Nested + class Update { - private CreateWorkLogCommand createCmd(String title) { + @Test + void appliesPresentFieldsAndLeavesAbsentFieldsUnchanged() { + // given + WorkLog created = aCreatedWorkLog("old"); + + // when + WorkLog updated = + update.handle( + new UpdateWorkLogCommand( + created.id(), + Patch.of("new title"), + Patch.absent(), + Patch.of("new content"), + Patch.absent(), + Patch.absent())); + + // then + assertThat(updated) + .extracting(WorkLog::title, WorkLog::summary, WorkLog::content) + .containsExactly("new title", "s", "new content"); + } + + @Test + void clearsTheSummaryOnAnExplicitNull() { + // given + WorkLog created = aCreatedWorkLog("t"); + + // when + WorkLog updated = + update.handle( + new UpdateWorkLogCommand( + created.id(), + Patch.absent(), + Patch.ofNull(), + Patch.absent(), + Patch.absent(), + Patch.absent())); + + // then + assertThat(updated.summary()).isEmpty(); + } + + @Test + void advancesAnInProgressWorkLogToClosed() { + // given + WorkLog inProgress = + update.handle(statusChange(aCreatedWorkLog("status demo").id(), IN_PROGRESS)); + + // when + WorkLog closed = update.handle(statusChange(inProgress.id(), CLOSED)); + + // then + assertThat(closed.status()).isEqualTo(CLOSED); + } + + @Test + void rejectsEditingAClosedWorkLog() { + // given + WorkLogId id = aCreatedWorkLog("status demo").id(); + update.handle(statusChange(id, IN_PROGRESS)); + update.handle(statusChange(id, CLOSED)); + + // when + Throwable thrown = + catchThrowable( + () -> + update.handle( + new UpdateWorkLogCommand( + id, + Patch.of("late edit"), + Patch.absent(), + Patch.absent(), + Patch.absent(), + Patch.absent()))); + + // then + assertThat(thrown) + .isInstanceOfSatisfying( + WorkLogInvariantException.class, + e -> assertThat(e.reason()).isEqualTo(Reason.CLOSED_WORKLOG_MUTATION)); + } + + @Test + void rejectsMovingAnInProgressWorkLogBackToOpen() { + // given + WorkLog inProgress = + update.handle(statusChange(aCreatedWorkLog("status revert").id(), IN_PROGRESS)); + + // when + Throwable thrown = catchThrowable(() -> update.handle(statusChange(inProgress.id(), OPEN))); + + // then + assertThat(thrown) + .isInstanceOfSatisfying( + WorkLogInvariantException.class, + e -> assertThat(e.reason()).isEqualTo(Reason.INVALID_STATUS_TRANSITION)); + } + } + + @Nested + class ListPage { + + @Test + void returnsTheItemsAndTheTotal() { + // given + aCreatedWorkLog("a"); + aCreatedWorkLog("b"); + + // when + WorkLogPage page = + new ListWorkLogsUseCase(repository, tx) + .handle(new ListWorkLogsQuery(0, 10, null, true, null)); + + // then + assertThat(page) + .extracting( + p -> p.items().stream().map(WorkLog::title).sorted().toList(), WorkLogPage::total) + .containsExactly(List.of("a", "b"), 2L); + } + } + + @Nested + class BatchCreate { + + private final BatchCreateWorkLogsUseCase batchCreate = + new BatchCreateWorkLogsUseCase(repository, IDS, tx); + private final BatchCreateWorkLogsCommand oneAndTwo = + new BatchCreateWorkLogsCommand(List.of(createCmd("one"), createCmd("two"))); + + @Test + void returnsEveryCreatedItemInCommandOrder() { + // when + List created = batchCreate.handle(oneAndTwo); + + // then + assertThat(created).extracting(WorkLog::title).containsExactly("one", "two"); + } + + @Test + void persistsEveryItem() { + // when + batchCreate.handle(oneAndTwo); + + // then + assertThat(repository.findPage(0, 20, null, true, null).items()) + .extracting(WorkLog::title) + .containsExactlyInAnyOrder("one", "two"); + } + + @Test + void savesAllItemsInOneWriteTransaction() { + // when + batchCreate.handle(oneAndTwo); + + // then + assertThat(tx.committed()).containsExactly(Boundary.WRITE); + } + } + + @Nested + class Delete { + + @Test + void rejectsAnUnknownIdAsNotFound() { + // given + DeleteWorkLogUseCase delete = new DeleteWorkLogUseCase(repository, tx); + + // when + Throwable thrown = catchThrowable(() -> delete.handle(new DeleteWorkLogCommand(ABSENT_ID))); + + // then + assertThat(thrown) + .isInstanceOf(WorkLogNotFoundException.class) + .hasMessage("WorkLog not found: " + ABSENT_ID.value()); + } + } + + private WorkLog aCreatedWorkLog(String title) { + return create.handle(createCmd(title)); + } + + private static CreateWorkLogCommand createCmd(String title) { + return createCmd("sample-owner", title); + } + + private static CreateWorkLogCommand createCmd(String owner, String title) { return new CreateWorkLogCommand( - "sample-owner", + owner, title, WorkCategory.DATABASE, "s", @@ -125,193 +303,8 @@ class WorkLogUseCasesTest { null); } - @Test - void createThenGetReturnsSaved() { - FakeRepo repo = new FakeRepo(); - WorkLog created = - new CreateWorkLogUseCase( - repo, IDS, STUB_EVENT_IDS, NO_OP_OUTBOX, NO_CORRELATION, UTC_CLOCK, TX) - .handle(createCmd("DB 튜닝")); - WorkLog got = new GetWorkLogUseCase(repo, TX).handle(new GetWorkLogQuery(created.id())); - assertThat(got.title()).isEqualTo("DB 튜닝"); - } - - @Test - void createSetsOwnerFromCommandPrincipal() { - FakeRepo repo = new FakeRepo(); - WorkLog created = - new CreateWorkLogUseCase( - repo, IDS, STUB_EVENT_IDS, NO_OP_OUTBOX, NO_CORRELATION, UTC_CLOCK, TX) - .handle( - new CreateWorkLogCommand( - "sub-7", - "owner demo", - WorkCategory.DATABASE, - "s", - "c", - List.of("postgres"), - List.of(), - LocalDate.of(2025, 1, 1), - null)); - assertThat(created.owner().value()).isEqualTo("sub-7"); - } - - @Test - void getMissingThrowsNotFound() { - FakeRepo repo = new FakeRepo(); - assertThatThrownBy(() -> new GetWorkLogUseCase(repo, TX).handle(new GetWorkLogQuery(ABSENT_ID))) - .isInstanceOf(WorkLogNotFoundException.class); - } - - @Test - void updateAppliesPatchThreeState() { - FakeRepo repo = new FakeRepo(); - WorkLog created = - new CreateWorkLogUseCase( - repo, IDS, STUB_EVENT_IDS, NO_OP_OUTBOX, NO_CORRELATION, UTC_CLOCK, TX) - .handle(createCmd("old")); - WorkLog updated = - new UpdateWorkLogUseCase(repo, TX) - .handle( - new UpdateWorkLogCommand( - created.id(), - Patch.of("new title"), - Patch.absent(), - Patch.of("new content"), - Patch.absent(), - Patch.absent())); - assertThat(updated.title()).isEqualTo("new title"); - assertThat(updated.content()).isEqualTo("new content"); - } - - @Test - void updateCanAdvanceStatusButClosedWorklogRejectsLaterMutation() { - FakeRepo repo = new FakeRepo(); - WorkLog created = - new CreateWorkLogUseCase( - repo, IDS, STUB_EVENT_IDS, NO_OP_OUTBOX, NO_CORRELATION, UTC_CLOCK, TX) - .handle(createCmd("status demo")); - WorkLog inProgress = - new UpdateWorkLogUseCase(repo, TX) - .handle( - new UpdateWorkLogCommand( - created.id(), - Patch.absent(), - Patch.absent(), - Patch.absent(), - Patch.absent(), - Patch.of(WorkLogStatus.IN_PROGRESS))); - WorkLog closed = - new UpdateWorkLogUseCase(repo, TX) - .handle( - new UpdateWorkLogCommand( - inProgress.id(), - Patch.absent(), - Patch.absent(), - Patch.absent(), - Patch.absent(), - Patch.of(WorkLogStatus.CLOSED))); - - assertThat(closed.status()).isEqualTo(WorkLogStatus.CLOSED); - assertThatThrownBy( - () -> - new UpdateWorkLogUseCase(repo, TX) - .handle( - new UpdateWorkLogCommand( - closed.id(), - Patch.of("late edit"), - Patch.absent(), - Patch.absent(), - Patch.absent(), - Patch.absent()))) - .isInstanceOf(WorkLogInvariantException.class) - .extracting(ex -> ((WorkLogInvariantException) ex).reason()) - .isEqualTo(WorkLogInvariantException.Reason.CLOSED_WORKLOG_MUTATION); - } - - @Test - void updateRejectsRevertingStatusToOpen() { - FakeRepo repo = new FakeRepo(); - WorkLog created = - new CreateWorkLogUseCase( - repo, IDS, STUB_EVENT_IDS, NO_OP_OUTBOX, NO_CORRELATION, UTC_CLOCK, TX) - .handle(createCmd("status revert")); - WorkLog inProgress = - new UpdateWorkLogUseCase(repo, TX) - .handle( - new UpdateWorkLogCommand( - created.id(), - Patch.absent(), - Patch.absent(), - Patch.absent(), - Patch.absent(), - Patch.of(WorkLogStatus.IN_PROGRESS))); - - assertThatThrownBy( - () -> - new UpdateWorkLogUseCase(repo, TX) - .handle( - new UpdateWorkLogCommand( - inProgress.id(), - Patch.absent(), - Patch.absent(), - Patch.absent(), - Patch.absent(), - Patch.of(WorkLogStatus.OPEN)))) - .isInstanceOf(WorkLogInvariantException.class) - .extracting(ex -> ((WorkLogInvariantException) ex).reason()) - .isEqualTo(WorkLogInvariantException.Reason.INVALID_STATUS_TRANSITION); - } - - @Test - void listReturnsPageWithTotal() { - FakeRepo repo = new FakeRepo(); - CreateWorkLogUseCase create = - new CreateWorkLogUseCase( - repo, IDS, STUB_EVENT_IDS, NO_OP_OUTBOX, NO_CORRELATION, UTC_CLOCK, TX); - create.handle(createCmd("a")); - create.handle(createCmd("b")); - var page = - new ListWorkLogsUseCase(repo, TX).handle(new ListWorkLogsQuery(0, 10, null, true, null)); - assertThat(page.items()).hasSize(2); - assertThat(page.total()).isEqualTo(2); - } - - @Test - void batchCreatePersistsEveryItemAtomically() { - FakeRepo repo = new FakeRepo(); - var batch = - new BatchCreateWorkLogsUseCase(repo, IDS, TX) - .handle(new BatchCreateWorkLogsCommand(List.of(createCmd("one"), createCmd("two")))); - assertThat(batch).hasSize(2); - assertThat(repo.store).hasSize(2); - } - - @Test - void updateExplicitNullClearsNullableField() { - FakeRepo repo = new FakeRepo(); - WorkLog created = - new CreateWorkLogUseCase( - repo, IDS, STUB_EVENT_IDS, NO_OP_OUTBOX, NO_CORRELATION, UTC_CLOCK, TX) - .handle(createCmd("t")); - WorkLog updated = - new UpdateWorkLogUseCase(repo, TX) - .handle( - new UpdateWorkLogCommand( - created.id(), - Patch.absent(), - Patch.ofNull(), - Patch.absent(), - Patch.absent(), - Patch.absent())); - assertThat(updated.summary()).isEqualTo(""); // updateSummary(null) normalizes to "" - } - - @Test - void deleteMissingThrowsNotFound() { - FakeRepo repo = new FakeRepo(); - assertThatThrownBy( - () -> new DeleteWorkLogUseCase(repo, TX).handle(new DeleteWorkLogCommand(ABSENT_ID))) - .isInstanceOf(WorkLogNotFoundException.class); + private static UpdateWorkLogCommand statusChange(WorkLogId id, WorkLogStatus status) { + return new UpdateWorkLogCommand( + id, Patch.absent(), Patch.absent(), Patch.absent(), Patch.absent(), Patch.of(status)); } } diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/authz/WorkLogAuthorizationContractTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/authz/WorkLogAuthorizationContractTest.java index bd5b7e6c..9d8a9bf6 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/authz/WorkLogAuthorizationContractTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/authz/WorkLogAuthorizationContractTest.java @@ -1,12 +1,8 @@ package dev.caskeleton.sample.portfolio.authz; +import static dev.caskeleton.sample.portfolio.fixtures.SamplePortfolioFixture.WORK_LOG_ID; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; +import static org.assertj.core.api.Assertions.catchThrowable; import dev.caskeleton.adapter.inbound.web.auth.AuthenticatedPrincipal; import dev.caskeleton.adapter.inbound.web.authz.AuthorizationAdapter; @@ -17,23 +13,24 @@ import dev.caskeleton.application.observability.CorrelationIdPort; import dev.caskeleton.application.outbox.LegacyOutboxAppendPort; import dev.caskeleton.application.outbox.NewOutboxEvent; import dev.caskeleton.application.transaction.TransactionPort; +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; import dev.caskeleton.sample.portfolio.application.command.CreateWorkLogCommand; import dev.caskeleton.sample.portfolio.application.command.DeleteWorkLogCommand; import dev.caskeleton.sample.portfolio.application.worklog.CreateWorkLogUseCase; import dev.caskeleton.sample.portfolio.application.worklog.DeleteWorkLogUseCase; import dev.caskeleton.sample.portfolio.domain.worklog.OutboxEventIdFactory; +import dev.caskeleton.sample.portfolio.domain.worklog.Period; import dev.caskeleton.sample.portfolio.domain.worklog.WorkCategory; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLog; -import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogId; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogIdFactory; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogRepository; +import dev.caskeleton.sample.portfolio.domain.worklog.testkit.InMemoryWorkLogRepository; import java.time.Clock; import java.time.LocalDate; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; -import java.util.function.Supplier; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -46,7 +43,6 @@ import org.springframework.security.access.AccessDeniedException; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.test.context.bean.override.mockito.MockitoBean; /** * End-to-end demonstration of the authorization contract (§5): real, method-secured use case beans @@ -64,19 +60,35 @@ import org.springframework.test.context.bean.override.mockito.MockitoBean; webEnvironment = SpringBootTest.WebEnvironment.NONE) class WorkLogAuthorizationContractTest { - private static final String ID = "0190bd6e-7c3e-7abc-8def-0123456789ab"; - @Autowired CreateWorkLogUseCase createUseCase; @Autowired DeleteWorkLogUseCase deleteUseCase; - @MockitoBean WorkLogRepository repository; - @MockitoBean WorkLogIdFactory idFactory; + // A context singleton shared by every test in this class, so each test's row is removed after it. + @Autowired InMemoryWorkLogRepository repository; @AfterEach void clearSecurityContext() { SecurityContextHolder.clearContext(); } + @AfterEach + void removeWorkLog() { + repository.deleteById(WORK_LOG_ID); + } + + private void storeWorkLog() { + repository.save( + WorkLog.create( + WORK_LOG_ID, + "stored", + WorkCategory.DATABASE, + "s", + "c", + List.of(), + List.of(), + new Period(LocalDate.of(2025, 1, 1), null))); + } + private void authenticateWithRoles(String... roles) { AuthenticatedPrincipal principal = new AuthenticatedPrincipal("sub-1", "u@example.com", Set.of(roles)); @@ -100,49 +112,65 @@ class WorkLogAuthorizationContractTest { @Test void authenticatedUserWithWritePermissionMayCreate() { + // given authenticateWithRoles("user"); - when(idFactory.newId()).thenReturn(WorkLogId.of(ID)); - when(repository.save(any())).thenAnswer(inv -> inv.getArgument(0)); + // when WorkLog created = createUseCase.handle(createCommand()); - assertThat(created).isNotNull(); - verify(repository).save(any()); + // then + assertThat(repository.findById(created.id())).map(WorkLog::title).contains("authz demo"); } @Test void authenticatedUserWithoutClosePermissionIsDeniedDelete() { + // given + storeWorkLog(); // tier-3: authenticated ≠ authorized. `user` lacks `worklog:close`. authenticateWithRoles("user"); - assertThatThrownBy(() -> deleteUseCase.handle(new DeleteWorkLogCommand(WorkLogId.of(ID)))) - .isInstanceOf(AccessDeniedException.class); - // enforcement happens before the use-case body — the repository is never touched. - verify(repository, never()).deleteById(any()); - verify(repository, never()).existsById(any()); + // when + Throwable thrown = + catchThrowable(() -> deleteUseCase.handle(new DeleteWorkLogCommand(WORK_LOG_ID))); + + // then + assertThat(thrown).isInstanceOf(AccessDeniedException.class).hasMessage("Access Denied"); + // enforcement happens before the use-case body — the row is still there. + assertThat(repository.existsById(WORK_LOG_ID)).isTrue(); } @Test void adminWithClosePermissionMayDelete() { + // given + storeWorkLog(); authenticateWithRoles("admin"); - when(repository.existsById(any())).thenReturn(true); - assertThatCode(() -> deleteUseCase.handle(new DeleteWorkLogCommand(WorkLogId.of(ID)))) - .doesNotThrowAnyException(); + // when + deleteUseCase.handle(new DeleteWorkLogCommand(WORK_LOG_ID)); - verify(repository).deleteById(any()); + // then + assertThat(repository.existsById(WORK_LOG_ID)).isFalse(); } + // No authentication in the context. Method security is a defense-in-depth backstop: + // it rejects the missing authentication outright (AuthenticationException) rather than + // reaching a permission check. In production the HTTP filter chain + // (.anyRequest().authenticated()) returns 401 before a request ever reaches here; this + // proves the use case is never silently invoked without an authenticated principal. @Test void unauthenticatedCallerIsDeniedFailClosed() { - // No authentication in the context. Method security is a defense-in-depth backstop: - // it rejects the missing authentication outright (AuthenticationException) rather than - // reaching a permission check. In production the HTTP filter chain - // (.anyRequest().authenticated()) returns 401 before a request ever reaches here; this - // proves the use case is never silently invoked without an authenticated principal. - assertThatThrownBy(() -> deleteUseCase.handle(new DeleteWorkLogCommand(WorkLogId.of(ID)))) - .isInstanceOf(AuthenticationException.class); - verify(repository, never()).deleteById(any()); + // given + storeWorkLog(); + + // when + Throwable thrown = + catchThrowable(() -> deleteUseCase.handle(new DeleteWorkLogCommand(WORK_LOG_ID))); + + // then + assertThat(thrown) + .isInstanceOf(AuthenticationException.class) + .hasMessage("An Authentication object was not found in the SecurityContext"); + assertThat(repository.existsById(WORK_LOG_ID)).isTrue(); } // Force CGLIB class proxies, mirroring Spring Boot's AOP default @@ -171,28 +199,18 @@ class WorkLogAuthorizationContractTest { /** Pass-through transaction boundary — the contract under test is authorization, not tx. */ @Bean - TransactionPort transactionPort() { - return new TransactionPort() { - @Override - public T inWrite(Supplier action) { - return action.get(); - } + DirectTransactionPort transactionPort() { + return new DirectTransactionPort(); + } - @Override - public T inRootWrite(Supplier action) { - return action.get(); - } + @Bean + InMemoryWorkLogRepository workLogRepository() { + return new InMemoryWorkLogRepository(); + } - @Override - public T inRead(Supplier action) { - return action.get(); - } - - @Override - public T inNew(Supplier action) { - return action.get(); - } - }; + @Bean + WorkLogIdFactory workLogIdFactory() { + return () -> WORK_LOG_ID; } @Bean diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/authz/WorkLogAuthorizationE2ETest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/authz/WorkLogAuthorizationE2ETest.java index 00d40ba5..13375b3b 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/authz/WorkLogAuthorizationE2ETest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/authz/WorkLogAuthorizationE2ETest.java @@ -1,9 +1,7 @@ package dev.caskeleton.sample.portfolio.authz; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; +import static dev.caskeleton.sample.portfolio.fixtures.SamplePortfolioFixture.WORK_LOG_ID; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -17,6 +15,7 @@ import dev.caskeleton.adapter.inbound.web.config.JacksonNullableConfig; import dev.caskeleton.adapter.inbound.web.envelope.EnvelopeBodyAdvice; import dev.caskeleton.adapter.inbound.web.error.GlobalExceptionHandler; import dev.caskeleton.application.transaction.TransactionPort; +import dev.caskeleton.application.transaction.testkit.DirectTransactionPort; import dev.caskeleton.sample.portfolio.adapter.inbound.web.controller.WorkLogController; import dev.caskeleton.sample.portfolio.adapter.inbound.web.json.WorkLogIdSerializer; import dev.caskeleton.sample.portfolio.application.worklog.BatchCreateWorkLogsUseCase; @@ -26,11 +25,15 @@ import dev.caskeleton.sample.portfolio.application.worklog.GetRepoStatsUseCase; import dev.caskeleton.sample.portfolio.application.worklog.GetWorkLogUseCase; import dev.caskeleton.sample.portfolio.application.worklog.ListWorkLogsUseCase; import dev.caskeleton.sample.portfolio.application.worklog.UpdateWorkLogUseCase; +import dev.caskeleton.sample.portfolio.domain.worklog.Period; +import dev.caskeleton.sample.portfolio.domain.worklog.WorkCategory; +import dev.caskeleton.sample.portfolio.domain.worklog.WorkLog; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogRepository; +import dev.caskeleton.sample.portfolio.domain.worklog.testkit.InMemoryWorkLogRepository; +import java.time.LocalDate; import java.util.List; import java.util.Map; import java.util.Set; -import java.util.function.Supplier; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -45,6 +48,7 @@ import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.ResultActions; /** * Negative + positive authorization E2E over the real {@link WorkLogController} DELETE @@ -76,12 +80,11 @@ import org.springframework.test.web.servlet.MockMvc; }) class WorkLogAuthorizationE2ETest { - private static final String ID = "0190bd6e-7c3e-7abc-8def-0123456789ab"; - @Autowired MockMvc mvc; - // The DeleteWorkLogUseCase @Bean is real (proxied); its repository is a reset-between-tests mock. - @MockitoBean WorkLogRepository repository; + // The DeleteWorkLogUseCase @Bean is real (proxied) over this in-memory repository, a context + // singleton shared by both tests, so each test's row is removed after it. + @Autowired InMemoryWorkLogRepository repository; // controller constructor collaborators that the DELETE path does not exercise @MockitoBean CreateWorkLogUseCase createUseCase; @@ -96,6 +99,24 @@ class WorkLogAuthorizationE2ETest { SecurityContextHolder.clearContext(); } + @AfterEach + void removeWorkLog() { + repository.deleteById(WORK_LOG_ID); + } + + private void storeWorkLog() { + repository.save( + WorkLog.create( + WORK_LOG_ID, + "stored", + WorkCategory.DATABASE, + "s", + "c", + List.of(), + List.of(), + new Period(LocalDate.of(2025, 1, 1), null))); + } + private void authenticateWithRoles(String... roles) { AuthenticatedPrincipal principal = new AuthenticatedPrincipal("sub-1", "u@example.com", Set.of(roles)); @@ -105,28 +126,37 @@ class WorkLogAuthorizationE2ETest { } @Test - void userDeletingAWorklogGets403InsufficientPermissionEnvelope() throws Exception { + void userDeletingAWorklogGets403InsufficientPermissionEnvelopeAndTheRowStays() throws Exception { + // given + storeWorkLog(); authenticateWithRoles("user"); // has worklog:write, NOT worklog:close - mvc.perform(delete("/worklogs/{id}", ID)) + // when + ResultActions result = mvc.perform(delete("/worklogs/{id}", WORK_LOG_ID.value())); + + // then + result .andExpect(status().isForbidden()) .andExpect(jsonPath("$.success").value(false)) .andExpect(jsonPath("$.error.code").value("AUTHZ_INSUFFICIENT_PERMISSION")) .andExpect(jsonPath("$.error.category").value("AUTHZ")) .andExpect(jsonPath("$.error.retryable").value(false)); - - // enforcement happened before the use-case body — the repository is untouched. - verify(repository, never()).deleteById(any()); + // enforcement happened before the use-case body — the row is untouched. + assertThat(repository.existsById(WORK_LOG_ID)).isTrue(); } @Test - void adminDeletingAWorklogSucceedsWith204() throws Exception { + void adminDeletingAWorklogGets204AndTheRowIsRemoved() throws Exception { + // given + storeWorkLog(); authenticateWithRoles("admin"); // has worklog:close - when(repository.existsById(any())).thenReturn(true); - mvc.perform(delete("/worklogs/{id}", ID)).andExpect(status().isNoContent()); + // when + ResultActions result = mvc.perform(delete("/worklogs/{id}", WORK_LOG_ID.value())); - verify(repository).deleteById(any()); + // then + result.andExpect(status().isNoContent()); + assertThat(repository.existsById(WORK_LOG_ID)).isFalse(); } @Configuration @@ -149,28 +179,13 @@ class WorkLogAuthorizationE2ETest { } @Bean - TransactionPort transactionPort() { - return new TransactionPort() { - @Override - public T inWrite(Supplier action) { - return action.get(); - } + DirectTransactionPort transactionPort() { + return new DirectTransactionPort(); + } - @Override - public T inRootWrite(Supplier action) { - return action.get(); - } - - @Override - public T inRead(Supplier action) { - return action.get(); - } - - @Override - public T inNew(Supplier action) { - return action.get(); - } - }; + @Bean + InMemoryWorkLogRepository workLogRepository() { + return new InMemoryWorkLogRepository(); } @Bean diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/bootstrap/management/SampleActuatorLoggersAccessTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/bootstrap/management/SampleActuatorLoggersAccessTest.java new file mode 100644 index 00000000..d74ae11b --- /dev/null +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/bootstrap/management/SampleActuatorLoggersAccessTest.java @@ -0,0 +1,31 @@ +package dev.caskeleton.sample.portfolio.bootstrap.management; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.IOException; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.springframework.boot.env.YamlPropertySourceLoader; +import org.springframework.core.env.PropertySource; +import org.springframework.core.io.ClassPathResource; + +class SampleActuatorLoggersAccessTest { + + @Test + void loggersEndpointIsReadOnlyBecauseTheSampleManagementPortIsUnauthenticated() + throws IOException { + // given + List> documents = + new YamlPropertySourceLoader() + .load("application", new ClassPathResource("application.yml")); + + // when + Object access = documents.get(0).getProperty("management.endpoint.loggers.access"); + + // then + assertThat(access) + .as( + "the sample permits every request, so a writable loggers endpoint lets anyone set TRACE") + .hasToString("read-only"); + } +} diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/bootstrap/objectstorage/PosterImageIdempotencyConfigTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/bootstrap/objectstorage/PosterImageIdempotencyConfigTest.java index d3c65058..ebcb63ce 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/bootstrap/objectstorage/PosterImageIdempotencyConfigTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/bootstrap/objectstorage/PosterImageIdempotencyConfigTest.java @@ -19,21 +19,41 @@ class PosterImageIdempotencyConfigTest { @TempDir Path root; + private final ApplicationContextRunner runner = + new ApplicationContextRunner().withUserConfiguration(PosterImageIdempotencyConfig.class); + @Test - void disabledConfigurationCreatesNoDigester() { - new ApplicationContextRunner() - .withUserConfiguration(PosterImageIdempotencyConfig.class) + void disabledConfigurationCreatesNeitherDigesterNorContextFactory() { + runner .withPropertyValues("app.poster-image.idempotency.enabled=false") .run( - context -> { - assertThat(context).doesNotHaveBean(PosterImageIdempotencyScopeDigesterPort.class); - assertThat(context) - .doesNotHaveBean(PosterImageSanitizedIdempotencyContextFactory.class); - }); + context -> + assertThat(context) + .doesNotHaveBean(PosterImageIdempotencyScopeDigesterPort.class) + .doesNotHaveBean(PosterImageSanitizedIdempotencyContextFactory.class)); } @Test void permissionCheckedExternalKeyRingCreatesRotationAwareDigester() throws Exception { + // given + Path keyRing = ownerOnlyKeyRing(); + + // when & then + runner + .withBean(PosterImageIdempotencyKeyEpochPort.class, FixedEpoch::new) + .withPropertyValues( + "app.poster-image.idempotency.enabled=true", + "app.poster-image.idempotency.key-ring-path=" + keyRing, + "app.poster-image.idempotency.bootstrap-active-key-version=key-v1") + .run( + context -> + assertThat(context) + .hasNotFailed() + .hasSingleBean(PosterImageIdempotencyScopeDigesterPort.class) + .hasSingleBean(PosterImageSanitizedIdempotencyContextFactory.class)); + } + + private Path ownerOnlyKeyRing() throws Exception { Path keyRing = root.resolve("poster-image.keys"); String key = Base64.getEncoder() @@ -46,21 +66,7 @@ class PosterImageIdempotencyConfigTest { } catch (UnsupportedOperationException ignored) { // The production loader applies the portable no-follow/regular-file/size checks. } - - new ApplicationContextRunner() - .withUserConfiguration(PosterImageIdempotencyConfig.class) - .withBean(PosterImageIdempotencyKeyEpochPort.class, FixedEpoch::new) - .withPropertyValues( - "app.poster-image.idempotency.enabled=true", - "app.poster-image.idempotency.key-ring-path=" + keyRing, - "app.poster-image.idempotency.bootstrap-active-key-version=key-v1") - .run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context).hasSingleBean(PosterImageIdempotencyScopeDigesterPort.class); - assertThat(context) - .hasSingleBean(PosterImageSanitizedIdempotencyContextFactory.class); - }); + return keyRing; } private static final class FixedEpoch implements PosterImageIdempotencyKeyEpochPort { diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/bootstrap/objectstorage/PosterImageRetirementConfigTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/bootstrap/objectstorage/PosterImageRetirementConfigTest.java index 78e324bd..0bdea1d3 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/bootstrap/objectstorage/PosterImageRetirementConfigTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/bootstrap/objectstorage/PosterImageRetirementConfigTest.java @@ -4,49 +4,61 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import dev.caskeleton.sample.portfolio.application.poster.ReconcilePosterImageRetirementUseCase; +import java.util.stream.Stream; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.NullSource; +import org.junit.jupiter.params.provider.ValueSource; import org.springframework.boot.test.context.runner.ApplicationContextRunner; class PosterImageRetirementConfigTest { + private final ApplicationContextRunner runner = + new ApplicationContextRunner().withUserConfiguration(PosterImageRetirementConfig.class); + @Test void disabledConfigurationCreatesNoWorker() { - new ApplicationContextRunner() - .withUserConfiguration(PosterImageRetirementConfig.class) + runner .withPropertyValues("app.poster-image.retirement.enabled=false") .run(context -> assertThat(context).doesNotHaveBean(PosterImageRetirementJob.class)); } @Test void enabledConfigurationRequiresBoundedIdentityAndCreatesOneWorker() { - new ApplicationContextRunner() - .withUserConfiguration(PosterImageRetirementConfig.class) - .withBean( - ReconcilePosterImageRetirementUseCase.class, - () -> mock(ReconcilePosterImageRetirementUseCase.class)) + enabled() .withPropertyValues( - "app.poster-image.retirement.enabled=true", "app.poster-image.retirement.claimant-digest=" + "a".repeat(64), "app.poster-image.retirement.batch-size=10", "app.poster-image.retirement.claim-lease=30s", "app.poster-image.retirement.operation-timeout=5s") .run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context).hasSingleBean(PosterImageRetirementJob.class); - }); + context -> + assertThat(context).hasNotFailed().hasSingleBean(PosterImageRetirementJob.class)); } - @Test - void enabledConfigurationRejectsRawOrMissingClaimantIdentity() { - new ApplicationContextRunner() - .withUserConfiguration(PosterImageRetirementConfig.class) + @ParameterizedTest + @NullSource + @ValueSource(strings = "worker-1") + void enabledConfigurationRejectsRawOrMissingClaimantIdentity(String claimant) { + enabled() + .withPropertyValues( + Stream.ofNullable(claimant) + .map(value -> "app.poster-image.retirement.claimant-digest=" + value) + .toArray(String[]::new)) + .run( + context -> + assertThat(context) + .getFailure() + .rootCause() + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("enabled Poster image retirement requires a claimant digest")); + } + + private ApplicationContextRunner enabled() { + return runner .withBean( ReconcilePosterImageRetirementUseCase.class, () -> mock(ReconcilePosterImageRetirementUseCase.class)) - .withPropertyValues( - "app.poster-image.retirement.enabled=true", - "app.poster-image.retirement.claimant-digest=worker-1") - .run(context -> assertThat(context).hasFailed()); + .withPropertyValues("app.poster-image.retirement.enabled=true"); } } diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/bootstrap/persistence/SamplePostgreSqlPersistenceConfigTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/bootstrap/persistence/SamplePostgreSqlPersistenceConfigTest.java index 8fcc501f..dee125d9 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/bootstrap/persistence/SamplePostgreSqlPersistenceConfigTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/bootstrap/persistence/SamplePostgreSqlPersistenceConfigTest.java @@ -3,22 +3,33 @@ package dev.caskeleton.sample.portfolio.bootstrap.persistence; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; +import java.util.Arrays; +import java.util.List; import javax.sql.DataSource; +import org.flywaydb.core.api.configuration.FluentConfiguration; import org.junit.jupiter.api.Test; class SamplePostgreSqlPersistenceConfigTest { @Test void sampleMigrationsUseTheirOwnLocationAndHistoryTimeline() { - var configuration = + // when + FluentConfiguration configuration = SamplePostgreSqlPersistenceConfig.sampleFlywayConfiguration(mock(DataSource.class)); - assertThat(configuration.getTable()).isEqualTo("flyway_sample_schema_history"); - assertThat(configuration.getBaselineVersion().getVersion()).isEqualTo("0"); - assertThat(configuration.isBaselineOnMigrate()).isTrue(); - assertThat(configuration.isCleanDisabled()).isTrue(); - assertThat(configuration.getLocations()) - .extracting(Object::toString) - .containsExactly("classpath:db/sample-migration"); + // then + assertThat(configuration) + .extracting( + FluentConfiguration::getTable, + config -> config.getBaselineVersion().getVersion(), + FluentConfiguration::isBaselineOnMigrate, + FluentConfiguration::isCleanDisabled, + config -> Arrays.stream(config.getLocations()).map(Object::toString).toList()) + .containsExactly( + "flyway_sample_schema_history", + "0", + true, + true, + List.of("classpath:db/sample-migration")); } } diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/bootstrap/security/SamplePublicAccessSecurityConfigTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/bootstrap/security/SamplePublicAccessSecurityConfigTest.java index cbd4d449..432cf7b4 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/bootstrap/security/SamplePublicAccessSecurityConfigTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/bootstrap/security/SamplePublicAccessSecurityConfigTest.java @@ -11,6 +11,7 @@ import dev.caskeleton.adapter.inbound.web.authz.MethodSecurityConfig; import dev.caskeleton.adapter.inbound.web.config.JacksonNullableConfig; import dev.caskeleton.adapter.inbound.web.envelope.EnvelopeBodyAdvice; import dev.caskeleton.adapter.inbound.web.error.GlobalExceptionHandler; +import dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebAdapterAutoConfiguration; import dev.caskeleton.sample.portfolio.SamplePortfolioApplication; import dev.caskeleton.sample.portfolio.adapter.inbound.web.controller.WorkLogController; import dev.caskeleton.sample.portfolio.adapter.inbound.web.error.DomainExceptionHandler; @@ -43,8 +44,12 @@ import org.springframework.core.annotation.AnnotationUtils; import org.springframework.http.MediaType; import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.ResultActions; -@SpringBootTest(classes = SamplePublicAccessSecurityConfigTest.TestBootstrap.class) +// The slice excludes the data layer; persistence-jpa is on while present, so it is switched off. +@SpringBootTest( + classes = SamplePublicAccessSecurityConfigTest.TestBootstrap.class, + properties = "ca-skeleton.persistence-jpa.enabled=false") @AutoConfigureMockMvc class SamplePublicAccessSecurityConfigTest { @@ -62,22 +67,29 @@ class SamplePublicAccessSecurityConfigTest { @Test void sampleWorklogWriteEndpointIsReachableWithoutAuthorizationHeader() throws Exception { + // given when(createUseCase.handle(any())).thenReturn(sample("public demo")); - mvc.perform( + // when + ResultActions result = + mvc.perform( post("/worklogs") .contentType(MediaType.APPLICATION_JSON) .content( "{\"title\":\"public" - + " demo\",\"category\":\"DATABASE\",\"periodStart\":\"2025-01-01\"}")) - .andExpect(status().isOk()); + + " demo\",\"category\":\"DATABASE\",\"periodStart\":\"2025-01-01\"}")); + + // then + result.andExpect(status().isOk()); } @Test void sampleCompositionRootDoesNotImportProductionJwtOrMethodSecurity() { + // when ComponentScan componentScan = AnnotationUtils.findAnnotation(SamplePortfolioApplication.class, ComponentScan.class); + // then assertThat(componentScan).isNotNull(); assertThat(componentScan.excludeFilters()) .flatExtracting(filter -> List.of(filter.classes())) @@ -86,9 +98,11 @@ class SamplePublicAccessSecurityConfigTest { @Test void productionCompositionRootDoesNotReferenceTestOnlyScanFilters() { + // when ComponentScan componentScan = AnnotationUtils.findAnnotation(SamplePortfolioApplication.class, ComponentScan.class); + // then assertThat(componentScan).isNotNull(); assertThat(componentScan.excludeFilters()) .flatExtracting(filter -> List.of(filter.classes())) @@ -114,7 +128,9 @@ class SamplePublicAccessSecurityConfigTest { exclude = { DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class, - OAuth2ResourceServerAutoConfiguration.class + OAuth2ResourceServerAutoConfiguration.class, + // The production web root brings the JWT and method security this sample leaves out. + WebAdapterAutoConfiguration.class }) @Import({ WorkLogController.class, diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/domain/poster/PosterIdTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/domain/poster/PosterIdTest.java index 7222aa84..23c1b879 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/domain/poster/PosterIdTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/domain/poster/PosterIdTest.java @@ -1,9 +1,12 @@ package dev.caskeleton.sample.portfolio.domain.poster; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.NullSource; +import org.junit.jupiter.params.provider.ValueSource; class PosterIdTest { @@ -14,13 +17,15 @@ class PosterIdTest { assertThat(PosterId.of(VALID).value()).isEqualTo(VALID); } - @Test - void rejectsMalformedOrNull() { - assertThatThrownBy(() -> PosterId.of("not-a-uuid")) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> PosterId.of(null)).isInstanceOf(IllegalArgumentException.class); - // an unhyphenated UUID is not canonical — the VO validates the canonical 8-4-4-4-12 form. - assertThatThrownBy(() -> PosterId.of("0190bd6e7c3e7abc8def0123456789ab")) - .isInstanceOf(IllegalArgumentException.class); + // An unhyphenated UUID is not canonical: the VO validates the 8-4-4-4-12 form. + @ParameterizedTest + @NullSource + @ValueSource(strings = {"not-a-uuid", "0190bd6e7c3e7abc8def0123456789ab"}) + void rejectsNullOrNonCanonicalValue(String value) { + Throwable thrown = catchThrowable(() -> PosterId.of(value)); + + assertThat(thrown) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Invalid PosterId format: " + value); } } diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/domain/poster/PosterImageReferenceTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/domain/poster/PosterImageReferenceTest.java index 0dfc23aa..b90d7934 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/domain/poster/PosterImageReferenceTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/domain/poster/PosterImageReferenceTest.java @@ -1,20 +1,25 @@ package dev.caskeleton.sample.portfolio.domain.poster; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.catchThrowable; import org.junit.jupiter.api.Test; class PosterImageReferenceTest { - @Test - void acceptsOnlyTheBoundedOpaquePublishedReferenceGrammar() { - PosterImageReference reference = - PosterImageReference.of("osr1.0123456789ab.0123456789abcdefghjkmnpqrs.d53d9429ac"); + private static final String PUBLISHED = "osr1.0123456789ab.0123456789abcdefghjkmnpqrs.d53d9429ac"; - assertThat(reference.value()) - .isEqualTo("osr1.0123456789ab.0123456789abcdefghjkmnpqrs.d53d9429ac"); - assertThatIllegalArgumentException() - .isThrownBy(() -> PosterImageReference.of("s3://bucket/posters/1")); + @Test + void acceptsAPublishedReferenceWithAMatchingChecksum() { + assertThat(PosterImageReference.of(PUBLISHED).value()).isEqualTo(PUBLISHED); + } + + @Test + void rejectsAStorageUriOutsideThePublishedReferenceGrammar() { + Throwable thrown = catchThrowable(() -> PosterImageReference.of("s3://bucket/posters/1")); + + assertThat(thrown) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("poster image reference is invalid"); } } diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/domain/poster/PosterTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/domain/poster/PosterTest.java index a81e9a09..00d3b1a7 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/domain/poster/PosterTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/domain/poster/PosterTest.java @@ -1,9 +1,12 @@ package dev.caskeleton.sample.portfolio.domain.poster; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.NullSource; +import org.junit.jupiter.params.provider.ValueSource; class PosterTest { @@ -11,78 +14,105 @@ class PosterTest { private static final PosterImageReference REFERENCE = PosterImageReference.of("osr1.0123456789ab.0123456789abcdefghjkmnpqrs.d53d9429ac"); - private Poster sample() { + private static Poster aDraft() { return Poster.create(ID, "여름 세일 배너", "7월 한정"); } @Test - void createStartsInDraftWithNoImageAndNullVersion() { - Poster p = sample(); - assertThat(p.id()).isEqualTo(ID); - assertThat(p.title()).isEqualTo("여름 세일 배너"); - assertThat(p.status()).isEqualTo(PosterStatus.DRAFT); - assertThat(p.hasImage()).isFalse(); - assertThat(p.version()).isNull(); + void createStartsAsAnImagelessUnversionedDraftWithTheGivenIdAndTitle() { + Poster poster = Poster.create(ID, "여름 세일 배너", "7월 한정"); + + assertThat(poster) + .extracting(Poster::id, Poster::title, Poster::status, Poster::hasImage, Poster::version) + .containsExactly(ID, "여름 세일 배너", PosterStatus.DRAFT, false, null); + } + + // Client-facing validation must surface as a domain invariant (-> 400), never an NPE (-> 500). + @ParameterizedTest + @NullSource + @ValueSource(strings = " ") + void createRejectsNullOrBlankTitleAsTitleBlankInvariant(String title) { + Throwable thrown = catchThrowable(() -> Poster.create(ID, title, "c")); + + assertThat(thrown) + .isInstanceOfSatisfying( + PosterInvariantException.class, + e -> assertThat(e.reason()).isEqualTo(PosterInvariantException.Reason.TITLE_BLANK)); } @Test - void nullTitleViolatesInvariantNotNpe() { - // client-facing validation must surface as a domain invariant (→ 400), never an NPE (→ 500). - assertThatThrownBy(() -> Poster.create(ID, null, "c")) - .isInstanceOf(PosterInvariantException.class) - .extracting(ex -> ((PosterInvariantException) ex).reason()) - .isEqualTo(PosterInvariantException.Reason.TITLE_BLANK); + void renameChangesTitle() { + // given + Poster poster = aDraft(); + + // when + poster.rename("새 제목"); + + // then + assertThat(poster.title()).isEqualTo("새 제목"); } @Test - void blankTitleViolatesInvariant() { - assertThatThrownBy(() -> Poster.create(ID, " ", "c")) - .isInstanceOf(PosterInvariantException.class) - .extracting(ex -> ((PosterInvariantException) ex).reason()) - .isEqualTo(PosterInvariantException.Reason.TITLE_BLANK); - } + void changeCaptionToNullStoresAnEmptyCaption() { + // given + Poster poster = aDraft(); - @Test - void renameChangesTitleAndChangeCaptionNormalizesNull() { - Poster p = sample(); - p.rename("새 제목"); - p.changeCaption(null); - assertThat(p.title()).isEqualTo("새 제목"); - assertThat(p.caption()).isEmpty(); + // when + poster.changeCaption(null); + + // then + assertThat(poster.caption()).isEmpty(); } @Test void publishWithoutImageIsRejected() { - Poster p = sample(); - assertThatThrownBy(p::publish) - .isInstanceOf(PosterInvariantException.class) - .extracting(ex -> ((PosterInvariantException) ex).reason()) - .isEqualTo(PosterInvariantException.Reason.IMAGE_REQUIRED); + // given + Poster poster = aDraft(); + + // when + Throwable thrown = catchThrowable(poster::publish); + + // then + assertThat(thrown) + .isInstanceOfSatisfying( + PosterInvariantException.class, + e -> assertThat(e.reason()).isEqualTo(PosterInvariantException.Reason.IMAGE_REQUIRED)); } @Test - void attachImageThenPublishTransitionsToPublished() { - Poster p = sample(); - p.attachImage("posters/x/image"); - p.publish(); - assertThat(p.status()).isEqualTo(PosterStatus.PUBLISHED); - assertThat(p.hasImage()).isTrue(); + void publishWithAnAttachedImageMovesToPublishedAndKeepsTheImage() { + // given + Poster poster = aDraft(); + poster.attachImage("posters/x/image"); + + // when + poster.publish(); + + // then + assertThat(poster) + .extracting(Poster::status, Poster::hasImage) + .containsExactly(PosterStatus.PUBLISHED, true); } @Test void canonicalWriterAttachesOnlyAPublishedOpaqueReference() { - Poster p = sample(); + // given + Poster poster = aDraft(); - p.attachPublishedImage(REFERENCE); + // when + poster.attachPublishedImage(REFERENCE); - assertThat(p.imageAttachment()).isEqualTo(new PublishedPosterImageAttachment(REFERENCE)); - assertThat(p.imageReference()).isEqualTo(REFERENCE.value()); - assertThat(p.imageKey()).isEqualTo(REFERENCE.value()); + // then + assertThat(poster) + .extracting(Poster::imageAttachment, Poster::imageReference, Poster::imageKey) + .containsExactly( + new PublishedPosterImageAttachment(REFERENCE), REFERENCE.value(), REFERENCE.value()); } @Test void dualReadRejectsAmbiguousLegacyAndPublishedColumns() { - assertThatThrownBy( + Throwable thrown = + catchThrowable( () -> Poster.rehydrate( ID, @@ -91,27 +121,42 @@ class PosterTest { "posters/legacy", REFERENCE.value(), PosterStatus.DRAFT, - 1L)) + 1L)); + + assertThat(thrown) .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("both"); + .hasMessage("poster cannot contain both legacy key and published reference"); } @Test void draftCanBeArchivedDirectly() { - Poster p = sample(); - p.archive(); - assertThat(p.status()).isEqualTo(PosterStatus.ARCHIVED); + // given + Poster poster = aDraft(); + + // when + poster.archive(); + + // then + assertThat(poster.status()).isEqualTo(PosterStatus.ARCHIVED); } @Test void archivedIsTerminalSoRepublishIsRejected() { - Poster p = sample(); - p.attachImage("posters/x/image"); - p.publish(); - p.archive(); - assertThatThrownBy(p::publish) - .isInstanceOf(PosterInvariantException.class) - .extracting(ex -> ((PosterInvariantException) ex).reason()) - .isEqualTo(PosterInvariantException.Reason.INVALID_STATUS_TRANSITION); + // given + Poster poster = aDraft(); + poster.attachImage("posters/x/image"); + poster.publish(); + poster.archive(); + + // when + Throwable thrown = catchThrowable(poster::publish); + + // then + assertThat(thrown) + .isInstanceOfSatisfying( + PosterInvariantException.class, + e -> + assertThat(e.reason()) + .isEqualTo(PosterInvariantException.Reason.INVALID_STATUS_TRANSITION)); } } diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/domain/worklog/PeriodTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/domain/worklog/PeriodTest.java index 2b3ecbc0..2ed67c6e 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/domain/worklog/PeriodTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/domain/worklog/PeriodTest.java @@ -1,41 +1,47 @@ package dev.caskeleton.sample.portfolio.domain.worklog; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; import java.time.LocalDate; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +// feature-business-rule-validation-contract C2 / D2: the business invariant ("end must not be +// before start") is enforced inside the value object's canonical constructor, and that constructor +// is the sole construction path — there is no setter or other constructor to bypass it, so no +// application-service or persistence path can hand out an invariant-violating Period. The last two +// tests are the "intentional bypass test" the design record's 테스트 계약 requires. class PeriodTest { @Test - void ongoingPeriodHasNullEnd() { - Period p = new Period(LocalDate.of(2025, 1, 1), null); - assertThat(p.isOngoing()).isTrue(); - } + void periodWithoutEndIsOngoing() { + Period period = new Period(LocalDate.of(2025, 1, 1), null); - @Test - void endBeforeStartIsRejected() { - assertThatThrownBy(() -> new Period(LocalDate.of(2025, 5, 1), LocalDate.of(2025, 1, 1))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("end"); + assertThat(period.isOngoing()).isTrue(); } @Test void startIsRequired() { - assertThatThrownBy(() -> new Period(null, null)).isInstanceOf(NullPointerException.class); + Throwable thrown = catchThrowable(() -> new Period(null, null)); + + assertThat(thrown).isInstanceOf(NullPointerException.class).hasMessage("start is required"); + } + + @ParameterizedTest + @CsvSource({"2025-05-01, 2025-01-01", "2030-12-31, 2030-01-01"}) + void endBeforeStartIsRejected(LocalDate start, LocalDate end) { + Throwable thrown = catchThrowable(() -> new Period(start, end)); + + assertThat(thrown) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("end must not be before start"); } - // feature-business-rule-validation-contract C2 / D2: the business invariant - // ("end must not be before start") is enforced inside the domain value object's - // canonical constructor. Period is an immutable record, so the compact canonical - // constructor is the SOLE construction path and there is no setter to bypass it — - // no application-service or persistence path can hand out an invariant-violating - // Period. This is the "intentional bypass test" the design record's 테스트 계약 requires. @Test - void invariantIsEnforcedOnTheSoleConstructionPathAndCannotBeBypassed() { - assertThatThrownBy(() -> new Period(LocalDate.of(2030, 12, 31), LocalDate.of(2030, 1, 1))) - .as("invariant must reject end-before-start on the sole (record) construction path (C2)") - .isInstanceOf(IllegalArgumentException.class); + void canonicalConstructorIsTheOnlyWayToBuildAPeriod() throws NoSuchMethodException { + assertThat(Period.class.getDeclaredConstructors()) + .containsExactly(Period.class.getDeclaredConstructor(LocalDate.class, LocalDate.class)); } } diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/domain/worklog/WorkLogIdPropertyTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/domain/worklog/WorkLogIdPropertyTest.java index 28a934a9..e2261051 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/domain/worklog/WorkLogIdPropertyTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/domain/worklog/WorkLogIdPropertyTest.java @@ -43,7 +43,9 @@ class WorkLogIdPropertyTest { // only asserts the rejection path. Assume.that(!value.matches(UUID_PATTERN)); - assertThatThrownBy(() -> WorkLogId.of(value)).isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> WorkLogId.of(value)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Invalid WorkLogId format: " + value); } /** 32 non-hex letters hyphenated to the UUID shape — always invalid (g-z are not hex). */ @@ -57,7 +59,9 @@ class WorkLogIdPropertyTest { @Property void rejectsNonHexLetters(@ForAll("nonHexUuidShapedStrings") String value) { - assertThatThrownBy(() -> WorkLogId.of(value)).isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> WorkLogId.of(value)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Invalid WorkLogId format: " + value); } /** Inserts hyphens into 32 chars to form the canonical 8-4-4-4-12 UUID layout. */ diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/domain/worklog/WorkLogIdTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/domain/worklog/WorkLogIdTest.java index 89866a53..08db7b74 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/domain/worklog/WorkLogIdTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/domain/worklog/WorkLogIdTest.java @@ -1,55 +1,40 @@ package dev.caskeleton.sample.portfolio.domain.worklog; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; -import java.util.Locale; -import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; class WorkLogIdTest { - private static final String VALID = "0190bd6e-7c3e-7abc-8def-0123456789ab"; // D19 fixture - - @Test - void acceptsCanonicalUuid() { - assertThat(WorkLogId.of(VALID).value()).isEqualTo(VALID); + // The VO regex is case-insensitive over hex; canonical lowercasing happens at the web edge. + @ParameterizedTest + @ValueSource( + strings = { + "0190bd6e-7c3e-7abc-8def-0123456789ab", // D19 fixture + "0190BD6E-7C3E-7ABC-8DEF-0123456789AB" + }) + void acceptsCanonicalUuidInEitherHexCase(String value) { + assertThat(WorkLogId.of(value).value()).isEqualTo(value); } - @Test - void rejectsNull() { - assertThatThrownBy(() -> WorkLogId.of(null)).isInstanceOf(IllegalArgumentException.class); - } + @ParameterizedTest(name = "{1}") + @CsvSource( + nullValues = "NULL", + value = { + "NULL, missing value", + "0190bd6e-7c3e-7abc-8def-0123456789zz, non-hex letter", + "0190bd6e-7c3e, too short", + "0190bd6e7c3e7abc8def0123456789ab, no 8-4-4-4-12 hyphen groups", + "01ARZ3NDEKTSV4RRFFQ69G5FAV, previous 26-char Crockford ULID form" + }) + void rejectsNonCanonicalValue(String value, String problem) { + Throwable thrown = catchThrowable(() -> WorkLogId.of(value)); - @Test - void acceptsUppercaseHexVariant() { - // The VO regex is case-insensitive over hex; canonical lowercasing happens at the web edge. - String uppercase = VALID.toUpperCase(Locale.ROOT); - assertThat(WorkLogId.of(uppercase).value()).isEqualTo(uppercase); - } - - @Test - void rejectsNonHexLetters() { - assertThatThrownBy(() -> WorkLogId.of("0190bd6e-7c3e-7abc-8def-0123456789zz")) // z is not hex - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void rejectsWrongLength() { - assertThatThrownBy(() -> WorkLogId.of("0190bd6e-7c3e")) // too short - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void rejectsUnhyphenatedUuid() { - assertThatThrownBy( - () -> WorkLogId.of("0190bd6e7c3e7abc8def0123456789ab")) // no 8-4-4-4-12 groups - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void rejectsCrockfordUlidFormat() { - // the previous 26-char Crockford ULID form is no longer a valid id - assertThatThrownBy(() -> WorkLogId.of("01ARZ3NDEKTSV4RRFFQ69G5FAV")) - .isInstanceOf(IllegalArgumentException.class); + assertThat(thrown) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Invalid WorkLogId format: " + value); } } diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/domain/worklog/WorkLogInvariantTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/domain/worklog/WorkLogInvariantTest.java index a212b481..1fede660 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/domain/worklog/WorkLogInvariantTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/domain/worklog/WorkLogInvariantTest.java @@ -1,7 +1,8 @@ package dev.caskeleton.sample.portfolio.domain.worklog; +import static dev.caskeleton.sample.portfolio.fixtures.SamplePortfolioFixture.WORK_LOG_ID; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; import dev.caskeleton.shared.error.ApiErrorCode; import java.time.LocalDate; @@ -15,11 +16,9 @@ import org.junit.jupiter.api.Test; */ class WorkLogInvariantTest { - private static final WorkLogId ID = WorkLogId.of("0190bd6e-7c3e-7abc-8def-0123456789ab"); - - private static WorkLog sample(String title) { + private static WorkLog aWorkLogTitled(String title) { return WorkLog.create( - ID, + WORK_LOG_ID, title, WorkCategory.BACKEND, "s", @@ -31,33 +30,48 @@ class WorkLogInvariantTest { @Test void blankTitleIsRejectedWithASafeReasonOnCreate() { - assertThatThrownBy(() -> sample(" ")) - .isInstanceOf(WorkLogInvariantException.class) - .extracting(ex -> ((WorkLogInvariantException) ex).reason()) - .isEqualTo(WorkLogInvariantException.Reason.TITLE_BLANK); + Throwable thrown = catchThrowable(() -> aWorkLogTitled(" ")); + + assertThat(thrown) + .isInstanceOfSatisfying( + WorkLogInvariantException.class, + e -> assertThat(e.reason()).isEqualTo(WorkLogInvariantException.Reason.TITLE_BLANK)); } @Test void renameToBlankIsRejected() { - WorkLog w = sample("ok"); - assertThatThrownBy(() -> w.rename("")).isInstanceOf(WorkLogInvariantException.class); + // given + WorkLog workLog = aWorkLogTitled("ok"); + + // when + Throwable thrown = catchThrowable(() -> workLog.rename("")); + + // then + assertThat(thrown) + .isInstanceOfSatisfying( + WorkLogInvariantException.class, + e -> assertThat(e.reason()).isEqualTo(WorkLogInvariantException.Reason.TITLE_BLANK)); } + // The "required" check (NPE) and the "must not be blank" invariant are distinct. @Test void nullTitleStaysANullCheckNotAnInvariantViolation() { - // The "required" check (NPE) and the "must not be blank" invariant are distinct. - assertThatThrownBy(() -> sample(null)).isInstanceOf(NullPointerException.class); + Throwable thrown = catchThrowable(() -> aWorkLogTitled(null)); + + assertThat(thrown).isInstanceOf(NullPointerException.class).hasMessage("title is required"); } // D2: the domain invariant exception carries only a safe domain reason — it must NOT // implement the operational ApiErrorCode contract. Translating reason() into an // error.category / log line is the application/web layer's responsibility. @Test - void invariantExceptionDoesNotKnowOperationalErrorCodes() { - WorkLogInvariantException ex = + void invariantExceptionCarriesOnlyADomainReasonNotAnOperationalErrorCode() { + WorkLogInvariantException exception = new WorkLogInvariantException(WorkLogInvariantException.Reason.TITLE_BLANK); - assertThat(ex).isNotInstanceOf(ApiErrorCode.class); - assertThat(ex.reason()).isEqualTo(WorkLogInvariantException.Reason.TITLE_BLANK); + assertThat(exception) + .isNotInstanceOf(ApiErrorCode.class) + .extracting(WorkLogInvariantException::reason) + .isEqualTo(WorkLogInvariantException.Reason.TITLE_BLANK); } } diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/domain/worklog/WorkLogTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/domain/worklog/WorkLogTest.java index b8f44670..4db9300e 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/domain/worklog/WorkLogTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/domain/worklog/WorkLogTest.java @@ -1,85 +1,153 @@ package dev.caskeleton.sample.portfolio.domain.worklog; +import static dev.caskeleton.sample.portfolio.fixtures.SamplePortfolioFixture.WORK_LOG_ID; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.junit.jupiter.params.provider.Arguments.arguments; import java.time.LocalDate; import java.util.List; +import java.util.stream.Stream; +import org.assertj.core.api.ThrowableAssert.ThrowingCallable; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; class WorkLogTest { - private static final WorkLogId ID = WorkLogId.of("0190bd6e-7c3e-7abc-8def-0123456789ab"); + private static final WorkLogOwner OWNER = WorkLogOwner.of("owner-1"); + private static final String TITLE = "DB 쿼리 튜닝"; + private static final WorkCategory CATEGORY = WorkCategory.DATABASE; + private static final Period PERIOD = new Period(LocalDate.of(2025, 1, 1), null); - private WorkLog sample() { + private static WorkLog anOpenWorkLog() { return WorkLog.create( - ID, - "DB 쿼리 튜닝", - WorkCategory.DATABASE, + WORK_LOG_ID, + TITLE, + CATEGORY, "slow query 개선", "...", List.of("postgres"), List.of(), - new Period(LocalDate.of(2025, 1, 1), null)); + PERIOD); + } + + private static WorkLog create( + WorkLogId id, WorkLogOwner owner, String title, WorkCategory category, Period period) { + return WorkLog.create(id, owner, title, category, "s", "c", List.of(), List.of(), period); } @Test void createKeepsAssignedIdAndFields() { - WorkLog w = sample(); - assertThat(w.id()).isEqualTo(ID); - assertThat(w.title()).isEqualTo("DB 쿼리 튜닝"); - assertThat(w.category()).isEqualTo(WorkCategory.DATABASE); + WorkLog workLog = anOpenWorkLog(); + + assertThat(workLog) + .extracting( + WorkLog::id, + WorkLog::title, + WorkLog::category, + WorkLog::summary, + WorkLog::content, + WorkLog::techStack, + WorkLog::links, + WorkLog::period) + .containsExactly( + WORK_LOG_ID, + TITLE, + CATEGORY, + "slow query 개선", + "...", + List.of("postgres"), + List.of(), + PERIOD); } - @Test - void titleIsRequired() { - assertThatThrownBy( - () -> - WorkLog.create( - ID, - null, - WorkCategory.DATABASE, - "s", - "c", - List.of(), - List.of(), - new Period(LocalDate.of(2025, 1, 1), null))) - .isInstanceOf(NullPointerException.class); + static Stream createCallsMissingOneRequiredArgument() { + return Stream.of( + arguments("id", (ThrowingCallable) () -> create(null, OWNER, TITLE, CATEGORY, PERIOD)), + arguments( + "owner", (ThrowingCallable) () -> create(WORK_LOG_ID, null, TITLE, CATEGORY, PERIOD)), + arguments( + "title", (ThrowingCallable) () -> create(WORK_LOG_ID, OWNER, null, CATEGORY, PERIOD)), + arguments( + "category", (ThrowingCallable) () -> create(WORK_LOG_ID, OWNER, TITLE, null, PERIOD)), + arguments( + "period", (ThrowingCallable) () -> create(WORK_LOG_ID, OWNER, TITLE, CATEGORY, null))); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("createCallsMissingOneRequiredArgument") + void createRejectsAMissingRequiredArgumentByName(String argument, ThrowingCallable create) { + Throwable thrown = catchThrowable(create); + + assertThat(thrown) + .isInstanceOf(NullPointerException.class) + .hasMessage(argument + " is required"); } @Test void renameChangesTitle() { - WorkLog w = sample(); - w.rename("새 제목"); - assertThat(w.title()).isEqualTo("새 제목"); + // given + WorkLog workLog = anOpenWorkLog(); + + // when + workLog.rename("새 제목"); + + // then + assertThat(workLog.title()).isEqualTo("새 제목"); } @Test - void createStartsOpenAndKeepsOwner() { - WorkLog w = sample(); - assertThat(w.status()).isEqualTo(WorkLogStatus.OPEN); - assertThat(w.owner()).isEqualTo(WorkLogOwner.of("sample-owner")); + void createWithoutOwnerStartsOpenOwnedByTheSampleOwner() { + WorkLog workLog = anOpenWorkLog(); + + assertThat(workLog) + .extracting(WorkLog::status, WorkLog::owner) + .containsExactly(WorkLogStatus.OPEN, WorkLogOwner.of("sample-owner")); } @Test - void statusTransitionIsOpenToInProgressToClosed() { - WorkLog w = sample(); - w.startProgress(); - assertThat(w.status()).isEqualTo(WorkLogStatus.IN_PROGRESS); + void startProgressMovesAnOpenWorkLogToInProgress() { + // given + WorkLog workLog = anOpenWorkLog(); - w.close(); - assertThat(w.status()).isEqualTo(WorkLogStatus.CLOSED); + // when + workLog.startProgress(); + + // then + assertThat(workLog.status()).isEqualTo(WorkLogStatus.IN_PROGRESS); + } + + @Test + void closeMovesAnInProgressWorkLogToClosed() { + // given + WorkLog workLog = anOpenWorkLog(); + workLog.startProgress(); + + // when + workLog.close(); + + // then + assertThat(workLog.status()).isEqualTo(WorkLogStatus.CLOSED); } @Test void closedWorklogRejectsContentMutation() { - WorkLog w = sample(); - w.startProgress(); - w.close(); + // given + WorkLog workLog = anOpenWorkLog(); + workLog.startProgress(); + workLog.close(); - assertThatThrownBy(() -> w.rename("닫힌 작업 수정")) - .isInstanceOf(WorkLogInvariantException.class) - .extracting(ex -> ((WorkLogInvariantException) ex).reason()) - .isEqualTo(WorkLogInvariantException.Reason.CLOSED_WORKLOG_MUTATION); + // when + Throwable thrown = catchThrowable(() -> workLog.rename("닫힌 작업 수정")); + + // then + assertThat(thrown) + .isInstanceOfSatisfying( + WorkLogInvariantException.class, + e -> + assertThat(e.reason()) + .isEqualTo(WorkLogInvariantException.Reason.CLOSED_WORKLOG_MUTATION)); } } diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/domain/worklog/testkit/InMemoryWorkLogRepositoryContractTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/domain/worklog/testkit/InMemoryWorkLogRepositoryContractTest.java new file mode 100644 index 00000000..3c17d403 --- /dev/null +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/domain/worklog/testkit/InMemoryWorkLogRepositoryContractTest.java @@ -0,0 +1,19 @@ +package dev.caskeleton.sample.portfolio.domain.worklog.testkit; + +import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogRepository; +import java.util.function.Supplier; + +class InMemoryWorkLogRepositoryContractTest extends WorkLogRepositoryContract { + + private final InMemoryWorkLogRepository repository = new InMemoryWorkLogRepository(); + + @Override + protected WorkLogRepository repository() { + return repository; + } + + @Override + protected T inTransaction(Supplier work) { + return work.get(); + } +} diff --git a/src/sample-portfolio/src/testFixtures/java/dev/caskeleton/sample/portfolio/application/posterimage/testkit/InMemoryPosterImageRetirementIntentStore.java b/src/sample-portfolio/src/testFixtures/java/dev/caskeleton/sample/portfolio/application/posterimage/testkit/InMemoryPosterImageRetirementIntentStore.java new file mode 100644 index 00000000..edc2014a --- /dev/null +++ b/src/sample-portfolio/src/testFixtures/java/dev/caskeleton/sample/portfolio/application/posterimage/testkit/InMemoryPosterImageRetirementIntentStore.java @@ -0,0 +1,98 @@ +package dev.caskeleton.sample.portfolio.application.posterimage.testkit; + +import dev.caskeleton.application.objectstorage.identity.ObjectOperationId; +import dev.caskeleton.sample.portfolio.application.posterimage.PosterImageRetirementIntent; +import dev.caskeleton.sample.portfolio.application.posterimage.PosterImageRetirementIntentState; +import dev.caskeleton.sample.portfolio.application.posterimage.PosterImageRetirementIntentStorePort; +import dev.caskeleton.sample.portfolio.application.posterimage.PosterImageUploadIntentConflictException; +import java.time.Duration; +import java.time.Instant; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; + +/** + * In-memory {@link PosterImageRetirementIntentStorePort} following the JPA adapter: create-or-read + * by operation or exact reference, revision-checked compare-and-set, and claims of the oldest ready + * intent. + */ +public final class InMemoryPosterImageRetirementIntentStore + implements PosterImageRetirementIntentStorePort { + + private final Map rows = new LinkedHashMap<>(); + + @Override + public PosterImageRetirementIntent createOrRead(PosterImageRetirementIntent proposed) { + Optional existing = + rows.values().stream() + .filter( + row -> + row.operationId().equals(proposed.operationId()) + || (row.reference().equals(proposed.reference()) + && row.exactVersion().equals(proposed.exactVersion()))) + .findFirst(); + if (existing.isEmpty()) { + rows.put(proposed.id(), proposed); + return proposed; + } + PosterImageRetirementIntent found = existing.orElseThrow(); + if (!found.operationId().equals(proposed.operationId()) + || !found.reference().equals(proposed.reference()) + || !found.exactVersion().equals(proposed.exactVersion())) { + throw new PosterImageUploadIntentConflictException( + "poster image retirement operation conflicts"); + } + return found; + } + + @Override + public Optional findByOperation(ObjectOperationId operation) { + return rows.values().stream().filter(row -> row.operationId().equals(operation)).findFirst(); + } + + @Override + public PosterImageRetirementIntent compareAndSet( + long expectedRevision, PosterImageRetirementIntent replacement) { + PosterImageRetirementIntent current = rows.get(replacement.id()); + if (current == null) { + throw new PosterImageUploadIntentConflictException( + "poster image retirement intent is absent"); + } + if (current.revision() != expectedRevision || replacement.revision() != expectedRevision + 1) { + throw new PosterImageUploadIntentConflictException( + "poster image retirement revision conflicts"); + } + rows.put(replacement.id(), replacement); + return replacement; + } + + @Override + public Optional claimReady( + String claimantDigest, Instant now, Duration leaseDuration) { + return rows.values().stream() + .filter(row -> claimable(row, now)) + .min( + Comparator.comparing(PosterImageRetirementIntent::updatedAt) + .thenComparing(PosterImageRetirementIntent::id)) + .map( + row -> + compareAndSet( + row.revision(), row.claim(row.revision(), claimantDigest, now, leaseDuration))); + } + + /** Every stored intent, in insertion order. */ + public List all() { + return List.copyOf(rows.values()); + } + + private static boolean claimable(PosterImageRetirementIntent row, Instant now) { + return (row.state() == PosterImageRetirementIntentState.PENDING + || row.state() == PosterImageRetirementIntentState.IN_FLIGHT) + && !row.retainUntil().isAfter(now) + && (row.retryAt() == null || !row.retryAt().isAfter(now)) + && (row.claimExpiresAt() == null || !row.claimExpiresAt().isAfter(now)); + } +} diff --git a/src/sample-portfolio/src/testFixtures/java/dev/caskeleton/sample/portfolio/domain/worklog/testkit/InMemoryWorkLogRepository.java b/src/sample-portfolio/src/testFixtures/java/dev/caskeleton/sample/portfolio/domain/worklog/testkit/InMemoryWorkLogRepository.java new file mode 100644 index 00000000..0e2254ef --- /dev/null +++ b/src/sample-portfolio/src/testFixtures/java/dev/caskeleton/sample/portfolio/domain/worklog/testkit/InMemoryWorkLogRepository.java @@ -0,0 +1,105 @@ +package dev.caskeleton.sample.portfolio.domain.worklog.testkit; + +import dev.caskeleton.sample.portfolio.domain.worklog.WorkCategory; +import dev.caskeleton.sample.portfolio.domain.worklog.WorkLog; +import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogId; +import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogPage; +import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogRepository; +import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogSortField; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Stream; + +/** + * In-memory {@link WorkLogRepository} with the semantics of {@code WorkLogRepositoryAdapter}, held + * to them by {@link WorkLogRepositoryContract}: it stores snapshots (a caller's later mutation is + * not saved), a new WorkLog is saved at version 0 and an update increments it, and {@code findPage} + * sorts, filters, and clamps page/size the way the adapter does. + * + *

    It does not model optimistic-lock conflicts on a stale version. + */ +public final class InMemoryWorkLogRepository implements WorkLogRepository { + + private static final int DEFAULT_PAGE_SIZE = 20; + + private final Map rows = new LinkedHashMap<>(); + + @Override + public WorkLog save(WorkLog workLog) { + long version; + if (workLog.version() == null) { + version = 0L; + } else { + WorkLog existing = rows.get(workLog.id()); + if (existing == null) { + throw new IllegalStateException( + "no persisted work_log row to carry audit creation from: " + workLog.id().value()); + } + version = existing.version() + 1; + } + WorkLog stored = copy(workLog, version); + rows.put(stored.id(), stored); + return copy(stored, version); + } + + @Override + public Optional findById(WorkLogId id) { + return Optional.ofNullable(rows.get(id)).map(w -> copy(w, w.version())); + } + + @Override + public WorkLogPage findPage( + int page, int size, WorkLogSortField sortField, boolean ascending, WorkCategory category) { + int safeSize = size <= 0 ? DEFAULT_PAGE_SIZE : size; + int safePage = Math.max(0, page); + List matching = + rows.values().stream().filter(w -> category == null || w.category() == category).toList(); + Stream ordered = matching.stream(); + if (sortField != null) { + Comparator order = comparator(sortField); + ordered = ordered.sorted(ascending ? order : order.reversed()); + } + List items = + ordered + .skip((long) safePage * safeSize) + .limit(safeSize) + .map(w -> copy(w, w.version())) + .toList(); + return new WorkLogPage(items, matching.size()); + } + + @Override + public boolean existsById(WorkLogId id) { + return rows.containsKey(id); + } + + @Override + public void deleteById(WorkLogId id) { + rows.remove(id); + } + + private static Comparator comparator(WorkLogSortField field) { + return switch (field) { + case TITLE -> Comparator.comparing(WorkLog::title); + case PERIOD_START -> Comparator.comparing(w -> w.period().start()); + }; + } + + private static WorkLog copy(WorkLog w, Long version) { + return WorkLog.rehydrate( + w.id(), + w.owner(), + w.title(), + w.category(), + w.status(), + w.summary(), + w.content(), + w.techStack(), + w.links(), + w.period(), + version); + } +} diff --git a/src/sample-portfolio/src/testFixtures/java/dev/caskeleton/sample/portfolio/domain/worklog/testkit/WorkLogRepositoryContract.java b/src/sample-portfolio/src/testFixtures/java/dev/caskeleton/sample/portfolio/domain/worklog/testkit/WorkLogRepositoryContract.java new file mode 100644 index 00000000..712e4587 --- /dev/null +++ b/src/sample-portfolio/src/testFixtures/java/dev/caskeleton/sample/portfolio/domain/worklog/testkit/WorkLogRepositoryContract.java @@ -0,0 +1,309 @@ +package dev.caskeleton.sample.portfolio.domain.worklog.testkit; + +import static org.assertj.core.api.Assertions.assertThat; + +import dev.caskeleton.sample.portfolio.domain.worklog.Period; +import dev.caskeleton.sample.portfolio.domain.worklog.WorkCategory; +import dev.caskeleton.sample.portfolio.domain.worklog.WorkLog; +import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogId; +import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogOwner; +import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogPage; +import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogRepository; +import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogSortField; +import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogStatus; +import java.time.LocalDate; +import java.util.List; +import java.util.Optional; +import java.util.function.Supplier; +import java.util.stream.IntStream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; + +/** + * What every {@link WorkLogRepository} promises, run against {@link InMemoryWorkLogRepository} and + * the PostgreSQL {@code WorkLogRepositoryAdapter} alike. + * + *

    Every call goes through {@link #inTransaction}, so each one commits before the next reads it: + * a read sees what the store kept, not the caller's object. + */ +public abstract class WorkLogRepositoryContract { + + private static final WorkLogId ALPHA = id(1); + private static final WorkLogId BRAVO = id(2); + private static final WorkLogId CHARLIE = id(3); + private static final WorkLogId UNKNOWN = id(99); + + /** The repository under test, empty at the start of each test. */ + protected abstract WorkLogRepository repository(); + + /** Runs {@code work} in one committed transaction of the repository under test. */ + protected abstract T inTransaction(Supplier work); + + @Test + void savingANewWorkLogStoresItAtVersionZero() { + // when + WorkLog saved = save(alpha()); + + // then + assertThat(saved.version()).isZero(); + } + + @Test + void findByIdReturnsEveryFieldThatWasSaved() { + // given + WorkLog saved = save(alpha()); + + // when + Optional found = find(ALPHA); + + // then + assertThat(found).get().usingRecursiveComparison().isEqualTo(saved); + } + + @Test + void findByIdOfAnUnknownIdIsEmpty() { + // given + save(alpha()); + + // when + Optional found = find(UNKNOWN); + + // then + assertThat(found).isEmpty(); + } + + @Test + void savingAChangedWorkLogStoresTheChangeAtTheNextVersion() { + // given + WorkLog saved = save(alpha()); + saved.rename("renamed"); + saved.startProgress(); + + // when + save(saved); + + // then + assertThat(find(ALPHA)) + .get() + .extracting(WorkLog::title, WorkLog::status, WorkLog::version) + .containsExactly("renamed", WorkLogStatus.IN_PROGRESS, 1L); + } + + @Test + void aChangeMadeAfterSavingIsNotStoredUntilSavedAgain() { + // given + WorkLog saved = save(alpha()); + saved.rename("unsaved"); + + // when + Optional found = find(ALPHA); + + // then + assertThat(found).get().extracting(WorkLog::title).isEqualTo("alpha"); + } + + @Test + void existsByIdIsTrueForASavedWorkLog() { + // given + save(alpha()); + + // when + boolean exists = inTransaction(() -> repository().existsById(ALPHA)); + + // then + assertThat(exists).isTrue(); + } + + @Test + void existsByIdIsFalseForAnUnknownId() { + // given + save(alpha()); + + // when + boolean exists = inTransaction(() -> repository().existsById(UNKNOWN)); + + // then + assertThat(exists).isFalse(); + } + + @Test + void deleteByIdRemovesOnlyThatWorkLog() { + // given + saveAll(); + + // when + inTransaction( + () -> { + repository().deleteById(BRAVO); + return null; + }); + + // then + assertThat(page(0, 20, WorkLogSortField.TITLE, true, null)) + .extracting(WorkLog::id) + .containsExactly(ALPHA, CHARLIE); + } + + @Test + void deleteByIdOfAnUnknownIdChangesNothing() { + // given + saveAll(); + + // when + inTransaction( + () -> { + repository().deleteById(UNKNOWN); + return null; + }); + + // then + assertThat(page(0, 20, WorkLogSortField.TITLE, true, null)) + .extracting(WorkLog::id) + .containsExactly(ALPHA, BRAVO, CHARLIE); + } + + @ParameterizedTest + @CsvSource({ + "TITLE, true, alpha|bravo|charlie", + "TITLE, false, charlie|bravo|alpha", + "PERIOD_START, true, bravo|charlie|alpha", + "PERIOD_START, false, alpha|charlie|bravo" + }) + void findPageOrdersByTheRequestedFieldAndDirection( + WorkLogSortField field, boolean ascending, String expectedTitles) { + // given + saveAll(); + + // when + WorkLogPage found = inTransaction(() -> repository().findPage(0, 20, field, ascending, null)); + + // then + assertThat(found.items()) + .extracting(WorkLog::title) + .containsExactly(expectedTitles.split("\\|")); + } + + @Test + void findPageWithoutASortFieldReturnsEveryWorkLog() { + // given + saveAll(); + + // when + WorkLogPage found = inTransaction(() -> repository().findPage(0, 20, null, true, null)); + + // then + assertThat(found.items()) + .extracting(WorkLog::id) + .containsExactlyInAnyOrder(ALPHA, BRAVO, CHARLIE); + } + + @Test + void findPageFiltersByCategoryAndCountsOnlyTheMatches() { + // given + saveAll(); + + // when + WorkLogPage found = + inTransaction( + () -> + repository().findPage(0, 20, WorkLogSortField.TITLE, true, WorkCategory.DATABASE)); + + // then + assertThat(found) + .extracting(WorkLogRepositoryContract::ids, WorkLogPage::total) + .containsExactly(List.of(ALPHA, CHARLIE), 2L); + } + + @Test + void findPageReturnsTheRequestedSliceAndTheTotalAcrossAllPages() { + // given + saveAll(); + + // when + WorkLogPage found = + inTransaction(() -> repository().findPage(1, 2, WorkLogSortField.TITLE, true, null)); + + // then + assertThat(found) + .extracting(WorkLogRepositoryContract::ids, WorkLogPage::total) + .containsExactly(List.of(CHARLIE), 3L); + } + + @Test + void findPageTreatsANegativePageAsTheFirstPage() { + // given + saveAll(); + + // when + WorkLogPage found = + inTransaction(() -> repository().findPage(-1, 2, WorkLogSortField.TITLE, true, null)); + + // then + assertThat(found.items()).extracting(WorkLog::id).containsExactly(ALPHA, BRAVO); + } + + @ParameterizedTest + @ValueSource(ints = {0, -1}) + void findPageTreatsANonPositiveSizeAsPagesOfTwenty(int size) { + // given + IntStream.rangeClosed(1, 21) + .forEach(n -> save(workLog(id(n), "title-%02d".formatted(n), WorkCategory.BACKEND, 1))); + + // when + WorkLogPage found = + inTransaction(() -> repository().findPage(0, size, WorkLogSortField.TITLE, true, null)); + + // then + assertThat(found) + .extracting(p -> p.items().size(), WorkLogPage::total) + .containsExactly(20, 21L); + } + + private WorkLog save(WorkLog workLog) { + return inTransaction(() -> repository().save(workLog)); + } + + private Optional find(WorkLogId id) { + return inTransaction(() -> repository().findById(id)); + } + + private List page( + int page, int size, WorkLogSortField field, boolean ascending, WorkCategory category) { + return inTransaction(() -> repository().findPage(page, size, field, ascending, category)) + .items(); + } + + /** Titles and period starts sort in different orders, so each sort field is observable. */ + private void saveAll() { + save(alpha()); + save(workLog(BRAVO, "bravo", WorkCategory.BACKEND, 1)); + save(workLog(CHARLIE, "charlie", WorkCategory.DATABASE, 2)); + } + + private static WorkLog alpha() { + return workLog(ALPHA, "alpha", WorkCategory.DATABASE, 3); + } + + private static WorkLog workLog(WorkLogId id, String title, WorkCategory category, int month) { + return WorkLog.create( + id, + WorkLogOwner.of("owner-1"), + title, + category, + "summary of " + title, + "content of " + title, + List.of("postgres", "jpa"), + List.of("https://example.test/" + title), + new Period(LocalDate.of(2025, month, 1), LocalDate.of(2025, month, 28))); + } + + private static List ids(WorkLogPage page) { + return page.items().stream().map(WorkLog::id).toList(); + } + + private static WorkLogId id(int n) { + return WorkLogId.of("0190bd6e-7c3e-7abc-8def-%012d".formatted(n)); + } +} diff --git a/src/sample-portfolio/src/webSystemTest/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/contract/OpenApiDriftContractTest.java b/src/sample-portfolio/src/webSystemTest/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/contract/OpenApiDriftContractTest.java index 49c5f22f..6e1d3225 100644 --- a/src/sample-portfolio/src/webSystemTest/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/contract/OpenApiDriftContractTest.java +++ b/src/sample-portfolio/src/webSystemTest/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/contract/OpenApiDriftContractTest.java @@ -59,7 +59,8 @@ import org.springframework.test.context.bean.override.mockito.MockitoBean; @SpringBootTest( classes = OpenApiDriftContractTest.OpenApiDriftTestApp.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, - properties = "management.server.port=0") + // The app excludes the data layer; persistence-jpa is on while present, so it is switched off. + properties = {"management.server.port=0", "ca-skeleton.persistence-jpa.enabled=false"}) @AutoConfigureTestRestTemplate class OpenApiDriftContractTest { @@ -91,34 +92,25 @@ class OpenApiDriftContractTest { @Test void runtimeOpenapiDocMatchesCommittedSnapshot() throws IOException { + // when ResponseEntity response = rest.getForEntity("http://localhost:" + port + "/v3/api-docs", String.class); - assertThat(response.getStatusCode().is2xxSuccessful()) + + // then + assertThat(response.getStatusCode().value()) .as("springdoc must serve the generated OpenAPI document") - .isTrue(); - + .isEqualTo(200); String canonical = canonicalize(response.getBody()); - if (Boolean.getBoolean(WRITE_FLAG)) { writeSnapshot(canonical); - return; // refresh mode: baseline (re)generated; no assertion + return; // refresh mode: baseline (re)generated; no comparison } - - String committed = readCommittedSnapshot(); - if (committed == null) { - fail( - "No committed OpenAPI snapshot on the classpath (" - + SNAPSHOT_RESOURCE - + "). Generate the " - + "baseline with: ./gradlew openapiCheckSnapshot -PapproveOpenApiChange"); - } - assertThat(canonical) .as( "the runtime springdoc /v3/api-docs drifted from the committed OpenAPI snapshot — if " + "this change is intended, regenerate with " + "./gradlew openapiCheckSnapshot -PapproveOpenApiChange") - .isEqualTo(canonicalize(committed)); + .isEqualTo(canonicalize(readCommittedSnapshot())); } @SuppressWarnings("unchecked") @@ -135,7 +127,14 @@ class OpenApiDriftContractTest { private String readCommittedSnapshot() throws IOException { try (InputStream in = getClass().getResourceAsStream(SNAPSHOT_RESOURCE)) { - return in == null ? null : new String(in.readAllBytes(), StandardCharsets.UTF_8); + if (in == null) { + fail( + "No committed OpenAPI snapshot on the classpath (" + + SNAPSHOT_RESOURCE + + "). Generate the baseline with: " + + "./gradlew openapiCheckSnapshot -PapproveOpenApiChange"); + } + return new String(in.readAllBytes(), StandardCharsets.UTF_8); } } @@ -166,7 +165,11 @@ class OpenApiDriftContractTest { OAuth2ResourceServerAutoConfiguration.class, DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class - }) + }, + // The snapshot is the controller's surface; the web adapter's filters and security are + // not part of it and need collaborators this slice does not assemble. + excludeName = + "dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebAdapterAutoConfiguration") @Import({WorkLogController.class, OpenApiContractConfig.class}) static class OpenApiDriftTestApp {} } diff --git a/src/sample-portfolio/src/webSystemTest/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/date/DateHeaderContractTest.java b/src/sample-portfolio/src/webSystemTest/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/date/DateHeaderContractTest.java index 884fca00..587da00e 100644 --- a/src/sample-portfolio/src/webSystemTest/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/date/DateHeaderContractTest.java +++ b/src/sample-portfolio/src/webSystemTest/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/date/DateHeaderContractTest.java @@ -1,8 +1,10 @@ package dev.caskeleton.sample.portfolio.adapter.inbound.web.date; import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.util.StringUtils.hasText; -import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @@ -29,7 +31,8 @@ import org.springframework.web.bind.annotation.RestController; @SpringBootTest( classes = DateHeaderContractTest.DateProbeApp.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, - properties = "management.server.port=0") + // The app excludes the data layer; persistence-jpa is on while present, so it is switched off. + properties = {"management.server.port=0", "ca-skeleton.persistence-jpa.enabled=false"}) @AutoConfigureTestRestTemplate class DateHeaderContractTest { @@ -37,20 +40,17 @@ class DateHeaderContractTest { @Autowired TestRestTemplate rest; - @Test - void successResponseCarriesADateHeader() { + @ParameterizedTest + @CsvSource({"/__date/ok, 200", "/__date/does-not-exist, 404"}) + void everyResponseCarriesADateHeader(String path, int expectedStatus) { + // when ResponseEntity response = - rest.getForEntity("http://localhost:" + port + "/__date/ok", String.class); - assertThat(response.getStatusCode().value()).isEqualTo(200); - assertThat(response.getHeaders().getFirst("Date")).isNotBlank(); - } + rest.getForEntity("http://localhost:" + port + path, String.class); - @Test - void errorResponseAlsoCarriesADateHeader() { - ResponseEntity response = - rest.getForEntity("http://localhost:" + port + "/__date/does-not-exist", String.class); - assertThat(response.getStatusCode().value()).isEqualTo(404); - assertThat(response.getHeaders().getFirst("Date")).isNotBlank(); + // then + assertThat(response) + .extracting(r -> r.getStatusCode().value(), r -> hasText(r.getHeaders().getFirst("Date"))) + .containsExactly(expectedStatus, true); } @SpringBootConfiguration @@ -62,7 +62,11 @@ class DateHeaderContractTest { OAuth2ResourceServerAutoConfiguration.class, DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class - }) + }, + // The Date header comes from Tomcat; the web adapter's filters and security need + // collaborators this probe app does not assemble. + excludeName = + "dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebAdapterAutoConfiguration") static class DateProbeApp { @RestController diff --git a/src/sample-portfolio/src/webSystemTest/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/filter/VirtualThreadMdcE2ETest.java b/src/sample-portfolio/src/webSystemTest/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/filter/VirtualThreadMdcE2ETest.java index 963cefe6..32fb177b 100644 --- a/src/sample-portfolio/src/webSystemTest/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/filter/VirtualThreadMdcE2ETest.java +++ b/src/sample-portfolio/src/webSystemTest/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/filter/VirtualThreadMdcE2ETest.java @@ -60,69 +60,79 @@ import org.springframework.web.bind.annotation.RestController; properties = { "spring.threads.virtual.enabled=true", "spring.jackson.deserialization.fail-on-unknown-properties=true", - "management.server.port=0" + "management.server.port=0", + // The app excludes the data layer; persistence-jpa is on while present, so it is off here. + "ca-skeleton.persistence-jpa.enabled=false" }) @AutoConfigureTestRestTemplate class VirtualThreadMdcE2ETest { private static final ParameterizedTypeReference> ENVELOPE_TYPE = new ParameterizedTypeReference<>() {}; + private static final String REQUEST_ID = "X-Request-Id"; @LocalServerPort int port; @Autowired TestRestTemplate http; @Test - void filterPropagatesRequestIdToControllerUnderVirtualThreads() { - ResponseEntity> response = - http.exchange( - URI.create("http://localhost:" + port + "/test-probe/context"), - HttpMethod.GET, - null, - ENVELOPE_TYPE); + void assignedRequestIdReachesTheControllerOnAVirtualThread() { + // when + ResponseEntity> response = probe(new HttpHeaders()); - assertThat(response.getStatusCode().is2xxSuccessful()).isTrue(); - @SuppressWarnings("unchecked") - Map body = (Map) response.getBody().get("data"); - assertThat(body).as("envelope.data must be the controller payload").isNotNull(); - - assertThat(body.get("virtualThread")) - .as( - "Tomcat must dispatch on a virtual thread when " - + "spring.threads.virtual.enabled=true") - .isEqualTo("true"); - - assertThat(body.get("requestId")) - .as( - "requestId set by RequestLoggingFilter must reach the controller — " - + "B6 propagation on a virtual carrier") - .isNotNull() + // then + assertThat(response) + .extracting( + r -> r.getStatusCode().value(), + r -> probeData(r).get("virtualThread"), + r -> probeData(r).get("requestId")) + .containsExactly(200, "true", response.getHeaders().getFirst(REQUEST_ID)); + assertThat(response.getHeaders().getFirst(REQUEST_ID)) + .as("the filter assigns a request id and echoes it as a header") + .isNotBlank() .isNotEqualTo("null"); - - String requestIdHeader = response.getHeaders().getFirst("X-Request-Id"); - assertThat(requestIdHeader) - .as("the filter echoes the requestId back as a header") - .isEqualTo(body.get("requestId")); } @Test - void filterRejectsClientSuppliedRequestIdUnderVirtualThreads() { + void clientSuppliedRequestIdIsReplacedByTheOneTheControllerSees() { + // given HttpHeaders headers = new HttpHeaders(); - headers.set("X-Request-Id", "client-supplied-abc"); - ResponseEntity> response = - http.exchange( - new RequestEntity<>( - headers, - HttpMethod.GET, - URI.create("http://localhost:" + port + "/test-probe/context")), - ENVELOPE_TYPE); + headers.set(REQUEST_ID, "client-supplied-abc"); - assertThat(response.getStatusCode().is2xxSuccessful()).isTrue(); - @SuppressWarnings("unchecked") - Map body = (Map) response.getBody().get("data"); - String assigned = String.valueOf(body.get("requestId")); - assertThat(assigned).isNotBlank().isNotEqualTo("client-supplied-abc"); - assertThat(response.getHeaders().getFirst("X-Request-Id")).isEqualTo(assigned); + // when + ResponseEntity> response = probe(headers); + + // then + assertThat(response) + .extracting( + r -> r.getStatusCode().value(), + r -> probeData(r).get("virtualThread"), + r -> probeData(r).get("requestId")) + .containsExactly(200, "true", response.getHeaders().getFirst(REQUEST_ID)); + assertThat(response.getHeaders().getFirst(REQUEST_ID)) + .as("the default trust policy replaces a client-supplied id") + .isNotBlank() + .isNotEqualTo("client-supplied-abc"); + } + + private ResponseEntity> probe(HttpHeaders headers) { + return http.exchange( + new RequestEntity<>( + headers, + HttpMethod.GET, + URI.create("http://localhost:" + port + "/test-probe/context")), + ENVELOPE_TYPE); + } + + /** + * The controller payload inside the response envelope's {@code data}; empty when the envelope has + * none (an error response), so the assertion reports the status instead of a + * NullPointerException. + */ + private static Map probeData(ResponseEntity> response) { + return response.getBody() != null && response.getBody().get("data") instanceof Map data + ? data + : Map.of(); } @SpringBootConfiguration @@ -135,7 +145,11 @@ class VirtualThreadMdcE2ETest { DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class, DataJpaRepositoriesAutoConfiguration.class - }) + }, + // The filter under test is imported below with a stub pseudonymizer; the rest of the web + // adapter (its security answers 401) is not part of this pin. + excludeName = + "dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebAdapterAutoConfiguration") @Import({ ContextProbeController.class, GlobalExceptionHandler.class, diff --git a/src/sample-portfolio/src/webSystemTest/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/openapi/OpenApiSnapshotTest.java b/src/sample-portfolio/src/webSystemTest/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/openapi/OpenApiSnapshotTest.java index e41b580b..de308f4a 100644 --- a/src/sample-portfolio/src/webSystemTest/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/openapi/OpenApiSnapshotTest.java +++ b/src/sample-portfolio/src/webSystemTest/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/openapi/OpenApiSnapshotTest.java @@ -1,6 +1,7 @@ package dev.caskeleton.sample.portfolio.adapter.inbound.web.openapi; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatObject; import dev.caskeleton.adapter.inbound.web.config.OpenApiContractConfig; import dev.caskeleton.sample.portfolio.adapter.inbound.web.controller.WorkLogController; @@ -28,7 +29,6 @@ import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.context.annotation.Import; import org.springframework.http.ResponseEntity; import org.springframework.test.context.bean.override.mockito.MockitoBean; -import tools.jackson.databind.JsonNode; import tools.jackson.databind.ObjectMapper; /** @@ -41,7 +41,8 @@ import tools.jackson.databind.ObjectMapper; @SpringBootTest( classes = OpenApiSnapshotTest.OpenApiTestApp.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, - properties = "management.server.port=0") + // The app excludes the data layer; persistence-jpa is on while present, so it is switched off. + properties = {"management.server.port=0", "ca-skeleton.persistence-jpa.enabled=false"}) @AutoConfigureTestRestTemplate class OpenApiSnapshotTest { @@ -62,31 +63,28 @@ class OpenApiSnapshotTest { @MockitoBean GetRepoStatsUseCase repoStatsUseCase; @Test - void apiDocsAreGeneratedAndDescribeTheWorklogsContract() throws Exception { + void apiDocsAreGeneratedAndDescribeTheWorklogsContract() { + // when ResponseEntity response = rest.getForEntity("http://localhost:" + port + "/v3/api-docs", String.class); - assertThat(response.getStatusCode().is2xxSuccessful()) + // then + assertThat(response.getStatusCode().value()) .as("springdoc must serve the generated OpenAPI document (D10 producer)") - .isTrue(); - String body = response.getBody(); - assertThat(body).isNotNull(); - assertThat(body).contains("\"openapi\""); // OAS 3.x document - assertThat(body).contains("/worklogs"); // real controller surface, not a stale schema - assertThat(body).contains("/worklogs:batchCreate"); // AIP-136 colon-verb custom method (D23) - - JsonNode apiErrorDetailsSchema = - objectMapper - .readTree(body) - .path("components") - .path("schemas") - .path("ApiError") - .path("properties") - .path("details"); - JsonNode apiErrorDetailsType = apiErrorDetailsSchema.get("type"); - assertThat(apiErrorDetailsType == null ? null : apiErrorDetailsType.asString()) - .as("the public ApiError.details contract must remain an object schema") - .isEqualTo("object"); + .isEqualTo(200); + // assertThatObject: JsonNode is Iterable, and the element-wise extracting would not apply here. + assertThatObject(objectMapper.readTree(response.getBody())) + .extracting( + // OAS 3.x document + apiDocs -> apiDocs.path("openapi").asString().startsWith("3."), + // the real controller surface, not a stale schema + apiDocs -> apiDocs.path("paths").has("/worklogs"), + // AIP-136 colon-verb custom method (D23) + apiDocs -> apiDocs.path("paths").has("/worklogs:batchCreate"), + // the public ApiError.details contract must remain an object schema + apiDocs -> + apiDocs.at("/components/schemas/ApiError/properties/details/type").asString()) + .containsExactly(true, true, true, "object"); } @SpringBootConfiguration @@ -98,7 +96,11 @@ class OpenApiSnapshotTest { OAuth2ResourceServerAutoConfiguration.class, DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class - }) + }, + // The api-docs describe the controller's surface; the web adapter's filters and security + // are not part of it and need collaborators this slice does not assemble. + excludeName = + "dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebAdapterAutoConfiguration") @Import({WorkLogController.class, OpenApiContractConfig.class}) static class OpenApiTestApp {} } diff --git a/src/shared-contract/build.gradle b/src/shared-contract/build.gradle index d20d390a..66e2450e 100644 --- a/src/shared-contract/build.gradle +++ b/src/shared-contract/build.gradle @@ -1,6 +1,5 @@ plugins { id 'ca.java-library' - id 'ca.strict-qualification' } // Skeleton-wide operational contracts only. No business/domain concepts. @@ -8,18 +7,12 @@ plugins { dependencies { } -def messagingSharedSchemaQualification = extensions.getByName('strictQualification').register( - 'messagingSharedSchemaQualificationTest', - sourceSets.test, - [ - 'dev.caskeleton.shared.contract.messaging.MessagingEnvelopeSchemaResourceTest' - ], - rootProject.layout.buildDirectory.dir( - 'test-results/messaging-evidence/shared'), - rootProject.layout.buildDirectory.dir( - 'test-results/messaging-evidence-binary/shared'), - 'Runs exact Messaging shared schema qualification tests.' -) -messagingSharedSchemaQualification.configure { - dependsOn ':prepareMessagingContractEvidence' +// Half of the root `verifyMessagingContracts`: the shared envelope schema, run by name, no skips. +strictTestLanes { + lane('messagingSharedSchemaQualificationTest') { + description = 'Runs exact Messaging shared schema qualification tests.' + requires 'dev.caskeleton.shared.contract.messaging.MessagingEnvelopeSchemaResourceTest' + rejectSkipped = true + jvmArgs '-Duser.timezone=UTC' + } } diff --git a/src/shared-contract/src/main/java/dev/caskeleton/shared/activation/MasterSwitch.java b/src/shared-contract/src/main/java/dev/caskeleton/shared/activation/MasterSwitch.java deleted file mode 100644 index 72e973a7..00000000 --- a/src/shared-contract/src/main/java/dev/caskeleton/shared/activation/MasterSwitch.java +++ /dev/null @@ -1,102 +0,0 @@ -package dev.caskeleton.shared.activation; - -import java.util.EnumMap; -import java.util.List; -import java.util.Map; - -/** - * The runtime capabilities this skeleton ships behind an explicit switch, and the names that - * address them. - * - *

    One place knows the names. Spread across conditions as string literals, a rename becomes a - * silent activation change: the condition stops matching, the adapter stops assembling, and nothing - * reports it. - * - *

    The superseded names sit in a static map rather than in an instance field, because Error - * Prone's {@code ImmutableEnumChecker} rejects a collection-typed field on an enum and this - * repository compiles with {@code -Werror}. The two scalar names stay as fields, since a String is - * already immutable. - */ -public enum MasterSwitch { - /** Relational persistence: entity scan, repositories, pool, migration. */ - PERSISTENCE_JPA("ca-skeleton.persistence-jpa.enabled", "APP_PERSISTENCE_JPA_ENABLED"), - /** MongoDB persistence. */ - PERSISTENCE_MONGO("ca-skeleton.persistence-mongo.enabled", "APP_PERSISTENCE_MONGO_ENABLED"), - /** Broker publication and consumption. */ - MESSAGING("app.messaging.enabled", "APP_MESSAGING_ENABLED"), - /** The notification delivery platform. */ - NOTIFICATION_PLATFORM( - "ca-skeleton.notification.platform.enabled", "APP_NOTIFICATION_PLATFORM_ENABLED"), - /** The GraphQL transport boundary. */ - GRAPHQL("backend.graphql.enabled", "APP_GRAPHQL_ENABLED"), - /** The shared Redis runtime substrate. */ - REDIS("app.redis.enabled", "APP_REDIS_ENABLED"), - /** The explicit Fileserver R2 publication capability. */ - FILESERVER("app.fileserver.enabled", "APP_FILESERVER_ENABLED"), - /** The HTTP upload/download Fileserver platform. */ - FILESERVER_PLATFORM("app.fileserver-platform.enabled", "APP_FILESERVER_PLATFORM_ENABLED"), - /** The outbound HTTP client platform. */ - HTTPCLIENT("app.httpclient.enabled", "APP_HTTPCLIENT_ENABLED"); - - private static final Map> SUPERSEDED = supersededProperties(); - - private final String property; - private final String environmentVariable; - - MasterSwitch(String property, String environmentVariable) { - this.property = property; - this.environmentVariable = environmentVariable; - } - - private static Map> supersededProperties() { - Map> superseded = new EnumMap<>(MasterSwitch.class); - // Gated only add-on beans while reading as a whole-adapter switch, and defaulted to on. - superseded.put(PERSISTENCE_JPA, List.of("app.jpa-platform.enabled")); - superseded.put(PERSISTENCE_MONGO, List.of()); - superseded.put(MESSAGING, List.of()); - // Deliberately empty. The notification provider selectors and the two GraphQL safety flags are - // often described as "legacy activation", and they are not alternative spellings of these - // switches — they are subordinate settings that stay meaningful while the adapter is on. - // Listing - // them here made every shipped configuration ambiguous, because a provider selector is present - // in the default configuration and would collide with a master switch that is legitimately set. - // Their own migrations are keyed to the settings that replace them: the provider selectors to - // the - // delivery-platform runtime, and backend.graphql.production / .environment to - // backend.graphql.deployment-mode. - superseded.put(NOTIFICATION_PLATFORM, List.of()); - superseded.put(GRAPHQL, List.of()); - superseded.put(REDIS, List.of()); - superseded.put(FILESERVER, List.of()); - superseded.put(FILESERVER_PLATFORM, List.of()); - superseded.put(HTTPCLIENT, List.of()); - return Map.copyOf(superseded); - } - - /** - * Returns the canonical Spring property name. - * - * @return the property this switch is read from - */ - public String property() { - return property; - } - - /** - * Returns the canonical environment variable name. - * - * @return the operator-facing environment variable - */ - public String environmentVariable() { - return environmentVariable; - } - - /** - * Returns property names this switch supersedes, which are now migration errors. - * - * @return superseded property names, possibly empty - */ - public List legacyProperties() { - return SUPERSEDED.get(this); - } -} diff --git a/src/shared-contract/src/main/java/dev/caskeleton/shared/activation/MasterSwitchParseResult.java b/src/shared-contract/src/main/java/dev/caskeleton/shared/activation/MasterSwitchParseResult.java deleted file mode 100644 index 081eb722..00000000 --- a/src/shared-contract/src/main/java/dev/caskeleton/shared/activation/MasterSwitchParseResult.java +++ /dev/null @@ -1,54 +0,0 @@ -package dev.caskeleton.shared.activation; - -/** - * The outcome of reading one master switch. Only {@link Off} and {@link On} may start a context. - */ -public sealed interface MasterSwitchParseResult { - - /** - * The switch this result describes. - * - * @return the owning switch - */ - MasterSwitch owner(); - - /** - * The switch is off, either explicitly or because nobody set it. - * - * @param owner the switch that is off - */ - record Off(MasterSwitch owner) implements MasterSwitchParseResult {} - - /** - * The switch is on. - * - * @param owner the switch that is on - */ - record On(MasterSwitch owner) implements MasterSwitchParseResult {} - - /** - * The value is neither {@code true} nor {@code false}. - * - * @param owner the switch that was misconfigured - * @param raw the rejected raw value - */ - record Invalid(MasterSwitch owner, String raw) implements MasterSwitchParseResult {} - - /** - * Canonical and legacy keys are both set. - * - * @param owner the switch addressed by both keys - * @param legacyProperty the superseded key that is also present - */ - record Ambiguous(MasterSwitch owner, String legacyProperty) implements MasterSwitchParseResult {} - - /** - * Only a superseded key is set. - * - * @param owner the switch the legacy key used to address - * @param legacyProperty the superseded key that is present - * @param replacementProperty the canonical key to use instead - */ - record LegacyOnly(MasterSwitch owner, String legacyProperty, String replacementProperty) - implements MasterSwitchParseResult {} -} diff --git a/src/shared-contract/src/main/java/dev/caskeleton/shared/activation/MasterSwitchParser.java b/src/shared-contract/src/main/java/dev/caskeleton/shared/activation/MasterSwitchParser.java deleted file mode 100644 index ade24cd9..00000000 --- a/src/shared-contract/src/main/java/dev/caskeleton/shared/activation/MasterSwitchParser.java +++ /dev/null @@ -1,51 +0,0 @@ -package dev.caskeleton.shared.activation; - -import java.util.Locale; -import java.util.Map; - -/** - * Reads one master switch, strictly. - * - *

    No Spring types, so the rule is testable without a context — and usable by the environment - * post-processor, which has to run before there is one. - * - *

    The strictness is the design. {@code yes} read as true turns something on by accident; {@code - * yes} read as false is a deployment that believes it turned something on and did not. Rejecting - * the value is the only answer that cannot be wrong in a way nobody notices. - */ -public final class MasterSwitchParser { - - private MasterSwitchParser() {} - - /** - * Parses a switch from its canonical raw value and whatever legacy keys are present. - * - * @param owner the switch being read - * @param canonicalRaw the raw canonical value, or null when unset - * @param legacyRaw legacy property names to their raw values; only present keys belong here - * @return the parse outcome - */ - public static MasterSwitchParseResult parse( - MasterSwitch owner, String canonicalRaw, Map legacyRaw) { - String legacyPresent = - owner.legacyProperties().stream().filter(legacyRaw::containsKey).findFirst().orElse(null); - - if (canonicalRaw != null && legacyPresent != null) { - return new MasterSwitchParseResult.Ambiguous(owner, legacyPresent); - } - if (canonicalRaw == null && legacyPresent != null) { - return new MasterSwitchParseResult.LegacyOnly(owner, legacyPresent, owner.property()); - } - if (canonicalRaw == null) { - return new MasterSwitchParseResult.Off(owner); - } - String normalized = canonicalRaw.toLowerCase(Locale.ROOT); - if ("true".equals(normalized)) { - return new MasterSwitchParseResult.On(owner); - } - if ("false".equals(normalized)) { - return new MasterSwitchParseResult.Off(owner); - } - return new MasterSwitchParseResult.Invalid(owner, canonicalRaw); - } -} diff --git a/src/shared-contract/src/test/java/dev/caskeleton/shared/activation/MasterSwitchParserTest.java b/src/shared-contract/src/test/java/dev/caskeleton/shared/activation/MasterSwitchParserTest.java deleted file mode 100644 index 2d5e0672..00000000 --- a/src/shared-contract/src/test/java/dev/caskeleton/shared/activation/MasterSwitchParserTest.java +++ /dev/null @@ -1,86 +0,0 @@ -package dev.caskeleton.shared.activation; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.Map; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -/** - * A master switch is the one value an operator must be able to trust absolutely. - * - *

    Every rule here exists because the permissive alternative fails silently. {@code yes} parsed - * as true is a deployment that turned something on by accident; {@code yes} parsed as false is a - * deployment that thought it turned something on and did not. Rejecting it is the only answer that - * cannot be wrong in a way nobody notices. - */ -class MasterSwitchParserTest { - - @Test - @DisplayName("an unset switch is off") - void unsetIsOff() { - assertThat(MasterSwitchParser.parse(MasterSwitch.GRAPHQL, null, Map.of())) - .isInstanceOf(MasterSwitchParseResult.Off.class); - } - - @Test - @DisplayName("true and false parse case-insensitively") - void booleansParse() { - assertThat(MasterSwitchParser.parse(MasterSwitch.GRAPHQL, "TRUE", Map.of())) - .isInstanceOf(MasterSwitchParseResult.On.class); - assertThat(MasterSwitchParser.parse(MasterSwitch.GRAPHQL, "False", Map.of())) - .isInstanceOf(MasterSwitchParseResult.Off.class); - } - - @Test - @DisplayName("yes, 1, on, blank, and whitespace are configuration errors rather than off") - void truthyLookalikesAreRejected() { - for (String raw : new String[] {"yes", "1", "on", "", " ", "true ", " false", "ture"}) { - assertThat(MasterSwitchParser.parse(MasterSwitch.MESSAGING, raw, Map.of())) - .as("%s must be rejected; a silent off here is a deployment that thinks it is on", raw) - .isInstanceOf(MasterSwitchParseResult.Invalid.class); - } - } - - @Test - @DisplayName("canonical and legacy together are ambiguous even when they agree") - void agreeingDuplicatesAreStillAmbiguous() { - MasterSwitchParseResult result = - MasterSwitchParser.parse( - MasterSwitch.PERSISTENCE_JPA, "true", Map.of("app.jpa-platform.enabled", "true")); - assertThat(result) - .as( - "two keys that agree today diverge the first time somebody edits one of them; the " - + "ambiguity is the defect, not the disagreement") - .isInstanceOf(MasterSwitchParseResult.Ambiguous.class); - } - - @Test - @DisplayName("a legacy key alone names its replacement") - void legacyAloneNamesTheReplacement() { - MasterSwitchParseResult result = - MasterSwitchParser.parse( - MasterSwitch.PERSISTENCE_JPA, null, Map.of("app.jpa-platform.enabled", "true")); - assertThat(result).isInstanceOf(MasterSwitchParseResult.LegacyOnly.class); - assertThat(((MasterSwitchParseResult.LegacyOnly) result).replacementProperty()) - .isEqualTo("ca-skeleton.persistence-jpa.enabled"); - } - - @Test - @DisplayName("every switch has one unique operator-facing APP_* environment name") - void environmentNamesAreCanonical() { - var names = - java.util.Arrays.stream(MasterSwitch.values()) - .map(MasterSwitch::environmentVariable) - .toList(); - - assertThat(names) - .allSatisfy( - name -> { - assertThat(name).startsWith("APP_").endsWith("_ENABLED"); - assertThat(name).doesNotContain("."); - }) - .doesNotHaveDuplicates(); - assertThat(MasterSwitch.GRAPHQL.environmentVariable()).isEqualTo("APP_GRAPHQL_ENABLED"); - } -}